babylonjs.loaders.js 282 KB

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