Пример #1
0
        /// <summary>
        /// The run algorithm.
        /// </summary>
        /// <returns>
        /// The <see cref="GraphHistory"/>.
        /// </returns>
        public GraphHistory RunAlgorithm()
        {
            this.graphHistory = new GraphHistory();

            var sourceNode   = this.residualGraph.Nodes.Find(n => n.Name.Equals(this.sourceNodeName));
            var terminalNode = this.residualGraph.Nodes.Find(n => n.Name.Equals(this.terminalNodeName));

            // add initial step to graph history
            this.graphHistory.AddGraphStep(this.flowGraph, this.residualGraph);

            Debug.WriteLine("\n** FordFulkerson");

            // MAX-FLOW
            this.FindMaxFlow(sourceNode, terminalNode);
            Debug.WriteLine("Max-Flow: {0}", this.MaxFlow);

            // MIN-CUT
            this.FindMinCut(sourceNode);
            this.graphHistory.AddGraphStep(this.flowGraph);

            Debug.WriteLine("Min-Cut: {0}", this.MinCut);

            Debug.WriteLine("Min-Cut-Nodes:");
            this.minCutNodes.ForEach(n => Debug.WriteLine(n.Name));

            Debug.WriteLine("Min-Cut-Edges:");
            this.minCutEdges.ForEach(e => Debug.WriteLine("{0}--{1}-->{2}", e.NodeFrom.Name, e.Capacity, e.NodeTo.Name));

            return(this.graphHistory);
        }
Пример #2
0
        // METHODS

        public MainWindow(string FileToLoad = "")
        {
            InitializeComponent();

            fileToLoad = FileToLoad;

            graphHistory = new GraphHistory();

            HistorySnapshop();
        }
Пример #3
0
        /// <summary>
        /// The execute calculate graph.
        /// </summary>
        private void ExecuteCalculateGraph()
        {
            const string Source        = "s";
            const string Target        = "t";
            var          fordFulkerson = new FordFulkerson(this.visualizedGraph, Source, Target);

            this.graphSteps   = fordFulkerson.RunAlgorithm();
            this.IsCalculated = true;
            this.MaxFlow      = fordFulkerson.MaxFlow;
            this.MinCut       = fordFulkerson.MinCut;

            this.currentStep = 0;
            this.RaiseFlowAndResidualGraphChanged(this);
        }
Пример #4
0
        /// <summary>
        /// Creates the graph history steps user controls.
        /// </summary>
        /// <param name="history">
        /// The history.
        /// </param>
        private void CreateGraphHistoryStepsUserControls(GraphHistory history)
        {
            foreach (GraphHistoryStep step in history)
            {
                var stepGrid = new Grid();
                stepGrid.ColumnDefinitions.Add(new ColumnDefinition());
                stepGrid.ColumnDefinitions.Add(new ColumnDefinition());

                var viewerFlow = this.CreateGraphViewer(new VisualGraph(step.FlowGraph).CreateFlowGraph());
                stepGrid.Children.Add(viewerFlow);
                viewerFlow.SetValue(Grid.ColumnProperty, 0);

                if (step.ResidualGraph != null)
                {
                    var viewerResidual =
                        this.CreateGraphViewer(new VisualGraph(step.ResidualGraph).CreateResidualGraph());
                    stepGrid.Children.Add(viewerResidual);
                    viewerResidual.SetValue(Grid.ColumnProperty, 1);
                }

                this.StepsStackPanel.Children.Add(stepGrid);
            }
        }
Пример #5
0
		private void FileMenuSelect( object objProperty )
		{
			if( objProperty.GetType() != typeof( FileMenuOptions ) )
			{
				return;
			}
			var option = (FileMenuOptions)objProperty;
			
			switch( option )
			{
			case FileMenuOptions.NewGraph:
			{
				if (EditorUtility.DisplayDialog("New Graph","Old graph will be lost, are you sure?","Confirm","Cancel")) {
					_nextGraph = new ShaderGraph();
					_nextGraph.Initialize( new Rect( 0, 0, Screen.width, Screen.height ), true);
					_graphNeedsUpdate = true;
					_lastGraphPath = "";
					_lastExportPath = "";
					_undoChain = new GraphHistory( _serializableTypes );
					_markDirtyOnLoad = true;
				}
				break;
			}
			case FileMenuOptions.ExportGraph:
			case FileMenuOptions.ExportAsGraph:
			{
				_shouldExportShader = true;
				if (!String.IsNullOrEmpty(_lastExportPath) && 
					option == FileMenuOptions.ExportGraph)
				{
					_quickExport = true;
				}

				if (!String.IsNullOrEmpty(_lastGraphPath))
				{
					_shouldSaveGraph = true;
					_quickSaving = true;
				}
				break;
			}
			case FileMenuOptions.SaveGraph:
			case FileMenuOptions.SaveAsGraph:
			{
				_shouldSaveGraph = true;
				if (!String.IsNullOrEmpty(_lastGraphPath) &&
					option == FileMenuOptions.SaveGraph)
				{
					_quickSaving = true;
				}
				break;
			}
			case FileMenuOptions.LoadGraph:
			{
				_shouldLoadGraph = true;
				break;
			}
			}
		}
