babylonjs.serializers.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. var GLTF2Export = /** @class */ (function () {
  145. function GLTF2Export() {
  146. }
  147. /**
  148. * Exports the geometry of a Mesh array in .gltf file format.
  149. * If glb is set to true, exports as .glb.
  150. * @param meshes
  151. * @param materials
  152. *
  153. * @returns {[fileName: string]: string | Blob} Returns an object with a .gltf, .glb and associates textures
  154. * as keys and their data and paths as values.
  155. */
  156. GLTF2Export.GLTF = function (scene, filename) {
  157. var glTFPrefix = filename.replace(/\.[^/.]+$/, "");
  158. var gltfGenerator = new BABYLON._GLTF2Exporter(scene);
  159. return gltfGenerator._generateGLTF(glTFPrefix);
  160. };
  161. /**
  162. *
  163. * @param meshes
  164. * @param filename
  165. *
  166. * @returns {[fileName: string]: string | Blob} Returns an object with a .glb filename as key and data as value
  167. */
  168. GLTF2Export.GLB = function (scene, filename) {
  169. var glTFPrefix = filename.replace(/\.[^/.]+$/, "");
  170. var gltfGenerator = new BABYLON._GLTF2Exporter(scene);
  171. return gltfGenerator._generateGLB(glTFPrefix);
  172. };
  173. /**
  174. * Downloads data from glTF object.
  175. *
  176. * @param gltfData glTF object with keys being file names and values being data
  177. */
  178. GLTF2Export.downloadFiles = function (gltfData) {
  179. /**
  180. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  181. * @param str
  182. * @param suffix
  183. *
  184. * @returns {boolean} indicating whether the suffix matches or not
  185. */
  186. function endsWith(str, suffix) {
  187. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  188. }
  189. for (var key in gltfData) {
  190. var link = document.createElement('a');
  191. document.body.appendChild(link);
  192. link.setAttribute("type", "hidden");
  193. link.download = key;
  194. var blob = gltfData[key];
  195. var mimeType = void 0;
  196. if (endsWith(key, ".glb")) {
  197. mimeType = { type: "model/gltf-binary" };
  198. }
  199. else if (endsWith(key, ".bin")) {
  200. mimeType = { type: "application/octet-stream" };
  201. }
  202. else if (endsWith(key, ".gltf")) {
  203. mimeType = { type: "model/gltf+json" };
  204. }
  205. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  206. link.click();
  207. }
  208. };
  209. return GLTF2Export;
  210. }());
  211. BABYLON.GLTF2Export = GLTF2Export;
  212. })(BABYLON || (BABYLON = {}));
  213. //# sourceMappingURL=babylon.glTFSerializer.js.map
  214. var BABYLON;
  215. (function (BABYLON) {
  216. var _GLTF2Exporter = /** @class */ (function () {
  217. function _GLTF2Exporter(babylonScene) {
  218. this.asset = { generator: "BabylonJS", version: "2.0" };
  219. this.babylonScene = babylonScene;
  220. this.bufferViews = new Array();
  221. this.accessors = new Array();
  222. this.meshes = new Array();
  223. this.scenes = new Array();
  224. this.nodes = new Array();
  225. var totalByteLength = 0;
  226. totalByteLength = this.createScene(this.babylonScene, totalByteLength);
  227. this.totalByteLength = totalByteLength;
  228. }
  229. /**
  230. * Creates a buffer view based on teh supplied arguments
  231. * @param bufferIndex
  232. * @param byteOffset
  233. * @param byteLength
  234. *
  235. * @returns {_IGLTFBufferView}
  236. */
  237. _GLTF2Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength) {
  238. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  239. if (byteOffset > 0) {
  240. bufferview.byteOffset = byteOffset;
  241. }
  242. return bufferview;
  243. };
  244. /**
  245. * Creates an accessor based on the supplied arguments
  246. * @param bufferviewIndex
  247. * @param name
  248. * @param type
  249. * @param componentType
  250. * @param count
  251. * @param min
  252. * @param max
  253. *
  254. * @returns {_IGLTFAccessor}
  255. */
  256. _GLTF2Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, min, max) {
  257. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  258. if (min) {
  259. accessor.min = min;
  260. }
  261. if (max) {
  262. accessor.max = max;
  263. }
  264. return accessor;
  265. };
  266. /**
  267. * Calculates the minimum and maximum values of an array of floats, based on stride
  268. * @param buff
  269. * @param vertexStart
  270. * @param vertexCount
  271. * @param arrayOffset
  272. * @param stride
  273. *
  274. * @returns {min: number[], max: number[]} min number array and max number array
  275. */
  276. _GLTF2Exporter.prototype.calculateMinMax = function (buff, vertexStart, vertexCount, arrayOffset, stride) {
  277. var min = [Infinity, Infinity, Infinity];
  278. var max = [-Infinity, -Infinity, -Infinity];
  279. var end = vertexStart + vertexCount;
  280. if (vertexCount > 0) {
  281. for (var i = vertexStart; i < end; ++i) {
  282. var index = stride * i;
  283. for (var j = 0; j < stride; ++j) {
  284. if (buff[index] < min[j]) {
  285. min[j] = buff[index];
  286. }
  287. if (buff[index] > max[j]) {
  288. max[j] = buff[index];
  289. }
  290. ++index;
  291. }
  292. }
  293. }
  294. return { min: min, max: max };
  295. };
  296. /**
  297. * Write mesh attribute data to buffer.
  298. * Returns the bytelength of the data.
  299. * @param vertexBufferType
  300. * @param submesh
  301. * @param meshAttributeArray
  302. * @param strideSize
  303. * @param byteOffset
  304. * @param dataBuffer
  305. * @param useRightHandedSystem
  306. *
  307. * @returns {number} 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. *
  419. * @returns {string} json data as string
  420. */
  421. _GLTF2Exporter.prototype.generateJSON = function (glb, glTFPrefix, prettyPrint) {
  422. var buffer = { byteLength: this.totalByteLength };
  423. var glTf = {
  424. buffers: [buffer],
  425. asset: this.asset,
  426. meshes: this.meshes,
  427. scenes: this.scenes,
  428. nodes: this.nodes,
  429. bufferViews: this.bufferViews,
  430. accessors: this.accessors
  431. };
  432. if (this.scenes.length > 0) {
  433. glTf.scene = 0;
  434. }
  435. if (!glb) {
  436. buffer.uri = glTFPrefix + ".bin";
  437. }
  438. var jsonText = prettyPrint ? JSON.stringify(glTf, null, 2) : JSON.stringify(glTf);
  439. return jsonText;
  440. };
  441. /**
  442. * Generates data for .gltf and .bin files based on the glTF prefix string
  443. * @param glTFPrefix
  444. *
  445. * @returns {[x: string]: string | Blob} object with glTF json tex filename
  446. * and binary file name as keys and their data as values
  447. */
  448. _GLTF2Exporter.prototype._generateGLTF = function (glTFPrefix) {
  449. var jsonText = this.generateJSON(false, glTFPrefix, true);
  450. var binaryBuffer = this.generateBinary();
  451. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  452. var glTFFileName = glTFPrefix + '.gltf';
  453. var glTFBinFile = glTFPrefix + '.bin';
  454. return _a = {},
  455. _a[glTFFileName] = jsonText,
  456. _a[glTFBinFile] = bin,
  457. _a;
  458. var _a;
  459. };
  460. /**
  461. * Creates a binary buffer for glTF
  462. *
  463. * @returns {ArrayBuffer}
  464. */
  465. _GLTF2Exporter.prototype.generateBinary = function () {
  466. var byteOffset = 0;
  467. var binaryBuffer = new ArrayBuffer(this.totalByteLength);
  468. var dataBuffer = new DataView(binaryBuffer);
  469. byteOffset = this.createScene(this.babylonScene, byteOffset, dataBuffer);
  470. return binaryBuffer;
  471. };
  472. /**
  473. * Generates a glb file from the json and binary data.
  474. * Returns an object with the glb file name as the key and data as the value.
  475. * @param jsonText
  476. * @param binaryBuffer
  477. * @param glTFPrefix
  478. *
  479. * @returns {[glbFileName: string]: Blob} object with glb filename as key and data as value
  480. */
  481. _GLTF2Exporter.prototype._generateGLB = function (glTFPrefix) {
  482. var jsonText = this.generateJSON(true);
  483. var binaryBuffer = this.generateBinary();
  484. var glbFileName = glTFPrefix + '.glb';
  485. var headerLength = 12;
  486. var chunkLengthPrefix = 8;
  487. var jsonLength = jsonText.length;
  488. var jsonRemainder = jsonLength % 4;
  489. var binRemainder = binaryBuffer.byteLength % 4;
  490. var jsonPadding = jsonRemainder === 0 ? jsonRemainder : 4 - jsonRemainder;
  491. var binPadding = binRemainder === 0 ? binRemainder : 4 - binRemainder;
  492. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding;
  493. //header
  494. var headerBuffer = new ArrayBuffer(headerLength);
  495. var headerBufferView = new DataView(headerBuffer);
  496. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  497. headerBufferView.setUint32(4, 2, true); // version
  498. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  499. //json chunk
  500. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  501. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  502. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  503. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  504. //json chunk bytes
  505. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  506. for (var i = 0; i < jsonLength; ++i) {
  507. jsonData[i] = jsonText.charCodeAt(i);
  508. }
  509. //json padding
  510. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  511. for (var i = 0; i < jsonPadding; ++i) {
  512. jsonPaddingView[i] = 0x20;
  513. }
  514. //binary chunk
  515. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  516. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  517. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength, true);
  518. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  519. // binary padding
  520. var binPaddingBuffer = new ArrayBuffer(binPadding);
  521. var binPaddingView = new Uint8Array(binPaddingBuffer);
  522. for (var i = 0; i < binPadding; ++i) {
  523. binPaddingView[i] = 0;
  524. }
  525. // binary data
  526. var glbFile = new Blob([headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer, binPaddingBuffer], { type: 'application/octet-stream' });
  527. return _a = {},
  528. _a[glbFileName] = glbFile,
  529. _a;
  530. var _a;
  531. };
  532. /**
  533. * Sets the TRS for each node
  534. * @param node
  535. * @param babylonMesh
  536. * @param useRightHandedSystem
  537. */
  538. _GLTF2Exporter.prototype.setNodeTransformation = function (node, babylonMesh, useRightHandedSystem) {
  539. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  540. if (useRightHandedSystem) {
  541. node.translation = babylonMesh.position.asArray();
  542. }
  543. else {
  544. node.translation = [babylonMesh.position.x, babylonMesh.position.y, -babylonMesh.position.z];
  545. }
  546. }
  547. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  548. if (useRightHandedSystem) {
  549. node.scale = babylonMesh.scaling.asArray();
  550. }
  551. else {
  552. node.scale = [babylonMesh.scaling.x, babylonMesh.scaling.y, -babylonMesh.scaling.z];
  553. }
  554. }
  555. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  556. if (babylonMesh.rotationQuaternion) {
  557. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  558. }
  559. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  560. if (useRightHandedSystem) {
  561. node.rotation = rotationQuaternion.asArray();
  562. }
  563. else {
  564. node.rotation = [-rotationQuaternion.x, -rotationQuaternion.y, rotationQuaternion.z, rotationQuaternion.w];
  565. }
  566. }
  567. };
  568. /**
  569. * Sets data for the primitive attributes of each submesh
  570. * @param mesh
  571. * @param babylonMesh
  572. * @param byteOffset
  573. * @param useRightHandedSystem
  574. * @param dataBuffer
  575. *
  576. * @returns {number} bytelength of the primitive attributes plus the passed in byteOffset
  577. */
  578. _GLTF2Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  579. // go through all mesh primitives (submeshes)
  580. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  581. var bufferMesh = null;
  582. var submesh = babylonMesh.subMeshes[j];
  583. var meshPrimitive = { attributes: {} };
  584. if (babylonMesh instanceof BABYLON.Mesh) {
  585. bufferMesh = babylonMesh;
  586. }
  587. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  588. bufferMesh = babylonMesh.sourceMesh;
  589. }
  590. // Loop through each attribute of the submesh (mesh primitive)
  591. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  592. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  593. var positionVertexBufferOffset = positionVertexBuffer.getOffset();
  594. var positions = positionVertexBuffer.getData();
  595. var positionStrideSize = positionVertexBuffer.getStrideSize();
  596. if (dataBuffer) {
  597. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.PositionKind, submesh, positions, positionStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  598. }
  599. else {
  600. // Create bufferview
  601. var byteLength = submesh.verticesCount * 12;
  602. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  603. byteOffset += byteLength;
  604. this.bufferViews.push(bufferview);
  605. // Create accessor
  606. var result = this.calculateMinMax(positions, submesh.verticesStart, submesh.verticesCount, positionVertexBufferOffset, positionStrideSize);
  607. var accessor = this.createAccessor(this.bufferViews.length - 1, "Position", "VEC3", 5126, submesh.verticesCount, result.min, result.max);
  608. this.accessors.push(accessor);
  609. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  610. }
  611. }
  612. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  613. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  614. var normals = normalVertexBuffer.getData();
  615. var normalStrideSize = normalVertexBuffer.getStrideSize();
  616. if (dataBuffer) {
  617. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.NormalKind, submesh, normals, normalStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  618. }
  619. else {
  620. // Create bufferview
  621. var byteLength = submesh.verticesCount * 12;
  622. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  623. byteOffset += byteLength;
  624. this.bufferViews.push(bufferview);
  625. // Create accessor
  626. var accessor = this.createAccessor(this.bufferViews.length - 1, "Normal", "VEC3", 5126, submesh.verticesCount);
  627. this.accessors.push(accessor);
  628. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  629. }
  630. }
  631. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  632. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  633. var tangents = tangentVertexBuffer.getData();
  634. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  635. if (dataBuffer) {
  636. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.TangentKind, submesh, tangents, tangentStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  637. }
  638. else {
  639. // Create bufferview
  640. var byteLength = submesh.verticesCount * 16;
  641. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  642. byteOffset += byteLength;
  643. this.bufferViews.push(bufferview);
  644. // Create accessor
  645. var accessor = this.createAccessor(this.bufferViews.length - 1, "Tangent", "VEC4", 5126, submesh.verticesCount);
  646. this.accessors.push(accessor);
  647. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  648. }
  649. }
  650. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  651. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  652. var colors = colorVertexBuffer.getData();
  653. var colorStrideSize = colorVertexBuffer.getStrideSize();
  654. if (dataBuffer) {
  655. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.ColorKind, submesh, colors, colorStrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  656. }
  657. else {
  658. // Create bufferview
  659. var byteLength = submesh.verticesCount * 16;
  660. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  661. byteOffset += byteLength;
  662. this.bufferViews.push(bufferview);
  663. // Create accessor
  664. var accessor = this.createAccessor(this.bufferViews.length - 1, "Color", "VEC4", 5126, submesh.verticesCount);
  665. this.accessors.push(accessor);
  666. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  667. }
  668. }
  669. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  670. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  671. var texCoords0 = texCoord0VertexBuffer.getData();
  672. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  673. if (dataBuffer) {
  674. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.UVKind, submesh, texCoords0, texCoord0StrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  675. }
  676. else {
  677. // Create bufferview
  678. var byteLength = submesh.verticesCount * 8;
  679. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  680. byteOffset += byteLength;
  681. this.bufferViews.push(bufferview);
  682. // Create accessor
  683. var accessor = this.createAccessor(this.bufferViews.length - 1, "Texture Coords", "VEC2", 5126, submesh.verticesCount);
  684. this.accessors.push(accessor);
  685. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  686. }
  687. }
  688. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  689. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  690. var texCoords1 = texCoord1VertexBuffer.getData();
  691. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  692. if (dataBuffer) {
  693. byteOffset += this.writeAttributeData(BABYLON.VertexBuffer.UV2Kind, submesh, texCoords1, texCoord1StrideSize, byteOffset, dataBuffer, useRightHandedSystem);
  694. }
  695. else {
  696. // Create bufferview
  697. var byteLength = submesh.verticesCount * 8;
  698. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  699. byteOffset += byteLength;
  700. this.bufferViews.push(bufferview);
  701. // Create accessor
  702. var accessor = this.createAccessor(this.bufferViews.length - 1, "Texture Coords", "VEC2", 5126, submesh.verticesCount);
  703. this.accessors.push(accessor);
  704. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  705. }
  706. }
  707. if (bufferMesh.getTotalIndices() > 0) {
  708. if (dataBuffer) {
  709. var indices = bufferMesh.getIndices();
  710. var start = submesh.indexStart;
  711. var end = submesh.indexCount + start;
  712. var byteOff = byteOffset;
  713. for (var k = start; k < end; k = k + 3) {
  714. dataBuffer.setUint32(byteOff, indices[k], true);
  715. byteOff += 4;
  716. dataBuffer.setUint32(byteOff, indices[k + 1], true);
  717. byteOff += 4;
  718. dataBuffer.setUint32(byteOff, indices[k + 2], true);
  719. byteOff += 4;
  720. }
  721. var byteLength = submesh.indexCount * 4;
  722. byteOffset += byteLength;
  723. }
  724. else {
  725. // Create bufferview
  726. var indicesCount = submesh.indexCount;
  727. var byteLength = indicesCount * 4;
  728. var bufferview = this.createBufferView(0, byteOffset, byteLength);
  729. byteOffset += byteLength;
  730. this.bufferViews.push(bufferview);
  731. // Create accessor
  732. var accessor = this.createAccessor(this.bufferViews.length - 1, "Indices", "SCALAR", 5125, indicesCount);
  733. this.accessors.push(accessor);
  734. meshPrimitive.indices = this.accessors.length - 1;
  735. }
  736. }
  737. if (bufferMesh.material) {
  738. //TODO: Implement Material
  739. }
  740. mesh.primitives.push(meshPrimitive);
  741. }
  742. return byteOffset;
  743. };
  744. /**
  745. * Creates a glTF scene based on the array of meshes.
  746. * Returns the the total byte offset.
  747. * @param gltf
  748. * @param byteOffset
  749. * @param buffer
  750. * @param dataBuffer
  751. *
  752. * @returns {number} bytelength + byteoffset
  753. */
  754. _GLTF2Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  755. if (babylonScene.meshes.length > 0) {
  756. var babylonMeshes = babylonScene.meshes;
  757. var scene = { nodes: new Array() };
  758. for (var i = 0; i < babylonMeshes.length; ++i) {
  759. // create node to hold translation/rotation/scale and the mesh
  760. var node = { mesh: -1 };
  761. var babylonMesh = babylonMeshes[i];
  762. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  763. // Set transformation
  764. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  765. // create mesh
  766. var mesh = { primitives: new Array() };
  767. mesh.primitives = [];
  768. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  769. // go through all mesh primitives (submeshes)
  770. this.meshes.push(mesh);
  771. node.mesh = this.meshes.length - 1;
  772. if (babylonMesh.name) {
  773. node.name = babylonMesh.name;
  774. }
  775. this.nodes.push(node);
  776. scene.nodes.push(this.nodes.length - 1);
  777. }
  778. this.scenes.push(scene);
  779. }
  780. return byteOffset;
  781. };
  782. return _GLTF2Exporter;
  783. }());
  784. BABYLON._GLTF2Exporter = _GLTF2Exporter;
  785. })(BABYLON || (BABYLON = {}));
  786. //# sourceMappingURL=babylon.glTFExporter.js.map
  787. (function universalModuleDefinition(root, factory) {
  788. var f = factory();
  789. if (root && root["BABYLON"]) {
  790. return;
  791. }
  792. if(typeof exports === 'object' && typeof module === 'object')
  793. module.exports = f;
  794. else if(typeof define === 'function' && define.amd)
  795. define(["BJSSerializers"], factory);
  796. else if(typeof exports === 'object')
  797. exports["BJSSerializers"] = f;
  798. else {
  799. root["BABYLON"] = f;
  800. }
  801. })(this, function() {
  802. return BABYLON;
  803. });