babylonjs.loaders.js 282 KB

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