Пример #1
0
        private bool IsNodeExportable(IIGameNode gameNode)
        {
            if (exportParameters is MaxExportParameters)
            {
                MaxExportParameters maxExporterParameters = (exportParameters as MaxExportParameters);
                if (maxExporterParameters.exportLayers != null && maxExporterParameters.exportLayers.Count > 0)
                {
                    if (!maxExporterParameters.exportLayers.HaveNode(gameNode.MaxNode))
                    {
                        return(false);
                    }
                }
            }
            if (gameNode.MaxNode.GetBoolProperty("babylonjs_noexport"))
            {
                return(false);
            }

            if (exportParameters.exportOnlySelected && !gameNode.MaxNode.Selected)
            {
                return(false);
            }

            if (!exportParameters.exportHiddenObjects && gameNode.MaxNode.IsHidden(NodeHideFlags.None, false))
            {
                return(false);
            }

            return(true);
        }
Пример #2
0
        public async void butExport_Click(object sender, EventArgs e)
        {
            treeView.Nodes.Clear();
            exportParameters = GetExportParameters();

            PreExportProcess preExportProcess = new PreExportProcess(exportParameters, logger);
            bool             abort            = false;

            try
            {
                abort = AutosaveWarning();
                if (abort)
                {
                    return;
                }

                if (exportParameters.usePreExportProcess)
                {
                    Loader.Core.FileHold();
                    preExportProcess.ApplyPreExport();
                }
                await DoExport(singleExportItem);
            }
            catch (Exception ex)
            {
                logger.RaiseError(ex.Message);
            }
            finally
            {
                if (exportParameters.usePreExportProcess && !exportParameters.applyPreprocessToScene)
                {
                    ScriptsUtilities.ExecuteMaxScriptCommand("fetchMaxFile quiet:true");
                }
            }
        }
Пример #3
0
        //deprecated
        public static void Export(MaxExportParameters exportParameters, bool logInListener)
        {
            Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf("WARNING - This method is DEPRECATED use " + "\n" + "Export(MaxExportParameters exportParameters, BabylonLogger _logger)" + "\n");
            var logger = new MaxScriptLogger(logInListener);

            Export(exportParameters, logger);
        }
Пример #4
0
        //leave the possibility to do get the outputh path from the babylon exporter with all the settings as presaved
        public static MaxExportParameters InitParameters(string outputPath)
        {
            long  txtQuality  = 100;
            float scaleFactor = 1f;
            MaxExportParameters exportParameters = new MaxExportParameters();

            exportParameters.outputPath                = outputPath;
            exportParameters.outputFormat              = Path.GetExtension(outputPath)?.Substring(1);
            exportParameters.textureFolder             = Loader.Core.RootNode.GetStringProperty("textureFolderPathProperty", string.Empty);
            exportParameters.generateManifest          = Loader.Core.RootNode.GetBoolProperty("babylonjs_generatemanifest");
            exportParameters.writeTextures             = Loader.Core.RootNode.GetBoolProperty("babylonjs_writetextures");
            exportParameters.overwriteTextures         = Loader.Core.RootNode.GetBoolProperty("babylonjs_overwritetextures");
            exportParameters.exportHiddenObjects       = Loader.Core.RootNode.GetBoolProperty("babylonjs_exporthidden");
            exportParameters.autoSaveSceneFile         = Loader.Core.RootNode.GetBoolProperty("babylonjs_autosave");
            exportParameters.exportOnlySelected        = Loader.Core.RootNode.GetBoolProperty("babylonjs_onlySelected");
            exportParameters.exportTangents            = Loader.Core.RootNode.GetBoolProperty("babylonjs_exporttangents");
            exportParameters.scaleFactor               = float.TryParse(Loader.Core.RootNode.GetStringProperty("babylonjs_txtScaleFactor", "1"), out scaleFactor) ? scaleFactor : 1;
            exportParameters.txtQuality                = long.TryParse(Loader.Core.RootNode.GetStringProperty("babylonjs_txtCompression", "100"), out txtQuality) ? txtQuality : 100;
            exportParameters.mergeAOwithMR             = Loader.Core.RootNode.GetBoolProperty("babylonjs_mergeAOwithMR");
            exportParameters.dracoCompression          = Loader.Core.RootNode.GetBoolProperty("babylonjs_dracoCompression");
            exportParameters.enableKHRLightsPunctual   = Loader.Core.RootNode.GetBoolProperty("babylonjs_khrLightsPunctual");
            exportParameters.enableKHRTextureTransform = Loader.Core.RootNode.GetBoolProperty("babylonjs_khrTextureTransform");
            exportParameters.enableKHRMaterialsUnlit   = Loader.Core.RootNode.GetBoolProperty("babylonjs_khr_materials_unlit");
            exportParameters.exportMaterials           = Loader.Core.RootNode.GetBoolProperty("babylonjs_export_materials");
            exportParameters.usePreExportProcess       = Loader.Core.RootNode.GetBoolProperty("babylonjs_preproces");
            exportParameters.flattenScene              = Loader.Core.RootNode.GetBoolProperty("babylonjs_flattenScene");
            exportParameters.mergeContainersAndXRef    = Loader.Core.RootNode.GetBoolProperty("babylonjs_mergecontainersandxref");
            exportParameters.bakeAnimationType         = (BakeAnimationType)Loader.Core.RootNode.GetFloatProperty("babylonjs_bakeAnimationsType", 0);

            exportParameters.pbrFull        = Loader.Core.RootNode.GetBoolProperty(ExportParameters.PBRFullPropertyName);
            exportParameters.pbrNoLight     = Loader.Core.RootNode.GetBoolProperty(ExportParameters.PBRNoLightPropertyName);
            exportParameters.pbrEnvironment = Loader.Core.RootNode.GetStringProperty(ExportParameters.PBREnvironmentPathPropertyName, string.Empty);
            return(exportParameters);
        }
Пример #5
0
        private async void butMultiExport_Click(object sender, EventArgs e)
        {
            treeView.Nodes.Clear();
            string outputFileExt = comboOutputFormat.SelectedItem.ToString();

            if (outputFileExt.Contains("binary babylon"))
            {
                outputFileExt = "babylon";
            }

            ExportItemList exportItemList = new ExportItemList(outputFileExt);

            exportItemList.LoadFromData();

            int numLoadedItems = exportItemList.Count;

            if (ModifierKeys == Keys.Shift)
            {
                MultiExportForm form = new MultiExportForm(exportItemList);
                form.ShowDialog(this);
            }
            else if (numLoadedItems > 0)
            {
                exportParameters = GetExportParameters();
                PreExportProcess preExportProcess = new PreExportProcess(exportParameters, logger);
                if (logger != null)
                {
                    preExportProcess.logger = logger;
                }
                bool abort = false;
                try
                {
                    abort = AutosaveWarning();
                    if (abort)
                    {
                        return;
                    }

                    if (exportParameters.usePreExportProcess)
                    {
                        Loader.Core.FileHold();
                        preExportProcess.ApplyPreExport();
                    }
                    await DoExport(exportItemList);
                }
                catch (Exception ex)
                {
                    logger.RaiseError(ex.Message);
                }
                finally
                {
                    if (exportParameters.usePreExportProcess && !exportParameters.applyPreprocessToScene)
                    {
                        ScriptsUtilities.ExecuteMaxScriptCommand("fetchMaxFile quiet:true");
                    }
                }
            }
        }
