예제 #1
0
        public static void LoadNewBrushFiles(string[] absNames)
        {
            try
            {
                foreach (string f in absNames)
                {
                    TerrainBrush b = FindBrushByFilename(f);
                    if (b == null)
                    {
                        b = TerrainConversionHelpers.CreateBrush(f);
                    }
                    else
                    {
                        TerrainConversionHelpers.CheckBrushModified(b);
                        continue;
                    }

                    if (b == null || !b.Valid)
                    {
                        continue;
                    }
                    _allBrushes.Add(b);
                }
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, true);
            }

            if (OnBrushCollectionChanged != null)
            {
                OnBrushCollectionChanged(null, EventArgs.Empty);
            }
        }
예제 #2
0
        /// <summary>
        /// Saves a screenshot of the current engine view with the given settings.
        /// </summary>
        public static void SaveScreenshot(ScreenshotSettings settings)
        {
            try
            {
                // Create a new file name (e.g. Screenshot0.png, Screenshot1.png, ...)
                string filename = FileHelper.CreateUniqueFilename(settings.Directory, settings.FileName, settings.FileExtension);
                if (filename == null)
                {
                    throw new DirectoryNotFoundException(String.Format("Directory {0} could not be found", settings.Directory));
                }

                filename = Path.Combine(settings.Directory, Path.ChangeExtension(filename, settings.FileExtension));

                // Render and save
                EditorManager.EngineManager.SaveScreenShot(filename, settings.ViewportWidth, settings.ViewportHeight, settings.FovX, settings.FovY);

                if (settings.OpenExternally)
                {
                    // Open the screenshot file with the associated external program
                    Process.Start(filename);
                }
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex);
                EditorManager.ShowMessageBox("Saving screenshot failed.\n\nDetailed message:\n" + ex.Message, "Saving screenshot", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #3
0
        private void button_EditvLuxSettings_Click(object sender, System.EventArgs e)
        {
            try
            {
                //add/edit lighting cfg (either custom or default name "lighting.cfg") to RCS:
                string lightingCfgFile = VLuxLightingTool.GetLightingCfgFile(_settings);

                ManagedBase.RCS.GetProvider().EditFile(lightingCfgFile);

                Process vLux = FileHelper.RunExternalTool("vLux", VLuxLightingDlg.vLuxEXEPath, VLuxArgumentString, true);

                if (vLux == null)
                {
                    return;
                }

                Console.WriteLine(vLux.StandardOutput.ReadToEnd());

                vLux.WaitForExit();
                int iExitCode = vLux.ExitCode;

                //add lighting cfg file to RCS
                ManagedBase.RCS.GetProvider().AddFile(lightingCfgFile, false /* Text file */);
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex);
                EditorManager.ShowMessageBox("Could not start vLux (\"" + VLuxLightingDlg.vLuxEXEPath + "\").\n\nDetailed message:\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void TestShapeSerialization()
        {
            const string TEST_SCENENAME = "TestShapeSerialization.scene";

            // setup new test project/scene
            TestManager.Helpers.CreateTestScene(TEST_SCENENAME);
            EditorProject project = EditorApp.Project;

            try
            {
                // create all registered shapes
                foreach (IShapeCreatorPlugin plugin in EditorManager.ShapeCreatorPlugins)
                {
                    plugin.ExecutePlugin();
                }
                string projectFile      = project.PathName;
                int    numCreatedShapes = CountShapeInstances(project.Scene);

                // cause engine view to refresh (to see that rendering the shapes doesn't cause a crash)
                TestManager.Helpers.ProcessEvents();

                // close map
                project.Save();

                ShapeCollection c1 = project.Scene.ActiveLayer.Root.ChildCollection;

                EditorManager.Scene.Close();
                project.Close();

                // reload map
                project = EditorManager.ProjectFactory.CreateInstance(null) as EditorProject;
                Assert.IsNotNull(project);

                project.Load(projectFile);
                EditorManager.Project = project;
                bool bResult = project.OpenScene(TEST_SCENENAME);
                Assert.IsTrue(bResult);

                // verify that shape instances exist
                int             numLoadedShapes = CountShapeInstances(project.Scene);
                ShapeCollection c2 = project.Scene.ActiveLayer.Root.ChildCollection;

                for (int i = 0; i < c1.Count; i++)
                {
                    ShapeBase s1 = c1[i];
                    ShapeBase s2 = c2[i];
                    Assert.AreEqual(s1.GetType(), s2.GetType());
                }

                Assert.AreEqual(numCreatedShapes, numLoadedShapes);

                TestManager.Helpers.CloseTestProject();
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, true);
            }
        }
예제 #5
0
        void listView_DragDrop(object sender, DragEventArgs e)
        {
            string[] imgFiles = GetDraggedBitmapFile(e);
            if (imgFiles == null)
            {
                return;
            }

            string dir        = TerrainEditor.AbsoluteBrushFilePath;
            bool   bAnyExists = false;
            string exists     = "";

            string[] tgtNames = new string[imgFiles.Length];
            int      i        = 0;

            foreach (string filename in imgFiles)
            {
                string relname = Path.GetFileName(filename);
                tgtNames[i] = Path.Combine(dir, relname);
                if (File.Exists(tgtNames[i]))
                {
                    bAnyExists = true;
                    exists    += "\n" + relname;
                }
                i++;
            }

            if (bAnyExists)
            {
                if (EditorManager.ShowMessageBox("A file named\n" + exists + "\n\nalready exists in the target directory.\n\nSelect 'Yes' to overwrite or 'No' to abort", "Overwrite files?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }
            }

            // copy the files
            try
            {
                for (i = 0; i < tgtNames.Length; i++)
                {
                    System.IO.File.Copy(imgFiles[i], tgtNames[i], true);
                }
            }
            catch (Exception ex)
            {
                EditorManager.ShowMessageBox("An error occurred while copying file(s):\n" + ex.Message, "File copy error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                EditorManager.DumpException(ex);
                return;
            }

            TerrainEditor.LoadNewBrushFiles(tgtNames);
        }
예제 #6
0
        /// <summary>
        /// Create a new project
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="projname"></param>
        /// <returns></returns>
        public static EditorProject CreateProject(string dir, string projname)
        {
            char   slash       = Path.DirectorySeparatorChar;
            string projdir     = dir;                                // x:\dir
            string projextname = projname + ".project";
            string projfile    = Path.Combine(projdir, projextname); // x:\dir\projname.project

            //create the project directory
            if (Directory.CreateDirectory(projdir) == null)
            {
                EditorManager.ShowMessageBox("Failed to create project directory", "Failed to create project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }

            //create the project file
            FileStream fs = File.Create(projfile);

            if (fs == null)
            {
                return(null);
            }

            //We don't store anything in the project file
            fs.Close();

            //Open the project and return it
            //EditorProject proj = new EditorProject();
            EditorProject proj = EditorManager.ProjectFactory.CreateInstance(null) as EditorProject;

            if (proj == null)
            {
                EditorManager.ShowMessageBox("Project must be derived from class 'EditorProject'", "Failed to create project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }

            proj.FileName = projextname;

            try
            {
                proj.Load(projfile);

                //Add the project file
                ManagedBase.RCS.GetProvider().AddFile(projfile, true /* Binary file - but files are until now empty, should we place text in there this needs to be changed */);
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex);
                proj = null;
            }

            return(proj);
        }
예제 #7
0
 public override void Undo()
 {
     ShapeTreeView.UIUpdateLock++;
     try
     {
         base.Undo();
     }
     catch (Exception ex)
     {
         EditorManager.DumpException(ex);
     }
     ShapeTreeView.UIUpdateLock--;
     InvalidateUI(); // easy method to rebuild list
 }
예제 #8
0
        public override ShapeBase CreateShape(string classname, string name, PropertyEntryCollection properties)
        {
            Type t = GetTypeByName(classname, typeof(ShapeBase), ThrowExceptions);

            if (t == null)
            {
                return(null);
            }

            string moreFailInfo = "";

            try
            {
                object[] args = new object[1] {
                    name
                };                              // always use the "name" constructor
                ShapeBase newObject = Activator.CreateInstance(t, args) as ShapeBase;
                if (newObject == null)
                {
                    if (ThrowExceptions)
                    {
                        throw new Exception("Failed to create instance of class '" + classname + "'");
                    }
                    return(null);
                }

                RecursiveParseProperties(newObject, properties);
                return(newObject);
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, false);
                moreFailInfo = "\nDetailed: ";
                if (ex.InnerException != null)
                {
                    moreFailInfo += ex.InnerException.ToString();
                }
                else
                {
                    moreFailInfo += ex.Message;
                }
            }

            if (ThrowExceptions)
            {
                throw new Exception("Failed to create instance of class '" + classname + "'" + moreFailInfo);
            }

            return(null);
        }
예제 #9
0
        /// <summary>
        /// Load all default brushes from the directory
        /// </summary>
        static void LoadAllBrushes()
        {
            if (!EditorManager.EngineManager.IsInitialized())
            {
                return;
            }

            try
            {
                FreeAllBrushes();
                string   dir   = AbsoluteBrushFilePath;
                string[] files = Directory.GetFiles(dir, "*.bmp");
                foreach (string f in files)
                {
                    TerrainBrush b = TerrainConversionHelpers.CreateBrush(f);
                    if (b == null || !b.Valid)
                    {
                        continue;
                    }
                    _allBrushes.Add(b);
                }
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, true);
            }

            if (OnBrushCollectionChanged != null)
            {
                OnBrushCollectionChanged(null, EventArgs.Empty);
            }

            if (!string.IsNullOrEmpty(_preferredBrushName))
            {
                TerrainBrush b = FindBrush(_preferredBrushName);
                if (b != null)
                {
                    CurrentBrush = b;
                }
            }
            if (CurrentBrush == null)
            {
                CurrentBrush = FindBrush("Smooth1"); // preferred brush to start with
            }
            if (CurrentBrush == null && _allBrushes.Count > 0)
            {
                CurrentBrush = (TerrainBrush)_allBrushes[0];
            }
        }
예제 #10
0
 void IScene_EngineInstancesChanged(object sender, EngineInstancesChangedArgs e)
 {
     if (e.action == EngineInstancesChangedArgs.Action.PostCreateAll && bNewScene)
     {
         bNewScene = false;
         try
         {
             MigrateToFmodShapes();
         }
         catch (Exception ex)
         {
             EditorManager.DumpException(ex, true);
         }
     }
 }
예제 #11
0
        public void TestEntityPropertySerialization()
        {
            try
            {
                const string TEST_SCENENAME = "TestEntityPropertySerialization";

                // setup new test project/scene
                TestManager.Helpers.CreateTestScene(TEST_SCENENAME);
                EditorProject project = EditorApp.Project;

                // create an entity shape
                EditorManager.GetShapeCreatorPluginByName("Entity").ExecutePlugin();
                ShapeBase entityShape = EditorManager.Scene.ActiveLayer.Root.ChildCollection[0];

                string projectFile      = project.PathName;
                int    numCreatedShapes = CountShapeInstances(project.Scene);

                // cause engine view to refresh (to see that rendering the shapes doesn't cause a crash)
                TestManager.Helpers.ProcessEvents();

                // close map
                project.Save();
                project.Close();

                // reload map
                project = EditorManager.ProjectFactory.CreateInstance(null) as EditorProject;
                Assert.IsNotNull(project);
                project.Load(projectFile);
                EditorManager.Project = project;
                bool bResult = project.OpenScene(TEST_SCENENAME);
                Assert.IsTrue(bResult);

                // verify that EntityProperty type is part of the active EntityClassManager assembly
                entityShape = EditorManager.Scene.ActiveLayer.Root.ChildCollection[0];
                DynamicPropertyCollection entityProperties = (DynamicPropertyCollection)entityShape.GetType().InvokeMember("EntityProperties", BindingFlags.GetProperty, null, entityShape, new object[] {});
                Assert.IsTrue(EditorManager.EngineManager.EntityClassManager.Exists(entityProperties.CollectionType.UniqueName));

                TestManager.Helpers.CloseTestProject();
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, true);
                throw ex;
            }
        }
예제 #12
0
        void ExportHeightmap(string filename, bool normalized)
        {
            bool result = false;

            try
            {
                File.Delete(filename);
                result = TerrainEditor.CurrentTerrain.EngineTerrain.ExportHeightmapAsDDS(filename, normalized);
            }
            catch (Exception e)
            {
                EditorManager.DumpException(e);
                result = false;
            }

            Assert.IsTrue(result);
            Assert.IsTrue(File.Exists(filename));
        }
예제 #13
0
    void FillProfileCombobox()
    {
      comboBox_Profile.Items.Clear();

      try
      {
        DirectoryInfo layerFolder = new DirectoryInfo(EditorManager.Scene.LayerDirectoryName);
        FileInfo[] files = layerFolder.GetFiles("*." + SceneExportProfile.FILE_EXTENSION_EXPORTPROFILE);
        foreach (FileInfo file in files)
        {
          string name = Path.GetFileNameWithoutExtension(file.Name);
          comboBox_Profile.Items.Add(name);
        }
      }
      catch (Exception ex)
      {
        EditorManager.DumpException(ex);
      }

    }
예제 #14
0
        /// <summary>
        /// see ITestHelpers.CloseTestProject
        /// </summary>
        public void CloseTestProject()
        {
            try
            {
                if (EditorManager.Scene != null)
                {
                    EditorManager.Scene.Close();
                }
                EditorApp.Project.Close();
                EditorManager.Project = null;
                EditorManager.Scene   = null;
                ProcessEvents();

                if (Directory.Exists(TestDirectory))
                {
                    Process eraseExec = new Process();
                    eraseExec.StartInfo.FileName        = "cmd";
                    eraseExec.StartInfo.Arguments       = "/c erase /s /q /f " + TestDirectory;
                    eraseExec.StartInfo.UseShellExecute = false;
                    eraseExec.StartInfo.CreateNoWindow  = true;
                    try
                    {
                        eraseExec.Start();
                        eraseExec.WaitForExit();
                        if (eraseExec.ExitCode != 0)
                        {
                            //System.Windows.Forms.MessageBox.Show("Executing 'erase /s /q /f '" + TestDirectory + "' did not work. Error Code: " + eraseExec.ExitCode.ToString());
                        }
                    }
                    catch (System.Exception)
                    {
                        //System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                    Directory.Delete(TestDirectory, true);
                }
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, true);
            }
        }
예제 #15
0
        private void button_EditvLuxSettings_Click(object sender, System.EventArgs e)
        {
            try
            {
                //add/edit lighting cfg (either custom or default name "lighting.cfg") to RCS:
                string lightingCfgFile = VLuxLightingTool.GetLightingCfgFile(_settings);

                ManagedBase.RCS.GetProvider().EditFile(lightingCfgFile);

                Process vLux = FileHelper.RunExternalTool("vLux", VLuxLightingDlg.vLuxEXEPath, VLuxArgumentString, true);

                if (vLux == null)
                {
                    return;
                }

                // ReadToEnd will block so we do so in another thread.
                Thread StandardOutputThread = new Thread(() => { Console.WriteLine(vLux.StandardOutput.ReadToEnd()); });

                using (WaitForProcessDlg waitDlg = new WaitForProcessDlg("vLux", vLux))
                {
                    waitDlg.ShowDialog(this);
                }

                // In case the user somehow succeeds in closing WaitForProcessDlg it will block here until the process in done.
                vLux.WaitForExit();
                int iExitCode = vLux.ExitCode;

                //add lighting cfg file to RCS
                ManagedBase.RCS.GetProvider().AddFile(lightingCfgFile, false /* Text file */);
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex);
                EditorManager.ShowMessageBox("Could not start vLux (\"" + VLuxLightingDlg.vLuxEXEPath + "\").\n\nDetailed message:\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #16
0
        /// <summary>
        /// Updates all project related creators, this function is called by the project update event
        /// </summary>
        protected void ProjectUpdate()
        {
            BeginAddCreators();
            StoreCollapsedState();
            ClearTree();
            EditorProject project = EditorApp.Project;

            if (project == null)
            {
                EndAddCreators();
                return;
            }

            int iCategoryIcon = EditorManager.GUI.ShapeTreeImages.AddBitmap(Path.Combine(EditorManager.AppDataDir, @"bitmaps\Shapes\folder_new.png"), Color.Magenta);

            // add all creator plugins in this project
            ShapeCreatorTreeNode catCreators = this.AddCategory(null, "Shape Creators", iCategoryIcon);
            IEditorPluginList    list        = EditorManager.SortedShapeCreatorPlugins;

            foreach (IShapeCreatorPlugin plugin in list)
            {
                if (!plugin.IsVisible())
                {
                    continue;
                }

                // Apply the search filter
                if (!searchPanel.MatchesFilter(plugin.GetPluginName()))
                {
                    continue;
                }

                ShapeCreatorTreeNode catPlugin = catCreators;
                string catName = plugin.GetPluginCategory();
                if (catName != null && catName.Length > 0)
                {
                    catPlugin = AddCategoryPath(catCreators, catName, "\\", -1);
                }

                AddCreator(catPlugin, plugin, plugin.GetPluginName(), plugin.IconIndex);
            }

            string prefabDir = project.MakeAbsolute(EditorManager.Settings.PrefabDirectory);

            if (Directory.Exists(prefabDir))
            {
                // Add prefabs from project directory:
                try
                {
                    AddPrefabCreators(prefabDir, null);
                }
                catch (Exception ex)
                {
                    EditorManager.DumpException(ex);
                }
            }

            // Expand all if no collapsed state was restored before, otherwise restore old one.
            // We can not expand/collapse the TreeNodes at creation time as they have no children
            // assigned when they are created.
            if (nodeState == null || nodeState.Length == 0 || searchPanel.IsActive)
            {
                treeView_Creators.ExpandAll();
            }
            else
            {
                RestoreCollapsedState(treeView_Creators.Nodes);
            }

            EndAddCreators();
        }
예제 #17
0
        public override ShapeLink CreateShapeLink(string classname, Shape3D ownerShape, string name, string primaryID)
        {
            Type t = _cachedClassTypes.ContainsKey(classname) ? _cachedClassTypes[classname] : null;

            if (t == null)
            {
                // loop through all assemblies and find the type by name
                Assembly[] assemblies = AssemblyHelper.GetEditorAssemblies();
                foreach (Assembly assembly in assemblies)
                {
                    Type[] types = null;
                    try
                    {
                        types = assembly.GetTypes();
                    }
                    catch (Exception ex)
                    {
                        EditorManager.IgnoreException(ex);
                    }
                    if (types == null)
                    {
                        continue;
                    }

                    foreach (Type type in types)
                    {
                        if (type.Name == classname && type.IsSubclassOf(typeof(ShapeLink)))
                        {
                            t = type;
                            break;
                        }
                    }
                    if (t != null)
                    {
                        break;
                    }
                }
                _cachedClassTypes[classname] = t; // can be null, which is also cached
            }

            if (t == null)
            {
                if (ThrowExceptions)
                {
                    throw new Exception("Unknown shape class '" + classname + "'");
                }
                return(null);
            }

            string moreFailInfo = "";

            try
            {
                object[] args = new object[3] {
                    ownerShape, name, primaryID
                };                                                     // always use this constructor
                ShapeLink newObject = Activator.CreateInstance(t, args) as ShapeLink;
                if (newObject == null)
                {
                    if (ThrowExceptions)
                    {
                        throw new Exception("Failed to create instance of class '" + classname + "'");
                    }
                    return(null);
                }
                return(newObject);
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, false);
                moreFailInfo = "\nDetailed: ";
                if (ex.InnerException != null)
                {
                    moreFailInfo += ex.InnerException.ToString();
                }
                else
                {
                    moreFailInfo += ex.Message;
                }
            }

            if (ThrowExceptions)
            {
                throw new Exception("Failed to create instance of class '" + classname + "'" + moreFailInfo);
            }
            return(null);
        }
예제 #18
0
        public bool RunLighting(bool bShowDlg, ZoneCollection zones, bool bIncludeMainZone)
        {
            bool bExportInfoOnly = false;

            if (bShowDlg)
            {
                VLuxLightingDlg dlg = new VLuxLightingDlg();
                dlg.Settings      = (EditorManager.Scene as EditorScene).Settings; // clone settings
                dlg.LightMainPart = bIncludeMainZone;

                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return(false);
                }
                // copy back settings:
                (EditorManager.Scene as EditorScene).Settings = dlg.Settings;

                if (!dlg.DoRelighting)
                {
                    return(true);
                }

                bExportInfoOnly = dlg.ExportInfoOnly;
            }

            // for progress bar
            int iRelevantCount = bIncludeMainZone ? 1 : 0;

            foreach (Zone zone in zones)
            {
                if (zone.RunLighting)
                {
                    iRelevantCount++;
                }
            }

            // nothing to light
            if (iRelevantCount == 0)
            {
                return(true);
            }

            Cursor oldCursor = EditorManager.MainForm.Cursor;

            EditorManager.MainForm.Cursor = Cursors.WaitCursor;

            VisionLightInfo info = new VisionLightInfo();

            EditorManager.Progress.ShowProgressDialog("Calculate static lighting");
            EditorManager.Progress.Percentage = 0.0f;
            float fPercentageStep = 100.0f / (float)iRelevantCount;

            // collect all infos
            foreach (Layer layer in EditorManager.Scene.Layers)
            {
                layer.GetStaticLightInfo(info);
            }

            // save all info files, for every zone and optionally main zone
            for (int i = 0; i <= zones.Count; i++)
            {
                Zone zone = null;
                if (i == zones.Count)
                {
                    if (!bIncludeMainZone)
                    {
                        continue;
                    }
                }
                else
                {
                    zone = zones[i];
                    if (!zone.RunLighting)
                    {
                        continue;
                    }
                }

                info.FilterByZone(zone);

                // save file that contains static lights
                string basename = "StaticLightingInfo";
                if (zone != null)
                {
                    zone.StaticLightInfo = (StaticLightInfo)info.Clone();
                    basename            += "_" + zone.ZoneName;
                }

                string absfilename = Path.Combine(EditorManager.Scene.LayerDirectoryName, basename + ".XML");
                if (!info.Save(absfilename))
                {
                    EditorManager.MainForm.Cursor = oldCursor;
                    EditorManager.Progress.HideProgressDialog();
                    return(false);
                }

                // also, collect static mesh information
                string meshRelFilename = Path.Combine(EditorManager.Scene.RelativeLayerDirectoryName, basename + ".temp");
                string meshAbsFilename = Path.Combine(EditorManager.Scene.LayerDirectoryName, basename + ".temp");
                EditorManager.EngineManager.CreateStaticLightingMeshes(meshAbsFilename, info);
                EditorManager.Progress.Percentage += fPercentageStep;
            }


            if (bExportInfoOnly)
            {
                EditorManager.MainForm.Cursor = oldCursor;
                EditorManager.Progress.HideProgressDialog();
                return(true);
            }

            // trigger the event (maybe another before info.Save?)
            EditorManager.TriggerSceneEvent(SceneEventArgs.Action.BeforeStaticLighting, true);

            // put together vLux parameter string
            string projectDir = EditorManager.Project.ProjectDir;

            if (projectDir.EndsWith(@"\"))
            {
                projectDir = projectDir.Remove(projectDir.Length - 1, 1);
            }

            // restart progress bar
            EditorManager.Progress.Percentage = 0.0f;

            // launch vLux n times
            bool bSuccess = true;

            for (int i = 0; i <= zones.Count; i++)
            {
                bool bVLuxSuccess = true;
                Zone zone         = null;
                if (i == zones.Count)
                {
                    if (!bIncludeMainZone)
                    {
                        continue;
                    }
                }
                else
                {
                    zone = zones[i];
                    if (!zone.Loaded || !zone.RunLighting)
                    {
                        continue;
                    }
                }

                // save file that contains static lights
                string basename = "StaticLightingInfo";
                if (zone != null)
                {
                    basename += "_" + zone.ZoneName;
                }

                string meshLitFilename = Path.Combine(EditorManager.Scene.LayerDirectoryName, basename + ".lit");



                // determine out filename (including relative path) and remove file extension
                string outFilename    = EditorManager.Scene.FileName;
                string outFilenameExt = Path.GetExtension(outFilename);
                if (outFilenameExt != null)
                {
                    outFilename = outFilename.Remove(outFilename.Length - outFilenameExt.Length, outFilenameExt.Length);
                }
                if (zone != null)
                {
                    outFilename += "_" + zone.ZoneName;
                }


                //set edit mode for relevant lighting files
                EditorManager.EngineManager.EditOrAddRCSLightingFiles(Path.Combine(projectDir, outFilename), zone, meshLitFilename, false);

                string paramStr = "\"\"";                                                      // no v3d (first parameter just empty quotes)

                paramStr += " -project \"" + projectDir + "\"";                                // the project folder
                paramStr += " -tempfolder \"" + EditorManager.Scene.LayerDirectoryName + "\""; // the relative folder name where the temp files are located
                paramStr += " -out \"" + outFilename + "\"";                                   // output filename
                if (zone != null)
                {
                    paramStr += " -zone \"" + zone.ZoneName + "\"";
                }
                //paramStr += " -title \"" + EditorApp.Scene.FileName + "\""; // no window title required in this mode
                paramStr += " -quiet -minimized";

                string lightingCfgFile = VLuxLightingTool.GetLightingCfgFile((EditorManager.Scene as EditorScene).Settings);

                ManagedBase.RCS.GetProvider().EditFile(lightingCfgFile);
                paramStr += " -config \"" + lightingCfgFile + "\"";

                try
                {
                    // create a batch file for stand-alone lighting
                    string     batchName = Path.Combine(EditorManager.Scene.LayerDirectoryName, "Relight_" + basename + ".bat");
                    TextWriter txt       = new StreamWriter(batchName);
                    txt.WriteLine("vLux.exe " + paramStr);
                    txt.Close();
                }
                catch (Exception ex)
                {
                    EditorManager.DumpException(ex);
                }


                try
                {
                    Process vLux = FileHelper.RunExternalTool("vLux", VLuxLightingDlg.vLuxEXEPath, paramStr, true);

                    if (vLux == null)
                    {
                        EditorManager.MainForm.Cursor = oldCursor;
                        EditorManager.Progress.HideProgressDialog();
                        return(false);
                    }

                    Console.WriteLine(vLux.StandardOutput.ReadToEnd());

                    vLux.WaitForExit();
                    int iExitCode = vLux.ExitCode; // can we do something with this?
                }
                catch (Exception ex)
                {
                    EditorManager.ShowMessageBox("vLux did not complete lighting. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    EditorManager.DumpException(ex);
                    bVLuxSuccess = false;
                }

                // wait until vLux is finished...

                EditorManager.Progress.Percentage += fPercentageStep;

                // reload the engine files
                if (bSuccess)
                {
                    bVLuxSuccess &= EditorManager.EngineManager.ReloadLightingFiles(outFilename, zone);
                    bVLuxSuccess &= EditorManager.EngineManager.ReloadStaticLightingMeshes(zone, meshLitFilename);

                    EditorManager.Scene.UpdateView(true);
                    EditorManager.Scene.UpdateView(true);

                    //add relevant lighting files to RCS
                    ManagedBase.RCS.GetProvider().AddFile(lightingCfgFile, false);
                    EditorManager.EngineManager.EditOrAddRCSLightingFiles(Path.Combine(projectDir, outFilename), zone, meshLitFilename, true);
                }


                System.Diagnostics.Debug.Assert(bVLuxSuccess, "lighting was not successful");
                bSuccess &= bVLuxSuccess;

                // trigger the event (maybe another before info.Save?)
                EditorManager.OnSceneEvent(new SceneEventArgs(SceneEventArgs.Action.AfterStaticLighting, bSuccess));
            }

            // Update all shader assignments
            IScene.SendShaderResourceChangedEvent(new EventArgs());

            // repaint
            EditorManager.Scene.UpdateView(false);

            EditorManager.MainForm.Cursor = oldCursor;
            EditorManager.Progress.HideProgressDialog();
            return(bSuccess);
        }
예제 #19
0
        public void TestLayerLocking()
        {
            try
            {
                const string TEST_SCENENAME  = "TestSceneLocking";
                const string TEST_SCENENAME2 = "TestSceneLocking_SaveAsTest";

                // Create a new project and scene
                TestManager.Helpers.CreateTestScene(TEST_SCENENAME);
                EditorProject project    = EditorApp.Project;
                IScene        scene      = project.Scene;
                Layer         firstLayer = scene.Layers[0];

                // First layer must be writeable
                Assert.IsTrue(firstLayer.OwnsLock);
                Assert.IsTrue(firstLayer.SaveToFile());

                // close scene
                string layerFilePath = firstLayer.AbsoluteLayerFilename;
                firstLayer = null;
                scene.Close();
                Assert.IsNull(project.Scene);

                // Get external lock on layer file
                IFileLock extFileLock = EditorManager.FileLockFactory.GetFileLock(layerFilePath);
                Assert.IsTrue(extFileLock.TryLock());

                // Reopen scene: must fail on saving layer (locked externally)
                Assert.IsTrue(project.OpenScene(TEST_SCENENAME));
                scene      = project.Scene;
                firstLayer = scene.Layers[0];
                Assert.IsFalse(firstLayer.OwnsLock);

                // Release lock: OwnsWriteLock state must get updated
                extFileLock.Unlock();
                // Give windows time to inform the file watcher
                System.Threading.Thread.Sleep(1000); TestManager.Helpers.ProcessEvents();
                // And then give the file watcher time to send his queued/delayed notification
                System.Threading.Thread.Sleep(1000); TestManager.Helpers.ProcessEvents();
                Assert.IsTrue(firstLayer.LockStatus == Layer.LayerLockStatus_e.NotLocked);

                // Let the scene lock the layer again: saving file must be successful
                firstLayer.TryLock(null, false);
                Assert.IsTrue(firstLayer.OwnsLock);
                Assert.IsTrue(firstLayer.SaveToFile());

                // Getting external lock must fail (since file is locked by scene)
                Assert.IsFalse(extFileLock.TryLock());

                // Rename the scene file
                Assert.IsTrue(scene.SaveAs(TEST_SCENENAME2));
                string renamedLayerFilePath = firstLayer.AbsoluteLayerFilename;
                Assert.IsTrue(renamedLayerFilePath != layerFilePath);

                // Getting external lock must work after scene-save-as
                Assert.IsTrue(firstLayer.OwnsLock);
                Assert.IsTrue(extFileLock.TryLock());
                extFileLock.Unlock();

                // Getting external lock on renamed file must fail
                IFileLock extFileLockRenamed = EditorManager.FileLockFactory.GetFileLock(renamedLayerFilePath);
                Assert.IsFalse(extFileLockRenamed.TryLock());

                // Verify that a scene can't be opened without closing it at first
                // (important, since we otherwise still have the lock on the old scene)
                Assert.IsFalse(project.OpenScene(TEST_SCENENAME));

                // Close scene
                scene.Close();
                Assert.IsNull(project.Scene);

                // Test correct behaviour for readonly layer files
                {
                    // Set the layer as readonly (as done by some version control systems
                    // when using exclusive locking)
                    File.SetAttributes(layerFilePath, File.GetAttributes(layerFilePath) | FileAttributes.ReadOnly);

                    // Reopen scene
                    Assert.IsTrue(project.OpenScene(TEST_SCENENAME));
                    scene      = project.Scene;
                    firstLayer = scene.Layers[0];

                    // Layer must not be locked due to being readonly.
                    Assert.IsFalse(firstLayer.OwnsLock);
                    Assert.AreEqual(Layer.LayerLockStatus_e.ReadOnly, firstLayer.LockStatus);

                    // Close scene
                    scene.Close();
                    Assert.IsNull(project.Scene);

                    // Set the layer as readonly (as done by some version control systems
                    // when using exclusive locking)
                    File.SetAttributes(layerFilePath, File.GetAttributes(layerFilePath) & (~FileAttributes.ReadOnly));
                }

                TestManager.Helpers.CloseTestProject();
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex);
                throw ex;
            }
        }
예제 #20
0
        void BatchSaveScreenShots()
        {
            ShapeCollection shapes = new ShapeCollection();

            // step #1: filter shapes
            {
                foreach (ShapeBase shape in this.ChildCollection)
                {
                    // filter?
                    shapes.Add(shape);
                }
                if (shapes.Count == 0)
                {
                    return;
                }
            }

            try
            {
                SetEditorCameraPosition();
                int   iResX = EditorManager.ActiveView.Size.Width;
                int   iResY = EditorManager.ActiveView.Size.Height;
                float fFOVX = 90;
                if (this.FOV > 0)
                {
                    fFOVX = this.FOV;
                }

                // step #2: prepare the target dir
                string folder = EditorManager.Project.MakeAbsolute(ShapeName);
                Directory.CreateDirectory(folder);

                // step #3: turn them all to invisible
                {
                    foreach (ShapeBase shape in shapes)
                    {
                        shape.SetVisible(false, true);
                    }
                }

                // step #4: render each and save a screenshot
                foreach (ShapeBase shape in shapes)
                {
                    shape.SetVisible(true, true);
                    string filename = Path.Combine(folder, shape.ShapeName + ".jpg");

                    // Render and save
                    EditorManager.ActiveView.UpdateView(true);
                    EditorManager.ActiveView.UpdateView(true);
                    EditorManager.EngineManager.SaveScreenShot(filename, iResX, iResY, fFOVX, 0.0f);
                    shape.SetVisible(false, true);
                }
            }
            catch (Exception ex)
            {
                EditorManager.DumpException(ex, true);
            }

            // #5: Cleanup
            {
                foreach (ShapeBase shape in shapes)
                {
                    shape.SetVisible(shape.FinalVisibleState, true);
                }
            }
        }