Example #1
0
        public static DocumentWindow OpenDocumentWindowForObject(DocumentInstance document, object obj)          //, bool canUseAlreadyOpened )
        {
            if (!IsDocumentObjectSupport(obj))
            {
                return(null);
            }

            //another document or no document
            {
                var objectToDocument = GetDocumentByObject(obj);
                if (objectToDocument == null || objectToDocument != document)
                {
                    var component = obj as Component;
                    if (component != null)
                    {
                        var fileName = ComponentUtility.GetOwnedFileNameOfComponent(component);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            var realFileName = VirtualPathUtility.GetRealPathByVirtual(fileName);

                            if (IsDocumentFileSupport(realFileName))
                            {
                                var documentWindow = OpenFileAsDocument(realFileName, true, true) as DocumentWindow;
                                if (documentWindow != null)
                                {
                                    var newDocument = documentWindow.Document;
                                    var newObject   = newDocument.ResultComponent.Components[component.GetPathFromRoot()];
                                    if (newObject != null)
                                    {
                                        return(OpenDocumentWindowForObject(newDocument, newObject));
                                    }
                                }

                                return(null);
                            }
                        }
                    }

                    return(null);
                }
            }

            //check for already opened
            var canUseAlreadyOpened = !EditorForm.ModifierKeys.HasFlag(Keys.Shift);

            if (canUseAlreadyOpened)
            {
                var openedWindow = EditorForm.Instance.WorkspaceController.FindWindowRecursive(document, obj);
                if (openedWindow != null)
                {
                    EditorForm.Instance.WorkspaceController.SelectDockWindow(openedWindow);
                    return(openedWindow);
                }
            }

            //create document window
            var window = CreateWindowImpl(document, obj, false);

            //!!!!
            bool floatingWindow = false;
            bool select         = true;

            EditorForm.Instance.WorkspaceController.AddDockWindow(window, floatingWindow, select);

            return(window);
        }
