FBXLoader.js 125 KB

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