babylon.glTF2Serializer.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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. *
  504. * @param babylonTexture - Babylon texture to extract.
  505. * @param mimeType - Mime Type of the babylonTexture.
  506. * @return - glTF texture, or null if the texture format is not supported.
  507. */
  508. _Exporter.prototype.exportTexture = function (babylonTexture, mimeType) {
  509. if (mimeType === void 0) { mimeType = "image/jpeg" /* JPEG */; }
  510. var textureInfo = null;
  511. var glTFTexture;
  512. glTFTexture = {
  513. source: this.images.length
  514. };
  515. var textureName = babylonTexture.getInternalTexture().url;
  516. if (textureName.search('/') !== -1) {
  517. var splitFilename = textureName.split('/');
  518. textureName = splitFilename[splitFilename.length - 1];
  519. var basefile = textureName.split('.')[0];
  520. var extension = textureName.split('.')[1];
  521. if (mimeType === "image/jpeg" /* JPEG */) {
  522. extension = ".jpg";
  523. }
  524. else if (mimeType === "image/png" /* PNG */) {
  525. extension = ".png";
  526. }
  527. else {
  528. throw new Error("Unsupported mime type " + mimeType);
  529. }
  530. textureName = basefile + extension;
  531. }
  532. var pixels = babylonTexture.readPixels();
  533. var imageCanvas = document.createElement('canvas');
  534. imageCanvas.id = "ImageCanvas";
  535. var ctx = imageCanvas.getContext('2d');
  536. var size = babylonTexture.getSize();
  537. imageCanvas.width = size.width;
  538. imageCanvas.height = size.height;
  539. var imgData = ctx.createImageData(size.width, size.height);
  540. imgData.data.set(pixels);
  541. ctx.putImageData(imgData, 0, 0);
  542. var base64Data = imageCanvas.toDataURL(mimeType);
  543. var binStr = atob(base64Data.split(',')[1]);
  544. var arr = new Uint8Array(binStr.length);
  545. for (var i = 0; i < binStr.length; ++i) {
  546. arr[i] = binStr.charCodeAt(i);
  547. }
  548. var imageValues = { data: arr, mimeType: mimeType };
  549. this.imageData[textureName] = imageValues;
  550. if (mimeType === "image/jpeg" /* JPEG */) {
  551. var glTFImage = {
  552. uri: textureName
  553. };
  554. var foundIndex = -1;
  555. for (var i = 0; i < this.images.length; ++i) {
  556. if (this.images[i].uri === textureName) {
  557. foundIndex = i;
  558. break;
  559. }
  560. }
  561. if (foundIndex === -1) {
  562. this.images.push(glTFImage);
  563. glTFTexture.source = this.images.length - 1;
  564. this.textures.push({
  565. source: this.images.length - 1
  566. });
  567. textureInfo = {
  568. index: this.images.length - 1
  569. };
  570. }
  571. else {
  572. glTFTexture.source = foundIndex;
  573. textureInfo = {
  574. index: foundIndex
  575. };
  576. }
  577. }
  578. return textureInfo;
  579. };
  580. /**
  581. * Creates a bufferview based on the vertices type for the Babylon mesh
  582. * @param kind - Indicates the type of vertices data.
  583. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  584. * @param byteOffset - The offset from the buffer to start indexing from.
  585. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  586. * @param dataBuffer - The buffer to write the bufferview data to.
  587. * @returns bytelength of the bufferview data.
  588. */
  589. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  590. var bufferMesh = null;
  591. var byteLength = 0;
  592. if (babylonMesh instanceof BABYLON.Mesh) {
  593. bufferMesh = babylonMesh;
  594. }
  595. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  596. bufferMesh = babylonMesh.sourceMesh;
  597. }
  598. if (bufferMesh !== null) {
  599. var vertexBuffer = null;
  600. var vertexBufferOffset = null;
  601. var vertexData = null;
  602. var vertexStrideSize = null;
  603. if (bufferMesh.getVerticesDataKinds().indexOf(kind) > -1) {
  604. vertexBuffer = bufferMesh.getVertexBuffer(kind);
  605. vertexBufferOffset = vertexBuffer.getOffset();
  606. vertexData = vertexBuffer.getData();
  607. vertexStrideSize = vertexBuffer.getStrideSize();
  608. if (dataBuffer && vertexData) {
  609. byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem);
  610. byteOffset += byteLength;
  611. }
  612. else {
  613. var bufferViewName = null;
  614. switch (kind) {
  615. case BABYLON.VertexBuffer.PositionKind: {
  616. byteLength = vertexData.length * 4;
  617. bufferViewName = "Position - " + bufferMesh.name;
  618. break;
  619. }
  620. case BABYLON.VertexBuffer.NormalKind: {
  621. byteLength = vertexData.length * 4;
  622. bufferViewName = "Normal - " + bufferMesh.name;
  623. break;
  624. }
  625. case BABYLON.VertexBuffer.TangentKind: {
  626. byteLength = vertexData.length * 4;
  627. bufferViewName = "Tangent - " + bufferMesh.name;
  628. break;
  629. }
  630. case BABYLON.VertexBuffer.ColorKind: {
  631. byteLength = vertexData.length * 4;
  632. bufferViewName = "Color - " + bufferMesh.name;
  633. break;
  634. }
  635. case BABYLON.VertexBuffer.UVKind: {
  636. byteLength = vertexData.length * 4;
  637. bufferViewName = "TexCoord 0 - " + bufferMesh.name;
  638. break;
  639. }
  640. case BABYLON.VertexBuffer.UV2Kind: {
  641. byteLength = vertexData.length * 4;
  642. bufferViewName = "TexCoord 1 - " + bufferMesh.name;
  643. break;
  644. }
  645. default: {
  646. console.warn("Unsupported VertexBuffer kind: " + kind);
  647. }
  648. }
  649. if (bufferViewName !== null) {
  650. var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, bufferViewName);
  651. byteOffset += byteLength;
  652. this.bufferViews.push(bufferView);
  653. }
  654. }
  655. }
  656. }
  657. return byteLength;
  658. };
  659. /**
  660. * Sets data for the primitive attributes of each submesh
  661. * @param mesh - glTF Mesh object to store the primitive attribute information.
  662. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  663. * @param byteOffset - The offset in bytes of the buffer data.
  664. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  665. * @param dataBuffer - Buffer to write the attribute data to.
  666. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  667. */
  668. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  669. var bufferMesh = null;
  670. if (babylonMesh instanceof BABYLON.Mesh) {
  671. bufferMesh = babylonMesh;
  672. }
  673. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  674. bufferMesh = babylonMesh.sourceMesh;
  675. }
  676. var positionBufferViewIndex = null;
  677. var normalBufferViewIndex = null;
  678. var colorBufferViewIndex = null;
  679. var tangentBufferViewIndex = null;
  680. var texCoord0BufferViewIndex = null;
  681. var texCoord1BufferViewIndex = null;
  682. var indexBufferViewIndex = null;
  683. if (bufferMesh !== null) {
  684. // For each BabylonMesh, create bufferviews for each 'kind'
  685. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  686. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.PositionKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  687. positionBufferViewIndex = this.bufferViews.length - 1;
  688. }
  689. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  690. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.NormalKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  691. normalBufferViewIndex = this.bufferViews.length - 1;
  692. }
  693. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  694. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.ColorKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  695. colorBufferViewIndex = this.bufferViews.length - 1;
  696. }
  697. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  698. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.TangentKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  699. colorBufferViewIndex = this.bufferViews.length - 1;
  700. }
  701. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  702. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UVKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  703. texCoord0BufferViewIndex = this.bufferViews.length - 1;
  704. }
  705. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  706. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UV2Kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  707. texCoord1BufferViewIndex = this.bufferViews.length - 1;
  708. }
  709. if (bufferMesh.getTotalIndices() > 0) {
  710. var indices = bufferMesh.getIndices();
  711. if (dataBuffer) {
  712. var end = indices.length;
  713. var byteOff = byteOffset;
  714. for (var k = 0; k < end; ++k) {
  715. dataBuffer.setUint32(byteOff, indices[k], true);
  716. byteOff += 4;
  717. }
  718. byteOffset = byteOff;
  719. }
  720. else {
  721. var byteLength = indices.length * 4;
  722. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  723. byteOffset += byteLength;
  724. this.bufferViews.push(bufferView);
  725. indexBufferViewIndex = this.bufferViews.length - 1;
  726. }
  727. }
  728. }
  729. // go through all mesh primitives (submeshes)
  730. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  731. var submesh = babylonMesh.subMeshes[j];
  732. var meshPrimitive = { attributes: {} };
  733. if (bufferMesh !== null) {
  734. // Create a bufferview storing all the positions
  735. if (!dataBuffer) {
  736. // Loop through each attribute of the submesh (mesh primitive)
  737. if (positionBufferViewIndex !== null) {
  738. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  739. var positions = positionVertexBuffer.getData();
  740. var positionStrideSize = positionVertexBuffer.getStrideSize();
  741. // Create accessor
  742. var result = this.calculateMinMax(positions, 0, positions.length / positionStrideSize, positionStrideSize, useRightHandedSystem);
  743. var accessor = this.createAccessor(positionBufferViewIndex, "Position", "VEC3" /* VEC3 */, 5126 /* FLOAT */, positions.length / positionStrideSize, 0, result.min, result.max);
  744. this.accessors.push(accessor);
  745. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  746. }
  747. if (normalBufferViewIndex !== null) {
  748. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  749. var normals = normalVertexBuffer.getData();
  750. var normalStrideSize = normalVertexBuffer.getStrideSize();
  751. // Create accessor
  752. var accessor = this.createAccessor(normalBufferViewIndex, "Normal", "VEC3" /* VEC3 */, 5126 /* FLOAT */, normals.length / normalStrideSize);
  753. this.accessors.push(accessor);
  754. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  755. }
  756. if (tangentBufferViewIndex !== null) {
  757. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  758. var tangents = tangentVertexBuffer.getData();
  759. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  760. // Create accessor
  761. var accessor = this.createAccessor(tangentBufferViewIndex, "Tangent", "VEC4" /* VEC4 */, 5126 /* FLOAT */, tangents.length / tangentStrideSize);
  762. this.accessors.push(accessor);
  763. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  764. }
  765. if (colorBufferViewIndex !== null) {
  766. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  767. var colors = colorVertexBuffer.getData();
  768. var colorStrideSize = colorVertexBuffer.getStrideSize();
  769. // Create accessor
  770. var accessor = this.createAccessor(colorBufferViewIndex, "Color", "VEC4" /* VEC4 */, 5126 /* FLOAT */, colors.length / colorStrideSize);
  771. this.accessors.push(accessor);
  772. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  773. }
  774. if (texCoord0BufferViewIndex !== null) {
  775. // Create accessor
  776. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  777. var texCoord0s = texCoord0VertexBuffer.getData();
  778. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  779. var accessor = this.createAccessor(texCoord0BufferViewIndex, "Texture Coords 0", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord0s.length / texCoord0StrideSize);
  780. this.accessors.push(accessor);
  781. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  782. }
  783. if (texCoord1BufferViewIndex !== null) {
  784. // Create accessor
  785. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  786. var texCoord1s = texCoord1VertexBuffer.getData();
  787. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  788. var accessor = this.createAccessor(texCoord1BufferViewIndex, "Texture Coords 1", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord1s.length / texCoord1StrideSize);
  789. this.accessors.push(accessor);
  790. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  791. }
  792. if (indexBufferViewIndex) {
  793. // Create accessor
  794. var accessor = this.createAccessor(indexBufferViewIndex, "Indices", "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4);
  795. this.accessors.push(accessor);
  796. meshPrimitive.indices = this.accessors.length - 1;
  797. }
  798. }
  799. if (bufferMesh.material) {
  800. if (bufferMesh.material instanceof BABYLON.StandardMaterial) {
  801. console.warn("Standard Material is currently not fully supported/implemented in glTF serializer");
  802. var babylonStandardMaterial = bufferMesh.material;
  803. var glTFPbrMetallicRoughness = GLTF2._GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  804. var glTFMaterial = { name: babylonStandardMaterial.name };
  805. if (!babylonStandardMaterial.backFaceCulling) {
  806. glTFMaterial.doubleSided = true;
  807. }
  808. if (babylonStandardMaterial.diffuseTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  809. var glTFTexture = this.exportTexture(babylonStandardMaterial.diffuseTexture);
  810. if (glTFTexture !== null) {
  811. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  812. }
  813. }
  814. if (babylonStandardMaterial.bumpTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  815. var glTFTexture = this.exportTexture(babylonStandardMaterial.bumpTexture);
  816. if (glTFTexture) {
  817. glTFMaterial.normalTexture = glTFTexture;
  818. }
  819. }
  820. if (babylonStandardMaterial.emissiveTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  821. var glTFEmissiveTexture = this.exportTexture(babylonStandardMaterial.emissiveTexture);
  822. if (glTFEmissiveTexture) {
  823. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  824. }
  825. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  826. }
  827. if (babylonStandardMaterial.ambientTexture && bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  828. var glTFOcclusionTexture = this.exportTexture(babylonStandardMaterial.ambientTexture);
  829. if (glTFOcclusionTexture) {
  830. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  831. }
  832. }
  833. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  834. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  835. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  836. }
  837. else {
  838. console.warn("glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  839. }
  840. }
  841. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  842. this.materials.push(glTFMaterial);
  843. meshPrimitive.material = this.materials.length - 1;
  844. }
  845. else if (bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  846. var babylonPBRMaterial = bufferMesh.material;
  847. var glTFPbrMetallicRoughness = {};
  848. if (babylonPBRMaterial.baseColor) {
  849. glTFPbrMetallicRoughness.baseColorFactor = [
  850. babylonPBRMaterial.baseColor.r,
  851. babylonPBRMaterial.baseColor.g,
  852. babylonPBRMaterial.baseColor.b,
  853. babylonPBRMaterial.alpha
  854. ];
  855. }
  856. if (babylonPBRMaterial.baseTexture !== undefined) {
  857. var glTFTexture = this.exportTexture(babylonPBRMaterial.baseTexture);
  858. if (glTFTexture !== null) {
  859. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  860. }
  861. glTFPbrMetallicRoughness.baseColorTexture;
  862. }
  863. if (babylonPBRMaterial.metallic !== undefined) {
  864. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMaterial.metallic;
  865. }
  866. if (babylonPBRMaterial.roughness !== undefined) {
  867. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMaterial.roughness;
  868. }
  869. var glTFMaterial = {
  870. name: babylonPBRMaterial.name
  871. };
  872. if (babylonPBRMaterial.doubleSided) {
  873. glTFMaterial.doubleSided = babylonPBRMaterial.doubleSided;
  874. }
  875. if (babylonPBRMaterial.normalTexture) {
  876. var glTFTexture = this.exportTexture(babylonPBRMaterial.normalTexture);
  877. if (glTFTexture) {
  878. glTFMaterial.normalTexture = glTFTexture;
  879. }
  880. }
  881. if (babylonPBRMaterial.occlusionTexture) {
  882. var glTFTexture = this.exportTexture(babylonPBRMaterial.occlusionTexture);
  883. if (glTFTexture) {
  884. glTFMaterial.occlusionTexture = glTFTexture;
  885. if (babylonPBRMaterial.occlusionStrength !== undefined) {
  886. glTFMaterial.occlusionTexture.strength = babylonPBRMaterial.occlusionStrength;
  887. }
  888. }
  889. }
  890. if (babylonPBRMaterial.emissiveTexture) {
  891. var glTFTexture = this.exportTexture(babylonPBRMaterial.emissiveTexture);
  892. if (glTFTexture !== null) {
  893. glTFMaterial.emissiveTexture = glTFTexture;
  894. }
  895. }
  896. if (!babylonPBRMaterial.emissiveColor.equals(new BABYLON.Color3(0.0, 0.0, 0.0))) {
  897. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  898. }
  899. if (babylonPBRMaterial.transparencyMode) {
  900. var alphaMode = GLTF2._GLTFMaterial.GetAlphaMode(babylonPBRMaterial);
  901. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  902. glTFMaterial.alphaMode = alphaMode;
  903. if (alphaMode === "BLEND" /* BLEND */) {
  904. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  905. }
  906. }
  907. }
  908. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  909. this.materials.push(glTFMaterial);
  910. meshPrimitive.material = this.materials.length - 1;
  911. }
  912. else {
  913. console.warn("Material type is not yet implemented in glTF serializer: " + bufferMesh.material.name);
  914. }
  915. }
  916. mesh.primitives.push(meshPrimitive);
  917. }
  918. }
  919. return byteOffset;
  920. };
  921. /**
  922. * Creates a glTF scene based on the array of meshes.
  923. * Returns the the total byte offset.
  924. * @param babylonScene - Babylon scene to get the mesh data from.
  925. * @param byteOffset - Offset to start from in bytes.
  926. * @param dataBuffer - Buffer to write geometry data to.
  927. * @returns bytelength + byteoffset
  928. */
  929. _Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  930. if (babylonScene.meshes.length > 0) {
  931. var babylonMeshes = babylonScene.meshes;
  932. var scene = { nodes: new Array() };
  933. for (var i = 0; i < babylonMeshes.length; ++i) {
  934. if (this.options &&
  935. this.options.shouldExportMesh !== undefined &&
  936. !this.options.shouldExportMesh(babylonMeshes[i])) {
  937. continue;
  938. }
  939. else {
  940. // create node to hold translation/rotation/scale and the mesh
  941. var node = { mesh: -1 };
  942. var babylonMesh = babylonMeshes[i];
  943. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  944. // Set transformation
  945. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  946. // create mesh
  947. var mesh = { primitives: new Array() };
  948. mesh.primitives = [];
  949. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  950. // go through all mesh primitives (submeshes)
  951. this.meshes.push(mesh);
  952. node.mesh = this.meshes.length - 1;
  953. if (babylonMesh.name) {
  954. node.name = babylonMesh.name;
  955. }
  956. this.nodes.push(node);
  957. scene.nodes.push(this.nodes.length - 1);
  958. }
  959. }
  960. this.scenes.push(scene);
  961. }
  962. return byteOffset;
  963. };
  964. return _Exporter;
  965. }());
  966. GLTF2._Exporter = _Exporter;
  967. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  968. })(BABYLON || (BABYLON = {}));
  969. //# sourceMappingURL=babylon.glTFExporter.js.map
  970. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  971. var BABYLON;
  972. (function (BABYLON) {
  973. /**
  974. * Class for holding and downloading glTF file data
  975. */
  976. var _GLTFData = /** @class */ (function () {
  977. /**
  978. * Initializes the glTF file object.
  979. */
  980. function _GLTFData() {
  981. this.glTFFiles = {};
  982. }
  983. /**
  984. * Downloads the glTF data as files based on their names and data.
  985. */
  986. _GLTFData.prototype.downloadFiles = function () {
  987. /**
  988. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  989. * @param str - Source string.
  990. * @param suffix - Suffix to search for in the source string.
  991. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  992. */
  993. function endsWith(str, suffix) {
  994. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  995. }
  996. for (var key in this.glTFFiles) {
  997. var link = document.createElement('a');
  998. document.body.appendChild(link);
  999. link.setAttribute("type", "hidden");
  1000. link.download = key;
  1001. var blob = this.glTFFiles[key];
  1002. var mimeType = void 0;
  1003. if (endsWith(key, ".glb")) {
  1004. mimeType = { type: "model/gltf-binary" };
  1005. }
  1006. else if (endsWith(key, ".bin")) {
  1007. mimeType = { type: "application/octet-stream" };
  1008. }
  1009. else if (endsWith(key, ".gltf")) {
  1010. mimeType = { type: "model/gltf+json" };
  1011. }
  1012. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1013. mimeType = { type: "image/jpeg" /* JPEG */ };
  1014. }
  1015. else if (endsWith(key, ".png")) {
  1016. mimeType = { type: "image/png" /* PNG */ };
  1017. }
  1018. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1019. link.click();
  1020. }
  1021. };
  1022. return _GLTFData;
  1023. }());
  1024. BABYLON._GLTFData = _GLTFData;
  1025. })(BABYLON || (BABYLON = {}));
  1026. //# sourceMappingURL=babylon.glTFData.js.map
  1027. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  1028. var BABYLON;
  1029. (function (BABYLON) {
  1030. var GLTF2;
  1031. (function (GLTF2) {
  1032. /**
  1033. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  1034. */
  1035. var _GLTFMaterial = /** @class */ (function () {
  1036. function _GLTFMaterial() {
  1037. }
  1038. /**
  1039. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  1040. * @param babylonStandardMaterial
  1041. * @returns - glTF Metallic Roughness Material representation
  1042. */
  1043. _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1044. var babylonSpecularGlossiness = {
  1045. diffuse: babylonStandardMaterial.diffuseColor,
  1046. opacity: babylonStandardMaterial.alpha,
  1047. specular: babylonStandardMaterial.specularColor || BABYLON.Color3.Black(),
  1048. glossiness: babylonStandardMaterial.specularPower / 256
  1049. };
  1050. if (babylonStandardMaterial.specularTexture) {
  1051. }
  1052. var babylonMetallicRoughness = _GLTFMaterial._ConvertToMetallicRoughness(babylonSpecularGlossiness);
  1053. var glTFPbrMetallicRoughness = {
  1054. baseColorFactor: [
  1055. babylonMetallicRoughness.baseColor.r,
  1056. babylonMetallicRoughness.baseColor.g,
  1057. babylonMetallicRoughness.baseColor.b,
  1058. babylonMetallicRoughness.opacity
  1059. ],
  1060. metallicFactor: babylonMetallicRoughness.metallic,
  1061. roughnessFactor: babylonMetallicRoughness.roughness
  1062. };
  1063. return glTFPbrMetallicRoughness;
  1064. };
  1065. /**
  1066. * Converts Specular Glossiness to Metallic Roughness. This is based on the algorithm used in the Babylon glTF 3ds Max Exporter.
  1067. * {@link https://github.com/BabylonJS/Exporters/blob/master/3ds%20Max/Max2Babylon/Exporter/BabylonExporter.GLTFExporter.Material.cs}
  1068. * @param babylonSpecularGlossiness - Babylon specular glossiness parameters
  1069. * @returns - Babylon metallic roughness values
  1070. */
  1071. _GLTFMaterial._ConvertToMetallicRoughness = function (babylonSpecularGlossiness) {
  1072. var diffuse = babylonSpecularGlossiness.diffuse;
  1073. var opacity = babylonSpecularGlossiness.opacity;
  1074. var specular = babylonSpecularGlossiness.specular;
  1075. var glossiness = BABYLON.Scalar.Clamp(babylonSpecularGlossiness.glossiness);
  1076. var oneMinusSpecularStrength = 1 - Math.max(specular.r, Math.max(specular.g, specular.b));
  1077. var diffusePerceivedBrightness = _GLTFMaterial.PerceivedBrightness(diffuse);
  1078. var specularPerceivedBrightness = _GLTFMaterial.PerceivedBrightness(specular);
  1079. var metallic = _GLTFMaterial.SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1080. var diffuseScaleFactor = oneMinusSpecularStrength / (1 - this.dielectricSpecular.r) / Math.max(1 - metallic, this.epsilon);
  1081. var baseColorFromDiffuse = diffuse.scale(diffuseScaleFactor);
  1082. var baseColorFromSpecular = specular.subtract(this.dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this.epsilon));
  1083. var lerpColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1084. var baseColor = new BABYLON.Color3();
  1085. lerpColor.clampToRef(0, 1, baseColor);
  1086. var babylonMetallicRoughness = {
  1087. baseColor: baseColor,
  1088. opacity: opacity,
  1089. metallic: metallic,
  1090. roughness: 1.0 - glossiness
  1091. };
  1092. return babylonMetallicRoughness;
  1093. };
  1094. /**
  1095. * Returns the perceived brightness value based on the provided color
  1096. * @param color - color used in calculating the perceived brightness
  1097. * @returns - perceived brightness value
  1098. */
  1099. _GLTFMaterial.PerceivedBrightness = function (color) {
  1100. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1101. };
  1102. /**
  1103. * Computes the metallic factor
  1104. * @param diffuse - diffused value
  1105. * @param specular - specular value
  1106. * @param oneMinusSpecularStrength - one minus the specular strength
  1107. * @returns - metallic value
  1108. */
  1109. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1110. if (specular < this.dielectricSpecular.r) {
  1111. return 0;
  1112. }
  1113. var a = this.dielectricSpecular.r;
  1114. var b = diffuse * oneMinusSpecularStrength / (1.0 - this.dielectricSpecular.r) + specular - 2.0 * this.dielectricSpecular.r;
  1115. var c = this.dielectricSpecular.r - specular;
  1116. var D = b * b - 4.0 * a * c;
  1117. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a));
  1118. };
  1119. /**
  1120. * Gets the glTF alpha mode from the Babylon Material
  1121. * @param babylonMaterial - Babylon Material
  1122. * @returns - The Babylon alpha mode value
  1123. */
  1124. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  1125. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1126. var babylonStandardMaterial = babylonMaterial;
  1127. if ((babylonStandardMaterial.alpha != 1.0) ||
  1128. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1129. (babylonStandardMaterial.opacityTexture != null)) {
  1130. return "BLEND" /* BLEND */;
  1131. }
  1132. else {
  1133. return "OPAQUE" /* OPAQUE */;
  1134. }
  1135. }
  1136. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1137. var babylonPBRMetallicRoughness = babylonMaterial;
  1138. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1139. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1140. return "OPAQUE" /* OPAQUE */;
  1141. }
  1142. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1143. return "BLEND" /* BLEND */;
  1144. }
  1145. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1146. return "MASK" /* MASK */;
  1147. }
  1148. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1149. console.warn("GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1150. return "BLEND" /* BLEND */;
  1151. }
  1152. default: {
  1153. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1154. }
  1155. }
  1156. }
  1157. else {
  1158. throw new Error("Unsupported Babylon material type");
  1159. }
  1160. };
  1161. /**
  1162. * Represents the dielectric specular values for R, G and B.
  1163. */
  1164. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1165. /**
  1166. * Epsilon value, used as a small tolerance value for a numeric value.
  1167. */
  1168. _GLTFMaterial.epsilon = 1e-6;
  1169. return _GLTFMaterial;
  1170. }());
  1171. GLTF2._GLTFMaterial = _GLTFMaterial;
  1172. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1173. })(BABYLON || (BABYLON = {}));
  1174. //# sourceMappingURL=babylon.glTFMaterial.js.map