Example #2
0
        static bool LoadFBX(ImportContext context, string virtualFileName, out List <MeshData> geometries)
        {
            geometries = null;

            var settings = context.settings;

            ImportFBX.LoadNativeLibrary();

            FbxManager    manager  = null;
            FbxIOSettings setting  = null;
            FbxImporter   importer = null;
            FbxScene      scene    = null;

            try
            {
                manager = FbxManager.Create();
                setting = FbxIOSettings.Create(manager, "IOSRoot");
                manager.SetIOSettings(setting);

                importer = FbxImporter.Create(manager, "");
                var realFileName = VirtualPathUtility.GetRealPathByVirtual(virtualFileName);
                //VirtualFileStream stream = null;
                //ToDo : FromStream
                bool status;
                if (!string.IsNullOrEmpty(realFileName) && File.Exists(realFileName))
                {
                    status = importer.Initialize(realFileName, -1, setting);
                }
                else
                {
                    return(false);
                    //throw new NotImplementedException();
                    //ToDo : ....
                    //stream = VirtualFile.Open( settings.virtualFileName );
                    //FbxStream fbxStream = null;
                    //SWIGTYPE_p_void streamData = null;

                    //status = impoter.Initialize( fbxStream, streamData, -1, setting );
                }

                if (!status)
                {
                    return(false);
                }

                scene  = FbxScene.Create(manager, "scene1");
                status = importer.Import(scene);
                if (!status)
                {
                    return(false);
                }

                //convert axis
                if (context.settings.component.ForceFrontXAxis)
                {
                    //Через такой конструктор не получится создать такие же оси как EPreDefinedAxisSystem.eMax - Front Axis имеет обратное направление, а направление задать нельзя.
                    //new FbxAxisSystem( FbxAxisSystem.EUpVector.eZAxis, FbxAxisSystem.EFrontVector.eParityOdd, FbxAxisSystem.ECoordSystem.eRightHanded );
                    //FromFBX Docs:
                    //The enum values ParityEven and ParityOdd denote the first one and the second one of the remain two axes in addition to the up axis.
                    //For example if the up axis is X, the remain two axes will be Y And Z, so the ParityEven is Y, and the ParityOdd is Z ;

                    //We desire to convert the scene from Y-Up to Z-Up. Using the predefined axis system: Max (UpVector = +Z, FrontVector = -Y, CoordSystem = +X (RightHanded))
                    var maxAxisSystem = new FbxAxisSystem(FbxAxisSystem.EPreDefinedAxisSystem.eMax);

                    if (!scene.GetGlobalSettings().GetAxisSystem().eq(maxAxisSystem))
                    {
                        maxAxisSystem.ConvertScene(scene);                           //No conversion will take place if the scene current axis system is equal to the new one. So condition can be removed.
                    }
                }

                //convert units
                if (!scene.GetGlobalSettings().GetSystemUnit().eq(FbxSystemUnit.m))
                {
                    FbxSystemUnit.m.ConvertScene(scene);
                }

                var additionalTransform = new Matrix4(settings.component.Rotation.Value.ToMatrix3() * Matrix3.FromScale(settings.component.Scale), settings.component.Position);

                var options = new ImportOptions
                {
                    NormalsOptions         = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate,
                    TangentsOptions        = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate,
                    ImportPostProcessFlags = ImportPostProcessFlags.FixInfacingNormals
                };
                options.ImportPostProcessFlags |= ImportPostProcessFlags.SmoothNormals | ImportPostProcessFlags.SmoothTangents;
                if (context.settings.component.FlipUVs)
                {
                    options.ImportPostProcessFlags |= ImportPostProcessFlags.FlipUVs;
                }
                //if( importContext.settings.component.MergeMeshGeometries )
                //	options.ImportPostProcessFlags |= ImportPostProcessFlags.MergeGeometriesByMaterials;

                var sceneLoader = new SceneLoader();
                sceneLoader.Load(scene, manager, options, additionalTransform);

                geometries = sceneLoader.Geometries;
                //foreach( var geometry in sceneLoader.Geometries )
                //	ImportGeometry( context, destinationMesh, geometry );

                ////check is it a billboard
                //MeshGetIsBillboard( context, destinationMesh );

                //stream?.Dispose();
            }
            finally
            {
                //Особенности удаления.
                //Создается через функцию: impoter = FbxImporter.Create(manager, "");
                //В таких случаях(создание не через конструктор, а возврат указателя из функции) SWIG задает флажок что объект не владеет ссылкой, поэтому Dispose ничего не делает.
                //Хотя в SWIG можно задать в конфигурации: %newobject FbxImporter::Create; Тогда объект будет владеть ссылкой. Но все равно в С++ наследники FbxObject не имеют public destructor
                //поэтому в Dispose вставлен: throw new MethodAccessException("C++ destructor does not have public access"). Поэтому удалять только через Destroy.

                try { scene?.Destroy(); } catch { }
                try { importer?.Destroy(); } catch { }
                try { setting?.Destroy(); } catch { }
                try { manager?.Destroy(); } catch { }
            }

            return(true);
        }
Example #3
0
 public static void ShowProjectSettings()
 {
     OpenFileAsDocument(VirtualPathUtility.GetRealPathByVirtual(ProjectSettings.FileName), true, true, true, "ProjectSettingsUserMode");
 }
Example #4
0
        private void EditorForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool?result = ShowDialogAndSaveDocuments(workspaceController.GetDockWindows());

            if (result == null)
            {
                e.Cancel = true;
                return;
            }

            //save docking state
            if (canSaveConfig)
            //if( !forceCloseForm )
            {
                string configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileName);
                EditorAPI.GetRestartApplication(out _, out var resetWindowsSettings);
                if (resetWindowsSettings)
                {
                    if (File.Exists(configFile))
                    {
                        File.Delete(configFile);
                    }
                }
                else
                {
                    if (!Directory.Exists(Path.GetDirectoryName(configFile)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(configFile));
                    }

                    workspaceController.SaveLayoutToFile(configFile);

                    // temp experimental:
                    //foreach (var wnd in workspaceController.OfType<WorkspaceWindow>())
                    //{
                    //	string configFileName = string.Format(workspaceConfigFileName, wnd.Name);
                    //	string workspaceConfigFile = VirtualPathUtils.GetRealPathByVirtual(configFileName);
                    //	var controller = wnd.WorkspaceController;
                    //	controller.SaveLayoutToFile(workspaceConfigFile);
                    //}
                }
            }

            EditorAPI.ClosingApplication = true;

            EditorLocalization.Shutdown();

            //destroy all documents
            {
                //!!!!может окна документов сначала удалить?
                foreach (var document in Documents.ToArray())
                {
                    document.Destroy();
                }
            }

            //destroy all viewport controls
            foreach (var control in EngineViewportControl.allInstances.ToArray())
            {
                control.Dispose();
            }

            if (!canSaveConfig)
            {
                EngineApp.NeedSaveConfig = false;
            }
            EngineApp.Shutdown();
        }
