FBXLoader.js 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267
  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. case 0:
  1014. model = new THREE.PointLight( color, intensity, distance, decay );
  1015. break;
  1016. case '1': // Directional
  1017. case 1:
  1018. model = new THREE.DirectionalLight( color, intensity );
  1019. break;
  1020. case '2': // Spot
  1021. case 2:
  1022. var angle = Math.PI / 3;
  1023. if ( lightAttribute.InnerAngle !== undefined ) {
  1024. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1025. }
  1026. var penumbra = 0; // Falloff / Field
  1027. if ( lightAttribute.OuterAngle !== undefined ) {
  1028. // note: this is not correct - FBX calculates outer and inner angle in degrees
  1029. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1030. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1031. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1032. penumbra = Math.max( penumbra, 1 );
  1033. }
  1034. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1035. break;
  1036. default:
  1037. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1038. model = new THREE.PointLight( color, intensity );
  1039. break;
  1040. }
  1041. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === '1' ) {
  1042. model.castShadow = true;
  1043. }
  1044. }
  1045. break;
  1046. case 'NurbsCurve':
  1047. var geometry = null;
  1048. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1049. var child = conns.children[ childrenIndex ];
  1050. if ( geometryMap.has( child.ID ) ) {
  1051. geometry = geometryMap.get( child.ID );
  1052. }
  1053. }
  1054. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1055. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1056. model = new THREE.Line( geometry, material );
  1057. break;
  1058. default:
  1059. model = new THREE.Object3D();
  1060. break;
  1061. }
  1062. }
  1063. model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' );
  1064. model.FBX_ID = id;
  1065. modelArray.push( model );
  1066. modelMap.set( id, model );
  1067. }
  1068. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1069. var model = modelArray[ modelArrayIndex ];
  1070. var node = ModelNode[ model.FBX_ID ];
  1071. if ( 'Lcl_Translation' in node.properties ) {
  1072. model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
  1073. }
  1074. if ( 'Lcl_Rotation' in node.properties ) {
  1075. var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( degreeToRadian );
  1076. rotation.push( 'ZYX' );
  1077. model.rotation.fromArray( rotation );
  1078. }
  1079. if ( 'Lcl_Scaling' in node.properties ) {
  1080. model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
  1081. }
  1082. if ( 'PreRotation' in node.properties ) {
  1083. var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( DEG2RAD ), 'ZYX' );
  1084. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1085. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1086. preRotations.multiply( currentRotation );
  1087. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1088. }
  1089. var conns = connections.get( model.FBX_ID );
  1090. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1091. var pIndex = findIndex( modelArray, function ( mod ) {
  1092. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1093. } );
  1094. if ( pIndex > - 1 ) {
  1095. modelArray[ pIndex ].add( model );
  1096. break;
  1097. }
  1098. }
  1099. if ( model.parent === null ) {
  1100. sceneGraph.add( model );
  1101. }
  1102. }
  1103. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1104. sceneGraph.updateMatrixWorld( true );
  1105. // Put skeleton into bind pose.
  1106. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1107. for ( var nodeID in BindPoseNode ) {
  1108. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1109. BindPoseNode = BindPoseNode[ nodeID ];
  1110. break;
  1111. }
  1112. }
  1113. if ( BindPoseNode ) {
  1114. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1115. var worldMatrices = new Map();
  1116. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1117. var node = PoseNode[ PoseNodeIndex ];
  1118. var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
  1119. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1120. }
  1121. }
  1122. for ( var FBX_ID in deformers ) {
  1123. var deformer = deformers[ FBX_ID ];
  1124. var subDeformers = deformer.map;
  1125. for ( var key in subDeformers ) {
  1126. var subDeformer = subDeformers[ key ];
  1127. var subDeformerIndex = subDeformer.index;
  1128. /**
  1129. * @type {THREE.Bone}
  1130. */
  1131. var bone = deformer.bones[ subDeformerIndex ];
  1132. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1133. break;
  1134. }
  1135. var mat = worldMatrices.get( bone.FBX_ID );
  1136. bone.matrixWorld.copy( mat );
  1137. }
  1138. // Now that skeleton is in bind pose, bind to model.
  1139. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1140. var conns = connections.get( deformer.FBX_ID );
  1141. var parents = conns.parents;
  1142. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1143. var parent = parents[ parentsIndex ];
  1144. if ( geometryMap.has( parent.ID ) ) {
  1145. var geoID = parent.ID;
  1146. var geoConns = connections.get( geoID );
  1147. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1148. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1149. var model = modelMap.get( geoConns.parents[ i ].ID );
  1150. //ASSERT model typeof SkinnedMesh
  1151. model.bind( deformer.skeleton, model.matrixWorld );
  1152. break;
  1153. }
  1154. }
  1155. }
  1156. }
  1157. }
  1158. //Skeleton is now bound, return objects to starting
  1159. //world positions.
  1160. sceneGraph.updateMatrixWorld( true );
  1161. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1162. // to attach animations to, since FBXs treat animations as animations for the entire scene,
  1163. // not just for individual objects.
  1164. sceneGraph.skeleton = {
  1165. bones: modelArray
  1166. };
  1167. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1168. addAnimations( sceneGraph, animations );
  1169. return sceneGraph;
  1170. }
  1171. /**
  1172. * Parses animation information from FBXTree and generates an AnimationInfoObject.
  1173. * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
  1174. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1175. */
  1176. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1177. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1178. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1179. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1180. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1181. /**
  1182. * @type {{
  1183. curves: Map<number, {
  1184. T: {
  1185. id: number;
  1186. attr: string;
  1187. internalID: number;
  1188. attrX: boolean;
  1189. attrY: boolean;
  1190. attrZ: boolean;
  1191. containerBoneID: number;
  1192. containerID: number;
  1193. curves: {
  1194. x: {
  1195. version: any;
  1196. id: number;
  1197. internalID: number;
  1198. times: number[];
  1199. values: number[];
  1200. attrFlag: number[];
  1201. attrData: number[];
  1202. };
  1203. y: {
  1204. version: any;
  1205. id: number;
  1206. internalID: number;
  1207. times: number[];
  1208. values: number[];
  1209. attrFlag: number[];
  1210. attrData: number[];
  1211. };
  1212. z: {
  1213. version: any;
  1214. id: number;
  1215. internalID: number;
  1216. times: number[];
  1217. values: number[];
  1218. attrFlag: number[];
  1219. attrData: number[];
  1220. };
  1221. };
  1222. },
  1223. R: {
  1224. id: number;
  1225. attr: string;
  1226. internalID: number;
  1227. attrX: boolean;
  1228. attrY: boolean;
  1229. attrZ: boolean;
  1230. containerBoneID: number;
  1231. containerID: number;
  1232. curves: {
  1233. x: {
  1234. version: any;
  1235. id: number;
  1236. internalID: number;
  1237. times: number[];
  1238. values: number[];
  1239. attrFlag: number[];
  1240. attrData: number[];
  1241. };
  1242. y: {
  1243. version: any;
  1244. id: number;
  1245. internalID: number;
  1246. times: number[];
  1247. values: number[];
  1248. attrFlag: number[];
  1249. attrData: number[];
  1250. };
  1251. z: {
  1252. version: any;
  1253. id: number;
  1254. internalID: number;
  1255. times: number[];
  1256. values: number[];
  1257. attrFlag: number[];
  1258. attrData: number[];
  1259. };
  1260. };
  1261. },
  1262. S: {
  1263. id: number;
  1264. attr: string;
  1265. internalID: number;
  1266. attrX: boolean;
  1267. attrY: boolean;
  1268. attrZ: boolean;
  1269. containerBoneID: number;
  1270. containerID: number;
  1271. curves: {
  1272. x: {
  1273. version: any;
  1274. id: number;
  1275. internalID: number;
  1276. times: number[];
  1277. values: number[];
  1278. attrFlag: number[];
  1279. attrData: number[];
  1280. };
  1281. y: {
  1282. version: any;
  1283. id: number;
  1284. internalID: number;
  1285. times: number[];
  1286. values: number[];
  1287. attrFlag: number[];
  1288. attrData: number[];
  1289. };
  1290. z: {
  1291. version: any;
  1292. id: number;
  1293. internalID: number;
  1294. times: number[];
  1295. values: number[];
  1296. attrFlag: number[];
  1297. attrData: number[];
  1298. };
  1299. };
  1300. }
  1301. }>,
  1302. layers: Map<number, {
  1303. T: {
  1304. id: number;
  1305. attr: string;
  1306. internalID: number;
  1307. attrX: boolean;
  1308. attrY: boolean;
  1309. attrZ: boolean;
  1310. containerBoneID: number;
  1311. containerID: number;
  1312. curves: {
  1313. x: {
  1314. version: any;
  1315. id: number;
  1316. internalID: number;
  1317. times: number[];
  1318. values: number[];
  1319. attrFlag: number[];
  1320. attrData: number[];
  1321. };
  1322. y: {
  1323. version: any;
  1324. id: number;
  1325. internalID: number;
  1326. times: number[];
  1327. values: number[];
  1328. attrFlag: number[];
  1329. attrData: number[];
  1330. };
  1331. z: {
  1332. version: any;
  1333. id: number;
  1334. internalID: number;
  1335. times: number[];
  1336. values: number[];
  1337. attrFlag: number[];
  1338. attrData: number[];
  1339. };
  1340. },
  1341. },
  1342. R: {
  1343. id: number;
  1344. attr: string;
  1345. internalID: number;
  1346. attrX: boolean;
  1347. attrY: boolean;
  1348. attrZ: boolean;
  1349. containerBoneID: number;
  1350. containerID: number;
  1351. curves: {
  1352. x: {
  1353. version: any;
  1354. id: number;
  1355. internalID: number;
  1356. times: number[];
  1357. values: number[];
  1358. attrFlag: number[];
  1359. attrData: number[];
  1360. };
  1361. y: {
  1362. version: any;
  1363. id: number;
  1364. internalID: number;
  1365. times: number[];
  1366. values: number[];
  1367. attrFlag: number[];
  1368. attrData: number[];
  1369. };
  1370. z: {
  1371. version: any;
  1372. id: number;
  1373. internalID: number;
  1374. times: number[];
  1375. values: number[];
  1376. attrFlag: number[];
  1377. attrData: number[];
  1378. };
  1379. },
  1380. },
  1381. S: {
  1382. id: number;
  1383. attr: string;
  1384. internalID: number;
  1385. attrX: boolean;
  1386. attrY: boolean;
  1387. attrZ: boolean;
  1388. containerBoneID: number;
  1389. containerID: number;
  1390. curves: {
  1391. x: {
  1392. version: any;
  1393. id: number;
  1394. internalID: number;
  1395. times: number[];
  1396. values: number[];
  1397. attrFlag: number[];
  1398. attrData: number[];
  1399. };
  1400. y: {
  1401. version: any;
  1402. id: number;
  1403. internalID: number;
  1404. times: number[];
  1405. values: number[];
  1406. attrFlag: number[];
  1407. attrData: number[];
  1408. };
  1409. z: {
  1410. version: any;
  1411. id: number;
  1412. internalID: number;
  1413. times: number[];
  1414. values: number[];
  1415. attrFlag: number[];
  1416. attrData: number[];
  1417. };
  1418. },
  1419. }
  1420. }[]>,
  1421. stacks: Map<number, {
  1422. name: string,
  1423. layers: {
  1424. T: {
  1425. id: number;
  1426. attr: string;
  1427. internalID: number;
  1428. attrX: boolean;
  1429. attrY: boolean;
  1430. attrZ: boolean;
  1431. containerBoneID: number;
  1432. containerID: number;
  1433. curves: {
  1434. x: {
  1435. version: any;
  1436. id: number;
  1437. internalID: number;
  1438. times: number[];
  1439. values: number[];
  1440. attrFlag: number[];
  1441. attrData: number[];
  1442. };
  1443. y: {
  1444. version: any;
  1445. id: number;
  1446. internalID: number;
  1447. times: number[];
  1448. values: number[];
  1449. attrFlag: number[];
  1450. attrData: number[];
  1451. };
  1452. z: {
  1453. version: any;
  1454. id: number;
  1455. internalID: number;
  1456. times: number[];
  1457. values: number[];
  1458. attrFlag: number[];
  1459. attrData: number[];
  1460. };
  1461. };
  1462. };
  1463. R: {
  1464. id: number;
  1465. attr: string;
  1466. internalID: number;
  1467. attrX: boolean;
  1468. attrY: boolean;
  1469. attrZ: boolean;
  1470. containerBoneID: number;
  1471. containerID: number;
  1472. curves: {
  1473. x: {
  1474. version: any;
  1475. id: number;
  1476. internalID: number;
  1477. times: number[];
  1478. values: number[];
  1479. attrFlag: number[];
  1480. attrData: number[];
  1481. };
  1482. y: {
  1483. version: any;
  1484. id: number;
  1485. internalID: number;
  1486. times: number[];
  1487. values: number[];
  1488. attrFlag: number[];
  1489. attrData: number[];
  1490. };
  1491. z: {
  1492. version: any;
  1493. id: number;
  1494. internalID: number;
  1495. times: number[];
  1496. values: number[];
  1497. attrFlag: number[];
  1498. attrData: number[];
  1499. };
  1500. };
  1501. };
  1502. S: {
  1503. id: number;
  1504. attr: string;
  1505. internalID: number;
  1506. attrX: boolean;
  1507. attrY: boolean;
  1508. attrZ: boolean;
  1509. containerBoneID: number;
  1510. containerID: number;
  1511. curves: {
  1512. x: {
  1513. version: any;
  1514. id: number;
  1515. internalID: number;
  1516. times: number[];
  1517. values: number[];
  1518. attrFlag: number[];
  1519. attrData: number[];
  1520. };
  1521. y: {
  1522. version: any;
  1523. id: number;
  1524. internalID: number;
  1525. times: number[];
  1526. values: number[];
  1527. attrFlag: number[];
  1528. attrData: number[];
  1529. };
  1530. z: {
  1531. version: any;
  1532. id: number;
  1533. internalID: number;
  1534. times: number[];
  1535. values: number[];
  1536. attrFlag: number[];
  1537. attrData: number[];
  1538. };
  1539. };
  1540. };
  1541. }[][],
  1542. length: number,
  1543. frames: number }>,
  1544. length: number,
  1545. fps: number,
  1546. frames: number
  1547. }}
  1548. */
  1549. var returnObject = {
  1550. curves: new Map(),
  1551. layers: {},
  1552. stacks: {},
  1553. length: 0,
  1554. fps: 30,
  1555. frames: 0
  1556. };
  1557. /**
  1558. * @type {Array.<{
  1559. id: number;
  1560. attr: string;
  1561. internalID: number;
  1562. attrX: boolean;
  1563. attrY: boolean;
  1564. attrZ: boolean;
  1565. containerBoneID: number;
  1566. containerID: number;
  1567. }>}
  1568. */
  1569. var animationCurveNodes = [];
  1570. for ( var nodeID in rawNodes ) {
  1571. if ( nodeID.match( /\d+/ ) ) {
  1572. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1573. animationCurveNodes.push( animationNode );
  1574. }
  1575. }
  1576. /**
  1577. * @type {Map.<number, {
  1578. id: number,
  1579. attr: string,
  1580. internalID: number,
  1581. attrX: boolean,
  1582. attrY: boolean,
  1583. attrZ: boolean,
  1584. containerBoneID: number,
  1585. containerID: number,
  1586. curves: {
  1587. x: {
  1588. version: any,
  1589. id: number,
  1590. internalID: number,
  1591. times: number[],
  1592. values: number[],
  1593. attrFlag: number[],
  1594. attrData: number[],
  1595. },
  1596. y: {
  1597. version: any,
  1598. id: number,
  1599. internalID: number,
  1600. times: number[],
  1601. values: number[],
  1602. attrFlag: number[],
  1603. attrData: number[],
  1604. },
  1605. z: {
  1606. version: any,
  1607. id: number,
  1608. internalID: number,
  1609. times: number[],
  1610. values: number[],
  1611. attrFlag: number[],
  1612. attrData: number[],
  1613. }
  1614. }
  1615. }>}
  1616. */
  1617. var tmpMap = new Map();
  1618. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1619. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1620. continue;
  1621. }
  1622. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1623. }
  1624. /**
  1625. * @type {{
  1626. version: any,
  1627. id: number,
  1628. internalID: number,
  1629. times: number[],
  1630. values: number[],
  1631. attrFlag: number[],
  1632. attrData: number[],
  1633. }[]}
  1634. */
  1635. var animationCurves = [];
  1636. for ( nodeID in rawCurves ) {
  1637. if ( nodeID.match( /\d+/ ) ) {
  1638. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1639. // seems like this check would be necessary?
  1640. if ( ! connections.has( animationCurve.id ) ) continue;
  1641. animationCurves.push( animationCurve );
  1642. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1643. var firstParentID = firstParentConn.ID;
  1644. var firstParentRelationship = firstParentConn.relationship;
  1645. var axis = '';
  1646. if ( firstParentRelationship.match( /X/ ) ) {
  1647. axis = 'x';
  1648. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1649. axis = 'y';
  1650. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1651. axis = 'z';
  1652. } else {
  1653. continue;
  1654. }
  1655. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1656. }
  1657. }
  1658. tmpMap.forEach( function ( curveNode ) {
  1659. var id = curveNode.containerBoneID;
  1660. if ( ! returnObject.curves.has( id ) ) {
  1661. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1662. }
  1663. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1664. if ( curveNode.attr === 'R' ) {
  1665. var curves = curveNode.curves;
  1666. // Seems like some FBX files have AnimationCurveNode
  1667. // which doesn't have any connected AnimationCurve.
  1668. // Setting animation parameter for them here.
  1669. if ( curves.x === null ) {
  1670. curves.x = {
  1671. version: null,
  1672. times: [ 0.0 ],
  1673. values: [ 0.0 ]
  1674. };
  1675. }
  1676. if ( curves.y === null ) {
  1677. curves.y = {
  1678. version: null,
  1679. times: [ 0.0 ],
  1680. values: [ 0.0 ]
  1681. };
  1682. }
  1683. if ( curves.z === null ) {
  1684. curves.z = {
  1685. version: null,
  1686. times: [ 0.0 ],
  1687. values: [ 0.0 ]
  1688. };
  1689. }
  1690. curves.x.values = curves.x.values.map( degreeToRadian );
  1691. curves.y.values = curves.y.values.map( degreeToRadian );
  1692. curves.z.values = curves.z.values.map( degreeToRadian );
  1693. if ( curveNode.preRotations !== null ) {
  1694. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1695. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1696. var frameRotation = new THREE.Euler();
  1697. var frameRotationQuaternion = new THREE.Quaternion();
  1698. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1699. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1700. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1701. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1702. curves.x.values[ frame ] = frameRotation.x;
  1703. curves.y.values[ frame ] = frameRotation.y;
  1704. curves.z.values[ frame ] = frameRotation.z;
  1705. }
  1706. }
  1707. }
  1708. } );
  1709. for ( var nodeID in rawLayers ) {
  1710. /**
  1711. * @type {{
  1712. T: {
  1713. id: number;
  1714. attr: string;
  1715. internalID: number;
  1716. attrX: boolean;
  1717. attrY: boolean;
  1718. attrZ: boolean;
  1719. containerBoneID: number;
  1720. containerID: number;
  1721. curves: {
  1722. x: {
  1723. version: any;
  1724. id: number;
  1725. internalID: number;
  1726. times: number[];
  1727. values: number[];
  1728. attrFlag: number[];
  1729. attrData: number[];
  1730. };
  1731. y: {
  1732. version: any;
  1733. id: number;
  1734. internalID: number;
  1735. times: number[];
  1736. values: number[];
  1737. attrFlag: number[];
  1738. attrData: number[];
  1739. };
  1740. z: {
  1741. version: any;
  1742. id: number;
  1743. internalID: number;
  1744. times: number[];
  1745. values: number[];
  1746. attrFlag: number[];
  1747. attrData: number[];
  1748. };
  1749. },
  1750. },
  1751. R: {
  1752. id: number;
  1753. attr: string;
  1754. internalID: number;
  1755. attrX: boolean;
  1756. attrY: boolean;
  1757. attrZ: boolean;
  1758. containerBoneID: number;
  1759. containerID: number;
  1760. curves: {
  1761. x: {
  1762. version: any;
  1763. id: number;
  1764. internalID: number;
  1765. times: number[];
  1766. values: number[];
  1767. attrFlag: number[];
  1768. attrData: number[];
  1769. };
  1770. y: {
  1771. version: any;
  1772. id: number;
  1773. internalID: number;
  1774. times: number[];
  1775. values: number[];
  1776. attrFlag: number[];
  1777. attrData: number[];
  1778. };
  1779. z: {
  1780. version: any;
  1781. id: number;
  1782. internalID: number;
  1783. times: number[];
  1784. values: number[];
  1785. attrFlag: number[];
  1786. attrData: number[];
  1787. };
  1788. },
  1789. },
  1790. S: {
  1791. id: number;
  1792. attr: string;
  1793. internalID: number;
  1794. attrX: boolean;
  1795. attrY: boolean;
  1796. attrZ: boolean;
  1797. containerBoneID: number;
  1798. containerID: number;
  1799. curves: {
  1800. x: {
  1801. version: any;
  1802. id: number;
  1803. internalID: number;
  1804. times: number[];
  1805. values: number[];
  1806. attrFlag: number[];
  1807. attrData: number[];
  1808. };
  1809. y: {
  1810. version: any;
  1811. id: number;
  1812. internalID: number;
  1813. times: number[];
  1814. values: number[];
  1815. attrFlag: number[];
  1816. attrData: number[];
  1817. };
  1818. z: {
  1819. version: any;
  1820. id: number;
  1821. internalID: number;
  1822. times: number[];
  1823. values: number[];
  1824. attrFlag: number[];
  1825. attrData: number[];
  1826. };
  1827. },
  1828. }
  1829. }[]}
  1830. */
  1831. var layer = [];
  1832. var children = connections.get( parseInt( nodeID ) ).children;
  1833. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1834. // Skip lockInfluenceWeights
  1835. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1836. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1837. var boneID = curveNode.containerBoneID;
  1838. if ( layer[ boneID ] === undefined ) {
  1839. layer[ boneID ] = {
  1840. T: null,
  1841. R: null,
  1842. S: null
  1843. };
  1844. }
  1845. layer[ boneID ][ curveNode.attr ] = curveNode;
  1846. }
  1847. }
  1848. returnObject.layers[ nodeID ] = layer;
  1849. }
  1850. for ( var nodeID in rawStacks ) {
  1851. var layers = [];
  1852. var children = connections.get( parseInt( nodeID ) ).children;
  1853. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1854. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1855. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1856. if ( currentLayer !== undefined ) {
  1857. layers.push( currentLayer );
  1858. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1859. var layer = currentLayer[ currentLayerIndex ];
  1860. if ( layer ) {
  1861. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1862. }
  1863. }
  1864. }
  1865. }
  1866. // Do we have an animation clip with actual length?
  1867. if ( timestamps.max > timestamps.min ) {
  1868. returnObject.stacks[ nodeID ] = {
  1869. name: rawStacks[ nodeID ].attrName,
  1870. layers: layers,
  1871. length: timestamps.max - timestamps.min,
  1872. frames: ( timestamps.max - timestamps.min ) * 30
  1873. };
  1874. }
  1875. }
  1876. return returnObject;
  1877. }
  1878. /**
  1879. * @param {Object} FBXTree
  1880. * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
  1881. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1882. * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
  1883. */
  1884. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1885. var rawModels = FBXTree.Objects.subNodes.Model;
  1886. var returnObject = {
  1887. /**
  1888. * @type {number}
  1889. */
  1890. id: animationCurveNode.id,
  1891. /**
  1892. * @type {string}
  1893. */
  1894. attr: animationCurveNode.attrName,
  1895. /**
  1896. * @type {number}
  1897. */
  1898. internalID: animationCurveNode.id,
  1899. /**
  1900. * @type {boolean}
  1901. */
  1902. attrX: false,
  1903. /**
  1904. * @type {boolean}
  1905. */
  1906. attrY: false,
  1907. /**
  1908. * @type {boolean}
  1909. */
  1910. attrZ: false,
  1911. /**
  1912. * @type {number}
  1913. */
  1914. containerBoneID: - 1,
  1915. /**
  1916. * @type {number}
  1917. */
  1918. containerID: - 1,
  1919. curves: {
  1920. x: null,
  1921. y: null,
  1922. z: null
  1923. },
  1924. /**
  1925. * @type {number[]}
  1926. */
  1927. preRotations: null
  1928. };
  1929. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1930. for ( var attributeKey in animationCurveNode.properties ) {
  1931. if ( attributeKey.match( /X/ ) ) {
  1932. returnObject.attrX = true;
  1933. }
  1934. if ( attributeKey.match( /Y/ ) ) {
  1935. returnObject.attrY = true;
  1936. }
  1937. if ( attributeKey.match( /Z/ ) ) {
  1938. returnObject.attrZ = true;
  1939. }
  1940. }
  1941. } else {
  1942. return null;
  1943. }
  1944. var conns = connections.get( returnObject.id );
  1945. var containerIndices = conns.parents;
  1946. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1947. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1948. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1949. } );
  1950. if ( boneID > - 1 ) {
  1951. returnObject.containerBoneID = boneID;
  1952. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1953. var model = rawModels[ returnObject.containerID.toString() ];
  1954. if ( 'PreRotation' in model.properties ) {
  1955. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1956. }
  1957. break;
  1958. }
  1959. }
  1960. return returnObject;
  1961. }
  1962. /**
  1963. * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
  1964. */
  1965. function parseAnimationCurve( animationCurve ) {
  1966. return {
  1967. version: null,
  1968. id: animationCurve.id,
  1969. internalID: animationCurve.id,
  1970. times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( convertFBXTimeToSeconds ),
  1971. values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
  1972. attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
  1973. attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
  1974. };
  1975. }
  1976. /**
  1977. * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1978. * than the max or min respectively.
  1979. * @param {{
  1980. T: {
  1981. id: number,
  1982. attr: string,
  1983. internalID: number,
  1984. attrX: boolean,
  1985. attrY: boolean,
  1986. attrZ: boolean,
  1987. containerBoneID: number,
  1988. containerID: number,
  1989. curves: {
  1990. x: {
  1991. version: any,
  1992. id: number,
  1993. internalID: number,
  1994. times: number[],
  1995. values: number[],
  1996. attrFlag: number[],
  1997. attrData: number[],
  1998. },
  1999. y: {
  2000. version: any,
  2001. id: number,
  2002. internalID: number,
  2003. times: number[],
  2004. values: number[],
  2005. attrFlag: number[],
  2006. attrData: number[],
  2007. },
  2008. z: {
  2009. version: any,
  2010. id: number,
  2011. internalID: number,
  2012. times: number[],
  2013. values: number[],
  2014. attrFlag: number[],
  2015. attrData: number[],
  2016. },
  2017. },
  2018. },
  2019. R: {
  2020. id: number,
  2021. attr: string,
  2022. internalID: number,
  2023. attrX: boolean,
  2024. attrY: boolean,
  2025. attrZ: boolean,
  2026. containerBoneID: number,
  2027. containerID: number,
  2028. curves: {
  2029. x: {
  2030. version: any,
  2031. id: number,
  2032. internalID: number,
  2033. times: number[],
  2034. values: number[],
  2035. attrFlag: number[],
  2036. attrData: number[],
  2037. },
  2038. y: {
  2039. version: any,
  2040. id: number,
  2041. internalID: number,
  2042. times: number[],
  2043. values: number[],
  2044. attrFlag: number[],
  2045. attrData: number[],
  2046. },
  2047. z: {
  2048. version: any,
  2049. id: number,
  2050. internalID: number,
  2051. times: number[],
  2052. values: number[],
  2053. attrFlag: number[],
  2054. attrData: number[],
  2055. },
  2056. },
  2057. },
  2058. S: {
  2059. id: number,
  2060. attr: string,
  2061. internalID: number,
  2062. attrX: boolean,
  2063. attrY: boolean,
  2064. attrZ: boolean,
  2065. containerBoneID: number,
  2066. containerID: number,
  2067. curves: {
  2068. x: {
  2069. version: any,
  2070. id: number,
  2071. internalID: number,
  2072. times: number[],
  2073. values: number[],
  2074. attrFlag: number[],
  2075. attrData: number[],
  2076. },
  2077. y: {
  2078. version: any,
  2079. id: number,
  2080. internalID: number,
  2081. times: number[],
  2082. values: number[],
  2083. attrFlag: number[],
  2084. attrData: number[],
  2085. },
  2086. z: {
  2087. version: any,
  2088. id: number,
  2089. internalID: number,
  2090. times: number[],
  2091. values: number[],
  2092. attrFlag: number[],
  2093. attrData: number[],
  2094. },
  2095. },
  2096. },
  2097. }} layer
  2098. */
  2099. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  2100. if ( layer.R ) {
  2101. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  2102. }
  2103. if ( layer.S ) {
  2104. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  2105. }
  2106. if ( layer.T ) {
  2107. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  2108. }
  2109. }
  2110. /**
  2111. * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  2112. * exceeds the maximum or minimum.
  2113. * @param {{
  2114. x: {
  2115. version: any,
  2116. id: number,
  2117. internalID: number,
  2118. times: number[],
  2119. values: number[],
  2120. attrFlag: number[],
  2121. attrData: number[],
  2122. },
  2123. y: {
  2124. version: any,
  2125. id: number,
  2126. internalID: number,
  2127. times: number[],
  2128. values: number[],
  2129. attrFlag: number[],
  2130. attrData: number[],
  2131. },
  2132. z: {
  2133. version: any,
  2134. id: number,
  2135. internalID: number,
  2136. times: number[],
  2137. values: number[],
  2138. attrFlag: number[],
  2139. attrData: number[],
  2140. }
  2141. }} curve
  2142. */
  2143. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  2144. if ( curve.x ) {
  2145. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  2146. }
  2147. if ( curve.y ) {
  2148. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  2149. }
  2150. if ( curve.z ) {
  2151. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  2152. }
  2153. }
  2154. /**
  2155. * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  2156. * @param {{times: number[]}} axis
  2157. */
  2158. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  2159. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  2160. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  2161. }
  2162. /**
  2163. * @param {{
  2164. curves: Map<number, {
  2165. T: {
  2166. id: number;
  2167. attr: string;
  2168. internalID: number;
  2169. attrX: boolean;
  2170. attrY: boolean;
  2171. attrZ: boolean;
  2172. containerBoneID: number;
  2173. containerID: number;
  2174. curves: {
  2175. x: {
  2176. version: any;
  2177. id: number;
  2178. internalID: number;
  2179. times: number[];
  2180. values: number[];
  2181. attrFlag: number[];
  2182. attrData: number[];
  2183. };
  2184. y: {
  2185. version: any;
  2186. id: number;
  2187. internalID: number;
  2188. times: number[];
  2189. values: number[];
  2190. attrFlag: number[];
  2191. attrData: number[];
  2192. };
  2193. z: {
  2194. version: any;
  2195. id: number;
  2196. internalID: number;
  2197. times: number[];
  2198. values: number[];
  2199. attrFlag: number[];
  2200. attrData: number[];
  2201. };
  2202. };
  2203. };
  2204. R: {
  2205. id: number;
  2206. attr: string;
  2207. internalID: number;
  2208. attrX: boolean;
  2209. attrY: boolean;
  2210. attrZ: boolean;
  2211. containerBoneID: number;
  2212. containerID: number;
  2213. curves: {
  2214. x: {
  2215. version: any;
  2216. id: number;
  2217. internalID: number;
  2218. times: number[];
  2219. values: number[];
  2220. attrFlag: number[];
  2221. attrData: number[];
  2222. };
  2223. y: {
  2224. version: any;
  2225. id: number;
  2226. internalID: number;
  2227. times: number[];
  2228. values: number[];
  2229. attrFlag: number[];
  2230. attrData: number[];
  2231. };
  2232. z: {
  2233. version: any;
  2234. id: number;
  2235. internalID: number;
  2236. times: number[];
  2237. values: number[];
  2238. attrFlag: number[];
  2239. attrData: number[];
  2240. };
  2241. };
  2242. };
  2243. S: {
  2244. id: number;
  2245. attr: string;
  2246. internalID: number;
  2247. attrX: boolean;
  2248. attrY: boolean;
  2249. attrZ: boolean;
  2250. containerBoneID: number;
  2251. containerID: number;
  2252. curves: {
  2253. x: {
  2254. version: any;
  2255. id: number;
  2256. internalID: number;
  2257. times: number[];
  2258. values: number[];
  2259. attrFlag: number[];
  2260. attrData: number[];
  2261. };
  2262. y: {
  2263. version: any;
  2264. id: number;
  2265. internalID: number;
  2266. times: number[];
  2267. values: number[];
  2268. attrFlag: number[];
  2269. attrData: number[];
  2270. };
  2271. z: {
  2272. version: any;
  2273. id: number;
  2274. internalID: number;
  2275. times: number[];
  2276. values: number[];
  2277. attrFlag: number[];
  2278. attrData: number[];
  2279. };
  2280. };
  2281. };
  2282. }>;
  2283. layers: Map<number, {
  2284. T: {
  2285. id: number;
  2286. attr: string;
  2287. internalID: number;
  2288. attrX: boolean;
  2289. attrY: boolean;
  2290. attrZ: boolean;
  2291. containerBoneID: number;
  2292. containerID: number;
  2293. curves: {
  2294. x: {
  2295. version: any;
  2296. id: number;
  2297. internalID: number;
  2298. times: number[];
  2299. values: number[];
  2300. attrFlag: number[];
  2301. attrData: number[];
  2302. };
  2303. y: {
  2304. version: any;
  2305. id: number;
  2306. internalID: number;
  2307. times: number[];
  2308. values: number[];
  2309. attrFlag: number[];
  2310. attrData: number[];
  2311. };
  2312. z: {
  2313. version: any;
  2314. id: number;
  2315. internalID: number;
  2316. times: number[];
  2317. values: number[];
  2318. attrFlag: number[];
  2319. attrData: number[];
  2320. };
  2321. };
  2322. };
  2323. R: {
  2324. id: number;
  2325. attr: string;
  2326. internalID: number;
  2327. attrX: boolean;
  2328. attrY: boolean;
  2329. attrZ: boolean;
  2330. containerBoneID: number;
  2331. containerID: number;
  2332. curves: {
  2333. x: {
  2334. version: any;
  2335. id: number;
  2336. internalID: number;
  2337. times: number[];
  2338. values: number[];
  2339. attrFlag: number[];
  2340. attrData: number[];
  2341. };
  2342. y: {
  2343. version: any;
  2344. id: number;
  2345. internalID: number;
  2346. times: number[];
  2347. values: number[];
  2348. attrFlag: number[];
  2349. attrData: number[];
  2350. };
  2351. z: {
  2352. version: any;
  2353. id: number;
  2354. internalID: number;
  2355. times: number[];
  2356. values: number[];
  2357. attrFlag: number[];
  2358. attrData: number[];
  2359. };
  2360. };
  2361. };
  2362. S: {
  2363. id: number;
  2364. attr: string;
  2365. internalID: number;
  2366. attrX: boolean;
  2367. attrY: boolean;
  2368. attrZ: boolean;
  2369. containerBoneID: number;
  2370. containerID: number;
  2371. curves: {
  2372. x: {
  2373. version: any;
  2374. id: number;
  2375. internalID: number;
  2376. times: number[];
  2377. values: number[];
  2378. attrFlag: number[];
  2379. attrData: number[];
  2380. };
  2381. y: {
  2382. version: any;
  2383. id: number;
  2384. internalID: number;
  2385. times: number[];
  2386. values: number[];
  2387. attrFlag: number[];
  2388. attrData: number[];
  2389. };
  2390. z: {
  2391. version: any;
  2392. id: number;
  2393. internalID: number;
  2394. times: number[];
  2395. values: number[];
  2396. attrFlag: number[];
  2397. attrData: number[];
  2398. };
  2399. };
  2400. };
  2401. }[]>;
  2402. stacks: Map<number, {
  2403. name: string;
  2404. layers: {
  2405. T: {
  2406. id: number;
  2407. attr: string;
  2408. internalID: number;
  2409. attrX: boolean;
  2410. attrY: boolean;
  2411. attrZ: boolean;
  2412. containerBoneID: number;
  2413. containerID: number;
  2414. curves: {
  2415. x: {
  2416. version: any;
  2417. id: number;
  2418. internalID: number;
  2419. times: number[];
  2420. values: number[];
  2421. attrFlag: number[];
  2422. attrData: number[];
  2423. };
  2424. y: {
  2425. version: any;
  2426. id: number;
  2427. internalID: number;
  2428. times: number[];
  2429. values: number[];
  2430. attrFlag: number[];
  2431. attrData: number[];
  2432. };
  2433. z: {
  2434. version: any;
  2435. id: number;
  2436. internalID: number;
  2437. times: number[];
  2438. values: number[];
  2439. attrFlag: number[];
  2440. attrData: number[];
  2441. };
  2442. };
  2443. };
  2444. R: {
  2445. id: number;
  2446. attr: string;
  2447. internalID: number;
  2448. attrX: boolean;
  2449. attrY: boolean;
  2450. attrZ: boolean;
  2451. containerBoneID: number;
  2452. containerID: number;
  2453. curves: {
  2454. x: {
  2455. version: any;
  2456. id: number;
  2457. internalID: number;
  2458. times: number[];
  2459. values: number[];
  2460. attrFlag: number[];
  2461. attrData: number[];
  2462. };
  2463. y: {
  2464. version: any;
  2465. id: number;
  2466. internalID: number;
  2467. times: number[];
  2468. values: number[];
  2469. attrFlag: number[];
  2470. attrData: number[];
  2471. };
  2472. z: {
  2473. version: any;
  2474. id: number;
  2475. internalID: number;
  2476. times: number[];
  2477. values: number[];
  2478. attrFlag: number[];
  2479. attrData: number[];
  2480. };
  2481. };
  2482. };
  2483. S: {
  2484. id: number;
  2485. attr: string;
  2486. internalID: number;
  2487. attrX: boolean;
  2488. attrY: boolean;
  2489. attrZ: boolean;
  2490. containerBoneID: number;
  2491. containerID: number;
  2492. curves: {
  2493. x: {
  2494. version: any;
  2495. id: number;
  2496. internalID: number;
  2497. times: number[];
  2498. values: number[];
  2499. attrFlag: number[];
  2500. attrData: number[];
  2501. };
  2502. y: {
  2503. version: any;
  2504. id: number;
  2505. internalID: number;
  2506. times: number[];
  2507. values: number[];
  2508. attrFlag: number[];
  2509. attrData: number[];
  2510. };
  2511. z: {
  2512. version: any;
  2513. id: number;
  2514. internalID: number;
  2515. times: number[];
  2516. values: number[];
  2517. attrFlag: number[];
  2518. attrData: number[];
  2519. };
  2520. };
  2521. };
  2522. }[][];
  2523. length: number;
  2524. frames: number;
  2525. }>;
  2526. length: number;
  2527. fps: number;
  2528. frames: number;
  2529. }} animations,
  2530. * @param {{skeleton: { bones: THREE.Bone[]}}} group
  2531. */
  2532. function addAnimations( group, animations ) {
  2533. if ( group.animations === undefined ) {
  2534. group.animations = [];
  2535. }
  2536. var stacks = animations.stacks;
  2537. for ( var key in stacks ) {
  2538. var stack = stacks[ key ];
  2539. /**
  2540. * @type {{
  2541. * name: string,
  2542. * fps: number,
  2543. * length: number,
  2544. * hierarchy: Array.<{
  2545. * parent: number,
  2546. * name: string,
  2547. * keys: Array.<{
  2548. * time: number,
  2549. * pos: Array.<number>,
  2550. * rot: Array.<number>,
  2551. * scl: Array.<number>
  2552. * }>
  2553. * }>
  2554. * }}
  2555. */
  2556. var animationData = {
  2557. name: stack.name,
  2558. fps: 30,
  2559. length: stack.length,
  2560. hierarchy: []
  2561. };
  2562. var bones = group.skeleton.bones;
  2563. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2564. var bone = bones[ bonesIndex ];
  2565. var name = bone.name.replace( /.*:/, '' );
  2566. var parentIndex = findIndex( bones, function ( parentBone ) {
  2567. return bone.parent === parentBone;
  2568. } );
  2569. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  2570. }
  2571. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  2572. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2573. var bone = bones[ bonesIndex ];
  2574. var boneIndex = bonesIndex;
  2575. var animationNode = stack.layers[ 0 ][ boneIndex ];
  2576. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  2577. var node = animationData.hierarchy[ hierarchyIndex ];
  2578. if ( node.name === bone.name ) {
  2579. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  2580. }
  2581. }
  2582. }
  2583. }
  2584. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  2585. }
  2586. }
  2587. var euler = new THREE.Euler();
  2588. var quaternion = new THREE.Quaternion();
  2589. /**
  2590. * @param {THREE.Bone} bone
  2591. */
  2592. function generateKey( animations, animationNode, bone, frame ) {
  2593. var key = {
  2594. time: frame / animations.fps,
  2595. pos: bone.position.toArray(),
  2596. rot: bone.quaternion.toArray(),
  2597. scl: bone.scale.toArray()
  2598. };
  2599. if ( animationNode === undefined ) return key;
  2600. try {
  2601. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  2602. key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
  2603. }
  2604. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  2605. var rotationX = animationNode.R.curves.x.values[ frame ];
  2606. var rotationY = animationNode.R.curves.y.values[ frame ];
  2607. var rotationZ = animationNode.R.curves.z.values[ frame ];
  2608. quaternion.setFromEuler( euler.set( rotationX, rotationY, rotationZ, 'ZYX' ) );
  2609. key.rot = quaternion.toArray();
  2610. }
  2611. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  2612. key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
  2613. }
  2614. } catch ( error ) {
  2615. // Curve is not fully plotted.
  2616. console.log( 'THREE.FBXLoader: ', bone );
  2617. console.log( 'THREE.FBXLoader: ', error );
  2618. }
  2619. return key;
  2620. }
  2621. var AXES = [ 'x', 'y', 'z' ];
  2622. function hasCurve( animationNode, attribute ) {
  2623. if ( animationNode === undefined ) {
  2624. return false;
  2625. }
  2626. var attributeNode = animationNode[ attribute ];
  2627. if ( ! attributeNode ) {
  2628. return false;
  2629. }
  2630. return AXES.every( function ( key ) {
  2631. return attributeNode.curves[ key ] !== null;
  2632. } );
  2633. }
  2634. function hasKeyOnFrame( attributeNode, frame ) {
  2635. return AXES.every( function ( key ) {
  2636. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  2637. } );
  2638. }
  2639. function isKeyExistOnFrame( curve, frame ) {
  2640. return curve.values[ frame ] !== undefined;
  2641. }
  2642. /**
  2643. * An instance of a Vertex with data for drawing vertices to the screen.
  2644. * @constructor
  2645. */
  2646. function Vertex() {
  2647. /**
  2648. * Position of the vertex.
  2649. * @type {THREE.Vector3}
  2650. */
  2651. this.position = new THREE.Vector3();
  2652. /**
  2653. * Normal of the vertex
  2654. * @type {THREE.Vector3}
  2655. */
  2656. this.normal = new THREE.Vector3();
  2657. /**
  2658. * UV coordinates of the vertex.
  2659. * @type {THREE.Vector2}
  2660. */
  2661. this.uv = new THREE.Vector2();
  2662. /**
  2663. * Color of the vertex
  2664. * @type {THREE.Vector3}
  2665. */
  2666. this.color = new THREE.Vector3();
  2667. /**
  2668. * Indices of the bones vertex is influenced by.
  2669. * @type {THREE.Vector4}
  2670. */
  2671. this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
  2672. /**
  2673. * Weights that each bone influences the vertex.
  2674. * @type {THREE.Vector4}
  2675. */
  2676. this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
  2677. }
  2678. Object.assign( Vertex.prototype, {
  2679. copy: function ( target ) {
  2680. var returnVar = target || new Vertex();
  2681. returnVar.position.copy( this.position );
  2682. returnVar.normal.copy( this.normal );
  2683. returnVar.uv.copy( this.uv );
  2684. returnVar.skinIndices.copy( this.skinIndices );
  2685. returnVar.skinWeights.copy( this.skinWeights );
  2686. return returnVar;
  2687. },
  2688. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2689. this.position.toArray( vertexBuffer, vertexBuffer.length );
  2690. this.normal.toArray( normalBuffer, normalBuffer.length );
  2691. this.uv.toArray( uvBuffer, uvBuffer.length );
  2692. this.color.toArray( colorBuffer, colorBuffer.length );
  2693. this.skinIndices.toArray( skinIndexBuffer, skinIndexBuffer.length );
  2694. this.skinWeights.toArray( skinWeightBuffer, skinWeightBuffer.length );
  2695. }
  2696. } );
  2697. /**
  2698. * @constructor
  2699. */
  2700. function Triangle() {
  2701. /**
  2702. * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
  2703. */
  2704. this.vertices = [];
  2705. }
  2706. Object.assign( Triangle.prototype, {
  2707. copy: function ( target ) {
  2708. var returnVar = target || new Triangle();
  2709. for ( var i = 0; i < this.vertices.length; ++ i ) {
  2710. this.vertices[ i ].copy( returnVar.vertices[ i ] );
  2711. }
  2712. return returnVar;
  2713. },
  2714. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2715. var vertices = this.vertices;
  2716. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  2717. vertices[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2718. }
  2719. }
  2720. } );
  2721. /**
  2722. * @constructor
  2723. */
  2724. function Face() {
  2725. /**
  2726. * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
  2727. */
  2728. this.triangles = [];
  2729. this.materialIndex = 0;
  2730. }
  2731. Object.assign( Face.prototype, {
  2732. copy: function ( target ) {
  2733. var returnVar = target || new Face();
  2734. for ( var i = 0; i < this.triangles.length; ++ i ) {
  2735. this.triangles[ i ].copy( returnVar.triangles[ i ] );
  2736. }
  2737. returnVar.materialIndex = this.materialIndex;
  2738. return returnVar;
  2739. },
  2740. genTrianglesFromVertices: function ( vertexArray ) {
  2741. for ( var i = 2; i < vertexArray.length; ++ i ) {
  2742. var triangle = new Triangle();
  2743. triangle.vertices[ 0 ] = vertexArray[ 0 ];
  2744. triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
  2745. triangle.vertices[ 2 ] = vertexArray[ i ];
  2746. this.triangles.push( triangle );
  2747. }
  2748. },
  2749. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer ) {
  2750. var triangles = this.triangles;
  2751. var materialIndex = this.materialIndex;
  2752. for ( var i = 0, l = triangles.length; i < l; ++ i ) {
  2753. triangles[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2754. append( materialIndexBuffer, [ materialIndex, materialIndex, materialIndex ] );
  2755. }
  2756. }
  2757. } );
  2758. /**
  2759. * @constructor
  2760. */
  2761. function Geometry() {
  2762. /**
  2763. * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
  2764. */
  2765. this.faces = [];
  2766. /**
  2767. * @type {{}|THREE.Skeleton}
  2768. */
  2769. this.skeleton = null;
  2770. }
  2771. Object.assign( Geometry.prototype, {
  2772. /**
  2773. * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  2774. */
  2775. flattenToBuffers: function () {
  2776. var vertexBuffer = [];
  2777. var normalBuffer = [];
  2778. var uvBuffer = [];
  2779. var colorBuffer = [];
  2780. var skinIndexBuffer = [];
  2781. var skinWeightBuffer = [];
  2782. var materialIndexBuffer = [];
  2783. var faces = this.faces;
  2784. for ( var i = 0, l = faces.length; i < l; ++ i ) {
  2785. faces[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer );
  2786. }
  2787. return {
  2788. vertexBuffer: vertexBuffer,
  2789. normalBuffer: normalBuffer,
  2790. uvBuffer: uvBuffer,
  2791. colorBuffer: colorBuffer,
  2792. skinIndexBuffer: skinIndexBuffer,
  2793. skinWeightBuffer: skinWeightBuffer,
  2794. materialIndexBuffer: materialIndexBuffer
  2795. };
  2796. }
  2797. } );
  2798. function TextParser() {}
  2799. Object.assign( TextParser.prototype, {
  2800. getPrevNode: function () {
  2801. return this.nodeStack[ this.currentIndent - 2 ];
  2802. },
  2803. getCurrentNode: function () {
  2804. return this.nodeStack[ this.currentIndent - 1 ];
  2805. },
  2806. getCurrentProp: function () {
  2807. return this.currentProp;
  2808. },
  2809. pushStack: function ( node ) {
  2810. this.nodeStack.push( node );
  2811. this.currentIndent += 1;
  2812. },
  2813. popStack: function () {
  2814. this.nodeStack.pop();
  2815. this.currentIndent -= 1;
  2816. },
  2817. setCurrentProp: function ( val, name ) {
  2818. this.currentProp = val;
  2819. this.currentPropName = name;
  2820. },
  2821. // ----------parse ---------------------------------------------------
  2822. parse: function ( text ) {
  2823. this.currentIndent = 0;
  2824. this.allNodes = new FBXTree();
  2825. this.nodeStack = [];
  2826. this.currentProp = [];
  2827. this.currentPropName = '';
  2828. var split = text.split( '\n' );
  2829. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  2830. var l = split[ lineNum ];
  2831. // skip comment line
  2832. if ( l.match( /^[\s\t]*;/ ) ) {
  2833. continue;
  2834. }
  2835. // skip empty line
  2836. if ( l.match( /^[\s\t]*$/ ) ) {
  2837. continue;
  2838. }
  2839. // beginning of node
  2840. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  2841. var match = l.match( beginningOfNodeExp );
  2842. if ( match ) {
  2843. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2844. var nodeAttrs = match[ 2 ].split( ',' );
  2845. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2846. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2847. }
  2848. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2849. continue;
  2850. }
  2851. // node's property
  2852. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  2853. var match = l.match( propExp );
  2854. if ( match ) {
  2855. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2856. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2857. // for special case: base64 image data follows "Content: ," line
  2858. // Content: ,
  2859. // "iVB..."
  2860. if ( propName === 'Content' && propValue === ',' ) {
  2861. propValue = split[ ++ lineNum ].replace( /"/g, '' ).trim();
  2862. }
  2863. this.parseNodeProperty( l, propName, propValue );
  2864. continue;
  2865. }
  2866. // end of node
  2867. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  2868. if ( l.match( endOfNodeExp ) ) {
  2869. this.nodeEnd();
  2870. continue;
  2871. }
  2872. // for special case,
  2873. //
  2874. // Vertices: *8670 {
  2875. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  2876. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  2877. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  2878. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  2879. //
  2880. // these case the lines must contiue with previous line
  2881. if ( l.match( /^[^\s\t}]/ ) ) {
  2882. this.parseNodePropertyContinued( l );
  2883. }
  2884. }
  2885. return this.allNodes;
  2886. },
  2887. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  2888. // var nodeName = match[1];
  2889. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  2890. var attrs = this.parseNodeAttr( nodeAttrs );
  2891. var currentNode = this.getCurrentNode();
  2892. // a top node
  2893. if ( this.currentIndent === 0 ) {
  2894. this.allNodes.add( nodeName, node );
  2895. } else {
  2896. // a subnode
  2897. // already exists subnode, then append it
  2898. if ( nodeName in currentNode.subNodes ) {
  2899. var tmp = currentNode.subNodes[ nodeName ];
  2900. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  2901. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  2902. if ( attrs.id === '' ) {
  2903. currentNode.subNodes[ nodeName ] = [];
  2904. currentNode.subNodes[ nodeName ].push( tmp );
  2905. } else {
  2906. currentNode.subNodes[ nodeName ] = {};
  2907. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  2908. }
  2909. }
  2910. if ( attrs.id === '' ) {
  2911. currentNode.subNodes[ nodeName ].push( node );
  2912. } else {
  2913. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2914. }
  2915. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  2916. currentNode.subNodes[ nodeName ] = {};
  2917. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2918. } else {
  2919. currentNode.subNodes[ nodeName ] = node;
  2920. }
  2921. }
  2922. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  2923. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  2924. if ( nodeAttrs ) {
  2925. node.id = attrs.id;
  2926. node.attrName = attrs.name;
  2927. node.attrType = attrs.type;
  2928. }
  2929. this.pushStack( node );
  2930. },
  2931. parseNodeAttr: function ( attrs ) {
  2932. var id = attrs[ 0 ];
  2933. if ( attrs[ 0 ] !== '' ) {
  2934. id = parseInt( attrs[ 0 ] );
  2935. if ( isNaN( id ) ) {
  2936. // PolygonVertexIndex: *16380 {
  2937. id = attrs[ 0 ];
  2938. }
  2939. }
  2940. var name = '', type = '';
  2941. if ( attrs.length > 1 ) {
  2942. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  2943. type = attrs[ 2 ];
  2944. }
  2945. return { id: id, name: name, type: type };
  2946. },
  2947. parseNodeProperty: function ( line, propName, propValue ) {
  2948. var currentNode = this.getCurrentNode();
  2949. var parentName = currentNode.name;
  2950. // special case parent node's is like "Properties70"
  2951. // these children nodes must treat with careful
  2952. if ( parentName !== undefined ) {
  2953. var propMatch = parentName.match( /Properties(\d)+/ );
  2954. if ( propMatch ) {
  2955. this.parseNodeSpecialProperty( line, propName, propValue );
  2956. return;
  2957. }
  2958. }
  2959. // special case Connections
  2960. if ( propName === 'C' ) {
  2961. var connProps = propValue.split( ',' ).slice( 1 );
  2962. var from = parseInt( connProps[ 0 ] );
  2963. var to = parseInt( connProps[ 1 ] );
  2964. var rest = propValue.split( ',' ).slice( 3 );
  2965. propName = 'connections';
  2966. propValue = [ from, to ];
  2967. append( propValue, rest );
  2968. if ( currentNode.properties[ propName ] === undefined ) {
  2969. currentNode.properties[ propName ] = [];
  2970. }
  2971. }
  2972. // special case Connections
  2973. if ( propName === 'Node' ) {
  2974. var id = parseInt( propValue );
  2975. currentNode.properties.id = id;
  2976. currentNode.id = id;
  2977. }
  2978. // already exists in properties, then append this
  2979. if ( propName in currentNode.properties ) {
  2980. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  2981. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2982. currentNode.properties[ propName ].push( propValue );
  2983. } else {
  2984. currentNode.properties[ propName ] += propValue;
  2985. }
  2986. } else {
  2987. // console.log( propName + ": " + propValue );
  2988. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2989. currentNode.properties[ propName ].push( propValue );
  2990. } else {
  2991. currentNode.properties[ propName ] = propValue;
  2992. }
  2993. }
  2994. this.setCurrentProp( currentNode.properties, propName );
  2995. },
  2996. // TODO:
  2997. parseNodePropertyContinued: function ( line ) {
  2998. this.currentProp[ this.currentPropName ] += line;
  2999. },
  3000. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  3001. // split this
  3002. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  3003. // into array like below
  3004. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  3005. var props = propValue.split( '",' );
  3006. for ( var i = 0, l = props.length; i < l; i ++ ) {
  3007. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  3008. }
  3009. var innerPropName = props[ 0 ];
  3010. var innerPropType1 = props[ 1 ];
  3011. var innerPropType2 = props[ 2 ];
  3012. var innerPropFlag = props[ 3 ];
  3013. var innerPropValue = props[ 4 ];
  3014. /*
  3015. if ( innerPropValue === undefined ) {
  3016. innerPropValue = props[3];
  3017. }
  3018. */
  3019. // cast value in its type
  3020. switch ( innerPropType1 ) {
  3021. case 'int':
  3022. innerPropValue = parseInt( innerPropValue );
  3023. break;
  3024. case 'double':
  3025. innerPropValue = parseFloat( innerPropValue );
  3026. break;
  3027. case 'ColorRGB':
  3028. case 'Vector3D':
  3029. innerPropValue = parseFloatArray( innerPropValue );
  3030. break;
  3031. }
  3032. // CAUTION: these props must append to parent's parent
  3033. this.getPrevNode().properties[ innerPropName ] = {
  3034. 'type': innerPropType1,
  3035. 'type2': innerPropType2,
  3036. 'flag': innerPropFlag,
  3037. 'value': innerPropValue
  3038. };
  3039. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  3040. },
  3041. nodeEnd: function () {
  3042. this.popStack();
  3043. },
  3044. /* ---------------------------------------------------------------- */
  3045. /* util */
  3046. isFlattenNode: function ( node ) {
  3047. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  3048. }
  3049. } );
  3050. // Binary format specification:
  3051. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  3052. // https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  3053. function BinaryParser() {}
  3054. Object.assign( BinaryParser.prototype, {
  3055. /**
  3056. * Parses binary data and builds FBXTree as much compatible as possible with the one built by TextParser.
  3057. * @param {ArrayBuffer} buffer
  3058. * @returns {THREE.FBXTree}
  3059. */
  3060. parse: function ( buffer ) {
  3061. var reader = new BinaryReader( buffer );
  3062. reader.skip( 23 ); // skip magic 23 bytes
  3063. var version = reader.getUint32();
  3064. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  3065. var allNodes = new FBXTree();
  3066. while ( ! this.endOfContent( reader ) ) {
  3067. var node = this.parseNode( reader, version );
  3068. if ( node !== null ) allNodes.add( node.name, node );
  3069. }
  3070. return allNodes;
  3071. },
  3072. /**
  3073. * Checks if reader has reached the end of content.
  3074. * @param {BinaryReader} reader
  3075. * @returns {boolean}
  3076. */
  3077. endOfContent: function ( reader ) {
  3078. // footer size: 160bytes + 16-byte alignment padding
  3079. // - 16bytes: magic
  3080. // - padding til 16-byte alignment (at least 1byte?)
  3081. // (seems like some exporters embed fixed 15 or 16bytes?)
  3082. // - 4bytes: magic
  3083. // - 4bytes: version
  3084. // - 120bytes: zero
  3085. // - 16bytes: magic
  3086. if ( reader.size() % 16 === 0 ) {
  3087. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  3088. } else {
  3089. return reader.getOffset() + 160 + 16 >= reader.size();
  3090. }
  3091. },
  3092. /**
  3093. * Parses Node as much compatible as possible with the one parsed by TextParser
  3094. * TODO: could be optimized more?
  3095. * @param {BinaryReader} reader
  3096. * @param {number} version
  3097. * @returns {Object} - Returns an Object as node, or null if NULL-record.
  3098. */
  3099. parseNode: function ( reader, version ) {
  3100. // The first three data sizes depends on version.
  3101. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3102. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3103. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3104. var nameLen = reader.getUint8();
  3105. var name = reader.getString( nameLen );
  3106. // Regards this node as NULL-record if endOffset is zero
  3107. if ( endOffset === 0 ) return null;
  3108. var propertyList = [];
  3109. for ( var i = 0; i < numProperties; i ++ ) {
  3110. propertyList.push( this.parseProperty( reader ) );
  3111. }
  3112. // Regards the first three elements in propertyList as id, attrName, and attrType
  3113. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  3114. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  3115. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  3116. var subNodes = {};
  3117. var properties = {};
  3118. var isSingleProperty = false;
  3119. // if this node represents just a single property
  3120. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  3121. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  3122. isSingleProperty = true;
  3123. }
  3124. while ( endOffset > reader.getOffset() ) {
  3125. var node = this.parseNode( reader, version );
  3126. if ( node === null ) continue;
  3127. // special case: child node is single property
  3128. if ( node.singleProperty === true ) {
  3129. var value = node.propertyList[ 0 ];
  3130. if ( Array.isArray( value ) ) {
  3131. // node represents
  3132. // Vertices: *3 {
  3133. // a: 0.01, 0.02, 0.03
  3134. // }
  3135. // of text format here.
  3136. node.properties[ node.name ] = node.propertyList[ 0 ];
  3137. subNodes[ node.name ] = node;
  3138. // Later phase expects single property array is in node.properties.a as String.
  3139. // TODO: optimize
  3140. node.properties.a = value.toString();
  3141. } else {
  3142. // node represents
  3143. // Version: 100
  3144. // of text format here.
  3145. properties[ node.name ] = value;
  3146. }
  3147. continue;
  3148. }
  3149. // special case: connections
  3150. if ( name === 'Connections' && node.name === 'C' ) {
  3151. var array = [];
  3152. // node.propertyList would be like
  3153. // ["OO", 111264976, 144038752, "d|x"] (?, from, to, additional values)
  3154. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  3155. array[ i - 1 ] = node.propertyList[ i ];
  3156. }
  3157. if ( properties.connections === undefined ) {
  3158. properties.connections = [];
  3159. }
  3160. properties.connections.push( array );
  3161. continue;
  3162. }
  3163. // special case: child node is Properties\d+
  3164. if ( node.name.match( /^Properties\d+$/ ) ) {
  3165. // move child node's properties to this node.
  3166. var keys = Object.keys( node.properties );
  3167. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  3168. var key = keys[ i ];
  3169. properties[ key ] = node.properties[ key ];
  3170. }
  3171. continue;
  3172. }
  3173. // special case: properties
  3174. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  3175. var innerPropName = node.propertyList[ 0 ];
  3176. var innerPropType1 = node.propertyList[ 1 ];
  3177. var innerPropType2 = node.propertyList[ 2 ];
  3178. var innerPropFlag = node.propertyList[ 3 ];
  3179. var innerPropValue;
  3180. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  3181. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  3182. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' ||
  3183. innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3184. innerPropValue = [
  3185. node.propertyList[ 4 ],
  3186. node.propertyList[ 5 ],
  3187. node.propertyList[ 6 ]
  3188. ];
  3189. } else {
  3190. innerPropValue = node.propertyList[ 4 ];
  3191. }
  3192. if ( innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3193. innerPropValue = innerPropValue.toString();
  3194. }
  3195. // this will be copied to parent. see above.
  3196. properties[ innerPropName ] = {
  3197. 'type': innerPropType1,
  3198. 'type2': innerPropType2,
  3199. 'flag': innerPropFlag,
  3200. 'value': innerPropValue
  3201. };
  3202. continue;
  3203. }
  3204. // standard case
  3205. // follows TextParser's manner.
  3206. if ( subNodes[ node.name ] === undefined ) {
  3207. if ( typeof node.id === 'number' ) {
  3208. subNodes[ node.name ] = {};
  3209. subNodes[ node.name ][ node.id ] = node;
  3210. } else {
  3211. subNodes[ node.name ] = node;
  3212. }
  3213. } else {
  3214. if ( node.id === '' ) {
  3215. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  3216. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  3217. }
  3218. subNodes[ node.name ].push( node );
  3219. } else {
  3220. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  3221. subNodes[ node.name ][ node.id ] = node;
  3222. } else {
  3223. // conflict id. irregular?
  3224. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  3225. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  3226. }
  3227. subNodes[ node.name ][ node.id ].push( node );
  3228. }
  3229. }
  3230. }
  3231. }
  3232. return {
  3233. singleProperty: isSingleProperty,
  3234. id: id,
  3235. attrName: attrName,
  3236. attrType: attrType,
  3237. name: name,
  3238. properties: properties,
  3239. propertyList: propertyList, // raw property list, would be used by parent
  3240. subNodes: subNodes
  3241. };
  3242. },
  3243. parseProperty: function ( reader ) {
  3244. var type = reader.getChar();
  3245. switch ( type ) {
  3246. case 'F':
  3247. return reader.getFloat32();
  3248. case 'D':
  3249. return reader.getFloat64();
  3250. case 'L':
  3251. return reader.getInt64();
  3252. case 'I':
  3253. return reader.getInt32();
  3254. case 'Y':
  3255. return reader.getInt16();
  3256. case 'C':
  3257. return reader.getBoolean();
  3258. case 'f':
  3259. case 'd':
  3260. case 'l':
  3261. case 'i':
  3262. case 'b':
  3263. var arrayLength = reader.getUint32();
  3264. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  3265. var compressedLength = reader.getUint32();
  3266. if ( encoding === 0 ) {
  3267. switch ( type ) {
  3268. case 'f':
  3269. return reader.getFloat32Array( arrayLength );
  3270. case 'd':
  3271. return reader.getFloat64Array( arrayLength );
  3272. case 'l':
  3273. return reader.getInt64Array( arrayLength );
  3274. case 'i':
  3275. return reader.getInt32Array( arrayLength );
  3276. case 'b':
  3277. return reader.getBooleanArray( arrayLength );
  3278. }
  3279. }
  3280. if ( window.Zlib === undefined ) {
  3281. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  3282. }
  3283. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  3284. var reader2 = new BinaryReader( inflate.decompress().buffer );
  3285. switch ( type ) {
  3286. case 'f':
  3287. return reader2.getFloat32Array( arrayLength );
  3288. case 'd':
  3289. return reader2.getFloat64Array( arrayLength );
  3290. case 'l':
  3291. return reader2.getInt64Array( arrayLength );
  3292. case 'i':
  3293. return reader2.getInt32Array( arrayLength );
  3294. case 'b':
  3295. return reader2.getBooleanArray( arrayLength );
  3296. }
  3297. case 'S':
  3298. var length = reader.getUint32();
  3299. return reader.getString( length );
  3300. case 'R':
  3301. var length = reader.getUint32();
  3302. return reader.getArrayBuffer( length );
  3303. default:
  3304. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  3305. }
  3306. }
  3307. } );
  3308. function BinaryReader( buffer, littleEndian ) {
  3309. this.dv = new DataView( buffer );
  3310. this.offset = 0;
  3311. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  3312. }
  3313. Object.assign( BinaryReader.prototype, {
  3314. getOffset: function () {
  3315. return this.offset;
  3316. },
  3317. size: function () {
  3318. return this.dv.buffer.byteLength;
  3319. },
  3320. skip: function ( length ) {
  3321. this.offset += length;
  3322. },
  3323. // seems like true/false representation depends on exporter.
  3324. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  3325. // then sees LSB.
  3326. getBoolean: function () {
  3327. return ( this.getUint8() & 1 ) === 1;
  3328. },
  3329. getBooleanArray: function ( size ) {
  3330. var a = [];
  3331. for ( var i = 0; i < size; i ++ ) {
  3332. a.push( this.getBoolean() );
  3333. }
  3334. return a;
  3335. },
  3336. getInt8: function () {
  3337. var value = this.dv.getInt8( this.offset );
  3338. this.offset += 1;
  3339. return value;
  3340. },
  3341. getInt8Array: function ( size ) {
  3342. var a = [];
  3343. for ( var i = 0; i < size; i ++ ) {
  3344. a.push( this.getInt8() );
  3345. }
  3346. return a;
  3347. },
  3348. getUint8: function () {
  3349. var value = this.dv.getUint8( this.offset );
  3350. this.offset += 1;
  3351. return value;
  3352. },
  3353. getUint8Array: function ( size ) {
  3354. var a = [];
  3355. for ( var i = 0; i < size; i ++ ) {
  3356. a.push( this.getUint8() );
  3357. }
  3358. return a;
  3359. },
  3360. getInt16: function () {
  3361. var value = this.dv.getInt16( this.offset, this.littleEndian );
  3362. this.offset += 2;
  3363. return value;
  3364. },
  3365. getInt16Array: function ( size ) {
  3366. var a = [];
  3367. for ( var i = 0; i < size; i ++ ) {
  3368. a.push( this.getInt16() );
  3369. }
  3370. return a;
  3371. },
  3372. getUint16: function () {
  3373. var value = this.dv.getUint16( this.offset, this.littleEndian );
  3374. this.offset += 2;
  3375. return value;
  3376. },
  3377. getUint16Array: function ( size ) {
  3378. var a = [];
  3379. for ( var i = 0; i < size; i ++ ) {
  3380. a.push( this.getUint16() );
  3381. }
  3382. return a;
  3383. },
  3384. getInt32: function () {
  3385. var value = this.dv.getInt32( this.offset, this.littleEndian );
  3386. this.offset += 4;
  3387. return value;
  3388. },
  3389. getInt32Array: function ( size ) {
  3390. var a = [];
  3391. for ( var i = 0; i < size; i ++ ) {
  3392. a.push( this.getInt32() );
  3393. }
  3394. return a;
  3395. },
  3396. getUint32: function () {
  3397. var value = this.dv.getUint32( this.offset, this.littleEndian );
  3398. this.offset += 4;
  3399. return value;
  3400. },
  3401. getUint32Array: function ( size ) {
  3402. var a = [];
  3403. for ( var i = 0; i < size; i ++ ) {
  3404. a.push( this.getUint32() );
  3405. }
  3406. return a;
  3407. },
  3408. // JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
  3409. // 1 << 32 will return 1 so using multiply operation instead here.
  3410. // There'd be a possibility that this method returns wrong value if the value
  3411. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  3412. // TODO: safely handle 64-bit integer
  3413. getInt64: function () {
  3414. var low, high;
  3415. if ( this.littleEndian ) {
  3416. low = this.getUint32();
  3417. high = this.getUint32();
  3418. } else {
  3419. high = this.getUint32();
  3420. low = this.getUint32();
  3421. }
  3422. // calculate negative value
  3423. if ( high & 0x80000000 ) {
  3424. high = ~ high & 0xFFFFFFFF;
  3425. low = ~ low & 0xFFFFFFFF;
  3426. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  3427. low = ( low + 1 ) & 0xFFFFFFFF;
  3428. return - ( high * 0x100000000 + low );
  3429. }
  3430. return high * 0x100000000 + low;
  3431. },
  3432. getInt64Array: function ( size ) {
  3433. var a = [];
  3434. for ( var i = 0; i < size; i ++ ) {
  3435. a.push( this.getInt64() );
  3436. }
  3437. return a;
  3438. },
  3439. // Note: see getInt64() comment
  3440. getUint64: function () {
  3441. var low, high;
  3442. if ( this.littleEndian ) {
  3443. low = this.getUint32();
  3444. high = this.getUint32();
  3445. } else {
  3446. high = this.getUint32();
  3447. low = this.getUint32();
  3448. }
  3449. return high * 0x100000000 + low;
  3450. },
  3451. getUint64Array: function ( size ) {
  3452. var a = [];
  3453. for ( var i = 0; i < size; i ++ ) {
  3454. a.push( this.getUint64() );
  3455. }
  3456. return a;
  3457. },
  3458. getFloat32: function () {
  3459. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  3460. this.offset += 4;
  3461. return value;
  3462. },
  3463. getFloat32Array: function ( size ) {
  3464. var a = [];
  3465. for ( var i = 0; i < size; i ++ ) {
  3466. a.push( this.getFloat32() );
  3467. }
  3468. return a;
  3469. },
  3470. getFloat64: function () {
  3471. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  3472. this.offset += 8;
  3473. return value;
  3474. },
  3475. getFloat64Array: function ( size ) {
  3476. var a = [];
  3477. for ( var i = 0; i < size; i ++ ) {
  3478. a.push( this.getFloat64() );
  3479. }
  3480. return a;
  3481. },
  3482. getArrayBuffer: function ( size ) {
  3483. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  3484. this.offset += size;
  3485. return value;
  3486. },
  3487. getChar: function () {
  3488. return String.fromCharCode( this.getUint8() );
  3489. },
  3490. getString: function ( size ) {
  3491. var s = '';
  3492. while ( size > 0 ) {
  3493. var value = this.getUint8();
  3494. size --;
  3495. if ( value === 0 ) break;
  3496. s += String.fromCharCode( value );
  3497. }
  3498. this.skip( size );
  3499. return s;
  3500. }
  3501. } );
  3502. function FBXTree() {}
  3503. Object.assign( FBXTree.prototype, {
  3504. add: function ( key, val ) {
  3505. this[ key ] = val;
  3506. },
  3507. searchConnectionParent: function ( id ) {
  3508. if ( this.__cache_search_connection_parent === undefined ) {
  3509. this.__cache_search_connection_parent = [];
  3510. }
  3511. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  3512. return this.__cache_search_connection_parent[ id ];
  3513. } else {
  3514. this.__cache_search_connection_parent[ id ] = [];
  3515. }
  3516. var conns = this.Connections.properties.connections;
  3517. var results = [];
  3518. for ( var i = 0; i < conns.length; ++ i ) {
  3519. if ( conns[ i ][ 0 ] == id ) {
  3520. // 0 means scene root
  3521. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  3522. results.push( res );
  3523. }
  3524. }
  3525. if ( results.length > 0 ) {
  3526. append( this.__cache_search_connection_parent[ id ], results );
  3527. return results;
  3528. } else {
  3529. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  3530. return [ - 1 ];
  3531. }
  3532. },
  3533. searchConnectionChildren: function ( id ) {
  3534. if ( this.__cache_search_connection_children === undefined ) {
  3535. this.__cache_search_connection_children = [];
  3536. }
  3537. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  3538. return this.__cache_search_connection_children[ id ];
  3539. } else {
  3540. this.__cache_search_connection_children[ id ] = [];
  3541. }
  3542. var conns = this.Connections.properties.connections;
  3543. var res = [];
  3544. for ( var i = 0; i < conns.length; ++ i ) {
  3545. if ( conns[ i ][ 1 ] == id ) {
  3546. // 0 means scene root
  3547. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  3548. // there may more than one kid, then search to the end
  3549. }
  3550. }
  3551. if ( res.length > 0 ) {
  3552. append( this.__cache_search_connection_children[ id ], res );
  3553. return res;
  3554. } else {
  3555. this.__cache_search_connection_children[ id ] = [ ];
  3556. return [ ];
  3557. }
  3558. },
  3559. searchConnectionType: function ( id, to ) {
  3560. var key = id + ',' + to; // TODO: to hash
  3561. if ( this.__cache_search_connection_type === undefined ) {
  3562. this.__cache_search_connection_type = {};
  3563. }
  3564. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  3565. return this.__cache_search_connection_type[ key ];
  3566. } else {
  3567. this.__cache_search_connection_type[ key ] = '';
  3568. }
  3569. var conns = this.Connections.properties.connections;
  3570. for ( var i = 0; i < conns.length; ++ i ) {
  3571. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  3572. // 0 means scene root
  3573. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  3574. return conns[ i ][ 2 ];
  3575. }
  3576. }
  3577. this.__cache_search_connection_type[ id ] = null;
  3578. return null;
  3579. }
  3580. } );
  3581. /**
  3582. * @param {ArrayBuffer} buffer
  3583. * @returns {boolean}
  3584. */
  3585. function isFbxFormatBinary( buffer ) {
  3586. var CORRECT = 'Kaydara FBX Binary \0';
  3587. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  3588. }
  3589. /**
  3590. * @returns {boolean}
  3591. */
  3592. function isFbxFormatASCII( text ) {
  3593. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  3594. var cursor = 0;
  3595. function read( offset ) {
  3596. var result = text[ offset - 1 ];
  3597. text = text.slice( cursor + offset );
  3598. cursor ++;
  3599. return result;
  3600. }
  3601. for ( var i = 0; i < CORRECT.length; ++ i ) {
  3602. var num = read( 1 );
  3603. if ( num === CORRECT[ i ] ) {
  3604. return false;
  3605. }
  3606. }
  3607. return true;
  3608. }
  3609. /**
  3610. * @returns {number}
  3611. */
  3612. function getFbxVersion( text ) {
  3613. var versionRegExp = /FBXVersion: (\d+)/;
  3614. var match = text.match( versionRegExp );
  3615. if ( match ) {
  3616. var version = parseInt( match[ 1 ] );
  3617. return version;
  3618. }
  3619. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  3620. }
  3621. /**
  3622. * Converts FBX ticks into real time seconds.
  3623. * @param {number} time - FBX tick timestamp to convert.
  3624. * @returns {number} - FBX tick in real world time.
  3625. */
  3626. function convertFBXTimeToSeconds( time ) {
  3627. // Constant is FBX ticks per second.
  3628. return time / 46186158000;
  3629. }
  3630. /**
  3631. * Parses comma separated list of float numbers and returns them in an array.
  3632. * @example
  3633. * // Returns [ 5.6, 9.4, 2.5, 1.4 ]
  3634. * parseFloatArray( "5.6,9.4,2.5,1.4" )
  3635. * @returns {number[]}
  3636. */
  3637. function parseFloatArray( string ) {
  3638. var array = string.split( ',' );
  3639. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3640. array[ i ] = parseFloat( array[ i ] );
  3641. }
  3642. return array;
  3643. }
  3644. /**
  3645. * Parses comma separated list of int numbers and returns them in an array.
  3646. * @example
  3647. * // Returns [ 5, 8, 2, 3 ]
  3648. * parseFloatArray( "5,8,2,3" )
  3649. * @returns {number[]}
  3650. */
  3651. function parseIntArray( string ) {
  3652. var array = string.split( ',' );
  3653. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3654. array[ i ] = parseInt( array[ i ] );
  3655. }
  3656. return array;
  3657. }
  3658. /**
  3659. * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
  3660. * @param {FBXVector3} property - Property to parse as Vector3.
  3661. * @returns {THREE.Vector3}
  3662. */
  3663. function parseVector3( property ) {
  3664. return new THREE.Vector3().fromArray( property.value );
  3665. }
  3666. /**
  3667. * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
  3668. * @param {FBXVector3} property - Property to parse as Color.
  3669. * @returns {THREE.Color}
  3670. */
  3671. function parseColor( property ) {
  3672. return new THREE.Color().fromArray( property.value );
  3673. }
  3674. function parseMatrixArray( floatString ) {
  3675. return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
  3676. }
  3677. /**
  3678. * Converts ArrayBuffer to String.
  3679. * @param {ArrayBuffer} buffer
  3680. * @param {number} from
  3681. * @param {number} to
  3682. * @returns {String}
  3683. */
  3684. function convertArrayBufferToString( buffer, from, to ) {
  3685. if ( from === undefined ) from = 0;
  3686. if ( to === undefined ) to = buffer.byteLength;
  3687. var array = new Uint8Array( buffer, from, to );
  3688. if ( window.TextDecoder !== undefined ) {
  3689. return new TextDecoder().decode( array );
  3690. }
  3691. var s = '';
  3692. for ( var i = 0, il = array.length; i < il; i ++ ) {
  3693. s += String.fromCharCode( array[ i ] );
  3694. }
  3695. return s;
  3696. }
  3697. /**
  3698. * Converts number from degrees into radians.
  3699. * @param {number} value
  3700. * @returns {number}
  3701. */
  3702. function degreeToRadian( value ) {
  3703. return value * DEG2RAD;
  3704. }
  3705. var DEG2RAD = Math.PI / 180;
  3706. //
  3707. function findIndex( array, func ) {
  3708. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3709. if ( func( array[ i ] ) ) return i;
  3710. }
  3711. return - 1;
  3712. }
  3713. function append( a, b ) {
  3714. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  3715. a[ j ] = b[ i ];
  3716. }
  3717. }
  3718. function slice( a, b, from, to ) {
  3719. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  3720. a[ j ] = b[ i ];
  3721. }
  3722. return a;
  3723. }
  3724. } )();