BabylonExporter.Mesh.cs 17 KB

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