babylonjs.loaders.js 284 KB

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