BabylonExporter.Mesh.cs 18 KB

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