BabylonExporter.Mesh.cs 23 KB

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