babylonjs.serializers.js 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var BABYLON = root.BABYLON || this.BABYLON;
  4. if(typeof exports === 'object' && typeof module === 'object') {
  5. BABYLON = BABYLON || require("babylonjs");
  6. module.exports = factory(BABYLON);
  7. } else if(typeof define === 'function' && define.amd) {
  8. amdDependencies.push("babylonjs");
  9. define("babylonjs-serializers", amdDependencies, factory);
  10. } else if(typeof exports === 'object') {
  11. BABYLON = BABYLON || require("babylonjs");
  12. exports["babylonjs-serializers"] = factory(BABYLON);
  13. } else {
  14. root["BABYLON"] = factory(BABYLON);
  15. }
  16. })(this, function(BABYLON) {
  17. BABYLON = BABYLON || this.BABYLON;
  18. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  19. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var OBJExport = /** @class */ (function () {
  23. function OBJExport() {
  24. }
  25. //Exports the geometrys of a Mesh array in .OBJ file format (text)
  26. OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
  27. var output = [];
  28. var v = 1;
  29. if (materials) {
  30. if (!matlibname) {
  31. matlibname = 'mat';
  32. }
  33. output.push("mtllib " + matlibname + ".mtl");
  34. }
  35. for (var j = 0; j < mesh.length; j++) {
  36. output.push("g object" + j);
  37. output.push("o object_" + j);
  38. //Uses the position of the item in the scene, to the file (this back to normal in the end)
  39. var lastMatrix = null;
  40. if (globalposition) {
  41. var newMatrix = BABYLON.Matrix.Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
  42. lastMatrix = BABYLON.Matrix.Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
  43. mesh[j].bakeTransformIntoVertices(newMatrix);
  44. }
  45. //TODO: submeshes (groups)
  46. //TODO: smoothing groups (s 1, s off);
  47. if (materials) {
  48. var mat = mesh[j].material;
  49. if (mat) {
  50. output.push("usemtl " + mat.id);
  51. }
  52. }
  53. var g = mesh[j].geometry;
  54. if (!g) {
  55. continue;
  56. }
  57. var trunkVerts = g.getVerticesData('position');
  58. var trunkNormals = g.getVerticesData('normal');
  59. var trunkUV = g.getVerticesData('uv');
  60. var trunkFaces = g.getIndices();
  61. var curV = 0;
  62. if (!trunkVerts || !trunkNormals || !trunkUV || !trunkFaces) {
  63. continue;
  64. }
  65. for (var i = 0; i < trunkVerts.length; i += 3) {
  66. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  67. curV++;
  68. }
  69. for (i = 0; i < trunkNormals.length; i += 3) {
  70. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  71. }
  72. for (i = 0; i < trunkUV.length; i += 2) {
  73. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  74. }
  75. for (i = 0; i < trunkFaces.length; i += 3) {
  76. output.push("f " + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) +
  77. " " + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) +
  78. " " + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v));
  79. }
  80. //back de previous matrix, to not change the original mesh in the scene
  81. if (globalposition && lastMatrix) {
  82. mesh[j].bakeTransformIntoVertices(lastMatrix);
  83. }
  84. v += curV;
  85. }
  86. var text = output.join("\n");
  87. return (text);
  88. };
  89. //Exports the material(s) of a mesh in .MTL file format (text)
  90. //TODO: Export the materials of mesh array
  91. OBJExport.MTL = function (mesh) {
  92. var output = [];
  93. var m = mesh.material;
  94. output.push("newmtl mat1");
  95. output.push(" Ns " + m.specularPower.toFixed(4));
  96. output.push(" Ni 1.5000");
  97. output.push(" d " + m.alpha.toFixed(4));
  98. output.push(" Tr 0.0000");
  99. output.push(" Tf 1.0000 1.0000 1.0000");
  100. output.push(" illum 2");
  101. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  102. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  103. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  104. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  105. //TODO: uv scale, offset, wrap
  106. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  107. var uvscale = "";
  108. if (m.ambientTexture) {
  109. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  110. }
  111. if (m.diffuseTexture) {
  112. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  113. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  114. }
  115. if (m.specularTexture) {
  116. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  117. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  118. if (m.useGlossinessFromSpecularMapAlpha) {
  119. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  120. }
  121. */
  122. }
  123. /* TODO: emissive texture not in .MAT format (???)
  124. if (m.emissiveTexture) {
  125. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  126. }
  127. */
  128. if (m.bumpTexture) {
  129. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  130. }
  131. if (m.opacityTexture) {
  132. output.push(" map_d " + uvscale + m.opacityTexture.name);
  133. }
  134. var text = output.join("\n");
  135. return (text);
  136. };
  137. return OBJExport;
  138. }());
  139. BABYLON.OBJExport = OBJExport;
  140. })(BABYLON || (BABYLON = {}));
  141. //# sourceMappingURL=babylon.objSerializer.js.map
  142. var BABYLON;
  143. (function (BABYLON) {
  144. ;
  145. /**
  146. * Class for generating glTF data from a Babylon scene.
  147. */
  148. var GLTF2Export = /** @class */ (function () {
  149. function GLTF2Export() {
  150. }
  151. /**
  152. * Exports the geometry of the scene to .gltf file format.
  153. * @param scene - Babylon scene with scene hierarchy information.
  154. * @param filePrefix - File prefix to use when generating the glTF file.
  155. * @param options - Exporter options.
  156. * @returns - Returns an object with a .gltf file and associates texture names
  157. * as keys and their data and paths as values.
  158. */
  159. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  160. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  161. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  162. if (scene.isReady) {
  163. return gltfGenerator._generateGLTF(glTFPrefix);
  164. }
  165. else {
  166. throw new Error("glTF Serializer: Scene is not ready!");
  167. }
  168. };
  169. /**
  170. * Exports the geometry of the scene to .glb file format.
  171. * @param scene - Babylon scene with scene hierarchy information.
  172. * @param filePrefix - File prefix to use when generating glb file.
  173. * @param options - Exporter options.
  174. * @returns - Returns an object with a .glb filename as key and data as value
  175. */
  176. GLTF2Export.GLB = function (scene, filePrefix, options) {
  177. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  178. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  179. if (scene.isReady) {
  180. return gltfGenerator._generateGLB(glTFPrefix);
  181. }
  182. else {
  183. throw new Error("glTF Serializer: Scene is not ready!");
  184. }
  185. };
  186. return GLTF2Export;
  187. }());
  188. BABYLON.GLTF2Export = GLTF2Export;
  189. })(BABYLON || (BABYLON = {}));
  190. //# sourceMappingURL=babylon.glTFSerializer.js.map
  191. /**
  192. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
  193. * @ignore - capitalization of GLTF2 module.
  194. */
  195. var BABYLON;
  196. (function (BABYLON) {
  197. var GLTF2;
  198. (function (GLTF2) {
  199. /**
  200. * Converts Babylon Scene into glTF 2.0.
  201. */
  202. var _Exporter = /** @class */ (function () {
  203. /**
  204. * Creates a glTF Exporter instance, which can accept optional exporter options.
  205. * @param babylonScene - Babylon scene object
  206. * @param options - Options to modify the behavior of the exporter.
  207. */
  208. function _Exporter(babylonScene, options) {
  209. this.asset = { generator: "BabylonJS", version: "2.0" };
  210. this.babylonScene = babylonScene;
  211. this.bufferViews = new Array();
  212. this.accessors = new Array();
  213. this.meshes = new Array();
  214. this.scenes = new Array();
  215. this.nodes = new Array();
  216. this.images = new Array();
  217. this.materials = new Array();
  218. this.textures = new Array();
  219. this.imageData = {};
  220. this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
  221. if (options) {
  222. this.options = options;
  223. }
  224. }
  225. /**
  226. * Creates a buffer view based on teh supplied arguments
  227. * @param bufferIndex - index value of the specified buffer
  228. * @param byteOffset - byte offset value
  229. * @param byteLength - byte length of the bufferView
  230. * @param byteStride - byte distance between conequential elements.
  231. * @param name - name of the buffer view
  232. * @returns - bufferView for glTF
  233. */
  234. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  235. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  236. if (byteOffset) {
  237. bufferview.byteOffset = byteOffset;
  238. }
  239. if (name) {
  240. bufferview.name = name;
  241. }
  242. if (byteStride) {
  243. bufferview.byteStride = byteStride;
  244. }
  245. return bufferview;
  246. };
  247. /**
  248. * Creates an accessor based on the supplied arguments
  249. * @param bufferviewIndex - The index of the bufferview referenced by this accessor.
  250. * @param name - The name of the accessor.
  251. * @param type - The type of the accessor.
  252. * @param componentType - The datatype of components in the attribute.
  253. * @param count - The number of attributes referenced by this accessor.
  254. * @param byteOffset - The offset relative to the start of the bufferView in bytes.
  255. * @param min - Minimum value of each component in this attribute.
  256. * @param max - Maximum value of each component in this attribute.
  257. * @returns - accessor for glTF
  258. */
  259. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  260. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  261. if (min) {
  262. accessor.min = min;
  263. }
  264. if (max) {
  265. accessor.max = max;
  266. }
  267. if (byteOffset) {
  268. accessor.byteOffset = byteOffset;
  269. }
  270. return accessor;
  271. };
  272. /**
  273. * Calculates the minimum and maximum values of an array of position floats.
  274. * @param positions - Positions array of a mesh.
  275. * @param vertexStart - Starting vertex offset to calculate min and max values.
  276. * @param vertexCount - Number of vertices to check for min and max values.
  277. * @returns - min number array and max number array.
  278. */
  279. _Exporter.prototype.calculateMinMaxPositions = function (positions, vertexStart, vertexCount) {
  280. var min = [Infinity, Infinity, Infinity];
  281. var max = [-Infinity, -Infinity, -Infinity];
  282. var positionStrideSize = 3;
  283. var end = vertexStart + vertexCount;
  284. if (vertexCount) {
  285. for (var i = vertexStart; i < end; ++i) {
  286. var indexOffset = positionStrideSize * i;
  287. var position = BABYLON.Vector3.FromArray(positions, indexOffset);
  288. var vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(position).asArray() : position.asArray();
  289. for (var j = 0; j < positionStrideSize; ++j) {
  290. var num = vector[j];
  291. if (num < min[j]) {
  292. min[j] = num;
  293. }
  294. if (num > max[j]) {
  295. max[j] = num;
  296. }
  297. ++indexOffset;
  298. }
  299. }
  300. }
  301. return { min: min, max: max };
  302. };
  303. /**
  304. * Converts a vector3 array to right-handed.
  305. * @param vector - vector3 Array to convert to right-handed.
  306. * @returns - right-handed Vector3 array.
  307. */
  308. _Exporter.GetRightHandedVector3 = function (vector) {
  309. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  310. };
  311. /**
  312. * Converts a vector4 array to right-handed.
  313. * @param vector - vector4 Array to convert to right-handed.
  314. * @returns - right-handed vector4 array.
  315. */
  316. _Exporter.GetRightHandedVector4 = function (vector) {
  317. return new BABYLON.Vector4(vector.x, vector.y, -vector.z, -vector.w);
  318. };
  319. /**
  320. * Converts a quaternion to right-handed.
  321. * @param quaternion - Source quaternion to convert to right-handed.
  322. */
  323. _Exporter.GetRightHandedQuaternion = function (quaternion) {
  324. return new BABYLON.Quaternion(-quaternion.x, -quaternion.y, quaternion.z, quaternion.w);
  325. };
  326. /**
  327. * Writes mesh attribute data to a data buffer.
  328. * Returns the bytelength of the data.
  329. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  330. * @param meshAttributeArray - Array containing the attribute data.
  331. * @param byteOffset - The offset to start counting bytes from.
  332. * @param dataBuffer - The buffer to write the binary data to.
  333. * @returns - Byte length of the attribute data.
  334. */
  335. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteOffset, dataBuffer) {
  336. var byteOff = byteOffset;
  337. var stride = BABYLON.VertexBuffer.DeduceStride(vertexBufferKind);
  338. var end = meshAttributeArray.length / stride;
  339. var byteLength = 0;
  340. for (var k = 0; k < end; ++k) {
  341. var index = k * stride;
  342. var vector = [];
  343. if (vertexBufferKind === BABYLON.VertexBuffer.PositionKind || vertexBufferKind === BABYLON.VertexBuffer.NormalKind) {
  344. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  345. vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(vertexData).asArray() : vertexData.asArray();
  346. }
  347. else if (vertexBufferKind === BABYLON.VertexBuffer.TangentKind || vertexBufferKind === BABYLON.VertexBuffer.ColorKind) {
  348. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  349. vector = (this.convertToRightHandedSystem && !(vertexBufferKind === BABYLON.VertexBuffer.ColorKind)) ? _Exporter.GetRightHandedVector4(vertexData).asArray() : vertexData.asArray();
  350. }
  351. else if (vertexBufferKind === BABYLON.VertexBuffer.UVKind || vertexBufferKind === BABYLON.VertexBuffer.UV2Kind) {
  352. vector = [meshAttributeArray[index], meshAttributeArray[index + 1]];
  353. }
  354. else {
  355. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  356. }
  357. for (var i = 0; i < vector.length; ++i) {
  358. dataBuffer.setFloat32(byteOff, vector[i], true);
  359. byteOff += 4;
  360. }
  361. }
  362. byteLength = meshAttributeArray.length * 4;
  363. return byteLength;
  364. };
  365. /**
  366. * Generates glTF json data
  367. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  368. * @param glTFPrefix - Text to use when prefixing a glTF file.
  369. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  370. * @returns - json data as string
  371. */
  372. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  373. var buffer = { byteLength: this.totalByteLength };
  374. var glTF = {
  375. asset: this.asset
  376. };
  377. if (buffer.byteLength) {
  378. glTF.buffers = [buffer];
  379. }
  380. if (this.nodes && this.nodes.length) {
  381. glTF.nodes = this.nodes;
  382. }
  383. if (this.meshes && this.meshes.length) {
  384. glTF.meshes = this.meshes;
  385. }
  386. if (this.scenes && this.scenes.length) {
  387. glTF.scenes = this.scenes;
  388. glTF.scene = 0;
  389. }
  390. if (this.bufferViews && this.bufferViews.length) {
  391. glTF.bufferViews = this.bufferViews;
  392. }
  393. if (this.accessors && this.accessors.length) {
  394. glTF.accessors = this.accessors;
  395. }
  396. if (this.materials && this.materials.length) {
  397. glTF.materials = this.materials;
  398. }
  399. if (this.textures && this.textures.length) {
  400. glTF.textures = this.textures;
  401. }
  402. if (this.images && this.images.length) {
  403. if (!shouldUseGlb) {
  404. glTF.images = this.images;
  405. }
  406. else {
  407. glTF.images = [];
  408. // Replace uri with bufferview and mime type for glb
  409. var imageLength = this.images.length;
  410. var byteOffset = this.totalByteLength;
  411. for (var i = 0; i < imageLength; ++i) {
  412. var image = this.images[i];
  413. if (image.uri) {
  414. var imageData = this.imageData[image.uri];
  415. var imageName = image.uri.split('.')[0] + " image";
  416. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  417. byteOffset += imageData.data.buffer.byteLength;
  418. this.bufferViews.push(bufferView);
  419. image.bufferView = this.bufferViews.length - 1;
  420. image.name = imageName;
  421. image.mimeType = imageData.mimeType;
  422. image.uri = undefined;
  423. glTF.images.push(image);
  424. }
  425. }
  426. buffer.byteLength = byteOffset;
  427. }
  428. }
  429. if (!shouldUseGlb) {
  430. buffer.uri = glTFPrefix + ".bin";
  431. }
  432. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  433. return jsonText;
  434. };
  435. /**
  436. * Generates data for .gltf and .bin files based on the glTF prefix string
  437. * @param glTFPrefix - Text to use when prefixing a glTF file.
  438. * @returns - GLTFData with glTF file data.
  439. */
  440. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  441. var binaryBuffer = this.generateBinary();
  442. var jsonText = this.generateJSON(false, glTFPrefix, true);
  443. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  444. var glTFFileName = glTFPrefix + '.gltf';
  445. var glTFBinFile = glTFPrefix + '.bin';
  446. var container = new BABYLON._GLTFData();
  447. container.glTFFiles[glTFFileName] = jsonText;
  448. container.glTFFiles[glTFBinFile] = bin;
  449. if (this.imageData) {
  450. for (var image in this.imageData) {
  451. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  452. }
  453. }
  454. return container;
  455. };
  456. /**
  457. * Creates a binary buffer for glTF
  458. * @returns - array buffer for binary data
  459. */
  460. _Exporter.prototype.generateBinary = function () {
  461. var byteOffset = 0;
  462. byteOffset = this.createScene(this.babylonScene, byteOffset);
  463. return this.binaryBuffer;
  464. };
  465. /**
  466. * Pads the number to a multiple of 4
  467. * @param num - number to pad
  468. * @returns - padded number
  469. */
  470. _Exporter.prototype._getPadding = function (num) {
  471. var remainder = num % 4;
  472. var padding = remainder === 0 ? remainder : 4 - remainder;
  473. return padding;
  474. };
  475. /**
  476. * Generates a glb file from the json and binary data.
  477. * Returns an object with the glb file name as the key and data as the value.
  478. * @param glTFPrefix
  479. * @returns - object with glb filename as key and data as value
  480. */
  481. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  482. var binaryBuffer = this.generateBinary();
  483. var jsonText = this.generateJSON(true);
  484. var glbFileName = glTFPrefix + '.glb';
  485. var headerLength = 12;
  486. var chunkLengthPrefix = 8;
  487. var jsonLength = jsonText.length;
  488. var imageByteLength = 0;
  489. for (var key in this.imageData) {
  490. imageByteLength += this.imageData[key].data.byteLength;
  491. }
  492. var jsonPadding = this._getPadding(jsonLength);
  493. var binPadding = this._getPadding(binaryBuffer.byteLength);
  494. var imagePadding = this._getPadding(imageByteLength);
  495. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  496. //header
  497. var headerBuffer = new ArrayBuffer(headerLength);
  498. var headerBufferView = new DataView(headerBuffer);
  499. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  500. headerBufferView.setUint32(4, 2, true); // version
  501. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  502. //json chunk
  503. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  504. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  505. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  506. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  507. //json chunk bytes
  508. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  509. for (var i = 0; i < jsonLength; ++i) {
  510. jsonData[i] = jsonText.charCodeAt(i);
  511. }
  512. //json padding
  513. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  514. for (var i = 0; i < jsonPadding; ++i) {
  515. jsonPaddingView[i] = 0x20;
  516. }
  517. //binary chunk
  518. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  519. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  520. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  521. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  522. // binary padding
  523. var binPaddingBuffer = new ArrayBuffer(binPadding);
  524. var binPaddingView = new Uint8Array(binPaddingBuffer);
  525. for (var i = 0; i < binPadding; ++i) {
  526. binPaddingView[i] = 0;
  527. }
  528. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  529. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  530. for (var i = 0; i < imagePadding; ++i) {
  531. imagePaddingView[i] = 0;
  532. }
  533. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  534. // binary data
  535. for (var key in this.imageData) {
  536. glbData.push(this.imageData[key].data.buffer);
  537. }
  538. glbData.push(binPaddingBuffer);
  539. glbData.push(imagePaddingBuffer);
  540. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  541. var container = new BABYLON._GLTFData();
  542. container.glTFFiles[glbFileName] = glbFile;
  543. return container;
  544. };
  545. /**
  546. * Sets the TRS for each node
  547. * @param node - glTF Node for storing the transformation data.
  548. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  549. */
  550. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh) {
  551. if (!babylonMesh.position.equalsToFloats(0, 0, 0)) {
  552. node.translation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
  553. }
  554. if (!babylonMesh.scaling.equalsToFloats(1, 1, 1)) {
  555. node.scale = babylonMesh.scaling.asArray();
  556. }
  557. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  558. if (babylonMesh.rotationQuaternion) {
  559. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  560. }
  561. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  562. node.rotation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedQuaternion(rotationQuaternion).asArray() : rotationQuaternion.asArray();
  563. }
  564. };
  565. /**
  566. * Creates a bufferview based on the vertices type for the Babylon mesh
  567. * @param kind - Indicates the type of vertices data.
  568. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  569. * @param byteOffset - The offset from the buffer to start indexing from.
  570. * @param dataBuffer - The buffer to write the bufferview data to.
  571. * @returns bytelength of the bufferview data.
  572. */
  573. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, dataBuffer) {
  574. var bufferMesh = null;
  575. var byteLength = 0;
  576. if (babylonMesh instanceof BABYLON.Mesh) {
  577. bufferMesh = babylonMesh;
  578. }
  579. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  580. bufferMesh = babylonMesh.sourceMesh;
  581. }
  582. if (bufferMesh) {
  583. var vertexData = bufferMesh.getVerticesData(kind);
  584. if (vertexData) {
  585. if (dataBuffer && vertexData) { // write data to buffer
  586. byteLength = this.writeAttributeData(kind, vertexData, byteOffset, dataBuffer);
  587. byteOffset += byteLength;
  588. }
  589. else {
  590. byteLength = vertexData.length * 4;
  591. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, kind + " - " + bufferMesh.name);
  592. byteOffset += byteLength;
  593. this.bufferViews.push(bufferView);
  594. }
  595. }
  596. }
  597. return byteLength;
  598. };
  599. /**
  600. * Sets data for the primitive attributes of each submesh
  601. * @param mesh - glTF Mesh object to store the primitive attribute information.
  602. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  603. * @param byteOffset - The offset in bytes of the buffer data.
  604. * @param dataBuffer - Buffer to write the attribute data to.
  605. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  606. */
  607. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, dataBuffer) {
  608. var bufferMesh = null;
  609. if (babylonMesh instanceof BABYLON.Mesh) {
  610. bufferMesh = babylonMesh;
  611. }
  612. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  613. bufferMesh = babylonMesh.sourceMesh;
  614. }
  615. var attributeData = [
  616. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */ },
  617. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */ },
  618. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */ },
  619. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */ },
  620. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */ },
  621. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */ },
  622. ];
  623. var indexBufferViewIndex = null;
  624. if (bufferMesh) {
  625. // For each BabylonMesh, create bufferviews for each 'kind'
  626. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  627. var attribute = attributeData_1[_i];
  628. var attributeKind = attribute.kind;
  629. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  630. byteOffset += this.createBufferViewKind(attributeKind, babylonMesh, byteOffset, dataBuffer);
  631. attribute.bufferViewIndex = this.bufferViews.length - 1;
  632. }
  633. }
  634. if (bufferMesh.getTotalIndices()) {
  635. var indices = bufferMesh.getIndices();
  636. if (indices) {
  637. if (dataBuffer) {
  638. var end = indices.length;
  639. var byteOff = byteOffset;
  640. for (var k = 0; k < end; ++k) {
  641. dataBuffer.setUint32(byteOff, indices[k], true);
  642. byteOff += 4;
  643. }
  644. byteOffset = byteOff;
  645. }
  646. else {
  647. var byteLength = indices.length * 4;
  648. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  649. byteOffset += byteLength;
  650. this.bufferViews.push(bufferView);
  651. indexBufferViewIndex = this.bufferViews.length - 1;
  652. }
  653. }
  654. }
  655. if (babylonMesh.subMeshes) {
  656. var uvCoordsPresent = false;
  657. // go through all mesh primitives (submeshes)
  658. for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
  659. var submesh = _b[_a];
  660. var meshPrimitive = { attributes: {} };
  661. // Create a bufferview storing all the positions
  662. if (!dataBuffer) {
  663. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  664. var attribute = attributeData_2[_c];
  665. var attributeKind = attribute.kind;
  666. var vertexData = bufferMesh.getVerticesData(attributeKind);
  667. if (vertexData) {
  668. var stride = BABYLON.VertexBuffer.DeduceStride(attributeKind);
  669. var minMax = void 0;
  670. var min = null;
  671. var max = null;
  672. var bufferViewIndex = attribute.bufferViewIndex;
  673. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  674. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  675. minMax = this.calculateMinMaxPositions(vertexData, 0, vertexData.length / stride);
  676. min = minMax.min;
  677. max = minMax.max;
  678. }
  679. var accessor = this.createAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, min, max);
  680. this.accessors.push(accessor);
  681. switch (attributeKind) {
  682. case BABYLON.VertexBuffer.PositionKind: {
  683. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  684. break;
  685. }
  686. case BABYLON.VertexBuffer.NormalKind: {
  687. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  688. break;
  689. }
  690. case BABYLON.VertexBuffer.ColorKind: {
  691. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  692. break;
  693. }
  694. case BABYLON.VertexBuffer.TangentKind: {
  695. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  696. break;
  697. }
  698. case BABYLON.VertexBuffer.UVKind: {
  699. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  700. uvCoordsPresent = true;
  701. break;
  702. }
  703. case BABYLON.VertexBuffer.UV2Kind: {
  704. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  705. uvCoordsPresent = true;
  706. break;
  707. }
  708. default: {
  709. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  710. }
  711. }
  712. }
  713. }
  714. }
  715. if (indexBufferViewIndex) {
  716. // Create accessor
  717. var accessor = this.createAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  718. this.accessors.push(accessor);
  719. meshPrimitive.indices = this.accessors.length - 1;
  720. }
  721. }
  722. if (bufferMesh.material) {
  723. var materialIndex = null;
  724. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial || bufferMesh.material instanceof BABYLON.PBRMaterial) {
  725. materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  726. }
  727. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  728. var babylonMultiMaterial = bufferMesh.material;
  729. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  730. if (material) {
  731. materialIndex = babylonMesh.getScene().materials.indexOf(material);
  732. }
  733. }
  734. else {
  735. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  736. }
  737. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  738. if (uvCoordsPresent || !GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  739. meshPrimitive.material = materialIndex;
  740. }
  741. else {
  742. // If no texture coordinate information is present, make a copy of the material without the textures to be glTF compliant.
  743. var newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  744. this.materials.push(newMat);
  745. meshPrimitive.material = this.materials.length - 1;
  746. }
  747. }
  748. }
  749. mesh.primitives.push(meshPrimitive);
  750. }
  751. }
  752. }
  753. return byteOffset;
  754. };
  755. /**
  756. * Creates a glTF scene based on the array of meshes.
  757. * Returns the the total byte offset.
  758. * @param babylonScene - Babylon scene to get the mesh data from.
  759. * @param byteOffset - Offset to start from in bytes.
  760. * @returns bytelength + byteoffset
  761. */
  762. _Exporter.prototype.createScene = function (babylonScene, byteOffset) {
  763. if (babylonScene.meshes.length) {
  764. var babylonMeshes = babylonScene.meshes;
  765. var scene = { nodes: new Array() };
  766. GLTF2._GLTFMaterial._ConvertMaterialsToGLTF(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.materials, this.imageData, true);
  767. var result = this.createNodeMap(babylonScene, byteOffset);
  768. this.nodeMap = result.nodeMap;
  769. this.totalByteLength = result.byteOffset;
  770. this.binaryBuffer = new ArrayBuffer(this.totalByteLength);
  771. var dataBuffer = new DataView(this.binaryBuffer);
  772. for (var i = 0; i < babylonMeshes.length; ++i) {
  773. var babylonMesh = babylonMeshes[i];
  774. // Build Hierarchy with the node map.
  775. var glTFNodeIndex = this.nodeMap[babylonMesh.uniqueId];
  776. var glTFNode = this.nodes[glTFNodeIndex];
  777. if (!babylonMesh.parent) {
  778. if (this.options &&
  779. this.options.shouldExportMesh != undefined &&
  780. !this.options.shouldExportMesh(babylonMesh)) {
  781. BABYLON.Tools.Log("Omitting " + babylonMesh.name + " from scene.");
  782. }
  783. else {
  784. scene.nodes.push(glTFNodeIndex);
  785. }
  786. }
  787. var directDescendents = babylonMesh.getDescendants(true);
  788. if (!glTFNode.children && directDescendents && directDescendents.length) {
  789. glTFNode.children = [];
  790. for (var _i = 0, directDescendents_1 = directDescendents; _i < directDescendents_1.length; _i++) {
  791. var descendent = directDescendents_1[_i];
  792. glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
  793. }
  794. }
  795. var mesh = { primitives: new Array() };
  796. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  797. }
  798. this.scenes.push(scene);
  799. }
  800. return byteOffset;
  801. };
  802. /**
  803. * Creates a mapping of Node unique id to node index
  804. * @param scene - Babylon Scene.
  805. * @param byteOffset - The initial byte offset.
  806. * @returns - Node mapping of unique id to index.
  807. */
  808. _Exporter.prototype.createNodeMap = function (scene, byteOffset) {
  809. var nodeMap = {};
  810. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  811. var babylonMesh = _a[_i];
  812. var result = this.createNode(babylonMesh, byteOffset, null);
  813. this.nodes.push(result.node);
  814. nodeMap[babylonMesh.uniqueId] = this.nodes.length - 1;
  815. byteOffset = result.byteOffset;
  816. }
  817. return { nodeMap: nodeMap, byteOffset: byteOffset };
  818. };
  819. /**
  820. * Creates a glTF node from a Babylon mesh.
  821. * @param babylonMesh - Source Babylon mesh.
  822. * @param byteOffset - The initial byte offset.
  823. * @param dataBuffer - Buffer for storing geometry data.
  824. * @returns - Object containing an INode and byteoffset.
  825. */
  826. _Exporter.prototype.createNode = function (babylonMesh, byteOffset, dataBuffer) {
  827. // create node to hold translation/rotation/scale and the mesh
  828. var node = {};
  829. if (babylonMesh.name) {
  830. node.name = babylonMesh.name;
  831. }
  832. // Set transformation
  833. this.setNodeTransformation(node, babylonMesh);
  834. // create mesh
  835. var mesh = { primitives: new Array() };
  836. mesh.primitives = [];
  837. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  838. if (mesh.primitives.length) {
  839. this.meshes.push(mesh);
  840. node.mesh = this.meshes.length - 1;
  841. }
  842. return { node: node, byteOffset: byteOffset };
  843. };
  844. return _Exporter;
  845. }());
  846. GLTF2._Exporter = _Exporter;
  847. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  848. })(BABYLON || (BABYLON = {}));
  849. //# sourceMappingURL=babylon.glTFExporter.js.map
  850. var BABYLON;
  851. (function (BABYLON) {
  852. /**
  853. * Class for holding and downloading glTF file data
  854. */
  855. var _GLTFData = /** @class */ (function () {
  856. /**
  857. * Initializes the glTF file object.
  858. */
  859. function _GLTFData() {
  860. this.glTFFiles = {};
  861. }
  862. /**
  863. * Downloads the glTF data as files based on their names and data.
  864. */
  865. _GLTFData.prototype.downloadFiles = function () {
  866. /**
  867. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  868. * @param str - Source string.
  869. * @param suffix - Suffix to search for in the source string.
  870. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  871. */
  872. function endsWith(str, suffix) {
  873. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  874. }
  875. for (var key in this.glTFFiles) {
  876. var link = document.createElement('a');
  877. document.body.appendChild(link);
  878. link.setAttribute("type", "hidden");
  879. link.download = key;
  880. var blob = this.glTFFiles[key];
  881. var mimeType = void 0;
  882. if (endsWith(key, ".glb")) {
  883. mimeType = { type: "model/gltf-binary" };
  884. }
  885. else if (endsWith(key, ".bin")) {
  886. mimeType = { type: "application/octet-stream" };
  887. }
  888. else if (endsWith(key, ".gltf")) {
  889. mimeType = { type: "model/gltf+json" };
  890. }
  891. else if (endsWith(key, ".jpeg" || ".jpg")) {
  892. mimeType = { type: "image/jpeg" /* JPEG */ };
  893. }
  894. else if (endsWith(key, ".png")) {
  895. mimeType = { type: "image/png" /* PNG */ };
  896. }
  897. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  898. link.click();
  899. }
  900. };
  901. return _GLTFData;
  902. }());
  903. BABYLON._GLTFData = _GLTFData;
  904. })(BABYLON || (BABYLON = {}));
  905. //# sourceMappingURL=babylon.glTFData.js.map
  906. var BABYLON;
  907. (function (BABYLON) {
  908. var GLTF2;
  909. (function (GLTF2) {
  910. /**
  911. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  912. */
  913. var _GLTFMaterial = /** @class */ (function () {
  914. function _GLTFMaterial() {
  915. }
  916. /**
  917. * Specifies if two colors are approximately equal in value.
  918. * @param color1 - first color to compare to.
  919. * @param color2 - second color to compare to.
  920. * @param epsilon - threshold value
  921. */
  922. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  923. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  924. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  925. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  926. };
  927. /**
  928. * Gets the materials from a Babylon scene and converts them to glTF materials.
  929. * @param scene - babylonjs scene.
  930. * @param mimeType - texture mime type.
  931. * @param images - array of images.
  932. * @param textures - array of textures.
  933. * @param materials - array of materials.
  934. * @param imageData - mapping of texture names to base64 textures
  935. * @param hasTextureCoords - specifies if texture coordinates are present on the material.
  936. */
  937. _GLTFMaterial._ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  938. for (var i = 0; i < babylonMaterials.length; ++i) {
  939. var babylonMaterial = babylonMaterials[i];
  940. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  941. _GLTFMaterial._ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  942. }
  943. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  944. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  945. }
  946. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  947. _GLTFMaterial._ConvertPBRMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  948. }
  949. else {
  950. throw new Error("Unsupported material type: " + babylonMaterial.name);
  951. }
  952. }
  953. };
  954. /**
  955. * Makes a copy of the glTF material without the texture parameters.
  956. * @param originalMaterial - original glTF material.
  957. * @returns glTF material without texture parameters
  958. */
  959. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  960. var newMaterial = {};
  961. if (originalMaterial) {
  962. newMaterial.name = originalMaterial.name;
  963. newMaterial.doubleSided = originalMaterial.doubleSided;
  964. newMaterial.alphaMode = originalMaterial.alphaMode;
  965. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  966. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  967. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  968. if (originalPBRMetallicRoughness) {
  969. newMaterial.pbrMetallicRoughness = {};
  970. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  971. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  972. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  973. }
  974. }
  975. return newMaterial;
  976. };
  977. /**
  978. * Specifies if the material has any texture parameters present.
  979. * @param material - glTF Material.
  980. * @returns boolean specifying if texture parameters are present
  981. */
  982. _GLTFMaterial._HasTexturesPresent = function (material) {
  983. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  984. return true;
  985. }
  986. var pbrMat = material.pbrMetallicRoughness;
  987. if (pbrMat) {
  988. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  989. return true;
  990. }
  991. }
  992. return false;
  993. };
  994. /**
  995. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  996. * @param babylonStandardMaterial
  997. * @returns - glTF Metallic Roughness Material representation
  998. */
  999. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1000. var P0 = new BABYLON.Vector2(0, 1);
  1001. var P1 = new BABYLON.Vector2(0, 0.1);
  1002. var P2 = new BABYLON.Vector2(0, 0.1);
  1003. var P3 = new BABYLON.Vector2(1300, 0.1);
  1004. /**
  1005. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  1006. * @param t - a value between 0 and 1.
  1007. * @param p0 - first control point.
  1008. * @param p1 - second control point.
  1009. * @param p2 - third control point.
  1010. * @param p3 - fourth control point.
  1011. * @returns - number result of cubic bezier curve at the specified t.
  1012. */
  1013. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  1014. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1015. 3 * (1 - t) * (1 - t) * t * p1 +
  1016. 3 * (1 - t) * t * t * p2 +
  1017. t * t * t * p3);
  1018. }
  1019. /**
  1020. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1021. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1022. * and roughness on the ordinant axis (y-axis).
  1023. * @param specularPower - specular power of standard material.
  1024. * @returns - Number representing the roughness value.
  1025. */
  1026. function _solveForRoughness(specularPower) {
  1027. var t = Math.pow(specularPower / P3.x, 0.333333);
  1028. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1029. }
  1030. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1031. var opacity = babylonStandardMaterial.alpha;
  1032. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  1033. var roughness = _solveForRoughness(specularPower);
  1034. var glTFPbrMetallicRoughness = {
  1035. baseColorFactor: [
  1036. diffuse.r,
  1037. diffuse.g,
  1038. diffuse.b,
  1039. opacity
  1040. ],
  1041. metallicFactor: 0,
  1042. roughnessFactor: roughness,
  1043. };
  1044. return glTFPbrMetallicRoughness;
  1045. };
  1046. /**
  1047. * Computes the metallic factor
  1048. * @param diffuse - diffused value
  1049. * @param specular - specular value
  1050. * @param oneMinusSpecularStrength - one minus the specular strength
  1051. * @returns - metallic value
  1052. */
  1053. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1054. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  1055. _GLTFMaterial._dielectricSpecular;
  1056. return 0;
  1057. }
  1058. var a = _GLTFMaterial._dielectricSpecular.r;
  1059. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  1060. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  1061. var D = b * b - 4.0 * a * c;
  1062. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1063. };
  1064. /**
  1065. * Gets the glTF alpha mode from the Babylon Material
  1066. * @param babylonMaterial - Babylon Material
  1067. * @returns - The Babylon alpha mode value
  1068. */
  1069. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  1070. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1071. var babylonStandardMaterial = babylonMaterial;
  1072. if ((babylonStandardMaterial.alpha != 1.0) ||
  1073. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1074. (babylonStandardMaterial.opacityTexture != null)) {
  1075. return "BLEND" /* BLEND */;
  1076. }
  1077. else {
  1078. return "OPAQUE" /* OPAQUE */;
  1079. }
  1080. }
  1081. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1082. var babylonPBRMetallicRoughness = babylonMaterial;
  1083. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1084. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1085. return "OPAQUE" /* OPAQUE */;
  1086. }
  1087. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1088. return "BLEND" /* BLEND */;
  1089. }
  1090. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1091. return "MASK" /* MASK */;
  1092. }
  1093. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1094. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1095. return "BLEND" /* BLEND */;
  1096. }
  1097. default: {
  1098. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1099. }
  1100. }
  1101. }
  1102. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1103. var babylonPBRMaterial = babylonMaterial;
  1104. switch (babylonPBRMaterial.transparencyMode) {
  1105. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1106. return "OPAQUE" /* OPAQUE */;
  1107. }
  1108. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1109. return "BLEND" /* BLEND */;
  1110. }
  1111. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1112. return "MASK" /* MASK */;
  1113. }
  1114. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1115. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1116. return "BLEND" /* BLEND */;
  1117. }
  1118. default: {
  1119. throw new Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  1120. }
  1121. }
  1122. }
  1123. else {
  1124. throw new Error("Unsupported Babylon material type");
  1125. }
  1126. };
  1127. /**
  1128. * Converts a Babylon Standard Material to a glTF Material.
  1129. * @param babylonStandardMaterial - BJS Standard Material.
  1130. * @param mimeType - mime type to use for the textures.
  1131. * @param images - array of glTF image interfaces.
  1132. * @param textures - array of glTF texture interfaces.
  1133. * @param materials - array of glTF material interfaces.
  1134. * @param imageData - map of image file name to data.
  1135. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1136. */
  1137. _GLTFMaterial._ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1138. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1139. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1140. var glTFMaterial = { name: babylonStandardMaterial.name };
  1141. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1142. if (!babylonStandardMaterial.twoSidedLighting) {
  1143. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1144. }
  1145. glTFMaterial.doubleSided = true;
  1146. }
  1147. if (hasTextureCoords) {
  1148. if (babylonStandardMaterial.diffuseTexture) {
  1149. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1150. if (glTFTexture != null) {
  1151. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1152. }
  1153. }
  1154. if (babylonStandardMaterial.bumpTexture) {
  1155. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1156. if (glTFTexture) {
  1157. glTFMaterial.normalTexture = glTFTexture;
  1158. }
  1159. }
  1160. if (babylonStandardMaterial.emissiveTexture) {
  1161. var glTFEmissiveTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1162. if (glTFEmissiveTexture) {
  1163. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1164. }
  1165. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1166. }
  1167. if (babylonStandardMaterial.ambientTexture) {
  1168. var glTFTexture = _GLTFMaterial._ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1169. if (glTFTexture) {
  1170. var occlusionTexture = {
  1171. index: glTFTexture.index
  1172. };
  1173. glTFMaterial.occlusionTexture = occlusionTexture;
  1174. occlusionTexture.strength = 1.0;
  1175. }
  1176. }
  1177. }
  1178. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1179. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1180. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1181. }
  1182. else {
  1183. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1184. }
  1185. }
  1186. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1187. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1188. }
  1189. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1190. materials.push(glTFMaterial);
  1191. };
  1192. /**
  1193. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1194. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1195. * @param mimeType - mime type to use for the textures.
  1196. * @param images - array of glTF image interfaces.
  1197. * @param textures - array of glTF texture interfaces.
  1198. * @param materials - array of glTF material interfaces.
  1199. * @param imageData - map of image file name to data.
  1200. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1201. */
  1202. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1203. var glTFPbrMetallicRoughness = {};
  1204. if (babylonPBRMetalRoughMaterial.baseColor) {
  1205. glTFPbrMetallicRoughness.baseColorFactor = [
  1206. babylonPBRMetalRoughMaterial.baseColor.r,
  1207. babylonPBRMetalRoughMaterial.baseColor.g,
  1208. babylonPBRMetalRoughMaterial.baseColor.b,
  1209. babylonPBRMetalRoughMaterial.alpha
  1210. ];
  1211. }
  1212. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1213. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1214. }
  1215. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1216. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1217. }
  1218. var glTFMaterial = {
  1219. name: babylonPBRMetalRoughMaterial.name
  1220. };
  1221. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1222. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1223. }
  1224. if (hasTextureCoords) {
  1225. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1226. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1227. if (glTFTexture != null) {
  1228. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1229. }
  1230. }
  1231. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1232. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1233. if (glTFTexture) {
  1234. glTFMaterial.normalTexture = glTFTexture;
  1235. }
  1236. }
  1237. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1238. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1239. if (glTFTexture) {
  1240. glTFMaterial.occlusionTexture = glTFTexture;
  1241. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1242. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1243. }
  1244. }
  1245. }
  1246. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1247. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1248. if (glTFTexture != null) {
  1249. glTFMaterial.emissiveTexture = glTFTexture;
  1250. }
  1251. }
  1252. }
  1253. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1254. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1255. }
  1256. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1257. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1258. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1259. glTFMaterial.alphaMode = alphaMode;
  1260. if (alphaMode === "BLEND" /* BLEND */) {
  1261. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1262. }
  1263. }
  1264. }
  1265. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1266. materials.push(glTFMaterial);
  1267. };
  1268. /**
  1269. * Converts an image typed array buffer to a base64 image.
  1270. * @param buffer - typed array buffer.
  1271. * @param width - width of the image.
  1272. * @param height - height of the image.
  1273. * @param mimeType - mimetype of the image.
  1274. * @returns - base64 image string.
  1275. */
  1276. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1277. var imageCanvas = document.createElement('canvas');
  1278. imageCanvas.id = "WriteCanvas";
  1279. var ctx = imageCanvas.getContext('2d');
  1280. imageCanvas.width = width;
  1281. imageCanvas.height = height;
  1282. var imgData = ctx.createImageData(width, height);
  1283. imgData.data.set(buffer);
  1284. ctx.putImageData(imgData, 0, 0);
  1285. return imageCanvas.toDataURL(mimeType);
  1286. };
  1287. /**
  1288. * Generates a white texture based on the specified width and height.
  1289. * @param width - width of the texture in pixels.
  1290. * @param height - height of the texture in pixels.
  1291. * @param scene - babylonjs scene.
  1292. * @returns - white texture.
  1293. */
  1294. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1295. var data = new Uint8Array(width * height * 4);
  1296. for (var i = 0; i < data.length; ++i) {
  1297. data[i] = 255;
  1298. }
  1299. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1300. return rawTexture;
  1301. };
  1302. /**
  1303. * 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.
  1304. * @param texture1 - first texture to resize.
  1305. * @param texture2 - second texture to resize.
  1306. * @param scene - babylonjs scene.
  1307. * @returns resized textures or null.
  1308. */
  1309. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1310. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1311. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1312. var resizedTexture1;
  1313. var resizedTexture2;
  1314. if (texture1Size.width < texture2Size.width) {
  1315. if (texture1) {
  1316. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1317. }
  1318. else {
  1319. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1320. }
  1321. resizedTexture2 = texture2;
  1322. }
  1323. else if (texture1Size.width > texture2Size.width) {
  1324. if (texture2) {
  1325. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1326. }
  1327. else {
  1328. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1329. }
  1330. resizedTexture1 = texture1;
  1331. }
  1332. else {
  1333. resizedTexture1 = texture1;
  1334. resizedTexture2 = texture2;
  1335. }
  1336. return {
  1337. "texture1": resizedTexture1,
  1338. "texture2": resizedTexture2
  1339. };
  1340. };
  1341. /**
  1342. * Convert Specular Glossiness Textures to Metallic Roughness.
  1343. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1344. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1345. * @param diffuseTexture - texture used to store diffuse information.
  1346. * @param specularGlossinessTexture - texture used to store specular and glossiness information.
  1347. * @param factors - specular glossiness material factors.
  1348. * @param mimeType - the mime type to use for the texture.
  1349. * @returns pbr metallic roughness interface or null.
  1350. */
  1351. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1352. if (!(diffuseTexture || specularGlossinessTexture)) {
  1353. return null;
  1354. }
  1355. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture.getScene();
  1356. if (!scene) {
  1357. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1358. }
  1359. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1360. var diffuseSize = resizedTextures.texture1.getSize();
  1361. var diffuseBuffer;
  1362. var specularGlossinessBuffer;
  1363. var width = diffuseSize.width;
  1364. var height = diffuseSize.height;
  1365. var pixels = (resizedTextures.texture1.readPixels());
  1366. if (pixels instanceof Uint8Array) {
  1367. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1368. }
  1369. else {
  1370. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1371. }
  1372. pixels = resizedTextures.texture2.readPixels();
  1373. if (pixels instanceof Uint8Array) {
  1374. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1375. }
  1376. else {
  1377. throw new Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1378. }
  1379. var byteLength = specularGlossinessBuffer.byteLength;
  1380. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1381. var baseColorBuffer = new Uint8Array(byteLength);
  1382. var strideSize = 4;
  1383. var maxBaseColor = BABYLON.Color3.Black();
  1384. var maxMetallic = 0;
  1385. var maxRoughness = 0;
  1386. for (var h = 0; h < height; ++h) {
  1387. for (var w = 0; w < width; ++w) {
  1388. var offset = (width * h + w) * strideSize;
  1389. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1390. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1391. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1392. var specularGlossiness = {
  1393. diffuseColor: diffuseColor,
  1394. specularColor: specularColor,
  1395. glossiness: glossiness
  1396. };
  1397. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1398. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1399. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1400. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1401. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1402. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1403. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1404. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1405. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1406. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1407. metallicRoughnessBuffer[offset] = 0;
  1408. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1409. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1410. metallicRoughnessBuffer[offset + 3] = 255;
  1411. }
  1412. }
  1413. // Retrieves the metallic roughness factors from the maximum texture values.
  1414. var metallicRoughnessFactors = {
  1415. baseColor: maxBaseColor,
  1416. metallic: maxMetallic,
  1417. roughness: maxRoughness
  1418. };
  1419. var writeOutMetallicRoughnessTexture = false;
  1420. var writeOutBaseColorTexture = false;
  1421. for (var h = 0; h < height; ++h) {
  1422. for (var w = 0; w < width; ++w) {
  1423. var destinationOffset = (width * h + w) * strideSize;
  1424. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1425. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1426. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1427. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1428. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  1429. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  1430. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  1431. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  1432. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1433. writeOutBaseColorTexture = true;
  1434. }
  1435. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1436. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1437. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1438. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1439. writeOutMetallicRoughnessTexture = true;
  1440. }
  1441. }
  1442. }
  1443. if (writeOutMetallicRoughnessTexture) {
  1444. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1445. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1446. }
  1447. if (writeOutBaseColorTexture) {
  1448. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1449. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1450. }
  1451. return metallicRoughnessFactors;
  1452. };
  1453. /**
  1454. * Converts specular glossiness material properties to metallic roughness.
  1455. * @param specularGlossiness - interface with specular glossiness material properties.
  1456. * @returns - interface with metallic roughness material properties.
  1457. */
  1458. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1459. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1460. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1461. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1462. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1463. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1464. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1465. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1466. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1467. var metallicRoughness = {
  1468. baseColor: baseColor,
  1469. metallic: metallic,
  1470. roughness: 1 - specularGlossiness.glossiness
  1471. };
  1472. return metallicRoughness;
  1473. };
  1474. /**
  1475. * Calculates the surface reflectance, independent of lighting conditions.
  1476. * @param color - Color source to calculate brightness from.
  1477. * @returns number representing the perceived brightness, or zero if color is undefined.
  1478. */
  1479. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1480. if (color) {
  1481. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1482. }
  1483. return 0;
  1484. };
  1485. /**
  1486. * Returns the maximum color component value.
  1487. * @param color
  1488. * @returns maximum color component value, or zero if color is null or undefined.
  1489. */
  1490. _GLTFMaterial._GetMaxComponent = function (color) {
  1491. if (color) {
  1492. return Math.max(color.r, Math.max(color.g, color.b));
  1493. }
  1494. return 0;
  1495. };
  1496. /**
  1497. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors.
  1498. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1499. * @param mimeType - mime type to use for the textures.
  1500. * @param images - array of glTF image interfaces.
  1501. * @param textures - array of glTF texture interfaces.
  1502. * @param glTFPbrMetallicRoughness - glTF PBR Metallic Roughness interface.
  1503. * @param imageData - map of image file name to data.
  1504. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1505. * @returns - glTF PBR Metallic Roughness factors.
  1506. */
  1507. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1508. var metallicRoughness = {
  1509. baseColor: babylonPBRMaterial.albedoColor,
  1510. metallic: babylonPBRMaterial.metallic,
  1511. roughness: babylonPBRMaterial.roughness
  1512. };
  1513. if (hasTextureCoords) {
  1514. if (babylonPBRMaterial.albedoTexture) {
  1515. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.albedoTexture, mimeType, images, textures, imageData);
  1516. if (glTFTexture) {
  1517. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1518. }
  1519. }
  1520. if (babylonPBRMaterial.metallicTexture) {
  1521. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.metallicTexture, mimeType, images, textures, imageData);
  1522. if (glTFTexture != null) {
  1523. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  1524. }
  1525. }
  1526. }
  1527. return metallicRoughness;
  1528. };
  1529. /**
  1530. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors.
  1531. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1532. * @param mimeType - mime type to use for the textures.
  1533. * @param images - array of glTF image interfaces.
  1534. * @param textures - array of glTF texture interfaces.
  1535. * @param glTFPbrMetallicRoughness - glTF PBR Metallic Roughness interface.
  1536. * @param imageData - map of image file name to data.
  1537. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1538. * @returns - glTF PBR Metallic Roughness factors.
  1539. */
  1540. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1541. var specGloss = {
  1542. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  1543. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  1544. glossiness: babylonPBRMaterial.microSurface || 1,
  1545. };
  1546. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  1547. throw new Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture currently not supported");
  1548. }
  1549. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  1550. if (!metallicRoughnessFactors) {
  1551. metallicRoughnessFactors = this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  1552. }
  1553. else {
  1554. if (hasTextureCoords) {
  1555. if (metallicRoughnessFactors.baseColorTextureBase64) {
  1556. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1557. if (glTFBaseColorTexture != null) {
  1558. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  1559. }
  1560. }
  1561. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  1562. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, imageData);
  1563. if (glTFMRColorTexture != null) {
  1564. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  1565. }
  1566. }
  1567. }
  1568. }
  1569. return metallicRoughnessFactors;
  1570. };
  1571. /**
  1572. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1573. * @param babylonPBRMaterial - BJS PBR Metallic Roughness Material.
  1574. * @param mimeType - mime type to use for the textures.
  1575. * @param images - array of glTF image interfaces.
  1576. * @param textures - array of glTF texture interfaces.
  1577. * @param materials - array of glTF material interfaces.
  1578. * @param imageData - map of image file name to data.
  1579. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1580. */
  1581. _GLTFMaterial._ConvertPBRMaterial = function (babylonPBRMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1582. var glTFPbrMetallicRoughness = {};
  1583. var metallicRoughness;
  1584. var glTFMaterial = {
  1585. name: babylonPBRMaterial.name
  1586. };
  1587. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  1588. if (useMetallicRoughness) {
  1589. metallicRoughness = this._ConvertMetalRoughFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1590. }
  1591. else {
  1592. metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  1593. }
  1594. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  1595. glTFPbrMetallicRoughness.baseColorFactor = [
  1596. metallicRoughness.baseColor.r,
  1597. metallicRoughness.baseColor.g,
  1598. metallicRoughness.baseColor.b,
  1599. babylonPBRMaterial.alpha
  1600. ];
  1601. }
  1602. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  1603. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  1604. }
  1605. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  1606. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  1607. }
  1608. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  1609. if (!babylonPBRMaterial.twoSidedLighting) {
  1610. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1611. }
  1612. glTFMaterial.doubleSided = true;
  1613. }
  1614. if (hasTextureCoords) {
  1615. if (babylonPBRMaterial.bumpTexture) {
  1616. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.bumpTexture, mimeType, images, textures, imageData);
  1617. if (glTFTexture) {
  1618. glTFMaterial.normalTexture = glTFTexture;
  1619. }
  1620. }
  1621. if (babylonPBRMaterial.ambientTexture) {
  1622. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.ambientTexture, mimeType, images, textures, imageData);
  1623. if (glTFTexture) {
  1624. var occlusionTexture = {
  1625. index: glTFTexture.index
  1626. };
  1627. glTFMaterial.occlusionTexture = occlusionTexture;
  1628. if (babylonPBRMaterial.ambientTextureStrength) {
  1629. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  1630. }
  1631. }
  1632. }
  1633. if (babylonPBRMaterial.emissiveTexture) {
  1634. var glTFTexture = _GLTFMaterial._ExportTexture(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1635. if (glTFTexture != null) {
  1636. glTFMaterial.emissiveTexture = glTFTexture;
  1637. }
  1638. }
  1639. }
  1640. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1641. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  1642. }
  1643. if (babylonPBRMaterial.transparencyMode != null) {
  1644. var alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  1645. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1646. glTFMaterial.alphaMode = alphaMode;
  1647. if (alphaMode === "BLEND" /* BLEND */) {
  1648. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  1649. }
  1650. }
  1651. }
  1652. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1653. materials.push(glTFMaterial);
  1654. };
  1655. /**
  1656. * Extracts a texture from a Babylon texture into file data and glTF data.
  1657. * @param babylonTexture - Babylon texture to extract.
  1658. * @param mimeType - Mime Type of the babylonTexture.
  1659. * @param images - Array of glTF images.
  1660. * @param textures - Array of glTF textures.
  1661. * @param imageData - map of image file name and data.
  1662. * @return - glTF texture info, or null if the texture format is not supported.
  1663. */
  1664. _GLTFMaterial._ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1665. var textureName = "texture_" + (textures.length - 1).toString();
  1666. var textureData = babylonTexture.getInternalTexture();
  1667. if (textureData != null) {
  1668. textureName = textureData.url || textureName;
  1669. }
  1670. textureName = BABYLON.Tools.GetFilename(textureName);
  1671. var baseFile = textureName.split('.')[0];
  1672. var extension = "";
  1673. if (mimeType === "image/jpeg" /* JPEG */) {
  1674. extension = ".jpg";
  1675. }
  1676. else if (mimeType === "image/png" /* PNG */) {
  1677. extension = ".png";
  1678. }
  1679. else {
  1680. throw new Error("Unsupported mime type " + mimeType);
  1681. }
  1682. textureName = baseFile + extension;
  1683. var pixels = babylonTexture.readPixels();
  1684. var size = babylonTexture.getSize();
  1685. var base64Data = this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  1686. return this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, imageData);
  1687. };
  1688. /**
  1689. * Builds a texture from base64 string.
  1690. * @param base64Texture - base64 texture string.
  1691. * @param textureName - Name to use for the texture.
  1692. * @param mimeType - image mime type for the texture.
  1693. * @param images - array of images.
  1694. * @param textures - array of textures.
  1695. * @param imageData - map of image data.
  1696. * @returns - glTF texture info, or null if the texture format is not supported.
  1697. */
  1698. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, imageData) {
  1699. var textureInfo = null;
  1700. var glTFTexture = {
  1701. source: images.length
  1702. };
  1703. var binStr = atob(base64Texture.split(',')[1]);
  1704. var arr = new Uint8Array(binStr.length);
  1705. for (var i = 0; i < binStr.length; ++i) {
  1706. arr[i] = binStr.charCodeAt(i);
  1707. }
  1708. var imageValues = { data: arr, mimeType: mimeType };
  1709. imageData[textureName] = imageValues;
  1710. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  1711. var glTFImage = {
  1712. uri: textureName
  1713. };
  1714. var foundIndex = -1;
  1715. for (var i = 0; i < images.length; ++i) {
  1716. if (images[i].uri === textureName) {
  1717. foundIndex = i;
  1718. break;
  1719. }
  1720. }
  1721. if (foundIndex === -1) {
  1722. images.push(glTFImage);
  1723. glTFTexture.source = images.length - 1;
  1724. textures.push({
  1725. source: images.length - 1
  1726. });
  1727. textureInfo = {
  1728. index: images.length - 1
  1729. };
  1730. }
  1731. else {
  1732. glTFTexture.source = foundIndex;
  1733. textureInfo = {
  1734. index: foundIndex
  1735. };
  1736. }
  1737. }
  1738. return textureInfo;
  1739. };
  1740. /**
  1741. * Represents the dielectric specular values for R, G and B.
  1742. */
  1743. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1744. /**
  1745. * Allows the maximum specular power to be defined for material calculations.
  1746. */
  1747. _GLTFMaterial._maxSpecularPower = 1024;
  1748. /**
  1749. * Numeric tolerance value
  1750. */
  1751. _GLTFMaterial._epsilon = 1e-6;
  1752. return _GLTFMaterial;
  1753. }());
  1754. GLTF2._GLTFMaterial = _GLTFMaterial;
  1755. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1756. })(BABYLON || (BABYLON = {}));
  1757. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1758. return BABYLON;
  1759. });