コード例 #1
0
        private void kryptonButtonDelete_Click(object sender, EventArgs e)
        {
            if (selectedPackage == null)
            {
                return;
            }
            if (!File.Exists(selectedPackage.FullFilePath))
            {
                return;
            }

            var template = Translate("Are you sure you want to delete \'{0}\'?");
            var text     = string.Format(template, selectedPackage.FullFilePath);

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.No)
            {
                return;
            }

            try
            {
                File.Delete(selectedPackage.FullFilePath);
            }
            catch (Exception e2)
            {
                EditorMessageBox.ShowWarning(e2.Message);
                return;
            }

            needUpdateList = true;
        }
コード例 #2
0
        private void ButtonClearAll_Click(ProcedureUI.Button sender)
        {
            if (EditorMessageBox.ShowQuestion(Translate("Delete all objects and child components?"), MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            var undoMultiAction = new UndoMultiAction();

            foreach (var groupOfObjects in GetObjects <Component_GroupOfObjects>())
            {
                var indexes = groupOfObjects.ObjectsGetAll();
                if (indexes.Count != 0)
                {
                    var action = new Component_GroupOfObjects_Editor.UndoActionCreateDelete(groupOfObjects, indexes.ToArray(), false, true);
                    undoMultiAction.AddAction(action);
                }

                var components = groupOfObjects.GetComponents();
                undoMultiAction.AddAction(new UndoActionComponentCreateDelete(Provider.DocumentWindow.Document, components, false));
            }

            if (undoMultiAction.Actions.Count != 0)
            {
                Provider.DocumentWindow.Document.CommitUndoAction(undoMultiAction);
            }
        }
コード例 #3
0
        private void ButtonClearObjects_Click(ProcedureUI.Button obj)
        {
            if (EditorMessageBox.ShowQuestion(Translate("Delete all objects of the element?"), MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            var undoMultiAction = new UndoMultiAction();

            foreach (var element in GetObjects <Component_GroupOfObjectsElement>())
            {
                var groupOfObjects = element.Parent as Component_GroupOfObjects;
                if (groupOfObjects != null)
                {
                    var indexes = element.GetObjectsOfElement();
                    if (indexes.Count != 0)
                    {
                        var action = new Component_GroupOfObjects_Editor.UndoActionCreateDelete(groupOfObjects, indexes.ToArray(), false, true);
                        undoMultiAction.AddAction(action);
                    }
                }
            }

            if (undoMultiAction.Actions.Count != 0)
            {
                Provider.DocumentWindow.Document.CommitUndoAction(undoMultiAction);
            }
        }
コード例 #4
0
        private void ButtonUpload_Click(ProcedureUI.Button sender)
        {
            if (EditorMessageBox.ShowQuestion("Upload selected products to the store?", EMessageBoxButtons.OKCancel) == EDialogResult.Cancel)
            {
                return;
            }

            var item = ScreenNotifications.ShowSticky("Processing...");

            try
            {
                foreach (var product in GetObjects <Component_StoreProduct>())
                {
                    if (!product.BuildArchive())
                    {
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Warning(e.Message);
                return;
            }
            finally
            {
                item.Close();
            }

            ScreenNotifications.Show("The product was prepared successfully.");
        }
コード例 #5
0
        private void kryptonNavigator1_TabClicked(object sender, ComponentFactory.Krypton.Navigator.KryptonPageEventArgs e)
        {
            //if( e.Item == kryptonPageSettings )
            //{
            //	Hide();
            //	EditorAPI.ShowProjectSettings();
            //	return;
            //}

            if (e.Item == kryptonPageBuild)
            {
                if (packagingNeedInit)
                {
                    PackagingInit();
                }
                return;
            }

            if (e.Item == kryptonPageExit)
            {
                if (EditorMessageBox.ShowQuestion(Translate("Exit the editor?"), EMessageBoxButtons.OKCancel) == EDialogResult.OK)
                {
                    EditorForm.Instance.Close();
                }
                return;
            }
        }
コード例 #6
0
        private void ButtonGenerate_Click(ProcedureUI.Button sender)
        {
            //!!!!support undo
            var text = "Generate world?\n\nUnable to undo the action.";

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.OKCancel) == EDialogResult.Cancel)
            {
                return;
            }

            var notification = ScreenNotifications.ShowSticky("Processing...");

            try
            {
                foreach (var generator in GetObjects <Component_WorldGenerator>())
                {
                    generator.Generate(Provider.DocumentWindow.Document);
                }

                //!!!!
                //clear undo history
                Provider.DocumentWindow.Document?.UndoSystem.Clear();
            }
            finally
            {
                notification.Close();
            }
        }
コード例 #7
0
        private void ButtonRandomizeGroups_Click(ProcedureUI.Button obj)
        {
            if (EditorMessageBox.ShowQuestion(Translate("Refresh surface groups randomly?"), MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            UpdateSurfaceElementVariations(true);
        }
コード例 #8
0
        private void ButtonResetColors_Click(ProcedureUI.Button obj)
        {
            if (EditorMessageBox.ShowQuestion(Translate("Reset color of the objects to \'1 1 1\'?"), MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            ResetColors();
        }
コード例 #9
0
        private unsafe void ButtonUpdateVariations_Click(ProcedureUI.Button sender)
        {
            if (EditorMessageBox.ShowQuestion(Translate("Update variations of the objects?"), MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            UpdateSurfaceElementVariations(false);
        }
コード例 #10
0
        void PackageCreate(bool run)
        {
            string folder = kryptonTextBoxPackageDestinationFolder.Text.Trim();

            if (string.IsNullOrEmpty(folder))
            {
                return;
            }

            //clear destination folder
            if (Directory.Exists(folder) && !IOUtility.IsDirectoryEmpty(folder))
            {
                var text = string.Format(Translate("Destination folder \'{0}\' is not empty. Clear folder and continue?"), folder);
                if (EditorMessageBox.ShowQuestion(text, MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }

                //delete
                try
                {
                    DirectoryInfo info = new DirectoryInfo(folder);
                    foreach (FileInfo file in info.GetFiles())
                    {
                        file.Delete();
                    }
                    foreach (DirectoryInfo directory in info.GetDirectories())
                    {
                        directory.Delete(true);
                    }
                }
                catch (Exception e)
                {
                    EditorMessageBox.ShowWarning(e.Message);
                    return;
                }
            }

            //start
            try
            {
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                packageBuildInstance = ProductBuildInstance.Start(GetSelectedBuildConfiguration(), folder, run);
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
                return;
            }

            PackagingUpdate();
        }
コード例 #11
0
        private void kryptonButtonDarkTheme_Click(object sender, EventArgs e)
        {
            if (EditorMessageBox.ShowQuestion("Set the dark theme and restart the editor to apply changes?", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            ProjectSettings.Get.Theme = Component_ProjectSettings.ThemeEnum.Dark;
            ProjectSettings.SaveToFileAndUpdate();
            EditorAPI.BeginRestartApplication();
        }
コード例 #12
0
        private void kryptonButtonDelete_Click(object sender, EventArgs e)
        {
            if (selectedPackage == null)
            {
                return;
            }

            bool installed = PackageManager.IsInstalled(selectedPackage.Identifier);

            //Uninstall & Delete
            var skipDeleteMessage = false;

            if (installed)
            {
                if (!TryUninstall())
                {
                    return;
                }
                skipDeleteMessage = true;
            }

            //check can delete
            if (!File.Exists(selectedPackage.FullFilePath))
            {
                return;
            }

            //ask to delete
            if (!skipDeleteMessage)
            {
                var template = Translate("Are you sure you want to delete \'{0}\'?");
                var text     = string.Format(template, selectedPackage.FullFilePath);
                if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.No)
                {
                    return;
                }
            }

            //delete
            try
            {
                File.Delete(selectedPackage.FullFilePath);
            }
            catch (Exception e2)
            {
                EditorMessageBox.ShowWarning(e2.Message);
                return;
            }

            needUpdateList = true;
        }
コード例 #13
0
        private void kryptonButtonNewCreate_Click(object sender, EventArgs e)
        {
            //!!!!

            string folder = kryptonTextBoxNewFolder.Text.Trim();

            if (string.IsNullOrEmpty(folder))
            {
                return;
            }

            try
            {
                while (Directory.Exists(folder) && !IOUtility.IsDirectoryEmpty(folder))
                {
                    var text   = string.Format(Translate("Destination folder \'{0}\' is not empty. Clear folder and continue?"), folder);
                    var result = EditorMessageBox.ShowQuestion(text, MessageBoxButtons.OKCancel);
                    if (result == DialogResult.Cancel)
                    {
                        return;
                    }

                    IOUtility.ClearDirectory(folder);
                }

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                creationInProgress             = true;
                progressBarNew.Visible         = true;
                kryptonButtonNewCancel.Visible = true;
                creationDirectory = folder;

                var tag = objectsBrowserNew.SelectedItems[0].Tag as string;
                creationTask = new Task(CreationFunction, tag);
                creationTask.Start();
            }
            catch (Exception ex)
            {
                EditorMessageBox.ShowWarning(ex.Message);
                return;
            }
        }
コード例 #14
0
ファイル: EditorForm.cs プロジェクト: yf885188/NeoAxisEngine
        //return: Cancel
        internal bool ShowDialogAndSaveDocument(DockWindow window)
        {
            var documentWindow = window as DocumentWindow;

            if (documentWindow == null)
            {
                return(false);
            }

            // If the page is dirty then we need to ask if it should be saved
            if (documentWindow.IsMainWindowInWorkspace && !documentWindow.IsDocumentSaved())
            {
                EDialogResult result;
                if (window.ShowDialogAndSaveDocumentAutoAnswer.HasValue)
                {
                    result = window.ShowDialogAndSaveDocumentAutoAnswer.Value;
                }
                else
                {
                    var text = EditorLocalization.Translate("General", "Save changes to the following files?") + "\n";
                    text  += "\n" + documentWindow.Document.Name;
                    result = EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNoCancel);
                }

                switch (result)
                {
                case EDialogResult.Cancel:

                    //!!!!тут?
                    EditorAPI.SetRestartApplication(false);

                    return(true);

                case EDialogResult.Yes:
                    //!!!!check error, return null
                    documentWindow.SaveDocument();
                    return(false);

                case EDialogResult.No:
                    return(false);
                }
            }

            return(false);
        }
コード例 #15
0
        private void buttonTypeSettingsDefaultValue_Click(object sender, EventArgs e)
        {
            var component = GetTypeSettingsComponent();

            if (component != null)
            {
                var text = EditorLocalization.Translate("SettingsWindow", "Reset to default?");
                if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                {
                    var oldValue = component.TypeSettingsPrivateObjects;

                    component.TypeSettingsPrivateObjects = null;

                    var undoItem = new UndoActionPropertiesChange.Item(component, (Metadata.Property)MetadataManager.GetTypeOfNetType(typeof(Component)).MetadataGetMemberBySignature("property:TypeSettingsPrivateObjects"), oldValue, null);
                    ObjectSettingsWindow.Document.UndoSystem.CommitAction(new UndoActionPropertiesChange(undoItem));
                    ObjectSettingsWindow.Document.Modified = true;
                }
            }
        }
コード例 #16
0
        private void KryptonButtonReset_Click(object sender, EventArgs e)
        {
            var settings = GetSettings();

            if (settings == null)
            {
                return;
            }

            if (EditorMessageBox.ShowQuestion(Translate("Reset the configuration of shortcuts to default?"), EMessageBoxButtons.YesNo) == EDialogResult.No)
            {
                return;
            }

            settings.ResetToDefault();
            if (Owner?.DocumentWindow?.Document != null)
            {
                Owner.DocumentWindow.Document.Modified = true;
            }
        }
コード例 #17
0
ファイル: EditorForm.cs プロジェクト: zwiglm/NeoAxisEngine
        // сохранить только выбранные окна. не обязательно все. например может использоваться
        // из метода "Закрыть все окна кроме текущего".
        internal bool?ShowDialogAndSaveDocuments(IEnumerable <DockWindow> windows)
        {
            var unsavedDocs = new List <DocumentInstance>();

            foreach (var wnd in windows)
            {
                if (wnd is IDocumentWindow docWnd && !docWnd.IsDocumentSaved())
                {
                    unsavedDocs.Add(docWnd.Document);
                }
            }

            if (unsavedDocs.Count == 0)
            {
                return(false);
            }

            var text = EditorLocalization.Translate("General", "Save changes to the following files?") + "\n";

            foreach (var doc in unsavedDocs)
            {
                text += "\n" + doc.Name;
            }

            switch (EditorMessageBox.ShowQuestion(text, MessageBoxButtons.YesNoCancel))
            {
            case DialogResult.Cancel:
                return(null);

            case DialogResult.Yes:
                //!!!!check error, return null
                unsavedDocs.ForEach(doc => doc.Save());
                return(true);

            case DialogResult.No:
                return(false);
            }

            return(false);
        }
コード例 #18
0
        public virtual bool TryDeleteObjects()
        {
            //!!!!!игнорить выделенные-вложенные. где еще так

            if (!CanDeleteObjects(out var objectsToDelete))
            {
                return(false);
            }

            string text;

            if (objectsToDelete.Count == 1)
            {
                string template = EditorLocalization.Translate("DocumentWindow", "Are you sure you want to delete \'{0}\'?");
                var    name     = objectsToDelete[0].ToString();
                text = string.Format(template, name);
            }
            else
            {
                string template = EditorLocalization.Translate("DocumentWindow", "Are you sure you want to delete selected objects?");
                text = string.Format(template, objectsToDelete.Count);
            }

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.No)
            {
                return(false);
            }

            //!!!!может сцену выбрать? везде так
            //clear selected objects
            SelectObjects(null);

            //add to undo with deletion
            var action = new UndoActionComponentCreateDelete(Document, objectsToDelete.Cast <Component>().ToArray(), false);

            Document.UndoSystem.CommitAction(action);
            Document.Modified = true;

            return(true);
        }
コード例 #19
0
        private void ButtonResizeMasks_Click(ProcedureUI.Button sender)
        {
            var terrain = GetTerrain();

            if (terrain == null)
            {
                return;
            }

            var layers = GetLayersToResizeMask(terrain);

            if (layers.Count == 0)
            {
                return;
            }

            var text = string.Format(EditorLocalization.Translate("Terrain", "Resize masks of selected layers to {0}x{0}?"), terrain.GetPaintMaskSizeInteger());

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.OKCancel) == EDialogResult.OK)
            {
                var undoMultiAction = new UndoMultiAction();

                foreach (var layer in layers)
                {
                    var oldValue = layer.Mask;

                    layer.Mask = Component_PaintLayer.ResizeMask(layer.Mask, terrain.GetPaintMaskSizeInteger());

                    var property = (Metadata.Property)layer.MetadataGetMemberBySignature("property:Mask");
                    var undoItem = new UndoActionPropertiesChange.Item(layer, property, oldValue);
                    undoMultiAction.AddAction(new UndoActionPropertiesChange(undoItem));
                }

                if (undoMultiAction.Actions.Count != 0)
                {
                    Provider.DocumentWindow.Document.CommitUndoAction(undoMultiAction);
                }
            }
        }
コード例 #20
0
        private void ButtonBakeIntoMesh_Click(ProcedureUI.Button sender)
        {
            var document        = Provider.DocumentWindow.Document;
            var undoMultiAction = new UndoMultiAction();

            var modifiers = GetMeshModifiers();

            if (modifiers.Length != 0)
            {
                string text;
                if (modifiers.Length > 1)
                {
                    text = Translate("Bake selected geometries into the mesh?");
                }
                else
                {
                    text = Translate("Bake selected geometry into the mesh?");
                }

                if (EditorMessageBox.ShowQuestion(text, System.Windows.Forms.MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    //bake
                    foreach (var modifier in modifiers)
                    {
                        modifier.BakeIntoMesh(document, undoMultiAction);
                    }

                    //delete and add to undo
                    undoMultiAction.AddAction(new UndoActionComponentCreateDelete(document, modifiers, false));

                    if (undoMultiAction.Actions.Count != 0)
                    {
                        document.CommitUndoAction(undoMultiAction);
                    }
                }
            }
        }
コード例 #21
0
        private void kryptonButtonInstall_Click(object sender, EventArgs e)
        {
            var info = PackageManager.ReadPackageArchiveInfo(selectedPackage.FullFilePath, out var error);

            if (info == null)
            {
                return;
            }

            var filesToCopy = new List <string>();

            foreach (var file in info.Files)
            {
                var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file);
                filesToCopy.Add(fullName);
            }

            var text = string.Format(Translate("Install {0}?\n\n{1} files will created."), selectedPackage.GetDisplayName(), filesToCopy.Count);

            //var text = string.Format( Translate( "Install {0}?\r\n\r\n{1} files will created." ), selectedPackage.Name, filesToCopy.Count );
            //var text = $"Install {selectedPackage.Name}?\r\n\r\n{filesToCopy.Count} files will created.";

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) != EDialogResult.Yes)
            {
                return;
            }

            var notification = ScreenNotifications.ShowSticky("Installing the package...");

            try
            {
                using (var archive = ZipFile.OpenRead(selectedPackage.FullFilePath))
                {
                    foreach (var entry in archive.Entries)
                    {
                        var  fileName  = entry.FullName;
                        bool directory = fileName[fileName.Length - 1] == '/';
                        if (fileName != "Package.info" && !directory)
                        {
                            var fullPath = Path.Combine(VirtualFileSystem.Directories.Project, fileName);

                            var directoryName = Path.GetDirectoryName(fullPath);
                            if (!Directory.Exists(directoryName))
                            {
                                Directory.CreateDirectory(directoryName);
                            }

                            entry.ExtractToFile(fullPath, true);
                        }
                    }
                }

                PackageManager.ChangeInstalledState(selectedPackage.Name, true);
            }
            catch (Exception e2)
            {
                EditorMessageBox.ShowWarning(e2.Message);
                return;
            }
            finally
            {
                notification.Close();
            }

            if (!string.IsNullOrEmpty(info.AddCSharpFilesToProject))
            {
                var toAdd = new ESet <string>();

                var path = Path.Combine(VirtualFileSystem.Directories.Assets, info.AddCSharpFilesToProject);
                if (Directory.Exists(path))
                {
                    var fullPaths = CSharpProjectFileUtility.GetProjectFileCSFiles(false, true);
                    var files     = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        if (!fullPaths.Contains(file))
                        {
                            toAdd.AddWithCheckAlreadyContained(file);
                        }
                    }
                }

                //	if( !fileItem.IsDirectory && Path.GetExtension( fileItem.FullPath ).ToLower() == ".cs" )
                //	{
                //		bool added = CSharpProjectFileUtility.GetProjectFileCSFiles( false, true ).Contains( fileItem.FullPath );
                //		if( !added )
                //			toAdd.Add( fileItem.FullPath );
                //	}

                if (toAdd.Count != 0)
                {
                    if (CSharpProjectFileUtility.UpdateProjectFile(toAdd, null, out var error2))
                    {
                        if (toAdd.Count > 1)
                        {
                            Log.Info(EditorLocalization.Translate("General", "Items have been added to the Project.csproj."));
                        }
                        else
                        {
                            Log.Info(EditorLocalization.Translate("General", "The item has been added to the Project.csproj."));
                        }
                    }
                    else
                    {
                        Log.Warning(error2);
                    }
                }
            }

            needUpdateList = true;

            if (info.MustRestart)
            {
                ShowRestartLabel();
            }

            if (!string.IsNullOrEmpty(info.OpenAfterInstall))
            {
                var realFileName = VirtualPathUtility.GetRealPathByVirtual(info.OpenAfterInstall);

                if (info.MustRestart)
                {
                    EditorSettingsSerialization.OpenFileAtStartup = realFileName;
                }
                else
                {
                    EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { realFileName }, Directory.Exists(realFileName));
                    EditorAPI.OpenFileAsDocument(realFileName, true, true);
                }
            }

            ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully installed."));

            //restart application
            if (info.MustRestart)
            {
                var text2 = EditorLocalization.Translate("General", "To apply changes need restart the editor. Restart?");
                if (EditorMessageBox.ShowQuestion(text2, EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                {
                    EditorAPI.BeginRestartApplication();
                }
            }
        }
コード例 #22
0
        void RenderByEngineRender()
        {
            var renderToFile = RenderToFile;
            var scene        = renderToFile.ParentRoot as Component_Scene;

            //get camera
            var camera = renderToFile.Camera.Value;

            if (camera == null)
            {
                camera = scene.Mode.Value == Component_Scene.ModeEnum._2D ? scene.CameraEditor2D : scene.CameraEditor;
            }
            if (camera == null)
            {
                EditorMessageBox.ShowWarning("Camera is not specified.");
                return;
            }

            var destRealFileName = renderToFile.OutputFileName.Value.Trim();

            if (!Path.IsPathRooted(destRealFileName) && !string.IsNullOrEmpty(destRealFileName))
            {
                destRealFileName = VirtualPathUtility.GetRealPathByVirtual(destRealFileName);
            }

            if (string.IsNullOrEmpty(destRealFileName))
            {
                var dialog = new SaveFileDialog();
                //dialog.InitialDirectory = Path.GetDirectoryName( RealFileName );
                if (renderToFile.Mode.Value == Component_RenderToFile.ModeEnum.Material)
                {
                    dialog.FileName = "Output.material";
                    dialog.Filter   = "Material files (*.material)|*.material";
                }
                else
                {
                    dialog.FileName = "Output.png";
                    dialog.Filter   = "PNG files (*.png)|*.png";
                }
                dialog.RestoreDirectory = true;
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                destRealFileName = dialog.FileName;
            }
            else
            {
                //!!!!material mode

                //file already exists
                if (File.Exists(destRealFileName))
                {
                    var text = $"The file with name \'{destRealFileName}\' is already exists. Overwrite?";
                    if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.OKCancel) == EDialogResult.Cancel)
                    {
                        return;
                    }
                }
            }

            var item = ScreenNotifications.ShowSticky("Processing...");

            try
            {
                if (renderToFile.Mode.Value == Component_RenderToFile.ModeEnum.Material)
                {
                    RenderMaterial(camera, destRealFileName);
                }
                else
                {
                    RenderScreenshot(camera, destRealFileName);
                }
            }
            finally
            {
                item.Close();
            }
        }
コード例 #23
0
        public virtual bool Creation(NewObjectCell.ObjectCreationContext context)
        {
            if (Window.IsFileCreation() && CreateCSharpClass)
            {
                context.disableFileCreation = true;

                GetCreateCSharpClassInfo(out var csharpRealFileName, out var csharpClassName, out var csharpClassNameWithoutNamespace);

                try
                {
                    //main file
                    {
                        string className = csharpClassName;
                        //string className = CreateCSharpClass ? csharpClassName : Window.SelectedType.Name;
                        var text = ".component " + className + "\r\n{\r\n}";

                        File.WriteAllText(context.fileCreationRealFileName, text);
                    }

                    //cs file
                    //if( CreateCSharpClass )
                    {
                        string code = @"using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using NeoAxis;

namespace Project
{
	public class {Name} : {Base}
	{
	}
}";

                        code = code.Replace("{Name}", csharpClassNameWithoutNamespace);
                        code = code.Replace("{Base}", Window.SelectedType.Name);

                        File.WriteAllText(csharpRealFileName, code);
                    }
                }
                catch (Exception e)
                {
                    EditorMessageBox.ShowWarning(e.Message);
                    //Log.Warning( e.Message );
                    return(false);
                }

                //if( CreateCSharpClass )
                {
                    //add to Project.csproj
                    {
                        var toAdd = new List <string>();

                        var fileName = Path.Combine("Assets", VirtualPathUtility.GetVirtualPathByReal(csharpRealFileName));
                        toAdd.Add(fileName);

                        if (CSharpProjectFileUtility.UpdateProjectFile(toAdd, null, out var error))
                        {
                            if (toAdd.Count > 1)
                            {
                                Log.Info(EditorLocalization.Translate("General", "Items have been added to the Project.csproj."));
                            }
                            else
                            {
                                Log.Info(EditorLocalization.Translate("General", "The item has been added to the Project.csproj."));
                            }
                        }
                        else
                        {
                            EditorMessageBox.ShowWarning(error);
                            //Log.Warning( error );
                            return(false);
                        }
                    }

                    Window.DisableUnableToCreateReason = true;

                    //restart application
                    var text = EditorLocalization.Translate("General", "To apply changes need restart the editor. Restart?\r\n\r\nThe editor must be restarted to compile and enable a new created C# class.");
                    if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                    {
                        EditorAPI.BeginRestartApplication();
                    }

                    Window.DisableUnableToCreateReason = false;
                }
            }

            return(true);
        }
コード例 #24
0
        public override void Register()
        {
            //Attach second selected to first
            {
                const string transformOffsetName = "Attach Transform Offset";

                var a = new EditorAction();
                a.Name        = "Attach Second to First";
                a.Description = "Attaches the second, third and next selected objects to the first selected object.";
                a.ImageSmall  = Properties.Resources.Attach_16;
                a.ImageBig    = Properties.Resources.Attach_32;
                a.RibbonText  = ("Attach", "");

                //!!!!выключить где-то?
                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length > 1)
                        {
                            var first = selectedObjects[0] as Component_ObjectInSpace;
                            if (first != null)
                            {
                                for (int n = 1; n < selectedObjects.Length; n++)
                                {
                                    var second = selectedObjects[n] as Component_ObjectInSpace;
                                    if (second != null)
                                    {
                                        var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform(second);
                                        if (objectToTransform != null)
                                        {
                                            second = objectToTransform;
                                        }

                                        //!!!!проверять? second.GetComponentByName( transformOffsetName ) as Component_TransformOffset == null
                                        if (!second.Transform.ReferenceSpecified && second.GetComponent(transformOffsetName) as Component_TransformOffset == null)
                                        {
                                            context.Enabled = true;
                                        }
                                    }

                                    ////!!!!проверять? second.GetComponentByName( transformOffsetName ) as Component_TransformOffset == null
                                    //if( second != null && !second.Transform.ReferenceSpecified && second.GetComponent( transformOffsetName ) as Component_TransformOffset == null )
                                    //{
                                    //	context.Enabled = true;
                                    //}
                                }
                            }
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;

                    var undoMultiAction = new UndoMultiAction();

                    var first = selectedObjects[0] as Component_ObjectInSpace;
                    for (int n = 1; n < selectedObjects.Length; n++)
                    {
                        var second = selectedObjects[n] as Component_ObjectInSpace;
                        if (second != null)
                        {
                            Component_ObjectInSpace_Utility.Attach(first, second, context.ObjectsInFocus.DocumentWindow.Document, undoMultiAction);
                        }
                    }

                    context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction(undoMultiAction);
                    context.ObjectsInFocus.DocumentWindow.Document.Modified = true;
                    ScreenNotifications.Show(Translate("The object was attached to another object."));

                    //var undoActions = new List<UndoSystem.Action>();

                    //var first = selectedObjects[ 0 ] as Component_ObjectInSpace;
                    //for( int n = 1; n < selectedObjects.Length; n++ )
                    //{
                    //	var second = selectedObjects[ n ] as Component_ObjectInSpace;
                    //	if( second != null )
                    //	{
                    //		var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform( second );
                    //		if( objectToTransform != null )
                    //			second = objectToTransform;

                    //		//create _TransformOffset
                    //		Component_TransformOffset transformOffset;
                    //		{
                    //			transformOffset = second.CreateComponent<Component_TransformOffset>( -1, false );
                    //			transformOffset.Name = transformOffsetName;
                    //			transformOffset.Source = ReferenceUtility.MakeReference<Transform>( null, ReferenceUtility.CalculateThisReference( transformOffset, first, "Transform" ) );

                    //			try
                    //			{
                    //				var f = first.Transform.Value;
                    //				var s = second.Transform.Value;
                    //				var offset = f.ToMatrix4().GetInverse() * s.ToMatrix4();
                    //				offset.Decompose( out Vector3 pos, out Quaternion rot, out Vector3 scl );

                    //				transformOffset.PositionOffset = pos;
                    //				transformOffset.RotationOffset = rot;
                    //				transformOffset.ScaleOffset = scl;
                    //				//transformOffset.Matrix = offset;

                    //				//var offset = new Mat4( s.Rotation.ToMat3(), s.Position ) * new Mat4( f.Rotation.ToMat3(), f.Position ).GetInverse();
                    //				//var f = first.Transform.Value;
                    //				//var s = second.Transform.Value;
                    //				//var offset = new Mat4( s.Rotation.ToMat3(), s.Position ) * new Mat4( f.Rotation.ToMat3(), f.Position ).GetInverse();
                    //				////var offset = second.Transform.Value.ToMat4() * first.Transform.Value.ToMat4().GetInverse();
                    //				//offset.Decompose( out Vec3 pos, out Quat rot, out Vec3 scl );

                    //				//transformOffset.PositionOffset = pos / f.Scale;// / s.Scale;
                    //				//transformOffset.RotationOffset = rot;

                    //				//transformOffset.ScaleOffset = s.Scale / f.Scale;
                    //				////transformOffset.ScaleOffset = scl;

                    //			}
                    //			catch { }

                    //			transformOffset.Enabled = true;

                    //			undoActions.Add( new UndoActionComponentCreateDelete( context.ObjectsInFocus.DocumentWindow.Document, new Component[] { transformOffset }, true ) );
                    //		}

                    //		//change Transform
                    //		{
                    //			//undo action
                    //			var property = (Metadata.Property)second.MetadataGetMemberBySignature( "property:Transform" );
                    //			var undoItem = new UndoActionPropertiesChange.Item( second, property, second.Transform, new object[ 0 ] );
                    //			undoActions.Add( new UndoActionPropertiesChange( new UndoActionPropertiesChange.Item[] { undoItem } ) );

                    //			//configure reference
                    //			second.Transform = ReferenceUtility.MakeReference<Transform>( null, ReferenceUtility.CalculateThisReference( second, transformOffset, "Result" ) );
                    //		}
                    //	}
                    //}

                    //context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction( new UndoMultiAction( undoActions ) );
                    //context.ObjectsInFocus.DocumentWindow.Document.Modified = true;
                    //ScreenNotifications.Show( "The object was attached to another object." );
                };

                EditorActions.Register(a);
            }

            //Detach from Another Object
            {
                //const string transformOffsetName = "Attach Transform Offset";

                var a = new EditorAction();
                a.Name        = "Detach from Another Object";
                a.Description = "Detaches selected objects from another object.";
                a.ImageSmall  = Properties.Resources.Detach_16;
                a.ImageBig    = Properties.Resources.Detach_32;
                a.RibbonText  = ("Detach", "");

                //!!!!выключить где-то?
                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length != 0 && Array.TrueForAll(selectedObjects, obj => obj is Component_ObjectInSpace))
                        {
                            foreach (Component_ObjectInSpace objectInSpace in selectedObjects)
                            {
                                var objectToDetach = Component_ObjectInSpace_Utility.FindObjectToDetach(objectInSpace);
                                if (objectToDetach != null)
                                {
                                    context.Enabled = true;
                                    break;
                                }

                                //var objectInSpace = objectInSpace2;
                                //var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform( objectInSpace );
                                //if( objectToTransform != null )
                                //	objectInSpace = objectToTransform;

                                //if( objectInSpace.GetComponent( transformOffsetName ) as Component_TransformOffset != null )
                                //{
                                //	context.Enabled = true;
                                //	break;
                                //}
                            }

                            //context.Enabled = Array.Exists( selectedObjects,
                            //	obj => ( (Component)obj ).GetComponent( transformOffsetName ) as Component_TransformOffset != null );
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    if (EditorMessageBox.ShowQuestion(Translate("Detach from another object?"), EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                    {
                        var undoMultiAction = new UndoMultiAction();

                        foreach (Component_ObjectInSpace objectInSpace in context.ObjectsInFocus.Objects)
                        {
                            var objectToDetach = Component_ObjectInSpace_Utility.FindObjectToDetach(objectInSpace);
                            if (objectToDetach != null)
                            {
                                Component_ObjectInSpace_Utility.Detach(objectToDetach, context.ObjectsInFocus.DocumentWindow.Document, undoMultiAction);
                            }
                        }

                        if (undoMultiAction.Actions.Count != 0)
                        {
                            context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction(undoMultiAction);
                            context.ObjectsInFocus.DocumentWindow.Document.Modified = true;
                            ScreenNotifications.Show(Translate("The object was detached from another object."));
                        }


                        //var undoActions = new List<UndoSystem.Action>();

                        //foreach( Component_ObjectInSpace objectInSpace2 in context.ObjectsInFocus.Objects )
                        //{
                        //	var objectInSpace = objectInSpace2;
                        //	var objectToTransform = Component_ObjectInSpace_Utility.CalculateObjectToTransform( objectInSpace );
                        //	if( objectToTransform != null )
                        //		objectInSpace = objectToTransform;

                        //	var transformOffset = objectInSpace.GetComponent( transformOffsetName ) as Component_TransformOffset;
                        //	if( transformOffset != null )
                        //	{
                        //		//change Transform
                        //		{
                        //			//undo action
                        //			var property = (Metadata.Property)objectInSpace.MetadataGetMemberBySignature( "property:Transform" );
                        //			var undoItem = new UndoActionPropertiesChange.Item( objectInSpace, property, objectInSpace.Transform, new object[ 0 ] );
                        //			undoActions.Add( new UndoActionPropertiesChange( new UndoActionPropertiesChange.Item[] { undoItem } ) );

                        //			//remove reference
                        //			objectInSpace.Transform = new Reference<Transform>( objectInSpace.Transform, "" );
                        //		}

                        //		//delete
                        //		undoActions.Add( new UndoActionComponentCreateDelete( context.ObjectsInFocus.DocumentWindow.Document, new Component[] { transformOffset }, false ) );
                        //	}
                        //}

                        //if( undoActions.Count != 0 )
                        //{
                        //	context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction( new UndoMultiAction( undoActions ) );
                        //	context.ObjectsInFocus.DocumentWindow.Document.Modified = true;
                        //	ScreenNotifications.Show( "The object was detached from another object." );
                        //}
                    }
                };

                EditorActions.Register(a);
            }
        }
コード例 #25
0
        public override void Register()
        {
            //Add Collision
            {
                const string bodyName = "Collision Body";

                var a = new EditorAction();
                a.Name        = "Add Collision";
                a.Description = "Adds a collision body to selected objects.";
                a.ImageSmall  = Properties.Resources.Add_16;
                a.ImageBig    = Properties.Resources.MeshCollision_32;
                a.ActionType  = EditorAction.ActionTypeEnum.DropDown;
                a.QatSupport  = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length != 0 && Array.TrueForAll(selectedObjects, obj => obj is Component_MeshInSpace))
                        {
                            context.Enabled = Array.Exists(selectedObjects, delegate(object obj)
                            {
                                var c = ((Component)obj).GetComponent(bodyName);
                                if (c != null)
                                {
                                    if (c is Component_RigidBody)
                                    {
                                        return(false);
                                    }
                                    if (c is Component_RigidBody2D)
                                    {
                                        return(false);
                                    }
                                }
                                return(true);
                            });
                        }

                        a.DropDownContextMenu.Tag = (context.ObjectsInFocus.DocumentWindow.Document, selectedObjects);
                    }
                };

                //context menu
                {
                    a.DropDownContextMenu = new KryptonContextMenu();

                    a.DropDownContextMenu.Opening += delegate(object sender, CancelEventArgs e)
                    {
                        var menu  = (KryptonContextMenu)sender;
                        var tuple = ((DocumentInstance, object[]))menu.Tag;

                        //"Collision Body of the Mesh"
                        {
                            var items2 = (KryptonContextMenuItems)menu.Items[0];
                            var item2  = (KryptonContextMenuItem)items2.Items[0];

                            bool enabled = false;

                            foreach (var obj in tuple.Item2)
                            {
                                var meshInSpace = obj as Component_MeshInSpace;
                                if (meshInSpace != null)
                                {
                                    Component_RigidBody collisionDefinition = null;
                                    {
                                        var mesh = meshInSpace.Mesh.Value;
                                        if (mesh != null)
                                        {
                                            collisionDefinition = mesh.GetComponent("Collision Definition") as Component_RigidBody;
                                        }
                                    }

                                    if (collisionDefinition != null)
                                    {
                                        enabled = true;
                                    }
                                }
                            }

                            item2.Enabled = enabled;
                        }
                    };

                    EventHandler clickHandler = delegate(object s, EventArgs e2)
                    {
                        var item          = (KryptonContextMenuItem)s;
                        var itemTag       = ((KryptonContextMenu, string))item.Tag;
                        var menu          = itemTag.Item1;
                        var collisionName = itemTag.Item2;

                        var menuTag         = ((DocumentInstance, object[]))menu.Tag;
                        var document        = menuTag.Item1;
                        var selectedObjects = menuTag.Item2;

                        List <UndoSystem.Action> undoActions = new List <UndoSystem.Action>();

                        foreach (var obj in selectedObjects)
                        {
                            if (obj is Component_MeshInSpace meshInSpace && meshInSpace.GetComponent(bodyName) as Component_RigidBody == null && meshInSpace.GetComponent(bodyName) as Component_RigidBody2D == null)
                            {
                                var mesh = meshInSpace.MeshOutput;
                                if (mesh == null)
                                {
                                    continue;
                                }

                                Component body = null;
                                bool      skip = false;

                                if (collisionName == "Use Collision of the Mesh")
                                {
                                    var collisionDefinition = mesh.GetComponent("Collision Definition") as Component_RigidBody;
                                    if (collisionDefinition != null)
                                    {
                                        var body2 = (Component_RigidBody)collisionDefinition.Clone();
                                        body             = body2;
                                        body2.Enabled    = false;
                                        body2.Name       = bodyName;
                                        body2.MotionType = Component_RigidBody.MotionTypeEnum.Static;
                                        body2.Transform  = meshInSpace.Transform;

                                        meshInSpace.AddComponent(body2);
                                    }
                                    else
                                    {
                                        skip = true;
                                    }
                                }
                                else
                                {
                                    Component_RigidBody CreateRigidBody()
                                    {
                                        var body2 = meshInSpace.CreateComponent <Component_RigidBody>(enabled: false);

                                        body2.Name      = bodyName;
                                        body2.Transform = meshInSpace.Transform;
                                        return(body2);
                                    }

                                    Component_RigidBody2D CreateRigidBody2D()
                                    {
                                        var body2 = meshInSpace.CreateComponent <Component_RigidBody2D>(enabled: false);

                                        body2.Name      = bodyName;
                                        body2.Transform = meshInSpace.Transform;
                                        return(body2);
                                    }

                                    switch (collisionName)
                                    {
                                    case "Box":
                                    {
                                        body = CreateRigidBody();
                                        var shape  = body.CreateComponent <Component_CollisionShape_Box>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);
                                        shape.Dimensions = bounds.GetSize();
                                    }
                                    break;

                                    case "Sphere":
                                    {
                                        body = CreateRigidBody();
                                        var shape  = body.CreateComponent <Component_CollisionShape_Sphere>();
                                        var sphere = mesh.Result.SpaceBounds.CalculatedBoundingSphere;
                                        shape.TransformRelativeToParent = new Transform(sphere.Origin, Quaternion.Identity);
                                        shape.Radius = sphere.Radius;
                                    }
                                    break;

                                    case "Capsule":
                                    {
                                        body = CreateRigidBody();
                                        var shape  = body.CreateComponent <Component_CollisionShape_Capsule>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);
                                        shape.Radius = Math.Max(bounds.GetSize().X, bounds.GetSize().Y) / 2;
                                        shape.Height = Math.Max(bounds.GetSize().Z - shape.Radius * 2, 0);
                                    }
                                    break;

                                    case "Cylinder":
                                    {
                                        body = CreateRigidBody();
                                        var shape  = body.CreateComponent <Component_CollisionShape_Cylinder>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);
                                        shape.Radius = Math.Max(bounds.GetSize().X, bounds.GetSize().Y) / 2;
                                        shape.Height = bounds.GetSize().Z;
                                    }
                                    break;

                                    case "Convex":
                                    {
                                        body = CreateRigidBody();
                                        var shape = body.CreateComponent <Component_CollisionShape_Mesh>();
                                        shape.ShapeType = Component_CollisionShape_Mesh.ShapeTypeEnum.Convex;
                                        shape.Mesh      = ReferenceUtility.MakeThisReference(shape, meshInSpace, "Mesh");
                                    }
                                    break;

                                    case "Convex Decomposition":
                                    {
                                        body = CreateRigidBody();

                                        var settings = new ConvexDecomposition.Settings();

                                        var form = new SpecifyParametersForm("Convex Decomposition", settings);
                                        form.CheckHandler = delegate(ref string error2)
                                        {
                                            return(true);
                                        };
                                        if (form.ShowDialog() != DialogResult.OK)
                                        {
                                            skip = true;
                                        }
                                        else
                                        {
                                            var clusters = ConvexDecomposition.Decompose(mesh.Result.ExtractedVerticesPositions, mesh.Result.ExtractedIndices, settings);

                                            if (clusters == null)
                                            {
                                                Log.Warning("Unable to decompose.");
                                                skip = true;
                                            }
                                            else
                                            {
                                                foreach (var cluster in clusters)
                                                {
                                                    var shape = body.CreateComponent <Component_CollisionShape_Mesh>();
                                                    shape.Vertices  = cluster.Vertices;
                                                    shape.Indices   = cluster.Indices;
                                                    shape.ShapeType = Component_CollisionShape_Mesh.ShapeTypeEnum.Convex;
                                                }
                                            }
                                        }
                                    }
                                    break;

                                    case "Mesh":
                                    {
                                        body = CreateRigidBody();
                                        var shape = body.CreateComponent <Component_CollisionShape_Mesh>();
                                        shape.Mesh = ReferenceUtility.MakeThisReference(shape, meshInSpace, "Mesh");
                                    }
                                    break;

                                    case "Box 2D":
                                    {
                                        body = CreateRigidBody2D();
                                        var shape  = body.CreateComponent <Component_CollisionShape2D_Box>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);
                                        shape.Dimensions = bounds.GetSize().ToVector2();
                                    }
                                    break;

                                    case "Circle 2D":
                                    {
                                        body = CreateRigidBody2D();
                                        var shape  = body.CreateComponent <Component_CollisionShape2D_Ellipse>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);
                                        var size = bounds.GetSize().ToVector2().MaxComponent();
                                        shape.Dimensions = new Vector2(size, size);
                                    }
                                    break;

                                    case "Ellipse 2D":
                                    {
                                        body = CreateRigidBody2D();
                                        var shape  = body.CreateComponent <Component_CollisionShape2D_Ellipse>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);
                                        shape.Dimensions = bounds.GetSize().ToVector2();
                                    }
                                    break;

                                    case "Capsule 2D":
                                    {
                                        body = CreateRigidBody2D();
                                        var shape  = body.CreateComponent <Component_CollisionShape2D_Capsule>();
                                        var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        shape.TransformRelativeToParent = new Transform(bounds.GetCenter(), Quaternion.Identity);

                                        var size = bounds.GetSize();

                                        if (size.X > size.Y)
                                        {
                                            shape.Axis   = 0;
                                            shape.Radius = size.Y / 2;
                                            shape.Height = Math.Max(size.X - shape.Radius * 2, 0);
                                        }
                                        else
                                        {
                                            shape.Axis   = 0;
                                            shape.Radius = size.X / 2;
                                            shape.Height = Math.Max(size.Y - shape.Radius * 2, 0);
                                        }
                                    }
                                    break;

                                    case "Convex 2D":
                                    {
                                        body = CreateRigidBody2D();

                                        var meshPoints = new Vector2[mesh.Result.ExtractedVerticesPositions.Length];
                                        for (int n = 0; n < meshPoints.Length; n++)
                                        {
                                            meshPoints[n] = mesh.Result.ExtractedVerticesPositions[n].ToVector2();
                                        }
                                        var points = MathAlgorithms.GetConvexByPoints(meshPoints);

                                        var vertices = new Vector3F[points.Count];
                                        var indices  = new int[(points.Count - 2) * 3];
                                        {
                                            for (int n = 0; n < points.Count; n++)
                                            {
                                                vertices[n] = new Vector3F(points[n].ToVector2F(), 0);
                                            }

                                            for (int nTriangle = 0; nTriangle < points.Count - 2; nTriangle++)
                                            {
                                                indices[nTriangle * 3 + 0] = 0;
                                                indices[nTriangle * 3 + 1] = nTriangle + 1;
                                                indices[nTriangle * 3 + 2] = nTriangle + 2;
                                            }
                                        }

                                        var shape = body.CreateComponent <Component_CollisionShape2D_Mesh>();
                                        shape.Vertices  = vertices;
                                        shape.Indices   = indices;
                                        shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex;

                                        //var polygons = new List<List<Vector2>>();
                                        //{
                                        //	var currentList = new List<Vector2>();

                                        //	for( int vertex = 0; vertex < points.Count; vertex++ )
                                        //	{
                                        //		currentList.Add( points[ vertex ] );

                                        //		if( currentList.Count == Settings.MaxPolygonVertices )
                                        //		{
                                        //			polygons.Add( currentList );

                                        //			currentList = new List<Vector2>();
                                        //			currentList.Add( points[ 0 ] );
                                        //			currentList.Add( points[ vertex ] );
                                        //		}
                                        //	}

                                        //	if( currentList.Count >= 3 )
                                        //		polygons.Add( currentList );
                                        //}

                                        //foreach( var points2 in polygons )
                                        //{
                                        //	var vertices = new Vector3F[ points2.Count ];
                                        //	var indices = new int[ ( points2.Count - 2 ) * 3 ];
                                        //	{
                                        //		for( int n = 0; n < points2.Count; n++ )
                                        //			vertices[ n ] = new Vector3F( points2[ n ].ToVector2F(), 0 );

                                        //		for( int nTriangle = 0; nTriangle < points2.Count - 2; nTriangle++ )
                                        //		{
                                        //			indices[ nTriangle * 3 + 0 ] = 0;
                                        //			indices[ nTriangle * 3 + 1 ] = nTriangle + 1;
                                        //			indices[ nTriangle * 3 + 2 ] = nTriangle + 2;
                                        //		}
                                        //	}

                                        //	var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>();
                                        //	shape.Vertices = vertices;
                                        //	shape.Indices = indices;
                                        //	shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex;
                                        //}
                                    }
                                    break;

                                    //case "Convex Decomposition 2D":
                                    //	{
                                    //		body = CreateRigidBody2D();

                                    //		var settings = new ConvexDecomposition.Settings();

                                    //		var form = new SpecifyParametersForm( "Convex Decomposition 2D", settings );
                                    //		form.CheckHandler = delegate ( ref string error2 )
                                    //		{
                                    //			return true;
                                    //		};
                                    //		if( form.ShowDialog() != DialogResult.OK )
                                    //			skip = true;
                                    //		else
                                    //		{
                                    //			//var sourceVertices = (Vector3F[])mesh.Result.ExtractedVerticesPositions.Clone();
                                    //			////reset Z
                                    //			//for( int n = 0; n < sourceVertices.Length; n++ )
                                    //			//	sourceVertices[ n ] = new Vector3F( sourceVertices[ n ].ToVector2(), 0 );

                                    //			//var sourceIndices = mesh.Result.ExtractedIndices;

                                    //			//var epsilon = 0.0001f;
                                    //			//MathAlgorithms.MergeEqualVerticesRemoveInvalidTriangles( sourceVertices, sourceIndices, epsilon, out var processedVertices, out var processedIndices, out var processedTrianglesToSourceIndex );

                                    //			//var vertices = new Vector3F[ mesh.Result.ExtractedVerticesPositions.Length ];
                                    //			////reset Z
                                    //			//for( int n = 0; n < vertices.Length; n++ )
                                    //			//	vertices[ n ] = new Vector3F( mesh.Result.ExtractedVerticesPositions[ n ].ToVector2(), 0 );

                                    //			//var clusters = ConvexDecomposition.Decompose( processedVertices, processedIndices, settings );


                                    //			var vertices = new Vector3F[ mesh.Result.ExtractedVerticesPositions.Length ];
                                    //			//reset Z
                                    //			for( int n = 0; n < vertices.Length; n++ )
                                    //				vertices[ n ] = new Vector3F( mesh.Result.ExtractedVerticesPositions[ n ].ToVector2(), 0 );

                                    //			var clusters = ConvexDecomposition.Decompose( vertices, mesh.Result.ExtractedIndices, settings );

                                    //			if( clusters == null )
                                    //			{
                                    //				Log.Warning( "Unable to decompose." );
                                    //				skip = true;
                                    //			}
                                    //			else
                                    //			{
                                    //				foreach( var cluster in clusters )
                                    //				{
                                    //					var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>();
                                    //					shape.Vertices = cluster.Vertices;
                                    //					shape.Indices = cluster.Indices;
                                    //					shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex;
                                    //				}
                                    //			}
                                    //		}



                                    //		//var sourceVertices = new Vertices();
                                    //		//foreach( var p in mesh.Result.ExtractedVerticesPositions )
                                    //		//	sourceVertices.Add( Physics2DUtility.Convert( p.ToVector2() ) );

                                    //		//var list = Triangulate.ConvexPartition( sourceVertices, TriangulationAlgorithm.Seidel, tolerance: 0.001f );

                                    //		//body = CreateRigidBody2D();

                                    //		//foreach( var convexVertices in list )
                                    //		//{
                                    //		//	var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>();

                                    //		//	var points = new List<Vector2>();
                                    //		//	foreach( var p in convexVertices )
                                    //		//		points.Add( Physics2DUtility.Convert( p ) );

                                    //		//	//var meshPoints = new Vector2[ mesh.Result.ExtractedVerticesPositions.Length ];
                                    //		//	//for( int n = 0; n < meshPoints.Length; n++ )
                                    //		//	//	meshPoints[ n ] = mesh.Result.ExtractedVerticesPositions[ n ].ToVector2();
                                    //		//	//var points = MathAlgorithms.GetConvexByPoints( meshPoints );

                                    //		//	var vertices = new Vector3F[ points.Count + 1 ];
                                    //		//	var indices = new int[ points.Count * 3 ];
                                    //		//	{
                                    //		//		var center = Vector2.Zero;
                                    //		//		foreach( var p in points )
                                    //		//			center += p;
                                    //		//		center /= points.Count;
                                    //		//		vertices[ 0 ] = new Vector3F( center.ToVector2F(), 0 );

                                    //		//		for( int n = 0; n < points.Count; n++ )
                                    //		//		{
                                    //		//			vertices[ 1 + n ] = new Vector3F( points[ n ].ToVector2F(), 0 );

                                    //		//			indices[ n * 3 + 0 ] = 0;
                                    //		//			indices[ n * 3 + 1 ] = 1 + n;
                                    //		//			indices[ n * 3 + 2 ] = 1 + ( ( n + 1 ) % points.Count );
                                    //		//		}
                                    //		//	}

                                    //		//	shape.Vertices = vertices;
                                    //		//	shape.Indices = indices;
                                    //		//	shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex;
                                    //		//}



                                    //		//body = CreateRigidBody2D();
                                    //		//var shape = body.CreateComponent<Component_CollisionShape2D_Mesh>();

                                    //		//var meshPoints = new Vector2[ mesh.Result.ExtractedVerticesPositions.Length ];
                                    //		//for( int n = 0; n < meshPoints.Length; n++ )
                                    //		//	meshPoints[ n ] = mesh.Result.ExtractedVerticesPositions[ n ].ToVector2();
                                    //		//var points = MathAlgorithms.GetConvexByPoints( meshPoints );

                                    //		//var vertices = new Vector3F[ points.Count + 1 ];
                                    //		//var indices = new int[ points.Count * 3 ];
                                    //		//{
                                    //		//	var center = Vector2.Zero;
                                    //		//	foreach( var p in points )
                                    //		//		center += p;
                                    //		//	center /= points.Count;
                                    //		//	vertices[ 0 ] = new Vector3F( center.ToVector2F(), 0 );

                                    //		//	for( int n = 0; n < points.Count; n++ )
                                    //		//	{
                                    //		//		vertices[ 1 + n ] = new Vector3F( points[ n ].ToVector2F(), 0 );

                                    //		//		indices[ n * 3 + 0 ] = 0;
                                    //		//		indices[ n * 3 + 1 ] = 1 + n;
                                    //		//		indices[ n * 3 + 2 ] = 1 + ( ( n + 1 ) % points.Count );
                                    //		//	}
                                    //		//}

                                    //		//shape.Vertices = vertices;
                                    //		//shape.Indices = indices;
                                    //		//shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.Convex;

                                    //		//var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                    //		//shape.TransformRelativeToParent = new Transform( bounds.GetCenter(), Quaternion.Identity );

                                    //		//shape.Mesh = ReferenceUtility.MakeThisReference( shape, meshInSpace, "Mesh" );

                                    //		//var shapeVertices = new Vector3F[ points.Count ];
                                    //		//for( int n = 0; n < shapeVertices.Length; n++ )
                                    //		//	shapeVertices[ n ] = new Vector3F( points[ n ].ToVector2F(), 0 );
                                    //		//shape.Vertices = shapeVertices;
                                    //	}
                                    //	break;

                                    case "Mesh 2D":
                                    {
                                        body = CreateRigidBody2D();
                                        var shape = body.CreateComponent <Component_CollisionShape2D_Mesh>();
                                        shape.Mesh      = ReferenceUtility.MakeThisReference(shape, meshInSpace, "Mesh");
                                        shape.ShapeType = Component_CollisionShape2D_Mesh.ShapeTypeEnum.TriangleMesh;

                                        //var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                        //shape.TransformRelativeToParent = new Transform( bounds.GetCenter(), Quaternion.Identity );

                                        //var halfSize = bounds.GetSize().ToVector2() * 0.5;

                                        //var meshPoints = new List<Vector2>( mesh.Result.ExtractedVerticesPositions.Length );
                                        //foreach( var p in mesh.Result.ExtractedVerticesPositions )
                                        //	meshPoints.Add( p.ToVector2() );
                                        //var convexPoints = MathAlgorithms.GetConvexByPoints( meshPoints );

                                        //var points = shape.PropertyGet( "Points" );
                                        //foreach( var p in convexPoints )
                                        //	points.MethodInvoke( "Add", p );

                                        //points.MethodInvoke( "Add", new Vector2( -halfSize.X, -halfSize.Y ) );
                                        //points.MethodInvoke( "Add", new Vector2( halfSize.X, -halfSize.Y ) );
                                        //points.MethodInvoke( "Add", new Vector2( halfSize.X, halfSize.Y ) );
                                        //points.MethodInvoke( "Add", new Vector2( -halfSize.X, halfSize.Y ) );
                                    }
                                    break;

                                    //case "Polygon 2D":
                                    //	{
                                    //		body = CreateRigidBody2D();
                                    //		if( body != null )
                                    //		{
                                    //			var shapeType = MetadataManager.GetType( "NeoAxis.Component_CollisionShape2D_Polygon" );
                                    //			if( shapeType != null )
                                    //			{
                                    //				var shape = body.CreateComponent( shapeType );
                                    //				var bounds = mesh.Result.SpaceBounds.CalculatedBoundingBox;
                                    //				shape.PropertySet( "TransformRelativeToParent", new Transform( bounds.GetCenter(), Quaternion.Identity ) );

                                    //				var halfSize = bounds.GetSize().ToVector2() * 0.5;

                                    //				var meshPoints = new List<Vector2>( mesh.Result.ExtractedVerticesPositions.Length );
                                    //				foreach( var p in mesh.Result.ExtractedVerticesPositions )
                                    //					meshPoints.Add( p.ToVector2() );
                                    //				var convexPoints = MathAlgorithms.GetConvexByPoints( meshPoints );

                                    //				var points = shape.PropertyGet( "Points" );
                                    //				foreach( var p in convexPoints )
                                    //					points.MethodInvoke( "Add", p );

                                    //				//points.MethodInvoke( "Add", new Vector2( -halfSize.X, -halfSize.Y ) );
                                    //				//points.MethodInvoke( "Add", new Vector2( halfSize.X, -halfSize.Y ) );
                                    //				//points.MethodInvoke( "Add", new Vector2( halfSize.X, halfSize.Y ) );
                                    //				//points.MethodInvoke( "Add", new Vector2( -halfSize.X, halfSize.Y ) );
                                    //			}
                                    //			else
                                    //				skip = true;
                                    //		}
                                    //	}
                                    //	break;

                                    default:
                                        Log.Warning("No implementation.");
                                        skip = true;
                                        continue;
                                    }
                                }

                                if (skip)
                                {
                                    body?.Dispose();
                                    continue;
                                }

                                if (body != null)
                                {
                                    body.Enabled = true;

                                    undoActions.Add(new UndoActionComponentCreateDelete(document, new Component[] { body }, true));

                                    //change Transform
                                    {
                                        //undo action
                                        var property = (Metadata.Property)meshInSpace.MetadataGetMemberBySignature("property:Transform");
                                        var undoItem = new UndoActionPropertiesChange.Item(meshInSpace, property, meshInSpace.Transform, new object[0]);
                                        undoActions.Add(new UndoActionPropertiesChange(new UndoActionPropertiesChange.Item[] { undoItem }));

                                        //configure reference
                                        meshInSpace.Transform = ReferenceUtility.MakeReference <Transform>(null, ReferenceUtility.CalculateThisReference(meshInSpace, body, "Transform"));
                                    }
                                }
                            }
                        }

                        if (undoActions.Count != 0)
                        {
                            document.UndoSystem.CommitAction(new UndoMultiAction(undoActions));
                            document.Modified = true;
                            ScreenNotifications.Show(Translate("The collision was added successfully."));
                        }
                    };

                    var items = new List <KryptonContextMenuItemBase>();
                    var names = new string[] { "Use Collision of the Mesh", "", "Box", "Sphere", "Capsule", "Cylinder", "Convex", "Convex Decomposition", "Mesh", "", "Box 2D", "Circle 2D", "Ellipse 2D", "Capsule 2D", "Convex 2D", /*"Convex Decomposition 2D", */ "Mesh 2D" };
                    foreach (var name in names)
                    {
                        if (name == "")
                        {
                            items.Add(new KryptonContextMenuSeparator());
                        }
                        else
                        {
                            var item = new KryptonContextMenuItem(name, null, clickHandler);
                            item.Tag = (a.DropDownContextMenu, name);
                            items.Add(item);
                        }
                    }

                    a.DropDownContextMenu.Items.Add(new KryptonContextMenuItems(items.ToArray()));
                }

                EditorActions.Register(a);
            }

            //Delete Collision
            {
                const string bodyName = "Collision Body";

                var a = new EditorAction();
                a.Name        = "Delete Collision";
                a.Description = "Deletes the collision body of selected objects.";
                a.ImageSmall  = Properties.Resources.Delete_16;
                a.ImageBig    = Properties.Resources.Delete_32;
                a.QatSupport  = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length != 0 && Array.TrueForAll(selectedObjects, obj => obj is Component_MeshInSpace))
                        {
                            context.Enabled = Array.Exists(selectedObjects, delegate(object obj)
                            {
                                var c = ((Component)obj).GetComponent(bodyName);
                                if (c != null)
                                {
                                    if (c is Component_RigidBody)
                                    {
                                        return(true);
                                    }
                                    if (c is Component_RigidBody2D)
                                    {
                                        return(true);
                                    }
                                }
                                return(false);
                            });
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    var text = string.Format(Translate("Delete \'{0}\'?"), bodyName);
                    if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                    {
                        List <UndoSystem.Action> undoActions = new List <UndoSystem.Action>();

                        foreach (Component_MeshInSpace meshInSpace in context.ObjectsInFocus.Objects)
                        {
                            Component body = null;
                            {
                                var c = meshInSpace.GetComponent(bodyName);
                                if (c != null && (c is Component_RigidBody || c is Component_RigidBody2D))
                                {
                                    body = c;
                                }
                            }

                            if (body != null)
                            {
                                var restoreValue = meshInSpace.Transform;

                                undoActions.Add(new UndoActionComponentCreateDelete(context.ObjectsInFocus.DocumentWindow.Document, new Component[] { body }, false));

                                //change Transform
                                if (meshInSpace.Transform.GetByReference == string.Format("this:${0}\\Transform", bodyName))
                                {
                                    //undo action
                                    var property = (Metadata.Property)meshInSpace.MetadataGetMemberBySignature("property:Transform");
                                    var undoItem = new UndoActionPropertiesChange.Item(meshInSpace, property, restoreValue, new object[0]);
                                    undoActions.Add(new UndoActionPropertiesChange(new UndoActionPropertiesChange.Item[] { undoItem }));

                                    //reset reference
                                    meshInSpace.Transform = restoreValue.Value;
                                }
                            }
                        }

                        if (undoActions.Count != 0)
                        {
                            context.ObjectsInFocus.DocumentWindow.Document.UndoSystem.CommitAction(new UndoMultiAction(undoActions));
                            context.ObjectsInFocus.DocumentWindow.Document.Modified = true;
                            ScreenNotifications.Show(Translate("The collision was deleted."));
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }
コード例 #26
0
        private void kryptonButtonUninstall_Click(object sender, EventArgs e)
        {
            var  filesToDelete = new List <string>();
            bool mustRestart   = false;

            //get list of files to delete
            if (File.Exists(selectedPackage.FullFilePath))
            {
                //get list of files from the package archive

                var info = PackageManager.ReadPackageArchiveInfo(selectedPackage.FullFilePath, out var error);
                if (info == null)
                {
                    ScreenNotifications.Show("Could not read the package info.", true);
                    Log.Warning(error);
                    return;
                }

                foreach (var file in info.Files)
                {
                    var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file);
                    if (File.Exists(fullName))
                    {
                        filesToDelete.Add(file);
                    }
                }

                mustRestart = info.MustRestart;
            }
            else
            {
                //get list of files from selectedPackage.Files in case when the archive file is not exists

                var str = selectedPackage.Files.Trim(new char[] { ' ', '\r', '\n' });

                var files = str.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var file in files)
                {
                    var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file);
                    if (File.Exists(fullName))
                    {
                        filesToDelete.Add(file);
                    }
                }

                //!!!!mustRestart
                mustRestart = true;
            }

            if (filesToDelete.Count == 0)
            {
                return;
            }

            var text = string.Format(Translate("Uninstall {0}?\n\n{1} files will deleted."), selectedPackage.GetDisplayName(), filesToDelete.Count);

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) != EDialogResult.Yes)
            {
                return;
            }

            var filesToDeletionAtStartup = new List <string>();

            try
            {
                //remove cs files from Project.csproj
                try
                {
                    var toRemove = new List <string>();

                    foreach (var file in filesToDelete)
                    {
                        var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file);
                        if (Path.GetExtension(fullName).ToLower() == ".cs")
                        {
                            toRemove.Add(VirtualPathUtility.NormalizePath(fullName));
                        }
                    }

                    if (toRemove.Count != 0)
                    {
                        CSharpProjectFileUtility.UpdateProjectFile(null, toRemove, out _);
                    }
                }
                catch { }

                //delete files
                foreach (var file in filesToDelete)
                {
                    var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file);

                    try
                    {
                        File.Delete(fullName);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        filesToDeletionAtStartup.Add(file);
                    }
                    catch (IOException)
                    {
                        filesToDeletionAtStartup.Add(file);
                    }
                }

                //delete empty folders
                {
                    var allFolders = new ESet <string>();
                    foreach (var file in filesToDelete)
                    {
                        var f = Path.GetDirectoryName(file);
                        while (!string.IsNullOrEmpty(f))
                        {
                            allFolders.AddWithCheckAlreadyContained(f);
                            f = Path.GetDirectoryName(f);
                        }
                    }

                    var list = allFolders.ToArray();
                    CollectionUtility.MergeSort(list, delegate(string f1, string f2)
                    {
                        var levels1 = f1.Split(new char[] { '\\' }).Length;
                        var levels2 = f2.Split(new char[] { '\\' }).Length;
                        return(levels2 - levels1);
                    });

                    foreach (var folder in list)
                    {
                        var fullName = Path.Combine(VirtualFileSystem.Directories.Project, folder);

                        if (Directory.Exists(fullName) && IsDirectoryEmpty(fullName))
                        {
                            Directory.Delete(fullName);
                        }
                    }
                }

                PackageManager.ChangeInstalledState(selectedPackage.Name, false);
            }
            catch (Exception e2)
            {
                EditorMessageBox.ShowWarning(e2.Message);
                return;
            }

            if (filesToDeletionAtStartup.Count != 0)
            {
                PackageManager.AddFilesToDeletionAtStartup(filesToDeletionAtStartup);
            }

            needUpdateList = true;

            if (mustRestart)
            {
                ShowRestartLabel();
            }

            ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully uninstalled."));
        }
