BabylonExporter.Mesh.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. using Autodesk.Max;
  2. using BabylonExport.Entities;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. namespace Max2Babylon
  9. {
  10. partial class BabylonExporter
  11. {
  12. private int bonesCount;
  13. readonly Dictionary<IIGameSkin, List<int>> skinSortedBones = new Dictionary<IIGameSkin, List<int>>();
  14. private bool IsMeshExportable(IIGameNode meshNode)
  15. {
  16. if (meshNode.MaxNode.GetBoolProperty("babylonjs_noexport"))
  17. {
  18. return false;
  19. }
  20. if (!ExportHiddenObjects && meshNode.MaxNode.IsHidden(NodeHideFlags.None, false))
  21. {
  22. return false;
  23. }
  24. return true;
  25. }
  26. private BabylonNode ExportDummy(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  27. {
  28. RaiseMessage(meshNode.Name, 1);
  29. var gameMesh = meshNode.IGameObject.AsGameMesh();
  30. bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
  31. // translated into a property because it has no parameters
  32. var babylonMesh = new BabylonMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
  33. babylonMesh.isDummy = true;
  34. // Position / rotation / scaling / hierarchy
  35. exportNode(babylonMesh, meshNode, scene, babylonScene);
  36. // Animations
  37. exportAnimation(babylonMesh, meshNode);
  38. babylonScene.MeshesList.Add(babylonMesh);
  39. return babylonMesh;
  40. }
  41. private BabylonNode ExportMesh(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  42. {
  43. if (IsMeshExportable(meshNode) == false)
  44. {
  45. return null;
  46. }
  47. RaiseMessage(meshNode.Name, 1);
  48. // Instances
  49. var tabs = Loader.Global.NodeTab.Create();
  50. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
  51. if (tabs.Count > 1)
  52. {
  53. // For a mesh with instances, we distinguish between master and instance meshes:
  54. // - a master mesh stores all the info of the mesh (transform, hierarchy, animations + vertices, indices, materials, bones...)
  55. // - an instance mesh only stores the info of the node (transform, hierarchy, animations)
  56. // Check if this mesh has already been exported
  57. BabylonMesh babylonMasterMesh = null;
  58. var index = 0;
  59. while (babylonMasterMesh == null &&
  60. index < tabs.Count)
  61. {
  62. #if MAX2017
  63. var indexer = index;
  64. #else
  65. var indexer = new IntPtr(index);
  66. #endif
  67. var tab = tabs[indexer];
  68. babylonMasterMesh = babylonScene.MeshesList.Find(_babylonMesh => {
  69. // Same id
  70. return _babylonMesh.id == tab.GetGuid().ToString() &&
  71. // Mesh is not a dummy
  72. _babylonMesh.isDummy == false;
  73. });
  74. index++;
  75. }
  76. if (babylonMasterMesh != null)
  77. {
  78. // Mesh already exported
  79. // Export this node as instance
  80. meshNode.MaxNode.MarkAsInstance();
  81. var babylonInstanceMesh = new BabylonAbstractMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
  82. // Add instance to master mesh
  83. List<BabylonAbstractMesh> list = babylonMasterMesh.instances != null ? babylonMasterMesh.instances.ToList() : new List<BabylonAbstractMesh>();
  84. list.Add(babylonInstanceMesh);
  85. babylonMasterMesh.instances = list.ToArray();
  86. // Export transform / hierarchy / animations
  87. exportNode(babylonInstanceMesh, meshNode, scene, babylonScene);
  88. // Animations
  89. exportAnimation(babylonInstanceMesh, meshNode);
  90. return babylonInstanceMesh;
  91. }
  92. }
  93. var gameMesh = meshNode.IGameObject.AsGameMesh();
  94. bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
  95. // translated into a property because it has no parameters
  96. var babylonMesh = new BabylonMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
  97. // Position / rotation / scaling / hierarchy
  98. exportNode(babylonMesh, meshNode, scene, babylonScene);
  99. // Animations
  100. exportAnimation(babylonMesh, meshNode);
  101. // Sounds
  102. var soundName = meshNode.MaxNode.GetStringProperty("babylonjs_sound_filename", "");
  103. if (!string.IsNullOrEmpty(soundName))
  104. {
  105. var filename = Path.GetFileName(soundName);
  106. var meshSound = new BabylonSound
  107. {
  108. name = filename,
  109. autoplay = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_autoplay", 1),
  110. loop = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_loop", 1),
  111. volume = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_volume", 1.0f),
  112. playbackRate = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_playbackrate", 1.0f),
  113. connectedMeshId = babylonMesh.id,
  114. isDirectional = false,
  115. spatialSound = false,
  116. distanceModel = meshNode.MaxNode.GetStringProperty("babylonjs_sound_distancemodel", "linear"),
  117. maxDistance = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_maxdistance", 100f),
  118. rolloffFactor = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_rolloff", 1.0f),
  119. refDistance = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_refdistance", 1.0f),
  120. };
  121. var isDirectional = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_directional");
  122. if (isDirectional)
  123. {
  124. meshSound.isDirectional = true;
  125. meshSound.coneInnerAngle = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneinnerangle", 360f);
  126. meshSound.coneOuterAngle = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneouterangle", 360f);
  127. meshSound.coneOuterGain = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneoutergain", 1.0f);
  128. }
  129. babylonScene.SoundsList.Add(meshSound);
  130. try
  131. {
  132. File.Copy(soundName, Path.Combine(babylonScene.OutputPath, filename), true);
  133. }
  134. catch
  135. {
  136. }
  137. }
  138. // Misc.
  139. #if MAX2017
  140. babylonMesh.isVisible = meshNode.MaxNode.Renderable;
  141. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows;
  142. babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics;
  143. #else
  144. babylonMesh.isVisible = meshNode.MaxNode.Renderable == 1;
  145. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
  146. babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;
  147. #endif
  148. babylonMesh.pickable = meshNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
  149. babylonMesh.showBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
  150. babylonMesh.showSubMeshesBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  151. babylonMesh.alphaIndex = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000);
  152. // Actions
  153. babylonMesh.actions = ExportNodeAction(meshNode);
  154. // Collisions
  155. babylonMesh.checkCollisions = meshNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
  156. var isSkinned = gameMesh.IsObjectSkinned;
  157. var skin = gameMesh.IGameSkin;
  158. var unskinnedMesh = gameMesh;
  159. IGMatrix skinInitPoseMatrix = Loader.Global.GMatrix.Create(Loader.Global.Matrix3.Create(true));
  160. List<int> boneIds = null;
  161. int maxNbBones = 0;
  162. if (isSkinned)
  163. {
  164. bonesCount = skin.TotalSkinBoneCount;
  165. skins.Add(skin);
  166. skinnedNodes.Add(meshNode);
  167. babylonMesh.skeletonId = skins.IndexOf(skin);
  168. skin.GetInitSkinTM(skinInitPoseMatrix);
  169. boneIds = SortBones(skin);
  170. skinSortedBones[skin] = boneIds;
  171. }
  172. // Mesh
  173. if (unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
  174. {
  175. if (unskinnedMesh.NumberOfFaces < 1)
  176. {
  177. RaiseError($"Mesh {babylonMesh.name} has no face", 2);
  178. }
  179. if (unskinnedMesh.NumberOfVerts < 3)
  180. {
  181. RaiseError($"Mesh {babylonMesh.name} has not enough vertices", 2);
  182. }
  183. if (unskinnedMesh.NumberOfVerts >= 65536)
  184. {
  185. RaiseWarning($"Mesh {babylonMesh.name} 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.", 2);
  186. }
  187. if (skin != null)
  188. {
  189. for (var vertexIndex = 0; vertexIndex < unskinnedMesh.NumberOfVerts; vertexIndex++)
  190. {
  191. maxNbBones = Math.Max(maxNbBones, skin.GetNumberOfBones(vertexIndex));
  192. }
  193. }
  194. // Physics
  195. var impostorText = meshNode.MaxNode.GetStringProperty("babylonjs_impostor", "None");
  196. if (impostorText != "None")
  197. {
  198. switch (impostorText)
  199. {
  200. case "Sphere":
  201. babylonMesh.physicsImpostor = 1;
  202. break;
  203. case "Box":
  204. babylonMesh.physicsImpostor = 2;
  205. break;
  206. case "Plane":
  207. babylonMesh.physicsImpostor = 3;
  208. break;
  209. default:
  210. babylonMesh.physicsImpostor = 0;
  211. break;
  212. }
  213. babylonMesh.physicsMass = meshNode.MaxNode.GetFloatProperty("babylonjs_mass");
  214. babylonMesh.physicsFriction = meshNode.MaxNode.GetFloatProperty("babylonjs_friction", 0.2f);
  215. babylonMesh.physicsRestitution = meshNode.MaxNode.GetFloatProperty("babylonjs_restitution", 0.2f);
  216. }
  217. // Material
  218. var mtl = meshNode.NodeMaterial;
  219. var multiMatsCount = 1;
  220. if (mtl != null)
  221. {
  222. babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
  223. if (!referencedMaterials.Contains(mtl))
  224. {
  225. referencedMaterials.Add(mtl);
  226. }
  227. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  228. }
  229. babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
  230. var vertices = new List<GlobalVertex>();
  231. var indices = new List<int>();
  232. var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
  233. bool hasUV = false;
  234. bool hasUV2 = false;
  235. for (int i = 0; i < mappingChannels.Count; ++i)
  236. {
  237. #if MAX2017
  238. var indexer = i;
  239. #else
  240. var indexer = new IntPtr(i);
  241. #endif
  242. var channelNum = mappingChannels[indexer];
  243. if (channelNum == 1)
  244. {
  245. hasUV = true;
  246. }
  247. else if (channelNum == 2)
  248. {
  249. hasUV2 = true;
  250. }
  251. }
  252. var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
  253. var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
  254. var optimizeVertices = meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
  255. // Compute normals
  256. var subMeshes = new List<BabylonSubMesh>();
  257. ExtractGeometry(vertices, indices, subMeshes, boneIds, skin, unskinnedMesh, hasUV, hasUV2, hasColor, hasAlpha, optimizeVertices, multiMatsCount, meshNode);
  258. if (vertices.Count >= 65536)
  259. {
  260. RaiseWarning($"Mesh {babylonMesh.name} has {vertices.Count} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", 2);
  261. if (!optimizeVertices)
  262. {
  263. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  264. }
  265. }
  266. RaiseMessage($"{vertices.Count} vertices, {indices.Count/3} faces", 2);
  267. // Buffers
  268. babylonMesh.positions = vertices.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  269. babylonMesh.normals = vertices.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  270. if (hasUV)
  271. {
  272. babylonMesh.uvs = vertices.SelectMany(v => new[] { v.UV.X, 1 - v.UV.Y }).ToArray();
  273. }
  274. if (hasUV2)
  275. {
  276. babylonMesh.uvs2 = vertices.SelectMany(v => new[] { v.UV2.X, 1 - v.UV2.Y }).ToArray();
  277. }
  278. if (skin != null)
  279. {
  280. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  281. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  282. babylonMesh.numBoneInfluencers = maxNbBones;
  283. if (maxNbBones > 4)
  284. {
  285. babylonMesh.matricesWeightsExtra = vertices.SelectMany(v => v.WeightsExtra != null ? v.WeightsExtra.ToArray() : new[] {0.0f, 0.0f, 0.0f, 0.0f }).ToArray();
  286. babylonMesh.matricesIndicesExtra = vertices.Select(v => v.BonesIndicesExtra).ToArray();
  287. }
  288. }
  289. if (hasColor)
  290. {
  291. babylonMesh.colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
  292. babylonMesh.hasVertexAlpha = hasAlpha;
  293. }
  294. babylonMesh.subMeshes = subMeshes.ToArray();
  295. // Buffers - Indices
  296. babylonMesh.indices = indices.ToArray();
  297. // ------------------------
  298. // ---- Morph targets -----
  299. // ------------------------
  300. // Retreive modifiers with morpher flag
  301. List<IIGameModifier> modifiers = new List<IIGameModifier>();
  302. for (int i = 0; i < meshNode.IGameObject.NumModifiers; i++)
  303. {
  304. var modifier = meshNode.IGameObject.GetIGameModifier(i);
  305. if (modifier.ModifierType == Autodesk.Max.IGameModifier.ModType.Morpher)
  306. {
  307. modifiers.Add(modifier);
  308. }
  309. }
  310. // Cast modifiers to morphers
  311. List<IIGameMorpher> morphers = modifiers.ConvertAll(new Converter<IIGameModifier, IIGameMorpher>(modifier => modifier.AsGameMorpher()));
  312. var hasMorphTarget = false;
  313. morphers.ForEach(morpher =>
  314. {
  315. if (morpher.NumberOfMorphTargets > 0)
  316. {
  317. hasMorphTarget = true;
  318. }
  319. });
  320. if (hasMorphTarget)
  321. {
  322. RaiseMessage("Export morph targets", 2);
  323. // Morph Target Manager
  324. var babylonMorphTargetManager = new BabylonMorphTargetManager();
  325. babylonScene.MorphTargetManagersList.Add(babylonMorphTargetManager);
  326. babylonMesh.morphTargetManagerId = babylonMorphTargetManager.id;
  327. // Morph Targets
  328. var babylonMorphTargets = new List<BabylonMorphTarget>();
  329. // All morphers are considered identical
  330. // Their targets are concatenated
  331. morphers.ForEach(morpher =>
  332. {
  333. for (int i = 0; i < morpher.NumberOfMorphTargets; i++)
  334. {
  335. // Morph target
  336. var maxMorphTarget = morpher.GetMorphTarget(i);
  337. var babylonMorphTarget = new BabylonMorphTarget
  338. {
  339. name = maxMorphTarget.Name
  340. };
  341. babylonMorphTargets.Add(babylonMorphTarget);
  342. // TODO - Influence
  343. babylonMorphTarget.influence = 0f;
  344. // Target geometry
  345. var targetVertices = ExtractVertices(maxMorphTarget, optimizeVertices);
  346. babylonMorphTarget.positions = targetVertices.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  347. babylonMorphTarget.normals = targetVertices.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  348. // Animations
  349. var animations = new List<BabylonAnimation>();
  350. var morphWeight = morpher.GetMorphWeight(i);
  351. ExportFloatGameController(morphWeight, "influence", animations);
  352. if (animations.Count > 0)
  353. {
  354. babylonMorphTarget.animations = animations.ToArray();
  355. }
  356. }
  357. });
  358. babylonMorphTargetManager.targets = babylonMorphTargets.ToArray();
  359. }
  360. }
  361. babylonScene.MeshesList.Add(babylonMesh);
  362. return babylonMesh;
  363. }
  364. private List<GlobalVertex> ExtractVertices(IIGameNode maxMorphTarget, bool optimizeVertices)
  365. {
  366. var gameMesh = maxMorphTarget.IGameObject.AsGameMesh();
  367. bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
  368. // translated into a property because it has no parameters
  369. var mtl = maxMorphTarget.NodeMaterial;
  370. var multiMatsCount = 1;
  371. if (mtl != null)
  372. {
  373. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  374. }
  375. var vertices = new List<GlobalVertex>();
  376. ExtractGeometry(vertices, new List<int>(), new List<BabylonSubMesh>(), null, null, gameMesh, false, false, false, false, optimizeVertices, multiMatsCount, maxMorphTarget);
  377. return vertices;
  378. }
  379. private void ExtractGeometry(List<GlobalVertex> vertices, List<int> indices, List<BabylonSubMesh> subMeshes, List<int> boneIds, IIGameSkin skin, IIGameMesh unskinnedMesh, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, bool optimizeVertices, int multiMatsCount, IIGameNode meshNode)
  380. {
  381. List<GlobalVertex>[] verticesAlreadyExported = null;
  382. if (optimizeVertices)
  383. {
  384. verticesAlreadyExported = new List<GlobalVertex>[unskinnedMesh.NumberOfVerts];
  385. }
  386. var indexStart = 0;
  387. for (int i = 0; i < multiMatsCount; ++i)
  388. {
  389. int materialId = meshNode.NodeMaterial?.GetMaterialID(i) ?? 0;
  390. var indexCount = 0;
  391. var minVertexIndex = int.MaxValue;
  392. var maxVertexIndex = int.MinValue;
  393. var subMesh = new BabylonSubMesh { indexStart = indexStart, materialIndex = i };
  394. if (multiMatsCount == 1)
  395. {
  396. for (int j = 0; j < unskinnedMesh.NumberOfFaces; ++j)
  397. {
  398. var face = unskinnedMesh.GetFace(j);
  399. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  400. }
  401. }
  402. else
  403. {
  404. ITab<IFaceEx> materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
  405. for (int j = 0; j < materialFaces.Count; ++j)
  406. {
  407. #if MAX2017
  408. var faceIndexer = j;
  409. #else
  410. var faceIndexer = new IntPtr(j);
  411. #endif
  412. var face = materialFaces[faceIndexer];
  413. #if !MAX2017
  414. Marshal.FreeHGlobal(faceIndexer);
  415. #endif
  416. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  417. }
  418. }
  419. if (indexCount != 0)
  420. {
  421. subMesh.indexCount = indexCount;
  422. subMesh.verticesStart = minVertexIndex;
  423. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  424. indexStart += indexCount;
  425. subMeshes.Add(subMesh);
  426. }
  427. }
  428. }
  429. 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)
  430. {
  431. var a = CreateGlobalVertex(unskinnedMesh, face, 0, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  432. var b = CreateGlobalVertex(unskinnedMesh, face, 2, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  433. var c = CreateGlobalVertex(unskinnedMesh, face, 1, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  434. indices.Add(a);
  435. indices.Add(b);
  436. indices.Add(c);
  437. if (a < minVertexIndex)
  438. {
  439. minVertexIndex = a;
  440. }
  441. if (b < minVertexIndex)
  442. {
  443. minVertexIndex = b;
  444. }
  445. if (c < minVertexIndex)
  446. {
  447. minVertexIndex = c;
  448. }
  449. if (a > maxVertexIndex)
  450. {
  451. maxVertexIndex = a;
  452. }
  453. if (b > maxVertexIndex)
  454. {
  455. maxVertexIndex = b;
  456. }
  457. if (c > maxVertexIndex)
  458. {
  459. maxVertexIndex = c;
  460. }
  461. indexCount += 3;
  462. CheckCancelled();
  463. }
  464. List<int> SortBones(IIGameSkin skin)
  465. {
  466. var boneIds = new List<int>();
  467. var boneIndex = new Dictionary<int, IIGameNode>();
  468. for (var index = 0; index < skin.TotalSkinBoneCount; index++)
  469. {
  470. var bone = skin.GetIGameBone(index, false);
  471. if (bone == null)
  472. {
  473. // non bone in skeletton
  474. boneIds.Add(-2);
  475. }
  476. else
  477. {
  478. boneIds.Add(bone.NodeID);
  479. boneIndex[bone.NodeID] = bone;
  480. }
  481. }
  482. while (true)
  483. {
  484. bool foundMisMatch = false;
  485. for (int i = 0; i < boneIds.Count; ++i)
  486. {
  487. var id = boneIds[i];
  488. if (id == -2)
  489. {
  490. continue;
  491. }
  492. var parent = boneIndex[id].NodeParent;
  493. if (parent != null)
  494. {
  495. var parentId = parent.NodeID;
  496. if (boneIds.IndexOf(parentId) > i)
  497. {
  498. boneIds.RemoveAt(i);
  499. boneIds.Insert(boneIds.IndexOf(parentId) + 1, id);
  500. foundMisMatch = true;
  501. break;
  502. }
  503. }
  504. }
  505. if (!foundMisMatch)
  506. {
  507. break;
  508. }
  509. }
  510. return boneIds;
  511. }
  512. 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)
  513. {
  514. var vertexIndex = (int)face.Vert[facePart];
  515. var vertex = new GlobalVertex
  516. {
  517. BaseIndex = vertexIndex,
  518. Position = mesh.GetVertex(vertexIndex, true),
  519. Normal = mesh.GetNormal((int)face.Norm[facePart], true)
  520. };
  521. if (hasUV)
  522. {
  523. var indices = new int[3];
  524. unsafe
  525. {
  526. fixed (int* indicesPtr = indices)
  527. {
  528. mesh.GetMapFaceIndex(1, face.MeshFaceIndex, new IntPtr(indicesPtr));
  529. }
  530. }
  531. var texCoord = mesh.GetMapVertex(1, indices[facePart]);
  532. vertex.UV = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  533. }
  534. if (hasUV2)
  535. {
  536. var indices = new int[3];
  537. unsafe
  538. {
  539. fixed (int* indicesPtr = indices)
  540. {
  541. mesh.GetMapFaceIndex(2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  542. }
  543. }
  544. var texCoord = mesh.GetMapVertex(2, indices[facePart]);
  545. vertex.UV2 = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  546. }
  547. if (hasColor)
  548. {
  549. var vertexColorIndex = (int)face.Color[facePart];
  550. var vertexColor = mesh.GetColorVertex(vertexColorIndex);
  551. float alpha = 1;
  552. if (hasAlpha)
  553. {
  554. var indices = new int[3];
  555. unsafe
  556. {
  557. fixed (int* indicesPtr = indices)
  558. {
  559. mesh.GetMapFaceIndex(-2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  560. }
  561. }
  562. var color = mesh.GetMapVertex(-2, indices[facePart]);
  563. alpha = color.X;
  564. }
  565. vertex.Color = new[] { vertexColor.X, vertexColor.Y, vertexColor.Z, alpha };
  566. }
  567. if (skin != null)
  568. {
  569. float weight0 = 0;
  570. float weight1 = 0;
  571. float weight2 = 0;
  572. float weight3 = 0;
  573. int bone0 = bonesCount;
  574. int bone1 = bonesCount;
  575. int bone2 = bonesCount;
  576. int bone3 = bonesCount;
  577. var nbBones = skin.GetNumberOfBones(vertexIndex);
  578. if (nbBones > 0)
  579. {
  580. bone0 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 0).NodeID);
  581. weight0 = skin.GetWeight(vertexIndex, 0);
  582. }
  583. if (nbBones > 1)
  584. {
  585. bone1 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 1).NodeID);
  586. weight1 = skin.GetWeight(vertexIndex, 1);
  587. }
  588. if (nbBones > 2)
  589. {
  590. bone2 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 2).NodeID);
  591. weight2 = skin.GetWeight(vertexIndex, 2);
  592. }
  593. if (nbBones > 3)
  594. {
  595. bone3 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 3).NodeID);
  596. weight3 = skin.GetWeight(vertexIndex, 3);
  597. }
  598. if (nbBones == 0)
  599. {
  600. weight0 = 1.0f;
  601. bone0 = bonesCount;
  602. }
  603. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, weight3);
  604. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  605. if (nbBones > 4)
  606. {
  607. bone0 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 4).NodeID);
  608. weight0 = skin.GetWeight(vertexIndex, 4);
  609. weight1 = 0;
  610. weight2 = 0;
  611. weight3 = 0;
  612. if (nbBones > 5)
  613. {
  614. bone1 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 5).NodeID);
  615. weight1 = skin.GetWeight(vertexIndex, 5);
  616. }
  617. if (nbBones > 6)
  618. {
  619. bone2 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 6).NodeID);
  620. weight2 = skin.GetWeight(vertexIndex, 6);
  621. }
  622. if (nbBones > 7)
  623. {
  624. bone3 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 7).NodeID);
  625. weight3 = skin.GetWeight(vertexIndex, 7);
  626. }
  627. vertex.WeightsExtra = Loader.Global.Point4.Create(weight0, weight1, weight2, weight3);
  628. vertex.BonesIndicesExtra = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  629. if (nbBones > 8)
  630. {
  631. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 8 bones influences per vertex.", 2);
  632. }
  633. }
  634. }
  635. if (verticesAlreadyExported != null)
  636. {
  637. if (verticesAlreadyExported[vertexIndex] != null)
  638. {
  639. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  640. if (index > -1)
  641. {
  642. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  643. }
  644. }
  645. else
  646. {
  647. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  648. }
  649. vertex.CurrentIndex = vertices.Count;
  650. verticesAlreadyExported[vertexIndex].Add(vertex);
  651. }
  652. vertices.Add(vertex);
  653. return vertices.Count - 1;
  654. }
  655. private void exportNode(BabylonAbstractMesh babylonAbstractMesh, IIGameNode maxGameNode, IIGameScene maxGameScene, BabylonScene babylonScene)
  656. {
  657. // Position / rotation / scaling
  658. exportTransform(babylonAbstractMesh, maxGameNode);
  659. // Hierarchy
  660. if (maxGameNode.NodeParent != null)
  661. {
  662. babylonAbstractMesh.parentId = maxGameNode.NodeParent.MaxNode.GetGuid().ToString();
  663. }
  664. }
  665. private void exportTransform(BabylonAbstractMesh babylonAbstractMesh, IIGameNode maxGameNode)
  666. {
  667. // Position / rotation / scaling
  668. var localTM = maxGameNode.GetObjectTM(0);
  669. if (maxGameNode.NodeParent != null)
  670. {
  671. var parentWorld = maxGameNode.NodeParent.GetObjectTM(0);
  672. localTM.MultiplyBy(parentWorld.Inverse);
  673. }
  674. var meshTrans = localTM.Translation;
  675. var meshRotation = localTM.Rotation;
  676. var meshScale = localTM.Scaling;
  677. babylonAbstractMesh.position = new[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  678. var rotationQuaternion = new BabylonQuaternion { X = meshRotation.X, Y = meshRotation.Y, Z = meshRotation.Z, W = -meshRotation.W };
  679. if (ExportQuaternionsInsteadOfEulers)
  680. {
  681. babylonAbstractMesh.rotationQuaternion = rotationQuaternion.ToArray();
  682. }
  683. else
  684. {
  685. babylonAbstractMesh.rotation = rotationQuaternion.toEulerAngles().ToArray();
  686. }
  687. babylonAbstractMesh.scaling = new[] { meshScale.X, meshScale.Y, meshScale.Z };
  688. }
  689. private void exportAnimation(BabylonNode babylonNode, IIGameNode maxGameNode)
  690. {
  691. var animations = new List<BabylonAnimation>();
  692. GenerateCoordinatesAnimations(maxGameNode, animations);
  693. if (!ExportFloatController(maxGameNode.MaxNode.VisController, "visibility", animations))
  694. {
  695. ExportFloatAnimation("visibility", animations, key => new[] { maxGameNode.MaxNode.GetVisibility(key, Tools.Forever) });
  696. }
  697. babylonNode.animations = animations.ToArray();
  698. if (maxGameNode.MaxNode.GetBoolProperty("babylonjs_autoanimate", 1))
  699. {
  700. babylonNode.autoAnimate = true;
  701. babylonNode.autoAnimateFrom = (int)maxGameNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_from");
  702. babylonNode.autoAnimateTo = (int)maxGameNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  703. babylonNode.autoAnimateLoop = maxGameNode.MaxNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  704. }
  705. }
  706. public void GenerateCoordinatesAnimations(IIGameNode meshNode, List<BabylonAnimation> animations)
  707. {
  708. if (meshNode.IGameControl.IsAnimated(IGameControlType.Pos) ||
  709. meshNode.IGameControl.IsAnimated(IGameControlType.PosX) ||
  710. meshNode.IGameControl.IsAnimated(IGameControlType.PosY) ||
  711. meshNode.IGameControl.IsAnimated(IGameControlType.PosZ))
  712. {
  713. ExportVector3Animation("position", animations, key =>
  714. {
  715. var worldMatrix = meshNode.GetObjectTM(key);
  716. if (meshNode.NodeParent != null)
  717. {
  718. var parentWorld = meshNode.NodeParent.GetObjectTM(key);
  719. worldMatrix.MultiplyBy(parentWorld.Inverse);
  720. }
  721. var trans = worldMatrix.Translation;
  722. return new[] { trans.X, trans.Y, trans.Z };
  723. });
  724. }
  725. if (meshNode.IGameControl.IsAnimated(IGameControlType.Rot) ||
  726. meshNode.IGameControl.IsAnimated(IGameControlType.EulerX) ||
  727. meshNode.IGameControl.IsAnimated(IGameControlType.EulerY) ||
  728. meshNode.IGameControl.IsAnimated(IGameControlType.EulerZ))
  729. {
  730. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  731. {
  732. var worldMatrix = meshNode.GetObjectTM(key);
  733. if (meshNode.NodeParent != null)
  734. {
  735. var parentWorld = meshNode.NodeParent.GetObjectTM(key);
  736. worldMatrix.MultiplyBy(parentWorld.Inverse);
  737. }
  738. var rot = worldMatrix.Rotation;
  739. return new[] { rot.X, rot.Y, rot.Z, -rot.W };
  740. });
  741. }
  742. if (meshNode.IGameControl.IsAnimated(IGameControlType.Scale))
  743. {
  744. ExportVector3Animation("scaling", animations, key =>
  745. {
  746. var worldMatrix = meshNode.GetObjectTM(key);
  747. if (meshNode.NodeParent != null)
  748. {
  749. var parentWorld = meshNode.NodeParent.GetObjectTM(key);
  750. worldMatrix.MultiplyBy(parentWorld.Inverse);
  751. }
  752. var scale = worldMatrix.Scaling;
  753. return new[] { scale.X, scale.Y, scale.Z };
  754. });
  755. }
  756. }
  757. }
  758. }