babylon.glTF1FileLoader.js 126 KB

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