babylon.glTF2Serializer.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. ;
  5. /**
  6. * Class for generating glTF data from a Babylon scene.
  7. */
  8. var GLTF2Export = /** @class */ (function () {
  9. function GLTF2Export() {
  10. }
  11. /**
  12. * Exports the geometry of the scene to .gltf file format.
  13. * @param scene - Babylon scene with scene hierarchy information.
  14. * @param filePrefix - File prefix to use when generating the glTF file.
  15. * @param options - Exporter options.
  16. * @returns - Returns an object with a .gltf file and associates texture names
  17. * as keys and their data and paths as values.
  18. */
  19. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  20. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  21. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  22. if (scene.isReady) {
  23. return gltfGenerator._generateGLTF(glTFPrefix);
  24. }
  25. else {
  26. throw new Error("glTF Serializer: Scene is not ready!");
  27. }
  28. };
  29. /**
  30. * Exports the geometry of the scene to .glb file format.
  31. * @param scene - Babylon scene with scene hierarchy information.
  32. * @param filePrefix - File prefix to use when generating glb file.
  33. * @param options - Exporter options.
  34. * @returns - Returns an object with a .glb filename as key and data as value
  35. */
  36. GLTF2Export.GLB = function (scene, filePrefix, options) {
  37. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  38. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  39. if (scene.isReady) {
  40. return gltfGenerator._generateGLB(glTFPrefix);
  41. }
  42. else {
  43. throw new Error("glTF Serializer: Scene is not ready!");
  44. }
  45. };
  46. return GLTF2Export;
  47. }());
  48. BABYLON.GLTF2Export = GLTF2Export;
  49. })(BABYLON || (BABYLON = {}));
  50. //# sourceMappingURL=babylon.glTFSerializer.js.map
  51. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  52. /**
  53. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
  54. * @ignore - capitalization of GLTF2 module.
  55. */
  56. var BABYLON;
  57. (function (BABYLON) {
  58. var GLTF2;
  59. (function (GLTF2) {
  60. /**
  61. * Converts Babylon Scene into glTF 2.0.
  62. */
  63. var _Exporter = /** @class */ (function () {
  64. /**
  65. * Creates a glTF Exporter instance, which can accept optional exporter options.
  66. * @param babylonScene - Babylon scene object
  67. * @param options - Options to modify the behavior of the exporter.
  68. */
  69. function _Exporter(babylonScene, options) {
  70. this.asset = { generator: "BabylonJS", version: "2.0" };
  71. this.babylonScene = babylonScene;
  72. this.bufferViews = new Array();
  73. this.accessors = new Array();
  74. this.meshes = new Array();
  75. this.scenes = new Array();
  76. this.nodes = new Array();
  77. this.images = new Array();
  78. this.materials = new Array();
  79. this.textures = new Array();
  80. this.imageData = {};
  81. if (options !== undefined) {
  82. this.options = options;
  83. }
  84. var totalByteLength = 0;
  85. totalByteLength = this.createScene(this.babylonScene, totalByteLength, null);
  86. this.totalByteLength = totalByteLength;
  87. }
  88. /**
  89. * Creates a buffer view based on teh supplied arguments
  90. * @param bufferIndex - index value of the specified buffer
  91. * @param byteOffset - byte offset value
  92. * @param byteLength - byte length of the bufferView
  93. * @param byteStride - byte distance between conequential elements.
  94. * @param name - name of the buffer view
  95. * @returns - bufferView for glTF
  96. */
  97. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  98. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  99. if (byteOffset > 0) {
  100. bufferview.byteOffset = byteOffset;
  101. }
  102. if (name) {
  103. bufferview.name = name;
  104. }
  105. if (byteStride) {
  106. bufferview.byteStride = byteStride;
  107. }
  108. return bufferview;
  109. };
  110. /**
  111. * Creates an accessor based on the supplied arguments
  112. * @param bufferviewIndex
  113. * @param name
  114. * @param type
  115. * @param componentType
  116. * @param count
  117. * @param min
  118. * @param max
  119. * @returns - accessor for glTF
  120. */
  121. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  122. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  123. if (min) {
  124. accessor.min = min;
  125. }
  126. if (max) {
  127. accessor.max = max;
  128. }
  129. if (byteOffset) {
  130. accessor.byteOffset = byteOffset;
  131. }
  132. return accessor;
  133. };
  134. /**
  135. * Calculates the minimum and maximum values of an array of floats, based on stride
  136. * @param buff - Data to check for min and max values.
  137. * @param vertexStart - Start offset to calculate min and max values.
  138. * @param vertexCount - Number of vertices to check for min and max values.
  139. * @param stride - Offset between consecutive attributes.
  140. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  141. * @returns - min number array and max number array.
  142. */
  143. _Exporter.prototype.calculateMinMax = function (buff, vertexStart, vertexCount, stride, useRightHandedSystem) {
  144. var min = [Infinity, Infinity, Infinity];
  145. var max = [-Infinity, -Infinity, -Infinity];
  146. var end = vertexStart + vertexCount;
  147. if (vertexCount > 0) {
  148. for (var i = vertexStart; i < end; ++i) {
  149. var index = stride * i;
  150. var scale = 1;
  151. for (var j = 0; j < stride; ++j) {
  152. if (j === (stride - 1) && !useRightHandedSystem) {
  153. scale = -1;
  154. }
  155. var num = scale * buff[index];
  156. if (num < min[j]) {
  157. min[j] = num;
  158. }
  159. if (num > max[j]) {
  160. max[j] = num;
  161. }
  162. ++index;
  163. }
  164. }
  165. }
  166. return { min: min, max: max };
  167. };
  168. /**
  169. * Writes mesh attribute data to a data buffer.
  170. * Returns the bytelength of the data.
  171. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  172. * @param meshAttributeArray - Array containing the attribute data.
  173. * @param strideSize - Represents the offset between consecutive attributes
  174. * @param byteOffset - The offset to start counting bytes from.
  175. * @param dataBuffer - The buffer to write the binary data to.
  176. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  177. * @returns - Byte length of the attribute data.
  178. */
  179. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, strideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem) {
  180. var byteOff = byteOffset;
  181. var start = 0;
  182. var end = meshAttributeArray.length / strideSize;
  183. var byteLength = 0;
  184. switch (vertexBufferKind) {
  185. case BABYLON.VertexBuffer.PositionKind: {
  186. for (var k = start; k < end; ++k) {
  187. var index = k * strideSize;
  188. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  189. byteOff += 4;
  190. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  191. byteOff += 4;
  192. if (useRightHandedSystem) {
  193. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  194. }
  195. else {
  196. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  197. }
  198. byteOff += 4;
  199. }
  200. byteLength = meshAttributeArray.length * 4;
  201. break;
  202. }
  203. case BABYLON.VertexBuffer.NormalKind: {
  204. for (var k = start; k < end; ++k) {
  205. var index = k * strideSize;
  206. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  207. byteOff += 4;
  208. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  209. byteOff += 4;
  210. if (useRightHandedSystem) {
  211. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  212. }
  213. else {
  214. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  215. }
  216. byteOff += 4;
  217. }
  218. byteLength = meshAttributeArray.length * 4;
  219. break;
  220. }
  221. case BABYLON.VertexBuffer.TangentKind: {
  222. for (var k = start; k < end; ++k) {
  223. var index = k * strideSize;
  224. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  225. byteOff += 4;
  226. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  227. byteOff += 4;
  228. if (useRightHandedSystem) {
  229. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  230. }
  231. else {
  232. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  233. }
  234. byteOff += 4;
  235. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  236. byteOff += 4;
  237. }
  238. byteLength = meshAttributeArray.length * 4;
  239. break;
  240. }
  241. case BABYLON.VertexBuffer.ColorKind: {
  242. for (var k = start; k < end; ++k) {
  243. var index = k * strideSize;
  244. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  245. byteOff += 4;
  246. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  247. byteOff += 4;
  248. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  249. byteOff += 4;
  250. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  251. byteOff += 4;
  252. }
  253. byteLength = meshAttributeArray.length * 4;
  254. break;
  255. }
  256. case BABYLON.VertexBuffer.UVKind: {
  257. for (var k = start; k < end; ++k) {
  258. var index = k * strideSize;
  259. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  260. byteOff += 4;
  261. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  262. byteOff += 4;
  263. }
  264. byteLength = meshAttributeArray.length * 4;
  265. break;
  266. }
  267. case BABYLON.VertexBuffer.UV2Kind: {
  268. for (var k = start; k < end; ++k) {
  269. var index = k * strideSize;
  270. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  271. byteOff += 4;
  272. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  273. byteOff += 4;
  274. }
  275. byteLength = meshAttributeArray.length * 4;
  276. break;
  277. }
  278. default: {
  279. throw new Error("Unsupported vertex buffer type: " + vertexBufferKind);
  280. }
  281. }
  282. return byteLength;
  283. };
  284. /**
  285. * Generates glTF json data
  286. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  287. * @param glTFPrefix - Text to use when prefixing a glTF file.
  288. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  289. * @returns - json data as string
  290. */
  291. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  292. var buffer = { byteLength: this.totalByteLength };
  293. var glTF = {
  294. asset: this.asset
  295. };
  296. if (buffer.byteLength > 0) {
  297. glTF.buffers = [buffer];
  298. }
  299. if (this.nodes && this.nodes.length !== 0) {
  300. glTF.nodes = this.nodes;
  301. }
  302. if (this.meshes && this.meshes.length !== 0) {
  303. glTF.meshes = this.meshes;
  304. }
  305. if (this.scenes && this.scenes.length !== 0) {
  306. glTF.scenes = this.scenes;
  307. glTF.scene = 0;
  308. }
  309. if (this.bufferViews && this.bufferViews.length !== 0) {
  310. glTF.bufferViews = this.bufferViews;
  311. }
  312. if (this.accessors && this.accessors.length !== 0) {
  313. glTF.accessors = this.accessors;
  314. }
  315. if (this.materials && this.materials.length !== 0) {
  316. glTF.materials = this.materials;
  317. }
  318. if (this.textures && this.textures.length !== 0) {
  319. glTF.textures = this.textures;
  320. }
  321. if (this.images && this.images.length !== 0) {
  322. if (!shouldUseGlb) {
  323. glTF.images = this.images;
  324. }
  325. else {
  326. glTF.images = [];
  327. // Replace uri with bufferview and mime type for glb
  328. var imageLength = this.images.length;
  329. var byteOffset = this.totalByteLength;
  330. for (var i = 0; i < imageLength; ++i) {
  331. var image = this.images[i];
  332. if (image.uri !== undefined) {
  333. var imageData = this.imageData[image.uri];
  334. var imageName = image.uri.split('.')[0] + " image";
  335. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  336. byteOffset += imageData.data.buffer.byteLength;
  337. this.bufferViews.push(bufferView);
  338. image.bufferView = this.bufferViews.length - 1;
  339. image.name = imageName;
  340. image.mimeType = imageData.mimeType;
  341. image.uri = undefined;
  342. glTF.images.push(image);
  343. }
  344. }
  345. buffer.byteLength = byteOffset;
  346. }
  347. }
  348. if (!shouldUseGlb) {
  349. buffer.uri = glTFPrefix + ".bin";
  350. }
  351. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  352. return jsonText;
  353. };
  354. /**
  355. * Generates data for .gltf and .bin files based on the glTF prefix string
  356. * @param glTFPrefix - Text to use when prefixing a glTF file.
  357. * @returns - GLTFData with glTF file data.
  358. */
  359. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  360. var jsonText = this.generateJSON(false, glTFPrefix, true);
  361. var binaryBuffer = this.generateBinary();
  362. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  363. var glTFFileName = glTFPrefix + '.gltf';
  364. var glTFBinFile = glTFPrefix + '.bin';
  365. var container = new BABYLON._GLTFData();
  366. container.glTFFiles[glTFFileName] = jsonText;
  367. container.glTFFiles[glTFBinFile] = bin;
  368. if (this.imageData !== null) {
  369. for (var image in this.imageData) {
  370. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  371. }
  372. }
  373. return container;
  374. };
  375. /**
  376. * Creates a binary buffer for glTF
  377. * @returns - array buffer for binary data
  378. */
  379. _Exporter.prototype.generateBinary = function () {
  380. var byteOffset = 0;
  381. var binaryBuffer = new ArrayBuffer(this.totalByteLength);
  382. var dataBuffer = new DataView(binaryBuffer);
  383. byteOffset = this.createScene(this.babylonScene, byteOffset, dataBuffer);
  384. return binaryBuffer;
  385. };
  386. /**
  387. * Pads the number to a multiple of 4
  388. * @param num - number to pad
  389. * @returns - padded number
  390. */
  391. _Exporter.prototype._getPadding = function (num) {
  392. var remainder = num % 4;
  393. var padding = remainder === 0 ? remainder : 4 - remainder;
  394. return padding;
  395. };
  396. /**
  397. * Generates a glb file from the json and binary data.
  398. * Returns an object with the glb file name as the key and data as the value.
  399. * @param glTFPrefix
  400. * @returns - object with glb filename as key and data as value
  401. */
  402. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  403. var jsonText = this.generateJSON(true);
  404. var binaryBuffer = this.generateBinary();
  405. var glbFileName = glTFPrefix + '.glb';
  406. var headerLength = 12;
  407. var chunkLengthPrefix = 8;
  408. var jsonLength = jsonText.length;
  409. var imageByteLength = 0;
  410. for (var key in this.imageData) {
  411. imageByteLength += this.imageData[key].data.byteLength;
  412. }
  413. var jsonPadding = this._getPadding(jsonLength);
  414. var binPadding = this._getPadding(binaryBuffer.byteLength);
  415. var imagePadding = this._getPadding(imageByteLength);
  416. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  417. //header
  418. var headerBuffer = new ArrayBuffer(headerLength);
  419. var headerBufferView = new DataView(headerBuffer);
  420. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  421. headerBufferView.setUint32(4, 2, true); // version
  422. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  423. //json chunk
  424. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  425. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  426. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  427. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  428. //json chunk bytes
  429. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  430. for (var i = 0; i < jsonLength; ++i) {
  431. jsonData[i] = jsonText.charCodeAt(i);
  432. }
  433. //json padding
  434. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  435. for (var i = 0; i < jsonPadding; ++i) {
  436. jsonPaddingView[i] = 0x20;
  437. }
  438. //binary chunk
  439. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  440. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  441. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  442. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  443. // binary padding
  444. var binPaddingBuffer = new ArrayBuffer(binPadding);
  445. var binPaddingView = new Uint8Array(binPaddingBuffer);
  446. for (var i = 0; i < binPadding; ++i) {
  447. binPaddingView[i] = 0;
  448. }
  449. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  450. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  451. for (var i = 0; i < imagePadding; ++i) {
  452. imagePaddingView[i] = 0;
  453. }
  454. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  455. // binary data
  456. for (var key in this.imageData) {
  457. glbData.push(this.imageData[key].data.buffer);
  458. }
  459. glbData.push(binPaddingBuffer);
  460. glbData.push(imagePaddingBuffer);
  461. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  462. var container = new BABYLON._GLTFData();
  463. container.glTFFiles[glbFileName] = glbFile;
  464. return container;
  465. };
  466. /**
  467. * Sets the TRS for each node
  468. * @param node - glTF Node for storing the transformation data.
  469. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  470. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  471. */
  472. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh, useRightHandedSystem) {
  473. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  474. if (useRightHandedSystem) {
  475. node.translation = babylonMesh.position.asArray();
  476. }
  477. else {
  478. node.translation = [babylonMesh.position.x, babylonMesh.position.y, -babylonMesh.position.z];
  479. }
  480. }
  481. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  482. if (useRightHandedSystem) {
  483. node.scale = babylonMesh.scaling.asArray();
  484. }
  485. else {
  486. node.scale = [babylonMesh.scaling.x, babylonMesh.scaling.y, -babylonMesh.scaling.z];
  487. }
  488. }
  489. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  490. if (babylonMesh.rotationQuaternion) {
  491. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  492. }
  493. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  494. if (useRightHandedSystem) {
  495. node.rotation = rotationQuaternion.asArray();
  496. }
  497. else {
  498. node.rotation = [-rotationQuaternion.x, -rotationQuaternion.y, rotationQuaternion.z, rotationQuaternion.w];
  499. }
  500. }
  501. };
  502. /**
  503. * Creates a bufferview based on the vertices type for the Babylon mesh
  504. * @param kind - Indicates the type of vertices data.
  505. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  506. * @param byteOffset - The offset from the buffer to start indexing from.
  507. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  508. * @param dataBuffer - The buffer to write the bufferview data to.
  509. * @returns bytelength of the bufferview data.
  510. */
  511. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  512. var bufferMesh = null;
  513. var byteLength = 0;
  514. if (babylonMesh instanceof BABYLON.Mesh) {
  515. bufferMesh = babylonMesh;
  516. }
  517. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  518. bufferMesh = babylonMesh.sourceMesh;
  519. }
  520. if (bufferMesh !== null) {
  521. var vertexBuffer = null;
  522. var vertexBufferOffset = null;
  523. var vertexData = null;
  524. var vertexStrideSize = null;
  525. if (bufferMesh.getVerticesDataKinds().indexOf(kind) > -1) {
  526. vertexBuffer = bufferMesh.getVertexBuffer(kind);
  527. vertexBufferOffset = vertexBuffer.getOffset();
  528. vertexData = vertexBuffer.getData();
  529. vertexStrideSize = vertexBuffer.getStrideSize();
  530. if (dataBuffer && vertexData) {
  531. byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem);
  532. byteOffset += byteLength;
  533. }
  534. else {
  535. var bufferViewName = null;
  536. switch (kind) {
  537. case BABYLON.VertexBuffer.PositionKind: {
  538. byteLength = vertexData.length * 4;
  539. bufferViewName = "Position - " + bufferMesh.name;
  540. break;
  541. }
  542. case BABYLON.VertexBuffer.NormalKind: {
  543. byteLength = vertexData.length * 4;
  544. bufferViewName = "Normal - " + bufferMesh.name;
  545. break;
  546. }
  547. case BABYLON.VertexBuffer.TangentKind: {
  548. byteLength = vertexData.length * 4;
  549. bufferViewName = "Tangent - " + bufferMesh.name;
  550. break;
  551. }
  552. case BABYLON.VertexBuffer.ColorKind: {
  553. byteLength = vertexData.length * 4;
  554. bufferViewName = "Color - " + bufferMesh.name;
  555. break;
  556. }
  557. case BABYLON.VertexBuffer.UVKind: {
  558. byteLength = vertexData.length * 4;
  559. bufferViewName = "TexCoord 0 - " + bufferMesh.name;
  560. break;
  561. }
  562. case BABYLON.VertexBuffer.UV2Kind: {
  563. byteLength = vertexData.length * 4;
  564. bufferViewName = "TexCoord 1 - " + bufferMesh.name;
  565. break;
  566. }
  567. default: {
  568. BABYLON.Tools.Warn("Unsupported VertexBuffer kind: " + kind);
  569. }
  570. }
  571. if (bufferViewName !== null) {
  572. var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, bufferViewName);
  573. byteOffset += byteLength;
  574. this.bufferViews.push(bufferView);
  575. }
  576. }
  577. }
  578. }
  579. return byteLength;
  580. };
  581. /**
  582. * Sets data for the primitive attributes of each submesh
  583. * @param mesh - glTF Mesh object to store the primitive attribute information.
  584. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  585. * @param byteOffset - The offset in bytes of the buffer data.
  586. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  587. * @param dataBuffer - Buffer to write the attribute data to.
  588. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  589. */
  590. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  591. var bufferMesh = null;
  592. if (babylonMesh instanceof BABYLON.Mesh) {
  593. bufferMesh = babylonMesh;
  594. }
  595. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  596. bufferMesh = babylonMesh.sourceMesh;
  597. }
  598. var positionBufferViewIndex = null;
  599. var normalBufferViewIndex = null;
  600. var colorBufferViewIndex = null;
  601. var tangentBufferViewIndex = null;
  602. var texCoord0BufferViewIndex = null;
  603. var texCoord1BufferViewIndex = null;
  604. var indexBufferViewIndex = null;
  605. if (bufferMesh !== null) {
  606. // For each BabylonMesh, create bufferviews for each 'kind'
  607. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  608. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.PositionKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  609. positionBufferViewIndex = this.bufferViews.length - 1;
  610. }
  611. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  612. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.NormalKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  613. normalBufferViewIndex = this.bufferViews.length - 1;
  614. }
  615. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  616. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.ColorKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  617. colorBufferViewIndex = this.bufferViews.length - 1;
  618. }
  619. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  620. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.TangentKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  621. colorBufferViewIndex = this.bufferViews.length - 1;
  622. }
  623. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  624. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UVKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  625. texCoord0BufferViewIndex = this.bufferViews.length - 1;
  626. }
  627. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  628. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UV2Kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  629. texCoord1BufferViewIndex = this.bufferViews.length - 1;
  630. }
  631. if (bufferMesh.getTotalIndices() > 0) {
  632. var indices = bufferMesh.getIndices();
  633. if (dataBuffer) {
  634. var end = indices.length;
  635. var byteOff = byteOffset;
  636. for (var k = 0; k < end; ++k) {
  637. dataBuffer.setUint32(byteOff, indices[k], true);
  638. byteOff += 4;
  639. }
  640. byteOffset = byteOff;
  641. }
  642. else {
  643. var byteLength = indices.length * 4;
  644. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  645. byteOffset += byteLength;
  646. this.bufferViews.push(bufferView);
  647. indexBufferViewIndex = this.bufferViews.length - 1;
  648. }
  649. }
  650. }
  651. // go through all mesh primitives (submeshes)
  652. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  653. var submesh = babylonMesh.subMeshes[j];
  654. var meshPrimitive = { attributes: {} };
  655. if (bufferMesh !== null) {
  656. // Create a bufferview storing all the positions
  657. if (!dataBuffer) {
  658. // Loop through each attribute of the submesh (mesh primitive)
  659. if (positionBufferViewIndex !== null) {
  660. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  661. var positions = positionVertexBuffer.getData();
  662. var positionStrideSize = positionVertexBuffer.getStrideSize();
  663. // Create accessor
  664. var result = this.calculateMinMax(positions, 0, positions.length / positionStrideSize, positionStrideSize, useRightHandedSystem);
  665. var accessor = this.createAccessor(positionBufferViewIndex, "Position", "VEC3" /* VEC3 */, 5126 /* FLOAT */, positions.length / positionStrideSize, 0, result.min, result.max);
  666. this.accessors.push(accessor);
  667. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  668. }
  669. if (normalBufferViewIndex !== null) {
  670. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  671. var normals = normalVertexBuffer.getData();
  672. var normalStrideSize = normalVertexBuffer.getStrideSize();
  673. // Create accessor
  674. var accessor = this.createAccessor(normalBufferViewIndex, "Normal", "VEC3" /* VEC3 */, 5126 /* FLOAT */, normals.length / normalStrideSize);
  675. this.accessors.push(accessor);
  676. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  677. }
  678. if (tangentBufferViewIndex !== null) {
  679. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  680. var tangents = tangentVertexBuffer.getData();
  681. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  682. // Create accessor
  683. var accessor = this.createAccessor(tangentBufferViewIndex, "Tangent", "VEC4" /* VEC4 */, 5126 /* FLOAT */, tangents.length / tangentStrideSize);
  684. this.accessors.push(accessor);
  685. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  686. }
  687. if (colorBufferViewIndex !== null) {
  688. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  689. var colors = colorVertexBuffer.getData();
  690. var colorStrideSize = colorVertexBuffer.getStrideSize();
  691. // Create accessor
  692. var accessor = this.createAccessor(colorBufferViewIndex, "Color", "VEC4" /* VEC4 */, 5126 /* FLOAT */, colors.length / colorStrideSize);
  693. this.accessors.push(accessor);
  694. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  695. }
  696. if (texCoord0BufferViewIndex !== null) {
  697. // Create accessor
  698. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  699. var texCoord0s = texCoord0VertexBuffer.getData();
  700. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  701. var accessor = this.createAccessor(texCoord0BufferViewIndex, "Texture Coords 0", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord0s.length / texCoord0StrideSize);
  702. this.accessors.push(accessor);
  703. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  704. }
  705. if (texCoord1BufferViewIndex !== null) {
  706. // Create accessor
  707. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  708. var texCoord1s = texCoord1VertexBuffer.getData();
  709. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  710. var accessor = this.createAccessor(texCoord1BufferViewIndex, "Texture Coords 1", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord1s.length / texCoord1StrideSize);
  711. this.accessors.push(accessor);
  712. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  713. }
  714. if (indexBufferViewIndex) {
  715. // Create accessor
  716. var accessor = this.createAccessor(indexBufferViewIndex, "Indices", "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4);
  717. this.accessors.push(accessor);
  718. meshPrimitive.indices = this.accessors.length - 1;
  719. }
  720. }
  721. if (bufferMesh.material) {
  722. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  723. var materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  724. meshPrimitive.material = materialIndex;
  725. }
  726. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  727. var babylonMultiMaterial = bufferMesh.material;
  728. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  729. if (material !== null) {
  730. var materialIndex = babylonMesh.getScene().materials.indexOf(material);
  731. meshPrimitive.material = materialIndex;
  732. }
  733. }
  734. else {
  735. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  736. }
  737. }
  738. mesh.primitives.push(meshPrimitive);
  739. }
  740. }
  741. return byteOffset;
  742. };
  743. /**
  744. * Creates a glTF scene based on the array of meshes.
  745. * Returns the the total byte offset.
  746. * @param babylonScene - Babylon scene to get the mesh data from.
  747. * @param byteOffset - Offset to start from in bytes.
  748. * @param dataBuffer - Buffer to write geometry data to.
  749. * @returns bytelength + byteoffset
  750. */
  751. _Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  752. if (babylonScene.meshes.length > 0) {
  753. var babylonMeshes = babylonScene.meshes;
  754. var scene = { nodes: new Array() };
  755. if (dataBuffer == null) {
  756. GLTF2._GLTFMaterial.ConvertMaterialsToGLTF(babylonScene.materials, "image/jpeg" /* JPEG */, this.images, this.textures, this.materials, this.imageData, true);
  757. }
  758. for (var i = 0; i < babylonMeshes.length; ++i) {
  759. if (this.options &&
  760. this.options.shouldExportMesh !== undefined &&
  761. !this.options.shouldExportMesh(babylonMeshes[i])) {
  762. continue;
  763. }
  764. else {
  765. // create node to hold translation/rotation/scale and the mesh
  766. var node = { mesh: -1 };
  767. var babylonMesh = babylonMeshes[i];
  768. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  769. // Set transformation
  770. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  771. // create mesh
  772. var mesh = { primitives: new Array() };
  773. mesh.primitives = [];
  774. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  775. // go through all mesh primitives (submeshes)
  776. this.meshes.push(mesh);
  777. node.mesh = this.meshes.length - 1;
  778. if (babylonMesh.name) {
  779. node.name = babylonMesh.name;
  780. }
  781. this.nodes.push(node);
  782. scene.nodes.push(this.nodes.length - 1);
  783. }
  784. }
  785. this.scenes.push(scene);
  786. }
  787. return byteOffset;
  788. };
  789. return _Exporter;
  790. }());
  791. GLTF2._Exporter = _Exporter;
  792. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  793. })(BABYLON || (BABYLON = {}));
  794. //# sourceMappingURL=babylon.glTFExporter.js.map
  795. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  796. var BABYLON;
  797. (function (BABYLON) {
  798. /**
  799. * Class for holding and downloading glTF file data
  800. */
  801. var _GLTFData = /** @class */ (function () {
  802. /**
  803. * Initializes the glTF file object.
  804. */
  805. function _GLTFData() {
  806. this.glTFFiles = {};
  807. }
  808. /**
  809. * Downloads the glTF data as files based on their names and data.
  810. */
  811. _GLTFData.prototype.downloadFiles = function () {
  812. /**
  813. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  814. * @param str - Source string.
  815. * @param suffix - Suffix to search for in the source string.
  816. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  817. */
  818. function endsWith(str, suffix) {
  819. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  820. }
  821. for (var key in this.glTFFiles) {
  822. var link = document.createElement('a');
  823. document.body.appendChild(link);
  824. link.setAttribute("type", "hidden");
  825. link.download = key;
  826. var blob = this.glTFFiles[key];
  827. var mimeType = void 0;
  828. if (endsWith(key, ".glb")) {
  829. mimeType = { type: "model/gltf-binary" };
  830. }
  831. else if (endsWith(key, ".bin")) {
  832. mimeType = { type: "application/octet-stream" };
  833. }
  834. else if (endsWith(key, ".gltf")) {
  835. mimeType = { type: "model/gltf+json" };
  836. }
  837. else if (endsWith(key, ".jpeg" || ".jpg")) {
  838. mimeType = { type: "image/jpeg" /* JPEG */ };
  839. }
  840. else if (endsWith(key, ".png")) {
  841. mimeType = { type: "image/png" /* PNG */ };
  842. }
  843. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  844. link.click();
  845. }
  846. };
  847. return _GLTFData;
  848. }());
  849. BABYLON._GLTFData = _GLTFData;
  850. })(BABYLON || (BABYLON = {}));
  851. //# sourceMappingURL=babylon.glTFData.js.map
  852. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  853. var BABYLON;
  854. (function (BABYLON) {
  855. var GLTF2;
  856. (function (GLTF2) {
  857. /**
  858. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  859. */
  860. var _GLTFMaterial = /** @class */ (function () {
  861. function _GLTFMaterial() {
  862. }
  863. /**
  864. * Gets the materials from a Babylon scene and converts them to glTF materials.
  865. * @param scene
  866. * @param mimeType
  867. * @param images
  868. * @param textures
  869. * @param materials
  870. * @param imageData
  871. * @param hasTextureCoords
  872. */
  873. _GLTFMaterial.ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  874. for (var i = 0; i < babylonMaterials.length; ++i) {
  875. var babylonMaterial = babylonMaterials[i];
  876. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  877. _GLTFMaterial.ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  878. }
  879. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  880. _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  881. }
  882. }
  883. };
  884. /**
  885. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  886. * @param babylonStandardMaterial
  887. * @returns - glTF Metallic Roughness Material representation
  888. */
  889. _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  890. var P0 = new BABYLON.Vector2(0, 1);
  891. var P1 = new BABYLON.Vector2(0, 0.1);
  892. var P2 = new BABYLON.Vector2(0, 0.1);
  893. var P3 = new BABYLON.Vector2(1300, 0.1);
  894. /**
  895. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  896. * @param t - a value between 0 and 1.
  897. * @param p0 - first control point.
  898. * @param p1 - second control point.
  899. * @param p2 - third control point.
  900. * @param p3 - fourth control point.
  901. * @returns - number result of cubic bezier curve at the specified t.
  902. */
  903. function cubicBezierCurve(t, p0, p1, p2, p3) {
  904. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  905. 3 * (1 - t) * (1 - t) * t * p1 +
  906. 3 * (1 - t) * t * t * p2 +
  907. t * t * t * p3);
  908. }
  909. /**
  910. * Evaluates a specified specular power value to determine the appropriate roughness value,
  911. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  912. * and roughness on the ordinant axis (y-axis).
  913. * @param specularPower - specular power of standard material.
  914. * @returns - Number representing the roughness value.
  915. */
  916. function solveForRoughness(specularPower) {
  917. var t = Math.pow(specularPower / P3.x, 0.333333);
  918. return cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  919. }
  920. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  921. var opacity = babylonStandardMaterial.alpha;
  922. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this.maxSpecularPower);
  923. var roughness = solveForRoughness(specularPower);
  924. var glTFPbrMetallicRoughness = {
  925. baseColorFactor: [
  926. diffuse.r,
  927. diffuse.g,
  928. diffuse.b,
  929. opacity
  930. ],
  931. metallicFactor: 0,
  932. roughnessFactor: roughness,
  933. };
  934. return glTFPbrMetallicRoughness;
  935. };
  936. /**
  937. * Computes the metallic factor
  938. * @param diffuse - diffused value
  939. * @param specular - specular value
  940. * @param oneMinusSpecularStrength - one minus the specular strength
  941. * @returns - metallic value
  942. */
  943. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  944. if (specular < _GLTFMaterial.dielectricSpecular.r) {
  945. _GLTFMaterial.dielectricSpecular;
  946. return 0;
  947. }
  948. var a = _GLTFMaterial.dielectricSpecular.r;
  949. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial.dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial.dielectricSpecular.r;
  950. var c = _GLTFMaterial.dielectricSpecular.r - specular;
  951. var D = b * b - 4.0 * a * c;
  952. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  953. };
  954. /**
  955. * Gets the glTF alpha mode from the Babylon Material
  956. * @param babylonMaterial - Babylon Material
  957. * @returns - The Babylon alpha mode value
  958. */
  959. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  960. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  961. var babylonStandardMaterial = babylonMaterial;
  962. if ((babylonStandardMaterial.alpha != 1.0) ||
  963. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  964. (babylonStandardMaterial.opacityTexture != null)) {
  965. return "BLEND" /* BLEND */;
  966. }
  967. else {
  968. return "OPAQUE" /* OPAQUE */;
  969. }
  970. }
  971. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  972. var babylonPBRMetallicRoughness = babylonMaterial;
  973. switch (babylonPBRMetallicRoughness.transparencyMode) {
  974. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  975. return "OPAQUE" /* OPAQUE */;
  976. }
  977. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  978. return "BLEND" /* BLEND */;
  979. }
  980. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  981. return "MASK" /* MASK */;
  982. }
  983. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  984. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  985. return "BLEND" /* BLEND */;
  986. }
  987. default: {
  988. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  989. }
  990. }
  991. }
  992. else {
  993. throw new Error("Unsupported Babylon material type");
  994. }
  995. };
  996. /**
  997. * Converts a Babylon Standard Material to a glTF Material.
  998. * @param babylonStandardMaterial - BJS Standard Material.
  999. * @param mimeType - mime type to use for the textures.
  1000. * @param images - array of glTF image interfaces.
  1001. * @param textures - array of glTF texture interfaces.
  1002. * @param materials - array of glTF material interfaces.
  1003. * @param imageData - map of image file name to data.
  1004. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1005. */
  1006. _GLTFMaterial.ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1007. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1008. var glTFPbrMetallicRoughness = _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1009. var glTFMaterial = { name: babylonStandardMaterial.name };
  1010. if (babylonStandardMaterial.backFaceCulling) {
  1011. if (!babylonStandardMaterial.twoSidedLighting) {
  1012. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1013. }
  1014. glTFMaterial.doubleSided = true;
  1015. }
  1016. if (hasTextureCoords) {
  1017. if (babylonStandardMaterial.diffuseTexture) {
  1018. var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1019. if (glTFTexture != null) {
  1020. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1021. }
  1022. }
  1023. if (babylonStandardMaterial.bumpTexture) {
  1024. var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1025. if (glTFTexture) {
  1026. glTFMaterial.normalTexture = glTFTexture;
  1027. }
  1028. }
  1029. if (babylonStandardMaterial.emissiveTexture) {
  1030. var glTFEmissiveTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1031. if (glTFEmissiveTexture) {
  1032. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1033. }
  1034. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1035. }
  1036. if (babylonStandardMaterial.ambientTexture) {
  1037. var glTFOcclusionTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1038. if (glTFOcclusionTexture) {
  1039. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  1040. }
  1041. }
  1042. }
  1043. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1044. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1045. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1046. }
  1047. else {
  1048. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1049. }
  1050. }
  1051. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1052. materials.push(glTFMaterial);
  1053. };
  1054. /**
  1055. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1056. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1057. * @param mimeType - mime type to use for the textures.
  1058. * @param images - array of glTF image interfaces.
  1059. * @param textures - array of glTF texture interfaces.
  1060. * @param materials - array of glTF material interfaces.
  1061. * @param imageData - map of image file name to data.
  1062. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1063. */
  1064. _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1065. var glTFPbrMetallicRoughness = {};
  1066. if (babylonPBRMetalRoughMaterial.baseColor) {
  1067. glTFPbrMetallicRoughness.baseColorFactor = [
  1068. babylonPBRMetalRoughMaterial.baseColor.r,
  1069. babylonPBRMetalRoughMaterial.baseColor.g,
  1070. babylonPBRMetalRoughMaterial.baseColor.b,
  1071. babylonPBRMetalRoughMaterial.alpha
  1072. ];
  1073. }
  1074. if (babylonPBRMetalRoughMaterial.metallic != null) {
  1075. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1076. }
  1077. if (babylonPBRMetalRoughMaterial.roughness != null) {
  1078. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1079. }
  1080. var glTFMaterial = {
  1081. name: babylonPBRMetalRoughMaterial.name
  1082. };
  1083. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1084. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1085. }
  1086. if (hasTextureCoords) {
  1087. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1088. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1089. if (glTFTexture != null) {
  1090. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1091. }
  1092. }
  1093. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1094. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1095. if (glTFTexture) {
  1096. glTFMaterial.normalTexture = glTFTexture;
  1097. }
  1098. }
  1099. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1100. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1101. if (glTFTexture) {
  1102. glTFMaterial.occlusionTexture = glTFTexture;
  1103. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1104. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1105. }
  1106. }
  1107. }
  1108. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1109. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1110. if (glTFTexture != null) {
  1111. glTFMaterial.emissiveTexture = glTFTexture;
  1112. }
  1113. }
  1114. }
  1115. if (babylonPBRMetalRoughMaterial.emissiveColor.equalsFloats(0.0, 0.0, 0.0)) {
  1116. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1117. }
  1118. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1119. var alphaMode = _GLTFMaterial.GetAlphaMode(babylonPBRMetalRoughMaterial);
  1120. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1121. glTFMaterial.alphaMode = alphaMode;
  1122. if (alphaMode === "BLEND" /* BLEND */) {
  1123. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1124. }
  1125. }
  1126. }
  1127. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1128. materials.push(glTFMaterial);
  1129. };
  1130. /**
  1131. * Extracts a texture from a Babylon texture into file data and glTF data.
  1132. * @param babylonTexture - Babylon texture to extract.
  1133. * @param mimeType - Mime Type of the babylonTexture.
  1134. * @param images - Array of glTF images.
  1135. * @param textures - Array of glTF textures.
  1136. * @param imageData - map of image file name and data.
  1137. * @return - glTF texture, or null if the texture format is not supported.
  1138. */
  1139. _GLTFMaterial.ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1140. var textureInfo = null;
  1141. var glTFTexture = {
  1142. source: images.length
  1143. };
  1144. var textureName = "texture_" + (textures.length - 1).toString();
  1145. var textureData = babylonTexture.getInternalTexture();
  1146. if (textureData != null) {
  1147. textureName = textureData.url;
  1148. }
  1149. textureName = BABYLON.Tools.GetFilename(textureName);
  1150. var baseFile = textureName.split('.')[0];
  1151. var extension = "";
  1152. if (mimeType === "image/jpeg" /* JPEG */) {
  1153. extension = ".jpg";
  1154. }
  1155. else if (mimeType === "image/png" /* PNG */) {
  1156. extension = ".png";
  1157. }
  1158. else {
  1159. BABYLON.Tools.Error("Unsupported mime type " + mimeType);
  1160. }
  1161. textureName = baseFile + extension;
  1162. var pixels = babylonTexture.readPixels();
  1163. var imageCanvas = document.createElement('canvas');
  1164. imageCanvas.id = "ImageCanvas";
  1165. var ctx = imageCanvas.getContext('2d');
  1166. var size = babylonTexture.getSize();
  1167. imageCanvas.width = size.width;
  1168. imageCanvas.height = size.height;
  1169. var imgData = ctx.createImageData(size.width, size.height);
  1170. imgData.data.set(pixels);
  1171. ctx.putImageData(imgData, 0, 0);
  1172. var base64Data = imageCanvas.toDataURL(mimeType);
  1173. var binStr = atob(base64Data.split(',')[1]);
  1174. var arr = new Uint8Array(binStr.length);
  1175. for (var i = 0; i < binStr.length; ++i) {
  1176. arr[i] = binStr.charCodeAt(i);
  1177. }
  1178. var imageValues = { data: arr, mimeType: mimeType };
  1179. imageData[textureName] = imageValues;
  1180. if (mimeType === "image/jpeg" /* JPEG */) {
  1181. var glTFImage = {
  1182. uri: textureName
  1183. };
  1184. var foundIndex = -1;
  1185. for (var i = 0; i < images.length; ++i) {
  1186. if (images[i].uri === textureName) {
  1187. foundIndex = i;
  1188. break;
  1189. }
  1190. }
  1191. if (foundIndex === -1) {
  1192. images.push(glTFImage);
  1193. glTFTexture.source = images.length - 1;
  1194. textures.push({
  1195. source: images.length - 1
  1196. });
  1197. textureInfo = {
  1198. index: images.length - 1
  1199. };
  1200. }
  1201. else {
  1202. glTFTexture.source = foundIndex;
  1203. textureInfo = {
  1204. index: foundIndex
  1205. };
  1206. }
  1207. }
  1208. return textureInfo;
  1209. };
  1210. /**
  1211. * Represents the dielectric specular values for R, G and B.
  1212. */
  1213. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1214. /**
  1215. * Allows the maximum specular power to be defined for material calculations.
  1216. */
  1217. _GLTFMaterial.maxSpecularPower = 1024;
  1218. return _GLTFMaterial;
  1219. }());
  1220. GLTF2._GLTFMaterial = _GLTFMaterial;
  1221. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1222. })(BABYLON || (BABYLON = {}));
  1223. //# sourceMappingURL=babylon.glTFMaterial.js.map