babylon.glTF2FileLoader.js 192 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Mode that determines the coordinate system to use.
  6. */
  7. var GLTFLoaderCoordinateSystemMode;
  8. (function (GLTFLoaderCoordinateSystemMode) {
  9. /**
  10. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  11. */
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  13. /**
  14. * Sets the useRightHandedSystem flag on the scene.
  15. */
  16. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  17. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  18. /**
  19. * Mode that determines what animations will start.
  20. */
  21. var GLTFLoaderAnimationStartMode;
  22. (function (GLTFLoaderAnimationStartMode) {
  23. /**
  24. * No animation will start.
  25. */
  26. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  27. /**
  28. * The first animation will start.
  29. */
  30. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  31. /**
  32. * All animations will start.
  33. */
  34. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  35. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  36. /**
  37. * Loader state.
  38. */
  39. var GLTFLoaderState;
  40. (function (GLTFLoaderState) {
  41. /**
  42. * The asset is loading.
  43. */
  44. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  45. /**
  46. * The asset is ready for rendering.
  47. */
  48. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  49. /**
  50. * The asset is completely loaded.
  51. */
  52. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  53. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  54. /**
  55. * File loader for loading glTF files into a scene.
  56. */
  57. var GLTFFileLoader = /** @class */ (function () {
  58. function GLTFFileLoader() {
  59. // #region Common options
  60. /**
  61. * Raised when the asset has been parsed
  62. */
  63. this.onParsedObservable = new BABYLON.Observable();
  64. // #endregion
  65. // #region V2 options
  66. /**
  67. * The coordinate system mode. Defaults to AUTO.
  68. */
  69. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  70. /**
  71. * The animation start mode. Defaults to FIRST.
  72. */
  73. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  74. /**
  75. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  76. */
  77. this.compileMaterials = false;
  78. /**
  79. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  80. */
  81. this.useClipPlane = false;
  82. /**
  83. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  84. */
  85. this.compileShadowGenerators = false;
  86. /**
  87. * Defines if the Alpha blended materials are only applied as coverage.
  88. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  89. * If true, no extra effects are applied to transparent pixels.
  90. */
  91. this.transparencyAsCoverage = false;
  92. /** @hidden */
  93. this._normalizeAnimationGroupsToBeginAtZero = true;
  94. /**
  95. * Function called before loading a url referenced by the asset.
  96. */
  97. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  98. /**
  99. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  100. */
  101. this.onMeshLoadedObservable = new BABYLON.Observable();
  102. /**
  103. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104. */
  105. this.onTextureLoadedObservable = new BABYLON.Observable();
  106. /**
  107. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  108. */
  109. this.onMaterialLoadedObservable = new BABYLON.Observable();
  110. /**
  111. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  112. */
  113. this.onCameraLoadedObservable = new BABYLON.Observable();
  114. /**
  115. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  116. * For assets with LODs, raised when all of the LODs are complete.
  117. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  118. */
  119. this.onCompleteObservable = new BABYLON.Observable();
  120. /**
  121. * Observable raised when an error occurs.
  122. */
  123. this.onErrorObservable = new BABYLON.Observable();
  124. /**
  125. * Observable raised after the loader is disposed.
  126. */
  127. this.onDisposeObservable = new BABYLON.Observable();
  128. /**
  129. * Observable raised after a loader extension is created.
  130. * Set additional options for a loader extension in this event.
  131. */
  132. this.onExtensionLoadedObservable = new BABYLON.Observable();
  133. // #endregion
  134. this._loader = null;
  135. /**
  136. * Name of the loader ("gltf")
  137. */
  138. this.name = "gltf";
  139. /**
  140. * Supported file extensions of the loader (.gltf, .glb)
  141. */
  142. this.extensions = {
  143. ".gltf": { isBinary: false },
  144. ".glb": { isBinary: true }
  145. };
  146. this._logIndentLevel = 0;
  147. this._loggingEnabled = false;
  148. /** @hidden */
  149. this._log = this._logDisabled;
  150. this._capturePerformanceCounters = false;
  151. /** @hidden */
  152. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  153. /** @hidden */
  154. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  155. }
  156. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  157. /**
  158. * Raised when the asset has been parsed
  159. */
  160. set: function (callback) {
  161. if (this._onParsedObserver) {
  162. this.onParsedObservable.remove(this._onParsedObserver);
  163. }
  164. this._onParsedObserver = this.onParsedObservable.add(callback);
  165. },
  166. enumerable: true,
  167. configurable: true
  168. });
  169. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  170. /**
  171. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  172. */
  173. set: function (callback) {
  174. if (this._onMeshLoadedObserver) {
  175. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  176. }
  177. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  183. /**
  184. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  185. */
  186. set: function (callback) {
  187. if (this._onTextureLoadedObserver) {
  188. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  189. }
  190. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  191. },
  192. enumerable: true,
  193. configurable: true
  194. });
  195. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  196. /**
  197. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  198. */
  199. set: function (callback) {
  200. if (this._onMaterialLoadedObserver) {
  201. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  202. }
  203. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  204. },
  205. enumerable: true,
  206. configurable: true
  207. });
  208. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  209. /**
  210. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  211. */
  212. set: function (callback) {
  213. if (this._onCameraLoadedObserver) {
  214. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  215. }
  216. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  217. },
  218. enumerable: true,
  219. configurable: true
  220. });
  221. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  222. /**
  223. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  224. * For assets with LODs, raised when all of the LODs are complete.
  225. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  226. */
  227. set: function (callback) {
  228. if (this._onCompleteObserver) {
  229. this.onCompleteObservable.remove(this._onCompleteObserver);
  230. }
  231. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  237. /**
  238. * Callback raised when an error occurs.
  239. */
  240. set: function (callback) {
  241. if (this._onErrorObserver) {
  242. this.onErrorObservable.remove(this._onErrorObserver);
  243. }
  244. this._onErrorObserver = this.onErrorObservable.add(callback);
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  250. /**
  251. * Callback raised after the loader is disposed.
  252. */
  253. set: function (callback) {
  254. if (this._onDisposeObserver) {
  255. this.onDisposeObservable.remove(this._onDisposeObserver);
  256. }
  257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  263. /**
  264. * Callback raised after a loader extension is created.
  265. */
  266. set: function (callback) {
  267. if (this._onExtensionLoadedObserver) {
  268. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  269. }
  270. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  271. },
  272. enumerable: true,
  273. configurable: true
  274. });
  275. /**
  276. * Returns a promise that resolves when the asset is completely loaded.
  277. * @returns a promise that resolves when the asset is completely loaded.
  278. */
  279. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  280. var _this = this;
  281. return new Promise(function (resolve, reject) {
  282. _this.onCompleteObservable.addOnce(function () {
  283. resolve();
  284. });
  285. _this.onErrorObservable.addOnce(function (reason) {
  286. reject(reason);
  287. });
  288. });
  289. };
  290. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  291. /**
  292. * The loader state or null if the loader is not active.
  293. */
  294. get: function () {
  295. return this._loader ? this._loader.state : null;
  296. },
  297. enumerable: true,
  298. configurable: true
  299. });
  300. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  301. /**
  302. * Defines if the loader logging is enabled.
  303. */
  304. get: function () {
  305. return this._loggingEnabled;
  306. },
  307. set: function (value) {
  308. if (this._loggingEnabled === value) {
  309. return;
  310. }
  311. this._loggingEnabled = value;
  312. if (this._loggingEnabled) {
  313. this._log = this._logEnabled;
  314. }
  315. else {
  316. this._log = this._logDisabled;
  317. }
  318. },
  319. enumerable: true,
  320. configurable: true
  321. });
  322. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  323. /**
  324. * Defines if the loader should capture performance counters.
  325. */
  326. get: function () {
  327. return this._capturePerformanceCounters;
  328. },
  329. set: function (value) {
  330. if (this._capturePerformanceCounters === value) {
  331. return;
  332. }
  333. this._capturePerformanceCounters = value;
  334. if (this._capturePerformanceCounters) {
  335. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  336. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  337. }
  338. else {
  339. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  340. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  341. }
  342. },
  343. enumerable: true,
  344. configurable: true
  345. });
  346. /**
  347. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  348. */
  349. GLTFFileLoader.prototype.dispose = function () {
  350. if (this._loader) {
  351. this._loader.dispose();
  352. this._loader = null;
  353. }
  354. this._clear();
  355. this.onDisposeObservable.notifyObservers(undefined);
  356. this.onDisposeObservable.clear();
  357. };
  358. /** @hidden */
  359. GLTFFileLoader.prototype._clear = function () {
  360. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  361. this.onMeshLoadedObservable.clear();
  362. this.onTextureLoadedObservable.clear();
  363. this.onMaterialLoadedObservable.clear();
  364. this.onCameraLoadedObservable.clear();
  365. this.onCompleteObservable.clear();
  366. this.onExtensionLoadedObservable.clear();
  367. };
  368. /**
  369. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  370. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  371. * @param scene the scene the meshes should be added to
  372. * @param data the glTF data to load
  373. * @param rootUrl root url to load from
  374. * @param onProgress event that fires when loading progress has occured
  375. * @param fullName Defines the FQDN of the file to load
  376. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  377. */
  378. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fullName) {
  379. var _this = this;
  380. return Promise.resolve().then(function () {
  381. var loaderData = _this._parse(data);
  382. _this._loader = _this._getLoader(loaderData);
  383. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fullName);
  384. });
  385. };
  386. /**
  387. * Imports all objects from the loaded glTF data and adds them to the scene
  388. * @param scene the scene the objects should be added to
  389. * @param data the glTF data to load
  390. * @param rootUrl root url to load from
  391. * @param onProgress event that fires when loading progress has occured
  392. * @param fullName Defines the FQDN of the file to load
  393. * @returns a promise which completes when objects have been loaded to the scene
  394. */
  395. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fullName) {
  396. var _this = this;
  397. return Promise.resolve().then(function () {
  398. var loaderData = _this._parse(data);
  399. _this._loader = _this._getLoader(loaderData);
  400. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fullName);
  401. });
  402. };
  403. /**
  404. * Load into an asset container.
  405. * @param scene The scene to load into
  406. * @param data The data to import
  407. * @param rootUrl The root url for scene and resources
  408. * @param onProgress The callback when the load progresses
  409. * @param fullName Defines the FQDN of the file to load
  410. * @returns The loaded asset container
  411. */
  412. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fullName) {
  413. var _this = this;
  414. return Promise.resolve().then(function () {
  415. var loaderData = _this._parse(data);
  416. _this._loader = _this._getLoader(loaderData);
  417. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fullName).then(function (result) {
  418. var container = new BABYLON.AssetContainer(scene);
  419. Array.prototype.push.apply(container.meshes, result.meshes);
  420. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  421. Array.prototype.push.apply(container.skeletons, result.skeletons);
  422. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  423. container.removeAllFromScene();
  424. return container;
  425. });
  426. });
  427. };
  428. /**
  429. * If the data string can be loaded directly.
  430. * @param data string contianing the file data
  431. * @returns if the data can be loaded directly
  432. */
  433. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  434. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  435. };
  436. /**
  437. * Instantiates a glTF file loader plugin.
  438. * @returns the created plugin
  439. */
  440. GLTFFileLoader.prototype.createPlugin = function () {
  441. return new GLTFFileLoader();
  442. };
  443. GLTFFileLoader.prototype._parse = function (data) {
  444. this._startPerformanceCounter("Parse");
  445. var parsedData;
  446. if (data instanceof ArrayBuffer) {
  447. this._log("Parsing binary");
  448. parsedData = this._parseBinary(data);
  449. }
  450. else {
  451. this._log("Parsing JSON");
  452. this._log("JSON length: " + data.length);
  453. parsedData = {
  454. json: JSON.parse(data),
  455. bin: null
  456. };
  457. }
  458. this.onParsedObservable.notifyObservers(parsedData);
  459. this.onParsedObservable.clear();
  460. this._endPerformanceCounter("Parse");
  461. return parsedData;
  462. };
  463. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  464. var asset = loaderData.json.asset || {};
  465. this._log("Asset version: " + asset.version);
  466. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  467. asset.generator && this._log("Asset generator: " + asset.generator);
  468. var version = GLTFFileLoader._parseVersion(asset.version);
  469. if (!version) {
  470. throw new Error("Invalid version: " + asset.version);
  471. }
  472. if (asset.minVersion !== undefined) {
  473. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  474. if (!minVersion) {
  475. throw new Error("Invalid minimum version: " + asset.minVersion);
  476. }
  477. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  478. throw new Error("Incompatible minimum version: " + asset.minVersion);
  479. }
  480. }
  481. var createLoaders = {
  482. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  483. 2: GLTFFileLoader._CreateGLTFLoaderV2
  484. };
  485. var createLoader = createLoaders[version.major];
  486. if (!createLoader) {
  487. throw new Error("Unsupported version: " + asset.version);
  488. }
  489. return createLoader(this);
  490. };
  491. GLTFFileLoader.prototype._parseBinary = function (data) {
  492. var Binary = {
  493. Magic: 0x46546C67
  494. };
  495. this._log("Binary length: " + data.byteLength);
  496. var binaryReader = new BinaryReader(data);
  497. var magic = binaryReader.readUint32();
  498. if (magic !== Binary.Magic) {
  499. throw new Error("Unexpected magic: " + magic);
  500. }
  501. var version = binaryReader.readUint32();
  502. if (this.loggingEnabled) {
  503. this._log("Binary version: " + version);
  504. }
  505. switch (version) {
  506. case 1: return this._parseV1(binaryReader);
  507. case 2: return this._parseV2(binaryReader);
  508. }
  509. throw new Error("Unsupported version: " + version);
  510. };
  511. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  512. var ContentFormat = {
  513. JSON: 0
  514. };
  515. var length = binaryReader.readUint32();
  516. if (length != binaryReader.getLength()) {
  517. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  518. }
  519. var contentLength = binaryReader.readUint32();
  520. var contentFormat = binaryReader.readUint32();
  521. var content;
  522. switch (contentFormat) {
  523. case ContentFormat.JSON: {
  524. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  525. break;
  526. }
  527. default: {
  528. throw new Error("Unexpected content format: " + contentFormat);
  529. }
  530. }
  531. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  532. var body = binaryReader.readUint8Array(bytesRemaining);
  533. return {
  534. json: content,
  535. bin: body
  536. };
  537. };
  538. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  539. var ChunkFormat = {
  540. JSON: 0x4E4F534A,
  541. BIN: 0x004E4942
  542. };
  543. var length = binaryReader.readUint32();
  544. if (length !== binaryReader.getLength()) {
  545. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  546. }
  547. // JSON chunk
  548. var chunkLength = binaryReader.readUint32();
  549. var chunkFormat = binaryReader.readUint32();
  550. if (chunkFormat !== ChunkFormat.JSON) {
  551. throw new Error("First chunk format is not JSON");
  552. }
  553. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  554. // Look for BIN chunk
  555. var bin = null;
  556. while (binaryReader.getPosition() < binaryReader.getLength()) {
  557. var chunkLength_1 = binaryReader.readUint32();
  558. var chunkFormat_1 = binaryReader.readUint32();
  559. switch (chunkFormat_1) {
  560. case ChunkFormat.JSON: {
  561. throw new Error("Unexpected JSON chunk");
  562. }
  563. case ChunkFormat.BIN: {
  564. bin = binaryReader.readUint8Array(chunkLength_1);
  565. break;
  566. }
  567. default: {
  568. // ignore unrecognized chunkFormat
  569. binaryReader.skipBytes(chunkLength_1);
  570. break;
  571. }
  572. }
  573. }
  574. return {
  575. json: json,
  576. bin: bin
  577. };
  578. };
  579. GLTFFileLoader._parseVersion = function (version) {
  580. if (version === "1.0" || version === "1.0.1") {
  581. return {
  582. major: 1,
  583. minor: 0
  584. };
  585. }
  586. var match = (version + "").match(/^(\d+)\.(\d+)/);
  587. if (!match) {
  588. return null;
  589. }
  590. return {
  591. major: parseInt(match[1]),
  592. minor: parseInt(match[2])
  593. };
  594. };
  595. GLTFFileLoader._compareVersion = function (a, b) {
  596. if (a.major > b.major)
  597. return 1;
  598. if (a.major < b.major)
  599. return -1;
  600. if (a.minor > b.minor)
  601. return 1;
  602. if (a.minor < b.minor)
  603. return -1;
  604. return 0;
  605. };
  606. GLTFFileLoader._decodeBufferToText = function (buffer) {
  607. var result = "";
  608. var length = buffer.byteLength;
  609. for (var i = 0; i < length; i++) {
  610. result += String.fromCharCode(buffer[i]);
  611. }
  612. return result;
  613. };
  614. /** @hidden */
  615. GLTFFileLoader.prototype._logOpen = function (message) {
  616. this._log(message);
  617. this._logIndentLevel++;
  618. };
  619. /** @hidden */
  620. GLTFFileLoader.prototype._logClose = function () {
  621. --this._logIndentLevel;
  622. };
  623. GLTFFileLoader.prototype._logEnabled = function (message) {
  624. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  625. BABYLON.Tools.Log("" + spaces + message);
  626. };
  627. GLTFFileLoader.prototype._logDisabled = function (message) {
  628. };
  629. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  630. BABYLON.Tools.StartPerformanceCounter(counterName);
  631. };
  632. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  633. };
  634. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  635. BABYLON.Tools.EndPerformanceCounter(counterName);
  636. };
  637. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  638. };
  639. // #endregion
  640. // #region V1 options
  641. /**
  642. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  643. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  644. * Defaults to true.
  645. * @hidden
  646. */
  647. GLTFFileLoader.IncrementalLoading = true;
  648. /**
  649. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  650. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  651. * @hidden
  652. */
  653. GLTFFileLoader.HomogeneousCoordinates = false;
  654. GLTFFileLoader._logSpaces = " ";
  655. return GLTFFileLoader;
  656. }());
  657. BABYLON.GLTFFileLoader = GLTFFileLoader;
  658. var BinaryReader = /** @class */ (function () {
  659. function BinaryReader(arrayBuffer) {
  660. this._arrayBuffer = arrayBuffer;
  661. this._dataView = new DataView(arrayBuffer);
  662. this._byteOffset = 0;
  663. }
  664. BinaryReader.prototype.getPosition = function () {
  665. return this._byteOffset;
  666. };
  667. BinaryReader.prototype.getLength = function () {
  668. return this._arrayBuffer.byteLength;
  669. };
  670. BinaryReader.prototype.readUint32 = function () {
  671. var value = this._dataView.getUint32(this._byteOffset, true);
  672. this._byteOffset += 4;
  673. return value;
  674. };
  675. BinaryReader.prototype.readUint8Array = function (length) {
  676. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  677. this._byteOffset += length;
  678. return value;
  679. };
  680. BinaryReader.prototype.skipBytes = function (length) {
  681. this._byteOffset += length;
  682. };
  683. return BinaryReader;
  684. }());
  685. if (BABYLON.SceneLoader) {
  686. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  687. }
  688. })(BABYLON || (BABYLON = {}));
  689. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  690. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  691. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  692. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  693. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  694. /**
  695. * Defines the module for importing and exporting glTF 2.0 assets
  696. */
  697. var BABYLON;
  698. (function (BABYLON) {
  699. var GLTF2;
  700. (function (GLTF2) {
  701. /**
  702. * Helper class for working with arrays when loading the glTF asset
  703. */
  704. var ArrayItem = /** @class */ (function () {
  705. function ArrayItem() {
  706. }
  707. /**
  708. * Gets an item from the given array.
  709. * @param context The context when loading the asset
  710. * @param array The array to get the item from
  711. * @param index The index to the array
  712. * @returns The array item
  713. */
  714. ArrayItem.Get = function (context, array, index) {
  715. if (!array || index == undefined || !array[index]) {
  716. throw new Error(context + ": Failed to find index (" + index + ")");
  717. }
  718. return array[index];
  719. };
  720. /**
  721. * Assign an `index` field to each item of the given array.
  722. * @param array The array of items
  723. */
  724. ArrayItem.Assign = function (array) {
  725. if (array) {
  726. for (var index = 0; index < array.length; index++) {
  727. array[index].index = index;
  728. }
  729. }
  730. };
  731. return ArrayItem;
  732. }());
  733. GLTF2.ArrayItem = ArrayItem;
  734. /**
  735. * The glTF 2.0 loader
  736. */
  737. var GLTFLoader = /** @class */ (function () {
  738. /** @hidden */
  739. function GLTFLoader(parent) {
  740. /** @hidden */
  741. this._completePromises = new Array();
  742. this._disposed = false;
  743. this._state = null;
  744. this._extensions = {};
  745. this._defaultBabylonMaterialData = {};
  746. this._requests = new Array();
  747. this._parent = parent;
  748. }
  749. /**
  750. * Registers a loader extension.
  751. * @param name The name of the loader extension.
  752. * @param factory The factory function that creates the loader extension.
  753. */
  754. GLTFLoader.RegisterExtension = function (name, factory) {
  755. if (GLTFLoader.UnregisterExtension(name)) {
  756. BABYLON.Tools.Warn("Extension with the name '" + name + "' already exists");
  757. }
  758. GLTFLoader._ExtensionFactories[name] = factory;
  759. // Keep the order of registration so that extensions registered first are called first.
  760. GLTFLoader._ExtensionNames.push(name);
  761. };
  762. /**
  763. * Unregisters a loader extension.
  764. * @param name The name of the loader extenion.
  765. * @returns A boolean indicating whether the extension has been unregistered
  766. */
  767. GLTFLoader.UnregisterExtension = function (name) {
  768. if (!GLTFLoader._ExtensionFactories[name]) {
  769. return false;
  770. }
  771. delete GLTFLoader._ExtensionFactories[name];
  772. var index = GLTFLoader._ExtensionNames.indexOf(name);
  773. if (index !== -1) {
  774. GLTFLoader._ExtensionNames.splice(index, 1);
  775. }
  776. return true;
  777. };
  778. Object.defineProperty(GLTFLoader.prototype, "state", {
  779. /**
  780. * Gets the loader state.
  781. */
  782. get: function () {
  783. return this._state;
  784. },
  785. enumerable: true,
  786. configurable: true
  787. });
  788. /** @hidden */
  789. GLTFLoader.prototype.dispose = function () {
  790. if (this._disposed) {
  791. return;
  792. }
  793. this._disposed = true;
  794. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  795. var request = _a[_i];
  796. request.abort();
  797. }
  798. this._requests.length = 0;
  799. delete this.gltf;
  800. delete this.babylonScene;
  801. this._completePromises.length = 0;
  802. for (var name_1 in this._extensions) {
  803. var extension = this._extensions[name_1];
  804. if (extension.dispose) {
  805. this._extensions[name_1].dispose();
  806. }
  807. }
  808. this._extensions = {};
  809. delete this._rootBabylonMesh;
  810. delete this._progressCallback;
  811. this._parent._clear();
  812. };
  813. /** @hidden */
  814. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fullName) {
  815. var _this = this;
  816. return Promise.resolve().then(function () {
  817. _this.babylonScene = scene;
  818. _this._rootUrl = rootUrl;
  819. _this._fullName = fullName || "" + Date.now();
  820. _this._progressCallback = onProgress;
  821. _this._loadData(data);
  822. var nodes = null;
  823. if (meshesNames) {
  824. var nodeMap_1 = {};
  825. if (_this.gltf.nodes) {
  826. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  827. var node = _a[_i];
  828. if (node.name) {
  829. nodeMap_1[node.name] = node.index;
  830. }
  831. }
  832. }
  833. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  834. nodes = names.map(function (name) {
  835. var node = nodeMap_1[name];
  836. if (node === undefined) {
  837. throw new Error("Failed to find node '" + name + "'");
  838. }
  839. return node;
  840. });
  841. }
  842. return _this._loadAsync(nodes, function () {
  843. return {
  844. meshes: _this._getMeshes(),
  845. particleSystems: [],
  846. skeletons: _this._getSkeletons(),
  847. animationGroups: _this._getAnimationGroups()
  848. };
  849. });
  850. });
  851. };
  852. /** @hidden */
  853. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fullName) {
  854. var _this = this;
  855. return Promise.resolve().then(function () {
  856. _this.babylonScene = scene;
  857. _this._rootUrl = rootUrl;
  858. _this._fullName = fullName || "" + Date.now();
  859. _this._progressCallback = onProgress;
  860. _this._loadData(data);
  861. return _this._loadAsync(null, function () { return undefined; });
  862. });
  863. };
  864. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  865. var _this = this;
  866. return Promise.resolve().then(function () {
  867. _this._loadExtensions();
  868. _this._checkExtensions();
  869. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  870. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  871. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  872. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  873. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  874. _this._extensionsOnLoading();
  875. var promises = new Array();
  876. if (nodes) {
  877. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  878. }
  879. else {
  880. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  881. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  882. }
  883. if (_this._parent.compileMaterials) {
  884. promises.push(_this._compileMaterialsAsync());
  885. }
  886. if (_this._parent.compileShadowGenerators) {
  887. promises.push(_this._compileShadowGeneratorsAsync());
  888. }
  889. var resultPromise = Promise.all(promises).then(function () {
  890. _this._setState(BABYLON.GLTFLoaderState.READY);
  891. _this._extensionsOnReady();
  892. _this._startAnimations();
  893. return resultFunc();
  894. });
  895. resultPromise.then(function () {
  896. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  897. BABYLON.Tools.SetImmediate(function () {
  898. if (!_this._disposed) {
  899. Promise.all(_this._completePromises).then(function () {
  900. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  901. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  902. _this._parent.onCompleteObservable.notifyObservers(undefined);
  903. _this._parent.onCompleteObservable.clear();
  904. _this.dispose();
  905. }, function (error) {
  906. _this._parent.onErrorObservable.notifyObservers(error);
  907. _this._parent.onErrorObservable.clear();
  908. _this.dispose();
  909. });
  910. }
  911. });
  912. });
  913. return resultPromise;
  914. }, function (error) {
  915. if (!_this._disposed) {
  916. _this._parent.onErrorObservable.notifyObservers(error);
  917. _this._parent.onErrorObservable.clear();
  918. _this.dispose();
  919. }
  920. throw error;
  921. });
  922. };
  923. GLTFLoader.prototype._loadData = function (data) {
  924. this.gltf = data.json;
  925. this._setupData();
  926. if (data.bin) {
  927. var buffers = this.gltf.buffers;
  928. if (buffers && buffers[0] && !buffers[0].uri) {
  929. var binaryBuffer = buffers[0];
  930. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  931. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  932. }
  933. binaryBuffer._data = Promise.resolve(data.bin);
  934. }
  935. else {
  936. BABYLON.Tools.Warn("Unexpected BIN chunk");
  937. }
  938. }
  939. };
  940. GLTFLoader.prototype._setupData = function () {
  941. ArrayItem.Assign(this.gltf.accessors);
  942. ArrayItem.Assign(this.gltf.animations);
  943. ArrayItem.Assign(this.gltf.buffers);
  944. ArrayItem.Assign(this.gltf.bufferViews);
  945. ArrayItem.Assign(this.gltf.cameras);
  946. ArrayItem.Assign(this.gltf.images);
  947. ArrayItem.Assign(this.gltf.materials);
  948. ArrayItem.Assign(this.gltf.meshes);
  949. ArrayItem.Assign(this.gltf.nodes);
  950. ArrayItem.Assign(this.gltf.samplers);
  951. ArrayItem.Assign(this.gltf.scenes);
  952. ArrayItem.Assign(this.gltf.skins);
  953. ArrayItem.Assign(this.gltf.textures);
  954. if (this.gltf.nodes) {
  955. var nodeParents = {};
  956. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  957. var node = _a[_i];
  958. if (node.children) {
  959. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  960. var index = _c[_b];
  961. nodeParents[index] = node.index;
  962. }
  963. }
  964. }
  965. var rootNode = this._createRootNode();
  966. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  967. var node = _e[_d];
  968. var parentIndex = nodeParents[node.index];
  969. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  970. }
  971. }
  972. };
  973. GLTFLoader.prototype._loadExtensions = function () {
  974. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  975. var name_2 = _a[_i];
  976. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  977. this._extensions[name_2] = extension;
  978. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  979. }
  980. this._parent.onExtensionLoadedObservable.clear();
  981. };
  982. GLTFLoader.prototype._checkExtensions = function () {
  983. if (this.gltf.extensionsRequired) {
  984. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  985. var name_3 = _a[_i];
  986. var extension = this._extensions[name_3];
  987. if (!extension || !extension.enabled) {
  988. throw new Error("Require extension " + name_3 + " is not available");
  989. }
  990. }
  991. }
  992. };
  993. GLTFLoader.prototype._setState = function (state) {
  994. this._state = state;
  995. this.log(BABYLON.GLTFLoaderState[this._state]);
  996. };
  997. GLTFLoader.prototype._createRootNode = function () {
  998. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this.babylonScene);
  999. var rootNode = {
  1000. _babylonMesh: this._rootBabylonMesh,
  1001. index: -1
  1002. };
  1003. switch (this._parent.coordinateSystemMode) {
  1004. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  1005. if (!this.babylonScene.useRightHandedSystem) {
  1006. rootNode.rotation = [0, 1, 0, 0];
  1007. rootNode.scale = [1, 1, -1];
  1008. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  1009. }
  1010. break;
  1011. }
  1012. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  1013. this.babylonScene.useRightHandedSystem = true;
  1014. break;
  1015. }
  1016. default: {
  1017. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  1018. }
  1019. }
  1020. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  1021. return rootNode;
  1022. };
  1023. /**
  1024. * Loads a glTF scene.
  1025. * @param context The context when loading the asset
  1026. * @param scene The glTF scene property
  1027. * @returns A promise that resolves when the load is complete
  1028. */
  1029. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  1030. var _this = this;
  1031. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  1032. if (extensionPromise) {
  1033. return extensionPromise;
  1034. }
  1035. var promises = new Array();
  1036. this.logOpen(context + " " + (scene.name || ""));
  1037. if (scene.nodes) {
  1038. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  1039. var index = _a[_i];
  1040. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  1041. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  1042. babylonMesh.parent = _this._rootBabylonMesh;
  1043. }));
  1044. }
  1045. }
  1046. promises.push(this._loadAnimationsAsync());
  1047. this.logClose();
  1048. return Promise.all(promises).then(function () { });
  1049. };
  1050. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  1051. if (node._primitiveBabylonMeshes) {
  1052. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  1053. var babylonMesh = _a[_i];
  1054. callback(babylonMesh);
  1055. }
  1056. }
  1057. else {
  1058. callback(node._babylonMesh);
  1059. }
  1060. };
  1061. GLTFLoader.prototype._getMeshes = function () {
  1062. var meshes = new Array();
  1063. // Root mesh is always first.
  1064. meshes.push(this._rootBabylonMesh);
  1065. var nodes = this.gltf.nodes;
  1066. if (nodes) {
  1067. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1068. var node = nodes_1[_i];
  1069. if (node._babylonMesh) {
  1070. meshes.push(node._babylonMesh);
  1071. }
  1072. if (node._primitiveBabylonMeshes) {
  1073. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  1074. var babylonMesh = _b[_a];
  1075. meshes.push(babylonMesh);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. return meshes;
  1081. };
  1082. GLTFLoader.prototype._getSkeletons = function () {
  1083. var skeletons = new Array();
  1084. var skins = this.gltf.skins;
  1085. if (skins) {
  1086. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1087. var skin = skins_1[_i];
  1088. if (skin._babylonSkeleton) {
  1089. skeletons.push(skin._babylonSkeleton);
  1090. }
  1091. }
  1092. }
  1093. return skeletons;
  1094. };
  1095. GLTFLoader.prototype._getAnimationGroups = function () {
  1096. var animationGroups = new Array();
  1097. var animations = this.gltf.animations;
  1098. if (animations) {
  1099. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1100. var animation = animations_1[_i];
  1101. if (animation._babylonAnimationGroup) {
  1102. animationGroups.push(animation._babylonAnimationGroup);
  1103. }
  1104. }
  1105. }
  1106. return animationGroups;
  1107. };
  1108. GLTFLoader.prototype._startAnimations = function () {
  1109. switch (this._parent.animationStartMode) {
  1110. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  1111. // do nothing
  1112. break;
  1113. }
  1114. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  1115. var babylonAnimationGroups = this._getAnimationGroups();
  1116. if (babylonAnimationGroups.length !== 0) {
  1117. babylonAnimationGroups[0].start(true);
  1118. }
  1119. break;
  1120. }
  1121. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  1122. var babylonAnimationGroups = this._getAnimationGroups();
  1123. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1124. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1125. babylonAnimationGroup.start(true);
  1126. }
  1127. break;
  1128. }
  1129. default: {
  1130. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1131. return;
  1132. }
  1133. }
  1134. };
  1135. /**
  1136. * Loads a glTF node.
  1137. * @param context The context when loading the asset
  1138. * @param node The glTF node property
  1139. * @param assign A function called synchronously after parsing the glTF properties
  1140. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  1141. */
  1142. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  1143. var _this = this;
  1144. if (assign === void 0) { assign = function () { }; }
  1145. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  1146. if (extensionPromise) {
  1147. return extensionPromise;
  1148. }
  1149. if (node._babylonMesh) {
  1150. throw new Error(context + ": Invalid recursive node hierarchy");
  1151. }
  1152. var promises = new Array();
  1153. this.logOpen(context + " " + (node.name || ""));
  1154. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node.index, this.babylonScene);
  1155. node._babylonMesh = babylonMesh;
  1156. babylonMesh.setEnabled(false);
  1157. GLTFLoader._LoadTransform(node, babylonMesh);
  1158. if (node.mesh != undefined) {
  1159. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  1160. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  1161. }
  1162. if (node.camera != undefined) {
  1163. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  1164. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  1165. babylonCamera.parent = babylonMesh;
  1166. }));
  1167. }
  1168. if (node.children) {
  1169. var _loop_1 = function (index) {
  1170. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  1171. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  1172. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1173. if (childNode.skin != undefined) {
  1174. childBabylonMesh.parent = _this._rootBabylonMesh;
  1175. return;
  1176. }
  1177. childBabylonMesh.parent = babylonMesh;
  1178. }));
  1179. };
  1180. var this_1 = this;
  1181. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1182. var index = _a[_i];
  1183. _loop_1(index);
  1184. }
  1185. }
  1186. assign(babylonMesh);
  1187. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1188. this.logClose();
  1189. return Promise.all(promises).then(function () {
  1190. babylonMesh.setEnabled(true);
  1191. return babylonMesh;
  1192. });
  1193. };
  1194. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  1195. var _this = this;
  1196. var promises = new Array();
  1197. this.logOpen(context + " " + (mesh.name || ""));
  1198. var primitives = mesh.primitives;
  1199. if (!primitives || primitives.length === 0) {
  1200. throw new Error(context + ": Primitives are missing");
  1201. }
  1202. ArrayItem.Assign(primitives);
  1203. if (primitives.length === 1) {
  1204. var primitive = primitives[0];
  1205. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  1206. }
  1207. else {
  1208. node._primitiveBabylonMeshes = [];
  1209. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1210. var primitive = primitives_1[_i];
  1211. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  1212. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  1213. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  1214. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1215. }
  1216. }
  1217. if (node.skin != undefined) {
  1218. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  1219. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  1220. }
  1221. this.logClose();
  1222. return Promise.all(promises).then(function () {
  1223. _this._forEachPrimitive(node, function (babylonMesh) {
  1224. babylonMesh._refreshBoundingInfo(true);
  1225. });
  1226. });
  1227. };
  1228. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  1229. var _this = this;
  1230. var promises = new Array();
  1231. this.logOpen("" + context);
  1232. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  1233. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  1234. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  1235. babylonGeometry.applyToMesh(babylonMesh);
  1236. });
  1237. }));
  1238. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  1239. if (primitive.material == undefined) {
  1240. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  1241. if (!babylonMaterial) {
  1242. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  1243. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1244. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  1245. }
  1246. babylonMesh.material = babylonMaterial;
  1247. }
  1248. else {
  1249. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  1250. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1251. babylonMesh.material = babylonMaterial;
  1252. }));
  1253. }
  1254. this.logClose();
  1255. return Promise.all(promises).then(function () { });
  1256. };
  1257. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1258. var _this = this;
  1259. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  1260. if (extensionPromise) {
  1261. return extensionPromise;
  1262. }
  1263. var attributes = primitive.attributes;
  1264. if (!attributes) {
  1265. throw new Error(context + ": Attributes are missing");
  1266. }
  1267. var promises = new Array();
  1268. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this.babylonScene);
  1269. if (primitive.indices == undefined) {
  1270. babylonMesh.isUnIndexed = true;
  1271. }
  1272. else {
  1273. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  1274. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1275. babylonGeometry.setIndices(data);
  1276. }));
  1277. }
  1278. var loadAttribute = function (attribute, kind, callback) {
  1279. if (attributes[attribute] == undefined) {
  1280. return;
  1281. }
  1282. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1283. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1284. babylonMesh._delayInfo.push(kind);
  1285. }
  1286. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1287. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  1288. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1289. }));
  1290. if (callback) {
  1291. callback(accessor);
  1292. }
  1293. };
  1294. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  1295. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  1296. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  1297. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  1298. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  1299. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  1300. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  1301. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  1302. if (accessor.type === "VEC4" /* VEC4 */) {
  1303. babylonMesh.hasVertexAlpha = true;
  1304. }
  1305. });
  1306. return Promise.all(promises).then(function () {
  1307. return babylonGeometry;
  1308. });
  1309. };
  1310. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1311. if (!primitive.targets) {
  1312. return;
  1313. }
  1314. if (node._numMorphTargets == undefined) {
  1315. node._numMorphTargets = primitive.targets.length;
  1316. }
  1317. else if (primitive.targets.length !== node._numMorphTargets) {
  1318. throw new Error(context + ": Primitives do not have the same number of targets");
  1319. }
  1320. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  1321. for (var index = 0; index < primitive.targets.length; index++) {
  1322. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1323. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  1324. // TODO: tell the target whether it has positions, normals, tangents
  1325. }
  1326. };
  1327. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1328. if (!primitive.targets) {
  1329. return Promise.resolve();
  1330. }
  1331. var promises = new Array();
  1332. var morphTargetManager = babylonMesh.morphTargetManager;
  1333. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1334. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1335. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1336. }
  1337. return Promise.all(promises).then(function () { });
  1338. };
  1339. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1340. var _this = this;
  1341. var promises = new Array();
  1342. var loadAttribute = function (attribute, kind, setData) {
  1343. if (attributes[attribute] == undefined) {
  1344. return;
  1345. }
  1346. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1347. if (!babylonVertexBuffer) {
  1348. return;
  1349. }
  1350. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1351. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1352. setData(babylonVertexBuffer, data);
  1353. }));
  1354. };
  1355. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1356. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1357. data[index] += value;
  1358. });
  1359. babylonMorphTarget.setPositions(data);
  1360. });
  1361. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1362. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1363. data[index] += value;
  1364. });
  1365. babylonMorphTarget.setNormals(data);
  1366. });
  1367. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1368. var dataIndex = 0;
  1369. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1370. // Tangent data for morph targets is stored as xyz delta.
  1371. // The vertexData.tangent is stored as xyzw.
  1372. // So we need to skip every fourth vertexData.tangent.
  1373. if (((index + 1) % 4) !== 0) {
  1374. data[dataIndex++] += value;
  1375. }
  1376. });
  1377. babylonMorphTarget.setTangents(data);
  1378. });
  1379. return Promise.all(promises).then(function () { });
  1380. };
  1381. GLTFLoader._LoadTransform = function (node, babylonNode) {
  1382. var position = BABYLON.Vector3.Zero();
  1383. var rotation = BABYLON.Quaternion.Identity();
  1384. var scaling = BABYLON.Vector3.One();
  1385. if (node.matrix) {
  1386. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  1387. matrix.decompose(scaling, rotation, position);
  1388. }
  1389. else {
  1390. if (node.translation)
  1391. position = BABYLON.Vector3.FromArray(node.translation);
  1392. if (node.rotation)
  1393. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  1394. if (node.scale)
  1395. scaling = BABYLON.Vector3.FromArray(node.scale);
  1396. }
  1397. babylonNode.position = position;
  1398. babylonNode.rotationQuaternion = rotation;
  1399. babylonNode.scaling = scaling;
  1400. };
  1401. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  1402. var _this = this;
  1403. var assignSkeleton = function (skeleton) {
  1404. _this._forEachPrimitive(node, function (babylonMesh) {
  1405. babylonMesh.skeleton = skeleton;
  1406. });
  1407. // Ignore the TRS of skinned nodes.
  1408. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1409. node._babylonMesh.position = BABYLON.Vector3.Zero();
  1410. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  1411. node._babylonMesh.scaling = BABYLON.Vector3.One();
  1412. };
  1413. if (skin._promise) {
  1414. return skin._promise.then(function () {
  1415. assignSkeleton(skin._babylonSkeleton);
  1416. });
  1417. }
  1418. var skeletonId = "skeleton" + skin.index;
  1419. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  1420. skin._babylonSkeleton = babylonSkeleton;
  1421. this._loadBones(context, skin);
  1422. assignSkeleton(babylonSkeleton);
  1423. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1424. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1425. }));
  1426. };
  1427. GLTFLoader.prototype._loadBones = function (context, skin) {
  1428. var babylonBones = {};
  1429. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1430. var index = _a[_i];
  1431. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  1432. this._loadBone(node, skin, babylonBones);
  1433. }
  1434. };
  1435. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  1436. var babylonBone = babylonBones[node.index];
  1437. if (babylonBone) {
  1438. return babylonBone;
  1439. }
  1440. var babylonParentBone = null;
  1441. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  1442. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  1443. }
  1444. var boneIndex = skin.joints.indexOf(node.index);
  1445. babylonBone = new BABYLON.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1446. babylonBones[node.index] = babylonBone;
  1447. node._babylonBones = node._babylonBones || [];
  1448. node._babylonBones.push(babylonBone);
  1449. return babylonBone;
  1450. };
  1451. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1452. if (skin.inverseBindMatrices == undefined) {
  1453. return Promise.resolve(null);
  1454. }
  1455. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  1456. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  1457. };
  1458. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1459. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1460. var babylonBone = _a[_i];
  1461. var baseMatrix = BABYLON.Matrix.Identity();
  1462. var boneIndex = babylonBone._index;
  1463. if (inverseBindMatricesData && boneIndex !== -1) {
  1464. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  1465. baseMatrix.invertToRef(baseMatrix);
  1466. }
  1467. var babylonParentBone = babylonBone.getParent();
  1468. if (babylonParentBone) {
  1469. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1470. }
  1471. babylonBone.updateMatrix(baseMatrix, false, false);
  1472. babylonBone._updateDifferenceMatrix(undefined, false);
  1473. }
  1474. };
  1475. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1476. return node.matrix ?
  1477. BABYLON.Matrix.FromArray(node.matrix) :
  1478. 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());
  1479. };
  1480. /**
  1481. * Loads a glTF camera.
  1482. * @param context The context when loading the asset
  1483. * @param camera The glTF camera property
  1484. * @param assign A function called synchronously after parsing the glTF properties
  1485. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  1486. */
  1487. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  1488. if (assign === void 0) { assign = function () { }; }
  1489. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  1490. if (extensionPromise) {
  1491. return extensionPromise;
  1492. }
  1493. var promises = new Array();
  1494. this.logOpen(context + " " + (camera.name || ""));
  1495. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera.index, BABYLON.Vector3.Zero(), this.babylonScene, false);
  1496. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  1497. switch (camera.type) {
  1498. case "perspective" /* PERSPECTIVE */: {
  1499. var perspective = camera.perspective;
  1500. if (!perspective) {
  1501. throw new Error(context + ": Camera perspective properties are missing");
  1502. }
  1503. babylonCamera.fov = perspective.yfov;
  1504. babylonCamera.minZ = perspective.znear;
  1505. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  1506. break;
  1507. }
  1508. case "orthographic" /* ORTHOGRAPHIC */: {
  1509. if (!camera.orthographic) {
  1510. throw new Error(context + ": Camera orthographic properties are missing");
  1511. }
  1512. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1513. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  1514. babylonCamera.orthoRight = camera.orthographic.xmag;
  1515. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  1516. babylonCamera.orthoTop = camera.orthographic.ymag;
  1517. babylonCamera.minZ = camera.orthographic.znear;
  1518. babylonCamera.maxZ = camera.orthographic.zfar;
  1519. break;
  1520. }
  1521. default: {
  1522. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  1523. }
  1524. }
  1525. assign(babylonCamera);
  1526. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  1527. return Promise.all(promises).then(function () {
  1528. return babylonCamera;
  1529. });
  1530. };
  1531. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1532. var animations = this.gltf.animations;
  1533. if (!animations) {
  1534. return Promise.resolve();
  1535. }
  1536. var promises = new Array();
  1537. for (var index = 0; index < animations.length; index++) {
  1538. var animation = animations[index];
  1539. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  1540. }
  1541. return Promise.all(promises).then(function () { });
  1542. };
  1543. /**
  1544. * Loads a glTF animation.
  1545. * @param context The context when loading the asset
  1546. * @param animation The glTF animation property
  1547. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  1548. */
  1549. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  1550. var _this = this;
  1551. var promise = this._extensionsLoadAnimationAsync(context, animation);
  1552. if (promise) {
  1553. return promise;
  1554. }
  1555. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  1556. animation._babylonAnimationGroup = babylonAnimationGroup;
  1557. var promises = new Array();
  1558. ArrayItem.Assign(animation.channels);
  1559. ArrayItem.Assign(animation.samplers);
  1560. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1561. var channel = _a[_i];
  1562. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  1563. }
  1564. return Promise.all(promises).then(function () {
  1565. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  1566. return babylonAnimationGroup;
  1567. });
  1568. };
  1569. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1570. var _this = this;
  1571. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  1572. // Ignore animations that have no animation targets.
  1573. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  1574. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  1575. return Promise.resolve();
  1576. }
  1577. // Ignore animations targeting TRS of skinned nodes.
  1578. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1579. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  1580. return Promise.resolve();
  1581. }
  1582. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  1583. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1584. var targetPath;
  1585. var animationType;
  1586. switch (channel.target.path) {
  1587. case "translation" /* TRANSLATION */: {
  1588. targetPath = "position";
  1589. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1590. break;
  1591. }
  1592. case "rotation" /* ROTATION */: {
  1593. targetPath = "rotationQuaternion";
  1594. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1595. break;
  1596. }
  1597. case "scale" /* SCALE */: {
  1598. targetPath = "scaling";
  1599. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1600. break;
  1601. }
  1602. case "weights" /* WEIGHTS */: {
  1603. targetPath = "influence";
  1604. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1605. break;
  1606. }
  1607. default: {
  1608. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  1609. }
  1610. }
  1611. var outputBufferOffset = 0;
  1612. var getNextOutputValue;
  1613. switch (targetPath) {
  1614. case "position": {
  1615. getNextOutputValue = function () {
  1616. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1617. outputBufferOffset += 3;
  1618. return value;
  1619. };
  1620. break;
  1621. }
  1622. case "rotationQuaternion": {
  1623. getNextOutputValue = function () {
  1624. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1625. outputBufferOffset += 4;
  1626. return value;
  1627. };
  1628. break;
  1629. }
  1630. case "scaling": {
  1631. getNextOutputValue = function () {
  1632. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1633. outputBufferOffset += 3;
  1634. return value;
  1635. };
  1636. break;
  1637. }
  1638. case "influence": {
  1639. getNextOutputValue = function () {
  1640. var value = new Array(targetNode._numMorphTargets);
  1641. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1642. value[i] = data.output[outputBufferOffset++];
  1643. }
  1644. return value;
  1645. };
  1646. break;
  1647. }
  1648. }
  1649. var getNextKey;
  1650. switch (data.interpolation) {
  1651. case "STEP" /* STEP */: {
  1652. getNextKey = function (frameIndex) { return ({
  1653. frame: data.input[frameIndex],
  1654. value: getNextOutputValue(),
  1655. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1656. }); };
  1657. break;
  1658. }
  1659. case "LINEAR" /* LINEAR */: {
  1660. getNextKey = function (frameIndex) { return ({
  1661. frame: data.input[frameIndex],
  1662. value: getNextOutputValue()
  1663. }); };
  1664. break;
  1665. }
  1666. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1667. getNextKey = function (frameIndex) { return ({
  1668. frame: data.input[frameIndex],
  1669. inTangent: getNextOutputValue(),
  1670. value: getNextOutputValue(),
  1671. outTangent: getNextOutputValue()
  1672. }); };
  1673. break;
  1674. }
  1675. }
  1676. var keys = new Array(data.input.length);
  1677. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1678. keys[frameIndex] = getNextKey(frameIndex);
  1679. }
  1680. if (targetPath === "influence") {
  1681. var _loop_2 = function (targetIndex) {
  1682. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1683. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1684. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1685. frame: key.frame,
  1686. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1687. value: key.value[targetIndex],
  1688. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1689. }); }));
  1690. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  1691. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1692. var babylonAnimationClone = babylonAnimation.clone();
  1693. morphTarget.animations.push(babylonAnimationClone);
  1694. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1695. });
  1696. };
  1697. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1698. _loop_2(targetIndex);
  1699. }
  1700. }
  1701. else {
  1702. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1703. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1704. babylonAnimation.setKeys(keys);
  1705. if (targetNode._babylonBones) {
  1706. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  1707. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  1708. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  1709. babylonAnimationTarget.animations.push(babylonAnimation);
  1710. }
  1711. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  1712. }
  1713. else {
  1714. targetNode._babylonMesh.animations.push(babylonAnimation);
  1715. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  1716. }
  1717. }
  1718. });
  1719. };
  1720. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1721. if (sampler._data) {
  1722. return sampler._data;
  1723. }
  1724. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1725. switch (interpolation) {
  1726. case "STEP" /* STEP */:
  1727. case "LINEAR" /* LINEAR */:
  1728. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1729. break;
  1730. }
  1731. default: {
  1732. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  1733. }
  1734. }
  1735. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  1736. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  1737. sampler._data = Promise.all([
  1738. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  1739. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  1740. ]).then(function (_a) {
  1741. var inputData = _a[0], outputData = _a[1];
  1742. return {
  1743. input: inputData,
  1744. interpolation: interpolation,
  1745. output: outputData,
  1746. };
  1747. });
  1748. return sampler._data;
  1749. };
  1750. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1751. if (buffer._data) {
  1752. return buffer._data;
  1753. }
  1754. if (!buffer.uri) {
  1755. throw new Error(context + "/uri: Value is missing");
  1756. }
  1757. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  1758. return buffer._data;
  1759. };
  1760. /**
  1761. * Loads a glTF buffer view.
  1762. * @param context The context when loading the asset
  1763. * @param bufferView The glTF buffer view property
  1764. * @returns A promise that resolves with the loaded data when the load is complete
  1765. */
  1766. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  1767. if (bufferView._data) {
  1768. return bufferView._data;
  1769. }
  1770. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  1771. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  1772. try {
  1773. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1774. }
  1775. catch (e) {
  1776. throw new Error(context + ": " + e.message);
  1777. }
  1778. });
  1779. return bufferView._data;
  1780. };
  1781. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  1782. if (accessor.type !== "SCALAR" /* SCALAR */) {
  1783. throw new Error(context + "/type: Invalid value " + accessor.type);
  1784. }
  1785. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  1786. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  1787. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  1788. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  1789. }
  1790. if (accessor._data) {
  1791. return accessor._data;
  1792. }
  1793. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1794. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1795. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1796. });
  1797. return accessor._data;
  1798. };
  1799. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  1800. // TODO: support normalized and stride
  1801. var _this = this;
  1802. if (accessor.componentType !== 5126 /* FLOAT */) {
  1803. throw new Error("Invalid component type " + accessor.componentType);
  1804. }
  1805. if (accessor._data) {
  1806. return accessor._data;
  1807. }
  1808. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1809. var length = numComponents * accessor.count;
  1810. if (accessor.bufferView == undefined) {
  1811. accessor._data = Promise.resolve(new Float32Array(length));
  1812. }
  1813. else {
  1814. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1815. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1816. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1817. });
  1818. }
  1819. if (accessor.sparse) {
  1820. var sparse_1 = accessor.sparse;
  1821. accessor._data = accessor._data.then(function (data) {
  1822. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  1823. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  1824. return Promise.all([
  1825. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  1826. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  1827. ]).then(function (_a) {
  1828. var indicesData = _a[0], valuesData = _a[1];
  1829. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  1830. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  1831. var valuesIndex = 0;
  1832. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1833. var dataIndex = indices[indicesIndex] * numComponents;
  1834. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1835. data[dataIndex++] = values[valuesIndex++];
  1836. }
  1837. }
  1838. return data;
  1839. });
  1840. });
  1841. }
  1842. return accessor._data;
  1843. };
  1844. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  1845. var _this = this;
  1846. if (bufferView._babylonBuffer) {
  1847. return bufferView._babylonBuffer;
  1848. }
  1849. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  1850. return new BABYLON.Buffer(_this.babylonScene.getEngine(), data, false);
  1851. });
  1852. return bufferView._babylonBuffer;
  1853. };
  1854. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  1855. var _this = this;
  1856. if (accessor._babylonVertexBuffer) {
  1857. return accessor._babylonVertexBuffer;
  1858. }
  1859. if (accessor.sparse) {
  1860. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1861. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  1862. });
  1863. }
  1864. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  1865. else if (accessor.byteOffset && accessor.byteOffset % BABYLON.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  1866. BABYLON.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  1867. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1868. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  1869. });
  1870. }
  1871. else {
  1872. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  1873. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  1874. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  1875. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1876. });
  1877. }
  1878. return accessor._babylonVertexBuffer;
  1879. };
  1880. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  1881. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  1882. throw new Error(context + ": Material type not supported");
  1883. }
  1884. var promises = new Array();
  1885. if (properties) {
  1886. if (properties.baseColorFactor) {
  1887. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1888. babylonMaterial.alpha = properties.baseColorFactor[3];
  1889. }
  1890. else {
  1891. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1892. }
  1893. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1894. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1895. if (properties.baseColorTexture) {
  1896. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  1897. babylonMaterial.albedoTexture = texture;
  1898. }));
  1899. }
  1900. if (properties.metallicRoughnessTexture) {
  1901. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  1902. babylonMaterial.metallicTexture = texture;
  1903. }));
  1904. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1905. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1906. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1907. }
  1908. }
  1909. return Promise.all(promises).then(function () { });
  1910. };
  1911. /** @hidden */
  1912. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  1913. if (assign === void 0) { assign = function () { }; }
  1914. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  1915. if (extensionPromise) {
  1916. return extensionPromise;
  1917. }
  1918. material._babylonData = material._babylonData || {};
  1919. var babylonData = material._babylonData[babylonDrawMode];
  1920. if (!babylonData) {
  1921. this.logOpen(context + " " + (material.name || ""));
  1922. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  1923. babylonData = {
  1924. material: babylonMaterial,
  1925. meshes: [],
  1926. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1927. };
  1928. material._babylonData[babylonDrawMode] = babylonData;
  1929. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1930. this.logClose();
  1931. }
  1932. babylonData.meshes.push(babylonMesh);
  1933. babylonMesh.onDisposeObservable.addOnce(function () {
  1934. var index = babylonData.meshes.indexOf(babylonMesh);
  1935. if (index !== -1) {
  1936. babylonData.meshes.splice(index, 1);
  1937. }
  1938. });
  1939. assign(babylonData.material);
  1940. return babylonData.promise.then(function () {
  1941. return babylonData.material;
  1942. });
  1943. };
  1944. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  1945. var babylonMaterial = new BABYLON.PBRMaterial(name, this.babylonScene);
  1946. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  1947. babylonMaterial.fillMode = babylonDrawMode;
  1948. babylonMaterial.enableSpecularAntiAliasing = true;
  1949. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1950. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1951. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1952. babylonMaterial.metallic = 1;
  1953. babylonMaterial.roughness = 1;
  1954. return babylonMaterial;
  1955. };
  1956. /**
  1957. * Creates a Babylon material from a glTF material.
  1958. * @param context The context when loading the asset
  1959. * @param material The glTF material property
  1960. * @param babylonDrawMode The draw mode for the Babylon material
  1961. * @returns The Babylon material
  1962. */
  1963. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  1964. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  1965. if (extensionPromise) {
  1966. return extensionPromise;
  1967. }
  1968. var name = material.name || "material" + material.index;
  1969. return this._createDefaultMaterial(name, babylonDrawMode);
  1970. };
  1971. /**
  1972. * Loads properties from a glTF material into a Babylon material.
  1973. * @param context The context when loading the asset
  1974. * @param material The glTF material property
  1975. * @param babylonMaterial The Babylon material
  1976. * @returns A promise that resolves when the load is complete
  1977. */
  1978. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1979. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  1980. if (extensionPromise) {
  1981. return extensionPromise;
  1982. }
  1983. var promises = new Array();
  1984. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1985. if (material.pbrMetallicRoughness) {
  1986. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material, material.pbrMetallicRoughness, babylonMaterial));
  1987. }
  1988. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  1989. return Promise.all(promises).then(function () { });
  1990. };
  1991. /**
  1992. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  1993. * @param context The context when loading the asset
  1994. * @param material The glTF material property
  1995. * @param babylonMaterial The Babylon material
  1996. * @returns A promise that resolves when the load is complete
  1997. */
  1998. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  1999. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2000. throw new Error(context + ": Material type not supported");
  2001. }
  2002. var promises = new Array();
  2003. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  2004. if (material.doubleSided) {
  2005. babylonMaterial.backFaceCulling = false;
  2006. babylonMaterial.twoSidedLighting = true;
  2007. }
  2008. if (material.normalTexture) {
  2009. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  2010. babylonMaterial.bumpTexture = texture;
  2011. }));
  2012. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  2013. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  2014. if (material.normalTexture.scale != undefined) {
  2015. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  2016. }
  2017. }
  2018. if (material.occlusionTexture) {
  2019. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  2020. babylonMaterial.ambientTexture = texture;
  2021. }));
  2022. babylonMaterial.useAmbientInGrayScale = true;
  2023. if (material.occlusionTexture.strength != undefined) {
  2024. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  2025. }
  2026. }
  2027. if (material.emissiveTexture) {
  2028. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  2029. babylonMaterial.emissiveTexture = texture;
  2030. }));
  2031. }
  2032. return Promise.all(promises).then(function () { });
  2033. };
  2034. /**
  2035. * Loads the alpha properties from a glTF material into a Babylon material.
  2036. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  2037. * @param context The context when loading the asset
  2038. * @param material The glTF material property
  2039. * @param babylonMaterial The Babylon material
  2040. */
  2041. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  2042. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  2043. throw new Error(context + ": Material type not supported");
  2044. }
  2045. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  2046. switch (alphaMode) {
  2047. case "OPAQUE" /* OPAQUE */: {
  2048. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  2049. break;
  2050. }
  2051. case "MASK" /* MASK */: {
  2052. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  2053. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  2054. if (babylonMaterial.albedoTexture) {
  2055. babylonMaterial.albedoTexture.hasAlpha = true;
  2056. }
  2057. break;
  2058. }
  2059. case "BLEND" /* BLEND */: {
  2060. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  2061. if (babylonMaterial.albedoTexture) {
  2062. babylonMaterial.albedoTexture.hasAlpha = true;
  2063. babylonMaterial.useAlphaFromAlbedoTexture = true;
  2064. }
  2065. break;
  2066. }
  2067. default: {
  2068. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  2069. }
  2070. }
  2071. };
  2072. /**
  2073. * Loads a glTF texture info.
  2074. * @param context The context when loading the asset
  2075. * @param textureInfo The glTF texture info property
  2076. * @param assign A function called synchronously after parsing the glTF properties
  2077. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  2078. */
  2079. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  2080. if (assign === void 0) { assign = function () { }; }
  2081. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  2082. if (extensionPromise) {
  2083. return extensionPromise;
  2084. }
  2085. this.logOpen("" + context);
  2086. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  2087. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  2088. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  2089. assign(babylonTexture);
  2090. });
  2091. this.logClose();
  2092. return promise;
  2093. };
  2094. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  2095. var _this = this;
  2096. if (assign === void 0) { assign = function () { }; }
  2097. var promises = new Array();
  2098. this.logOpen(context + " " + (texture.name || ""));
  2099. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  2100. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  2101. var deferred = new BABYLON.Deferred();
  2102. var babylonTexture = new BABYLON.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  2103. if (!_this._disposed) {
  2104. deferred.resolve();
  2105. }
  2106. }, function (message, exception) {
  2107. if (!_this._disposed) {
  2108. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  2109. }
  2110. });
  2111. promises.push(deferred.promise);
  2112. babylonTexture.name = texture.name || "texture" + texture.index;
  2113. babylonTexture.wrapU = samplerData.wrapU;
  2114. babylonTexture.wrapV = samplerData.wrapV;
  2115. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  2116. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  2117. var dataUrl = "data:" + _this._fullName + (image.uri || "image" + image.index);
  2118. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  2119. }));
  2120. assign(babylonTexture);
  2121. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  2122. this.logClose();
  2123. return Promise.all(promises).then(function () {
  2124. return babylonTexture;
  2125. });
  2126. };
  2127. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  2128. if (!sampler._data) {
  2129. sampler._data = {
  2130. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  2131. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  2132. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  2133. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  2134. };
  2135. }
  2136. ;
  2137. return sampler._data;
  2138. };
  2139. /**
  2140. * Loads a glTF image.
  2141. * @param context The context when loading the asset
  2142. * @param image The glTF image property
  2143. * @returns A promise that resolves with the loaded data when the load is complete
  2144. */
  2145. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  2146. if (!image._data) {
  2147. this.logOpen(context + " " + (image.name || ""));
  2148. if (image.uri) {
  2149. image._data = this.loadUriAsync(context + "/uri", image.uri);
  2150. }
  2151. else {
  2152. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  2153. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  2154. }
  2155. this.logClose();
  2156. }
  2157. return image._data;
  2158. };
  2159. /**
  2160. * Loads a glTF uri.
  2161. * @param context The context when loading the asset
  2162. * @param uri The base64 or relative uri
  2163. * @returns A promise that resolves with the loaded data when the load is complete
  2164. */
  2165. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  2166. var _this = this;
  2167. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  2168. if (extensionPromise) {
  2169. return extensionPromise;
  2170. }
  2171. if (!GLTFLoader._ValidateUri(uri)) {
  2172. throw new Error(context + ": '" + uri + "' is invalid");
  2173. }
  2174. if (BABYLON.Tools.IsBase64(uri)) {
  2175. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  2176. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  2177. return Promise.resolve(data);
  2178. }
  2179. this.log("Loading " + uri);
  2180. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  2181. return new Promise(function (resolve, reject) {
  2182. if (!_this._disposed) {
  2183. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  2184. if (!_this._disposed) {
  2185. var data = new Uint8Array(fileData);
  2186. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  2187. resolve(data);
  2188. }
  2189. }, function (event) {
  2190. if (!_this._disposed) {
  2191. if (request_1) {
  2192. request_1._lengthComputable = event.lengthComputable;
  2193. request_1._loaded = event.loaded;
  2194. request_1._total = event.total;
  2195. }
  2196. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  2197. try {
  2198. _this._onProgress();
  2199. }
  2200. catch (e) {
  2201. reject(e);
  2202. }
  2203. }
  2204. }
  2205. }, _this.babylonScene.database, true, function (request, exception) {
  2206. if (!_this._disposed) {
  2207. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2208. }
  2209. });
  2210. _this._requests.push(request_1);
  2211. }
  2212. });
  2213. });
  2214. };
  2215. GLTFLoader.prototype._onProgress = function () {
  2216. if (!this._progressCallback) {
  2217. return;
  2218. }
  2219. var lengthComputable = true;
  2220. var loaded = 0;
  2221. var total = 0;
  2222. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2223. var request = _a[_i];
  2224. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2225. return;
  2226. }
  2227. lengthComputable = lengthComputable && request._lengthComputable;
  2228. loaded += request._loaded;
  2229. total += request._total;
  2230. }
  2231. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2232. };
  2233. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  2234. // Set defaults if undefined
  2235. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2236. switch (mode) {
  2237. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2238. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2239. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2240. default:
  2241. BABYLON.Tools.Warn(context + ": Invalid value (" + mode + ")");
  2242. return BABYLON.Texture.WRAP_ADDRESSMODE;
  2243. }
  2244. };
  2245. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  2246. // Set defaults if undefined
  2247. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  2248. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  2249. if (magFilter === 9729 /* LINEAR */) {
  2250. switch (minFilter) {
  2251. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  2252. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  2253. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  2254. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  2255. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  2256. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2257. default:
  2258. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2259. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2260. }
  2261. }
  2262. else {
  2263. if (magFilter !== 9728 /* NEAREST */) {
  2264. BABYLON.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  2265. }
  2266. switch (minFilter) {
  2267. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  2268. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  2269. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2270. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  2271. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  2272. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  2273. default:
  2274. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2275. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2276. }
  2277. }
  2278. };
  2279. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2280. var buffer = bufferView.buffer;
  2281. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2282. try {
  2283. switch (componentType) {
  2284. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2285. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2286. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2287. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2288. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2289. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2290. default: throw new Error("Invalid component type " + componentType);
  2291. }
  2292. }
  2293. catch (e) {
  2294. throw new Error(context + ": " + e);
  2295. }
  2296. };
  2297. GLTFLoader._GetNumComponents = function (context, type) {
  2298. switch (type) {
  2299. case "SCALAR": return 1;
  2300. case "VEC2": return 2;
  2301. case "VEC3": return 3;
  2302. case "VEC4": return 4;
  2303. case "MAT2": return 4;
  2304. case "MAT3": return 9;
  2305. case "MAT4": return 16;
  2306. }
  2307. throw new Error(context + ": Invalid type (" + type + ")");
  2308. };
  2309. GLTFLoader._ValidateUri = function (uri) {
  2310. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2311. };
  2312. GLTFLoader._GetDrawMode = function (context, mode) {
  2313. if (mode == undefined) {
  2314. mode = 4 /* TRIANGLES */;
  2315. }
  2316. switch (mode) {
  2317. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  2318. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  2319. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  2320. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  2321. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  2322. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  2323. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  2324. }
  2325. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2326. };
  2327. GLTFLoader.prototype._compileMaterialsAsync = function () {
  2328. var _this = this;
  2329. this._parent._startPerformanceCounter("Compile materials");
  2330. var promises = new Array();
  2331. if (this.gltf.materials) {
  2332. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  2333. var material = _a[_i];
  2334. if (material._babylonData) {
  2335. for (var babylonDrawMode in material._babylonData) {
  2336. var babylonData = material._babylonData[babylonDrawMode];
  2337. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  2338. var babylonMesh = _c[_b];
  2339. // Ensure nonUniformScaling is set if necessary.
  2340. babylonMesh.computeWorldMatrix(true);
  2341. var babylonMaterial = babylonData.material;
  2342. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2343. if (this._parent.useClipPlane) {
  2344. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2345. }
  2346. }
  2347. }
  2348. }
  2349. }
  2350. }
  2351. return Promise.all(promises).then(function () {
  2352. _this._parent._endPerformanceCounter("Compile materials");
  2353. });
  2354. };
  2355. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  2356. var _this = this;
  2357. this._parent._startPerformanceCounter("Compile shadow generators");
  2358. var promises = new Array();
  2359. var lights = this.babylonScene.lights;
  2360. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2361. var light = lights_1[_i];
  2362. var generator = light.getShadowGenerator();
  2363. if (generator) {
  2364. promises.push(generator.forceCompilationAsync());
  2365. }
  2366. }
  2367. return Promise.all(promises).then(function () {
  2368. _this._parent._endPerformanceCounter("Compile shadow generators");
  2369. });
  2370. };
  2371. GLTFLoader.prototype._forEachExtensions = function (action) {
  2372. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2373. var name_4 = _a[_i];
  2374. var extension = this._extensions[name_4];
  2375. if (extension.enabled) {
  2376. action(extension);
  2377. }
  2378. }
  2379. };
  2380. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  2381. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2382. var name_5 = _a[_i];
  2383. var extension = this._extensions[name_5];
  2384. if (extension.enabled) {
  2385. var loaderProperty = property;
  2386. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  2387. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  2388. if (!activeLoaderExtensions[name_5]) {
  2389. activeLoaderExtensions[name_5] = true;
  2390. try {
  2391. var result = actionAsync(extension);
  2392. if (result) {
  2393. return result;
  2394. }
  2395. }
  2396. finally {
  2397. delete activeLoaderExtensions[name_5];
  2398. }
  2399. }
  2400. }
  2401. }
  2402. return null;
  2403. };
  2404. GLTFLoader.prototype._extensionsOnLoading = function () {
  2405. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  2406. };
  2407. GLTFLoader.prototype._extensionsOnReady = function () {
  2408. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  2409. };
  2410. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  2411. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  2412. };
  2413. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  2414. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  2415. };
  2416. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  2417. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  2418. };
  2419. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  2420. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2421. };
  2422. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2423. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  2424. };
  2425. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  2426. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  2427. };
  2428. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2429. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2430. };
  2431. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  2432. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  2433. };
  2434. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  2435. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  2436. };
  2437. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  2438. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  2439. };
  2440. /**
  2441. * Helper method called by a loader extension to load an glTF extension.
  2442. * @param context The context when loading the asset
  2443. * @param property The glTF property to load the extension from
  2444. * @param extensionName The name of the extension to load
  2445. * @param actionAsync The action to run
  2446. * @returns The promise returned by actionAsync or null if the extension does not exist
  2447. */
  2448. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  2449. if (!property.extensions) {
  2450. return null;
  2451. }
  2452. var extensions = property.extensions;
  2453. var extension = extensions[extensionName];
  2454. if (!extension) {
  2455. return null;
  2456. }
  2457. return actionAsync(context + "/extensions/" + extensionName, extension);
  2458. };
  2459. /**
  2460. * Helper method called by a loader extension to load a glTF extra.
  2461. * @param context The context when loading the asset
  2462. * @param property The glTF property to load the extra from
  2463. * @param extensionName The name of the extension to load
  2464. * @param actionAsync The action to run
  2465. * @returns The promise returned by actionAsync or null if the extra does not exist
  2466. */
  2467. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  2468. if (!property.extras) {
  2469. return null;
  2470. }
  2471. var extras = property.extras;
  2472. var extra = extras[extensionName];
  2473. if (!extra) {
  2474. return null;
  2475. }
  2476. return actionAsync(context + "/extras/" + extensionName, extra);
  2477. };
  2478. /**
  2479. * Increments the indentation level and logs a message.
  2480. * @param message The message to log
  2481. */
  2482. GLTFLoader.prototype.logOpen = function (message) {
  2483. this._parent._logOpen(message);
  2484. };
  2485. /**
  2486. * Decrements the indentation level.
  2487. */
  2488. GLTFLoader.prototype.logClose = function () {
  2489. this._parent._logClose();
  2490. };
  2491. /**
  2492. * Logs a message
  2493. * @param message The message to log
  2494. */
  2495. GLTFLoader.prototype.log = function (message) {
  2496. this._parent._log(message);
  2497. };
  2498. /**
  2499. * Starts a performance counter.
  2500. * @param counterName The name of the performance counter
  2501. */
  2502. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  2503. this._parent._startPerformanceCounter(counterName);
  2504. };
  2505. /**
  2506. * Ends a performance counter.
  2507. * @param counterName The name of the performance counter
  2508. */
  2509. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  2510. this._parent._endPerformanceCounter(counterName);
  2511. };
  2512. GLTFLoader._DefaultSampler = { index: -1 };
  2513. GLTFLoader._ExtensionNames = new Array();
  2514. GLTFLoader._ExtensionFactories = {};
  2515. return GLTFLoader;
  2516. }());
  2517. GLTF2.GLTFLoader = GLTFLoader;
  2518. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  2519. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2520. })(BABYLON || (BABYLON = {}));
  2521. //# sourceMappingURL=babylon.glTFLoader.js.map
  2522. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2523. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2524. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2525. var BABYLON;
  2526. (function (BABYLON) {
  2527. var GLTF2;
  2528. (function (GLTF2) {
  2529. var Extensions;
  2530. (function (Extensions) {
  2531. var NAME = "MSFT_audio_emitter";
  2532. /**
  2533. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  2534. */
  2535. var MSFT_audio_emitter = /** @class */ (function () {
  2536. /** @hidden */
  2537. function MSFT_audio_emitter(loader) {
  2538. /** The name of this extension. */
  2539. this.name = NAME;
  2540. /** Defines whether this extension is enabled. */
  2541. this.enabled = true;
  2542. this._loader = loader;
  2543. }
  2544. /** @hidden */
  2545. MSFT_audio_emitter.prototype.dispose = function () {
  2546. delete this._loader;
  2547. delete this._clips;
  2548. delete this._emitters;
  2549. };
  2550. /** @hidden */
  2551. MSFT_audio_emitter.prototype.onLoading = function () {
  2552. var extensions = this._loader.gltf.extensions;
  2553. if (extensions && extensions[this.name]) {
  2554. var extension = extensions[this.name];
  2555. this._clips = extension.clips;
  2556. this._emitters = extension.emitters;
  2557. GLTF2.ArrayItem.Assign(this._clips);
  2558. GLTF2.ArrayItem.Assign(this._emitters);
  2559. }
  2560. };
  2561. /** @hidden */
  2562. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  2563. var _this = this;
  2564. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  2565. var promises = new Array();
  2566. promises.push(_this._loader.loadSceneAsync(context, scene));
  2567. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  2568. var emitterIndex = _a[_i];
  2569. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  2570. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  2571. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  2572. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  2573. }
  2574. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  2575. }
  2576. return Promise.all(promises).then(function () { });
  2577. });
  2578. };
  2579. /** @hidden */
  2580. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  2581. var _this = this;
  2582. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  2583. var promises = new Array();
  2584. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  2585. var _loop_1 = function (emitterIndex) {
  2586. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  2587. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  2588. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  2589. var sound = _a[_i];
  2590. sound.attachToMesh(babylonMesh);
  2591. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  2592. sound.setLocalDirectionToMesh(BABYLON.Vector3.Forward());
  2593. sound.setDirectionalCone(2 * BABYLON.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  2594. }
  2595. }
  2596. }));
  2597. };
  2598. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  2599. var emitterIndex = _a[_i];
  2600. _loop_1(emitterIndex);
  2601. }
  2602. assign(babylonMesh);
  2603. }).then(function (babylonMesh) {
  2604. return Promise.all(promises).then(function () {
  2605. return babylonMesh;
  2606. });
  2607. });
  2608. });
  2609. };
  2610. /** @hidden */
  2611. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  2612. var _this = this;
  2613. return GLTF2.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  2614. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  2615. var promises = new Array();
  2616. GLTF2.ArrayItem.Assign(extension.events);
  2617. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  2618. var event_1 = _a[_i];
  2619. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  2620. }
  2621. return Promise.all(promises).then(function () {
  2622. return babylonAnimationGroup;
  2623. });
  2624. });
  2625. });
  2626. };
  2627. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  2628. if (clip._objectURL) {
  2629. return clip._objectURL;
  2630. }
  2631. var promise;
  2632. if (clip.uri) {
  2633. promise = this._loader.loadUriAsync(context, clip.uri);
  2634. }
  2635. else {
  2636. var bufferView = GLTF2.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  2637. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  2638. }
  2639. clip._objectURL = promise.then(function (data) {
  2640. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  2641. });
  2642. return clip._objectURL;
  2643. };
  2644. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  2645. var _this = this;
  2646. emitter._babylonSounds = emitter._babylonSounds || [];
  2647. if (!emitter._babylonData) {
  2648. var clipPromises = new Array();
  2649. var name_1 = emitter.name || "emitter" + emitter.index;
  2650. var options_1 = {
  2651. loop: false,
  2652. autoplay: false,
  2653. volume: emitter.volume == undefined ? 1 : emitter.volume,
  2654. };
  2655. var _loop_2 = function (i) {
  2656. var clipContext = "#/extensions/" + this_1.name + "/clips";
  2657. var clip = GLTF2.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  2658. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  2659. var sound = emitter._babylonSounds[i] = new BABYLON.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  2660. sound.refDistance = emitter.refDistance || 1;
  2661. sound.maxDistance = emitter.maxDistance || 256;
  2662. sound.rolloffFactor = emitter.rolloffFactor || 1;
  2663. sound.distanceModel = emitter.distanceModel || 'exponential';
  2664. sound._positionInEmitterSpace = true;
  2665. }));
  2666. };
  2667. var this_1 = this;
  2668. for (var i = 0; i < emitter.clips.length; i++) {
  2669. _loop_2(i);
  2670. }
  2671. var promise = Promise.all(clipPromises).then(function () {
  2672. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  2673. var weightedSound = new BABYLON.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  2674. if (emitter.innerAngle)
  2675. weightedSound.directionalConeInnerAngle = 2 * BABYLON.Tools.ToDegrees(emitter.innerAngle);
  2676. if (emitter.outerAngle)
  2677. weightedSound.directionalConeOuterAngle = 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle);
  2678. if (emitter.volume)
  2679. weightedSound.volume = emitter.volume;
  2680. emitter._babylonData.sound = weightedSound;
  2681. });
  2682. emitter._babylonData = {
  2683. loaded: promise
  2684. };
  2685. }
  2686. return emitter._babylonData.loaded;
  2687. };
  2688. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  2689. switch (action) {
  2690. case "play" /* play */: {
  2691. return function (currentFrame) {
  2692. var frameOffset = (startOffset || 0) + (currentFrame - time);
  2693. sound.play(frameOffset);
  2694. };
  2695. }
  2696. case "stop" /* stop */: {
  2697. return function (currentFrame) {
  2698. sound.stop();
  2699. };
  2700. }
  2701. case "pause" /* pause */: {
  2702. return function (currentFrame) {
  2703. sound.pause();
  2704. };
  2705. }
  2706. default: {
  2707. throw new Error(context + ": Unsupported action " + action);
  2708. }
  2709. }
  2710. };
  2711. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  2712. var _this = this;
  2713. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  2714. return Promise.resolve();
  2715. }
  2716. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  2717. var emitterIndex = event.emitter;
  2718. var emitter = GLTF2.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  2719. return this._loadEmitterAsync(context, emitter).then(function () {
  2720. var sound = emitter._babylonData.sound;
  2721. if (sound) {
  2722. var babylonAnimationEvent = new BABYLON.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  2723. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  2724. // Make sure all started audio stops when this animation is terminated.
  2725. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  2726. sound.stop();
  2727. });
  2728. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  2729. sound.pause();
  2730. });
  2731. }
  2732. });
  2733. };
  2734. return MSFT_audio_emitter;
  2735. }());
  2736. Extensions.MSFT_audio_emitter = MSFT_audio_emitter;
  2737. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  2738. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2739. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2740. })(BABYLON || (BABYLON = {}));
  2741. //# sourceMappingURL=MSFT_audio_emitter.js.map
  2742. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2743. var BABYLON;
  2744. (function (BABYLON) {
  2745. var GLTF2;
  2746. (function (GLTF2) {
  2747. var Extensions;
  2748. (function (Extensions) {
  2749. var NAME = "MSFT_lod";
  2750. /**
  2751. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  2752. */
  2753. var MSFT_lod = /** @class */ (function () {
  2754. /** @hidden */
  2755. function MSFT_lod(loader) {
  2756. /** The name of this extension. */
  2757. this.name = NAME;
  2758. /** Defines whether this extension is enabled. */
  2759. this.enabled = true;
  2760. /**
  2761. * Maximum number of LODs to load, starting from the lowest LOD.
  2762. */
  2763. this.maxLODsToLoad = Number.MAX_VALUE;
  2764. /**
  2765. * Observable raised when all node LODs of one level are loaded.
  2766. * The event data is the index of the loaded LOD starting from zero.
  2767. * Dispose the loader to cancel the loading of the next level of LODs.
  2768. */
  2769. this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  2770. /**
  2771. * Observable raised when all material LODs of one level are loaded.
  2772. * The event data is the index of the loaded LOD starting from zero.
  2773. * Dispose the loader to cancel the loading of the next level of LODs.
  2774. */
  2775. this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  2776. this._nodeIndexLOD = null;
  2777. this._nodeSignalLODs = new Array();
  2778. this._nodePromiseLODs = new Array();
  2779. this._materialIndexLOD = null;
  2780. this._materialSignalLODs = new Array();
  2781. this._materialPromiseLODs = new Array();
  2782. this._loader = loader;
  2783. }
  2784. /** @hidden */
  2785. MSFT_lod.prototype.dispose = function () {
  2786. delete this._loader;
  2787. this._nodeIndexLOD = null;
  2788. this._nodeSignalLODs.length = 0;
  2789. this._nodePromiseLODs.length = 0;
  2790. this._materialIndexLOD = null;
  2791. this._materialSignalLODs.length = 0;
  2792. this._materialPromiseLODs.length = 0;
  2793. this.onMaterialLODsLoadedObservable.clear();
  2794. this.onNodeLODsLoadedObservable.clear();
  2795. };
  2796. /** @hidden */
  2797. MSFT_lod.prototype.onReady = function () {
  2798. var _this = this;
  2799. var _loop_1 = function (indexLOD) {
  2800. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  2801. if (indexLOD !== 0) {
  2802. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  2803. }
  2804. _this._loader.log("Loaded node LOD " + indexLOD);
  2805. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  2806. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  2807. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  2808. if (_this._nodeSignalLODs[indexLOD]) {
  2809. _this._nodeSignalLODs[indexLOD].resolve();
  2810. }
  2811. }
  2812. });
  2813. this_1._loader._completePromises.push(promise);
  2814. };
  2815. var this_1 = this;
  2816. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  2817. _loop_1(indexLOD);
  2818. }
  2819. var _loop_2 = function (indexLOD) {
  2820. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  2821. if (indexLOD !== 0) {
  2822. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  2823. }
  2824. _this._loader.log("Loaded material LOD " + indexLOD);
  2825. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  2826. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  2827. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  2828. if (_this._materialSignalLODs[indexLOD]) {
  2829. _this._materialSignalLODs[indexLOD].resolve();
  2830. }
  2831. }
  2832. });
  2833. this_2._loader._completePromises.push(promise);
  2834. };
  2835. var this_2 = this;
  2836. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  2837. _loop_2(indexLOD);
  2838. }
  2839. };
  2840. /** @hidden */
  2841. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  2842. var _this = this;
  2843. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  2844. var firstPromise;
  2845. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  2846. _this._loader.logOpen("" + extensionContext);
  2847. var _loop_3 = function (indexLOD) {
  2848. var nodeLOD = nodeLODs[indexLOD];
  2849. if (indexLOD !== 0) {
  2850. _this._nodeIndexLOD = indexLOD;
  2851. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  2852. }
  2853. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  2854. if (indexLOD !== 0) {
  2855. // TODO: should not rely on _babylonMesh
  2856. var previousNodeLOD = nodeLODs[indexLOD - 1];
  2857. if (previousNodeLOD._babylonMesh) {
  2858. previousNodeLOD._babylonMesh.dispose();
  2859. delete previousNodeLOD._babylonMesh;
  2860. _this._disposeUnusedMaterials();
  2861. }
  2862. }
  2863. return babylonMesh;
  2864. });
  2865. if (indexLOD === 0) {
  2866. firstPromise = promise;
  2867. }
  2868. else {
  2869. _this._nodeIndexLOD = null;
  2870. }
  2871. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  2872. _this._nodePromiseLODs[indexLOD].push(promise);
  2873. };
  2874. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  2875. _loop_3(indexLOD);
  2876. }
  2877. _this._loader.logClose();
  2878. return firstPromise;
  2879. });
  2880. };
  2881. /** @hidden */
  2882. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2883. var _this = this;
  2884. // Don't load material LODs if already loading a node LOD.
  2885. if (this._nodeIndexLOD) {
  2886. return null;
  2887. }
  2888. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  2889. var firstPromise;
  2890. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  2891. _this._loader.logOpen("" + extensionContext);
  2892. var _loop_4 = function (indexLOD) {
  2893. var materialLOD = materialLODs[indexLOD];
  2894. if (indexLOD !== 0) {
  2895. _this._materialIndexLOD = indexLOD;
  2896. }
  2897. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  2898. if (indexLOD === 0) {
  2899. assign(babylonMaterial);
  2900. }
  2901. }).then(function (babylonMaterial) {
  2902. if (indexLOD !== 0) {
  2903. assign(babylonMaterial);
  2904. // TODO: should not rely on _babylonData
  2905. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  2906. if (previousBabylonDataLOD[babylonDrawMode]) {
  2907. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  2908. delete previousBabylonDataLOD[babylonDrawMode];
  2909. }
  2910. }
  2911. return babylonMaterial;
  2912. });
  2913. if (indexLOD === 0) {
  2914. firstPromise = promise;
  2915. }
  2916. else {
  2917. _this._materialIndexLOD = null;
  2918. }
  2919. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  2920. _this._materialPromiseLODs[indexLOD].push(promise);
  2921. };
  2922. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2923. _loop_4(indexLOD);
  2924. }
  2925. _this._loader.logClose();
  2926. return firstPromise;
  2927. });
  2928. };
  2929. /** @hidden */
  2930. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2931. var _this = this;
  2932. // Defer the loading of uris if loading a material or node LOD.
  2933. if (this._materialIndexLOD !== null) {
  2934. this._loader.log("deferred");
  2935. var previousIndexLOD = this._materialIndexLOD - 1;
  2936. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2937. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  2938. return _this._loader.loadUriAsync(context, uri);
  2939. });
  2940. }
  2941. else if (this._nodeIndexLOD !== null) {
  2942. this._loader.log("deferred");
  2943. var previousIndexLOD = this._nodeIndexLOD - 1;
  2944. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2945. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  2946. return _this._loader.loadUriAsync(context, uri);
  2947. });
  2948. }
  2949. return null;
  2950. };
  2951. /**
  2952. * Gets an array of LOD properties from lowest to highest.
  2953. */
  2954. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2955. if (this.maxLODsToLoad <= 0) {
  2956. throw new Error("maxLODsToLoad must be greater than zero");
  2957. }
  2958. var properties = new Array();
  2959. for (var i = ids.length - 1; i >= 0; i--) {
  2960. properties.push(GLTF2.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  2961. if (properties.length === this.maxLODsToLoad) {
  2962. return properties;
  2963. }
  2964. }
  2965. properties.push(property);
  2966. return properties;
  2967. };
  2968. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  2969. // TODO: should not rely on _babylonData
  2970. var materials = this._loader.gltf.materials;
  2971. if (materials) {
  2972. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  2973. var material = materials_1[_i];
  2974. if (material._babylonData) {
  2975. for (var drawMode in material._babylonData) {
  2976. var babylonData = material._babylonData[drawMode];
  2977. if (babylonData.meshes.length === 0) {
  2978. babylonData.material.dispose(false, true);
  2979. delete material._babylonData[drawMode];
  2980. }
  2981. }
  2982. }
  2983. }
  2984. }
  2985. };
  2986. return MSFT_lod;
  2987. }());
  2988. Extensions.MSFT_lod = MSFT_lod;
  2989. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  2990. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2991. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2992. })(BABYLON || (BABYLON = {}));
  2993. //# sourceMappingURL=MSFT_lod.js.map
  2994. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2995. var BABYLON;
  2996. (function (BABYLON) {
  2997. var GLTF2;
  2998. (function (GLTF2) {
  2999. var Extensions;
  3000. (function (Extensions) {
  3001. var NAME = "MSFT_minecraftMesh";
  3002. /** @hidden */
  3003. var MSFT_minecraftMesh = /** @class */ (function () {
  3004. function MSFT_minecraftMesh(loader) {
  3005. this.name = NAME;
  3006. this.enabled = true;
  3007. this._loader = loader;
  3008. }
  3009. MSFT_minecraftMesh.prototype.dispose = function () {
  3010. delete this._loader;
  3011. };
  3012. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3013. var _this = this;
  3014. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  3015. if (extra) {
  3016. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3017. throw new Error(extraContext + ": Material type not supported");
  3018. }
  3019. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  3020. if (babylonMaterial.needAlphaBlending()) {
  3021. babylonMaterial.forceDepthWrite = true;
  3022. babylonMaterial.separateCullingPass = true;
  3023. }
  3024. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  3025. babylonMaterial.twoSidedLighting = true;
  3026. return promise;
  3027. }
  3028. return null;
  3029. });
  3030. };
  3031. return MSFT_minecraftMesh;
  3032. }());
  3033. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  3034. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  3035. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3036. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3037. })(BABYLON || (BABYLON = {}));
  3038. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  3039. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3040. var BABYLON;
  3041. (function (BABYLON) {
  3042. var GLTF2;
  3043. (function (GLTF2) {
  3044. var Extensions;
  3045. (function (Extensions) {
  3046. var NAME = "MSFT_sRGBFactors";
  3047. /** @hidden */
  3048. var MSFT_sRGBFactors = /** @class */ (function () {
  3049. function MSFT_sRGBFactors(loader) {
  3050. this.name = NAME;
  3051. this.enabled = true;
  3052. this._loader = loader;
  3053. }
  3054. MSFT_sRGBFactors.prototype.dispose = function () {
  3055. delete this._loader;
  3056. };
  3057. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3058. var _this = this;
  3059. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  3060. if (extra) {
  3061. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3062. throw new Error(extraContext + ": Material type not supported");
  3063. }
  3064. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  3065. if (!babylonMaterial.albedoTexture) {
  3066. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  3067. }
  3068. if (!babylonMaterial.reflectivityTexture) {
  3069. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  3070. }
  3071. return promise;
  3072. }
  3073. return null;
  3074. });
  3075. };
  3076. return MSFT_sRGBFactors;
  3077. }());
  3078. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  3079. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  3080. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3081. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3082. })(BABYLON || (BABYLON = {}));
  3083. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  3084. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3085. var BABYLON;
  3086. (function (BABYLON) {
  3087. var GLTF2;
  3088. (function (GLTF2) {
  3089. var Extensions;
  3090. (function (Extensions) {
  3091. var NAME = "KHR_draco_mesh_compression";
  3092. /**
  3093. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  3094. */
  3095. var KHR_draco_mesh_compression = /** @class */ (function () {
  3096. /** @hidden */
  3097. function KHR_draco_mesh_compression(loader) {
  3098. /** The name of this extension. */
  3099. this.name = NAME;
  3100. /** Defines whether this extension is enabled. */
  3101. this.enabled = BABYLON.DracoCompression.DecoderAvailable;
  3102. this._loader = loader;
  3103. }
  3104. /** @hidden */
  3105. KHR_draco_mesh_compression.prototype.dispose = function () {
  3106. if (this._dracoCompression) {
  3107. this._dracoCompression.dispose();
  3108. delete this._dracoCompression;
  3109. }
  3110. delete this._loader;
  3111. };
  3112. /** @hidden */
  3113. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3114. var _this = this;
  3115. return GLTF2.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  3116. if (primitive.mode != undefined) {
  3117. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  3118. primitive.mode !== 4 /* TRIANGLES */) {
  3119. throw new Error(context + ": Unsupported mode " + primitive.mode);
  3120. }
  3121. // TODO: handle triangle strips
  3122. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  3123. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3124. }
  3125. }
  3126. var attributes = {};
  3127. var loadAttribute = function (name, kind) {
  3128. var uniqueId = extension.attributes[name];
  3129. if (uniqueId == undefined) {
  3130. return;
  3131. }
  3132. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3133. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3134. babylonMesh._delayInfo.push(kind);
  3135. }
  3136. attributes[kind] = uniqueId;
  3137. };
  3138. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3139. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3140. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3141. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3142. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3143. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3144. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3145. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3146. var bufferView = GLTF2.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  3147. if (!bufferView._dracoBabylonGeometry) {
  3148. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  3149. if (!_this._dracoCompression) {
  3150. _this._dracoCompression = new BABYLON.DracoCompression();
  3151. }
  3152. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  3153. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader.babylonScene);
  3154. babylonVertexData.applyToGeometry(babylonGeometry);
  3155. return babylonGeometry;
  3156. }).catch(function (error) {
  3157. throw new Error(context + ": " + error.message);
  3158. });
  3159. });
  3160. }
  3161. return bufferView._dracoBabylonGeometry;
  3162. });
  3163. };
  3164. return KHR_draco_mesh_compression;
  3165. }());
  3166. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  3167. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  3168. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3169. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3170. })(BABYLON || (BABYLON = {}));
  3171. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  3172. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3173. var BABYLON;
  3174. (function (BABYLON) {
  3175. var GLTF2;
  3176. (function (GLTF2) {
  3177. var Extensions;
  3178. (function (Extensions) {
  3179. var NAME = "KHR_materials_pbrSpecularGlossiness";
  3180. /**
  3181. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  3182. */
  3183. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  3184. /** @hidden */
  3185. function KHR_materials_pbrSpecularGlossiness(loader) {
  3186. /** The name of this extension. */
  3187. this.name = NAME;
  3188. /** Defines whether this extension is enabled. */
  3189. this.enabled = true;
  3190. this._loader = loader;
  3191. }
  3192. /** @hidden */
  3193. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  3194. delete this._loader;
  3195. };
  3196. /** @hidden */
  3197. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3198. var _this = this;
  3199. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  3200. var promises = new Array();
  3201. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3202. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  3203. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3204. return Promise.all(promises).then(function () { });
  3205. });
  3206. };
  3207. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  3208. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3209. throw new Error(context + ": Material type not supported");
  3210. }
  3211. var promises = new Array();
  3212. babylonMaterial.metallic = null;
  3213. babylonMaterial.roughness = null;
  3214. if (properties.diffuseFactor) {
  3215. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  3216. babylonMaterial.alpha = properties.diffuseFactor[3];
  3217. }
  3218. else {
  3219. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3220. }
  3221. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  3222. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  3223. if (properties.diffuseTexture) {
  3224. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  3225. babylonMaterial.albedoTexture = texture;
  3226. return Promise.resolve();
  3227. }));
  3228. }
  3229. if (properties.specularGlossinessTexture) {
  3230. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  3231. babylonMaterial.reflectivityTexture = texture;
  3232. return Promise.resolve();
  3233. }));
  3234. babylonMaterial.reflectivityTexture.hasAlpha = true;
  3235. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3236. }
  3237. return Promise.all(promises).then(function () { });
  3238. };
  3239. return KHR_materials_pbrSpecularGlossiness;
  3240. }());
  3241. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  3242. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  3243. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3244. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3245. })(BABYLON || (BABYLON = {}));
  3246. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  3247. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3248. var BABYLON;
  3249. (function (BABYLON) {
  3250. var GLTF2;
  3251. (function (GLTF2) {
  3252. var Extensions;
  3253. (function (Extensions) {
  3254. var NAME = "KHR_materials_unlit";
  3255. /**
  3256. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  3257. */
  3258. var KHR_materials_unlit = /** @class */ (function () {
  3259. /** @hidden */
  3260. function KHR_materials_unlit(loader) {
  3261. /** The name of this extension. */
  3262. this.name = NAME;
  3263. /** Defines whether this extension is enabled. */
  3264. this.enabled = true;
  3265. this._loader = loader;
  3266. }
  3267. /** @hidden */
  3268. KHR_materials_unlit.prototype.dispose = function () {
  3269. delete this._loader;
  3270. };
  3271. /** @hidden */
  3272. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3273. var _this = this;
  3274. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  3275. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  3276. });
  3277. };
  3278. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  3279. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  3280. throw new Error(context + ": Material type not supported");
  3281. }
  3282. var promises = new Array();
  3283. babylonMaterial.unlit = true;
  3284. var properties = material.pbrMetallicRoughness;
  3285. if (properties) {
  3286. if (properties.baseColorFactor) {
  3287. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3288. babylonMaterial.alpha = properties.baseColorFactor[3];
  3289. }
  3290. else {
  3291. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3292. }
  3293. if (properties.baseColorTexture) {
  3294. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3295. babylonMaterial.albedoTexture = texture;
  3296. return Promise.resolve();
  3297. }));
  3298. }
  3299. }
  3300. if (material.doubleSided) {
  3301. babylonMaterial.backFaceCulling = false;
  3302. babylonMaterial.twoSidedLighting = true;
  3303. }
  3304. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  3305. return Promise.all(promises).then(function () { });
  3306. };
  3307. return KHR_materials_unlit;
  3308. }());
  3309. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  3310. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  3311. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3312. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3313. })(BABYLON || (BABYLON = {}));
  3314. //# sourceMappingURL=KHR_materials_unlit.js.map
  3315. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. var GLTF2;
  3319. (function (GLTF2) {
  3320. var Extensions;
  3321. (function (Extensions) {
  3322. var NAME = "KHR_lights";
  3323. var LightType;
  3324. (function (LightType) {
  3325. LightType["AMBIENT"] = "ambient";
  3326. LightType["DIRECTIONAL"] = "directional";
  3327. LightType["POINT"] = "point";
  3328. LightType["SPOT"] = "spot";
  3329. })(LightType || (LightType = {}));
  3330. /**
  3331. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  3332. */
  3333. var KHR_lights = /** @class */ (function () {
  3334. /** @hidden */
  3335. function KHR_lights(loader) {
  3336. /** The name of this extension. */
  3337. this.name = NAME;
  3338. /** Defines whether this extension is enabled. */
  3339. this.enabled = true;
  3340. this._loader = loader;
  3341. }
  3342. /** @hidden */
  3343. KHR_lights.prototype.dispose = function () {
  3344. delete this._loader;
  3345. delete this._lights;
  3346. };
  3347. /** @hidden */
  3348. KHR_lights.prototype.onLoading = function () {
  3349. var extensions = this._loader.gltf.extensions;
  3350. if (extensions && extensions[this.name]) {
  3351. var extension = extensions[this.name];
  3352. this._lights = extension.lights;
  3353. }
  3354. };
  3355. /** @hidden */
  3356. KHR_lights.prototype.loadSceneAsync = function (context, scene) {
  3357. var _this = this;
  3358. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3359. var promise = _this._loader.loadSceneAsync(context, scene);
  3360. var light = GLTF2.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  3361. if (light.type !== LightType.AMBIENT) {
  3362. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  3363. }
  3364. _this._loader.babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  3365. return promise;
  3366. });
  3367. };
  3368. /** @hidden */
  3369. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  3370. var _this = this;
  3371. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3372. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  3373. var babylonLight;
  3374. var name = babylonMesh.name;
  3375. var light = GLTF2.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  3376. switch (light.type) {
  3377. case LightType.AMBIENT: {
  3378. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  3379. }
  3380. case LightType.DIRECTIONAL: {
  3381. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader.babylonScene);
  3382. break;
  3383. }
  3384. case LightType.POINT: {
  3385. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader.babylonScene);
  3386. break;
  3387. }
  3388. case LightType.SPOT: {
  3389. // TODO: support inner and outer cone angles
  3390. //const innerConeAngle = spotLight.innerConeAngle || 0;
  3391. var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;
  3392. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader.babylonScene);
  3393. break;
  3394. }
  3395. default: {
  3396. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3397. }
  3398. }
  3399. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  3400. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3401. babylonLight.parent = babylonMesh;
  3402. assign(babylonMesh);
  3403. });
  3404. });
  3405. };
  3406. return KHR_lights;
  3407. }());
  3408. Extensions.KHR_lights = KHR_lights;
  3409. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  3410. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3411. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3412. })(BABYLON || (BABYLON = {}));
  3413. //# sourceMappingURL=KHR_lights.js.map
  3414. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3415. var BABYLON;
  3416. (function (BABYLON) {
  3417. var GLTF2;
  3418. (function (GLTF2) {
  3419. var Extensions;
  3420. (function (Extensions) {
  3421. var NAME = "KHR_texture_transform";
  3422. /**
  3423. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  3424. */
  3425. var KHR_texture_transform = /** @class */ (function () {
  3426. /** @hidden */
  3427. function KHR_texture_transform(loader) {
  3428. /** The name of this extension. */
  3429. this.name = NAME;
  3430. /** Defines whether this extension is enabled. */
  3431. this.enabled = true;
  3432. this._loader = loader;
  3433. }
  3434. /** @hidden */
  3435. KHR_texture_transform.prototype.dispose = function () {
  3436. delete this._loader;
  3437. };
  3438. /** @hidden */
  3439. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  3440. var _this = this;
  3441. return GLTF2.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  3442. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  3443. if (!(babylonTexture instanceof BABYLON.Texture)) {
  3444. throw new Error(extensionContext + ": Texture type not supported");
  3445. }
  3446. if (extension.offset) {
  3447. babylonTexture.uOffset = extension.offset[0];
  3448. babylonTexture.vOffset = extension.offset[1];
  3449. }
  3450. // Always rotate around the origin.
  3451. babylonTexture.uRotationCenter = 0;
  3452. babylonTexture.vRotationCenter = 0;
  3453. if (extension.rotation) {
  3454. babylonTexture.wAng = -extension.rotation;
  3455. }
  3456. if (extension.scale) {
  3457. babylonTexture.uScale = extension.scale[0];
  3458. babylonTexture.vScale = extension.scale[1];
  3459. }
  3460. if (extension.texCoord != undefined) {
  3461. babylonTexture.coordinatesIndex = extension.texCoord;
  3462. }
  3463. assign(babylonTexture);
  3464. });
  3465. });
  3466. };
  3467. return KHR_texture_transform;
  3468. }());
  3469. Extensions.KHR_texture_transform = KHR_texture_transform;
  3470. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  3471. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3472. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3473. })(BABYLON || (BABYLON = {}));
  3474. //# sourceMappingURL=KHR_texture_transform.js.map
  3475. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3476. var BABYLON;
  3477. (function (BABYLON) {
  3478. var GLTF2;
  3479. (function (GLTF2) {
  3480. var Extensions;
  3481. (function (Extensions) {
  3482. var NAME = "EXT_lights_imageBased";
  3483. /**
  3484. * [Specification](TODO) (Experimental)
  3485. */
  3486. var EXT_lights_imageBased = /** @class */ (function () {
  3487. /** @hidden */
  3488. function EXT_lights_imageBased(loader) {
  3489. /** The name of this extension. */
  3490. this.name = NAME;
  3491. /** Defines whether this extension is enabled. */
  3492. this.enabled = true;
  3493. this._loader = loader;
  3494. }
  3495. /** @hidden */
  3496. EXT_lights_imageBased.prototype.dispose = function () {
  3497. delete this._loader;
  3498. delete this._lights;
  3499. };
  3500. /** @hidden */
  3501. EXT_lights_imageBased.prototype.onLoading = function () {
  3502. var extensions = this._loader.gltf.extensions;
  3503. if (extensions && extensions[this.name]) {
  3504. var extension = extensions[this.name];
  3505. this._lights = extension.lights;
  3506. }
  3507. };
  3508. /** @hidden */
  3509. EXT_lights_imageBased.prototype.loadSceneAsync = function (context, scene) {
  3510. var _this = this;
  3511. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3512. var promises = new Array();
  3513. promises.push(_this._loader.loadSceneAsync(context, scene));
  3514. _this._loader.logOpen("" + extensionContext);
  3515. var light = GLTF2.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  3516. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3517. _this._loader.babylonScene.environmentTexture = texture;
  3518. }));
  3519. _this._loader.logClose();
  3520. return Promise.all(promises).then(function () { });
  3521. });
  3522. };
  3523. EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {
  3524. var _this = this;
  3525. if (!light._loaded) {
  3526. var promises = new Array();
  3527. this._loader.logOpen("" + context);
  3528. var imageData_1 = new Array(light.specularImages.length);
  3529. var _loop_1 = function (mipmap) {
  3530. var faces = light.specularImages[mipmap];
  3531. imageData_1[mipmap] = new Array(faces.length);
  3532. var _loop_2 = function (face) {
  3533. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3534. this_1._loader.logOpen("" + specularImageContext);
  3535. var index = faces[face];
  3536. var image = GLTF2.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  3537. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  3538. imageData_1[mipmap][face] = data;
  3539. }));
  3540. this_1._loader.logClose();
  3541. };
  3542. for (var face = 0; face < faces.length; face++) {
  3543. _loop_2(face);
  3544. }
  3545. };
  3546. var this_1 = this;
  3547. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3548. _loop_1(mipmap);
  3549. }
  3550. this._loader.logClose();
  3551. light._loaded = Promise.all(promises).then(function () {
  3552. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  3553. light._babylonTexture = babylonTexture;
  3554. if (light.intensity != undefined) {
  3555. babylonTexture.level = light.intensity;
  3556. }
  3557. if (light.rotation) {
  3558. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  3559. // Invert the rotation so that positive rotation is counter-clockwise.
  3560. if (!_this._loader.babylonScene.useRightHandedSystem) {
  3561. rotation = BABYLON.Quaternion.Inverse(rotation);
  3562. }
  3563. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3564. }
  3565. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3566. sphericalHarmonics.scale(light.intensity);
  3567. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3568. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3569. // Compute the lod generation scale to fit exactly to the number of levels available.
  3570. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  3571. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3572. });
  3573. }
  3574. return light._loaded.then(function () {
  3575. return light._babylonTexture;
  3576. });
  3577. };
  3578. return EXT_lights_imageBased;
  3579. }());
  3580. Extensions.EXT_lights_imageBased = EXT_lights_imageBased;
  3581. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_imageBased(loader); });
  3582. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3583. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3584. })(BABYLON || (BABYLON = {}));
  3585. //# sourceMappingURL=EXT_lights_imageBased.js.map