BabylonExporter.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. using Autodesk.Max;
  10. using BabylonExport.Entities;
  11. using Newtonsoft.Json;
  12. using Color = System.Drawing.Color;
  13. using System.Runtime.InteropServices;
  14. namespace Max2Babylon
  15. {
  16. internal partial class BabylonExporter
  17. {
  18. public event Action<int> OnImportProgressChanged;
  19. public event Action<string, int> OnWarning;
  20. public event Action<string, Color, int, bool> OnMessage;
  21. public event Action<string, int> OnError;
  22. readonly List<string> alreadyExportedTextures = new List<string>();
  23. public bool AutoSave3dsMaxFile { get; set; }
  24. public bool ExportHiddenObjects { get; set; }
  25. public bool IsCancelled { get; set; }
  26. public bool CopyTexturesToOutput { get; set; }
  27. public string MaxSceneFileName { get; set; }
  28. public bool ExportQuaternionsInsteadOfEulers { get; set; }
  29. void ReportProgressChanged(int progress)
  30. {
  31. if (OnImportProgressChanged != null)
  32. {
  33. OnImportProgressChanged(progress);
  34. }
  35. }
  36. void RaiseError(string error, int rank = 0)
  37. {
  38. if (OnError != null)
  39. {
  40. OnError(error, rank);
  41. }
  42. }
  43. void RaiseWarning(string warning, int rank = 0)
  44. {
  45. if (OnWarning != null)
  46. {
  47. OnWarning(warning, rank);
  48. }
  49. }
  50. void RaiseMessage(string message, int rank = 0, bool emphasis = false)
  51. {
  52. RaiseMessage(message, Color.Black, rank, emphasis);
  53. }
  54. void RaiseMessage(string message, Color color, int rank = 0, bool emphasis = false)
  55. {
  56. if (OnMessage != null)
  57. {
  58. OnMessage(message, color, rank, emphasis);
  59. }
  60. }
  61. void CheckCancelled()
  62. {
  63. Application.DoEvents();
  64. if (IsCancelled)
  65. {
  66. throw new OperationCanceledException();
  67. }
  68. }
  69. public async Task ExportAsync(string outputFile, bool generateManifest, bool onlySelected, bool generateBinary, Form callerForm)
  70. {
  71. var gameConversionManger = Loader.Global.ConversionManager;
  72. gameConversionManger.CoordSystem = Autodesk.Max.IGameConversionManager.CoordSystem.D3d;
  73. var gameScene = Loader.Global.IGameInterface;
  74. gameScene.InitialiseIGame(onlySelected);
  75. gameScene.SetStaticFrame(0);
  76. MaxSceneFileName = gameScene.SceneFileName;
  77. IsCancelled = false;
  78. RaiseMessage("Exportation started", Color.Blue);
  79. ReportProgressChanged(0);
  80. var babylonScene = new BabylonScene(Path.GetDirectoryName(outputFile));
  81. var rawScene = Loader.Core.RootNode;
  82. alreadyExportedTextures.Clear();
  83. if (!Directory.Exists(babylonScene.OutputPath))
  84. {
  85. RaiseError("Exportation stopped: Output folder does not exist");
  86. ReportProgressChanged(100);
  87. return;
  88. }
  89. var watch = new Stopwatch();
  90. watch.Start();
  91. // Save scene
  92. RaiseMessage("Saving 3ds max file");
  93. if (AutoSave3dsMaxFile)
  94. {
  95. if (callerForm != null)
  96. {
  97. callerForm.BringToFront();
  98. }
  99. }
  100. // Global
  101. babylonScene.autoClear = true;
  102. babylonScene.clearColor = Loader.Core.GetBackGround(0, Tools.Forever).ToArray();
  103. babylonScene.ambientColor = Loader.Core.GetAmbient(0, Tools.Forever).ToArray();
  104. babylonScene.gravity = rawScene.GetVector3Property("babylonjs_gravity");
  105. ExportQuaternionsInsteadOfEulers = rawScene.GetBoolProperty("babylonjs_exportquaternions", 1);
  106. // Cameras
  107. BabylonCamera mainCamera = null;
  108. ICameraObject mainCameraNode = null;
  109. RaiseMessage("Exporting cameras");
  110. var camerasTab = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Camera);
  111. for (int ix = 0; ix < camerasTab.Count; ++ix)
  112. {
  113. var indexer = new IntPtr(ix);
  114. var cameraNode = camerasTab[indexer];
  115. Marshal.FreeHGlobal(indexer);
  116. ExportCamera(gameScene, cameraNode, babylonScene);
  117. if (mainCamera == null && babylonScene.CamerasList.Count > 0)
  118. {
  119. mainCameraNode = (cameraNode.MaxNode.ObjectRef as ICameraObject);
  120. mainCamera = babylonScene.CamerasList[0];
  121. babylonScene.activeCameraID = mainCamera.id;
  122. RaiseMessage("Active camera set to " + mainCamera.name, Color.Green, 1, true);
  123. }
  124. }
  125. if (mainCamera == null)
  126. {
  127. RaiseWarning("No camera defined", 1);
  128. }
  129. else
  130. {
  131. RaiseMessage(string.Format("Total: {0}", babylonScene.CamerasList.Count), Color.Gray, 1);
  132. }
  133. // Fog
  134. for (var index = 0; index < Loader.Core.NumAtmospheric; index++)
  135. {
  136. var atmospheric = Loader.Core.GetAtmospheric(index);
  137. if (atmospheric.Active(0) && atmospheric.ClassName == "Fog")
  138. {
  139. var fog = atmospheric as IStdFog;
  140. RaiseMessage("Exporting fog");
  141. if (fog != null)
  142. {
  143. babylonScene.fogColor = fog.GetColor(0).ToArray();
  144. babylonScene.fogMode = 3;
  145. }
  146. #if !MAX2015
  147. else
  148. {
  149. var paramBlock = atmospheric.GetReference(0) as IIParamBlock;
  150. babylonScene.fogColor = Tools.GetParamBlockValueColor(paramBlock, "Fog Color");
  151. babylonScene.fogMode = 3;
  152. }
  153. #endif
  154. if (mainCamera != null)
  155. {
  156. babylonScene.fogStart = mainCameraNode.GetEnvRange(0, 0, Tools.Forever);
  157. babylonScene.fogEnd = mainCameraNode.GetEnvRange(0, 1, Tools.Forever);
  158. }
  159. }
  160. }
  161. // Meshes
  162. ReportProgressChanged(10);
  163. RaiseMessage("Exporting meshes");
  164. var meshes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Mesh);
  165. var progressionStep = 80.0f / meshes.Count;
  166. var progression = 10.0f;
  167. for (int ix = 0; ix < meshes.Count; ++ix)
  168. {
  169. var indexer = new IntPtr(ix);
  170. var meshNode = meshes[indexer];
  171. Marshal.FreeHGlobal(indexer);
  172. ExportMesh(gameScene, meshNode, babylonScene);
  173. ReportProgressChanged((int)progression);
  174. progression += progressionStep;
  175. CheckCancelled();
  176. }
  177. // Materials
  178. RaiseMessage("Exporting materials");
  179. var matsToExport = referencedMaterials.ToArray(); // Snapshot because multimaterials can export new materials
  180. foreach (var mat in matsToExport)
  181. {
  182. ExportMaterial(mat, babylonScene);
  183. CheckCancelled();
  184. }
  185. RaiseMessage(string.Format("Total: {0}", babylonScene.MaterialsList.Count + babylonScene.MultiMaterialsList.Count), Color.Gray, 1);
  186. // Lights
  187. RaiseMessage("Exporting lights");
  188. var lightNodes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Light);
  189. for (var i = 0; i < lightNodes.Count; ++i)
  190. {
  191. ExportLight(gameScene, lightNodes[new IntPtr(i)], babylonScene);
  192. CheckCancelled();
  193. }
  194. if (babylonScene.LightsList.Count == 0)
  195. {
  196. RaiseWarning("No light defined", 1);
  197. RaiseWarning("A default hemispheric light was added for your convenience", 1);
  198. ExportDefaultLight(babylonScene);
  199. }
  200. else
  201. {
  202. RaiseMessage(string.Format("Total: {0}", babylonScene.LightsList.Count), Color.Gray, 1);
  203. }
  204. // Skeletons
  205. if (skins.Count > 0)
  206. {
  207. RaiseMessage("Exporting skeletons");
  208. foreach (var skin in skins)
  209. {
  210. ExportSkin(skin, babylonScene);
  211. }
  212. }
  213. // Output
  214. RaiseMessage("Saving to output file");
  215. babylonScene.Prepare(false);
  216. var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings());
  217. var sb = new StringBuilder();
  218. var sw = new StringWriter(sb, CultureInfo.InvariantCulture);
  219. await Task.Run(() =>
  220. {
  221. using (var jsonWriter = new JsonTextWriterOptimized(sw))
  222. {
  223. jsonWriter.Formatting = Formatting.None;
  224. jsonSerializer.Serialize(jsonWriter, babylonScene);
  225. }
  226. File.WriteAllText(outputFile, sb.ToString());
  227. if (generateManifest)
  228. {
  229. File.WriteAllText(outputFile + ".manifest",
  230. "{\r\n\"version\" : 1,\r\n\"enableSceneOffline\" : true,\r\n\"enableTexturesOffline\" : true\r\n}");
  231. }
  232. });
  233. // Binary
  234. if (generateBinary)
  235. {
  236. RaiseMessage("Generating binary files");
  237. BabylonFileConverter.BinaryConverter.Convert(outputFile, Path.GetDirectoryName(outputFile) + "\\Binary",
  238. message => RaiseMessage(message, 1),
  239. error => RaiseError(error, 1));
  240. }
  241. ReportProgressChanged(100);
  242. watch.Stop();
  243. RaiseMessage(string.Format("Exportation done in {0:0.00}s", watch.ElapsedMilliseconds / 1000.0), Color.Blue);
  244. }
  245. }
  246. }