babylonjs.loaders.js 279 KB

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