FBXLoader.js 118 KB

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