Пример #6
0
        //leave the possibility to get the output path from the babylon exporter with all the settings previously-saved
        public static MaxExportParameters InitParameters(string outputPath)
        {
            long  txtQuality  = 100;
            float scaleFactor = 1f;

            MaxExportParameters exportParameters = new MaxExportParameters();

            exportParameters.outputPath                = outputPath;
            exportParameters.outputFormat              = Path.GetExtension(outputPath)?.Substring(1);
            exportParameters.textureFolder             = Loader.Core.RootNode.GetStringProperty("textureFolderPathProperty", string.Empty);
            exportParameters.generateManifest          = Loader.Core.RootNode.GetBoolProperty("babylonjs_generatemanifest");
            exportParameters.writeTextures             = Loader.Core.RootNode.GetBoolProperty("babylonjs_writetextures");
            exportParameters.overwriteTextures         = Loader.Core.RootNode.GetBoolProperty("babylonjs_overwritetextures");
            exportParameters.exportHiddenObjects       = Loader.Core.RootNode.GetBoolProperty("babylonjs_exporthidden");
            exportParameters.exportAsSubmodel          = Loader.Core.RootNode.GetBoolProperty("flightsim_exportAsSubmodel");
            exportParameters.autoSaveSceneFile         = Loader.Core.RootNode.GetBoolProperty("babylonjs_autosave");
            exportParameters.exportOnlySelected        = Loader.Core.RootNode.GetBoolProperty("babylonjs_onlySelected");
            exportParameters.exportTangents            = Loader.Core.RootNode.GetBoolProperty("babylonjs_exporttangents");
            exportParameters.scaleFactor               = float.TryParse(Loader.Core.RootNode.GetStringProperty("babylonjs_txtScaleFactor", "1"), out scaleFactor) ? scaleFactor : 1;
            exportParameters.txtQuality                = long.TryParse(Loader.Core.RootNode.GetStringProperty("babylonjs_txtCompression", "100"), out txtQuality) ? txtQuality : 100;
            exportParameters.mergeAOwithMR             = Loader.Core.RootNode.GetBoolProperty("babylonjs_mergeAOwithMR");
            exportParameters.dracoCompression          = Loader.Core.RootNode.GetBoolProperty("babylonjs_dracoCompression");
            exportParameters.enableKHRLightsPunctual   = Loader.Core.RootNode.GetBoolProperty("babylonjs_khrLightsPunctual");
            exportParameters.enableKHRTextureTransform = Loader.Core.RootNode.GetBoolProperty("babylonjs_khrTextureTransform");
            exportParameters.enableKHRMaterialsUnlit   = Loader.Core.RootNode.GetBoolProperty("babylonjs_khr_materials_unlit");
            exportParameters.exportMaterials           = Loader.Core.RootNode.GetBoolProperty("babylonjs_export_materials");

            exportParameters.exportMorphTangents    = Loader.Core.RootNode.GetBoolProperty("babylonjs_export_Morph_Tangents");
            exportParameters.exportMorphNormals     = Loader.Core.RootNode.GetBoolProperty("babylonjs_export_Morph_Normals");
            exportParameters.usePreExportProcess    = Loader.Core.RootNode.GetBoolProperty("babylonjs_preproces");
            exportParameters.mergeContainersAndXRef = Loader.Core.RootNode.GetBoolProperty("babylonjs_mergecontainersandxref");
            exportParameters.flattenGroups          = Loader.Core.RootNode.GetBoolProperty("flightsim_flattenGroups");
            exportParameters.applyPreprocessToScene = Loader.Core.RootNode.GetBoolProperty("babylonjs_applyPreprocess");

            exportParameters.pbrFull        = Loader.Core.RootNode.GetBoolProperty(ExportParameters.PBRFullPropertyName);
            exportParameters.pbrNoLight     = Loader.Core.RootNode.GetBoolProperty(ExportParameters.PBRNoLightPropertyName);
            exportParameters.pbrEnvironment = Loader.Core.RootNode.GetStringProperty(ExportParameters.PBREnvironmentPathPropertyName, string.Empty);
            exportParameters.exportNode     = null;

            exportParameters.animationExportType           = (AnimationExportType)Loader.Core.RootNode.GetFloatProperty("babylonjs_export_animations_type", 0);
            exportParameters.enableASBAnimationRetargeting = Loader.Core.RootNode.GetBoolProperty("babylonjs_asb_animation_retargeting", 0);
            exportParameters.enableASBUniqueID             = Loader.Core.RootNode.GetBoolProperty("flightsim_asb_unique_id", 1);

            exportParameters.removeLodPrefix        = Loader.Core.RootNode.GetBoolProperty("flightsim_removelodprefix");
            exportParameters.removeNamespaces       = Loader.Core.RootNode.GetBoolProperty("flightsim_removenamespaces");
            exportParameters.tangentSpaceConvention = (TangentSpaceConvention)Loader.Core.RootNode.GetFloatProperty("flightsim_tangent_space_convention", 0);
            exportParameters.bakeAnimationType      = (BakeAnimationType)Loader.Core.RootNode.GetFloatProperty("babylonjs_bakeAnimationsType", 0);
            exportParameters.keepInstances          = Loader.Core.RootNode.GetBoolProperty("flightsim_keepInstances", 1);

            exportParameters.logLevel = (LogLevel)Loader.Core.RootNode.GetFloatProperty("babylonjs_logLevel", 1);

            return(exportParameters);
        }
Пример #7
0
        public static void Export(MaxExportParameters exportParameters, ILoggingProvider _logger)
        {
            if (Loader.Class_ID == null)
            {
                Loader.AssemblyMain();
            }
            // Check output format is valid
            List <string> validFormats = new List <string>(new string[] { "babylon", "binary babylon", "gltf", "glb" });

            if (!validFormats.Contains(exportParameters.outputFormat))
            {
                Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf("ERROR - Valid output formats are: " + validFormats.ToArray().ToString(true) + "\n");
                return;
            }

            BabylonExporter exporter = new BabylonExporter(_logger);

            // Start export
            exporter.Export(exportParameters);
        }
