123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.IO;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using Autodesk.Max;
- using BabylonExport.Entities;
- using Newtonsoft.Json;
- using Color = System.Drawing.Color;
- using System.Runtime.InteropServices;
- namespace Max2Babylon
- {
- internal partial class BabylonExporter
- {
- public event Action<int> OnImportProgressChanged;
- public event Action<string, int> OnWarning;
- public event Action<string, Color, int, bool> OnMessage;
- public event Action<string, int> OnError;
- public bool AutoSave3dsMaxFile { get; set; }
- public bool ExportHiddenObjects { get; set; }
- public bool IsCancelled { get; set; }
- public bool CopyTexturesToOutput { get; set; }
- public string MaxSceneFileName { get; set; }
- public bool ExportQuaternionsInsteadOfEulers { get; set; }
- void ReportProgressChanged(int progress)
- {
- if (OnImportProgressChanged != null)
- {
- OnImportProgressChanged(progress);
- }
- }
- void RaiseError(string error, int rank = 0)
- {
- if (OnError != null)
- {
- OnError(error, rank);
- }
- }
- void RaiseWarning(string warning, int rank = 0)
- {
- if (OnWarning != null)
- {
- OnWarning(warning, rank);
- }
- }
- void RaiseMessage(string message, int rank = 0, bool emphasis = false)
- {
- RaiseMessage(message, Color.Black, rank, emphasis);
- }
- void RaiseMessage(string message, Color color, int rank = 0, bool emphasis = false)
- {
- if (OnMessage != null)
- {
- OnMessage(message, color, rank, emphasis);
- }
- }
- void CheckCancelled()
- {
- Application.DoEvents();
- if (IsCancelled)
- {
- throw new OperationCanceledException();
- }
- }
- public async Task ExportAsync(string outputFile, bool generateManifest, bool onlySelected, bool generateBinary, Form callerForm)
- {
- var gameConversionManger = Loader.Global.ConversionManager;
- gameConversionManger.CoordSystem = Autodesk.Max.IGameConversionManager.CoordSystem.D3d;
- var gameScene = Loader.Global.IGameInterface;
- gameScene.InitialiseIGame(onlySelected);
- gameScene.SetStaticFrame(0);
- MaxSceneFileName = gameScene.SceneFileName;
- IsCancelled = false;
- RaiseMessage("Exportation started", Color.Blue);
- ReportProgressChanged(0);
- var babylonScene = new BabylonScene(Path.GetDirectoryName(outputFile));
- var rawScene = Loader.Core.RootNode;
- if (!Directory.Exists(babylonScene.OutputPath))
- {
- RaiseError("Exportation stopped: Output folder does not exist");
- ReportProgressChanged(100);
- return;
- }
- var watch = new Stopwatch();
- watch.Start();
- // Save scene
- RaiseMessage("Saving 3ds max file");
- if (AutoSave3dsMaxFile)
- {
- var forceSave = Loader.Core.FileSave;
- callerForm?.BringToFront();
- }
- // Producer
- babylonScene.producer = new BabylonProducer
- {
- name = "3dsmax",
- #if MAX2017
- version = "2017",
- #else
- version = Loader.Core.ProductVersion.ToString(),
- #endif
- exporter_version = "0.4.5",
- file = Path.GetFileName(outputFile)
- };
- // Global
- babylonScene.autoClear = true;
- babylonScene.clearColor = Loader.Core.GetBackGround(0, Tools.Forever).ToArray();
- babylonScene.ambientColor = Loader.Core.GetAmbient(0, Tools.Forever).ToArray();
- babylonScene.gravity = rawScene.GetVector3Property("babylonjs_gravity");
- ExportQuaternionsInsteadOfEulers = rawScene.GetBoolProperty("babylonjs_exportquaternions", 1);
- // Sounds
- var soundName = rawScene.GetStringProperty("babylonjs_sound_filename", "");
- if (!string.IsNullOrEmpty(soundName))
- {
- var filename = Path.GetFileName(soundName);
- var globalSound = new BabylonSound
- {
- autoplay = rawScene.GetBoolProperty("babylonjs_sound_autoplay", 1),
- loop = rawScene.GetBoolProperty("babylonjs_sound_loop", 1),
- name = filename
- };
- babylonScene.SoundsList.Add(globalSound);
- try
- {
- File.Copy(soundName, Path.Combine(babylonScene.OutputPath, filename), true);
- }
- catch
- {
- }
- }
- // Cameras
- BabylonCamera mainCamera = null;
- ICameraObject mainCameraNode = null;
- RaiseMessage("Exporting cameras");
- var camerasTab = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Camera);
- for (int ix = 0; ix < camerasTab.Count; ++ix)
- {
- #if MAX2017
- var indexer = ix;
- #else
- var indexer = new IntPtr(ix);
- #endif
- var cameraNode = camerasTab[indexer];
- #if !MAX2017
- Marshal.FreeHGlobal(indexer);
- #endif
-
- ExportCamera(gameScene, cameraNode, babylonScene);
- if (mainCamera == null && babylonScene.CamerasList.Count > 0)
- {
- mainCameraNode = (cameraNode.MaxNode.ObjectRef as ICameraObject);
- mainCamera = babylonScene.CamerasList[0];
- babylonScene.activeCameraID = mainCamera.id;
- RaiseMessage("Active camera set to " + mainCamera.name, Color.Green, 1, true);
- }
- }
- if (mainCamera == null)
- {
- RaiseWarning("No camera defined", 1);
- }
- else
- {
- RaiseMessage(string.Format("Total: {0}", babylonScene.CamerasList.Count), Color.Gray, 1);
- }
- // Fog
- for (var index = 0; index < Loader.Core.NumAtmospheric; index++)
- {
- var atmospheric = Loader.Core.GetAtmospheric(index);
- if (atmospheric.Active(0) && atmospheric.ClassName == "Fog")
- {
- var fog = atmospheric as IStdFog;
- RaiseMessage("Exporting fog");
- if (fog != null)
- {
- babylonScene.fogColor = fog.GetColor(0).ToArray();
- babylonScene.fogMode = 3;
- }
- #if !MAX2015 && !MAX2016 && !MAX2017
- else
- {
- var paramBlock = atmospheric.GetReference(0) as IIParamBlock;
- babylonScene.fogColor = Tools.GetParamBlockValueColor(paramBlock, "Fog Color");
- babylonScene.fogMode = 3;
- }
- #endif
- if (mainCamera != null)
- {
- babylonScene.fogStart = mainCameraNode.GetEnvRange(0, 0, Tools.Forever);
- babylonScene.fogEnd = mainCameraNode.GetEnvRange(0, 1, Tools.Forever);
- }
- }
- }
- // Meshes
- ReportProgressChanged(10);
- RaiseMessage("Exporting meshes");
- var meshes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Mesh);
- var progressionStep = 80.0f / meshes.Count;
- var progression = 10.0f;
- for (int ix = 0; ix < meshes.Count; ++ix)
- {
- #if MAX2017
- var indexer = ix;
- #else
- var indexer = new IntPtr(ix);
- #endif
- var meshNode = meshes[indexer];
- #if !MAX2017
- Marshal.FreeHGlobal(indexer);
- #endif
- ExportMesh(gameScene, meshNode, babylonScene);
- ReportProgressChanged((int)progression);
- progression += progressionStep;
- CheckCancelled();
- }
- // Materials
- RaiseMessage("Exporting materials");
- var matsToExport = referencedMaterials.ToArray(); // Snapshot because multimaterials can export new materials
- foreach (var mat in matsToExport)
- {
- ExportMaterial(mat, babylonScene);
- CheckCancelled();
- }
- RaiseMessage(string.Format("Total: {0}", babylonScene.MaterialsList.Count + babylonScene.MultiMaterialsList.Count), Color.Gray, 1);
- // Lights
- RaiseMessage("Exporting lights");
- var lightNodes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Light);
- for (var i = 0; i < lightNodes.Count; ++i)
- {
- #if MAX2017
- ExportLight(gameScene, lightNodes[i], babylonScene);
- #else
- ExportLight(gameScene, lightNodes[new IntPtr(i)], babylonScene);
- #endif
- CheckCancelled();
- }
- if (babylonScene.LightsList.Count == 0)
- {
- RaiseWarning("No light defined", 1);
- RaiseWarning("A default hemispheric light was added for your convenience", 1);
- ExportDefaultLight(babylonScene);
- }
- else
- {
- RaiseMessage(string.Format("Total: {0}", babylonScene.LightsList.Count), Color.Gray, 1);
- }
- // Skeletons
- if (skins.Count > 0)
- {
- RaiseMessage("Exporting skeletons");
- foreach (var skin in skins)
- {
- ExportSkin(skin, babylonScene);
- }
- }
- // Actions
- babylonScene.actions = ExportNodeAction(gameScene.GetIGameNode(rawScene));
- // Output
- RaiseMessage("Saving to output file");
- babylonScene.Prepare(false);
- var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings());
- var sb = new StringBuilder();
- var sw = new StringWriter(sb, CultureInfo.InvariantCulture);
- await Task.Run(() =>
- {
- using (var jsonWriter = new JsonTextWriterOptimized(sw))
- {
- jsonWriter.Formatting = Formatting.None;
- jsonSerializer.Serialize(jsonWriter, babylonScene);
- }
- File.WriteAllText(outputFile, sb.ToString());
- if (generateManifest)
- {
- File.WriteAllText(outputFile + ".manifest",
- "{\r\n\"version\" : 1,\r\n\"enableSceneOffline\" : true,\r\n\"enableTexturesOffline\" : true\r\n}");
- }
- });
- // Binary
- if (generateBinary)
- {
- RaiseMessage("Generating binary files");
- BabylonFileConverter.BinaryConverter.Convert(outputFile, Path.GetDirectoryName(outputFile) + "\\Binary",
- message => RaiseMessage(message, 1),
- error => RaiseError(error, 1));
- }
- ReportProgressChanged(100);
- watch.Stop();
- RaiseMessage(string.Format("Exportation done in {0:0.00}s", watch.ElapsedMilliseconds / 1000.0), Color.Blue);
- }
- }
- }
|