babylon.glTF2FileLoader.js 192 KB

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