FBXLoader.js 127 KB

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