babylonjs.serializers.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  2. var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || (typeof require !== 'undefined' && require("babylonjs"));
  3. var BABYLON = babylonDependency;
  4. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  5. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  6. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  8. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9. };
  10. var __extends = (this && this.__extends) || (function () {
  11. var extendStatics = Object.setPrototypeOf ||
  12. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  13. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  14. return function (d, b) {
  15. extendStatics(d, b);
  16. function __() { this.constructor = d; }
  17. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18. };
  19. })();
  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. var GLTF2Export = /** @class */ (function () {
  146. function GLTF2Export() {
  147. }
  148. /**
  149. * Exports the geometry of a Mesh array in .gltf file format.
  150. * @param meshes
  151. * @param materials
  152. * @param options
  153. *
  154. * @returns - Returns an object with a .gltf, .glb and associates textures
  155. * as keys and their data and paths as values.
  156. */
  157. GLTF2Export.GLTF = function (scene, filename, options) {
  158. var glTFPrefix = filename.replace(/\.[^/.]+$/, "");
  159. var gltfGenerator = new BABYLON._GLTF2Exporter(scene, options);
  160. if (scene.isReady) {
  161. return gltfGenerator._generateGLTF(glTFPrefix);
  162. }
  163. else {
  164. throw new Error("glTF Serializer: Scene is not ready!");
  165. }
  166. };
  167. /**
  168. *
  169. * @param meshes
  170. * @param filename
  171. *
  172. * @returns - Returns an object with a .glb filename as key and data as value
  173. */
  174. GLTF2Export.GLB = function (scene, filename, options) {
  175. var glTFPrefix = filename.replace(/\.[^/.]+$/, "");
  176. var gltfGenerator = new BABYLON._GLTF2Exporter(scene, options);
  177. if (scene.isReady) {
  178. return gltfGenerator._generateGLB(glTFPrefix);
  179. }
  180. else {
  181. throw new Error("glTF Serializer: Scene is not ready!");
  182. }
  183. };
  184. return GLTF2Export;
  185. }());
  186. BABYLON.GLTF2Export = GLTF2Export;
  187. })(BABYLON || (BABYLON = {}));
  188. //# sourceMappingURL=babylon.glTFSerializer.js.map
  189. var BABYLON;
  190. (function (BABYLON) {
  191. /**
  192. * glTF Image mimetype enum
  193. */
  194. var _EGLTFImageMimeTypeEnum;
  195. (function (_EGLTFImageMimeTypeEnum) {
  196. _EGLTFImageMimeTypeEnum["PNG"] = "image/png";
  197. _EGLTFImageMimeTypeEnum["JPG"] = "image/jpeg";
  198. })(_EGLTFImageMimeTypeEnum || (_EGLTFImageMimeTypeEnum = {}));
  199. /**
  200. * glTF Alpha Mode Enum
  201. */
  202. var _EGLTFAlphaModeEnum;
  203. (function (_EGLTFAlphaModeEnum) {
  204. _EGLTFAlphaModeEnum["OPAQUE"] = "OPAQUE";
  205. _EGLTFAlphaModeEnum["MASK"] = "MASK";
  206. _EGLTFAlphaModeEnum["BLEND"] = "BLEND";
  207. })(_EGLTFAlphaModeEnum = BABYLON._EGLTFAlphaModeEnum || (BABYLON._EGLTFAlphaModeEnum = {}));
  208. /**
  209. * Converts Babylon Scene into glTF 2.0
  210. */
  211. var _GLTF2Exporter = /** @class */ (function () {
  212. function _GLTF2Exporter(babylonScene, options) {
  213. this.asset = { generator: "BabylonJS", version: "2.0" };
  214. this.babylonScene = babylonScene;
  215. this.bufferViews = new Array();
  216. this.accessors = new Array();
  217. this.meshes = new Array();
  218. this.scenes = new Array();
  219. this.nodes = new Array();
  220. this.images = new Array();
  221. this.materials = new Array();
  222. this.imageData = {};
  223. if (options !== undefined) {
  224. this.options = options;
  225. }
  226. var totalByteLength = 0;
  227. totalByteLength = this.createScene(this.babylonScene, totalByteLength);
  228. this.totalByteLength = totalByteLength;
  229. }
  230. /**
  231. * Creates a buffer view based on teh supplied arguments
  232. * @param {number} bufferIndex - index value of the specified buffer
  233. * @param {number} byteOffset - byte offset value
  234. * @param {number} byteLength - byte length of the bufferView
  235. * @returns - bufferView for glTF
  236. */
  237. _GLTF2Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, name) {
  238. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  239. if (byteOffset > 0) {
  240. bufferview.byteOffset = byteOffset;
  241. }
  242. if (name) {
  243. bufferview.name = name;
  244. }
  245. return bufferview;
  246. };
  247. /**
  248. * Creates an accessor based on the supplied arguments
  249. * @param bufferviewIndex
  250. * @param name
  251. * @param type
  252. * @param componentType
  253. * @param count
  254. * @param min
  255. * @param max
  256. * @returns - accessor for glTF
  257. */
  258. _GLTF2Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, min, max) {
  259. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  260. if (min) {
  261. accessor.min = min;
  262. }
  263. if (max) {
  264. accessor.max = max;
  265. }
  266. return accessor;
  267. };
  268. /**
  269. * Calculates the minimum and maximum values of an array of floats, based on stride
  270. * @param buff
  271. * @param vertexStart
  272. * @param vertexCount
  273. * @param arrayOffset
  274. * @param stride
  275. * @returns - min number array and max number array
  276. */
  277. _GLTF2Exporter.prototype.calculateMinMax = function (buff, vertexStart, vertexCount, arrayOffset, stride) {
  278. var min = [Infinity, Infinity, Infinity];
  279. var max = [-Infinity, -Infinity, -Infinity];
  280. var end = vertexStart + vertexCount;
  281. if (vertexCount > 0) {
  282. for (var i = vertexStart; i < end; ++i) {
  283. var index = stride * i;
  284. for (var j = 0; j < stride; ++j) {
  285. if (buff[index] < min[j]) {
  286. min[j] = buff[index];
  287. }
  288. if (buff[index] > max[j]) {
  289. max[j] = buff[index];
  290. }
  291. ++index;
  292. }
  293. }
  294. }
  295. return { min: min, max: max };
  296. };
  297. /**
  298. * Write mesh attribute data to buffer.
  299. * Returns the bytelength of the data.
  300. * @param vertexBufferType
  301. * @param submesh
  302. * @param meshAttributeArray
  303. * @param strideSize
  304. * @param byteOffset
  305. * @param dataBuffer
  306. * @param useRightHandedSystem
  307. * @returns - byte length
  308. */
  309. _GLTF2Exporter.prototype.writeAttributeData = function (vertexBufferType, submesh, meshAttributeArray, strideSize, byteOffset, dataBuffer, useRightHandedSystem) {
  310. var byteOff = byteOffset;
  311. var end = submesh.verticesStart + submesh.verticesCount;
  312. var byteLength = 0;
  313. switch (vertexBufferType) {
  314. case BABYLON.VertexBuffer.PositionKind: {
  315. for (var k = submesh.verticesStart; k < end; ++k) {
  316. var index = k * strideSize;
  317. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  318. byteOff += 4;
  319. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  320. byteOff += 4;
  321. if (useRightHandedSystem) {
  322. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  323. }
  324. else {
  325. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  326. }
  327. byteOff += 4;
  328. }
  329. byteLength = submesh.verticesCount * 12;
  330. break;
  331. }
  332. case BABYLON.VertexBuffer.NormalKind: {
  333. for (var k = submesh.verticesStart; k < end; ++k) {
  334. var index = k * strideSize;
  335. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  336. byteOff += 4;
  337. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  338. byteOff += 4;
  339. if (useRightHandedSystem) {
  340. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  341. }
  342. else {
  343. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  344. }
  345. byteOff += 4;
  346. }
  347. byteLength = submesh.verticesCount * 12;
  348. break;
  349. }
  350. case BABYLON.VertexBuffer.TangentKind: {
  351. for (var k = submesh.indexStart; k < end; ++k) {
  352. var index = k * strideSize;
  353. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  354. byteOff += 4;
  355. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  356. byteOff += 4;
  357. if (useRightHandedSystem) {
  358. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  359. }
  360. else {
  361. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  362. }
  363. byteOff += 4;
  364. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  365. byteOff += 4;
  366. }
  367. byteLength = submesh.verticesCount * 16;
  368. break;
  369. }
  370. case BABYLON.VertexBuffer.ColorKind: {
  371. for (var k = submesh.verticesStart; k < end; ++k) {
  372. var index = k * strideSize;
  373. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  374. byteOff += 4;
  375. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  376. byteOff += 4;
  377. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  378. byteOff += 4;
  379. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  380. byteOff += 4;
  381. }
  382. byteLength = submesh.verticesCount * 16;
  383. break;
  384. }
  385. case BABYLON.VertexBuffer.UVKind: {
  386. for (var k = submesh.verticesStart; k < end; ++k) {
  387. var index = k * strideSize;
  388. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  389. byteOff += 4;
  390. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  391. byteOff += 4;
  392. }
  393. byteLength = submesh.verticesCount * 8;
  394. break;
  395. }
  396. case BABYLON.VertexBuffer.UV2Kind: {
  397. for (var k = submesh.verticesStart; k < end; ++k) {
  398. var index = k * strideSize;
  399. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  400. byteOff += 4;
  401. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  402. byteOff += 4;
  403. }
  404. byteLength = submesh.verticesCount * 8;
  405. break;
  406. }
  407. default: {
  408. throw new Error("Unsupported vertex buffer type: " + vertexBufferType);
  409. }
  410. }
  411. return byteLength;
  412. };
  413. /**
  414. * Generates glTF json data
  415. * @param glb
  416. * @param glTFPrefix
  417. * @param prettyPrint
  418. * @returns - json data as string
  419. */
  420. _GLTF2Exporter.prototype.generateJSON = function (glb, glTFPrefix, prettyPrint) {
  421. var buffer = { byteLength: this.totalByteLength };
  422. var glTF = {
  423. asset: this.asset
  424. };
  425. if (buffer.byteLength > 0) {
  426. glTF.buffers = [buffer];
  427. }
  428. if (this.nodes && this.nodes.length !== 0) {
  429. glTF.nodes = this.nodes;
  430. }
  431. if (this.meshes && this.meshes.length !== 0) {
  432. glTF.meshes = this.meshes;
  433. }
  434. if (this.scenes && this.scenes.length !== 0) {
  435. glTF.scenes = this.scenes;
  436. glTF.scene = 0;
  437. }
  438. if (this.bufferViews && this.bufferViews.length !== 0) {
  439. glTF.bufferViews = this.bufferViews;
  440. }
  441. if (this.accessors && this.accessors.length !== 0) {
  442. glTF.accessors = this.accessors;
  443. }
  444. if (this.materials && this.materials.length !== 0) {
  445. glTF.materials = this.materials;
  446. }
  447. if (this.textures && this.textures.length !== 0) {
  448. glTF.textures = this.textures;
  449. }
  450. if (this.images && this.images.length !== 0) {
  451. if (!glb) {
  452. glTF.images = this.images;
  453. }
  454. else {
  455. glTF.images = [];
  456. // Replace uri with bufferview and mime type for glb
  457. var imageLength = this.images.length;
  458. var byteOffset = this.totalByteLength;
  459. for (var i = 0; i < imageLength; ++i) {
  460. var image = this.images[i];
  461. if (image.uri !== undefined) {
  462. var imageData = this.imageData[image.uri];
  463. var imageName = image.uri.split('.')[0] + " image";
  464. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, imageName);
  465. byteOffset += imageData.data.buffer.byteLength;
  466. this.bufferViews.push(bufferView);
  467. image.bufferView = this.bufferViews.length - 1;
  468. image.name = imageName;
  469. image.mimeType = imageData.mimeType;
  470. image.uri = undefined;
  471. glTF.images.push(image);
  472. }
  473. }
  474. buffer.byteLength = byteOffset;
  475. }
  476. }
  477. if (!glb) {
  478. buffer.uri = glTFPrefix + ".bin";
  479. }
  480. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  481. return jsonText;
  482. };
  483. /**
  484. * Generates data for .gltf and .bin files based on the glTF prefix string
  485. * @param glTFPrefix
  486. * @returns - object with glTF json tex filename
  487. * and binary file name as keys and their data as values
  488. */
  489. _GLTF2Exporter.prototype._generateGLTF = function (glTFPrefix) {
  490. var jsonText = this.generateJSON(false, glTFPrefix, true);
  491. var binaryBuffer = this.generateBinary();
  492. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  493. var glTFFileName = glTFPrefix + '.gltf';
  494. var glTFBinFile = glTFPrefix + '.bin';
  495. var container = new BABYLON._GLTFData();
  496. container.glTFFiles[glTFFileName] = jsonText;
  497. container.glTFFiles[glTFBinFile] = bin;
  498. if (this.imageData !== null) {
  499. for (var image in this.imageData) {
  500. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  501. }
  502. }
  503. return container;
  504. };
  505. /**
  506. * Creates a binary buffer for glTF
  507. * @returns - array buffer for binary data
  508. */
  509. _GLTF2Exporter.prototype.generateBinary = function () {
  510. var byteOffset = 0;
  511. var binaryBuffer = new ArrayBuffer(this.totalByteLength);
  512. var dataBuffer = new DataView(binaryBuffer);
  513. byteOffset = this.createScene(this.babylonScene, byteOffset, dataBuffer);
  514. return binaryBuffer;
  515. };
  516. /**
  517. * Pads the number to a power of 4
  518. * @param num - number to pad
  519. * @returns - padded number
  520. */
  521. _GLTF2Exporter.prototype._getPadding = function (num) {
  522. var remainder = num % 4;
  523. var padding = remainder === 0 ? remainder : 4 - remainder;
  524. return padding;
  525. };
  526. /**
  527. * Generates a glb file from the json and binary data.
  528. * Returns an object with the glb file name as the key and data as the value.
  529. * @param jsonText
  530. * @param binaryBuffer
  531. * @param glTFPrefix
  532. * @returns - object with glb filename as key and data as value
  533. */
  534. _GLTF2Exporter.prototype._generateGLB = function (glTFPrefix) {
  535. var jsonText = this.generateJSON(true);
  536. var binaryBuffer = this.generateBinary();
  537. var glbFileName = glTFPrefix + '.glb';
  538. var headerLength = 12;
  539. var chunkLengthPrefix = 8;
  540. var jsonLength = jsonText.length;
  541. var imageByteLength = 0;
  542. for (var key in this.imageData) {
  543. imageByteLength += this.imageData[key].data.byteLength;
  544. }
  545. var jsonPadding = this._getPadding(jsonLength);
  546. var binPadding = this._getPadding(binaryBuffer.byteLength);
  547. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength;
  548. //header
  549. var headerBuffer = new ArrayBuffer(headerLength);
  550. var headerBufferView = new DataView(headerBuffer);
  551. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  552. headerBufferView.setUint32(4, 2, true); // version
  553. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  554. //json chunk
  555. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  556. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  557. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  558. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  559. //json chunk bytes
  560. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  561. for (var i = 0; i < jsonLength; ++i) {
  562. jsonData[i] = jsonText.charCodeAt(i);
  563. }
  564. //json padding
  565. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  566. for (var i = 0; i < jsonPadding; ++i) {
  567. jsonPaddingView[i] = 0x20;
  568. }
  569. //binary chunk
  570. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  571. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  572. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength, true);
  573. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  574. // binary padding
  575. var binPaddingBuffer = new ArrayBuffer(binPadding);
  576. var binPaddingView = new Uint8Array(binPaddingBuffer);
  577. for (var i = 0; i < binPadding; ++i) {
  578. binPaddingView[i] = 0;
  579. }
  580. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  581. // binary data
  582. for (var key in this.imageData) {
  583. glbData.push(this.imageData[key].data.buffer);
  584. }
  585. glbData.push(binPaddingBuffer);
  586. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  587. var container = new BABYLON._GLTFData();
  588. container.glTFFiles[glbFileName] = glbFile;
  589. return container;
  590. };
  591. /**
  592. * Sets the TRS for each node
  593. * @param node
  594. * @param babylonMesh
  595. * @param useRightHandedSystem
  596. */
  597. _GLTF2Exporter.prototype.setNodeTransformation = function (node, babylonMesh, useRightHandedSystem) {
  598. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  599. if (useRightHandedSystem) {
  600. node.translation = babylonMesh.position.asArray();
  601. }
  602. else {
  603. node.translation = [babylonMesh.position.x, babylonMesh.position.y, -babylonMesh.position.z];
  604. }
  605. }
  606. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  607. if (useRightHandedSystem) {
  608. node.scale = babylonMesh.scaling.asArray();
  609. }
  610. else {
  611. node.scale = [babylonMesh.scaling.x, babylonMesh.scaling.y, -babylonMesh.scaling.z];
  612. }
  613. }
  614. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  615. if (babylonMesh.rotationQuaternion) {
  616. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  617. }
  618. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  619. if (useRightHandedSystem) {
  620. node.rotation = rotationQuaternion.asArray();
  621. }
  622. else {
  623. node.rotation = [-rotationQuaternion.x, -rotationQuaternion.y, rotationQuaternion.z, rotationQuaternion.w];
  624. }
  625. }
  626. };
  627. /**
  628. *
  629. * @param babylonTexture
  630. * @return - glTF texture, or null if the texture format is not supported
  631. */
  632. _GLTF2Exporter.prototype.exportTexture = function (babylonTexture, mimeType) {
  633. if (mimeType === void 0) { mimeType = _EGLTFImageMimeTypeEnum.JPG; }
  634. var textureInfo = null;
  635. var glTFTexture;
  636. glTFTexture = {
  637. source: this.images.length
  638. };
  639. var textureName = babylonTexture.getInternalTexture().url;
  640. if (textureName.search('/') !== -1) {
  641. var splitFilename = textureName.split('/');
  642. textureName = splitFilename[splitFilename.length - 1];
  643. var basefile = textureName.split('.')[0];
  644. var extension = textureName.split('.')[1];
  645. if (mimeType === _EGLTFImageMimeTypeEnum.JPG) {
  646. extension = ".jpg";
  647. }
  648. else if (mimeType === _EGLTFImageMimeTypeEnum.PNG) {
  649. extension = ".png";
  650. }
  651. else {
  652. throw new Error("Unsupported mime type " + mimeType);
  653. }
  654. textureName = basefile + extension;
  655. }
  656. var pixels = babylonTexture.readPixels();
  657. var imageCanvas = document.createElement('canvas');
  658. imageCanvas.id = "ImageCanvas";
  659. var ctx = imageCanvas.getContext('2d');
  660. var size = babylonTexture.getSize();
  661. imageCanvas.width = size.width;
  662. imageCanvas.height = size.height;
  663. var imgData = ctx.createImageData(size.width, size.height);
  664. imgData.data.set(pixels);
  665. ctx.putImageData(imgData, 0, 0);
  666. var base64Data = imageCanvas.toDataURL(mimeType);
  667. var binStr = atob(base64Data.split(',')[1]);
  668. var arr = new Uint8Array(binStr.length);
  669. for (var i = 0; i < binStr.length; ++i) {
  670. arr[i] = binStr.charCodeAt(i);
  671. }
  672. var imageValues = { data: arr, mimeType: mimeType };
  673. this.imageData[textureName] = imageValues;
  674. if (mimeType === _EGLTFImageMimeTypeEnum.JPG) {
  675. var glTFImage = {
  676. uri: textureName
  677. };
  678. var foundIndex = -1;
  679. for (var i = 0; i < this.images.length; ++i) {
  680. if (this.images[i].uri === textureName) {
  681. foundIndex = i;
  682. break;
  683. }
  684. }
  685. if (foundIndex === -1) {
  686. this.images.push(glTFImage);
  687. glTFTexture.source = this.images.length - 1;
  688. this.textures.push({
  689. source: this.images.length - 1
  690. });
  691. textureInfo = {
  692. index: this.images.length - 1
  693. };
  694. }
  695. else {
  696. glTFTexture.source = foundIndex;
  697. textureInfo = {
  698. index: foundIndex
  699. };
  700. }
  701. }
  702. return textureInfo;
  703. };
  704. /**
  705. * Sets data for the primitive attributes of each submesh
  706. * @param mesh
  707. * @param babylonMesh
  708. * @param byteOffset
  709. * @param useRightHandedSystem
  710. * @param dataBuffer
  711. * @returns - bytelength of the primitive attributes plus the passed in byteOffset
  712. */
  713. _GLTF2Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  714. // go through all mesh primitives (submeshes)
  715. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  716. var bufferMesh = null;
  717. var submesh = babylonMesh.subMeshes[j];
  718. var meshPrimitive = { attributes: {} };
  719. if (babylonMesh instanceof BABYLON.Mesh) {
  720. bufferMesh = babylonMesh;
  721. }
  722. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  723. bufferMesh = babylonMesh.sourceMesh;
  724. }
  725. // Loop through each attribute of the submesh (mesh primitive)
  726. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  727. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  728. var positionVertexBufferOffset = positionVertexBuffer.getOffset();
  729. var positions = positionVertexBuffer.getData();
  730. var positionStrideSize = positionVertexBuffer.getStrideSize();
  731. if (dataBuffer) {
  732. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.PositionKind, submesh, positions, positionStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  733. }
  734. else {
  735. // Create bufferview
  736. var byteLength = submesh.verticesCount * 12;
  737. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Positions");
  738. byteOffset += byteLength;
  739. this.bufferViews.push(bufferview);
  740. // Create accessor
  741. var result = this.calculateMinMax(positions, submesh.verticesStart, submesh.verticesCount, positionVertexBufferOffset, positionStrideSize);
  742. var accessor = this.createAccessor(this.bufferViews.length - 1, "Position", "VEC3", 5126, submesh.verticesCount, result.min, result.max);
  743. this.accessors.push(accessor);
  744. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  745. }
  746. }
  747. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  748. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  749. var normals = normalVertexBuffer.getData();
  750. var normalStrideSize = normalVertexBuffer.getStrideSize();
  751. if (dataBuffer) {
  752. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.NormalKind, submesh, normals, normalStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  753. }
  754. else {
  755. // Create bufferview
  756. var byteLength = submesh.verticesCount * 12;
  757. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Normals");
  758. byteOffset += byteLength;
  759. this.bufferViews.push(bufferview);
  760. // Create accessor
  761. var accessor = this.createAccessor(this.bufferViews.length - 1, "Normal", "VEC3", 5126, submesh.verticesCount);
  762. this.accessors.push(accessor);
  763. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  764. }
  765. }
  766. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  767. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  768. var tangents = tangentVertexBuffer.getData();
  769. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  770. if (dataBuffer) {
  771. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.TangentKind, submesh, tangents, tangentStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  772. }
  773. else {
  774. // Create bufferview
  775. var byteLength = submesh.verticesCount * 16;
  776. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Tangents");
  777. byteOffset += byteLength;
  778. this.bufferViews.push(bufferview);
  779. // Create accessor
  780. var accessor = this.createAccessor(this.bufferViews.length - 1, "Tangent", "VEC4", 5126, submesh.verticesCount);
  781. this.accessors.push(accessor);
  782. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  783. }
  784. }
  785. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  786. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  787. var colors = colorVertexBuffer.getData();
  788. var colorStrideSize = colorVertexBuffer.getStrideSize();
  789. if (dataBuffer) {
  790. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.ColorKind, submesh, colors, colorStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  791. }
  792. else {
  793. // Create bufferview
  794. var byteLength = submesh.verticesCount * 16;
  795. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Colors");
  796. byteOffset += byteLength;
  797. this.bufferViews.push(bufferview);
  798. // Create accessor
  799. var accessor = this.createAccessor(this.bufferViews.length - 1, "Color", "VEC4", 5126, submesh.verticesCount);
  800. this.accessors.push(accessor);
  801. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  802. }
  803. }
  804. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  805. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  806. var texCoords0 = texCoord0VertexBuffer.getData();
  807. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  808. if (dataBuffer) {
  809. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.UVKind, submesh, texCoords0, texCoord0StrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  810. }
  811. else {
  812. // Create bufferview
  813. var byteLength = submesh.verticesCount * 8;
  814. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Texture Coords0");
  815. byteOffset += byteLength;
  816. this.bufferViews.push(bufferview);
  817. // Create accessor
  818. var accessor = this.createAccessor(this.bufferViews.length - 1, "Texture Coords", "VEC2", 5126, submesh.verticesCount);
  819. this.accessors.push(accessor);
  820. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  821. }
  822. }
  823. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  824. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  825. var texCoords1 = texCoord1VertexBuffer.getData();
  826. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  827. if (dataBuffer) {
  828. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.UV2Kind, submesh, texCoords1, texCoord1StrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  829. }
  830. else {
  831. // Create bufferview
  832. var byteLength = submesh.verticesCount * 8;
  833. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Texture Coords 1");
  834. byteOffset += byteLength;
  835. this.bufferViews.push(bufferview);
  836. // Create accessor
  837. var accessor = this.createAccessor(this.bufferViews.length - 1, "Texture Coords", "VEC2", 5126, submesh.verticesCount);
  838. this.accessors.push(accessor);
  839. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  840. }
  841. }
  842. if (bufferMesh.getTotalIndices() > 0) {
  843. if (dataBuffer) {
  844. var indices = bufferMesh.getIndices();
  845. var start = submesh.indexStart;
  846. var end = submesh.indexCount + start;
  847. var byteOff = byteOffset;
  848. for (var k = start; k < end; k = k + 3) {
  849. dataBuffer.setUint32(byteOff, indices[k], true);
  850. byteOff += 4;
  851. dataBuffer.setUint32(byteOff, indices[k + 1], true);
  852. byteOff += 4;
  853. dataBuffer.setUint32(byteOff, indices[k + 2], true);
  854. byteOff += 4;
  855. }
  856. var byteLength = submesh.indexCount * 4;
  857. byteOffset += byteLength;
  858. }
  859. else {
  860. // Create bufferview
  861. var indicesCount = submesh.indexCount;
  862. var byteLength = indicesCount * 4;
  863. var bufferview = this.createBufferView(0, byteOffset, byteLength, "Indices");
  864. byteOffset += byteLength;
  865. this.bufferViews.push(bufferview);
  866. // Create accessor
  867. var accessor = this.createAccessor(this.bufferViews.length - 1, "Indices", "SCALAR", 5125, indicesCount);
  868. this.accessors.push(accessor);
  869. meshPrimitive.indices = this.accessors.length - 1;
  870. }
  871. }
  872. if (bufferMesh.material) {
  873. if (bufferMesh.material instanceof BABYLON.StandardMaterial) {
  874. var babylonStandardMaterial = bufferMesh.material;
  875. var glTFMaterial = { name: babylonStandardMaterial.name };
  876. if (!babylonStandardMaterial.backFaceCulling) {
  877. glTFMaterial.doubleSided = true;
  878. }
  879. if (babylonStandardMaterial.bumpTexture) {
  880. var glTFTexture = this.exportTexture(babylonStandardMaterial.bumpTexture);
  881. if (glTFTexture) {
  882. glTFMaterial.normalTexture = glTFTexture;
  883. }
  884. }
  885. if (babylonStandardMaterial.emissiveTexture) {
  886. var glTFEmissiveTexture = this.exportTexture(babylonStandardMaterial.emissiveTexture);
  887. if (glTFEmissiveTexture) {
  888. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  889. }
  890. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  891. }
  892. if (babylonStandardMaterial.ambientTexture) {
  893. var glTFOcclusionTexture = this.exportTexture(babylonStandardMaterial.ambientTexture);
  894. if (glTFOcclusionTexture) {
  895. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  896. }
  897. }
  898. // Spec Gloss
  899. var babylonSpecularGlossiness = {
  900. diffuse: babylonStandardMaterial.diffuseColor,
  901. opacity: babylonStandardMaterial.alpha,
  902. specular: babylonStandardMaterial.specularColor || BABYLON.Color3.Black(),
  903. glossiness: babylonStandardMaterial.specularPower / 256
  904. };
  905. if (babylonStandardMaterial.specularTexture) {
  906. }
  907. var babylonMetallicRoughness = BABYLON._GLTFMaterial.ConvertToMetallicRoughness(babylonSpecularGlossiness);
  908. var glTFPbrMetallicRoughness = {
  909. baseColorFactor: [
  910. babylonMetallicRoughness.baseColor.r,
  911. babylonMetallicRoughness.baseColor.g,
  912. babylonMetallicRoughness.baseColor.b,
  913. babylonMetallicRoughness.opacity
  914. ],
  915. metallicFactor: babylonMetallicRoughness.metallic,
  916. roughnessFactor: babylonMetallicRoughness.roughness
  917. };
  918. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  919. // TODO: Handle Textures
  920. this.materials.push(glTFMaterial);
  921. meshPrimitive.material = this.materials.length - 1;
  922. }
  923. else if (bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  924. if (!this.textures) {
  925. this.textures = new Array();
  926. }
  927. var babylonPBRMaterial = bufferMesh.material;
  928. var glTFPbrMetallicRoughness = {};
  929. if (babylonPBRMaterial.baseColor) {
  930. glTFPbrMetallicRoughness.baseColorFactor = [
  931. babylonPBRMaterial.baseColor.r,
  932. babylonPBRMaterial.baseColor.g,
  933. babylonPBRMaterial.baseColor.b,
  934. babylonPBRMaterial.alpha
  935. ];
  936. }
  937. if (babylonPBRMaterial.baseTexture !== undefined) {
  938. var glTFTexture = this.exportTexture(babylonPBRMaterial.baseTexture);
  939. if (glTFTexture !== null) {
  940. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  941. }
  942. glTFPbrMetallicRoughness.baseColorTexture;
  943. }
  944. if (babylonPBRMaterial.metallic !== undefined) {
  945. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMaterial.metallic;
  946. }
  947. if (babylonPBRMaterial.roughness !== undefined) {
  948. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMaterial.roughness;
  949. }
  950. var glTFMaterial = {
  951. name: babylonPBRMaterial.name
  952. };
  953. if (babylonPBRMaterial.doubleSided) {
  954. glTFMaterial.doubleSided = babylonPBRMaterial.doubleSided;
  955. }
  956. if (babylonPBRMaterial.normalTexture) {
  957. var glTFTexture = this.exportTexture(babylonPBRMaterial.normalTexture);
  958. if (glTFTexture) {
  959. glTFMaterial.normalTexture = glTFTexture;
  960. }
  961. }
  962. if (babylonPBRMaterial.occlusionTexture) {
  963. var glTFTexture = this.exportTexture(babylonPBRMaterial.occlusionTexture);
  964. if (glTFTexture) {
  965. glTFMaterial.occlusionTexture = glTFTexture;
  966. if (babylonPBRMaterial.occlusionStrength !== undefined) {
  967. glTFMaterial.occlusionTexture.strength = babylonPBRMaterial.occlusionStrength;
  968. }
  969. }
  970. }
  971. if (babylonPBRMaterial.emissiveTexture) {
  972. var glTFTexture = this.exportTexture(babylonPBRMaterial.emissiveTexture);
  973. if (glTFTexture !== null) {
  974. glTFMaterial.emissiveTexture = glTFTexture;
  975. }
  976. }
  977. if (!babylonPBRMaterial.emissiveColor.equals(new BABYLON.Color3(0.0, 0.0, 0.0))) {
  978. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  979. }
  980. if (babylonPBRMaterial.transparencyMode) {
  981. var alphaMode = BABYLON._GLTFMaterial.GetAlphaMode(babylonPBRMaterial);
  982. if (alphaMode !== _EGLTFAlphaModeEnum.OPAQUE) {
  983. glTFMaterial.alphaMode = alphaMode;
  984. if (alphaMode === _EGLTFAlphaModeEnum.BLEND) {
  985. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  986. }
  987. }
  988. }
  989. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  990. // TODO: Handle Textures
  991. this.materials.push(glTFMaterial);
  992. meshPrimitive.material = this.materials.length - 1;
  993. }
  994. }
  995. mesh.primitives.push(meshPrimitive);
  996. }
  997. return byteOffset;
  998. };
  999. /**
  1000. * Creates a glTF scene based on the array of meshes.
  1001. * Returns the the total byte offset.
  1002. * @param gltf
  1003. * @param byteOffset
  1004. * @param buffer
  1005. * @param dataBuffer
  1006. * @returns bytelength + byteoffset
  1007. */
  1008. _GLTF2Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  1009. if (babylonScene.meshes.length > 0) {
  1010. var babylonMeshes = babylonScene.meshes;
  1011. var scene = { nodes: new Array() };
  1012. for (var i = 0; i < babylonMeshes.length; ++i) {
  1013. if (this.options &&
  1014. this.options.shouldExportMesh !== undefined &&
  1015. !this.options.shouldExportMesh(babylonMeshes[i])) {
  1016. continue;
  1017. }
  1018. else {
  1019. // create node to hold translation/rotation/scale and the mesh
  1020. var node = { mesh: -1 };
  1021. var babylonMesh = babylonMeshes[i];
  1022. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  1023. // Set transformation
  1024. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  1025. // create mesh
  1026. var mesh = { primitives: new Array() };
  1027. mesh.primitives = [];
  1028. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  1029. // go through all mesh primitives (submeshes)
  1030. this.meshes.push(mesh);
  1031. node.mesh = this.meshes.length - 1;
  1032. if (babylonMesh.name) {
  1033. node.name = babylonMesh.name;
  1034. }
  1035. this.nodes.push(node);
  1036. scene.nodes.push(this.nodes.length - 1);
  1037. }
  1038. }
  1039. this.scenes.push(scene);
  1040. }
  1041. return byteOffset;
  1042. };
  1043. return _GLTF2Exporter;
  1044. }());
  1045. BABYLON._GLTF2Exporter = _GLTF2Exporter;
  1046. })(BABYLON || (BABYLON = {}));
  1047. //# sourceMappingURL=babylon.glTFExporter.js.map
  1048. var BABYLON;
  1049. (function (BABYLON) {
  1050. /**
  1051. * Class for holding and downloading glTF file data
  1052. */
  1053. var _GLTFData = /** @class */ (function () {
  1054. function _GLTFData() {
  1055. this.glTFFiles = {};
  1056. }
  1057. /**
  1058. * Downloads glTF data.
  1059. */
  1060. _GLTFData.prototype.downloadFiles = function () {
  1061. /**
  1062. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1063. * @param str
  1064. * @param suffix
  1065. * @returns - indicating whether the suffix matches or not
  1066. */
  1067. function endsWith(str, suffix) {
  1068. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1069. }
  1070. for (var key in this.glTFFiles) {
  1071. var link = document.createElement('a');
  1072. document.body.appendChild(link);
  1073. link.setAttribute("type", "hidden");
  1074. link.download = key;
  1075. var blob = this.glTFFiles[key];
  1076. var mimeType = void 0;
  1077. if (endsWith(key, ".glb")) {
  1078. mimeType = { type: "model/gltf-binary" };
  1079. }
  1080. else if (endsWith(key, ".bin")) {
  1081. mimeType = { type: "application/octet-stream" };
  1082. }
  1083. else if (endsWith(key, ".gltf")) {
  1084. mimeType = { type: "model/gltf+json" };
  1085. }
  1086. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1087. link.click();
  1088. }
  1089. };
  1090. return _GLTFData;
  1091. }());
  1092. BABYLON._GLTFData = _GLTFData;
  1093. })(BABYLON || (BABYLON = {}));
  1094. //# sourceMappingURL=babylon.glTFData.js.map
  1095. var BABYLON;
  1096. (function (BABYLON) {
  1097. /**
  1098. * Utility methods for working with glTF material conversion properties
  1099. */
  1100. var _GLTFMaterial = /** @class */ (function () {
  1101. function _GLTFMaterial() {
  1102. }
  1103. /**
  1104. * Converts Specular Glossiness to Metallic Roughness
  1105. * @param babylonSpecularGlossiness - Babylon specular glossiness parameters
  1106. * @returns - Babylon metallic roughness values
  1107. */
  1108. _GLTFMaterial.ConvertToMetallicRoughness = function (babylonSpecularGlossiness) {
  1109. var diffuse = babylonSpecularGlossiness.diffuse;
  1110. var opacity = babylonSpecularGlossiness.opacity;
  1111. var specular = babylonSpecularGlossiness.specular;
  1112. var glossiness = babylonSpecularGlossiness.glossiness;
  1113. var oneMinusSpecularStrength = 1 - Math.max(specular.r, Math.max(specular.g, specular.b));
  1114. var diffusePerceivedBrightness = _GLTFMaterial.PerceivedBrightness(diffuse);
  1115. var specularPerceivedBrightness = _GLTFMaterial.PerceivedBrightness(specular);
  1116. var metallic = _GLTFMaterial.SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1117. var diffuseScaleFactor = oneMinusSpecularStrength / (1 - this.dielectricSpecular.r) / Math.max(1 - metallic, this.epsilon);
  1118. var baseColorFromDiffuse = diffuse.scale(diffuseScaleFactor);
  1119. var baseColorFromSpecular = specular.subtract(this.dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this.epsilon));
  1120. var lerpColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1121. var baseColor = new BABYLON.Color3();
  1122. lerpColor.clampToRef(0, 1, baseColor);
  1123. var babylonMetallicRoughness = {
  1124. baseColor: baseColor,
  1125. opacity: opacity,
  1126. metallic: metallic,
  1127. roughness: 1.0 - glossiness
  1128. };
  1129. return babylonMetallicRoughness;
  1130. };
  1131. /**
  1132. * Returns the perceived brightness value based on the provided color
  1133. * @param color - color used in calculating the perceived brightness
  1134. * @returns - perceived brightness value
  1135. */
  1136. _GLTFMaterial.PerceivedBrightness = function (color) {
  1137. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1138. };
  1139. /**
  1140. * Computes the metallic factor
  1141. * @param diffuse - diffused value
  1142. * @param specular - specular value
  1143. * @param oneMinusSpecularStrength - one minus the specular strength
  1144. * @returns - metallic value
  1145. */
  1146. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1147. if (specular < this.dielectricSpecular.r) {
  1148. return 0;
  1149. }
  1150. var a = this.dielectricSpecular.r;
  1151. var b = diffuse * oneMinusSpecularStrength / (1.0 - this.dielectricSpecular.r) + specular - 2.0 * this.dielectricSpecular.r;
  1152. var c = this.dielectricSpecular.r - specular;
  1153. var D = b * b - 4.0 * a * c;
  1154. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a));
  1155. };
  1156. /**
  1157. * Gets the glTF alpha mode from the Babylon Material
  1158. * @param babylonMaterial - Babylon Material
  1159. * @returns - The Babylon alpha mode value
  1160. */
  1161. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  1162. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1163. var babylonStandardMaterial = babylonMaterial;
  1164. if ((babylonStandardMaterial.alpha != 1.0) ||
  1165. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1166. (babylonStandardMaterial.opacityTexture != null)) {
  1167. return BABYLON._EGLTFAlphaModeEnum.BLEND;
  1168. }
  1169. else {
  1170. return BABYLON._EGLTFAlphaModeEnum.OPAQUE;
  1171. }
  1172. }
  1173. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1174. var babylonPBRMetallicRoughness = babylonMaterial;
  1175. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1176. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1177. return BABYLON._EGLTFAlphaModeEnum.OPAQUE;
  1178. }
  1179. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1180. return BABYLON._EGLTFAlphaModeEnum.BLEND;
  1181. }
  1182. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1183. return BABYLON._EGLTFAlphaModeEnum.MASK;
  1184. }
  1185. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1186. console.warn("GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1187. return BABYLON._EGLTFAlphaModeEnum.BLEND;
  1188. }
  1189. default: {
  1190. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1191. }
  1192. }
  1193. }
  1194. else {
  1195. throw new Error("Unsupported Babylon material type");
  1196. }
  1197. };
  1198. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1199. _GLTFMaterial.epsilon = 1e-6;
  1200. return _GLTFMaterial;
  1201. }());
  1202. BABYLON._GLTFMaterial = _GLTFMaterial;
  1203. })(BABYLON || (BABYLON = {}));
  1204. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1205. (function universalModuleDefinition(root, factory) {
  1206. var f = factory();
  1207. if (root && root["BABYLON"]) {
  1208. return;
  1209. }
  1210. if(typeof exports === 'object' && typeof module === 'object')
  1211. module.exports = f;
  1212. else if(typeof define === 'function' && define.amd)
  1213. define(["BJSSerializers"], factory);
  1214. else if(typeof exports === 'object')
  1215. exports["BJSSerializers"] = f;
  1216. else {
  1217. root["BABYLON"] = f;
  1218. }
  1219. })(this, function() {
  1220. return BABYLON;
  1221. });