Пример #8
0
        public static void Export(MaxExportParameters exportParameters, bool logInListener)
        {
            if (Loader.Class_ID == null)
            {
                Loader.AssemblyMain();
            }
            // Check output format is valid
            List <string> validFormats = new List <string>(new string[] { "babylon", "binary babylon", "gltf", "glb" });

            if (!validFormats.Contains(exportParameters.outputFormat))
            {
                Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf("ERROR - Valid output formats are: " + validFormats.ToArray().ToString(true) + "\n");
                return;
            }

            BabylonExporter exporter = new BabylonExporter();

            if (logInListener)
            {
                // Init log system
                exporter.OnWarning += (warning, rank) =>
                {
                    Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf(warning + "\n");
                };
                exporter.OnError += (error, rank) =>
                {
                    Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf(error + "\n");
                };
                exporter.OnMessage += (message, color, rank, emphasis) =>
                {
                    Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf(message + "\n");
                };
                exporter.OnVerbose += (message, color, rank, emphasis) =>
                {
                    Autodesk.Max.GlobalInterface.Instance.TheListener.EditStream.Printf(message + "\n");
                };
            }

            // Start export
            exporter.Export(exportParameters);
        }
Пример #9
0
        private async Task <bool> DoExport(ExportItem exportItem, bool multiExport = false, bool clearLogs = true)
        {
            new BabylonAnimationActionItem().Close();
            SaveOptions();

            //store layer visibility status and force visibility on

            Dictionary <IILayer, bool> layerState = new Dictionary <IILayer, bool>();

            if (exportItem.Layers != null)
            {
                foreach (IILayer layer in exportItem.Layers)
                {
                    List <IILayer> treeLayers = layer.LayerTree().ToList();
                    treeLayers.Add(layer);

                    foreach (IILayer l in treeLayers)
                    {
#if MAX2015
                        layerState.Add(l, l.IsHidden);
#else
                        layerState.Add(l, l.IsHidden(false));
#endif
                        l.Hide(false, false);
                    }
                }
            }

            exporter = new BabylonExporter();

            if (clearLogs)
            {
                treeView.Nodes.Clear();
            }

            exporter.OnExportProgressChanged += progress =>
            {
                progressBar.Value = progress;
                Application.DoEvents();
            };

            exporter.OnWarning += (warning, rank) => CreateWarningMessage(warning, rank);

            exporter.OnError += (error, rank) => CreateErrorMessage(error, rank);

            exporter.OnMessage += (message, color, rank, emphasis) => CreateMessage(message, color, rank, emphasis);

            exporter.OnVerbose += (message, color, rank, emphasis) =>
            {
                try
                {
                    currentNode = CreateTreeNode(rank, message, color);

                    if (emphasis)
                    {
                        currentNode.EnsureVisible();
                    }
                }
                catch
                {
                    //do nothing
                }
                Application.DoEvents();
            };

            butExport.Enabled       = false;
            butExportAndRun.Enabled = false;
            butMultiExport.Enabled  = false;
            butCancel.Enabled       = true;

            bool success = true;
            try
            {
                string modelAbsolutePath = multiExport ? exportItem.ExportFilePathAbsolute : txtModelPath.Text;
                string textureExportPath = multiExport ? exportItem.ExportTexturesesFolderAbsolute : txtTexturesPath.Text;

                var scaleFactorParsed    = 1.0f;
                var textureQualityParsed = 100L;
                try
                {
                    scaleFactorParsed = float.Parse(txtScaleFactor.Text);
                }
                catch (Exception e)
                {
                    throw new InvalidDataException(String.Format("Invalid Scale Factor value: {0}", txtScaleFactor.Text));
                }
                try
                {
                    textureQualityParsed = long.Parse(txtQuality.Text);
                }
                catch (Exception e)
                {
                    throw new InvalidDataException(String.Format("Invalid Texture Quality value: {0}", txtScaleFactor.Text));
                }

                MaxExportParameters exportParameters = new MaxExportParameters
                {
                    outputPath                 = modelAbsolutePath,
                    textureFolder              = textureExportPath,
                    outputFormat               = comboOutputFormat.SelectedItem.ToString(),
                    scaleFactor                = scaleFactorParsed,
                    writeTextures              = chkWriteTextures.Enabled && chkWriteTextures.Checked,
                    overwriteTextures          = chkOverwriteTextures.Enabled && chkOverwriteTextures.Checked,
                    exportHiddenObjects        = chkHidden.Checked,
                    exportOnlySelected         = chkOnlySelected.Checked,
                    generateManifest           = chkManifest.Checked,
                    autoSaveSceneFile          = chkAutoSave.Checked,
                    exportTangents             = chkExportTangents.Checked,
                    exportMorphTangents        = chkExportMorphTangents.Checked,
                    exportMorphNormals         = chkExportMorphNormals.Checked,
                    txtQuality                 = textureQualityParsed,
                    mergeAOwithMR              = chkMergeAOwithMR.Enabled && chkMergeAOwithMR.Checked,
                    bakeAnimationType          = (BakeAnimationType)cmbBakeAnimationOptions.SelectedIndex,
                    dracoCompression           = chkDracoCompression.Enabled && chkDracoCompression.Checked,
                    enableKHRLightsPunctual    = chkKHRLightsPunctual.Checked,
                    enableKHRTextureTransform  = chkKHRTextureTransform.Checked,
                    enableKHRMaterialsUnlit    = chkKHRMaterialsUnlit.Checked,
                    exportMaterials            = chkExportMaterials.Enabled && chkExportMaterials.Checked,
                    exportAnimations           = chkExportAnimations.Checked,
                    exportAnimationsOnly       = chkExportAnimationsOnly.Checked,
                    optimizeAnimations         = !chkDoNotOptimizeAnimations.Checked,
                    animgroupExportNonAnimated = chkAnimgroupExportNonAnimated.Checked,
                    exportNode                 = exportItem?.Node,
                    exportLayers               = exportItem?.Layers,
                    pbrNoLight                 = chkNoAutoLight.Checked,
                    pbrFull                = chkFullPBR.Checked,
                    pbrEnvironment         = txtEnvironmentName.Text,
                    usePreExportProcess    = chkUsePreExportProces.Checked,
                    flattenScene           = chkFlatten.Enabled && chkFlatten.Checked,
                    mergeContainersAndXRef = chkMrgContainersAndXref.Checked,
                    useMultiExporter       = multiExport
                };

                exporter.callerForm = this;

                exporter.Export(exportParameters);
            }
            catch (OperationCanceledException)
            {
                progressBar.Value = 0;
                success           = false;
                ScriptsUtilities.ExecuteMaxScriptCommand(@"global BabylonExporterStatus = ""Available""");
            }
            catch (Exception ex)
            {
                IUTF8Str operationStatus = GlobalInterface.Instance.UTF8Str.Create("BabylonExportAborted");
                Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, operationStatus);

                currentNode = CreateTreeNode(0, "Export cancelled: " + ex.Message, Color.Red);
                currentNode = CreateTreeNode(1, ex.ToString(), Color.Red);
                currentNode.EnsureVisible();

                progressBar.Value = 0;
                success           = false;
                ScriptsUtilities.ExecuteMaxScriptCommand(@"global BabylonExporterStatus = Available");
            }

            butCancel.Enabled       = false;
            butExport.Enabled       = true;
            butMultiExport.Enabled  = true;
            butExportAndRun.Enabled = WebServer.IsSupported;

            BringToFront();

            //re-store layer visibility status
            if (exportItem.Layers != null)
            {
                foreach (IILayer layer in exportItem.Layers)
                {
                    List <IILayer> treeLayers = layer.LayerTree().ToList();
                    treeLayers.Add(layer);
                    foreach (IILayer l in treeLayers)
                    {
                        bool exist;
                        layerState.TryGetValue(l, out exist);
                        if (exist)
                        {
                            l.Hide(layerState[l], false);
                        }
                    }
                }
            }

            return(success);
        }
