babylon.glTF2Serializer.js 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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 ? false : true;
  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 byteOffset - The offset to start counting bytes from.
  193. * @param dataBuffer - The buffer to write the binary data to.
  194. * @returns - Byte length of the attribute data.
  195. */
  196. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteOffset, dataBuffer) {
  197. var byteOff = byteOffset;
  198. var stride = BABYLON.VertexBuffer.DeduceStride(vertexBufferKind);
  199. var end = meshAttributeArray.length / stride;
  200. var byteLength = 0;
  201. for (var k = 0; k < end; ++k) {
  202. var index = k * stride;
  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.equalsToFloats(0, 0, 0)) {
  413. node.translation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
  414. }
  415. if (!babylonMesh.scaling.equalsToFloats(1, 1, 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 vertexData = bufferMesh.getVerticesData(kind);
  445. if (vertexData) {
  446. if (dataBuffer && vertexData) { // write data to buffer
  447. byteLength = this.writeAttributeData(kind, vertexData, byteOffset, dataBuffer);
  448. byteOffset += byteLength;
  449. }
  450. else {
  451. byteLength = vertexData.length * 4;
  452. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, kind + " - " + bufferMesh.name);
  453. byteOffset += byteLength;
  454. this.bufferViews.push(bufferView);
  455. }
  456. }
  457. }
  458. return byteLength;
  459. };
  460. /**
  461. * Sets data for the primitive attributes of each submesh
  462. * @param mesh - glTF Mesh object to store the primitive attribute information.
  463. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  464. * @param byteOffset - The offset in bytes of the buffer data.
  465. * @param dataBuffer - Buffer to write the attribute data to.
  466. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  467. */
  468. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, dataBuffer) {
  469. var bufferMesh = null;
  470. if (babylonMesh instanceof BABYLON.Mesh) {
  471. bufferMesh = babylonMesh;
  472. }
  473. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  474. bufferMesh = babylonMesh.sourceMesh;
  475. }
  476. var attributeData = [
  477. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */ },
  478. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */ },
  479. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */ },
  480. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */ },
  481. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */ },
  482. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */ },
  483. ];
  484. var indexBufferViewIndex = null;
  485. if (bufferMesh) {
  486. // For each BabylonMesh, create bufferviews for each 'kind'
  487. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  488. var attribute = attributeData_1[_i];
  489. var attributeKind = attribute.kind;
  490. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  491. byteOffset += this.createBufferViewKind(attributeKind, babylonMesh, byteOffset, dataBuffer);
  492. attribute.bufferViewIndex = this.bufferViews.length - 1;
  493. }
  494. }
  495. if (bufferMesh.getTotalIndices()) {
  496. var indices = bufferMesh.getIndices();
  497. if (indices) {
  498. if (dataBuffer) {
  499. var end = indices.length;
  500. var byteOff = byteOffset;
  501. for (var k = 0; k < end; ++k) {
  502. dataBuffer.setUint32(byteOff, indices[k], true);
  503. byteOff += 4;
  504. }
  505. byteOffset = byteOff;
  506. }
  507. else {
  508. var byteLength = indices.length * 4;
  509. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  510. byteOffset += byteLength;
  511. this.bufferViews.push(bufferView);
  512. indexBufferViewIndex = this.bufferViews.length - 1;
  513. }
  514. }
  515. }
  516. if (babylonMesh.subMeshes) {
  517. var uvCoordsPresent = false;
  518. // go through all mesh primitives (submeshes)
  519. for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
  520. var submesh = _b[_a];
  521. var meshPrimitive = { attributes: {} };
  522. // Create a bufferview storing all the positions
  523. if (!dataBuffer) {
  524. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  525. var attribute = attributeData_2[_c];
  526. var attributeKind = attribute.kind;
  527. var vertexData = bufferMesh.getVerticesData(attributeKind);
  528. if (vertexData) {
  529. var stride = BABYLON.VertexBuffer.DeduceStride(attributeKind);
  530. var minMax = void 0;
  531. var min = null;
  532. var max = null;
  533. var bufferViewIndex = attribute.bufferViewIndex;
  534. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  535. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  536. minMax = this.calculateMinMaxPositions(vertexData, 0, vertexData.length / stride);
  537. min = minMax.min;
  538. max = minMax.max;
  539. }
  540. var accessor = this.createAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, min, max);
  541. this.accessors.push(accessor);
  542. switch (attributeKind) {
  543. case BABYLON.VertexBuffer.PositionKind: {
  544. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  545. break;
  546. }
  547. case BABYLON.VertexBuffer.NormalKind: {
  548. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  549. break;
  550. }
  551. case BABYLON.VertexBuffer.ColorKind: {
  552. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  553. break;
  554. }
  555. case BABYLON.VertexBuffer.TangentKind: {
  556. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  557. break;
  558. }
  559. case BABYLON.VertexBuffer.UVKind: {
  560. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  561. uvCoordsPresent = true;
  562. break;
  563. }
  564. case BABYLON.VertexBuffer.UV2Kind: {
  565. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  566. uvCoordsPresent = true;
  567. break;
  568. }
  569. default: {
  570. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  571. }
  572. }
  573. }
  574. }
  575. }
  576. if (indexBufferViewIndex) {
  577. // Create accessor
  578. var accessor = this.createAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  579. this.accessors.push(accessor);
  580. meshPrimitive.indices = this.accessors.length - 1;
  581. }
  582. }
  583. if (bufferMesh.material) {
  584. var materialIndex = null;
  585. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial || bufferMesh.material instanceof BABYLON.PBRMaterial) {
  586. materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  587. }
  588. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  589. var babylonMultiMaterial = bufferMesh.material;
  590. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  591. if (material) {
  592. materialIndex = babylonMesh.getScene().materials.indexOf(material);
  593. }
  594. }
  595. else {
  596. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  597. }
  598. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  599. if (uvCoordsPresent || !GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  600. meshPrimitive.material = materialIndex;
  601. }
  602. else {
  603. // If no texture coordinate information is present, make a copy of the material without the textures to be glTF compliant.
  604. var newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  605. this.materials.push(newMat);
  606. meshPrimitive.material = this.materials.length - 1;
  607. }
  608. }
  609. }
  610. mesh.primitives.push(meshPrimitive);
  611. }
  612. }
  613. }
  614. return byteOffset;
  615. };
  616. /**
  617. * Creates a glTF scene based on the array of meshes.
  618. * Returns the the total byte offset.
  619. * @param babylonScene - Babylon scene to get the mesh data from.
  620. * @param byteOffset - Offset to start from in bytes.
  621. * @returns bytelength + byteoffset
  622. */
  623. _Exporter.prototype.createScene = function (babylonScene, byteOffset) {
  624. if (babylonScene.meshes.length) {
  625. var babylonMeshes = babylonScene.meshes;
  626. var scene = { nodes: new Array() };
  627. GLTF2._GLTFMaterial._ConvertMaterialsToGLTF(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.materials, this.imageData, true);
  628. var result = this.createNodeMap(babylonScene, byteOffset);
  629. this.nodeMap = result.nodeMap;
  630. this.totalByteLength = result.byteOffset;
  631. this.binaryBuffer = new ArrayBuffer(this.totalByteLength);
  632. var dataBuffer = new DataView(this.binaryBuffer);
  633. for (var i = 0; i < babylonMeshes.length; ++i) {
  634. var babylonMesh = babylonMeshes[i];
  635. // Build Hierarchy with the node map.
  636. var glTFNodeIndex = this.nodeMap[babylonMesh.uniqueId];
  637. var glTFNode = this.nodes[glTFNodeIndex];
  638. if (!babylonMesh.parent) {
  639. if (this.options &&
  640. this.options.shouldExportMesh != undefined &&
  641. !this.options.shouldExportMesh(babylonMesh)) {
  642. BABYLON.Tools.Log("Omitting " + babylonMesh.name + " from scene.");
  643. }
  644. else {
  645. scene.nodes.push(glTFNodeIndex);
  646. }
  647. }
  648. var directDescendents = babylonMesh.getDescendants(true);
  649. if (!glTFNode.children && directDescendents && directDescendents.length) {
  650. glTFNode.children = [];
  651. for (var _i = 0, directDescendents_1 = directDescendents; _i < directDescendents_1.length; _i++) {
  652. var descendent = directDescendents_1[_i];
  653. glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
  654. }
  655. }
  656. var mesh = { primitives: new Array() };
  657. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  658. }
  659. this.scenes.push(scene);
  660. }
  661. return byteOffset;
  662. };
  663. /**
  664. * Creates a mapping of Node unique id to node index
  665. * @param scene - Babylon Scene.
  666. * @param byteOffset - The initial byte offset.
  667. * @returns - Node mapping of unique id to index.
  668. */
  669. _Exporter.prototype.createNodeMap = function (scene, byteOffset) {
  670. var nodeMap = {};
  671. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  672. var babylonMesh = _a[_i];
  673. var result = this.createNode(babylonMesh, byteOffset, null);
  674. this.nodes.push(result.node);
  675. nodeMap[babylonMesh.uniqueId] = this.nodes.length - 1;
  676. byteOffset = result.byteOffset;
  677. }
  678. return { nodeMap: nodeMap, byteOffset: byteOffset };
  679. };
  680. /**
  681. * Creates a glTF node from a Babylon mesh.
  682. * @param babylonMesh - Source Babylon mesh.
  683. * @param byteOffset - The initial byte offset.
  684. * @param dataBuffer - Buffer for storing geometry data.
  685. * @returns - Object containing an INode and byteoffset.
  686. */
  687. _Exporter.prototype.createNode = function (babylonMesh, byteOffset, dataBuffer) {
  688. // create node to hold translation/rotation/scale and the mesh
  689. var node = {};
  690. if (babylonMesh.name) {
  691. node.name = babylonMesh.name;
  692. }
  693. // Set transformation
  694. this.setNodeTransformation(node, babylonMesh);
  695. // create mesh
  696. var mesh = { primitives: new Array() };
  697. mesh.primitives = [];
  698. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  699. if (mesh.primitives.length) {
  700. this.meshes.push(mesh);
  701. node.mesh = this.meshes.length - 1;
  702. }
  703. return { node: node, byteOffset: byteOffset };
  704. };
  705. return _Exporter;
  706. }());
  707. GLTF2._Exporter = _Exporter;
  708. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  709. })(BABYLON || (BABYLON = {}));
  710. //# sourceMappingURL=babylon.glTFExporter.js.map
  711. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  712. var BABYLON;
  713. (function (BABYLON) {
  714. /**
  715. * Class for holding and downloading glTF file data
  716. */
  717. var _GLTFData = /** @class */ (function () {
  718. /**
  719. * Initializes the glTF file object.
  720. */
  721. function _GLTFData() {
  722. this.glTFFiles = {};
  723. }
  724. /**
  725. * Downloads the glTF data as files based on their names and data.
  726. */
  727. _GLTFData.prototype.downloadFiles = function () {
  728. /**
  729. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  730. * @param str - Source string.
  731. * @param suffix - Suffix to search for in the source string.
  732. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  733. */
  734. function endsWith(str, suffix) {
  735. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  736. }
  737. for (var key in this.glTFFiles) {
  738. var link = document.createElement('a');
  739. document.body.appendChild(link);
  740. link.setAttribute("type", "hidden");
  741. link.download = key;
  742. var blob = this.glTFFiles[key];
  743. var mimeType = void 0;
  744. if (endsWith(key, ".glb")) {
  745. mimeType = { type: "model/gltf-binary" };
  746. }
  747. else if (endsWith(key, ".bin")) {
  748. mimeType = { type: "application/octet-stream" };
  749. }
  750. else if (endsWith(key, ".gltf")) {
  751. mimeType = { type: "model/gltf+json" };
  752. }
  753. else if (endsWith(key, ".jpeg" || ".jpg")) {
  754. mimeType = { type: "image/jpeg" /* JPEG */ };
  755. }
  756. else if (endsWith(key, ".png")) {
  757. mimeType = { type: "image/png" /* PNG */ };
  758. }
  759. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  760. link.click();
  761. }
  762. };
  763. return _GLTFData;
  764. }());
  765. BABYLON._GLTFData = _GLTFData;
  766. })(BABYLON || (BABYLON = {}));
  767. //# sourceMappingURL=babylon.glTFData.js.map
  768. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  769. var BABYLON;
  770. (function (BABYLON) {
  771. var GLTF2;
  772. (function (GLTF2) {
  773. /**
  774. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  775. */
  776. var _GLTFMaterial = /** @class */ (function () {
  777. function _GLTFMaterial() {
  778. }
  779. /**
  780. * Specifies if two colors are approximately equal in value.
  781. * @param color1 - first color to compare to.
  782. * @param color2 - second color to compare to.
  783. * @param epsilon - threshold value
  784. */
  785. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  786. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  787. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  788. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  789. };
  790. /**
  791. * Gets the materials from a Babylon scene and converts them to glTF materials.
  792. * @param scene - babylonjs scene.
  793. * @param mimeType - texture mime type.
  794. * @param images - array of images.
  795. * @param textures - array of textures.
  796. * @param materials - array of materials.
  797. * @param imageData - mapping of texture names to base64 textures
  798. * @param hasTextureCoords - specifies if texture coordinates are present on the material.
  799. */
  800. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  801. for (var i = 0; i < babylonMaterials.length; ++i) {
  802. var babylonMaterial = babylonMaterials[i];
  803. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  804. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  805. }
  806. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  807. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  808. }
  809. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  810. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  811. }
  812. else {
  813. throw new Error("Unsupported material type: " + babylonMaterial.name);
  814. }
  815. }
  816. };
  817. /**
  818. * Makes a copy of the glTF material without the texture parameters.
  819. * @param originalMaterial - original glTF material.
  820. * @returns glTF material without texture parameters
  821. */
  822. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  823. var newMaterial = {};
  824. if (originalMaterial) {
  825. newMaterial.name = originalMaterial.name;
  826. newMaterial.doubleSided = originalMaterial.doubleSided;
  827. newMaterial.alphaMode = originalMaterial.alphaMode;
  828. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  829. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  830. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  831. if (originalPBRMetallicRoughness) {
  832. newMaterial.pbrMetallicRoughness = {};
  833. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  834. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  835. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  836. }
  837. }
  838. return newMaterial;
  839. };
  840. /**
  841. * Specifies if the material has any texture parameters present.
  842. * @param material - glTF Material.
  843. * @returns boolean specifying if texture parameters are present
  844. */
  845. _GLTFMaterial._HasTexturesPresent = function (material) {
  846. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  847. return true;
  848. }
  849. var pbrMat = material.pbrMetallicRoughness;
  850. if (pbrMat) {
  851. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  852. return true;
  853. }
  854. }
  855. return false;
  856. };
  857. /**
  858. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  859. * @param babylonStandardMaterial
  860. * @returns - glTF Metallic Roughness Material representation
  861. */
  862. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  863. var P0 = new BABYLON.Vector2(0, 1);
  864. var P1 = new BABYLON.Vector2(0, 0.1);
  865. var P2 = new BABYLON.Vector2(0, 0.1);
  866. var P3 = new BABYLON.Vector2(1300, 0.1);
  867. /**
  868. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  869. * @param t - a value between 0 and 1.
  870. * @param p0 - first control point.
  871. * @param p1 - second control point.
  872. * @param p2 - third control point.
  873. * @param p3 - fourth control point.
  874. * @returns - number result of cubic bezier curve at the specified t.
  875. */
  876. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  877. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  878. 3 * (1 - t) * (1 - t) * t * p1 +
  879. 3 * (1 - t) * t * t * p2 +
  880. t * t * t * p3);
  881. }
  882. /**
  883. * Evaluates a specified specular power value to determine the appropriate roughness value,
  884. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  885. * and roughness on the ordinant axis (y-axis).
  886. * @param specularPower - specular power of standard material.
  887. * @returns - Number representing the roughness value.
  888. */
  889. function _solveForRoughness(specularPower) {
  890. var t = Math.pow(specularPower / P3.x, 0.333333);
  891. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  892. }
  893. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  894. var opacity = babylonStandardMaterial.alpha;
  895. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  896. var roughness = _solveForRoughness(specularPower);
  897. var glTFPbrMetallicRoughness = {
  898. baseColorFactor: [
  899. diffuse.r,
  900. diffuse.g,
  901. diffuse.b,
  902. opacity
  903. ],
  904. metallicFactor: 0,
  905. roughnessFactor: roughness,
  906. };
  907. return glTFPbrMetallicRoughness;
  908. };
  909. /**
  910. * Computes the metallic factor
  911. * @param diffuse - diffused value
  912. * @param specular - specular value
  913. * @param oneMinusSpecularStrength - one minus the specular strength
  914. * @returns - metallic value
  915. */
  916. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  917. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  918. _GLTFMaterial._dielectricSpecular;
  919. return 0;
  920. }
  921. var a = _GLTFMaterial._dielectricSpecular.r;
  922. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  923. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  924. var D = b * b - 4.0 * a * c;
  925. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  926. };
  927. /**
  928. * Gets the glTF alpha mode from the Babylon Material
  929. * @param babylonMaterial - Babylon Material
  930. * @returns - The Babylon alpha mode value
  931. */
  932. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  933. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  934. var babylonStandardMaterial = babylonMaterial;
  935. if ((babylonStandardMaterial.alpha != 1.0) ||
  936. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  937. (babylonStandardMaterial.opacityTexture != null)) {
  938. return "BLEND" /* BLEND */;
  939. }
  940. else {
  941. return "OPAQUE" /* OPAQUE */;
  942. }
  943. }
  944. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  945. var babylonPBRMetallicRoughness = babylonMaterial;
  946. switch (babylonPBRMetallicRoughness.transparencyMode) {
  947. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  948. return "OPAQUE" /* OPAQUE */;
  949. }
  950. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  951. return "BLEND" /* BLEND */;
  952. }
  953. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  954. return "MASK" /* MASK */;
  955. }
  956. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  957. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  958. return "BLEND" /* BLEND */;
  959. }
  960. default: {
  961. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  962. }
  963. }
  964. }
  965. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  966. var babylonPBRMaterial = babylonMaterial;
  967. switch (babylonPBRMaterial.transparencyMode) {
  968. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  969. return "OPAQUE" /* OPAQUE */;
  970. }
  971. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  972. return "BLEND" /* BLEND */;
  973. }
  974. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  975. return "MASK" /* MASK */;
  976. }
  977. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  978. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  979. return "BLEND" /* BLEND */;
  980. }
  981. default: {
  982. throw new Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  983. }
  984. }
  985. }
  986. else {
  987. throw new Error("Unsupported Babylon material type");
  988. }
  989. };
  990. /**
  991. * Converts a Babylon Standard Material to a glTF Material.
  992. * @param babylonStandardMaterial - BJS Standard Material.
  993. * @param mimeType - mime type to use for the textures.
  994. * @param images - array of glTF image interfaces.
  995. * @param textures - array of glTF texture interfaces.
  996. * @param materials - array of glTF material interfaces.
  997. * @param imageData - map of image file name to data.
  998. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  999. */
  1000. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1001. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1002. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1003. var glTFMaterial = { name: babylonStandardMaterial.name };
  1004. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1005. if (!babylonStandardMaterial.twoSidedLighting) {
  1006. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1007. }
  1008. glTFMaterial.doubleSided = true;
  1009. }
  1010. if (hasTextureCoords) {
  1011. if (babylonStandardMaterial.diffuseTexture) {
  1012. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1013. if (glTFTexture != null) {
  1014. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1015. }
  1016. }
  1017. if (babylonStandardMaterial.bumpTexture) {
  1018. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1019. if (glTFTexture) {
  1020. glTFMaterial.normalTexture = glTFTexture;
  1021. }
  1022. }
  1023. if (babylonStandardMaterial.emissiveTexture) {
  1024. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1025. if (glTFEmissiveTexture) {
  1026. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1027. }
  1028. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1029. }
  1030. if (babylonStandardMaterial.ambientTexture) {
  1031. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1032. if (glTFTexture) {
  1033. var occlusionTexture = {
  1034. index: glTFTexture.index
  1035. };
  1036. glTFMaterial.occlusionTexture = occlusionTexture;
  1037. occlusionTexture.strength = 1.0;
  1038. }
  1039. }
  1040. }
  1041. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1042. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1043. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1044. }
  1045. else {
  1046. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1047. }
  1048. }
  1049. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1050. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1051. }
  1052. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1053. materials.push(glTFMaterial);
  1054. };
  1055. /**
  1056. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1057. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1058. * @param mimeType - mime type to use for the textures.
  1059. * @param images - array of glTF image interfaces.
  1060. * @param textures - array of glTF texture interfaces.
  1061. * @param materials - array of glTF material interfaces.
  1062. * @param imageData - map of image file name to data.
  1063. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1064. */
  1065. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1066. var glTFPbrMetallicRoughness = {};
  1067. if (babylonPBRMetalRoughMaterial.baseColor) {
  1068. glTFPbrMetallicRoughness.baseColorFactor = [
  1069. babylonPBRMetalRoughMaterial.baseColor.r,
  1070. babylonPBRMetalRoughMaterial.baseColor.g,
  1071. babylonPBRMetalRoughMaterial.baseColor.b,
  1072. babylonPBRMetalRoughMaterial.alpha
  1073. ];
  1074. }
  1075. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1076. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1077. }
  1078. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1079. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1080. }
  1081. var glTFMaterial = {
  1082. name: babylonPBRMetalRoughMaterial.name
  1083. };
  1084. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1085. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1086. }
  1087. if (hasTextureCoords) {
  1088. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1089. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1090. if (glTFTexture != null) {
  1091. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1092. }
  1093. }
  1094. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1095. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1096. if (glTFTexture) {
  1097. glTFMaterial.normalTexture = glTFTexture;
  1098. }
  1099. }
  1100. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1101. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1102. if (glTFTexture) {
  1103. glTFMaterial.occlusionTexture = glTFTexture;
  1104. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1105. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1106. }
  1107. }
  1108. }
  1109. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1110. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1111. if (glTFTexture != null) {
  1112. glTFMaterial.emissiveTexture = glTFTexture;
  1113. }
  1114. }
  1115. }
  1116. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1117. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1118. }
  1119. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1120. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1121. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1122. glTFMaterial.alphaMode = alphaMode;
  1123. if (alphaMode === "BLEND" /* BLEND */) {
  1124. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1125. }
  1126. }
  1127. }
  1128. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1129. materials.push(glTFMaterial);
  1130. };
  1131. /**
  1132. * Converts an image typed array buffer to a base64 image.
  1133. * @param buffer - typed array buffer.
  1134. * @param width - width of the image.
  1135. * @param height - height of the image.
  1136. * @param mimeType - mimetype of the image.
  1137. * @returns - base64 image string.
  1138. */
  1139. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1140. var imageCanvas = document.createElement('canvas');
  1141. imageCanvas.id = "WriteCanvas";
  1142. var ctx = imageCanvas.getContext('2d');
  1143. imageCanvas.width = width;
  1144. imageCanvas.height = height;
  1145. var imgData = ctx.createImageData(width, height);
  1146. imgData.data.set(buffer);
  1147. ctx.putImageData(imgData, 0, 0);
  1148. return imageCanvas.toDataURL(mimeType);
  1149. };
  1150. /**
  1151. * Generates a white texture based on the specified width and height.
  1152. * @param width - width of the texture in pixels.
  1153. * @param height - height of the texture in pixels.
  1154. * @param scene - babylonjs scene.
  1155. * @returns - white texture.
  1156. */
  1157. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1158. var data = new Uint8Array(width * height * 4);
  1159. for (var i = 0; i < data.length; ++i) {
  1160. data[i] = 255;
  1161. }
  1162. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1163. return rawTexture;
  1164. };
  1165. /**
  1166. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null.
  1167. * @param texture1 - first texture to resize.
  1168. * @param texture2 - second texture to resize.
  1169. * @param scene - babylonjs scene.
  1170. * @returns resized textures or null.
  1171. */
  1172. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1173. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1174. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1175. var resizedTexture1;
  1176. var resizedTexture2;
  1177. if (texture1Size.width < texture2Size.width) {
  1178. if (texture1) {
  1179. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1180. }
  1181. else {
  1182. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1183. }
  1184. resizedTexture2 = texture2;
  1185. }
  1186. else if (texture1Size.width > texture2Size.width) {
  1187. if (texture2) {
  1188. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1189. }
  1190. else {
  1191. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1192. }
  1193. resizedTexture1 = texture1;
  1194. }
  1195. else {
  1196. resizedTexture1 = texture1;
  1197. resizedTexture2 = texture2;
  1198. }
  1199. return {
  1200. "texture1": resizedTexture1,
  1201. "texture2": resizedTexture2
  1202. };
  1203. };
  1204. /**
  1205. * Convert Specular Glossiness Textures to Metallic Roughness.
  1206. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1207. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1208. * @param diffuseTexture - texture used to store diffuse information.
  1209. * @param specularGlossinessTexture - texture used to store specular and glossiness information.
  1210. * @param factors - specular glossiness material factors.
  1211. * @param mimeType - the mime type to use for the texture.
  1212. * @returns pbr metallic roughness interface or null.
  1213. */
  1214. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1215. if (!(diffuseTexture || specularGlossinessTexture)) {
  1216. return null;
  1217. }
  1218. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1219. if (!scene) {
  1220. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1221. }
  1222. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1223. var diffuseSize = resizedTextures.texture1.getSize();
  1224. var diffuseBuffer;
  1225. var specularGlossinessBuffer;
  1226. var width = diffuseSize.width;
  1227. var height = diffuseSize.height;
  1228. var pixels = (resizedTextures.texture1.readPixels());
  1229. if (pixels instanceof Uint8Array) {
  1230. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1231. }
  1232. else {
  1233. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1234. }
  1235. pixels = resizedTextures.texture2.readPixels();
  1236. if (pixels instanceof Uint8Array) {
  1237. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1238. }
  1239. else {
  1240. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1241. }
  1242. var byteLength = specularGlossinessBuffer.byteLength;
  1243. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1244. var baseColorBuffer = new Uint8Array(byteLength);
  1245. var strideSize = 4;
  1246. var maxBaseColor = BABYLON.Color3.Black();
  1247. var maxMetallic = 0;
  1248. var maxRoughness = 0;
  1249. for (var h = 0; h < height; ++h) {
  1250. for (var w = 0; w < width; ++w) {
  1251. var offset = (width * h + w) * strideSize;
  1252. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1253. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1254. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1255. var specularGlossiness = {
  1256. diffuseColor: diffuseColor,
  1257. specularColor: specularColor,
  1258. glossiness: glossiness
  1259. };
  1260. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1261. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1262. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1263. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1264. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1265. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1266. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1267. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1268. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1269. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1270. metallicRoughnessBuffer[offset] = 0;
  1271. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1272. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1273. metallicRoughnessBuffer[offset + 3] = 255;
  1274. }
  1275. }
  1276. // Retrieves the metallic roughness factors from the maximum texture values.
  1277. var metallicRoughnessFactors = {
  1278. baseColor: maxBaseColor,
  1279. metallic: maxMetallic,
  1280. roughness: maxRoughness
  1281. };
  1282. var writeOutMetallicRoughnessTexture = false;
  1283. var writeOutBaseColorTexture = false;
  1284. for (var h = 0; h < height; ++h) {
  1285. for (var w = 0; w < width; ++w) {
  1286. var destinationOffset = (width * h + w) * strideSize;
  1287. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1288. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1289. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1290. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1291. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  1292. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  1293. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  1294. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  1295. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1296. writeOutBaseColorTexture = true;
  1297. }
  1298. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1299. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1300. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1301. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1302. writeOutMetallicRoughnessTexture = true;
  1303. }
  1304. }
  1305. }
  1306. if (writeOutMetallicRoughnessTexture) {
  1307. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1308. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1309. }
  1310. if (writeOutBaseColorTexture) {
  1311. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1312. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1313. }
  1314. return metallicRoughnessFactors;
  1315. };
  1316. /**
  1317. * Converts specular glossiness material properties to metallic roughness.
  1318. * @param specularGlossiness - interface with specular glossiness material properties.
  1319. * @returns - interface with metallic roughness material properties.
  1320. */
  1321. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1322. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1323. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1324. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1325. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1326. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1327. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1328. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1329. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1330. var metallicRoughness = {
  1331. baseColor: baseColor,
  1332. metallic: metallic,
  1333. roughness: 1 - specularGlossiness.glossiness
  1334. };
  1335. return metallicRoughness;
  1336. };
  1337. /**
  1338. * Calculates the surface reflectance, independent of lighting conditions.
  1339. * @param color - Color source to calculate brightness from.
  1340. * @returns number representing the perceived brightness, or zero if color is undefined.
  1341. */
  1342. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1343. if (color) {
  1344. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1345. }
  1346. return 0;
  1347. };
  1348. /**
  1349. * Returns the maximum color component value.
  1350. * @param color
  1351. * @returns maximum color component value, or zero if color is null or undefined.
  1352. */
  1353. _GLTFMaterial._GetMaxComponent = function (color) {
  1354. if (color) {
  1355. return Math.max(color.r, Math.max(color.g, color.b));
  1356. }
  1357. return 0;
  1358. };
  1359. /**
  1360. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors.
  1361. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1362. * @param mimeType - mime type to use for the textures.
  1363. * @param images - array of glTF image interfaces.
  1364. * @param textures - array of glTF texture interfaces.
  1365. * @param glTFPbrMetallicRoughness - glTF PBR Metallic Roughness interface.
  1366. * @param imageData - map of image file name to data.
  1367. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1368. * @returns - glTF PBR Metallic Roughness factors.
  1369. */
  1370. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1371. var metallicRoughness = {
  1372. baseColor: babylonPBRMaterial.albedoColor,
  1373. metallic: babylonPBRMaterial.metallic,
  1374. roughness: babylonPBRMaterial.roughness
  1375. };
  1376. if (hasTextureCoords) {
  1377. if (babylonPBRMaterial.albedoTexture) {
  1378. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, imageData);
  1379. if (glTFTexture) {
  1380. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1381. }
  1382. }
  1383. if (babylonPBRMaterial.metallicTexture) {
  1384. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, imageData);
  1385. if (glTFTexture != null) {
  1386. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1387. }
  1388. }
  1389. }
  1390. return metallicRoughness;
  1391. };
  1392. /**
  1393. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors.
  1394. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1395. * @param mimeType - mime type to use for the textures.
  1396. * @param images - array of glTF image interfaces.
  1397. * @param textures - array of glTF texture interfaces.
  1398. * @param glTFPbrMetallicRoughness - glTF PBR Metallic Roughness interface.
  1399. * @param imageData - map of image file name to data.
  1400. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1401. * @returns - glTF PBR Metallic Roughness factors.
  1402. */
  1403. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1404. var specGloss = {
  1405. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  1406. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  1407. glossiness: babylonPBRMaterial.microSurface || 1,
  1408. };
  1409. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  1410. throw new Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  1411. }
  1412. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  1413. if (!metallicRoughnessFactors) {
  1414. metallicRoughnessFactors = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  1415. }
  1416. else {
  1417. if (hasTextureCoords) {
  1418. if (metallicRoughnessFactors.baseColorTextureBase64) {
  1419. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1420. if (glTFBaseColorTexture != null) {
  1421. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  1422. }
  1423. }
  1424. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  1425. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1426. if (glTFMRColorTexture != null) {
  1427. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. return metallicRoughnessFactors;
  1433. };
  1434. /**
  1435. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1436. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1437. * @param mimeType - mime type to use for the textures.
  1438. * @param images - array of glTF image interfaces.
  1439. * @param textures - array of glTF texture interfaces.
  1440. * @param materials - array of glTF material interfaces.
  1441. * @param imageData - map of image file name to data.
  1442. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1443. */
  1444. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1445. var glTFPbrMetallicRoughness = {};
  1446. var metallicRoughness;
  1447. var glTFMaterial = {
  1448. name: babylonPBRMaterial.name
  1449. };
  1450. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  1451. if (useMetallicRoughness) {
  1452. metallicRoughness = this._ConvertMetalRoughFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1453. }
  1454. else {
  1455. metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1456. }
  1457. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  1458. glTFPbrMetallicRoughness.baseColorFactor = [
  1459. metallicRoughness.baseColor.r,
  1460. metallicRoughness.baseColor.g,
  1461. metallicRoughness.baseColor.b,
  1462. babylonPBRMaterial.alpha
  1463. ];
  1464. }
  1465. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  1466. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  1467. }
  1468. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  1469. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  1470. }
  1471. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  1472. if (!babylonPBRMaterial.twoSidedLighting) {
  1473. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1474. }
  1475. glTFMaterial.doubleSided = true;
  1476. }
  1477. if (hasTextureCoords) {
  1478. if (babylonPBRMaterial.bumpTexture) {
  1479. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, imageData);
  1480. if (glTFTexture) {
  1481. glTFMaterial.normalTexture = glTFTexture;
  1482. }
  1483. }
  1484. if (babylonPBRMaterial.ambientTexture) {
  1485. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, imageData);
  1486. if (glTFTexture) {
  1487. var occlusionTexture = {
  1488. index: glTFTexture.index
  1489. };
  1490. glTFMaterial.occlusionTexture = occlusionTexture;
  1491. if (babylonPBRMaterial.ambientTextureStrength) {
  1492. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  1493. }
  1494. }
  1495. }
  1496. if (babylonPBRMaterial.emissiveTexture) {
  1497. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1498. if (glTFTexture != null) {
  1499. glTFMaterial.emissiveTexture = glTFTexture;
  1500. }
  1501. }
  1502. }
  1503. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1504. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1505. }
  1506. if (babylonPBRMaterial.transparencyMode != null) {
  1507. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  1508. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1509. glTFMaterial.alphaMode = alphaMode;
  1510. if (alphaMode === "BLEND" /* BLEND */) {
  1511. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1512. }
  1513. }
  1514. }
  1515. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1516. materials.push(glTFMaterial);
  1517. };
  1518. /**
  1519. * Extracts a texture from a Babylon texture into file data and glTF data.
  1520. * @param babylonTexture - Babylon texture to extract.
  1521. * @param mimeType - Mime Type of the babylonTexture.
  1522. * @param images - Array of glTF images.
  1523. * @param textures - Array of glTF textures.
  1524. * @param imageData - map of image file name and data.
  1525. * @return - glTF texture info, or null if the texture format is not supported.
  1526. */
  1527. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1528. var textureName = "texture_" + (textures.length - 1).toString();
  1529. var textureData = babylonTexture.getInternalTexture();
  1530. if (textureData != null) {
  1531. textureName = textureData.url || textureName;
  1532. }
  1533. textureName = BABYLON.Tools.GetFilename(textureName);
  1534. var baseFile = textureName.split('.')[0];
  1535. var extension = "";
  1536. if (mimeType === "image/jpeg" /* JPEG */) {
  1537. extension = ".jpg";
  1538. }
  1539. else if (mimeType === "image/png" /* PNG */) {
  1540. extension = ".png";
  1541. }
  1542. else {
  1543. throw new Error("Unsupported mime type " + mimeType);
  1544. }
  1545. textureName = baseFile + extension;
  1546. var pixels = babylonTexture.readPixels();
  1547. var size = babylonTexture.getSize();
  1548. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  1549. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, imageData);
  1550. };
  1551. /**
  1552. * Builds a texture from base64 string.
  1553. * @param base64Texture - base64 texture string.
  1554. * @param textureName - Name to use for the texture.
  1555. * @param mimeType - image mime type for the texture.
  1556. * @param images - array of images.
  1557. * @param textures - array of textures.
  1558. * @param imageData - map of image data.
  1559. * @returns - glTF texture info, or null if the texture format is not supported.
  1560. */
  1561. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, imageData) {
  1562. var textureInfo = null;
  1563. var glTFTexture = {
  1564. source: images.length
  1565. };
  1566. var binStr = atob(base64Texture.split(',')[1]);
  1567. var arr = new Uint8Array(binStr.length);
  1568. for (var i = 0; i < binStr.length; ++i) {
  1569. arr[i] = binStr.charCodeAt(i);
  1570. }
  1571. var imageValues = { data: arr, mimeType: mimeType };
  1572. imageData[textureName] = imageValues;
  1573. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  1574. var glTFImage = {
  1575. uri: textureName
  1576. };
  1577. var foundIndex = -1;
  1578. for (var i = 0; i < images.length; ++i) {
  1579. if (images[i].uri === textureName) {
  1580. foundIndex = i;
  1581. break;
  1582. }
  1583. }
  1584. if (foundIndex === -1) {
  1585. images.push(glTFImage);
  1586. glTFTexture.source = images.length - 1;
  1587. textures.push({
  1588. source: images.length - 1
  1589. });
  1590. textureInfo = {
  1591. index: images.length - 1
  1592. };
  1593. }
  1594. else {
  1595. glTFTexture.source = foundIndex;
  1596. textureInfo = {
  1597. index: foundIndex
  1598. };
  1599. }
  1600. }
  1601. return textureInfo;
  1602. };
  1603. /**
  1604. * Represents the dielectric specular values for R, G and B.
  1605. */
  1606. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1607. /**
  1608. * Allows the maximum specular power to be defined for material calculations.
  1609. */
  1610. _GLTFMaterial._maxSpecularPower = 1024;
  1611. /**
  1612. * Numeric tolerance value
  1613. */
  1614. _GLTFMaterial._epsilon = 1e-6;
  1615. return _GLTFMaterial;
  1616. }());
  1617. GLTF2._GLTFMaterial = _GLTFMaterial;
  1618. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1619. })(BABYLON || (BABYLON = {}));
  1620. //# sourceMappingURL=babylon.glTFMaterial.js.map