Example #5
0
        //

        public StartPageWindow()
        {
            InitializeComponent();

            if (WinFormsUtility.IsDesignerHosted(this))
            {
                return;
            }

            if (EditorAPI.DarkTheme)
            {
                BackColor = Color.FromArgb(40, 40, 40);
                EditorThemeUtility.ApplyDarkThemeToToolTip(toolTip1);
            }

            contentBrowserNewScene.Options.PanelMode = ContentBrowser.PanelModeEnum.List;
            contentBrowserNewScene.Options.ListMode  = ContentBrowser.ListModeEnum.Tiles;
            contentBrowserNewScene.UseSelectedTreeNodeAsRootForList = false;
            contentBrowserNewScene.Options.Breadcrumb    = false;
            contentBrowserNewScene.Options.TileImageSize = 100;
            //contentBrowserNewScene.Options.TileImageSize = 128;

            //add items
            try
            {
                var items = new List <ContentBrowser.Item>();

                //scenes
                foreach (var template in Component_Scene.NewObjectSettingsScene.GetTemplates())
                {
                    contentBrowserNewScene.AddImageKey(template.Name, template.Preview);

                    var item = new ContentBrowserItem_Virtual(contentBrowserNewScene, null, template.ToString() + " scene");
                    item.Tag      = template;
                    item.imageKey = template.Name;

                    items.Add(item);
                }

                //UI Control
                {
                    var path = VirtualPathUtility.GetRealPathByVirtual(@"Base\Tools\NewResourceTemplates\UIControl.ui");
                    if (File.Exists(path))
                    {
                        var name = Path.GetFileNameWithoutExtension(path);

                        if (previewImageNewUIControl == null)
                        {
                            var previewPath = Path.Combine(Path.GetDirectoryName(path), name + ".png");
                            previewImageNewUIControl = File.Exists(previewPath) ? Image.FromFile(previewPath) : null;
                        }

                        if (previewImageNewUIControl != null)
                        {
                            contentBrowserNewScene.AddImageKey(name, previewImageNewUIControl);
                        }

                        var item = new ContentBrowserItem_Virtual(contentBrowserNewScene, null, "UI Control");
                        item.Tag = "UIControl";
                        if (previewImageNewUIControl != null)
                        {
                            item.imageKey = name;
                        }

                        items.Add(item);
                    }
                }

                //Select resource
                {
                    var name = "SelectResource";

                    if (previewImageNewResource == null)
                    {
                        var previewPath = VirtualPathUtility.GetRealPathByVirtual(@"Base\Tools\NewResourceTemplates\Resource.png");
                        previewImageNewResource = File.Exists(previewPath) ? Image.FromFile(previewPath) : null;
                    }

                    if (previewImageNewResource != null)
                    {
                        contentBrowserNewScene.AddImageKey(name, previewImageNewResource);
                    }

                    var item = new ContentBrowserItem_Virtual(contentBrowserNewScene, null, "Select type");
                    item.Tag = "Resource";
                    if (previewImageNewResource != null)
                    {
                        item.imageKey = name;
                    }

                    items.Add(item);
                }

                ////!!!!
                //{
                //	var item = new ContentBrowserItem_Virtual( contentBrowserNewScene, null, "C# Class Library" );
                //	//!!!!
                //	//item.Tag = template;
                //	item.imageKey = "";//template.Name;

                //	item.ShowDisabled = true;

                //	items.Add( item );
                //}

                ////!!!!
                //{
                //	var item = new ContentBrowserItem_Virtual( contentBrowserNewScene, null, "Executable App" );
                //	//!!!!
                //	//item.Tag = template;
                //	item.imageKey = "";//template.Name;

                //	item.ShowDisabled = true;

                //	items.Add( item );
                //}

                if (items.Count != 0)
                {
                    contentBrowserNewScene.SetData(items, false);
                    contentBrowserNewScene.SelectItems(new ContentBrowser.Item[] { items[0] });
                }
            }
            catch (Exception exc)
            {
                Log.Warning(exc.Message);
                //contentBrowserNewScene.SetError( "Error: " + exc.Message );
            }

            contentBrowserNewScene.ItemAfterChoose += ContentBrowserNewScene_ItemAfterChoose;


            contentBrowserOpenScene.Options.PanelMode = ContentBrowser.PanelModeEnum.List;
            contentBrowserOpenScene.Options.ListMode  = ContentBrowser.ListModeEnum.List;
            contentBrowserOpenScene.UseSelectedTreeNodeAsRootForList = false;
            contentBrowserOpenScene.Options.Breadcrumb = false;

            var imageSize = EditorAPI.DPIScale >= 1.25f ? 13 : 16;

            contentBrowserOpenScene.Options.ListImageSize   = imageSize;
            contentBrowserOpenScene.Options.ListColumnWidth = 10000;
            contentBrowserOpenScene.ListViewModeOverride    = new EngineListView.DefaultListMode(contentBrowserOpenScene.GetListView(), imageSize);

            contentBrowserOpenScene.PreloadResourceOnSelection = false;

            UpdateOpenScenes();

            WindowTitle = EditorLocalization.Translate("StartPageWindow", WindowTitle);
        }
