FBXLoader.js 128 KB

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