babylon.glTF1FileLoader.js 115 KB

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