babylonjs.loaders.js 276 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473
  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 asset is completely loaded, immediately before the loader is disposed.
  1068. * For assets with LODs, raised when all of the LODs are complete.
  1069. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  1070. */
  1071. this.onCompleteObservable = new BABYLON.Observable();
  1072. /**
  1073. * Raised when the loader is disposed.
  1074. */
  1075. this.onDisposeObservable = new BABYLON.Observable();
  1076. /**
  1077. * Raised after a loader extension is created.
  1078. * Set additional options for a loader extension in this event.
  1079. */
  1080. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1081. // #endregion
  1082. this._loader = null;
  1083. this.name = "gltf";
  1084. this.extensions = {
  1085. ".gltf": { isBinary: false },
  1086. ".glb": { isBinary: true }
  1087. };
  1088. }
  1089. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  1090. set: function (callback) {
  1091. if (this._onParsedObserver) {
  1092. this.onParsedObservable.remove(this._onParsedObserver);
  1093. }
  1094. this._onParsedObserver = this.onParsedObservable.add(callback);
  1095. },
  1096. enumerable: true,
  1097. configurable: true
  1098. });
  1099. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  1100. set: function (callback) {
  1101. if (this._onMeshLoadedObserver) {
  1102. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  1103. }
  1104. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  1105. },
  1106. enumerable: true,
  1107. configurable: true
  1108. });
  1109. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  1110. set: function (callback) {
  1111. if (this._onTextureLoadedObserver) {
  1112. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  1113. }
  1114. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  1115. },
  1116. enumerable: true,
  1117. configurable: true
  1118. });
  1119. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  1120. set: function (callback) {
  1121. if (this._onMaterialLoadedObserver) {
  1122. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  1123. }
  1124. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  1125. },
  1126. enumerable: true,
  1127. configurable: true
  1128. });
  1129. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  1130. set: function (callback) {
  1131. if (this._onCompleteObserver) {
  1132. this.onCompleteObservable.remove(this._onCompleteObserver);
  1133. }
  1134. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  1135. },
  1136. enumerable: true,
  1137. configurable: true
  1138. });
  1139. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  1140. set: function (callback) {
  1141. if (this._onDisposeObserver) {
  1142. this.onDisposeObservable.remove(this._onDisposeObserver);
  1143. }
  1144. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  1145. },
  1146. enumerable: true,
  1147. configurable: true
  1148. });
  1149. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  1150. set: function (callback) {
  1151. if (this._onExtensionLoadedObserver) {
  1152. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  1153. }
  1154. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  1155. },
  1156. enumerable: true,
  1157. configurable: true
  1158. });
  1159. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  1160. /**
  1161. * The loader state or null if not active.
  1162. */
  1163. get: function () {
  1164. return this._loader ? this._loader.state : null;
  1165. },
  1166. enumerable: true,
  1167. configurable: true
  1168. });
  1169. /**
  1170. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  1171. */
  1172. GLTFFileLoader.prototype.dispose = function () {
  1173. if (this._loader) {
  1174. this._loader.dispose();
  1175. this._loader = null;
  1176. }
  1177. this.onMeshLoadedObservable.clear();
  1178. this.onTextureLoadedObservable.clear();
  1179. this.onMaterialLoadedObservable.clear();
  1180. this.onDisposeObservable.notifyObservers(this);
  1181. this.onDisposeObservable.clear();
  1182. };
  1183. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1184. var _this = this;
  1185. return Promise.resolve().then(function () {
  1186. var loaderData = _this._parse(data);
  1187. _this._loader = _this._getLoader(loaderData);
  1188. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  1189. });
  1190. };
  1191. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1192. var _this = this;
  1193. return Promise.resolve().then(function () {
  1194. var loaderData = _this._parse(data);
  1195. _this._loader = _this._getLoader(loaderData);
  1196. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  1197. });
  1198. };
  1199. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  1200. var _this = this;
  1201. return Promise.resolve().then(function () {
  1202. var loaderData = _this._parse(data);
  1203. _this._loader = _this._getLoader(loaderData);
  1204. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  1205. var container = new BABYLON.AssetContainer(scene);
  1206. Array.prototype.push.apply(container.meshes, result.meshes);
  1207. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  1208. Array.prototype.push.apply(container.skeletons, result.skeletons);
  1209. container.removeAllFromScene();
  1210. return container;
  1211. });
  1212. });
  1213. };
  1214. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  1215. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  1216. };
  1217. GLTFFileLoader.prototype.createPlugin = function () {
  1218. return new GLTFFileLoader();
  1219. };
  1220. GLTFFileLoader.prototype._parse = function (data) {
  1221. var parsedData;
  1222. if (data instanceof ArrayBuffer) {
  1223. parsedData = GLTFFileLoader._parseBinary(data);
  1224. }
  1225. else {
  1226. parsedData = {
  1227. json: JSON.parse(data),
  1228. bin: null
  1229. };
  1230. }
  1231. this.onParsedObservable.notifyObservers(parsedData);
  1232. this.onParsedObservable.clear();
  1233. return parsedData;
  1234. };
  1235. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  1236. var _this = this;
  1237. var loaderVersion = { major: 2, minor: 0 };
  1238. var asset = loaderData.json.asset || {};
  1239. var version = GLTFFileLoader._parseVersion(asset.version);
  1240. if (!version) {
  1241. throw new Error("Invalid version: " + asset.version);
  1242. }
  1243. if (asset.minVersion !== undefined) {
  1244. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  1245. if (!minVersion) {
  1246. throw new Error("Invalid minimum version: " + asset.minVersion);
  1247. }
  1248. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  1249. throw new Error("Incompatible minimum version: " + asset.minVersion);
  1250. }
  1251. }
  1252. var createLoaders = {
  1253. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  1254. 2: GLTFFileLoader.CreateGLTFLoaderV2
  1255. };
  1256. var createLoader = createLoaders[version.major];
  1257. if (!createLoader) {
  1258. throw new Error("Unsupported version: " + asset.version);
  1259. }
  1260. var loader = createLoader();
  1261. loader.coordinateSystemMode = this.coordinateSystemMode;
  1262. loader.animationStartMode = this.animationStartMode;
  1263. loader.compileMaterials = this.compileMaterials;
  1264. loader.useClipPlane = this.useClipPlane;
  1265. loader.compileShadowGenerators = this.compileShadowGenerators;
  1266. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  1267. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  1268. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  1269. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  1270. loader.onCompleteObservable.add(function () {
  1271. _this.onMeshLoadedObservable.clear();
  1272. _this.onTextureLoadedObservable.clear();
  1273. _this.onMaterialLoadedObservable.clear();
  1274. _this.onCompleteObservable.notifyObservers(_this);
  1275. _this.onCompleteObservable.clear();
  1276. });
  1277. return loader;
  1278. };
  1279. GLTFFileLoader._parseBinary = function (data) {
  1280. var Binary = {
  1281. Magic: 0x46546C67
  1282. };
  1283. var binaryReader = new BinaryReader(data);
  1284. var magic = binaryReader.readUint32();
  1285. if (magic !== Binary.Magic) {
  1286. throw new Error("Unexpected magic: " + magic);
  1287. }
  1288. var version = binaryReader.readUint32();
  1289. switch (version) {
  1290. case 1: return GLTFFileLoader._parseV1(binaryReader);
  1291. case 2: return GLTFFileLoader._parseV2(binaryReader);
  1292. }
  1293. throw new Error("Unsupported version: " + version);
  1294. };
  1295. GLTFFileLoader._parseV1 = function (binaryReader) {
  1296. var ContentFormat = {
  1297. JSON: 0
  1298. };
  1299. var length = binaryReader.readUint32();
  1300. if (length != binaryReader.getLength()) {
  1301. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1302. }
  1303. var contentLength = binaryReader.readUint32();
  1304. var contentFormat = binaryReader.readUint32();
  1305. var content;
  1306. switch (contentFormat) {
  1307. case ContentFormat.JSON: {
  1308. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  1309. break;
  1310. }
  1311. default: {
  1312. throw new Error("Unexpected content format: " + contentFormat);
  1313. }
  1314. }
  1315. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  1316. var body = binaryReader.readUint8Array(bytesRemaining);
  1317. return {
  1318. json: content,
  1319. bin: body
  1320. };
  1321. };
  1322. GLTFFileLoader._parseV2 = function (binaryReader) {
  1323. var ChunkFormat = {
  1324. JSON: 0x4E4F534A,
  1325. BIN: 0x004E4942
  1326. };
  1327. var length = binaryReader.readUint32();
  1328. if (length !== binaryReader.getLength()) {
  1329. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1330. }
  1331. // JSON chunk
  1332. var chunkLength = binaryReader.readUint32();
  1333. var chunkFormat = binaryReader.readUint32();
  1334. if (chunkFormat !== ChunkFormat.JSON) {
  1335. throw new Error("First chunk format is not JSON");
  1336. }
  1337. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  1338. // Look for BIN chunk
  1339. var bin = null;
  1340. while (binaryReader.getPosition() < binaryReader.getLength()) {
  1341. var chunkLength_1 = binaryReader.readUint32();
  1342. var chunkFormat_1 = binaryReader.readUint32();
  1343. switch (chunkFormat_1) {
  1344. case ChunkFormat.JSON: {
  1345. throw new Error("Unexpected JSON chunk");
  1346. }
  1347. case ChunkFormat.BIN: {
  1348. bin = binaryReader.readUint8Array(chunkLength_1);
  1349. break;
  1350. }
  1351. default: {
  1352. // ignore unrecognized chunkFormat
  1353. binaryReader.skipBytes(chunkLength_1);
  1354. break;
  1355. }
  1356. }
  1357. }
  1358. return {
  1359. json: json,
  1360. bin: bin
  1361. };
  1362. };
  1363. GLTFFileLoader._parseVersion = function (version) {
  1364. if (version === "1.0" || version === "1.0.1") {
  1365. return {
  1366. major: 1,
  1367. minor: 0
  1368. };
  1369. }
  1370. var match = (version + "").match(/^(\d+)\.(\d+)/);
  1371. if (!match) {
  1372. return null;
  1373. }
  1374. return {
  1375. major: parseInt(match[1]),
  1376. minor: parseInt(match[2])
  1377. };
  1378. };
  1379. GLTFFileLoader._compareVersion = function (a, b) {
  1380. if (a.major > b.major)
  1381. return 1;
  1382. if (a.major < b.major)
  1383. return -1;
  1384. if (a.minor > b.minor)
  1385. return 1;
  1386. if (a.minor < b.minor)
  1387. return -1;
  1388. return 0;
  1389. };
  1390. GLTFFileLoader._decodeBufferToText = function (buffer) {
  1391. var result = "";
  1392. var length = buffer.byteLength;
  1393. for (var i = 0; i < length; i++) {
  1394. result += String.fromCharCode(buffer[i]);
  1395. }
  1396. return result;
  1397. };
  1398. // #endregion
  1399. // #region V1 options
  1400. GLTFFileLoader.IncrementalLoading = true;
  1401. GLTFFileLoader.HomogeneousCoordinates = false;
  1402. return GLTFFileLoader;
  1403. }());
  1404. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1405. var BinaryReader = /** @class */ (function () {
  1406. function BinaryReader(arrayBuffer) {
  1407. this._arrayBuffer = arrayBuffer;
  1408. this._dataView = new DataView(arrayBuffer);
  1409. this._byteOffset = 0;
  1410. }
  1411. BinaryReader.prototype.getPosition = function () {
  1412. return this._byteOffset;
  1413. };
  1414. BinaryReader.prototype.getLength = function () {
  1415. return this._arrayBuffer.byteLength;
  1416. };
  1417. BinaryReader.prototype.readUint32 = function () {
  1418. var value = this._dataView.getUint32(this._byteOffset, true);
  1419. this._byteOffset += 4;
  1420. return value;
  1421. };
  1422. BinaryReader.prototype.readUint8Array = function (length) {
  1423. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1424. this._byteOffset += length;
  1425. return value;
  1426. };
  1427. BinaryReader.prototype.skipBytes = function (length) {
  1428. this._byteOffset += length;
  1429. };
  1430. return BinaryReader;
  1431. }());
  1432. if (BABYLON.SceneLoader) {
  1433. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1434. }
  1435. })(BABYLON || (BABYLON = {}));
  1436. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1437. var BABYLON;
  1438. (function (BABYLON) {
  1439. var GLTF1;
  1440. (function (GLTF1) {
  1441. /**
  1442. * Enums
  1443. */
  1444. var EComponentType;
  1445. (function (EComponentType) {
  1446. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1447. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1448. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1449. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1450. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1451. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  1452. var EShaderType;
  1453. (function (EShaderType) {
  1454. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1455. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1456. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  1457. var EParameterType;
  1458. (function (EParameterType) {
  1459. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1460. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1461. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1462. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1463. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1464. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1465. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1466. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1467. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1468. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1469. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1470. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1471. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1472. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1473. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1474. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1475. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1476. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1477. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1478. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1479. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1480. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  1481. var ETextureWrapMode;
  1482. (function (ETextureWrapMode) {
  1483. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1484. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1485. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1486. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  1487. var ETextureFilterType;
  1488. (function (ETextureFilterType) {
  1489. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1490. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1491. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1492. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1493. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1494. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1495. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  1496. var ETextureFormat;
  1497. (function (ETextureFormat) {
  1498. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1499. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1500. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1501. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1502. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1503. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  1504. var ECullingType;
  1505. (function (ECullingType) {
  1506. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1507. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1508. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1509. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  1510. var EBlendingFunction;
  1511. (function (EBlendingFunction) {
  1512. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1513. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1514. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1515. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1516. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1517. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1518. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1519. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1520. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1521. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1522. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1523. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1524. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1525. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1526. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1527. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  1528. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1529. })(BABYLON || (BABYLON = {}));
  1530. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  1531. var BABYLON;
  1532. (function (BABYLON) {
  1533. var GLTF1;
  1534. (function (GLTF1) {
  1535. /**
  1536. * Tokenizer. Used for shaders compatibility
  1537. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1538. */
  1539. var ETokenType;
  1540. (function (ETokenType) {
  1541. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1542. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1543. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1544. })(ETokenType || (ETokenType = {}));
  1545. var Tokenizer = /** @class */ (function () {
  1546. function Tokenizer(toParse) {
  1547. this._pos = 0;
  1548. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1549. this._toParse = toParse;
  1550. this._maxPos = toParse.length;
  1551. }
  1552. Tokenizer.prototype.getNextToken = function () {
  1553. if (this.isEnd())
  1554. return ETokenType.END_OF_INPUT;
  1555. this.currentString = this.read();
  1556. this.currentToken = ETokenType.UNKNOWN;
  1557. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1558. this.currentToken = ETokenType.IDENTIFIER;
  1559. this.currentIdentifier = this.currentString;
  1560. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1561. this.currentIdentifier += this.currentString;
  1562. this.forward();
  1563. }
  1564. }
  1565. return this.currentToken;
  1566. };
  1567. Tokenizer.prototype.peek = function () {
  1568. return this._toParse[this._pos];
  1569. };
  1570. Tokenizer.prototype.read = function () {
  1571. return this._toParse[this._pos++];
  1572. };
  1573. Tokenizer.prototype.forward = function () {
  1574. this._pos++;
  1575. };
  1576. Tokenizer.prototype.isEnd = function () {
  1577. return this._pos >= this._maxPos;
  1578. };
  1579. return Tokenizer;
  1580. }());
  1581. /**
  1582. * Values
  1583. */
  1584. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1585. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1586. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1587. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1588. /**
  1589. * Parse
  1590. */
  1591. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1592. for (var buf in parsedBuffers) {
  1593. var parsedBuffer = parsedBuffers[buf];
  1594. gltfRuntime.buffers[buf] = parsedBuffer;
  1595. gltfRuntime.buffersCount++;
  1596. }
  1597. };
  1598. var parseShaders = function (parsedShaders, gltfRuntime) {
  1599. for (var sha in parsedShaders) {
  1600. var parsedShader = parsedShaders[sha];
  1601. gltfRuntime.shaders[sha] = parsedShader;
  1602. gltfRuntime.shaderscount++;
  1603. }
  1604. };
  1605. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1606. for (var object in parsedObjects) {
  1607. var parsedObject = parsedObjects[object];
  1608. gltfRuntime[runtimeProperty][object] = parsedObject;
  1609. }
  1610. };
  1611. /**
  1612. * Utils
  1613. */
  1614. var normalizeUVs = function (buffer) {
  1615. if (!buffer) {
  1616. return;
  1617. }
  1618. for (var i = 0; i < buffer.length / 2; i++) {
  1619. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1620. }
  1621. };
  1622. var getAttribute = function (attributeParameter) {
  1623. if (attributeParameter.semantic === "NORMAL") {
  1624. return "normal";
  1625. }
  1626. else if (attributeParameter.semantic === "POSITION") {
  1627. return "position";
  1628. }
  1629. else if (attributeParameter.semantic === "JOINT") {
  1630. return "matricesIndices";
  1631. }
  1632. else if (attributeParameter.semantic === "WEIGHT") {
  1633. return "matricesWeights";
  1634. }
  1635. else if (attributeParameter.semantic === "COLOR") {
  1636. return "color";
  1637. }
  1638. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1639. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1640. return "uv" + (channel === 0 ? "" : channel + 1);
  1641. }
  1642. return null;
  1643. };
  1644. /**
  1645. * Loads and creates animations
  1646. */
  1647. var loadAnimations = function (gltfRuntime) {
  1648. for (var anim in gltfRuntime.animations) {
  1649. var animation = gltfRuntime.animations[anim];
  1650. if (!animation.channels || !animation.samplers) {
  1651. continue;
  1652. }
  1653. var lastAnimation = null;
  1654. for (var i = 0; i < animation.channels.length; i++) {
  1655. // Get parameters and load buffers
  1656. var channel = animation.channels[i];
  1657. var sampler = animation.samplers[channel.sampler];
  1658. if (!sampler) {
  1659. continue;
  1660. }
  1661. var inputData = null;
  1662. var outputData = null;
  1663. if (animation.parameters) {
  1664. inputData = animation.parameters[sampler.input];
  1665. outputData = animation.parameters[sampler.output];
  1666. }
  1667. else {
  1668. inputData = sampler.input;
  1669. outputData = sampler.output;
  1670. }
  1671. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1672. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1673. var targetID = channel.target.id;
  1674. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1675. if (targetNode === null) {
  1676. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1677. }
  1678. if (targetNode === null) {
  1679. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1680. continue;
  1681. }
  1682. var isBone = targetNode instanceof BABYLON.Bone;
  1683. // Get target path (position, rotation or scaling)
  1684. var targetPath = channel.target.path;
  1685. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1686. if (targetPathIndex !== -1) {
  1687. targetPath = babylonAnimationPaths[targetPathIndex];
  1688. }
  1689. // Determine animation type
  1690. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1691. if (!isBone) {
  1692. if (targetPath === "rotationQuaternion") {
  1693. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1694. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1695. }
  1696. else {
  1697. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1698. }
  1699. }
  1700. // Create animation and key frames
  1701. var babylonAnimation = null;
  1702. var keys = [];
  1703. var arrayOffset = 0;
  1704. var modifyKey = false;
  1705. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1706. babylonAnimation = lastAnimation;
  1707. modifyKey = true;
  1708. }
  1709. if (!modifyKey) {
  1710. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1711. }
  1712. // For each frame
  1713. for (var j = 0; j < bufferInput.length; j++) {
  1714. var value = null;
  1715. if (targetPath === "rotationQuaternion") {
  1716. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1717. arrayOffset += 4;
  1718. }
  1719. else {
  1720. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1721. arrayOffset += 3;
  1722. }
  1723. if (isBone) {
  1724. var bone = targetNode;
  1725. var translation = BABYLON.Vector3.Zero();
  1726. var rotationQuaternion = new BABYLON.Quaternion();
  1727. var scaling = BABYLON.Vector3.Zero();
  1728. // Warning on decompose
  1729. var mat = bone.getBaseMatrix();
  1730. if (modifyKey && lastAnimation) {
  1731. mat = lastAnimation.getKeys()[j].value;
  1732. }
  1733. mat.decompose(scaling, rotationQuaternion, translation);
  1734. if (targetPath === "position") {
  1735. translation = value;
  1736. }
  1737. else if (targetPath === "rotationQuaternion") {
  1738. rotationQuaternion = value;
  1739. }
  1740. else {
  1741. scaling = value;
  1742. }
  1743. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1744. }
  1745. if (!modifyKey) {
  1746. keys.push({
  1747. frame: bufferInput[j],
  1748. value: value
  1749. });
  1750. }
  1751. else if (lastAnimation) {
  1752. lastAnimation.getKeys()[j].value = value;
  1753. }
  1754. }
  1755. // Finish
  1756. if (!modifyKey && babylonAnimation) {
  1757. babylonAnimation.setKeys(keys);
  1758. targetNode.animations.push(babylonAnimation);
  1759. }
  1760. lastAnimation = babylonAnimation;
  1761. gltfRuntime.scene.stopAnimation(targetNode);
  1762. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1763. }
  1764. }
  1765. };
  1766. /**
  1767. * Returns the bones transformation matrix
  1768. */
  1769. var configureBoneTransformation = function (node) {
  1770. var mat = null;
  1771. if (node.translation || node.rotation || node.scale) {
  1772. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1773. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1774. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1775. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1776. }
  1777. else {
  1778. mat = BABYLON.Matrix.FromArray(node.matrix);
  1779. }
  1780. return mat;
  1781. };
  1782. /**
  1783. * Returns the parent bone
  1784. */
  1785. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1786. // Try to find
  1787. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1788. if (newSkeleton.bones[i].name === jointName) {
  1789. return newSkeleton.bones[i];
  1790. }
  1791. }
  1792. // Not found, search in gltf nodes
  1793. var nodes = gltfRuntime.nodes;
  1794. for (var nde in nodes) {
  1795. var node = nodes[nde];
  1796. if (!node.jointName) {
  1797. continue;
  1798. }
  1799. var children = node.children;
  1800. for (var i = 0; i < children.length; i++) {
  1801. var child = gltfRuntime.nodes[children[i]];
  1802. if (!child.jointName) {
  1803. continue;
  1804. }
  1805. if (child.jointName === jointName) {
  1806. var mat = configureBoneTransformation(node);
  1807. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1808. bone.id = nde;
  1809. return bone;
  1810. }
  1811. }
  1812. }
  1813. return null;
  1814. };
  1815. /**
  1816. * Returns the appropriate root node
  1817. */
  1818. var getNodeToRoot = function (nodesToRoot, id) {
  1819. for (var i = 0; i < nodesToRoot.length; i++) {
  1820. var nodeToRoot = nodesToRoot[i];
  1821. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1822. var child = nodeToRoot.node.children[j];
  1823. if (child === id) {
  1824. return nodeToRoot.bone;
  1825. }
  1826. }
  1827. }
  1828. return null;
  1829. };
  1830. /**
  1831. * Returns the node with the joint name
  1832. */
  1833. var getJointNode = function (gltfRuntime, jointName) {
  1834. var nodes = gltfRuntime.nodes;
  1835. var node = nodes[jointName];
  1836. if (node) {
  1837. return {
  1838. node: node,
  1839. id: jointName
  1840. };
  1841. }
  1842. for (var nde in nodes) {
  1843. node = nodes[nde];
  1844. if (node.jointName === jointName) {
  1845. return {
  1846. node: node,
  1847. id: nde
  1848. };
  1849. }
  1850. }
  1851. return null;
  1852. };
  1853. /**
  1854. * Checks if a nodes is in joints
  1855. */
  1856. var nodeIsInJoints = function (skins, id) {
  1857. for (var i = 0; i < skins.jointNames.length; i++) {
  1858. if (skins.jointNames[i] === id) {
  1859. return true;
  1860. }
  1861. }
  1862. return false;
  1863. };
  1864. /**
  1865. * Fills the nodes to root for bones and builds hierarchy
  1866. */
  1867. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1868. // Creates nodes for root
  1869. for (var nde in gltfRuntime.nodes) {
  1870. var node = gltfRuntime.nodes[nde];
  1871. var id = nde;
  1872. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1873. continue;
  1874. }
  1875. // Create node to root bone
  1876. var mat = configureBoneTransformation(node);
  1877. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  1878. bone.id = id;
  1879. nodesToRoot.push({ bone: bone, node: node, id: id });
  1880. }
  1881. // Parenting
  1882. for (var i = 0; i < nodesToRoot.length; i++) {
  1883. var nodeToRoot = nodesToRoot[i];
  1884. var children = nodeToRoot.node.children;
  1885. for (var j = 0; j < children.length; j++) {
  1886. var child = null;
  1887. for (var k = 0; k < nodesToRoot.length; k++) {
  1888. if (nodesToRoot[k].id === children[j]) {
  1889. child = nodesToRoot[k];
  1890. break;
  1891. }
  1892. }
  1893. if (child) {
  1894. child.bone._parent = nodeToRoot.bone;
  1895. nodeToRoot.bone.children.push(child.bone);
  1896. }
  1897. }
  1898. }
  1899. };
  1900. /**
  1901. * Imports a skeleton
  1902. */
  1903. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1904. if (!newSkeleton) {
  1905. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  1906. }
  1907. if (!skins.babylonSkeleton) {
  1908. return newSkeleton;
  1909. }
  1910. // Find the root bones
  1911. var nodesToRoot = [];
  1912. var nodesToRootToAdd = [];
  1913. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1914. newSkeleton.bones = [];
  1915. // Joints
  1916. for (var i = 0; i < skins.jointNames.length; i++) {
  1917. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1918. if (!jointNode) {
  1919. continue;
  1920. }
  1921. var node = jointNode.node;
  1922. if (!node) {
  1923. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1924. continue;
  1925. }
  1926. var id = jointNode.id;
  1927. // Optimize, if the bone already exists...
  1928. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1929. if (existingBone) {
  1930. newSkeleton.bones.push(existingBone);
  1931. continue;
  1932. }
  1933. // Search for parent bone
  1934. var foundBone = false;
  1935. var parentBone = null;
  1936. for (var j = 0; j < i; j++) {
  1937. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  1938. if (!jointNode_1) {
  1939. continue;
  1940. }
  1941. var joint = jointNode_1.node;
  1942. if (!joint) {
  1943. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1944. continue;
  1945. }
  1946. var children = joint.children;
  1947. if (!children) {
  1948. continue;
  1949. }
  1950. foundBone = false;
  1951. for (var k = 0; k < children.length; k++) {
  1952. if (children[k] === id) {
  1953. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1954. foundBone = true;
  1955. break;
  1956. }
  1957. }
  1958. if (foundBone) {
  1959. break;
  1960. }
  1961. }
  1962. // Create bone
  1963. var mat = configureBoneTransformation(node);
  1964. if (!parentBone && nodesToRoot.length > 0) {
  1965. parentBone = getNodeToRoot(nodesToRoot, id);
  1966. if (parentBone) {
  1967. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1968. nodesToRootToAdd.push(parentBone);
  1969. }
  1970. }
  1971. }
  1972. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1973. bone.id = id;
  1974. }
  1975. // Polish
  1976. var bones = newSkeleton.bones;
  1977. newSkeleton.bones = [];
  1978. for (var i = 0; i < skins.jointNames.length; i++) {
  1979. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1980. if (!jointNode) {
  1981. continue;
  1982. }
  1983. for (var j = 0; j < bones.length; j++) {
  1984. if (bones[j].id === jointNode.id) {
  1985. newSkeleton.bones.push(bones[j]);
  1986. break;
  1987. }
  1988. }
  1989. }
  1990. newSkeleton.prepare();
  1991. // Finish
  1992. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1993. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1994. }
  1995. return newSkeleton;
  1996. };
  1997. /**
  1998. * Imports a mesh and its geometries
  1999. */
  2000. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  2001. if (!newMesh) {
  2002. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2003. newMesh.id = id;
  2004. }
  2005. if (!node.babylonNode) {
  2006. return newMesh;
  2007. }
  2008. var subMaterials = [];
  2009. var vertexData = null;
  2010. var verticesStarts = new Array();
  2011. var verticesCounts = new Array();
  2012. var indexStarts = new Array();
  2013. var indexCounts = new Array();
  2014. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2015. var meshID = meshes[meshIndex];
  2016. var mesh = gltfRuntime.meshes[meshID];
  2017. if (!mesh) {
  2018. continue;
  2019. }
  2020. // Positions, normals and UVs
  2021. for (var i = 0; i < mesh.primitives.length; i++) {
  2022. // Temporary vertex data
  2023. var tempVertexData = new BABYLON.VertexData();
  2024. var primitive = mesh.primitives[i];
  2025. if (primitive.mode !== 4) {
  2026. // continue;
  2027. }
  2028. var attributes = primitive.attributes;
  2029. var accessor = null;
  2030. var buffer = null;
  2031. // Set positions, normal and uvs
  2032. for (var semantic in attributes) {
  2033. // Link accessor and buffer view
  2034. accessor = gltfRuntime.accessors[attributes[semantic]];
  2035. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2036. if (semantic === "NORMAL") {
  2037. tempVertexData.normals = new Float32Array(buffer.length);
  2038. tempVertexData.normals.set(buffer);
  2039. }
  2040. else if (semantic === "POSITION") {
  2041. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  2042. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  2043. for (var j = 0; j < buffer.length; j += 4) {
  2044. tempVertexData.positions[j] = buffer[j];
  2045. tempVertexData.positions[j + 1] = buffer[j + 1];
  2046. tempVertexData.positions[j + 2] = buffer[j + 2];
  2047. }
  2048. }
  2049. else {
  2050. tempVertexData.positions = new Float32Array(buffer.length);
  2051. tempVertexData.positions.set(buffer);
  2052. }
  2053. verticesCounts.push(tempVertexData.positions.length);
  2054. }
  2055. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2056. var channel = Number(semantic.split("_")[1]);
  2057. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2058. var uvs = new Float32Array(buffer.length);
  2059. uvs.set(buffer);
  2060. normalizeUVs(uvs);
  2061. tempVertexData.set(uvs, uvKind);
  2062. }
  2063. else if (semantic === "JOINT") {
  2064. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2065. tempVertexData.matricesIndices.set(buffer);
  2066. }
  2067. else if (semantic === "WEIGHT") {
  2068. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2069. tempVertexData.matricesWeights.set(buffer);
  2070. }
  2071. else if (semantic === "COLOR") {
  2072. tempVertexData.colors = new Float32Array(buffer.length);
  2073. tempVertexData.colors.set(buffer);
  2074. }
  2075. }
  2076. // Indices
  2077. accessor = gltfRuntime.accessors[primitive.indices];
  2078. if (accessor) {
  2079. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2080. tempVertexData.indices = new Int32Array(buffer.length);
  2081. tempVertexData.indices.set(buffer);
  2082. indexCounts.push(tempVertexData.indices.length);
  2083. }
  2084. else {
  2085. // Set indices on the fly
  2086. var indices = [];
  2087. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2088. indices.push(j);
  2089. }
  2090. tempVertexData.indices = new Int32Array(indices);
  2091. indexCounts.push(tempVertexData.indices.length);
  2092. }
  2093. if (!vertexData) {
  2094. vertexData = tempVertexData;
  2095. }
  2096. else {
  2097. vertexData.merge(tempVertexData);
  2098. }
  2099. // Sub material
  2100. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  2101. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  2102. // Update vertices start and index start
  2103. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2104. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2105. }
  2106. }
  2107. var material;
  2108. if (subMaterials.length > 1) {
  2109. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  2110. material.subMaterials = subMaterials;
  2111. }
  2112. else {
  2113. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  2114. }
  2115. if (subMaterials.length === 1) {
  2116. material = subMaterials[0];
  2117. }
  2118. if (!newMesh.material) {
  2119. newMesh.material = material;
  2120. }
  2121. // Apply geometry
  2122. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  2123. newMesh.computeWorldMatrix(true);
  2124. // Apply submeshes
  2125. newMesh.subMeshes = [];
  2126. var index = 0;
  2127. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2128. var meshID = meshes[meshIndex];
  2129. var mesh = gltfRuntime.meshes[meshID];
  2130. if (!mesh) {
  2131. continue;
  2132. }
  2133. for (var i = 0; i < mesh.primitives.length; i++) {
  2134. if (mesh.primitives[i].mode !== 4) {
  2135. //continue;
  2136. }
  2137. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  2138. index++;
  2139. }
  2140. }
  2141. // Finish
  2142. return newMesh;
  2143. };
  2144. /**
  2145. * Configure node transformation from position, rotation and scaling
  2146. */
  2147. var configureNode = function (newNode, position, rotation, scaling) {
  2148. if (newNode.position) {
  2149. newNode.position = position;
  2150. }
  2151. if (newNode.rotationQuaternion || newNode.rotation) {
  2152. newNode.rotationQuaternion = rotation;
  2153. }
  2154. if (newNode.scaling) {
  2155. newNode.scaling = scaling;
  2156. }
  2157. };
  2158. /**
  2159. * Configures node from transformation matrix
  2160. */
  2161. var configureNodeFromMatrix = function (newNode, node, parent) {
  2162. if (node.matrix) {
  2163. var position = new BABYLON.Vector3(0, 0, 0);
  2164. var rotation = new BABYLON.Quaternion();
  2165. var scaling = new BABYLON.Vector3(0, 0, 0);
  2166. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2167. mat.decompose(scaling, rotation, position);
  2168. configureNode(newNode, position, rotation, scaling);
  2169. }
  2170. else if (node.translation && node.rotation && node.scale) {
  2171. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  2172. }
  2173. newNode.computeWorldMatrix(true);
  2174. };
  2175. /**
  2176. * Imports a node
  2177. */
  2178. var importNode = function (gltfRuntime, node, id, parent) {
  2179. var lastNode = null;
  2180. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  2181. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  2182. return null;
  2183. }
  2184. }
  2185. // Meshes
  2186. if (node.skin) {
  2187. if (node.meshes) {
  2188. var skin = gltfRuntime.skins[node.skin];
  2189. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  2190. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  2191. if (newMesh.skeleton === null) {
  2192. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  2193. if (!skin.babylonSkeleton) {
  2194. skin.babylonSkeleton = newMesh.skeleton;
  2195. }
  2196. }
  2197. lastNode = newMesh;
  2198. }
  2199. }
  2200. else if (node.meshes) {
  2201. /**
  2202. * Improve meshes property
  2203. */
  2204. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  2205. lastNode = newMesh;
  2206. }
  2207. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2208. var light = gltfRuntime.lights[node.light];
  2209. if (light) {
  2210. if (light.type === "ambient") {
  2211. var ambienLight = light[light.type];
  2212. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2213. hemiLight.name = node.name || "";
  2214. if (ambienLight.color) {
  2215. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  2216. }
  2217. lastNode = hemiLight;
  2218. }
  2219. else if (light.type === "directional") {
  2220. var directionalLight = light[light.type];
  2221. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2222. dirLight.name = node.name || "";
  2223. if (directionalLight.color) {
  2224. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  2225. }
  2226. lastNode = dirLight;
  2227. }
  2228. else if (light.type === "point") {
  2229. var pointLight = light[light.type];
  2230. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2231. ptLight.name = node.name || "";
  2232. if (pointLight.color) {
  2233. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  2234. }
  2235. lastNode = ptLight;
  2236. }
  2237. else if (light.type === "spot") {
  2238. var spotLight = light[light.type];
  2239. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2240. spLight.name = node.name || "";
  2241. if (spotLight.color) {
  2242. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  2243. }
  2244. if (spotLight.fallOfAngle) {
  2245. spLight.angle = spotLight.fallOfAngle;
  2246. }
  2247. if (spotLight.fallOffExponent) {
  2248. spLight.exponent = spotLight.fallOffExponent;
  2249. }
  2250. lastNode = spLight;
  2251. }
  2252. }
  2253. }
  2254. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2255. var camera = gltfRuntime.cameras[node.camera];
  2256. if (camera) {
  2257. if (camera.type === "orthographic") {
  2258. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2259. orthoCamera.name = node.name || "";
  2260. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  2261. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2262. lastNode = orthoCamera;
  2263. }
  2264. else if (camera.type === "perspective") {
  2265. var perspectiveCamera = camera[camera.type];
  2266. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2267. persCamera.name = node.name || "";
  2268. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2269. if (!perspectiveCamera.aspectRatio) {
  2270. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2271. }
  2272. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2273. persCamera.maxZ = perspectiveCamera.zfar;
  2274. persCamera.minZ = perspectiveCamera.znear;
  2275. }
  2276. lastNode = persCamera;
  2277. }
  2278. }
  2279. }
  2280. // Empty node
  2281. if (!node.jointName) {
  2282. if (node.babylonNode) {
  2283. return node.babylonNode;
  2284. }
  2285. else if (lastNode === null) {
  2286. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2287. node.babylonNode = dummy;
  2288. lastNode = dummy;
  2289. }
  2290. }
  2291. if (lastNode !== null) {
  2292. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  2293. configureNodeFromMatrix(lastNode, node, parent);
  2294. }
  2295. else {
  2296. var translation = node.translation || [0, 0, 0];
  2297. var rotation = node.rotation || [0, 0, 0, 1];
  2298. var scale = node.scale || [1, 1, 1];
  2299. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  2300. }
  2301. lastNode.updateCache(true);
  2302. node.babylonNode = lastNode;
  2303. }
  2304. return lastNode;
  2305. };
  2306. /**
  2307. * Traverses nodes and creates them
  2308. */
  2309. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2310. if (meshIncluded === void 0) { meshIncluded = false; }
  2311. var node = gltfRuntime.nodes[id];
  2312. var newNode = null;
  2313. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  2314. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2315. meshIncluded = true;
  2316. }
  2317. else {
  2318. meshIncluded = false;
  2319. }
  2320. }
  2321. else {
  2322. meshIncluded = true;
  2323. }
  2324. if (!node.jointName && meshIncluded) {
  2325. newNode = importNode(gltfRuntime, node, id, parent);
  2326. if (newNode !== null) {
  2327. newNode.id = id;
  2328. newNode.parent = parent;
  2329. }
  2330. }
  2331. if (node.children) {
  2332. for (var i = 0; i < node.children.length; i++) {
  2333. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2334. }
  2335. }
  2336. };
  2337. /**
  2338. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2339. */
  2340. var postLoad = function (gltfRuntime) {
  2341. // Nodes
  2342. var currentScene = gltfRuntime.currentScene;
  2343. if (currentScene) {
  2344. for (var i = 0; i < currentScene.nodes.length; i++) {
  2345. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2346. }
  2347. }
  2348. else {
  2349. for (var thing in gltfRuntime.scenes) {
  2350. currentScene = gltfRuntime.scenes[thing];
  2351. for (var i = 0; i < currentScene.nodes.length; i++) {
  2352. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2353. }
  2354. }
  2355. }
  2356. // Set animations
  2357. loadAnimations(gltfRuntime);
  2358. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2359. var skeleton = gltfRuntime.scene.skeletons[i];
  2360. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2361. }
  2362. };
  2363. /**
  2364. * onBind shaderrs callback to set uniforms and matrices
  2365. */
  2366. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2367. var materialValues = material.values || technique.parameters;
  2368. for (var unif in unTreatedUniforms) {
  2369. var uniform = unTreatedUniforms[unif];
  2370. var type = uniform.type;
  2371. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  2372. if (uniform.semantic && !uniform.source && !uniform.node) {
  2373. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2374. }
  2375. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2376. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  2377. if (source === null) {
  2378. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  2379. }
  2380. if (source === null) {
  2381. continue;
  2382. }
  2383. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2384. }
  2385. }
  2386. else {
  2387. var value = materialValues[technique.uniforms[unif]];
  2388. if (!value) {
  2389. continue;
  2390. }
  2391. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2392. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2393. if (texture === null || texture === undefined) {
  2394. continue;
  2395. }
  2396. shaderMaterial.getEffect().setTexture(unif, texture);
  2397. }
  2398. else {
  2399. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  2400. }
  2401. }
  2402. }
  2403. onSuccess(shaderMaterial);
  2404. };
  2405. /**
  2406. * Prepare uniforms to send the only one time
  2407. * Loads the appropriate textures
  2408. */
  2409. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2410. var materialValues = material.values || technique.parameters;
  2411. var techniqueUniforms = technique.uniforms;
  2412. /**
  2413. * Prepare values here (not matrices)
  2414. */
  2415. for (var unif in unTreatedUniforms) {
  2416. var uniform = unTreatedUniforms[unif];
  2417. var type = uniform.type;
  2418. var value = materialValues[techniqueUniforms[unif]];
  2419. if (value === undefined) {
  2420. // In case the value is the same for all materials
  2421. value = uniform.value;
  2422. }
  2423. if (!value) {
  2424. continue;
  2425. }
  2426. var onLoadTexture = function (uniformName) {
  2427. return function (texture) {
  2428. if (uniform.value && uniformName) {
  2429. // Static uniform
  2430. shaderMaterial.setTexture(uniformName, texture);
  2431. delete unTreatedUniforms[uniformName];
  2432. }
  2433. };
  2434. };
  2435. // Texture (sampler2D)
  2436. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2437. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2438. }
  2439. else {
  2440. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2441. // Static uniform
  2442. delete unTreatedUniforms[unif];
  2443. }
  2444. }
  2445. }
  2446. };
  2447. /**
  2448. * Shader compilation failed
  2449. */
  2450. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2451. return function (effect, error) {
  2452. shaderMaterial.dispose(true);
  2453. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2454. };
  2455. };
  2456. /**
  2457. * Shader compilation success
  2458. */
  2459. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2460. return function (_) {
  2461. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2462. shaderMaterial.onBind = function (mesh) {
  2463. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2464. };
  2465. };
  2466. };
  2467. /**
  2468. * Returns the appropriate uniform if already handled by babylon
  2469. */
  2470. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2471. for (var unif in technique.uniforms) {
  2472. var uniform = technique.uniforms[unif];
  2473. var uniformParameter = technique.parameters[uniform];
  2474. if (tokenizer.currentIdentifier === unif) {
  2475. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2476. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2477. if (transformIndex !== -1) {
  2478. delete unTreatedUniforms[unif];
  2479. return babylonTransforms[transformIndex];
  2480. }
  2481. }
  2482. }
  2483. }
  2484. return tokenizer.currentIdentifier;
  2485. };
  2486. /**
  2487. * All shaders loaded. Create materials one by one
  2488. */
  2489. var importMaterials = function (gltfRuntime) {
  2490. // Create materials
  2491. for (var mat in gltfRuntime.materials) {
  2492. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2493. }
  2494. };
  2495. /**
  2496. * Implementation of the base glTF spec
  2497. */
  2498. var GLTFLoaderBase = /** @class */ (function () {
  2499. function GLTFLoaderBase() {
  2500. }
  2501. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2502. var gltfRuntime = {
  2503. extensions: {},
  2504. accessors: {},
  2505. buffers: {},
  2506. bufferViews: {},
  2507. meshes: {},
  2508. lights: {},
  2509. cameras: {},
  2510. nodes: {},
  2511. images: {},
  2512. textures: {},
  2513. shaders: {},
  2514. programs: {},
  2515. samplers: {},
  2516. techniques: {},
  2517. materials: {},
  2518. animations: {},
  2519. skins: {},
  2520. extensionsUsed: [],
  2521. scenes: {},
  2522. buffersCount: 0,
  2523. shaderscount: 0,
  2524. scene: scene,
  2525. rootUrl: rootUrl,
  2526. loadedBufferCount: 0,
  2527. loadedBufferViews: {},
  2528. loadedShaderCount: 0,
  2529. importOnlyMeshes: false,
  2530. dummyNodes: []
  2531. };
  2532. // Parse
  2533. if (parsedData.extensions) {
  2534. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2535. }
  2536. if (parsedData.extensionsUsed) {
  2537. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2538. }
  2539. if (parsedData.buffers) {
  2540. parseBuffers(parsedData.buffers, gltfRuntime);
  2541. }
  2542. if (parsedData.bufferViews) {
  2543. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2544. }
  2545. if (parsedData.accessors) {
  2546. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2547. }
  2548. if (parsedData.meshes) {
  2549. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2550. }
  2551. if (parsedData.lights) {
  2552. parseObject(parsedData.lights, "lights", gltfRuntime);
  2553. }
  2554. if (parsedData.cameras) {
  2555. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2556. }
  2557. if (parsedData.nodes) {
  2558. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2559. }
  2560. if (parsedData.images) {
  2561. parseObject(parsedData.images, "images", gltfRuntime);
  2562. }
  2563. if (parsedData.textures) {
  2564. parseObject(parsedData.textures, "textures", gltfRuntime);
  2565. }
  2566. if (parsedData.shaders) {
  2567. parseShaders(parsedData.shaders, gltfRuntime);
  2568. }
  2569. if (parsedData.programs) {
  2570. parseObject(parsedData.programs, "programs", gltfRuntime);
  2571. }
  2572. if (parsedData.samplers) {
  2573. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2574. }
  2575. if (parsedData.techniques) {
  2576. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2577. }
  2578. if (parsedData.materials) {
  2579. parseObject(parsedData.materials, "materials", gltfRuntime);
  2580. }
  2581. if (parsedData.animations) {
  2582. parseObject(parsedData.animations, "animations", gltfRuntime);
  2583. }
  2584. if (parsedData.skins) {
  2585. parseObject(parsedData.skins, "skins", gltfRuntime);
  2586. }
  2587. if (parsedData.scenes) {
  2588. gltfRuntime.scenes = parsedData.scenes;
  2589. }
  2590. if (parsedData.scene && parsedData.scenes) {
  2591. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2592. }
  2593. return gltfRuntime;
  2594. };
  2595. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2596. var buffer = gltfRuntime.buffers[id];
  2597. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  2598. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  2599. }
  2600. else {
  2601. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  2602. if (request) {
  2603. onError(request.status + " " + request.statusText);
  2604. }
  2605. });
  2606. }
  2607. };
  2608. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2609. var texture = gltfRuntime.textures[id];
  2610. if (!texture || !texture.source) {
  2611. onError("");
  2612. return;
  2613. }
  2614. if (texture.babylonTexture) {
  2615. onSuccess(null);
  2616. return;
  2617. }
  2618. var source = gltfRuntime.images[texture.source];
  2619. if (BABYLON.Tools.IsBase64(source.uri)) {
  2620. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  2621. }
  2622. else {
  2623. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  2624. if (request) {
  2625. onError(request.status + " " + request.statusText);
  2626. }
  2627. });
  2628. }
  2629. };
  2630. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2631. var texture = gltfRuntime.textures[id];
  2632. if (texture.babylonTexture) {
  2633. onSuccess(texture.babylonTexture);
  2634. return;
  2635. }
  2636. var sampler = gltfRuntime.samplers[texture.sampler];
  2637. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2638. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2639. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2640. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2641. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2642. var blob = new Blob([buffer]);
  2643. var blobURL = URL.createObjectURL(blob);
  2644. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2645. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2646. if (sampler.wrapS !== undefined) {
  2647. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2648. }
  2649. if (sampler.wrapT !== undefined) {
  2650. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2651. }
  2652. newTexture.name = id;
  2653. texture.babylonTexture = newTexture;
  2654. onSuccess(newTexture);
  2655. };
  2656. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2657. var shader = gltfRuntime.shaders[id];
  2658. if (BABYLON.Tools.IsBase64(shader.uri)) {
  2659. var shaderString = atob(shader.uri.split(",")[1]);
  2660. onSuccess(shaderString);
  2661. }
  2662. else {
  2663. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  2664. if (request) {
  2665. onError(request.status + " " + request.statusText);
  2666. }
  2667. });
  2668. }
  2669. };
  2670. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2671. var material = gltfRuntime.materials[id];
  2672. if (!material.technique) {
  2673. if (onError) {
  2674. onError("No technique found.");
  2675. }
  2676. return;
  2677. }
  2678. var technique = gltfRuntime.techniques[material.technique];
  2679. if (!technique) {
  2680. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2681. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2682. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2683. onSuccess(defaultMaterial);
  2684. return;
  2685. }
  2686. var program = gltfRuntime.programs[technique.program];
  2687. var states = technique.states;
  2688. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2689. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2690. var newVertexShader = "";
  2691. var newPixelShader = "";
  2692. var vertexTokenizer = new Tokenizer(vertexShader);
  2693. var pixelTokenizer = new Tokenizer(pixelShader);
  2694. var unTreatedUniforms = {};
  2695. var uniforms = [];
  2696. var attributes = [];
  2697. var samplers = [];
  2698. // Fill uniform, sampler2D and attributes
  2699. for (var unif in technique.uniforms) {
  2700. var uniform = technique.uniforms[unif];
  2701. var uniformParameter = technique.parameters[uniform];
  2702. unTreatedUniforms[unif] = uniformParameter;
  2703. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2704. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2705. if (transformIndex !== -1) {
  2706. uniforms.push(babylonTransforms[transformIndex]);
  2707. delete unTreatedUniforms[unif];
  2708. }
  2709. else {
  2710. uniforms.push(unif);
  2711. }
  2712. }
  2713. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2714. samplers.push(unif);
  2715. }
  2716. else {
  2717. uniforms.push(unif);
  2718. }
  2719. }
  2720. for (var attr in technique.attributes) {
  2721. var attribute = technique.attributes[attr];
  2722. var attributeParameter = technique.parameters[attribute];
  2723. if (attributeParameter.semantic) {
  2724. attributes.push(getAttribute(attributeParameter));
  2725. }
  2726. }
  2727. // Configure vertex shader
  2728. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2729. var tokenType = vertexTokenizer.currentToken;
  2730. if (tokenType !== ETokenType.IDENTIFIER) {
  2731. newVertexShader += vertexTokenizer.currentString;
  2732. continue;
  2733. }
  2734. var foundAttribute = false;
  2735. for (var attr in technique.attributes) {
  2736. var attribute = technique.attributes[attr];
  2737. var attributeParameter = technique.parameters[attribute];
  2738. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2739. newVertexShader += getAttribute(attributeParameter);
  2740. foundAttribute = true;
  2741. break;
  2742. }
  2743. }
  2744. if (foundAttribute) {
  2745. continue;
  2746. }
  2747. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2748. }
  2749. // Configure pixel shader
  2750. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2751. var tokenType = pixelTokenizer.currentToken;
  2752. if (tokenType !== ETokenType.IDENTIFIER) {
  2753. newPixelShader += pixelTokenizer.currentString;
  2754. continue;
  2755. }
  2756. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2757. }
  2758. // Create shader material
  2759. var shaderPath = {
  2760. vertex: program.vertexShader + id,
  2761. fragment: program.fragmentShader + id
  2762. };
  2763. var options = {
  2764. attributes: attributes,
  2765. uniforms: uniforms,
  2766. samplers: samplers,
  2767. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2768. };
  2769. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2770. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2771. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2772. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2773. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2774. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2775. if (states && states.functions) {
  2776. var functions = states.functions;
  2777. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2778. shaderMaterial.backFaceCulling = false;
  2779. }
  2780. var blendFunc = functions.blendFuncSeparate;
  2781. if (blendFunc) {
  2782. 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) {
  2783. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2784. }
  2785. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2786. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2787. }
  2788. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2789. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2790. }
  2791. 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) {
  2792. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2793. }
  2794. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2795. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2796. }
  2797. 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) {
  2798. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2799. }
  2800. }
  2801. }
  2802. };
  2803. return GLTFLoaderBase;
  2804. }());
  2805. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2806. /**
  2807. * glTF V1 Loader
  2808. */
  2809. var GLTFLoader = /** @class */ (function () {
  2810. function GLTFLoader() {
  2811. // #region Stubs for IGLTFLoader interface
  2812. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2813. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2814. this.compileMaterials = false;
  2815. this.useClipPlane = false;
  2816. this.compileShadowGenerators = false;
  2817. this.onDisposeObservable = new BABYLON.Observable();
  2818. this.onMeshLoadedObservable = new BABYLON.Observable();
  2819. this.onTextureLoadedObservable = new BABYLON.Observable();
  2820. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2821. this.onCompleteObservable = new BABYLON.Observable();
  2822. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2823. this.state = null;
  2824. }
  2825. GLTFLoader.RegisterExtension = function (extension) {
  2826. if (GLTFLoader.Extensions[extension.name]) {
  2827. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2828. return;
  2829. }
  2830. GLTFLoader.Extensions[extension.name] = extension;
  2831. };
  2832. GLTFLoader.prototype.dispose = function () { };
  2833. // #endregion
  2834. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2835. var _this = this;
  2836. scene.useRightHandedSystem = true;
  2837. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2838. gltfRuntime.importOnlyMeshes = true;
  2839. if (meshesNames === "") {
  2840. gltfRuntime.importMeshesNames = [];
  2841. }
  2842. else if (typeof meshesNames === "string") {
  2843. gltfRuntime.importMeshesNames = [meshesNames];
  2844. }
  2845. else if (meshesNames && !(meshesNames instanceof Array)) {
  2846. gltfRuntime.importMeshesNames = [meshesNames];
  2847. }
  2848. else {
  2849. gltfRuntime.importMeshesNames = [];
  2850. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2851. }
  2852. // Create nodes
  2853. _this._createNodes(gltfRuntime);
  2854. var meshes = new Array();
  2855. var skeletons = new Array();
  2856. // Fill arrays of meshes and skeletons
  2857. for (var nde in gltfRuntime.nodes) {
  2858. var node = gltfRuntime.nodes[nde];
  2859. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2860. meshes.push(node.babylonNode);
  2861. }
  2862. }
  2863. for (var skl in gltfRuntime.skins) {
  2864. var skin = gltfRuntime.skins[skl];
  2865. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2866. skeletons.push(skin.babylonSkeleton);
  2867. }
  2868. }
  2869. // Load buffers, shaders, materials, etc.
  2870. _this._loadBuffersAsync(gltfRuntime, function () {
  2871. _this._loadShadersAsync(gltfRuntime, function () {
  2872. importMaterials(gltfRuntime);
  2873. postLoad(gltfRuntime);
  2874. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2875. onSuccess(meshes, [], skeletons);
  2876. }
  2877. });
  2878. }, onProgress);
  2879. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2880. onSuccess(meshes, [], skeletons);
  2881. }
  2882. }, onError);
  2883. return true;
  2884. };
  2885. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2886. var _this = this;
  2887. return new Promise(function (resolve, reject) {
  2888. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  2889. resolve({
  2890. meshes: meshes,
  2891. particleSystems: particleSystems,
  2892. skeletons: skeletons
  2893. });
  2894. }, onProgress, function (message) {
  2895. reject(new Error(message));
  2896. });
  2897. });
  2898. };
  2899. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2900. var _this = this;
  2901. scene.useRightHandedSystem = true;
  2902. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2903. // Load runtime extensios
  2904. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2905. // Create nodes
  2906. _this._createNodes(gltfRuntime);
  2907. // Load buffers, shaders, materials, etc.
  2908. _this._loadBuffersAsync(gltfRuntime, function () {
  2909. _this._loadShadersAsync(gltfRuntime, function () {
  2910. importMaterials(gltfRuntime);
  2911. postLoad(gltfRuntime);
  2912. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2913. onSuccess();
  2914. }
  2915. });
  2916. });
  2917. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2918. onSuccess();
  2919. }
  2920. }, onError);
  2921. }, onError);
  2922. };
  2923. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2924. var _this = this;
  2925. return new Promise(function (resolve, reject) {
  2926. _this._loadAsync(scene, data, rootUrl, function () {
  2927. resolve();
  2928. }, onProgress, function (message) {
  2929. reject(new Error(message));
  2930. });
  2931. });
  2932. };
  2933. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2934. var hasShaders = false;
  2935. var processShader = function (sha, shader) {
  2936. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2937. gltfRuntime.loadedShaderCount++;
  2938. if (shaderString) {
  2939. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2940. }
  2941. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2942. onload();
  2943. }
  2944. }, function () {
  2945. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2946. });
  2947. };
  2948. for (var sha in gltfRuntime.shaders) {
  2949. hasShaders = true;
  2950. var shader = gltfRuntime.shaders[sha];
  2951. if (shader) {
  2952. processShader.bind(this, sha, shader)();
  2953. }
  2954. else {
  2955. BABYLON.Tools.Error("No shader named: " + sha);
  2956. }
  2957. }
  2958. if (!hasShaders) {
  2959. onload();
  2960. }
  2961. };
  2962. ;
  2963. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2964. var hasBuffers = false;
  2965. var processBuffer = function (buf, buffer) {
  2966. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2967. gltfRuntime.loadedBufferCount++;
  2968. if (bufferView) {
  2969. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2970. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2971. }
  2972. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2973. }
  2974. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2975. onLoad();
  2976. }
  2977. }, function () {
  2978. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2979. });
  2980. };
  2981. for (var buf in gltfRuntime.buffers) {
  2982. hasBuffers = true;
  2983. var buffer = gltfRuntime.buffers[buf];
  2984. if (buffer) {
  2985. processBuffer.bind(this, buf, buffer)();
  2986. }
  2987. else {
  2988. BABYLON.Tools.Error("No buffer named: " + buf);
  2989. }
  2990. }
  2991. if (!hasBuffers) {
  2992. onLoad();
  2993. }
  2994. };
  2995. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2996. var currentScene = gltfRuntime.currentScene;
  2997. if (currentScene) {
  2998. // Only one scene even if multiple scenes are defined
  2999. for (var i = 0; i < currentScene.nodes.length; i++) {
  3000. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3001. }
  3002. }
  3003. else {
  3004. // Load all scenes
  3005. for (var thing in gltfRuntime.scenes) {
  3006. currentScene = gltfRuntime.scenes[thing];
  3007. for (var i = 0; i < currentScene.nodes.length; i++) {
  3008. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3009. }
  3010. }
  3011. }
  3012. };
  3013. GLTFLoader.Extensions = {};
  3014. return GLTFLoader;
  3015. }());
  3016. GLTF1.GLTFLoader = GLTFLoader;
  3017. ;
  3018. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  3019. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3020. })(BABYLON || (BABYLON = {}));
  3021. //# sourceMappingURL=babylon.glTFLoader.js.map
  3022. var BABYLON;
  3023. (function (BABYLON) {
  3024. var GLTF1;
  3025. (function (GLTF1) {
  3026. /**
  3027. * Utils functions for GLTF
  3028. */
  3029. var GLTFUtils = /** @class */ (function () {
  3030. function GLTFUtils() {
  3031. }
  3032. /**
  3033. * Sets the given "parameter" matrix
  3034. * @param scene: the {BABYLON.Scene} object
  3035. * @param source: the source node where to pick the matrix
  3036. * @param parameter: the GLTF technique parameter
  3037. * @param uniformName: the name of the shader's uniform
  3038. * @param shaderMaterial: the shader material
  3039. */
  3040. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  3041. var mat = null;
  3042. if (parameter.semantic === "MODEL") {
  3043. mat = source.getWorldMatrix();
  3044. }
  3045. else if (parameter.semantic === "PROJECTION") {
  3046. mat = scene.getProjectionMatrix();
  3047. }
  3048. else if (parameter.semantic === "VIEW") {
  3049. mat = scene.getViewMatrix();
  3050. }
  3051. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  3052. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  3053. }
  3054. else if (parameter.semantic === "MODELVIEW") {
  3055. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  3056. }
  3057. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  3058. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  3059. }
  3060. else if (parameter.semantic === "MODELINVERSE") {
  3061. mat = source.getWorldMatrix().invert();
  3062. }
  3063. else if (parameter.semantic === "VIEWINVERSE") {
  3064. mat = scene.getViewMatrix().invert();
  3065. }
  3066. else if (parameter.semantic === "PROJECTIONINVERSE") {
  3067. mat = scene.getProjectionMatrix().invert();
  3068. }
  3069. else if (parameter.semantic === "MODELVIEWINVERSE") {
  3070. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  3071. }
  3072. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  3073. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  3074. }
  3075. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  3076. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  3077. }
  3078. else {
  3079. debugger;
  3080. }
  3081. if (mat) {
  3082. switch (parameter.type) {
  3083. case GLTF1.EParameterType.FLOAT_MAT2:
  3084. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  3085. break;
  3086. case GLTF1.EParameterType.FLOAT_MAT3:
  3087. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  3088. break;
  3089. case GLTF1.EParameterType.FLOAT_MAT4:
  3090. shaderMaterial.setMatrix(uniformName, mat);
  3091. break;
  3092. default: break;
  3093. }
  3094. }
  3095. };
  3096. /**
  3097. * Sets the given "parameter" matrix
  3098. * @param shaderMaterial: the shader material
  3099. * @param uniform: the name of the shader's uniform
  3100. * @param value: the value of the uniform
  3101. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  3102. */
  3103. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  3104. switch (type) {
  3105. case GLTF1.EParameterType.FLOAT:
  3106. shaderMaterial.setFloat(uniform, value);
  3107. return true;
  3108. case GLTF1.EParameterType.FLOAT_VEC2:
  3109. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  3110. return true;
  3111. case GLTF1.EParameterType.FLOAT_VEC3:
  3112. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  3113. return true;
  3114. case GLTF1.EParameterType.FLOAT_VEC4:
  3115. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  3116. return true;
  3117. default: return false;
  3118. }
  3119. };
  3120. /**
  3121. * Returns the wrap mode of the texture
  3122. * @param mode: the mode value
  3123. */
  3124. GLTFUtils.GetWrapMode = function (mode) {
  3125. switch (mode) {
  3126. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3127. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3128. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3129. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3130. }
  3131. };
  3132. /**
  3133. * Returns the byte stride giving an accessor
  3134. * @param accessor: the GLTF accessor objet
  3135. */
  3136. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3137. // Needs this function since "byteStride" isn't requiered in glTF format
  3138. var type = accessor.type;
  3139. switch (type) {
  3140. case "VEC2": return 2;
  3141. case "VEC3": return 3;
  3142. case "VEC4": return 4;
  3143. case "MAT2": return 4;
  3144. case "MAT3": return 9;
  3145. case "MAT4": return 16;
  3146. default: return 1;
  3147. }
  3148. };
  3149. /**
  3150. * Returns the texture filter mode giving a mode value
  3151. * @param mode: the filter mode value
  3152. */
  3153. GLTFUtils.GetTextureFilterMode = function (mode) {
  3154. switch (mode) {
  3155. case GLTF1.ETextureFilterType.LINEAR:
  3156. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  3157. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3158. case GLTF1.ETextureFilterType.NEAREST:
  3159. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3160. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3161. }
  3162. };
  3163. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  3164. var byteOffset = bufferView.byteOffset + byteOffset;
  3165. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  3166. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3167. throw new Error("Buffer access is out of range");
  3168. }
  3169. var buffer = loadedBufferView.buffer;
  3170. byteOffset += loadedBufferView.byteOffset;
  3171. switch (componentType) {
  3172. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3173. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3174. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3175. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3176. default: return new Float32Array(buffer, byteOffset, byteLength);
  3177. }
  3178. };
  3179. /**
  3180. * Returns a buffer from its accessor
  3181. * @param gltfRuntime: the GLTF runtime
  3182. * @param accessor: the GLTF accessor
  3183. */
  3184. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  3185. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  3186. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3187. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  3188. };
  3189. /**
  3190. * Decodes a buffer view into a string
  3191. * @param view: the buffer view
  3192. */
  3193. GLTFUtils.DecodeBufferToText = function (view) {
  3194. var result = "";
  3195. var length = view.byteLength;
  3196. for (var i = 0; i < length; ++i) {
  3197. result += String.fromCharCode(view[i]);
  3198. }
  3199. return result;
  3200. };
  3201. /**
  3202. * Returns the default material of gltf. Related to
  3203. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  3204. * @param scene: the Babylon.js scene
  3205. */
  3206. GLTFUtils.GetDefaultMaterial = function (scene) {
  3207. if (!GLTFUtils._DefaultMaterial) {
  3208. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  3209. "precision highp float;",
  3210. "",
  3211. "uniform mat4 worldView;",
  3212. "uniform mat4 projection;",
  3213. "",
  3214. "attribute vec3 position;",
  3215. "",
  3216. "void main(void)",
  3217. "{",
  3218. " gl_Position = projection * worldView * vec4(position, 1.0);",
  3219. "}"
  3220. ].join("\n");
  3221. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  3222. "precision highp float;",
  3223. "",
  3224. "uniform vec4 u_emission;",
  3225. "",
  3226. "void main(void)",
  3227. "{",
  3228. " gl_FragColor = u_emission;",
  3229. "}"
  3230. ].join("\n");
  3231. var shaderPath = {
  3232. vertex: "GLTFDefaultMaterial",
  3233. fragment: "GLTFDefaultMaterial"
  3234. };
  3235. var options = {
  3236. attributes: ["position"],
  3237. uniforms: ["worldView", "projection", "u_emission"],
  3238. samplers: new Array(),
  3239. needAlphaBlending: false
  3240. };
  3241. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  3242. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  3243. }
  3244. return GLTFUtils._DefaultMaterial;
  3245. };
  3246. // The GLTF default material
  3247. GLTFUtils._DefaultMaterial = null;
  3248. return GLTFUtils;
  3249. }());
  3250. GLTF1.GLTFUtils = GLTFUtils;
  3251. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3252. })(BABYLON || (BABYLON = {}));
  3253. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. var GLTF1;
  3257. (function (GLTF1) {
  3258. var GLTFLoaderExtension = /** @class */ (function () {
  3259. function GLTFLoaderExtension(name) {
  3260. this._name = name;
  3261. }
  3262. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3263. get: function () {
  3264. return this._name;
  3265. },
  3266. enumerable: true,
  3267. configurable: true
  3268. });
  3269. /**
  3270. * Defines an override for loading the runtime
  3271. * Return true to stop further extensions from loading the runtime
  3272. */
  3273. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3274. return false;
  3275. };
  3276. /**
  3277. * Defines an onverride for creating gltf runtime
  3278. * Return true to stop further extensions from creating the runtime
  3279. */
  3280. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3281. return false;
  3282. };
  3283. /**
  3284. * Defines an override for loading buffers
  3285. * Return true to stop further extensions from loading this buffer
  3286. */
  3287. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3288. return false;
  3289. };
  3290. /**
  3291. * Defines an override for loading texture buffers
  3292. * Return true to stop further extensions from loading this texture data
  3293. */
  3294. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3295. return false;
  3296. };
  3297. /**
  3298. * Defines an override for creating textures
  3299. * Return true to stop further extensions from loading this texture
  3300. */
  3301. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3302. return false;
  3303. };
  3304. /**
  3305. * Defines an override for loading shader strings
  3306. * Return true to stop further extensions from loading this shader data
  3307. */
  3308. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3309. return false;
  3310. };
  3311. /**
  3312. * Defines an override for loading materials
  3313. * Return true to stop further extensions from loading this material
  3314. */
  3315. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3316. return false;
  3317. };
  3318. // ---------
  3319. // Utilities
  3320. // ---------
  3321. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3322. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3323. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3324. }, function () {
  3325. setTimeout(function () {
  3326. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3327. });
  3328. });
  3329. };
  3330. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3331. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3332. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3333. }, function () {
  3334. setTimeout(function () {
  3335. onSuccess();
  3336. });
  3337. });
  3338. };
  3339. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3340. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3341. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3342. }, function () {
  3343. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3344. });
  3345. };
  3346. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3347. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  3348. };
  3349. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3350. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3351. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3352. }, function () {
  3353. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3354. });
  3355. };
  3356. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3357. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3358. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3359. }, function () {
  3360. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3361. });
  3362. };
  3363. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3364. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3365. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3366. }, function () {
  3367. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3368. });
  3369. };
  3370. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3371. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3372. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3373. }, function () {
  3374. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3375. });
  3376. };
  3377. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3378. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  3379. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  3380. if (func(loaderExtension)) {
  3381. return;
  3382. }
  3383. }
  3384. defaultFunc();
  3385. };
  3386. return GLTFLoaderExtension;
  3387. }());
  3388. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  3389. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3390. })(BABYLON || (BABYLON = {}));
  3391. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3392. var BABYLON;
  3393. (function (BABYLON) {
  3394. var GLTF1;
  3395. (function (GLTF1) {
  3396. var BinaryExtensionBufferName = "binary_glTF";
  3397. ;
  3398. ;
  3399. var GLTFBinaryExtension = /** @class */ (function (_super) {
  3400. __extends(GLTFBinaryExtension, _super);
  3401. function GLTFBinaryExtension() {
  3402. return _super.call(this, "KHR_binary_glTF") || this;
  3403. }
  3404. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3405. var extensionsUsed = data.json.extensionsUsed;
  3406. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  3407. return false;
  3408. }
  3409. this._bin = data.bin;
  3410. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3411. return true;
  3412. };
  3413. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3414. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  3415. return false;
  3416. }
  3417. if (id !== BinaryExtensionBufferName) {
  3418. return false;
  3419. }
  3420. onSuccess(this._bin);
  3421. return true;
  3422. };
  3423. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3424. var texture = gltfRuntime.textures[id];
  3425. var source = gltfRuntime.images[texture.source];
  3426. if (!source.extensions || !(this.name in source.extensions)) {
  3427. return false;
  3428. }
  3429. var sourceExt = source.extensions[this.name];
  3430. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  3431. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3432. onSuccess(buffer);
  3433. return true;
  3434. };
  3435. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3436. var shader = gltfRuntime.shaders[id];
  3437. if (!shader.extensions || !(this.name in shader.extensions)) {
  3438. return false;
  3439. }
  3440. var binaryExtensionShader = shader.extensions[this.name];
  3441. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  3442. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3443. setTimeout(function () {
  3444. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  3445. onSuccess(shaderString);
  3446. });
  3447. return true;
  3448. };
  3449. return GLTFBinaryExtension;
  3450. }(GLTF1.GLTFLoaderExtension));
  3451. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  3452. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  3453. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3454. })(BABYLON || (BABYLON = {}));
  3455. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  3456. var BABYLON;
  3457. (function (BABYLON) {
  3458. var GLTF1;
  3459. (function (GLTF1) {
  3460. ;
  3461. ;
  3462. ;
  3463. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3464. __extends(GLTFMaterialsCommonExtension, _super);
  3465. function GLTFMaterialsCommonExtension() {
  3466. return _super.call(this, "KHR_materials_common") || this;
  3467. }
  3468. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3469. if (!gltfRuntime.extensions)
  3470. return false;
  3471. var extension = gltfRuntime.extensions[this.name];
  3472. if (!extension)
  3473. return false;
  3474. // Create lights
  3475. var lights = extension.lights;
  3476. if (lights) {
  3477. for (var thing in lights) {
  3478. var light = lights[thing];
  3479. switch (light.type) {
  3480. case "ambient":
  3481. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  3482. var ambient = light.ambient;
  3483. if (ambient) {
  3484. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  3485. }
  3486. break;
  3487. case "point":
  3488. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  3489. var point = light.point;
  3490. if (point) {
  3491. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  3492. }
  3493. break;
  3494. case "directional":
  3495. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  3496. var directional = light.directional;
  3497. if (directional) {
  3498. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  3499. }
  3500. break;
  3501. case "spot":
  3502. var spot = light.spot;
  3503. if (spot) {
  3504. 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);
  3505. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  3506. }
  3507. break;
  3508. default:
  3509. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3510. break;
  3511. }
  3512. }
  3513. }
  3514. return false;
  3515. };
  3516. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3517. var material = gltfRuntime.materials[id];
  3518. if (!material || !material.extensions)
  3519. return false;
  3520. var extension = material.extensions[this.name];
  3521. if (!extension)
  3522. return false;
  3523. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3524. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3525. if (extension.technique === "CONSTANT") {
  3526. standardMaterial.disableLighting = true;
  3527. }
  3528. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3529. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3530. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3531. // Ambient
  3532. if (typeof extension.values.ambient === "string") {
  3533. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3534. }
  3535. else {
  3536. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3537. }
  3538. // Diffuse
  3539. if (typeof extension.values.diffuse === "string") {
  3540. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3541. }
  3542. else {
  3543. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3544. }
  3545. // Emission
  3546. if (typeof extension.values.emission === "string") {
  3547. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3548. }
  3549. else {
  3550. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3551. }
  3552. // Specular
  3553. if (typeof extension.values.specular === "string") {
  3554. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3555. }
  3556. else {
  3557. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3558. }
  3559. return true;
  3560. };
  3561. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3562. // Create buffer from texture url
  3563. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3564. // Create texture from buffer
  3565. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3566. }, onError);
  3567. };
  3568. return GLTFMaterialsCommonExtension;
  3569. }(GLTF1.GLTFLoaderExtension));
  3570. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3571. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3572. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3573. })(BABYLON || (BABYLON = {}));
  3574. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  3575. var BABYLON;
  3576. (function (BABYLON) {
  3577. var GLTF2;
  3578. (function (GLTF2) {
  3579. var ArrayItem = /** @class */ (function () {
  3580. function ArrayItem() {
  3581. }
  3582. ArrayItem.Assign = function (values) {
  3583. if (values) {
  3584. for (var index = 0; index < values.length; index++) {
  3585. values[index]._index = index;
  3586. }
  3587. }
  3588. };
  3589. return ArrayItem;
  3590. }());
  3591. GLTF2.ArrayItem = ArrayItem;
  3592. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3593. })(BABYLON || (BABYLON = {}));
  3594. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  3595. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  3596. var BABYLON;
  3597. (function (BABYLON) {
  3598. var GLTF2;
  3599. (function (GLTF2) {
  3600. var GLTFLoader = /** @class */ (function () {
  3601. function GLTFLoader() {
  3602. this._completePromises = new Array();
  3603. this._disposed = false;
  3604. this._state = null;
  3605. this._extensions = {};
  3606. this._defaultSampler = {};
  3607. this._requests = new Array();
  3608. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  3609. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  3610. this.compileMaterials = false;
  3611. this.useClipPlane = false;
  3612. this.compileShadowGenerators = false;
  3613. this.onDisposeObservable = new BABYLON.Observable();
  3614. this.onMeshLoadedObservable = new BABYLON.Observable();
  3615. this.onTextureLoadedObservable = new BABYLON.Observable();
  3616. this.onMaterialLoadedObservable = new BABYLON.Observable();
  3617. this.onExtensionLoadedObservable = new BABYLON.Observable();
  3618. this.onCompleteObservable = new BABYLON.Observable();
  3619. }
  3620. GLTFLoader._Register = function (name, factory) {
  3621. if (GLTFLoader._Factories[name]) {
  3622. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  3623. return;
  3624. }
  3625. GLTFLoader._Factories[name] = factory;
  3626. // Keep the order of registration so that extensions registered first are called first.
  3627. GLTFLoader._Names.push(name);
  3628. };
  3629. Object.defineProperty(GLTFLoader.prototype, "state", {
  3630. get: function () {
  3631. return this._state;
  3632. },
  3633. enumerable: true,
  3634. configurable: true
  3635. });
  3636. GLTFLoader.prototype.dispose = function () {
  3637. if (this._disposed) {
  3638. return;
  3639. }
  3640. this._disposed = true;
  3641. this.onDisposeObservable.notifyObservers(this);
  3642. this.onDisposeObservable.clear();
  3643. this._clear();
  3644. };
  3645. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  3646. var _this = this;
  3647. return Promise.resolve().then(function () {
  3648. var nodes = null;
  3649. if (meshesNames) {
  3650. var nodeMap_1 = {};
  3651. if (_this._gltf.nodes) {
  3652. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  3653. var node = _a[_i];
  3654. if (node.name) {
  3655. nodeMap_1[node.name] = node;
  3656. }
  3657. }
  3658. }
  3659. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  3660. nodes = names.map(function (name) {
  3661. var node = nodeMap_1[name];
  3662. if (!node) {
  3663. throw new Error("Failed to find node " + name);
  3664. }
  3665. return node;
  3666. });
  3667. }
  3668. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  3669. return {
  3670. meshes: _this._getMeshes(),
  3671. particleSystems: [],
  3672. skeletons: _this._getSkeletons(),
  3673. };
  3674. });
  3675. });
  3676. };
  3677. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  3678. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  3679. };
  3680. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  3681. var _this = this;
  3682. return Promise.resolve().then(function () {
  3683. _this._loadExtensions();
  3684. _this._babylonScene = scene;
  3685. _this._rootUrl = rootUrl;
  3686. _this._progressCallback = onProgress;
  3687. _this._state = BABYLON.GLTFLoaderState.Loading;
  3688. _this._loadData(data);
  3689. _this._checkExtensions();
  3690. var promises = new Array();
  3691. if (nodes) {
  3692. promises.push(_this._loadNodesAsync(nodes));
  3693. }
  3694. else {
  3695. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  3696. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  3697. }
  3698. if (_this.compileMaterials) {
  3699. promises.push(_this._compileMaterialsAsync());
  3700. }
  3701. if (_this.compileShadowGenerators) {
  3702. promises.push(_this._compileShadowGeneratorsAsync());
  3703. }
  3704. return Promise.all(promises).then(function () {
  3705. _this._state = BABYLON.GLTFLoaderState.Ready;
  3706. _this._startAnimations();
  3707. BABYLON.Tools.SetImmediate(function () {
  3708. if (!_this._disposed) {
  3709. Promise.all(_this._completePromises).then(function () {
  3710. _this._state = BABYLON.GLTFLoaderState.Complete;
  3711. _this.onCompleteObservable.notifyObservers(_this);
  3712. _this.onCompleteObservable.clear();
  3713. _this._clear();
  3714. }).catch(function (error) {
  3715. BABYLON.Tools.Error("glTF Loader: " + error.message);
  3716. _this._clear();
  3717. });
  3718. }
  3719. });
  3720. });
  3721. }).catch(function (error) {
  3722. BABYLON.Tools.Error("glTF Loader: " + error.message);
  3723. _this._clear();
  3724. throw error;
  3725. });
  3726. };
  3727. GLTFLoader.prototype._loadExtensions = function () {
  3728. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  3729. var name_1 = _a[_i];
  3730. var extension = GLTFLoader._Factories[name_1](this);
  3731. this._extensions[name_1] = extension;
  3732. this.onExtensionLoadedObservable.notifyObservers(extension);
  3733. }
  3734. this.onExtensionLoadedObservable.clear();
  3735. };
  3736. GLTFLoader.prototype._loadData = function (data) {
  3737. this._gltf = data.json;
  3738. this._setupData();
  3739. if (data.bin) {
  3740. var buffers = this._gltf.buffers;
  3741. if (buffers && buffers[0] && !buffers[0].uri) {
  3742. var binaryBuffer = buffers[0];
  3743. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  3744. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3745. }
  3746. binaryBuffer._data = Promise.resolve(data.bin);
  3747. }
  3748. else {
  3749. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3750. }
  3751. }
  3752. };
  3753. GLTFLoader.prototype._setupData = function () {
  3754. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  3755. GLTF2.ArrayItem.Assign(this._gltf.animations);
  3756. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  3757. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  3758. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  3759. GLTF2.ArrayItem.Assign(this._gltf.images);
  3760. GLTF2.ArrayItem.Assign(this._gltf.materials);
  3761. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  3762. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  3763. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  3764. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  3765. GLTF2.ArrayItem.Assign(this._gltf.skins);
  3766. GLTF2.ArrayItem.Assign(this._gltf.textures);
  3767. if (this._gltf.nodes) {
  3768. var nodeParents = {};
  3769. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  3770. var node = _a[_i];
  3771. if (node.children) {
  3772. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  3773. var index = _c[_b];
  3774. nodeParents[index] = node._index;
  3775. }
  3776. }
  3777. }
  3778. var rootNode = this._createRootNode();
  3779. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  3780. var node = _e[_d];
  3781. var parentIndex = nodeParents[node._index];
  3782. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  3783. }
  3784. }
  3785. };
  3786. GLTFLoader.prototype._checkExtensions = function () {
  3787. if (this._gltf.extensionsRequired) {
  3788. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  3789. var name_2 = _a[_i];
  3790. var extension = this._extensions[name_2];
  3791. if (!extension || !extension.enabled) {
  3792. throw new Error("Require extension " + name_2 + " is not available");
  3793. }
  3794. }
  3795. }
  3796. };
  3797. GLTFLoader.prototype._createRootNode = function () {
  3798. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  3799. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  3800. switch (this.coordinateSystemMode) {
  3801. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  3802. if (!this._babylonScene.useRightHandedSystem) {
  3803. rootNode.rotation = [0, 1, 0, 0];
  3804. rootNode.scale = [1, 1, -1];
  3805. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  3806. }
  3807. break;
  3808. }
  3809. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  3810. this._babylonScene.useRightHandedSystem = true;
  3811. break;
  3812. }
  3813. default: {
  3814. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  3815. }
  3816. }
  3817. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  3818. return rootNode;
  3819. };
  3820. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  3821. var promises = new Array();
  3822. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  3823. var node = nodes_1[_i];
  3824. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  3825. }
  3826. promises.push(this._loadAnimationsAsync());
  3827. return Promise.all(promises).then(function () { });
  3828. };
  3829. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  3830. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  3831. if (promise) {
  3832. return promise;
  3833. }
  3834. var promises = new Array();
  3835. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  3836. var index = _a[_i];
  3837. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  3838. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  3839. }
  3840. promises.push(this._loadAnimationsAsync());
  3841. return Promise.all(promises).then(function () { });
  3842. };
  3843. GLTFLoader.prototype._getMeshes = function () {
  3844. var meshes = new Array();
  3845. // Root mesh is always first.
  3846. meshes.push(this._rootBabylonMesh);
  3847. var nodes = this._gltf.nodes;
  3848. if (nodes) {
  3849. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  3850. var node = nodes_2[_i];
  3851. if (node._babylonMesh) {
  3852. meshes.push(node._babylonMesh);
  3853. }
  3854. if (node._primitiveBabylonMeshes) {
  3855. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  3856. var babylonMesh = _b[_a];
  3857. meshes.push(babylonMesh);
  3858. }
  3859. }
  3860. }
  3861. }
  3862. return meshes;
  3863. };
  3864. GLTFLoader.prototype._getSkeletons = function () {
  3865. var skeletons = new Array();
  3866. var skins = this._gltf.skins;
  3867. if (skins) {
  3868. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  3869. var skin = skins_1[_i];
  3870. if (skin._babylonSkeleton) {
  3871. skeletons.push(skin._babylonSkeleton);
  3872. }
  3873. }
  3874. }
  3875. return skeletons;
  3876. };
  3877. GLTFLoader.prototype._startAnimations = function () {
  3878. var animations = this._gltf.animations;
  3879. if (!animations) {
  3880. return;
  3881. }
  3882. switch (this.animationStartMode) {
  3883. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  3884. // do nothing
  3885. break;
  3886. }
  3887. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  3888. var animation = animations[0];
  3889. animation._babylonAnimationGroup.start(true);
  3890. break;
  3891. }
  3892. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  3893. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  3894. var animation = animations_1[_i];
  3895. animation._babylonAnimationGroup.start(true);
  3896. }
  3897. break;
  3898. }
  3899. default: {
  3900. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  3901. return;
  3902. }
  3903. }
  3904. };
  3905. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  3906. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  3907. if (promise) {
  3908. return promise;
  3909. }
  3910. if (node._babylonMesh) {
  3911. throw new Error(context + ": Invalid recursive node hierarchy");
  3912. }
  3913. var promises = new Array();
  3914. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  3915. node._babylonMesh = babylonMesh;
  3916. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3917. node._babylonAnimationTargets.push(babylonMesh);
  3918. GLTFLoader._LoadTransform(node, babylonMesh);
  3919. if (node.mesh != undefined) {
  3920. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  3921. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  3922. }
  3923. if (node.children) {
  3924. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3925. var index = _a[_i];
  3926. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  3927. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  3928. }
  3929. }
  3930. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3931. return Promise.all(promises).then(function () { });
  3932. };
  3933. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  3934. // TODO: instancing
  3935. var promises = new Array();
  3936. var primitives = mesh.primitives;
  3937. if (!primitives || primitives.length === 0) {
  3938. throw new Error(context + ": Primitives are missing");
  3939. }
  3940. GLTF2.ArrayItem.Assign(primitives);
  3941. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3942. var primitive = primitives_1[_i];
  3943. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  3944. }
  3945. if (node.skin != undefined) {
  3946. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  3947. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  3948. }
  3949. return Promise.all(promises).then(function () {
  3950. if (node._primitiveBabylonMeshes) {
  3951. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3952. var primitiveBabylonMesh = _a[_i];
  3953. primitiveBabylonMesh._refreshBoundingInfo(true);
  3954. }
  3955. }
  3956. });
  3957. };
  3958. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  3959. var _this = this;
  3960. var promises = new Array();
  3961. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  3962. babylonMesh.setEnabled(false);
  3963. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  3964. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  3965. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3966. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  3967. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  3968. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  3969. }));
  3970. if (primitive.material == undefined) {
  3971. babylonMesh.material = this._getDefaultMaterial();
  3972. }
  3973. else {
  3974. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  3975. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  3976. }
  3977. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3978. return Promise.all(promises).then(function () {
  3979. babylonMesh.setEnabled(true);
  3980. });
  3981. };
  3982. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3983. var _this = this;
  3984. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  3985. if (promise) {
  3986. return promise;
  3987. }
  3988. var attributes = primitive.attributes;
  3989. if (!attributes) {
  3990. throw new Error(context + ": Attributes are missing");
  3991. }
  3992. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  3993. // TODO: handle other primitive modes
  3994. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3995. }
  3996. var promises = new Array();
  3997. var babylonVertexData = new BABYLON.VertexData();
  3998. if (primitive.indices == undefined) {
  3999. var positionAccessorIndex = attributes["POSITION"];
  4000. if (positionAccessorIndex != undefined) {
  4001. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  4002. babylonVertexData.indices = new Uint32Array(accessor.count);
  4003. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  4004. babylonVertexData.indices[i] = i;
  4005. }
  4006. }
  4007. }
  4008. else {
  4009. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  4010. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  4011. babylonVertexData.indices = data;
  4012. }));
  4013. }
  4014. var loadAttribute = function (attribute, kind) {
  4015. if (attributes[attribute] == undefined) {
  4016. return;
  4017. }
  4018. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4019. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4020. babylonMesh._delayInfo.push(kind);
  4021. }
  4022. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  4023. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4024. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  4025. if (attribute === "COLOR_0") {
  4026. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  4027. babylonMesh.hasVertexAlpha = true;
  4028. if (accessor.type === "VEC3") {
  4029. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  4030. }
  4031. }
  4032. babylonVertexData.set(attributeData, kind);
  4033. }));
  4034. };
  4035. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4036. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4037. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4038. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4039. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4040. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4041. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4042. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4043. return Promise.all(promises).then(function () {
  4044. return babylonVertexData;
  4045. });
  4046. };
  4047. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  4048. if (!primitive.targets) {
  4049. return;
  4050. }
  4051. if (node._numMorphTargets == undefined) {
  4052. node._numMorphTargets = primitive.targets.length;
  4053. }
  4054. else if (primitive.targets.length !== node._numMorphTargets) {
  4055. throw new Error(context + ": Primitives do not have the same number of targets");
  4056. }
  4057. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  4058. for (var index = 0; index < primitive.targets.length; index++) {
  4059. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  4060. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  4061. // TODO: tell the target whether it has positions, normals, tangents
  4062. }
  4063. };
  4064. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  4065. if (!primitive.targets) {
  4066. return Promise.resolve();
  4067. }
  4068. var promises = new Array();
  4069. var morphTargetManager = babylonMesh.morphTargetManager;
  4070. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  4071. var babylonMorphTarget = morphTargetManager.getTarget(index);
  4072. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  4073. }
  4074. return Promise.all(promises).then(function () { });
  4075. };
  4076. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  4077. var _this = this;
  4078. var promises = new Array();
  4079. var loadAttribute = function (attribute, setData) {
  4080. if (attributes[attribute] == undefined) {
  4081. return;
  4082. }
  4083. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  4084. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4085. setData(data);
  4086. }));
  4087. };
  4088. loadAttribute("POSITION", function (data) {
  4089. if (babylonVertexData.positions) {
  4090. for (var i = 0; i < data.length; i++) {
  4091. data[i] += babylonVertexData.positions[i];
  4092. }
  4093. babylonMorphTarget.setPositions(data);
  4094. }
  4095. });
  4096. loadAttribute("NORMAL", function (data) {
  4097. if (babylonVertexData.normals) {
  4098. for (var i = 0; i < data.length; i++) {
  4099. data[i] += babylonVertexData.normals[i];
  4100. }
  4101. babylonMorphTarget.setNormals(data);
  4102. }
  4103. });
  4104. loadAttribute("TANGENT", function (data) {
  4105. if (babylonVertexData.tangents) {
  4106. // Tangent data for morph targets is stored as xyz delta.
  4107. // The vertexData.tangent is stored as xyzw.
  4108. // So we need to skip every fourth vertexData.tangent.
  4109. for (var i = 0, j = 0; i < data.length; i++) {
  4110. data[i] += babylonVertexData.tangents[j++];
  4111. if ((i + 1) % 3 == 0) {
  4112. j++;
  4113. }
  4114. }
  4115. babylonMorphTarget.setTangents(data);
  4116. }
  4117. });
  4118. return Promise.all(promises).then(function () { });
  4119. };
  4120. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  4121. if (accessor.componentType == 5126 /* FLOAT */) {
  4122. return data;
  4123. }
  4124. var factor = 1;
  4125. if (accessor.normalized) {
  4126. switch (accessor.componentType) {
  4127. case 5121 /* UNSIGNED_BYTE */: {
  4128. factor = 1 / 255;
  4129. break;
  4130. }
  4131. case 5123 /* UNSIGNED_SHORT */: {
  4132. factor = 1 / 65535;
  4133. break;
  4134. }
  4135. default: {
  4136. throw new Error(context + ": Invalid component type " + accessor.componentType);
  4137. }
  4138. }
  4139. }
  4140. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  4141. for (var i = 0; i < result.length; i++) {
  4142. result[i] = data[i] * factor;
  4143. }
  4144. return result;
  4145. };
  4146. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  4147. var result = new Float32Array(data.length / 3 * 4);
  4148. var offset = 0;
  4149. for (var i = 0; i < result.length; i++) {
  4150. if ((i + 1) % 4 === 0) {
  4151. result[i] = 1;
  4152. }
  4153. else {
  4154. result[i] = data[offset++];
  4155. }
  4156. }
  4157. return result;
  4158. };
  4159. GLTFLoader._LoadTransform = function (node, babylonNode) {
  4160. var position = BABYLON.Vector3.Zero();
  4161. var rotation = BABYLON.Quaternion.Identity();
  4162. var scaling = BABYLON.Vector3.One();
  4163. if (node.matrix) {
  4164. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  4165. matrix.decompose(scaling, rotation, position);
  4166. }
  4167. else {
  4168. if (node.translation)
  4169. position = BABYLON.Vector3.FromArray(node.translation);
  4170. if (node.rotation)
  4171. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  4172. if (node.scale)
  4173. scaling = BABYLON.Vector3.FromArray(node.scale);
  4174. }
  4175. babylonNode.position = position;
  4176. babylonNode.rotationQuaternion = rotation;
  4177. babylonNode.scaling = scaling;
  4178. };
  4179. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  4180. var _this = this;
  4181. var assignSkeleton = function () {
  4182. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4183. var babylonMesh = _a[_i];
  4184. babylonMesh.skeleton = skin._babylonSkeleton;
  4185. }
  4186. node._babylonMesh.parent = _this._rootBabylonMesh;
  4187. node._babylonMesh.position = BABYLON.Vector3.Zero();
  4188. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  4189. node._babylonMesh.scaling = BABYLON.Vector3.One();
  4190. };
  4191. if (skin._loaded) {
  4192. return skin._loaded.then(function () {
  4193. assignSkeleton();
  4194. });
  4195. }
  4196. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  4197. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  4198. var skeletonId = "skeleton" + skin._index;
  4199. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  4200. skin._babylonSkeleton = babylonSkeleton;
  4201. _this._loadBones(context, skin, inverseBindMatricesData);
  4202. assignSkeleton();
  4203. }));
  4204. };
  4205. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  4206. if (skin.inverseBindMatrices == undefined) {
  4207. return Promise.resolve(null);
  4208. }
  4209. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  4210. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  4211. return data;
  4212. });
  4213. };
  4214. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  4215. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  4216. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  4217. node._babylonAnimationTargets.push(babylonBone);
  4218. return babylonBone;
  4219. };
  4220. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  4221. var babylonBones = {};
  4222. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  4223. var index = _a[_i];
  4224. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  4225. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  4226. }
  4227. };
  4228. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  4229. var babylonBone = babylonBones[node._index];
  4230. if (babylonBone) {
  4231. return babylonBone;
  4232. }
  4233. var boneIndex = skin.joints.indexOf(node._index);
  4234. var baseMatrix = BABYLON.Matrix.Identity();
  4235. if (inverseBindMatricesData && boneIndex !== -1) {
  4236. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  4237. baseMatrix.invertToRef(baseMatrix);
  4238. }
  4239. var babylonParentBone = null;
  4240. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  4241. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  4242. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  4243. }
  4244. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  4245. babylonBones[node._index] = babylonBone;
  4246. return babylonBone;
  4247. };
  4248. GLTFLoader.prototype._getNodeMatrix = function (node) {
  4249. return node.matrix ?
  4250. BABYLON.Matrix.FromArray(node.matrix) :
  4251. 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());
  4252. };
  4253. GLTFLoader.prototype._loadAnimationsAsync = function () {
  4254. var animations = this._gltf.animations;
  4255. if (!animations) {
  4256. return Promise.resolve();
  4257. }
  4258. var promises = new Array();
  4259. for (var index = 0; index < animations.length; index++) {
  4260. var animation = animations[index];
  4261. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  4262. }
  4263. return Promise.all(promises).then(function () { });
  4264. };
  4265. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  4266. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  4267. animation._babylonAnimationGroup = babylonAnimationGroup;
  4268. var promises = new Array();
  4269. GLTF2.ArrayItem.Assign(animation.channels);
  4270. GLTF2.ArrayItem.Assign(animation.samplers);
  4271. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  4272. var channel = _a[_i];
  4273. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  4274. }
  4275. return Promise.all(promises).then(function () {
  4276. babylonAnimationGroup.normalize();
  4277. });
  4278. };
  4279. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  4280. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  4281. if (!targetNode._babylonMesh) {
  4282. return Promise.resolve();
  4283. }
  4284. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  4285. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  4286. var targetPath;
  4287. var animationType;
  4288. switch (channel.target.path) {
  4289. case "translation" /* TRANSLATION */: {
  4290. targetPath = "position";
  4291. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4292. break;
  4293. }
  4294. case "rotation" /* ROTATION */: {
  4295. targetPath = "rotationQuaternion";
  4296. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  4297. break;
  4298. }
  4299. case "scale" /* SCALE */: {
  4300. targetPath = "scaling";
  4301. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4302. break;
  4303. }
  4304. case "weights" /* WEIGHTS */: {
  4305. targetPath = "influence";
  4306. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  4307. break;
  4308. }
  4309. default: {
  4310. throw new Error(context + ": Invalid target path " + channel.target.path);
  4311. }
  4312. }
  4313. var outputBufferOffset = 0;
  4314. var getNextOutputValue;
  4315. switch (targetPath) {
  4316. case "position": {
  4317. getNextOutputValue = function () {
  4318. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4319. outputBufferOffset += 3;
  4320. return value;
  4321. };
  4322. break;
  4323. }
  4324. case "rotationQuaternion": {
  4325. getNextOutputValue = function () {
  4326. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  4327. outputBufferOffset += 4;
  4328. return value;
  4329. };
  4330. break;
  4331. }
  4332. case "scaling": {
  4333. getNextOutputValue = function () {
  4334. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4335. outputBufferOffset += 3;
  4336. return value;
  4337. };
  4338. break;
  4339. }
  4340. case "influence": {
  4341. getNextOutputValue = function () {
  4342. var value = new Array(targetNode._numMorphTargets);
  4343. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  4344. value[i] = data.output[outputBufferOffset++];
  4345. }
  4346. return value;
  4347. };
  4348. break;
  4349. }
  4350. }
  4351. var getNextKey;
  4352. switch (data.interpolation) {
  4353. case "STEP" /* STEP */: {
  4354. getNextKey = function (frameIndex) { return ({
  4355. frame: data.input[frameIndex],
  4356. value: getNextOutputValue(),
  4357. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  4358. }); };
  4359. break;
  4360. }
  4361. case "LINEAR" /* LINEAR */: {
  4362. getNextKey = function (frameIndex) { return ({
  4363. frame: data.input[frameIndex],
  4364. value: getNextOutputValue()
  4365. }); };
  4366. break;
  4367. }
  4368. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4369. getNextKey = function (frameIndex) { return ({
  4370. frame: data.input[frameIndex],
  4371. inTangent: getNextOutputValue(),
  4372. value: getNextOutputValue(),
  4373. outTangent: getNextOutputValue()
  4374. }); };
  4375. break;
  4376. }
  4377. }
  4378. var keys;
  4379. if (data.input.length === 1) {
  4380. var key = getNextKey(0);
  4381. keys = [
  4382. { frame: key.frame, value: key.value },
  4383. { frame: key.frame + 1, value: key.value }
  4384. ];
  4385. }
  4386. else {
  4387. keys = new Array(data.input.length);
  4388. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  4389. keys[frameIndex] = getNextKey(frameIndex);
  4390. }
  4391. }
  4392. if (targetPath === "influence") {
  4393. var _loop_1 = function (targetIndex) {
  4394. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4395. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4396. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4397. frame: key.frame,
  4398. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4399. value: key.value[targetIndex],
  4400. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4401. }); }));
  4402. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4403. var babylonMesh = _a[_i];
  4404. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  4405. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  4406. }
  4407. };
  4408. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  4409. _loop_1(targetIndex);
  4410. }
  4411. }
  4412. else {
  4413. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4414. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4415. babylonAnimation.setKeys(keys);
  4416. if (targetNode._babylonAnimationTargets) {
  4417. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  4418. var target = _a[_i];
  4419. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  4420. }
  4421. }
  4422. }
  4423. });
  4424. };
  4425. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  4426. if (sampler._data) {
  4427. return sampler._data;
  4428. }
  4429. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  4430. switch (interpolation) {
  4431. case "STEP" /* STEP */:
  4432. case "LINEAR" /* LINEAR */:
  4433. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4434. break;
  4435. }
  4436. default: {
  4437. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  4438. }
  4439. }
  4440. var inputData;
  4441. var outputData;
  4442. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  4443. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  4444. sampler._data = Promise.all([
  4445. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  4446. inputData = data;
  4447. }),
  4448. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  4449. outputData = data;
  4450. })
  4451. ]).then(function () {
  4452. return {
  4453. input: inputData,
  4454. interpolation: interpolation,
  4455. output: outputData,
  4456. };
  4457. });
  4458. return sampler._data;
  4459. };
  4460. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  4461. if (buffer._data) {
  4462. return buffer._data;
  4463. }
  4464. if (!buffer.uri) {
  4465. throw new Error(context + ": Uri is missing");
  4466. }
  4467. buffer._data = this._loadUriAsync(context, buffer.uri);
  4468. return buffer._data;
  4469. };
  4470. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  4471. if (bufferView._data) {
  4472. return bufferView._data;
  4473. }
  4474. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  4475. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  4476. try {
  4477. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  4478. }
  4479. catch (e) {
  4480. throw new Error(context + ": " + e.message);
  4481. }
  4482. });
  4483. return bufferView._data;
  4484. };
  4485. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  4486. var _this = this;
  4487. if (accessor.sparse) {
  4488. throw new Error(context + ": Sparse accessors are not currently supported");
  4489. }
  4490. if (accessor._data) {
  4491. return accessor._data;
  4492. }
  4493. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  4494. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  4495. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  4496. var byteOffset = accessor.byteOffset || 0;
  4497. var byteStride = bufferView.byteStride;
  4498. if (byteStride === 0) {
  4499. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  4500. }
  4501. try {
  4502. switch (accessor.componentType) {
  4503. case 5120 /* BYTE */: {
  4504. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4505. }
  4506. case 5121 /* UNSIGNED_BYTE */: {
  4507. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4508. }
  4509. case 5122 /* SHORT */: {
  4510. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4511. }
  4512. case 5123 /* UNSIGNED_SHORT */: {
  4513. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4514. }
  4515. case 5125 /* UNSIGNED_INT */: {
  4516. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4517. }
  4518. case 5126 /* FLOAT */: {
  4519. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  4520. }
  4521. default: {
  4522. throw new Error(context + ": Invalid component type " + accessor.componentType);
  4523. }
  4524. }
  4525. }
  4526. catch (e) {
  4527. throw new Error(context + ": " + e);
  4528. }
  4529. });
  4530. return accessor._data;
  4531. };
  4532. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  4533. byteOffset += data.byteOffset;
  4534. var targetLength = count * numComponents;
  4535. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  4536. return new typedArray(data.buffer, byteOffset, targetLength);
  4537. }
  4538. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  4539. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  4540. var targetBuffer = new typedArray(targetLength);
  4541. var sourceIndex = 0;
  4542. var targetIndex = 0;
  4543. while (targetIndex < targetLength) {
  4544. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  4545. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  4546. targetIndex++;
  4547. }
  4548. sourceIndex += elementStride;
  4549. }
  4550. return targetBuffer;
  4551. };
  4552. GLTFLoader.prototype._getDefaultMaterial = function () {
  4553. var id = "__gltf_default";
  4554. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  4555. if (!babylonMaterial) {
  4556. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  4557. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4558. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  4559. babylonMaterial.metallic = 1;
  4560. babylonMaterial.roughness = 1;
  4561. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4562. }
  4563. return babylonMaterial;
  4564. };
  4565. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  4566. var promises = new Array();
  4567. var babylonMaterial = material._babylonMaterial;
  4568. // Ensure metallic workflow
  4569. babylonMaterial.metallic = 1;
  4570. babylonMaterial.roughness = 1;
  4571. var properties = material.pbrMetallicRoughness;
  4572. if (properties) {
  4573. if (properties.baseColorFactor) {
  4574. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4575. babylonMaterial.alpha = properties.baseColorFactor[3];
  4576. }
  4577. else {
  4578. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4579. }
  4580. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  4581. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  4582. if (properties.baseColorTexture) {
  4583. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4584. babylonMaterial.albedoTexture = texture;
  4585. }));
  4586. }
  4587. if (properties.metallicRoughnessTexture) {
  4588. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  4589. babylonMaterial.metallicTexture = texture;
  4590. }));
  4591. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4592. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4593. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4594. }
  4595. }
  4596. this._loadMaterialAlphaProperties(context, material);
  4597. return Promise.all(promises).then(function () { });
  4598. };
  4599. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4600. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  4601. if (promise) {
  4602. return promise;
  4603. }
  4604. material._babylonMeshes = material._babylonMeshes || [];
  4605. material._babylonMeshes.push(babylonMesh);
  4606. if (material._loaded) {
  4607. babylonMesh.material = material._babylonMaterial;
  4608. return material._loaded;
  4609. }
  4610. var promises = new Array();
  4611. var babylonMaterial = this._createMaterial(material);
  4612. material._babylonMaterial = babylonMaterial;
  4613. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  4614. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  4615. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4616. babylonMesh.material = babylonMaterial;
  4617. return (material._loaded = Promise.all(promises).then(function () { }));
  4618. };
  4619. GLTFLoader.prototype._createMaterial = function (material) {
  4620. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  4621. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  4622. return babylonMaterial;
  4623. };
  4624. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  4625. var promises = new Array();
  4626. var babylonMaterial = material._babylonMaterial;
  4627. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  4628. if (material.doubleSided) {
  4629. babylonMaterial.backFaceCulling = false;
  4630. babylonMaterial.twoSidedLighting = true;
  4631. }
  4632. if (material.normalTexture) {
  4633. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  4634. babylonMaterial.bumpTexture = texture;
  4635. }));
  4636. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  4637. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  4638. if (material.normalTexture.scale != undefined) {
  4639. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4640. }
  4641. }
  4642. if (material.occlusionTexture) {
  4643. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  4644. babylonMaterial.ambientTexture = texture;
  4645. }));
  4646. babylonMaterial.useAmbientInGrayScale = true;
  4647. if (material.occlusionTexture.strength != undefined) {
  4648. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4649. }
  4650. }
  4651. if (material.emissiveTexture) {
  4652. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  4653. babylonMaterial.emissiveTexture = texture;
  4654. }));
  4655. }
  4656. return Promise.all(promises).then(function () { });
  4657. };
  4658. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  4659. var babylonMaterial = material._babylonMaterial;
  4660. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  4661. switch (alphaMode) {
  4662. case "OPAQUE" /* OPAQUE */: {
  4663. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4664. break;
  4665. }
  4666. case "MASK" /* MASK */: {
  4667. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  4668. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  4669. if (babylonMaterial.alpha) {
  4670. if (babylonMaterial.alpha === 0) {
  4671. babylonMaterial.alphaCutOff = 1;
  4672. }
  4673. else {
  4674. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  4675. }
  4676. babylonMaterial.alpha = 1;
  4677. }
  4678. if (babylonMaterial.albedoTexture) {
  4679. babylonMaterial.albedoTexture.hasAlpha = true;
  4680. }
  4681. break;
  4682. }
  4683. case "BLEND" /* BLEND */: {
  4684. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  4685. if (babylonMaterial.albedoTexture) {
  4686. babylonMaterial.albedoTexture.hasAlpha = true;
  4687. babylonMaterial.useAlphaFromAlbedoTexture = true;
  4688. }
  4689. break;
  4690. }
  4691. default: {
  4692. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  4693. }
  4694. }
  4695. };
  4696. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  4697. var _this = this;
  4698. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  4699. context = "#/textures/" + textureInfo.index;
  4700. var promises = new Array();
  4701. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  4702. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  4703. var deferred = new BABYLON.Deferred();
  4704. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  4705. if (!_this._disposed) {
  4706. deferred.resolve();
  4707. }
  4708. }, function (message, exception) {
  4709. if (!_this._disposed) {
  4710. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  4711. }
  4712. });
  4713. promises.push(deferred.promise);
  4714. babylonTexture.name = texture.name || "texture" + texture._index;
  4715. babylonTexture.wrapU = samplerData.wrapU;
  4716. babylonTexture.wrapV = samplerData.wrapV;
  4717. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  4718. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  4719. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  4720. babylonTexture.updateURL(objectURL);
  4721. }));
  4722. assign(babylonTexture);
  4723. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  4724. return Promise.all(promises).then(function () { });
  4725. };
  4726. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  4727. if (!sampler._data) {
  4728. sampler._data = {
  4729. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  4730. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  4731. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  4732. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  4733. };
  4734. }
  4735. ;
  4736. return sampler._data;
  4737. };
  4738. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  4739. if (image._objectURL) {
  4740. return image._objectURL;
  4741. }
  4742. var promise;
  4743. if (image.uri) {
  4744. promise = this._loadUriAsync(context, image.uri);
  4745. }
  4746. else {
  4747. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  4748. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  4749. }
  4750. image._objectURL = promise.then(function (data) {
  4751. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  4752. });
  4753. return image._objectURL;
  4754. };
  4755. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  4756. var _this = this;
  4757. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  4758. if (promise) {
  4759. return promise;
  4760. }
  4761. if (!GLTFLoader._ValidateUri(uri)) {
  4762. throw new Error(context + ": Uri '" + uri + "' is invalid");
  4763. }
  4764. if (BABYLON.Tools.IsBase64(uri)) {
  4765. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  4766. }
  4767. return new Promise(function (resolve, reject) {
  4768. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  4769. if (!_this._disposed) {
  4770. resolve(new Uint8Array(data));
  4771. }
  4772. }, function (event) {
  4773. if (!_this._disposed) {
  4774. try {
  4775. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  4776. request._lengthComputable = event.lengthComputable;
  4777. request._loaded = event.loaded;
  4778. request._total = event.total;
  4779. _this._onProgress();
  4780. }
  4781. }
  4782. catch (e) {
  4783. reject(e);
  4784. }
  4785. }
  4786. }, _this._babylonScene.database, true, function (request, exception) {
  4787. if (!_this._disposed) {
  4788. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  4789. }
  4790. });
  4791. _this._requests.push(request);
  4792. });
  4793. };
  4794. GLTFLoader.prototype._onProgress = function () {
  4795. if (!this._progressCallback) {
  4796. return;
  4797. }
  4798. var lengthComputable = true;
  4799. var loaded = 0;
  4800. var total = 0;
  4801. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4802. var request = _a[_i];
  4803. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  4804. return;
  4805. }
  4806. lengthComputable = lengthComputable && request._lengthComputable;
  4807. loaded += request._loaded;
  4808. total += request._total;
  4809. }
  4810. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  4811. };
  4812. GLTFLoader._GetProperty = function (context, array, index) {
  4813. if (!array || index == undefined || !array[index]) {
  4814. throw new Error(context + ": Failed to find index " + index);
  4815. }
  4816. return array[index];
  4817. };
  4818. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  4819. // Set defaults if undefined
  4820. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  4821. switch (mode) {
  4822. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  4823. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  4824. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  4825. default:
  4826. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  4827. return BABYLON.Texture.WRAP_ADDRESSMODE;
  4828. }
  4829. };
  4830. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  4831. // Set defaults if undefined
  4832. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  4833. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  4834. if (magFilter === 9729 /* LINEAR */) {
  4835. switch (minFilter) {
  4836. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  4837. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  4838. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  4839. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  4840. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  4841. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4842. default:
  4843. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  4844. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4845. }
  4846. }
  4847. else {
  4848. if (magFilter !== 9728 /* NEAREST */) {
  4849. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  4850. }
  4851. switch (minFilter) {
  4852. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  4853. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  4854. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4855. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  4856. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  4857. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  4858. default:
  4859. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  4860. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4861. }
  4862. }
  4863. };
  4864. GLTFLoader._GetNumComponents = function (context, type) {
  4865. switch (type) {
  4866. case "SCALAR": return 1;
  4867. case "VEC2": return 2;
  4868. case "VEC3": return 3;
  4869. case "VEC4": return 4;
  4870. case "MAT2": return 4;
  4871. case "MAT3": return 9;
  4872. case "MAT4": return 16;
  4873. }
  4874. throw new Error(context + ": Invalid type " + type);
  4875. };
  4876. GLTFLoader._ValidateUri = function (uri) {
  4877. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  4878. };
  4879. GLTFLoader.prototype._compileMaterialsAsync = function () {
  4880. var promises = new Array();
  4881. if (this._gltf.materials) {
  4882. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  4883. var material = _a[_i];
  4884. var babylonMaterial = material._babylonMaterial;
  4885. var babylonMeshes = material._babylonMeshes;
  4886. if (babylonMaterial && babylonMeshes) {
  4887. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  4888. var babylonMesh = babylonMeshes_1[_b];
  4889. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  4890. if (this.useClipPlane) {
  4891. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  4892. }
  4893. }
  4894. }
  4895. }
  4896. }
  4897. return Promise.all(promises).then(function () { });
  4898. };
  4899. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  4900. var promises = new Array();
  4901. var lights = this._babylonScene.lights;
  4902. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  4903. var light = lights_1[_i];
  4904. var generator = light.getShadowGenerator();
  4905. if (generator) {
  4906. promises.push(generator.forceCompilationAsync());
  4907. }
  4908. }
  4909. return Promise.all(promises).then(function () { });
  4910. };
  4911. GLTFLoader.prototype._clear = function () {
  4912. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4913. var request = _a[_i];
  4914. request.abort();
  4915. }
  4916. this._requests.length = 0;
  4917. if (this._gltf && this._gltf.images) {
  4918. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  4919. var image = _c[_b];
  4920. if (image._objectURL) {
  4921. image._objectURL.then(function (value) {
  4922. URL.revokeObjectURL(value);
  4923. });
  4924. image._objectURL = undefined;
  4925. }
  4926. }
  4927. }
  4928. delete this._gltf;
  4929. delete this._babylonScene;
  4930. this._completePromises.length = 0;
  4931. for (var name_3 in this._extensions) {
  4932. this._extensions[name_3].dispose();
  4933. }
  4934. this._extensions = {};
  4935. delete this._rootBabylonMesh;
  4936. delete this._progressCallback;
  4937. this.onMeshLoadedObservable.clear();
  4938. this.onTextureLoadedObservable.clear();
  4939. this.onMaterialLoadedObservable.clear();
  4940. };
  4941. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  4942. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  4943. var name_4 = _a[_i];
  4944. var extension = this._extensions[name_4];
  4945. if (extension.enabled) {
  4946. var promise = actionAsync(extension);
  4947. if (promise) {
  4948. return promise;
  4949. }
  4950. }
  4951. }
  4952. return null;
  4953. };
  4954. GLTFLoader._Names = new Array();
  4955. GLTFLoader._Factories = {};
  4956. return GLTFLoader;
  4957. }());
  4958. GLTF2.GLTFLoader = GLTFLoader;
  4959. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4960. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4961. })(BABYLON || (BABYLON = {}));
  4962. //# sourceMappingURL=babylon.glTFLoader.js.map
  4963. var BABYLON;
  4964. (function (BABYLON) {
  4965. var GLTF2;
  4966. (function (GLTF2) {
  4967. var GLTFLoaderExtension = /** @class */ (function () {
  4968. function GLTFLoaderExtension(loader) {
  4969. this.enabled = true;
  4970. this._loader = loader;
  4971. }
  4972. GLTFLoaderExtension.prototype.dispose = function () {
  4973. delete this._loader;
  4974. };
  4975. // #region Overridable Methods
  4976. /** Override this method to modify the default behavior for loading scenes. */
  4977. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4978. /** Override this method to modify the default behavior for loading nodes. */
  4979. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4980. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  4981. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  4982. /** Override this method to modify the default behavior for loading materials. */
  4983. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  4984. /** Override this method to modify the default behavior for loading uris. */
  4985. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4986. // #endregion
  4987. /** Helper method called by a loader extension to load an glTF extension. */
  4988. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4989. if (!property.extensions) {
  4990. return null;
  4991. }
  4992. var extensions = property.extensions;
  4993. var extension = extensions[this.name];
  4994. if (!extension) {
  4995. return null;
  4996. }
  4997. // Clear out the extension before executing the action to avoid recursing into the same property.
  4998. delete extensions[this.name];
  4999. try {
  5000. return actionAsync(context + "/extensions/" + this.name, extension);
  5001. }
  5002. finally {
  5003. // Restore the extension after executing the action.
  5004. extensions[this.name] = extension;
  5005. }
  5006. };
  5007. /** Helper method called by the loader to allow extensions to override loading scenes. */
  5008. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  5009. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  5010. };
  5011. /** Helper method called by the loader to allow extensions to override loading nodes. */
  5012. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  5013. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  5014. };
  5015. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  5016. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  5017. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  5018. };
  5019. /** Helper method called by the loader to allow extensions to override loading materials. */
  5020. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  5021. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  5022. };
  5023. /** Helper method called by the loader to allow extensions to override loading uris. */
  5024. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  5025. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  5026. };
  5027. return GLTFLoaderExtension;
  5028. }());
  5029. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  5030. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5031. })(BABYLON || (BABYLON = {}));
  5032. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  5033. var BABYLON;
  5034. (function (BABYLON) {
  5035. var GLTF2;
  5036. (function (GLTF2) {
  5037. var Extensions;
  5038. (function (Extensions) {
  5039. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  5040. var NAME = "MSFT_lod";
  5041. var MSFT_lod = /** @class */ (function (_super) {
  5042. __extends(MSFT_lod, _super);
  5043. function MSFT_lod() {
  5044. var _this = _super !== null && _super.apply(this, arguments) || this;
  5045. _this.name = NAME;
  5046. /**
  5047. * Maximum number of LODs to load, starting from the lowest LOD.
  5048. */
  5049. _this.maxLODsToLoad = Number.MAX_VALUE;
  5050. _this._loadingNodeLOD = null;
  5051. _this._loadNodeSignals = {};
  5052. _this._loadingMaterialLOD = null;
  5053. _this._loadMaterialSignals = {};
  5054. return _this;
  5055. }
  5056. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  5057. var _this = this;
  5058. return this._loadExtensionAsync(context, node, function (context, extension) {
  5059. var firstPromise;
  5060. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  5061. var _loop_1 = function (indexLOD) {
  5062. var nodeLOD = nodeLODs[indexLOD];
  5063. if (indexLOD !== 0) {
  5064. _this._loadingNodeLOD = nodeLOD;
  5065. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  5066. }
  5067. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  5068. if (indexLOD !== 0) {
  5069. var previousNodeLOD = nodeLODs[indexLOD - 1];
  5070. previousNodeLOD._babylonMesh.setEnabled(false);
  5071. }
  5072. if (indexLOD !== nodeLODs.length - 1) {
  5073. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  5074. _this._loadNodeSignals[nodeIndex].resolve();
  5075. delete _this._loadNodeSignals[nodeIndex];
  5076. }
  5077. });
  5078. if (indexLOD === 0) {
  5079. firstPromise = promise;
  5080. }
  5081. else {
  5082. _this._loader._completePromises.push(promise);
  5083. _this._loadingNodeLOD = null;
  5084. }
  5085. };
  5086. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  5087. _loop_1(indexLOD);
  5088. }
  5089. return firstPromise;
  5090. });
  5091. };
  5092. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  5093. var _this = this;
  5094. // Don't load material LODs if already loading a node LOD.
  5095. if (this._loadingNodeLOD) {
  5096. return null;
  5097. }
  5098. return this._loadExtensionAsync(context, material, function (context, extension) {
  5099. var firstPromise;
  5100. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  5101. var _loop_2 = function (indexLOD) {
  5102. var materialLOD = materialLODs[indexLOD];
  5103. if (indexLOD !== 0) {
  5104. _this._loadingMaterialLOD = materialLOD;
  5105. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  5106. }
  5107. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  5108. if (indexLOD !== materialLODs.length - 1) {
  5109. var materialIndex = materialLODs[indexLOD + 1]._index;
  5110. _this._loadMaterialSignals[materialIndex].resolve();
  5111. delete _this._loadMaterialSignals[materialIndex];
  5112. }
  5113. });
  5114. if (indexLOD === 0) {
  5115. firstPromise = promise;
  5116. }
  5117. else {
  5118. _this._loader._completePromises.push(promise);
  5119. _this._loadingMaterialLOD = null;
  5120. }
  5121. };
  5122. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  5123. _loop_2(indexLOD);
  5124. }
  5125. return firstPromise;
  5126. });
  5127. };
  5128. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  5129. var _this = this;
  5130. // Defer the loading of uris if loading a material or node LOD.
  5131. if (this._loadingMaterialLOD) {
  5132. var index = this._loadingMaterialLOD._index;
  5133. return this._loadMaterialSignals[index].promise.then(function () {
  5134. return _this._loader._loadUriAsync(context, uri);
  5135. });
  5136. }
  5137. else if (this._loadingNodeLOD) {
  5138. var index = this._loadingNodeLOD._index;
  5139. return this._loadNodeSignals[index].promise.then(function () {
  5140. return _this._loader._loadUriAsync(context, uri);
  5141. });
  5142. }
  5143. return null;
  5144. };
  5145. /**
  5146. * Gets an array of LOD properties from lowest to highest.
  5147. */
  5148. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  5149. if (this.maxLODsToLoad <= 0) {
  5150. throw new Error("maxLODsToLoad must be greater than zero");
  5151. }
  5152. var properties = new Array();
  5153. for (var i = ids.length - 1; i >= 0; i--) {
  5154. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  5155. if (properties.length === this.maxLODsToLoad) {
  5156. return properties;
  5157. }
  5158. }
  5159. properties.push(property);
  5160. return properties;
  5161. };
  5162. return MSFT_lod;
  5163. }(GLTF2.GLTFLoaderExtension));
  5164. Extensions.MSFT_lod = MSFT_lod;
  5165. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  5166. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5167. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5168. })(BABYLON || (BABYLON = {}));
  5169. //# sourceMappingURL=MSFT_lod.js.map
  5170. var BABYLON;
  5171. (function (BABYLON) {
  5172. var GLTF2;
  5173. (function (GLTF2) {
  5174. var Extensions;
  5175. (function (Extensions) {
  5176. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  5177. var NAME = "KHR_draco_mesh_compression";
  5178. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  5179. __extends(KHR_draco_mesh_compression, _super);
  5180. function KHR_draco_mesh_compression(loader) {
  5181. var _this = _super.call(this, loader) || this;
  5182. _this.name = NAME;
  5183. _this._dracoCompression = null;
  5184. // Disable extension if decoder is not available.
  5185. if (!BABYLON.DracoCompression.DecoderUrl) {
  5186. _this.enabled = false;
  5187. }
  5188. return _this;
  5189. }
  5190. KHR_draco_mesh_compression.prototype.dispose = function () {
  5191. if (this._dracoCompression) {
  5192. this._dracoCompression.dispose();
  5193. }
  5194. _super.prototype.dispose.call(this);
  5195. };
  5196. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  5197. var _this = this;
  5198. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  5199. if (primitive.mode != undefined) {
  5200. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  5201. primitive.mode !== 4 /* TRIANGLES */) {
  5202. throw new Error(context + ": Unsupported mode " + primitive.mode);
  5203. }
  5204. // TODO: handle triangle strips
  5205. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  5206. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  5207. }
  5208. }
  5209. var attributes = {};
  5210. var loadAttribute = function (name, kind) {
  5211. var uniqueId = extension.attributes[name];
  5212. if (uniqueId == undefined) {
  5213. return;
  5214. }
  5215. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  5216. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  5217. babylonMesh._delayInfo.push(kind);
  5218. }
  5219. attributes[kind] = uniqueId;
  5220. };
  5221. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  5222. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  5223. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  5224. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  5225. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  5226. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  5227. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  5228. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  5229. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  5230. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  5231. try {
  5232. if (!_this._dracoCompression) {
  5233. _this._dracoCompression = new BABYLON.DracoCompression();
  5234. }
  5235. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  5236. }
  5237. catch (e) {
  5238. throw new Error(context + ": " + e.message);
  5239. }
  5240. });
  5241. });
  5242. };
  5243. return KHR_draco_mesh_compression;
  5244. }(GLTF2.GLTFLoaderExtension));
  5245. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  5246. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  5247. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5248. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5249. })(BABYLON || (BABYLON = {}));
  5250. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  5251. var BABYLON;
  5252. (function (BABYLON) {
  5253. var GLTF2;
  5254. (function (GLTF2) {
  5255. var Extensions;
  5256. (function (Extensions) {
  5257. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  5258. var NAME = "KHR_materials_pbrSpecularGlossiness";
  5259. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  5260. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  5261. function KHR_materials_pbrSpecularGlossiness() {
  5262. var _this = _super !== null && _super.apply(this, arguments) || this;
  5263. _this.name = NAME;
  5264. return _this;
  5265. }
  5266. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  5267. var _this = this;
  5268. return this._loadExtensionAsync(context, material, function (context, extension) {
  5269. material._babylonMeshes = material._babylonMeshes || [];
  5270. material._babylonMeshes.push(babylonMesh);
  5271. if (material._loaded) {
  5272. babylonMesh.material = material._babylonMaterial;
  5273. return material._loaded;
  5274. }
  5275. var promises = new Array();
  5276. var babylonMaterial = _this._loader._createMaterial(material);
  5277. material._babylonMaterial = babylonMaterial;
  5278. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  5279. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  5280. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5281. babylonMesh.material = babylonMaterial;
  5282. return (material._loaded = Promise.all(promises).then(function () { }));
  5283. });
  5284. };
  5285. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  5286. var promises = new Array();
  5287. var babylonMaterial = material._babylonMaterial;
  5288. if (properties.diffuseFactor) {
  5289. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  5290. babylonMaterial.alpha = properties.diffuseFactor[3];
  5291. }
  5292. else {
  5293. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5294. }
  5295. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  5296. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  5297. if (properties.diffuseTexture) {
  5298. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  5299. babylonMaterial.albedoTexture = texture;
  5300. }));
  5301. }
  5302. if (properties.specularGlossinessTexture) {
  5303. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  5304. babylonMaterial.reflectivityTexture = texture;
  5305. }));
  5306. babylonMaterial.reflectivityTexture.hasAlpha = true;
  5307. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  5308. }
  5309. loader._loadMaterialAlphaProperties(context, material);
  5310. return Promise.all(promises).then(function () { });
  5311. };
  5312. return KHR_materials_pbrSpecularGlossiness;
  5313. }(GLTF2.GLTFLoaderExtension));
  5314. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  5315. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  5316. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5317. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5318. })(BABYLON || (BABYLON = {}));
  5319. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  5320. var BABYLON;
  5321. (function (BABYLON) {
  5322. var GLTF2;
  5323. (function (GLTF2) {
  5324. var Extensions;
  5325. (function (Extensions) {
  5326. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  5327. var NAME = "KHR_lights";
  5328. var LightType;
  5329. (function (LightType) {
  5330. LightType["AMBIENT"] = "ambient";
  5331. LightType["DIRECTIONAL"] = "directional";
  5332. LightType["POINT"] = "point";
  5333. LightType["SPOT"] = "spot";
  5334. })(LightType || (LightType = {}));
  5335. var KHR_lights = /** @class */ (function (_super) {
  5336. __extends(KHR_lights, _super);
  5337. function KHR_lights() {
  5338. var _this = _super !== null && _super.apply(this, arguments) || this;
  5339. _this.name = NAME;
  5340. return _this;
  5341. }
  5342. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  5343. var _this = this;
  5344. return this._loadExtensionAsync(context, scene, function (context, extension) {
  5345. var promise = _this._loader._loadSceneAsync(context, scene);
  5346. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  5347. if (light.type !== LightType.AMBIENT) {
  5348. throw new Error(context + ": Only ambient lights are allowed on a scene");
  5349. }
  5350. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  5351. return promise;
  5352. });
  5353. };
  5354. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  5355. var _this = this;
  5356. return this._loadExtensionAsync(context, node, function (context, extension) {
  5357. var promise = _this._loader._loadNodeAsync(context, node);
  5358. var babylonLight;
  5359. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  5360. var name = node._babylonMesh.name;
  5361. switch (light.type) {
  5362. case LightType.AMBIENT: {
  5363. throw new Error(context + ": Ambient lights are not allowed on a node");
  5364. }
  5365. case LightType.DIRECTIONAL: {
  5366. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  5367. break;
  5368. }
  5369. case LightType.POINT: {
  5370. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  5371. break;
  5372. }
  5373. case LightType.SPOT: {
  5374. var spotLight = light;
  5375. // TODO: support inner and outer cone angles
  5376. //const innerConeAngle = spotLight.innerConeAngle || 0;
  5377. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  5378. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  5379. break;
  5380. }
  5381. default: {
  5382. throw new Error(context + ": Invalid light type " + light.type);
  5383. }
  5384. }
  5385. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  5386. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  5387. babylonLight.parent = node._babylonMesh;
  5388. return promise;
  5389. });
  5390. };
  5391. Object.defineProperty(KHR_lights.prototype, "_lights", {
  5392. get: function () {
  5393. var extensions = this._loader._gltf.extensions;
  5394. if (!extensions || !extensions[this.name]) {
  5395. throw new Error("#/extensions: " + this.name + " not found");
  5396. }
  5397. var extension = extensions[this.name];
  5398. return extension.lights;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. return KHR_lights;
  5404. }(GLTF2.GLTFLoaderExtension));
  5405. Extensions.KHR_lights = KHR_lights;
  5406. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  5407. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  5408. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5409. })(BABYLON || (BABYLON = {}));
  5410. //# sourceMappingURL=KHR_lights.js.map
  5411. return BABYLON;
  5412. });