BabylonExporter.Mesh.cs 32 KB

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