Пример #10
0
        public void Export(ExportParameters exportParameters)
        {
            this.exportParameters = exportParameters;
            IINode exportNode = null;

            if (exportParameters is MaxExportParameters)
            {
                MaxExportParameters maxExporterParameters = (exportParameters as MaxExportParameters);
                exportNode = maxExporterParameters.exportNode;
                if (maxExporterParameters.flattenScene)
                {
                    FlattenHierarchy(exportNode);
                }
                if (maxExporterParameters.mergeInheritedContainers)
                {
                    ExportClosedContainers();
                }
            }



            this.scaleFactor = Tools.GetScaleFactorToMeters();

            var scaleFactorFloat = 1.0f;
            // Check input text is valid
            float scaleFactor = exportParameters.scaleFactor;

            long quality = exportParameters.txtQuality;

            try
            {
                if (quality < 0 || quality > 100)
                {
                    throw new Exception();
                }
            }
            catch
            {
                RaiseError("Quality is not a valid number. It should be an integer between 0 and 100.");
                RaiseError("This parameter sets the quality of jpg compression.");
                return;
            }



            var gameConversionManger = Loader.Global.ConversionManager;

            gameConversionManger.CoordSystem = Autodesk.Max.IGameConversionManager.CoordSystem.D3d;

            var gameScene = Loader.Global.IGameInterface;

            if (exportNode == null || exportNode.IsRootNode)
            {
                gameScene.InitialiseIGame(false);
            }
            else
            {
                gameScene.InitialiseIGame(exportNode, true);
            }

            gameScene.SetStaticFrame(0);

            MaxSceneFileName = gameScene.SceneFileName;

            IsCancelled = false;

            string fileExportString = exportNode != null
                ? $"{exportNode.NodeName} | {exportParameters.outputPath}"
                : exportParameters.outputPath;

            RaiseMessage($"Exportation started: {fileExportString}", Color.Blue);
            ReportProgressChanged(0);

            string tempOutputDirectory  = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string outputDirectory      = Path.GetDirectoryName(exportParameters.outputPath);
            string folderOuputDirectory = exportParameters.textureFolder;
            string outputFileName       = Path.GetFileName(exportParameters.outputPath);

            // Check directory exists
            if (!Directory.Exists(outputDirectory))
            {
                RaiseError("Exportation stopped: Output folder does not exist");
                ReportProgressChanged(100);
                return;
            }
            Directory.CreateDirectory(tempOutputDirectory);

            var outputBabylonDirectory = tempOutputDirectory;

            // Force output file extension to be babylon
            outputFileName = Path.ChangeExtension(outputFileName, "babylon");

            var babylonScene = new BabylonScene(outputBabylonDirectory);

            var rawScene = Loader.Core.RootNode;

            var watch = new Stopwatch();

            watch.Start();

            string outputFormat = exportParameters.outputFormat;

            isBabylonExported = outputFormat == "babylon" || outputFormat == "binary babylon";
            isGltfExported    = outputFormat == "gltf" || outputFormat == "glb";

            // Get scene parameters
            optimizeAnimations = !Loader.Core.RootNode.GetBoolProperty("babylonjs_donotoptimizeanimations");
            exportNonAnimated  = Loader.Core.RootNode.GetBoolProperty("babylonjs_animgroup_exportnonanimated");

            // Save scene
            if (exportParameters.autoSaveSceneFile)
            {
                RaiseMessage("Saving 3ds max file");
                var forceSave = Loader.Core.FileSave;

                callerForm?.BringToFront();
            }

            // Producer
            babylonScene.producer = new BabylonProducer
            {
                name = "3dsmax",
#if MAX2019
                version = "2019",
#elif MAX2018
                version = "2018",
#elif MAX2017
                version = "2017",
#else
                version = Loader.Core.ProductVersion.ToString(),
#endif
                exporter_version = exporterVersion,
                file             = outputFileName
            };

            // Global
            babylonScene.autoClear    = true;
            babylonScene.clearColor   = Loader.Core.GetBackGround(0, Tools.Forever).ToArray();
            babylonScene.ambientColor = Loader.Core.GetAmbient(0, Tools.Forever).ToArray();

            babylonScene.TimelineStartFrame      = Loader.Core.AnimRange.Start / Loader.Global.TicksPerFrame;
            babylonScene.TimelineEndFrame        = Loader.Core.AnimRange.End / Loader.Global.TicksPerFrame;
            babylonScene.TimelineFramesPerSecond = MaxSceneTicksPerSecond / Loader.Global.TicksPerFrame;

            babylonScene.gravity             = rawScene.GetVector3Property("babylonjs_gravity");
            ExportQuaternionsInsteadOfEulers = rawScene.GetBoolProperty("babylonjs_exportquaternions", 1);
            if (string.IsNullOrEmpty(exportParameters.pbrEnvironment) && Loader.Core.UseEnvironmentMap && Loader.Core.EnvironmentMap != null)
            {
                // Environment texture
                var environmentMap = Loader.Core.EnvironmentMap;
                // Copy image file to output if necessary
                var babylonTexture = ExportEnvironmnentTexture(environmentMap, babylonScene);
                if (babylonTexture != null)
                {
                    babylonScene.environmentTexture = babylonTexture.name;

                    // Skybox
                    babylonScene.createDefaultSkybox = rawScene.GetBoolProperty("babylonjs_createDefaultSkybox");
                    babylonScene.skyboxBlurLevel     = rawScene.GetFloatProperty("babylonjs_skyboxBlurLevel");
                }
            }
            else if (!string.IsNullOrEmpty(exportParameters.pbrEnvironment))
            {
                babylonScene.createDefaultSkybox = rawScene.GetBoolProperty("babylonjs_createDefaultSkybox");
                babylonScene.skyboxBlurLevel     = rawScene.GetFloatProperty("babylonjs_skyboxBlurLevel");
            }

            // Instantiate custom material exporters
            materialExporters = new Dictionary <ClassIDWrapper, IMaxMaterialExporter>();
            foreach (Type type in Tools.GetAllLoadableTypes())
            {
                if (type.IsAbstract || type.IsInterface || !typeof(IMaxMaterialExporter).IsAssignableFrom(type))
                {
                    continue;
                }

                IMaxMaterialExporter exporter = Activator.CreateInstance(type) as IMaxMaterialExporter;

                if (exporter == null)
                {
                    RaiseWarning("Creating exporter instance failed: " + type.Name, 1);
                }

                materialExporters.Add(exporter.MaterialClassID, exporter);
            }

            // 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);

                if (isBabylonExported)
                {
                    try
                    {
                        File.Copy(soundName, Path.Combine(babylonScene.OutputPath, filename), true);
                    }
                    catch
                    {
                    }
                }
            }

            // Root nodes
            RaiseMessage("Exporting nodes");
            HashSet <IIGameNode> maxRootNodes = getRootNodes(gameScene);
            var progressionStep = 80.0f / maxRootNodes.Count;
            var progression     = 10.0f;
            ReportProgressChanged((int)progression);
            referencedMaterials.Clear();
            Tools.guids.Clear();
            // Reseting is optionnal. It makes each morph target manager export starts from id = 0.
            BabylonMorphTargetManager.Reset();
            foreach (var maxRootNode in maxRootNodes)
            {
                BabylonNode node = exportNodeRec(maxRootNode, babylonScene, gameScene);

                // if we're exporting from a specific node, reset the pivot to {0,0,0}
                if (node != null && exportNode != null && !exportNode.IsRootNode)
                {
                    SetNodePosition(ref node, ref babylonScene, new float[] { 0, 0, 0 });
                }

                progression += progressionStep;
                ReportProgressChanged((int)progression);
                CheckCancelled();
            }
            ;
            RaiseMessage(string.Format("Total meshes: {0}", babylonScene.MeshesList.Count), Color.Gray, 1);


            // In 3DS Max the default camera look down (in the -z direction for the 3DS Max reference (+y for babylon))
            // In Babylon the default camera look to the horizon (in the +z direction for the babylon reference)
            // In glTF the default camera look to the horizon (in the +Z direction for glTF reference)
            RaiseMessage("Update camera rotation and position", 1);
            for (int index = 0; index < babylonScene.CamerasList.Count; index++)
            {
                BabylonCamera camera = babylonScene.CamerasList[index];
                FixCamera(ref camera, ref babylonScene);
            }

            // Light for glTF
            if (isGltfExported)
            {
                RaiseMessage("Update light rotation for glTF export", 1);
                for (int index = 0; index < babylonScene.LightsList.Count; index++)
                {
                    BabylonNode light = babylonScene.LightsList[index];
                    FixNodeRotation(ref light, ref babylonScene, -Math.PI / 2);
                }
            }

            // Main camera
            BabylonCamera babylonMainCamera   = null;
            ICameraObject maxMainCameraObject = null;
            if (babylonMainCamera == null && babylonScene.CamerasList.Count > 0)
            {
                // Set first camera as main one
                babylonMainCamera           = babylonScene.CamerasList[0];
                babylonScene.activeCameraID = babylonMainCamera.id;
                RaiseMessage("Active camera set to " + babylonMainCamera.name, Color.Green, 1, true);

                // Retreive camera node with same GUID
                var maxCameraNodesAsTab = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Camera);
                var maxCameraNodes      = TabToList(maxCameraNodesAsTab);
                var maxMainCameraNode   = maxCameraNodes.Find(_camera => _camera.MaxNode.GetGuid().ToString() == babylonMainCamera.id);
                maxMainCameraObject = (maxMainCameraNode.MaxNode.ObjectRef as ICameraObject);
            }

            if (babylonMainCamera == null)
            {
                RaiseWarning("No camera defined", 1);
            }
            else
            {
                RaiseMessage(string.Format("Total cameras: {0}", babylonScene.CamerasList.Count), Color.Gray, 1);
            }

            // Default light
            bool addDefaultLight = rawScene.GetBoolProperty("babylonjs_addDefaultLight", 1);
            if (!exportParameters.pbrNoLight && addDefaultLight && 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 lights: {0}", babylonScene.LightsList.Count), Color.Gray, 1);
            }

            if (scaleFactorFloat != 1.0f)
            {
                RaiseMessage("A root node is added for scaling", 1);

                // Create root node for scaling
                BabylonMesh rootNode = new BabylonMesh {
                    name = "root", id = Guid.NewGuid().ToString()
                };
                rootNode.isDummy = true;
                float rootNodeScale = scaleFactorFloat;
                rootNode.scaling = new float[3] {
                    rootNodeScale, rootNodeScale, rootNodeScale
                };

                if (ExportQuaternionsInsteadOfEulers)
                {
                    rootNode.rotationQuaternion = new float[] { 0, 0, 0, 1 };
                }
                else
                {
                    rootNode.rotation = new float[] { 0, 0, 0 };
                }

                // Update all top nodes
                var babylonNodes = new List <BabylonNode>();
                babylonNodes.AddRange(babylonScene.MeshesList);
                babylonNodes.AddRange(babylonScene.CamerasList);
                babylonNodes.AddRange(babylonScene.LightsList);
                foreach (BabylonNode babylonNode in babylonNodes)
                {
                    if (babylonNode.parentId == null)
                    {
                        babylonNode.parentId = rootNode.id;
                    }
                }

                // Store root node
                babylonScene.MeshesList.Add(rootNode);
            }

            // Materials
            if (exportParameters.exportMaterials)
            {
                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);
            }
            else
            {
                RaiseMessage("Skipping material export.");
            }

            // 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 (babylonMainCamera != null)
                    {
                        babylonScene.fogStart = maxMainCameraObject.GetEnvRange(0, 0, Tools.Forever);
                        babylonScene.fogEnd   = maxMainCameraObject.GetEnvRange(0, 1, Tools.Forever);
                    }
                }
            }

            // Skeletons
            if (skins.Count > 0)
            {
                RaiseMessage("Exporting skeletons");
                foreach (var skin in skins)
                {
                    ExportSkin(skin, babylonScene);
                }
            }

            // ----------------------------
            // ----- Animation groups -----
            // ----------------------------
            RaiseMessage("Export animation groups");
            // add animation groups to the scene
            babylonScene.animationGroups = ExportAnimationGroups(babylonScene);

            if (isBabylonExported)
            {
                // if we are exporting to .Babylon then remove then remove animations from nodes if there are animation groups.
                if (babylonScene.animationGroups.Count > 0)
                {
                    foreach (BabylonNode node in babylonScene.MeshesList)
                    {
                        node.animations = null;
                    }
                    foreach (BabylonNode node in babylonScene.LightsList)
                    {
                        node.animations = null;
                    }
                    foreach (BabylonNode node in babylonScene.CamerasList)
                    {
                        node.animations = null;
                    }
                    foreach (BabylonSkeleton skel in babylonScene.SkeletonsList)
                    {
                        foreach (BabylonBone bone in skel.bones)
                        {
                            bone.animation = null;
                        }
                    }
                }

                // setup a default skybox for the scene for .Babylon export.
                var sourcePath = exportParameters.pbrEnvironment;
                if (!string.IsNullOrEmpty(sourcePath))
                {
                    var fileName = Path.GetFileName(sourcePath);

                    // Allow only dds file format
                    if (!fileName.EndsWith(".dds"))
                    {
                        RaiseWarning("Failed to export defauenvironment texture: only .dds format is supported.");
                    }
                    else
                    {
                        RaiseMessage($"texture id = Max_Babylon_Default_Environment");
                        babylonScene.environmentTexture = fileName;

                        if (exportParameters.writeTextures)
                        {
                            try
                            {
                                var destPath = Path.Combine(babylonScene.OutputPath, fileName);
                                if (File.Exists(sourcePath) && sourcePath != destPath)
                                {
                                    File.Copy(sourcePath, destPath, true);
                                }
                            }
                            catch
                            {
                                // silently fails
                                RaiseMessage($"Fail to export the default env texture", 3);
                            }
                        }
                    }
                }
            }


            // Output
            babylonScene.Prepare(false, false);
            if (isBabylonExported)
            {
                RaiseMessage("Saving to output file");

                var outputFile = Path.Combine(outputBabylonDirectory, outputFileName);

                var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings());
                var sb             = new StringBuilder();
                var sw             = new StringWriter(sb, CultureInfo.InvariantCulture);
                using (var jsonWriter = new JsonTextWriterOptimized(sw))
                {
                    jsonWriter.Formatting = Formatting.None;
                    jsonSerializer.Serialize(jsonWriter, babylonScene);
                }
                File.WriteAllText(outputFile, sb.ToString());

                if (exportParameters.generateManifest)
                {
                    File.WriteAllText(outputFile + ".manifest",
                                      "{\r\n\"version\" : 1,\r\n\"enableSceneOffline\" : true,\r\n\"enableTexturesOffline\" : true\r\n}");
                }

                // Binary
                if (outputFormat == "binary babylon")
                {
                    RaiseMessage("Generating binary files");
                    BabylonFileConverter.BinaryConverter.Convert(outputFile, outputBabylonDirectory + "\\Binary",
                                                                 message => RaiseMessage(message, 1),
                                                                 error => RaiseError(error, 1));
                }
            }

            ReportProgressChanged(100);

            // Export glTF
            if (isGltfExported)
            {
                bool generateBinary = outputFormat == "glb";

                GLTFExporter gltfExporter = new GLTFExporter();
                exportParameters.customGLTFMaterialExporter = new MaxGLTFMaterialExporter(exportParameters, gltfExporter, this);
                gltfExporter.ExportGltf(this.exportParameters, babylonScene, tempOutputDirectory, outputFileName, generateBinary, this);
            }
            // Move files to output directory
            var filePaths = Directory.GetFiles(tempOutputDirectory);
            if (outputFormat == "binary babylon")
            {
                var tempBinaryOutputDirectory = Path.Combine(tempOutputDirectory, "Binary");
                var binaryFilePaths           = Directory.GetFiles(tempBinaryOutputDirectory);
                foreach (var filePath in binaryFilePaths)
                {
                    if (filePath.EndsWith(".binary.babylon"))
                    {
                        var file         = Path.GetFileName(filePath);
                        var tempFilePath = Path.Combine(tempBinaryOutputDirectory, file);
                        var outputFile   = Path.Combine(outputDirectory, file);

                        IUTF8Str maxNotification = GlobalInterface.Instance.UTF8Str.Create(outputFile);
                        Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, maxNotification);
                        moveFileToOutputDirectory(tempFilePath, outputFile, exportParameters);
                        Loader.Global.BroadcastNotification(SystemNotificationCode.PostExport, maxNotification);
                    }
                    else if (filePath.EndsWith(".babylonbinarymeshdata"))
                    {
                        var file         = Path.GetFileName(filePath);
                        var tempFilePath = Path.Combine(tempBinaryOutputDirectory, file);
                        var outputFile   = Path.Combine(outputDirectory, file);

                        IUTF8Str maxNotification = GlobalInterface.Instance.UTF8Str.Create(outputFile);
                        Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, maxNotification);
                        moveFileToOutputDirectory(tempFilePath, outputFile, exportParameters);
                        Loader.Global.BroadcastNotification(SystemNotificationCode.PostExport, maxNotification);
                    }
                }
            }
            if (outputFormat == "glb")
            {
                foreach (var file_path in filePaths)
                {
                    if (Path.GetExtension(file_path) == ".glb")
                    {
                        var file         = Path.GetFileName(file_path);
                        var tempFilePath = Path.Combine(tempOutputDirectory, file);
                        var outputFile   = Path.Combine(outputDirectory, file);


                        IUTF8Str maxNotification = GlobalInterface.Instance.UTF8Str.Create(outputFile);
                        Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, maxNotification);
                        moveFileToOutputDirectory(tempFilePath, outputFile, exportParameters);
                        Loader.Global.BroadcastNotification(SystemNotificationCode.PostExport, maxNotification);

                        break;
                    }
                }
            }
            else
            {
                foreach (var filePath in filePaths)
                {
                    var    file         = Path.GetFileName(filePath);
                    string ext          = Path.GetExtension(file);
                    var    tempFilePath = Path.Combine(tempOutputDirectory, file);
                    var    outputPath   = Path.Combine(outputDirectory, file);
                    if (!string.IsNullOrWhiteSpace(exportParameters.textureFolder) && TextureUtilities.ExtensionIsValidGLTFTexture(ext))
                    {
                        outputPath = Path.Combine(exportParameters.textureFolder, file);
                    }

                    IUTF8Str maxNotification = GlobalInterface.Instance.UTF8Str.Create(outputPath);
                    Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, maxNotification);
                    moveFileToOutputDirectory(tempFilePath, outputPath, exportParameters);
                    Loader.Global.BroadcastNotification(SystemNotificationCode.PostExport, maxNotification);
                }
            }
            Directory.Delete(tempOutputDirectory, true);
            watch.Stop();

            RaiseMessage(string.Format("Exportation done in {0:0.00}s: {1}", watch.ElapsedMilliseconds / 1000.0, fileExportString), Color.Blue);
            IUTF8Str max_notification = Autodesk.Max.GlobalInterface.Instance.UTF8Str.Create("BabylonExportComplete");
            Loader.Global.BroadcastNotification(SystemNotificationCode.PostExport, max_notification);
        }
