FBXLoader.js 126 KB

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