Example #6
0
        private void EditorForm_Load(object sender, EventArgs e)
        {
            if (WinFormsUtility.IsDesignerHosted(this))
            {
                return;
            }

            //hide ribbon to avoid redrawing
            kryptonRibbon.Visible = false;

            // create cover
            coverControl           = new Control();
            coverControl.BackColor = Color.FromArgb(40, 40, 40);
            coverControl.Dock      = DockStyle.Fill;
            Controls.Add(coverControl);
            coverControl.BringToFront();
            Application.DoEvents();

            ////dpi
            //try
            //{
            //	using( Graphics graphics = CreateGraphics() )
            //	{
            //		dpi = graphics.DpiX;
            //	}
            //}
            //catch( Exception ex )
            //{
            //	dpi = 96;
            //	Log.Warning( "EditorForm: CreateGraphics: Call failed. " + ex.Message );
            //}

            kryptonRibbon.RibbonTabs.Clear();

            {
                EngineApp.InitSettings.UseApplicationWindowHandle = Handle;

                if (!EngineApp.Create())
                {
                    Log.Fatal("EngineApp.Create() failed.");
                    Close();
                    return;
                }

                //эксепшен не генегируется, просто падает

                //bool created = false;

                //if( Debugger.IsAttached )
                //	created = EngineApp.Create();
                //else
                //{
                //	try
                //	{
                //		//!!!!
                //		Log.Info( "dd" );

                //		created = EngineApp.Create();

                //		//!!!!
                //		Log.Info( "tt" );

                //	}
                //	catch( Exception e2 )
                //	{
                //		//!!!!
                //		Log.Info( "ee" );

                //		Log.FatalAsException( e2.ToString() );
                //	}
                //}

                //if( !created )
                //{
                //	Log.Fatal( "EngineApp.Create() failed." );
                //	Close();
                //	return;
                //}
            }

            EngineApp.DefaultSoundChannelGroup.Volume = 0;

            EnableLocalization();

            //set theme
            if (ProjectSettings.Get.Theme.Value == Component_ProjectSettings.ThemeEnum.Dark)
            {
                kryptonManager.GlobalPaletteMode = PaletteModeManager.NeoAxisBlack;
            }
            else
            {
                kryptonManager.GlobalPaletteMode = PaletteModeManager.NeoAxisBlue;
            }

            KryptonDarkThemeUtility.DarkTheme = EditorAPI.DarkTheme;
            if (EditorAPI.DarkTheme)
            {
                EditorAssemblyInterface.Instance.SetDarkTheme();
            }
            Aga.Controls.Tree.NodeControls.BaseTextControl.DarkTheme = EditorAPI.DarkTheme;

            BackColor = EditorAPI.DarkTheme ? Color.FromArgb(40, 40, 40) : Color.FromArgb(240, 240, 240);

            //app button
            kryptonRibbon.RibbonAppButton.AppButtonText = EditorLocalization.Translate("AppButton", kryptonRibbon.RibbonAppButton.AppButtonText);
            if (DarkTheme)
            {
                kryptonRibbon.RibbonAppButton.AppButtonBaseColorDark  = Color.FromArgb(40, 40, 40);
                kryptonRibbon.RibbonAppButton.AppButtonBaseColorLight = Color.FromArgb(54, 54, 54);
            }

            //!!!! default editor layout:

            // IsSystemWindow = true for this:
            // для этих "системных" окон используется отдельная логика сериализации (окна создаются до загрузки конфига)
            // и отдельная логика закрытия (hide/remove)
            workspaceController.AddToDockspaceStack(new DockWindow[] { new ObjectsWindow(), new SettingsWindow() }, DockingEdge.Right);
            //workspaceController.AddDockspace(new MembersWindow(), "Members", DockingEdge.Right, new Size(300, 300));
            workspaceController.AddToDockspaceStack(new DockWindow[] { new ResourcesWindow(), new SolutionExplorer(), new PreviewWindow() }, DockingEdge.Left);
            workspaceController.AddToDockspace(new DockWindow[] { new MessageLogWindow(), new OutputWindow(), new DebugInfoWindow() }, DockingEdge.Bottom);

            Log.Info("Use Log.Info(), Log.Warning() methods to write to the window. These methods can be used in the Player. Press '~' to open console of the Player.");
            OutputWindow.Print("Use OutputWindow.Print() method to write to the window. Unlike Message Log window, this window is not a list. Here you can add text in arbitrary format.\n");

            //!!!!
            //workspaceController.AddDockWindow( new TipsWindow(), true, false );

            //!!!!эвент чтобы свои добавлять. и пример

            //load docking state
            {
                string configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileName);
                //default settings
                if (!File.Exists(configFile))
                {
                    configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileNameDefault);
                }

                if (File.Exists(configFile))
                {
                    //try
                    //{
                    ////!!!! If xml broken, we will not get an exception.
                    //// the exception is swallowed inside the krypton.
                    //// how do I know if an error has occurred?
                    workspaceController.LoadLayoutFromFile(configFile);
                    //}
                    //	catch
                    //	{
                    //		//!!!!TODO: layout broken. fix this!
                    //	}
                }
            }

            InitQAT();
            InitRibbon();

            UpdateText();

            //apply editor settings
            EditorSettingsSerialization.InitAfterFormLoad();

            XmlDocumentationFiles.PreloadBaseAssemblies();

            EditorAPI.SelectedDocumentWindowChanged += EditorAPI_SelectedDocumentWindowChanged;

            UpdateRecentProjectsInRegistry();

            LoginUtility.RequestFullLicenseInfo();

            kryptonRibbon.BeforeMinimizedModeChanged += KryptonRibbon_BeforeMinimizedModeChanged;
            kryptonRibbon.MinimizedModeChanged       += KryptonRibbon_MinimizedModeChanged;

            KryptonWinFormsUtility.editorFormStartTemporaryLockUpdateAction = delegate()
            {
                if (IsHandleCreated && !EditorAPI.ClosingApplication)
                {
                    KryptonWinFormsUtility.LockFormUpdate(this);
                    unlockFormUpdateInTimer = DateTime.Now + TimeSpan.FromSeconds(0.1);
                }
            };

            loaded = true;
        }
