babylon.glTF2FileLoader.js 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = /** @class */ (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.compileMaterials = false;
  19. this.compileShadowGenerators = false;
  20. this.useClipPlane = false;
  21. this.name = "gltf";
  22. this.extensions = {
  23. ".gltf": { isBinary: false },
  24. ".glb": { isBinary: true }
  25. };
  26. }
  27. GLTFFileLoader.prototype.dispose = function () {
  28. if (this._loader) {
  29. this._loader.dispose();
  30. }
  31. };
  32. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  33. try {
  34. var loaderData = GLTFFileLoader._parse(data);
  35. if (this.onParsed) {
  36. this.onParsed(loaderData);
  37. }
  38. this._loader = this._getLoader(loaderData);
  39. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  40. }
  41. catch (e) {
  42. onError(e.message);
  43. }
  44. };
  45. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  46. try {
  47. var loaderData = GLTFFileLoader._parse(data);
  48. if (this.onParsed) {
  49. this.onParsed(loaderData);
  50. }
  51. this._loader = this._getLoader(loaderData);
  52. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  53. }
  54. catch (e) {
  55. onError(e.message);
  56. }
  57. };
  58. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  59. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  60. };
  61. GLTFFileLoader.prototype.createPlugin = function () {
  62. return new GLTFFileLoader();
  63. };
  64. GLTFFileLoader._parse = function (data) {
  65. if (data instanceof ArrayBuffer) {
  66. return GLTFFileLoader._parseBinary(data);
  67. }
  68. return {
  69. json: JSON.parse(data),
  70. bin: null
  71. };
  72. };
  73. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  74. var loaderVersion = { major: 2, minor: 0 };
  75. var asset = loaderData.json.asset || {};
  76. var version = GLTFFileLoader._parseVersion(asset.version);
  77. if (!version) {
  78. throw new Error("Invalid version: " + asset.version);
  79. }
  80. if (asset.minVersion !== undefined) {
  81. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82. if (!minVersion) {
  83. throw new Error("Invalid minimum version: " + asset.minVersion);
  84. }
  85. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  86. throw new Error("Incompatible minimum version: " + asset.minVersion);
  87. }
  88. }
  89. var createLoaders = {
  90. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91. 2: GLTFFileLoader.CreateGLTFLoaderV2
  92. };
  93. var createLoader = createLoaders[version.major];
  94. if (!createLoader) {
  95. throw new Error("Unsupported version: " + asset.version);
  96. }
  97. return createLoader(this);
  98. };
  99. GLTFFileLoader._parseBinary = function (data) {
  100. var Binary = {
  101. Magic: 0x46546C67
  102. };
  103. var binaryReader = new BinaryReader(data);
  104. var magic = binaryReader.readUint32();
  105. if (magic !== Binary.Magic) {
  106. throw new Error("Unexpected magic: " + magic);
  107. }
  108. var version = binaryReader.readUint32();
  109. switch (version) {
  110. case 1: return GLTFFileLoader._parseV1(binaryReader);
  111. case 2: return GLTFFileLoader._parseV2(binaryReader);
  112. }
  113. throw new Error("Unsupported version: " + version);
  114. };
  115. GLTFFileLoader._parseV1 = function (binaryReader) {
  116. var ContentFormat = {
  117. JSON: 0
  118. };
  119. var length = binaryReader.readUint32();
  120. if (length != binaryReader.getLength()) {
  121. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  122. }
  123. var contentLength = binaryReader.readUint32();
  124. var contentFormat = binaryReader.readUint32();
  125. var content;
  126. switch (contentFormat) {
  127. case ContentFormat.JSON: {
  128. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  129. break;
  130. }
  131. default: {
  132. throw new Error("Unexpected content format: " + contentFormat);
  133. }
  134. }
  135. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  136. var body = binaryReader.readUint8Array(bytesRemaining);
  137. return {
  138. json: content,
  139. bin: body
  140. };
  141. };
  142. GLTFFileLoader._parseV2 = function (binaryReader) {
  143. var ChunkFormat = {
  144. JSON: 0x4E4F534A,
  145. BIN: 0x004E4942
  146. };
  147. var length = binaryReader.readUint32();
  148. if (length !== binaryReader.getLength()) {
  149. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  150. }
  151. // JSON chunk
  152. var chunkLength = binaryReader.readUint32();
  153. var chunkFormat = binaryReader.readUint32();
  154. if (chunkFormat !== ChunkFormat.JSON) {
  155. throw new Error("First chunk format is not JSON");
  156. }
  157. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  158. // Look for BIN chunk
  159. var bin = null;
  160. while (binaryReader.getPosition() < binaryReader.getLength()) {
  161. var chunkLength_1 = binaryReader.readUint32();
  162. var chunkFormat_1 = binaryReader.readUint32();
  163. switch (chunkFormat_1) {
  164. case ChunkFormat.JSON: {
  165. throw new Error("Unexpected JSON chunk");
  166. }
  167. case ChunkFormat.BIN: {
  168. bin = binaryReader.readUint8Array(chunkLength_1);
  169. break;
  170. }
  171. default: {
  172. // ignore unrecognized chunkFormat
  173. binaryReader.skipBytes(chunkLength_1);
  174. break;
  175. }
  176. }
  177. }
  178. return {
  179. json: json,
  180. bin: bin
  181. };
  182. };
  183. GLTFFileLoader._parseVersion = function (version) {
  184. if (version === "1.0" || version === "1.0.1") {
  185. return {
  186. major: 1,
  187. minor: 0
  188. };
  189. }
  190. var match = (version + "").match(/^(\d+)\.(\d+)/);
  191. if (!match) {
  192. return null;
  193. }
  194. return {
  195. major: parseInt(match[1]),
  196. minor: parseInt(match[2])
  197. };
  198. };
  199. GLTFFileLoader._compareVersion = function (a, b) {
  200. if (a.major > b.major)
  201. return 1;
  202. if (a.major < b.major)
  203. return -1;
  204. if (a.minor > b.minor)
  205. return 1;
  206. if (a.minor < b.minor)
  207. return -1;
  208. return 0;
  209. };
  210. GLTFFileLoader._decodeBufferToText = function (buffer) {
  211. var result = "";
  212. var length = buffer.byteLength;
  213. for (var i = 0; i < length; i++) {
  214. result += String.fromCharCode(buffer[i]);
  215. }
  216. return result;
  217. };
  218. // V1 options
  219. GLTFFileLoader.HomogeneousCoordinates = false;
  220. GLTFFileLoader.IncrementalLoading = true;
  221. return GLTFFileLoader;
  222. }());
  223. BABYLON.GLTFFileLoader = GLTFFileLoader;
  224. var BinaryReader = /** @class */ (function () {
  225. function BinaryReader(arrayBuffer) {
  226. this._arrayBuffer = arrayBuffer;
  227. this._dataView = new DataView(arrayBuffer);
  228. this._byteOffset = 0;
  229. }
  230. BinaryReader.prototype.getPosition = function () {
  231. return this._byteOffset;
  232. };
  233. BinaryReader.prototype.getLength = function () {
  234. return this._arrayBuffer.byteLength;
  235. };
  236. BinaryReader.prototype.readUint32 = function () {
  237. var value = this._dataView.getUint32(this._byteOffset, true);
  238. this._byteOffset += 4;
  239. return value;
  240. };
  241. BinaryReader.prototype.readUint8Array = function (length) {
  242. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  243. this._byteOffset += length;
  244. return value;
  245. };
  246. BinaryReader.prototype.skipBytes = function (length) {
  247. this._byteOffset += length;
  248. };
  249. return BinaryReader;
  250. }());
  251. if (BABYLON.SceneLoader) {
  252. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  253. }
  254. })(BABYLON || (BABYLON = {}));
  255. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  256. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  257. var BABYLON;
  258. (function (BABYLON) {
  259. var GLTF2;
  260. (function (GLTF2) {
  261. /**
  262. * Enums
  263. */
  264. var EComponentType;
  265. (function (EComponentType) {
  266. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  267. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  268. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  269. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  270. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  271. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  272. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  273. var EMeshPrimitiveMode;
  274. (function (EMeshPrimitiveMode) {
  275. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  276. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  277. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  278. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  279. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  280. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  281. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  282. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  283. var ETextureMagFilter;
  284. (function (ETextureMagFilter) {
  285. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  286. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  287. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  288. var ETextureMinFilter;
  289. (function (ETextureMinFilter) {
  290. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  291. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  292. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  293. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  294. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  295. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  296. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  297. var ETextureWrapMode;
  298. (function (ETextureWrapMode) {
  299. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  300. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  301. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  302. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  303. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  304. })(BABYLON || (BABYLON = {}));
  305. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  306. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  307. var BABYLON;
  308. (function (BABYLON) {
  309. var GLTF2;
  310. (function (GLTF2) {
  311. var GLTFLoaderTracker = /** @class */ (function () {
  312. function GLTFLoaderTracker(onComplete) {
  313. this._pendingCount = 0;
  314. this._callback = onComplete;
  315. }
  316. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  317. this._pendingCount++;
  318. };
  319. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  320. if (--this._pendingCount === 0) {
  321. this._callback();
  322. }
  323. };
  324. return GLTFLoaderTracker;
  325. }());
  326. var GLTFLoader = /** @class */ (function () {
  327. function GLTFLoader(parent) {
  328. this._disposed = false;
  329. this._renderReady = false;
  330. this._requests = new Array();
  331. this._renderReadyObservable = new BABYLON.Observable();
  332. // Count of pending work that needs to complete before the asset is rendered.
  333. this._renderPendingCount = 0;
  334. // Count of pending work that needs to complete before the loader is disposed.
  335. this._loaderPendingCount = 0;
  336. this._loaderTrackers = new Array();
  337. this._parent = parent;
  338. if (!GLTFLoader._progressEventFactory) {
  339. if (typeof window["ProgressEvent"] === "function") {
  340. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  341. }
  342. else {
  343. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  344. }
  345. }
  346. }
  347. GLTFLoader.RegisterExtension = function (extension) {
  348. if (GLTFLoader.Extensions[extension.name]) {
  349. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  350. return;
  351. }
  352. GLTFLoader.Extensions[extension.name] = extension;
  353. // Keep the order of registration so that extensions registered first are called first.
  354. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  355. };
  356. GLTFLoader._createProgressEventByConstructor = function (name, data) {
  357. return new ProgressEvent(name, data);
  358. };
  359. GLTFLoader._createProgressEventByDocument = function (name, data) {
  360. var event = document.createEvent("ProgressEvent");
  361. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  362. return event;
  363. };
  364. GLTFLoader.prototype.dispose = function () {
  365. if (this._disposed) {
  366. return;
  367. }
  368. this._disposed = true;
  369. // Abort requests that are not complete
  370. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  371. var request = _a[_i];
  372. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  373. request.abort();
  374. }
  375. }
  376. // Revoke object urls created during load
  377. if (this._gltf.textures) {
  378. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  379. var texture = _c[_b];
  380. if (texture.url) {
  381. URL.revokeObjectURL(texture.url);
  382. }
  383. }
  384. }
  385. };
  386. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  387. var _this = this;
  388. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  389. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  390. }, onProgress, onError);
  391. };
  392. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  393. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  394. };
  395. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  396. var _this = this;
  397. this._tryCatchOnError(function () {
  398. _this._loadData(data);
  399. _this._babylonScene = scene;
  400. _this._rootUrl = rootUrl;
  401. _this._successCallback = onSuccess;
  402. _this._progressCallback = onProgress;
  403. _this._errorCallback = onError;
  404. _this._addPendingData(_this);
  405. _this._loadDefaultScene(nodeNames);
  406. _this._loadAnimations();
  407. _this._removePendingData(_this);
  408. });
  409. };
  410. GLTFLoader.prototype._onProgress = function () {
  411. if (!this._progressCallback) {
  412. return;
  413. }
  414. var loaded = 0;
  415. var total = 0;
  416. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  417. var request = _a[_i];
  418. if (!request._loaded || !request._total) {
  419. return;
  420. }
  421. loaded += request._loaded;
  422. total += request._total;
  423. }
  424. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  425. lengthComputable: true,
  426. loaded: loaded,
  427. total: total
  428. }));
  429. };
  430. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  431. if (this._renderReady) {
  432. func();
  433. }
  434. else {
  435. this._renderReadyObservable.add(func);
  436. }
  437. };
  438. GLTFLoader.prototype._onRenderReady = function () {
  439. this._rootNode.babylonMesh.setEnabled(true);
  440. this._startAnimations();
  441. this._successCallback();
  442. this._renderReadyObservable.notifyObservers(this);
  443. };
  444. GLTFLoader.prototype._onComplete = function () {
  445. if (this._parent.onComplete) {
  446. this._parent.onComplete();
  447. }
  448. this.dispose();
  449. };
  450. GLTFLoader.prototype._loadData = function (data) {
  451. this._gltf = data.json;
  452. // Assign the index of each object for convinience.
  453. GLTFLoader._AssignIndices(this._gltf.accessors);
  454. GLTFLoader._AssignIndices(this._gltf.animations);
  455. GLTFLoader._AssignIndices(this._gltf.buffers);
  456. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  457. GLTFLoader._AssignIndices(this._gltf.images);
  458. GLTFLoader._AssignIndices(this._gltf.materials);
  459. GLTFLoader._AssignIndices(this._gltf.meshes);
  460. GLTFLoader._AssignIndices(this._gltf.nodes);
  461. GLTFLoader._AssignIndices(this._gltf.scenes);
  462. GLTFLoader._AssignIndices(this._gltf.skins);
  463. GLTFLoader._AssignIndices(this._gltf.textures);
  464. if (data.bin) {
  465. var buffers = this._gltf.buffers;
  466. if (buffers && buffers[0] && !buffers[0].uri) {
  467. var binaryBuffer = buffers[0];
  468. if (binaryBuffer.byteLength != data.bin.byteLength) {
  469. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  470. }
  471. binaryBuffer.loadedData = data.bin;
  472. }
  473. else {
  474. BABYLON.Tools.Warn("Unexpected BIN chunk");
  475. }
  476. }
  477. };
  478. GLTFLoader.prototype._getMeshes = function () {
  479. var meshes = new Array();
  480. // Root mesh is always first.
  481. meshes.push(this._rootNode.babylonMesh);
  482. var nodes = this._gltf.nodes;
  483. if (nodes) {
  484. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  485. var node = nodes_1[_i];
  486. if (node.babylonMesh) {
  487. meshes.push(node.babylonMesh);
  488. }
  489. }
  490. }
  491. return meshes;
  492. };
  493. GLTFLoader.prototype._getSkeletons = function () {
  494. var skeletons = new Array();
  495. var skins = this._gltf.skins;
  496. if (skins) {
  497. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  498. var skin = skins_1[_i];
  499. if (skin.babylonSkeleton) {
  500. skeletons.push(skin.babylonSkeleton);
  501. }
  502. }
  503. }
  504. return skeletons;
  505. };
  506. GLTFLoader.prototype._getAnimationTargets = function () {
  507. var targets = new Array();
  508. var animations = this._gltf.animations;
  509. if (animations) {
  510. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  511. var animation = animations_1[_i];
  512. targets.push.apply(targets, animation.targets);
  513. }
  514. }
  515. return targets;
  516. };
  517. GLTFLoader.prototype._startAnimations = function () {
  518. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  519. var target = _a[_i];
  520. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  521. }
  522. };
  523. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  524. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  525. if (!scene) {
  526. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  527. }
  528. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  529. };
  530. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  531. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  532. switch (this._parent.coordinateSystemMode) {
  533. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  534. if (!this._babylonScene.useRightHandedSystem) {
  535. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  536. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  537. }
  538. break;
  539. }
  540. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  541. // do nothing
  542. break;
  543. }
  544. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  545. this._babylonScene.useRightHandedSystem = true;
  546. break;
  547. }
  548. default: {
  549. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  550. return;
  551. }
  552. }
  553. if (this._parent.onMeshLoaded) {
  554. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  555. }
  556. var nodeIndices = scene.nodes;
  557. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  558. node.parent = parentNode;
  559. return true;
  560. }, this._rootNode);
  561. if (nodeNames) {
  562. if (!(nodeNames instanceof Array)) {
  563. nodeNames = [nodeNames];
  564. }
  565. var filteredNodeIndices_1 = new Array();
  566. this._traverseNodes(context, nodeIndices, function (node) {
  567. if (nodeNames.indexOf(node.name) !== -1) {
  568. filteredNodeIndices_1.push(node.index);
  569. return false;
  570. }
  571. return true;
  572. }, this._rootNode);
  573. nodeIndices = filteredNodeIndices_1;
  574. }
  575. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  576. var index = nodeIndices_1[_i];
  577. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  578. if (!node) {
  579. throw new Error(context + ": Failed to find node " + index);
  580. }
  581. this._loadNode("#/nodes/" + index, node);
  582. }
  583. // Disable the root mesh until the asset is ready to render.
  584. this._rootNode.babylonMesh.setEnabled(false);
  585. };
  586. GLTFLoader.prototype._loadNode = function (context, node) {
  587. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  588. return;
  589. }
  590. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  591. node.babylonMesh.hasVertexAlpha = true;
  592. this._loadTransform(node);
  593. if (node.mesh != null) {
  594. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  595. if (!mesh) {
  596. throw new Error(context + ": Failed to find mesh " + node.mesh);
  597. }
  598. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  599. }
  600. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  601. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  602. node.babylonAnimationTargets.push(node.babylonMesh);
  603. if (node.skin != null) {
  604. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  605. if (!skin) {
  606. throw new Error(context + ": Failed to find skin " + node.skin);
  607. }
  608. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  609. }
  610. if (node.camera != null) {
  611. // TODO: handle cameras
  612. }
  613. if (node.children) {
  614. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  615. var index = _a[_i];
  616. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  617. if (!childNode) {
  618. throw new Error(context + ": Failed to find child node " + index);
  619. }
  620. this._loadNode("#/nodes/" + index, childNode);
  621. }
  622. }
  623. if (this._parent.onMeshLoaded) {
  624. this._parent.onMeshLoaded(node.babylonMesh);
  625. }
  626. };
  627. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  628. var _this = this;
  629. var primitives = mesh.primitives;
  630. if (!primitives || primitives.length === 0) {
  631. throw new Error(context + ": Primitives are missing");
  632. }
  633. this._createMorphTargets(context, node, mesh);
  634. this._loadAllVertexDataAsync(context, mesh, function () {
  635. _this._loadMorphTargets(context, node, mesh);
  636. var vertexData = new BABYLON.VertexData();
  637. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  638. var primitive = primitives_1[_i];
  639. vertexData.merge(primitive.vertexData);
  640. }
  641. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  642. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  643. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  644. node.babylonMesh.subMeshes = [];
  645. var verticesStart = 0;
  646. var indicesStart = 0;
  647. for (var index = 0; index < primitives.length; index++) {
  648. var vertexData_1 = primitives[index].vertexData;
  649. var verticesCount = vertexData_1.positions.length;
  650. var indicesCount = vertexData_1.indices.length;
  651. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  652. verticesStart += verticesCount;
  653. indicesStart += indicesCount;
  654. }
  655. ;
  656. });
  657. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  658. node.babylonMesh.material = multiMaterial;
  659. var subMaterials = multiMaterial.subMaterials;
  660. var _loop_1 = function (index) {
  661. var primitive = primitives[index];
  662. if (primitive.material == null) {
  663. subMaterials[index] = this_1._getDefaultMaterial();
  664. }
  665. else {
  666. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  667. if (!material) {
  668. throw new Error(context + ": Failed to find material " + primitive.material);
  669. }
  670. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  671. if (isNew && _this._parent.onMaterialLoaded) {
  672. _this._parent.onMaterialLoaded(babylonMaterial);
  673. }
  674. subMaterials[index] = babylonMaterial;
  675. });
  676. }
  677. };
  678. var this_1 = this;
  679. for (var index = 0; index < primitives.length; index++) {
  680. _loop_1(index);
  681. }
  682. ;
  683. };
  684. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  685. var primitives = mesh.primitives;
  686. var numRemainingPrimitives = primitives.length;
  687. var _loop_2 = function (index) {
  688. var primitive = primitives[index];
  689. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  690. primitive.vertexData = vertexData;
  691. if (--numRemainingPrimitives === 0) {
  692. onSuccess();
  693. }
  694. });
  695. };
  696. var this_2 = this;
  697. for (var index = 0; index < primitives.length; index++) {
  698. _loop_2(index);
  699. }
  700. };
  701. /**
  702. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  703. * @param {ArrayBufferView} data
  704. * @param {IGLTFAccessor} accessor
  705. */
  706. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  707. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  708. return data;
  709. }
  710. var buffer = data;
  711. var factor = 1;
  712. switch (accessor.componentType) {
  713. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  714. factor = 1 / 255;
  715. break;
  716. }
  717. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  718. factor = 1 / 65535;
  719. break;
  720. }
  721. default: {
  722. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  723. }
  724. }
  725. var result = new Float32Array(accessor.count * 2);
  726. for (var i = 0; i < result.length; ++i) {
  727. result[i] = buffer[i] * factor;
  728. }
  729. return result;
  730. };
  731. /**
  732. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  733. * @param {ArrayBufferView} data
  734. * @param {IGLTFAccessor} accessor
  735. */
  736. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  737. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  738. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  739. return data;
  740. }
  741. var buffer = data;
  742. var factor = 1;
  743. switch (accessor.componentType) {
  744. case GLTF2.EComponentType.FLOAT: {
  745. factor = 1;
  746. break;
  747. }
  748. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  749. factor = 1 / 255;
  750. break;
  751. }
  752. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  753. factor = 1 / 65535;
  754. break;
  755. }
  756. default: {
  757. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  758. }
  759. }
  760. var result = new Float32Array(accessor.count * 4);
  761. if (colorComponentCount === 4) {
  762. for (var i = 0; i < result.length; ++i) {
  763. result[i] = buffer[i] * factor;
  764. }
  765. }
  766. else {
  767. var offset = 0;
  768. for (var i = 0; i < result.length; ++i) {
  769. if ((i + 1) % 4 === 0) {
  770. result[i] = 1;
  771. }
  772. else {
  773. result[i] = buffer[offset++] * factor;
  774. }
  775. }
  776. }
  777. return result;
  778. };
  779. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  780. var _this = this;
  781. var attributes = primitive.attributes;
  782. if (!attributes) {
  783. throw new Error(context + ": Attributes are missing");
  784. }
  785. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  786. // TODO: handle other primitive modes
  787. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  788. }
  789. var vertexData = new BABYLON.VertexData();
  790. var numRemainingAttributes = Object.keys(attributes).length;
  791. var _loop_3 = function (attribute) {
  792. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  793. if (!accessor) {
  794. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  795. }
  796. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  797. switch (attribute) {
  798. case "POSITION": {
  799. vertexData.positions = data;
  800. break;
  801. }
  802. case "NORMAL": {
  803. vertexData.normals = data;
  804. break;
  805. }
  806. case "TANGENT": {
  807. vertexData.tangents = data;
  808. break;
  809. }
  810. case "TEXCOORD_0": {
  811. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  812. break;
  813. }
  814. case "TEXCOORD_1": {
  815. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  816. break;
  817. }
  818. case "JOINTS_0": {
  819. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  820. break;
  821. }
  822. case "WEIGHTS_0": {
  823. //TODO: need to add support for normalized weights.
  824. vertexData.matricesWeights = data;
  825. break;
  826. }
  827. case "COLOR_0": {
  828. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  829. break;
  830. }
  831. default: {
  832. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  833. break;
  834. }
  835. }
  836. if (--numRemainingAttributes === 0) {
  837. if (primitive.indices == null) {
  838. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  839. for (var i = 0; i < vertexData.indices.length; i++) {
  840. vertexData.indices[i] = i;
  841. }
  842. onSuccess(vertexData);
  843. }
  844. else {
  845. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  846. if (!indicesAccessor) {
  847. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  848. }
  849. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  850. vertexData.indices = data;
  851. onSuccess(vertexData);
  852. });
  853. }
  854. }
  855. });
  856. };
  857. var this_3 = this;
  858. for (var attribute in attributes) {
  859. _loop_3(attribute);
  860. }
  861. };
  862. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  863. var primitives = mesh.primitives;
  864. var targets = primitives[0].targets;
  865. if (!targets) {
  866. return;
  867. }
  868. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  869. var primitive = primitives_2[_i];
  870. if (!primitive.targets || primitive.targets.length != targets.length) {
  871. throw new Error(context + ": All primitives are required to list the same number of targets");
  872. }
  873. }
  874. var morphTargetManager = new BABYLON.MorphTargetManager();
  875. node.babylonMesh.morphTargetManager = morphTargetManager;
  876. for (var index = 0; index < targets.length; index++) {
  877. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  878. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  879. }
  880. };
  881. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  882. var morphTargetManager = node.babylonMesh.morphTargetManager;
  883. if (!morphTargetManager) {
  884. return;
  885. }
  886. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  887. var numTargets = morphTargetManager.numTargets;
  888. for (var index = 0; index < numTargets; index++) {
  889. var vertexData = new BABYLON.VertexData();
  890. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  891. var primitive = _a[_i];
  892. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  893. }
  894. if (!vertexData.positions) {
  895. throw new Error(context + ": Positions are missing");
  896. }
  897. var target = morphTargetManager.getTarget(index);
  898. target.setPositions(vertexData.positions);
  899. target.setNormals(vertexData.normals);
  900. target.setTangents(vertexData.tangents);
  901. }
  902. });
  903. };
  904. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  905. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  906. var _loop_4 = function (primitive) {
  907. var targets = primitive.targets;
  908. primitive.targetsVertexData = new Array(targets.length);
  909. var _loop_5 = function (index) {
  910. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  911. primitive.targetsVertexData[index] = vertexData;
  912. if (--numRemainingTargets === 0) {
  913. onSuccess();
  914. }
  915. });
  916. };
  917. for (var index = 0; index < targets.length; index++) {
  918. _loop_5(index);
  919. }
  920. };
  921. var this_4 = this;
  922. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  923. var primitive = _a[_i];
  924. _loop_4(primitive);
  925. }
  926. };
  927. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  928. var targetVertexData = new BABYLON.VertexData();
  929. var numRemainingAttributes = Object.keys(attributes).length;
  930. var _loop_6 = function (attribute) {
  931. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  932. if (!accessor) {
  933. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  934. }
  935. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  936. // glTF stores morph target information as deltas while babylon.js expects the final data.
  937. // As a result we have to add the original data to the delta to calculate the final data.
  938. var values = data;
  939. switch (attribute) {
  940. case "POSITION": {
  941. for (var i = 0; i < values.length; i++) {
  942. values[i] += vertexData.positions[i];
  943. }
  944. targetVertexData.positions = values;
  945. break;
  946. }
  947. case "NORMAL": {
  948. for (var i = 0; i < values.length; i++) {
  949. values[i] += vertexData.normals[i];
  950. }
  951. targetVertexData.normals = values;
  952. break;
  953. }
  954. case "TANGENT": {
  955. // Tangent data for morph targets is stored as xyz delta.
  956. // The vertexData.tangent is stored as xyzw.
  957. // So we need to skip every fourth vertexData.tangent.
  958. for (var i = 0, j = 0; i < values.length; i++, j++) {
  959. values[i] += vertexData.tangents[j];
  960. if ((i + 1) % 3 == 0) {
  961. j++;
  962. }
  963. }
  964. targetVertexData.tangents = values;
  965. break;
  966. }
  967. default: {
  968. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  969. break;
  970. }
  971. }
  972. if (--numRemainingAttributes === 0) {
  973. onSuccess(targetVertexData);
  974. }
  975. });
  976. };
  977. var this_5 = this;
  978. for (var attribute in attributes) {
  979. _loop_6(attribute);
  980. }
  981. };
  982. GLTFLoader.prototype._loadTransform = function (node) {
  983. var position = BABYLON.Vector3.Zero();
  984. var rotation = BABYLON.Quaternion.Identity();
  985. var scaling = BABYLON.Vector3.One();
  986. if (node.matrix) {
  987. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  988. matrix.decompose(scaling, rotation, position);
  989. }
  990. else {
  991. if (node.translation)
  992. position = BABYLON.Vector3.FromArray(node.translation);
  993. if (node.rotation)
  994. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  995. if (node.scale)
  996. scaling = BABYLON.Vector3.FromArray(node.scale);
  997. }
  998. node.babylonMesh.position = position;
  999. node.babylonMesh.rotationQuaternion = rotation;
  1000. node.babylonMesh.scaling = scaling;
  1001. };
  1002. GLTFLoader.prototype._loadSkin = function (context, skin) {
  1003. var _this = this;
  1004. if (skin.babylonSkeleton) {
  1005. return skin.babylonSkeleton;
  1006. }
  1007. var skeletonId = "skeleton" + skin.index;
  1008. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  1009. if (skin.inverseBindMatrices == null) {
  1010. this._loadBones(context, skin, null);
  1011. }
  1012. else {
  1013. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  1014. if (!accessor) {
  1015. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  1016. }
  1017. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  1018. _this._loadBones(context, skin, data);
  1019. });
  1020. }
  1021. return skin.babylonSkeleton;
  1022. };
  1023. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  1024. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  1025. node.babylonBones = node.babylonBones || {};
  1026. node.babylonBones[skin.index] = babylonBone;
  1027. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  1028. node.babylonAnimationTargets.push(babylonBone);
  1029. return babylonBone;
  1030. };
  1031. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  1032. var babylonBones = {};
  1033. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1034. var index = _a[_i];
  1035. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  1036. if (!node) {
  1037. throw new Error(context + ": Failed to find joint " + index);
  1038. }
  1039. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  1040. }
  1041. };
  1042. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  1043. var babylonBone = babylonBones[node.index];
  1044. if (babylonBone) {
  1045. return babylonBone;
  1046. }
  1047. var boneIndex = skin.joints.indexOf(node.index);
  1048. var baseMatrix = BABYLON.Matrix.Identity();
  1049. if (inverseBindMatrixData && boneIndex !== -1) {
  1050. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  1051. baseMatrix.invertToRef(baseMatrix);
  1052. }
  1053. var babylonParentBone = null;
  1054. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  1055. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  1056. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1057. }
  1058. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  1059. babylonBones[node.index] = babylonBone;
  1060. return babylonBone;
  1061. };
  1062. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1063. return node.matrix ?
  1064. BABYLON.Matrix.FromArray(node.matrix) :
  1065. 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());
  1066. };
  1067. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  1068. if (parentNode === void 0) { parentNode = null; }
  1069. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  1070. var index = indices_1[_i];
  1071. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  1072. if (!node) {
  1073. throw new Error(context + ": Failed to find node " + index);
  1074. }
  1075. this._traverseNode(context, node, action, parentNode);
  1076. }
  1077. };
  1078. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  1079. if (parentNode === void 0) { parentNode = null; }
  1080. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  1081. return;
  1082. }
  1083. if (!action(node, parentNode)) {
  1084. return;
  1085. }
  1086. if (node.children) {
  1087. this._traverseNodes(context, node.children, action, node);
  1088. }
  1089. };
  1090. GLTFLoader.prototype._loadAnimations = function () {
  1091. var animations = this._gltf.animations;
  1092. if (!animations) {
  1093. return;
  1094. }
  1095. for (var index = 0; index < animations.length; index++) {
  1096. var animation = animations[index];
  1097. this._loadAnimation("#/animations/" + index, animation);
  1098. }
  1099. };
  1100. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  1101. animation.targets = [];
  1102. for (var index = 0; index < animation.channels.length; index++) {
  1103. var channel = GLTFLoader._GetProperty(animation.channels, index);
  1104. if (!channel) {
  1105. throw new Error(context + ": Failed to find channel " + index);
  1106. }
  1107. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  1108. if (!sampler) {
  1109. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  1110. }
  1111. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  1112. }
  1113. };
  1114. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  1115. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  1116. if (!targetNode) {
  1117. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  1118. }
  1119. var targetPath;
  1120. var animationType;
  1121. switch (channel.target.path) {
  1122. case "translation": {
  1123. targetPath = "position";
  1124. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1125. break;
  1126. }
  1127. case "rotation": {
  1128. targetPath = "rotationQuaternion";
  1129. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1130. break;
  1131. }
  1132. case "scale": {
  1133. targetPath = "scaling";
  1134. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1135. break;
  1136. }
  1137. case "weights": {
  1138. targetPath = "influence";
  1139. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1140. break;
  1141. }
  1142. default: {
  1143. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  1144. }
  1145. }
  1146. var inputData;
  1147. var outputData;
  1148. var checkSuccess = function () {
  1149. if (!inputData || !outputData) {
  1150. return;
  1151. }
  1152. var outputBufferOffset = 0;
  1153. var getNextOutputValue;
  1154. switch (targetPath) {
  1155. case "position": {
  1156. getNextOutputValue = function () {
  1157. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  1158. outputBufferOffset += 3;
  1159. return value;
  1160. };
  1161. break;
  1162. }
  1163. case "rotationQuaternion": {
  1164. getNextOutputValue = function () {
  1165. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  1166. outputBufferOffset += 4;
  1167. return value;
  1168. };
  1169. break;
  1170. }
  1171. case "scaling": {
  1172. getNextOutputValue = function () {
  1173. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  1174. outputBufferOffset += 3;
  1175. return value;
  1176. };
  1177. break;
  1178. }
  1179. case "influence": {
  1180. getNextOutputValue = function () {
  1181. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  1182. var value = new Array(numTargets);
  1183. for (var i = 0; i < numTargets; i++) {
  1184. value[i] = outputData[outputBufferOffset++];
  1185. }
  1186. return value;
  1187. };
  1188. break;
  1189. }
  1190. }
  1191. var getNextKey;
  1192. switch (sampler.interpolation) {
  1193. case "LINEAR": {
  1194. getNextKey = function (frameIndex) { return ({
  1195. frame: inputData[frameIndex],
  1196. value: getNextOutputValue()
  1197. }); };
  1198. break;
  1199. }
  1200. case "CUBICSPLINE": {
  1201. getNextKey = function (frameIndex) { return ({
  1202. frame: inputData[frameIndex],
  1203. inTangent: getNextOutputValue(),
  1204. value: getNextOutputValue(),
  1205. outTangent: getNextOutputValue()
  1206. }); };
  1207. break;
  1208. }
  1209. default: {
  1210. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  1211. }
  1212. }
  1213. ;
  1214. var keys;
  1215. if (inputData.length === 1) {
  1216. var key = getNextKey(0);
  1217. keys = [
  1218. { frame: key.frame, value: key.value },
  1219. { frame: key.frame + 1, value: key.value }
  1220. ];
  1221. }
  1222. else {
  1223. keys = new Array(inputData.length);
  1224. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  1225. keys[frameIndex] = getNextKey(frameIndex);
  1226. }
  1227. }
  1228. if (targetPath === "influence") {
  1229. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  1230. var _loop_7 = function (targetIndex) {
  1231. var morphTarget = morphTargetManager.getTarget(targetIndex);
  1232. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  1233. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1234. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1235. frame: key.frame,
  1236. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1237. value: key.value[targetIndex],
  1238. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1239. }); }));
  1240. morphTarget.animations.push(babylonAnimation);
  1241. animation.targets.push(morphTarget);
  1242. };
  1243. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  1244. _loop_7(targetIndex);
  1245. }
  1246. }
  1247. else {
  1248. var animationName = animation.name || "anim" + animation.index;
  1249. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1250. babylonAnimation.setKeys(keys);
  1251. if (targetNode.babylonAnimationTargets) {
  1252. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  1253. var target = _a[_i];
  1254. target.animations.push(babylonAnimation.clone());
  1255. animation.targets.push(target);
  1256. }
  1257. }
  1258. }
  1259. };
  1260. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  1261. if (!inputAccessor) {
  1262. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  1263. }
  1264. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  1265. inputData = data;
  1266. checkSuccess();
  1267. });
  1268. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  1269. if (!outputAccessor) {
  1270. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  1271. }
  1272. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  1273. outputData = data;
  1274. checkSuccess();
  1275. });
  1276. };
  1277. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  1278. var _this = this;
  1279. this._addPendingData(buffer);
  1280. if (buffer.loadedData) {
  1281. onSuccess(buffer.loadedData);
  1282. this._removePendingData(buffer);
  1283. }
  1284. else if (buffer.loadedObservable) {
  1285. buffer.loadedObservable.add(function (buffer) {
  1286. onSuccess(buffer.loadedData);
  1287. _this._removePendingData(buffer);
  1288. });
  1289. }
  1290. else {
  1291. if (!buffer.uri) {
  1292. throw new Error(context + ": Uri is missing");
  1293. }
  1294. buffer.loadedObservable = new BABYLON.Observable();
  1295. buffer.loadedObservable.add(function (buffer) {
  1296. onSuccess(buffer.loadedData);
  1297. _this._removePendingData(buffer);
  1298. });
  1299. this._loadUriAsync(context, buffer.uri, function (data) {
  1300. buffer.loadedData = data;
  1301. buffer.loadedObservable.notifyObservers(buffer);
  1302. buffer.loadedObservable = undefined;
  1303. });
  1304. }
  1305. };
  1306. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  1307. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  1308. if (!buffer) {
  1309. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1310. }
  1311. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  1312. var data;
  1313. try {
  1314. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1315. }
  1316. catch (e) {
  1317. throw new Error(context + ": " + e.message);
  1318. }
  1319. onSuccess(data);
  1320. });
  1321. };
  1322. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  1323. var _this = this;
  1324. if (accessor.sparse) {
  1325. throw new Error(context + ": Sparse accessors are not currently supported");
  1326. }
  1327. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  1328. if (!bufferView) {
  1329. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1330. }
  1331. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  1332. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  1333. if (numComponents === 0) {
  1334. throw new Error(context + ": Invalid type " + accessor.type);
  1335. }
  1336. var data;
  1337. var byteOffset = accessor.byteOffset || 0;
  1338. var byteStride = bufferView.byteStride;
  1339. try {
  1340. switch (accessor.componentType) {
  1341. case GLTF2.EComponentType.BYTE: {
  1342. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1343. break;
  1344. }
  1345. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  1346. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1347. break;
  1348. }
  1349. case GLTF2.EComponentType.SHORT: {
  1350. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1351. break;
  1352. }
  1353. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  1354. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1355. break;
  1356. }
  1357. case GLTF2.EComponentType.UNSIGNED_INT: {
  1358. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1359. break;
  1360. }
  1361. case GLTF2.EComponentType.FLOAT: {
  1362. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  1363. break;
  1364. }
  1365. default: {
  1366. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1367. }
  1368. }
  1369. }
  1370. catch (e) {
  1371. throw new Error(context + ": " + e);
  1372. }
  1373. onSuccess(data);
  1374. });
  1375. };
  1376. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  1377. byteOffset += data.byteOffset;
  1378. var targetLength = count * numComponents;
  1379. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1380. return new typedArray(data.buffer, byteOffset, targetLength);
  1381. }
  1382. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1383. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1384. var targetBuffer = new typedArray(targetLength);
  1385. var sourceIndex = 0;
  1386. var targetIndex = 0;
  1387. while (targetIndex < targetLength) {
  1388. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1389. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1390. targetIndex++;
  1391. }
  1392. sourceIndex += elementStride;
  1393. }
  1394. return targetBuffer;
  1395. };
  1396. GLTFLoader.prototype._addPendingData = function (data) {
  1397. if (!this._renderReady) {
  1398. this._renderPendingCount++;
  1399. }
  1400. this._addLoaderPendingData(data);
  1401. };
  1402. GLTFLoader.prototype._removePendingData = function (data) {
  1403. var _this = this;
  1404. if (!this._renderReady) {
  1405. if (--this._renderPendingCount === 0) {
  1406. this._addLoaderPendingData(this);
  1407. this._compileMaterialsAsync(function () {
  1408. _this._compileShadowGeneratorsAsync(function () {
  1409. _this._removeLoaderPendingData(_this);
  1410. _this._renderReady = true;
  1411. _this._onRenderReady();
  1412. });
  1413. });
  1414. }
  1415. }
  1416. this._removeLoaderPendingData(data);
  1417. };
  1418. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  1419. this._loaderPendingCount++;
  1420. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  1421. var tracker = _a[_i];
  1422. tracker._addPendingData(data);
  1423. }
  1424. };
  1425. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  1426. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  1427. var tracker = _a[_i];
  1428. tracker._removePendingData(data);
  1429. }
  1430. if (--this._loaderPendingCount === 0) {
  1431. this._onComplete();
  1432. }
  1433. };
  1434. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  1435. var _this = this;
  1436. var tracker = new GLTFLoaderTracker(function () {
  1437. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  1438. onComplete();
  1439. });
  1440. this._loaderTrackers.push(tracker);
  1441. this._addLoaderPendingData(tracker);
  1442. action();
  1443. this._removeLoaderPendingData(tracker);
  1444. };
  1445. GLTFLoader.prototype._getDefaultMaterial = function () {
  1446. if (!this._defaultMaterial) {
  1447. var id = "__gltf_default";
  1448. var material = this._babylonScene.getMaterialByName(id);
  1449. if (!material) {
  1450. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1451. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1452. material.metallic = 1;
  1453. material.roughness = 1;
  1454. }
  1455. this._defaultMaterial = material;
  1456. }
  1457. return this._defaultMaterial;
  1458. };
  1459. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  1460. var babylonMaterial = material.babylonMaterial;
  1461. // Ensure metallic workflow
  1462. babylonMaterial.metallic = 1;
  1463. babylonMaterial.roughness = 1;
  1464. var properties = material.pbrMetallicRoughness;
  1465. if (!properties) {
  1466. return;
  1467. }
  1468. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1469. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1470. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1471. if (properties.baseColorTexture) {
  1472. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  1473. if (!texture) {
  1474. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1475. }
  1476. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1477. }
  1478. if (properties.metallicRoughnessTexture) {
  1479. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1480. if (!texture) {
  1481. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1482. }
  1483. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1484. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1485. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1486. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1487. }
  1488. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1489. };
  1490. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  1491. if (material.babylonMaterial) {
  1492. assign(material.babylonMaterial, false);
  1493. return;
  1494. }
  1495. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1496. return;
  1497. }
  1498. this._createPbrMaterial(material);
  1499. this._loadMaterialBaseProperties(context, material);
  1500. this._loadMaterialMetallicRoughnessProperties(context, material);
  1501. assign(material.babylonMaterial, true);
  1502. };
  1503. GLTFLoader.prototype._createPbrMaterial = function (material) {
  1504. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1505. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1506. material.babylonMaterial = babylonMaterial;
  1507. };
  1508. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  1509. var babylonMaterial = material.babylonMaterial;
  1510. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1511. if (material.doubleSided) {
  1512. babylonMaterial.backFaceCulling = false;
  1513. babylonMaterial.twoSidedLighting = true;
  1514. }
  1515. if (material.normalTexture) {
  1516. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  1517. if (!texture) {
  1518. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1519. }
  1520. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1521. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1522. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1523. if (material.normalTexture.scale != null) {
  1524. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1525. }
  1526. }
  1527. if (material.occlusionTexture) {
  1528. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  1529. if (!texture) {
  1530. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1531. }
  1532. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1533. babylonMaterial.useAmbientInGrayScale = true;
  1534. if (material.occlusionTexture.strength != null) {
  1535. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1536. }
  1537. }
  1538. if (material.emissiveTexture) {
  1539. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  1540. if (!texture) {
  1541. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1542. }
  1543. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1544. }
  1545. };
  1546. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  1547. var babylonMaterial = material.babylonMaterial;
  1548. var alphaMode = material.alphaMode || "OPAQUE";
  1549. switch (alphaMode) {
  1550. case "OPAQUE": {
  1551. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1552. break;
  1553. }
  1554. case "MASK": {
  1555. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  1556. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1557. if (colorFactor) {
  1558. if (colorFactor[3] == 0) {
  1559. babylonMaterial.alphaCutOff = 1;
  1560. }
  1561. else {
  1562. babylonMaterial.alphaCutOff /= colorFactor[3];
  1563. }
  1564. }
  1565. if (babylonMaterial.albedoTexture) {
  1566. babylonMaterial.albedoTexture.hasAlpha = true;
  1567. }
  1568. break;
  1569. }
  1570. case "BLEND": {
  1571. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1572. if (colorFactor) {
  1573. babylonMaterial.alpha = colorFactor[3];
  1574. }
  1575. if (babylonMaterial.albedoTexture) {
  1576. babylonMaterial.albedoTexture.hasAlpha = true;
  1577. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1578. }
  1579. break;
  1580. }
  1581. default: {
  1582. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  1583. }
  1584. }
  1585. };
  1586. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  1587. var _this = this;
  1588. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  1589. if (!sampler) {
  1590. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1591. }
  1592. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1593. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1594. this._addPendingData(texture);
  1595. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1596. _this._tryCatchOnError(function () {
  1597. _this._removePendingData(texture);
  1598. });
  1599. }, function (message) {
  1600. _this._tryCatchOnError(function () {
  1601. throw new Error(context + ": " + message);
  1602. });
  1603. });
  1604. if (texture.url) {
  1605. babylonTexture.updateURL(texture.url);
  1606. }
  1607. else if (texture.dataReadyObservable) {
  1608. texture.dataReadyObservable.add(function (texture) {
  1609. babylonTexture.updateURL(texture.url);
  1610. });
  1611. }
  1612. else {
  1613. texture.dataReadyObservable = new BABYLON.Observable();
  1614. texture.dataReadyObservable.add(function (texture) {
  1615. babylonTexture.updateURL(texture.url);
  1616. });
  1617. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  1618. if (!image_1) {
  1619. throw new Error(context + ": Failed to find source " + texture.source);
  1620. }
  1621. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  1622. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  1623. texture.dataReadyObservable.notifyObservers(texture);
  1624. texture.dataReadyObservable = undefined;
  1625. });
  1626. }
  1627. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1628. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  1629. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  1630. babylonTexture.name = texture.name || "texture" + texture.index;
  1631. if (this._parent.onTextureLoaded) {
  1632. this._parent.onTextureLoaded(babylonTexture);
  1633. }
  1634. return babylonTexture;
  1635. };
  1636. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  1637. if (image.uri) {
  1638. this._loadUriAsync(context, image.uri, onSuccess);
  1639. }
  1640. else {
  1641. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  1642. if (!bufferView) {
  1643. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1644. }
  1645. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1646. }
  1647. };
  1648. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  1649. var _this = this;
  1650. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  1651. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  1652. return;
  1653. }
  1654. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  1655. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1656. }
  1657. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  1658. _this._tryCatchOnError(function () {
  1659. onSuccess(new Uint8Array(data));
  1660. });
  1661. }, function (event) {
  1662. _this._tryCatchOnError(function () {
  1663. if (request && !_this._renderReady) {
  1664. request._loaded = event.loaded;
  1665. request._total = event.total;
  1666. _this._onProgress();
  1667. }
  1668. });
  1669. }, this._babylonScene.database, true, function (request) {
  1670. _this._tryCatchOnError(function () {
  1671. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1672. });
  1673. });
  1674. if (request) {
  1675. request._loaded = null;
  1676. request._total = null;
  1677. this._requests.push(request);
  1678. }
  1679. };
  1680. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  1681. if (this._disposed) {
  1682. return;
  1683. }
  1684. try {
  1685. handler();
  1686. }
  1687. catch (e) {
  1688. BABYLON.Tools.Error("glTF Loader: " + e.message);
  1689. if (this._errorCallback) {
  1690. this._errorCallback(e.message);
  1691. }
  1692. this.dispose();
  1693. }
  1694. };
  1695. GLTFLoader._AssignIndices = function (array) {
  1696. if (array) {
  1697. for (var index = 0; index < array.length; index++) {
  1698. array[index].index = index;
  1699. }
  1700. }
  1701. };
  1702. GLTFLoader._GetProperty = function (array, index) {
  1703. if (!array || index == undefined || !array[index]) {
  1704. return null;
  1705. }
  1706. return array[index];
  1707. };
  1708. GLTFLoader._GetTextureWrapMode = function (mode) {
  1709. // Set defaults if undefined
  1710. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1711. switch (mode) {
  1712. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1713. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1714. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1715. default:
  1716. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1717. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1718. }
  1719. };
  1720. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  1721. // Set defaults if undefined
  1722. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1723. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1724. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1725. switch (minFilter) {
  1726. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1727. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1728. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1729. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1730. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1731. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1732. default:
  1733. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1734. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1735. }
  1736. }
  1737. else {
  1738. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1739. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1740. }
  1741. switch (minFilter) {
  1742. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1743. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1744. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1745. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1746. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1747. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1748. default:
  1749. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1750. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1751. }
  1752. }
  1753. };
  1754. GLTFLoader._GetNumComponents = function (type) {
  1755. switch (type) {
  1756. case "SCALAR": return 1;
  1757. case "VEC2": return 2;
  1758. case "VEC3": return 3;
  1759. case "VEC4": return 4;
  1760. case "MAT2": return 4;
  1761. case "MAT3": return 9;
  1762. case "MAT4": return 16;
  1763. }
  1764. return 0;
  1765. };
  1766. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  1767. var _this = this;
  1768. if (!this._parent.compileMaterials) {
  1769. onSuccess();
  1770. return;
  1771. }
  1772. if (this._parent.useClipPlane) {
  1773. babylonMaterial.forceCompilation(babylonMesh, function () {
  1774. babylonMaterial.forceCompilation(babylonMesh, function () {
  1775. _this._tryCatchOnError(onSuccess);
  1776. }, { clipPlane: true });
  1777. });
  1778. }
  1779. else {
  1780. babylonMaterial.forceCompilation(babylonMesh, function () {
  1781. _this._tryCatchOnError(onSuccess);
  1782. });
  1783. }
  1784. };
  1785. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  1786. if (!this._parent.compileMaterials || !this._gltf.materials) {
  1787. onSuccess();
  1788. return;
  1789. }
  1790. var meshes = this._getMeshes();
  1791. var remaining = 0;
  1792. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  1793. var mesh = meshes_1[_i];
  1794. if (mesh.material instanceof BABYLON.MultiMaterial) {
  1795. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  1796. var subMaterial = _b[_a];
  1797. if (subMaterial) {
  1798. remaining++;
  1799. }
  1800. }
  1801. }
  1802. }
  1803. if (remaining === 0) {
  1804. onSuccess();
  1805. return;
  1806. }
  1807. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  1808. var mesh = meshes_2[_c];
  1809. if (mesh.material instanceof BABYLON.MultiMaterial) {
  1810. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  1811. var subMaterial = _e[_d];
  1812. if (subMaterial) {
  1813. this._compileMaterialAsync(subMaterial, mesh, function () {
  1814. if (--remaining === 0) {
  1815. onSuccess();
  1816. }
  1817. });
  1818. }
  1819. }
  1820. }
  1821. }
  1822. };
  1823. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  1824. var _this = this;
  1825. if (!this._parent.compileShadowGenerators) {
  1826. onSuccess();
  1827. return;
  1828. }
  1829. var lights = this._babylonScene.lights;
  1830. var remaining = 0;
  1831. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  1832. var light = lights_1[_i];
  1833. var generator = light.getShadowGenerator();
  1834. if (generator) {
  1835. remaining++;
  1836. }
  1837. }
  1838. if (remaining === 0) {
  1839. onSuccess();
  1840. return;
  1841. }
  1842. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  1843. var light = lights_2[_a];
  1844. var generator = light.getShadowGenerator();
  1845. if (generator) {
  1846. generator.forceCompilation(function () {
  1847. if (--remaining === 0) {
  1848. _this._tryCatchOnError(onSuccess);
  1849. }
  1850. });
  1851. }
  1852. }
  1853. };
  1854. GLTFLoader.Extensions = {};
  1855. return GLTFLoader;
  1856. }());
  1857. GLTF2.GLTFLoader = GLTFLoader;
  1858. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1859. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1860. })(BABYLON || (BABYLON = {}));
  1861. //# sourceMappingURL=babylon.glTFLoader.js.map
  1862. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1863. var BABYLON;
  1864. (function (BABYLON) {
  1865. var GLTF2;
  1866. (function (GLTF2) {
  1867. /**
  1868. * Utils functions for GLTF
  1869. */
  1870. var GLTFUtils = /** @class */ (function () {
  1871. function GLTFUtils() {
  1872. }
  1873. /**
  1874. * If the uri is a base64 string
  1875. * @param uri: the uri to test
  1876. */
  1877. GLTFUtils.IsBase64 = function (uri) {
  1878. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1879. };
  1880. /**
  1881. * Decode the base64 uri
  1882. * @param uri: the uri to decode
  1883. */
  1884. GLTFUtils.DecodeBase64 = function (uri) {
  1885. var decodedString = atob(uri.split(",")[1]);
  1886. var bufferLength = decodedString.length;
  1887. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1888. for (var i = 0; i < bufferLength; i++) {
  1889. bufferView[i] = decodedString.charCodeAt(i);
  1890. }
  1891. return bufferView.buffer;
  1892. };
  1893. GLTFUtils.ValidateUri = function (uri) {
  1894. return (uri.indexOf("..") === -1);
  1895. };
  1896. return GLTFUtils;
  1897. }());
  1898. GLTF2.GLTFUtils = GLTFUtils;
  1899. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1900. })(BABYLON || (BABYLON = {}));
  1901. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1902. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1903. var BABYLON;
  1904. (function (BABYLON) {
  1905. var GLTF2;
  1906. (function (GLTF2) {
  1907. var GLTFLoaderExtension = /** @class */ (function () {
  1908. function GLTFLoaderExtension() {
  1909. this.enabled = true;
  1910. }
  1911. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  1912. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  1913. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  1914. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  1915. var _this = this;
  1916. if (!property.extensions) {
  1917. return false;
  1918. }
  1919. var extension = property.extensions[this.name];
  1920. if (!extension) {
  1921. return false;
  1922. }
  1923. // Clear out the extension before executing the action to avoid recursing into the same property.
  1924. property.extensions[this.name] = undefined;
  1925. action(context + "extensions/" + this.name, extension, function () {
  1926. // Restore the extension after completing the action.
  1927. property.extensions[_this.name] = extension;
  1928. });
  1929. return true;
  1930. };
  1931. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  1932. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  1933. };
  1934. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  1935. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  1936. };
  1937. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  1938. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  1939. };
  1940. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1941. var extensions = GLTFLoaderExtension._Extensions;
  1942. if (!extensions) {
  1943. return false;
  1944. }
  1945. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  1946. var extension = extensions_1[_i];
  1947. if (extension.enabled && action(extension)) {
  1948. return true;
  1949. }
  1950. }
  1951. return false;
  1952. };
  1953. //
  1954. // Utilities
  1955. //
  1956. GLTFLoaderExtension._Extensions = [];
  1957. return GLTFLoaderExtension;
  1958. }());
  1959. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1960. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1961. })(BABYLON || (BABYLON = {}));
  1962. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1963. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1964. var __extends = (this && this.__extends) || (function () {
  1965. var extendStatics = Object.setPrototypeOf ||
  1966. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1967. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1968. return function (d, b) {
  1969. extendStatics(d, b);
  1970. function __() { this.constructor = d; }
  1971. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1972. };
  1973. })();
  1974. var BABYLON;
  1975. (function (BABYLON) {
  1976. var GLTF2;
  1977. (function (GLTF2) {
  1978. var Extensions;
  1979. (function (Extensions) {
  1980. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  1981. var MSFTLOD = /** @class */ (function (_super) {
  1982. __extends(MSFTLOD, _super);
  1983. function MSFTLOD() {
  1984. var _this = _super !== null && _super.apply(this, arguments) || this;
  1985. /**
  1986. * Specify the minimal delay between LODs in ms (default = 250)
  1987. */
  1988. _this.Delay = 250;
  1989. return _this;
  1990. }
  1991. Object.defineProperty(MSFTLOD.prototype, "name", {
  1992. get: function () {
  1993. return "MSFT_lod";
  1994. },
  1995. enumerable: true,
  1996. configurable: true
  1997. });
  1998. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  1999. return this._loadExtension(context, node, function (context, extension, onComplete) {
  2000. for (var i = extension.ids.length - 1; i >= 0; i--) {
  2001. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  2002. if (!lodNode) {
  2003. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  2004. }
  2005. loader._traverseNode(context, lodNode, action, parentNode);
  2006. }
  2007. loader._traverseNode(context, node, action, parentNode);
  2008. onComplete();
  2009. });
  2010. };
  2011. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  2012. var _this = this;
  2013. return this._loadExtension(context, node, function (context, extension, onComplete) {
  2014. var nodes = [node];
  2015. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  2016. var index = _a[_i];
  2017. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  2018. if (!lodNode) {
  2019. throw new Error(context + ": Failed to find node " + index);
  2020. }
  2021. nodes.push(lodNode);
  2022. }
  2023. loader._addLoaderPendingData(node);
  2024. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  2025. loader._removeLoaderPendingData(node);
  2026. onComplete();
  2027. });
  2028. });
  2029. };
  2030. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  2031. var _this = this;
  2032. loader._whenAction(function () {
  2033. loader._loadNode(context, nodes[index]);
  2034. }, function () {
  2035. if (index !== nodes.length - 1) {
  2036. var previousNode = nodes[index + 1];
  2037. previousNode.babylonMesh.setEnabled(false);
  2038. }
  2039. if (index === 0) {
  2040. onComplete();
  2041. return;
  2042. }
  2043. setTimeout(function () {
  2044. loader._tryCatchOnError(function () {
  2045. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  2046. });
  2047. }, _this.Delay);
  2048. });
  2049. };
  2050. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  2051. var _this = this;
  2052. return this._loadExtension(context, material, function (context, extension, onComplete) {
  2053. var materials = [material];
  2054. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  2055. var index = _a[_i];
  2056. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  2057. if (!lodMaterial) {
  2058. throw new Error(context + ": Failed to find material " + index);
  2059. }
  2060. materials.push(lodMaterial);
  2061. }
  2062. loader._addLoaderPendingData(material);
  2063. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  2064. loader._removeLoaderPendingData(material);
  2065. onComplete();
  2066. });
  2067. });
  2068. };
  2069. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  2070. var _this = this;
  2071. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  2072. if (index === materials.length - 1) {
  2073. assign(babylonMaterial, isNew);
  2074. // Load the next LOD when the loader is ready to render.
  2075. loader._executeWhenRenderReady(function () {
  2076. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  2077. });
  2078. }
  2079. else {
  2080. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  2081. assign(babylonMaterial, isNew);
  2082. if (index === 0) {
  2083. onComplete();
  2084. }
  2085. else {
  2086. setTimeout(function () {
  2087. loader._tryCatchOnError(function () {
  2088. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  2089. });
  2090. }, _this.Delay);
  2091. }
  2092. });
  2093. }
  2094. });
  2095. };
  2096. return MSFTLOD;
  2097. }(GLTF2.GLTFLoaderExtension));
  2098. Extensions.MSFTLOD = MSFTLOD;
  2099. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  2100. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2101. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2102. })(BABYLON || (BABYLON = {}));
  2103. //# sourceMappingURL=MSFT_lod.js.map
  2104. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2105. var __extends = (this && this.__extends) || (function () {
  2106. var extendStatics = Object.setPrototypeOf ||
  2107. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2108. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2109. return function (d, b) {
  2110. extendStatics(d, b);
  2111. function __() { this.constructor = d; }
  2112. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2113. };
  2114. })();
  2115. var BABYLON;
  2116. (function (BABYLON) {
  2117. var GLTF2;
  2118. (function (GLTF2) {
  2119. var Extensions;
  2120. (function (Extensions) {
  2121. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  2122. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  2123. function KHRMaterialsPbrSpecularGlossiness() {
  2124. return _super !== null && _super.apply(this, arguments) || this;
  2125. }
  2126. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  2127. get: function () {
  2128. return "KHR_materials_pbrSpecularGlossiness";
  2129. },
  2130. enumerable: true,
  2131. configurable: true
  2132. });
  2133. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  2134. var _this = this;
  2135. return this._loadExtension(context, material, function (context, extension, onComplete) {
  2136. loader._createPbrMaterial(material);
  2137. loader._loadMaterialBaseProperties(context, material);
  2138. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  2139. assign(material.babylonMaterial, true);
  2140. onComplete();
  2141. });
  2142. };
  2143. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  2144. var babylonMaterial = material.babylonMaterial;
  2145. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  2146. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  2147. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  2148. if (properties.diffuseTexture) {
  2149. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  2150. if (!texture) {
  2151. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  2152. }
  2153. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  2154. }
  2155. if (properties.specularGlossinessTexture) {
  2156. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  2157. if (!texture) {
  2158. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  2159. }
  2160. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  2161. babylonMaterial.reflectivityTexture.hasAlpha = true;
  2162. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  2163. }
  2164. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  2165. };
  2166. return KHRMaterialsPbrSpecularGlossiness;
  2167. }(GLTF2.GLTFLoaderExtension));
  2168. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  2169. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  2170. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2171. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2172. })(BABYLON || (BABYLON = {}));
  2173. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map