Пример #6
0
		protected NodeEditor( )
		{
			_shaderEditorResourceDir = Application.dataPath
												+ Path.DirectorySeparatorChar
												+ "StrumpyShaderEditor"
												+ Path.DirectorySeparatorChar
												+ "Editor"
												+ Path.DirectorySeparatorChar
												+ "Resources"
												+ Path.DirectorySeparatorChar;
			_internalTempDir = "Internal"
							+ Path.DirectorySeparatorChar
							+ "Temp"
							+ Path.DirectorySeparatorChar;
			_internalTempUnityPath = "Internal/Temp/";
			_autosavePath = _shaderEditorResourceDir
							+ _internalTempDir
							+ "autosave.sgraph";
			_tempShaderPathFull = _shaderEditorResourceDir
								+ _internalTempDir
								+ TempShaderName + ".shader";
			_shaderTemplatePath = _shaderEditorResourceDir
								+ "Internal"
								+ Path.DirectorySeparatorChar
								+ "ShaderTemplate.template";
			_graphsDir = _shaderEditorResourceDir
								+ "Public"
								+ Path.DirectorySeparatorChar
								+ "Graphs";
			
			_selectedGraph = new ShaderGraph();
			
			_popupMenu = new PopupMenu( );
			
			//Find all the nodes that exist in the assembly (for submission to popup menu)
			var types = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes());
			foreach (var type in types)
			{
				foreach (var attribute in Attribute.GetCustomAttributes(type).OfType<NodeMetaData>())
				{
					NodeMetaData attribute2 = attribute;
					_popupMenu.AddItem( new ExecutableMenuItem( attribute.Category, attribute.DisplayName, 
								delegate( Vector2 location ){ 
									var toAdd = Activator.CreateInstance(attribute2.NodeType) as Node;
									if (toAdd == null)
									{
										return;
									}
									_selectedGraph.CurrentSubGraph.AddNode(toAdd);
									toAdd.NodePositionInGraph = new EditorRect( location.x, location.y, 10f, 10f);
									MarkDirty();
								}, String.IsNullOrEmpty(attribute.Descriptor) ? "" : attribute.Descriptor ) );
				}
			}
			_popupMenu.SortMenu();
			
			//Find all the serializable types
			_serializableTypes.Clear();
			foreach (var type in types)
			{
				var typeAttributes = Attribute.GetCustomAttributes(type);
				foreach (var attribute in typeAttributes)
				{
					if (attribute is DataContractAttribute)
					{
						_serializableTypes.Add(type);
					}
				}
			}
			
			//Finally load the last graph
			LoadLastGraph();
			_selectedGraph.Initialize( new Rect( 0,0, Screen.width, Screen.height ), true );
			_undoChain = new GraphHistory( _serializableTypes );
			
			_shouldOpenPreviewWindow = true;
		}