Example #7
0
        bool CreateObject()
        {
            creationData.ClearCreatedObjects();

            //!!!!в окнах/окне делать активным после создания

            //creationData.selectedType = SelectedType;
            //creationData.replaceSelectedTypeFunction?.Invoke( this );

            //!!!!
            //create objects
            {
                creationData.beforeCreateObjectsFunction?.Invoke(this, SelectedType);

                //default creation behaviour
                if (creationData.createdObjects == null)
                {
                    creationData.createdObjects = new List <object>();

                    if (creationData.initParentObjects != null)
                    {
                        foreach (var parentObject in creationData.initParentObjects)
                        {
                            var parentComponent = parentObject as Component;

                            object obj;
                            if (parentComponent != null)
                            {
                                var insertIndex = EditorUtility.GetNewObjectInsertIndex(parentComponent, SelectedType);
                                obj = parentComponent.CreateComponent(SelectedType, insertIndex, false);
                            }
                            else
                            {
                                obj = SelectedType.InvokeInstance(null);
                            }

                            creationData.createdObjects.Add(obj);
                            creationData.createdObjectsToApplySettings.Add(obj);
                            var c = obj as Component;
                            if (c != null)
                            {
                                creationData.createdComponentsOnTopLevel.Add(c);
                            }
                        }
                    }
                    else
                    {
                        var obj = SelectedType.InvokeInstance(null);

                        creationData.createdObjects.Add(obj);
                        creationData.createdObjectsToApplySettings.Add(obj);
                        var c = obj as Component;
                        if (c != null)
                        {
                            creationData.createdComponentsOnTopLevel.Add(c);
                        }
                    }
                }
            }

            //!!!!
            //no created objects
            if (creationData.createdObjects.Count == 0)
            {
                //!!!!
                return(false);
            }

            string realFileName = "";

            if (IsFileCreation())
            {
                realFileName = VirtualPathUtility.GetRealPathByVirtual(textBoxName.Text);
            }

            //create folder for file creation
            if (IsFileCreation())
            {
                var directoryName = Path.GetDirectoryName(realFileName);
                if (!Directory.Exists(directoryName))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryName);
                    }
                    catch (Exception e)
                    {
                        Log.Warning(e.Message);
                        return(false);
                    }
                }
            }

            //init settings of objects
            bool disableFileCreation = false;

            foreach (var createdObject in creationData.createdObjectsToApplySettings)
            {
                if (!ApplyCreationSettingsToObject(createdObject, ref disableFileCreation))
                {
                    return(false);
                }
            }

            //action before enabled
            creationData.additionActionBeforeEnabled?.Invoke(this);

            //finalization of creation
            foreach (var component in creationData.createdComponentsOnTopLevel)
            {
                component.Enabled = true;
            }

            creationData.additionActionAfterEnabled?.Invoke(this);
            //foreach( var obj in createdObjects )
            //	creationData.additionActionAfterEnabled?.Invoke( this, obj, newObjectsFromAdditionActions );

            //file creation. save to file
            if (IsFileCreation())
            {
                //!!!!проверки
                //!!!!!!!overwrite

                if (creationData.createdComponentsOnTopLevel.Count == 1 && !disableFileCreation)
                {
                    var createdComponent = creationData.createdComponentsOnTopLevel[0];
                    if (!ComponentUtility.SaveComponentToFile(createdComponent, realFileName, null, out string error))
                    {
                        if (!string.IsNullOrEmpty(error))
                        {
                            //!!!!
                            Log.Warning(error);
                            return(false);
                        }
                    }
                }

                //Dispose created objects for file creation mode
                foreach (var obj in creationData.createdObjects)
                {
                    var d = obj as IDisposable;
                    if (d != null)
                    {
                        d.Dispose();
                    }
                }
            }

            //update document
            if (!IsFileCreation())
            {
                //update document
                //!!!!!
                var document = creationData.initDocumentWindow.Document;
                if (document != null)
                {
                    //!!!!только компоненты?

                    var action = new UndoActionComponentCreateDelete(document, creationData.createdComponentsOnTopLevel, true);

                    //List<Component> created = new List<Component>();
                    //created.AddRange( createdComponents );
                    //foreach( var obj in newObjectsFromAdditionActions )
                    //{
                    //	var component = obj as Component;
                    //	if( component != null )
                    //		created.Add( component );
                    //}
                    //var action = new UndoActionComponentCreateDelete( created, true );
                    document.UndoSystem.CommitAction(action);

                    document.Modified = true;
                }
                else
                {
                    //!!!!надо ли?
                    Log.Warning("impl");
                }
            }

            //select and open
            if (IsFileCreation())
            {
                //!!!!не обязательно основное окно

                //select new file in Resources window
                EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { realFileName });

                //open file
                EditorAPI.OpenFileAsDocument(realFileName, true, true);
            }
            else
            {
                //select created components
                if (creationData.createdFromContentBrowser != null)
                {
                    var creator = creationData.createdFromContentBrowser;
                    if (creator.IsHandleCreated && !creator.IsDisposed)
                    {
                        ContentBrowserUtility.SelectComponentItems(creator, creationData.createdComponentsOnTopLevel.ToArray());
                    }
                }
                else
                {
                    EditorAPI.SelectComponentsInMainObjectsWindow(creationData.initDocumentWindow, creationData.createdComponentsOnTopLevel.ToArray());
                }

                //open editor
                if (creationData.createdComponentsOnTopLevel.Count == 1)
                {
                    var component = creationData.createdComponentsOnTopLevel[0];

                    if (!component.EditorReadOnlyInHierarchy)
                    {
                        //!!!!пока так
                        if (component is Component_FlowGraph || component is Component_CSharpScript)
                        {
                            EditorAPI.OpenDocumentWindowForObject(creationData.initDocumentWindow.Document, component);
                        }
                    }
                    //if( EditorAPI.IsDocumentObjectSupport( component ) && !component.EditorReadOnlyInHierarchy )
                    //	EditorAPI.OpenDocumentWindowForObject( creationData.initDocumentWindow.Document, component );
                }
            }

            //finish creation
            creationData.ClearCreatedObjects();

            return(true);
        }
