babylon.glTF1FileLoader.js 116 KB

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