babylonjs.serializers.js 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. 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;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory(require("babylonjs"));
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs-serializers", ["babylonjs"], factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs-serializers"] = factory(require("babylonjs"));
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function(BABYLON) {
  28. var BABYLON;
  29. (function (BABYLON) {
  30. var OBJExport = /** @class */ (function () {
  31. function OBJExport() {
  32. }
  33. //Exports the geometrys of a Mesh array in .OBJ file format (text)
  34. OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
  35. var output = [];
  36. var v = 1;
  37. if (materials) {
  38. if (!matlibname) {
  39. matlibname = 'mat';
  40. }
  41. output.push("mtllib " + matlibname + ".mtl");
  42. }
  43. for (var j = 0; j < mesh.length; j++) {
  44. output.push("g object" + j);
  45. output.push("o object_" + j);
  46. //Uses the position of the item in the scene, to the file (this back to normal in the end)
  47. var lastMatrix = null;
  48. if (globalposition) {
  49. var newMatrix = BABYLON.Matrix.Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
  50. lastMatrix = BABYLON.Matrix.Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
  51. mesh[j].bakeTransformIntoVertices(newMatrix);
  52. }
  53. //TODO: submeshes (groups)
  54. //TODO: smoothing groups (s 1, s off);
  55. if (materials) {
  56. var mat = mesh[j].material;
  57. if (mat) {
  58. output.push("usemtl " + mat.id);
  59. }
  60. }
  61. var g = mesh[j].geometry;
  62. if (!g) {
  63. continue;
  64. }
  65. var trunkVerts = g.getVerticesData('position');
  66. var trunkNormals = g.getVerticesData('normal');
  67. var trunkUV = g.getVerticesData('uv');
  68. var trunkFaces = g.getIndices();
  69. var curV = 0;
  70. if (!trunkVerts || !trunkNormals || !trunkUV || !trunkFaces) {
  71. continue;
  72. }
  73. for (var i = 0; i < trunkVerts.length; i += 3) {
  74. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  75. curV++;
  76. }
  77. for (i = 0; i < trunkNormals.length; i += 3) {
  78. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  79. }
  80. for (i = 0; i < trunkUV.length; i += 2) {
  81. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  82. }
  83. for (i = 0; i < trunkFaces.length; i += 3) {
  84. output.push("f " + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) +
  85. " " + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) +
  86. " " + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v));
  87. }
  88. //back de previous matrix, to not change the original mesh in the scene
  89. if (globalposition && lastMatrix) {
  90. mesh[j].bakeTransformIntoVertices(lastMatrix);
  91. }
  92. v += curV;
  93. }
  94. var text = output.join("\n");
  95. return (text);
  96. };
  97. //Exports the material(s) of a mesh in .MTL file format (text)
  98. //TODO: Export the materials of mesh array
  99. OBJExport.MTL = function (mesh) {
  100. var output = [];
  101. var m = mesh.material;
  102. output.push("newmtl mat1");
  103. output.push(" Ns " + m.specularPower.toFixed(4));
  104. output.push(" Ni 1.5000");
  105. output.push(" d " + m.alpha.toFixed(4));
  106. output.push(" Tr 0.0000");
  107. output.push(" Tf 1.0000 1.0000 1.0000");
  108. output.push(" illum 2");
  109. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  110. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  111. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  112. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  113. //TODO: uv scale, offset, wrap
  114. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  115. var uvscale = "";
  116. if (m.ambientTexture) {
  117. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  118. }
  119. if (m.diffuseTexture) {
  120. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  121. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  122. }
  123. if (m.specularTexture) {
  124. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  125. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  126. if (m.useGlossinessFromSpecularMapAlpha) {
  127. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  128. }
  129. */
  130. }
  131. /* TODO: emissive texture not in .MAT format (???)
  132. if (m.emissiveTexture) {
  133. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  134. }
  135. */
  136. if (m.bumpTexture) {
  137. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  138. }
  139. if (m.opacityTexture) {
  140. output.push(" map_d " + uvscale + m.opacityTexture.name);
  141. }
  142. var text = output.join("\n");
  143. return (text);
  144. };
  145. return OBJExport;
  146. }());
  147. BABYLON.OBJExport = OBJExport;
  148. })(BABYLON || (BABYLON = {}));
  149. //# sourceMappingURL=babylon.objSerializer.js.map
  150. var BABYLON;
  151. (function (BABYLON) {
  152. ;
  153. /**
  154. * Class for generating glTF data from a Babylon scene.
  155. */
  156. var GLTF2Export = /** @class */ (function () {
  157. function GLTF2Export() {
  158. }
  159. /**
  160. * Exports the geometry of the scene to .gltf file format.
  161. * @param scene - Babylon scene with scene hierarchy information.
  162. * @param filePrefix - File prefix to use when generating the glTF file.
  163. * @param options - Exporter options.
  164. * @returns - Returns an object with a .gltf file and associates texture names
  165. * as keys and their data and paths as values.
  166. */
  167. GLTF2Export.GLTF = function (scene, filePrefix, options) {
  168. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  169. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  170. if (scene.isReady) {
  171. return gltfGenerator._generateGLTF(glTFPrefix);
  172. }
  173. else {
  174. throw new Error("glTF Serializer: Scene is not ready!");
  175. }
  176. };
  177. /**
  178. * Exports the geometry of the scene to .glb file format.
  179. * @param scene - Babylon scene with scene hierarchy information.
  180. * @param filePrefix - File prefix to use when generating glb file.
  181. * @param options - Exporter options.
  182. * @returns - Returns an object with a .glb filename as key and data as value
  183. */
  184. GLTF2Export.GLB = function (scene, filePrefix, options) {
  185. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  186. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  187. if (scene.isReady) {
  188. return gltfGenerator._generateGLB(glTFPrefix);
  189. }
  190. else {
  191. throw new Error("glTF Serializer: Scene is not ready!");
  192. }
  193. };
  194. return GLTF2Export;
  195. }());
  196. BABYLON.GLTF2Export = GLTF2Export;
  197. })(BABYLON || (BABYLON = {}));
  198. //# sourceMappingURL=babylon.glTFSerializer.js.map
  199. /**
  200. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally.
  201. * @ignore - capitalization of GLTF2 module.
  202. */
  203. var BABYLON;
  204. (function (BABYLON) {
  205. var GLTF2;
  206. (function (GLTF2) {
  207. /**
  208. * Converts Babylon Scene into glTF 2.0.
  209. */
  210. var _Exporter = /** @class */ (function () {
  211. /**
  212. * Creates a glTF Exporter instance, which can accept optional exporter options.
  213. * @param babylonScene - Babylon scene object
  214. * @param options - Options to modify the behavior of the exporter.
  215. */
  216. function _Exporter(babylonScene, options) {
  217. this.asset = { generator: "BabylonJS", version: "2.0" };
  218. this.babylonScene = babylonScene;
  219. this.bufferViews = new Array();
  220. this.accessors = new Array();
  221. this.meshes = new Array();
  222. this.scenes = new Array();
  223. this.nodes = new Array();
  224. this.images = new Array();
  225. this.materials = new Array();
  226. this.textures = new Array();
  227. this.imageData = {};
  228. this.convertToRightHandedSystem = !this.babylonScene.useRightHandedSystem;
  229. if (options) {
  230. this.options = options;
  231. }
  232. }
  233. /**
  234. * Creates a buffer view based on teh supplied arguments
  235. * @param bufferIndex - index value of the specified buffer
  236. * @param byteOffset - byte offset value
  237. * @param byteLength - byte length of the bufferView
  238. * @param byteStride - byte distance between conequential elements.
  239. * @param name - name of the buffer view
  240. * @returns - bufferView for glTF
  241. */
  242. _Exporter.prototype.createBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  243. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  244. if (byteOffset) {
  245. bufferview.byteOffset = byteOffset;
  246. }
  247. if (name) {
  248. bufferview.name = name;
  249. }
  250. if (byteStride) {
  251. bufferview.byteStride = byteStride;
  252. }
  253. return bufferview;
  254. };
  255. /**
  256. * Creates an accessor based on the supplied arguments
  257. * @param bufferviewIndex - The index of the bufferview referenced by this accessor.
  258. * @param name - The name of the accessor.
  259. * @param type - The type of the accessor.
  260. * @param componentType - The datatype of components in the attribute.
  261. * @param count - The number of attributes referenced by this accessor.
  262. * @param byteOffset - The offset relative to the start of the bufferView in bytes.
  263. * @param min - Minimum value of each component in this attribute.
  264. * @param max - Maximum value of each component in this attribute.
  265. * @returns - accessor for glTF
  266. */
  267. _Exporter.prototype.createAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  268. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  269. if (min) {
  270. accessor.min = min;
  271. }
  272. if (max) {
  273. accessor.max = max;
  274. }
  275. if (byteOffset) {
  276. accessor.byteOffset = byteOffset;
  277. }
  278. return accessor;
  279. };
  280. /**
  281. * Calculates the minimum and maximum values of an array of position floats.
  282. * @param positions - Positions array of a mesh.
  283. * @param vertexStart - Starting vertex offset to calculate min and max values.
  284. * @param vertexCount - Number of vertices to check for min and max values.
  285. * @returns - min number array and max number array.
  286. */
  287. _Exporter.prototype.calculateMinMaxPositions = function (positions, vertexStart, vertexCount) {
  288. var min = [Infinity, Infinity, Infinity];
  289. var max = [-Infinity, -Infinity, -Infinity];
  290. var positionStrideSize = 3;
  291. var end = vertexStart + vertexCount;
  292. if (vertexCount) {
  293. for (var i = vertexStart; i < end; ++i) {
  294. var indexOffset = positionStrideSize * i;
  295. var position = BABYLON.Vector3.FromArray(positions, indexOffset);
  296. var vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(position).asArray() : position.asArray();
  297. for (var j = 0; j < positionStrideSize; ++j) {
  298. var num = vector[j];
  299. if (num < min[j]) {
  300. min[j] = num;
  301. }
  302. if (num > max[j]) {
  303. max[j] = num;
  304. }
  305. ++indexOffset;
  306. }
  307. }
  308. }
  309. return { min: min, max: max };
  310. };
  311. /**
  312. * Converts a vector3 array to right-handed.
  313. * @param vector - vector3 Array to convert to right-handed.
  314. * @returns - right-handed Vector3 array.
  315. */
  316. _Exporter.GetRightHandedVector3 = function (vector) {
  317. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  318. };
  319. /**
  320. * Converts a vector4 array to right-handed.
  321. * @param vector - vector4 Array to convert to right-handed.
  322. * @returns - right-handed vector4 array.
  323. */
  324. _Exporter.GetRightHandedVector4 = function (vector) {
  325. return new BABYLON.Vector4(vector.x, vector.y, -vector.z, -vector.w);
  326. };
  327. /**
  328. * Converts a quaternion to right-handed.
  329. * @param quaternion - Source quaternion to convert to right-handed.
  330. */
  331. _Exporter.GetRightHandedQuaternion = function (quaternion) {
  332. return new BABYLON.Quaternion(-quaternion.x, -quaternion.y, quaternion.z, quaternion.w);
  333. };
  334. /**
  335. * Writes mesh attribute data to a data buffer.
  336. * Returns the bytelength of the data.
  337. * @param vertexBufferKind - Indicates what kind of vertex data is being passed in.
  338. * @param meshAttributeArray - Array containing the attribute data.
  339. * @param strideSize - Represents the offset between consecutive attributes
  340. * @param byteOffset - The offset to start counting bytes from.
  341. * @param dataBuffer - The buffer to write the binary data to.
  342. * @returns - Byte length of the attribute data.
  343. */
  344. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, strideSize, vertexBufferOffset, byteOffset, dataBuffer) {
  345. var byteOff = byteOffset;
  346. var end = meshAttributeArray.length / strideSize;
  347. var byteLength = 0;
  348. for (var k = 0; k < end; ++k) {
  349. var index = k * strideSize;
  350. var vector = [];
  351. if (vertexBufferKind === BABYLON.VertexBuffer.PositionKind || vertexBufferKind === BABYLON.VertexBuffer.NormalKind) {
  352. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  353. vector = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(vertexData).asArray() : vertexData.asArray();
  354. }
  355. else if (vertexBufferKind === BABYLON.VertexBuffer.TangentKind || vertexBufferKind === BABYLON.VertexBuffer.ColorKind) {
  356. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  357. vector = (this.convertToRightHandedSystem && !(vertexBufferKind === BABYLON.VertexBuffer.ColorKind)) ? _Exporter.GetRightHandedVector4(vertexData).asArray() : vertexData.asArray();
  358. }
  359. else if (vertexBufferKind === BABYLON.VertexBuffer.UVKind || vertexBufferKind === BABYLON.VertexBuffer.UV2Kind) {
  360. vector = [meshAttributeArray[index], meshAttributeArray[index + 1]];
  361. }
  362. else {
  363. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  364. }
  365. for (var i = 0; i < vector.length; ++i) {
  366. dataBuffer.setFloat32(byteOff, vector[i], true);
  367. byteOff += 4;
  368. }
  369. }
  370. byteLength = meshAttributeArray.length * 4;
  371. return byteLength;
  372. };
  373. /**
  374. * Generates glTF json data
  375. * @param shouldUseGlb - Indicates whether the json should be written for a glb file.
  376. * @param glTFPrefix - Text to use when prefixing a glTF file.
  377. * @param prettyPrint - Indicates whether the json file should be pretty printed (true) or not (false).
  378. * @returns - json data as string
  379. */
  380. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  381. var buffer = { byteLength: this.totalByteLength };
  382. var glTF = {
  383. asset: this.asset
  384. };
  385. if (buffer.byteLength) {
  386. glTF.buffers = [buffer];
  387. }
  388. if (this.nodes && this.nodes.length) {
  389. glTF.nodes = this.nodes;
  390. }
  391. if (this.meshes && this.meshes.length) {
  392. glTF.meshes = this.meshes;
  393. }
  394. if (this.scenes && this.scenes.length) {
  395. glTF.scenes = this.scenes;
  396. glTF.scene = 0;
  397. }
  398. if (this.bufferViews && this.bufferViews.length) {
  399. glTF.bufferViews = this.bufferViews;
  400. }
  401. if (this.accessors && this.accessors.length) {
  402. glTF.accessors = this.accessors;
  403. }
  404. if (this.materials && this.materials.length) {
  405. glTF.materials = this.materials;
  406. }
  407. if (this.textures && this.textures.length) {
  408. glTF.textures = this.textures;
  409. }
  410. if (this.images && this.images.length) {
  411. if (!shouldUseGlb) {
  412. glTF.images = this.images;
  413. }
  414. else {
  415. glTF.images = [];
  416. // Replace uri with bufferview and mime type for glb
  417. var imageLength = this.images.length;
  418. var byteOffset = this.totalByteLength;
  419. for (var i = 0; i < imageLength; ++i) {
  420. var image = this.images[i];
  421. if (image.uri) {
  422. var imageData = this.imageData[image.uri];
  423. var imageName = image.uri.split('.')[0] + " image";
  424. var bufferView = this.createBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  425. byteOffset += imageData.data.buffer.byteLength;
  426. this.bufferViews.push(bufferView);
  427. image.bufferView = this.bufferViews.length - 1;
  428. image.name = imageName;
  429. image.mimeType = imageData.mimeType;
  430. image.uri = undefined;
  431. glTF.images.push(image);
  432. }
  433. }
  434. buffer.byteLength = byteOffset;
  435. }
  436. }
  437. if (!shouldUseGlb) {
  438. buffer.uri = glTFPrefix + ".bin";
  439. }
  440. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  441. return jsonText;
  442. };
  443. /**
  444. * Generates data for .gltf and .bin files based on the glTF prefix string
  445. * @param glTFPrefix - Text to use when prefixing a glTF file.
  446. * @returns - GLTFData with glTF file data.
  447. */
  448. _Exporter.prototype._generateGLTF = function (glTFPrefix) {
  449. var binaryBuffer = this.generateBinary();
  450. var jsonText = this.generateJSON(false, glTFPrefix, true);
  451. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  452. var glTFFileName = glTFPrefix + '.gltf';
  453. var glTFBinFile = glTFPrefix + '.bin';
  454. var container = new BABYLON._GLTFData();
  455. container.glTFFiles[glTFFileName] = jsonText;
  456. container.glTFFiles[glTFBinFile] = bin;
  457. if (this.imageData) {
  458. for (var image in this.imageData) {
  459. container.glTFFiles[image] = new Blob([this.imageData[image].data], { type: this.imageData[image].mimeType });
  460. }
  461. }
  462. return container;
  463. };
  464. /**
  465. * Creates a binary buffer for glTF
  466. * @returns - array buffer for binary data
  467. */
  468. _Exporter.prototype.generateBinary = function () {
  469. var byteOffset = 0;
  470. byteOffset = this.createScene(this.babylonScene, byteOffset);
  471. return this.binaryBuffer;
  472. };
  473. /**
  474. * Pads the number to a multiple of 4
  475. * @param num - number to pad
  476. * @returns - padded number
  477. */
  478. _Exporter.prototype._getPadding = function (num) {
  479. var remainder = num % 4;
  480. var padding = remainder === 0 ? remainder : 4 - remainder;
  481. return padding;
  482. };
  483. /**
  484. * Generates a glb file from the json and binary data.
  485. * Returns an object with the glb file name as the key and data as the value.
  486. * @param glTFPrefix
  487. * @returns - object with glb filename as key and data as value
  488. */
  489. _Exporter.prototype._generateGLB = function (glTFPrefix) {
  490. var binaryBuffer = this.generateBinary();
  491. var jsonText = this.generateJSON(true);
  492. var glbFileName = glTFPrefix + '.glb';
  493. var headerLength = 12;
  494. var chunkLengthPrefix = 8;
  495. var jsonLength = jsonText.length;
  496. var imageByteLength = 0;
  497. for (var key in this.imageData) {
  498. imageByteLength += this.imageData[key].data.byteLength;
  499. }
  500. var jsonPadding = this._getPadding(jsonLength);
  501. var binPadding = this._getPadding(binaryBuffer.byteLength);
  502. var imagePadding = this._getPadding(imageByteLength);
  503. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  504. //header
  505. var headerBuffer = new ArrayBuffer(headerLength);
  506. var headerBufferView = new DataView(headerBuffer);
  507. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  508. headerBufferView.setUint32(4, 2, true); // version
  509. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  510. //json chunk
  511. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  512. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  513. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  514. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  515. //json chunk bytes
  516. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  517. for (var i = 0; i < jsonLength; ++i) {
  518. jsonData[i] = jsonText.charCodeAt(i);
  519. }
  520. //json padding
  521. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  522. for (var i = 0; i < jsonPadding; ++i) {
  523. jsonPaddingView[i] = 0x20;
  524. }
  525. //binary chunk
  526. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  527. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  528. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  529. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  530. // binary padding
  531. var binPaddingBuffer = new ArrayBuffer(binPadding);
  532. var binPaddingView = new Uint8Array(binPaddingBuffer);
  533. for (var i = 0; i < binPadding; ++i) {
  534. binPaddingView[i] = 0;
  535. }
  536. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  537. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  538. for (var i = 0; i < imagePadding; ++i) {
  539. imagePaddingView[i] = 0;
  540. }
  541. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  542. // binary data
  543. for (var key in this.imageData) {
  544. glbData.push(this.imageData[key].data.buffer);
  545. }
  546. glbData.push(binPaddingBuffer);
  547. glbData.push(imagePaddingBuffer);
  548. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  549. var container = new BABYLON._GLTFData();
  550. container.glTFFiles[glbFileName] = glbFile;
  551. return container;
  552. };
  553. /**
  554. * Sets the TRS for each node
  555. * @param node - glTF Node for storing the transformation data.
  556. * @param babylonMesh - Babylon mesh used as the source for the transformation data.
  557. */
  558. _Exporter.prototype.setNodeTransformation = function (node, babylonMesh) {
  559. if (!(babylonMesh.position.x === 0 && babylonMesh.position.y === 0 && babylonMesh.position.z === 0)) {
  560. node.translation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedVector3(babylonMesh.position).asArray() : babylonMesh.position.asArray();
  561. }
  562. if (!(babylonMesh.scaling.x === 1 && babylonMesh.scaling.y === 1 && babylonMesh.scaling.z === 1)) {
  563. node.scale = babylonMesh.scaling.asArray();
  564. }
  565. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonMesh.rotation.y, babylonMesh.rotation.x, babylonMesh.rotation.z);
  566. if (babylonMesh.rotationQuaternion) {
  567. rotationQuaternion = rotationQuaternion.multiply(babylonMesh.rotationQuaternion);
  568. }
  569. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  570. node.rotation = this.convertToRightHandedSystem ? _Exporter.GetRightHandedQuaternion(rotationQuaternion).asArray() : rotationQuaternion.asArray();
  571. }
  572. };
  573. /**
  574. * Creates a bufferview based on the vertices type for the Babylon mesh
  575. * @param kind - Indicates the type of vertices data.
  576. * @param babylonMesh - The Babylon mesh to get the vertices data from.
  577. * @param byteOffset - The offset from the buffer to start indexing from.
  578. * @param dataBuffer - The buffer to write the bufferview data to.
  579. * @returns bytelength of the bufferview data.
  580. */
  581. _Exporter.prototype.createBufferViewKind = function (kind, babylonMesh, byteOffset, dataBuffer) {
  582. var bufferMesh = null;
  583. var byteLength = 0;
  584. if (babylonMesh instanceof BABYLON.Mesh) {
  585. bufferMesh = babylonMesh;
  586. }
  587. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  588. bufferMesh = babylonMesh.sourceMesh;
  589. }
  590. if (bufferMesh) {
  591. var vertexBuffer = null;
  592. var vertexBufferOffset = null;
  593. var vertexData = null;
  594. var vertexStrideSize = null;
  595. if (bufferMesh.isVerticesDataPresent(kind)) {
  596. vertexBuffer = bufferMesh.getVertexBuffer(kind);
  597. if (vertexBuffer) {
  598. vertexBufferOffset = vertexBuffer.getOffset();
  599. vertexData = vertexBuffer.getData();
  600. if (vertexData) {
  601. vertexStrideSize = vertexBuffer.getStrideSize();
  602. if (dataBuffer && vertexData) {
  603. byteLength = this.writeAttributeData(kind, vertexData, vertexStrideSize, vertexBufferOffset, byteOffset, dataBuffer);
  604. byteOffset += byteLength;
  605. }
  606. else {
  607. byteLength = vertexData.length * 4;
  608. var bufferView = this.createBufferView(0, byteOffset, byteLength, vertexStrideSize * 4, kind + " - " + bufferMesh.name);
  609. byteOffset += byteLength;
  610. this.bufferViews.push(bufferView);
  611. }
  612. }
  613. }
  614. }
  615. }
  616. return byteLength;
  617. };
  618. /**
  619. * Sets data for the primitive attributes of each submesh
  620. * @param mesh - glTF Mesh object to store the primitive attribute information.
  621. * @param babylonMesh - Babylon mesh to get the primitive attribute data from.
  622. * @param byteOffset - The offset in bytes of the buffer data.
  623. * @param dataBuffer - Buffer to write the attribute data to.
  624. * @returns - bytelength of the primitive attributes plus the passed in byteOffset.
  625. */
  626. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonMesh, byteOffset, dataBuffer) {
  627. var bufferMesh = null;
  628. if (babylonMesh instanceof BABYLON.Mesh) {
  629. bufferMesh = babylonMesh;
  630. }
  631. else if (babylonMesh instanceof BABYLON.InstancedMesh) {
  632. bufferMesh = babylonMesh.sourceMesh;
  633. }
  634. var attributeData = [
  635. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */ },
  636. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */ },
  637. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */ },
  638. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */ },
  639. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */ },
  640. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */ },
  641. ];
  642. var indexBufferViewIndex = null;
  643. if (bufferMesh) {
  644. // For each BabylonMesh, create bufferviews for each 'kind'
  645. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  646. var attribute = attributeData_1[_i];
  647. var attributeKind = attribute.kind;
  648. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  649. byteOffset += this.createBufferViewKind(attributeKind, babylonMesh, byteOffset, dataBuffer);
  650. attribute.bufferViewIndex = this.bufferViews.length - 1;
  651. }
  652. }
  653. if (bufferMesh.getTotalIndices()) {
  654. var indices = bufferMesh.getIndices();
  655. if (indices) {
  656. if (dataBuffer) {
  657. var end = indices.length;
  658. var byteOff = byteOffset;
  659. for (var k = 0; k < end; ++k) {
  660. dataBuffer.setUint32(byteOff, indices[k], true);
  661. byteOff += 4;
  662. }
  663. byteOffset = byteOff;
  664. }
  665. else {
  666. var byteLength = indices.length * 4;
  667. var bufferView = this.createBufferView(0, byteOffset, byteLength, undefined, "Indices - " + bufferMesh.name);
  668. byteOffset += byteLength;
  669. this.bufferViews.push(bufferView);
  670. indexBufferViewIndex = this.bufferViews.length - 1;
  671. }
  672. }
  673. }
  674. if (babylonMesh.subMeshes) {
  675. // go through all mesh primitives (submeshes)
  676. for (var _a = 0, _b = babylonMesh.subMeshes; _a < _b.length; _a++) {
  677. var submesh = _b[_a];
  678. var meshPrimitive = { attributes: {} };
  679. // Create a bufferview storing all the positions
  680. if (!dataBuffer) {
  681. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  682. var attribute = attributeData_2[_c];
  683. var attributeKind = attribute.kind;
  684. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  685. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  686. if (vertexBuffer) {
  687. var bufferData = vertexBuffer.getData();
  688. if (bufferData) {
  689. var strideSize = vertexBuffer.getStrideSize();
  690. var minMax = void 0;
  691. var min = null;
  692. var max = null;
  693. var bufferViewIndex = attribute.bufferViewIndex;
  694. if (bufferViewIndex != undefined) {
  695. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  696. minMax = this.calculateMinMaxPositions(bufferData, 0, bufferData.length / strideSize);
  697. min = minMax.min;
  698. max = minMax.max;
  699. }
  700. var accessor = this.createAccessor(bufferViewIndex, attributeKind + " - " + babylonMesh.name, attribute.accessorType, 5126 /* FLOAT */, bufferData.length / strideSize, 0, min, max);
  701. this.accessors.push(accessor);
  702. switch (attributeKind) {
  703. case BABYLON.VertexBuffer.PositionKind: {
  704. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  705. break;
  706. }
  707. case BABYLON.VertexBuffer.NormalKind: {
  708. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  709. break;
  710. }
  711. case BABYLON.VertexBuffer.ColorKind: {
  712. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  713. break;
  714. }
  715. case BABYLON.VertexBuffer.TangentKind: {
  716. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  717. break;
  718. }
  719. case BABYLON.VertexBuffer.UVKind: {
  720. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  721. break;
  722. }
  723. case BABYLON.VertexBuffer.UV2Kind: {
  724. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  725. break;
  726. }
  727. default: {
  728. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  729. }
  730. }
  731. }
  732. }
  733. }
  734. }
  735. }
  736. if (indexBufferViewIndex) {
  737. // Create accessor
  738. var accessor = this.createAccessor(indexBufferViewIndex, "indices - " + babylonMesh.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  739. this.accessors.push(accessor);
  740. meshPrimitive.indices = this.accessors.length - 1;
  741. }
  742. }
  743. if (bufferMesh.material) {
  744. if (bufferMesh.material instanceof BABYLON.StandardMaterial || bufferMesh.material instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  745. var materialIndex = babylonMesh.getScene().materials.indexOf(bufferMesh.material);
  746. meshPrimitive.material = materialIndex;
  747. }
  748. else if (bufferMesh.material instanceof BABYLON.MultiMaterial) {
  749. var babylonMultiMaterial = bufferMesh.material;
  750. var material = babylonMultiMaterial.subMaterials[submesh.materialIndex];
  751. if (material) {
  752. var materialIndex = babylonMesh.getScene().materials.indexOf(material);
  753. meshPrimitive.material = materialIndex;
  754. }
  755. }
  756. else {
  757. BABYLON.Tools.Warn("Material type " + bufferMesh.material.getClassName() + " for material " + bufferMesh.material.name + " is not yet implemented in glTF serializer.");
  758. }
  759. }
  760. mesh.primitives.push(meshPrimitive);
  761. }
  762. }
  763. }
  764. return byteOffset;
  765. };
  766. /**
  767. * Creates a glTF scene based on the array of meshes.
  768. * Returns the the total byte offset.
  769. * @param babylonScene - Babylon scene to get the mesh data from.
  770. * @param byteOffset - Offset to start from in bytes.
  771. * @returns bytelength + byteoffset
  772. */
  773. _Exporter.prototype.createScene = function (babylonScene, byteOffset) {
  774. if (babylonScene.meshes.length) {
  775. var babylonMeshes = babylonScene.meshes;
  776. var scene = { nodes: new Array() };
  777. GLTF2._GLTFMaterial.ConvertMaterialsToGLTF(babylonScene.materials, "image/jpeg" /* JPEG */, this.images, this.textures, this.materials, this.imageData, true);
  778. var result = this.createNodeMap(babylonScene, byteOffset);
  779. this.nodeMap = result.nodeMap;
  780. this.totalByteLength = result.byteOffset;
  781. this.binaryBuffer = new ArrayBuffer(this.totalByteLength);
  782. var dataBuffer = new DataView(this.binaryBuffer);
  783. for (var i = 0; i < babylonMeshes.length; ++i) {
  784. if (this.options &&
  785. this.options.shouldExportMesh != undefined &&
  786. !this.options.shouldExportMesh(babylonMeshes[i])) {
  787. continue;
  788. }
  789. else {
  790. var babylonMesh = babylonMeshes[i];
  791. // Build Hierarchy with the node map.
  792. var glTFNodeIndex = this.nodeMap[babylonMesh.uniqueId];
  793. var glTFNode = this.nodes[glTFNodeIndex];
  794. if (!babylonMesh.parent) {
  795. scene.nodes.push(glTFNodeIndex);
  796. }
  797. var directDescendents = babylonMesh.getDescendants(true);
  798. if (!glTFNode.children && directDescendents && directDescendents.length) {
  799. glTFNode.children = [];
  800. for (var _i = 0, directDescendents_1 = directDescendents; _i < directDescendents_1.length; _i++) {
  801. var descendent = directDescendents_1[_i];
  802. glTFNode.children.push(this.nodeMap[descendent.uniqueId]);
  803. }
  804. }
  805. var mesh = { primitives: new Array() };
  806. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  807. }
  808. }
  809. this.scenes.push(scene);
  810. }
  811. return byteOffset;
  812. };
  813. /**
  814. * Creates a mapping of Node unique id to node index
  815. * @param scene - Babylon Scene.
  816. * @param byteOffset - The initial byte offset.
  817. * @returns - Node mapping of unique id to index.
  818. */
  819. _Exporter.prototype.createNodeMap = function (scene, byteOffset) {
  820. var nodeMap = {};
  821. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  822. var babylonMesh = _a[_i];
  823. var result = this.createNode(babylonMesh, byteOffset, null);
  824. this.nodes.push(result.node);
  825. nodeMap[babylonMesh.uniqueId] = this.nodes.length - 1;
  826. byteOffset = result.byteOffset;
  827. }
  828. return { nodeMap: nodeMap, byteOffset: byteOffset };
  829. };
  830. /**
  831. * Creates a glTF node from a Babylon mesh.
  832. * @param babylonMesh - Source Babylon mesh.
  833. * @param byteOffset - The initial byte offset.
  834. * @param dataBuffer - Buffer for storing geometry data.
  835. * @returns - Object containing an INode and byteoffset.
  836. */
  837. _Exporter.prototype.createNode = function (babylonMesh, byteOffset, dataBuffer) {
  838. // create node to hold translation/rotation/scale and the mesh
  839. var node = {};
  840. if (babylonMesh.name) {
  841. node.name = babylonMesh.name;
  842. }
  843. // Set transformation
  844. this.setNodeTransformation(node, babylonMesh);
  845. // create mesh
  846. var mesh = { primitives: new Array() };
  847. mesh.primitives = [];
  848. byteOffset = this.setPrimitiveAttributes(mesh, babylonMesh, byteOffset, dataBuffer);
  849. if (mesh.primitives.length) {
  850. this.meshes.push(mesh);
  851. node.mesh = this.meshes.length - 1;
  852. }
  853. return { node: node, byteOffset: byteOffset };
  854. };
  855. return _Exporter;
  856. }());
  857. GLTF2._Exporter = _Exporter;
  858. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  859. })(BABYLON || (BABYLON = {}));
  860. //# sourceMappingURL=babylon.glTFExporter.js.map
  861. var BABYLON;
  862. (function (BABYLON) {
  863. /**
  864. * Class for holding and downloading glTF file data
  865. */
  866. var _GLTFData = /** @class */ (function () {
  867. /**
  868. * Initializes the glTF file object.
  869. */
  870. function _GLTFData() {
  871. this.glTFFiles = {};
  872. }
  873. /**
  874. * Downloads the glTF data as files based on their names and data.
  875. */
  876. _GLTFData.prototype.downloadFiles = function () {
  877. /**
  878. * Checks for a matching suffix at the end of a string (for ES5 and lower).
  879. * @param str - Source string.
  880. * @param suffix - Suffix to search for in the source string.
  881. * @returns - Boolean indicating whether the suffix was found (true) or not (false).
  882. */
  883. function endsWith(str, suffix) {
  884. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  885. }
  886. for (var key in this.glTFFiles) {
  887. var link = document.createElement('a');
  888. document.body.appendChild(link);
  889. link.setAttribute("type", "hidden");
  890. link.download = key;
  891. var blob = this.glTFFiles[key];
  892. var mimeType = void 0;
  893. if (endsWith(key, ".glb")) {
  894. mimeType = { type: "model/gltf-binary" };
  895. }
  896. else if (endsWith(key, ".bin")) {
  897. mimeType = { type: "application/octet-stream" };
  898. }
  899. else if (endsWith(key, ".gltf")) {
  900. mimeType = { type: "model/gltf+json" };
  901. }
  902. else if (endsWith(key, ".jpeg" || ".jpg")) {
  903. mimeType = { type: "image/jpeg" /* JPEG */ };
  904. }
  905. else if (endsWith(key, ".png")) {
  906. mimeType = { type: "image/png" /* PNG */ };
  907. }
  908. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  909. link.click();
  910. }
  911. };
  912. return _GLTFData;
  913. }());
  914. BABYLON._GLTFData = _GLTFData;
  915. })(BABYLON || (BABYLON = {}));
  916. //# sourceMappingURL=babylon.glTFData.js.map
  917. var BABYLON;
  918. (function (BABYLON) {
  919. var GLTF2;
  920. (function (GLTF2) {
  921. /**
  922. * Utility methods for working with glTF material conversion properties. This class should only be used internally.
  923. */
  924. var _GLTFMaterial = /** @class */ (function () {
  925. function _GLTFMaterial() {
  926. }
  927. /**
  928. * Gets the materials from a Babylon scene and converts them to glTF materials.
  929. * @param scene
  930. * @param mimeType
  931. * @param images
  932. * @param textures
  933. * @param materials
  934. * @param imageData
  935. * @param hasTextureCoords
  936. */
  937. _GLTFMaterial.ConvertMaterialsToGLTF = function (babylonMaterials, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  938. for (var i = 0; i < babylonMaterials.length; ++i) {
  939. var babylonMaterial = babylonMaterials[i];
  940. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  941. _GLTFMaterial.ConvertStandardMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  942. }
  943. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  944. _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial(babylonMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords);
  945. }
  946. }
  947. };
  948. /**
  949. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material.
  950. * @param babylonStandardMaterial
  951. * @returns - glTF Metallic Roughness Material representation
  952. */
  953. _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  954. var P0 = new BABYLON.Vector2(0, 1);
  955. var P1 = new BABYLON.Vector2(0, 0.1);
  956. var P2 = new BABYLON.Vector2(0, 0.1);
  957. var P3 = new BABYLON.Vector2(1300, 0.1);
  958. /**
  959. * Given the control points, solve for x based on a given t for a cubic bezier curve.
  960. * @param t - a value between 0 and 1.
  961. * @param p0 - first control point.
  962. * @param p1 - second control point.
  963. * @param p2 - third control point.
  964. * @param p3 - fourth control point.
  965. * @returns - number result of cubic bezier curve at the specified t.
  966. */
  967. function cubicBezierCurve(t, p0, p1, p2, p3) {
  968. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  969. 3 * (1 - t) * (1 - t) * t * p1 +
  970. 3 * (1 - t) * t * t * p2 +
  971. t * t * t * p3);
  972. }
  973. /**
  974. * Evaluates a specified specular power value to determine the appropriate roughness value,
  975. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  976. * and roughness on the ordinant axis (y-axis).
  977. * @param specularPower - specular power of standard material.
  978. * @returns - Number representing the roughness value.
  979. */
  980. function solveForRoughness(specularPower) {
  981. var t = Math.pow(specularPower / P3.x, 0.333333);
  982. return cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  983. }
  984. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  985. var opacity = babylonStandardMaterial.alpha;
  986. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this.maxSpecularPower);
  987. var roughness = solveForRoughness(specularPower);
  988. var glTFPbrMetallicRoughness = {
  989. baseColorFactor: [
  990. diffuse.r,
  991. diffuse.g,
  992. diffuse.b,
  993. opacity
  994. ],
  995. metallicFactor: 0,
  996. roughnessFactor: roughness,
  997. };
  998. return glTFPbrMetallicRoughness;
  999. };
  1000. /**
  1001. * Computes the metallic factor
  1002. * @param diffuse - diffused value
  1003. * @param specular - specular value
  1004. * @param oneMinusSpecularStrength - one minus the specular strength
  1005. * @returns - metallic value
  1006. */
  1007. _GLTFMaterial.SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1008. if (specular < _GLTFMaterial.dielectricSpecular.r) {
  1009. _GLTFMaterial.dielectricSpecular;
  1010. return 0;
  1011. }
  1012. var a = _GLTFMaterial.dielectricSpecular.r;
  1013. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial.dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial.dielectricSpecular.r;
  1014. var c = _GLTFMaterial.dielectricSpecular.r - specular;
  1015. var D = b * b - 4.0 * a * c;
  1016. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1017. };
  1018. /**
  1019. * Gets the glTF alpha mode from the Babylon Material
  1020. * @param babylonMaterial - Babylon Material
  1021. * @returns - The Babylon alpha mode value
  1022. */
  1023. _GLTFMaterial.GetAlphaMode = function (babylonMaterial) {
  1024. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1025. var babylonStandardMaterial = babylonMaterial;
  1026. if ((babylonStandardMaterial.alpha != 1.0) ||
  1027. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1028. (babylonStandardMaterial.opacityTexture != null)) {
  1029. return "BLEND" /* BLEND */;
  1030. }
  1031. else {
  1032. return "OPAQUE" /* OPAQUE */;
  1033. }
  1034. }
  1035. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1036. var babylonPBRMetallicRoughness = babylonMaterial;
  1037. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1038. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1039. return "OPAQUE" /* OPAQUE */;
  1040. }
  1041. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1042. return "BLEND" /* BLEND */;
  1043. }
  1044. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1045. return "MASK" /* MASK */;
  1046. }
  1047. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1048. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1049. return "BLEND" /* BLEND */;
  1050. }
  1051. default: {
  1052. throw new Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1053. }
  1054. }
  1055. }
  1056. else {
  1057. throw new Error("Unsupported Babylon material type");
  1058. }
  1059. };
  1060. /**
  1061. * Converts a Babylon Standard Material to a glTF Material.
  1062. * @param babylonStandardMaterial - BJS Standard Material.
  1063. * @param mimeType - mime type to use for the textures.
  1064. * @param images - array of glTF image interfaces.
  1065. * @param textures - array of glTF texture interfaces.
  1066. * @param materials - array of glTF material interfaces.
  1067. * @param imageData - map of image file name to data.
  1068. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1069. */
  1070. _GLTFMaterial.ConvertStandardMaterial = function (babylonStandardMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1071. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Standard Material is currently not fully supported/implemented in glTF serializer");
  1072. var glTFPbrMetallicRoughness = _GLTFMaterial.ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1073. var glTFMaterial = { name: babylonStandardMaterial.name };
  1074. if (babylonStandardMaterial.backFaceCulling) {
  1075. if (!babylonStandardMaterial.twoSidedLighting) {
  1076. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1077. }
  1078. glTFMaterial.doubleSided = true;
  1079. }
  1080. if (hasTextureCoords) {
  1081. if (babylonStandardMaterial.diffuseTexture) {
  1082. var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, imageData);
  1083. if (glTFTexture != null) {
  1084. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1085. }
  1086. }
  1087. if (babylonStandardMaterial.bumpTexture) {
  1088. var glTFTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.bumpTexture, mimeType, images, textures, imageData);
  1089. if (glTFTexture) {
  1090. glTFMaterial.normalTexture = glTFTexture;
  1091. }
  1092. }
  1093. if (babylonStandardMaterial.emissiveTexture) {
  1094. var glTFEmissiveTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1095. if (glTFEmissiveTexture) {
  1096. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1097. }
  1098. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1099. }
  1100. if (babylonStandardMaterial.ambientTexture) {
  1101. var glTFOcclusionTexture = _GLTFMaterial.ExportTexture(babylonStandardMaterial.ambientTexture, mimeType, images, textures, imageData);
  1102. if (glTFOcclusionTexture) {
  1103. glTFMaterial.occlusionTexture = glTFOcclusionTexture;
  1104. }
  1105. }
  1106. }
  1107. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1108. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1109. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1110. }
  1111. else {
  1112. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1113. }
  1114. }
  1115. if (babylonStandardMaterial.emissiveColor) {
  1116. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1117. }
  1118. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1119. materials.push(glTFMaterial);
  1120. };
  1121. /**
  1122. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material.
  1123. * @param babylonPBRMetalRoughMaterial - BJS PBR Metallic Roughness Material.
  1124. * @param mimeType - mime type to use for the textures.
  1125. * @param images - array of glTF image interfaces.
  1126. * @param textures - array of glTF texture interfaces.
  1127. * @param materials - array of glTF material interfaces.
  1128. * @param imageData - map of image file name to data.
  1129. * @param hasTextureCoords - specifies if texture coordinates are present on the submesh to determine if textures should be applied.
  1130. */
  1131. _GLTFMaterial.ConvertPBRMetallicRoughnessMaterial = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, materials, imageData, hasTextureCoords) {
  1132. var glTFPbrMetallicRoughness = {};
  1133. if (babylonPBRMetalRoughMaterial.baseColor) {
  1134. glTFPbrMetallicRoughness.baseColorFactor = [
  1135. babylonPBRMetalRoughMaterial.baseColor.r,
  1136. babylonPBRMetalRoughMaterial.baseColor.g,
  1137. babylonPBRMetalRoughMaterial.baseColor.b,
  1138. babylonPBRMetalRoughMaterial.alpha
  1139. ];
  1140. }
  1141. if (babylonPBRMetalRoughMaterial.metallic != null) {
  1142. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1143. }
  1144. if (babylonPBRMetalRoughMaterial.roughness != null) {
  1145. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1146. }
  1147. var glTFMaterial = {
  1148. name: babylonPBRMetalRoughMaterial.name
  1149. };
  1150. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1151. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1152. }
  1153. if (hasTextureCoords) {
  1154. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1155. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, imageData);
  1156. if (glTFTexture != null) {
  1157. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1158. }
  1159. }
  1160. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1161. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, imageData);
  1162. if (glTFTexture) {
  1163. glTFMaterial.normalTexture = glTFTexture;
  1164. }
  1165. }
  1166. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1167. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, imageData);
  1168. if (glTFTexture) {
  1169. glTFMaterial.occlusionTexture = glTFTexture;
  1170. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1171. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1172. }
  1173. }
  1174. }
  1175. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1176. var glTFTexture = _GLTFMaterial.ExportTexture(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, imageData);
  1177. if (glTFTexture != null) {
  1178. glTFMaterial.emissiveTexture = glTFTexture;
  1179. }
  1180. }
  1181. }
  1182. if (babylonPBRMetalRoughMaterial.emissiveColor.equalsFloats(0.0, 0.0, 0.0)) {
  1183. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1184. }
  1185. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1186. var alphaMode = _GLTFMaterial.GetAlphaMode(babylonPBRMetalRoughMaterial);
  1187. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1188. glTFMaterial.alphaMode = alphaMode;
  1189. if (alphaMode === "BLEND" /* BLEND */) {
  1190. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1191. }
  1192. }
  1193. }
  1194. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1195. materials.push(glTFMaterial);
  1196. };
  1197. /**
  1198. * Extracts a texture from a Babylon texture into file data and glTF data.
  1199. * @param babylonTexture - Babylon texture to extract.
  1200. * @param mimeType - Mime Type of the babylonTexture.
  1201. * @param images - Array of glTF images.
  1202. * @param textures - Array of glTF textures.
  1203. * @param imageData - map of image file name and data.
  1204. * @return - glTF texture, or null if the texture format is not supported.
  1205. */
  1206. _GLTFMaterial.ExportTexture = function (babylonTexture, mimeType, images, textures, imageData) {
  1207. var textureInfo = null;
  1208. var glTFTexture = {
  1209. source: images.length
  1210. };
  1211. var textureName = "texture_" + (textures.length - 1).toString();
  1212. var textureData = babylonTexture.getInternalTexture();
  1213. if (textureData != null) {
  1214. textureName = textureData.url;
  1215. }
  1216. textureName = BABYLON.Tools.GetFilename(textureName);
  1217. var baseFile = textureName.split('.')[0];
  1218. var extension = "";
  1219. if (mimeType === "image/jpeg" /* JPEG */) {
  1220. extension = ".jpg";
  1221. }
  1222. else if (mimeType === "image/png" /* PNG */) {
  1223. extension = ".png";
  1224. }
  1225. else {
  1226. BABYLON.Tools.Error("Unsupported mime type " + mimeType);
  1227. }
  1228. textureName = baseFile + extension;
  1229. var pixels = babylonTexture.readPixels();
  1230. var imageCanvas = document.createElement('canvas');
  1231. imageCanvas.id = "ImageCanvas";
  1232. var ctx = imageCanvas.getContext('2d');
  1233. var size = babylonTexture.getSize();
  1234. imageCanvas.width = size.width;
  1235. imageCanvas.height = size.height;
  1236. var imgData = ctx.createImageData(size.width, size.height);
  1237. imgData.data.set(pixels);
  1238. ctx.putImageData(imgData, 0, 0);
  1239. var base64Data = imageCanvas.toDataURL(mimeType);
  1240. var binStr = atob(base64Data.split(',')[1]);
  1241. var arr = new Uint8Array(binStr.length);
  1242. for (var i = 0; i < binStr.length; ++i) {
  1243. arr[i] = binStr.charCodeAt(i);
  1244. }
  1245. var imageValues = { data: arr, mimeType: mimeType };
  1246. imageData[textureName] = imageValues;
  1247. if (mimeType === "image/jpeg" /* JPEG */) {
  1248. var glTFImage = {
  1249. uri: textureName
  1250. };
  1251. var foundIndex = -1;
  1252. for (var i = 0; i < images.length; ++i) {
  1253. if (images[i].uri === textureName) {
  1254. foundIndex = i;
  1255. break;
  1256. }
  1257. }
  1258. if (foundIndex === -1) {
  1259. images.push(glTFImage);
  1260. glTFTexture.source = images.length - 1;
  1261. textures.push({
  1262. source: images.length - 1
  1263. });
  1264. textureInfo = {
  1265. index: images.length - 1
  1266. };
  1267. }
  1268. else {
  1269. glTFTexture.source = foundIndex;
  1270. textureInfo = {
  1271. index: foundIndex
  1272. };
  1273. }
  1274. }
  1275. return textureInfo;
  1276. };
  1277. /**
  1278. * Represents the dielectric specular values for R, G and B.
  1279. */
  1280. _GLTFMaterial.dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  1281. /**
  1282. * Allows the maximum specular power to be defined for material calculations.
  1283. */
  1284. _GLTFMaterial.maxSpecularPower = 1024;
  1285. return _GLTFMaterial;
  1286. }());
  1287. GLTF2._GLTFMaterial = _GLTFMaterial;
  1288. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1289. })(BABYLON || (BABYLON = {}));
  1290. //# sourceMappingURL=babylon.glTFMaterial.js.map
  1291. return BABYLON;
  1292. });