babylon.glTFFileLoader.js 263 KB

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