babylon.glTF2FileLoader.js 121 KB

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