FBXLoader.js 116 KB

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