コード例 #27
0
        private void ButtonImport_Click(ProcedureUI.Button sender)
        {
            var sky = GetFirstObject <Component_Skybox>();

            if (sky == null)
            {
                return;
            }
            var scene = sky.FindParent <Component_Scene>();

            if (scene == null)
            {
                return;
            }

            var link = editLink.Text;

            var notification = ScreenNotifications.ShowSticky("Importing...");

            try
            {
                string destVirtualFileName;
                {
                    string name = sky.GetPathFromRoot();
                    foreach (char c in new string( Path.GetInvalidFileNameChars()) + new string( Path.GetInvalidPathChars()))
                    {
                        name = name.Replace(c.ToString(), "_");
                    }
                    name = name.Replace(" ", "_");
                    destVirtualFileName = Path.Combine(ComponentUtility.GetOwnedFileNameOfComponent(scene) + "_Files", name);

                    destVirtualFileName += Path.GetExtension(link);
                }

                var destRealFileName = VirtualPathUtility.GetRealPathByVirtual(destVirtualFileName);


                if (File.Exists(destRealFileName))
                {
                    if (EditorMessageBox.ShowQuestion($"Overwrite \'{destRealFileName}\'?", EMessageBoxButtons.OKCancel) == EDialogResult.Cancel)
                    {
                        return;
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(destRealFileName));

                if (File.Exists(link))
                {
                    File.Copy(link, destRealFileName, true);
                }
                else
                {
                    //if( Uri.IsWellFormedUriString( link, UriKind.Absolute ) )
                    //{
                    using (var client = new WebClient())
                        client.DownloadFile(link, destRealFileName);
                    //}
                }

                var oldValue = sky.Cubemap;

                sky.Cubemap = ReferenceUtility.MakeReference(destVirtualFileName);

                //undo
                var property   = (Metadata.Property)sky.MetadataGetMemberBySignature("property:Cubemap");
                var undoItem   = new UndoActionPropertiesChange.Item(sky, property, oldValue);
                var undoAction = new UndoActionPropertiesChange(undoItem);
                Provider.DocumentWindow.Document.CommitUndoAction(undoAction);
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
            }
            finally
            {
                notification.Close();
            }
        }
コード例 #28
0
        void RenderByEngineRender()
        {
            var renderToFile = RenderToFile;
            var scene        = renderToFile.ParentRoot as Component_Scene;

            //get camera
            var camera = renderToFile.Camera.Value;

            if (camera == null)
            {
                camera = scene.Mode.Value == Component_Scene.ModeEnum._2D ? scene.CameraEditor2D : scene.CameraEditor;
            }
            if (camera == null)
            {
                EditorMessageBox.ShowWarning("Camera is not specified.");
                return;
            }

            var destRealFileName = renderToFile.OutputFileName;

            if (string.IsNullOrEmpty(destRealFileName))
            {
                var dialog = new SaveFileDialog();
                //dialog.InitialDirectory = Path.GetDirectoryName( RealFileName );
                dialog.FileName = "Render.png";
                //dialog.FileName = RealFileName;
                dialog.Filter           = "PNG files (*.png)|*.png";      //dialog.Filter = "All files (*.*)|*.*";
                dialog.RestoreDirectory = true;
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                destRealFileName = dialog.FileName;
            }
            else
            {
                //file already exists
                if (File.Exists(destRealFileName))
                {
                    var text = $"The file with name \'{destRealFileName}\' is already exists. Overwrite?";
                    if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.OKCancel) == EDialogResult.Cancel)
                    {
                        return;
                    }
                }
            }

            Component_Image texture     = null;
            Component_Image textureRead = null;

            try
            {
                //create
                var resolution = renderToFile.Resolution.Value;

                //!!!!impl
                var         hdr    = false;     //HDR.Value;
                PixelFormat format = hdr ? PixelFormat.Float16RGBA : PixelFormat.A8R8G8B8;
                //PixelFormat format = hdr ? PixelFormat.Float32RGBA : PixelFormat.A8R8G8B8;

                texture               = ComponentUtility.CreateComponent <Component_Image>(null, true, false);
                texture.CreateType    = Component_Image.TypeEnum._2D;
                texture.CreateSize    = resolution;             // new Vector2I( size, size );
                texture.CreateMipmaps = false;
                texture.CreateFormat  = format;
                texture.CreateUsage   = Component_Image.Usages.RenderTarget;
                texture.CreateFSAA    = 0;
                texture.Enabled       = true;

                var renderTexture = texture.Result.GetRenderTarget(0, 0);
                var viewport      = renderTexture.AddViewport(true, true);
                viewport.AttachedScene = scene;

                textureRead               = ComponentUtility.CreateComponent <Component_Image>(null, true, false);
                textureRead.CreateType    = Component_Image.TypeEnum._2D;
                textureRead.CreateSize    = resolution;
                textureRead.CreateMipmaps = false;
                textureRead.CreateFormat  = format;
                textureRead.CreateUsage   = Component_Image.Usages.ReadBack | Component_Image.Usages.BlitDestination;
                textureRead.CreateFSAA    = 0;
                textureRead.Enabled       = true;
                //!!!!
                textureRead.Result.PrepareNativeObject();

                //render
                //var image2D = new ImageUtility.Image2D( PixelFormat.Float32RGB, new Vector2I( size * 4, size * 3 ) );

                //var position = Transform.Value.Position;

                //for( int face = 0; face < 6; face++ )
                //{

                //Vector3 dir = Vector3.Zero;
                //Vector3 up = Vector3.Zero;

                ////flipped
                //switch( face )
                //{
                //case 0: dir = -Vector3.YAxis; up = Vector3.ZAxis; break;
                //case 1: dir = Vector3.YAxis; up = Vector3.ZAxis; break;
                //case 2: dir = Vector3.ZAxis; up = -Vector3.XAxis; break;
                //case 3: dir = -Vector3.ZAxis; up = Vector3.XAxis; break;
                //case 4: dir = Vector3.XAxis; up = Vector3.ZAxis; break;
                //case 5: dir = -Vector3.XAxis; up = Vector3.ZAxis; break;
                //}

                try
                {
                    scene.GetDisplayDevelopmentDataInThisApplicationOverride += Scene_GetDisplayDevelopmentDataInThisApplicationOverride;

                    var cameraSettings = new Viewport.CameraSettingsClass(viewport, camera);

                    //var cameraSettings = new Viewport.CameraSettingsClass( viewport, 1, 90, NearClipPlane.Value, FarClipPlane.Value, position, dir, up, ProjectionType.Perspective, 1, 1, 1 );

                    viewport.Update(true, cameraSettings);

                    //clear temp data
                    viewport.RenderingContext.MultiRenderTarget_DestroyAll();
                    viewport.RenderingContext.DynamicTexture_DestroyAll();
                }
                finally
                {
                    scene.GetDisplayDevelopmentDataInThisApplicationOverride -= Scene_GetDisplayDevelopmentDataInThisApplicationOverride;
                }

                texture.Result.GetRealObject(true).BlitTo(viewport.RenderingContext.CurrentViewNumber, textureRead.Result.GetRealObject(true), 0, 0);


                //!!!!pitch

                //get data
                var totalBytes = PixelFormatUtility.GetNumElemBytes(format) * resolution.X * resolution.Y;
                var data       = new byte[totalBytes];
                unsafe
                {
                    fixed(byte *pBytes = data)
                    {
                        var demandedFrame = textureRead.Result.GetRealObject(true).Read((IntPtr)pBytes, 0);

                        while (RenderingSystem.CallBgfxFrame() < demandedFrame)
                        {
                        }
                    }
                }

                var image = new ImageUtility.Image2D(format, resolution, data);

                //reset alpha channel
                for (int y = 0; y < image.Size.Y; y++)
                {
                    for (int x = 0; x < image.Size.X; x++)
                    {
                        var pixel = image.GetPixel(new Vector2I(x, y));
                        pixel.W = 1.0f;
                        image.SetPixel(new Vector2I(x, y), pixel);
                    }
                }

                //image.Data
                //image2D.Blit( index * size, faceImage );

                //Vector2I index = Vector2I.Zero;
                //switch( face )
                //{
                //case 0: index = new Vector2I( 2, 1 ); break;
                //case 1: index = new Vector2I( 0, 1 ); break;
                //case 2: index = new Vector2I( 1, 0 ); break;
                //case 3: index = new Vector2I( 1, 2 ); break;
                //case 4: index = new Vector2I( 1, 1 ); break;
                //case 5: index = new Vector2I( 3, 1 ); break;
                //}

                //var faceImage = new ImageUtility.Image2D( format, new Vector2I( size, size ), data );
                //image2D.Blit( index * size, faceImage );
                //}

                if (!Directory.Exists(Path.GetDirectoryName(destRealFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(destRealFileName));
                }

                if (!ImageUtility.Save(destRealFileName, image.Data, image.Size, 1, image.Format, 1, 0, out var error))
                {
                    throw new Exception(error);
                }
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
                return;
            }
            finally
            {
                texture?.Dispose();
                textureRead?.Dispose();
            }

            ScreenNotifications.Show("Rendering completed successfully.");
        }