FBXLoader.js 127 KB

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