babylon.glTF2FileLoader.js 130 KB

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