FBXLoader.js 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016
  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. */
  22. ( function () {
  23. /**
  24. * Generates a loader for loading FBX files from URL and parsing into
  25. * a THREE.Group.
  26. * @param {THREE.LoadingManager} manager - Loading Manager for loader to use.
  27. */
  28. THREE.FBXLoader = function ( manager ) {
  29. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  30. };
  31. Object.assign( THREE.FBXLoader.prototype, {
  32. /**
  33. * Loads an ASCII/Binary FBX file from URL and parses into a THREE.Group.
  34. * THREE.Group will have an animations property of AnimationClips
  35. * of the different animations exported with the FBX.
  36. * @param {string} url - URL of the FBX file.
  37. * @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed.
  38. * @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server.
  39. * @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors).
  40. */
  41. load: function ( url, onLoad, onProgress, onError ) {
  42. var self = this;
  43. var resourceDirectory = url.split( /[\\\/]/ );
  44. resourceDirectory.pop();
  45. resourceDirectory = resourceDirectory.join( '/' ) + '/';
  46. var loader = new THREE.FileLoader( this.manager );
  47. loader.setResponseType( 'arraybuffer' );
  48. loader.load( url, function ( buffer ) {
  49. try {
  50. var scene = self.parse( buffer, resourceDirectory );
  51. onLoad( scene );
  52. } catch ( error ) {
  53. window.setTimeout( function () {
  54. if ( onError ) onError( error );
  55. self.manager.itemError( url );
  56. }, 0 );
  57. }
  58. }, onProgress, onError );
  59. },
  60. /**
  61. * Parses an ASCII/Binary FBX file and returns a THREE.Group.
  62. * THREE.Group will have an animations property of AnimationClips
  63. * of the different animations within the FBX file.
  64. * @param {ArrayBuffer} FBXBuffer - Contents of FBX file to parse.
  65. * @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from.
  66. * @returns {THREE.Group}
  67. */
  68. parse: function ( FBXBuffer, resourceDirectory ) {
  69. var FBXTree;
  70. if ( isFbxFormatBinary( FBXBuffer ) ) {
  71. FBXTree = new BinaryParser().parse( FBXBuffer );
  72. } else {
  73. var FBXText = convertArrayBufferToString( FBXBuffer );
  74. if ( ! isFbxFormatASCII( FBXText ) ) {
  75. throw new Error( 'FBXLoader: Unknown format.' );
  76. self.manager.itemError( url );
  77. return;
  78. }
  79. if ( getFbxVersion( FBXText ) < 7000 ) {
  80. throw new Error( 'FBXLoader: FBX version not supported for file at ' + url + ', FileVersion: ' + getFbxVersion( FBXText ) );
  81. self.manager.itemError( url );
  82. return;
  83. }
  84. FBXTree = new TextParser().parse( FBXText );
  85. }
  86. // console.log( FBXTree );
  87. var connections = parseConnections( FBXTree );
  88. var images = parseImages( FBXTree );
  89. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  90. var materials = parseMaterials( FBXTree, textures, connections );
  91. var deformers = parseDeformers( FBXTree, connections );
  92. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  93. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  94. return sceneGraph;
  95. }
  96. } );
  97. /**
  98. * Parses map of relationships between objects.
  99. * @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree
  100. * @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  101. */
  102. function parseConnections( FBXTree ) {
  103. /**
  104. * @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  105. */
  106. var connectionMap = new Map();
  107. if ( 'Connections' in FBXTree ) {
  108. /**
  109. * @type {[number, number, string][]}
  110. */
  111. var connectionArray = FBXTree.Connections.properties.connections;
  112. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  113. var connection = connectionArray[ connectionArrayIndex ];
  114. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  115. connectionMap.set( connection[ 0 ], {
  116. parents: [],
  117. children: []
  118. } );
  119. }
  120. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  121. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  122. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  123. connectionMap.set( connection[ 1 ], {
  124. parents: [],
  125. children: []
  126. } );
  127. }
  128. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  129. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  130. }
  131. }
  132. return connectionMap;
  133. }
  134. /**
  135. * Parses map of images referenced in FBXTree.
  136. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  137. * @returns {Map<number, string(image blob URL)>}
  138. */
  139. function parseImages( FBXTree ) {
  140. /**
  141. * @type {Map<number, string(image blob URL)>}
  142. */
  143. var imageMap = new Map();
  144. if ( 'Video' in FBXTree.Objects.subNodes ) {
  145. var videoNodes = FBXTree.Objects.subNodes.Video;
  146. for ( var nodeID in videoNodes ) {
  147. var videoNode = videoNodes[ nodeID ];
  148. // raw image data is in videoNode.properties.Content
  149. if ( 'Content' in videoNode.properties ) {
  150. var image = parseImage( videoNodes[ nodeID ] );
  151. imageMap.set( parseInt( nodeID ), image );
  152. }
  153. }
  154. }
  155. return imageMap;
  156. }
  157. /**
  158. * @param {videoNode} videoNode - Node to get texture image information from.
  159. * @returns {string} - image blob URL
  160. */
  161. function parseImage( videoNode ) {
  162. var buffer = videoNode.properties.Content;
  163. var array = new Uint8Array( buffer );
  164. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  165. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  166. var type;
  167. switch ( extension ) {
  168. case 'bmp':
  169. type = 'image/bmp';
  170. break;
  171. case 'jpg':
  172. type = 'image/jpeg';
  173. break;
  174. case 'png':
  175. type = 'image/png';
  176. break;
  177. case 'tif':
  178. type = 'image/tiff';
  179. break;
  180. default:
  181. console.warn( 'FBXLoader: No support image type ' + extension );
  182. return;
  183. }
  184. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  185. }
  186. /**
  187. * Parses map of textures referenced in FBXTree.
  188. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  189. * @param {THREE.TextureLoader} loader
  190. * @param {Map<number, string(image blob URL)>} imageMap
  191. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  192. * @returns {Map<number, THREE.Texture>}
  193. */
  194. function parseTextures( FBXTree, loader, imageMap, connections ) {
  195. /**
  196. * @type {Map<number, THREE.Texture>}
  197. */
  198. var textureMap = new Map();
  199. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  200. var textureNodes = FBXTree.Objects.subNodes.Texture;
  201. for ( var nodeID in textureNodes ) {
  202. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  203. textureMap.set( parseInt( nodeID ), texture );
  204. }
  205. }
  206. return textureMap;
  207. }
  208. /**
  209. * @param {textureNode} textureNode - Node to get texture information from.
  210. * @param {THREE.TextureLoader} loader
  211. * @param {Map<number, string(image blob URL)>} imageMap
  212. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  213. * @returns {THREE.Texture}
  214. */
  215. function parseTexture( textureNode, loader, imageMap, connections ) {
  216. var FBX_ID = textureNode.id;
  217. var name = textureNode.name;
  218. var fileName;
  219. var filePath = textureNode.properties.FileName;
  220. var relativeFilePath = textureNode.properties.RelativeFilename;
  221. var children = connections.get( FBX_ID ).children;
  222. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  223. fileName = imageMap.get( children[ 0 ].ID );
  224. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' &&
  225. relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  226. // use textureNode.properties.RelativeFilename
  227. // if it exists and it doesn't seem an absolute path
  228. fileName = relativeFilePath;
  229. } else {
  230. var split = filePath.split( /[\\\/]/ );
  231. if ( split.length > 0 ) {
  232. fileName = split[ split.length - 1 ];
  233. } else {
  234. fileName = filePath;
  235. }
  236. }
  237. var currentPath = loader.path;
  238. if ( fileName.indexOf( 'blob:' ) === 0 ) {
  239. loader.setPath( undefined );
  240. }
  241. /**
  242. * @type {THREE.Texture}
  243. */
  244. var texture = loader.load( fileName );
  245. texture.name = name;
  246. texture.FBX_ID = FBX_ID;
  247. loader.setPath( currentPath );
  248. return texture;
  249. }
  250. /**
  251. * Parses map of Material information.
  252. * @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree
  253. * @param {Map<number, THREE.Texture>} textureMap
  254. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  255. * @returns {Map<number, THREE.Material>}
  256. */
  257. function parseMaterials( FBXTree, textureMap, connections ) {
  258. var materialMap = new Map();
  259. if ( 'Material' in FBXTree.Objects.subNodes ) {
  260. var materialNodes = FBXTree.Objects.subNodes.Material;
  261. for ( var nodeID in materialNodes ) {
  262. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  263. materialMap.set( parseInt( nodeID ), material );
  264. }
  265. }
  266. return materialMap;
  267. }
  268. /**
  269. * Takes information from Material node and returns a generated THREE.Material
  270. * @param {FBXMaterialNode} materialNode
  271. * @param {Map<number, THREE.Texture>} textureMap
  272. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  273. * @returns {THREE.Material}
  274. */
  275. function parseMaterial( materialNode, textureMap, connections ) {
  276. var FBX_ID = materialNode.id;
  277. var name = materialNode.attrName;
  278. var type = materialNode.properties.ShadingModel;
  279. //Case where FBXs wrap shading model in property object.
  280. if ( typeof type === 'object' ) {
  281. type = type.value;
  282. }
  283. var children = connections.get( FBX_ID ).children;
  284. var parameters = parseParameters( materialNode.properties, textureMap, children );
  285. var material;
  286. switch ( type ) {
  287. case 'phong':
  288. material = new THREE.MeshPhongMaterial();
  289. break;
  290. case 'lambert':
  291. material = new THREE.MeshLambertMaterial();
  292. break;
  293. default:
  294. console.warn( 'No implementation given for material type ' + type + ' in FBXLoader.js. Defaulting to basic material' );
  295. material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  296. break;
  297. }
  298. material.setValues( parameters );
  299. material.name = name;
  300. return material;
  301. }
  302. /**
  303. * @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties
  304. */
  305. /**
  306. * @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack
  307. */
  308. /**
  309. * @param {FBXMaterialProperties} properties
  310. * @param {Map<number, THREE.Texture>} textureMap
  311. * @param {{ID: number, relationship: string}[]} childrenRelationships
  312. * @returns {THREEMaterialParameterPack}
  313. */
  314. function parseParameters( properties, textureMap, childrenRelationships ) {
  315. var parameters = {};
  316. if ( properties.Diffuse ) {
  317. parameters.color = parseColor( properties.Diffuse );
  318. }
  319. if ( properties.Specular ) {
  320. parameters.specular = parseColor( properties.Specular );
  321. }
  322. if ( properties.Shininess ) {
  323. parameters.shininess = properties.Shininess.value;
  324. }
  325. if ( properties.Emissive ) {
  326. parameters.emissive = parseColor( properties.Emissive );
  327. }
  328. if ( properties.EmissiveFactor ) {
  329. parameters.emissiveIntensity = properties.EmissiveFactor.value;
  330. }
  331. if ( properties.Opacity ) {
  332. parameters.opacity = properties.Opacity.value;
  333. }
  334. if ( parameters.opacity < 1.0 ) {
  335. parameters.transparent = true;
  336. }
  337. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  338. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  339. var type = relationship.relationship;
  340. switch ( type ) {
  341. case "DiffuseColor":
  342. case " \"DiffuseColor":
  343. parameters.map = textureMap.get( relationship.ID );
  344. break;
  345. case " \"AmbientColor":
  346. case " \"Bump":
  347. case " \"EmissiveColor":
  348. case "AmbientColor":
  349. case "Bump":
  350. case "EmissiveColor":
  351. default:
  352. console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
  353. break;
  354. }
  355. }
  356. return parameters;
  357. }
  358. /**
  359. * Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  360. * @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree
  361. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  362. * @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>}
  363. */
  364. function parseDeformers( FBXTree, connections ) {
  365. var deformers = {};
  366. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  367. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  368. for ( var nodeID in DeformerNodes ) {
  369. var deformerNode = DeformerNodes[ nodeID ];
  370. if ( deformerNode.attrType === 'Skin' ) {
  371. var conns = connections.get( parseInt( nodeID ) );
  372. var skeleton = parseSkeleton( conns, DeformerNodes );
  373. skeleton.FBX_ID = parseInt( nodeID );
  374. deformers[ nodeID ] = skeleton;
  375. }
  376. }
  377. }
  378. return deformers;
  379. }
  380. /**
  381. * Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes.
  382. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
  383. * @param {Object.<number, FBXSubDeformerNode>} DeformerNodes
  384. * @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}}
  385. */
  386. function parseSkeleton( connections, DeformerNodes ) {
  387. var subDeformers = {};
  388. var children = connections.children;
  389. for ( var i = 0, l = children.length; i < l; ++ i ) {
  390. var child = children[ i ];
  391. var subDeformerNode = DeformerNodes[ child.ID ];
  392. var subDeformer = {
  393. FBX_ID: child.ID,
  394. index: i,
  395. indices: [],
  396. weights: [],
  397. transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
  398. transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  399. linkMode: subDeformerNode.properties.Mode
  400. };
  401. if ( 'Indexes' in subDeformerNode.subNodes ) {
  402. subDeformer.indices = parseIntArray( subDeformerNode.subNodes.Indexes.properties.a );
  403. subDeformer.weights = parseFloatArray( subDeformerNode.subNodes.Weights.properties.a );
  404. }
  405. subDeformers[ child.ID ] = subDeformer;
  406. }
  407. return {
  408. map: subDeformers,
  409. bones: []
  410. };
  411. }
  412. /**
  413. * Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries
  414. * @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree
  415. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  416. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  417. * @returns {Map<number, THREE.BufferGeometry>}
  418. */
  419. function parseGeometries( FBXTree, connections, deformers ) {
  420. var geometryMap = new Map();
  421. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  422. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  423. for ( var nodeID in geometryNodes ) {
  424. var relationships = connections.get( parseInt( nodeID ) );
  425. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  426. geometryMap.set( parseInt( nodeID ), geo );
  427. }
  428. }
  429. return geometryMap;
  430. }
  431. /**
  432. * Generates BufferGeometry from FBXGeometryNode.
  433. * @param {FBXGeometryNode} geometryNode
  434. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  435. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers
  436. * @returns {THREE.BufferGeometry}
  437. */
  438. function parseGeometry( geometryNode, relationships, deformers ) {
  439. switch ( geometryNode.attrType ) {
  440. case 'Mesh':
  441. return parseMeshGeometry( geometryNode, relationships, deformers );
  442. break;
  443. case 'NurbsCurve':
  444. return parseNurbsGeometry( geometryNode );
  445. break;
  446. }
  447. }
  448. /**
  449. * Specialty function for parsing Mesh based Geometry Nodes.
  450. * @param {FBXGeometryNode} geometryNode
  451. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes.
  452. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers - Map object of deformers and subDeformers by ID.
  453. * @returns {THREE.BufferGeometry}
  454. */
  455. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  456. for ( var i = 0; i < relationships.children.length; ++ i ) {
  457. var deformer = deformers[ relationships.children[ i ].ID ];
  458. if ( deformer !== undefined ) break;
  459. }
  460. return genGeometry( geometryNode, deformer );
  461. }
  462. /**
  463. * @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer - Skeleton representation for geometry instance.
  464. * @returns {THREE.BufferGeometry}
  465. */
  466. function genGeometry( geometryNode, deformer ) {
  467. var geometry = new Geometry();
  468. var subNodes = geometryNode.subNodes;
  469. // First, each index is going to be its own vertex.
  470. var vertexBuffer = parseFloatArray( subNodes.Vertices.properties.a );
  471. var indexBuffer = parseIntArray( subNodes.PolygonVertexIndex.properties.a );
  472. if ( subNodes.LayerElementNormal ) {
  473. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  474. }
  475. if ( subNodes.LayerElementUV ) {
  476. var uvInfo = getUVs( subNodes.LayerElementUV[ 0 ] );
  477. }
  478. if ( subNodes.LayerElementColor ) {
  479. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  480. }
  481. if ( subNodes.LayerElementMaterial ) {
  482. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  483. }
  484. var faceVertexBuffer = [];
  485. var polygonIndex = 0;
  486. for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; polygonVertexIndex ++ ) {
  487. var vertexIndex = indexBuffer[ polygonVertexIndex ];
  488. var endOfFace = false;
  489. if ( vertexIndex < 0 ) {
  490. vertexIndex = vertexIndex ^ - 1;
  491. indexBuffer[ polygonVertexIndex ] = vertexIndex;
  492. endOfFace = true;
  493. }
  494. var vertex = new Vertex();
  495. var weightIndices = [];
  496. var weights = [];
  497. vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
  498. if ( deformer ) {
  499. var subDeformers = deformer.map;
  500. for ( var key in subDeformers ) {
  501. var subDeformer = subDeformers[ key ];
  502. var indices = subDeformer.indices;
  503. for ( var j = 0; j < indices.length; j ++ ) {
  504. var index = indices[ j ];
  505. if ( index === vertexIndex ) {
  506. weights.push( subDeformer.weights[ j ] );
  507. weightIndices.push( subDeformer.index );
  508. break;
  509. }
  510. }
  511. }
  512. if ( weights.length > 4 ) {
  513. console.warn( 'FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  514. var WIndex = [ 0, 0, 0, 0 ];
  515. var Weight = [ 0, 0, 0, 0 ];
  516. weights.forEach( function ( weight, weightIndex ) {
  517. var currentWeight = weight;
  518. var currentIndex = weightIndices[ weightIndex ];
  519. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  520. if ( currentWeight > comparedWeight ) {
  521. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  522. currentWeight = comparedWeight;
  523. var tmp = WIndex[ comparedWeightIndex ];
  524. WIndex[ comparedWeightIndex ] = currentIndex;
  525. currentIndex = tmp;
  526. }
  527. } );
  528. } );
  529. weightIndices = WIndex;
  530. weights = Weight;
  531. }
  532. for ( var i = weights.length; i < 4; ++ i ) {
  533. weights[ i ] = 0;
  534. weightIndices[ i ] = 0;
  535. }
  536. vertex.skinWeights.fromArray( weights );
  537. vertex.skinIndices.fromArray( weightIndices );
  538. }
  539. if ( normalInfo ) {
  540. vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
  541. }
  542. if ( uvInfo ) {
  543. vertex.uv.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo ) );
  544. }
  545. if ( colorInfo ) {
  546. vertex.color.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo ) );
  547. }
  548. faceVertexBuffer.push( vertex );
  549. if ( endOfFace ) {
  550. var face = new Face();
  551. face.genTrianglesFromVertices( faceVertexBuffer );
  552. if ( materialInfo !== undefined ) {
  553. var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
  554. face.materialIndex = materials[ 0 ];
  555. } else {
  556. // Seems like some models don't have materialInfo(subNodes.LayerElementMaterial).
  557. // Set 0 in such a case.
  558. face.materialIndex = 0;
  559. }
  560. geometry.faces.push( face );
  561. faceVertexBuffer = [];
  562. polygonIndex ++;
  563. endOfFace = false;
  564. }
  565. }
  566. /**
  567. * @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  568. */
  569. var bufferInfo = geometry.flattenToBuffers();
  570. var geo = new THREE.BufferGeometry();
  571. geo.name = geometryNode.name;
  572. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( bufferInfo.vertexBuffer, 3 ) );
  573. if ( bufferInfo.normalBuffer.length > 0 ) {
  574. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( bufferInfo.normalBuffer, 3 ) );
  575. }
  576. if ( bufferInfo.uvBuffer.length > 0 ) {
  577. geo.addAttribute( 'uv', new THREE.Float32BufferAttribute( bufferInfo.uvBuffer, 2 ) );
  578. }
  579. if ( subNodes.LayerElementColor ) {
  580. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( bufferInfo.colorBuffer, 3 ) );
  581. }
  582. if ( deformer ) {
  583. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( bufferInfo.skinIndexBuffer, 4 ) );
  584. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( bufferInfo.skinWeightBuffer, 4 ) );
  585. geo.FBX_Deformer = deformer;
  586. }
  587. // Convert the material indices of each vertex into rendering groups on the geometry.
  588. var materialIndexBuffer = bufferInfo.materialIndexBuffer;
  589. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  590. var startIndex = 0;
  591. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  592. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  593. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  594. prevMaterialIndex = materialIndexBuffer[ i ];
  595. startIndex = i;
  596. }
  597. }
  598. return geo;
  599. }
  600. /**
  601. * Parses normal information for geometry.
  602. * @param {FBXGeometryNode} geometryNode
  603. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  604. */
  605. function getNormals( NormalNode ) {
  606. var mappingType = NormalNode.properties.MappingInformationType;
  607. var referenceType = NormalNode.properties.ReferenceInformationType;
  608. var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
  609. var indexBuffer = [];
  610. if ( referenceType === 'IndexToDirect' ) {
  611. if ( 'NormalIndex' in NormalNode.subNodes ) {
  612. indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
  613. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  614. indexBuffer = parseIntArray( NormalNode.subNodes.NormalsIndex.properties.a );
  615. }
  616. }
  617. return {
  618. dataSize: 3,
  619. buffer: buffer,
  620. indices: indexBuffer,
  621. mappingType: mappingType,
  622. referenceType: referenceType
  623. };
  624. }
  625. /**
  626. * Parses UV information for geometry.
  627. * @param {FBXGeometryNode} geometryNode
  628. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  629. */
  630. function getUVs( UVNode ) {
  631. var mappingType = UVNode.properties.MappingInformationType;
  632. var referenceType = UVNode.properties.ReferenceInformationType;
  633. var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
  634. var indexBuffer = [];
  635. if ( referenceType === 'IndexToDirect' ) {
  636. indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
  637. }
  638. return {
  639. dataSize: 2,
  640. buffer: buffer,
  641. indices: indexBuffer,
  642. mappingType: mappingType,
  643. referenceType: referenceType
  644. };
  645. }
  646. /**
  647. * Parses Vertex Color information for geometry.
  648. * @param {FBXGeometryNode} geometryNode
  649. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  650. */
  651. function getColors( ColorNode ) {
  652. var mappingType = ColorNode.properties.MappingInformationType;
  653. var referenceType = ColorNode.properties.ReferenceInformationType;
  654. var buffer = parseFloatArray( ColorNode.subNodes.Colors.properties.a );
  655. var indexBuffer = [];
  656. if ( referenceType === 'IndexToDirect' ) {
  657. indexBuffer = parseFloatArray( ColorNode.subNodes.ColorIndex.properties.a );
  658. }
  659. return {
  660. dataSize: 4,
  661. buffer: buffer,
  662. indices: indexBuffer,
  663. mappingType: mappingType,
  664. referenceType: referenceType
  665. };
  666. }
  667. /**
  668. * Parses material application information for geometry.
  669. * @param {FBXGeometryNode}
  670. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  671. */
  672. function getMaterials( MaterialNode ) {
  673. var mappingType = MaterialNode.properties.MappingInformationType;
  674. var referenceType = MaterialNode.properties.ReferenceInformationType;
  675. if ( mappingType === 'NoMappingInformation' ) {
  676. return {
  677. dataSize: 1,
  678. buffer: [ 0 ],
  679. indices: [ 0 ],
  680. mappingType: 'AllSame',
  681. referenceType: referenceType
  682. };
  683. }
  684. var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
  685. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  686. // we expect. So we create an intermediate buffer that points to the index in the buffer,
  687. // for conforming with the other functions we've written for other data.
  688. var materialIndices = [];
  689. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  690. materialIndices.push( materialIndexBufferIndex );
  691. }
  692. return {
  693. dataSize: 1,
  694. buffer: materialIndexBuffer,
  695. indices: materialIndices,
  696. mappingType: mappingType,
  697. referenceType: referenceType
  698. };
  699. }
  700. /**
  701. * Function uses the infoObject and given indices to return value array of object.
  702. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  703. * @param {number} polygonIndex - Index of polygon in geometry.
  704. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  705. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  706. * @returns {number[]}
  707. */
  708. var dataArray = [];
  709. var GetData = {
  710. ByPolygonVertex: {
  711. /**
  712. * Function uses the infoObject and given indices to return value array of object.
  713. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  714. * @param {number} polygonIndex - Index of polygon in geometry.
  715. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  716. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  717. * @returns {number[]}
  718. */
  719. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  720. var from = ( polygonVertexIndex * infoObject.dataSize );
  721. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  722. // return infoObject.buffer.slice( from, to );
  723. return slice( dataArray, infoObject.buffer, from, to );
  724. },
  725. /**
  726. * Function uses the infoObject and given indices to return value array of object.
  727. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  728. * @param {number} polygonIndex - Index of polygon in geometry.
  729. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  730. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  731. * @returns {number[]}
  732. */
  733. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  734. var index = infoObject.indices[ polygonVertexIndex ];
  735. var from = ( index * infoObject.dataSize );
  736. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  737. // return infoObject.buffer.slice( from, to );
  738. return slice( dataArray, infoObject.buffer, from, to );
  739. }
  740. },
  741. ByPolygon: {
  742. /**
  743. * Function uses the infoObject and given indices to return value array of object.
  744. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  745. * @param {number} polygonIndex - Index of polygon in geometry.
  746. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  747. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  748. * @returns {number[]}
  749. */
  750. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  751. var from = polygonIndex * infoObject.dataSize;
  752. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  753. // return infoObject.buffer.slice( from, to );
  754. return slice( dataArray, infoObject.buffer, from, to );
  755. },
  756. /**
  757. * Function uses the infoObject and given indices to return value array of object.
  758. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  759. * @param {number} polygonIndex - Index of polygon in geometry.
  760. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  761. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  762. * @returns {number[]}
  763. */
  764. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  765. var index = infoObject.indices[ polygonIndex ];
  766. var from = index * infoObject.dataSize;
  767. var to = index * infoObject.dataSize + infoObject.dataSize;
  768. // return infoObject.buffer.slice( from, to );
  769. return slice( dataArray, infoObject.buffer, from, to );
  770. }
  771. },
  772. ByVertice: {
  773. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  774. var from = ( vertexIndex * infoObject.dataSize );
  775. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  776. // return infoObject.buffer.slice( from, to );
  777. return slice( dataArray, infoObject.buffer, from, to );
  778. }
  779. },
  780. AllSame: {
  781. /**
  782. * Function uses the infoObject and given indices to return value array of object.
  783. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  784. * @param {number} polygonIndex - Index of polygon in geometry.
  785. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  786. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  787. * @returns {number[]}
  788. */
  789. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  790. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  791. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  792. // return infoObject.buffer.slice( from, to );
  793. return slice( dataArray, infoObject.buffer, from, to );
  794. }
  795. }
  796. };
  797. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  798. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  799. }
  800. /**
  801. * Specialty function for parsing NurbsCurve based Geometry Nodes.
  802. * @param {FBXGeometryNode} geometryNode
  803. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  804. * @returns {THREE.BufferGeometry}
  805. */
  806. function parseNurbsGeometry( geometryNode ) {
  807. if ( THREE.NURBSCurve === undefined ) {
  808. console.error( "THREE.FBXLoader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry." );
  809. return new THREE.BufferGeometry();
  810. }
  811. var order = parseInt( geometryNode.properties.Order );
  812. if ( isNaN( order ) ) {
  813. console.error( "FBXLoader: Invalid Order " + geometryNode.properties.Order + " given for geometry ID: " + geometryNode.id );
  814. return new THREE.BufferGeometry();
  815. }
  816. var degree = order - 1;
  817. var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a );
  818. var controlPoints = [];
  819. var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a );
  820. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  821. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  822. }
  823. var startKnot, endKnot;
  824. if ( geometryNode.properties.Form === 'Closed' ) {
  825. controlPoints.push( controlPoints[ 0 ] );
  826. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  827. startKnot = degree;
  828. endKnot = knots.length - 1 - startKnot;
  829. for ( var i = 0; i < degree; ++ i ) {
  830. controlPoints.push( controlPoints[ i ] );
  831. }
  832. }
  833. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  834. var vertices = curve.getPoints( controlPoints.length * 7 );
  835. var positions = new Float32Array( vertices.length * 3 );
  836. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  837. vertices[ i ].toArray( positions, i * 3 );
  838. }
  839. var geometry = new THREE.BufferGeometry();
  840. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  841. return geometry;
  842. }
  843. /**
  844. * Finally generates Scene graph and Scene graph Objects.
  845. * @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree
  846. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  847. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  848. * @param {Map<number, THREE.BufferGeometry>} geometryMap
  849. * @param {Map<number, THREE.Material>} materialMap
  850. * @returns {THREE.Group}
  851. */
  852. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  853. var sceneGraph = new THREE.Group();
  854. var ModelNode = FBXTree.Objects.subNodes.Model;
  855. /**
  856. * @type {Array.<THREE.Object3D>}
  857. */
  858. var modelArray = [];
  859. /**
  860. * @type {Map.<number, THREE.Object3D>}
  861. */
  862. var modelMap = new Map();
  863. for ( var nodeID in ModelNode ) {
  864. var id = parseInt( nodeID );
  865. var node = ModelNode[ nodeID ];
  866. var conns = connections.get( id );
  867. var model = null;
  868. for ( var i = 0; i < conns.parents.length; ++ i ) {
  869. for ( var FBX_ID in deformers ) {
  870. var deformer = deformers[ FBX_ID ];
  871. var subDeformers = deformer.map;
  872. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  873. if ( subDeformer ) {
  874. var model2 = model;
  875. model = new THREE.Bone();
  876. deformer.bones[ subDeformer.index ] = model;
  877. // seems like we need this not to make non-connected bone, maybe?
  878. // TODO: confirm
  879. if ( model2 !== null ) model.add( model2 );
  880. }
  881. }
  882. }
  883. if ( ! model ) {
  884. switch ( node.attrType ) {
  885. case "Mesh":
  886. /**
  887. * @type {?THREE.BufferGeometry}
  888. */
  889. var geometry = null;
  890. /**
  891. * @type {THREE.MultiMaterial|THREE.Material}
  892. */
  893. var material = null;
  894. /**
  895. * @type {Array.<THREE.Material>}
  896. */
  897. var materials = [];
  898. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  899. var child = conns.children[ childrenIndex ];
  900. if ( geometryMap.has( child.ID ) ) {
  901. geometry = geometryMap.get( child.ID );
  902. }
  903. if ( materialMap.has( child.ID ) ) {
  904. materials.push( materialMap.get( child.ID ) );
  905. }
  906. }
  907. if ( materials.length > 1 ) {
  908. material = new THREE.MultiMaterial( materials );
  909. } else if ( materials.length > 0 ) {
  910. material = materials[ 0 ];
  911. } else {
  912. material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  913. materials.push( material );
  914. }
  915. if ( 'color' in geometry.attributes ) {
  916. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++materialIndex ) {
  917. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  918. }
  919. }
  920. if ( geometry.FBX_Deformer ) {
  921. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  922. materials[ materialsIndex ].skinning = true;
  923. }
  924. model = new THREE.SkinnedMesh( geometry, material );
  925. } else {
  926. model = new THREE.Mesh( geometry, material );
  927. }
  928. break;
  929. case "NurbsCurve":
  930. var geometry = null;
  931. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  932. var child = conns.children[ childrenIndex ];
  933. if ( geometryMap.has( child.ID ) ) {
  934. geometry = geometryMap.get( child.ID );
  935. }
  936. }
  937. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  938. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  939. model = new THREE.Line( geometry, material );
  940. break;
  941. default:
  942. model = new THREE.Object3D();
  943. break;
  944. }
  945. }
  946. model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' );
  947. model.FBX_ID = id;
  948. modelArray.push( model );
  949. modelMap.set( id, model );
  950. }
  951. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  952. var model = modelArray[ modelArrayIndex ];
  953. var node = ModelNode[ model.FBX_ID ];
  954. if ( 'Lcl_Translation' in node.properties ) {
  955. model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
  956. }
  957. if ( 'Lcl_Rotation' in node.properties ) {
  958. var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( degreeToRadian );
  959. rotation.push( 'ZYX' );
  960. model.rotation.fromArray( rotation );
  961. }
  962. if ( 'Lcl_Scaling' in node.properties ) {
  963. model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
  964. }
  965. if ( 'PreRotation' in node.properties ) {
  966. var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( DEG2RAD ), 'ZYX' );
  967. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  968. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  969. preRotations.multiply( currentRotation );
  970. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  971. }
  972. var conns = connections.get( model.FBX_ID );
  973. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  974. var pIndex = findIndex( modelArray, function ( mod ) {
  975. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  976. } );
  977. if ( pIndex > - 1 ) {
  978. modelArray[ pIndex ].add( model );
  979. break;
  980. }
  981. }
  982. if ( model.parent === null ) {
  983. sceneGraph.add( model );
  984. }
  985. }
  986. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  987. sceneGraph.updateMatrixWorld( true );
  988. // Put skeleton into bind pose.
  989. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  990. for ( var nodeID in BindPoseNode ) {
  991. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  992. BindPoseNode = BindPoseNode[ nodeID ];
  993. break;
  994. }
  995. }
  996. if ( BindPoseNode ) {
  997. var PoseNode = BindPoseNode.subNodes.PoseNode;
  998. var worldMatrices = new Map();
  999. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1000. var node = PoseNode[ PoseNodeIndex ];
  1001. var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
  1002. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1003. }
  1004. }
  1005. for ( var FBX_ID in deformers ) {
  1006. var deformer = deformers[ FBX_ID ];
  1007. var subDeformers = deformer.map;
  1008. for ( var key in subDeformers ) {
  1009. var subDeformer = subDeformers[ key ];
  1010. var subDeformerIndex = subDeformer.index;
  1011. /**
  1012. * @type {THREE.Bone}
  1013. */
  1014. var bone = deformer.bones[ subDeformerIndex ];
  1015. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1016. break;
  1017. }
  1018. var mat = worldMatrices.get( bone.FBX_ID );
  1019. bone.matrixWorld.copy( mat );
  1020. }
  1021. // Now that skeleton is in bind pose, bind to model.
  1022. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1023. var conns = connections.get( deformer.FBX_ID );
  1024. var parents = conns.parents;
  1025. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1026. var parent = parents[ parentsIndex ];
  1027. if ( geometryMap.has( parent.ID ) ) {
  1028. var geoID = parent.ID;
  1029. var geoConns = connections.get( geoID );
  1030. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1031. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1032. var model = modelMap.get( geoConns.parents[ i ].ID );
  1033. //ASSERT model typeof SkinnedMesh
  1034. model.bind( deformer.skeleton, model.matrixWorld );
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. }
  1041. //Skeleton is now bound, return objects to starting
  1042. //world positions.
  1043. sceneGraph.updateMatrixWorld( true );
  1044. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1045. // to attach animations to, since FBXs treat animations as animations for the entire scene,
  1046. // not just for individual objects.
  1047. sceneGraph.skeleton = {
  1048. bones: modelArray
  1049. };
  1050. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1051. addAnimations( sceneGraph, animations );
  1052. return sceneGraph;
  1053. }
  1054. /**
  1055. * Parses animation information from FBXTree and generates an AnimationInfoObject.
  1056. * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
  1057. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1058. */
  1059. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1060. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1061. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1062. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1063. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1064. /**
  1065. * @type {{
  1066. curves: Map<number, {
  1067. T: {
  1068. id: number;
  1069. attr: string;
  1070. internalID: number;
  1071. attrX: boolean;
  1072. attrY: boolean;
  1073. attrZ: boolean;
  1074. containerBoneID: number;
  1075. containerID: number;
  1076. curves: {
  1077. x: {
  1078. version: any;
  1079. id: number;
  1080. internalID: number;
  1081. times: number[];
  1082. values: number[];
  1083. attrFlag: number[];
  1084. attrData: number[];
  1085. };
  1086. y: {
  1087. version: any;
  1088. id: number;
  1089. internalID: number;
  1090. times: number[];
  1091. values: number[];
  1092. attrFlag: number[];
  1093. attrData: number[];
  1094. };
  1095. z: {
  1096. version: any;
  1097. id: number;
  1098. internalID: number;
  1099. times: number[];
  1100. values: number[];
  1101. attrFlag: number[];
  1102. attrData: number[];
  1103. };
  1104. };
  1105. },
  1106. R: {
  1107. id: number;
  1108. attr: string;
  1109. internalID: number;
  1110. attrX: boolean;
  1111. attrY: boolean;
  1112. attrZ: boolean;
  1113. containerBoneID: number;
  1114. containerID: number;
  1115. curves: {
  1116. x: {
  1117. version: any;
  1118. id: number;
  1119. internalID: number;
  1120. times: number[];
  1121. values: number[];
  1122. attrFlag: number[];
  1123. attrData: number[];
  1124. };
  1125. y: {
  1126. version: any;
  1127. id: number;
  1128. internalID: number;
  1129. times: number[];
  1130. values: number[];
  1131. attrFlag: number[];
  1132. attrData: number[];
  1133. };
  1134. z: {
  1135. version: any;
  1136. id: number;
  1137. internalID: number;
  1138. times: number[];
  1139. values: number[];
  1140. attrFlag: number[];
  1141. attrData: number[];
  1142. };
  1143. };
  1144. },
  1145. S: {
  1146. id: number;
  1147. attr: string;
  1148. internalID: number;
  1149. attrX: boolean;
  1150. attrY: boolean;
  1151. attrZ: boolean;
  1152. containerBoneID: number;
  1153. containerID: number;
  1154. curves: {
  1155. x: {
  1156. version: any;
  1157. id: number;
  1158. internalID: number;
  1159. times: number[];
  1160. values: number[];
  1161. attrFlag: number[];
  1162. attrData: number[];
  1163. };
  1164. y: {
  1165. version: any;
  1166. id: number;
  1167. internalID: number;
  1168. times: number[];
  1169. values: number[];
  1170. attrFlag: number[];
  1171. attrData: number[];
  1172. };
  1173. z: {
  1174. version: any;
  1175. id: number;
  1176. internalID: number;
  1177. times: number[];
  1178. values: number[];
  1179. attrFlag: number[];
  1180. attrData: number[];
  1181. };
  1182. };
  1183. }
  1184. }>,
  1185. layers: Map<number, {
  1186. T: {
  1187. id: number;
  1188. attr: string;
  1189. internalID: number;
  1190. attrX: boolean;
  1191. attrY: boolean;
  1192. attrZ: boolean;
  1193. containerBoneID: number;
  1194. containerID: number;
  1195. curves: {
  1196. x: {
  1197. version: any;
  1198. id: number;
  1199. internalID: number;
  1200. times: number[];
  1201. values: number[];
  1202. attrFlag: number[];
  1203. attrData: number[];
  1204. };
  1205. y: {
  1206. version: any;
  1207. id: number;
  1208. internalID: number;
  1209. times: number[];
  1210. values: number[];
  1211. attrFlag: number[];
  1212. attrData: number[];
  1213. };
  1214. z: {
  1215. version: any;
  1216. id: number;
  1217. internalID: number;
  1218. times: number[];
  1219. values: number[];
  1220. attrFlag: number[];
  1221. attrData: number[];
  1222. };
  1223. },
  1224. },
  1225. R: {
  1226. id: number;
  1227. attr: string;
  1228. internalID: number;
  1229. attrX: boolean;
  1230. attrY: boolean;
  1231. attrZ: boolean;
  1232. containerBoneID: number;
  1233. containerID: number;
  1234. curves: {
  1235. x: {
  1236. version: any;
  1237. id: number;
  1238. internalID: number;
  1239. times: number[];
  1240. values: number[];
  1241. attrFlag: number[];
  1242. attrData: number[];
  1243. };
  1244. y: {
  1245. version: any;
  1246. id: number;
  1247. internalID: number;
  1248. times: number[];
  1249. values: number[];
  1250. attrFlag: number[];
  1251. attrData: number[];
  1252. };
  1253. z: {
  1254. version: any;
  1255. id: number;
  1256. internalID: number;
  1257. times: number[];
  1258. values: number[];
  1259. attrFlag: number[];
  1260. attrData: number[];
  1261. };
  1262. },
  1263. },
  1264. S: {
  1265. id: number;
  1266. attr: string;
  1267. internalID: number;
  1268. attrX: boolean;
  1269. attrY: boolean;
  1270. attrZ: boolean;
  1271. containerBoneID: number;
  1272. containerID: number;
  1273. curves: {
  1274. x: {
  1275. version: any;
  1276. id: number;
  1277. internalID: number;
  1278. times: number[];
  1279. values: number[];
  1280. attrFlag: number[];
  1281. attrData: number[];
  1282. };
  1283. y: {
  1284. version: any;
  1285. id: number;
  1286. internalID: number;
  1287. times: number[];
  1288. values: number[];
  1289. attrFlag: number[];
  1290. attrData: number[];
  1291. };
  1292. z: {
  1293. version: any;
  1294. id: number;
  1295. internalID: number;
  1296. times: number[];
  1297. values: number[];
  1298. attrFlag: number[];
  1299. attrData: number[];
  1300. };
  1301. },
  1302. }
  1303. }[]>,
  1304. stacks: Map<number, {
  1305. name: string,
  1306. layers: {
  1307. T: {
  1308. id: number;
  1309. attr: string;
  1310. internalID: number;
  1311. attrX: boolean;
  1312. attrY: boolean;
  1313. attrZ: boolean;
  1314. containerBoneID: number;
  1315. containerID: number;
  1316. curves: {
  1317. x: {
  1318. version: any;
  1319. id: number;
  1320. internalID: number;
  1321. times: number[];
  1322. values: number[];
  1323. attrFlag: number[];
  1324. attrData: number[];
  1325. };
  1326. y: {
  1327. version: any;
  1328. id: number;
  1329. internalID: number;
  1330. times: number[];
  1331. values: number[];
  1332. attrFlag: number[];
  1333. attrData: number[];
  1334. };
  1335. z: {
  1336. version: any;
  1337. id: number;
  1338. internalID: number;
  1339. times: number[];
  1340. values: number[];
  1341. attrFlag: number[];
  1342. attrData: number[];
  1343. };
  1344. };
  1345. };
  1346. R: {
  1347. id: number;
  1348. attr: string;
  1349. internalID: number;
  1350. attrX: boolean;
  1351. attrY: boolean;
  1352. attrZ: boolean;
  1353. containerBoneID: number;
  1354. containerID: number;
  1355. curves: {
  1356. x: {
  1357. version: any;
  1358. id: number;
  1359. internalID: number;
  1360. times: number[];
  1361. values: number[];
  1362. attrFlag: number[];
  1363. attrData: number[];
  1364. };
  1365. y: {
  1366. version: any;
  1367. id: number;
  1368. internalID: number;
  1369. times: number[];
  1370. values: number[];
  1371. attrFlag: number[];
  1372. attrData: number[];
  1373. };
  1374. z: {
  1375. version: any;
  1376. id: number;
  1377. internalID: number;
  1378. times: number[];
  1379. values: number[];
  1380. attrFlag: number[];
  1381. attrData: number[];
  1382. };
  1383. };
  1384. };
  1385. S: {
  1386. id: number;
  1387. attr: string;
  1388. internalID: number;
  1389. attrX: boolean;
  1390. attrY: boolean;
  1391. attrZ: boolean;
  1392. containerBoneID: number;
  1393. containerID: number;
  1394. curves: {
  1395. x: {
  1396. version: any;
  1397. id: number;
  1398. internalID: number;
  1399. times: number[];
  1400. values: number[];
  1401. attrFlag: number[];
  1402. attrData: number[];
  1403. };
  1404. y: {
  1405. version: any;
  1406. id: number;
  1407. internalID: number;
  1408. times: number[];
  1409. values: number[];
  1410. attrFlag: number[];
  1411. attrData: number[];
  1412. };
  1413. z: {
  1414. version: any;
  1415. id: number;
  1416. internalID: number;
  1417. times: number[];
  1418. values: number[];
  1419. attrFlag: number[];
  1420. attrData: number[];
  1421. };
  1422. };
  1423. };
  1424. }[][],
  1425. length: number,
  1426. frames: number }>,
  1427. length: number,
  1428. fps: number,
  1429. frames: number
  1430. }}
  1431. */
  1432. var returnObject = {
  1433. curves: new Map(),
  1434. layers: {},
  1435. stacks: {},
  1436. length: 0,
  1437. fps: 30,
  1438. frames: 0
  1439. };
  1440. /**
  1441. * @type {Array.<{
  1442. id: number;
  1443. attr: string;
  1444. internalID: number;
  1445. attrX: boolean;
  1446. attrY: boolean;
  1447. attrZ: boolean;
  1448. containerBoneID: number;
  1449. containerID: number;
  1450. }>}
  1451. */
  1452. var animationCurveNodes = [];
  1453. for ( var nodeID in rawNodes ) {
  1454. if ( nodeID.match( /\d+/ ) ) {
  1455. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1456. animationCurveNodes.push( animationNode );
  1457. }
  1458. }
  1459. /**
  1460. * @type {Map.<number, {
  1461. id: number,
  1462. attr: string,
  1463. internalID: number,
  1464. attrX: boolean,
  1465. attrY: boolean,
  1466. attrZ: boolean,
  1467. containerBoneID: number,
  1468. containerID: number,
  1469. curves: {
  1470. x: {
  1471. version: any,
  1472. id: number,
  1473. internalID: number,
  1474. times: number[],
  1475. values: number[],
  1476. attrFlag: number[],
  1477. attrData: number[],
  1478. },
  1479. y: {
  1480. version: any,
  1481. id: number,
  1482. internalID: number,
  1483. times: number[],
  1484. values: number[],
  1485. attrFlag: number[],
  1486. attrData: number[],
  1487. },
  1488. z: {
  1489. version: any,
  1490. id: number,
  1491. internalID: number,
  1492. times: number[],
  1493. values: number[],
  1494. attrFlag: number[],
  1495. attrData: number[],
  1496. }
  1497. }
  1498. }>}
  1499. */
  1500. var tmpMap = new Map();
  1501. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1502. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1503. continue;
  1504. }
  1505. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1506. }
  1507. /**
  1508. * @type {{
  1509. version: any,
  1510. id: number,
  1511. internalID: number,
  1512. times: number[],
  1513. values: number[],
  1514. attrFlag: number[],
  1515. attrData: number[],
  1516. }[]}
  1517. */
  1518. var animationCurves = [];
  1519. for ( nodeID in rawCurves ) {
  1520. if ( nodeID.match( /\d+/ ) ) {
  1521. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1522. // seems like this check would be necessary?
  1523. if ( ! connections.has( animationCurve.id ) ) continue;
  1524. animationCurves.push( animationCurve );
  1525. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1526. var firstParentID = firstParentConn.ID;
  1527. var firstParentRelationship = firstParentConn.relationship;
  1528. var axis = '';
  1529. if ( firstParentRelationship.match( /X/ ) ) {
  1530. axis = 'x';
  1531. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1532. axis = 'y';
  1533. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1534. axis = 'z';
  1535. } else {
  1536. continue;
  1537. }
  1538. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1539. }
  1540. }
  1541. tmpMap.forEach( function ( curveNode ) {
  1542. var id = curveNode.containerBoneID;
  1543. if ( ! returnObject.curves.has( id ) ) {
  1544. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1545. }
  1546. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1547. if ( curveNode.attr === 'R' ) {
  1548. var curves = curveNode.curves;
  1549. curves.x.values = curves.x.values.map( degreeToRadian );
  1550. curves.y.values = curves.y.values.map( degreeToRadian );
  1551. curves.z.values = curves.z.values.map( degreeToRadian );
  1552. if ( curveNode.preRotations !== null ) {
  1553. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1554. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1555. var frameRotation = new THREE.Euler();
  1556. var frameRotationQuaternion = new THREE.Quaternion();
  1557. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1558. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1559. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1560. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1561. curves.x.values[ frame ] = frameRotation.x;
  1562. curves.y.values[ frame ] = frameRotation.y;
  1563. curves.z.values[ frame ] = frameRotation.z;
  1564. }
  1565. }
  1566. }
  1567. } );
  1568. for ( var nodeID in rawLayers ) {
  1569. /**
  1570. * @type {{
  1571. T: {
  1572. id: number;
  1573. attr: string;
  1574. internalID: number;
  1575. attrX: boolean;
  1576. attrY: boolean;
  1577. attrZ: boolean;
  1578. containerBoneID: number;
  1579. containerID: number;
  1580. curves: {
  1581. x: {
  1582. version: any;
  1583. id: number;
  1584. internalID: number;
  1585. times: number[];
  1586. values: number[];
  1587. attrFlag: number[];
  1588. attrData: number[];
  1589. };
  1590. y: {
  1591. version: any;
  1592. id: number;
  1593. internalID: number;
  1594. times: number[];
  1595. values: number[];
  1596. attrFlag: number[];
  1597. attrData: number[];
  1598. };
  1599. z: {
  1600. version: any;
  1601. id: number;
  1602. internalID: number;
  1603. times: number[];
  1604. values: number[];
  1605. attrFlag: number[];
  1606. attrData: number[];
  1607. };
  1608. },
  1609. },
  1610. R: {
  1611. id: number;
  1612. attr: string;
  1613. internalID: number;
  1614. attrX: boolean;
  1615. attrY: boolean;
  1616. attrZ: boolean;
  1617. containerBoneID: number;
  1618. containerID: number;
  1619. curves: {
  1620. x: {
  1621. version: any;
  1622. id: number;
  1623. internalID: number;
  1624. times: number[];
  1625. values: number[];
  1626. attrFlag: number[];
  1627. attrData: number[];
  1628. };
  1629. y: {
  1630. version: any;
  1631. id: number;
  1632. internalID: number;
  1633. times: number[];
  1634. values: number[];
  1635. attrFlag: number[];
  1636. attrData: number[];
  1637. };
  1638. z: {
  1639. version: any;
  1640. id: number;
  1641. internalID: number;
  1642. times: number[];
  1643. values: number[];
  1644. attrFlag: number[];
  1645. attrData: number[];
  1646. };
  1647. },
  1648. },
  1649. S: {
  1650. id: number;
  1651. attr: string;
  1652. internalID: number;
  1653. attrX: boolean;
  1654. attrY: boolean;
  1655. attrZ: boolean;
  1656. containerBoneID: number;
  1657. containerID: number;
  1658. curves: {
  1659. x: {
  1660. version: any;
  1661. id: number;
  1662. internalID: number;
  1663. times: number[];
  1664. values: number[];
  1665. attrFlag: number[];
  1666. attrData: number[];
  1667. };
  1668. y: {
  1669. version: any;
  1670. id: number;
  1671. internalID: number;
  1672. times: number[];
  1673. values: number[];
  1674. attrFlag: number[];
  1675. attrData: number[];
  1676. };
  1677. z: {
  1678. version: any;
  1679. id: number;
  1680. internalID: number;
  1681. times: number[];
  1682. values: number[];
  1683. attrFlag: number[];
  1684. attrData: number[];
  1685. };
  1686. },
  1687. }
  1688. }[]}
  1689. */
  1690. var layer = [];
  1691. var children = connections.get( parseInt( nodeID ) ).children;
  1692. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1693. // Skip lockInfluenceWeights
  1694. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1695. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1696. var boneID = curveNode.containerBoneID;
  1697. if ( layer[ boneID ] === undefined ) {
  1698. layer[ boneID ] = {
  1699. T: null,
  1700. R: null,
  1701. S: null
  1702. };
  1703. }
  1704. layer[ boneID ][ curveNode.attr ] = curveNode;
  1705. }
  1706. }
  1707. returnObject.layers[ nodeID ] = layer;
  1708. }
  1709. for ( var nodeID in rawStacks ) {
  1710. var layers = [];
  1711. var children = connections.get( parseInt( nodeID ) ).children;
  1712. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1713. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1714. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1715. if ( currentLayer !== undefined ) {
  1716. layers.push( currentLayer );
  1717. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1718. var layer = currentLayer[ currentLayerIndex ];
  1719. if ( layer ) {
  1720. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1721. }
  1722. }
  1723. }
  1724. }
  1725. // Do we have an animation clip with actual length?
  1726. if ( timestamps.max > timestamps.min ) {
  1727. returnObject.stacks[ nodeID ] = {
  1728. name: rawStacks[ nodeID ].attrName,
  1729. layers: layers,
  1730. length: timestamps.max - timestamps.min,
  1731. frames: ( timestamps.max - timestamps.min ) * 30
  1732. };
  1733. }
  1734. }
  1735. return returnObject;
  1736. }
  1737. /**
  1738. * @param {Object} FBXTree
  1739. * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
  1740. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1741. * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
  1742. */
  1743. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1744. var rawModels = FBXTree.Objects.subNodes.Model;
  1745. var returnObject = {
  1746. /**
  1747. * @type {number}
  1748. */
  1749. id: animationCurveNode.id,
  1750. /**
  1751. * @type {string}
  1752. */
  1753. attr: animationCurveNode.attrName,
  1754. /**
  1755. * @type {number}
  1756. */
  1757. internalID: animationCurveNode.id,
  1758. /**
  1759. * @type {boolean}
  1760. */
  1761. attrX: false,
  1762. /**
  1763. * @type {boolean}
  1764. */
  1765. attrY: false,
  1766. /**
  1767. * @type {boolean}
  1768. */
  1769. attrZ: false,
  1770. /**
  1771. * @type {number}
  1772. */
  1773. containerBoneID: - 1,
  1774. /**
  1775. * @type {number}
  1776. */
  1777. containerID: - 1,
  1778. curves: {
  1779. x: null,
  1780. y: null,
  1781. z: null
  1782. },
  1783. /**
  1784. * @type {number[]}
  1785. */
  1786. preRotations: null
  1787. };
  1788. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1789. for ( var attributeKey in animationCurveNode.properties ) {
  1790. if ( attributeKey.match( /X/ ) ) {
  1791. returnObject.attrX = true;
  1792. }
  1793. if ( attributeKey.match( /Y/ ) ) {
  1794. returnObject.attrY = true;
  1795. }
  1796. if ( attributeKey.match( /Z/ ) ) {
  1797. returnObject.attrZ = true;
  1798. }
  1799. }
  1800. } else {
  1801. return null;
  1802. }
  1803. var conns = connections.get( returnObject.id );
  1804. var containerIndices = conns.parents;
  1805. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1806. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1807. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1808. } );
  1809. if ( boneID > - 1 ) {
  1810. returnObject.containerBoneID = boneID;
  1811. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1812. var model = rawModels[ returnObject.containerID.toString() ];
  1813. if ( 'PreRotation' in model.properties ) {
  1814. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1815. }
  1816. break;
  1817. }
  1818. }
  1819. return returnObject;
  1820. }
  1821. /**
  1822. * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
  1823. */
  1824. function parseAnimationCurve( animationCurve ) {
  1825. return {
  1826. version: null,
  1827. id: animationCurve.id,
  1828. internalID: animationCurve.id,
  1829. times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( convertFBXTimeToSeconds ),
  1830. values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
  1831. attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
  1832. attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
  1833. };
  1834. }
  1835. /**
  1836. * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1837. * than the max or min respectively.
  1838. * @param {{
  1839. T: {
  1840. id: number,
  1841. attr: string,
  1842. internalID: number,
  1843. attrX: boolean,
  1844. attrY: boolean,
  1845. attrZ: boolean,
  1846. containerBoneID: number,
  1847. containerID: number,
  1848. curves: {
  1849. x: {
  1850. version: any,
  1851. id: number,
  1852. internalID: number,
  1853. times: number[],
  1854. values: number[],
  1855. attrFlag: number[],
  1856. attrData: number[],
  1857. },
  1858. y: {
  1859. version: any,
  1860. id: number,
  1861. internalID: number,
  1862. times: number[],
  1863. values: number[],
  1864. attrFlag: number[],
  1865. attrData: number[],
  1866. },
  1867. z: {
  1868. version: any,
  1869. id: number,
  1870. internalID: number,
  1871. times: number[],
  1872. values: number[],
  1873. attrFlag: number[],
  1874. attrData: number[],
  1875. },
  1876. },
  1877. },
  1878. R: {
  1879. id: number,
  1880. attr: string,
  1881. internalID: number,
  1882. attrX: boolean,
  1883. attrY: boolean,
  1884. attrZ: boolean,
  1885. containerBoneID: number,
  1886. containerID: number,
  1887. curves: {
  1888. x: {
  1889. version: any,
  1890. id: number,
  1891. internalID: number,
  1892. times: number[],
  1893. values: number[],
  1894. attrFlag: number[],
  1895. attrData: number[],
  1896. },
  1897. y: {
  1898. version: any,
  1899. id: number,
  1900. internalID: number,
  1901. times: number[],
  1902. values: number[],
  1903. attrFlag: number[],
  1904. attrData: number[],
  1905. },
  1906. z: {
  1907. version: any,
  1908. id: number,
  1909. internalID: number,
  1910. times: number[],
  1911. values: number[],
  1912. attrFlag: number[],
  1913. attrData: number[],
  1914. },
  1915. },
  1916. },
  1917. S: {
  1918. id: number,
  1919. attr: string,
  1920. internalID: number,
  1921. attrX: boolean,
  1922. attrY: boolean,
  1923. attrZ: boolean,
  1924. containerBoneID: number,
  1925. containerID: number,
  1926. curves: {
  1927. x: {
  1928. version: any,
  1929. id: number,
  1930. internalID: number,
  1931. times: number[],
  1932. values: number[],
  1933. attrFlag: number[],
  1934. attrData: number[],
  1935. },
  1936. y: {
  1937. version: any,
  1938. id: number,
  1939. internalID: number,
  1940. times: number[],
  1941. values: number[],
  1942. attrFlag: number[],
  1943. attrData: number[],
  1944. },
  1945. z: {
  1946. version: any,
  1947. id: number,
  1948. internalID: number,
  1949. times: number[],
  1950. values: number[],
  1951. attrFlag: number[],
  1952. attrData: number[],
  1953. },
  1954. },
  1955. },
  1956. }} layer
  1957. */
  1958. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  1959. if ( layer.R ) {
  1960. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  1961. }
  1962. if ( layer.S ) {
  1963. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  1964. }
  1965. if ( layer.T ) {
  1966. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  1967. }
  1968. }
  1969. /**
  1970. * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  1971. * exceeds the maximum or minimum.
  1972. * @param {{
  1973. x: {
  1974. version: any,
  1975. id: number,
  1976. internalID: number,
  1977. times: number[],
  1978. values: number[],
  1979. attrFlag: number[],
  1980. attrData: number[],
  1981. },
  1982. y: {
  1983. version: any,
  1984. id: number,
  1985. internalID: number,
  1986. times: number[],
  1987. values: number[],
  1988. attrFlag: number[],
  1989. attrData: number[],
  1990. },
  1991. z: {
  1992. version: any,
  1993. id: number,
  1994. internalID: number,
  1995. times: number[],
  1996. values: number[],
  1997. attrFlag: number[],
  1998. attrData: number[],
  1999. }
  2000. }} curve
  2001. */
  2002. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  2003. if ( curve.x ) {
  2004. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  2005. }
  2006. if ( curve.y ) {
  2007. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  2008. }
  2009. if ( curve.z ) {
  2010. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  2011. }
  2012. }
  2013. /**
  2014. * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  2015. * @param {{times: number[]}} axis
  2016. */
  2017. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  2018. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  2019. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  2020. }
  2021. /**
  2022. * @param {{
  2023. curves: Map<number, {
  2024. T: {
  2025. id: number;
  2026. attr: string;
  2027. internalID: number;
  2028. attrX: boolean;
  2029. attrY: boolean;
  2030. attrZ: boolean;
  2031. containerBoneID: number;
  2032. containerID: number;
  2033. curves: {
  2034. x: {
  2035. version: any;
  2036. id: number;
  2037. internalID: number;
  2038. times: number[];
  2039. values: number[];
  2040. attrFlag: number[];
  2041. attrData: number[];
  2042. };
  2043. y: {
  2044. version: any;
  2045. id: number;
  2046. internalID: number;
  2047. times: number[];
  2048. values: number[];
  2049. attrFlag: number[];
  2050. attrData: number[];
  2051. };
  2052. z: {
  2053. version: any;
  2054. id: number;
  2055. internalID: number;
  2056. times: number[];
  2057. values: number[];
  2058. attrFlag: number[];
  2059. attrData: number[];
  2060. };
  2061. };
  2062. };
  2063. R: {
  2064. id: number;
  2065. attr: string;
  2066. internalID: number;
  2067. attrX: boolean;
  2068. attrY: boolean;
  2069. attrZ: boolean;
  2070. containerBoneID: number;
  2071. containerID: number;
  2072. curves: {
  2073. x: {
  2074. version: any;
  2075. id: number;
  2076. internalID: number;
  2077. times: number[];
  2078. values: number[];
  2079. attrFlag: number[];
  2080. attrData: number[];
  2081. };
  2082. y: {
  2083. version: any;
  2084. id: number;
  2085. internalID: number;
  2086. times: number[];
  2087. values: number[];
  2088. attrFlag: number[];
  2089. attrData: number[];
  2090. };
  2091. z: {
  2092. version: any;
  2093. id: number;
  2094. internalID: number;
  2095. times: number[];
  2096. values: number[];
  2097. attrFlag: number[];
  2098. attrData: number[];
  2099. };
  2100. };
  2101. };
  2102. S: {
  2103. id: number;
  2104. attr: string;
  2105. internalID: number;
  2106. attrX: boolean;
  2107. attrY: boolean;
  2108. attrZ: boolean;
  2109. containerBoneID: number;
  2110. containerID: number;
  2111. curves: {
  2112. x: {
  2113. version: any;
  2114. id: number;
  2115. internalID: number;
  2116. times: number[];
  2117. values: number[];
  2118. attrFlag: number[];
  2119. attrData: number[];
  2120. };
  2121. y: {
  2122. version: any;
  2123. id: number;
  2124. internalID: number;
  2125. times: number[];
  2126. values: number[];
  2127. attrFlag: number[];
  2128. attrData: number[];
  2129. };
  2130. z: {
  2131. version: any;
  2132. id: number;
  2133. internalID: number;
  2134. times: number[];
  2135. values: number[];
  2136. attrFlag: number[];
  2137. attrData: number[];
  2138. };
  2139. };
  2140. };
  2141. }>;
  2142. layers: Map<number, {
  2143. T: {
  2144. id: number;
  2145. attr: string;
  2146. internalID: number;
  2147. attrX: boolean;
  2148. attrY: boolean;
  2149. attrZ: boolean;
  2150. containerBoneID: number;
  2151. containerID: number;
  2152. curves: {
  2153. x: {
  2154. version: any;
  2155. id: number;
  2156. internalID: number;
  2157. times: number[];
  2158. values: number[];
  2159. attrFlag: number[];
  2160. attrData: number[];
  2161. };
  2162. y: {
  2163. version: any;
  2164. id: number;
  2165. internalID: number;
  2166. times: number[];
  2167. values: number[];
  2168. attrFlag: number[];
  2169. attrData: number[];
  2170. };
  2171. z: {
  2172. version: any;
  2173. id: number;
  2174. internalID: number;
  2175. times: number[];
  2176. values: number[];
  2177. attrFlag: number[];
  2178. attrData: number[];
  2179. };
  2180. };
  2181. };
  2182. R: {
  2183. id: number;
  2184. attr: string;
  2185. internalID: number;
  2186. attrX: boolean;
  2187. attrY: boolean;
  2188. attrZ: boolean;
  2189. containerBoneID: number;
  2190. containerID: number;
  2191. curves: {
  2192. x: {
  2193. version: any;
  2194. id: number;
  2195. internalID: number;
  2196. times: number[];
  2197. values: number[];
  2198. attrFlag: number[];
  2199. attrData: number[];
  2200. };
  2201. y: {
  2202. version: any;
  2203. id: number;
  2204. internalID: number;
  2205. times: number[];
  2206. values: number[];
  2207. attrFlag: number[];
  2208. attrData: number[];
  2209. };
  2210. z: {
  2211. version: any;
  2212. id: number;
  2213. internalID: number;
  2214. times: number[];
  2215. values: number[];
  2216. attrFlag: number[];
  2217. attrData: number[];
  2218. };
  2219. };
  2220. };
  2221. S: {
  2222. id: number;
  2223. attr: string;
  2224. internalID: number;
  2225. attrX: boolean;
  2226. attrY: boolean;
  2227. attrZ: boolean;
  2228. containerBoneID: number;
  2229. containerID: number;
  2230. curves: {
  2231. x: {
  2232. version: any;
  2233. id: number;
  2234. internalID: number;
  2235. times: number[];
  2236. values: number[];
  2237. attrFlag: number[];
  2238. attrData: number[];
  2239. };
  2240. y: {
  2241. version: any;
  2242. id: number;
  2243. internalID: number;
  2244. times: number[];
  2245. values: number[];
  2246. attrFlag: number[];
  2247. attrData: number[];
  2248. };
  2249. z: {
  2250. version: any;
  2251. id: number;
  2252. internalID: number;
  2253. times: number[];
  2254. values: number[];
  2255. attrFlag: number[];
  2256. attrData: number[];
  2257. };
  2258. };
  2259. };
  2260. }[]>;
  2261. stacks: Map<number, {
  2262. name: string;
  2263. layers: {
  2264. T: {
  2265. id: number;
  2266. attr: string;
  2267. internalID: number;
  2268. attrX: boolean;
  2269. attrY: boolean;
  2270. attrZ: boolean;
  2271. containerBoneID: number;
  2272. containerID: number;
  2273. curves: {
  2274. x: {
  2275. version: any;
  2276. id: number;
  2277. internalID: number;
  2278. times: number[];
  2279. values: number[];
  2280. attrFlag: number[];
  2281. attrData: number[];
  2282. };
  2283. y: {
  2284. version: any;
  2285. id: number;
  2286. internalID: number;
  2287. times: number[];
  2288. values: number[];
  2289. attrFlag: number[];
  2290. attrData: number[];
  2291. };
  2292. z: {
  2293. version: any;
  2294. id: number;
  2295. internalID: number;
  2296. times: number[];
  2297. values: number[];
  2298. attrFlag: number[];
  2299. attrData: number[];
  2300. };
  2301. };
  2302. };
  2303. R: {
  2304. id: number;
  2305. attr: string;
  2306. internalID: number;
  2307. attrX: boolean;
  2308. attrY: boolean;
  2309. attrZ: boolean;
  2310. containerBoneID: number;
  2311. containerID: number;
  2312. curves: {
  2313. x: {
  2314. version: any;
  2315. id: number;
  2316. internalID: number;
  2317. times: number[];
  2318. values: number[];
  2319. attrFlag: number[];
  2320. attrData: number[];
  2321. };
  2322. y: {
  2323. version: any;
  2324. id: number;
  2325. internalID: number;
  2326. times: number[];
  2327. values: number[];
  2328. attrFlag: number[];
  2329. attrData: number[];
  2330. };
  2331. z: {
  2332. version: any;
  2333. id: number;
  2334. internalID: number;
  2335. times: number[];
  2336. values: number[];
  2337. attrFlag: number[];
  2338. attrData: number[];
  2339. };
  2340. };
  2341. };
  2342. S: {
  2343. id: number;
  2344. attr: string;
  2345. internalID: number;
  2346. attrX: boolean;
  2347. attrY: boolean;
  2348. attrZ: boolean;
  2349. containerBoneID: number;
  2350. containerID: number;
  2351. curves: {
  2352. x: {
  2353. version: any;
  2354. id: number;
  2355. internalID: number;
  2356. times: number[];
  2357. values: number[];
  2358. attrFlag: number[];
  2359. attrData: number[];
  2360. };
  2361. y: {
  2362. version: any;
  2363. id: number;
  2364. internalID: number;
  2365. times: number[];
  2366. values: number[];
  2367. attrFlag: number[];
  2368. attrData: number[];
  2369. };
  2370. z: {
  2371. version: any;
  2372. id: number;
  2373. internalID: number;
  2374. times: number[];
  2375. values: number[];
  2376. attrFlag: number[];
  2377. attrData: number[];
  2378. };
  2379. };
  2380. };
  2381. }[][];
  2382. length: number;
  2383. frames: number;
  2384. }>;
  2385. length: number;
  2386. fps: number;
  2387. frames: number;
  2388. }} animations,
  2389. * @param {{skeleton: { bones: THREE.Bone[]}}} group
  2390. */
  2391. function addAnimations( group, animations ) {
  2392. if ( group.animations === undefined ) {
  2393. group.animations = [];
  2394. }
  2395. var stacks = animations.stacks;
  2396. for ( var key in stacks ) {
  2397. var stack = stacks[ key ];
  2398. /**
  2399. * @type {{
  2400. * name: string,
  2401. * fps: number,
  2402. * length: number,
  2403. * hierarchy: Array.<{
  2404. * parent: number,
  2405. * name: string,
  2406. * keys: Array.<{
  2407. * time: number,
  2408. * pos: Array.<number>,
  2409. * rot: Array.<number>,
  2410. * scl: Array.<number>
  2411. * }>
  2412. * }>
  2413. * }}
  2414. */
  2415. var animationData = {
  2416. name: stack.name,
  2417. fps: 30,
  2418. length: stack.length,
  2419. hierarchy: []
  2420. };
  2421. var bones = group.skeleton.bones;
  2422. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2423. var bone = bones[ bonesIndex ];
  2424. var name = bone.name.replace( /.*:/, '' );
  2425. var parentIndex = findIndex( bones, function ( parentBone ) {
  2426. return bone.parent === parentBone;
  2427. } );
  2428. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  2429. }
  2430. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  2431. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2432. var bone = bones[ bonesIndex ];
  2433. var boneIndex = bonesIndex;
  2434. var animationNode = stack.layers[ 0 ][ boneIndex ];
  2435. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  2436. var node = animationData.hierarchy[ hierarchyIndex ];
  2437. if ( node.name === bone.name ) {
  2438. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  2439. }
  2440. }
  2441. }
  2442. }
  2443. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  2444. }
  2445. }
  2446. var euler = new THREE.Euler();
  2447. var quaternion = new THREE.Quaternion();
  2448. /**
  2449. * @param {THREE.Bone} bone
  2450. */
  2451. function generateKey( animations, animationNode, bone, frame ) {
  2452. var key = {
  2453. time: frame / animations.fps,
  2454. pos: bone.position.toArray(),
  2455. rot: bone.quaternion.toArray(),
  2456. scl: bone.scale.toArray()
  2457. };
  2458. if ( animationNode === undefined ) return key;
  2459. try {
  2460. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  2461. key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
  2462. }
  2463. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  2464. var rotationX = animationNode.R.curves.x.values[ frame ];
  2465. var rotationY = animationNode.R.curves.y.values[ frame ];
  2466. var rotationZ = animationNode.R.curves.z.values[ frame ];
  2467. quaternion.setFromEuler( euler.set( rotationX, rotationY, rotationZ, 'ZYX' ) );
  2468. key.rot = quaternion.toArray();
  2469. }
  2470. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  2471. key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
  2472. }
  2473. } catch ( error ) {
  2474. // Curve is not fully plotted.
  2475. console.log( bone );
  2476. console.log( error );
  2477. }
  2478. return key;
  2479. }
  2480. var AXES = [ 'x', 'y', 'z' ];
  2481. function hasCurve( animationNode, attribute ) {
  2482. if ( animationNode === undefined ) {
  2483. return false;
  2484. }
  2485. var attributeNode = animationNode[ attribute ];
  2486. if ( ! attributeNode ) {
  2487. return false;
  2488. }
  2489. return AXES.every( function ( key ) {
  2490. return attributeNode.curves[ key ] !== null;
  2491. } );
  2492. }
  2493. function hasKeyOnFrame( attributeNode, frame ) {
  2494. return AXES.every( function ( key ) {
  2495. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  2496. } );
  2497. }
  2498. function isKeyExistOnFrame( curve, frame ) {
  2499. return curve.values[ frame ] !== undefined;
  2500. }
  2501. /**
  2502. * An instance of a Vertex with data for drawing vertices to the screen.
  2503. * @constructor
  2504. */
  2505. function Vertex() {
  2506. /**
  2507. * Position of the vertex.
  2508. * @type {THREE.Vector3}
  2509. */
  2510. this.position = new THREE.Vector3();
  2511. /**
  2512. * Normal of the vertex
  2513. * @type {THREE.Vector3}
  2514. */
  2515. this.normal = new THREE.Vector3();
  2516. /**
  2517. * UV coordinates of the vertex.
  2518. * @type {THREE.Vector2}
  2519. */
  2520. this.uv = new THREE.Vector2();
  2521. /**
  2522. * Color of the vertex
  2523. * @type {THREE.Vector3}
  2524. */
  2525. this.color = new THREE.Vector3();
  2526. /**
  2527. * Indices of the bones vertex is influenced by.
  2528. * @type {THREE.Vector4}
  2529. */
  2530. this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
  2531. /**
  2532. * Weights that each bone influences the vertex.
  2533. * @type {THREE.Vector4}
  2534. */
  2535. this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
  2536. }
  2537. Object.assign( Vertex.prototype, {
  2538. copy: function ( target ) {
  2539. var returnVar = target || new Vertex();
  2540. returnVar.position.copy( this.position );
  2541. returnVar.normal.copy( this.normal );
  2542. returnVar.uv.copy( this.uv );
  2543. returnVar.skinIndices.copy( this.skinIndices );
  2544. returnVar.skinWeights.copy( this.skinWeights );
  2545. return returnVar;
  2546. },
  2547. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2548. this.position.toArray( vertexBuffer, vertexBuffer.length );
  2549. this.normal.toArray( normalBuffer, normalBuffer.length );
  2550. this.uv.toArray( uvBuffer, uvBuffer.length );
  2551. this.color.toArray( colorBuffer, colorBuffer.length );
  2552. this.skinIndices.toArray( skinIndexBuffer, skinIndexBuffer.length );
  2553. this.skinWeights.toArray( skinWeightBuffer, skinWeightBuffer.length );
  2554. }
  2555. } );
  2556. /**
  2557. * @constructor
  2558. */
  2559. function Triangle() {
  2560. /**
  2561. * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
  2562. */
  2563. this.vertices = [];
  2564. }
  2565. Object.assign( Triangle.prototype, {
  2566. copy: function ( target ) {
  2567. var returnVar = target || new Triangle();
  2568. for ( var i = 0; i < this.vertices.length; ++ i ) {
  2569. this.vertices[ i ].copy( returnVar.vertices[ i ] );
  2570. }
  2571. return returnVar;
  2572. },
  2573. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2574. var vertices = this.vertices;
  2575. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  2576. vertices[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2577. }
  2578. }
  2579. } );
  2580. /**
  2581. * @constructor
  2582. */
  2583. function Face() {
  2584. /**
  2585. * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
  2586. */
  2587. this.triangles = [];
  2588. this.materialIndex = 0;
  2589. }
  2590. Object.assign( Face.prototype, {
  2591. copy: function ( target ) {
  2592. var returnVar = target || new Face();
  2593. for ( var i = 0; i < this.triangles.length; ++ i ) {
  2594. this.triangles[ i ].copy( returnVar.triangles[ i ] );
  2595. }
  2596. returnVar.materialIndex = this.materialIndex;
  2597. return returnVar;
  2598. },
  2599. genTrianglesFromVertices: function ( vertexArray ) {
  2600. for ( var i = 2; i < vertexArray.length; ++ i ) {
  2601. var triangle = new Triangle();
  2602. triangle.vertices[ 0 ] = vertexArray[ 0 ];
  2603. triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
  2604. triangle.vertices[ 2 ] = vertexArray[ i ];
  2605. this.triangles.push( triangle );
  2606. }
  2607. },
  2608. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer ) {
  2609. var triangles = this.triangles;
  2610. var materialIndex = this.materialIndex;
  2611. for ( var i = 0, l = triangles.length; i < l; ++ i ) {
  2612. triangles[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2613. append( materialIndexBuffer, [ materialIndex, materialIndex, materialIndex ] );
  2614. }
  2615. }
  2616. } );
  2617. /**
  2618. * @constructor
  2619. */
  2620. function Geometry() {
  2621. /**
  2622. * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
  2623. */
  2624. this.faces = [];
  2625. /**
  2626. * @type {{}|THREE.Skeleton}
  2627. */
  2628. this.skeleton = null;
  2629. }
  2630. Object.assign( Geometry.prototype, {
  2631. /**
  2632. * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  2633. */
  2634. flattenToBuffers: function () {
  2635. var vertexBuffer = [];
  2636. var normalBuffer = [];
  2637. var uvBuffer = [];
  2638. var colorBuffer = [];
  2639. var skinIndexBuffer = [];
  2640. var skinWeightBuffer = [];
  2641. var materialIndexBuffer = [];
  2642. var faces = this.faces;
  2643. for ( var i = 0, l = faces.length; i < l; ++ i ) {
  2644. faces[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer );
  2645. }
  2646. return {
  2647. vertexBuffer: vertexBuffer,
  2648. normalBuffer: normalBuffer,
  2649. uvBuffer: uvBuffer,
  2650. colorBuffer: colorBuffer,
  2651. skinIndexBuffer: skinIndexBuffer,
  2652. skinWeightBuffer: skinWeightBuffer,
  2653. materialIndexBuffer: materialIndexBuffer
  2654. };
  2655. }
  2656. } );
  2657. function TextParser() {}
  2658. Object.assign( TextParser.prototype, {
  2659. getPrevNode: function () {
  2660. return this.nodeStack[ this.currentIndent - 2 ];
  2661. },
  2662. getCurrentNode: function () {
  2663. return this.nodeStack[ this.currentIndent - 1 ];
  2664. },
  2665. getCurrentProp: function () {
  2666. return this.currentProp;
  2667. },
  2668. pushStack: function ( node ) {
  2669. this.nodeStack.push( node );
  2670. this.currentIndent += 1;
  2671. },
  2672. popStack: function () {
  2673. this.nodeStack.pop();
  2674. this.currentIndent -= 1;
  2675. },
  2676. setCurrentProp: function ( val, name ) {
  2677. this.currentProp = val;
  2678. this.currentPropName = name;
  2679. },
  2680. // ----------parse ---------------------------------------------------
  2681. parse: function ( text ) {
  2682. this.currentIndent = 0;
  2683. this.allNodes = new FBXTree();
  2684. this.nodeStack = [];
  2685. this.currentProp = [];
  2686. this.currentPropName = '';
  2687. var split = text.split( "\n" );
  2688. for ( var line in split ) {
  2689. var l = split[ line ];
  2690. // short cut
  2691. if ( l.match( /^[\s\t]*;/ ) ) {
  2692. continue;
  2693. } // skip comment line
  2694. if ( l.match( /^[\s\t]*$/ ) ) {
  2695. continue;
  2696. } // skip empty line
  2697. // beginning of node
  2698. var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
  2699. var match = l.match( beginningOfNodeExp );
  2700. if ( match ) {
  2701. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
  2702. var nodeAttrs = match[ 2 ].split( ',' );
  2703. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2704. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2705. }
  2706. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2707. continue;
  2708. }
  2709. // node's property
  2710. var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
  2711. var match = l.match( propExp );
  2712. if ( match ) {
  2713. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  2714. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  2715. this.parseNodeProperty( l, propName, propValue );
  2716. continue;
  2717. }
  2718. // end of node
  2719. var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
  2720. if ( l.match( endOfNodeExp ) ) {
  2721. this.nodeEnd();
  2722. continue;
  2723. }
  2724. // for special case,
  2725. //
  2726. // Vertices: *8670 {
  2727. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  2728. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  2729. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  2730. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  2731. //
  2732. // these case the lines must contiue with previous line
  2733. if ( l.match( /^[^\s\t}]/ ) ) {
  2734. this.parseNodePropertyContinued( l );
  2735. }
  2736. }
  2737. return this.allNodes;
  2738. },
  2739. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  2740. // var nodeName = match[1];
  2741. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  2742. var attrs = this.parseNodeAttr( nodeAttrs );
  2743. var currentNode = this.getCurrentNode();
  2744. // a top node
  2745. if ( this.currentIndent === 0 ) {
  2746. this.allNodes.add( nodeName, node );
  2747. } else {
  2748. // a subnode
  2749. // already exists subnode, then append it
  2750. if ( nodeName in currentNode.subNodes ) {
  2751. var tmp = currentNode.subNodes[ nodeName ];
  2752. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  2753. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  2754. if ( attrs.id === '' ) {
  2755. currentNode.subNodes[ nodeName ] = [];
  2756. currentNode.subNodes[ nodeName ].push( tmp );
  2757. } else {
  2758. currentNode.subNodes[ nodeName ] = {};
  2759. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  2760. }
  2761. }
  2762. if ( attrs.id === '' ) {
  2763. currentNode.subNodes[ nodeName ].push( node );
  2764. } else {
  2765. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2766. }
  2767. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  2768. currentNode.subNodes[ nodeName ] = {};
  2769. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2770. } else {
  2771. currentNode.subNodes[ nodeName ] = node;
  2772. }
  2773. }
  2774. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  2775. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  2776. if ( nodeAttrs ) {
  2777. node.id = attrs.id;
  2778. node.attrName = attrs.name;
  2779. node.attrType = attrs.type;
  2780. }
  2781. this.pushStack( node );
  2782. },
  2783. parseNodeAttr: function ( attrs ) {
  2784. var id = attrs[ 0 ];
  2785. if ( attrs[ 0 ] !== "" ) {
  2786. id = parseInt( attrs[ 0 ] );
  2787. if ( isNaN( id ) ) {
  2788. // PolygonVertexIndex: *16380 {
  2789. id = attrs[ 0 ];
  2790. }
  2791. }
  2792. var name = '', type = '';
  2793. if ( attrs.length > 1 ) {
  2794. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  2795. type = attrs[ 2 ];
  2796. }
  2797. return { id: id, name: name, type: type };
  2798. },
  2799. parseNodeProperty: function ( line, propName, propValue ) {
  2800. var currentNode = this.getCurrentNode();
  2801. var parentName = currentNode.name;
  2802. // special case parent node's is like "Properties70"
  2803. // these chilren nodes must treat with careful
  2804. if ( parentName !== undefined ) {
  2805. var propMatch = parentName.match( /Properties(\d)+/ );
  2806. if ( propMatch ) {
  2807. this.parseNodeSpecialProperty( line, propName, propValue );
  2808. return;
  2809. }
  2810. }
  2811. // special case Connections
  2812. if ( propName == 'C' ) {
  2813. var connProps = propValue.split( ',' ).slice( 1 );
  2814. var from = parseInt( connProps[ 0 ] );
  2815. var to = parseInt( connProps[ 1 ] );
  2816. var rest = propValue.split( ',' ).slice( 3 );
  2817. propName = 'connections';
  2818. propValue = [ from, to ];
  2819. append( propValue, rest );
  2820. if ( currentNode.properties[ propName ] === undefined ) {
  2821. currentNode.properties[ propName ] = [];
  2822. }
  2823. }
  2824. // special case Connections
  2825. if ( propName == 'Node' ) {
  2826. var id = parseInt( propValue );
  2827. currentNode.properties.id = id;
  2828. currentNode.id = id;
  2829. }
  2830. // already exists in properties, then append this
  2831. if ( propName in currentNode.properties ) {
  2832. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  2833. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2834. currentNode.properties[ propName ].push( propValue );
  2835. } else {
  2836. currentNode.properties[ propName ] += propValue;
  2837. }
  2838. } else {
  2839. // console.log( propName + ": " + propValue );
  2840. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2841. currentNode.properties[ propName ].push( propValue );
  2842. } else {
  2843. currentNode.properties[ propName ] = propValue;
  2844. }
  2845. }
  2846. this.setCurrentProp( currentNode.properties, propName );
  2847. },
  2848. // TODO:
  2849. parseNodePropertyContinued: function ( line ) {
  2850. this.currentProp[ this.currentPropName ] += line;
  2851. },
  2852. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  2853. // split this
  2854. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  2855. // into array like below
  2856. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  2857. var props = propValue.split( '",' );
  2858. for ( var i = 0, l = props.length; i < l; i ++ ) {
  2859. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  2860. }
  2861. var innerPropName = props[ 0 ];
  2862. var innerPropType1 = props[ 1 ];
  2863. var innerPropType2 = props[ 2 ];
  2864. var innerPropFlag = props[ 3 ];
  2865. var innerPropValue = props[ 4 ];
  2866. /*
  2867. if ( innerPropValue === undefined ) {
  2868. innerPropValue = props[3];
  2869. }
  2870. */
  2871. // cast value in its type
  2872. switch ( innerPropType1 ) {
  2873. case "int":
  2874. innerPropValue = parseInt( innerPropValue );
  2875. break;
  2876. case "double":
  2877. innerPropValue = parseFloat( innerPropValue );
  2878. break;
  2879. case "ColorRGB":
  2880. case "Vector3D":
  2881. innerPropValue = parseFloatArray( innerPropValue );
  2882. break;
  2883. }
  2884. // CAUTION: these props must append to parent's parent
  2885. this.getPrevNode().properties[ innerPropName ] = {
  2886. 'type': innerPropType1,
  2887. 'type2': innerPropType2,
  2888. 'flag': innerPropFlag,
  2889. 'value': innerPropValue
  2890. };
  2891. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  2892. },
  2893. nodeEnd: function () {
  2894. this.popStack();
  2895. },
  2896. /* ---------------------------------------------------------------- */
  2897. /* util */
  2898. isFlattenNode: function ( node ) {
  2899. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  2900. }
  2901. } );
  2902. // Binary format specification:
  2903. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  2904. // https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  2905. function BinaryParser() {}
  2906. Object.assign( BinaryParser.prototype, {
  2907. /**
  2908. * Parses binary data and builds FBXTree as much compatible as possible with the one built by TextParser.
  2909. * @param {ArrayBuffer} buffer
  2910. * @returns {THREE.FBXTree}
  2911. */
  2912. parse: function ( buffer ) {
  2913. var reader = new BinaryReader( buffer );
  2914. reader.skip( 23 ); // skip magic 23 bytes
  2915. var version = reader.getUint32();
  2916. console.log( 'FBX binary version: ' + version );
  2917. var allNodes = new FBXTree();
  2918. while ( ! this.endOfContent( reader ) ) {
  2919. var node = this.parseNode( reader, version );
  2920. if ( node !== null ) allNodes.add( node.name, node );
  2921. }
  2922. return allNodes;
  2923. },
  2924. /**
  2925. * Checks if reader has reached the end of content.
  2926. * @param {BinaryReader} reader
  2927. * @returns {boolean}
  2928. */
  2929. endOfContent: function( reader ) {
  2930. // footer size: 160bytes + 16-byte alignment padding
  2931. // - 16bytes: magic
  2932. // - padding til 16-byte alignment (at least 1byte?)
  2933. // (seems like some exporters embed fixed 15bytes?)
  2934. // - 4bytes: magic
  2935. // - 4bytes: version
  2936. // - 120bytes: zero
  2937. // - 16bytes: magic
  2938. if ( reader.size() % 16 === 0 ) {
  2939. return ( ( reader.getOffset() + 160 + 16 ) & ~0xf ) >= reader.size();
  2940. } else {
  2941. return reader.getOffset() + 160 + 15 >= reader.size();
  2942. }
  2943. },
  2944. /**
  2945. * Parses Node as much compatible as possible with the one parsed by TextParser
  2946. * TODO: could be optimized more?
  2947. * @param {BinaryReader} reader
  2948. * @param {number} version
  2949. * @returns {Object} - Returns an Object as node, or null if NULL-record.
  2950. */
  2951. parseNode: function ( reader, version ) {
  2952. // The first three data sizes depends on version.
  2953. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2954. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2955. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2956. var nameLen = reader.getUint8();
  2957. var name = reader.getString( nameLen );
  2958. // Regards this node as NULL-record if endOffset is zero
  2959. if ( endOffset === 0 ) return null;
  2960. var propertyList = [];
  2961. for ( var i = 0; i < numProperties; i ++ ) {
  2962. propertyList.push( this.parseProperty( reader ) );
  2963. }
  2964. // Regards the first three elements in propertyList as id, attrName, and attrType
  2965. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  2966. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  2967. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  2968. var subNodes = {};
  2969. var properties = {};
  2970. var isSingleProperty = false;
  2971. // if this node represents just a single property
  2972. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2973. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  2974. isSingleProperty = true;
  2975. }
  2976. while ( endOffset > reader.getOffset() ) {
  2977. var node = this.parseNode( reader, version );
  2978. if ( node === null ) continue;
  2979. // special case: child node is single property
  2980. if ( node.singleProperty === true ) {
  2981. var value = node.propertyList[ 0 ];
  2982. if ( Array.isArray( value ) ) {
  2983. // node represents
  2984. // Vertices: *3 {
  2985. // a: 0.01, 0.02, 0.03
  2986. // }
  2987. // of text format here.
  2988. node.properties[ node.name ] = node.propertyList[ 0 ];
  2989. subNodes[ node.name ] = node;
  2990. // Later phase expects single property array is in node.properties.a as String.
  2991. // TODO: optimize
  2992. node.properties.a = value.toString();
  2993. } else {
  2994. // node represents
  2995. // Version: 100
  2996. // of text format here.
  2997. properties[ node.name ] = value;
  2998. }
  2999. continue;
  3000. }
  3001. // special case: connections
  3002. if ( name === 'Connections' && node.name === 'C' ) {
  3003. var array = [];
  3004. // node.propertyList would be like
  3005. // ["OO", 111264976, 144038752, "d|x"] (?, from, to, additional values)
  3006. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  3007. array[ i - 1 ] = node.propertyList[ i ];
  3008. }
  3009. if ( properties.connections === undefined ) {
  3010. properties.connections = [];
  3011. }
  3012. properties.connections.push( array );
  3013. continue;
  3014. }
  3015. // special case: child node is Properties\d+
  3016. if ( node.name.match( /^Properties\d+$/ ) ) {
  3017. // move child node's properties to this node.
  3018. var keys = Object.keys( node.properties );
  3019. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  3020. var key = keys[ i ];
  3021. properties[ key ] = node.properties[ key ];
  3022. }
  3023. continue;
  3024. }
  3025. // special case: properties
  3026. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  3027. var innerPropName = node.propertyList[ 0 ];
  3028. var innerPropType1 = node.propertyList[ 1 ];
  3029. var innerPropType2 = node.propertyList[ 2 ];
  3030. var innerPropFlag = node.propertyList[ 3 ];
  3031. var innerPropValue;
  3032. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  3033. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  3034. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' ||
  3035. innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3036. innerPropValue = [
  3037. node.propertyList[ 4 ],
  3038. node.propertyList[ 5 ],
  3039. node.propertyList[ 6 ]
  3040. ];
  3041. } else {
  3042. innerPropValue = node.propertyList[ 4 ];
  3043. }
  3044. if ( innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3045. innerPropValue = innerPropValue.toString();
  3046. }
  3047. // this will be copied to parent. see above.
  3048. properties[ innerPropName ] = {
  3049. 'type': innerPropType1,
  3050. 'type2': innerPropType2,
  3051. 'flag': innerPropFlag,
  3052. 'value': innerPropValue
  3053. };
  3054. continue;
  3055. }
  3056. // standard case
  3057. // follows TextParser's manner.
  3058. if ( subNodes[ node.name ] === undefined ) {
  3059. if ( typeof node.id === 'number' ) {
  3060. subNodes[ node.name ] = {};
  3061. subNodes[ node.name ][ node.id ] = node;
  3062. } else {
  3063. subNodes[ node.name ] = node;
  3064. }
  3065. } else {
  3066. if ( node.id === '' ) {
  3067. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  3068. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  3069. }
  3070. subNodes[ node.name ].push( node );
  3071. } else {
  3072. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  3073. subNodes[ node.name ][ node.id ] = node;
  3074. } else {
  3075. // conflict id. irregular?
  3076. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  3077. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  3078. }
  3079. subNodes[ node.name ][ node.id ].push( node );
  3080. }
  3081. }
  3082. }
  3083. }
  3084. return {
  3085. singleProperty: isSingleProperty,
  3086. id: id,
  3087. attrName: attrName,
  3088. attrType: attrType,
  3089. name: name,
  3090. properties: properties,
  3091. propertyList: propertyList, // raw property list, would be used by parent
  3092. subNodes: subNodes
  3093. };
  3094. },
  3095. parseProperty: function ( reader ) {
  3096. var type = reader.getChar();
  3097. switch ( type ) {
  3098. case 'F':
  3099. return reader.getFloat32();
  3100. case 'D':
  3101. return reader.getFloat64();
  3102. case 'L':
  3103. return reader.getInt64();
  3104. case 'I':
  3105. return reader.getInt32();
  3106. case 'Y':
  3107. return reader.getInt16();
  3108. case 'C':
  3109. return reader.getBoolean();
  3110. case 'f':
  3111. case 'd':
  3112. case 'l':
  3113. case 'i':
  3114. case 'b':
  3115. var arrayLength = reader.getUint32();
  3116. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  3117. var compressedLength = reader.getUint32();
  3118. if ( encoding === 0 ) {
  3119. switch ( type ) {
  3120. case 'f':
  3121. return reader.getFloat32Array( arrayLength );
  3122. case 'd':
  3123. return reader.getFloat64Array( arrayLength );
  3124. case 'l':
  3125. return reader.getInt64Array( arrayLength );
  3126. case 'i':
  3127. return reader.getInt32Array( arrayLength );
  3128. case 'b':
  3129. return reader.getBooleanArray( arrayLength );
  3130. }
  3131. }
  3132. if ( window.Zlib === undefined ) {
  3133. throw new Error( 'FBXLoader: Import https://github.com/imaya/zlib.js' );
  3134. }
  3135. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) );
  3136. var reader2 = new BinaryReader( inflate.decompress().buffer );
  3137. switch ( type ) {
  3138. case 'f':
  3139. return reader2.getFloat32Array( arrayLength );
  3140. case 'd':
  3141. return reader2.getFloat64Array( arrayLength );
  3142. case 'l':
  3143. return reader2.getInt64Array( arrayLength );
  3144. case 'i':
  3145. return reader2.getInt32Array( arrayLength );
  3146. case 'b':
  3147. return reader2.getBooleanArray( arrayLength );
  3148. }
  3149. case 'S':
  3150. var length = reader.getUint32();
  3151. return reader.getString( length );
  3152. case 'R':
  3153. var length = reader.getUint32();
  3154. return reader.getArrayBuffer( length );
  3155. default:
  3156. throw new Error( 'FBXLoader: Unknown property type ' + type );
  3157. }
  3158. }
  3159. } );
  3160. function BinaryReader( buffer, littleEndian ) {
  3161. this.dv = new DataView( buffer );
  3162. this.offset = 0;
  3163. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  3164. }
  3165. Object.assign( BinaryReader.prototype, {
  3166. getOffset: function () {
  3167. return this.offset;
  3168. },
  3169. size: function () {
  3170. return this.dv.buffer.byteLength;
  3171. },
  3172. skip: function ( length ) {
  3173. this.offset += length;
  3174. },
  3175. // seems like true/false representation depends on exporter.
  3176. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  3177. // then sees LSB.
  3178. getBoolean: function () {
  3179. return ( this.getUint8() & 1 ) === 1;
  3180. },
  3181. getBooleanArray: function ( size ) {
  3182. var a = [];
  3183. for ( var i = 0; i < size; i ++ ) {
  3184. a.push( this.getBoolean() );
  3185. }
  3186. return a;
  3187. },
  3188. getInt8: function () {
  3189. var value = this.dv.getInt8( this.offset );
  3190. this.offset += 1;
  3191. return value;
  3192. },
  3193. getInt8Array: function ( size ) {
  3194. var a = [];
  3195. for ( var i = 0; i < size; i ++ ) {
  3196. a.push( this.getInt8() );
  3197. }
  3198. return a;
  3199. },
  3200. getUint8: function () {
  3201. var value = this.dv.getUint8( this.offset );
  3202. this.offset += 1;
  3203. return value;
  3204. },
  3205. getUint8Array: function ( size ) {
  3206. var a = [];
  3207. for ( var i = 0; i < size; i ++ ) {
  3208. a.push( this.getUint8() );
  3209. }
  3210. return a;
  3211. },
  3212. getInt16: function () {
  3213. var value = this.dv.getInt16( this.offset, this.littleEndian );
  3214. this.offset += 2;
  3215. return value;
  3216. },
  3217. getInt16Array: function ( size ) {
  3218. var a = [];
  3219. for ( var i = 0; i < size; i ++ ) {
  3220. a.push( this.getInt16() );
  3221. }
  3222. return a;
  3223. },
  3224. getUint16: function () {
  3225. var value = this.dv.getUint16( this.offset, this.littleEndian );
  3226. this.offset += 2;
  3227. return value;
  3228. },
  3229. getUint16Array: function ( size ) {
  3230. var a = [];
  3231. for ( var i = 0; i < size; i ++ ) {
  3232. a.push( this.getUint16() );
  3233. }
  3234. return a;
  3235. },
  3236. getInt32: function () {
  3237. var value = this.dv.getInt32( this.offset, this.littleEndian );
  3238. this.offset += 4;
  3239. return value;
  3240. },
  3241. getInt32Array: function ( size ) {
  3242. var a = [];
  3243. for ( var i = 0; i < size; i ++ ) {
  3244. a.push( this.getInt32() );
  3245. }
  3246. return a;
  3247. },
  3248. getUint32: function () {
  3249. var value = this.dv.getUint32( this.offset, this.littleEndian );
  3250. this.offset += 4;
  3251. return value;
  3252. },
  3253. getUint32Array: function ( size ) {
  3254. var a = [];
  3255. for ( var i = 0; i < size; i ++ ) {
  3256. a.push( this.getUint32() );
  3257. }
  3258. return a;
  3259. },
  3260. // JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
  3261. // 1 << 32 will return 1 so using multiply operation instead here.
  3262. // There'd be a possibility that this method returns wrong value if the value
  3263. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  3264. // TODO: safely handle 64-bit integer
  3265. getInt64: function () {
  3266. var low, high;
  3267. if ( this.littleEndian ) {
  3268. low = this.getUint32();
  3269. high = this.getUint32();
  3270. } else {
  3271. high = this.getUint32();
  3272. low = this.getUint32();
  3273. }
  3274. // calculate negative value
  3275. if ( high & 0x80000000 ) {
  3276. high = ~high & 0xFFFFFFFF;
  3277. low = ~low & 0xFFFFFFFF;
  3278. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  3279. low = ( low + 1 ) & 0xFFFFFFFF;
  3280. return - ( high * 0x100000000 + low );
  3281. }
  3282. return high * 0x100000000 + low;
  3283. },
  3284. getInt64Array: function ( size ) {
  3285. var a = [];
  3286. for ( var i = 0; i < size; i ++ ) {
  3287. a.push( this.getInt64() );
  3288. }
  3289. return a;
  3290. },
  3291. // Note: see getInt64() comment
  3292. getUint64: function () {
  3293. var low, high;
  3294. if ( this.littleEndian ) {
  3295. low = this.getUint32();
  3296. high = this.getUint32();
  3297. } else {
  3298. high = this.getUint32();
  3299. low = this.getUint32();
  3300. }
  3301. return high * 0x100000000 + low;
  3302. },
  3303. getUint64Array: function ( size ) {
  3304. var a = [];
  3305. for ( var i = 0; i < size; i ++ ) {
  3306. a.push( this.getUint64() );
  3307. }
  3308. return a;
  3309. },
  3310. getFloat32: function () {
  3311. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  3312. this.offset += 4;
  3313. return value;
  3314. },
  3315. getFloat32Array: function ( size ) {
  3316. var a = [];
  3317. for ( var i = 0; i < size; i ++ ) {
  3318. a.push( this.getFloat32() );
  3319. }
  3320. return a;
  3321. },
  3322. getFloat64: function () {
  3323. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  3324. this.offset += 8;
  3325. return value;
  3326. },
  3327. getFloat64Array: function ( size ) {
  3328. var a = [];
  3329. for ( var i = 0; i < size; i ++ ) {
  3330. a.push( this.getFloat64() );
  3331. }
  3332. return a;
  3333. },
  3334. getArrayBuffer: function ( size ) {
  3335. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  3336. this.offset += size;
  3337. return value;
  3338. },
  3339. getChar: function () {
  3340. return String.fromCharCode( this.getUint8() );
  3341. },
  3342. getString: function ( size ) {
  3343. var s = '';
  3344. while ( size > 0 ) {
  3345. var value = this.getUint8();
  3346. size--;
  3347. if ( value === 0 ) break;
  3348. s += String.fromCharCode( value );
  3349. }
  3350. this.skip( size );
  3351. return s;
  3352. }
  3353. } );
  3354. function FBXTree() {}
  3355. Object.assign( FBXTree.prototype, {
  3356. add: function ( key, val ) {
  3357. this[ key ] = val;
  3358. },
  3359. searchConnectionParent: function ( id ) {
  3360. if ( this.__cache_search_connection_parent === undefined ) {
  3361. this.__cache_search_connection_parent = [];
  3362. }
  3363. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  3364. return this.__cache_search_connection_parent[ id ];
  3365. } else {
  3366. this.__cache_search_connection_parent[ id ] = [];
  3367. }
  3368. var conns = this.Connections.properties.connections;
  3369. var results = [];
  3370. for ( var i = 0; i < conns.length; ++ i ) {
  3371. if ( conns[ i ][ 0 ] == id ) {
  3372. // 0 means scene root
  3373. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  3374. results.push( res );
  3375. }
  3376. }
  3377. if ( results.length > 0 ) {
  3378. append( this.__cache_search_connection_parent[ id ], results );
  3379. return results;
  3380. } else {
  3381. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  3382. return [ - 1 ];
  3383. }
  3384. },
  3385. searchConnectionChildren: function ( id ) {
  3386. if ( this.__cache_search_connection_children === undefined ) {
  3387. this.__cache_search_connection_children = [];
  3388. }
  3389. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  3390. return this.__cache_search_connection_children[ id ];
  3391. } else {
  3392. this.__cache_search_connection_children[ id ] = [];
  3393. }
  3394. var conns = this.Connections.properties.connections;
  3395. var res = [];
  3396. for ( var i = 0; i < conns.length; ++ i ) {
  3397. if ( conns[ i ][ 1 ] == id ) {
  3398. // 0 means scene root
  3399. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  3400. // there may more than one kid, then search to the end
  3401. }
  3402. }
  3403. if ( res.length > 0 ) {
  3404. append( this.__cache_search_connection_children[ id ], res );
  3405. return res;
  3406. } else {
  3407. this.__cache_search_connection_children[ id ] = [ ];
  3408. return [ ];
  3409. }
  3410. },
  3411. searchConnectionType: function ( id, to ) {
  3412. var key = id + ',' + to; // TODO: to hash
  3413. if ( this.__cache_search_connection_type === undefined ) {
  3414. this.__cache_search_connection_type = {};
  3415. }
  3416. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  3417. return this.__cache_search_connection_type[ key ];
  3418. } else {
  3419. this.__cache_search_connection_type[ key ] = '';
  3420. }
  3421. var conns = this.Connections.properties.connections;
  3422. for ( var i = 0; i < conns.length; ++ i ) {
  3423. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  3424. // 0 means scene root
  3425. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  3426. return conns[ i ][ 2 ];
  3427. }
  3428. }
  3429. this.__cache_search_connection_type[ id ] = null;
  3430. return null;
  3431. }
  3432. } );
  3433. /**
  3434. * @param {ArrayBuffer} buffer
  3435. * @returns {boolean}
  3436. */
  3437. function isFbxFormatBinary( buffer ) {
  3438. var CORRECT = 'Kaydara FBX Binary \0';
  3439. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  3440. }
  3441. /**
  3442. * @returns {boolean}
  3443. */
  3444. function isFbxFormatASCII( text ) {
  3445. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  3446. var cursor = 0;
  3447. function read( offset ) {
  3448. var result = text[ offset - 1 ];
  3449. text = text.slice( cursor + offset );
  3450. cursor ++;
  3451. return result;
  3452. }
  3453. for ( var i = 0; i < CORRECT.length; ++ i ) {
  3454. var num = read( 1 );
  3455. if ( num == CORRECT[ i ] ) {
  3456. return false;
  3457. }
  3458. }
  3459. return true;
  3460. }
  3461. /**
  3462. * @returns {number}
  3463. */
  3464. function getFbxVersion( text ) {
  3465. var versionRegExp = /FBXVersion: (\d+)/;
  3466. var match = text.match( versionRegExp );
  3467. if ( match ) {
  3468. var version = parseInt( match[ 1 ] );
  3469. return version;
  3470. }
  3471. throw new Error( 'FBXLoader: Cannot find the version number for the file given.' );
  3472. }
  3473. /**
  3474. * Converts FBX ticks into real time seconds.
  3475. * @param {number} time - FBX tick timestamp to convert.
  3476. * @returns {number} - FBX tick in real world time.
  3477. */
  3478. function convertFBXTimeToSeconds( time ) {
  3479. // Constant is FBX ticks per second.
  3480. return time / 46186158000;
  3481. }
  3482. /**
  3483. * Parses comma separated list of float numbers and returns them in an array.
  3484. * @example
  3485. * // Returns [ 5.6, 9.4, 2.5, 1.4 ]
  3486. * parseFloatArray( "5.6,9.4,2.5,1.4" )
  3487. * @returns {number[]}
  3488. */
  3489. function parseFloatArray( string ) {
  3490. var array = string.split( ',' );
  3491. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3492. array[ i ] = parseFloat( array[ i ] );
  3493. }
  3494. return array;
  3495. }
  3496. /**
  3497. * Parses comma separated list of int numbers and returns them in an array.
  3498. * @example
  3499. * // Returns [ 5, 8, 2, 3 ]
  3500. * parseFloatArray( "5,8,2,3" )
  3501. * @returns {number[]}
  3502. */
  3503. function parseIntArray( string ) {
  3504. var array = string.split( ',' );
  3505. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3506. array[ i ] = parseInt( array[ i ] );
  3507. }
  3508. return array;
  3509. }
  3510. /**
  3511. * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
  3512. * @param {FBXVector3} property - Property to parse as Vector3.
  3513. * @returns {THREE.Vector3}
  3514. */
  3515. function parseVector3( property ) {
  3516. return new THREE.Vector3().fromArray( property.value );
  3517. }
  3518. /**
  3519. * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
  3520. * @param {FBXVector3} property - Property to parse as Color.
  3521. * @returns {THREE.Color}
  3522. */
  3523. function parseColor( property ) {
  3524. return new THREE.Color().fromArray( property.value );
  3525. }
  3526. function parseMatrixArray( floatString ) {
  3527. return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
  3528. }
  3529. /**
  3530. * Converts ArrayBuffer to String.
  3531. * @param {ArrayBuffer} buffer
  3532. * @param {number} from
  3533. * @param {number} to
  3534. * @returns {String}
  3535. */
  3536. function convertArrayBufferToString( buffer, from, to ) {
  3537. if ( from === undefined ) from = 0;
  3538. if ( to === undefined ) to = buffer.byteLength;
  3539. var array = new Uint8Array( buffer, from, to );
  3540. var s = '';
  3541. for ( var i = 0, il = array.length; i < il; i ++ ) {
  3542. s += String.fromCharCode( array[ i ] );
  3543. }
  3544. return s;
  3545. }
  3546. /**
  3547. * Converts number from degrees into radians.
  3548. * @param {number} value
  3549. * @returns {number}
  3550. */
  3551. function degreeToRadian( value ) {
  3552. return value * DEG2RAD;
  3553. }
  3554. var DEG2RAD = Math.PI / 180;
  3555. //
  3556. function findIndex( array, func ) {
  3557. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3558. if ( func( array[ i ] ) ) return i;
  3559. }
  3560. return -1;
  3561. }
  3562. function append( a, b ) {
  3563. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  3564. a[ j ] = b[ i ];
  3565. }
  3566. }
  3567. function slice( a, b, from, to ) {
  3568. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  3569. a[ j ] = b[ i ];
  3570. }
  3571. return a;
  3572. }
  3573. } )();