Пример #7
0
		public void Update()
		{
			wantsMouseMove = true;
			
			//Need to force recreate the preview window if transitioning from
			//game to editor or back
			if( _isPlayingInEditor != EditorApplication.isPlaying )
			{
				DisablePreview();
				_shouldOpenPreviewWindow = true;
				_isPlayingInEditor = EditorApplication.isPlaying;
			}
			
			if( _shouldOpenPreviewWindow && PreviewSupported() )
			{
				//Find the preview window
				var types = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes());
				var previewWindowType = types.FirstOrDefault( x => x.FullName == "StrumpyPreviewWindow" );
				if( previewWindowType != null )
				{
					_previewWindow = GetWindow( previewWindowType, true, "Preview" ) as PreviewWindowInternal;
					if (_previewWindow != null)
					{
						_previewWindow.Initialize(this);
						_previewWindow.wantsMouseMove = true;
						_previewWindow.ShouldUpdate = true;
						_shouldOpenPreviewWindow = false;
					}
				}
			}
			
			//Update preview
			if (_shouldUpdateShader)
			{
				if (_selectedGraph.IsGraphValid())
				{
					File.WriteAllText(_tempShaderPathFull, _selectedGraph.GetShader(_shaderTemplatePath, true));
					var currentShader = Resources.Load(_internalTempUnityPath + TempShaderName) as Shader;
					var path = AssetDatabase.GetAssetPath(currentShader);
					AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
					
					if( _previewWindow != null )
						_previewWindow.PreviewMaterial = new Material(currentShader);
					
					
					_graphNeedsUpdate = false;
					InstructionCounter.CountInstructions(); // Update the instruction count
					CacheCount(); // Solve the tooltip (Cached)
				}
				else
				{
					EditorUtility.DisplayDialog("Save Shader Error", "Cannot update shader, there are errors in the graph", "Ok");
				}
				_shouldUpdateShader = false;
			}
			
			//Save graph
			if (_shouldSaveGraph)
			{
				var path = _quickSaving ? _lastGraphPath : EditorUtility.SaveFilePanel("Save shader graph to file...", _graphsDir, "shader.sgraph", "sgraph");
				if (!string.IsNullOrEmpty(path))
				{
					var writer = new FileStream(path, FileMode.Create);
					var ser = new DataContractSerializer(typeof (ShaderGraph), _serializableTypes, int.MaxValue, false, false, null);
					ser.WriteObject(writer, _selectedGraph);
					writer.Close();
					_lastGraphPath = path;
				}
				_shouldSaveGraph = false;
				_quickSaving = false;
			}
			
			//Load graph
			if( _shouldLoadGraph )
			{
				var loadDir = _graphsDir;

				if(!String.IsNullOrEmpty(_lastGraphPath))
					loadDir = _lastGraphPath;

				var path = string.IsNullOrEmpty(_overrideLoadPath) ? EditorUtility.OpenFilePanel("Load shader graph...", loadDir, "sgraph") : _overrideLoadPath;
				bool didLoad = false;
						
				if (!string.IsNullOrEmpty(path))
				{
					try
					{
						using( var fs = new FileStream(path, FileMode.Open) )
						{
							using( var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()) )
							{
								var ser = new DataContractSerializer(typeof (ShaderGraph), _serializableTypes, int.MaxValue, false, false, null);
								var loaded = ser.ReadObject(reader, true) as ShaderGraph;
								if (loaded != null)
								{
									_undoChain = new GraphHistory( _serializableTypes );
									_nextGraph = loaded;
									loaded.Initialize( new Rect(0, 0, Screen.width, Screen.height), true);
									_lastGraphPath = path;
									_lastExportPath = "";
									didLoad = true;
								}
							}
						}
					}
					catch( Exception e ){
						Debug.Log( e );
					}
					//Try loading autosave graph (it's in a differnt xml format)
					try
					{
						if( !didLoad )
						{
							using( var fs = new FileStream(path, FileMode.Open) )
							{
								using( var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()) )
								{
									var ser = new DataContractSerializer(typeof(AutoSaveGraph), _serializableTypes, int.MaxValue, false, false, null);
									var loaded = ser.ReadObject(reader, true) as AutoSaveGraph;
									if (loaded != null)
									{
										_undoChain = new GraphHistory( _serializableTypes );
										_nextGraph = loaded.Graph;
										_nextGraph.Initialize( new Rect(0, 0, Screen.width, Screen.height), true);
										_lastGraphPath = "";
										_lastExportPath = "";
										didLoad = true;
									}
									
								}
							}
						}
					}
					catch( Exception e)
					{
						Debug.Log(e);
					}
					
					if( !didLoad )
					{
						EditorUtility.DisplayDialog("Load Shader Error", "Could not load shader", "Ok");
					}
				}
				_shouldLoadGraph = false;
				_shouldUpdateShader = true;
				_overrideLoadPath = "";
			}
			
			//Export the shader to a .shader file
			if (_shouldExportShader)
			{
				if (_selectedGraph.IsGraphValid())
				{
					var path = _quickExport ? _lastExportPath : EditorUtility.SaveFilePanel("Export shader to file...", Application.dataPath, "shader.shader", "shader");
					_lastExportPath = path; // For quick exporting - Texel
					if (!string.IsNullOrEmpty(path))
					{
						File.WriteAllText(path, _selectedGraph.GetShader(_shaderTemplatePath, false));
						AssetDatabase.Refresh(); // Investigate if this is optimal
					}
					
					InstructionCounter.CountInstructions(); // Update the instruction count
					CacheCount(); // Solve the tooltip (Cached)
				}
				else
				{
					EditorUtility.DisplayDialog("Export Shader Error", "Cannot export shader, there are errors in the graph", "Ok");
				}
				_shouldExportShader = false;
				_quickExport = false;
			}
			Repaint();
		}