Пример #11
0
        private async Task <bool> DoExport(ExportItem exportItem, bool multiExport = false, bool clearLogs = true)
        {
            SaveOptions();

            exporter = new BabylonExporter();

            if (clearLogs)
            {
                treeView.Nodes.Clear();
            }

            exporter.OnImportProgressChanged += progress =>
            {
                progressBar.Value = progress;
                Application.DoEvents();
            };

            exporter.OnWarning += (warning, rank) =>
            {
                try
                {
                    currentNode = CreateTreeNode(rank, warning, Color.DarkOrange);
                    currentNode.EnsureVisible();
                }
                catch
                {
                }
                Application.DoEvents();
            };

            exporter.OnError += (error, rank) =>
            {
                try
                {
                    currentNode = CreateTreeNode(rank, error, Color.Red);
                    currentNode.EnsureVisible();
                }
                catch
                {
                }
                Application.DoEvents();
            };

            exporter.OnMessage += (message, color, rank, emphasis) =>
            {
                try
                {
                    currentNode = CreateTreeNode(rank, message, color);

                    if (emphasis)
                    {
                        currentNode.EnsureVisible();
                    }
                }
                catch
                {
                }
                Application.DoEvents();
            };

            butExport.Enabled       = false;
            butExportAndRun.Enabled = false;
            butMultiExport.Enabled  = false;
            butCancel.Enabled       = true;

            bool success = true;

            try
            {
                string modelAbsolutePath             = multiExport ? exportItem.ExportFilePathAbsolute : txtModelName.Text;
                string textureExportPath             = multiExport ? exportItem.ExportTexturesesFolderPath : txtTextureName.Text;
                MaxExportParameters exportParameters = new MaxExportParameters
                {
                    outputPath                 = modelAbsolutePath,
                    textureFolder              = textureExportPath,
                    outputFormat               = comboOutputFormat.SelectedItem.ToString(),
                    scaleFactor                = float.Parse(txtScaleFactor.Text),
                    writeTextures              = chkWriteTextures.Checked,
                    overwriteTextures          = chkOverwriteTextures.Checked,
                    exportHiddenObjects        = chkHidden.Checked,
                    exportOnlySelected         = chkOnlySelected.Checked,
                    generateManifest           = chkManifest.Checked,
                    autoSaveSceneFile          = chkAutoSave.Checked,
                    exportTangents             = chkExportTangents.Checked,
                    exportMorphTangents        = chkExportMorphTangents.Checked,
                    exportMorphNormals         = chkExportMorphNormals.Checked,
                    txtQuality                 = long.Parse(txtQuality.Text),
                    mergeAOwithMR              = chkMergeAOwithMR.Checked,
                    dracoCompression           = chkDracoCompression.Checked,
                    enableKHRLightsPunctual    = chkKHRLightsPunctual.Checked,
                    enableKHRTextureTransform  = chkKHRTextureTransform.Checked,
                    enableKHRMaterialsUnlit    = chkKHRMaterialsUnlit.Checked,
                    exportMaterials            = chkExportMaterials.Checked,
                    optimizeAnimations         = !chkDoNotOptimizeAnimations.Checked,
                    animgroupExportNonAnimated = chkAnimgroupExportNonAnimated.Checked,
                    exportNode                 = exportItem != null ? exportItem.Node : null,
                    pbrNoLight                 = chkNoAutoLight.Checked,
                    pbrFull                  = chkFullPBR.Checked,
                    pbrEnvironment           = txtEnvironmentName.Text,
                    usePreExportProcess      = chkUsePreExportProces.Checked,
                    flattenScene             = chkFlatten.Checked,
                    mergeInheritedContainers = chkMrgInheritedContainers.Checked
                };

                exporter.callerForm = this;

                exporter.Export(exportParameters);
            }
            catch (OperationCanceledException)
            {
                progressBar.Value = 0;
                success           = false;
            }
            catch (Exception ex)
            {
                IUTF8Str operationStatus = GlobalInterface.Instance.UTF8Str.Create("BabylonExportAborted");
                Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, operationStatus);

                currentNode = CreateTreeNode(0, "Export cancelled: " + ex.Message, Color.Red);
                currentNode = CreateTreeNode(1, ex.ToString(), Color.Red);
                currentNode.EnsureVisible();

                progressBar.Value = 0;
                success           = false;
            }

            butCancel.Enabled       = false;
            butExport.Enabled       = true;
            butMultiExport.Enabled  = true;
            butExportAndRun.Enabled = WebServer.IsSupported;

            BringToFront();

            return(success);
        }
