FBXLoader.js 119 KB

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