BabylonExporter.Mesh.cs 18 KB

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