BabylonExporter.Mesh.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using Autodesk.Max;
  6. using BabylonExport.Entities;
  7. using MaxSharp;
  8. namespace Max2Babylon
  9. {
  10. partial class BabylonExporter
  11. {
  12. private void ExportMesh(Node meshNode, BabylonScene babylonScene, CancellationToken token)
  13. {
  14. if (meshNode._Node.GetBoolProperty("babylonjs_noexport"))
  15. {
  16. return;
  17. }
  18. var babylonMesh = new BabylonMesh();
  19. int vx1, vx2, vx3;
  20. babylonMesh.name = meshNode.Name;
  21. babylonMesh.id = meshNode.GetGuid().ToString();
  22. if (meshNode.HasParent())
  23. {
  24. babylonMesh.parentId = meshNode.Parent.GetGuid().ToString();
  25. }
  26. // Misc.
  27. babylonMesh.isVisible = meshNode._Node.Renderable == 1;
  28. babylonMesh.pickable = meshNode._Node.GetBoolProperty("babylonjs_checkpickable");
  29. babylonMesh.receiveShadows = meshNode._Node.RcvShadows == 1;
  30. babylonMesh.showBoundingBox = meshNode._Node.GetBoolProperty("babylonjs_showboundingbox");
  31. babylonMesh.showSubMeshesBoundingBox = meshNode._Node.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  32. // Collisions
  33. babylonMesh.checkCollisions = meshNode._Node.GetBoolProperty("babylonjs_checkcollisions");
  34. // Position / rotation / scaling
  35. var wm = meshNode.GetWorldMatrix(0, meshNode.HasParent());
  36. babylonMesh.position = wm.Trans.ToArraySwitched();
  37. var parts = Loader.Global.AffineParts.Create();
  38. Loader.Global.DecompAffine(wm, parts);
  39. //var rotate = new float[3];
  40. //IntPtr xPtr = Marshal.AllocHGlobal(sizeof(float));
  41. //IntPtr yPtr = Marshal.AllocHGlobal(sizeof(float));
  42. //IntPtr zPtr = Marshal.AllocHGlobal(sizeof(float));
  43. //parts.Q.GetEuler(xPtr, yPtr, zPtr);
  44. //Marshal.Copy(xPtr, rotate, 0, 1);
  45. //Marshal.Copy(yPtr, rotate, 1, 1);
  46. //Marshal.Copy(zPtr, rotate, 2, 1);
  47. //var temp = -rotate[1];
  48. //rotate[0] = rotate[0] * parts.F;
  49. //rotate[1] = -rotate[2] * parts.F;
  50. //rotate[2] = temp * parts.F;
  51. //babylonMesh.rotation = rotate;
  52. babylonMesh.rotationQuaternion = parts.Q.ToArray();
  53. babylonMesh.scaling = parts.K.ToArraySwitched();
  54. if (wm.Parity)
  55. {
  56. vx1 = 2;
  57. vx2 = 1;
  58. vx3 = 0;
  59. }
  60. else
  61. {
  62. vx1 = 0;
  63. vx2 = 1;
  64. vx3 = 2;
  65. }
  66. // Pivot
  67. var pivotMatrix = Matrix3.Identity._IMatrix3;
  68. pivotMatrix.PreTranslate(meshNode._Node.ObjOffsetPos);
  69. Loader.Global.PreRotateMatrix(pivotMatrix, meshNode._Node.ObjOffsetRot);
  70. Loader.Global.ApplyScaling(pivotMatrix, meshNode._Node.ObjOffsetScale);
  71. babylonMesh.pivotMatrix = pivotMatrix.ToArray();
  72. // Mesh
  73. var objectState = meshNode._Node.EvalWorldState(0, false);
  74. bool mustBeDeleted;
  75. var triObject = objectState.Obj.GetMesh(out mustBeDeleted);
  76. var mesh = triObject != null ? triObject.Mesh : null;
  77. var computedMesh = meshNode.GetMesh();
  78. RaiseMessage(meshNode.Name, mesh == null ? System.Drawing.Color.Gray : System.Drawing.Color.Black, true);
  79. if (mesh != null)
  80. {
  81. mesh.BuildNormals();
  82. if (mesh.NumFaces < 1)
  83. {
  84. RaiseError(string.Format("Mesh {0} has no face", babylonMesh.name));
  85. }
  86. if (mesh.NumVerts < 3)
  87. {
  88. RaiseError(string.Format("Mesh {0} has not enough vertices", babylonMesh.name));
  89. }
  90. if (mesh.NumVerts >= 65536)
  91. {
  92. RaiseError(string.Format("Mesh {0} has too many vertices (more than 65535)", babylonMesh.name));
  93. }
  94. // Material
  95. var mtl = meshNode.Material;
  96. var multiMatsCount = 1;
  97. if (mtl != null)
  98. {
  99. babylonMesh.materialId = mtl.GetGuid().ToString();
  100. if (!referencedMaterials.Contains(mtl))
  101. {
  102. referencedMaterials.Add(mtl);
  103. }
  104. multiMatsCount = Math.Max(mtl.NumSubMaterials, 1);
  105. }
  106. babylonMesh.visibility = meshNode._Node.GetVisibility(0, Interval.Forever._IInterval);
  107. var vertices = new List<GlobalVertex>();
  108. var indices = new List<int>();
  109. var matIDs = new List<int>();
  110. var hasUV = mesh.NumTVerts > 0;
  111. var hasUV2 = mesh.GetNumMapVerts(2) > 0;
  112. var optimizeVertices = meshNode._Node.GetBoolProperty("babylonjs_optimizevertices");
  113. // Compute normals
  114. VNormal[] vnorms = null;
  115. List<GlobalVertex>[] verticesAlreadyExported = null;
  116. if (!optimizeVertices)
  117. {
  118. vnorms = Tools.ComputeNormals(mesh);
  119. }
  120. else
  121. {
  122. verticesAlreadyExported = new List<GlobalVertex>[mesh.NumVerts];
  123. }
  124. for (var face = 0; face < mesh.NumFaces; face++)
  125. {
  126. indices.Add(CreateGlobalVertex(mesh, computedMesh, face, vx1, vertices, hasUV, hasUV2, vnorms, verticesAlreadyExported));
  127. indices.Add(CreateGlobalVertex(mesh, computedMesh, face, vx2, vertices, hasUV, hasUV2, vnorms, verticesAlreadyExported));
  128. indices.Add(CreateGlobalVertex(mesh, computedMesh, face, vx3, vertices, hasUV, hasUV2, vnorms, verticesAlreadyExported));
  129. matIDs.Add(mesh.Faces[face].MatID % multiMatsCount);
  130. if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();
  131. }
  132. if (vertices.Count >= 65536)
  133. {
  134. RaiseError(string.Format("Mesh {0} has too many vertices: {1} (limit is 65535)", babylonMesh.name, vertices.Count));
  135. if (!optimizeVertices)
  136. {
  137. RaiseError("You can try to optimize your object using [Try to optimize vertices] option");
  138. }
  139. }
  140. RaiseMessage(string.Format("{0} vertices, {1} faces", vertices.Count, indices.Count / 3), true, false, true);
  141. // Buffers
  142. babylonMesh.positions = vertices.SelectMany(v => v.Position.ToArraySwitched()).ToArray();
  143. babylonMesh.normals = vertices.SelectMany(v => v.Normal.ToArraySwitched()).ToArray();
  144. if (hasUV)
  145. {
  146. babylonMesh.uvs = vertices.SelectMany(v => v.UV.ToArray()).ToArray();
  147. }
  148. if (hasUV2)
  149. {
  150. babylonMesh.uvs2 = vertices.SelectMany(v => v.UV2.ToArray()).ToArray();
  151. }
  152. // Submeshes
  153. var sortedIndices = new List<int>();
  154. var subMeshes = new List<BabylonSubMesh>();
  155. var indexStart = 0;
  156. for (var index = 0; index < multiMatsCount; index++)
  157. {
  158. var subMesh = new BabylonSubMesh();
  159. var indexCount = 0;
  160. var minVertexIndex = int.MaxValue;
  161. var maxVertexIndex = int.MinValue;
  162. subMesh.indexStart = indexStart;
  163. subMesh.materialIndex = index;
  164. for (var face = 0; face < matIDs.Count; face++)
  165. {
  166. if (matIDs[face] == index)
  167. {
  168. var a = indices[3 * face];
  169. var b = indices[3 * face + 1];
  170. var c = indices[3 * face + 2];
  171. sortedIndices.Add(a);
  172. sortedIndices.Add(b);
  173. sortedIndices.Add(c);
  174. indexCount += 3;
  175. if (a < minVertexIndex)
  176. {
  177. minVertexIndex = a;
  178. }
  179. if (b < minVertexIndex)
  180. {
  181. minVertexIndex = b;
  182. }
  183. if (c < minVertexIndex)
  184. {
  185. minVertexIndex = c;
  186. }
  187. if (a > maxVertexIndex)
  188. {
  189. maxVertexIndex = a;
  190. }
  191. if (b > maxVertexIndex)
  192. {
  193. maxVertexIndex = b;
  194. }
  195. if (c > maxVertexIndex)
  196. {
  197. maxVertexIndex = c;
  198. }
  199. }
  200. }
  201. if (indexCount != 0)
  202. {
  203. subMesh.indexCount = indexCount;
  204. subMesh.verticesStart = minVertexIndex;
  205. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  206. indexStart += indexCount;
  207. subMeshes.Add(subMesh);
  208. }
  209. if (token.IsCancellationRequested) token.ThrowIfCancellationRequested();
  210. }
  211. babylonMesh.subMeshes = subMeshes.ToArray();
  212. // Buffers - Indices
  213. babylonMesh.indices = sortedIndices.ToArray();
  214. if (mustBeDeleted)
  215. {
  216. triObject.DeleteMe();
  217. }
  218. }
  219. // Animations
  220. var animations = new List<BabylonAnimation>();
  221. if (!ExportVector3Controller(meshNode._Node.TMController.PositionController, "position", animations))
  222. {
  223. ExportVector3Animation("position", animations, key =>
  224. {
  225. var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  226. return worldMatrix.Trans.ToArraySwitched();
  227. });
  228. }
  229. if (!ExportQuaternionController(meshNode._Node.TMController.RotationController, "rotationQuaternion", animations))
  230. {
  231. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  232. {
  233. var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  234. var affineParts = Loader.Global.AffineParts.Create();
  235. Loader.Global.DecompAffine(worldMatrix, affineParts);
  236. return affineParts.Q.ToArray();
  237. });
  238. }
  239. if (!ExportVector3Controller(meshNode._Node.TMController.ScaleController, "scaling", animations))
  240. {
  241. ExportVector3Animation("scaling", animations, key =>
  242. {
  243. var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  244. var affineParts = Loader.Global.AffineParts.Create();
  245. Loader.Global.DecompAffine(worldMatrix, affineParts);
  246. return affineParts.K.ToArraySwitched();
  247. });
  248. }
  249. if (!ExportFloatController(meshNode._Node.VisController, "visibility", animations))
  250. {
  251. ExportFloatAnimation("visibility", animations, key => new[] {meshNode._Node.GetVisibility(key, Interval.Forever._IInterval)});
  252. }
  253. babylonMesh.animations = animations.ToArray();
  254. if (meshNode._Node.GetBoolProperty("babylonjs_autoanimate"))
  255. {
  256. babylonMesh.autoAnimate = true;
  257. babylonMesh.autoAnimateFrom = (int)meshNode._Node.GetFloatProperty("babylonjs_autoanimate_from");
  258. babylonMesh.autoAnimateTo = (int)meshNode._Node.GetFloatProperty("babylonjs_autoanimate_to");
  259. babylonMesh.autoAnimateLoop = meshNode._Node.GetBoolProperty("babylonjs_autoanimateloop");
  260. }
  261. babylonScene.MeshesList.Add(babylonMesh);
  262. }
  263. int CreateGlobalVertex(IMesh mesh, Mesh computedMesh, int face, int facePart, List<GlobalVertex> vertices, bool hasUV, bool hasUV2, VNormal[] vnorms, List<GlobalVertex>[] verticesAlreadyExported)
  264. {
  265. var faceObject = mesh.Faces[face];
  266. var vertexIndex = (int)faceObject.V[facePart];
  267. var vertex = new GlobalVertex
  268. {
  269. BaseIndex = vertexIndex,
  270. Position = mesh.Verts[vertexIndex],
  271. Normal = (vnorms != null) ? vnorms[vertexIndex].GetNormal(faceObject.SmGroup) : computedMesh.vnormals[vertexIndex]._IPoint3
  272. };
  273. if (hasUV)
  274. {
  275. var tvertexIndex = (int)mesh.TvFace[face].T[facePart];
  276. vertex.UV = Loader.Global.Point2.Create(mesh.TVerts[tvertexIndex].X, mesh.TVerts[tvertexIndex].Y);
  277. }
  278. if (hasUV2)
  279. {
  280. var tvertexIndex = (int)mesh.MapFaces(2)[face].T[facePart];
  281. vertex.UV2 = Loader.Global.Point2.Create(mesh.MapVerts(2)[tvertexIndex].X, mesh.MapVerts(2)[tvertexIndex].Y);
  282. }
  283. if (verticesAlreadyExported != null)
  284. {
  285. if (verticesAlreadyExported[vertexIndex] != null)
  286. {
  287. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  288. if (index > -1)
  289. {
  290. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  291. }
  292. }
  293. else
  294. {
  295. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  296. }
  297. vertex.CurrentIndex = vertices.Count;
  298. verticesAlreadyExported[vertexIndex].Add(vertex);
  299. }
  300. vertices.Add(vertex);
  301. return vertices.Count - 1;
  302. }
  303. }
  304. }