FBXLoader.js 127 KB

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