babylon.glTF2Serializer.js 62 KB

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