babylon.glTF2FileLoader.js 191 KB

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