FBXLoader.js 127 KB

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