BabylonExporter.Mesh.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  13. {
  14. if (meshNode.MaxNode.IsInstance())
  15. {
  16. return;
  17. }
  18. if (meshNode.MaxNode.GetBoolProperty("babylonjs_noexport"))
  19. {
  20. return;
  21. }
  22. if (!ExportHiddenObjects && meshNode.MaxNode.IsHidden(NodeHideFlags.None, false))
  23. {
  24. return;
  25. }
  26. var gameMesh = meshNode.IGameObject.AsGameMesh();
  27. bool initialized = gameMesh.InitializeData; //needed, the property is in fact a method initializing the exporter that has wrongly been auto
  28. // translated into a property because it has no parameters
  29. var babylonMesh = new BabylonMesh();
  30. babylonMesh.name = meshNode.Name;
  31. babylonMesh.id = meshNode.MaxNode.GetGuid().ToString();
  32. if (meshNode.NodeParent != null)
  33. {
  34. babylonMesh.parentId = meshNode.NodeParent.MaxNode.GetGuid().ToString();
  35. }
  36. // Misc.
  37. babylonMesh.isVisible = meshNode.MaxNode.Renderable == 1;
  38. babylonMesh.pickable = meshNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
  39. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
  40. babylonMesh.showBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
  41. babylonMesh.showSubMeshesBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  42. babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;
  43. babylonMesh.alphaIndex = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000);
  44. // Collisions
  45. babylonMesh.checkCollisions = meshNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
  46. bool isSkinned = gameMesh.IsObjectSkinned;
  47. var skin = gameMesh.IGameSkin;
  48. var unskinnedMesh = gameMesh;
  49. IGMatrix skinInitPoseMatrix = Loader.Global.GMatrix.Create(Loader.Global.Matrix3.Create(true));
  50. if (isSkinned)
  51. {
  52. bonesCount = skin.TotalSkinBoneCount;
  53. skins.Add(skin);
  54. skinnedNodes.Add(meshNode);
  55. babylonMesh.skeletonId = skins.IndexOf(skin);
  56. skin.GetInitSkinTM(skinInitPoseMatrix);
  57. }
  58. // Position / rotation / scaling
  59. {
  60. var localTM = meshNode.GetObjectTM(0);
  61. var meshTrans = localTM.Translation;
  62. var meshRotation = localTM.Rotation;
  63. var meshScale = localTM.Scaling;
  64. babylonMesh.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  65. babylonMesh.rotationQuaternion = new float[] { meshRotation.X, meshRotation.Y, meshRotation.Z, -meshRotation.W };
  66. babylonMesh.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  67. }
  68. // Mesh
  69. RaiseMessage(meshNode.Name, 1);
  70. if (unskinnedMesh != null && unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
  71. {
  72. if (unskinnedMesh.NumberOfFaces < 1)
  73. {
  74. RaiseError(string.Format("Mesh {0} has no face", babylonMesh.name), 2);
  75. }
  76. if (unskinnedMesh.NumberOfVerts < 3)
  77. {
  78. RaiseError(string.Format("Mesh {0} has not enough vertices", babylonMesh.name), 2);
  79. }
  80. if (unskinnedMesh.NumberOfVerts >= 65536)
  81. {
  82. 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);
  83. }
  84. // Material
  85. var mtl = meshNode.NodeMaterial;
  86. var multiMatsCount = 1;
  87. if (mtl != null)
  88. {
  89. babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
  90. if (!referencedMaterials.Contains(mtl))
  91. {
  92. referencedMaterials.Add(mtl);
  93. }
  94. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  95. }
  96. babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
  97. var vertices = new List<GlobalVertex>();
  98. var indices = new List<int>();
  99. var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
  100. bool hasUV = false;
  101. bool hasUV2 = false;
  102. for (int i = 0; i < mappingChannels.Count; ++i)
  103. {
  104. IntPtr indexer = new IntPtr(i);
  105. var channelNum = mappingChannels[indexer];
  106. if (channelNum == 1)
  107. {
  108. hasUV = true;
  109. }
  110. else if (channelNum == 2)
  111. {
  112. hasUV2 = true;
  113. }
  114. }
  115. var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
  116. var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
  117. var optimizeVertices = meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
  118. // Compute normals
  119. List<GlobalVertex>[] verticesAlreadyExported = null;
  120. if (optimizeVertices)
  121. {
  122. verticesAlreadyExported = new List<GlobalVertex>[unskinnedMesh.NumberOfVerts];
  123. }
  124. var subMeshes = new List<BabylonSubMesh>();
  125. var indexStart = 0;
  126. for (int i = 0; i < multiMatsCount; ++i)
  127. {
  128. if (meshNode.NodeMaterial == null)
  129. {
  130. continue;
  131. }
  132. int materialId = meshNode.NodeMaterial.GetMaterialID(i);
  133. ITab<IFaceEx> materialFaces = null;
  134. var indexCount = 0;
  135. var minVertexIndex = int.MaxValue;
  136. var maxVertexIndex = int.MinValue;
  137. var subMesh = new BabylonSubMesh();
  138. subMesh.indexStart = indexStart;
  139. subMesh.materialIndex = i;
  140. if (multiMatsCount == 1)
  141. {
  142. for (int j = 0; j < unskinnedMesh.NumberOfFaces; ++j)
  143. {
  144. var face = unskinnedMesh.GetFace(j);
  145. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face);
  146. }
  147. }
  148. else
  149. {
  150. materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
  151. for (int j = 0; j < materialFaces.Count; ++j)
  152. {
  153. var faceIndexer = new IntPtr(j);
  154. var face = materialFaces[faceIndexer];
  155. Marshal.FreeHGlobal(faceIndexer);
  156. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face);
  157. }
  158. }
  159. if (indexCount != 0)
  160. {
  161. subMesh.indexCount = indexCount;
  162. subMesh.verticesStart = minVertexIndex;
  163. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  164. indexStart += indexCount;
  165. subMeshes.Add(subMesh);
  166. }
  167. }
  168. if (vertices.Count >= 65536)
  169. {
  170. RaiseWarning(string.Format("Mesh {0} has {1} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", babylonMesh.name, vertices.Count), 2);
  171. if (!optimizeVertices)
  172. {
  173. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  174. }
  175. }
  176. RaiseMessage(string.Format("{0} vertices, {1} faces", vertices.Count, indices.Count / 3), 2);
  177. // Buffers
  178. babylonMesh.positions = vertices.SelectMany(v => new float[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  179. babylonMesh.normals = vertices.SelectMany(v => new float[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  180. if (hasUV)
  181. {
  182. babylonMesh.uvs = vertices.SelectMany(v => new float[] { v.UV.X, 1 - v.UV.Y }).ToArray();
  183. }
  184. if (hasUV2)
  185. {
  186. babylonMesh.uvs2 = vertices.SelectMany(v => new float[] { v.UV2.X, 1 - v.UV2.Y }).ToArray();
  187. }
  188. if (skin != null)
  189. {
  190. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  191. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  192. }
  193. if (hasColor)
  194. {
  195. babylonMesh.colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
  196. babylonMesh.hasVertexAlpha = hasAlpha;
  197. }
  198. babylonMesh.subMeshes = subMeshes.ToArray();
  199. // Buffers - Indices
  200. babylonMesh.indices = indices.ToArray();
  201. }
  202. // Instances
  203. var tabs = Loader.Global.NodeTab.Create();
  204. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
  205. var instances = new List<BabylonAbstractMesh>();
  206. for (var index = 0; index < tabs.Count; index++)
  207. {
  208. var indexer = new IntPtr(index);
  209. var tab = tabs[indexer];
  210. Marshal.FreeHGlobal(indexer);
  211. if (meshNode.MaxNode.GetGuid() == tab.GetGuid())
  212. {
  213. continue;
  214. }
  215. var instanceGameNode = scene.GetIGameNode(tab);
  216. if (instanceGameNode == null)
  217. {
  218. continue;
  219. }
  220. tab.MarkAsInstance();
  221. var instance = new BabylonAbstractMesh { name = tab.Name };
  222. {
  223. var localTM = meshNode.GetObjectTM(0);
  224. var meshTrans = localTM.Translation;
  225. var meshRotation = localTM.Rotation;
  226. var meshScale = localTM.Scaling;
  227. instance.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  228. float rotx = 0, roty = 0, rotz = 0;
  229. unsafe
  230. {
  231. meshRotation.GetEuler(new IntPtr(&rotx), new IntPtr(&roty), new IntPtr(&rotz));
  232. }
  233. instance.rotation = new float[] { rotx, roty, rotz };
  234. instance.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  235. }
  236. var instanceAnimations = new List<BabylonAnimation>();
  237. GenerateCoordinatesAnimations(meshNode, instanceAnimations);
  238. instance.animations = instanceAnimations.ToArray();
  239. instances.Add(instance);
  240. }
  241. babylonMesh.instances = instances.ToArray();
  242. // Animations
  243. var animations = new List<BabylonAnimation>();
  244. GenerateCoordinatesAnimations(meshNode, animations);
  245. if (!ExportFloatController(meshNode.MaxNode.VisController, "visibility", animations))
  246. {
  247. ExportFloatAnimation("visibility", animations, key => new[] { meshNode.MaxNode.GetVisibility(key, Tools.Forever) });
  248. }
  249. babylonMesh.animations = animations.ToArray();
  250. if (meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimate", 1))
  251. {
  252. babylonMesh.autoAnimate = true;
  253. babylonMesh.autoAnimateFrom = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_from");
  254. babylonMesh.autoAnimateTo = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  255. babylonMesh.autoAnimateLoop = meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  256. }
  257. babylonScene.MeshesList.Add(babylonMesh);
  258. }
  259. private void ExtractFace(IIGameSkin skin, IIGameMesh unskinnedMesh, List<GlobalVertex> vertices, List<int> indices, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, List<GlobalVertex>[] verticesAlreadyExported, ref int indexCount, ref int minVertexIndex, ref int maxVertexIndex, IFaceEx face)
  260. {
  261. var a = CreateGlobalVertex(unskinnedMesh, face, 0, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin);
  262. var b = CreateGlobalVertex(unskinnedMesh, face, 2, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin);
  263. var c = CreateGlobalVertex(unskinnedMesh, face, 1, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin);
  264. indices.Add(a);
  265. indices.Add(b);
  266. indices.Add(c);
  267. if (a < minVertexIndex)
  268. {
  269. minVertexIndex = a;
  270. }
  271. if (b < minVertexIndex)
  272. {
  273. minVertexIndex = b;
  274. }
  275. if (c < minVertexIndex)
  276. {
  277. minVertexIndex = c;
  278. }
  279. if (a > maxVertexIndex)
  280. {
  281. maxVertexIndex = a;
  282. }
  283. if (b > maxVertexIndex)
  284. {
  285. maxVertexIndex = b;
  286. }
  287. if (c > maxVertexIndex)
  288. {
  289. maxVertexIndex = c;
  290. }
  291. indexCount += 3;
  292. CheckCancelled();
  293. }
  294. public static void GenerateCoordinatesAnimations(IIGameNode meshNode, List<BabylonAnimation> animations)
  295. {
  296. ExportVector3Animation("position", animations, key =>
  297. {
  298. var worldMatrix = meshNode.GetObjectTM(key);
  299. var trans = worldMatrix.Translation;
  300. return new float[] { trans.X, trans.Y, trans.Z };
  301. });
  302. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  303. {
  304. var worldMatrix = meshNode.GetObjectTM(key);
  305. var rot = worldMatrix.Rotation;
  306. return new float[] { rot.X, rot.Y, rot.Z, -rot.W };
  307. });
  308. ExportVector3Animation("scaling", animations, key =>
  309. {
  310. var worldMatrix = meshNode.GetObjectTM(key);
  311. var scale = worldMatrix.Scaling;
  312. return new float[] { scale.X, scale.Y, scale.Z };
  313. });
  314. }
  315. int CreateGlobalVertex(IIGameMesh mesh, IFaceEx face, int facePart, List<GlobalVertex> vertices, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, List<GlobalVertex>[] verticesAlreadyExported, IIGameSkin skin)
  316. {
  317. var vertexIndex = (int)face.Vert[facePart];
  318. var vertex = new GlobalVertex
  319. {
  320. BaseIndex = vertexIndex,
  321. Position = mesh.GetVertex(vertexIndex, true),
  322. Normal = mesh.GetNormal((int)face.Norm[facePart], true)
  323. };
  324. if (hasUV)
  325. {
  326. int[] indices = new int[3];
  327. unsafe
  328. {
  329. fixed (int* indicesPtr = indices)
  330. {
  331. mesh.GetMapFaceIndex(1, face.MeshFaceIndex, new IntPtr(indicesPtr));
  332. }
  333. }
  334. var texCoord = mesh.GetMapVertex(1, indices[facePart]);
  335. vertex.UV = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  336. }
  337. if (hasUV2)
  338. {
  339. int[] indices = new int[3];
  340. unsafe
  341. {
  342. fixed (int* indicesPtr = indices)
  343. {
  344. mesh.GetMapFaceIndex(2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  345. }
  346. }
  347. var texCoord = mesh.GetMapVertex(2, indices[facePart]);
  348. vertex.UV2 = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  349. }
  350. if (hasColor)
  351. {
  352. var vertexColorIndex = (int)face.Color[facePart];
  353. var vertexColor = mesh.GetColorVertex(vertexColorIndex);
  354. float alpha = 1;
  355. if (hasAlpha)
  356. {
  357. IPoint3 p = Loader.Global.Point3.Create();
  358. mesh.GetMapFaceIndex(-2, face.MeshFaceIndex, p.GetNativeHandle());
  359. alpha = p.X;
  360. }
  361. vertex.Color = new float[] { vertexColor.X, vertexColor.Y, vertexColor.Z, alpha };
  362. }
  363. if (skin != null)
  364. {
  365. float weight0 = 0;
  366. float weight1 = 0;
  367. float weight2 = 0;
  368. int bone0 = bonesCount;
  369. int bone1 = bonesCount;
  370. int bone2 = bonesCount;
  371. int bone3 = bonesCount;
  372. int nbBones = skin.GetNumberOfBones(vertexIndex);
  373. if (nbBones > 0)
  374. {
  375. bone0 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 0), false);
  376. weight0 = skin.GetWeight(vertexIndex, 0);
  377. }
  378. if (nbBones > 1)
  379. {
  380. bone1 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 1), false);
  381. weight1 = skin.GetWeight(vertexIndex, 1);
  382. }
  383. if (nbBones > 2)
  384. {
  385. bone2 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 2), false);
  386. weight2 = skin.GetWeight(vertexIndex, 2);
  387. }
  388. if (nbBones > 3)
  389. {
  390. bone3 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 3), false);
  391. }
  392. if (nbBones == 0)
  393. {
  394. weight0 = 1.0f;
  395. bone0 = bonesCount;
  396. }
  397. if (nbBones > 4)
  398. {
  399. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 4 bones influences per vertex.", 2);
  400. }
  401. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, 1.0 - weight0 - weight1 - weight2);
  402. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  403. }
  404. if (verticesAlreadyExported != null)
  405. {
  406. if (verticesAlreadyExported[vertexIndex] != null)
  407. {
  408. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  409. if (index > -1)
  410. {
  411. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  412. }
  413. }
  414. else
  415. {
  416. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  417. }
  418. vertex.CurrentIndex = vertices.Count;
  419. verticesAlreadyExported[vertexIndex].Add(vertex);
  420. }
  421. vertices.Add(vertex);
  422. return vertices.Count - 1;
  423. }
  424. }
  425. }