FBXLoader.js 115 KB

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