babylon.glTF2FileLoader.js 82 KB

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