babylon.glTF2FileLoader.js 115 KB

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