babylonjs.serializers.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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. /**
  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. if (options !== undefined) {
  221. this.options = options;
  222. }
  223. var totalByteLength = 0;
  224. totalByteLength = this.createScene(this.babylonScene, totalByteLength, null);
  225. this.totalByteLength = totalByteLength;
  226. }
  227. /**
  228. * Creates a buffer view based on teh supplied arguments
  229. * @param bufferIndex - index value of the specified buffer
  230. * @param byteOffset - byte offset value
  231. * @param byteLength - byte length of the bufferView
  232. * @param byteStride - byte distance between conequential elements.
  233. * @param name - name of the buffer view
  234. * @returns - bufferView for glTF
  235. */
  236. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  237. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  238. if (byteOffset > 0) {
  239. bufferview.byteOffset = byteOffset;
  240. }
  241. if (name) {
  242. bufferview.name = name;
  243. }
  244. if (byteStride) {
  245. bufferview.byteStride = byteStride;
  246. }
  247. return bufferview;
  248. };
  249. /**
  250. * Creates an accessor based on the supplied arguments
  251. * @param bufferviewIndex
  252. * @param name
  253. * @param type
  254. * @param componentType
  255. * @param count
  256. * @param min
  257. * @param max
  258. * @returns - accessor for glTF
  259. */
  260. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  261. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  262. if (min) {
  263. accessor.min = min;
  264. }
  265. if (max) {
  266. accessor.max = max;
  267. }
  268. if (byteOffset) {
  269. accessor.byteOffset = byteOffset;
  270. }
  271. return accessor;
  272. };
  273. /**
  274. * Calculates the minimum and maximum values of an array of floats, based on stride
  275. * @param buff - Data to check for min and max values.
  276. * @param vertexStart - Start offset to calculate min and max values.
  277. * @param vertexCount - Number of vertices to check for min and max values.
  278. * @param stride - Offset between consecutive attributes.
  279. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  280. * @returns - min number array and max number array.
  281. */
  282. _Exporter.prototype.calculateMinMax = function (buff, vertexStart, vertexCount, stride, useRightHandedSystem) {
  283. var min = [Infinity, Infinity, Infinity];
  284. var max = [-Infinity, -Infinity, -Infinity];
  285. var end = vertexStart + vertexCount;
  286. if (vertexCount > 0) {
  287. for (var i = vertexStart; i < end; ++i) {
  288. var index = stride * i;
  289. var scale = 1;
  290. for (var j = 0; j < stride; ++j) {
  291. if (j === (stride - 1) && !useRightHandedSystem) {
  292. scale = -1;
  293. }
  294. var num = scale * buff[index];
  295. if (num < min[j]) {
  296. min[j] = num;
  297. }
  298. if (num > max[j]) {
  299. max[j] = num;
  300. }
  301. ++index;
  302. }
  303. }
  304. }
  305. return { min: min, max: max };
  306. };
  307. /**
  308. * Writes mesh attribute data to a data buffer.
  309. * Returns the bytelength of the data.
  310. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  311. * @param meshAttributeArray - Array containing the attribute data.
  312. * @param strideSize - Represents the offset between consecutive attributes
  313. * @param byteOffset - The offset to start counting bytes from.
  314. * @param dataBuffer - The buffer to write the binary data to.
  315. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  316. * @returns - Byte length of the attribute data.
  317. */
  318. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, strideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem) {
  319. var byteOff = byteOffset;
  320. var start = 0;
  321. var end = meshAttributeArray.length / strideSize;
  322. var byteLength = 0;
  323. switch (vertexBufferKind) {
  324. case BABYLON.VertexBuffer.PositionKind: {
  325. for (var k = start; k < end; ++k) {
  326. var index = k * strideSize;
  327. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  328. byteOff += 4;
  329. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  330. byteOff += 4;
  331. if (useRightHandedSystem) {
  332. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  333. }
  334. else {
  335. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  336. }
  337. byteOff += 4;
  338. }
  339. byteLength = meshAttributeArray.length * 4;
  340. break;
  341. }
  342. case BABYLON.VertexBuffer.NormalKind: {
  343. for (var k = start; k < end; ++k) {
  344. var index = k * strideSize;
  345. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  346. byteOff += 4;
  347. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  348. byteOff += 4;
  349. if (useRightHandedSystem) {
  350. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  351. }
  352. else {
  353. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  354. }
  355. byteOff += 4;
  356. }
  357. byteLength = meshAttributeArray.length * 4;
  358. break;
  359. }
  360. case BABYLON.VertexBuffer.TangentKind: {
  361. for (var k = start; k < end; ++k) {
  362. var index = k * strideSize;
  363. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  364. byteOff += 4;
  365. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  366. byteOff += 4;
  367. if (useRightHandedSystem) {
  368. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  369. }
  370. else {
  371. dataBuffer.setFloat32(byteOff, -meshAttributeArray[index + 2], true);
  372. }
  373. byteOff += 4;
  374. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  375. byteOff += 4;
  376. }
  377. byteLength = meshAttributeArray.length * 4;
  378. break;
  379. }
  380. case BABYLON.VertexBuffer.ColorKind: {
  381. for (var k = start; k < end; ++k) {
  382. var index = k * strideSize;
  383. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  384. byteOff += 4;
  385. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  386. byteOff += 4;
  387. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 2], true);
  388. byteOff += 4;
  389. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 3], true);
  390. byteOff += 4;
  391. }
  392. byteLength = meshAttributeArray.length * 4;
  393. break;
  394. }
  395. case BABYLON.VertexBuffer.UVKind: {
  396. for (var k = start; k < end; ++k) {
  397. var index = k * strideSize;
  398. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  399. byteOff += 4;
  400. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  401. byteOff += 4;
  402. }
  403. byteLength = meshAttributeArray.length * 4;
  404. break;
  405. }
  406. case BABYLON.VertexBuffer.UV2Kind: {
  407. for (var k = start; k < end; ++k) {
  408. var index = k * strideSize;
  409. dataBuffer.setFloat32(byteOff, meshAttributeArray[index], true);
  410. byteOff += 4;
  411. dataBuffer.setFloat32(byteOff, meshAttributeArray[index + 1], true);
  412. byteOff += 4;
  413. }
  414. byteLength = meshAttributeArray.length * 4;
  415. break;
  416. }
  417. default: {
  418. throw new Error("Unsupported vertex buffer type: " + vertexBufferKind);
  419. }
  420. }
  421. return byteLength;
  422. };
  423. /**
  424. * Generates glTF json data
  425. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  426. * @param glTFPrefix - Text to use when prefixing a glTF file.
  427. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  428. * @returns - json data as string
  429. */
  430. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  431. var buffer = { byteLength: this.totalByteLength };
  432. var glTF = {
  433. asset: this.asset
  434. };
  435. if (buffer.byteLength > 0) {
  436. glTF.buffers = [buffer];
  437. }
  438. if (this.nodes && this.nodes.length !== 0) {
  439. glTF.nodes = this.nodes;
  440. }
  441. if (this.meshes && this.meshes.length !== 0) {
  442. glTF.meshes = this.meshes;
  443. }
  444. if (this.scenes && this.scenes.length !== 0) {
  445. glTF.scenes = this.scenes;
  446. glTF.scene = 0;
  447. }
  448. if (this.bufferViews && this.bufferViews.length !== 0) {
  449. glTF.bufferViews = this.bufferViews;
  450. }
  451. if (this.accessors && this.accessors.length !== 0) {
  452. glTF.accessors = this.accessors;
  453. }
  454. if (this.materials && this.materials.length !== 0) {
  455. glTF.materials = this.materials;
  456. }
  457. if (this.textures && this.textures.length !== 0) {
  458. glTF.textures = this.textures;
  459. }
  460. if (this.images && this.images.length !== 0) {
  461. if (!shouldUseGlb) {
  462. glTF.images = this.images;
  463. }
  464. else {
  465. glTF.images = [];
  466. // Replace uri with bufferview and mime type for glb
  467. var imageLength = this.images.length;
  468. var byteOffset = this.totalByteLength;
  469. for (var i = 0; i < imageLength; ++i) {
  470. var image = this.images[i];
  471. if (image.uri !== undefined) {
  472. var imageData = this.imageData[image.uri];
  473. var imageName = image.uri.split('.')[0] + " image";
  474. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  475. byteOffset += imageData.data.buffer.byteLength;
  476. this.bufferViews.push(bufferView);
  477. image.bufferView = this.bufferViews.length - 1;
  478. image.name = imageName;
  479. image.mimeType = imageData.mimeType;
  480. image.uri = undefined;
  481. glTF.images.push(image);
  482. }
  483. }
  484. buffer.byteLength = byteOffset;
  485. }
  486. }
  487. if (!shouldUseGlb) {
  488. buffer.uri = glTFPrefix + ".bin";
  489. }
  490. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  491. return jsonText;
  492. };
  493. /**
  494. * Generates data for .gltf and .bin files based on the glTF prefix string
  495. * @param glTFPrefix - Text to use when prefixing a glTF file.
  496. * @returns - GLTFData with glTF file data.
  497. */
  498. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  499. var jsonText = this.generateJSON(false, glTFPrefix, true);
  500. var binaryBuffer = this.generateBinary();
  501. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  502. var glTFFileName = glTFPrefix + '.gltf';
  503. var glTFBinFile = glTFPrefix + '.bin';
  504. var container = new BABYLON._GLTFData();
  505. container.glTFFiles[glTFFileName] = jsonText;
  506. container.glTFFiles[glTFBinFile] = bin;
  507. if (this.imageData !== null) {
  508. for (var image in this.imageData) {
  509. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  510. }
  511. }
  512. return container;
  513. };
  514. /**
  515. * Creates a binary buffer for glTF
  516. * @returns - array buffer for binary data
  517. */
  518. _Exporter.prototype.generateBinary = function () {
  519. var byteOffset = 0;
  520. var binaryBuffer = new ArrayBuffer(this.totalByteLength);
  521. var dataBuffer = new DataView(binaryBuffer);
  522. byteOffset = this.createScene(this.babylonScene, byteOffset, dataBuffer);
  523. return binaryBuffer;
  524. };
  525. /**
  526. * Pads the number to a multiple of 4
  527. * @param num - number to pad
  528. * @returns - padded number
  529. */
  530. _Exporter.prototype._getPadding = function (num) {
  531. var remainder = num % 4;
  532. var padding = remainder === 0 ? remainder : 4 - remainder;
  533. return padding;
  534. };
  535. /**
  536. * Generates a glb file from the json and binary data.
  537. * Returns an object with the glb file name as the key and data as the value.
  538. * @param glTFPrefix
  539. * @returns - object with glb filename as key and data as value
  540. */
  541. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  542. var jsonText = this.generateJSON(true);
  543. var binaryBuffer = this.generateBinary();
  544. var glbFileName = glTFPrefix + '.glb';
  545. var headerLength = 12;
  546. var chunkLengthPrefix = 8;
  547. var jsonLength = jsonText.length;
  548. var imageByteLength = 0;
  549. for (var key in this.imageData) {
  550. imageByteLength += this.imageData[key].data.byteLength;
  551. }
  552. var jsonPadding = this._getPadding(jsonLength);
  553. var binPadding = this._getPadding(binaryBuffer.byteLength);
  554. var imagePadding = this._getPadding(imageByteLength);
  555. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  556. //header
  557. var headerBuffer = new ArrayBuffer(headerLength);
  558. var headerBufferView = new DataView(headerBuffer);
  559. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  560. headerBufferView.setUint32(4, 2, true); // version
  561. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  562. //json chunk
  563. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  564. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  565. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  566. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  567. //json chunk bytes
  568. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  569. for (var i = 0; i < jsonLength; ++i) {
  570. jsonData[i] = jsonText.charCodeAt(i);
  571. }
  572. //json padding
  573. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  574. for (var i = 0; i < jsonPadding; ++i) {
  575. jsonPaddingView[i] = 0x20;
  576. }
  577. //binary chunk
  578. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  579. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  580. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  581. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  582. // binary padding
  583. var binPaddingBuffer = new ArrayBuffer(binPadding);
  584. var binPaddingView = new Uint8Array(binPaddingBuffer);
  585. for (var i = 0; i < binPadding; ++i) {
  586. binPaddingView[i] = 0;
  587. }
  588. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  589. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  590. for (var i = 0; i < imagePadding; ++i) {
  591. imagePaddingView[i] = 0;
  592. }
  593. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  594. // binary data
  595. for (var key in this.imageData) {
  596. glbData.push(this.imageData[key].data.buffer);
  597. }
  598. glbData.push(binPaddingBuffer);
  599. glbData.push(imagePaddingBuffer);
  600. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  601. var container = new BABYLON._GLTFData();
  602. container.glTFFiles[glbFileName] = glbFile;
  603. return container;
  604. };
  605. /**
  606. * Sets the TRS for each node
  607. * @param node - glTF Node for storing the transformation data.
  608. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  609. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  610. */
  611. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh, useRightHandedSystem) {
  612. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  613. if (useRightHandedSystem) {
  614. node.translation = babylonMesh.position.asArray();
  615. }
  616. else {
  617. node.translation = [babylonMesh.position.x, babylonMesh.position.y, -babylonMesh.position.z];
  618. }
  619. }
  620. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  621. if (useRightHandedSystem) {
  622. node.scale = babylonMesh.scaling.asArray();
  623. }
  624. else {
  625. node.scale = [babylonMesh.scaling.x, babylonMesh.scaling.y, -babylonMesh.scaling.z];
  626. }
  627. }
  628. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  629. if (babylonMesh.rotationQuaternion) {
  630. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  631. }
  632. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  633. if (useRightHandedSystem) {
  634. node.rotation = rotationQuaternion.asArray();
  635. }
  636. else {
  637. node.rotation = [-rotationQuaternion.x, -rotationQuaternion.y, rotationQuaternion.z, rotationQuaternion.w];
  638. }
  639. }
  640. };
  641. /**
  642. * Creates a bufferview based on the vertices type for the Babylon mesh
  643. * @param kind - Indicates the type of vertices data.
  644. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  645. * @param byteOffset - The offset from the buffer to start indexing from.
  646. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  647. * @param dataBuffer - The buffer to write the bufferview data to.
  648. * @returns bytelength of the bufferview data.
  649. */
  650. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  651. var bufferMesh = null;
  652. var byteLength = 0;
  653. if (babylonMesh instanceof BABYLON.Mesh) {
  654. bufferMesh = babylonMesh;
  655. }
  656. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  657. bufferMesh = babylonMesh.sourceMesh;
  658. }
  659. if (bufferMesh !== null) {
  660. var vertexBuffer = null;
  661. var vertexBufferOffset = null;
  662. var vertexData = null;
  663. var vertexStrideSize = null;
  664. if (bufferMesh.getVerticesDataKinds().indexOf(kind) > -1) {
  665. vertexBuffer = bufferMesh.getVertexBuffer(kind);
  666. vertexBufferOffset = vertexBuffer.getOffset();
  667. vertexData = vertexBuffer.getData();
  668. vertexStrideSize = vertexBuffer.getStrideSize();
  669. if (dataBuffer && vertexData) {
  670. byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer, useRightHandedSystem);
  671. byteOffset += byteLength;
  672. }
  673. else {
  674. var bufferViewName = null;
  675. switch (kind) {
  676. case BABYLON.VertexBuffer.PositionKind: {
  677. byteLength = vertexData.length * 4;
  678. bufferViewName = "Position - " + bufferMesh.name;
  679. break;
  680. }
  681. case BABYLON.VertexBuffer.NormalKind: {
  682. byteLength = vertexData.length * 4;
  683. bufferViewName = "Normal - " + bufferMesh.name;
  684. break;
  685. }
  686. case BABYLON.VertexBuffer.TangentKind: {
  687. byteLength = vertexData.length * 4;
  688. bufferViewName = "Tangent - " + bufferMesh.name;
  689. break;
  690. }
  691. case BABYLON.VertexBuffer.ColorKind: {
  692. byteLength = vertexData.length * 4;
  693. bufferViewName = "Color - " + bufferMesh.name;
  694. break;
  695. }
  696. case BABYLON.VertexBuffer.UVKind: {
  697. byteLength = vertexData.length * 4;
  698. bufferViewName = "TexCoord 0 - " + bufferMesh.name;
  699. break;
  700. }
  701. case BABYLON.VertexBuffer.UV2Kind: {
  702. byteLength = vertexData.length * 4;
  703. bufferViewName = "TexCoord 1 - " + bufferMesh.name;
  704. break;
  705. }
  706. default: {
  707. BABYLON.Tools.Warn("Unsupported VertexBuffer kind: " + kind);
  708. }
  709. }
  710. if (bufferViewName !== null) {
  711. var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, bufferViewName);
  712. byteOffset += byteLength;
  713. this.bufferViews.push(bufferView);
  714. }
  715. }
  716. }
  717. }
  718. return byteLength;
  719. };
  720. /**
  721. * Sets data for the primitive attributes of each submesh
  722. * @param mesh - glTF Mesh object to store the primitive attribute information.
  723. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  724. * @param byteOffset - The offset in bytes of the buffer data.
  725. * @param useRightHandedSystem - Indicates whether the data should be modified for a right or left handed coordinate system.
  726. * @param dataBuffer - Buffer to write the attribute data to.
  727. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  728. */
  729. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer) {
  730. var bufferMesh = null;
  731. if (babylonMesh instanceof BABYLON.Mesh) {
  732. bufferMesh = babylonMesh;
  733. }
  734. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  735. bufferMesh = babylonMesh.sourceMesh;
  736. }
  737. var positionBufferViewIndex = null;
  738. var normalBufferViewIndex = null;
  739. var colorBufferViewIndex = null;
  740. var tangentBufferViewIndex = null;
  741. var texCoord0BufferViewIndex = null;
  742. var texCoord1BufferViewIndex = null;
  743. var indexBufferViewIndex = null;
  744. if (bufferMesh !== null) {
  745. // For each BabylonMesh, create bufferviews for each 'kind'
  746. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  747. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.PositionKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  748. positionBufferViewIndex = this.bufferViews.length - 1;
  749. }
  750. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  751. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.NormalKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  752. normalBufferViewIndex = this.bufferViews.length - 1;
  753. }
  754. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  755. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.ColorKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  756. colorBufferViewIndex = this.bufferViews.length - 1;
  757. }
  758. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  759. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.TangentKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  760. colorBufferViewIndex = this.bufferViews.length - 1;
  761. }
  762. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  763. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UVKind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  764. texCoord0BufferViewIndex = this.bufferViews.length - 1;
  765. }
  766. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  767. byteOffset += this.createBufferViewKind(BABYLON.VertexBuffer.UV2Kind, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  768. texCoord1BufferViewIndex = this.bufferViews.length - 1;
  769. }
  770. if (bufferMesh.getTotalIndices() > 0) {
  771. var indices = bufferMesh.getIndices();
  772. if (dataBuffer) {
  773. var end = indices.length;
  774. var byteOff = byteOffset;
  775. for (var k = 0; k < end; ++k) {
  776. dataBuffer.setUint32(byteOff, indices[k], true);
  777. byteOff += 4;
  778. }
  779. byteOffset = byteOff;
  780. }
  781. else {
  782. var byteLength = indices.length * 4;
  783. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  784. byteOffset += byteLength;
  785. this.bufferViews.push(bufferView);
  786. indexBufferViewIndex = this.bufferViews.length - 1;
  787. }
  788. }
  789. }
  790. // go through all mesh primitives (submeshes)
  791. for (var j = 0; j < babylonMesh.subMeshes.length; ++j) {
  792. var submesh = babylonMesh.subMeshes[j];
  793. var meshPrimitive = { attributes: {} };
  794. if (bufferMesh !== null) {
  795. // Create a bufferview storing all the positions
  796. if (!dataBuffer) {
  797. // Loop through each attribute of the submesh (mesh primitive)
  798. if (positionBufferViewIndex !== null) {
  799. var positionVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  800. var positions = positionVertexBuffer.getData();
  801. var positionStrideSize = positionVertexBuffer.getStrideSize();
  802. // Create accessor
  803. var result = this.calculateMinMax(positions, 0, positions.length / positionStrideSize, positionStrideSize, useRightHandedSystem);
  804. var accessor = this.createAccessor(positionBufferViewIndex, "Position", "VEC3" /* VEC3 */, 5126 /* FLOAT */, positions.length / positionStrideSize, 0, result.min, result.max);
  805. this.accessors.push(accessor);
  806. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  807. }
  808. if (normalBufferViewIndex !== null) {
  809. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  810. var normals = normalVertexBuffer.getData();
  811. var normalStrideSize = normalVertexBuffer.getStrideSize();
  812. // Create accessor
  813. var accessor = this.createAccessor(normalBufferViewIndex, "Normal", "VEC3" /* VEC3 */, 5126 /* FLOAT */, normals.length / normalStrideSize);
  814. this.accessors.push(accessor);
  815. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  816. }
  817. if (tangentBufferViewIndex !== null) {
  818. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  819. var tangents = tangentVertexBuffer.getData();
  820. var tangentStrideSize = tangentVertexBuffer.getStrideSize();
  821. // Create accessor
  822. var accessor = this.createAccessor(tangentBufferViewIndex, "Tangent", "VEC4" /* VEC4 */, 5126 /* FLOAT */, tangents.length / tangentStrideSize);
  823. this.accessors.push(accessor);
  824. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  825. }
  826. if (colorBufferViewIndex !== null) {
  827. var colorVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.ColorKind);
  828. var colors = colorVertexBuffer.getData();
  829. var colorStrideSize = colorVertexBuffer.getStrideSize();
  830. // Create accessor
  831. var accessor = this.createAccessor(colorBufferViewIndex, "Color", "VEC4" /* VEC4 */, 5126 /* FLOAT */, colors.length / colorStrideSize);
  832. this.accessors.push(accessor);
  833. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  834. }
  835. if (texCoord0BufferViewIndex !== null) {
  836. // Create accessor
  837. var texCoord0VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UVKind);
  838. var texCoord0s = texCoord0VertexBuffer.getData();
  839. var texCoord0StrideSize = texCoord0VertexBuffer.getStrideSize();
  840. var accessor = this.createAccessor(texCoord0BufferViewIndex, "Texture Coords 0", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord0s.length / texCoord0StrideSize);
  841. this.accessors.push(accessor);
  842. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  843. }
  844. if (texCoord1BufferViewIndex !== null) {
  845. // Create accessor
  846. var texCoord1VertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind);
  847. var texCoord1s = texCoord1VertexBuffer.getData();
  848. var texCoord1StrideSize = texCoord1VertexBuffer.getStrideSize();
  849. var accessor = this.createAccessor(texCoord1BufferViewIndex, "Texture Coords 1", "VEC2" /* VEC2 */, 5126 /* FLOAT */, texCoord1s.length / texCoord1StrideSize);
  850. this.accessors.push(accessor);
  851. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  852. }
  853. if (indexBufferViewIndex) {
  854. // Create accessor
  855. var accessor = this.createAccessor(indexBufferViewIndex, "Indices", "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4);
  856. this.accessors.push(accessor);
  857. meshPrimitive.indices = this.accessors.length - 1;
  858. }
  859. }
  860. if (bufferMesh.material) {
  861. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  862. var materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  863. meshPrimitive.material = materialIndex;
  864. }
  865. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  866. var babylonMultiMaterial = bufferMesh.material;
  867. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  868. if (material !== null) {
  869. var materialIndex = babylonMesh.getScene().materials.indexOf(material);
  870. meshPrimitive.material = materialIndex;
  871. }
  872. }
  873. else {
  874. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  875. }
  876. }
  877. mesh.primitives.push(meshPrimitive);
  878. }
  879. }
  880. return byteOffset;
  881. };
  882. /**
  883. * Creates a glTF scene based on the array of meshes.
  884. * Returns the the total byte offset.
  885. * @param babylonScene - Babylon scene to get the mesh data from.
  886. * @param byteOffset - Offset to start from in bytes.
  887. * @param dataBuffer - Buffer to write geometry data to.
  888. * @returns bytelength + byteoffset
  889. */
  890. _Exporter.prototype.createScene = function (babylonScene, byteOffset, dataBuffer) {
  891. if (babylonScene.meshes.length > 0) {
  892. var babylonMeshes = babylonScene.meshes;
  893. var scene = { nodes: new Array() };
  894. if (dataBuffer == null) {
  895. GLTF2._GLTFMaterial.ConvertMaterialsToGLTF(babylonScene.materials, "image/jpeg" /* JPEG */, this.images, this.textures, this.materials, this.imageData, true);
  896. }
  897. for (var i = 0; i < babylonMeshes.length; ++i) {
  898. if (this.options &&
  899. this.options.shouldExportMesh !== undefined &&
  900. !this.options.shouldExportMesh(babylonMeshes[i])) {
  901. continue;
  902. }
  903. else {
  904. // create node to hold translation/rotation/scale and the mesh
  905. var node = { mesh: -1 };
  906. var babylonMesh = babylonMeshes[i];
  907. var useRightHandedSystem = babylonMesh.getScene().useRightHandedSystem;
  908. // Set transformation
  909. this.setNodeTransformation(node, babylonMesh, useRightHandedSystem);
  910. // create mesh
  911. var mesh = { primitives: new Array() };
  912. mesh.primitives = [];
  913. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, useRightHandedSystem, dataBuffer);
  914. // go through all mesh primitives (submeshes)
  915. this.meshes.push(mesh);
  916. node.mesh = this.meshes.length - 1;
  917. if (babylonMesh.name) {
  918. node.name = babylonMesh.name;
  919. }
  920. this.nodes.push(node);
  921. scene.nodes.push(this.nodes.length - 1);
  922. }
  923. }
  924. this.scenes.push(scene);
  925. }
  926. return byteOffset;
  927. };
  928. return _Exporter;
  929. }());
  930. GLTF2._Exporter = _Exporter;
  931. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  932. })(BABYLON || (BABYLON = {}));
  933. //# sourceMappingURL=babylon.glTFExporter.js.map
  934. var BABYLON;
  935. (function (BABYLON) {
  936. /**
  937. * Class for holding and downloading glTF file data
  938. */
  939. var _GLTFData = /** @class */ (function () {
  940. /**
  941. * Initializes the glTF file object.
  942. */
  943. function _GLTFData() {
  944. this.glTFFiles = {};
  945. }
  946. /**
  947. * Downloads the glTF data as files based on their names and data.
  948. */
  949. _GLTFData.prototype.downloadFiles = function () {
  950. /**
  951. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  952. * @param str - Source string.
  953. * @param suffix - Suffix to search for in the source string.
  954. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  955. */
  956. function endsWith(str, suffix) {
  957. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  958. }
  959. for (var key in this.glTFFiles) {
  960. var link = document.createElement('a');
  961. document.body.appendChild(link);
  962. link.setAttribute("type", "hidden");
  963. link.download = key;
  964. var blob = this.glTFFiles[key];
  965. var mimeType = void 0;
  966. if (endsWith(key, ".glb")) {
  967. mimeType = { type: "model/gltf-binary" };
  968. }
  969. else if (endsWith(key, ".bin")) {
  970. mimeType = { type: "application/octet-stream" };
  971. }
  972. else if (endsWith(key, ".gltf")) {
  973. mimeType = { type: "model/gltf+json" };
  974. }
  975. else if (endsWith(key, ".jpeg" || ".jpg")) {
  976. mimeType = { type: "image/jpeg" /* JPEG */ };
  977. }
  978. else if (endsWith(key, ".png")) {
  979. mimeType = { type: "image/png" /* PNG */ };
  980. }
  981. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  982. link.click();
  983. }
  984. };
  985. return _GLTFData;
  986. }());
  987. BABYLON._GLTFData = _GLTFData;
  988. })(BABYLON || (BABYLON = {}));
  989. //# sourceMappingURL=babylon.glTFData.js.map
  990. var BABYLON;
  991. (function (BABYLON) {
  992. var GLTF2;
  993. (function (GLTF2) {
  994. /**
  995. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  996. */
  997. var _GLTFMaterial = /** @class */ (function () {
  998. function _GLTFMaterial() {
  999. }
  1000. /**
  1001. * Gets the materials from a Babylon scene and converts them to glTF materials.
  1002. * @param scene
  1003. * @param mimeType
  1004. * @param images
  1005. * @param textures
  1006. * @param materials
  1007. * @param imageData
  1008. * @param hasTextureCoords
  1009. */
  1010. _GLTFMaterial.ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1011. for (var i = 0; i < babylonMaterials.length; ++i) {
  1012. var babylonMaterial = babylonMaterials[i];
  1013. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1014. _GLTFMaterial.ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  1015. }
  1016. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1017. _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  1018. }
  1019. }
  1020. };
  1021. /**
  1022. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  1023. * @param babylonStandardMaterial
  1024. * @returns - glTF Metallic Roughness Material representation
  1025. */
  1026. _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1027. var P0 = new BABYLON.Vector2(0, 1);
  1028. var P1 = new BABYLON.Vector2(0, 0.1);
  1029. var P2 = new BABYLON.Vector2(0, 0.1);
  1030. var P3 = new BABYLON.Vector2(1300, 0.1);
  1031. /**
  1032. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  1033. * @param t - a value between 0 and 1.
  1034. * @param p0 - first control point.
  1035. * @param p1 - second control point.
  1036. * @param p2 - third control point.
  1037. * @param p3 - fourth control point.
  1038. * @returns - number result of cubic bezier curve at the specified t.
  1039. */
  1040. function cubicBezierCurve(t, p0, p1, p2, p3) {
  1041. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1042. 3 * (1 - t) * (1 - t) * t * p1 +
  1043. 3 * (1 - t) * t * t * p2 +
  1044. t * t * t * p3);
  1045. }
  1046. /**
  1047. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1048. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1049. * and roughness on the ordinant axis (y-axis).
  1050. * @param specularPower - specular power of standard material.
  1051. * @returns - Number representing the roughness value.
  1052. */
  1053. function solveForRoughness(specularPower) {
  1054. var t = Math.pow(specularPower / P3.x, 0.333333);
  1055. return cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1056. }
  1057. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1058. var opacity = babylonStandardMaterial.alpha;
  1059. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this.maxSpecularPower);
  1060. var roughness = solveForRoughness(specularPower);
  1061. var glTFPbrMetallicRoughness = {
  1062. baseColorFactor: [
  1063. diffuse.r,
  1064. diffuse.g,
  1065. diffuse.b,
  1066. opacity
  1067. ],
  1068. metallicFactor: 0,
  1069. roughnessFactor: roughness,
  1070. };
  1071. return glTFPbrMetallicRoughness;
  1072. };
  1073. /**
  1074. * Computes the metallic factor
  1075. * @param diffuse - diffused value
  1076. * @param specular - specular value
  1077. * @param oneMinusSpecularStrength - one minus the specular strength
  1078. * @returns - metallic value
  1079. */
  1080. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1081. if (specular < _GLTFMaterial.dielectricSpecular.r) {
  1082. _GLTFMaterial.dielectricSpecular;
  1083. return 0;
  1084. }
  1085. var a = _GLTFMaterial.dielectricSpecular.r;
  1086. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial.dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial.dielectricSpecular.r;
  1087. var c = _GLTFMaterial.dielectricSpecular.r - specular;
  1088. var D = b * b - 4.0 * a * c;
  1089. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1090. };
  1091. /**
  1092. * Gets the glTF alpha mode from the Babylon Material
  1093. * @param babylonMaterial - Babylon Material
  1094. * @returns - The Babylon alpha mode value
  1095. */
  1096. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  1097. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1098. var babylonStandardMaterial = babylonMaterial;
  1099. if ((babylonStandardMaterial.alpha != 1.0) ||
  1100. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1101. (babylonStandardMaterial.opacityTexture != null)) {
  1102. return "BLEND" /* BLEND */;
  1103. }
  1104. else {
  1105. return "OPAQUE" /* OPAQUE */;
  1106. }
  1107. }
  1108. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1109. var babylonPBRMetallicRoughness = babylonMaterial;
  1110. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1111. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1112. return "OPAQUE" /* OPAQUE */;
  1113. }
  1114. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1115. return "BLEND" /* BLEND */;
  1116. }
  1117. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1118. return "MASK" /* MASK */;
  1119. }
  1120. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1121. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1122. return "BLEND" /* BLEND */;
  1123. }
  1124. default: {
  1125. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1126. }
  1127. }
  1128. }
  1129. else {
  1130. throw new Error("Unsupported Babylon material type");
  1131. }
  1132. };
  1133. /**
  1134. * Converts a Babylon Standard Material to a glTF Material.
  1135. * @param babylonStandardMaterial - BJS Standard Material.
  1136. * @param mimeType - mime type to use for the textures.
  1137. * @param images - array of glTF image interfaces.
  1138. * @param textures - array of glTF texture interfaces.
  1139. * @param materials - array of glTF material interfaces.
  1140. * @param imageData - map of image file name to data.
  1141. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1142. */
  1143. _GLTFMaterial.ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1144. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1145. var glTFPbrMetallicRoughness = _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1146. var glTFMaterial = { name: babylonStandardMaterial.name };
  1147. if (babylonStandardMaterial.backFaceCulling) {
  1148. if (!babylonStandardMaterial.twoSidedLighting) {
  1149. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1150. }
  1151. glTFMaterial.doubleSided = true;
  1152. }
  1153. if (hasTextureCoords) {
  1154. if (babylonStandardMaterial.diffuseTexture) {
  1155. var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1156. if (glTFTexture != null) {
  1157. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1158. }
  1159. }
  1160. if (babylonStandardMaterial.bumpTexture) {
  1161. var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1162. if (glTFTexture) {
  1163. glTFMaterial.normalTexture = glTFTexture;
  1164. }
  1165. }
  1166. if (babylonStandardMaterial.emissiveTexture) {
  1167. var glTFEmissiveTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1168. if (glTFEmissiveTexture) {
  1169. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1170. }
  1171. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1172. }
  1173. if (babylonStandardMaterial.ambientTexture) {
  1174. var glTFOcclusionTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1175. if (glTFOcclusionTexture) {
  1176. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  1177. }
  1178. }
  1179. }
  1180. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1181. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1182. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1183. }
  1184. else {
  1185. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1186. }
  1187. }
  1188. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1189. materials.push(glTFMaterial);
  1190. };
  1191. /**
  1192. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1193. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1194. * @param mimeType - mime type to use for the textures.
  1195. * @param images - array of glTF image interfaces.
  1196. * @param textures - array of glTF texture interfaces.
  1197. * @param materials - array of glTF material interfaces.
  1198. * @param imageData - map of image file name to data.
  1199. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1200. */
  1201. _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1202. var glTFPbrMetallicRoughness = {};
  1203. if (babylonPBRMetalRoughMaterial.baseColor) {
  1204. glTFPbrMetallicRoughness.baseColorFactor = [
  1205. babylonPBRMetalRoughMaterial.baseColor.r,
  1206. babylonPBRMetalRoughMaterial.baseColor.g,
  1207. babylonPBRMetalRoughMaterial.baseColor.b,
  1208. babylonPBRMetalRoughMaterial.alpha
  1209. ];
  1210. }
  1211. if (babylonPBRMetalRoughMaterial.metallic != null) {
  1212. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1213. }
  1214. if (babylonPBRMetalRoughMaterial.roughness != null) {
  1215. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1216. }
  1217. var glTFMaterial = {
  1218. name: babylonPBRMetalRoughMaterial.name
  1219. };
  1220. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1221. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1222. }
  1223. if (hasTextureCoords) {
  1224. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1225. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1226. if (glTFTexture != null) {
  1227. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1228. }
  1229. }
  1230. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1231. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1232. if (glTFTexture) {
  1233. glTFMaterial.normalTexture = glTFTexture;
  1234. }
  1235. }
  1236. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1237. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1238. if (glTFTexture) {
  1239. glTFMaterial.occlusionTexture = glTFTexture;
  1240. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1241. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1242. }
  1243. }
  1244. }
  1245. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1246. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1247. if (glTFTexture != null) {
  1248. glTFMaterial.emissiveTexture = glTFTexture;
  1249. }
  1250. }
  1251. }
  1252. if (babylonPBRMetalRoughMaterial.emissiveColor.equalsFloats(0.0, 0.0, 0.0)) {
  1253. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1254. }
  1255. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1256. var alphaMode = _GLTFMaterial.GetAlphaMode(babylonPBRMetalRoughMaterial);
  1257. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1258. glTFMaterial.alphaMode = alphaMode;
  1259. if (alphaMode === "BLEND" /* BLEND */) {
  1260. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1261. }
  1262. }
  1263. }
  1264. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1265. materials.push(glTFMaterial);
  1266. };
  1267. /**
  1268. * Extracts a texture from a Babylon texture into file data and glTF data.
  1269. * @param babylonTexture - Babylon texture to extract.
  1270. * @param mimeType - Mime Type of the babylonTexture.
  1271. * @param images - Array of glTF images.
  1272. * @param textures - Array of glTF textures.
  1273. * @param imageData - map of image file name and data.
  1274. * @return - glTF texture, or null if the texture format is not supported.
  1275. */
  1276. _GLTFMaterial.ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1277. var textureInfo = null;
  1278. var glTFTexture = {
  1279. source: images.length
  1280. };
  1281. var textureName = "texture_" + (textures.length - 1).toString();
  1282. var textureData = babylonTexture.getInternalTexture();
  1283. if (textureData != null) {
  1284. textureName = textureData.url;
  1285. }
  1286. textureName = BABYLON.Tools.GetFilename(textureName);
  1287. var baseFile = textureName.split('.')[0];
  1288. var extension = "";
  1289. if (mimeType === "image/jpeg" /* JPEG */) {
  1290. extension = ".jpg";
  1291. }
  1292. else if (mimeType === "image/png" /* PNG */) {
  1293. extension = ".png";
  1294. }
  1295. else {
  1296. BABYLON.Tools.Error("Unsupported mime type " + mimeType);
  1297. }
  1298. textureName = baseFile + extension;
  1299. var pixels = babylonTexture.readPixels();
  1300. var imageCanvas = document.createElement('canvas');
  1301. imageCanvas.id = "ImageCanvas";
  1302. var ctx = imageCanvas.getContext('2d');
  1303. var size = babylonTexture.getSize();
  1304. imageCanvas.width = size.width;
  1305. imageCanvas.height = size.height;
  1306. var imgData = ctx.createImageData(size.width, size.height);
  1307. imgData.data.set(pixels);
  1308. ctx.putImageData(imgData, 0, 0);
  1309. var base64Data = imageCanvas.toDataURL(mimeType);
  1310. var binStr = atob(base64Data.split(',')[1]);
  1311. var arr = new Uint8Array(binStr.length);
  1312. for (var i = 0; i < binStr.length; ++i) {
  1313. arr[i] = binStr.charCodeAt(i);
  1314. }
  1315. var imageValues = { data: arr, mimeType: mimeType };
  1316. imageData[textureName] = imageValues;
  1317. if (mimeType === "image/jpeg" /* JPEG */) {
  1318. var glTFImage = {
  1319. uri: textureName
  1320. };
  1321. var foundIndex = -1;
  1322. for (var i = 0; i < images.length; ++i) {
  1323. if (images[i].uri === textureName) {
  1324. foundIndex = i;
  1325. break;
  1326. }
  1327. }
  1328. if (foundIndex === -1) {
  1329. images.push(glTFImage);
  1330. glTFTexture.source = images.length - 1;
  1331. textures.push({
  1332. source: images.length - 1
  1333. });
  1334. textureInfo = {
  1335. index: images.length - 1
  1336. };
  1337. }
  1338. else {
  1339. glTFTexture.source = foundIndex;
  1340. textureInfo = {
  1341. index: foundIndex
  1342. };
  1343. }
  1344. }
  1345. return textureInfo;
  1346. };
  1347. /**
  1348. * Represents the dielectric specular values for R, G and B.
  1349. */
  1350. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1351. /**
  1352. * Allows the maximum specular power to be defined for material calculations.
  1353. */
  1354. _GLTFMaterial.maxSpecularPower = 1024;
  1355. return _GLTFMaterial;
  1356. }());
  1357. GLTF2._GLTFMaterial = _GLTFMaterial;
  1358. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1361. (function universalModuleDefinition(root, factory) {
  1362. var f = factory();
  1363. if (root && root["BABYLON"]) {
  1364. return;
  1365. }
  1366. if(typeof exports === 'object' && typeof module === 'object')
  1367. module.exports = f;
  1368. else if(typeof define === 'function' && define.amd)
  1369. define(["BJSSerializers"], factory);
  1370. else if(typeof exports === 'object')
  1371. exports["BJSSerializers"] = f;
  1372. else {
  1373. root["BABYLON"] = f;
  1374. }
  1375. })(this, function() {
  1376. return BABYLON;
  1377. });