babylon.glTF2FileLoader.js 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFFileLoader = (function () {
  5. function GLTFFileLoader() {
  6. this.extensions = {
  7. ".gltf": { isBinary: false },
  8. ".glb": { isBinary: true }
  9. };
  10. }
  11. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  12. var loaderData = GLTFFileLoader._parse(data);
  13. var loader = this._getLoader(loaderData);
  14. if (!loader) {
  15. onError();
  16. return;
  17. }
  18. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onError);
  19. };
  20. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  21. var loaderData = GLTFFileLoader._parse(data);
  22. var loader = this._getLoader(loaderData);
  23. if (!loader) {
  24. onError();
  25. return;
  26. }
  27. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onError);
  28. };
  29. GLTFFileLoader._parse = function (data) {
  30. if (data instanceof ArrayBuffer) {
  31. return GLTFFileLoader._parseBinary(data);
  32. }
  33. return {
  34. json: JSON.parse(data),
  35. bin: null
  36. };
  37. };
  38. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  39. var loaderVersion = { major: 2, minor: 0 };
  40. var asset = loaderData.json.asset || {};
  41. var version = GLTFFileLoader._parseVersion(asset.version);
  42. if (!version) {
  43. BABYLON.Tools.Error("Invalid version");
  44. return null;
  45. }
  46. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  47. if (minVersion) {
  48. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  49. BABYLON.Tools.Error("Incompatible version");
  50. return null;
  51. }
  52. }
  53. var loaders = {
  54. 1: GLTFFileLoader.GLTFLoaderV1,
  55. 2: GLTFFileLoader.GLTFLoaderV2
  56. };
  57. var loader = loaders[version.major];
  58. if (loader === undefined) {
  59. BABYLON.Tools.Error("Unsupported version");
  60. return null;
  61. }
  62. if (loader === null) {
  63. BABYLON.Tools.Error("v" + version.major + " loader is not available");
  64. return null;
  65. }
  66. return loader;
  67. };
  68. GLTFFileLoader._parseBinary = function (data) {
  69. var Binary = {
  70. Magic: 0x46546C67
  71. };
  72. var binaryReader = new BinaryReader(data);
  73. var magic = binaryReader.readUint32();
  74. if (magic !== Binary.Magic) {
  75. BABYLON.Tools.Error("Unexpected magic: " + magic);
  76. return null;
  77. }
  78. var version = binaryReader.readUint32();
  79. switch (version) {
  80. case 1: return GLTFFileLoader._parseV1(binaryReader);
  81. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82. }
  83. BABYLON.Tools.Error("Unsupported version: " + version);
  84. return null;
  85. };
  86. GLTFFileLoader._parseV1 = function (binaryReader) {
  87. var ContentFormat = {
  88. JSON: 0
  89. };
  90. var length = binaryReader.readUint32();
  91. if (length != binaryReader.getLength()) {
  92. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  93. return null;
  94. }
  95. var contentLength = binaryReader.readUint32();
  96. var contentFormat = binaryReader.readUint32();
  97. var content;
  98. switch (contentFormat) {
  99. case ContentFormat.JSON:
  100. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101. break;
  102. default:
  103. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  104. return null;
  105. }
  106. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107. var body = binaryReader.readUint8Array(bytesRemaining);
  108. return {
  109. json: content,
  110. bin: body
  111. };
  112. };
  113. GLTFFileLoader._parseV2 = function (binaryReader) {
  114. var ChunkFormat = {
  115. JSON: 0x4E4F534A,
  116. BIN: 0x004E4942
  117. };
  118. var length = binaryReader.readUint32();
  119. if (length !== binaryReader.getLength()) {
  120. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  121. return null;
  122. }
  123. // JSON chunk
  124. var chunkLength = binaryReader.readUint32();
  125. var chunkFormat = binaryReader.readUint32();
  126. if (chunkFormat !== ChunkFormat.JSON) {
  127. BABYLON.Tools.Error("First chunk format is not JSON");
  128. return null;
  129. }
  130. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  131. // Look for BIN chunk
  132. var bin = null;
  133. while (binaryReader.getPosition() < binaryReader.getLength()) {
  134. chunkLength = binaryReader.readUint32();
  135. chunkFormat = binaryReader.readUint32();
  136. switch (chunkFormat) {
  137. case ChunkFormat.JSON:
  138. BABYLON.Tools.Error("Unexpected JSON chunk");
  139. return null;
  140. case ChunkFormat.BIN:
  141. bin = binaryReader.readUint8Array(chunkLength);
  142. break;
  143. default:
  144. // ignore unrecognized chunkFormat
  145. binaryReader.skipBytes(chunkLength);
  146. break;
  147. }
  148. }
  149. return {
  150. json: json,
  151. bin: bin
  152. };
  153. };
  154. GLTFFileLoader._parseVersion = function (version) {
  155. if (!version) {
  156. return null;
  157. }
  158. var parts = version.split(".");
  159. if (parts.length === 0) {
  160. return null;
  161. }
  162. var major = parseInt(parts[0]);
  163. if (major > 1 && parts.length != 2) {
  164. return null;
  165. }
  166. var minor = parseInt(parts[1]);
  167. return {
  168. major: major,
  169. minor: parseInt(parts[0])
  170. };
  171. };
  172. GLTFFileLoader._compareVersion = function (a, b) {
  173. if (a.major > b.major)
  174. return 1;
  175. if (a.major < b.major)
  176. return -1;
  177. if (a.minor > b.minor)
  178. return 1;
  179. if (a.minor < b.minor)
  180. return -1;
  181. return 0;
  182. };
  183. GLTFFileLoader._decodeBufferToText = function (view) {
  184. var result = "";
  185. var length = view.byteLength;
  186. for (var i = 0; i < length; ++i) {
  187. result += String.fromCharCode(view[i]);
  188. }
  189. return result;
  190. };
  191. return GLTFFileLoader;
  192. }());
  193. GLTFFileLoader.GLTFLoaderV1 = null;
  194. GLTFFileLoader.GLTFLoaderV2 = null;
  195. GLTFFileLoader.HomogeneousCoordinates = false;
  196. GLTFFileLoader.IncrementalLoading = true;
  197. BABYLON.GLTFFileLoader = GLTFFileLoader;
  198. var BinaryReader = (function () {
  199. function BinaryReader(arrayBuffer) {
  200. this._arrayBuffer = arrayBuffer;
  201. this._dataView = new DataView(arrayBuffer);
  202. this._byteOffset = 0;
  203. }
  204. BinaryReader.prototype.getPosition = function () {
  205. return this._byteOffset;
  206. };
  207. BinaryReader.prototype.getLength = function () {
  208. return this._arrayBuffer.byteLength;
  209. };
  210. BinaryReader.prototype.readUint32 = function () {
  211. var value = this._dataView.getUint32(this._byteOffset, true);
  212. this._byteOffset += 4;
  213. return value;
  214. };
  215. BinaryReader.prototype.readUint8Array = function (length) {
  216. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  217. this._byteOffset += length;
  218. return value;
  219. };
  220. BinaryReader.prototype.skipBytes = function (length) {
  221. this._byteOffset += length;
  222. };
  223. return BinaryReader;
  224. }());
  225. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  226. })(BABYLON || (BABYLON = {}));
  227. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  228. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  229. var BABYLON;
  230. (function (BABYLON) {
  231. var GLTF2;
  232. (function (GLTF2) {
  233. /**
  234. * Enums
  235. */
  236. var EBufferViewTarget;
  237. (function (EBufferViewTarget) {
  238. EBufferViewTarget[EBufferViewTarget["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
  239. EBufferViewTarget[EBufferViewTarget["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
  240. })(EBufferViewTarget = GLTF2.EBufferViewTarget || (GLTF2.EBufferViewTarget = {}));
  241. var EComponentType;
  242. (function (EComponentType) {
  243. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  244. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  245. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  246. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  247. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  248. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  249. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  250. var EMeshPrimitiveMode;
  251. (function (EMeshPrimitiveMode) {
  252. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  253. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  254. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  255. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  256. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  257. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  258. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  259. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  260. var EParameterType;
  261. (function (EParameterType) {
  262. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  263. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  264. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  265. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  266. EParameterType[EParameterType["INT"] = 5124] = "INT";
  267. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  268. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  269. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  270. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  271. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  272. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  273. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  274. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  275. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  276. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  277. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  278. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  279. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  280. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  281. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  282. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  283. })(EParameterType = GLTF2.EParameterType || (GLTF2.EParameterType = {}));
  284. var ETextureMagFilter;
  285. (function (ETextureMagFilter) {
  286. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  287. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  288. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  289. var ETextureMinFilter;
  290. (function (ETextureMinFilter) {
  291. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  292. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  293. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  294. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  295. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  296. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  297. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  298. var ETextureFormat;
  299. (function (ETextureFormat) {
  300. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  301. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  302. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  303. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  304. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  305. })(ETextureFormat = GLTF2.ETextureFormat || (GLTF2.ETextureFormat = {}));
  306. var ETextureTarget;
  307. (function (ETextureTarget) {
  308. ETextureTarget[ETextureTarget["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
  309. })(ETextureTarget = GLTF2.ETextureTarget || (GLTF2.ETextureTarget = {}));
  310. var ETextureType;
  311. (function (ETextureType) {
  312. ETextureType[ETextureType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  313. ETextureType[ETextureType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  314. ETextureType[ETextureType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  315. ETextureType[ETextureType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  316. })(ETextureType = GLTF2.ETextureType || (GLTF2.ETextureType = {}));
  317. var ETextureWrapMode;
  318. (function (ETextureWrapMode) {
  319. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  320. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  321. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  322. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  323. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  324. })(BABYLON || (BABYLON = {}));
  325. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  326. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  327. var BABYLON;
  328. (function (BABYLON) {
  329. var GLTF2;
  330. (function (GLTF2) {
  331. /**
  332. * Values
  333. */
  334. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  335. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  336. /**
  337. * Utils
  338. */
  339. var normalizeUVs = function (buffer) {
  340. if (!buffer) {
  341. return;
  342. }
  343. for (var i = 0; i < buffer.length / 2; i++) {
  344. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  345. }
  346. };
  347. var createStringId = function (index) {
  348. return "node" + index;
  349. };
  350. /**
  351. * Returns the animation path (glTF -> Babylon)
  352. */
  353. var getAnimationPath = function (path) {
  354. var index = glTFAnimationPaths.indexOf(path);
  355. if (index !== -1) {
  356. return babylonAnimationPaths[index];
  357. }
  358. return path;
  359. };
  360. /**
  361. * Loads and creates animations
  362. */
  363. var loadAnimations = function (runtime) {
  364. var animations = runtime.gltf.animations;
  365. if (!animations) {
  366. return;
  367. }
  368. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  369. var animation = animations[animationIndex];
  370. if (!animation || !animation.channels || !animation.samplers) {
  371. continue;
  372. }
  373. var lastAnimation = null;
  374. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  375. var channel = animation.channels[channelIndex];
  376. if (!channel) {
  377. continue;
  378. }
  379. var sampler = animation.samplers[channel.sampler];
  380. if (!sampler) {
  381. continue;
  382. }
  383. var inputData = sampler.input;
  384. var outputData = sampler.output;
  385. var bufferInput = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[inputData]);
  386. var bufferOutput = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[outputData]);
  387. var targetID = channel.target.node;
  388. var targetNode = runtime.babylonScene.getNodeByID(createStringId(targetID));
  389. if (targetNode === null) {
  390. BABYLON.Tools.Warn("Creating animation index " + animationIndex + " but cannot find node index " + targetID + " to attach to");
  391. continue;
  392. }
  393. var isBone = targetNode instanceof BABYLON.Bone;
  394. // Get target path (position, rotation or scaling)
  395. var targetPath = channel.target.path;
  396. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  397. if (targetPathIndex !== -1) {
  398. targetPath = babylonAnimationPaths[targetPathIndex];
  399. }
  400. // Determine animation type
  401. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  402. if (!isBone) {
  403. if (targetPath === "rotationQuaternion") {
  404. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  405. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  406. }
  407. else {
  408. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  409. }
  410. }
  411. // Create animation and key frames
  412. var babylonAnimation = null;
  413. var keys = [];
  414. var arrayOffset = 0;
  415. var modifyKey = false;
  416. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  417. babylonAnimation = lastAnimation;
  418. modifyKey = true;
  419. }
  420. if (!modifyKey) {
  421. var animationName = animation.name || "anim" + animationIndex;
  422. babylonAnimation = new BABYLON.Animation(animationName, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  423. }
  424. // For each frame
  425. for (var j = 0; j < bufferInput.length; j++) {
  426. var value = null;
  427. if (targetPath === "rotationQuaternion") {
  428. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  429. arrayOffset += 4;
  430. }
  431. else {
  432. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  433. arrayOffset += 3;
  434. }
  435. if (isBone) {
  436. var bone = targetNode;
  437. var translation = BABYLON.Vector3.Zero();
  438. var rotationQuaternion = new BABYLON.Quaternion();
  439. var scaling = BABYLON.Vector3.Zero();
  440. // Warning on decompose
  441. var mat = bone.getBaseMatrix();
  442. if (modifyKey) {
  443. mat = lastAnimation.getKeys()[j].value;
  444. }
  445. mat.decompose(scaling, rotationQuaternion, translation);
  446. if (targetPath === "position") {
  447. translation = value;
  448. }
  449. else if (targetPath === "rotationQuaternion") {
  450. rotationQuaternion = value;
  451. }
  452. else {
  453. scaling = value;
  454. }
  455. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  456. }
  457. if (!modifyKey) {
  458. keys.push({
  459. frame: bufferInput[j],
  460. value: value
  461. });
  462. }
  463. else {
  464. lastAnimation.getKeys()[j].value = value;
  465. }
  466. }
  467. // Finish
  468. if (!modifyKey) {
  469. babylonAnimation.setKeys(keys);
  470. targetNode.animations.push(babylonAnimation);
  471. }
  472. lastAnimation = babylonAnimation;
  473. runtime.babylonScene.stopAnimation(targetNode);
  474. runtime.babylonScene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  475. }
  476. }
  477. };
  478. /**
  479. * Returns the bones transformation matrix
  480. */
  481. var configureBoneTransformation = function (node) {
  482. var mat = null;
  483. if (node.translation || node.rotation || node.scale) {
  484. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  485. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  486. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  487. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  488. }
  489. else {
  490. mat = node.matrix ? BABYLON.Matrix.FromArray(node.matrix) : BABYLON.Matrix.Identity();
  491. }
  492. return mat;
  493. };
  494. /**
  495. * Returns the parent bone
  496. */
  497. var getParentBone = function (runtime, skin, index, newSkeleton) {
  498. // Try to find
  499. var nodeStringID = createStringId(index);
  500. for (var i = 0; i < newSkeleton.bones.length; i++) {
  501. if (newSkeleton.bones[i].id === nodeStringID) {
  502. return newSkeleton.bones[i].getParent();
  503. }
  504. }
  505. // Not found, search in gltf nodes
  506. var joints = skin.joints;
  507. for (var j = 0; j < joints.length; j++) {
  508. var parentID = joints[j];
  509. var parent = runtime.gltf.nodes[parentID];
  510. var children = parent.children;
  511. for (var i = 0; i < children.length; i++) {
  512. var childID = children[i];
  513. var child = runtime.gltf.nodes[childID];
  514. if (!nodeIsInJoints(skin, childID)) {
  515. continue;
  516. }
  517. if (childID === index) {
  518. var mat = configureBoneTransformation(parent);
  519. var bone = new BABYLON.Bone(parent.name || createStringId(parentID), newSkeleton, getParentBone(runtime, skin, parentID, newSkeleton), mat);
  520. bone.id = createStringId(parentID);
  521. return bone;
  522. }
  523. }
  524. }
  525. return null;
  526. };
  527. /**
  528. * Returns the appropriate root node
  529. */
  530. var getNodeToRoot = function (nodesToRoot, index) {
  531. for (var i = 0; i < nodesToRoot.length; i++) {
  532. var nodeToRoot = nodesToRoot[i];
  533. if (nodeToRoot.node.children) {
  534. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  535. var child = nodeToRoot.node.children[j];
  536. if (child === index) {
  537. return nodeToRoot.bone;
  538. }
  539. }
  540. }
  541. }
  542. return null;
  543. };
  544. /**
  545. * Returns the node with the node index
  546. */
  547. var getJointNode = function (runtime, index) {
  548. var node = runtime.gltf.nodes[index];
  549. if (node) {
  550. return {
  551. node: node,
  552. index: index
  553. };
  554. }
  555. return null;
  556. };
  557. /**
  558. * Checks if a nodes is in joints
  559. */
  560. var nodeIsInJoints = function (skin, index) {
  561. for (var i = 0; i < skin.joints.length; i++) {
  562. if (skin.joints[i] === index) {
  563. return true;
  564. }
  565. }
  566. return false;
  567. };
  568. /**
  569. * Fills the nodes to root for bones and builds hierarchy
  570. */
  571. var getNodesToRoot = function (runtime, newSkeleton, skin, nodesToRoot) {
  572. // Creates nodes for root
  573. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  574. var node = runtime.gltf.nodes[i];
  575. if (nodeIsInJoints(skin, i)) {
  576. continue;
  577. }
  578. // Create node to root bone
  579. var mat = configureBoneTransformation(node);
  580. var bone = new BABYLON.Bone(node.name || createStringId(i), newSkeleton, null, mat);
  581. bone.id = createStringId(i);
  582. nodesToRoot.push({ bone: bone, node: node, index: i });
  583. }
  584. // Parenting
  585. for (var i = 0; i < nodesToRoot.length; i++) {
  586. var nodeToRoot = nodesToRoot[i];
  587. var children = nodeToRoot.node.children;
  588. if (children) {
  589. for (var j = 0; j < children.length; j++) {
  590. var child = null;
  591. for (var k = 0; k < nodesToRoot.length; k++) {
  592. if (nodesToRoot[k].index === children[j]) {
  593. child = nodesToRoot[k];
  594. break;
  595. }
  596. }
  597. if (child) {
  598. child.bone._parent = nodeToRoot.bone;
  599. nodeToRoot.bone.children.push(child.bone);
  600. }
  601. }
  602. }
  603. }
  604. };
  605. /**
  606. * Imports a skeleton
  607. */
  608. var importSkeleton = function (runtime, skinNode, skin) {
  609. var name = skin.name || "skin" + skinNode.skin;
  610. var babylonSkeleton = skin.babylonSkeleton;
  611. if (!babylonSkeleton) {
  612. babylonSkeleton = new BABYLON.Skeleton(name, "skin" + skinNode.skin, runtime.babylonScene);
  613. }
  614. if (!skin.babylonSkeleton) {
  615. return babylonSkeleton;
  616. }
  617. // Matrices
  618. var accessor = runtime.gltf.accessors[skin.inverseBindMatrices];
  619. var buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  620. // Find the root bones
  621. var nodesToRoot = [];
  622. var nodesToRootToAdd = [];
  623. getNodesToRoot(runtime, babylonSkeleton, skin, nodesToRoot);
  624. babylonSkeleton.bones = [];
  625. // Joints
  626. for (var i = 0; i < skin.joints.length; i++) {
  627. var jointNode = getJointNode(runtime, skin.joints[i]);
  628. var node = jointNode.node;
  629. if (!node) {
  630. BABYLON.Tools.Warn("Joint index " + skin.joints[i] + " does not exist");
  631. continue;
  632. }
  633. var index = jointNode.index;
  634. var stringID = createStringId(index);
  635. // Optimize, if the bone already exists...
  636. var existingBone = runtime.babylonScene.getBoneByID(stringID);
  637. if (existingBone) {
  638. babylonSkeleton.bones.push(existingBone);
  639. continue;
  640. }
  641. // Search for parent bone
  642. var foundBone = false;
  643. var parentBone = null;
  644. for (var j = 0; j < i; j++) {
  645. var joint = getJointNode(runtime, skin.joints[j]).node;
  646. if (!joint) {
  647. BABYLON.Tools.Warn("Joint index " + skin.joints[j] + " does not exist when looking for parent");
  648. continue;
  649. }
  650. var children = joint.children;
  651. foundBone = false;
  652. for (var k = 0; k < children.length; k++) {
  653. if (children[k] === index) {
  654. parentBone = getParentBone(runtime, skin, skin.joints[j], babylonSkeleton);
  655. foundBone = true;
  656. break;
  657. }
  658. }
  659. if (foundBone) {
  660. break;
  661. }
  662. }
  663. // Create bone
  664. var mat = configureBoneTransformation(node);
  665. if (!parentBone && nodesToRoot.length > 0) {
  666. parentBone = getNodeToRoot(nodesToRoot, index);
  667. if (parentBone) {
  668. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  669. nodesToRootToAdd.push(parentBone);
  670. }
  671. }
  672. }
  673. var bone = new BABYLON.Bone(node.name || stringID, babylonSkeleton, parentBone, mat);
  674. bone.id = stringID;
  675. }
  676. // Polish
  677. var bones = babylonSkeleton.bones;
  678. babylonSkeleton.bones = [];
  679. for (var i = 0; i < skin.joints.length; i++) {
  680. var jointNode = getJointNode(runtime, skin.joints[i]);
  681. if (!jointNode) {
  682. continue;
  683. }
  684. var jointNodeStringId = createStringId(jointNode.index);
  685. for (var j = 0; j < bones.length; j++) {
  686. if (bones[j].id === jointNodeStringId) {
  687. babylonSkeleton.bones.push(bones[j]);
  688. break;
  689. }
  690. }
  691. }
  692. babylonSkeleton.prepare();
  693. // Finish
  694. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  695. babylonSkeleton.bones.push(nodesToRootToAdd[i]);
  696. }
  697. return babylonSkeleton;
  698. };
  699. /**
  700. * Gets a material
  701. */
  702. var getMaterial = function (runtime, index) {
  703. if (index === undefined) {
  704. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  705. }
  706. var materials = runtime.gltf.materials;
  707. if (!materials || index < 0 || index >= materials.length) {
  708. BABYLON.Tools.Error("Invalid material index");
  709. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  710. }
  711. var material = runtime.gltf.materials[index].babylonMaterial;
  712. if (!material) {
  713. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  714. }
  715. return material;
  716. };
  717. /**
  718. * Imports a mesh and its geometries
  719. */
  720. var importMesh = function (runtime, node, mesh) {
  721. var name = mesh.name || node.name || "mesh" + node.mesh;
  722. var babylonMesh = node.babylonNode;
  723. if (!babylonMesh) {
  724. babylonMesh = new BABYLON.Mesh(name, runtime.babylonScene);
  725. }
  726. if (!node.babylonNode) {
  727. return babylonMesh;
  728. }
  729. var multiMat = new BABYLON.MultiMaterial(name, runtime.babylonScene);
  730. if (!babylonMesh.material) {
  731. babylonMesh.material = multiMat;
  732. }
  733. var vertexData = new BABYLON.VertexData();
  734. var geometry = new BABYLON.Geometry(name, runtime.babylonScene, vertexData, false, babylonMesh);
  735. var verticesStarts = [];
  736. var verticesCounts = [];
  737. var indexStarts = [];
  738. var indexCounts = [];
  739. // Positions, normals and UVs
  740. for (var index = 0; index < mesh.primitives.length; index++) {
  741. // Temporary vertex data
  742. var tempVertexData = new BABYLON.VertexData();
  743. var primitive = mesh.primitives[index];
  744. if (primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  745. // continue;
  746. }
  747. var attributes = primitive.attributes;
  748. var accessor = null;
  749. var buffer = null;
  750. // Set positions, normal and uvs
  751. for (var semantic in attributes) {
  752. // Link accessor and buffer view
  753. accessor = runtime.gltf.accessors[attributes[semantic]];
  754. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  755. if (semantic === "NORMAL") {
  756. tempVertexData.normals = new Float32Array(buffer.length);
  757. tempVertexData.normals.set(buffer);
  758. }
  759. else if (semantic === "POSITION") {
  760. tempVertexData.positions = new Float32Array(buffer.length);
  761. tempVertexData.positions.set(buffer);
  762. verticesCounts.push(tempVertexData.positions.length);
  763. }
  764. else if (semantic === "TANGENT") {
  765. tempVertexData.tangents = new Float32Array(buffer.length);
  766. tempVertexData.tangents.set(buffer);
  767. }
  768. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  769. var channel = Number(semantic.split("_")[1]);
  770. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  771. var uvs = new Float32Array(buffer.length);
  772. uvs.set(buffer);
  773. normalizeUVs(uvs);
  774. tempVertexData.set(uvs, uvKind);
  775. }
  776. else if (semantic === "JOINT") {
  777. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  778. tempVertexData.matricesIndices.set(buffer);
  779. }
  780. else if (semantic === "WEIGHT") {
  781. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  782. tempVertexData.matricesWeights.set(buffer);
  783. }
  784. else if (semantic === "COLOR_0") {
  785. tempVertexData.colors = new Float32Array(buffer.length);
  786. tempVertexData.colors.set(buffer);
  787. }
  788. else {
  789. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  790. }
  791. }
  792. // Indices
  793. accessor = runtime.gltf.accessors[primitive.indices];
  794. if (accessor) {
  795. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  796. tempVertexData.indices = new Int32Array(buffer.length);
  797. tempVertexData.indices.set(buffer);
  798. indexCounts.push(tempVertexData.indices.length);
  799. }
  800. else {
  801. // Set indices on the fly
  802. var indices = [];
  803. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  804. indices.push(j);
  805. }
  806. tempVertexData.indices = new Int32Array(indices);
  807. indexCounts.push(tempVertexData.indices.length);
  808. }
  809. vertexData.merge(tempVertexData);
  810. tempVertexData = undefined;
  811. // Sub material
  812. var material = getMaterial(runtime, primitive.material);
  813. multiMat.subMaterials.push(material);
  814. // Update vertices start and index start
  815. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  816. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  817. }
  818. // Apply geometry
  819. geometry.setAllVerticesData(vertexData, false);
  820. babylonMesh.computeWorldMatrix(true);
  821. // Apply submeshes
  822. babylonMesh.subMeshes = [];
  823. for (var index = 0; index < mesh.primitives.length; index++) {
  824. if (mesh.primitives[index].mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  825. //continue;
  826. }
  827. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], babylonMesh, babylonMesh, true);
  828. }
  829. // Finish
  830. return babylonMesh;
  831. };
  832. /**
  833. * Configures node transformation
  834. */
  835. var configureNode = function (babylonNode, node) {
  836. var position = BABYLON.Vector3.Zero();
  837. var rotation = BABYLON.Quaternion.Identity();
  838. var scaling = new BABYLON.Vector3(1, 1, 1);
  839. if (node.matrix) {
  840. var mat = BABYLON.Matrix.FromArray(node.matrix);
  841. mat.decompose(scaling, rotation, position);
  842. }
  843. else {
  844. if (node.translation) {
  845. position = BABYLON.Vector3.FromArray(node.translation);
  846. }
  847. if (node.rotation) {
  848. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  849. }
  850. if (node.scale) {
  851. scaling = BABYLON.Vector3.FromArray(node.scale);
  852. }
  853. }
  854. babylonNode.position = position;
  855. babylonNode.rotationQuaternion = rotation;
  856. if (babylonNode instanceof BABYLON.Mesh) {
  857. var mesh = babylonNode;
  858. mesh.scaling = scaling;
  859. }
  860. };
  861. /**
  862. * Imports a node
  863. */
  864. var importNode = function (runtime, node) {
  865. var babylonNode = null;
  866. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  867. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  868. return null;
  869. }
  870. }
  871. // Meshes
  872. if (node.skin !== undefined) {
  873. if (node.mesh !== undefined) {
  874. var skin = runtime.gltf.skins[node.skin];
  875. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  876. var newSkeleton = importSkeleton(runtime, node, skin);
  877. if (newSkeleton) {
  878. newMesh.skeleton = newSkeleton;
  879. skin.babylonSkeleton = newSkeleton;
  880. }
  881. babylonNode = newMesh;
  882. }
  883. }
  884. else if (node.mesh !== undefined) {
  885. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  886. }
  887. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  888. var camera = runtime.gltf.cameras[node.camera];
  889. if (camera !== undefined) {
  890. if (camera.type === "orthographic") {
  891. var orthographicCamera = camera.orthographic;
  892. var orthoCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  893. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  894. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  895. babylonNode = orthoCamera;
  896. }
  897. else if (camera.type === "perspective") {
  898. var perspectiveCamera = camera.perspective;
  899. var persCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  900. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  901. if (!perspectiveCamera.aspectRatio) {
  902. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  903. }
  904. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  905. persCamera.maxZ = perspectiveCamera.zfar;
  906. persCamera.minZ = perspectiveCamera.znear;
  907. }
  908. babylonNode = persCamera;
  909. }
  910. }
  911. }
  912. // Empty node
  913. if (node.babylonNode) {
  914. return node.babylonNode;
  915. }
  916. else if (babylonNode === null) {
  917. var dummy = new BABYLON.Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  918. node.babylonNode = dummy;
  919. babylonNode = dummy;
  920. }
  921. if (babylonNode !== null) {
  922. configureNode(babylonNode, node);
  923. babylonNode.updateCache(true);
  924. node.babylonNode = babylonNode;
  925. }
  926. return babylonNode;
  927. };
  928. /**
  929. * Traverses nodes and creates them
  930. */
  931. var traverseNodes = function (runtime, index, parent, meshIncluded) {
  932. var node = runtime.gltf.nodes[index];
  933. var newNode = null;
  934. if (runtime.importOnlyMeshes && !meshIncluded) {
  935. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  936. meshIncluded = true;
  937. }
  938. else {
  939. meshIncluded = false;
  940. }
  941. }
  942. else {
  943. meshIncluded = true;
  944. }
  945. if (meshIncluded) {
  946. newNode = importNode(runtime, node);
  947. if (newNode !== null) {
  948. newNode.id = createStringId(index);
  949. newNode.parent = parent;
  950. }
  951. }
  952. if (node.children) {
  953. for (var i = 0; i < node.children.length; i++) {
  954. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  955. }
  956. }
  957. };
  958. var importScene = function (runtime) {
  959. var scene = runtime.gltf.scene || 0;
  960. var scenes = runtime.gltf.scenes;
  961. if (scenes) {
  962. var nodes = scenes[scene].nodes;
  963. for (var i = 0; i < nodes.length; i++) {
  964. traverseNodes(runtime, nodes[i], null);
  965. }
  966. }
  967. else {
  968. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  969. traverseNodes(runtime, i, null);
  970. }
  971. }
  972. };
  973. /**
  974. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  975. */
  976. var postLoad = function (runtime) {
  977. importScene(runtime);
  978. // Set animations
  979. loadAnimations(runtime);
  980. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  981. var skeleton = runtime.babylonScene.skeletons[i];
  982. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  983. }
  984. // Revoke object urls created during load
  985. if (runtime.gltf.textures) {
  986. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  987. var texture = runtime.gltf.textures[i];
  988. if (texture.blobURL) {
  989. URL.revokeObjectURL(texture.blobURL);
  990. }
  991. }
  992. }
  993. };
  994. var BinaryReader = (function () {
  995. function BinaryReader(arrayBuffer) {
  996. this._arrayBuffer = arrayBuffer;
  997. this._dataView = new DataView(arrayBuffer);
  998. this._byteOffset = 0;
  999. }
  1000. BinaryReader.prototype.getPosition = function () {
  1001. return this._byteOffset;
  1002. };
  1003. BinaryReader.prototype.getLength = function () {
  1004. return this._arrayBuffer.byteLength;
  1005. };
  1006. BinaryReader.prototype.readUint32 = function () {
  1007. var value = this._dataView.getUint32(this._byteOffset, true);
  1008. this._byteOffset += 4;
  1009. return value;
  1010. };
  1011. BinaryReader.prototype.readUint8Array = function (length) {
  1012. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1013. this._byteOffset += length;
  1014. return value;
  1015. };
  1016. BinaryReader.prototype.skipBytes = function (length) {
  1017. this._byteOffset += length;
  1018. };
  1019. return BinaryReader;
  1020. }());
  1021. /**
  1022. * glTF File Loader Plugin
  1023. */
  1024. var GLTFLoader = (function () {
  1025. function GLTFLoader() {
  1026. }
  1027. GLTFLoader.RegisterExtension = function (extension) {
  1028. if (GLTFLoader.Extensions[extension.name]) {
  1029. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1030. return;
  1031. }
  1032. GLTFLoader.Extensions[extension.name] = extension;
  1033. };
  1034. GLTFLoader.LoadMaterial = function (runtime, index) {
  1035. var material = runtime.gltf.materials[index];
  1036. if (!material)
  1037. return null;
  1038. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  1039. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1040. material.babylonMaterial.useScalarInLinearSpace = true;
  1041. return material;
  1042. };
  1043. GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  1044. // Ensure metallic workflow
  1045. material.babylonMaterial.metallic = 1;
  1046. material.babylonMaterial.roughness = 1;
  1047. var properties = material.pbrMetallicRoughness;
  1048. if (!properties) {
  1049. onSuccess();
  1050. return;
  1051. }
  1052. //
  1053. // Load Factors
  1054. //
  1055. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1056. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  1057. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  1058. //
  1059. // Load Textures
  1060. //
  1061. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  1062. onSuccess();
  1063. return;
  1064. }
  1065. var checkSuccess = function () {
  1066. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  1067. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture)) {
  1068. onSuccess();
  1069. }
  1070. };
  1071. if (properties.baseColorTexture) {
  1072. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture, function (texture) {
  1073. material.babylonMaterial.albedoTexture = texture;
  1074. GLTFLoader.LoadAlphaProperties(runtime, material);
  1075. checkSuccess();
  1076. }, function () {
  1077. BABYLON.Tools.Error("Failed to load base color texture");
  1078. onError();
  1079. });
  1080. }
  1081. if (properties.metallicRoughnessTexture) {
  1082. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture, function (texture) {
  1083. material.babylonMaterial.metallicTexture = texture;
  1084. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1085. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1086. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1087. checkSuccess();
  1088. }, function () {
  1089. BABYLON.Tools.Error("Failed to load metallic roughness texture");
  1090. onError();
  1091. });
  1092. }
  1093. };
  1094. GLTFLoader.LoadCommonMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  1095. //
  1096. // Load Factors
  1097. //
  1098. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  1099. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1100. if (material.doubleSided) {
  1101. material.babylonMaterial.backFaceCulling = false;
  1102. material.babylonMaterial.twoSidedLighting = true;
  1103. }
  1104. //
  1105. // Load Textures
  1106. //
  1107. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  1108. onSuccess();
  1109. return;
  1110. }
  1111. var checkSuccess = function () {
  1112. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  1113. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  1114. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  1115. onSuccess();
  1116. }
  1117. };
  1118. if (material.normalTexture) {
  1119. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, function (babylonTexture) {
  1120. material.babylonMaterial.bumpTexture = babylonTexture;
  1121. if (material.normalTexture.scale !== undefined) {
  1122. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1123. }
  1124. checkSuccess();
  1125. }, function () {
  1126. BABYLON.Tools.Error("Failed to load normal texture");
  1127. onError();
  1128. });
  1129. }
  1130. if (material.occlusionTexture) {
  1131. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, function (babylonTexture) {
  1132. material.babylonMaterial.ambientTexture = babylonTexture;
  1133. material.babylonMaterial.useAmbientInGrayScale = true;
  1134. if (material.occlusionTexture.strength !== undefined) {
  1135. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1136. }
  1137. checkSuccess();
  1138. }, function () {
  1139. BABYLON.Tools.Error("Failed to load occlusion texture");
  1140. onError();
  1141. });
  1142. }
  1143. if (material.emissiveTexture) {
  1144. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, function (babylonTexture) {
  1145. material.babylonMaterial.emissiveTexture = babylonTexture;
  1146. checkSuccess();
  1147. }, function () {
  1148. BABYLON.Tools.Error("Failed to load emissive texture");
  1149. onError();
  1150. });
  1151. }
  1152. };
  1153. GLTFLoader.LoadAlphaProperties = function (runtime, material) {
  1154. var alphaMode = material.alphaMode || "OPAQUE";
  1155. switch (alphaMode) {
  1156. case "OPAQUE":
  1157. // default is opaque
  1158. break;
  1159. case "MASK":
  1160. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1161. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1162. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  1163. break;
  1164. case "BLEND":
  1165. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1166. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1167. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1168. break;
  1169. default:
  1170. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  1171. }
  1172. };
  1173. GLTFLoader.LoadTextureAsync = function (runtime, textureInfo, onSuccess, onError) {
  1174. var texture = runtime.gltf.textures[textureInfo.index];
  1175. var texCoord = textureInfo.texCoord || 0;
  1176. if (!texture || texture.source === undefined) {
  1177. onError();
  1178. return;
  1179. }
  1180. if (texture.babylonTextures) {
  1181. var babylonTexture = texture.babylonTextures[texCoord];
  1182. if (!babylonTexture) {
  1183. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1184. babylonTexture = texture.babylonTextures[i];
  1185. if (babylonTexture) {
  1186. babylonTexture = babylonTexture.clone();
  1187. babylonTexture.coordinatesIndex = texCoord;
  1188. break;
  1189. }
  1190. }
  1191. }
  1192. onSuccess(babylonTexture);
  1193. return;
  1194. }
  1195. var source = runtime.gltf.images[texture.source];
  1196. var sourceURL = runtime.rootUrl + source.uri;
  1197. if (texture.blobURL) {
  1198. sourceURL = texture.blobURL;
  1199. }
  1200. else {
  1201. if (source.uri === undefined) {
  1202. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  1203. var buffer = GLTF2.GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE);
  1204. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  1205. sourceURL = texture.blobURL;
  1206. }
  1207. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1208. var decodedBuffer = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1209. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  1210. sourceURL = texture.blobURL;
  1211. }
  1212. }
  1213. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  1214. };
  1215. GLTFLoader._createTextureAsync = function (runtime, texture, texCoord, url, onSuccess, onError) {
  1216. var sampler = texture.sampler ? runtime.gltf.samplers[texture.sampler] : {};
  1217. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1218. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1219. var babylonTexture = new BABYLON.Texture(url, runtime.babylonScene, noMipMaps, true, samplingMode, function () {
  1220. onSuccess(babylonTexture);
  1221. }, onError);
  1222. babylonTexture.coordinatesIndex = texCoord;
  1223. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1224. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1225. babylonTexture.name = texture.name;
  1226. // Cache the texture
  1227. texture.babylonTextures = texture.babylonTextures || [];
  1228. texture.babylonTextures[texCoord] = babylonTexture;
  1229. };
  1230. /**
  1231. * Import meshes
  1232. */
  1233. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1234. scene.useRightHandedSystem = true;
  1235. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  1236. if (!runtime) {
  1237. onError();
  1238. return;
  1239. }
  1240. if (meshesNames === "") {
  1241. runtime.importMeshesNames = [];
  1242. }
  1243. else if (typeof meshesNames === "string") {
  1244. runtime.importMeshesNames = [meshesNames];
  1245. }
  1246. else if (meshesNames && !(meshesNames instanceof Array)) {
  1247. runtime.importMeshesNames = [meshesNames];
  1248. }
  1249. else {
  1250. runtime.importMeshesNames = [];
  1251. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1252. }
  1253. // Load scene
  1254. importScene(runtime);
  1255. var meshes = [];
  1256. var skeletons = [];
  1257. // Fill arrays of meshes and skeletons
  1258. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  1259. var node = runtime.gltf.nodes[i];
  1260. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1261. meshes.push(node.babylonNode);
  1262. }
  1263. }
  1264. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  1265. var skin = runtime.gltf.skins[i];
  1266. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1267. skeletons.push(skin.babylonSkeleton);
  1268. }
  1269. }
  1270. // Load buffers, materials, etc.
  1271. GLTFLoader._loadBuffersAsync(runtime, function () {
  1272. GLTFLoader._loadMaterialsAsync(runtime, function () {
  1273. postLoad(runtime);
  1274. onSuccess(meshes, null, skeletons);
  1275. }, onError);
  1276. }, onError);
  1277. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1278. onSuccess(meshes, null, skeletons);
  1279. }
  1280. };
  1281. /**
  1282. * Load scene
  1283. */
  1284. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1285. scene.useRightHandedSystem = true;
  1286. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  1287. if (!runtime) {
  1288. onError();
  1289. return;
  1290. }
  1291. importScene(runtime);
  1292. GLTFLoader._loadBuffersAsync(runtime, function () {
  1293. GLTFLoader._loadMaterialsAsync(runtime, function () {
  1294. postLoad(runtime);
  1295. onSuccess();
  1296. }, onError);
  1297. }, onError);
  1298. };
  1299. GLTFLoader._loadBuffersAsync = function (runtime, onSuccess, onError) {
  1300. var _this = this;
  1301. if (runtime.gltf.buffers.length == 0) {
  1302. onSuccess();
  1303. return;
  1304. }
  1305. var successCount = 0;
  1306. runtime.gltf.buffers.forEach(function (buffer, index) {
  1307. _this._loadBufferAsync(runtime, index, function () {
  1308. if (++successCount === runtime.gltf.buffers.length) {
  1309. onSuccess();
  1310. }
  1311. }, onError);
  1312. });
  1313. };
  1314. GLTFLoader._loadBufferAsync = function (runtime, index, onSuccess, onError) {
  1315. var buffer = runtime.gltf.buffers[index];
  1316. if (buffer.uri === undefined) {
  1317. // buffer.loadedBufferView should already be set
  1318. onSuccess();
  1319. }
  1320. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  1321. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1322. setTimeout(function () {
  1323. buffer.loadedBufferView = new Uint8Array(data);
  1324. onSuccess();
  1325. });
  1326. }
  1327. else {
  1328. BABYLON.Tools.LoadFile(runtime.rootUrl + buffer.uri, function (data) {
  1329. buffer.loadedBufferView = new Uint8Array(data);
  1330. onSuccess();
  1331. }, null, null, true, onError);
  1332. }
  1333. };
  1334. GLTFLoader._loadMaterialsAsync = function (runtime, onSuccess, onError) {
  1335. var materials = runtime.gltf.materials;
  1336. if (!materials) {
  1337. onSuccess();
  1338. return;
  1339. }
  1340. var successCount = 0;
  1341. for (var i = 0; i < materials.length; i++) {
  1342. GLTF2.GLTFLoaderExtension.LoadMaterialAsync(runtime, i, function () {
  1343. if (++successCount === materials.length) {
  1344. onSuccess();
  1345. }
  1346. }, onError);
  1347. }
  1348. };
  1349. GLTFLoader._createRuntime = function (scene, data, rootUrl, importOnlyMeshes) {
  1350. var runtime = {
  1351. gltf: data.json,
  1352. babylonScene: scene,
  1353. rootUrl: rootUrl,
  1354. importOnlyMeshes: importOnlyMeshes,
  1355. };
  1356. var binaryBuffer;
  1357. var buffers = runtime.gltf.buffers;
  1358. if (buffers.length > 0 && buffers[0].uri === undefined) {
  1359. binaryBuffer = buffers[0];
  1360. }
  1361. if (data.bin) {
  1362. if (!binaryBuffer) {
  1363. BABYLON.Tools.Error("Unexpected BIN chunk");
  1364. return null;
  1365. }
  1366. if (binaryBuffer.byteLength != data.bin.byteLength) {
  1367. BABYLON.Tools.Error("Binary buffer length from JSON does not match chunk length");
  1368. return null;
  1369. }
  1370. binaryBuffer.loadedBufferView = data.bin;
  1371. }
  1372. GLTF2.GLTFLoaderExtension.PostCreateRuntime(runtime);
  1373. return runtime;
  1374. };
  1375. return GLTFLoader;
  1376. }());
  1377. GLTFLoader.Extensions = {};
  1378. GLTF2.GLTFLoader = GLTFLoader;
  1379. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1380. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1381. })(BABYLON || (BABYLON = {}));
  1382. //# sourceMappingURL=babylon.glTFLoader.js.map
  1383. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1384. var BABYLON;
  1385. (function (BABYLON) {
  1386. var GLTF2;
  1387. (function (GLTF2) {
  1388. /**
  1389. * Utils functions for GLTF
  1390. */
  1391. var GLTFUtils = (function () {
  1392. function GLTFUtils() {
  1393. }
  1394. /**
  1395. * If the uri is a base64 string
  1396. * @param uri: the uri to test
  1397. */
  1398. GLTFUtils.IsBase64 = function (uri) {
  1399. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1400. };
  1401. /**
  1402. * Decode the base64 uri
  1403. * @param uri: the uri to decode
  1404. */
  1405. GLTFUtils.DecodeBase64 = function (uri) {
  1406. var decodedString = atob(uri.split(",")[1]);
  1407. var bufferLength = decodedString.length;
  1408. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1409. for (var i = 0; i < bufferLength; i++) {
  1410. bufferView[i] = decodedString.charCodeAt(i);
  1411. }
  1412. return bufferView.buffer;
  1413. };
  1414. /**
  1415. * Returns the wrap mode of the texture
  1416. * @param mode: the mode value
  1417. */
  1418. GLTFUtils.GetWrapMode = function (mode) {
  1419. switch (mode) {
  1420. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1421. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1422. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1423. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1424. }
  1425. };
  1426. /**
  1427. * Returns the byte stride giving an accessor
  1428. * @param accessor: the GLTF accessor objet
  1429. */
  1430. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1431. // Needs this function since "byteStride" isn't requiered in glTF format
  1432. var type = accessor.type;
  1433. switch (type) {
  1434. case "VEC2": return 2;
  1435. case "VEC3": return 3;
  1436. case "VEC4": return 4;
  1437. case "MAT2": return 4;
  1438. case "MAT3": return 9;
  1439. case "MAT4": return 16;
  1440. default: return 1;
  1441. }
  1442. };
  1443. /**
  1444. * Returns the texture filter mode giving a mode value
  1445. * @param mode: the filter mode value
  1446. */
  1447. GLTFUtils.GetTextureFilterMode = function (mode) {
  1448. switch (mode) {
  1449. case GLTF2.ETextureMinFilter.LINEAR:
  1450. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1451. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1452. case GLTF2.ETextureMinFilter.NEAREST:
  1453. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1454. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1455. }
  1456. };
  1457. GLTFUtils.GetBufferFromBufferView = function (runtime, bufferView, byteOffset, byteLength, componentType) {
  1458. var byteOffset = bufferView.byteOffset + byteOffset;
  1459. var loadedBufferView = runtime.gltf.buffers[bufferView.buffer].loadedBufferView;
  1460. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1461. throw new Error("Buffer access is out of range");
  1462. }
  1463. var buffer = loadedBufferView.buffer;
  1464. byteOffset += loadedBufferView.byteOffset;
  1465. switch (componentType) {
  1466. case GLTF2.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1467. case GLTF2.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1468. case GLTF2.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1469. case GLTF2.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1470. case GLTF2.EComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, byteLength);
  1471. default: return new Float32Array(buffer, byteOffset, byteLength);
  1472. }
  1473. };
  1474. /**
  1475. * Returns a buffer from its accessor
  1476. * @param runtime: the GLTF runtime
  1477. * @param accessor: the GLTF accessor
  1478. */
  1479. GLTFUtils.GetBufferFromAccessor = function (runtime, accessor) {
  1480. var bufferView = runtime.gltf.bufferViews[accessor.bufferView];
  1481. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1482. return GLTFUtils.GetBufferFromBufferView(runtime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1483. };
  1484. /**
  1485. * Decodes a buffer view into a string
  1486. * @param view: the buffer view
  1487. */
  1488. GLTFUtils.DecodeBufferToText = function (view) {
  1489. var result = "";
  1490. var length = view.byteLength;
  1491. for (var i = 0; i < length; ++i) {
  1492. result += String.fromCharCode(view[i]);
  1493. }
  1494. return result;
  1495. };
  1496. /**
  1497. * Returns the default material of gltf.
  1498. * @param scene: the Babylon.js scene
  1499. */
  1500. GLTFUtils.GetDefaultMaterial = function (runtime) {
  1501. if (!runtime.defaultMaterial) {
  1502. var material = new BABYLON.PBRMaterial("gltf_default", runtime.babylonScene);
  1503. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1504. material.metallic = 1;
  1505. material.roughness = 1;
  1506. runtime.defaultMaterial = material;
  1507. }
  1508. return runtime.defaultMaterial;
  1509. };
  1510. return GLTFUtils;
  1511. }());
  1512. GLTF2.GLTFUtils = GLTFUtils;
  1513. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1514. })(BABYLON || (BABYLON = {}));
  1515. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1516. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1517. var BABYLON;
  1518. (function (BABYLON) {
  1519. var GLTF2;
  1520. (function (GLTF2) {
  1521. var GLTFLoaderExtension = (function () {
  1522. function GLTFLoaderExtension(name) {
  1523. this._name = name;
  1524. }
  1525. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1526. get: function () {
  1527. return this._name;
  1528. },
  1529. enumerable: true,
  1530. configurable: true
  1531. });
  1532. GLTFLoaderExtension.prototype.postCreateRuntime = function (runtime) { };
  1533. // Return true to stop other extensions from loading materials.
  1534. GLTFLoaderExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) { return false; };
  1535. // ---------
  1536. // Utilities
  1537. // ---------
  1538. GLTFLoaderExtension.PostCreateRuntime = function (runtime) {
  1539. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1540. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1541. extension.postCreateRuntime(runtime);
  1542. }
  1543. };
  1544. GLTFLoaderExtension.LoadMaterialAsync = function (runtime, index, onSuccess, onError) {
  1545. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1546. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1547. if (extension.loadMaterialAsync(runtime, index, onSuccess, onError)) {
  1548. return;
  1549. }
  1550. }
  1551. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  1552. if (!material) {
  1553. onSuccess();
  1554. return;
  1555. }
  1556. var metallicRoughnessPropertiesSuccess = false;
  1557. var commonPropertiesSuccess = false;
  1558. var checkSuccess = function () {
  1559. if (metallicRoughnessPropertiesSuccess && commonPropertiesSuccess) {
  1560. onSuccess();
  1561. }
  1562. };
  1563. GLTF2.GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync(runtime, material, function () {
  1564. metallicRoughnessPropertiesSuccess = true;
  1565. checkSuccess();
  1566. }, onError);
  1567. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  1568. commonPropertiesSuccess = true;
  1569. checkSuccess();
  1570. }, onError);
  1571. };
  1572. return GLTFLoaderExtension;
  1573. }());
  1574. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1575. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1576. })(BABYLON || (BABYLON = {}));
  1577. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1578. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1579. var __extends = (this && this.__extends) || (function () {
  1580. var extendStatics = Object.setPrototypeOf ||
  1581. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1582. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1583. return function (d, b) {
  1584. extendStatics(d, b);
  1585. function __() { this.constructor = d; }
  1586. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1587. };
  1588. })();
  1589. var BABYLON;
  1590. (function (BABYLON) {
  1591. var GLTF2;
  1592. (function (GLTF2) {
  1593. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  1594. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  1595. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  1596. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  1597. }
  1598. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) {
  1599. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  1600. if (!material || !material.extensions)
  1601. return false;
  1602. var properties = material.extensions[this.name];
  1603. if (!properties)
  1604. return false;
  1605. //
  1606. // Load Factors
  1607. //
  1608. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1609. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1610. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1611. //
  1612. // Load Textures
  1613. //
  1614. var commonMaterialPropertiesSuccess = false;
  1615. var checkSuccess = function () {
  1616. if ((!properties.diffuseTexture || material.babylonMaterial.albedoTexture) &&
  1617. (!properties.specularGlossinessTexture || material.babylonMaterial.reflectivityTexture) &&
  1618. commonMaterialPropertiesSuccess) {
  1619. onSuccess();
  1620. }
  1621. };
  1622. if (properties.diffuseTexture) {
  1623. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.diffuseTexture, function (texture) {
  1624. material.babylonMaterial.albedoTexture = texture;
  1625. GLTF2.GLTFLoader.LoadAlphaProperties(runtime, material);
  1626. checkSuccess();
  1627. }, function () {
  1628. BABYLON.Tools.Warn("Failed to load diffuse texture");
  1629. onError();
  1630. });
  1631. }
  1632. if (properties.specularGlossinessTexture) {
  1633. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.specularGlossinessTexture, function (texture) {
  1634. material.babylonMaterial.reflectivityTexture = texture;
  1635. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1636. checkSuccess();
  1637. }, function () {
  1638. BABYLON.Tools.Warn("Failed to load metallic roughness texture");
  1639. onError();
  1640. });
  1641. }
  1642. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  1643. commonMaterialPropertiesSuccess = true;
  1644. checkSuccess();
  1645. }, onError);
  1646. return true;
  1647. };
  1648. return GLTFMaterialsPbrSpecularGlossinessExtension;
  1649. }(GLTF2.GLTFLoaderExtension));
  1650. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  1651. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  1652. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1653. })(BABYLON || (BABYLON = {}));
  1654. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map