Example #8
0
        //[Browsable( false )]
        //public Component ParentComponent
        //{
        //	get { return initData.parentObject as Component; }
        //}

        public string GetFileCreationRealFileName()
        {
            return(IsFileCreation() ? VirtualPathUtility.GetRealPathByVirtual(textBoxName.Text) : "");
        }
Example #9
0
        public virtual void EditorActionClick(EditorAction.ClickContext context)
        {
            switch (context.Action.Name)
            {
            case "Save":
                Save(null);
                break;

            case "Save As":
            {
#if !DEPLOY
                var dialog = new CommonSaveFileDialog();
                dialog.InitialDirectory = Path.GetDirectoryName(RealFileName);
                dialog.DefaultFileName  = Path.GetFileName(RealFileName);
                dialog.Filters.Add(new CommonFileDialogFilter("All Files", ".*"));
                if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                {
                    return;
                }

                var saveAsFileName = dialog.FileName;

                //if( File.Exists( saveAsFileName ) )
                //{
                //	var text = string.Format( EditorLocalization.Translate( "General", "A file with the name \'{0}\' already exists. Overwrite?" ), saveAsFileName );
                //	if( EditorMessageBox.ShowQuestion( text, MessageBoxButtons.OKCancel ) != DialogResult.OK )
                //		return;
                //}

                if (string.Compare(RealFileName, saveAsFileName, true) == 0)
                {
                    Save();
                }
                else
                {
                    Save(saveAsFileName, false);
                    EditorAPI.OpenFileAsDocument(saveAsFileName, true, true);
                }
#endif
            }
            break;

            case "Undo":
                if (undoSystem != null)
                {
                    if (undoSystem.DoUndo())
                    {
                        Modified = true;
                    }
                }
                break;

            case "Redo":
                if (undoSystem != null)
                {
                    if (undoSystem.DoRedo())
                    {
                        Modified = true;
                    }
                }
                break;

            case "Play":
            {
                var component = LoadedResource?.ResultComponent;
                if (component != null && RunSimulation.CheckTypeSupportedByPlayer(component.BaseType))
                {
                    if (!EditorAPI.SaveDocuments())
                    {
                        return;
                    }
                    //if( Modified )
                    //{
                    //	if( !Save( null ) )
                    //		return;
                    //}

                    //!!!!не только standalone
                    var realFileName = VirtualPathUtility.GetRealPathByVirtual(LoadedResource.Owner.Name);
                    RunSimulation.Run(realFileName, RunSimulation.RunMethod.Player);
                }
            }
            break;

            case "Find Resource":
                if (!string.IsNullOrEmpty(RealFileName))
                {
                    EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { RealFileName });
                }
                break;
            }
        }
Example #10
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();
            }
        }