BabylonExporter.GLTFExporter.Mesh.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using Autodesk.Max;
  2. using BabylonExport.Entities;
  3. using GLTFExport.Entities;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. namespace Max2Babylon
  9. {
  10. partial class BabylonExporter
  11. {
  12. private GLTFMesh ExportMesh(BabylonMesh babylonMesh, GLTF gltf, BabylonScene babylonScene)
  13. {
  14. RaiseMessage("GLTFExporter.Mesh | Export mesh named: " + babylonMesh.name, 1);
  15. // --------------------------
  16. // --- Mesh from babylon ----
  17. // --------------------------
  18. if (babylonMesh.positions == null)
  19. {
  20. RaiseMessage("GLTFExporter.Mesh | Mesh is a dummy", 2);
  21. return null;
  22. }
  23. RaiseMessage("GLTFExporter.Mesh | Mesh from babylon", 2);
  24. // Retreive general data from babylon mesh
  25. int nbVertices = babylonMesh.positions.Length / 3;
  26. bool hasUV = babylonMesh.uvs != null && babylonMesh.uvs.Length > 0;
  27. bool hasUV2 = babylonMesh.uvs2 != null && babylonMesh.uvs2.Length > 0;
  28. bool hasColor = babylonMesh.colors != null && babylonMesh.colors.Length > 0;
  29. RaiseMessage("GLTFExporter.Mesh | nbVertices=" + nbVertices, 3);
  30. RaiseMessage("GLTFExporter.Mesh | hasUV=" + hasUV, 3);
  31. RaiseMessage("GLTFExporter.Mesh | hasUV2=" + hasUV2, 3);
  32. RaiseMessage("GLTFExporter.Mesh | hasColor=" + hasColor, 3);
  33. // Retreive vertices data from babylon mesh
  34. List<GLTFGlobalVertex> globalVertices = new List<GLTFGlobalVertex>();
  35. for (int indexVertex = 0; indexVertex < nbVertices; indexVertex++)
  36. {
  37. GLTFGlobalVertex globalVertex = new GLTFGlobalVertex();
  38. globalVertex.Position = createIPoint3(babylonMesh.positions, indexVertex);
  39. // Switch from left to right handed coordinate system
  40. //globalVertex.Position.X *= -1;
  41. globalVertex.Normal = createIPoint3(babylonMesh.normals, indexVertex);
  42. if (hasUV)
  43. {
  44. globalVertex.UV = createIPoint2(babylonMesh.uvs, indexVertex);
  45. // For glTF, the origin of the UV coordinates (0, 0) corresponds to the upper left corner of a texture image
  46. // While for Babylon, it corresponds to the lower left corner of a texture image
  47. globalVertex.UV.Y = 1 - globalVertex.UV.Y;
  48. }
  49. if (hasUV2)
  50. {
  51. globalVertex.UV2 = createIPoint2(babylonMesh.uvs2, indexVertex);
  52. // For glTF, the origin of the UV coordinates (0, 0) corresponds to the upper left corner of a texture image
  53. // While for Babylon, it corresponds to the lower left corner of a texture image
  54. globalVertex.UV2.Y = 1 - globalVertex.UV2.Y;
  55. }
  56. if (hasColor)
  57. {
  58. globalVertex.Color = createIPoint4(babylonMesh.colors, indexVertex).ToArray();
  59. }
  60. globalVertices.Add(globalVertex);
  61. }
  62. // Retreive indices from babylon mesh
  63. List<ushort> babylonIndices = new List<ushort>();
  64. babylonIndices = babylonMesh.indices.ToList().ConvertAll(new Converter<int, ushort>(n => (ushort)n));
  65. // For triangle primitives in gltf, the front face has a counter-clockwise (CCW) winding order
  66. // Swap face side
  67. //for (int i = 0; i < babylonIndices.Count; i += 3)
  68. //{
  69. // var tmp = babylonIndices[i];
  70. // babylonIndices[i] = babylonIndices[i + 2];
  71. // babylonIndices[i + 2] = tmp;
  72. //}
  73. // --------------------------
  74. // ------- Init glTF --------
  75. // --------------------------
  76. RaiseMessage("GLTFExporter.Mesh | Init glTF", 2);
  77. // Mesh
  78. var gltfMesh = new GLTFMesh { name = babylonMesh.name };
  79. gltfMesh.index = gltf.MeshesList.Count;
  80. gltf.MeshesList.Add(gltfMesh);
  81. gltfMesh.idGroupInstance = babylonMesh.idGroupInstance;
  82. // Buffer
  83. var buffer = new GLTFBuffer
  84. {
  85. uri = gltfMesh.name + ".bin"
  86. };
  87. buffer.index = gltf.BuffersList.Count;
  88. gltf.BuffersList.Add(buffer);
  89. // BufferView - Scalar
  90. var bufferViewScalar = new GLTFBufferView
  91. {
  92. name = "bufferViewScalar",
  93. buffer = buffer.index,
  94. Buffer = buffer
  95. };
  96. bufferViewScalar.index = gltf.BufferViewsList.Count;
  97. gltf.BufferViewsList.Add(bufferViewScalar);
  98. // BufferView - Vector3
  99. var bufferViewFloatVec3 = new GLTFBufferView
  100. {
  101. name = "bufferViewFloatVec3",
  102. buffer = buffer.index,
  103. Buffer = buffer,
  104. byteOffset = 0,
  105. byteStride = 12 // Field only defined for buffer views that contain vertex attributes. A vertex needs 3 * 4 bytes
  106. };
  107. bufferViewFloatVec3.index = gltf.BufferViewsList.Count;
  108. gltf.BufferViewsList.Add(bufferViewFloatVec3);
  109. // BufferView - Vector4
  110. GLTFBufferView bufferViewFloatVec4 = null;
  111. if (hasColor)
  112. {
  113. bufferViewFloatVec4 = new GLTFBufferView
  114. {
  115. name = "bufferViewFloatVec4",
  116. buffer = buffer.index,
  117. Buffer = buffer,
  118. byteOffset = 0,
  119. byteStride = 16 // Field only defined for buffer views that contain vertex attributes. A vertex needs 4 * 4 bytes
  120. };
  121. bufferViewFloatVec4.index = gltf.BufferViewsList.Count;
  122. gltf.BufferViewsList.Add(bufferViewFloatVec4);
  123. }
  124. // BufferView - Vector2
  125. GLTFBufferView bufferViewFloatVec2 = null;
  126. if (hasUV || hasUV2)
  127. {
  128. bufferViewFloatVec2 = new GLTFBufferView
  129. {
  130. name = "bufferViewFloatVec2",
  131. buffer = buffer.index,
  132. Buffer = buffer,
  133. byteStride = 8 // Field only defined for buffer views that contain vertex attributes. A vertex needs 2 * 4 bytes
  134. };
  135. bufferViewFloatVec2.index = gltf.BufferViewsList.Count;
  136. gltf.BufferViewsList.Add(bufferViewFloatVec2);
  137. }
  138. // --------------------------
  139. // ---- glTF primitives -----
  140. // --------------------------
  141. RaiseMessage("GLTFExporter.Mesh | glTF primitives", 2);
  142. var meshPrimitives = new List<GLTFMeshPrimitive>();
  143. // Global vertices are sorted per submesh
  144. var globalVerticesSubMeshes = new List<List<GLTFGlobalVertex>>();
  145. // In gltf, indices of each mesh primitive are 0-based (ie: min value is 0)
  146. // Thus, the gltf indices list is a concatenation of sub lists all 0-based
  147. // Example for 2 triangles, each being a submesh:
  148. // babylonIndices = {0,1,2, 3,4,5} gives as result gltfIndicies = {0,1,2, 0,1,2}
  149. var gltfIndices = new List<ushort>();
  150. foreach (BabylonSubMesh babylonSubMesh in babylonMesh.subMeshes)
  151. {
  152. // --------------------------
  153. // ------ SubMesh data ------
  154. // --------------------------
  155. List<GLTFGlobalVertex> globalVerticesSubMesh = globalVertices.GetRange(babylonSubMesh.verticesStart, babylonSubMesh.verticesCount);
  156. globalVerticesSubMeshes.Add(globalVerticesSubMesh);
  157. List<ushort> _indices = babylonIndices.GetRange(babylonSubMesh.indexStart, babylonSubMesh.indexCount);
  158. // Indices of this submesh / primitive are updated to be 0-based
  159. var minIndiceValue = _indices.Min(); // Should be equal to babylonSubMesh.indexStart
  160. for (int indexIndice = 0; indexIndice < _indices.Count; indexIndice++)
  161. {
  162. _indices[indexIndice] -= minIndiceValue;
  163. }
  164. gltfIndices.AddRange(_indices);
  165. // --------------------------
  166. // -- Init glTF primitive ---
  167. // --------------------------
  168. // MeshPrimitive
  169. var meshPrimitive = new GLTFMeshPrimitive
  170. {
  171. attributes = new Dictionary<string, int>()
  172. };
  173. meshPrimitives.Add(meshPrimitive);
  174. // Accessor - Indices
  175. var accessorIndices = new GLTFAccessor
  176. {
  177. name = "accessorIndices",
  178. bufferView = bufferViewScalar.index,
  179. BufferView = bufferViewScalar,
  180. componentType = GLTFAccessor.ComponentType.UNSIGNED_SHORT,
  181. type = GLTFAccessor.TypeEnum.SCALAR.ToString()
  182. };
  183. accessorIndices.index = gltf.AccessorsList.Count;
  184. gltf.AccessorsList.Add(accessorIndices);
  185. meshPrimitive.indices = accessorIndices.index;
  186. // Accessor - Positions
  187. var accessorPositions = new GLTFAccessor
  188. {
  189. name = "accessorPositions",
  190. bufferView = bufferViewFloatVec3.index,
  191. BufferView = bufferViewFloatVec3,
  192. componentType = GLTFAccessor.ComponentType.FLOAT,
  193. type = GLTFAccessor.TypeEnum.VEC3.ToString(),
  194. min = new float[] { float.MaxValue, float.MaxValue, float.MaxValue },
  195. max = new float[] { float.MinValue, float.MinValue, float.MinValue }
  196. };
  197. accessorPositions.index = gltf.AccessorsList.Count;
  198. gltf.AccessorsList.Add(accessorPositions);
  199. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.POSITION.ToString(), accessorPositions.index);
  200. // Accessor - Normals
  201. var accessorNormals = new GLTFAccessor
  202. {
  203. name = "accessorNormals",
  204. bufferView = bufferViewFloatVec3.index,
  205. BufferView = bufferViewFloatVec3,
  206. componentType = GLTFAccessor.ComponentType.FLOAT,
  207. type = GLTFAccessor.TypeEnum.VEC3.ToString()
  208. };
  209. accessorNormals.index = gltf.AccessorsList.Count;
  210. gltf.AccessorsList.Add(accessorNormals);
  211. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.NORMAL.ToString(), accessorNormals.index);
  212. // Accessor - Colors
  213. GLTFAccessor accessorColors = null;
  214. if (hasColor)
  215. {
  216. accessorColors = new GLTFAccessor
  217. {
  218. name = "accessorColors",
  219. bufferView = bufferViewFloatVec4.index,
  220. BufferView = bufferViewFloatVec4,
  221. componentType = GLTFAccessor.ComponentType.FLOAT,
  222. type = GLTFAccessor.TypeEnum.VEC4.ToString()
  223. };
  224. accessorColors.index = gltf.AccessorsList.Count;
  225. gltf.AccessorsList.Add(accessorColors);
  226. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.COLOR_0.ToString(), accessorColors.index);
  227. }
  228. // Accessor - UV
  229. GLTFAccessor accessorUVs = null;
  230. if (hasUV)
  231. {
  232. accessorUVs = new GLTFAccessor
  233. {
  234. name = "accessorUVs",
  235. bufferView = bufferViewFloatVec2.index,
  236. BufferView = bufferViewFloatVec2,
  237. componentType = GLTFAccessor.ComponentType.FLOAT,
  238. type = GLTFAccessor.TypeEnum.VEC2.ToString()
  239. };
  240. accessorUVs.index = gltf.AccessorsList.Count;
  241. gltf.AccessorsList.Add(accessorUVs);
  242. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.TEXCOORD_0.ToString(), accessorUVs.index);
  243. }
  244. // Accessor - UV2
  245. GLTFAccessor accessorUV2s = null;
  246. if (hasUV2)
  247. {
  248. accessorUV2s = new GLTFAccessor
  249. {
  250. name = "accessorUV2s",
  251. bufferView = bufferViewFloatVec2.index,
  252. BufferView = bufferViewFloatVec2,
  253. componentType = GLTFAccessor.ComponentType.FLOAT,
  254. type = GLTFAccessor.TypeEnum.VEC2.ToString()
  255. };
  256. accessorUV2s.index = gltf.AccessorsList.Count;
  257. gltf.AccessorsList.Add(accessorUV2s);
  258. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.TEXCOORD_1.ToString(), accessorUV2s.index);
  259. }
  260. // --------------------------
  261. // - Update glTF primitive --
  262. // --------------------------
  263. RaiseMessage("GLTFExporter.Mesh | Mesh as glTF", 3);
  264. // Material
  265. if (babylonMesh.materialId != null)
  266. {
  267. // Retreive the babylon material
  268. var babylonMaterialId = babylonMesh.materialId;
  269. var babylonMaterials = new List<BabylonMaterial>(babylonScene.materials);
  270. var babylonMaterial = babylonMaterials.Find(_babylonMaterial => _babylonMaterial.id == babylonMaterialId);
  271. if (babylonMaterial == null)
  272. {
  273. // It's a multi material
  274. var babylonMultiMaterials = new List<BabylonMultiMaterial>(babylonScene.multiMaterials);
  275. var babylonMultiMaterial = babylonMultiMaterials.Find(_babylonMultiMaterial => _babylonMultiMaterial.id == babylonMesh.materialId);
  276. babylonMaterialId = babylonMultiMaterial.materials[babylonSubMesh.materialIndex];
  277. babylonMaterial = babylonMaterials.Find(_babylonMaterial => _babylonMaterial.id == babylonMaterialId);
  278. }
  279. // Update primitive material index
  280. var indexMaterial = babylonMaterialsToExport.FindIndex(_babylonMaterial => _babylonMaterial == babylonMaterial);
  281. if (indexMaterial == -1)
  282. {
  283. // Store material for exportation
  284. indexMaterial = babylonMaterialsToExport.Count;
  285. babylonMaterialsToExport.Add(babylonMaterial);
  286. }
  287. meshPrimitive.material = indexMaterial;
  288. // TODO - Add and retreive info from babylon material
  289. meshPrimitive.mode = GLTFMeshPrimitive.FillMode.TRIANGLES;
  290. }
  291. // Update min and max vertex position for each component (X, Y, Z)
  292. globalVerticesSubMesh.ForEach((globalVertex) =>
  293. {
  294. var positionArray = new float[] { globalVertex.Position.X, globalVertex.Position.Y, globalVertex.Position.Z };
  295. for (int indexComponent = 0; indexComponent < positionArray.Length; indexComponent++)
  296. {
  297. if (positionArray[indexComponent] < accessorPositions.min[indexComponent])
  298. {
  299. accessorPositions.min[indexComponent] = positionArray[indexComponent];
  300. }
  301. if (positionArray[indexComponent] > accessorPositions.max[indexComponent])
  302. {
  303. accessorPositions.max[indexComponent] = positionArray[indexComponent];
  304. }
  305. }
  306. });
  307. // Update byte length and count of accessors, bufferViews and buffers
  308. // Scalar
  309. AddElementsToAccessor(accessorIndices, _indices.Count);
  310. // Ensure the byteoffset is a multiple of 4
  311. // Indices accessor element size if 2
  312. // So the count needs to be even
  313. if (gltfIndices.Count % 2 != 0)
  314. {
  315. gltfIndices.Add(0);
  316. bufferViewScalar.byteLength += 2;
  317. buffer.byteLength += 2;
  318. }
  319. // Vector3
  320. AddElementsToAccessor(accessorPositions, globalVerticesSubMesh.Count);
  321. AddElementsToAccessor(accessorNormals, globalVerticesSubMesh.Count);
  322. // Vector4
  323. if (hasColor)
  324. {
  325. AddElementsToAccessor(accessorColors, globalVerticesSubMesh.Count);
  326. }
  327. // Vector2
  328. if (hasUV)
  329. {
  330. AddElementsToAccessor(accessorUVs, globalVerticesSubMesh.Count);
  331. }
  332. if (hasUV2)
  333. {
  334. AddElementsToAccessor(accessorUV2s, globalVerticesSubMesh.Count);
  335. }
  336. }
  337. gltfMesh.primitives = meshPrimitives.ToArray();
  338. // Update byte offset of bufferViews
  339. GLTFBufferView lastBufferView = null;
  340. gltf.BufferViewsList.FindAll(bufferView => bufferView.buffer == buffer.index).ForEach(bufferView =>
  341. {
  342. if (lastBufferView != null)
  343. {
  344. bufferView.byteOffset = lastBufferView.byteOffset + lastBufferView.byteLength;
  345. }
  346. lastBufferView = bufferView;
  347. });
  348. // --------------------------
  349. // --------- Saving ---------
  350. // --------------------------
  351. string outputBinaryFile = Path.Combine(gltf.OutputPath, gltfMesh.name + ".bin");
  352. RaiseMessage("GLTFExporter.Mesh | Saving " + outputBinaryFile, 2);
  353. // Write data to binary file
  354. using (BinaryWriter writer = new BinaryWriter(File.Open(outputBinaryFile, FileMode.Create)))
  355. {
  356. // BufferView - Scalar
  357. gltfIndices.ForEach(n => writer.Write(n));
  358. // BufferView - Vector3
  359. globalVerticesSubMeshes.ForEach(globalVerticesSubMesh =>
  360. {
  361. List<float> vertices = globalVerticesSubMesh.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToList();
  362. vertices.ForEach(n => writer.Write(n));
  363. List<float> normals = globalVerticesSubMesh.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToList();
  364. normals.ForEach(n => writer.Write(n));
  365. });
  366. // BufferView - Vector4
  367. globalVerticesSubMeshes.ForEach(globalVerticesSubMesh =>
  368. {
  369. if (hasColor)
  370. {
  371. List<float> colors = globalVerticesSubMesh.SelectMany(v => new[] { v.Color[0], v.Color[1], v.Color[2], v.Color[3] }).ToList();
  372. colors.ForEach(n => writer.Write(n));
  373. }
  374. });
  375. // BufferView - Vector2
  376. globalVerticesSubMeshes.ForEach(globalVerticesSubMesh =>
  377. {
  378. if (hasUV)
  379. {
  380. List<float> uvs = globalVerticesSubMesh.SelectMany(v => new[] { v.UV.X, v.UV.Y }).ToList();
  381. uvs.ForEach(n => writer.Write(n));
  382. }
  383. if (hasUV2)
  384. {
  385. List<float> uvs2 = globalVerticesSubMesh.SelectMany(v => new[] { v.UV2.X, v.UV2.Y }).ToList();
  386. uvs2.ForEach(n => writer.Write(n));
  387. }
  388. });
  389. }
  390. return gltfMesh;
  391. }
  392. private IPoint2 createIPoint2(float[] array, int index)
  393. {
  394. var startIndex = index * 2;
  395. return Loader.Global.Point2.Create(array[startIndex], array[startIndex + 1]);
  396. }
  397. private IPoint3 createIPoint3(float[] array, int index)
  398. {
  399. var startIndex = index * 3;
  400. return Loader.Global.Point3.Create(array[startIndex], array[startIndex + 1], array[startIndex + 2]);
  401. }
  402. private IPoint4 createIPoint4(float[] array, int index)
  403. {
  404. var startIndex = index * 4;
  405. return Loader.Global.Point4.Create(array[startIndex], array[startIndex + 1], array[startIndex + 2], array[startIndex + 3]);
  406. }
  407. private void AddElementsToAccessor(GLTFAccessor accessor, int count)
  408. {
  409. GLTFBufferView bufferView = accessor.BufferView;
  410. GLTFBuffer buffer = bufferView.Buffer;
  411. accessor.byteOffset = bufferView.byteLength;
  412. accessor.count += count;
  413. bufferView.byteLength += accessor.getByteLength();
  414. buffer.byteLength += accessor.getByteLength();
  415. }
  416. }
  417. }