BabylonExporter.Mesh.cs 17 KB

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