FBXLoader.js 127 KB

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