babylon.glTF1FileLoader.js 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675
  1. "use strict";
  2. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var GLTFLoaderCoordinateSystemMode;
  6. (function (GLTFLoaderCoordinateSystemMode) {
  7. /**
  8. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  9. */
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  11. /**
  12. * Sets the useRightHandedSystem flag on the scene.
  13. */
  14. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  15. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  16. var GLTFLoaderAnimationStartMode;
  17. (function (GLTFLoaderAnimationStartMode) {
  18. /**
  19. * No animation will start.
  20. */
  21. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  22. /**
  23. * The first animation will start.
  24. */
  25. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  26. /**
  27. * All animations will start.
  28. */
  29. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  30. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  31. var GLTFLoaderState;
  32. (function (GLTFLoaderState) {
  33. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  34. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  35. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  36. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  37. var GLTFFileLoader = /** @class */ (function () {
  38. function GLTFFileLoader() {
  39. // #region Common options
  40. /**
  41. * Raised when the asset has been parsed.
  42. * The data.json property stores the glTF JSON.
  43. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  44. */
  45. this.onParsedObservable = new BABYLON.Observable();
  46. // #endregion
  47. // #region V2 options
  48. /**
  49. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  50. */
  51. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  52. /**
  53. * The animation start mode (NONE, FIRST, ALL).
  54. */
  55. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  56. /**
  57. * Set to true to compile materials before raising the success callback.
  58. */
  59. this.compileMaterials = false;
  60. /**
  61. * Set to true to also compile materials with clip planes.
  62. */
  63. this.useClipPlane = false;
  64. /**
  65. * Set to true to compile shadow generators before raising the success callback.
  66. */
  67. this.compileShadowGenerators = false;
  68. /**
  69. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  70. */
  71. this.onMeshLoadedObservable = new BABYLON.Observable();
  72. /**
  73. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  74. */
  75. this.onTextureLoadedObservable = new BABYLON.Observable();
  76. /**
  77. * Raised when the loader creates a material after parsing the glTF properties of the material.
  78. */
  79. this.onMaterialLoadedObservable = new BABYLON.Observable();
  80. /**
  81. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  82. */
  83. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  84. /**
  85. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  86. * For assets with LODs, raised when all of the LODs are complete.
  87. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88. */
  89. this.onCompleteObservable = new BABYLON.Observable();
  90. /**
  91. * Raised when the loader is disposed.
  92. */
  93. this.onDisposeObservable = new BABYLON.Observable();
  94. /**
  95. * Raised after a loader extension is created.
  96. * Set additional options for a loader extension in this event.
  97. */
  98. this.onExtensionLoadedObservable = new BABYLON.Observable();
  99. // #endregion
  100. this._loader = null;
  101. this.name = "gltf";
  102. this.extensions = {
  103. ".gltf": { isBinary: false },
  104. ".glb": { isBinary: true }
  105. };
  106. }
  107. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  108. set: function (callback) {
  109. if (this._onParsedObserver) {
  110. this.onParsedObservable.remove(this._onParsedObserver);
  111. }
  112. this._onParsedObserver = this.onParsedObservable.add(callback);
  113. },
  114. enumerable: true,
  115. configurable: true
  116. });
  117. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  118. set: function (callback) {
  119. if (this._onMeshLoadedObserver) {
  120. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  121. }
  122. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  123. },
  124. enumerable: true,
  125. configurable: true
  126. });
  127. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  128. set: function (callback) {
  129. if (this._onTextureLoadedObserver) {
  130. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  131. }
  132. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  133. },
  134. enumerable: true,
  135. configurable: true
  136. });
  137. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  138. set: function (callback) {
  139. if (this._onMaterialLoadedObserver) {
  140. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  141. }
  142. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  143. },
  144. enumerable: true,
  145. configurable: true
  146. });
  147. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  148. set: function (callback) {
  149. if (this._onAnimationGroupLoadedObserver) {
  150. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  151. }
  152. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  153. },
  154. enumerable: true,
  155. configurable: true
  156. });
  157. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  158. set: function (callback) {
  159. if (this._onCompleteObserver) {
  160. this.onCompleteObservable.remove(this._onCompleteObserver);
  161. }
  162. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  168. set: function (callback) {
  169. if (this._onDisposeObserver) {
  170. this.onDisposeObservable.remove(this._onDisposeObserver);
  171. }
  172. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  173. },
  174. enumerable: true,
  175. configurable: true
  176. });
  177. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  178. set: function (callback) {
  179. if (this._onExtensionLoadedObserver) {
  180. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  181. }
  182. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. /**
  188. * Gets a promise that resolves when the asset is completely loaded.
  189. * @returns A promise that resolves when the asset is completely loaded.
  190. */
  191. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  192. var _this = this;
  193. return new Promise(function (resolve) {
  194. _this.onCompleteObservable.add(function () {
  195. resolve();
  196. }, undefined, undefined, undefined, true);
  197. });
  198. };
  199. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  200. /**
  201. * The loader state or null if not active.
  202. */
  203. get: function () {
  204. return this._loader ? this._loader.state : null;
  205. },
  206. enumerable: true,
  207. configurable: true
  208. });
  209. /**
  210. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  211. */
  212. GLTFFileLoader.prototype.dispose = function () {
  213. if (this._loader) {
  214. this._loader.dispose();
  215. this._loader = null;
  216. }
  217. this.onMeshLoadedObservable.clear();
  218. this.onTextureLoadedObservable.clear();
  219. this.onMaterialLoadedObservable.clear();
  220. this.onDisposeObservable.notifyObservers(this);
  221. this.onDisposeObservable.clear();
  222. };
  223. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  224. var _this = this;
  225. return Promise.resolve().then(function () {
  226. var loaderData = _this._parse(data);
  227. _this._loader = _this._getLoader(loaderData);
  228. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  229. });
  230. };
  231. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  232. var _this = this;
  233. return Promise.resolve().then(function () {
  234. var loaderData = _this._parse(data);
  235. _this._loader = _this._getLoader(loaderData);
  236. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  237. });
  238. };
  239. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  240. var _this = this;
  241. return Promise.resolve().then(function () {
  242. var loaderData = _this._parse(data);
  243. _this._loader = _this._getLoader(loaderData);
  244. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  245. var container = new BABYLON.AssetContainer(scene);
  246. Array.prototype.push.apply(container.meshes, result.meshes);
  247. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  248. Array.prototype.push.apply(container.skeletons, result.skeletons);
  249. container.removeAllFromScene();
  250. return container;
  251. });
  252. });
  253. };
  254. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  255. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  256. };
  257. GLTFFileLoader.prototype.createPlugin = function () {
  258. return new GLTFFileLoader();
  259. };
  260. GLTFFileLoader.prototype._parse = function (data) {
  261. var parsedData;
  262. if (data instanceof ArrayBuffer) {
  263. parsedData = GLTFFileLoader._parseBinary(data);
  264. }
  265. else {
  266. parsedData = {
  267. json: JSON.parse(data),
  268. bin: null
  269. };
  270. }
  271. this.onParsedObservable.notifyObservers(parsedData);
  272. this.onParsedObservable.clear();
  273. return parsedData;
  274. };
  275. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  276. var _this = this;
  277. var loaderVersion = { major: 2, minor: 0 };
  278. var asset = loaderData.json.asset || {};
  279. var version = GLTFFileLoader._parseVersion(asset.version);
  280. if (!version) {
  281. throw new Error("Invalid version: " + asset.version);
  282. }
  283. if (asset.minVersion !== undefined) {
  284. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  285. if (!minVersion) {
  286. throw new Error("Invalid minimum version: " + asset.minVersion);
  287. }
  288. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  289. throw new Error("Incompatible minimum version: " + asset.minVersion);
  290. }
  291. }
  292. var createLoaders = {
  293. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  294. 2: GLTFFileLoader.CreateGLTFLoaderV2
  295. };
  296. var createLoader = createLoaders[version.major];
  297. if (!createLoader) {
  298. throw new Error("Unsupported version: " + asset.version);
  299. }
  300. var loader = createLoader();
  301. loader.coordinateSystemMode = this.coordinateSystemMode;
  302. loader.animationStartMode = this.animationStartMode;
  303. loader.compileMaterials = this.compileMaterials;
  304. loader.useClipPlane = this.useClipPlane;
  305. loader.compileShadowGenerators = this.compileShadowGenerators;
  306. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  307. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  308. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  309. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  310. loader.onCompleteObservable.add(function () {
  311. _this.onMeshLoadedObservable.clear();
  312. _this.onTextureLoadedObservable.clear();
  313. _this.onMaterialLoadedObservable.clear();
  314. _this.onCompleteObservable.notifyObservers(_this);
  315. _this.onCompleteObservable.clear();
  316. });
  317. return loader;
  318. };
  319. GLTFFileLoader._parseBinary = function (data) {
  320. var Binary = {
  321. Magic: 0x46546C67
  322. };
  323. var binaryReader = new BinaryReader(data);
  324. var magic = binaryReader.readUint32();
  325. if (magic !== Binary.Magic) {
  326. throw new Error("Unexpected magic: " + magic);
  327. }
  328. var version = binaryReader.readUint32();
  329. switch (version) {
  330. case 1: return GLTFFileLoader._parseV1(binaryReader);
  331. case 2: return GLTFFileLoader._parseV2(binaryReader);
  332. }
  333. throw new Error("Unsupported version: " + version);
  334. };
  335. GLTFFileLoader._parseV1 = function (binaryReader) {
  336. var ContentFormat = {
  337. JSON: 0
  338. };
  339. var length = binaryReader.readUint32();
  340. if (length != binaryReader.getLength()) {
  341. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  342. }
  343. var contentLength = binaryReader.readUint32();
  344. var contentFormat = binaryReader.readUint32();
  345. var content;
  346. switch (contentFormat) {
  347. case ContentFormat.JSON: {
  348. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  349. break;
  350. }
  351. default: {
  352. throw new Error("Unexpected content format: " + contentFormat);
  353. }
  354. }
  355. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  356. var body = binaryReader.readUint8Array(bytesRemaining);
  357. return {
  358. json: content,
  359. bin: body
  360. };
  361. };
  362. GLTFFileLoader._parseV2 = function (binaryReader) {
  363. var ChunkFormat = {
  364. JSON: 0x4E4F534A,
  365. BIN: 0x004E4942
  366. };
  367. var length = binaryReader.readUint32();
  368. if (length !== binaryReader.getLength()) {
  369. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  370. }
  371. // JSON chunk
  372. var chunkLength = binaryReader.readUint32();
  373. var chunkFormat = binaryReader.readUint32();
  374. if (chunkFormat !== ChunkFormat.JSON) {
  375. throw new Error("First chunk format is not JSON");
  376. }
  377. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  378. // Look for BIN chunk
  379. var bin = null;
  380. while (binaryReader.getPosition() < binaryReader.getLength()) {
  381. var chunkLength_1 = binaryReader.readUint32();
  382. var chunkFormat_1 = binaryReader.readUint32();
  383. switch (chunkFormat_1) {
  384. case ChunkFormat.JSON: {
  385. throw new Error("Unexpected JSON chunk");
  386. }
  387. case ChunkFormat.BIN: {
  388. bin = binaryReader.readUint8Array(chunkLength_1);
  389. break;
  390. }
  391. default: {
  392. // ignore unrecognized chunkFormat
  393. binaryReader.skipBytes(chunkLength_1);
  394. break;
  395. }
  396. }
  397. }
  398. return {
  399. json: json,
  400. bin: bin
  401. };
  402. };
  403. GLTFFileLoader._parseVersion = function (version) {
  404. if (version === "1.0" || version === "1.0.1") {
  405. return {
  406. major: 1,
  407. minor: 0
  408. };
  409. }
  410. var match = (version + "").match(/^(\d+)\.(\d+)/);
  411. if (!match) {
  412. return null;
  413. }
  414. return {
  415. major: parseInt(match[1]),
  416. minor: parseInt(match[2])
  417. };
  418. };
  419. GLTFFileLoader._compareVersion = function (a, b) {
  420. if (a.major > b.major)
  421. return 1;
  422. if (a.major < b.major)
  423. return -1;
  424. if (a.minor > b.minor)
  425. return 1;
  426. if (a.minor < b.minor)
  427. return -1;
  428. return 0;
  429. };
  430. GLTFFileLoader._decodeBufferToText = function (buffer) {
  431. var result = "";
  432. var length = buffer.byteLength;
  433. for (var i = 0; i < length; i++) {
  434. result += String.fromCharCode(buffer[i]);
  435. }
  436. return result;
  437. };
  438. // #endregion
  439. // #region V1 options
  440. GLTFFileLoader.IncrementalLoading = true;
  441. GLTFFileLoader.HomogeneousCoordinates = false;
  442. return GLTFFileLoader;
  443. }());
  444. BABYLON.GLTFFileLoader = GLTFFileLoader;
  445. var BinaryReader = /** @class */ (function () {
  446. function BinaryReader(arrayBuffer) {
  447. this._arrayBuffer = arrayBuffer;
  448. this._dataView = new DataView(arrayBuffer);
  449. this._byteOffset = 0;
  450. }
  451. BinaryReader.prototype.getPosition = function () {
  452. return this._byteOffset;
  453. };
  454. BinaryReader.prototype.getLength = function () {
  455. return this._arrayBuffer.byteLength;
  456. };
  457. BinaryReader.prototype.readUint32 = function () {
  458. var value = this._dataView.getUint32(this._byteOffset, true);
  459. this._byteOffset += 4;
  460. return value;
  461. };
  462. BinaryReader.prototype.readUint8Array = function (length) {
  463. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  464. this._byteOffset += length;
  465. return value;
  466. };
  467. BinaryReader.prototype.skipBytes = function (length) {
  468. this._byteOffset += length;
  469. };
  470. return BinaryReader;
  471. }());
  472. if (BABYLON.SceneLoader) {
  473. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  474. }
  475. })(BABYLON || (BABYLON = {}));
  476. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  477. "use strict";
  478. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  479. var BABYLON;
  480. (function (BABYLON) {
  481. var GLTF1;
  482. (function (GLTF1) {
  483. /**
  484. * Enums
  485. */
  486. var EComponentType;
  487. (function (EComponentType) {
  488. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  489. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  490. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  491. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  492. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  493. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  494. var EShaderType;
  495. (function (EShaderType) {
  496. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  497. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  498. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  499. var EParameterType;
  500. (function (EParameterType) {
  501. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  502. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  503. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  504. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  505. EParameterType[EParameterType["INT"] = 5124] = "INT";
  506. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  507. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  508. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  509. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  510. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  511. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  512. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  513. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  514. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  515. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  516. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  517. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  518. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  519. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  520. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  521. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  522. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  523. var ETextureWrapMode;
  524. (function (ETextureWrapMode) {
  525. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  526. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  527. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  528. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  529. var ETextureFilterType;
  530. (function (ETextureFilterType) {
  531. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  532. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  533. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  534. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  535. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  536. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  537. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  538. var ETextureFormat;
  539. (function (ETextureFormat) {
  540. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  541. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  542. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  543. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  544. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  545. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  546. var ECullingType;
  547. (function (ECullingType) {
  548. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  549. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  550. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  551. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  552. var EBlendingFunction;
  553. (function (EBlendingFunction) {
  554. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  555. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  556. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  557. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  558. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  559. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  560. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  561. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  562. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  563. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  564. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  565. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  566. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  567. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  568. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  569. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  570. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  571. })(BABYLON || (BABYLON = {}));
  572. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  573. "use strict";
  574. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  575. var BABYLON;
  576. (function (BABYLON) {
  577. var GLTF1;
  578. (function (GLTF1) {
  579. /**
  580. * Tokenizer. Used for shaders compatibility
  581. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  582. */
  583. var ETokenType;
  584. (function (ETokenType) {
  585. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  586. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  587. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  588. })(ETokenType || (ETokenType = {}));
  589. var Tokenizer = /** @class */ (function () {
  590. function Tokenizer(toParse) {
  591. this._pos = 0;
  592. this.currentToken = ETokenType.UNKNOWN;
  593. this.currentIdentifier = "";
  594. this.currentString = "";
  595. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  596. this._toParse = toParse;
  597. this._maxPos = toParse.length;
  598. }
  599. Tokenizer.prototype.getNextToken = function () {
  600. if (this.isEnd())
  601. return ETokenType.END_OF_INPUT;
  602. this.currentString = this.read();
  603. this.currentToken = ETokenType.UNKNOWN;
  604. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  605. this.currentToken = ETokenType.IDENTIFIER;
  606. this.currentIdentifier = this.currentString;
  607. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  608. this.currentIdentifier += this.currentString;
  609. this.forward();
  610. }
  611. }
  612. return this.currentToken;
  613. };
  614. Tokenizer.prototype.peek = function () {
  615. return this._toParse[this._pos];
  616. };
  617. Tokenizer.prototype.read = function () {
  618. return this._toParse[this._pos++];
  619. };
  620. Tokenizer.prototype.forward = function () {
  621. this._pos++;
  622. };
  623. Tokenizer.prototype.isEnd = function () {
  624. return this._pos >= this._maxPos;
  625. };
  626. return Tokenizer;
  627. }());
  628. /**
  629. * Values
  630. */
  631. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  632. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  633. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  634. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  635. /**
  636. * Parse
  637. */
  638. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  639. for (var buf in parsedBuffers) {
  640. var parsedBuffer = parsedBuffers[buf];
  641. gltfRuntime.buffers[buf] = parsedBuffer;
  642. gltfRuntime.buffersCount++;
  643. }
  644. };
  645. var parseShaders = function (parsedShaders, gltfRuntime) {
  646. for (var sha in parsedShaders) {
  647. var parsedShader = parsedShaders[sha];
  648. gltfRuntime.shaders[sha] = parsedShader;
  649. gltfRuntime.shaderscount++;
  650. }
  651. };
  652. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  653. for (var object in parsedObjects) {
  654. var parsedObject = parsedObjects[object];
  655. gltfRuntime[runtimeProperty][object] = parsedObject;
  656. }
  657. };
  658. /**
  659. * Utils
  660. */
  661. var normalizeUVs = function (buffer) {
  662. if (!buffer) {
  663. return;
  664. }
  665. for (var i = 0; i < buffer.length / 2; i++) {
  666. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  667. }
  668. };
  669. var getAttribute = function (attributeParameter) {
  670. if (attributeParameter.semantic === "NORMAL") {
  671. return "normal";
  672. }
  673. else if (attributeParameter.semantic === "POSITION") {
  674. return "position";
  675. }
  676. else if (attributeParameter.semantic === "JOINT") {
  677. return "matricesIndices";
  678. }
  679. else if (attributeParameter.semantic === "WEIGHT") {
  680. return "matricesWeights";
  681. }
  682. else if (attributeParameter.semantic === "COLOR") {
  683. return "color";
  684. }
  685. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  686. var channel = Number(attributeParameter.semantic.split("_")[1]);
  687. return "uv" + (channel === 0 ? "" : channel + 1);
  688. }
  689. return null;
  690. };
  691. /**
  692. * Loads and creates animations
  693. */
  694. var loadAnimations = function (gltfRuntime) {
  695. for (var anim in gltfRuntime.animations) {
  696. var animation = gltfRuntime.animations[anim];
  697. if (!animation.channels || !animation.samplers) {
  698. continue;
  699. }
  700. var lastAnimation = null;
  701. for (var i = 0; i < animation.channels.length; i++) {
  702. // Get parameters and load buffers
  703. var channel = animation.channels[i];
  704. var sampler = animation.samplers[channel.sampler];
  705. if (!sampler) {
  706. continue;
  707. }
  708. var inputData = null;
  709. var outputData = null;
  710. if (animation.parameters) {
  711. inputData = animation.parameters[sampler.input];
  712. outputData = animation.parameters[sampler.output];
  713. }
  714. else {
  715. inputData = sampler.input;
  716. outputData = sampler.output;
  717. }
  718. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  719. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  720. var targetID = channel.target.id;
  721. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  722. if (targetNode === null) {
  723. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  724. }
  725. if (targetNode === null) {
  726. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  727. continue;
  728. }
  729. var isBone = targetNode instanceof BABYLON.Bone;
  730. // Get target path (position, rotation or scaling)
  731. var targetPath = channel.target.path;
  732. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  733. if (targetPathIndex !== -1) {
  734. targetPath = babylonAnimationPaths[targetPathIndex];
  735. }
  736. // Determine animation type
  737. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  738. if (!isBone) {
  739. if (targetPath === "rotationQuaternion") {
  740. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  741. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  742. }
  743. else {
  744. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  745. }
  746. }
  747. // Create animation and key frames
  748. var babylonAnimation = null;
  749. var keys = [];
  750. var arrayOffset = 0;
  751. var modifyKey = false;
  752. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  753. babylonAnimation = lastAnimation;
  754. modifyKey = true;
  755. }
  756. if (!modifyKey) {
  757. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  758. }
  759. // For each frame
  760. for (var j = 0; j < bufferInput.length; j++) {
  761. var value = null;
  762. if (targetPath === "rotationQuaternion") {
  763. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  764. arrayOffset += 4;
  765. }
  766. else {
  767. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  768. arrayOffset += 3;
  769. }
  770. if (isBone) {
  771. var bone = targetNode;
  772. var translation = BABYLON.Vector3.Zero();
  773. var rotationQuaternion = new BABYLON.Quaternion();
  774. var scaling = BABYLON.Vector3.Zero();
  775. // Warning on decompose
  776. var mat = bone.getBaseMatrix();
  777. if (modifyKey && lastAnimation) {
  778. mat = lastAnimation.getKeys()[j].value;
  779. }
  780. mat.decompose(scaling, rotationQuaternion, translation);
  781. if (targetPath === "position") {
  782. translation = value;
  783. }
  784. else if (targetPath === "rotationQuaternion") {
  785. rotationQuaternion = value;
  786. }
  787. else {
  788. scaling = value;
  789. }
  790. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  791. }
  792. if (!modifyKey) {
  793. keys.push({
  794. frame: bufferInput[j],
  795. value: value
  796. });
  797. }
  798. else if (lastAnimation) {
  799. lastAnimation.getKeys()[j].value = value;
  800. }
  801. }
  802. // Finish
  803. if (!modifyKey && babylonAnimation) {
  804. babylonAnimation.setKeys(keys);
  805. targetNode.animations.push(babylonAnimation);
  806. }
  807. lastAnimation = babylonAnimation;
  808. gltfRuntime.scene.stopAnimation(targetNode);
  809. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  810. }
  811. }
  812. };
  813. /**
  814. * Returns the bones transformation matrix
  815. */
  816. var configureBoneTransformation = function (node) {
  817. var mat = null;
  818. if (node.translation || node.rotation || node.scale) {
  819. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  820. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  821. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  822. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  823. }
  824. else {
  825. mat = BABYLON.Matrix.FromArray(node.matrix);
  826. }
  827. return mat;
  828. };
  829. /**
  830. * Returns the parent bone
  831. */
  832. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  833. // Try to find
  834. for (var i = 0; i < newSkeleton.bones.length; i++) {
  835. if (newSkeleton.bones[i].name === jointName) {
  836. return newSkeleton.bones[i];
  837. }
  838. }
  839. // Not found, search in gltf nodes
  840. var nodes = gltfRuntime.nodes;
  841. for (var nde in nodes) {
  842. var node = nodes[nde];
  843. if (!node.jointName) {
  844. continue;
  845. }
  846. var children = node.children;
  847. for (var i = 0; i < children.length; i++) {
  848. var child = gltfRuntime.nodes[children[i]];
  849. if (!child.jointName) {
  850. continue;
  851. }
  852. if (child.jointName === jointName) {
  853. var mat = configureBoneTransformation(node);
  854. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  855. bone.id = nde;
  856. return bone;
  857. }
  858. }
  859. }
  860. return null;
  861. };
  862. /**
  863. * Returns the appropriate root node
  864. */
  865. var getNodeToRoot = function (nodesToRoot, id) {
  866. for (var i = 0; i < nodesToRoot.length; i++) {
  867. var nodeToRoot = nodesToRoot[i];
  868. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  869. var child = nodeToRoot.node.children[j];
  870. if (child === id) {
  871. return nodeToRoot.bone;
  872. }
  873. }
  874. }
  875. return null;
  876. };
  877. /**
  878. * Returns the node with the joint name
  879. */
  880. var getJointNode = function (gltfRuntime, jointName) {
  881. var nodes = gltfRuntime.nodes;
  882. var node = nodes[jointName];
  883. if (node) {
  884. return {
  885. node: node,
  886. id: jointName
  887. };
  888. }
  889. for (var nde in nodes) {
  890. node = nodes[nde];
  891. if (node.jointName === jointName) {
  892. return {
  893. node: node,
  894. id: nde
  895. };
  896. }
  897. }
  898. return null;
  899. };
  900. /**
  901. * Checks if a nodes is in joints
  902. */
  903. var nodeIsInJoints = function (skins, id) {
  904. for (var i = 0; i < skins.jointNames.length; i++) {
  905. if (skins.jointNames[i] === id) {
  906. return true;
  907. }
  908. }
  909. return false;
  910. };
  911. /**
  912. * Fills the nodes to root for bones and builds hierarchy
  913. */
  914. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  915. // Creates nodes for root
  916. for (var nde in gltfRuntime.nodes) {
  917. var node = gltfRuntime.nodes[nde];
  918. var id = nde;
  919. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  920. continue;
  921. }
  922. // Create node to root bone
  923. var mat = configureBoneTransformation(node);
  924. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  925. bone.id = id;
  926. nodesToRoot.push({ bone: bone, node: node, id: id });
  927. }
  928. // Parenting
  929. for (var i = 0; i < nodesToRoot.length; i++) {
  930. var nodeToRoot = nodesToRoot[i];
  931. var children = nodeToRoot.node.children;
  932. for (var j = 0; j < children.length; j++) {
  933. var child = null;
  934. for (var k = 0; k < nodesToRoot.length; k++) {
  935. if (nodesToRoot[k].id === children[j]) {
  936. child = nodesToRoot[k];
  937. break;
  938. }
  939. }
  940. if (child) {
  941. child.bone._parent = nodeToRoot.bone;
  942. nodeToRoot.bone.children.push(child.bone);
  943. }
  944. }
  945. }
  946. };
  947. /**
  948. * Imports a skeleton
  949. */
  950. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  951. if (!newSkeleton) {
  952. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  953. }
  954. if (!skins.babylonSkeleton) {
  955. return newSkeleton;
  956. }
  957. // Find the root bones
  958. var nodesToRoot = [];
  959. var nodesToRootToAdd = [];
  960. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  961. newSkeleton.bones = [];
  962. // Joints
  963. for (var i = 0; i < skins.jointNames.length; i++) {
  964. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  965. if (!jointNode) {
  966. continue;
  967. }
  968. var node = jointNode.node;
  969. if (!node) {
  970. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  971. continue;
  972. }
  973. var id = jointNode.id;
  974. // Optimize, if the bone already exists...
  975. var existingBone = gltfRuntime.scene.getBoneByID(id);
  976. if (existingBone) {
  977. newSkeleton.bones.push(existingBone);
  978. continue;
  979. }
  980. // Search for parent bone
  981. var foundBone = false;
  982. var parentBone = null;
  983. for (var j = 0; j < i; j++) {
  984. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  985. if (!jointNode_1) {
  986. continue;
  987. }
  988. var joint = jointNode_1.node;
  989. if (!joint) {
  990. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  991. continue;
  992. }
  993. var children = joint.children;
  994. if (!children) {
  995. continue;
  996. }
  997. foundBone = false;
  998. for (var k = 0; k < children.length; k++) {
  999. if (children[k] === id) {
  1000. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1001. foundBone = true;
  1002. break;
  1003. }
  1004. }
  1005. if (foundBone) {
  1006. break;
  1007. }
  1008. }
  1009. // Create bone
  1010. var mat = configureBoneTransformation(node);
  1011. if (!parentBone && nodesToRoot.length > 0) {
  1012. parentBone = getNodeToRoot(nodesToRoot, id);
  1013. if (parentBone) {
  1014. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1015. nodesToRootToAdd.push(parentBone);
  1016. }
  1017. }
  1018. }
  1019. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1020. bone.id = id;
  1021. }
  1022. // Polish
  1023. var bones = newSkeleton.bones;
  1024. newSkeleton.bones = [];
  1025. for (var i = 0; i < skins.jointNames.length; i++) {
  1026. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1027. if (!jointNode) {
  1028. continue;
  1029. }
  1030. for (var j = 0; j < bones.length; j++) {
  1031. if (bones[j].id === jointNode.id) {
  1032. newSkeleton.bones.push(bones[j]);
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. newSkeleton.prepare();
  1038. // Finish
  1039. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1040. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1041. }
  1042. return newSkeleton;
  1043. };
  1044. /**
  1045. * Imports a mesh and its geometries
  1046. */
  1047. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1048. if (!newMesh) {
  1049. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1050. newMesh.id = id;
  1051. }
  1052. if (!node.babylonNode) {
  1053. return newMesh;
  1054. }
  1055. var subMaterials = [];
  1056. var vertexData = null;
  1057. var verticesStarts = new Array();
  1058. var verticesCounts = new Array();
  1059. var indexStarts = new Array();
  1060. var indexCounts = new Array();
  1061. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1062. var meshID = meshes[meshIndex];
  1063. var mesh = gltfRuntime.meshes[meshID];
  1064. if (!mesh) {
  1065. continue;
  1066. }
  1067. // Positions, normals and UVs
  1068. for (var i = 0; i < mesh.primitives.length; i++) {
  1069. // Temporary vertex data
  1070. var tempVertexData = new BABYLON.VertexData();
  1071. var primitive = mesh.primitives[i];
  1072. if (primitive.mode !== 4) {
  1073. // continue;
  1074. }
  1075. var attributes = primitive.attributes;
  1076. var accessor = null;
  1077. var buffer = null;
  1078. // Set positions, normal and uvs
  1079. for (var semantic in attributes) {
  1080. // Link accessor and buffer view
  1081. accessor = gltfRuntime.accessors[attributes[semantic]];
  1082. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1083. if (semantic === "NORMAL") {
  1084. tempVertexData.normals = new Float32Array(buffer.length);
  1085. tempVertexData.normals.set(buffer);
  1086. }
  1087. else if (semantic === "POSITION") {
  1088. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1089. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1090. for (var j = 0; j < buffer.length; j += 4) {
  1091. tempVertexData.positions[j] = buffer[j];
  1092. tempVertexData.positions[j + 1] = buffer[j + 1];
  1093. tempVertexData.positions[j + 2] = buffer[j + 2];
  1094. }
  1095. }
  1096. else {
  1097. tempVertexData.positions = new Float32Array(buffer.length);
  1098. tempVertexData.positions.set(buffer);
  1099. }
  1100. verticesCounts.push(tempVertexData.positions.length);
  1101. }
  1102. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1103. var channel = Number(semantic.split("_")[1]);
  1104. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1105. var uvs = new Float32Array(buffer.length);
  1106. uvs.set(buffer);
  1107. normalizeUVs(uvs);
  1108. tempVertexData.set(uvs, uvKind);
  1109. }
  1110. else if (semantic === "JOINT") {
  1111. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1112. tempVertexData.matricesIndices.set(buffer);
  1113. }
  1114. else if (semantic === "WEIGHT") {
  1115. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1116. tempVertexData.matricesWeights.set(buffer);
  1117. }
  1118. else if (semantic === "COLOR") {
  1119. tempVertexData.colors = new Float32Array(buffer.length);
  1120. tempVertexData.colors.set(buffer);
  1121. }
  1122. }
  1123. // Indices
  1124. accessor = gltfRuntime.accessors[primitive.indices];
  1125. if (accessor) {
  1126. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1127. tempVertexData.indices = new Int32Array(buffer.length);
  1128. tempVertexData.indices.set(buffer);
  1129. indexCounts.push(tempVertexData.indices.length);
  1130. }
  1131. else {
  1132. // Set indices on the fly
  1133. var indices = [];
  1134. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1135. indices.push(j);
  1136. }
  1137. tempVertexData.indices = new Int32Array(indices);
  1138. indexCounts.push(tempVertexData.indices.length);
  1139. }
  1140. if (!vertexData) {
  1141. vertexData = tempVertexData;
  1142. }
  1143. else {
  1144. vertexData.merge(tempVertexData);
  1145. }
  1146. // Sub material
  1147. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1148. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1149. // Update vertices start and index start
  1150. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1151. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1152. }
  1153. }
  1154. var material;
  1155. if (subMaterials.length > 1) {
  1156. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1157. material.subMaterials = subMaterials;
  1158. }
  1159. else {
  1160. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1161. }
  1162. if (subMaterials.length === 1) {
  1163. material = subMaterials[0];
  1164. }
  1165. if (!newMesh.material) {
  1166. newMesh.material = material;
  1167. }
  1168. // Apply geometry
  1169. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1170. newMesh.computeWorldMatrix(true);
  1171. // Apply submeshes
  1172. newMesh.subMeshes = [];
  1173. var index = 0;
  1174. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1175. var meshID = meshes[meshIndex];
  1176. var mesh = gltfRuntime.meshes[meshID];
  1177. if (!mesh) {
  1178. continue;
  1179. }
  1180. for (var i = 0; i < mesh.primitives.length; i++) {
  1181. if (mesh.primitives[i].mode !== 4) {
  1182. //continue;
  1183. }
  1184. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1185. index++;
  1186. }
  1187. }
  1188. // Finish
  1189. return newMesh;
  1190. };
  1191. /**
  1192. * Configure node transformation from position, rotation and scaling
  1193. */
  1194. var configureNode = function (newNode, position, rotation, scaling) {
  1195. if (newNode.position) {
  1196. newNode.position = position;
  1197. }
  1198. if (newNode.rotationQuaternion || newNode.rotation) {
  1199. newNode.rotationQuaternion = rotation;
  1200. }
  1201. if (newNode.scaling) {
  1202. newNode.scaling = scaling;
  1203. }
  1204. };
  1205. /**
  1206. * Configures node from transformation matrix
  1207. */
  1208. var configureNodeFromMatrix = function (newNode, node, parent) {
  1209. if (node.matrix) {
  1210. var position = new BABYLON.Vector3(0, 0, 0);
  1211. var rotation = new BABYLON.Quaternion();
  1212. var scaling = new BABYLON.Vector3(0, 0, 0);
  1213. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1214. mat.decompose(scaling, rotation, position);
  1215. configureNode(newNode, position, rotation, scaling);
  1216. }
  1217. else if (node.translation && node.rotation && node.scale) {
  1218. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1219. }
  1220. newNode.computeWorldMatrix(true);
  1221. };
  1222. /**
  1223. * Imports a node
  1224. */
  1225. var importNode = function (gltfRuntime, node, id, parent) {
  1226. var lastNode = null;
  1227. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1228. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1229. return null;
  1230. }
  1231. }
  1232. // Meshes
  1233. if (node.skin) {
  1234. if (node.meshes) {
  1235. var skin = gltfRuntime.skins[node.skin];
  1236. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1237. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1238. if (newMesh.skeleton === null) {
  1239. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1240. if (!skin.babylonSkeleton) {
  1241. skin.babylonSkeleton = newMesh.skeleton;
  1242. }
  1243. }
  1244. lastNode = newMesh;
  1245. }
  1246. }
  1247. else if (node.meshes) {
  1248. /**
  1249. * Improve meshes property
  1250. */
  1251. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1252. lastNode = newMesh;
  1253. }
  1254. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1255. var light = gltfRuntime.lights[node.light];
  1256. if (light) {
  1257. if (light.type === "ambient") {
  1258. var ambienLight = light[light.type];
  1259. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1260. hemiLight.name = node.name || "";
  1261. if (ambienLight.color) {
  1262. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1263. }
  1264. lastNode = hemiLight;
  1265. }
  1266. else if (light.type === "directional") {
  1267. var directionalLight = light[light.type];
  1268. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1269. dirLight.name = node.name || "";
  1270. if (directionalLight.color) {
  1271. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1272. }
  1273. lastNode = dirLight;
  1274. }
  1275. else if (light.type === "point") {
  1276. var pointLight = light[light.type];
  1277. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1278. ptLight.name = node.name || "";
  1279. if (pointLight.color) {
  1280. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1281. }
  1282. lastNode = ptLight;
  1283. }
  1284. else if (light.type === "spot") {
  1285. var spotLight = light[light.type];
  1286. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1287. spLight.name = node.name || "";
  1288. if (spotLight.color) {
  1289. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1290. }
  1291. if (spotLight.fallOfAngle) {
  1292. spLight.angle = spotLight.fallOfAngle;
  1293. }
  1294. if (spotLight.fallOffExponent) {
  1295. spLight.exponent = spotLight.fallOffExponent;
  1296. }
  1297. lastNode = spLight;
  1298. }
  1299. }
  1300. }
  1301. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1302. var camera = gltfRuntime.cameras[node.camera];
  1303. if (camera) {
  1304. if (camera.type === "orthographic") {
  1305. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1306. orthoCamera.name = node.name || "";
  1307. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1308. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1309. lastNode = orthoCamera;
  1310. }
  1311. else if (camera.type === "perspective") {
  1312. var perspectiveCamera = camera[camera.type];
  1313. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1314. persCamera.name = node.name || "";
  1315. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1316. if (!perspectiveCamera.aspectRatio) {
  1317. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1318. }
  1319. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1320. persCamera.maxZ = perspectiveCamera.zfar;
  1321. persCamera.minZ = perspectiveCamera.znear;
  1322. }
  1323. lastNode = persCamera;
  1324. }
  1325. }
  1326. }
  1327. // Empty node
  1328. if (!node.jointName) {
  1329. if (node.babylonNode) {
  1330. return node.babylonNode;
  1331. }
  1332. else if (lastNode === null) {
  1333. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1334. node.babylonNode = dummy;
  1335. lastNode = dummy;
  1336. }
  1337. }
  1338. if (lastNode !== null) {
  1339. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1340. configureNodeFromMatrix(lastNode, node, parent);
  1341. }
  1342. else {
  1343. var translation = node.translation || [0, 0, 0];
  1344. var rotation = node.rotation || [0, 0, 0, 1];
  1345. var scale = node.scale || [1, 1, 1];
  1346. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1347. }
  1348. lastNode.updateCache(true);
  1349. node.babylonNode = lastNode;
  1350. }
  1351. return lastNode;
  1352. };
  1353. /**
  1354. * Traverses nodes and creates them
  1355. */
  1356. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1357. if (meshIncluded === void 0) { meshIncluded = false; }
  1358. var node = gltfRuntime.nodes[id];
  1359. var newNode = null;
  1360. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1361. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1362. meshIncluded = true;
  1363. }
  1364. else {
  1365. meshIncluded = false;
  1366. }
  1367. }
  1368. else {
  1369. meshIncluded = true;
  1370. }
  1371. if (!node.jointName && meshIncluded) {
  1372. newNode = importNode(gltfRuntime, node, id, parent);
  1373. if (newNode !== null) {
  1374. newNode.id = id;
  1375. newNode.parent = parent;
  1376. }
  1377. }
  1378. if (node.children) {
  1379. for (var i = 0; i < node.children.length; i++) {
  1380. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1381. }
  1382. }
  1383. };
  1384. /**
  1385. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1386. */
  1387. var postLoad = function (gltfRuntime) {
  1388. // Nodes
  1389. var currentScene = gltfRuntime.currentScene;
  1390. if (currentScene) {
  1391. for (var i = 0; i < currentScene.nodes.length; i++) {
  1392. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1393. }
  1394. }
  1395. else {
  1396. for (var thing in gltfRuntime.scenes) {
  1397. currentScene = gltfRuntime.scenes[thing];
  1398. for (var i = 0; i < currentScene.nodes.length; i++) {
  1399. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1400. }
  1401. }
  1402. }
  1403. // Set animations
  1404. loadAnimations(gltfRuntime);
  1405. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1406. var skeleton = gltfRuntime.scene.skeletons[i];
  1407. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1408. }
  1409. };
  1410. /**
  1411. * onBind shaderrs callback to set uniforms and matrices
  1412. */
  1413. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1414. var materialValues = material.values || technique.parameters;
  1415. for (var unif in unTreatedUniforms) {
  1416. var uniform = unTreatedUniforms[unif];
  1417. var type = uniform.type;
  1418. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1419. if (uniform.semantic && !uniform.source && !uniform.node) {
  1420. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1421. }
  1422. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1423. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1424. if (source === null) {
  1425. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1426. }
  1427. if (source === null) {
  1428. continue;
  1429. }
  1430. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1431. }
  1432. }
  1433. else {
  1434. var value = materialValues[technique.uniforms[unif]];
  1435. if (!value) {
  1436. continue;
  1437. }
  1438. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1439. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1440. if (texture === null || texture === undefined) {
  1441. continue;
  1442. }
  1443. shaderMaterial.getEffect().setTexture(unif, texture);
  1444. }
  1445. else {
  1446. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1447. }
  1448. }
  1449. }
  1450. onSuccess(shaderMaterial);
  1451. };
  1452. /**
  1453. * Prepare uniforms to send the only one time
  1454. * Loads the appropriate textures
  1455. */
  1456. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1457. var materialValues = material.values || technique.parameters;
  1458. var techniqueUniforms = technique.uniforms;
  1459. /**
  1460. * Prepare values here (not matrices)
  1461. */
  1462. for (var unif in unTreatedUniforms) {
  1463. var uniform = unTreatedUniforms[unif];
  1464. var type = uniform.type;
  1465. var value = materialValues[techniqueUniforms[unif]];
  1466. if (value === undefined) {
  1467. // In case the value is the same for all materials
  1468. value = uniform.value;
  1469. }
  1470. if (!value) {
  1471. continue;
  1472. }
  1473. var onLoadTexture = function (uniformName) {
  1474. return function (texture) {
  1475. if (uniform.value && uniformName) {
  1476. // Static uniform
  1477. shaderMaterial.setTexture(uniformName, texture);
  1478. delete unTreatedUniforms[uniformName];
  1479. }
  1480. };
  1481. };
  1482. // Texture (sampler2D)
  1483. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1484. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1485. }
  1486. else {
  1487. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1488. // Static uniform
  1489. delete unTreatedUniforms[unif];
  1490. }
  1491. }
  1492. }
  1493. };
  1494. /**
  1495. * Shader compilation failed
  1496. */
  1497. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1498. return function (effect, error) {
  1499. shaderMaterial.dispose(true);
  1500. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1501. };
  1502. };
  1503. /**
  1504. * Shader compilation success
  1505. */
  1506. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1507. return function (_) {
  1508. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1509. shaderMaterial.onBind = function (mesh) {
  1510. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1511. };
  1512. };
  1513. };
  1514. /**
  1515. * Returns the appropriate uniform if already handled by babylon
  1516. */
  1517. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1518. for (var unif in technique.uniforms) {
  1519. var uniform = technique.uniforms[unif];
  1520. var uniformParameter = technique.parameters[uniform];
  1521. if (tokenizer.currentIdentifier === unif) {
  1522. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1523. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1524. if (transformIndex !== -1) {
  1525. delete unTreatedUniforms[unif];
  1526. return babylonTransforms[transformIndex];
  1527. }
  1528. }
  1529. }
  1530. }
  1531. return tokenizer.currentIdentifier;
  1532. };
  1533. /**
  1534. * All shaders loaded. Create materials one by one
  1535. */
  1536. var importMaterials = function (gltfRuntime) {
  1537. // Create materials
  1538. for (var mat in gltfRuntime.materials) {
  1539. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1540. }
  1541. };
  1542. /**
  1543. * Implementation of the base glTF spec
  1544. */
  1545. var GLTFLoaderBase = /** @class */ (function () {
  1546. function GLTFLoaderBase() {
  1547. }
  1548. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1549. var gltfRuntime = {
  1550. extensions: {},
  1551. accessors: {},
  1552. buffers: {},
  1553. bufferViews: {},
  1554. meshes: {},
  1555. lights: {},
  1556. cameras: {},
  1557. nodes: {},
  1558. images: {},
  1559. textures: {},
  1560. shaders: {},
  1561. programs: {},
  1562. samplers: {},
  1563. techniques: {},
  1564. materials: {},
  1565. animations: {},
  1566. skins: {},
  1567. extensionsUsed: [],
  1568. scenes: {},
  1569. buffersCount: 0,
  1570. shaderscount: 0,
  1571. scene: scene,
  1572. rootUrl: rootUrl,
  1573. loadedBufferCount: 0,
  1574. loadedBufferViews: {},
  1575. loadedShaderCount: 0,
  1576. importOnlyMeshes: false,
  1577. dummyNodes: []
  1578. };
  1579. // Parse
  1580. if (parsedData.extensions) {
  1581. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1582. }
  1583. if (parsedData.extensionsUsed) {
  1584. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1585. }
  1586. if (parsedData.buffers) {
  1587. parseBuffers(parsedData.buffers, gltfRuntime);
  1588. }
  1589. if (parsedData.bufferViews) {
  1590. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1591. }
  1592. if (parsedData.accessors) {
  1593. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1594. }
  1595. if (parsedData.meshes) {
  1596. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1597. }
  1598. if (parsedData.lights) {
  1599. parseObject(parsedData.lights, "lights", gltfRuntime);
  1600. }
  1601. if (parsedData.cameras) {
  1602. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1603. }
  1604. if (parsedData.nodes) {
  1605. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1606. }
  1607. if (parsedData.images) {
  1608. parseObject(parsedData.images, "images", gltfRuntime);
  1609. }
  1610. if (parsedData.textures) {
  1611. parseObject(parsedData.textures, "textures", gltfRuntime);
  1612. }
  1613. if (parsedData.shaders) {
  1614. parseShaders(parsedData.shaders, gltfRuntime);
  1615. }
  1616. if (parsedData.programs) {
  1617. parseObject(parsedData.programs, "programs", gltfRuntime);
  1618. }
  1619. if (parsedData.samplers) {
  1620. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1621. }
  1622. if (parsedData.techniques) {
  1623. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1624. }
  1625. if (parsedData.materials) {
  1626. parseObject(parsedData.materials, "materials", gltfRuntime);
  1627. }
  1628. if (parsedData.animations) {
  1629. parseObject(parsedData.animations, "animations", gltfRuntime);
  1630. }
  1631. if (parsedData.skins) {
  1632. parseObject(parsedData.skins, "skins", gltfRuntime);
  1633. }
  1634. if (parsedData.scenes) {
  1635. gltfRuntime.scenes = parsedData.scenes;
  1636. }
  1637. if (parsedData.scene && parsedData.scenes) {
  1638. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1639. }
  1640. return gltfRuntime;
  1641. };
  1642. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1643. var buffer = gltfRuntime.buffers[id];
  1644. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1645. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1646. }
  1647. else {
  1648. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1649. if (request) {
  1650. onError(request.status + " " + request.statusText);
  1651. }
  1652. });
  1653. }
  1654. };
  1655. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1656. var texture = gltfRuntime.textures[id];
  1657. if (!texture || !texture.source) {
  1658. onError("");
  1659. return;
  1660. }
  1661. if (texture.babylonTexture) {
  1662. onSuccess(null);
  1663. return;
  1664. }
  1665. var source = gltfRuntime.images[texture.source];
  1666. if (BABYLON.Tools.IsBase64(source.uri)) {
  1667. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1668. }
  1669. else {
  1670. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1671. if (request) {
  1672. onError(request.status + " " + request.statusText);
  1673. }
  1674. });
  1675. }
  1676. };
  1677. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1678. var texture = gltfRuntime.textures[id];
  1679. if (texture.babylonTexture) {
  1680. onSuccess(texture.babylonTexture);
  1681. return;
  1682. }
  1683. var sampler = gltfRuntime.samplers[texture.sampler];
  1684. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1685. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1686. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1687. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1688. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1689. var blob = new Blob([buffer]);
  1690. var blobURL = URL.createObjectURL(blob);
  1691. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1692. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1693. if (sampler.wrapS !== undefined) {
  1694. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1695. }
  1696. if (sampler.wrapT !== undefined) {
  1697. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1698. }
  1699. newTexture.name = id;
  1700. texture.babylonTexture = newTexture;
  1701. onSuccess(newTexture);
  1702. };
  1703. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1704. var shader = gltfRuntime.shaders[id];
  1705. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1706. var shaderString = atob(shader.uri.split(",")[1]);
  1707. if (onSuccess) {
  1708. onSuccess(shaderString);
  1709. }
  1710. }
  1711. else {
  1712. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1713. if (request && onError) {
  1714. onError(request.status + " " + request.statusText);
  1715. }
  1716. });
  1717. }
  1718. };
  1719. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1720. var material = gltfRuntime.materials[id];
  1721. if (!material.technique) {
  1722. if (onError) {
  1723. onError("No technique found.");
  1724. }
  1725. return;
  1726. }
  1727. var technique = gltfRuntime.techniques[material.technique];
  1728. if (!technique) {
  1729. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1730. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1731. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1732. onSuccess(defaultMaterial);
  1733. return;
  1734. }
  1735. var program = gltfRuntime.programs[technique.program];
  1736. var states = technique.states;
  1737. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1738. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1739. var newVertexShader = "";
  1740. var newPixelShader = "";
  1741. var vertexTokenizer = new Tokenizer(vertexShader);
  1742. var pixelTokenizer = new Tokenizer(pixelShader);
  1743. var unTreatedUniforms = {};
  1744. var uniforms = [];
  1745. var attributes = [];
  1746. var samplers = [];
  1747. // Fill uniform, sampler2D and attributes
  1748. for (var unif in technique.uniforms) {
  1749. var uniform = technique.uniforms[unif];
  1750. var uniformParameter = technique.parameters[uniform];
  1751. unTreatedUniforms[unif] = uniformParameter;
  1752. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1753. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1754. if (transformIndex !== -1) {
  1755. uniforms.push(babylonTransforms[transformIndex]);
  1756. delete unTreatedUniforms[unif];
  1757. }
  1758. else {
  1759. uniforms.push(unif);
  1760. }
  1761. }
  1762. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1763. samplers.push(unif);
  1764. }
  1765. else {
  1766. uniforms.push(unif);
  1767. }
  1768. }
  1769. for (var attr in technique.attributes) {
  1770. var attribute = technique.attributes[attr];
  1771. var attributeParameter = technique.parameters[attribute];
  1772. if (attributeParameter.semantic) {
  1773. attributes.push(getAttribute(attributeParameter));
  1774. }
  1775. }
  1776. // Configure vertex shader
  1777. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1778. var tokenType = vertexTokenizer.currentToken;
  1779. if (tokenType !== ETokenType.IDENTIFIER) {
  1780. newVertexShader += vertexTokenizer.currentString;
  1781. continue;
  1782. }
  1783. var foundAttribute = false;
  1784. for (var attr in technique.attributes) {
  1785. var attribute = technique.attributes[attr];
  1786. var attributeParameter = technique.parameters[attribute];
  1787. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1788. newVertexShader += getAttribute(attributeParameter);
  1789. foundAttribute = true;
  1790. break;
  1791. }
  1792. }
  1793. if (foundAttribute) {
  1794. continue;
  1795. }
  1796. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1797. }
  1798. // Configure pixel shader
  1799. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1800. var tokenType = pixelTokenizer.currentToken;
  1801. if (tokenType !== ETokenType.IDENTIFIER) {
  1802. newPixelShader += pixelTokenizer.currentString;
  1803. continue;
  1804. }
  1805. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1806. }
  1807. // Create shader material
  1808. var shaderPath = {
  1809. vertex: program.vertexShader + id,
  1810. fragment: program.fragmentShader + id
  1811. };
  1812. var options = {
  1813. attributes: attributes,
  1814. uniforms: uniforms,
  1815. samplers: samplers,
  1816. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1817. };
  1818. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1819. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1820. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1821. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1822. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1823. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1824. if (states && states.functions) {
  1825. var functions = states.functions;
  1826. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1827. shaderMaterial.backFaceCulling = false;
  1828. }
  1829. var blendFunc = functions.blendFuncSeparate;
  1830. if (blendFunc) {
  1831. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1832. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1833. }
  1834. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1835. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1836. }
  1837. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1838. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1839. }
  1840. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1841. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1842. }
  1843. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1844. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1845. }
  1846. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1847. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1848. }
  1849. }
  1850. }
  1851. };
  1852. return GLTFLoaderBase;
  1853. }());
  1854. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1855. /**
  1856. * glTF V1 Loader
  1857. */
  1858. var GLTFLoader = /** @class */ (function () {
  1859. function GLTFLoader() {
  1860. // #region Stubs for IGLTFLoader interface
  1861. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1862. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1863. this.compileMaterials = false;
  1864. this.useClipPlane = false;
  1865. this.compileShadowGenerators = false;
  1866. this.onDisposeObservable = new BABYLON.Observable();
  1867. this.onMeshLoadedObservable = new BABYLON.Observable();
  1868. this.onTextureLoadedObservable = new BABYLON.Observable();
  1869. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1870. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  1871. this.onCompleteObservable = new BABYLON.Observable();
  1872. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1873. this.state = null;
  1874. }
  1875. GLTFLoader.RegisterExtension = function (extension) {
  1876. if (GLTFLoader.Extensions[extension.name]) {
  1877. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1878. return;
  1879. }
  1880. GLTFLoader.Extensions[extension.name] = extension;
  1881. };
  1882. GLTFLoader.prototype.dispose = function () { };
  1883. // #endregion
  1884. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1885. var _this = this;
  1886. scene.useRightHandedSystem = true;
  1887. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1888. gltfRuntime.importOnlyMeshes = true;
  1889. if (meshesNames === "") {
  1890. gltfRuntime.importMeshesNames = [];
  1891. }
  1892. else if (typeof meshesNames === "string") {
  1893. gltfRuntime.importMeshesNames = [meshesNames];
  1894. }
  1895. else if (meshesNames && !(meshesNames instanceof Array)) {
  1896. gltfRuntime.importMeshesNames = [meshesNames];
  1897. }
  1898. else {
  1899. gltfRuntime.importMeshesNames = [];
  1900. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1901. }
  1902. // Create nodes
  1903. _this._createNodes(gltfRuntime);
  1904. var meshes = new Array();
  1905. var skeletons = new Array();
  1906. // Fill arrays of meshes and skeletons
  1907. for (var nde in gltfRuntime.nodes) {
  1908. var node = gltfRuntime.nodes[nde];
  1909. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1910. meshes.push(node.babylonNode);
  1911. }
  1912. }
  1913. for (var skl in gltfRuntime.skins) {
  1914. var skin = gltfRuntime.skins[skl];
  1915. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1916. skeletons.push(skin.babylonSkeleton);
  1917. }
  1918. }
  1919. // Load buffers, shaders, materials, etc.
  1920. _this._loadBuffersAsync(gltfRuntime, function () {
  1921. _this._loadShadersAsync(gltfRuntime, function () {
  1922. importMaterials(gltfRuntime);
  1923. postLoad(gltfRuntime);
  1924. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1925. onSuccess(meshes, [], skeletons);
  1926. }
  1927. });
  1928. }, onProgress);
  1929. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1930. onSuccess(meshes, [], skeletons);
  1931. }
  1932. }, onError);
  1933. return true;
  1934. };
  1935. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1936. var _this = this;
  1937. return new Promise(function (resolve, reject) {
  1938. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  1939. resolve({
  1940. meshes: meshes,
  1941. particleSystems: particleSystems,
  1942. skeletons: skeletons
  1943. });
  1944. }, onProgress, function (message) {
  1945. reject(new Error(message));
  1946. });
  1947. });
  1948. };
  1949. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1950. var _this = this;
  1951. scene.useRightHandedSystem = true;
  1952. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1953. // Load runtime extensios
  1954. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1955. // Create nodes
  1956. _this._createNodes(gltfRuntime);
  1957. // Load buffers, shaders, materials, etc.
  1958. _this._loadBuffersAsync(gltfRuntime, function () {
  1959. _this._loadShadersAsync(gltfRuntime, function () {
  1960. importMaterials(gltfRuntime);
  1961. postLoad(gltfRuntime);
  1962. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1963. onSuccess();
  1964. }
  1965. });
  1966. });
  1967. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1968. onSuccess();
  1969. }
  1970. }, onError);
  1971. }, onError);
  1972. };
  1973. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1974. var _this = this;
  1975. return new Promise(function (resolve, reject) {
  1976. _this._loadAsync(scene, data, rootUrl, function () {
  1977. resolve();
  1978. }, onProgress, function (message) {
  1979. reject(new Error(message));
  1980. });
  1981. });
  1982. };
  1983. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1984. var hasShaders = false;
  1985. var processShader = function (sha, shader) {
  1986. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1987. if (shaderString instanceof ArrayBuffer) {
  1988. return;
  1989. }
  1990. gltfRuntime.loadedShaderCount++;
  1991. if (shaderString) {
  1992. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1993. }
  1994. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1995. onload();
  1996. }
  1997. }, function () {
  1998. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1999. });
  2000. };
  2001. for (var sha in gltfRuntime.shaders) {
  2002. hasShaders = true;
  2003. var shader = gltfRuntime.shaders[sha];
  2004. if (shader) {
  2005. processShader.bind(this, sha, shader)();
  2006. }
  2007. else {
  2008. BABYLON.Tools.Error("No shader named: " + sha);
  2009. }
  2010. }
  2011. if (!hasShaders) {
  2012. onload();
  2013. }
  2014. };
  2015. ;
  2016. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2017. var hasBuffers = false;
  2018. var processBuffer = function (buf, buffer) {
  2019. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2020. gltfRuntime.loadedBufferCount++;
  2021. if (bufferView) {
  2022. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2023. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2024. }
  2025. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2026. }
  2027. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2028. onLoad();
  2029. }
  2030. }, function () {
  2031. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2032. });
  2033. };
  2034. for (var buf in gltfRuntime.buffers) {
  2035. hasBuffers = true;
  2036. var buffer = gltfRuntime.buffers[buf];
  2037. if (buffer) {
  2038. processBuffer.bind(this, buf, buffer)();
  2039. }
  2040. else {
  2041. BABYLON.Tools.Error("No buffer named: " + buf);
  2042. }
  2043. }
  2044. if (!hasBuffers) {
  2045. onLoad();
  2046. }
  2047. };
  2048. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2049. var currentScene = gltfRuntime.currentScene;
  2050. if (currentScene) {
  2051. // Only one scene even if multiple scenes are defined
  2052. for (var i = 0; i < currentScene.nodes.length; i++) {
  2053. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2054. }
  2055. }
  2056. else {
  2057. // Load all scenes
  2058. for (var thing in gltfRuntime.scenes) {
  2059. currentScene = gltfRuntime.scenes[thing];
  2060. for (var i = 0; i < currentScene.nodes.length; i++) {
  2061. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2062. }
  2063. }
  2064. }
  2065. };
  2066. GLTFLoader.Extensions = {};
  2067. return GLTFLoader;
  2068. }());
  2069. GLTF1.GLTFLoader = GLTFLoader;
  2070. ;
  2071. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2072. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2073. })(BABYLON || (BABYLON = {}));
  2074. //# sourceMappingURL=babylon.glTFLoader.js.map
  2075. "use strict";
  2076. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2077. var BABYLON;
  2078. (function (BABYLON) {
  2079. var GLTF1;
  2080. (function (GLTF1) {
  2081. /**
  2082. * Utils functions for GLTF
  2083. */
  2084. var GLTFUtils = /** @class */ (function () {
  2085. function GLTFUtils() {
  2086. }
  2087. /**
  2088. * Sets the given "parameter" matrix
  2089. * @param scene: the {BABYLON.Scene} object
  2090. * @param source: the source node where to pick the matrix
  2091. * @param parameter: the GLTF technique parameter
  2092. * @param uniformName: the name of the shader's uniform
  2093. * @param shaderMaterial: the shader material
  2094. */
  2095. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2096. var mat = null;
  2097. if (parameter.semantic === "MODEL") {
  2098. mat = source.getWorldMatrix();
  2099. }
  2100. else if (parameter.semantic === "PROJECTION") {
  2101. mat = scene.getProjectionMatrix();
  2102. }
  2103. else if (parameter.semantic === "VIEW") {
  2104. mat = scene.getViewMatrix();
  2105. }
  2106. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2107. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2108. }
  2109. else if (parameter.semantic === "MODELVIEW") {
  2110. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2111. }
  2112. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2113. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2114. }
  2115. else if (parameter.semantic === "MODELINVERSE") {
  2116. mat = source.getWorldMatrix().invert();
  2117. }
  2118. else if (parameter.semantic === "VIEWINVERSE") {
  2119. mat = scene.getViewMatrix().invert();
  2120. }
  2121. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2122. mat = scene.getProjectionMatrix().invert();
  2123. }
  2124. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2125. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2126. }
  2127. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2128. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2129. }
  2130. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2131. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2132. }
  2133. else {
  2134. debugger;
  2135. }
  2136. if (mat) {
  2137. switch (parameter.type) {
  2138. case GLTF1.EParameterType.FLOAT_MAT2:
  2139. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2140. break;
  2141. case GLTF1.EParameterType.FLOAT_MAT3:
  2142. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2143. break;
  2144. case GLTF1.EParameterType.FLOAT_MAT4:
  2145. shaderMaterial.setMatrix(uniformName, mat);
  2146. break;
  2147. default: break;
  2148. }
  2149. }
  2150. };
  2151. /**
  2152. * Sets the given "parameter" matrix
  2153. * @param shaderMaterial: the shader material
  2154. * @param uniform: the name of the shader's uniform
  2155. * @param value: the value of the uniform
  2156. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2157. */
  2158. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2159. switch (type) {
  2160. case GLTF1.EParameterType.FLOAT:
  2161. shaderMaterial.setFloat(uniform, value);
  2162. return true;
  2163. case GLTF1.EParameterType.FLOAT_VEC2:
  2164. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2165. return true;
  2166. case GLTF1.EParameterType.FLOAT_VEC3:
  2167. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2168. return true;
  2169. case GLTF1.EParameterType.FLOAT_VEC4:
  2170. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2171. return true;
  2172. default: return false;
  2173. }
  2174. };
  2175. /**
  2176. * Returns the wrap mode of the texture
  2177. * @param mode: the mode value
  2178. */
  2179. GLTFUtils.GetWrapMode = function (mode) {
  2180. switch (mode) {
  2181. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2182. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2183. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2184. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2185. }
  2186. };
  2187. /**
  2188. * Returns the byte stride giving an accessor
  2189. * @param accessor: the GLTF accessor objet
  2190. */
  2191. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2192. // Needs this function since "byteStride" isn't requiered in glTF format
  2193. var type = accessor.type;
  2194. switch (type) {
  2195. case "VEC2": return 2;
  2196. case "VEC3": return 3;
  2197. case "VEC4": return 4;
  2198. case "MAT2": return 4;
  2199. case "MAT3": return 9;
  2200. case "MAT4": return 16;
  2201. default: return 1;
  2202. }
  2203. };
  2204. /**
  2205. * Returns the texture filter mode giving a mode value
  2206. * @param mode: the filter mode value
  2207. */
  2208. GLTFUtils.GetTextureFilterMode = function (mode) {
  2209. switch (mode) {
  2210. case GLTF1.ETextureFilterType.LINEAR:
  2211. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2212. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2213. case GLTF1.ETextureFilterType.NEAREST:
  2214. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2215. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2216. }
  2217. };
  2218. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2219. var byteOffset = bufferView.byteOffset + byteOffset;
  2220. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2221. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2222. throw new Error("Buffer access is out of range");
  2223. }
  2224. var buffer = loadedBufferView.buffer;
  2225. byteOffset += loadedBufferView.byteOffset;
  2226. switch (componentType) {
  2227. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2228. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2229. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2230. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2231. default: return new Float32Array(buffer, byteOffset, byteLength);
  2232. }
  2233. };
  2234. /**
  2235. * Returns a buffer from its accessor
  2236. * @param gltfRuntime: the GLTF runtime
  2237. * @param accessor: the GLTF accessor
  2238. */
  2239. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2240. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2241. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2242. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2243. };
  2244. /**
  2245. * Decodes a buffer view into a string
  2246. * @param view: the buffer view
  2247. */
  2248. GLTFUtils.DecodeBufferToText = function (view) {
  2249. var result = "";
  2250. var length = view.byteLength;
  2251. for (var i = 0; i < length; ++i) {
  2252. result += String.fromCharCode(view[i]);
  2253. }
  2254. return result;
  2255. };
  2256. /**
  2257. * Returns the default material of gltf. Related to
  2258. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2259. * @param scene: the Babylon.js scene
  2260. */
  2261. GLTFUtils.GetDefaultMaterial = function (scene) {
  2262. if (!GLTFUtils._DefaultMaterial) {
  2263. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2264. "precision highp float;",
  2265. "",
  2266. "uniform mat4 worldView;",
  2267. "uniform mat4 projection;",
  2268. "",
  2269. "attribute vec3 position;",
  2270. "",
  2271. "void main(void)",
  2272. "{",
  2273. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2274. "}"
  2275. ].join("\n");
  2276. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2277. "precision highp float;",
  2278. "",
  2279. "uniform vec4 u_emission;",
  2280. "",
  2281. "void main(void)",
  2282. "{",
  2283. " gl_FragColor = u_emission;",
  2284. "}"
  2285. ].join("\n");
  2286. var shaderPath = {
  2287. vertex: "GLTFDefaultMaterial",
  2288. fragment: "GLTFDefaultMaterial"
  2289. };
  2290. var options = {
  2291. attributes: ["position"],
  2292. uniforms: ["worldView", "projection", "u_emission"],
  2293. samplers: new Array(),
  2294. needAlphaBlending: false
  2295. };
  2296. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2297. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2298. }
  2299. return GLTFUtils._DefaultMaterial;
  2300. };
  2301. // The GLTF default material
  2302. GLTFUtils._DefaultMaterial = null;
  2303. return GLTFUtils;
  2304. }());
  2305. GLTF1.GLTFUtils = GLTFUtils;
  2306. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2307. })(BABYLON || (BABYLON = {}));
  2308. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2309. "use strict";
  2310. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2311. var BABYLON;
  2312. (function (BABYLON) {
  2313. var GLTF1;
  2314. (function (GLTF1) {
  2315. var GLTFLoaderExtension = /** @class */ (function () {
  2316. function GLTFLoaderExtension(name) {
  2317. this._name = name;
  2318. }
  2319. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2320. get: function () {
  2321. return this._name;
  2322. },
  2323. enumerable: true,
  2324. configurable: true
  2325. });
  2326. /**
  2327. * Defines an override for loading the runtime
  2328. * Return true to stop further extensions from loading the runtime
  2329. */
  2330. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2331. return false;
  2332. };
  2333. /**
  2334. * Defines an onverride for creating gltf runtime
  2335. * Return true to stop further extensions from creating the runtime
  2336. */
  2337. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2338. return false;
  2339. };
  2340. /**
  2341. * Defines an override for loading buffers
  2342. * Return true to stop further extensions from loading this buffer
  2343. */
  2344. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2345. return false;
  2346. };
  2347. /**
  2348. * Defines an override for loading texture buffers
  2349. * Return true to stop further extensions from loading this texture data
  2350. */
  2351. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2352. return false;
  2353. };
  2354. /**
  2355. * Defines an override for creating textures
  2356. * Return true to stop further extensions from loading this texture
  2357. */
  2358. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2359. return false;
  2360. };
  2361. /**
  2362. * Defines an override for loading shader strings
  2363. * Return true to stop further extensions from loading this shader data
  2364. */
  2365. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2366. return false;
  2367. };
  2368. /**
  2369. * Defines an override for loading materials
  2370. * Return true to stop further extensions from loading this material
  2371. */
  2372. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2373. return false;
  2374. };
  2375. // ---------
  2376. // Utilities
  2377. // ---------
  2378. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2379. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2380. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2381. }, function () {
  2382. setTimeout(function () {
  2383. if (!onSuccess) {
  2384. return;
  2385. }
  2386. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2387. });
  2388. });
  2389. };
  2390. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2391. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2392. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2393. }, function () {
  2394. setTimeout(function () {
  2395. onSuccess();
  2396. });
  2397. });
  2398. };
  2399. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2400. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2401. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2402. }, function () {
  2403. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2404. });
  2405. };
  2406. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2407. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2408. if (buffer) {
  2409. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2410. }
  2411. }, onError);
  2412. };
  2413. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2414. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2415. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2416. }, function () {
  2417. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2418. });
  2419. };
  2420. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2421. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2422. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2423. }, function () {
  2424. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2425. });
  2426. };
  2427. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2428. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2429. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2430. }, function () {
  2431. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2432. });
  2433. };
  2434. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2435. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2436. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2437. }, function () {
  2438. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2439. });
  2440. };
  2441. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2442. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2443. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2444. if (func(loaderExtension)) {
  2445. return;
  2446. }
  2447. }
  2448. defaultFunc();
  2449. };
  2450. return GLTFLoaderExtension;
  2451. }());
  2452. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2453. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2454. })(BABYLON || (BABYLON = {}));
  2455. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2456. "use strict";
  2457. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2458. var __extends = (this && this.__extends) || (function () {
  2459. var extendStatics = Object.setPrototypeOf ||
  2460. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2461. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2462. return function (d, b) {
  2463. extendStatics(d, b);
  2464. function __() { this.constructor = d; }
  2465. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2466. };
  2467. })();
  2468. var BABYLON;
  2469. (function (BABYLON) {
  2470. var GLTF1;
  2471. (function (GLTF1) {
  2472. var BinaryExtensionBufferName = "binary_glTF";
  2473. ;
  2474. ;
  2475. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2476. __extends(GLTFBinaryExtension, _super);
  2477. function GLTFBinaryExtension() {
  2478. return _super.call(this, "KHR_binary_glTF") || this;
  2479. }
  2480. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2481. var extensionsUsed = data.json.extensionsUsed;
  2482. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2483. return false;
  2484. }
  2485. this._bin = data.bin;
  2486. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2487. return true;
  2488. };
  2489. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2490. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2491. return false;
  2492. }
  2493. if (id !== BinaryExtensionBufferName) {
  2494. return false;
  2495. }
  2496. onSuccess(this._bin);
  2497. return true;
  2498. };
  2499. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2500. var texture = gltfRuntime.textures[id];
  2501. var source = gltfRuntime.images[texture.source];
  2502. if (!source.extensions || !(this.name in source.extensions)) {
  2503. return false;
  2504. }
  2505. var sourceExt = source.extensions[this.name];
  2506. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2507. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2508. onSuccess(buffer);
  2509. return true;
  2510. };
  2511. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2512. var shader = gltfRuntime.shaders[id];
  2513. if (!shader.extensions || !(this.name in shader.extensions)) {
  2514. return false;
  2515. }
  2516. var binaryExtensionShader = shader.extensions[this.name];
  2517. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2518. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2519. setTimeout(function () {
  2520. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2521. onSuccess(shaderString);
  2522. });
  2523. return true;
  2524. };
  2525. return GLTFBinaryExtension;
  2526. }(GLTF1.GLTFLoaderExtension));
  2527. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2528. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2529. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2530. })(BABYLON || (BABYLON = {}));
  2531. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2532. "use strict";
  2533. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2534. var __extends = (this && this.__extends) || (function () {
  2535. var extendStatics = Object.setPrototypeOf ||
  2536. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2537. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2538. return function (d, b) {
  2539. extendStatics(d, b);
  2540. function __() { this.constructor = d; }
  2541. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2542. };
  2543. })();
  2544. var BABYLON;
  2545. (function (BABYLON) {
  2546. var GLTF1;
  2547. (function (GLTF1) {
  2548. ;
  2549. ;
  2550. ;
  2551. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2552. __extends(GLTFMaterialsCommonExtension, _super);
  2553. function GLTFMaterialsCommonExtension() {
  2554. return _super.call(this, "KHR_materials_common") || this;
  2555. }
  2556. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2557. if (!gltfRuntime.extensions)
  2558. return false;
  2559. var extension = gltfRuntime.extensions[this.name];
  2560. if (!extension)
  2561. return false;
  2562. // Create lights
  2563. var lights = extension.lights;
  2564. if (lights) {
  2565. for (var thing in lights) {
  2566. var light = lights[thing];
  2567. switch (light.type) {
  2568. case "ambient":
  2569. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2570. var ambient = light.ambient;
  2571. if (ambient) {
  2572. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2573. }
  2574. break;
  2575. case "point":
  2576. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2577. var point = light.point;
  2578. if (point) {
  2579. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2580. }
  2581. break;
  2582. case "directional":
  2583. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2584. var directional = light.directional;
  2585. if (directional) {
  2586. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2587. }
  2588. break;
  2589. case "spot":
  2590. var spot = light.spot;
  2591. if (spot) {
  2592. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2593. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2594. }
  2595. break;
  2596. default:
  2597. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2598. break;
  2599. }
  2600. }
  2601. }
  2602. return false;
  2603. };
  2604. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2605. var material = gltfRuntime.materials[id];
  2606. if (!material || !material.extensions)
  2607. return false;
  2608. var extension = material.extensions[this.name];
  2609. if (!extension)
  2610. return false;
  2611. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2612. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2613. if (extension.technique === "CONSTANT") {
  2614. standardMaterial.disableLighting = true;
  2615. }
  2616. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2617. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2618. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2619. // Ambient
  2620. if (typeof extension.values.ambient === "string") {
  2621. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2622. }
  2623. else {
  2624. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2625. }
  2626. // Diffuse
  2627. if (typeof extension.values.diffuse === "string") {
  2628. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2629. }
  2630. else {
  2631. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2632. }
  2633. // Emission
  2634. if (typeof extension.values.emission === "string") {
  2635. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2636. }
  2637. else {
  2638. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2639. }
  2640. // Specular
  2641. if (typeof extension.values.specular === "string") {
  2642. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2643. }
  2644. else {
  2645. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2646. }
  2647. return true;
  2648. };
  2649. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2650. // Create buffer from texture url
  2651. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2652. // Create texture from buffer
  2653. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2654. }, onError);
  2655. };
  2656. return GLTFMaterialsCommonExtension;
  2657. }(GLTF1.GLTFLoaderExtension));
  2658. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2659. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2660. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2661. })(BABYLON || (BABYLON = {}));
  2662. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map