BabylonExporter.Mesh.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. List<int> boneIds = null;
  51. if (isSkinned)
  52. {
  53. //unskinnedMesh = skin.InitialPose;
  54. bonesCount = skin.TotalSkinBoneCount;
  55. skins.Add(skin);
  56. skinnedNodes.Add(meshNode);
  57. babylonMesh.skeletonId = skins.IndexOf(skin);
  58. skin.GetInitSkinTM(skinInitPoseMatrix);
  59. boneIds = new List<int>();
  60. for (var index = 0; index < skin.TotalSkinBoneCount; index++)
  61. {
  62. var bone = skin.GetIGameBone(index, false);
  63. if(bone == null)
  64. {
  65. // non bone in skeletton
  66. boneIds.Add(-2);
  67. }
  68. else
  69. {
  70. boneIds.Add(bone.NodeID);
  71. }
  72. }
  73. }
  74. // Position / rotation / scaling
  75. {
  76. //var localTM = unskinnedMesh.IGameObjectTM;
  77. //var worldTM = meshNode.GetWorldTM(0);
  78. var localTM = meshNode.GetObjectTM(0);
  79. var meshTrans = localTM.Translation;
  80. var meshRotation = localTM.Rotation;
  81. var meshScale = localTM.Scaling;
  82. babylonMesh.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  83. //float rotx = 0, roty = 0, rotz = 0;
  84. //unsafe
  85. //{
  86. // meshRotation.GetEuler(new IntPtr(&rotx), new IntPtr(&roty), new IntPtr(&rotz));
  87. //}
  88. //babylonMesh.rotation = new float[] { rotx, roty, rotz };
  89. babylonMesh.rotationQuaternion = new float[] { meshRotation.X, meshRotation.Y, meshRotation.Z, -meshRotation.W };
  90. babylonMesh.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  91. }
  92. //// Pivot // something to do with GameMesh ?
  93. //meshNode.GetObjectTM
  94. //var pivotMatrix = Tools.Identity;
  95. //pivotMatrix.PreTranslate(meshNode.ObjOffsetPos);
  96. //Loader.Global.PreRotateMatrix(pivotMatrix, meshNode.ObjOffsetRot);
  97. //Loader.Global.ApplyScaling(pivotMatrix, meshNode.ObjOffsetScale);
  98. //babylonMesh.pivotMatrix = pivotMatrix.ToArray();
  99. // Mesh
  100. RaiseMessage(meshNode.Name, 1);
  101. if (unskinnedMesh != null && unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
  102. {
  103. if (unskinnedMesh.NumberOfFaces < 1)
  104. {
  105. RaiseError(string.Format("Mesh {0} has no face", babylonMesh.name), 2);
  106. }
  107. if (unskinnedMesh.NumberOfVerts < 3)
  108. {
  109. RaiseError(string.Format("Mesh {0} has not enough vertices", babylonMesh.name), 2);
  110. }
  111. if (unskinnedMesh.NumberOfVerts >= 65536)
  112. {
  113. 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);
  114. }
  115. // Material
  116. var mtl = meshNode.NodeMaterial;
  117. var multiMatsCount = 1;
  118. if (mtl != null)
  119. {
  120. babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
  121. if (!referencedMaterials.Contains(mtl))
  122. {
  123. referencedMaterials.Add(mtl);
  124. }
  125. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  126. }
  127. babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
  128. var vertices = new List<GlobalVertex>();
  129. var indices = new List<int>();
  130. var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
  131. bool hasUV = false;
  132. bool hasUV2 = false;
  133. for (int i = 0; i < mappingChannels.Count; ++i)
  134. {
  135. IntPtr indexer = new IntPtr(i);
  136. var channelNum = mappingChannels[indexer];
  137. if (channelNum == 1)
  138. {
  139. hasUV = true;
  140. }
  141. else if (channelNum == 2)
  142. {
  143. hasUV2 = true;
  144. }
  145. }
  146. var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
  147. var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
  148. var optimizeVertices = meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
  149. // Compute normals
  150. // VNormal[] vnorms = Tools.ComputeNormals(mesh, optimizeVertices);
  151. List<GlobalVertex>[] verticesAlreadyExported = null;
  152. if (optimizeVertices)
  153. {
  154. verticesAlreadyExported = new List<GlobalVertex>[unskinnedMesh.NumberOfVerts];
  155. }
  156. var subMeshes = new List<BabylonSubMesh>();
  157. var indexStart = 0;
  158. for (int i = 0; i < multiMatsCount; ++i)
  159. {
  160. int materialId = meshNode.NodeMaterial.GetMaterialID(i);
  161. ITab<IFaceEx> materialFaces = null;
  162. var indexCount = 0;
  163. var minVertexIndex = int.MaxValue;
  164. var maxVertexIndex = int.MinValue;
  165. var subMesh = new BabylonSubMesh();
  166. subMesh.indexStart = indexStart;
  167. subMesh.materialIndex = i;
  168. if (multiMatsCount == 1)
  169. {
  170. for(int j = 0; j < unskinnedMesh.NumberOfFaces; ++j)
  171. {
  172. var face = unskinnedMesh.GetFace(j);
  173. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  174. }
  175. }
  176. else
  177. {
  178. materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
  179. for (int j = 0; j < materialFaces.Count; ++j)
  180. {
  181. var faceIndexer = new IntPtr(j);
  182. var face = materialFaces[faceIndexer];
  183. Marshal.FreeHGlobal(faceIndexer);
  184. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  185. }
  186. }
  187. if (indexCount != 0)
  188. {
  189. subMesh.indexCount = indexCount;
  190. subMesh.verticesStart = minVertexIndex;
  191. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  192. indexStart += indexCount;
  193. subMeshes.Add(subMesh);
  194. }
  195. }
  196. if (vertices.Count >= 65536)
  197. {
  198. RaiseError(string.Format("Mesh {0} has too many vertices: {1} (limit is 65535)", babylonMesh.name, vertices.Count), 2);
  199. if (!optimizeVertices)
  200. {
  201. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  202. }
  203. }
  204. RaiseMessage(string.Format("{0} vertices, {1} faces", vertices.Count, indices.Count / 3), 2);
  205. // Buffers
  206. babylonMesh.positions = vertices.SelectMany(v => new float[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  207. babylonMesh.normals = vertices.SelectMany(v => new float[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  208. if (hasUV)
  209. {
  210. babylonMesh.uvs = vertices.SelectMany(v => new float[] { v.UV.X, 1 - v.UV.Y }).ToArray();
  211. }
  212. if (hasUV2)
  213. {
  214. babylonMesh.uvs2 = vertices.SelectMany(v => new float[] { v.UV2.X, 1 - v.UV2.Y }).ToArray();
  215. }
  216. if (skin != null)
  217. {
  218. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  219. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  220. }
  221. if (hasColor)
  222. {
  223. babylonMesh.colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
  224. babylonMesh.hasVertexAlpha = hasAlpha;
  225. }
  226. babylonMesh.subMeshes = subMeshes.ToArray();
  227. // Buffers - Indices
  228. babylonMesh.indices = indices.ToArray();
  229. }
  230. // handle instances and animations
  231. // Instances
  232. var tabs = Loader.Global.NodeTab.Create();
  233. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
  234. var instances = new List<BabylonAbstractMesh>();
  235. for (var index = 0; index < tabs.Count; index++)
  236. {
  237. var indexer = new IntPtr(index);
  238. var tab = tabs[indexer];
  239. Marshal.FreeHGlobal(indexer);
  240. if (meshNode.MaxNode.GetGuid() == tab.GetGuid())
  241. {
  242. continue;
  243. }
  244. var instanceGameNode = scene.GetIGameNode(tab);
  245. if (instanceGameNode == null)
  246. {
  247. continue;
  248. }
  249. tab.MarkAsInstance();
  250. var instance = new BabylonAbstractMesh { name = tab.Name };
  251. {
  252. var localTM = meshNode.GetObjectTM(0);
  253. //var worldTM = meshNode.GetWorldTM(0);
  254. //var objTM = meshNode.GetObjectTM(0);
  255. var meshTrans = localTM.Translation;
  256. var meshRotation = localTM.Rotation;
  257. var meshScale = localTM.Scaling;
  258. instance.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  259. float rotx = 0, roty = 0, rotz = 0;
  260. unsafe
  261. {
  262. meshRotation.GetEuler(new IntPtr(&rotx), new IntPtr(&roty), new IntPtr(&rotz));
  263. }
  264. instance.rotation = new float[] { rotx, roty, rotz };
  265. instance.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  266. }
  267. var instanceAnimations = new List<BabylonAnimation>();
  268. GenerateCoordinatesAnimations(meshNode, instanceAnimations);
  269. instance.animations = instanceAnimations.ToArray();
  270. instances.Add(instance);
  271. }
  272. babylonMesh.instances = instances.ToArray();
  273. // Animations
  274. var animations = new List<BabylonAnimation>();
  275. GenerateCoordinatesAnimations(meshNode, animations);
  276. if (!ExportFloatController(meshNode.MaxNode.VisController, "visibility", animations))
  277. {
  278. ExportFloatAnimation("visibility", animations, key => new[] { meshNode.MaxNode.GetVisibility(key, Tools.Forever) });
  279. }
  280. babylonMesh.animations = animations.ToArray();
  281. if (meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimate", 1))
  282. {
  283. babylonMesh.autoAnimate = true;
  284. babylonMesh.autoAnimateFrom = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_from");
  285. babylonMesh.autoAnimateTo = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  286. babylonMesh.autoAnimateLoop = meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  287. }
  288. babylonScene.MeshesList.Add(babylonMesh);
  289. }
  290. 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, List<int> boneIds)
  291. {
  292. var a = CreateGlobalVertex(unskinnedMesh, face, 0, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  293. var b = CreateGlobalVertex(unskinnedMesh, face, 2, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  294. var c = CreateGlobalVertex(unskinnedMesh, face, 1, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  295. indices.Add(a);
  296. indices.Add(b);
  297. indices.Add(c);
  298. if (a < minVertexIndex)
  299. {
  300. minVertexIndex = a;
  301. }
  302. if (b < minVertexIndex)
  303. {
  304. minVertexIndex = b;
  305. }
  306. if (c < minVertexIndex)
  307. {
  308. minVertexIndex = c;
  309. }
  310. if (a > maxVertexIndex)
  311. {
  312. maxVertexIndex = a;
  313. }
  314. if (b > maxVertexIndex)
  315. {
  316. maxVertexIndex = b;
  317. }
  318. if (c > maxVertexIndex)
  319. {
  320. maxVertexIndex = c;
  321. }
  322. indexCount += 3;
  323. CheckCancelled();
  324. }
  325. public static void GenerateCoordinatesAnimations(IIGameNode meshNode, List<BabylonAnimation> animations)
  326. {
  327. //if (!ExportVector3Controller(meshNode.TMController.PositionController, "position", animations))
  328. //{
  329. ExportVector3Animation("position", animations, key =>
  330. {
  331. var worldMatrix = meshNode.GetObjectTM(key);
  332. var trans = worldMatrix.Translation;
  333. return new float[] { trans.X, trans.Y, trans.Z };
  334. });
  335. //}
  336. //if (!ExportQuaternionController(meshNode.TMController.RotationController, "rotationQuaternion", animations))
  337. //{
  338. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  339. {
  340. var worldMatrix = meshNode.GetObjectTM(key);
  341. var rot = worldMatrix.Rotation;
  342. return new float[] { rot.X, rot.Y, rot.Z, -rot.W };
  343. });
  344. //}
  345. //if (!ExportVector3Controller(meshNode.TMController.ScaleController, "scaling", animations))
  346. //{
  347. ExportVector3Animation("scaling", animations, key =>
  348. {
  349. var worldMatrix = meshNode.GetObjectTM(key);
  350. var scale = worldMatrix.Scaling;
  351. return new float[] { scale.X, scale.Y, scale.Z };
  352. });
  353. // }
  354. }
  355. int CreateGlobalVertex(IIGameMesh mesh, IFaceEx face, int facePart, List<GlobalVertex> vertices, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, List<GlobalVertex>[] verticesAlreadyExported, IIGameSkin skin, List<int> boneIds)
  356. {
  357. var vertexIndex = (int)face.Vert[facePart];
  358. var vertex = new GlobalVertex
  359. {
  360. BaseIndex = vertexIndex,
  361. Position = mesh.GetVertex(vertexIndex, true),
  362. Normal = mesh.GetNormal((int)face.Norm[facePart], true) //vnorms[vertexIndex].GetNormal(verticesAlreadyExported != null ? 1 : faceObject.SmGroup)
  363. };
  364. if (hasUV)
  365. {
  366. int[] indices = new int[3];
  367. unsafe
  368. {
  369. fixed (int* indicesPtr = indices)
  370. {
  371. mesh.GetMapFaceIndex(1, face.MeshFaceIndex, new IntPtr(indicesPtr));
  372. }
  373. }
  374. var texCoord = mesh.GetMapVertex(1, indices[facePart]);
  375. vertex.UV = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  376. }
  377. if (hasUV2)
  378. {
  379. int[] indices = new int[3];
  380. unsafe
  381. {
  382. fixed (int* indicesPtr = indices)
  383. {
  384. mesh.GetMapFaceIndex(2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  385. }
  386. }
  387. var texCoord = mesh.GetMapVertex(2, indices[facePart]);
  388. vertex.UV2 = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  389. }
  390. if (hasColor)
  391. {
  392. var vertexColorIndex = (int)face.Color[facePart];
  393. var vertexColor = mesh.GetColorVertex(vertexColorIndex);
  394. float alpha = 1;
  395. if (hasAlpha)
  396. {
  397. IPoint3 p = Loader.Global.Point3.Create();
  398. mesh.GetMapFaceIndex(-2, face.MeshFaceIndex, p.GetNativeHandle());
  399. alpha = p.X;
  400. }
  401. vertex.Color = new float[] { vertexColor.X, vertexColor.Y, vertexColor.Z, alpha };
  402. }
  403. if (skin != null)
  404. {
  405. float weight0 = 0;
  406. float weight1 = 0;
  407. float weight2 = 0;
  408. int bone0 = bonesCount;
  409. int bone1 = bonesCount;
  410. int bone2 = bonesCount;
  411. int bone3 = bonesCount;
  412. int nbBones = skin.GetNumberOfBones(vertexIndex);
  413. if (nbBones > 0)
  414. {
  415. bone0 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 0).NodeID);
  416. weight0 = skin.GetWeight(vertexIndex, 0);
  417. }
  418. if (nbBones > 1)
  419. {
  420. bone1 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 1).NodeID);
  421. weight1 = skin.GetWeight(vertexIndex, 1);
  422. }
  423. if (nbBones > 2)
  424. {
  425. bone2 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 2).NodeID);
  426. weight2 = skin.GetWeight(vertexIndex, 2);
  427. }
  428. if (nbBones > 3)
  429. {
  430. bone3 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 3).NodeID);
  431. }
  432. if (nbBones == 0)
  433. {
  434. weight0 = 1.0f;
  435. bone0 = bonesCount;
  436. }
  437. if (nbBones > 4)
  438. {
  439. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 4 bones influences per vertex.", 2);
  440. }
  441. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, 1.0 - weight0 - weight1 - weight2);
  442. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  443. }
  444. if (verticesAlreadyExported != null)
  445. {
  446. if (verticesAlreadyExported[vertexIndex] != null)
  447. {
  448. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  449. if (index > -1)
  450. {
  451. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  452. }
  453. }
  454. else
  455. {
  456. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  457. }
  458. vertex.CurrentIndex = vertices.Count;
  459. verticesAlreadyExported[vertexIndex].Add(vertex);
  460. }
  461. vertices.Add(vertex);
  462. return vertices.Count - 1;
  463. }
  464. }
  465. }