BabylonExporter.cs 11 KB

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