babylon.glTFFileLoader.js 229 KB

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