Пример #12
0
        private MaxExportParameters GetExportParameters()
        {
            var scaleFactorParsed    = 1.0f;
            var textureQualityParsed = 100L;

            try
            {
                scaleFactorParsed = float.Parse(txtScaleFactor.Text);
            }
            catch (Exception e)
            {
                throw new InvalidDataException(String.Format("Invalid Scale Factor value: {0}", txtScaleFactor.Text));
            }
            try
            {
                textureQualityParsed = long.Parse(txtQuality.Text);
            }
            catch (Exception e)
            {
                throw new InvalidDataException(String.Format("Invalid Texture Quality value: {0}", txtScaleFactor.Text));
            }

            MaxExportParameters exportParameters = new MaxExportParameters
            {
                outputFormat                  = comboOutputFormat.SelectedItem.ToString(),
                scaleFactor                   = scaleFactorParsed,
                writeTextures                 = chkWriteTextures.Enabled && chkWriteTextures.Checked,
                overwriteTextures             = chkOverwriteTextures.Enabled && chkOverwriteTextures.Checked,
                exportHiddenObjects           = chkHidden.Checked,
                exportOnlySelected            = chkOnlySelected.Checked,
                exportAsSubmodel              = chkExportAsSubmodel.Checked,
                generateManifest              = chkManifest.Checked,
                autoSaveSceneFile             = chkAutoSave.Checked,
                exportTangents                = chkExportTangents.Checked,
                exportMorphTangents           = chkExportMorphTangents.Checked,
                exportMorphNormals            = chkExportMorphNormals.Checked,
                txtQuality                    = textureQualityParsed,
                mergeAOwithMR                 = chkMergeAOwithMR.Enabled && chkMergeAOwithMR.Checked,
                bakeAnimationType             = (BakeAnimationType)cmbBakeAnimationOptions.SelectedIndex,
                logLevel                      = (LogLevel)logLevelcmb.SelectedIndex,
                dracoCompression              = chkDracoCompression.Enabled && chkDracoCompression.Checked,
                enableKHRLightsPunctual       = chkKHRLightsPunctual.Checked,
                enableKHRTextureTransform     = chkKHRTextureTransform.Checked,
                enableKHRMaterialsUnlit       = chkKHRMaterialsUnlit.Checked,
                exportMaterials               = chkExportMaterials.Enabled && chkExportMaterials.Checked,
                animationExportType           = (AnimationExportType)cmbExportAnimationType.SelectedIndex,
                enableASBAnimationRetargeting = chkASBAnimationRetargeting.Checked,
                enableASBUniqueID             = chkUniqueID.Checked,
                pbrNoLight                    = chkNoAutoLight.Checked,
                pbrFull                = chkFullPBR.Checked,
                pbrEnvironment         = txtEnvironmentName.Text,
                usePreExportProcess    = chkUsePreExportProces.Checked,
                applyPreprocessToScene = chkApplyPreprocessToScene.Checked,
                mergeContainersAndXRef = chkMrgContainersAndXref.Checked,
                flattenGroups          = chkFlattenGroups.Checked,
                tangentSpaceConvention = (TangentSpaceConvention)cmbNormalMapConvention.SelectedIndex,
                keepInstances          = chkKeepInstances.Checked,
                removeLodPrefix        = chk_RemoveLodPrefix.Checked,
                removeNamespaces       = chkRemoveNamespace.Checked,
                srcTextureExtension    = txtSrcTextureExt.Text,
                dstTextureExtension    = txtDstTextureExt.Text
            };

            return(exportParameters);
        }
        private async Task <bool> DoExport(ExportItem exportItem, bool multiExport = false, bool clearLogs = true)
        {
            new BabylonAnimationActionItem().Close();
            SaveOptions();

            if (multiExport)
            {
                ShowExportItemLayers(exportItem.Layers);
            }

            exporter = new BabylonExporter();

            if (clearLogs)
            {
                treeView.Nodes.Clear();
            }

            exporter.OnExportProgressChanged += progress =>
            {
                progressBar.Value = progress;
                Application.DoEvents();
            };

            exporter.OnWarning += (warning, rank) => CreateWarningMessage(warning, rank);

            exporter.OnError += (error, rank) => CreateErrorMessage(error, rank);

            exporter.OnMessage += (message, color, rank, emphasis) => CreateMessage(message, color, rank, emphasis);

            exporter.OnVerbose += (message, color, rank, emphasis) => CreateMessage(message, color, rank, emphasis);

            exporter.OnPrint += (message, color, rank, emphasis) => CreateMessage(message, color, rank, emphasis);

            butExport.Enabled       = false;
            butExportAndRun.Enabled = false;
            butMultiExport.Enabled  = false;
            butCancel.Enabled       = true;

            bool success = true;

            try
            {
                string modelAbsolutePath = multiExport ? exportItem.ExportFilePathAbsolute : txtModelPath.Text;
                string textureExportPath = multiExport ? exportItem.ExportTexturesesFolderAbsolute : txtTexturesPath.Text;

                var scaleFactorParsed    = 1.0f;
                var textureQualityParsed = 100L;
                try
                {
                    scaleFactorParsed = float.Parse(txtScaleFactor.Text);
                }
                catch (Exception e)
                {
                    throw new InvalidDataException(String.Format("Invalid Scale Factor value: {0}", txtScaleFactor.Text));
                }
                try
                {
                    textureQualityParsed = long.Parse(txtQuality.Text);
                }
                catch (Exception e)
                {
                    throw new InvalidDataException(String.Format("Invalid Texture Quality value: {0}", txtScaleFactor.Text));
                }

                MaxExportParameters exportParameters = new MaxExportParameters
                {
                    outputPath                    = modelAbsolutePath,
                    textureFolder                 = textureExportPath,
                    outputFormat                  = comboOutputFormat.SelectedItem.ToString(),
                    scaleFactor                   = scaleFactorParsed,
                    writeTextures                 = chkWriteTextures.Enabled && chkWriteTextures.Checked,
                    overwriteTextures             = chkOverwriteTextures.Enabled && chkOverwriteTextures.Checked,
                    exportHiddenObjects           = chkHidden.Checked,
                    exportOnlySelected            = chkOnlySelected.Checked,
                    generateManifest              = chkManifest.Checked,
                    autoSaveSceneFile             = chkAutoSave.Checked,
                    exportTangents                = chkExportTangents.Checked,
                    exportMorphTangents           = chkExportMorphTangents.Checked,
                    exportMorphNormals            = chkExportMorphNormals.Checked,
                    txtQuality                    = textureQualityParsed,
                    mergeAOwithMR                 = chkMergeAOwithMR.Enabled && chkMergeAOwithMR.Checked,
                    bakeAnimationType             = (BakeAnimationType)cmbBakeAnimationOptions.SelectedIndex,
                    logLevel                      = (LogLevel)logLevelcmb.SelectedIndex,
                    dracoCompression              = chkDracoCompression.Enabled && chkDracoCompression.Checked,
                    enableKHRLightsPunctual       = chkKHRLightsPunctual.Checked,
                    enableKHRTextureTransform     = chkKHRTextureTransform.Checked,
                    enableKHRMaterialsUnlit       = chkKHRMaterialsUnlit.Checked,
                    exportMaterials               = chkExportMaterials.Enabled && chkExportMaterials.Checked,
                    animationExportType           = (AnimationExportType)cmbExportAnimationType.SelectedIndex,
                    enableASBAnimationRetargeting = chkASBAnimationRetargeting.Checked,
                    optimizeAnimations            = !chkDoNotOptimizeAnimations.Checked,
                    animgroupExportNonAnimated    = chkAnimgroupExportNonAnimated.Checked,
                    exportNode                    = exportItem?.Node,
                    exportLayers                  = exportItem?.Layers,
                    pbrNoLight                    = chkNoAutoLight.Checked,
                    pbrFull                = chkFullPBR.Checked,
                    pbrEnvironment         = txtEnvironmentName.Text,
                    usePreExportProcess    = chkUsePreExportProces.Checked,
                    flattenScene           = chkFlatten.Enabled && chkFlatten.Checked,
                    mergeContainersAndXRef = chkMrgContainersAndXref.Checked,
                    useMultiExporter       = multiExport,
                    tangentSpaceConvention = (TangentSpaceConvention)cmbNormalMapConvention.SelectedIndex,
                    removeLodPrefix        = chk_RemoveLodPrefix.Checked,
                    removeNamespaces       = chkRemoveNamespace.Checked,
                    srcTextureExtension    = txtSrcTextureExt.Text,
                    dstTextureExtension    = txtDstTextureExt.Text
                };

                exporter.callerForm = this;

                exporter.Export(exportParameters);
            }
            catch (OperationCanceledException)
            {
                progressBar.Value = 0;
                success           = false;
                ScriptsUtilities.ExecuteMaxScriptCommand(@"global BabylonExporterStatus = ""Available""");
            }
            catch (Exception ex)
            {
                IUTF8Str operationStatus = GlobalInterface.Instance.UTF8Str.Create("BabylonExportAborted");
                Loader.Global.BroadcastNotification(SystemNotificationCode.PreExport, operationStatus);

                currentNode = CreateTreeNode(0, "Export cancelled: " + ex.Message, Color.Red);
                currentNode = CreateTreeNode(1, ex.ToString(), Color.Red);
                currentNode.EnsureVisible();

                progressBar.Value = 0;
                success           = false;
                ScriptsUtilities.ExecuteMaxScriptCommand(@"global BabylonExporterStatus = Available");
            }

            butCancel.Enabled       = false;
            butExport.Enabled       = true;
            butMultiExport.Enabled  = true;
            butExportAndRun.Enabled = WebServer.IsSupported;

            BringToFront();

            return(success);
        }
Пример #14
0
 // Expose this entrypoint to MaxScript, as it does not seem to support C# optional parameters
 public static void Export(MaxExportParameters exportParameters)
 {
     Export(exportParameters, false);
 }