babylonjs.loaders.js 312 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var BABYLON = root.BABYLON || this.BABYLON;
  4. if(typeof exports === 'object' && typeof module === 'object') {
  5. BABYLON = BABYLON || require("babylonjs");
  6. module.exports = factory(BABYLON);
  7. } else if(typeof define === 'function' && define.amd) {
  8. amdDependencies.push("babylonjs");
  9. define("babylonjs-loaders", amdDependencies, factory);
  10. } else if(typeof exports === 'object') {
  11. BABYLON = BABYLON || require("babylonjs");
  12. exports["babylonjs-loaders"] = factory(BABYLON);
  13. } else {
  14. root["BABYLON"] = factory(BABYLON);
  15. }
  16. })(this, function(BABYLON) {
  17. BABYLON = BABYLON || this.BABYLON;
  18. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  19. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var STLFileLoader = /** @class */ (function () {
  23. function STLFileLoader() {
  24. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  25. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  26. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  27. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  28. this.name = "stl";
  29. // force data to come in as an ArrayBuffer
  30. // we'll convert to string if it looks like it's an ASCII .stl
  31. this.extensions = {
  32. ".stl": { isBinary: true },
  33. };
  34. }
  35. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  36. var matches;
  37. if (this.isBinary(data)) {
  38. // binary .stl
  39. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  40. this.parseBinary(babylonMesh, data);
  41. if (meshes) {
  42. meshes.push(babylonMesh);
  43. }
  44. return true;
  45. }
  46. // ASCII .stl
  47. // convert to string
  48. var array_buffer = new Uint8Array(data);
  49. var str = '';
  50. for (var i = 0; i < data.byteLength; i++) {
  51. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  52. }
  53. data = str;
  54. while (matches = this.solidPattern.exec(data)) {
  55. var meshName = matches[1];
  56. var meshNameFromEnd = matches[3];
  57. if (meshName != meshNameFromEnd) {
  58. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  59. return false;
  60. }
  61. // check meshesNames
  62. if (meshesNames && meshName) {
  63. if (meshesNames instanceof Array) {
  64. if (!meshesNames.indexOf(meshName)) {
  65. continue;
  66. }
  67. }
  68. else {
  69. if (meshName !== meshesNames) {
  70. continue;
  71. }
  72. }
  73. }
  74. // stl mesh name can be empty as well
  75. meshName = meshName || "stlmesh";
  76. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  77. this.parseASCII(babylonMesh, matches[2]);
  78. if (meshes) {
  79. meshes.push(babylonMesh);
  80. }
  81. }
  82. return true;
  83. };
  84. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  85. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  86. if (result) {
  87. scene.createDefaultCameraOrLight();
  88. }
  89. return result;
  90. };
  91. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  92. var container = new BABYLON.AssetContainer(scene);
  93. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  94. container.removeAllFromScene();
  95. return container;
  96. };
  97. STLFileLoader.prototype.isBinary = function (data) {
  98. // check if file size is correct for binary stl
  99. var faceSize, nFaces, reader;
  100. reader = new DataView(data);
  101. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  102. nFaces = reader.getUint32(80, true);
  103. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104. return true;
  105. }
  106. // check characters higher than ASCII to confirm binary
  107. var fileLength = reader.byteLength;
  108. for (var index = 0; index < fileLength; index++) {
  109. if (reader.getUint8(index) > 127) {
  110. return true;
  111. }
  112. }
  113. return false;
  114. };
  115. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  116. var reader = new DataView(data);
  117. var faces = reader.getUint32(80, true);
  118. var dataOffset = 84;
  119. var faceLength = 12 * 4 + 2;
  120. var offset = 0;
  121. var positions = new Float32Array(faces * 3 * 3);
  122. var normals = new Float32Array(faces * 3 * 3);
  123. var indices = new Uint32Array(faces * 3);
  124. var indicesCount = 0;
  125. for (var face = 0; face < faces; face++) {
  126. var start = dataOffset + face * faceLength;
  127. var normalX = reader.getFloat32(start, true);
  128. var normalY = reader.getFloat32(start + 4, true);
  129. var normalZ = reader.getFloat32(start + 8, true);
  130. for (var i = 1; i <= 3; i++) {
  131. var vertexstart = start + i * 12;
  132. // ordering is intentional to match ascii import
  133. positions[offset] = reader.getFloat32(vertexstart, true);
  134. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  135. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  136. normals[offset] = normalX;
  137. normals[offset + 2] = normalY;
  138. normals[offset + 1] = normalZ;
  139. offset += 3;
  140. }
  141. indices[indicesCount] = indicesCount++;
  142. indices[indicesCount] = indicesCount++;
  143. indices[indicesCount] = indicesCount++;
  144. }
  145. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  146. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  147. mesh.setIndices(indices);
  148. mesh.computeWorldMatrix(true);
  149. };
  150. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  151. var positions = [];
  152. var normals = [];
  153. var indices = [];
  154. var indicesCount = 0;
  155. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  156. var matches;
  157. while (matches = this.facetsPattern.exec(solidData)) {
  158. var facet = matches[1];
  159. //one normal per face
  160. var normalMatches = this.normalPattern.exec(facet);
  161. this.normalPattern.lastIndex = 0;
  162. if (!normalMatches) {
  163. continue;
  164. }
  165. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  166. var vertexMatch;
  167. while (vertexMatch = this.vertexPattern.exec(facet)) {
  168. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  169. normals.push(normal[0], normal[1], normal[2]);
  170. }
  171. indices.push(indicesCount++, indicesCount++, indicesCount++);
  172. this.vertexPattern.lastIndex = 0;
  173. }
  174. this.facetsPattern.lastIndex = 0;
  175. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  176. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  177. mesh.setIndices(indices);
  178. mesh.computeWorldMatrix(true);
  179. };
  180. return STLFileLoader;
  181. }());
  182. BABYLON.STLFileLoader = STLFileLoader;
  183. if (BABYLON.SceneLoader) {
  184. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  185. }
  186. })(BABYLON || (BABYLON = {}));
  187. //# sourceMappingURL=babylon.stlFileLoader.js.map
  188. var BABYLON;
  189. (function (BABYLON) {
  190. /**
  191. * Class reading and parsing the MTL file bundled with the obj file.
  192. */
  193. var MTLFileLoader = /** @class */ (function () {
  194. function MTLFileLoader() {
  195. // All material loaded from the mtl will be set here
  196. this.materials = [];
  197. }
  198. /**
  199. * This function will read the mtl file and create each material described inside
  200. * This function could be improve by adding :
  201. * -some component missing (Ni, Tf...)
  202. * -including the specific options available
  203. *
  204. * @param scene
  205. * @param data
  206. * @param rootUrl
  207. */
  208. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  209. if (data instanceof ArrayBuffer) {
  210. return;
  211. }
  212. //Split the lines from the file
  213. var lines = data.split('\n');
  214. //Space char
  215. var delimiter_pattern = /\s+/;
  216. //Array with RGB colors
  217. var color;
  218. //New material
  219. var material = null;
  220. //Look at each line
  221. for (var i = 0; i < lines.length; i++) {
  222. var line = lines[i].trim();
  223. // Blank line or comment
  224. if (line.length === 0 || line.charAt(0) === '#') {
  225. continue;
  226. }
  227. //Get the first parameter (keyword)
  228. var pos = line.indexOf(' ');
  229. var key = (pos >= 0) ? line.substring(0, pos) : line;
  230. key = key.toLowerCase();
  231. //Get the data following the key
  232. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  233. //This mtl keyword will create the new material
  234. if (key === "newmtl") {
  235. //Check if it is the first material.
  236. // Materials specifications are described after this keyword.
  237. if (material) {
  238. //Add the previous material in the material array.
  239. this.materials.push(material);
  240. }
  241. //Create a new material.
  242. // value is the name of the material read in the mtl file
  243. material = new BABYLON.StandardMaterial(value, scene);
  244. }
  245. else if (key === "kd" && material) {
  246. // Diffuse color (color under white light) using RGB values
  247. //value = "r g b"
  248. color = value.split(delimiter_pattern, 3).map(parseFloat);
  249. //color = [r,g,b]
  250. //Set tghe color into the material
  251. material.diffuseColor = BABYLON.Color3.FromArray(color);
  252. }
  253. else if (key === "ka" && material) {
  254. // Ambient color (color under shadow) using RGB values
  255. //value = "r g b"
  256. color = value.split(delimiter_pattern, 3).map(parseFloat);
  257. //color = [r,g,b]
  258. //Set tghe color into the material
  259. material.ambientColor = BABYLON.Color3.FromArray(color);
  260. }
  261. else if (key === "ks" && material) {
  262. // Specular color (color when light is reflected from shiny surface) using RGB values
  263. //value = "r g b"
  264. color = value.split(delimiter_pattern, 3).map(parseFloat);
  265. //color = [r,g,b]
  266. //Set the color into the material
  267. material.specularColor = BABYLON.Color3.FromArray(color);
  268. }
  269. else if (key === "ke" && material) {
  270. // Emissive color using RGB values
  271. color = value.split(delimiter_pattern, 3).map(parseFloat);
  272. material.emissiveColor = BABYLON.Color3.FromArray(color);
  273. }
  274. else if (key === "ns" && material) {
  275. //value = "Integer"
  276. material.specularPower = parseFloat(value);
  277. }
  278. else if (key === "d" && material) {
  279. //d is dissolve for current material. It mean alpha for BABYLON
  280. material.alpha = parseFloat(value);
  281. //Texture
  282. //This part can be improved by adding the possible options of texture
  283. }
  284. else if (key === "map_ka" && material) {
  285. // ambient texture map with a loaded image
  286. //We must first get the folder of the image
  287. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  288. }
  289. else if (key === "map_kd" && material) {
  290. // Diffuse texture map with a loaded image
  291. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  292. }
  293. else if (key === "map_ks" && material) {
  294. // Specular texture map with a loaded image
  295. //We must first get the folder of the image
  296. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  297. }
  298. else if (key === "map_ns") {
  299. //Specular
  300. //Specular highlight component
  301. //We must first get the folder of the image
  302. //
  303. //Not supported by BABYLON
  304. //
  305. // continue;
  306. }
  307. else if (key === "map_bump" && material) {
  308. //The bump texture
  309. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  310. }
  311. else if (key === "map_d" && material) {
  312. // The dissolve of the material
  313. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  314. //Options for illumination
  315. }
  316. else if (key === "illum") {
  317. //Illumination
  318. if (value === "0") {
  319. //That mean Kd == Kd
  320. }
  321. else if (value === "1") {
  322. //Color on and Ambient on
  323. }
  324. else if (value === "2") {
  325. //Highlight on
  326. }
  327. else if (value === "3") {
  328. //Reflection on and Ray trace on
  329. }
  330. else if (value === "4") {
  331. //Transparency: Glass on, Reflection: Ray trace on
  332. }
  333. else if (value === "5") {
  334. //Reflection: Fresnel on and Ray trace on
  335. }
  336. else if (value === "6") {
  337. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  338. }
  339. else if (value === "7") {
  340. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  341. }
  342. else if (value === "8") {
  343. //Reflection on and Ray trace off
  344. }
  345. else if (value === "9") {
  346. //Transparency: Glass on, Reflection: Ray trace off
  347. }
  348. else if (value === "10") {
  349. //Casts shadows onto invisible surfaces
  350. }
  351. }
  352. else {
  353. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  354. }
  355. }
  356. //At the end of the file, add the last material
  357. if (material) {
  358. this.materials.push(material);
  359. }
  360. };
  361. /**
  362. * Gets the texture for the material.
  363. *
  364. * If the material is imported from input file,
  365. * We sanitize the url to ensure it takes the textre from aside the material.
  366. *
  367. * @param rootUrl The root url to load from
  368. * @param value The value stored in the mtl
  369. * @return The Texture
  370. */
  371. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  372. if (!value) {
  373. return null;
  374. }
  375. var url = rootUrl;
  376. // Load from input file.
  377. if (rootUrl === "file:") {
  378. var lastDelimiter = value.lastIndexOf("\\");
  379. if (lastDelimiter === -1) {
  380. lastDelimiter = value.lastIndexOf("/");
  381. }
  382. if (lastDelimiter > -1) {
  383. url += value.substr(lastDelimiter + 1);
  384. }
  385. else {
  386. url += value;
  387. }
  388. }
  389. // Not from input file.
  390. else {
  391. url += value;
  392. }
  393. return new BABYLON.Texture(url, scene);
  394. };
  395. return MTLFileLoader;
  396. }());
  397. BABYLON.MTLFileLoader = MTLFileLoader;
  398. var OBJFileLoader = /** @class */ (function () {
  399. function OBJFileLoader() {
  400. this.name = "obj";
  401. this.extensions = ".obj";
  402. this.obj = /^o/;
  403. this.group = /^g/;
  404. this.mtllib = /^mtllib /;
  405. this.usemtl = /^usemtl /;
  406. this.smooth = /^s /;
  407. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  408. // vn float float float
  409. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  410. // vt float float
  411. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  412. // f vertex vertex vertex ...
  413. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  414. // f vertex/uvs vertex/uvs vertex/uvs ...
  415. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  416. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  417. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  418. // f vertex//normal vertex//normal vertex//normal ...
  419. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  420. }
  421. /**
  422. * Calls synchronously the MTL file attached to this obj.
  423. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  424. * Without this function materials are not displayed in the first frame (but displayed after).
  425. * In consequence it is impossible to get material information in your HTML file
  426. *
  427. * @param url The URL of the MTL file
  428. * @param rootUrl
  429. * @param onSuccess Callback function to be called when the MTL file is loaded
  430. * @private
  431. */
  432. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  433. //The complete path to the mtl file
  434. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  435. // Loads through the babylon tools to allow fileInput search.
  436. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  437. };
  438. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  439. //get the meshes from OBJ file
  440. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  441. //Push meshes from OBJ file into the variable mesh of this function
  442. if (meshes) {
  443. loadedMeshes.forEach(function (mesh) {
  444. meshes.push(mesh);
  445. });
  446. }
  447. return true;
  448. };
  449. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  450. //Get the 3D model
  451. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  452. };
  453. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  454. var container = new BABYLON.AssetContainer(scene);
  455. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  456. container.removeAllFromScene();
  457. return container;
  458. };
  459. /**
  460. * Read the OBJ file and create an Array of meshes.
  461. * Each mesh contains all information given by the OBJ and the MTL file.
  462. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  463. *
  464. * @param meshesNames
  465. * @param scene BABYLON.Scene The scene where are displayed the data
  466. * @param data String The content of the obj file
  467. * @param rootUrl String The path to the folder
  468. * @returns Array<AbstractMesh>
  469. * @private
  470. */
  471. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  472. var positions = []; //values for the positions of vertices
  473. var normals = []; //Values for the normals
  474. var uvs = []; //Values for the textures
  475. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  476. var handledMesh; //The current mesh of meshes array
  477. var indicesForBabylon = []; //The list of indices for VertexData
  478. var wrappedPositionForBabylon = []; //The list of position in vectors
  479. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  480. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  481. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  482. var curPositionInIndices = 0;
  483. var hasMeshes = false; //Meshes are defined in the file
  484. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  485. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  486. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  487. var triangles = []; //Indices from new triangles coming from polygons
  488. var materialNameFromObj = ""; //The name of the current material
  489. var fileToLoad = ""; //The name of the mtlFile to load
  490. var materialsFromMTLFile = new MTLFileLoader();
  491. var objMeshName = ""; //The name of the current obj mesh
  492. var increment = 1; //Id for meshes created by the multimaterial
  493. var isFirstMaterial = true;
  494. /**
  495. * Search for obj in the given array.
  496. * This function is called to check if a couple of data already exists in an array.
  497. *
  498. * If found, returns the index of the founded tuple index. Returns -1 if not found
  499. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  500. * @param obj Array<number>
  501. * @returns {boolean}
  502. */
  503. var isInArray = function (arr, obj) {
  504. if (!arr[obj[0]])
  505. arr[obj[0]] = { normals: [], idx: [] };
  506. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  507. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  508. };
  509. var isInArrayUV = function (arr, obj) {
  510. if (!arr[obj[0]])
  511. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  512. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  513. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  514. return arr[obj[0]].idx[idx];
  515. }
  516. return -1;
  517. };
  518. /**
  519. * This function set the data for each triangle.
  520. * Data are position, normals and uvs
  521. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  522. * If the tuple already exist, add only their indice
  523. *
  524. * @param indicePositionFromObj Integer The index in positions array
  525. * @param indiceUvsFromObj Integer The index in uvs array
  526. * @param indiceNormalFromObj Integer The index in normals array
  527. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  528. * @param textureVectorFromOBJ Vector3 The value of uvs
  529. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  530. */
  531. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  532. //Check if this tuple already exists in the list of tuples
  533. var _index;
  534. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  535. _index = isInArrayUV(tuplePosNorm, [
  536. indicePositionFromObj,
  537. indiceNormalFromObj,
  538. indiceUvsFromObj
  539. ]);
  540. }
  541. else {
  542. _index = isInArray(tuplePosNorm, [
  543. indicePositionFromObj,
  544. indiceNormalFromObj
  545. ]);
  546. }
  547. //If it not exists
  548. if (_index == -1) {
  549. //Add an new indice.
  550. //The array of indices is only an array with his length equal to the number of triangles - 1.
  551. //We add vertices data in this order
  552. indicesForBabylon.push(wrappedPositionForBabylon.length);
  553. //Push the position of vertice for Babylon
  554. //Each element is a BABYLON.Vector3(x,y,z)
  555. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  556. //Push the uvs for Babylon
  557. //Each element is a BABYLON.Vector3(u,v)
  558. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  559. //Push the normals for Babylon
  560. //Each element is a BABYLON.Vector3(x,y,z)
  561. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  562. //Add the tuple in the comparison list
  563. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  564. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  565. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  566. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  567. }
  568. else {
  569. //The tuple already exists
  570. //Add the index of the already existing tuple
  571. //At this index we can get the value of position, normal and uvs of vertex
  572. indicesForBabylon.push(_index);
  573. }
  574. };
  575. /**
  576. * Transform BABYLON.Vector() object onto 3 digits in an array
  577. */
  578. var unwrapData = function () {
  579. //Every array has the same length
  580. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  581. //Push the x, y, z values of each element in the unwrapped array
  582. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  583. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  584. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  585. }
  586. // Reset arrays for the next new meshes
  587. wrappedPositionForBabylon = [];
  588. wrappedNormalsForBabylon = [];
  589. wrappedUvsForBabylon = [];
  590. tuplePosNorm = [];
  591. curPositionInIndices = 0;
  592. };
  593. /**
  594. * Create triangles from polygons by recursion
  595. * The best to understand how it works is to draw it in the same time you get the recursion.
  596. * It is important to notice that a triangle is a polygon
  597. * We get 4 patterns of face defined in OBJ File :
  598. * facePattern1 = ["1","2","3","4","5","6"]
  599. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  600. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  601. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  602. * Each pattern is divided by the same method
  603. * @param face Array[String] The indices of elements
  604. * @param v Integer The variable to increment
  605. */
  606. var getTriangles = function (face, v) {
  607. //Work for each element of the array
  608. if (v + 1 < face.length) {
  609. //Add on the triangle variable the indexes to obtain triangles
  610. triangles.push(face[0], face[v], face[v + 1]);
  611. //Incrementation for recursion
  612. v += 1;
  613. //Recursion
  614. getTriangles(face, v);
  615. }
  616. //Result obtained after 2 iterations:
  617. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  618. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  619. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  620. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  621. };
  622. /**
  623. * Create triangles and push the data for each polygon for the pattern 1
  624. * In this pattern we get vertice positions
  625. * @param face
  626. * @param v
  627. */
  628. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  629. //Get the indices of triangles for each polygon
  630. getTriangles(face, v);
  631. //For each element in the triangles array.
  632. //This var could contains 1 to an infinity of triangles
  633. for (var k = 0; k < triangles.length; k++) {
  634. // Set position indice
  635. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  636. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  637. positions[indicePositionFromObj], //Get the vectors data
  638. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  639. );
  640. }
  641. //Reset variable for the next line
  642. triangles = [];
  643. };
  644. /**
  645. * Create triangles and push the data for each polygon for the pattern 2
  646. * In this pattern we get vertice positions and uvsu
  647. * @param face
  648. * @param v
  649. */
  650. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  651. //Get the indices of triangles for each polygon
  652. getTriangles(face, v);
  653. for (var k = 0; k < triangles.length; k++) {
  654. //triangle[k] = "1/1"
  655. //Split the data for getting position and uv
  656. var point = triangles[k].split("/"); // ["1", "1"]
  657. //Set position indice
  658. var indicePositionFromObj = parseInt(point[0]) - 1;
  659. //Set uv indice
  660. var indiceUvsFromObj = parseInt(point[1]) - 1;
  661. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  662. positions[indicePositionFromObj], //Get the values for each element
  663. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  664. );
  665. }
  666. //Reset variable for the next line
  667. triangles = [];
  668. };
  669. /**
  670. * Create triangles and push the data for each polygon for the pattern 3
  671. * In this pattern we get vertice positions, uvs and normals
  672. * @param face
  673. * @param v
  674. */
  675. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  676. //Get the indices of triangles for each polygon
  677. getTriangles(face, v);
  678. for (var k = 0; k < triangles.length; k++) {
  679. //triangle[k] = "1/1/1"
  680. //Split the data for getting position, uv, and normals
  681. var point = triangles[k].split("/"); // ["1", "1", "1"]
  682. // Set position indice
  683. var indicePositionFromObj = parseInt(point[0]) - 1;
  684. // Set uv indice
  685. var indiceUvsFromObj = parseInt(point[1]) - 1;
  686. // Set normal indice
  687. var indiceNormalFromObj = parseInt(point[2]) - 1;
  688. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  689. );
  690. }
  691. //Reset variable for the next line
  692. triangles = [];
  693. };
  694. /**
  695. * Create triangles and push the data for each polygon for the pattern 4
  696. * In this pattern we get vertice positions and normals
  697. * @param face
  698. * @param v
  699. */
  700. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  701. getTriangles(face, v);
  702. for (var k = 0; k < triangles.length; k++) {
  703. //triangle[k] = "1//1"
  704. //Split the data for getting position and normals
  705. var point = triangles[k].split("//"); // ["1", "1"]
  706. // We check indices, and normals
  707. var indicePositionFromObj = parseInt(point[0]) - 1;
  708. var indiceNormalFromObj = parseInt(point[1]) - 1;
  709. setData(indicePositionFromObj, 1, //Default value for uv
  710. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  711. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  712. }
  713. //Reset variable for the next line
  714. triangles = [];
  715. };
  716. var addPreviousObjMesh = function () {
  717. //Check if it is not the first mesh. Otherwise we don't have data.
  718. if (meshesFromObj.length > 0) {
  719. //Get the previous mesh for applying the data about the faces
  720. //=> in obj file, faces definition append after the name of the mesh
  721. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  722. //Set the data into Array for the mesh
  723. unwrapData();
  724. // Reverse tab. Otherwise face are displayed in the wrong sens
  725. indicesForBabylon.reverse();
  726. //Set the information for the mesh
  727. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  728. handledMesh.indices = indicesForBabylon.slice();
  729. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  730. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  731. handledMesh.uvs = unwrappedUVForBabylon.slice();
  732. //Reset the array for the next mesh
  733. indicesForBabylon = [];
  734. unwrappedPositionsForBabylon = [];
  735. unwrappedNormalsForBabylon = [];
  736. unwrappedUVForBabylon = [];
  737. }
  738. };
  739. //Main function
  740. //Split the file into lines
  741. var lines = data.split('\n');
  742. //Look at each line
  743. for (var i = 0; i < lines.length; i++) {
  744. var line = lines[i].trim();
  745. var result;
  746. //Comment or newLine
  747. if (line.length === 0 || line.charAt(0) === '#') {
  748. continue;
  749. //Get information about one position possible for the vertices
  750. }
  751. else if ((result = this.vertexPattern.exec(line)) !== null) {
  752. //Create a Vector3 with the position x, y, z
  753. //Value of result:
  754. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  755. //Add the Vector in the list of positions
  756. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  757. }
  758. else if ((result = this.normalPattern.exec(line)) !== null) {
  759. //Create a Vector3 with the normals x, y, z
  760. //Value of result
  761. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  762. //Add the Vector in the list of normals
  763. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  764. }
  765. else if ((result = this.uvPattern.exec(line)) !== null) {
  766. //Create a Vector2 with the normals u, v
  767. //Value of result
  768. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  769. //Add the Vector in the list of uvs
  770. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  771. //Identify patterns of faces
  772. //Face could be defined in different type of pattern
  773. }
  774. else if ((result = this.facePattern3.exec(line)) !== null) {
  775. //Value of result:
  776. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  777. //Set the data for this face
  778. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  779. 1);
  780. }
  781. else if ((result = this.facePattern4.exec(line)) !== null) {
  782. //Value of result:
  783. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  784. //Set the data for this face
  785. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  786. 1);
  787. }
  788. else if ((result = this.facePattern2.exec(line)) !== null) {
  789. //Value of result:
  790. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  791. //Set the data for this face
  792. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  793. 1);
  794. }
  795. else if ((result = this.facePattern1.exec(line)) !== null) {
  796. //Value of result
  797. //["f 1 2 3", "1 2 3"...]
  798. //Set the data for this face
  799. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  800. 1);
  801. //Define a mesh or an object
  802. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  803. }
  804. else if (this.group.test(line) || this.obj.test(line)) {
  805. //Create a new mesh corresponding to the name of the group.
  806. //Definition of the mesh
  807. var objMesh =
  808. //Set the name of the current obj mesh
  809. {
  810. name: line.substring(2).trim(),
  811. indices: undefined,
  812. positions: undefined,
  813. normals: undefined,
  814. uvs: undefined,
  815. materialName: ""
  816. };
  817. addPreviousObjMesh();
  818. //Push the last mesh created with only the name
  819. meshesFromObj.push(objMesh);
  820. //Set this variable to indicate that now meshesFromObj has objects defined inside
  821. hasMeshes = true;
  822. isFirstMaterial = true;
  823. increment = 1;
  824. //Keyword for applying a material
  825. }
  826. else if (this.usemtl.test(line)) {
  827. //Get the name of the material
  828. materialNameFromObj = line.substring(7).trim();
  829. //If this new material is in the same mesh
  830. if (!isFirstMaterial) {
  831. //Set the data for the previous mesh
  832. addPreviousObjMesh();
  833. //Create a new mesh
  834. var objMesh =
  835. //Set the name of the current obj mesh
  836. {
  837. name: objMeshName + "_mm" + increment.toString(),
  838. indices: undefined,
  839. positions: undefined,
  840. normals: undefined,
  841. uvs: undefined,
  842. materialName: materialNameFromObj
  843. };
  844. increment++;
  845. //If meshes are already defined
  846. meshesFromObj.push(objMesh);
  847. }
  848. //Set the material name if the previous line define a mesh
  849. if (hasMeshes && isFirstMaterial) {
  850. //Set the material name to the previous mesh (1 material per mesh)
  851. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  852. isFirstMaterial = false;
  853. }
  854. //Keyword for loading the mtl file
  855. }
  856. else if (this.mtllib.test(line)) {
  857. //Get the name of mtl file
  858. fileToLoad = line.substring(7).trim();
  859. //Apply smoothing
  860. }
  861. else if (this.smooth.test(line)) {
  862. // smooth shading => apply smoothing
  863. //Toda y I don't know it work with babylon and with obj.
  864. //With the obj file an integer is set
  865. }
  866. else {
  867. //If there is another possibility
  868. console.log("Unhandled expression at line : " + line);
  869. }
  870. }
  871. //At the end of the file, add the last mesh into the meshesFromObj array
  872. if (hasMeshes) {
  873. //Set the data for the last mesh
  874. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  875. //Reverse indices for displaying faces in the good sens
  876. indicesForBabylon.reverse();
  877. //Get the good array
  878. unwrapData();
  879. //Set array
  880. handledMesh.indices = indicesForBabylon;
  881. handledMesh.positions = unwrappedPositionsForBabylon;
  882. handledMesh.normals = unwrappedNormalsForBabylon;
  883. handledMesh.uvs = unwrappedUVForBabylon;
  884. }
  885. //If any o or g keyword found, create a mesj with a random id
  886. if (!hasMeshes) {
  887. // reverse tab of indices
  888. indicesForBabylon.reverse();
  889. //Get positions normals uvs
  890. unwrapData();
  891. //Set data for one mesh
  892. meshesFromObj.push({
  893. name: BABYLON.Geometry.RandomId(),
  894. indices: indicesForBabylon,
  895. positions: unwrappedPositionsForBabylon,
  896. normals: unwrappedNormalsForBabylon,
  897. uvs: unwrappedUVForBabylon,
  898. materialName: materialNameFromObj
  899. });
  900. }
  901. //Create a BABYLON.Mesh list
  902. var babylonMeshesArray = []; //The mesh for babylon
  903. var materialToUse = new Array();
  904. //Set data for each mesh
  905. for (var j = 0; j < meshesFromObj.length; j++) {
  906. //check meshesNames (stlFileLoader)
  907. if (meshesNames && meshesFromObj[j].name) {
  908. if (meshesNames instanceof Array) {
  909. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  910. continue;
  911. }
  912. }
  913. else {
  914. if (meshesFromObj[j].name !== meshesNames) {
  915. continue;
  916. }
  917. }
  918. }
  919. //Get the current mesh
  920. //Set the data with VertexBuffer for each mesh
  921. handledMesh = meshesFromObj[j];
  922. //Create a BABYLON.Mesh with the name of the obj mesh
  923. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  924. //Push the name of the material to an array
  925. //This is indispensable for the importMesh function
  926. materialToUse.push(meshesFromObj[j].materialName);
  927. var vertexData = new BABYLON.VertexData(); //The container for the values
  928. //Set the data for the babylonMesh
  929. vertexData.positions = handledMesh.positions;
  930. vertexData.normals = handledMesh.normals;
  931. vertexData.uvs = handledMesh.uvs;
  932. vertexData.indices = handledMesh.indices;
  933. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  934. vertexData.applyToMesh(babylonMesh);
  935. if (OBJFileLoader.INVERT_Y) {
  936. babylonMesh.scaling.y *= -1;
  937. }
  938. //Push the mesh into an array
  939. babylonMeshesArray.push(babylonMesh);
  940. }
  941. //load the materials
  942. //Check if we have a file to load
  943. if (fileToLoad !== "") {
  944. //Load the file synchronously
  945. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  946. //Create materials thanks MTLLoader function
  947. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  948. //Look at each material loaded in the mtl file
  949. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  950. //Three variables to get all meshes with the same material
  951. var startIndex = 0;
  952. var _indices = [];
  953. var _index;
  954. //The material from MTL file is used in the meshes loaded
  955. //Push the indice in an array
  956. //Check if the material is not used for another mesh
  957. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  958. _indices.push(_index);
  959. startIndex = _index + 1;
  960. }
  961. //If the material is not used dispose it
  962. if (_index == -1 && _indices.length == 0) {
  963. //If the material is not needed, remove it
  964. materialsFromMTLFile.materials[n].dispose();
  965. }
  966. else {
  967. for (var o = 0; o < _indices.length; o++) {
  968. //Apply the material to the BABYLON.Mesh for each mesh with the material
  969. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  970. }
  971. }
  972. }
  973. });
  974. }
  975. //Return an array with all BABYLON.Mesh
  976. return babylonMeshesArray;
  977. };
  978. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  979. OBJFileLoader.INVERT_Y = false;
  980. return OBJFileLoader;
  981. }());
  982. BABYLON.OBJFileLoader = OBJFileLoader;
  983. if (BABYLON.SceneLoader) {
  984. //Add this loader into the register plugin
  985. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  986. }
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.objFileLoader.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. /**
  992. * Mode that determines the coordinate system to use.
  993. */
  994. var GLTFLoaderCoordinateSystemMode;
  995. (function (GLTFLoaderCoordinateSystemMode) {
  996. /**
  997. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  998. */
  999. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  1000. /**
  1001. * Sets the useRightHandedSystem flag on the scene.
  1002. */
  1003. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  1004. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  1005. /**
  1006. * Mode that determines what animations will start.
  1007. */
  1008. var GLTFLoaderAnimationStartMode;
  1009. (function (GLTFLoaderAnimationStartMode) {
  1010. /**
  1011. * No animation will start.
  1012. */
  1013. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  1014. /**
  1015. * The first animation will start.
  1016. */
  1017. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  1018. /**
  1019. * All animations will start.
  1020. */
  1021. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  1022. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  1023. /**
  1024. * Loader state.
  1025. */
  1026. var GLTFLoaderState;
  1027. (function (GLTFLoaderState) {
  1028. /**
  1029. * The asset is loading.
  1030. */
  1031. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  1032. /**
  1033. * The asset is ready for rendering.
  1034. */
  1035. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  1036. /**
  1037. * The asset is completely loaded.
  1038. */
  1039. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  1040. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  1041. /**
  1042. * File loader for loading glTF files into a scene.
  1043. */
  1044. var GLTFFileLoader = /** @class */ (function () {
  1045. function GLTFFileLoader() {
  1046. // #region Common options
  1047. /**
  1048. * Raised when the asset has been parsed
  1049. */
  1050. this.onParsedObservable = new BABYLON.Observable();
  1051. // #endregion
  1052. // #region V2 options
  1053. /**
  1054. * The coordinate system mode. Defaults to AUTO.
  1055. */
  1056. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  1057. /**
  1058. * The animation start mode. Defaults to FIRST.
  1059. */
  1060. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  1061. /**
  1062. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  1063. */
  1064. this.compileMaterials = false;
  1065. /**
  1066. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  1067. */
  1068. this.useClipPlane = false;
  1069. /**
  1070. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  1071. */
  1072. this.compileShadowGenerators = false;
  1073. /**
  1074. * Defines if the Alpha blended materials are only applied as coverage.
  1075. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  1076. * If true, no extra effects are applied to transparent pixels.
  1077. */
  1078. this.transparencyAsCoverage = false;
  1079. /** @hidden */
  1080. this._normalizeAnimationGroupsToBeginAtZero = true;
  1081. /**
  1082. * Defines if the loader logging is enabled.
  1083. */
  1084. this.loggingEnabled = false;
  1085. /**
  1086. * Observable raised when the loader logs a message.
  1087. */
  1088. this.onLogObservable = new BABYLON.Observable();
  1089. this._logIndentLevel = 0;
  1090. /**
  1091. * Function called before loading a url referenced by the asset.
  1092. */
  1093. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  1094. /**
  1095. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  1096. */
  1097. this.onMeshLoadedObservable = new BABYLON.Observable();
  1098. /**
  1099. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  1100. */
  1101. this.onTextureLoadedObservable = new BABYLON.Observable();
  1102. /**
  1103. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  1104. */
  1105. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1106. /**
  1107. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  1108. */
  1109. this.onCameraLoadedObservable = new BABYLON.Observable();
  1110. /**
  1111. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  1112. * For assets with LODs, raised when all of the LODs are complete.
  1113. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  1114. */
  1115. this.onCompleteObservable = new BABYLON.Observable();
  1116. /**
  1117. * Observable raised after the loader is disposed.
  1118. */
  1119. this.onDisposeObservable = new BABYLON.Observable();
  1120. /**
  1121. * Observable raised after a loader extension is created.
  1122. * Set additional options for a loader extension in this event.
  1123. */
  1124. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1125. // #endregion
  1126. this._loader = null;
  1127. /**
  1128. * Name of the loader ("gltf")
  1129. */
  1130. this.name = "gltf";
  1131. /**
  1132. * Supported file extensions of the loader (.gltf, .glb)
  1133. */
  1134. this.extensions = {
  1135. ".gltf": { isBinary: false },
  1136. ".glb": { isBinary: true }
  1137. };
  1138. }
  1139. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  1140. /**
  1141. * Raised when the asset has been parsed
  1142. */
  1143. set: function (callback) {
  1144. if (this._onParsedObserver) {
  1145. this.onParsedObservable.remove(this._onParsedObserver);
  1146. }
  1147. this._onParsedObserver = this.onParsedObservable.add(callback);
  1148. },
  1149. enumerable: true,
  1150. configurable: true
  1151. });
  1152. /** @hidden */
  1153. GLTFFileLoader.prototype._log = function (message) {
  1154. if (this.loggingEnabled) {
  1155. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  1156. this.onLogObservable.notifyObservers("" + spaces + message);
  1157. BABYLON.Tools.Log("" + spaces + message);
  1158. }
  1159. };
  1160. /** @hidden */
  1161. GLTFFileLoader.prototype._logOpen = function (message) {
  1162. this._log(message);
  1163. this._logIndentLevel++;
  1164. };
  1165. /** @hidden */
  1166. GLTFFileLoader.prototype._logClose = function () {
  1167. --this._logIndentLevel;
  1168. };
  1169. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  1170. /**
  1171. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  1172. */
  1173. set: function (callback) {
  1174. if (this._onMeshLoadedObserver) {
  1175. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  1176. }
  1177. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  1178. },
  1179. enumerable: true,
  1180. configurable: true
  1181. });
  1182. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  1183. /**
  1184. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  1185. */
  1186. set: function (callback) {
  1187. if (this._onTextureLoadedObserver) {
  1188. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  1189. }
  1190. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  1191. },
  1192. enumerable: true,
  1193. configurable: true
  1194. });
  1195. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  1196. /**
  1197. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  1198. */
  1199. set: function (callback) {
  1200. if (this._onMaterialLoadedObserver) {
  1201. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  1202. }
  1203. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  1204. },
  1205. enumerable: true,
  1206. configurable: true
  1207. });
  1208. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  1209. /**
  1210. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  1211. */
  1212. set: function (callback) {
  1213. if (this._onCameraLoadedObserver) {
  1214. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  1215. }
  1216. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  1217. },
  1218. enumerable: true,
  1219. configurable: true
  1220. });
  1221. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  1222. /**
  1223. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  1224. */
  1225. set: function (callback) {
  1226. if (this._onCompleteObserver) {
  1227. this.onCompleteObservable.remove(this._onCompleteObserver);
  1228. }
  1229. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  1230. },
  1231. enumerable: true,
  1232. configurable: true
  1233. });
  1234. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  1235. /**
  1236. * Callback raised after the loader is disposed.
  1237. */
  1238. set: function (callback) {
  1239. if (this._onDisposeObserver) {
  1240. this.onDisposeObservable.remove(this._onDisposeObserver);
  1241. }
  1242. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  1248. /**
  1249. * Callback raised after a loader extension is created.
  1250. */
  1251. set: function (callback) {
  1252. if (this._onExtensionLoadedObserver) {
  1253. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  1254. }
  1255. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  1256. },
  1257. enumerable: true,
  1258. configurable: true
  1259. });
  1260. /**
  1261. * Returns a promise that resolves when the asset is completely loaded.
  1262. * @returns a promise that resolves when the asset is completely loaded.
  1263. */
  1264. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  1265. var _this = this;
  1266. return new Promise(function (resolve) {
  1267. _this.onCompleteObservable.addOnce(function () {
  1268. resolve();
  1269. });
  1270. });
  1271. };
  1272. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  1273. /**
  1274. * The loader state or null if the loader is not active.
  1275. */
  1276. get: function () {
  1277. return this._loader ? this._loader.state : null;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. /**
  1283. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  1284. */
  1285. GLTFFileLoader.prototype.dispose = function () {
  1286. if (this._loader) {
  1287. this._loader.dispose();
  1288. this._loader = null;
  1289. }
  1290. this._clear();
  1291. this.onDisposeObservable.notifyObservers(undefined);
  1292. this.onDisposeObservable.clear();
  1293. };
  1294. /** @hidden */
  1295. GLTFFileLoader.prototype._clear = function () {
  1296. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  1297. this.onMeshLoadedObservable.clear();
  1298. this.onTextureLoadedObservable.clear();
  1299. this.onMaterialLoadedObservable.clear();
  1300. this.onCameraLoadedObservable.clear();
  1301. this.onCompleteObservable.clear();
  1302. this.onExtensionLoadedObservable.clear();
  1303. };
  1304. /**
  1305. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  1306. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  1307. * @param scene the scene the meshes should be added to
  1308. * @param data the glTF data to load
  1309. * @param rootUrl root url to load from
  1310. * @param onProgress event that fires when loading progress has occured
  1311. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  1312. */
  1313. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1314. var _this = this;
  1315. return Promise.resolve().then(function () {
  1316. var loaderData = _this._parse(data);
  1317. _this._loader = _this._getLoader(loaderData);
  1318. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  1319. });
  1320. };
  1321. /**
  1322. * Imports all objects from the loaded glTF data and adds them to the scene
  1323. * @param scene the scene the objects should be added to
  1324. * @param data the glTF data to load
  1325. * @param rootUrl root url to load from
  1326. * @param onProgress event that fires when loading progress has occured
  1327. * @returns a promise which completes when objects have been loaded to the scene
  1328. */
  1329. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1330. var _this = this;
  1331. return Promise.resolve().then(function () {
  1332. var loaderData = _this._parse(data);
  1333. _this._loader = _this._getLoader(loaderData);
  1334. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  1335. });
  1336. };
  1337. /**
  1338. * Load into an asset container.
  1339. * @param scene The scene to load into
  1340. * @param data The data to import
  1341. * @param rootUrl The root url for scene and resources
  1342. * @param onProgress The callback when the load progresses
  1343. * @returns The loaded asset container
  1344. */
  1345. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  1346. var _this = this;
  1347. return Promise.resolve().then(function () {
  1348. var loaderData = _this._parse(data);
  1349. _this._loader = _this._getLoader(loaderData);
  1350. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  1351. var container = new BABYLON.AssetContainer(scene);
  1352. Array.prototype.push.apply(container.meshes, result.meshes);
  1353. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  1354. Array.prototype.push.apply(container.skeletons, result.skeletons);
  1355. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  1356. container.removeAllFromScene();
  1357. return container;
  1358. });
  1359. });
  1360. };
  1361. /**
  1362. * If the data string can be loaded directly.
  1363. * @param data string contianing the file data
  1364. * @returns if the data can be loaded directly
  1365. */
  1366. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  1367. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  1368. };
  1369. /**
  1370. * Instantiates a glTF file loader plugin.
  1371. * @returns the created plugin
  1372. */
  1373. GLTFFileLoader.prototype.createPlugin = function () {
  1374. return new GLTFFileLoader();
  1375. };
  1376. GLTFFileLoader.prototype._parse = function (data) {
  1377. var parsedData;
  1378. if (data instanceof ArrayBuffer) {
  1379. if (this.loggingEnabled) {
  1380. this._log("Parsing binary");
  1381. }
  1382. parsedData = this._parseBinary(data);
  1383. }
  1384. else {
  1385. if (this.loggingEnabled) {
  1386. this._log("Parsing JSON");
  1387. this._log("JSON length: " + data.length);
  1388. }
  1389. parsedData = {
  1390. json: JSON.parse(data),
  1391. bin: null
  1392. };
  1393. }
  1394. this.onParsedObservable.notifyObservers(parsedData);
  1395. this.onParsedObservable.clear();
  1396. return parsedData;
  1397. };
  1398. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  1399. var asset = loaderData.json.asset || {};
  1400. if (this.loggingEnabled) {
  1401. this._log("Asset version: " + asset.version);
  1402. if (asset.minVersion) {
  1403. this._log("Asset minimum version: " + asset.minVersion);
  1404. }
  1405. if (asset.generator) {
  1406. this._log("Asset generator: " + asset.generator);
  1407. }
  1408. }
  1409. var version = GLTFFileLoader._parseVersion(asset.version);
  1410. if (!version) {
  1411. throw new Error("Invalid version: " + asset.version);
  1412. }
  1413. if (asset.minVersion !== undefined) {
  1414. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  1415. if (!minVersion) {
  1416. throw new Error("Invalid minimum version: " + asset.minVersion);
  1417. }
  1418. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  1419. throw new Error("Incompatible minimum version: " + asset.minVersion);
  1420. }
  1421. }
  1422. var createLoaders = {
  1423. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  1424. 2: GLTFFileLoader._CreateGLTFLoaderV2
  1425. };
  1426. var createLoader = createLoaders[version.major];
  1427. if (!createLoader) {
  1428. throw new Error("Unsupported version: " + asset.version);
  1429. }
  1430. return createLoader(this);
  1431. };
  1432. GLTFFileLoader.prototype._parseBinary = function (data) {
  1433. var Binary = {
  1434. Magic: 0x46546C67
  1435. };
  1436. if (this.loggingEnabled) {
  1437. this._log("Binary length: " + data.byteLength);
  1438. }
  1439. var binaryReader = new BinaryReader(data);
  1440. var magic = binaryReader.readUint32();
  1441. if (magic !== Binary.Magic) {
  1442. throw new Error("Unexpected magic: " + magic);
  1443. }
  1444. var version = binaryReader.readUint32();
  1445. if (this.loggingEnabled) {
  1446. this._log("Binary version: " + version);
  1447. }
  1448. switch (version) {
  1449. case 1: return this._parseV1(binaryReader);
  1450. case 2: return this._parseV2(binaryReader);
  1451. }
  1452. throw new Error("Unsupported version: " + version);
  1453. };
  1454. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  1455. var ContentFormat = {
  1456. JSON: 0
  1457. };
  1458. var length = binaryReader.readUint32();
  1459. if (length != binaryReader.getLength()) {
  1460. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1461. }
  1462. var contentLength = binaryReader.readUint32();
  1463. var contentFormat = binaryReader.readUint32();
  1464. var content;
  1465. switch (contentFormat) {
  1466. case ContentFormat.JSON: {
  1467. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  1468. break;
  1469. }
  1470. default: {
  1471. throw new Error("Unexpected content format: " + contentFormat);
  1472. }
  1473. }
  1474. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  1475. var body = binaryReader.readUint8Array(bytesRemaining);
  1476. return {
  1477. json: content,
  1478. bin: body
  1479. };
  1480. };
  1481. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  1482. var ChunkFormat = {
  1483. JSON: 0x4E4F534A,
  1484. BIN: 0x004E4942
  1485. };
  1486. var length = binaryReader.readUint32();
  1487. if (length !== binaryReader.getLength()) {
  1488. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1489. }
  1490. // JSON chunk
  1491. var chunkLength = binaryReader.readUint32();
  1492. var chunkFormat = binaryReader.readUint32();
  1493. if (chunkFormat !== ChunkFormat.JSON) {
  1494. throw new Error("First chunk format is not JSON");
  1495. }
  1496. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  1497. // Look for BIN chunk
  1498. var bin = null;
  1499. while (binaryReader.getPosition() < binaryReader.getLength()) {
  1500. var chunkLength_1 = binaryReader.readUint32();
  1501. var chunkFormat_1 = binaryReader.readUint32();
  1502. switch (chunkFormat_1) {
  1503. case ChunkFormat.JSON: {
  1504. throw new Error("Unexpected JSON chunk");
  1505. }
  1506. case ChunkFormat.BIN: {
  1507. bin = binaryReader.readUint8Array(chunkLength_1);
  1508. break;
  1509. }
  1510. default: {
  1511. // ignore unrecognized chunkFormat
  1512. binaryReader.skipBytes(chunkLength_1);
  1513. break;
  1514. }
  1515. }
  1516. }
  1517. return {
  1518. json: json,
  1519. bin: bin
  1520. };
  1521. };
  1522. GLTFFileLoader._parseVersion = function (version) {
  1523. if (version === "1.0" || version === "1.0.1") {
  1524. return {
  1525. major: 1,
  1526. minor: 0
  1527. };
  1528. }
  1529. var match = (version + "").match(/^(\d+)\.(\d+)/);
  1530. if (!match) {
  1531. return null;
  1532. }
  1533. return {
  1534. major: parseInt(match[1]),
  1535. minor: parseInt(match[2])
  1536. };
  1537. };
  1538. GLTFFileLoader._compareVersion = function (a, b) {
  1539. if (a.major > b.major)
  1540. return 1;
  1541. if (a.major < b.major)
  1542. return -1;
  1543. if (a.minor > b.minor)
  1544. return 1;
  1545. if (a.minor < b.minor)
  1546. return -1;
  1547. return 0;
  1548. };
  1549. GLTFFileLoader._decodeBufferToText = function (buffer) {
  1550. var result = "";
  1551. var length = buffer.byteLength;
  1552. for (var i = 0; i < length; i++) {
  1553. result += String.fromCharCode(buffer[i]);
  1554. }
  1555. return result;
  1556. };
  1557. // #endregion
  1558. // #region V1 options
  1559. /**
  1560. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  1561. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  1562. * Defaults to true.
  1563. * @hidden
  1564. */
  1565. GLTFFileLoader.IncrementalLoading = true;
  1566. /**
  1567. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  1568. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  1569. * @hidden
  1570. */
  1571. GLTFFileLoader.HomogeneousCoordinates = false;
  1572. GLTFFileLoader._logSpaces = " ";
  1573. return GLTFFileLoader;
  1574. }());
  1575. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1576. var BinaryReader = /** @class */ (function () {
  1577. function BinaryReader(arrayBuffer) {
  1578. this._arrayBuffer = arrayBuffer;
  1579. this._dataView = new DataView(arrayBuffer);
  1580. this._byteOffset = 0;
  1581. }
  1582. BinaryReader.prototype.getPosition = function () {
  1583. return this._byteOffset;
  1584. };
  1585. BinaryReader.prototype.getLength = function () {
  1586. return this._arrayBuffer.byteLength;
  1587. };
  1588. BinaryReader.prototype.readUint32 = function () {
  1589. var value = this._dataView.getUint32(this._byteOffset, true);
  1590. this._byteOffset += 4;
  1591. return value;
  1592. };
  1593. BinaryReader.prototype.readUint8Array = function (length) {
  1594. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1595. this._byteOffset += length;
  1596. return value;
  1597. };
  1598. BinaryReader.prototype.skipBytes = function (length) {
  1599. this._byteOffset += length;
  1600. };
  1601. return BinaryReader;
  1602. }());
  1603. if (BABYLON.SceneLoader) {
  1604. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1605. }
  1606. })(BABYLON || (BABYLON = {}));
  1607. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1608. var BABYLON;
  1609. (function (BABYLON) {
  1610. var GLTF1;
  1611. (function (GLTF1) {
  1612. /**
  1613. * Enums
  1614. */
  1615. var EComponentType;
  1616. (function (EComponentType) {
  1617. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1618. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1619. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1620. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1621. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1622. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  1623. var EShaderType;
  1624. (function (EShaderType) {
  1625. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1626. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1627. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  1628. var EParameterType;
  1629. (function (EParameterType) {
  1630. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1631. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1632. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1633. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1634. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1635. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1636. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1637. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1638. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1639. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1640. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1641. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1642. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1643. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1644. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1645. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1646. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1647. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1648. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1649. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1650. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1651. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  1652. var ETextureWrapMode;
  1653. (function (ETextureWrapMode) {
  1654. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1655. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1656. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1657. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  1658. var ETextureFilterType;
  1659. (function (ETextureFilterType) {
  1660. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1661. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1662. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1663. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1664. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1665. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1666. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  1667. var ETextureFormat;
  1668. (function (ETextureFormat) {
  1669. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1670. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1671. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1672. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1673. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1674. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  1675. var ECullingType;
  1676. (function (ECullingType) {
  1677. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1678. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1679. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1680. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  1681. var EBlendingFunction;
  1682. (function (EBlendingFunction) {
  1683. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1684. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1685. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1686. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1687. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1688. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1689. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1690. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1691. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1692. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1693. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1694. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1695. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1696. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1697. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1698. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  1699. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1700. })(BABYLON || (BABYLON = {}));
  1701. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  1702. var BABYLON;
  1703. (function (BABYLON) {
  1704. var GLTF1;
  1705. (function (GLTF1) {
  1706. /**
  1707. * Tokenizer. Used for shaders compatibility
  1708. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1709. */
  1710. var ETokenType;
  1711. (function (ETokenType) {
  1712. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1713. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1714. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1715. })(ETokenType || (ETokenType = {}));
  1716. var Tokenizer = /** @class */ (function () {
  1717. function Tokenizer(toParse) {
  1718. this._pos = 0;
  1719. this.currentToken = ETokenType.UNKNOWN;
  1720. this.currentIdentifier = "";
  1721. this.currentString = "";
  1722. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1723. this._toParse = toParse;
  1724. this._maxPos = toParse.length;
  1725. }
  1726. Tokenizer.prototype.getNextToken = function () {
  1727. if (this.isEnd())
  1728. return ETokenType.END_OF_INPUT;
  1729. this.currentString = this.read();
  1730. this.currentToken = ETokenType.UNKNOWN;
  1731. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1732. this.currentToken = ETokenType.IDENTIFIER;
  1733. this.currentIdentifier = this.currentString;
  1734. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1735. this.currentIdentifier += this.currentString;
  1736. this.forward();
  1737. }
  1738. }
  1739. return this.currentToken;
  1740. };
  1741. Tokenizer.prototype.peek = function () {
  1742. return this._toParse[this._pos];
  1743. };
  1744. Tokenizer.prototype.read = function () {
  1745. return this._toParse[this._pos++];
  1746. };
  1747. Tokenizer.prototype.forward = function () {
  1748. this._pos++;
  1749. };
  1750. Tokenizer.prototype.isEnd = function () {
  1751. return this._pos >= this._maxPos;
  1752. };
  1753. return Tokenizer;
  1754. }());
  1755. /**
  1756. * Values
  1757. */
  1758. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1759. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1760. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1761. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1762. /**
  1763. * Parse
  1764. */
  1765. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1766. for (var buf in parsedBuffers) {
  1767. var parsedBuffer = parsedBuffers[buf];
  1768. gltfRuntime.buffers[buf] = parsedBuffer;
  1769. gltfRuntime.buffersCount++;
  1770. }
  1771. };
  1772. var parseShaders = function (parsedShaders, gltfRuntime) {
  1773. for (var sha in parsedShaders) {
  1774. var parsedShader = parsedShaders[sha];
  1775. gltfRuntime.shaders[sha] = parsedShader;
  1776. gltfRuntime.shaderscount++;
  1777. }
  1778. };
  1779. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1780. for (var object in parsedObjects) {
  1781. var parsedObject = parsedObjects[object];
  1782. gltfRuntime[runtimeProperty][object] = parsedObject;
  1783. }
  1784. };
  1785. /**
  1786. * Utils
  1787. */
  1788. var normalizeUVs = function (buffer) {
  1789. if (!buffer) {
  1790. return;
  1791. }
  1792. for (var i = 0; i < buffer.length / 2; i++) {
  1793. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1794. }
  1795. };
  1796. var getAttribute = function (attributeParameter) {
  1797. if (attributeParameter.semantic === "NORMAL") {
  1798. return "normal";
  1799. }
  1800. else if (attributeParameter.semantic === "POSITION") {
  1801. return "position";
  1802. }
  1803. else if (attributeParameter.semantic === "JOINT") {
  1804. return "matricesIndices";
  1805. }
  1806. else if (attributeParameter.semantic === "WEIGHT") {
  1807. return "matricesWeights";
  1808. }
  1809. else if (attributeParameter.semantic === "COLOR") {
  1810. return "color";
  1811. }
  1812. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1813. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1814. return "uv" + (channel === 0 ? "" : channel + 1);
  1815. }
  1816. return null;
  1817. };
  1818. /**
  1819. * Loads and creates animations
  1820. */
  1821. var loadAnimations = function (gltfRuntime) {
  1822. for (var anim in gltfRuntime.animations) {
  1823. var animation = gltfRuntime.animations[anim];
  1824. if (!animation.channels || !animation.samplers) {
  1825. continue;
  1826. }
  1827. var lastAnimation = null;
  1828. for (var i = 0; i < animation.channels.length; i++) {
  1829. // Get parameters and load buffers
  1830. var channel = animation.channels[i];
  1831. var sampler = animation.samplers[channel.sampler];
  1832. if (!sampler) {
  1833. continue;
  1834. }
  1835. var inputData = null;
  1836. var outputData = null;
  1837. if (animation.parameters) {
  1838. inputData = animation.parameters[sampler.input];
  1839. outputData = animation.parameters[sampler.output];
  1840. }
  1841. else {
  1842. inputData = sampler.input;
  1843. outputData = sampler.output;
  1844. }
  1845. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1846. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1847. var targetID = channel.target.id;
  1848. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1849. if (targetNode === null) {
  1850. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1851. }
  1852. if (targetNode === null) {
  1853. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1854. continue;
  1855. }
  1856. var isBone = targetNode instanceof BABYLON.Bone;
  1857. // Get target path (position, rotation or scaling)
  1858. var targetPath = channel.target.path;
  1859. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1860. if (targetPathIndex !== -1) {
  1861. targetPath = babylonAnimationPaths[targetPathIndex];
  1862. }
  1863. // Determine animation type
  1864. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1865. if (!isBone) {
  1866. if (targetPath === "rotationQuaternion") {
  1867. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1868. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1869. }
  1870. else {
  1871. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1872. }
  1873. }
  1874. // Create animation and key frames
  1875. var babylonAnimation = null;
  1876. var keys = [];
  1877. var arrayOffset = 0;
  1878. var modifyKey = false;
  1879. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1880. babylonAnimation = lastAnimation;
  1881. modifyKey = true;
  1882. }
  1883. if (!modifyKey) {
  1884. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1885. }
  1886. // For each frame
  1887. for (var j = 0; j < bufferInput.length; j++) {
  1888. var value = null;
  1889. if (targetPath === "rotationQuaternion") { // VEC4
  1890. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1891. arrayOffset += 4;
  1892. }
  1893. else { // Position and scaling are VEC3
  1894. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1895. arrayOffset += 3;
  1896. }
  1897. if (isBone) {
  1898. var bone = targetNode;
  1899. var translation = BABYLON.Vector3.Zero();
  1900. var rotationQuaternion = new BABYLON.Quaternion();
  1901. var scaling = BABYLON.Vector3.Zero();
  1902. // Warning on decompose
  1903. var mat = bone.getBaseMatrix();
  1904. if (modifyKey && lastAnimation) {
  1905. mat = lastAnimation.getKeys()[j].value;
  1906. }
  1907. mat.decompose(scaling, rotationQuaternion, translation);
  1908. if (targetPath === "position") {
  1909. translation = value;
  1910. }
  1911. else if (targetPath === "rotationQuaternion") {
  1912. rotationQuaternion = value;
  1913. }
  1914. else {
  1915. scaling = value;
  1916. }
  1917. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1918. }
  1919. if (!modifyKey) {
  1920. keys.push({
  1921. frame: bufferInput[j],
  1922. value: value
  1923. });
  1924. }
  1925. else if (lastAnimation) {
  1926. lastAnimation.getKeys()[j].value = value;
  1927. }
  1928. }
  1929. // Finish
  1930. if (!modifyKey && babylonAnimation) {
  1931. babylonAnimation.setKeys(keys);
  1932. targetNode.animations.push(babylonAnimation);
  1933. }
  1934. lastAnimation = babylonAnimation;
  1935. gltfRuntime.scene.stopAnimation(targetNode);
  1936. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1937. }
  1938. }
  1939. };
  1940. /**
  1941. * Returns the bones transformation matrix
  1942. */
  1943. var configureBoneTransformation = function (node) {
  1944. var mat = null;
  1945. if (node.translation || node.rotation || node.scale) {
  1946. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1947. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1948. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1949. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1950. }
  1951. else {
  1952. mat = BABYLON.Matrix.FromArray(node.matrix);
  1953. }
  1954. return mat;
  1955. };
  1956. /**
  1957. * Returns the parent bone
  1958. */
  1959. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1960. // Try to find
  1961. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1962. if (newSkeleton.bones[i].name === jointName) {
  1963. return newSkeleton.bones[i];
  1964. }
  1965. }
  1966. // Not found, search in gltf nodes
  1967. var nodes = gltfRuntime.nodes;
  1968. for (var nde in nodes) {
  1969. var node = nodes[nde];
  1970. if (!node.jointName) {
  1971. continue;
  1972. }
  1973. var children = node.children;
  1974. for (var i = 0; i < children.length; i++) {
  1975. var child = gltfRuntime.nodes[children[i]];
  1976. if (!child.jointName) {
  1977. continue;
  1978. }
  1979. if (child.jointName === jointName) {
  1980. var mat = configureBoneTransformation(node);
  1981. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1982. bone.id = nde;
  1983. return bone;
  1984. }
  1985. }
  1986. }
  1987. return null;
  1988. };
  1989. /**
  1990. * Returns the appropriate root node
  1991. */
  1992. var getNodeToRoot = function (nodesToRoot, id) {
  1993. for (var i = 0; i < nodesToRoot.length; i++) {
  1994. var nodeToRoot = nodesToRoot[i];
  1995. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1996. var child = nodeToRoot.node.children[j];
  1997. if (child === id) {
  1998. return nodeToRoot.bone;
  1999. }
  2000. }
  2001. }
  2002. return null;
  2003. };
  2004. /**
  2005. * Returns the node with the joint name
  2006. */
  2007. var getJointNode = function (gltfRuntime, jointName) {
  2008. var nodes = gltfRuntime.nodes;
  2009. var node = nodes[jointName];
  2010. if (node) {
  2011. return {
  2012. node: node,
  2013. id: jointName
  2014. };
  2015. }
  2016. for (var nde in nodes) {
  2017. node = nodes[nde];
  2018. if (node.jointName === jointName) {
  2019. return {
  2020. node: node,
  2021. id: nde
  2022. };
  2023. }
  2024. }
  2025. return null;
  2026. };
  2027. /**
  2028. * Checks if a nodes is in joints
  2029. */
  2030. var nodeIsInJoints = function (skins, id) {
  2031. for (var i = 0; i < skins.jointNames.length; i++) {
  2032. if (skins.jointNames[i] === id) {
  2033. return true;
  2034. }
  2035. }
  2036. return false;
  2037. };
  2038. /**
  2039. * Fills the nodes to root for bones and builds hierarchy
  2040. */
  2041. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  2042. // Creates nodes for root
  2043. for (var nde in gltfRuntime.nodes) {
  2044. var node = gltfRuntime.nodes[nde];
  2045. var id = nde;
  2046. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  2047. continue;
  2048. }
  2049. // Create node to root bone
  2050. var mat = configureBoneTransformation(node);
  2051. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  2052. bone.id = id;
  2053. nodesToRoot.push({ bone: bone, node: node, id: id });
  2054. }
  2055. // Parenting
  2056. for (var i = 0; i < nodesToRoot.length; i++) {
  2057. var nodeToRoot = nodesToRoot[i];
  2058. var children = nodeToRoot.node.children;
  2059. for (var j = 0; j < children.length; j++) {
  2060. var child = null;
  2061. for (var k = 0; k < nodesToRoot.length; k++) {
  2062. if (nodesToRoot[k].id === children[j]) {
  2063. child = nodesToRoot[k];
  2064. break;
  2065. }
  2066. }
  2067. if (child) {
  2068. child.bone._parent = nodeToRoot.bone;
  2069. nodeToRoot.bone.children.push(child.bone);
  2070. }
  2071. }
  2072. }
  2073. };
  2074. /**
  2075. * Imports a skeleton
  2076. */
  2077. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  2078. if (!newSkeleton) {
  2079. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  2080. }
  2081. if (!skins.babylonSkeleton) {
  2082. return newSkeleton;
  2083. }
  2084. // Find the root bones
  2085. var nodesToRoot = [];
  2086. var nodesToRootToAdd = [];
  2087. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  2088. newSkeleton.bones = [];
  2089. // Joints
  2090. for (var i = 0; i < skins.jointNames.length; i++) {
  2091. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  2092. if (!jointNode) {
  2093. continue;
  2094. }
  2095. var node = jointNode.node;
  2096. if (!node) {
  2097. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  2098. continue;
  2099. }
  2100. var id = jointNode.id;
  2101. // Optimize, if the bone already exists...
  2102. var existingBone = gltfRuntime.scene.getBoneByID(id);
  2103. if (existingBone) {
  2104. newSkeleton.bones.push(existingBone);
  2105. continue;
  2106. }
  2107. // Search for parent bone
  2108. var foundBone = false;
  2109. var parentBone = null;
  2110. for (var j = 0; j < i; j++) {
  2111. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  2112. if (!jointNode_1) {
  2113. continue;
  2114. }
  2115. var joint = jointNode_1.node;
  2116. if (!joint) {
  2117. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  2118. continue;
  2119. }
  2120. var children = joint.children;
  2121. if (!children) {
  2122. continue;
  2123. }
  2124. foundBone = false;
  2125. for (var k = 0; k < children.length; k++) {
  2126. if (children[k] === id) {
  2127. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  2128. foundBone = true;
  2129. break;
  2130. }
  2131. }
  2132. if (foundBone) {
  2133. break;
  2134. }
  2135. }
  2136. // Create bone
  2137. var mat = configureBoneTransformation(node);
  2138. if (!parentBone && nodesToRoot.length > 0) {
  2139. parentBone = getNodeToRoot(nodesToRoot, id);
  2140. if (parentBone) {
  2141. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  2142. nodesToRootToAdd.push(parentBone);
  2143. }
  2144. }
  2145. }
  2146. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  2147. bone.id = id;
  2148. }
  2149. // Polish
  2150. var bones = newSkeleton.bones;
  2151. newSkeleton.bones = [];
  2152. for (var i = 0; i < skins.jointNames.length; i++) {
  2153. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  2154. if (!jointNode) {
  2155. continue;
  2156. }
  2157. for (var j = 0; j < bones.length; j++) {
  2158. if (bones[j].id === jointNode.id) {
  2159. newSkeleton.bones.push(bones[j]);
  2160. break;
  2161. }
  2162. }
  2163. }
  2164. newSkeleton.prepare();
  2165. // Finish
  2166. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  2167. newSkeleton.bones.push(nodesToRootToAdd[i]);
  2168. }
  2169. return newSkeleton;
  2170. };
  2171. /**
  2172. * Imports a mesh and its geometries
  2173. */
  2174. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  2175. if (!newMesh) {
  2176. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2177. newMesh.id = id;
  2178. }
  2179. if (!node.babylonNode) {
  2180. return newMesh;
  2181. }
  2182. var subMaterials = [];
  2183. var vertexData = null;
  2184. var verticesStarts = new Array();
  2185. var verticesCounts = new Array();
  2186. var indexStarts = new Array();
  2187. var indexCounts = new Array();
  2188. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2189. var meshID = meshes[meshIndex];
  2190. var mesh = gltfRuntime.meshes[meshID];
  2191. if (!mesh) {
  2192. continue;
  2193. }
  2194. // Positions, normals and UVs
  2195. for (var i = 0; i < mesh.primitives.length; i++) {
  2196. // Temporary vertex data
  2197. var tempVertexData = new BABYLON.VertexData();
  2198. var primitive = mesh.primitives[i];
  2199. if (primitive.mode !== 4) {
  2200. // continue;
  2201. }
  2202. var attributes = primitive.attributes;
  2203. var accessor = null;
  2204. var buffer = null;
  2205. // Set positions, normal and uvs
  2206. for (var semantic in attributes) {
  2207. // Link accessor and buffer view
  2208. accessor = gltfRuntime.accessors[attributes[semantic]];
  2209. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2210. if (semantic === "NORMAL") {
  2211. tempVertexData.normals = new Float32Array(buffer.length);
  2212. tempVertexData.normals.set(buffer);
  2213. }
  2214. else if (semantic === "POSITION") {
  2215. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  2216. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  2217. for (var j = 0; j < buffer.length; j += 4) {
  2218. tempVertexData.positions[j] = buffer[j];
  2219. tempVertexData.positions[j + 1] = buffer[j + 1];
  2220. tempVertexData.positions[j + 2] = buffer[j + 2];
  2221. }
  2222. }
  2223. else {
  2224. tempVertexData.positions = new Float32Array(buffer.length);
  2225. tempVertexData.positions.set(buffer);
  2226. }
  2227. verticesCounts.push(tempVertexData.positions.length);
  2228. }
  2229. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2230. var channel = Number(semantic.split("_")[1]);
  2231. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2232. var uvs = new Float32Array(buffer.length);
  2233. uvs.set(buffer);
  2234. normalizeUVs(uvs);
  2235. tempVertexData.set(uvs, uvKind);
  2236. }
  2237. else if (semantic === "JOINT") {
  2238. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2239. tempVertexData.matricesIndices.set(buffer);
  2240. }
  2241. else if (semantic === "WEIGHT") {
  2242. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2243. tempVertexData.matricesWeights.set(buffer);
  2244. }
  2245. else if (semantic === "COLOR") {
  2246. tempVertexData.colors = new Float32Array(buffer.length);
  2247. tempVertexData.colors.set(buffer);
  2248. }
  2249. }
  2250. // Indices
  2251. accessor = gltfRuntime.accessors[primitive.indices];
  2252. if (accessor) {
  2253. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2254. tempVertexData.indices = new Int32Array(buffer.length);
  2255. tempVertexData.indices.set(buffer);
  2256. indexCounts.push(tempVertexData.indices.length);
  2257. }
  2258. else {
  2259. // Set indices on the fly
  2260. var indices = [];
  2261. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2262. indices.push(j);
  2263. }
  2264. tempVertexData.indices = new Int32Array(indices);
  2265. indexCounts.push(tempVertexData.indices.length);
  2266. }
  2267. if (!vertexData) {
  2268. vertexData = tempVertexData;
  2269. }
  2270. else {
  2271. vertexData.merge(tempVertexData);
  2272. }
  2273. // Sub material
  2274. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  2275. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  2276. // Update vertices start and index start
  2277. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2278. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2279. }
  2280. }
  2281. var material;
  2282. if (subMaterials.length > 1) {
  2283. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  2284. material.subMaterials = subMaterials;
  2285. }
  2286. else {
  2287. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  2288. }
  2289. if (subMaterials.length === 1) {
  2290. material = subMaterials[0];
  2291. }
  2292. if (!newMesh.material) {
  2293. newMesh.material = material;
  2294. }
  2295. // Apply geometry
  2296. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  2297. newMesh.computeWorldMatrix(true);
  2298. // Apply submeshes
  2299. newMesh.subMeshes = [];
  2300. var index = 0;
  2301. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2302. var meshID = meshes[meshIndex];
  2303. var mesh = gltfRuntime.meshes[meshID];
  2304. if (!mesh) {
  2305. continue;
  2306. }
  2307. for (var i = 0; i < mesh.primitives.length; i++) {
  2308. if (mesh.primitives[i].mode !== 4) {
  2309. //continue;
  2310. }
  2311. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  2312. index++;
  2313. }
  2314. }
  2315. // Finish
  2316. return newMesh;
  2317. };
  2318. /**
  2319. * Configure node transformation from position, rotation and scaling
  2320. */
  2321. var configureNode = function (newNode, position, rotation, scaling) {
  2322. if (newNode.position) {
  2323. newNode.position = position;
  2324. }
  2325. if (newNode.rotationQuaternion || newNode.rotation) {
  2326. newNode.rotationQuaternion = rotation;
  2327. }
  2328. if (newNode.scaling) {
  2329. newNode.scaling = scaling;
  2330. }
  2331. };
  2332. /**
  2333. * Configures node from transformation matrix
  2334. */
  2335. var configureNodeFromMatrix = function (newNode, node, parent) {
  2336. if (node.matrix) {
  2337. var position = new BABYLON.Vector3(0, 0, 0);
  2338. var rotation = new BABYLON.Quaternion();
  2339. var scaling = new BABYLON.Vector3(0, 0, 0);
  2340. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2341. mat.decompose(scaling, rotation, position);
  2342. configureNode(newNode, position, rotation, scaling);
  2343. }
  2344. else if (node.translation && node.rotation && node.scale) {
  2345. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  2346. }
  2347. newNode.computeWorldMatrix(true);
  2348. };
  2349. /**
  2350. * Imports a node
  2351. */
  2352. var importNode = function (gltfRuntime, node, id, parent) {
  2353. var lastNode = null;
  2354. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  2355. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  2356. return null;
  2357. }
  2358. }
  2359. // Meshes
  2360. if (node.skin) {
  2361. if (node.meshes) {
  2362. var skin = gltfRuntime.skins[node.skin];
  2363. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  2364. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  2365. if (newMesh.skeleton === null) {
  2366. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  2367. if (!skin.babylonSkeleton) {
  2368. skin.babylonSkeleton = newMesh.skeleton;
  2369. }
  2370. }
  2371. lastNode = newMesh;
  2372. }
  2373. }
  2374. else if (node.meshes) {
  2375. /**
  2376. * Improve meshes property
  2377. */
  2378. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  2379. lastNode = newMesh;
  2380. }
  2381. // Lights
  2382. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2383. var light = gltfRuntime.lights[node.light];
  2384. if (light) {
  2385. if (light.type === "ambient") {
  2386. var ambienLight = light[light.type];
  2387. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2388. hemiLight.name = node.name || "";
  2389. if (ambienLight.color) {
  2390. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  2391. }
  2392. lastNode = hemiLight;
  2393. }
  2394. else if (light.type === "directional") {
  2395. var directionalLight = light[light.type];
  2396. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2397. dirLight.name = node.name || "";
  2398. if (directionalLight.color) {
  2399. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  2400. }
  2401. lastNode = dirLight;
  2402. }
  2403. else if (light.type === "point") {
  2404. var pointLight = light[light.type];
  2405. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2406. ptLight.name = node.name || "";
  2407. if (pointLight.color) {
  2408. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  2409. }
  2410. lastNode = ptLight;
  2411. }
  2412. else if (light.type === "spot") {
  2413. var spotLight = light[light.type];
  2414. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2415. spLight.name = node.name || "";
  2416. if (spotLight.color) {
  2417. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  2418. }
  2419. if (spotLight.fallOfAngle) {
  2420. spLight.angle = spotLight.fallOfAngle;
  2421. }
  2422. if (spotLight.fallOffExponent) {
  2423. spLight.exponent = spotLight.fallOffExponent;
  2424. }
  2425. lastNode = spLight;
  2426. }
  2427. }
  2428. }
  2429. // Cameras
  2430. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2431. var camera = gltfRuntime.cameras[node.camera];
  2432. if (camera) {
  2433. if (camera.type === "orthographic") {
  2434. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  2435. orthoCamera.name = node.name || "";
  2436. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  2437. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2438. lastNode = orthoCamera;
  2439. }
  2440. else if (camera.type === "perspective") {
  2441. var perspectiveCamera = camera[camera.type];
  2442. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  2443. persCamera.name = node.name || "";
  2444. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2445. if (!perspectiveCamera.aspectRatio) {
  2446. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2447. }
  2448. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2449. persCamera.maxZ = perspectiveCamera.zfar;
  2450. persCamera.minZ = perspectiveCamera.znear;
  2451. }
  2452. lastNode = persCamera;
  2453. }
  2454. }
  2455. }
  2456. // Empty node
  2457. if (!node.jointName) {
  2458. if (node.babylonNode) {
  2459. return node.babylonNode;
  2460. }
  2461. else if (lastNode === null) {
  2462. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2463. node.babylonNode = dummy;
  2464. lastNode = dummy;
  2465. }
  2466. }
  2467. if (lastNode !== null) {
  2468. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  2469. configureNodeFromMatrix(lastNode, node, parent);
  2470. }
  2471. else {
  2472. var translation = node.translation || [0, 0, 0];
  2473. var rotation = node.rotation || [0, 0, 0, 1];
  2474. var scale = node.scale || [1, 1, 1];
  2475. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  2476. }
  2477. lastNode.updateCache(true);
  2478. node.babylonNode = lastNode;
  2479. }
  2480. return lastNode;
  2481. };
  2482. /**
  2483. * Traverses nodes and creates them
  2484. */
  2485. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2486. if (meshIncluded === void 0) { meshIncluded = false; }
  2487. var node = gltfRuntime.nodes[id];
  2488. var newNode = null;
  2489. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  2490. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2491. meshIncluded = true;
  2492. }
  2493. else {
  2494. meshIncluded = false;
  2495. }
  2496. }
  2497. else {
  2498. meshIncluded = true;
  2499. }
  2500. if (!node.jointName && meshIncluded) {
  2501. newNode = importNode(gltfRuntime, node, id, parent);
  2502. if (newNode !== null) {
  2503. newNode.id = id;
  2504. newNode.parent = parent;
  2505. }
  2506. }
  2507. if (node.children) {
  2508. for (var i = 0; i < node.children.length; i++) {
  2509. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2510. }
  2511. }
  2512. };
  2513. /**
  2514. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2515. */
  2516. var postLoad = function (gltfRuntime) {
  2517. // Nodes
  2518. var currentScene = gltfRuntime.currentScene;
  2519. if (currentScene) {
  2520. for (var i = 0; i < currentScene.nodes.length; i++) {
  2521. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2522. }
  2523. }
  2524. else {
  2525. for (var thing in gltfRuntime.scenes) {
  2526. currentScene = gltfRuntime.scenes[thing];
  2527. for (var i = 0; i < currentScene.nodes.length; i++) {
  2528. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2529. }
  2530. }
  2531. }
  2532. // Set animations
  2533. loadAnimations(gltfRuntime);
  2534. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2535. var skeleton = gltfRuntime.scene.skeletons[i];
  2536. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2537. }
  2538. };
  2539. /**
  2540. * onBind shaderrs callback to set uniforms and matrices
  2541. */
  2542. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2543. var materialValues = material.values || technique.parameters;
  2544. for (var unif in unTreatedUniforms) {
  2545. var uniform = unTreatedUniforms[unif];
  2546. var type = uniform.type;
  2547. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  2548. if (uniform.semantic && !uniform.source && !uniform.node) {
  2549. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2550. }
  2551. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2552. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  2553. if (source === null) {
  2554. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  2555. }
  2556. if (source === null) {
  2557. continue;
  2558. }
  2559. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2560. }
  2561. }
  2562. else {
  2563. var value = materialValues[technique.uniforms[unif]];
  2564. if (!value) {
  2565. continue;
  2566. }
  2567. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2568. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2569. if (texture === null || texture === undefined) {
  2570. continue;
  2571. }
  2572. shaderMaterial.getEffect().setTexture(unif, texture);
  2573. }
  2574. else {
  2575. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  2576. }
  2577. }
  2578. }
  2579. onSuccess(shaderMaterial);
  2580. };
  2581. /**
  2582. * Prepare uniforms to send the only one time
  2583. * Loads the appropriate textures
  2584. */
  2585. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2586. var materialValues = material.values || technique.parameters;
  2587. var techniqueUniforms = technique.uniforms;
  2588. /**
  2589. * Prepare values here (not matrices)
  2590. */
  2591. for (var unif in unTreatedUniforms) {
  2592. var uniform = unTreatedUniforms[unif];
  2593. var type = uniform.type;
  2594. var value = materialValues[techniqueUniforms[unif]];
  2595. if (value === undefined) {
  2596. // In case the value is the same for all materials
  2597. value = uniform.value;
  2598. }
  2599. if (!value) {
  2600. continue;
  2601. }
  2602. var onLoadTexture = function (uniformName) {
  2603. return function (texture) {
  2604. if (uniform.value && uniformName) {
  2605. // Static uniform
  2606. shaderMaterial.setTexture(uniformName, texture);
  2607. delete unTreatedUniforms[uniformName];
  2608. }
  2609. };
  2610. };
  2611. // Texture (sampler2D)
  2612. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2613. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2614. }
  2615. // Others
  2616. else {
  2617. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2618. // Static uniform
  2619. delete unTreatedUniforms[unif];
  2620. }
  2621. }
  2622. }
  2623. };
  2624. /**
  2625. * Shader compilation failed
  2626. */
  2627. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2628. return function (effect, error) {
  2629. shaderMaterial.dispose(true);
  2630. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2631. };
  2632. };
  2633. /**
  2634. * Shader compilation success
  2635. */
  2636. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2637. return function (_) {
  2638. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2639. shaderMaterial.onBind = function (mesh) {
  2640. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2641. };
  2642. };
  2643. };
  2644. /**
  2645. * Returns the appropriate uniform if already handled by babylon
  2646. */
  2647. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2648. for (var unif in technique.uniforms) {
  2649. var uniform = technique.uniforms[unif];
  2650. var uniformParameter = technique.parameters[uniform];
  2651. if (tokenizer.currentIdentifier === unif) {
  2652. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2653. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2654. if (transformIndex !== -1) {
  2655. delete unTreatedUniforms[unif];
  2656. return babylonTransforms[transformIndex];
  2657. }
  2658. }
  2659. }
  2660. }
  2661. return tokenizer.currentIdentifier;
  2662. };
  2663. /**
  2664. * All shaders loaded. Create materials one by one
  2665. */
  2666. var importMaterials = function (gltfRuntime) {
  2667. // Create materials
  2668. for (var mat in gltfRuntime.materials) {
  2669. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2670. }
  2671. };
  2672. /**
  2673. * Implementation of the base glTF spec
  2674. */
  2675. var GLTFLoaderBase = /** @class */ (function () {
  2676. function GLTFLoaderBase() {
  2677. }
  2678. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2679. var gltfRuntime = {
  2680. extensions: {},
  2681. accessors: {},
  2682. buffers: {},
  2683. bufferViews: {},
  2684. meshes: {},
  2685. lights: {},
  2686. cameras: {},
  2687. nodes: {},
  2688. images: {},
  2689. textures: {},
  2690. shaders: {},
  2691. programs: {},
  2692. samplers: {},
  2693. techniques: {},
  2694. materials: {},
  2695. animations: {},
  2696. skins: {},
  2697. extensionsUsed: [],
  2698. scenes: {},
  2699. buffersCount: 0,
  2700. shaderscount: 0,
  2701. scene: scene,
  2702. rootUrl: rootUrl,
  2703. loadedBufferCount: 0,
  2704. loadedBufferViews: {},
  2705. loadedShaderCount: 0,
  2706. importOnlyMeshes: false,
  2707. dummyNodes: []
  2708. };
  2709. // Parse
  2710. if (parsedData.extensions) {
  2711. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2712. }
  2713. if (parsedData.extensionsUsed) {
  2714. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2715. }
  2716. if (parsedData.buffers) {
  2717. parseBuffers(parsedData.buffers, gltfRuntime);
  2718. }
  2719. if (parsedData.bufferViews) {
  2720. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2721. }
  2722. if (parsedData.accessors) {
  2723. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2724. }
  2725. if (parsedData.meshes) {
  2726. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2727. }
  2728. if (parsedData.lights) {
  2729. parseObject(parsedData.lights, "lights", gltfRuntime);
  2730. }
  2731. if (parsedData.cameras) {
  2732. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2733. }
  2734. if (parsedData.nodes) {
  2735. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2736. }
  2737. if (parsedData.images) {
  2738. parseObject(parsedData.images, "images", gltfRuntime);
  2739. }
  2740. if (parsedData.textures) {
  2741. parseObject(parsedData.textures, "textures", gltfRuntime);
  2742. }
  2743. if (parsedData.shaders) {
  2744. parseShaders(parsedData.shaders, gltfRuntime);
  2745. }
  2746. if (parsedData.programs) {
  2747. parseObject(parsedData.programs, "programs", gltfRuntime);
  2748. }
  2749. if (parsedData.samplers) {
  2750. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2751. }
  2752. if (parsedData.techniques) {
  2753. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2754. }
  2755. if (parsedData.materials) {
  2756. parseObject(parsedData.materials, "materials", gltfRuntime);
  2757. }
  2758. if (parsedData.animations) {
  2759. parseObject(parsedData.animations, "animations", gltfRuntime);
  2760. }
  2761. if (parsedData.skins) {
  2762. parseObject(parsedData.skins, "skins", gltfRuntime);
  2763. }
  2764. if (parsedData.scenes) {
  2765. gltfRuntime.scenes = parsedData.scenes;
  2766. }
  2767. if (parsedData.scene && parsedData.scenes) {
  2768. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2769. }
  2770. return gltfRuntime;
  2771. };
  2772. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2773. var buffer = gltfRuntime.buffers[id];
  2774. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  2775. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  2776. }
  2777. else {
  2778. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  2779. if (request) {
  2780. onError(request.status + " " + request.statusText);
  2781. }
  2782. });
  2783. }
  2784. };
  2785. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2786. var texture = gltfRuntime.textures[id];
  2787. if (!texture || !texture.source) {
  2788. onError("");
  2789. return;
  2790. }
  2791. if (texture.babylonTexture) {
  2792. onSuccess(null);
  2793. return;
  2794. }
  2795. var source = gltfRuntime.images[texture.source];
  2796. if (BABYLON.Tools.IsBase64(source.uri)) {
  2797. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  2798. }
  2799. else {
  2800. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  2801. if (request) {
  2802. onError(request.status + " " + request.statusText);
  2803. }
  2804. });
  2805. }
  2806. };
  2807. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2808. var texture = gltfRuntime.textures[id];
  2809. if (texture.babylonTexture) {
  2810. onSuccess(texture.babylonTexture);
  2811. return;
  2812. }
  2813. var sampler = gltfRuntime.samplers[texture.sampler];
  2814. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2815. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2816. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2817. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2818. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2819. var blob = new Blob([buffer]);
  2820. var blobURL = URL.createObjectURL(blob);
  2821. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2822. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2823. if (sampler.wrapS !== undefined) {
  2824. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2825. }
  2826. if (sampler.wrapT !== undefined) {
  2827. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2828. }
  2829. newTexture.name = id;
  2830. texture.babylonTexture = newTexture;
  2831. onSuccess(newTexture);
  2832. };
  2833. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2834. var shader = gltfRuntime.shaders[id];
  2835. if (BABYLON.Tools.IsBase64(shader.uri)) {
  2836. var shaderString = atob(shader.uri.split(",")[1]);
  2837. if (onSuccess) {
  2838. onSuccess(shaderString);
  2839. }
  2840. }
  2841. else {
  2842. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  2843. if (request && onError) {
  2844. onError(request.status + " " + request.statusText);
  2845. }
  2846. });
  2847. }
  2848. };
  2849. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2850. var material = gltfRuntime.materials[id];
  2851. if (!material.technique) {
  2852. if (onError) {
  2853. onError("No technique found.");
  2854. }
  2855. return;
  2856. }
  2857. var technique = gltfRuntime.techniques[material.technique];
  2858. if (!technique) {
  2859. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2860. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2861. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2862. onSuccess(defaultMaterial);
  2863. return;
  2864. }
  2865. var program = gltfRuntime.programs[technique.program];
  2866. var states = technique.states;
  2867. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2868. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2869. var newVertexShader = "";
  2870. var newPixelShader = "";
  2871. var vertexTokenizer = new Tokenizer(vertexShader);
  2872. var pixelTokenizer = new Tokenizer(pixelShader);
  2873. var unTreatedUniforms = {};
  2874. var uniforms = [];
  2875. var attributes = [];
  2876. var samplers = [];
  2877. // Fill uniform, sampler2D and attributes
  2878. for (var unif in technique.uniforms) {
  2879. var uniform = technique.uniforms[unif];
  2880. var uniformParameter = technique.parameters[uniform];
  2881. unTreatedUniforms[unif] = uniformParameter;
  2882. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2883. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2884. if (transformIndex !== -1) {
  2885. uniforms.push(babylonTransforms[transformIndex]);
  2886. delete unTreatedUniforms[unif];
  2887. }
  2888. else {
  2889. uniforms.push(unif);
  2890. }
  2891. }
  2892. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2893. samplers.push(unif);
  2894. }
  2895. else {
  2896. uniforms.push(unif);
  2897. }
  2898. }
  2899. for (var attr in technique.attributes) {
  2900. var attribute = technique.attributes[attr];
  2901. var attributeParameter = technique.parameters[attribute];
  2902. if (attributeParameter.semantic) {
  2903. attributes.push(getAttribute(attributeParameter));
  2904. }
  2905. }
  2906. // Configure vertex shader
  2907. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2908. var tokenType = vertexTokenizer.currentToken;
  2909. if (tokenType !== ETokenType.IDENTIFIER) {
  2910. newVertexShader += vertexTokenizer.currentString;
  2911. continue;
  2912. }
  2913. var foundAttribute = false;
  2914. for (var attr in technique.attributes) {
  2915. var attribute = technique.attributes[attr];
  2916. var attributeParameter = technique.parameters[attribute];
  2917. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2918. newVertexShader += getAttribute(attributeParameter);
  2919. foundAttribute = true;
  2920. break;
  2921. }
  2922. }
  2923. if (foundAttribute) {
  2924. continue;
  2925. }
  2926. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2927. }
  2928. // Configure pixel shader
  2929. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2930. var tokenType = pixelTokenizer.currentToken;
  2931. if (tokenType !== ETokenType.IDENTIFIER) {
  2932. newPixelShader += pixelTokenizer.currentString;
  2933. continue;
  2934. }
  2935. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2936. }
  2937. // Create shader material
  2938. var shaderPath = {
  2939. vertex: program.vertexShader + id,
  2940. fragment: program.fragmentShader + id
  2941. };
  2942. var options = {
  2943. attributes: attributes,
  2944. uniforms: uniforms,
  2945. samplers: samplers,
  2946. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2947. };
  2948. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2949. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2950. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2951. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2952. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2953. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2954. if (states && states.functions) {
  2955. var functions = states.functions;
  2956. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2957. shaderMaterial.backFaceCulling = false;
  2958. }
  2959. var blendFunc = functions.blendFuncSeparate;
  2960. if (blendFunc) {
  2961. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2962. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2963. }
  2964. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2965. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2966. }
  2967. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2968. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2969. }
  2970. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2971. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2972. }
  2973. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2974. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2975. }
  2976. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2977. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2978. }
  2979. }
  2980. }
  2981. };
  2982. return GLTFLoaderBase;
  2983. }());
  2984. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2985. /**
  2986. * glTF V1 Loader
  2987. */
  2988. var GLTFLoader = /** @class */ (function () {
  2989. function GLTFLoader() {
  2990. this.state = null;
  2991. }
  2992. GLTFLoader.RegisterExtension = function (extension) {
  2993. if (GLTFLoader.Extensions[extension.name]) {
  2994. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2995. return;
  2996. }
  2997. GLTFLoader.Extensions[extension.name] = extension;
  2998. };
  2999. GLTFLoader.prototype.dispose = function () {
  3000. // do nothing
  3001. };
  3002. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3003. var _this = this;
  3004. scene.useRightHandedSystem = true;
  3005. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  3006. gltfRuntime.importOnlyMeshes = true;
  3007. if (meshesNames === "") {
  3008. gltfRuntime.importMeshesNames = [];
  3009. }
  3010. else if (typeof meshesNames === "string") {
  3011. gltfRuntime.importMeshesNames = [meshesNames];
  3012. }
  3013. else if (meshesNames && !(meshesNames instanceof Array)) {
  3014. gltfRuntime.importMeshesNames = [meshesNames];
  3015. }
  3016. else {
  3017. gltfRuntime.importMeshesNames = [];
  3018. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  3019. }
  3020. // Create nodes
  3021. _this._createNodes(gltfRuntime);
  3022. var meshes = new Array();
  3023. var skeletons = new Array();
  3024. // Fill arrays of meshes and skeletons
  3025. for (var nde in gltfRuntime.nodes) {
  3026. var node = gltfRuntime.nodes[nde];
  3027. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  3028. meshes.push(node.babylonNode);
  3029. }
  3030. }
  3031. for (var skl in gltfRuntime.skins) {
  3032. var skin = gltfRuntime.skins[skl];
  3033. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  3034. skeletons.push(skin.babylonSkeleton);
  3035. }
  3036. }
  3037. // Load buffers, shaders, materials, etc.
  3038. _this._loadBuffersAsync(gltfRuntime, function () {
  3039. _this._loadShadersAsync(gltfRuntime, function () {
  3040. importMaterials(gltfRuntime);
  3041. postLoad(gltfRuntime);
  3042. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3043. onSuccess(meshes, skeletons);
  3044. }
  3045. });
  3046. }, onProgress);
  3047. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3048. onSuccess(meshes, skeletons);
  3049. }
  3050. }, onError);
  3051. return true;
  3052. };
  3053. /**
  3054. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  3055. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  3056. * @param scene the scene the meshes should be added to
  3057. * @param data gltf data containing information of the meshes in a loaded file
  3058. * @param rootUrl root url to load from
  3059. * @param onProgress event that fires when loading progress has occured
  3060. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  3061. */
  3062. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  3063. var _this = this;
  3064. return new Promise(function (resolve, reject) {
  3065. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  3066. resolve({
  3067. meshes: meshes,
  3068. particleSystems: [],
  3069. skeletons: skeletons,
  3070. animationGroups: []
  3071. });
  3072. }, onProgress, function (message) {
  3073. reject(new Error(message));
  3074. });
  3075. });
  3076. };
  3077. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  3078. var _this = this;
  3079. scene.useRightHandedSystem = true;
  3080. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  3081. // Load runtime extensios
  3082. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  3083. // Create nodes
  3084. _this._createNodes(gltfRuntime);
  3085. // Load buffers, shaders, materials, etc.
  3086. _this._loadBuffersAsync(gltfRuntime, function () {
  3087. _this._loadShadersAsync(gltfRuntime, function () {
  3088. importMaterials(gltfRuntime);
  3089. postLoad(gltfRuntime);
  3090. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  3091. onSuccess();
  3092. }
  3093. });
  3094. });
  3095. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  3096. onSuccess();
  3097. }
  3098. }, onError);
  3099. }, onError);
  3100. };
  3101. /**
  3102. * Imports all objects from a loaded gltf file and adds them to the scene
  3103. * @param scene the scene the objects should be added to
  3104. * @param data gltf data containing information of the meshes in a loaded file
  3105. * @param rootUrl root url to load from
  3106. * @param onProgress event that fires when loading progress has occured
  3107. * @returns a promise which completes when objects have been loaded to the scene
  3108. */
  3109. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  3110. var _this = this;
  3111. return new Promise(function (resolve, reject) {
  3112. _this._loadAsync(scene, data, rootUrl, function () {
  3113. resolve();
  3114. }, onProgress, function (message) {
  3115. reject(new Error(message));
  3116. });
  3117. });
  3118. };
  3119. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  3120. var hasShaders = false;
  3121. var processShader = function (sha, shader) {
  3122. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  3123. if (shaderString instanceof ArrayBuffer) {
  3124. return;
  3125. }
  3126. gltfRuntime.loadedShaderCount++;
  3127. if (shaderString) {
  3128. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  3129. }
  3130. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  3131. onload();
  3132. }
  3133. }, function () {
  3134. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  3135. });
  3136. };
  3137. for (var sha in gltfRuntime.shaders) {
  3138. hasShaders = true;
  3139. var shader = gltfRuntime.shaders[sha];
  3140. if (shader) {
  3141. processShader.bind(this, sha, shader)();
  3142. }
  3143. else {
  3144. BABYLON.Tools.Error("No shader named: " + sha);
  3145. }
  3146. }
  3147. if (!hasShaders) {
  3148. onload();
  3149. }
  3150. };
  3151. ;
  3152. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  3153. var hasBuffers = false;
  3154. var processBuffer = function (buf, buffer) {
  3155. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  3156. gltfRuntime.loadedBufferCount++;
  3157. if (bufferView) {
  3158. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  3159. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  3160. }
  3161. gltfRuntime.loadedBufferViews[buf] = bufferView;
  3162. }
  3163. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  3164. onLoad();
  3165. }
  3166. }, function () {
  3167. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  3168. });
  3169. };
  3170. for (var buf in gltfRuntime.buffers) {
  3171. hasBuffers = true;
  3172. var buffer = gltfRuntime.buffers[buf];
  3173. if (buffer) {
  3174. processBuffer.bind(this, buf, buffer)();
  3175. }
  3176. else {
  3177. BABYLON.Tools.Error("No buffer named: " + buf);
  3178. }
  3179. }
  3180. if (!hasBuffers) {
  3181. onLoad();
  3182. }
  3183. };
  3184. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  3185. var currentScene = gltfRuntime.currentScene;
  3186. if (currentScene) {
  3187. // Only one scene even if multiple scenes are defined
  3188. for (var i = 0; i < currentScene.nodes.length; i++) {
  3189. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3190. }
  3191. }
  3192. else {
  3193. // Load all scenes
  3194. for (var thing in gltfRuntime.scenes) {
  3195. currentScene = gltfRuntime.scenes[thing];
  3196. for (var i = 0; i < currentScene.nodes.length; i++) {
  3197. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3198. }
  3199. }
  3200. }
  3201. };
  3202. GLTFLoader.Extensions = {};
  3203. return GLTFLoader;
  3204. }());
  3205. GLTF1.GLTFLoader = GLTFLoader;
  3206. ;
  3207. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  3208. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3209. })(BABYLON || (BABYLON = {}));
  3210. //# sourceMappingURL=babylon.glTFLoader.js.map
  3211. var BABYLON;
  3212. (function (BABYLON) {
  3213. var GLTF1;
  3214. (function (GLTF1) {
  3215. /**
  3216. * Utils functions for GLTF
  3217. */
  3218. var GLTFUtils = /** @class */ (function () {
  3219. function GLTFUtils() {
  3220. }
  3221. /**
  3222. * Sets the given "parameter" matrix
  3223. * @param scene: the {BABYLON.Scene} object
  3224. * @param source: the source node where to pick the matrix
  3225. * @param parameter: the GLTF technique parameter
  3226. * @param uniformName: the name of the shader's uniform
  3227. * @param shaderMaterial: the shader material
  3228. */
  3229. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  3230. var mat = null;
  3231. if (parameter.semantic === "MODEL") {
  3232. mat = source.getWorldMatrix();
  3233. }
  3234. else if (parameter.semantic === "PROJECTION") {
  3235. mat = scene.getProjectionMatrix();
  3236. }
  3237. else if (parameter.semantic === "VIEW") {
  3238. mat = scene.getViewMatrix();
  3239. }
  3240. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  3241. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  3242. }
  3243. else if (parameter.semantic === "MODELVIEW") {
  3244. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  3245. }
  3246. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  3247. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  3248. }
  3249. else if (parameter.semantic === "MODELINVERSE") {
  3250. mat = source.getWorldMatrix().invert();
  3251. }
  3252. else if (parameter.semantic === "VIEWINVERSE") {
  3253. mat = scene.getViewMatrix().invert();
  3254. }
  3255. else if (parameter.semantic === "PROJECTIONINVERSE") {
  3256. mat = scene.getProjectionMatrix().invert();
  3257. }
  3258. else if (parameter.semantic === "MODELVIEWINVERSE") {
  3259. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  3260. }
  3261. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  3262. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  3263. }
  3264. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  3265. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  3266. }
  3267. else {
  3268. debugger;
  3269. }
  3270. if (mat) {
  3271. switch (parameter.type) {
  3272. case GLTF1.EParameterType.FLOAT_MAT2:
  3273. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  3274. break;
  3275. case GLTF1.EParameterType.FLOAT_MAT3:
  3276. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  3277. break;
  3278. case GLTF1.EParameterType.FLOAT_MAT4:
  3279. shaderMaterial.setMatrix(uniformName, mat);
  3280. break;
  3281. default: break;
  3282. }
  3283. }
  3284. };
  3285. /**
  3286. * Sets the given "parameter" matrix
  3287. * @param shaderMaterial: the shader material
  3288. * @param uniform: the name of the shader's uniform
  3289. * @param value: the value of the uniform
  3290. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  3291. */
  3292. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  3293. switch (type) {
  3294. case GLTF1.EParameterType.FLOAT:
  3295. shaderMaterial.setFloat(uniform, value);
  3296. return true;
  3297. case GLTF1.EParameterType.FLOAT_VEC2:
  3298. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  3299. return true;
  3300. case GLTF1.EParameterType.FLOAT_VEC3:
  3301. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  3302. return true;
  3303. case GLTF1.EParameterType.FLOAT_VEC4:
  3304. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  3305. return true;
  3306. default: return false;
  3307. }
  3308. };
  3309. /**
  3310. * Returns the wrap mode of the texture
  3311. * @param mode: the mode value
  3312. */
  3313. GLTFUtils.GetWrapMode = function (mode) {
  3314. switch (mode) {
  3315. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3316. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3317. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3318. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3319. }
  3320. };
  3321. /**
  3322. * Returns the byte stride giving an accessor
  3323. * @param accessor: the GLTF accessor objet
  3324. */
  3325. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3326. // Needs this function since "byteStride" isn't requiered in glTF format
  3327. var type = accessor.type;
  3328. switch (type) {
  3329. case "VEC2": return 2;
  3330. case "VEC3": return 3;
  3331. case "VEC4": return 4;
  3332. case "MAT2": return 4;
  3333. case "MAT3": return 9;
  3334. case "MAT4": return 16;
  3335. default: return 1;
  3336. }
  3337. };
  3338. /**
  3339. * Returns the texture filter mode giving a mode value
  3340. * @param mode: the filter mode value
  3341. */
  3342. GLTFUtils.GetTextureFilterMode = function (mode) {
  3343. switch (mode) {
  3344. case GLTF1.ETextureFilterType.LINEAR:
  3345. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  3346. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3347. case GLTF1.ETextureFilterType.NEAREST:
  3348. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3349. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3350. }
  3351. };
  3352. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  3353. var byteOffset = bufferView.byteOffset + byteOffset;
  3354. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  3355. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3356. throw new Error("Buffer access is out of range");
  3357. }
  3358. var buffer = loadedBufferView.buffer;
  3359. byteOffset += loadedBufferView.byteOffset;
  3360. switch (componentType) {
  3361. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3362. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3363. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3364. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3365. default: return new Float32Array(buffer, byteOffset, byteLength);
  3366. }
  3367. };
  3368. /**
  3369. * Returns a buffer from its accessor
  3370. * @param gltfRuntime: the GLTF runtime
  3371. * @param accessor: the GLTF accessor
  3372. */
  3373. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  3374. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  3375. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3376. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  3377. };
  3378. /**
  3379. * Decodes a buffer view into a string
  3380. * @param view: the buffer view
  3381. */
  3382. GLTFUtils.DecodeBufferToText = function (view) {
  3383. var result = "";
  3384. var length = view.byteLength;
  3385. for (var i = 0; i < length; ++i) {
  3386. result += String.fromCharCode(view[i]);
  3387. }
  3388. return result;
  3389. };
  3390. /**
  3391. * Returns the default material of gltf. Related to
  3392. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  3393. * @param scene: the Babylon.js scene
  3394. */
  3395. GLTFUtils.GetDefaultMaterial = function (scene) {
  3396. if (!GLTFUtils._DefaultMaterial) {
  3397. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  3398. "precision highp float;",
  3399. "",
  3400. "uniform mat4 worldView;",
  3401. "uniform mat4 projection;",
  3402. "",
  3403. "attribute vec3 position;",
  3404. "",
  3405. "void main(void)",
  3406. "{",
  3407. " gl_Position = projection * worldView * vec4(position, 1.0);",
  3408. "}"
  3409. ].join("\n");
  3410. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  3411. "precision highp float;",
  3412. "",
  3413. "uniform vec4 u_emission;",
  3414. "",
  3415. "void main(void)",
  3416. "{",
  3417. " gl_FragColor = u_emission;",
  3418. "}"
  3419. ].join("\n");
  3420. var shaderPath = {
  3421. vertex: "GLTFDefaultMaterial",
  3422. fragment: "GLTFDefaultMaterial"
  3423. };
  3424. var options = {
  3425. attributes: ["position"],
  3426. uniforms: ["worldView", "projection", "u_emission"],
  3427. samplers: new Array(),
  3428. needAlphaBlending: false
  3429. };
  3430. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  3431. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  3432. }
  3433. return GLTFUtils._DefaultMaterial;
  3434. };
  3435. // The GLTF default material
  3436. GLTFUtils._DefaultMaterial = null;
  3437. return GLTFUtils;
  3438. }());
  3439. GLTF1.GLTFUtils = GLTFUtils;
  3440. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3441. })(BABYLON || (BABYLON = {}));
  3442. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3443. var BABYLON;
  3444. (function (BABYLON) {
  3445. var GLTF1;
  3446. (function (GLTF1) {
  3447. var GLTFLoaderExtension = /** @class */ (function () {
  3448. function GLTFLoaderExtension(name) {
  3449. this._name = name;
  3450. }
  3451. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3452. get: function () {
  3453. return this._name;
  3454. },
  3455. enumerable: true,
  3456. configurable: true
  3457. });
  3458. /**
  3459. * Defines an override for loading the runtime
  3460. * Return true to stop further extensions from loading the runtime
  3461. */
  3462. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3463. return false;
  3464. };
  3465. /**
  3466. * Defines an onverride for creating gltf runtime
  3467. * Return true to stop further extensions from creating the runtime
  3468. */
  3469. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3470. return false;
  3471. };
  3472. /**
  3473. * Defines an override for loading buffers
  3474. * Return true to stop further extensions from loading this buffer
  3475. */
  3476. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3477. return false;
  3478. };
  3479. /**
  3480. * Defines an override for loading texture buffers
  3481. * Return true to stop further extensions from loading this texture data
  3482. */
  3483. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3484. return false;
  3485. };
  3486. /**
  3487. * Defines an override for creating textures
  3488. * Return true to stop further extensions from loading this texture
  3489. */
  3490. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3491. return false;
  3492. };
  3493. /**
  3494. * Defines an override for loading shader strings
  3495. * Return true to stop further extensions from loading this shader data
  3496. */
  3497. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3498. return false;
  3499. };
  3500. /**
  3501. * Defines an override for loading materials
  3502. * Return true to stop further extensions from loading this material
  3503. */
  3504. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3505. return false;
  3506. };
  3507. // ---------
  3508. // Utilities
  3509. // ---------
  3510. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3511. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3512. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3513. }, function () {
  3514. setTimeout(function () {
  3515. if (!onSuccess) {
  3516. return;
  3517. }
  3518. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3519. });
  3520. });
  3521. };
  3522. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3523. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3524. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3525. }, function () {
  3526. setTimeout(function () {
  3527. onSuccess();
  3528. });
  3529. });
  3530. };
  3531. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3532. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3533. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3534. }, function () {
  3535. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3536. });
  3537. };
  3538. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3539. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3540. if (buffer) {
  3541. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3542. }
  3543. }, onError);
  3544. };
  3545. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3546. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3547. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3548. }, function () {
  3549. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3550. });
  3551. };
  3552. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3553. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3554. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3555. }, function () {
  3556. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3557. });
  3558. };
  3559. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3560. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3561. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3562. }, function () {
  3563. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3564. });
  3565. };
  3566. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3567. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3568. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3569. }, function () {
  3570. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3571. });
  3572. };
  3573. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3574. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  3575. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  3576. if (func(loaderExtension)) {
  3577. return;
  3578. }
  3579. }
  3580. defaultFunc();
  3581. };
  3582. return GLTFLoaderExtension;
  3583. }());
  3584. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  3585. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3586. })(BABYLON || (BABYLON = {}));
  3587. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3588. var BABYLON;
  3589. (function (BABYLON) {
  3590. var GLTF1;
  3591. (function (GLTF1) {
  3592. var BinaryExtensionBufferName = "binary_glTF";
  3593. ;
  3594. ;
  3595. var GLTFBinaryExtension = /** @class */ (function (_super) {
  3596. __extends(GLTFBinaryExtension, _super);
  3597. function GLTFBinaryExtension() {
  3598. return _super.call(this, "KHR_binary_glTF") || this;
  3599. }
  3600. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3601. var extensionsUsed = data.json.extensionsUsed;
  3602. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  3603. return false;
  3604. }
  3605. this._bin = data.bin;
  3606. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3607. return true;
  3608. };
  3609. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3610. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  3611. return false;
  3612. }
  3613. if (id !== BinaryExtensionBufferName) {
  3614. return false;
  3615. }
  3616. onSuccess(this._bin);
  3617. return true;
  3618. };
  3619. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3620. var texture = gltfRuntime.textures[id];
  3621. var source = gltfRuntime.images[texture.source];
  3622. if (!source.extensions || !(this.name in source.extensions)) {
  3623. return false;
  3624. }
  3625. var sourceExt = source.extensions[this.name];
  3626. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  3627. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3628. onSuccess(buffer);
  3629. return true;
  3630. };
  3631. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3632. var shader = gltfRuntime.shaders[id];
  3633. if (!shader.extensions || !(this.name in shader.extensions)) {
  3634. return false;
  3635. }
  3636. var binaryExtensionShader = shader.extensions[this.name];
  3637. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  3638. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3639. setTimeout(function () {
  3640. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  3641. onSuccess(shaderString);
  3642. });
  3643. return true;
  3644. };
  3645. return GLTFBinaryExtension;
  3646. }(GLTF1.GLTFLoaderExtension));
  3647. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  3648. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  3649. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3650. })(BABYLON || (BABYLON = {}));
  3651. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  3652. var BABYLON;
  3653. (function (BABYLON) {
  3654. var GLTF1;
  3655. (function (GLTF1) {
  3656. ;
  3657. ;
  3658. ;
  3659. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3660. __extends(GLTFMaterialsCommonExtension, _super);
  3661. function GLTFMaterialsCommonExtension() {
  3662. return _super.call(this, "KHR_materials_common") || this;
  3663. }
  3664. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3665. if (!gltfRuntime.extensions)
  3666. return false;
  3667. var extension = gltfRuntime.extensions[this.name];
  3668. if (!extension)
  3669. return false;
  3670. // Create lights
  3671. var lights = extension.lights;
  3672. if (lights) {
  3673. for (var thing in lights) {
  3674. var light = lights[thing];
  3675. switch (light.type) {
  3676. case "ambient":
  3677. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  3678. var ambient = light.ambient;
  3679. if (ambient) {
  3680. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  3681. }
  3682. break;
  3683. case "point":
  3684. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  3685. var point = light.point;
  3686. if (point) {
  3687. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  3688. }
  3689. break;
  3690. case "directional":
  3691. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  3692. var directional = light.directional;
  3693. if (directional) {
  3694. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  3695. }
  3696. break;
  3697. case "spot":
  3698. var spot = light.spot;
  3699. if (spot) {
  3700. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  3701. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  3702. }
  3703. break;
  3704. default:
  3705. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3706. break;
  3707. }
  3708. }
  3709. }
  3710. return false;
  3711. };
  3712. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3713. var material = gltfRuntime.materials[id];
  3714. if (!material || !material.extensions)
  3715. return false;
  3716. var extension = material.extensions[this.name];
  3717. if (!extension)
  3718. return false;
  3719. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3720. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3721. if (extension.technique === "CONSTANT") {
  3722. standardMaterial.disableLighting = true;
  3723. }
  3724. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3725. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3726. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3727. // Ambient
  3728. if (typeof extension.values.ambient === "string") {
  3729. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3730. }
  3731. else {
  3732. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3733. }
  3734. // Diffuse
  3735. if (typeof extension.values.diffuse === "string") {
  3736. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3737. }
  3738. else {
  3739. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3740. }
  3741. // Emission
  3742. if (typeof extension.values.emission === "string") {
  3743. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3744. }
  3745. else {
  3746. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3747. }
  3748. // Specular
  3749. if (typeof extension.values.specular === "string") {
  3750. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3751. }
  3752. else {
  3753. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3754. }
  3755. return true;
  3756. };
  3757. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3758. // Create buffer from texture url
  3759. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3760. // Create texture from buffer
  3761. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3762. }, onError);
  3763. };
  3764. return GLTFMaterialsCommonExtension;
  3765. }(GLTF1.GLTFLoaderExtension));
  3766. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3767. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3768. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3769. })(BABYLON || (BABYLON = {}));
  3770. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  3771. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  3772. /**
  3773. * Defines the module used to import/export glTF 2.0 assets
  3774. */
  3775. var BABYLON;
  3776. (function (BABYLON) {
  3777. var GLTF2;
  3778. (function (GLTF2) {
  3779. var _ArrayItem = /** @class */ (function () {
  3780. function _ArrayItem() {
  3781. }
  3782. _ArrayItem.Assign = function (values) {
  3783. if (values) {
  3784. for (var index = 0; index < values.length; index++) {
  3785. values[index]._index = index;
  3786. }
  3787. }
  3788. };
  3789. return _ArrayItem;
  3790. }());
  3791. /** @hidden */
  3792. var GLTFLoader = /** @class */ (function () {
  3793. function GLTFLoader(parent) {
  3794. this._completePromises = new Array();
  3795. this._onReadyObservable = new BABYLON.Observable();
  3796. this._disposed = false;
  3797. this._state = null;
  3798. this._extensions = {};
  3799. this._defaultSampler = {};
  3800. this._defaultBabylonMaterials = {};
  3801. this._requests = new Array();
  3802. this._parent = parent;
  3803. }
  3804. GLTFLoader._Register = function (name, factory) {
  3805. if (GLTFLoader._ExtensionFactories[name]) {
  3806. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  3807. return;
  3808. }
  3809. GLTFLoader._ExtensionFactories[name] = factory;
  3810. // Keep the order of registration so that extensions registered first are called first.
  3811. GLTFLoader._ExtensionNames.push(name);
  3812. };
  3813. Object.defineProperty(GLTFLoader.prototype, "state", {
  3814. /**
  3815. * Loader state or null if the loader is not active.
  3816. */
  3817. get: function () {
  3818. return this._state;
  3819. },
  3820. enumerable: true,
  3821. configurable: true
  3822. });
  3823. GLTFLoader.prototype.dispose = function () {
  3824. if (this._disposed) {
  3825. return;
  3826. }
  3827. this._disposed = true;
  3828. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3829. var request = _a[_i];
  3830. request.abort();
  3831. }
  3832. this._requests.length = 0;
  3833. delete this._gltf;
  3834. delete this._babylonScene;
  3835. this._completePromises.length = 0;
  3836. this._onReadyObservable.clear();
  3837. for (var name_1 in this._extensions) {
  3838. this._extensions[name_1].dispose();
  3839. }
  3840. this._extensions = {};
  3841. delete this._rootBabylonMesh;
  3842. delete this._progressCallback;
  3843. this._parent._clear();
  3844. };
  3845. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  3846. var _this = this;
  3847. return Promise.resolve().then(function () {
  3848. _this._babylonScene = scene;
  3849. _this._rootUrl = rootUrl;
  3850. _this._progressCallback = onProgress;
  3851. _this._loadData(data);
  3852. var nodes = null;
  3853. if (meshesNames) {
  3854. var nodeMap_1 = {};
  3855. if (_this._gltf.nodes) {
  3856. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  3857. var node = _a[_i];
  3858. if (node.name) {
  3859. nodeMap_1[node.name] = node;
  3860. }
  3861. }
  3862. }
  3863. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  3864. nodes = names.map(function (name) {
  3865. var node = nodeMap_1[name];
  3866. if (!node) {
  3867. throw new Error("Failed to find node '" + name + "'");
  3868. }
  3869. return node;
  3870. });
  3871. }
  3872. return _this._loadAsync(nodes).then(function () {
  3873. return {
  3874. meshes: _this._getMeshes(),
  3875. particleSystems: [],
  3876. skeletons: _this._getSkeletons(),
  3877. animationGroups: _this._getAnimationGroups()
  3878. };
  3879. });
  3880. });
  3881. };
  3882. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  3883. var _this = this;
  3884. return Promise.resolve().then(function () {
  3885. _this._babylonScene = scene;
  3886. _this._rootUrl = rootUrl;
  3887. _this._progressCallback = onProgress;
  3888. _this._loadData(data);
  3889. return _this._loadAsync(null);
  3890. });
  3891. };
  3892. GLTFLoader.prototype._loadAsync = function (nodes) {
  3893. var _this = this;
  3894. return Promise.resolve().then(function () {
  3895. _this._state = BABYLON.GLTFLoaderState.LOADING;
  3896. _this._parent._log("Loading");
  3897. _this._loadExtensions();
  3898. _this._checkExtensions();
  3899. var promises = new Array();
  3900. if (nodes) {
  3901. promises.push(_this._loadNodesAsync(nodes));
  3902. }
  3903. else {
  3904. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  3905. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  3906. }
  3907. if (_this._parent.compileMaterials) {
  3908. promises.push(_this._compileMaterialsAsync());
  3909. }
  3910. if (_this._parent.compileShadowGenerators) {
  3911. promises.push(_this._compileShadowGeneratorsAsync());
  3912. }
  3913. var resultPromise = Promise.all(promises).then(function () {
  3914. _this._state = BABYLON.GLTFLoaderState.READY;
  3915. _this._parent._log("Ready");
  3916. _this._onReadyObservable.notifyObservers(_this);
  3917. _this._startAnimations();
  3918. });
  3919. resultPromise.then(function () {
  3920. if (_this._rootBabylonMesh) {
  3921. _this._rootBabylonMesh.setEnabled(true);
  3922. }
  3923. BABYLON.Tools.SetImmediate(function () {
  3924. if (!_this._disposed) {
  3925. Promise.all(_this._completePromises).then(function () {
  3926. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  3927. _this._parent._log("Complete");
  3928. _this._parent.onCompleteObservable.notifyObservers(undefined);
  3929. _this._parent.onCompleteObservable.clear();
  3930. _this.dispose();
  3931. }).catch(function (error) {
  3932. BABYLON.Tools.Error("glTF Loader: " + error.message);
  3933. _this.dispose();
  3934. });
  3935. }
  3936. });
  3937. });
  3938. return resultPromise;
  3939. }).catch(function (error) {
  3940. if (!_this._disposed) {
  3941. BABYLON.Tools.Error("glTF Loader: " + error.message);
  3942. _this.dispose();
  3943. throw error;
  3944. }
  3945. });
  3946. };
  3947. GLTFLoader.prototype._loadData = function (data) {
  3948. this._gltf = data.json;
  3949. this._setupData();
  3950. if (data.bin) {
  3951. var buffers = this._gltf.buffers;
  3952. if (buffers && buffers[0] && !buffers[0].uri) {
  3953. var binaryBuffer = buffers[0];
  3954. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  3955. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3956. }
  3957. binaryBuffer._data = Promise.resolve(data.bin);
  3958. }
  3959. else {
  3960. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3961. }
  3962. }
  3963. };
  3964. GLTFLoader.prototype._setupData = function () {
  3965. _ArrayItem.Assign(this._gltf.accessors);
  3966. _ArrayItem.Assign(this._gltf.animations);
  3967. _ArrayItem.Assign(this._gltf.buffers);
  3968. _ArrayItem.Assign(this._gltf.bufferViews);
  3969. _ArrayItem.Assign(this._gltf.cameras);
  3970. _ArrayItem.Assign(this._gltf.images);
  3971. _ArrayItem.Assign(this._gltf.materials);
  3972. _ArrayItem.Assign(this._gltf.meshes);
  3973. _ArrayItem.Assign(this._gltf.nodes);
  3974. _ArrayItem.Assign(this._gltf.samplers);
  3975. _ArrayItem.Assign(this._gltf.scenes);
  3976. _ArrayItem.Assign(this._gltf.skins);
  3977. _ArrayItem.Assign(this._gltf.textures);
  3978. if (this._gltf.nodes) {
  3979. var nodeParents = {};
  3980. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  3981. var node = _a[_i];
  3982. if (node.children) {
  3983. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  3984. var index = _c[_b];
  3985. nodeParents[index] = node._index;
  3986. }
  3987. }
  3988. }
  3989. var rootNode = this._createRootNode();
  3990. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  3991. var node = _e[_d];
  3992. var parentIndex = nodeParents[node._index];
  3993. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  3994. }
  3995. }
  3996. };
  3997. GLTFLoader.prototype._loadExtensions = function () {
  3998. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  3999. var name_2 = _a[_i];
  4000. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  4001. this._extensions[name_2] = extension;
  4002. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  4003. }
  4004. this._parent.onExtensionLoadedObservable.clear();
  4005. };
  4006. GLTFLoader.prototype._checkExtensions = function () {
  4007. if (this._gltf.extensionsRequired) {
  4008. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  4009. var name_3 = _a[_i];
  4010. var extension = this._extensions[name_3];
  4011. if (!extension || !extension.enabled) {
  4012. throw new Error("Require extension " + name_3 + " is not available");
  4013. }
  4014. }
  4015. }
  4016. };
  4017. GLTFLoader.prototype._createRootNode = function () {
  4018. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  4019. this._rootBabylonMesh.setEnabled(false);
  4020. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  4021. switch (this._parent.coordinateSystemMode) {
  4022. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  4023. if (!this._babylonScene.useRightHandedSystem) {
  4024. rootNode.rotation = [0, 1, 0, 0];
  4025. rootNode.scale = [1, 1, -1];
  4026. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  4027. }
  4028. break;
  4029. }
  4030. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  4031. this._babylonScene.useRightHandedSystem = true;
  4032. break;
  4033. }
  4034. default: {
  4035. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  4036. }
  4037. }
  4038. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  4039. return rootNode;
  4040. };
  4041. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  4042. var promises = new Array();
  4043. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  4044. var node = nodes_1[_i];
  4045. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  4046. }
  4047. promises.push(this._loadAnimationsAsync());
  4048. return Promise.all(promises).then(function () { });
  4049. };
  4050. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  4051. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  4052. if (promise) {
  4053. return promise;
  4054. }
  4055. var promises = new Array();
  4056. this._parent._logOpen(context + " " + (scene.name || ""));
  4057. if (scene.nodes) {
  4058. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  4059. var index = _a[_i];
  4060. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  4061. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  4062. }
  4063. }
  4064. promises.push(this._loadAnimationsAsync());
  4065. this._parent._logClose();
  4066. return Promise.all(promises).then(function () { });
  4067. };
  4068. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  4069. if (node._primitiveBabylonMeshes) {
  4070. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4071. var babylonMesh = _a[_i];
  4072. callback(babylonMesh);
  4073. }
  4074. }
  4075. else {
  4076. callback(node._babylonMesh);
  4077. }
  4078. };
  4079. GLTFLoader.prototype._getMeshes = function () {
  4080. var meshes = new Array();
  4081. // Root mesh is always first.
  4082. meshes.push(this._rootBabylonMesh);
  4083. var nodes = this._gltf.nodes;
  4084. if (nodes) {
  4085. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  4086. var node = nodes_2[_i];
  4087. if (node._babylonMesh) {
  4088. meshes.push(node._babylonMesh);
  4089. }
  4090. if (node._primitiveBabylonMeshes) {
  4091. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  4092. var babylonMesh = _b[_a];
  4093. meshes.push(babylonMesh);
  4094. }
  4095. }
  4096. }
  4097. }
  4098. return meshes;
  4099. };
  4100. GLTFLoader.prototype._getSkeletons = function () {
  4101. var skeletons = new Array();
  4102. var skins = this._gltf.skins;
  4103. if (skins) {
  4104. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  4105. var skin = skins_1[_i];
  4106. if (skin._babylonSkeleton) {
  4107. skeletons.push(skin._babylonSkeleton);
  4108. }
  4109. }
  4110. }
  4111. return skeletons;
  4112. };
  4113. GLTFLoader.prototype._getAnimationGroups = function () {
  4114. var animationGroups = new Array();
  4115. var animations = this._gltf.animations;
  4116. if (animations) {
  4117. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  4118. var animation = animations_1[_i];
  4119. if (animation._babylonAnimationGroup) {
  4120. animationGroups.push(animation._babylonAnimationGroup);
  4121. }
  4122. }
  4123. }
  4124. return animationGroups;
  4125. };
  4126. GLTFLoader.prototype._startAnimations = function () {
  4127. switch (this._parent.animationStartMode) {
  4128. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  4129. // do nothing
  4130. break;
  4131. }
  4132. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  4133. var babylonAnimationGroups = this._getAnimationGroups();
  4134. if (babylonAnimationGroups.length !== 0) {
  4135. babylonAnimationGroups[0].start(true);
  4136. }
  4137. break;
  4138. }
  4139. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  4140. var babylonAnimationGroups = this._getAnimationGroups();
  4141. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  4142. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  4143. babylonAnimationGroup.start(true);
  4144. }
  4145. break;
  4146. }
  4147. default: {
  4148. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  4149. return;
  4150. }
  4151. }
  4152. };
  4153. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  4154. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  4155. if (promise) {
  4156. return promise;
  4157. }
  4158. if (node._babylonMesh) {
  4159. throw new Error(context + ": Invalid recursive node hierarchy");
  4160. }
  4161. var promises = new Array();
  4162. this._parent._logOpen(context + " " + (node.name || ""));
  4163. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  4164. node._babylonMesh = babylonMesh;
  4165. GLTFLoader._LoadTransform(node, babylonMesh);
  4166. if (node.mesh != undefined) {
  4167. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  4168. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  4169. }
  4170. if (node.camera != undefined) {
  4171. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  4172. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  4173. }
  4174. if (node.children) {
  4175. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  4176. var index = _a[_i];
  4177. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  4178. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  4179. }
  4180. }
  4181. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  4182. this._parent._logClose();
  4183. return Promise.all(promises).then(function () { });
  4184. };
  4185. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  4186. var _this = this;
  4187. var promises = new Array();
  4188. this._parent._logOpen(context + " " + (mesh.name || ""));
  4189. var primitives = mesh.primitives;
  4190. if (!primitives || primitives.length === 0) {
  4191. throw new Error(context + ": Primitives are missing");
  4192. }
  4193. _ArrayItem.Assign(primitives);
  4194. if (primitives.length === 1) {
  4195. var primitive = primitives[0];
  4196. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  4197. }
  4198. else {
  4199. node._primitiveBabylonMeshes = [];
  4200. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  4201. var primitive = primitives_1[_i];
  4202. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  4203. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  4204. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  4205. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  4206. }
  4207. }
  4208. if (node.skin != undefined) {
  4209. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  4210. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  4211. }
  4212. this._parent._logClose();
  4213. return Promise.all(promises).then(function () {
  4214. _this._forEachPrimitive(node, function (babylonMesh) {
  4215. babylonMesh._refreshBoundingInfo(true);
  4216. });
  4217. });
  4218. };
  4219. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  4220. var _this = this;
  4221. var promises = new Array();
  4222. this._parent._logOpen("" + context);
  4223. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  4224. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  4225. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  4226. babylonGeometry.applyToMesh(babylonMesh);
  4227. });
  4228. }));
  4229. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  4230. if (primitive.material == undefined) {
  4231. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  4232. }
  4233. else {
  4234. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  4235. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  4236. babylonMesh.material = babylonMaterial;
  4237. }));
  4238. }
  4239. this._parent._logClose();
  4240. return Promise.all(promises).then(function () { });
  4241. };
  4242. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4243. var _this = this;
  4244. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  4245. if (promise) {
  4246. return promise;
  4247. }
  4248. var attributes = primitive.attributes;
  4249. if (!attributes) {
  4250. throw new Error(context + ": Attributes are missing");
  4251. }
  4252. var promises = new Array();
  4253. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  4254. if (primitive.indices == undefined) {
  4255. babylonMesh.isUnIndexed = true;
  4256. }
  4257. else {
  4258. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  4259. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4260. babylonGeometry.setIndices(data);
  4261. }));
  4262. }
  4263. var loadAttribute = function (attribute, kind, callback) {
  4264. if (attributes[attribute] == undefined) {
  4265. return;
  4266. }
  4267. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4268. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4269. babylonMesh._delayInfo.push(kind);
  4270. }
  4271. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  4272. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  4273. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  4274. }));
  4275. if (callback) {
  4276. callback(accessor);
  4277. }
  4278. };
  4279. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4280. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4281. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4282. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4283. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4284. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4285. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4286. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  4287. if (accessor.type === "VEC4" /* VEC4 */) {
  4288. babylonMesh.hasVertexAlpha = true;
  4289. }
  4290. });
  4291. return Promise.all(promises).then(function () {
  4292. return babylonGeometry;
  4293. });
  4294. };
  4295. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  4296. if (!primitive.targets) {
  4297. return;
  4298. }
  4299. if (node._numMorphTargets == undefined) {
  4300. node._numMorphTargets = primitive.targets.length;
  4301. }
  4302. else if (primitive.targets.length !== node._numMorphTargets) {
  4303. throw new Error(context + ": Primitives do not have the same number of targets");
  4304. }
  4305. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  4306. for (var index = 0; index < primitive.targets.length; index++) {
  4307. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  4308. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  4309. // TODO: tell the target whether it has positions, normals, tangents
  4310. }
  4311. };
  4312. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  4313. if (!primitive.targets) {
  4314. return Promise.resolve();
  4315. }
  4316. var promises = new Array();
  4317. var morphTargetManager = babylonMesh.morphTargetManager;
  4318. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  4319. var babylonMorphTarget = morphTargetManager.getTarget(index);
  4320. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  4321. }
  4322. return Promise.all(promises).then(function () { });
  4323. };
  4324. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  4325. var _this = this;
  4326. var promises = new Array();
  4327. var loadAttribute = function (attribute, kind, setData) {
  4328. if (attributes[attribute] == undefined) {
  4329. return;
  4330. }
  4331. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  4332. if (!babylonVertexBuffer) {
  4333. return;
  4334. }
  4335. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  4336. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4337. setData(babylonVertexBuffer, data);
  4338. }));
  4339. };
  4340. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  4341. babylonVertexBuffer.forEach(data.length, function (value, index) {
  4342. data[index] += value;
  4343. });
  4344. babylonMorphTarget.setPositions(data);
  4345. });
  4346. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  4347. babylonVertexBuffer.forEach(data.length, function (value, index) {
  4348. data[index] += value;
  4349. });
  4350. babylonMorphTarget.setNormals(data);
  4351. });
  4352. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  4353. var dataIndex = 0;
  4354. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  4355. // Tangent data for morph targets is stored as xyz delta.
  4356. // The vertexData.tangent is stored as xyzw.
  4357. // So we need to skip every fourth vertexData.tangent.
  4358. if (((index + 1) % 4) !== 0) {
  4359. data[dataIndex++] += value;
  4360. }
  4361. });
  4362. babylonMorphTarget.setTangents(data);
  4363. });
  4364. return Promise.all(promises).then(function () { });
  4365. };
  4366. GLTFLoader._LoadTransform = function (node, babylonNode) {
  4367. var position = BABYLON.Vector3.Zero();
  4368. var rotation = BABYLON.Quaternion.Identity();
  4369. var scaling = BABYLON.Vector3.One();
  4370. if (node.matrix) {
  4371. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  4372. matrix.decompose(scaling, rotation, position);
  4373. }
  4374. else {
  4375. if (node.translation)
  4376. position = BABYLON.Vector3.FromArray(node.translation);
  4377. if (node.rotation)
  4378. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  4379. if (node.scale)
  4380. scaling = BABYLON.Vector3.FromArray(node.scale);
  4381. }
  4382. babylonNode.position = position;
  4383. babylonNode.rotationQuaternion = rotation;
  4384. babylonNode.scaling = scaling;
  4385. };
  4386. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  4387. var _this = this;
  4388. var assignSkeleton = function (skeleton) {
  4389. _this._forEachPrimitive(node, function (babylonMesh) {
  4390. babylonMesh.skeleton = skeleton;
  4391. });
  4392. // Ignore the TRS of skinned nodes.
  4393. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4394. node._babylonMesh.parent = _this._rootBabylonMesh;
  4395. node._babylonMesh.position = BABYLON.Vector3.Zero();
  4396. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  4397. node._babylonMesh.scaling = BABYLON.Vector3.One();
  4398. };
  4399. if (skin._loaded) {
  4400. return skin._loaded.then(function () {
  4401. assignSkeleton(skin._babylonSkeleton);
  4402. });
  4403. }
  4404. var skeletonId = "skeleton" + skin._index;
  4405. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  4406. skin._babylonSkeleton = babylonSkeleton;
  4407. this._loadBones(context, skin);
  4408. assignSkeleton(babylonSkeleton);
  4409. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  4410. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  4411. }));
  4412. };
  4413. GLTFLoader.prototype._loadBones = function (context, skin) {
  4414. var babylonBones = {};
  4415. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  4416. var index = _a[_i];
  4417. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  4418. this._loadBone(node, skin, babylonBones);
  4419. }
  4420. };
  4421. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  4422. var babylonBone = babylonBones[node._index];
  4423. if (babylonBone) {
  4424. return babylonBone;
  4425. }
  4426. var babylonParentBone = null;
  4427. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  4428. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  4429. }
  4430. var boneIndex = skin.joints.indexOf(node._index);
  4431. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  4432. babylonBones[node._index] = babylonBone;
  4433. node._babylonBones = node._babylonBones || [];
  4434. node._babylonBones.push(babylonBone);
  4435. return babylonBone;
  4436. };
  4437. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  4438. if (skin.inverseBindMatrices == undefined) {
  4439. return Promise.resolve(null);
  4440. }
  4441. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  4442. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  4443. };
  4444. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  4445. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  4446. var babylonBone = _a[_i];
  4447. var baseMatrix = BABYLON.Matrix.Identity();
  4448. var boneIndex = babylonBone._index;
  4449. if (inverseBindMatricesData && boneIndex !== -1) {
  4450. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  4451. baseMatrix.invertToRef(baseMatrix);
  4452. }
  4453. var babylonParentBone = babylonBone.getParent();
  4454. if (babylonParentBone) {
  4455. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  4456. }
  4457. babylonBone.updateMatrix(baseMatrix, false, false);
  4458. babylonBone._updateDifferenceMatrix(undefined, false);
  4459. }
  4460. };
  4461. GLTFLoader.prototype._getNodeMatrix = function (node) {
  4462. return node.matrix ?
  4463. BABYLON.Matrix.FromArray(node.matrix) :
  4464. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  4465. };
  4466. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  4467. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  4468. babylonCamera.parent = babylonMesh;
  4469. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  4470. switch (camera.type) {
  4471. case "perspective" /* PERSPECTIVE */: {
  4472. var perspective = camera.perspective;
  4473. if (!perspective) {
  4474. throw new Error(context + ": Camera perspective properties are missing");
  4475. }
  4476. babylonCamera.fov = perspective.yfov;
  4477. babylonCamera.minZ = perspective.znear;
  4478. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  4479. break;
  4480. }
  4481. case "orthographic" /* ORTHOGRAPHIC */: {
  4482. if (!camera.orthographic) {
  4483. throw new Error(context + ": Camera orthographic properties are missing");
  4484. }
  4485. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  4486. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  4487. babylonCamera.orthoRight = camera.orthographic.xmag;
  4488. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  4489. babylonCamera.orthoTop = camera.orthographic.ymag;
  4490. babylonCamera.minZ = camera.orthographic.znear;
  4491. babylonCamera.maxZ = camera.orthographic.zfar;
  4492. break;
  4493. }
  4494. default: {
  4495. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  4496. }
  4497. }
  4498. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  4499. };
  4500. GLTFLoader.prototype._loadAnimationsAsync = function () {
  4501. var animations = this._gltf.animations;
  4502. if (!animations) {
  4503. return Promise.resolve();
  4504. }
  4505. var promises = new Array();
  4506. for (var index = 0; index < animations.length; index++) {
  4507. var animation = animations[index];
  4508. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  4509. }
  4510. return Promise.all(promises).then(function () { });
  4511. };
  4512. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  4513. var _this = this;
  4514. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  4515. animation._babylonAnimationGroup = babylonAnimationGroup;
  4516. var promises = new Array();
  4517. _ArrayItem.Assign(animation.channels);
  4518. _ArrayItem.Assign(animation.samplers);
  4519. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  4520. var channel = _a[_i];
  4521. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  4522. }
  4523. return Promise.all(promises).then(function () {
  4524. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  4525. });
  4526. };
  4527. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  4528. var _this = this;
  4529. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  4530. // Ignore animations that have no animation targets.
  4531. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  4532. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  4533. return Promise.resolve();
  4534. }
  4535. // Ignore animations targeting TRS of skinned nodes.
  4536. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4537. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  4538. return Promise.resolve();
  4539. }
  4540. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  4541. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  4542. var targetPath;
  4543. var animationType;
  4544. switch (channel.target.path) {
  4545. case "translation" /* TRANSLATION */: {
  4546. targetPath = "position";
  4547. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4548. break;
  4549. }
  4550. case "rotation" /* ROTATION */: {
  4551. targetPath = "rotationQuaternion";
  4552. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  4553. break;
  4554. }
  4555. case "scale" /* SCALE */: {
  4556. targetPath = "scaling";
  4557. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4558. break;
  4559. }
  4560. case "weights" /* WEIGHTS */: {
  4561. targetPath = "influence";
  4562. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  4563. break;
  4564. }
  4565. default: {
  4566. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  4567. }
  4568. }
  4569. var outputBufferOffset = 0;
  4570. var getNextOutputValue;
  4571. switch (targetPath) {
  4572. case "position": {
  4573. getNextOutputValue = function () {
  4574. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4575. outputBufferOffset += 3;
  4576. return value;
  4577. };
  4578. break;
  4579. }
  4580. case "rotationQuaternion": {
  4581. getNextOutputValue = function () {
  4582. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  4583. outputBufferOffset += 4;
  4584. return value;
  4585. };
  4586. break;
  4587. }
  4588. case "scaling": {
  4589. getNextOutputValue = function () {
  4590. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4591. outputBufferOffset += 3;
  4592. return value;
  4593. };
  4594. break;
  4595. }
  4596. case "influence": {
  4597. getNextOutputValue = function () {
  4598. var value = new Array(targetNode._numMorphTargets);
  4599. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  4600. value[i] = data.output[outputBufferOffset++];
  4601. }
  4602. return value;
  4603. };
  4604. break;
  4605. }
  4606. }
  4607. var getNextKey;
  4608. switch (data.interpolation) {
  4609. case "STEP" /* STEP */: {
  4610. getNextKey = function (frameIndex) { return ({
  4611. frame: data.input[frameIndex],
  4612. value: getNextOutputValue(),
  4613. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  4614. }); };
  4615. break;
  4616. }
  4617. case "LINEAR" /* LINEAR */: {
  4618. getNextKey = function (frameIndex) { return ({
  4619. frame: data.input[frameIndex],
  4620. value: getNextOutputValue()
  4621. }); };
  4622. break;
  4623. }
  4624. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4625. getNextKey = function (frameIndex) { return ({
  4626. frame: data.input[frameIndex],
  4627. inTangent: getNextOutputValue(),
  4628. value: getNextOutputValue(),
  4629. outTangent: getNextOutputValue()
  4630. }); };
  4631. break;
  4632. }
  4633. }
  4634. var keys = new Array(data.input.length);
  4635. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  4636. keys[frameIndex] = getNextKey(frameIndex);
  4637. }
  4638. if (targetPath === "influence") {
  4639. var _loop_1 = function (targetIndex) {
  4640. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4641. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4642. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4643. frame: key.frame,
  4644. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4645. value: key.value[targetIndex],
  4646. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4647. }); }));
  4648. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  4649. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  4650. var babylonAnimationClone = babylonAnimation.clone();
  4651. morphTarget.animations.push(babylonAnimationClone);
  4652. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  4653. });
  4654. };
  4655. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  4656. _loop_1(targetIndex);
  4657. }
  4658. }
  4659. else {
  4660. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4661. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4662. babylonAnimation.setKeys(keys);
  4663. if (targetNode._babylonBones) {
  4664. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  4665. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  4666. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  4667. babylonAnimationTarget.animations.push(babylonAnimation);
  4668. }
  4669. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  4670. }
  4671. else {
  4672. targetNode._babylonMesh.animations.push(babylonAnimation);
  4673. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  4674. }
  4675. }
  4676. });
  4677. };
  4678. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  4679. if (sampler._data) {
  4680. return sampler._data;
  4681. }
  4682. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  4683. switch (interpolation) {
  4684. case "STEP" /* STEP */:
  4685. case "LINEAR" /* LINEAR */:
  4686. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4687. break;
  4688. }
  4689. default: {
  4690. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  4691. }
  4692. }
  4693. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  4694. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  4695. sampler._data = Promise.all([
  4696. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  4697. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  4698. ]).then(function (_a) {
  4699. var inputData = _a[0], outputData = _a[1];
  4700. return {
  4701. input: inputData,
  4702. interpolation: interpolation,
  4703. output: outputData,
  4704. };
  4705. });
  4706. return sampler._data;
  4707. };
  4708. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  4709. if (buffer._data) {
  4710. return buffer._data;
  4711. }
  4712. if (!buffer.uri) {
  4713. throw new Error(context + ": Uri is missing");
  4714. }
  4715. buffer._data = this._loadUriAsync(context, buffer.uri);
  4716. return buffer._data;
  4717. };
  4718. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  4719. if (bufferView._data) {
  4720. return bufferView._data;
  4721. }
  4722. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  4723. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  4724. try {
  4725. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  4726. }
  4727. catch (e) {
  4728. throw new Error(context + ": " + e.message);
  4729. }
  4730. });
  4731. return bufferView._data;
  4732. };
  4733. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  4734. if (accessor.type !== "SCALAR" /* SCALAR */) {
  4735. throw new Error(context + ": Invalid type " + accessor.type);
  4736. }
  4737. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  4738. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  4739. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  4740. throw new Error(context + ": Invalid component type " + accessor.componentType);
  4741. }
  4742. if (accessor._data) {
  4743. return accessor._data;
  4744. }
  4745. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  4746. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4747. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  4748. });
  4749. return accessor._data;
  4750. };
  4751. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  4752. // TODO: support normalized and stride
  4753. var _this = this;
  4754. if (accessor.componentType !== 5126 /* FLOAT */) {
  4755. throw new Error("Invalid component type " + accessor.componentType);
  4756. }
  4757. if (accessor._data) {
  4758. return accessor._data;
  4759. }
  4760. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  4761. var length = numComponents * accessor.count;
  4762. if (accessor.bufferView == undefined) {
  4763. accessor._data = Promise.resolve(new Float32Array(length));
  4764. }
  4765. else {
  4766. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  4767. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4768. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  4769. });
  4770. }
  4771. if (accessor.sparse) {
  4772. var sparse_1 = accessor.sparse;
  4773. accessor._data = accessor._data.then(function (data) {
  4774. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  4775. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  4776. return Promise.all([
  4777. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  4778. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  4779. ]).then(function (_a) {
  4780. var indicesData = _a[0], valuesData = _a[1];
  4781. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  4782. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  4783. var valuesIndex = 0;
  4784. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  4785. var dataIndex = indices[indicesIndex] * numComponents;
  4786. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  4787. data[dataIndex++] = values[valuesIndex++];
  4788. }
  4789. }
  4790. return data;
  4791. });
  4792. });
  4793. }
  4794. return accessor._data;
  4795. };
  4796. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  4797. var _this = this;
  4798. if (bufferView._babylonBuffer) {
  4799. return bufferView._babylonBuffer;
  4800. }
  4801. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  4802. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  4803. });
  4804. return bufferView._babylonBuffer;
  4805. };
  4806. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  4807. var _this = this;
  4808. if (accessor._babylonVertexBuffer) {
  4809. return accessor._babylonVertexBuffer;
  4810. }
  4811. if (accessor.sparse) {
  4812. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  4813. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  4814. });
  4815. }
  4816. else {
  4817. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  4818. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  4819. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  4820. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  4821. });
  4822. }
  4823. return accessor._babylonVertexBuffer;
  4824. };
  4825. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  4826. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  4827. if (!babylonMaterial) {
  4828. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  4829. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4830. babylonMaterial.metallic = 1;
  4831. babylonMaterial.roughness = 1;
  4832. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4833. }
  4834. return babylonMaterial;
  4835. };
  4836. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  4837. var promises = new Array();
  4838. // Ensure metallic workflow
  4839. babylonMaterial.metallic = 1;
  4840. babylonMaterial.roughness = 1;
  4841. var properties = material.pbrMetallicRoughness;
  4842. if (properties) {
  4843. if (properties.baseColorFactor) {
  4844. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4845. babylonMaterial.alpha = properties.baseColorFactor[3];
  4846. }
  4847. else {
  4848. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4849. }
  4850. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  4851. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  4852. if (properties.baseColorTexture) {
  4853. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4854. babylonMaterial.albedoTexture = texture;
  4855. }));
  4856. }
  4857. if (properties.metallicRoughnessTexture) {
  4858. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  4859. babylonMaterial.metallicTexture = texture;
  4860. }));
  4861. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4862. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4863. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4864. }
  4865. }
  4866. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4867. return Promise.all(promises).then(function () { });
  4868. };
  4869. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  4870. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  4871. if (promise) {
  4872. return promise;
  4873. }
  4874. material._babylonData = material._babylonData || {};
  4875. var babylonData = material._babylonData[babylonDrawMode];
  4876. if (!babylonData) {
  4877. var promises = new Array();
  4878. this._parent._logOpen(context + " " + (material.name || ""));
  4879. var name_4 = material.name || "material_" + material._index;
  4880. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  4881. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4882. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  4883. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4884. babylonData = {
  4885. material: babylonMaterial,
  4886. meshes: [],
  4887. loaded: Promise.all(promises).then(function () { })
  4888. };
  4889. material._babylonData[babylonDrawMode] = babylonData;
  4890. this._parent._logClose();
  4891. }
  4892. babylonData.meshes.push(babylonMesh);
  4893. assign(babylonData.material);
  4894. return babylonData.loaded;
  4895. };
  4896. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  4897. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  4898. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  4899. babylonMaterial.fillMode = drawMode;
  4900. babylonMaterial.enableSpecularAntiAliasing = true;
  4901. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  4902. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  4903. return babylonMaterial;
  4904. };
  4905. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  4906. var promises = new Array();
  4907. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  4908. if (material.doubleSided) {
  4909. babylonMaterial.backFaceCulling = false;
  4910. babylonMaterial.twoSidedLighting = true;
  4911. }
  4912. if (material.normalTexture) {
  4913. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  4914. babylonMaterial.bumpTexture = texture;
  4915. }));
  4916. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  4917. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  4918. if (material.normalTexture.scale != undefined) {
  4919. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4920. }
  4921. }
  4922. if (material.occlusionTexture) {
  4923. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  4924. babylonMaterial.ambientTexture = texture;
  4925. }));
  4926. babylonMaterial.useAmbientInGrayScale = true;
  4927. if (material.occlusionTexture.strength != undefined) {
  4928. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4929. }
  4930. }
  4931. if (material.emissiveTexture) {
  4932. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  4933. babylonMaterial.emissiveTexture = texture;
  4934. }));
  4935. }
  4936. return Promise.all(promises).then(function () { });
  4937. };
  4938. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  4939. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  4940. switch (alphaMode) {
  4941. case "OPAQUE" /* OPAQUE */: {
  4942. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4943. break;
  4944. }
  4945. case "MASK" /* MASK */: {
  4946. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  4947. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  4948. if (babylonMaterial.albedoTexture) {
  4949. babylonMaterial.albedoTexture.hasAlpha = true;
  4950. }
  4951. break;
  4952. }
  4953. case "BLEND" /* BLEND */: {
  4954. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  4955. if (babylonMaterial.albedoTexture) {
  4956. babylonMaterial.albedoTexture.hasAlpha = true;
  4957. babylonMaterial.useAlphaFromAlbedoTexture = true;
  4958. }
  4959. break;
  4960. }
  4961. default: {
  4962. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  4963. }
  4964. }
  4965. };
  4966. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  4967. var _this = this;
  4968. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  4969. if (promise) {
  4970. return promise;
  4971. }
  4972. this._parent._logOpen("" + context);
  4973. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  4974. context = "#/textures/" + textureInfo.index;
  4975. var promises = new Array();
  4976. this._parent._logOpen(context + " " + (texture.name || ""));
  4977. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  4978. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  4979. var deferred = new BABYLON.Deferred();
  4980. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  4981. if (!_this._disposed) {
  4982. deferred.resolve();
  4983. }
  4984. }, function (message, exception) {
  4985. if (!_this._disposed) {
  4986. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  4987. }
  4988. });
  4989. promises.push(deferred.promise);
  4990. babylonTexture.name = texture.name || "texture" + texture._index;
  4991. babylonTexture.wrapU = samplerData.wrapU;
  4992. babylonTexture.wrapV = samplerData.wrapV;
  4993. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  4994. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  4995. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  4996. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  4997. babylonTexture.updateURL(dataUrl, blob);
  4998. }));
  4999. assign(babylonTexture);
  5000. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  5001. this._parent._logClose();
  5002. this._parent._logClose();
  5003. return Promise.all(promises).then(function () { });
  5004. };
  5005. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  5006. if (!sampler._data) {
  5007. sampler._data = {
  5008. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  5009. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  5010. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  5011. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  5012. };
  5013. }
  5014. ;
  5015. return sampler._data;
  5016. };
  5017. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  5018. if (!image._blob) {
  5019. this._parent._logOpen(context + " " + (image.name || ""));
  5020. var promise = void 0;
  5021. if (image.uri) {
  5022. promise = this._loadUriAsync(context, image.uri);
  5023. }
  5024. else {
  5025. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  5026. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  5027. }
  5028. image._blob = promise.then(function (data) {
  5029. return new Blob([data], { type: image.mimeType });
  5030. });
  5031. this._parent._logClose();
  5032. }
  5033. return image._blob;
  5034. };
  5035. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  5036. var _this = this;
  5037. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  5038. if (promise) {
  5039. return promise;
  5040. }
  5041. if (!GLTFLoader._ValidateUri(uri)) {
  5042. throw new Error(context + ": Uri '" + uri + "' is invalid");
  5043. }
  5044. if (BABYLON.Tools.IsBase64(uri)) {
  5045. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  5046. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  5047. return Promise.resolve(data);
  5048. }
  5049. this._parent._log("Loading " + uri);
  5050. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  5051. return new Promise(function (resolve, reject) {
  5052. if (!_this._disposed) {
  5053. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  5054. if (!_this._disposed) {
  5055. var data = new Uint8Array(fileData);
  5056. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  5057. resolve(data);
  5058. }
  5059. }, function (event) {
  5060. if (!_this._disposed) {
  5061. if (request_1) {
  5062. request_1._lengthComputable = event.lengthComputable;
  5063. request_1._loaded = event.loaded;
  5064. request_1._total = event.total;
  5065. }
  5066. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  5067. try {
  5068. _this._onProgress();
  5069. }
  5070. catch (e) {
  5071. reject(e);
  5072. }
  5073. }
  5074. }
  5075. }, _this._babylonScene.database, true, function (request, exception) {
  5076. if (!_this._disposed) {
  5077. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  5078. }
  5079. });
  5080. _this._requests.push(request_1);
  5081. }
  5082. });
  5083. });
  5084. };
  5085. GLTFLoader.prototype._onProgress = function () {
  5086. if (!this._progressCallback) {
  5087. return;
  5088. }
  5089. var lengthComputable = true;
  5090. var loaded = 0;
  5091. var total = 0;
  5092. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  5093. var request = _a[_i];
  5094. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  5095. return;
  5096. }
  5097. lengthComputable = lengthComputable && request._lengthComputable;
  5098. loaded += request._loaded;
  5099. total += request._total;
  5100. }
  5101. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  5102. };
  5103. GLTFLoader._GetProperty = function (context, array, index) {
  5104. if (!array || index == undefined || !array[index]) {
  5105. throw new Error(context + ": Failed to find index (" + index + ")");
  5106. }
  5107. return array[index];
  5108. };
  5109. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  5110. // Set defaults if undefined
  5111. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  5112. switch (mode) {
  5113. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  5114. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  5115. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  5116. default:
  5117. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  5118. return BABYLON.Texture.WRAP_ADDRESSMODE;
  5119. }
  5120. };
  5121. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  5122. // Set defaults if undefined
  5123. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  5124. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  5125. if (magFilter === 9729 /* LINEAR */) {
  5126. switch (minFilter) {
  5127. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  5128. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  5129. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  5130. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  5131. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  5132. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  5133. default:
  5134. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  5135. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  5136. }
  5137. }
  5138. else {
  5139. if (magFilter !== 9728 /* NEAREST */) {
  5140. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  5141. }
  5142. switch (minFilter) {
  5143. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  5144. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  5145. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  5146. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  5147. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  5148. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  5149. default:
  5150. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  5151. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  5152. }
  5153. }
  5154. };
  5155. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  5156. var buffer = bufferView.buffer;
  5157. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  5158. try {
  5159. switch (componentType) {
  5160. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  5161. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  5162. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  5163. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  5164. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  5165. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  5166. default: throw new Error("Invalid component type " + componentType);
  5167. }
  5168. }
  5169. catch (e) {
  5170. throw new Error(context + ": " + e);
  5171. }
  5172. };
  5173. GLTFLoader._GetNumComponents = function (context, type) {
  5174. switch (type) {
  5175. case "SCALAR": return 1;
  5176. case "VEC2": return 2;
  5177. case "VEC3": return 3;
  5178. case "VEC4": return 4;
  5179. case "MAT2": return 4;
  5180. case "MAT3": return 9;
  5181. case "MAT4": return 16;
  5182. }
  5183. throw new Error(context + ": Invalid type (" + type + ")");
  5184. };
  5185. GLTFLoader._ValidateUri = function (uri) {
  5186. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  5187. };
  5188. GLTFLoader._GetDrawMode = function (context, mode) {
  5189. if (mode == undefined) {
  5190. mode = 4 /* TRIANGLES */;
  5191. }
  5192. switch (mode) {
  5193. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  5194. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  5195. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  5196. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  5197. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  5198. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  5199. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  5200. }
  5201. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  5202. };
  5203. GLTFLoader.prototype._compileMaterialsAsync = function () {
  5204. var promises = new Array();
  5205. if (this._gltf.materials) {
  5206. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  5207. var material = _a[_i];
  5208. if (material._babylonData) {
  5209. for (var babylonDrawMode in material._babylonData) {
  5210. var babylonData = material._babylonData[babylonDrawMode];
  5211. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  5212. var babylonMesh = _c[_b];
  5213. // Ensure nonUniformScaling is set if necessary.
  5214. babylonMesh.computeWorldMatrix(true);
  5215. var babylonMaterial = babylonData.material;
  5216. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  5217. if (this._parent.useClipPlane) {
  5218. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  5219. }
  5220. }
  5221. }
  5222. }
  5223. }
  5224. }
  5225. return Promise.all(promises).then(function () { });
  5226. };
  5227. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  5228. var promises = new Array();
  5229. var lights = this._babylonScene.lights;
  5230. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  5231. var light = lights_1[_i];
  5232. var generator = light.getShadowGenerator();
  5233. if (generator) {
  5234. promises.push(generator.forceCompilationAsync());
  5235. }
  5236. }
  5237. return Promise.all(promises).then(function () { });
  5238. };
  5239. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  5240. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  5241. var name_5 = _a[_i];
  5242. var extension = this._extensions[name_5];
  5243. if (extension.enabled) {
  5244. var promise = actionAsync(extension);
  5245. if (promise) {
  5246. return promise;
  5247. }
  5248. }
  5249. }
  5250. return null;
  5251. };
  5252. GLTFLoader._ExtensionNames = new Array();
  5253. GLTFLoader._ExtensionFactories = {};
  5254. return GLTFLoader;
  5255. }());
  5256. GLTF2.GLTFLoader = GLTFLoader;
  5257. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  5258. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5259. })(BABYLON || (BABYLON = {}));
  5260. //# sourceMappingURL=babylon.glTFLoader.js.map
  5261. var BABYLON;
  5262. (function (BABYLON) {
  5263. var GLTF2;
  5264. (function (GLTF2) {
  5265. /**
  5266. * Abstract class that can be implemented to extend existing glTF loader behavior.
  5267. */
  5268. var GLTFLoaderExtension = /** @class */ (function () {
  5269. /**
  5270. * Creates new GLTFLoaderExtension
  5271. * @param loader defines the GLTFLoader to use
  5272. */
  5273. function GLTFLoaderExtension(loader) {
  5274. /**
  5275. * Gets or sets a boolean indicating if the extension is enabled
  5276. */
  5277. this.enabled = true;
  5278. this._loader = loader;
  5279. }
  5280. /**
  5281. * Release all resources
  5282. */
  5283. GLTFLoaderExtension.prototype.dispose = function () {
  5284. delete this._loader;
  5285. };
  5286. // #region Overridable Methods
  5287. /**
  5288. * Override this method to modify the default behavior for loading scenes.
  5289. * @hidden
  5290. */
  5291. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  5292. /**
  5293. * Override this method to modify the default behavior for loading nodes.
  5294. * @hidden
  5295. */
  5296. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  5297. /**
  5298. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  5299. * @hidden
  5300. */
  5301. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  5302. /**
  5303. * Override this method to modify the default behavior for loading materials.
  5304. * @hidden
  5305. */
  5306. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  5307. /**
  5308. * Override this method to modify the default behavior for loading textures.
  5309. * @hidden
  5310. */
  5311. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  5312. /**
  5313. * Override this method to modify the default behavior for loading uris.
  5314. * @hidden
  5315. */
  5316. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  5317. // #endregion
  5318. /**
  5319. * Helper method called by a loader extension to load an glTF extension.
  5320. * @hidden
  5321. */
  5322. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  5323. if (!property.extensions) {
  5324. return null;
  5325. }
  5326. var extensions = property.extensions;
  5327. var extension = extensions[this.name];
  5328. if (!extension) {
  5329. return null;
  5330. }
  5331. // Clear out the extension before executing the action to avoid infinite recursion.
  5332. delete extensions[this.name];
  5333. try {
  5334. return actionAsync(context + "/extensions/" + this.name, extension);
  5335. }
  5336. finally {
  5337. // Restore the extension after executing the action.
  5338. extensions[this.name] = extension;
  5339. }
  5340. };
  5341. /**
  5342. * Helper method called by the loader to allow extensions to override loading scenes.
  5343. * @hidden
  5344. */
  5345. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  5346. if (!property.extras) {
  5347. return null;
  5348. }
  5349. var extras = property.extras;
  5350. var value = extras[this.name];
  5351. if (value === undefined) {
  5352. return null;
  5353. }
  5354. // Clear out the extras value before executing the action to avoid infinite recursion.
  5355. delete extras[this.name];
  5356. try {
  5357. return actionAsync(context + "/extras/" + this.name, value);
  5358. }
  5359. finally {
  5360. // Restore the extras value after executing the action.
  5361. extras[this.name] = value;
  5362. }
  5363. };
  5364. /**
  5365. * Helper method called by the loader to allow extensions to override loading scenes.
  5366. * @hidden
  5367. */
  5368. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  5369. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  5370. };
  5371. /**
  5372. * Helper method called by the loader to allow extensions to override loading nodes.
  5373. * @hidden
  5374. */
  5375. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  5376. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  5377. };
  5378. /**
  5379. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  5380. * @hidden
  5381. */
  5382. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  5383. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  5384. };
  5385. /**
  5386. * Helper method called by the loader to allow extensions to override loading materials.
  5387. * @hidden
  5388. */
  5389. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  5390. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  5391. };
  5392. /**
  5393. * Helper method called by the loader to allow extensions to override loading textures.
  5394. * @hidden
  5395. */
  5396. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  5397. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  5398. };
  5399. /**
  5400. * Helper method called by the loader to allow extensions to override loading uris.
  5401. * @hidden
  5402. */
  5403. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  5404. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  5405. };
  5406. return GLTFLoaderExtension;
  5407. }());
  5408. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  5409. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5410. })(BABYLON || (BABYLON = {}));
  5411. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  5412. var BABYLON;
  5413. (function (BABYLON) {
  5414. var GLTF2;
  5415. (function (GLTF2) {
  5416. var Extensions;
  5417. (function (Extensions) {
  5418. var NAME = "MSFT_lod";
  5419. /**
  5420. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  5421. */
  5422. var MSFT_lod = /** @class */ (function (_super) {
  5423. __extends(MSFT_lod, _super);
  5424. function MSFT_lod(loader) {
  5425. var _this = _super.call(this, loader) || this;
  5426. _this.name = NAME;
  5427. /**
  5428. * Maximum number of LODs to load, starting from the lowest LOD.
  5429. */
  5430. _this.maxLODsToLoad = Number.MAX_VALUE;
  5431. /**
  5432. * Observable raised when all node LODs of one level are loaded.
  5433. * The event data is the index of the loaded LOD starting from zero.
  5434. * Dispose the loader to cancel the loading of the next level of LODs.
  5435. */
  5436. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  5437. /**
  5438. * Observable raised when all material LODs of one level are loaded.
  5439. * The event data is the index of the loaded LOD starting from zero.
  5440. * Dispose the loader to cancel the loading of the next level of LODs.
  5441. */
  5442. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  5443. _this._loadingNodeLOD = null;
  5444. _this._loadNodeSignals = {};
  5445. _this._loadNodePromises = new Array();
  5446. _this._loadingMaterialLOD = null;
  5447. _this._loadMaterialSignals = {};
  5448. _this._loadMaterialPromises = new Array();
  5449. _this._loader._onReadyObservable.addOnce(function () {
  5450. var _loop_1 = function (indexLOD) {
  5451. Promise.all(_this._loadNodePromises[indexLOD]).then(function () {
  5452. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  5453. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  5454. });
  5455. };
  5456. for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) {
  5457. _loop_1(indexLOD);
  5458. }
  5459. var _loop_2 = function (indexLOD) {
  5460. Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () {
  5461. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  5462. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  5463. });
  5464. };
  5465. for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) {
  5466. _loop_2(indexLOD);
  5467. }
  5468. });
  5469. return _this;
  5470. }
  5471. MSFT_lod.prototype.dispose = function () {
  5472. _super.prototype.dispose.call(this);
  5473. this._loadingNodeLOD = null;
  5474. this._loadNodeSignals = {};
  5475. this._loadingMaterialLOD = null;
  5476. this._loadMaterialSignals = {};
  5477. this.onMaterialLODsLoadedObservable.clear();
  5478. this.onNodeLODsLoadedObservable.clear();
  5479. };
  5480. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  5481. var _this = this;
  5482. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  5483. var firstPromise;
  5484. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  5485. _this._loader._parent._logOpen("" + extensionContext);
  5486. var _loop_3 = function (indexLOD) {
  5487. var nodeLOD = nodeLODs[indexLOD];
  5488. if (indexLOD !== 0) {
  5489. _this._loadingNodeLOD = nodeLOD;
  5490. if (!_this._loadNodeSignals[nodeLOD._index]) {
  5491. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  5492. }
  5493. }
  5494. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  5495. if (indexLOD !== 0) {
  5496. var previousNodeLOD = nodeLODs[indexLOD - 1];
  5497. if (previousNodeLOD._babylonMesh) {
  5498. previousNodeLOD._babylonMesh.dispose(false, true);
  5499. delete previousNodeLOD._babylonMesh;
  5500. }
  5501. }
  5502. if (indexLOD !== nodeLODs.length - 1) {
  5503. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  5504. if (_this._loadNodeSignals[nodeIndex]) {
  5505. _this._loadNodeSignals[nodeIndex].resolve();
  5506. delete _this._loadNodeSignals[nodeIndex];
  5507. }
  5508. }
  5509. });
  5510. if (indexLOD === 0) {
  5511. firstPromise = promise;
  5512. }
  5513. else {
  5514. _this._loader._completePromises.push(promise);
  5515. _this._loadingNodeLOD = null;
  5516. }
  5517. _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || [];
  5518. _this._loadNodePromises[indexLOD].push(promise);
  5519. };
  5520. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  5521. _loop_3(indexLOD);
  5522. }
  5523. _this._loader._parent._logClose();
  5524. return firstPromise;
  5525. });
  5526. };
  5527. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  5528. var _this = this;
  5529. // Don't load material LODs if already loading a node LOD.
  5530. if (this._loadingNodeLOD) {
  5531. return null;
  5532. }
  5533. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  5534. var firstPromise;
  5535. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  5536. _this._loader._parent._logOpen("" + extensionContext);
  5537. var _loop_4 = function (indexLOD) {
  5538. var materialLOD = materialLODs[indexLOD];
  5539. if (indexLOD !== 0) {
  5540. _this._loadingMaterialLOD = materialLOD;
  5541. if (!_this._loadMaterialSignals[materialLOD._index]) {
  5542. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  5543. }
  5544. }
  5545. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  5546. if (indexLOD !== 0) {
  5547. var babylonDataLOD = materialLOD._babylonData;
  5548. assign(babylonDataLOD[babylonDrawMode].material);
  5549. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  5550. if (previousBabylonDataLOD[babylonDrawMode]) {
  5551. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  5552. delete previousBabylonDataLOD[babylonDrawMode];
  5553. }
  5554. }
  5555. if (indexLOD !== materialLODs.length - 1) {
  5556. var materialIndex = materialLODs[indexLOD + 1]._index;
  5557. if (_this._loadMaterialSignals[materialIndex]) {
  5558. _this._loadMaterialSignals[materialIndex].resolve();
  5559. delete _this._loadMaterialSignals[materialIndex];
  5560. }
  5561. }
  5562. });
  5563. if (indexLOD === 0) {
  5564. firstPromise = promise;
  5565. }
  5566. else {
  5567. _this._loader._completePromises.push(promise);
  5568. _this._loadingMaterialLOD = null;
  5569. }
  5570. _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || [];
  5571. _this._loadMaterialPromises[indexLOD].push(promise);
  5572. };
  5573. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  5574. _loop_4(indexLOD);
  5575. }
  5576. _this._loader._parent._logClose();
  5577. return firstPromise;
  5578. });
  5579. };
  5580. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  5581. var _this = this;
  5582. if (this._loadingMaterialLOD || this._loadingNodeLOD) {
  5583. if (this._loader._parent.loggingEnabled) {
  5584. this._loader._parent._log("deferred");
  5585. }
  5586. }
  5587. // Defer the loading of uris if loading a material or node LOD.
  5588. if (this._loadingMaterialLOD) {
  5589. var index = this._loadingMaterialLOD._index;
  5590. return this._loadMaterialSignals[index].promise.then(function () {
  5591. return _this._loader._loadUriAsync(context, uri);
  5592. });
  5593. }
  5594. else if (this._loadingNodeLOD) {
  5595. var index = this._loadingNodeLOD._index;
  5596. return this._loadNodeSignals[index].promise.then(function () {
  5597. return _this._loader._loadUriAsync(context, uri);
  5598. });
  5599. }
  5600. return null;
  5601. };
  5602. /**
  5603. * Gets an array of LOD properties from lowest to highest.
  5604. */
  5605. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  5606. if (this.maxLODsToLoad <= 0) {
  5607. throw new Error("maxLODsToLoad must be greater than zero");
  5608. }
  5609. var properties = new Array();
  5610. for (var i = ids.length - 1; i >= 0; i--) {
  5611. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  5612. if (properties.length === this.maxLODsToLoad) {
  5613. return properties;
  5614. }
  5615. }
  5616. properties.push(property);
  5617. return properties;
  5618. };
  5619. return MSFT_lod;
  5620. }(GLTF2.GLTFLoaderExtension));
  5621. Extensions.MSFT_lod = MSFT_lod;
  5622. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  5623. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5624. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5625. })(BABYLON || (BABYLON = {}));
  5626. //# sourceMappingURL=MSFT_lod.js.map
  5627. var BABYLON;
  5628. (function (BABYLON) {
  5629. var GLTF2;
  5630. (function (GLTF2) {
  5631. var Extensions;
  5632. (function (Extensions) {
  5633. var NAME = "MSFT_minecraftMesh";
  5634. /** @hidden */
  5635. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  5636. __extends(MSFT_minecraftMesh, _super);
  5637. function MSFT_minecraftMesh() {
  5638. var _this = _super !== null && _super.apply(this, arguments) || this;
  5639. _this.name = NAME;
  5640. return _this;
  5641. }
  5642. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  5643. var _this = this;
  5644. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  5645. if (value) {
  5646. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  5647. if (babylonMaterial.needAlphaBlending()) {
  5648. babylonMaterial.forceDepthWrite = true;
  5649. babylonMaterial.separateCullingPass = true;
  5650. }
  5651. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  5652. babylonMaterial.twoSidedLighting = true;
  5653. assign(babylonMaterial);
  5654. });
  5655. }
  5656. return null;
  5657. });
  5658. };
  5659. return MSFT_minecraftMesh;
  5660. }(GLTF2.GLTFLoaderExtension));
  5661. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  5662. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  5663. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5664. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5665. })(BABYLON || (BABYLON = {}));
  5666. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  5667. var BABYLON;
  5668. (function (BABYLON) {
  5669. var GLTF2;
  5670. (function (GLTF2) {
  5671. var Extensions;
  5672. (function (Extensions) {
  5673. var NAME = "MSFT_sRGBFactors";
  5674. /** @hidden */
  5675. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  5676. __extends(MSFT_sRGBFactors, _super);
  5677. function MSFT_sRGBFactors() {
  5678. var _this = _super !== null && _super.apply(this, arguments) || this;
  5679. _this.name = NAME;
  5680. return _this;
  5681. }
  5682. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  5683. var _this = this;
  5684. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  5685. if (value) {
  5686. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  5687. if (!babylonMaterial.albedoTexture) {
  5688. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  5689. }
  5690. if (!babylonMaterial.reflectivityTexture) {
  5691. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  5692. }
  5693. assign(babylonMaterial);
  5694. });
  5695. }
  5696. return null;
  5697. });
  5698. };
  5699. return MSFT_sRGBFactors;
  5700. }(GLTF2.GLTFLoaderExtension));
  5701. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  5702. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  5703. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5704. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5705. })(BABYLON || (BABYLON = {}));
  5706. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  5707. var BABYLON;
  5708. (function (BABYLON) {
  5709. var GLTF2;
  5710. (function (GLTF2) {
  5711. var Extensions;
  5712. (function (Extensions) {
  5713. var NAME = "KHR_draco_mesh_compression";
  5714. /**
  5715. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  5716. */
  5717. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  5718. __extends(KHR_draco_mesh_compression, _super);
  5719. function KHR_draco_mesh_compression(loader) {
  5720. var _this = _super.call(this, loader) || this;
  5721. _this.name = NAME;
  5722. _this._dracoCompression = null;
  5723. // Disable extension if decoder is not available.
  5724. if (!BABYLON.DracoCompression.DecoderAvailable) {
  5725. _this.enabled = false;
  5726. }
  5727. return _this;
  5728. }
  5729. KHR_draco_mesh_compression.prototype.dispose = function () {
  5730. if (this._dracoCompression) {
  5731. this._dracoCompression.dispose();
  5732. }
  5733. _super.prototype.dispose.call(this);
  5734. };
  5735. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  5736. var _this = this;
  5737. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  5738. if (primitive.mode != undefined) {
  5739. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  5740. primitive.mode !== 4 /* TRIANGLES */) {
  5741. throw new Error(context + ": Unsupported mode " + primitive.mode);
  5742. }
  5743. // TODO: handle triangle strips
  5744. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  5745. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  5746. }
  5747. }
  5748. var attributes = {};
  5749. var loadAttribute = function (name, kind) {
  5750. var uniqueId = extension.attributes[name];
  5751. if (uniqueId == undefined) {
  5752. return;
  5753. }
  5754. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  5755. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  5756. babylonMesh._delayInfo.push(kind);
  5757. }
  5758. attributes[kind] = uniqueId;
  5759. };
  5760. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  5761. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  5762. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  5763. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  5764. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  5765. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  5766. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  5767. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  5768. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  5769. if (!bufferView._dracoBabylonGeometry) {
  5770. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  5771. if (!_this._dracoCompression) {
  5772. _this._dracoCompression = new BABYLON.DracoCompression();
  5773. }
  5774. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  5775. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  5776. babylonVertexData.applyToGeometry(babylonGeometry);
  5777. return babylonGeometry;
  5778. }).catch(function (error) {
  5779. throw new Error(context + ": " + error.message);
  5780. });
  5781. });
  5782. }
  5783. return bufferView._dracoBabylonGeometry;
  5784. });
  5785. };
  5786. return KHR_draco_mesh_compression;
  5787. }(GLTF2.GLTFLoaderExtension));
  5788. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  5789. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  5790. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5791. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5792. })(BABYLON || (BABYLON = {}));
  5793. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  5794. var BABYLON;
  5795. (function (BABYLON) {
  5796. var GLTF2;
  5797. (function (GLTF2) {
  5798. var Extensions;
  5799. (function (Extensions) {
  5800. var NAME = "KHR_materials_pbrSpecularGlossiness";
  5801. /**
  5802. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  5803. */
  5804. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  5805. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  5806. function KHR_materials_pbrSpecularGlossiness() {
  5807. var _this = _super !== null && _super.apply(this, arguments) || this;
  5808. _this.name = NAME;
  5809. return _this;
  5810. }
  5811. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  5812. var _this = this;
  5813. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  5814. material._babylonData = material._babylonData || {};
  5815. var babylonData = material._babylonData[babylonDrawMode];
  5816. if (!babylonData) {
  5817. var promises = new Array();
  5818. var name_1 = material.name || "materialSG_" + material._index;
  5819. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  5820. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  5821. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  5822. _this._loader._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5823. babylonData = {
  5824. material: babylonMaterial,
  5825. meshes: [],
  5826. loaded: Promise.all(promises).then(function () { })
  5827. };
  5828. material._babylonData[babylonDrawMode] = babylonData;
  5829. }
  5830. babylonData.meshes.push(babylonMesh);
  5831. assign(babylonData.material);
  5832. return babylonData.loaded;
  5833. });
  5834. };
  5835. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  5836. var promises = new Array();
  5837. if (properties.diffuseFactor) {
  5838. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  5839. babylonMaterial.alpha = properties.diffuseFactor[3];
  5840. }
  5841. else {
  5842. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5843. }
  5844. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  5845. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  5846. if (properties.diffuseTexture) {
  5847. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  5848. babylonMaterial.albedoTexture = texture;
  5849. }));
  5850. }
  5851. if (properties.specularGlossinessTexture) {
  5852. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  5853. babylonMaterial.reflectivityTexture = texture;
  5854. }));
  5855. babylonMaterial.reflectivityTexture.hasAlpha = true;
  5856. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  5857. }
  5858. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  5859. return Promise.all(promises).then(function () { });
  5860. };
  5861. return KHR_materials_pbrSpecularGlossiness;
  5862. }(GLTF2.GLTFLoaderExtension));
  5863. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  5864. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  5865. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5866. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5867. })(BABYLON || (BABYLON = {}));
  5868. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  5869. var BABYLON;
  5870. (function (BABYLON) {
  5871. var GLTF2;
  5872. (function (GLTF2) {
  5873. var Extensions;
  5874. (function (Extensions) {
  5875. var NAME = "KHR_materials_unlit";
  5876. /**
  5877. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  5878. */
  5879. var KHR_materials_unlit = /** @class */ (function (_super) {
  5880. __extends(KHR_materials_unlit, _super);
  5881. function KHR_materials_unlit() {
  5882. var _this = _super !== null && _super.apply(this, arguments) || this;
  5883. _this.name = NAME;
  5884. return _this;
  5885. }
  5886. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  5887. var _this = this;
  5888. return this._loadExtensionAsync(context, material, function () {
  5889. material._babylonData = material._babylonData || {};
  5890. var babylonData = material._babylonData[babylonDrawMode];
  5891. if (!babylonData) {
  5892. var name_1 = material.name || "materialUnlit_" + material._index;
  5893. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  5894. babylonMaterial.unlit = true;
  5895. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  5896. _this._loader._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5897. babylonData = {
  5898. material: babylonMaterial,
  5899. meshes: [],
  5900. loaded: promise
  5901. };
  5902. material._babylonData[babylonDrawMode] = babylonData;
  5903. }
  5904. babylonData.meshes.push(babylonMesh);
  5905. assign(babylonData.material);
  5906. return babylonData.loaded;
  5907. });
  5908. };
  5909. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  5910. var promises = new Array();
  5911. // Ensure metallic workflow
  5912. babylonMaterial.metallic = 1;
  5913. babylonMaterial.roughness = 1;
  5914. var properties = material.pbrMetallicRoughness;
  5915. if (properties) {
  5916. if (properties.baseColorFactor) {
  5917. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  5918. babylonMaterial.alpha = properties.baseColorFactor[3];
  5919. }
  5920. else {
  5921. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5922. }
  5923. if (properties.baseColorTexture) {
  5924. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  5925. babylonMaterial.albedoTexture = texture;
  5926. }));
  5927. }
  5928. }
  5929. if (material.doubleSided) {
  5930. babylonMaterial.backFaceCulling = false;
  5931. babylonMaterial.twoSidedLighting = true;
  5932. }
  5933. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  5934. return Promise.all(promises).then(function () { });
  5935. };
  5936. return KHR_materials_unlit;
  5937. }(GLTF2.GLTFLoaderExtension));
  5938. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  5939. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  5940. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5941. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5942. })(BABYLON || (BABYLON = {}));
  5943. //# sourceMappingURL=KHR_materials_unlit.js.map
  5944. var BABYLON;
  5945. (function (BABYLON) {
  5946. var GLTF2;
  5947. (function (GLTF2) {
  5948. var Extensions;
  5949. (function (Extensions) {
  5950. var NAME = "KHR_lights";
  5951. var LightType;
  5952. (function (LightType) {
  5953. LightType["AMBIENT"] = "ambient";
  5954. LightType["DIRECTIONAL"] = "directional";
  5955. LightType["POINT"] = "point";
  5956. LightType["SPOT"] = "spot";
  5957. })(LightType || (LightType = {}));
  5958. /**
  5959. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  5960. */
  5961. var KHR_lights = /** @class */ (function (_super) {
  5962. __extends(KHR_lights, _super);
  5963. function KHR_lights() {
  5964. var _this = _super !== null && _super.apply(this, arguments) || this;
  5965. _this.name = NAME;
  5966. return _this;
  5967. }
  5968. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  5969. var _this = this;
  5970. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  5971. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  5972. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  5973. if (light.type !== LightType.AMBIENT) {
  5974. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  5975. }
  5976. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  5977. return promise;
  5978. });
  5979. };
  5980. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  5981. var _this = this;
  5982. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  5983. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  5984. var babylonLight;
  5985. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  5986. var name = node._babylonMesh.name;
  5987. switch (light.type) {
  5988. case LightType.AMBIENT: {
  5989. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  5990. }
  5991. case LightType.DIRECTIONAL: {
  5992. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  5993. break;
  5994. }
  5995. case LightType.POINT: {
  5996. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  5997. break;
  5998. }
  5999. case LightType.SPOT: {
  6000. var spotLight = light;
  6001. // TODO: support inner and outer cone angles
  6002. //const innerConeAngle = spotLight.innerConeAngle || 0;
  6003. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  6004. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  6005. break;
  6006. }
  6007. default: {
  6008. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  6009. }
  6010. }
  6011. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  6012. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  6013. babylonLight.parent = node._babylonMesh;
  6014. return promise;
  6015. });
  6016. };
  6017. Object.defineProperty(KHR_lights.prototype, "_lights", {
  6018. get: function () {
  6019. var extensions = this._loader._gltf.extensions;
  6020. if (!extensions || !extensions[this.name]) {
  6021. throw new Error("#/extensions: '" + this.name + "' not found");
  6022. }
  6023. var extension = extensions[this.name];
  6024. return extension.lights;
  6025. },
  6026. enumerable: true,
  6027. configurable: true
  6028. });
  6029. return KHR_lights;
  6030. }(GLTF2.GLTFLoaderExtension));
  6031. Extensions.KHR_lights = KHR_lights;
  6032. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  6033. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  6034. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6035. })(BABYLON || (BABYLON = {}));
  6036. var BABYLON;
  6037. (function (BABYLON) {
  6038. var GLTF2;
  6039. (function (GLTF2) {
  6040. var Extensions;
  6041. (function (Extensions) {
  6042. var NAME = "KHR_texture_transform";
  6043. /**
  6044. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  6045. */
  6046. var KHR_texture_transform = /** @class */ (function (_super) {
  6047. __extends(KHR_texture_transform, _super);
  6048. function KHR_texture_transform() {
  6049. var _this = _super !== null && _super.apply(this, arguments) || this;
  6050. _this.name = NAME;
  6051. return _this;
  6052. }
  6053. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  6054. var _this = this;
  6055. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  6056. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  6057. if (extension.offset) {
  6058. babylonTexture.uOffset = extension.offset[0];
  6059. babylonTexture.vOffset = extension.offset[1];
  6060. }
  6061. // Always rotate around the origin.
  6062. babylonTexture.uRotationCenter = 0;
  6063. babylonTexture.vRotationCenter = 0;
  6064. if (extension.rotation) {
  6065. babylonTexture.wAng = -extension.rotation;
  6066. }
  6067. if (extension.scale) {
  6068. babylonTexture.uScale = extension.scale[0];
  6069. babylonTexture.vScale = extension.scale[1];
  6070. }
  6071. if (extension.texCoord != undefined) {
  6072. babylonTexture.coordinatesIndex = extension.texCoord;
  6073. }
  6074. assign(babylonTexture);
  6075. });
  6076. });
  6077. };
  6078. return KHR_texture_transform;
  6079. }(GLTF2.GLTFLoaderExtension));
  6080. Extensions.KHR_texture_transform = KHR_texture_transform;
  6081. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  6082. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  6083. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6084. })(BABYLON || (BABYLON = {}));
  6085. return BABYLON;
  6086. });