diff --git a/Source/Core/Actions/Action.cs b/Source/Core/Actions/Action.cs index 24c0b774..1807f096 100644 --- a/Source/Core/Actions/Action.cs +++ b/Source/Core/Actions/Action.cs @@ -192,7 +192,8 @@ namespace CodeImp.DoomBuilder.Actions } //mxd. This returns the shortcut key description for an action name - public static string GetShortcutKeyDesc(string actionName) { + public static string GetShortcutKeyDesc(string actionName) + { Action a = General.Actions.GetActionByName(actionName); if(a.ShortcutKey == 0) return a.Title + " (not bound to a key)"; return GetShortcutKeyDesc(a.ShortcutKey); diff --git a/Source/Core/Actions/HintsManager.cs b/Source/Core/Actions/HintsManager.cs index 8f118e36..933e0145 100644 --- a/Source/Core/Actions/HintsManager.cs +++ b/Source/Core/Actions/HintsManager.cs @@ -36,7 +36,8 @@ namespace CodeImp.DoomBuilder.Actions #region ================== Constructor - public HintsManager() { + public HintsManager() + { hints = new Dictionary>(StringComparer.Ordinal); } @@ -46,39 +47,45 @@ namespace CodeImp.DoomBuilder.Actions //Hints.cfg is dev-only stuff so bare minimum of boilerplate is present //(e.g. create your Hints.cfg exactly the way it's done in the main project). - internal void LoadHints(Assembly asm) { + internal void LoadHints(Assembly asm) + { // Find a resource named Hints.cfg string[] resnames = asm.GetManifestResourceNames(); string asmname = asm.GetName().Name.ToLowerInvariant() + "_"; - foreach (string rn in resnames) { + foreach (string rn in resnames) + { // Found one? - if(rn.EndsWith(HINTS_RESOURCE, StringComparison.InvariantCultureIgnoreCase)) { + if(rn.EndsWith(HINTS_RESOURCE, StringComparison.InvariantCultureIgnoreCase)) + { string line; string classname = string.Empty; string groupname = string.Empty; List lines = new List(2); // Get a stream from the resource - using(Stream data = asm.GetManifestResourceStream(rn)) { - using(StreamReader reader = new StreamReader(data, Encoding.ASCII)) { - while (!reader.EndOfStream) { - lines.Add(reader.ReadLine()); - } + using(Stream data = asm.GetManifestResourceStream(rn)) + { + using(StreamReader reader = new StreamReader(data, Encoding.ASCII)) + { + while (!reader.EndOfStream) lines.Add(reader.ReadLine()); } } Dictionary> group = new Dictionary>(StringComparer.Ordinal); - foreach(string s in lines) { + foreach(string s in lines) + { line = s.Trim(); if(string.IsNullOrEmpty(line) || line.StartsWith("//")) continue; //class declaration? - if(line.StartsWith(CLASS_MARKER)) { - if(!string.IsNullOrEmpty(classname)) { - hints.Add(asmname + classname, processHints(group)); + if(line.StartsWith(CLASS_MARKER)) + { + if(!string.IsNullOrEmpty(classname)) + { + hints.Add(asmname + classname, ProcessHints(group)); } classname = line.Substring(6, line.Length - 6); @@ -88,7 +95,8 @@ namespace CodeImp.DoomBuilder.Actions } //group declaration? - if(line.StartsWith(GROUP_MARKER)) { + if(line.StartsWith(GROUP_MARKER)) + { groupname = line.Substring(6, line.Length - 6); group.Add(groupname, new List()); continue; @@ -99,7 +107,8 @@ namespace CodeImp.DoomBuilder.Actions //replace action names with keys int start = line.IndexOf(""); - while(start != -1) { + while(start != -1) + { int end = line.IndexOf(""); string key = line.Substring(start + 3, end - start - 3); line = line.Substring(0, start) + "{\\b " + Action.GetShortcutKeyDesc(key) + "}" + line.Substring(end + 4, line.Length - end - 4); @@ -110,24 +119,28 @@ namespace CodeImp.DoomBuilder.Actions } //add the last class - hints.Add(asmname + classname, processHints(group)); + hints.Add(asmname + classname, ProcessHints(group)); break; } } } - private static Dictionary processHints(Dictionary> hintsgroup) { + private static Dictionary ProcessHints(Dictionary> hintsgroup) + { var result = new Dictionary(StringComparer.Ordinal); - foreach(KeyValuePair> group in hintsgroup) { + foreach(KeyValuePair> group in hintsgroup) + { result.Add(group.Key, "{\\rtf1" + string.Join("\\par\\par ", group.Value.ToArray()) + "}"); } return result; } - public void ShowHints(Type type, string groupname) { + public void ShowHints(Type type, string groupname) + { string fullname = type.Assembly.GetName().Name.ToLowerInvariant() + "_" + type.Name; - if (!hints.ContainsKey(fullname) || !hints[fullname].ContainsKey(groupname)) { + if (!hints.ContainsKey(fullname) || !hints[fullname].ContainsKey(groupname)) + { General.Interface.ShowHints(DEFAULT_HINT); #if DEBUG Console.WriteLine("WARNING: Unable to get hints for class '" + fullname + "', group '" + groupname + "'"); @@ -141,7 +154,8 @@ namespace CodeImp.DoomBuilder.Actions #region ================== Utility - public static string GetRtfString(string text) { + public static string GetRtfString(string text) + { text = text.Replace("", "{\\b ").Replace("", "}").Replace("
", "\\par\\par "); return "{\\rtf1" + text + "}"; } diff --git a/Source/Core/Compilers/AccCompiler.cs b/Source/Core/Compilers/AccCompiler.cs index 1f5e4b6c..152a04f3 100644 --- a/Source/Core/Compilers/AccCompiler.cs +++ b/Source/Core/Compilers/AccCompiler.cs @@ -74,16 +74,19 @@ namespace CodeImp.DoomBuilder.Compilers //xabis // Copy includes from the resources into the compiler's folder, preserving relative pathing and naming - foreach (string include in General.Map.ScriptIncludes) { + foreach (string include in General.Map.ScriptIncludes) + { //grab the script text from the resources MemoryStream s = General.Map.Data.LoadFile(include); - if (s != null) { + if (s != null) + { //pull the pk3 or directory sub folder out if applicable FileInfo fi = new FileInfo(Path.Combine(this.tempdir.FullName, include)); //do not allow files to be overwritten, either accidentally or maliciously - if (!fi.Exists) { + if (!fi.Exists) + { General.WriteLogLine("Copying script include: " + include); //create the directory path as needed diff --git a/Source/Core/Compilers/Compiler.cs b/Source/Core/Compilers/Compiler.cs index d00f34d5..66af2c21 100644 --- a/Source/Core/Compilers/Compiler.cs +++ b/Source/Core/Compilers/Compiler.cs @@ -135,9 +135,12 @@ namespace CodeImp.DoomBuilder.Compilers foreach(string f in info.Files) { string sourcefile = Path.Combine(info.Path, f); - if (!File.Exists(sourcefile)) { + if (!File.Exists(sourcefile)) + { General.ErrorLogger.Add(ErrorType.Error, "The file '" + f + "' required by the '" + info.Name + "' compiler is missing. According to the compiler configuration in '" + info.FileName + "', the was expected to be found in the following path: " + info.Path); - } else { + } + else + { string targetfile = Path.Combine(tempdir.FullName, f); File.Copy(sourcefile, targetfile, true); } @@ -172,7 +175,8 @@ namespace CodeImp.DoomBuilder.Compilers try { // Go for all assemblies - foreach(Assembly a in asms) { + foreach(Assembly a in asms) + { // Find the class Type[] types = (Equals(a, General.ThisAssembly) ? a.GetTypes() : a.GetExportedTypes()); diff --git a/Source/Core/Compilers/NodesCompiler.cs b/Source/Core/Compilers/NodesCompiler.cs index f7db4b0c..eb5edf22 100644 --- a/Source/Core/Compilers/NodesCompiler.cs +++ b/Source/Core/Compilers/NodesCompiler.cs @@ -129,13 +129,15 @@ namespace CodeImp.DoomBuilder.Compilers General.WriteLogLine("Compile time: " + deltatime.TotalSeconds.ToString("########0.00") + " seconds"); //mxd - if (process.ExitCode > 0 || errorsInNormalOurput || errorsInErrorOutput) { - if (errorsInNormalOurput) { + if (process.ExitCode > 0 || errorsInNormalOurput || errorsInErrorOutput) + { + if (errorsInNormalOurput) + { ReportError(new CompilerError(outMsg)); General.WriteLogLine("Normal output: " + outMsg); } - - if (errorsInErrorOutput) { + if (errorsInErrorOutput) + { ReportError(new CompilerError(outErr)); General.WriteLogLine("Error output: " + outErr); } diff --git a/Source/Core/Config/ConfigurationInfo.cs b/Source/Core/Config/ConfigurationInfo.cs index c718af4b..87fe0e66 100644 --- a/Source/Core/Config/ConfigurationInfo.cs +++ b/Source/Core/Config/ConfigurationInfo.cs @@ -303,12 +303,13 @@ namespace CodeImp.DoomBuilder.Config //mxd private void SaveTestEngines() { - IDictionary resinfo, rlinfo; + IDictionary rlinfo; // Fill structure - resinfo = new ListDictionary(); + IDictionary resinfo = new ListDictionary(); - for(int i = 0; i < testEngines.Count; i++) { + for(int i = 0; i < testEngines.Count; i++) + { rlinfo = new ListDictionary(); rlinfo.Add("testprogramname", testEngines[i].TestProgramName); rlinfo.Add("testprogram", testEngines[i].TestProgram); @@ -328,12 +329,13 @@ namespace CodeImp.DoomBuilder.Config //mxd private void SaveLinedefColorPresets() { - IDictionary resinfo, rlinfo; + IDictionary rlinfo; // Fill structure - resinfo = new ListDictionary(); + IDictionary resinfo = new ListDictionary(); - for(int i = 0; i < linedefColorPresets.Length; i++) { + for(int i = 0; i < linedefColorPresets.Length; i++) + { rlinfo = new ListDictionary(); rlinfo.Add("name", linedefColorPresets[i].Name); rlinfo.Add("color", linedefColorPresets[i].Color.ToInt()); diff --git a/Source/Core/Config/GameConfiguration.cs b/Source/Core/Config/GameConfiguration.cs index 005d316b..e143395f 100644 --- a/Source/Core/Config/GameConfiguration.cs +++ b/Source/Core/Config/GameConfiguration.cs @@ -406,7 +406,8 @@ namespace CodeImp.DoomBuilder.Config #region ================== Loading // This loads the map lumps - private void LoadMapLumps() { + private void LoadMapLumps() + { // Get map lumps list IDictionary dic = cfg.ReadSetting("maplumpnames", new Hashtable()); foreach(DictionaryEntry de in dic) @@ -418,7 +419,8 @@ namespace CodeImp.DoomBuilder.Config } // This loads the enumerations - private void LoadEnums() { + private void LoadEnums() + { // Get enums list IDictionary dic = cfg.ReadSetting("enums", new Hashtable()); foreach(DictionaryEntry de in dic) @@ -805,7 +807,8 @@ namespace CodeImp.DoomBuilder.Config } // Texture Sets - private void LoadTextureSets() { + private void LoadTextureSets() + { // Get sets IDictionary dic = cfg.ReadSetting("texturesets", new Hashtable()); foreach(DictionaryEntry de in dic) @@ -846,7 +849,8 @@ namespace CodeImp.DoomBuilder.Config } //mxd - private void LoadStringDictionary(Dictionary target, string settingname) { + private void LoadStringDictionary(Dictionary target, string settingname) + { IDictionary dic = cfg.ReadSetting(settingname, new Hashtable()); foreach(DictionaryEntry de in dic) target.Add(de.Key.ToString(), de.Value.ToString()); diff --git a/Source/Core/Config/ProgramConfiguration.cs b/Source/Core/Config/ProgramConfiguration.cs index dc26b693..b7049954 100644 --- a/Source/Core/Config/ProgramConfiguration.cs +++ b/Source/Core/Config/ProgramConfiguration.cs @@ -482,7 +482,7 @@ namespace CodeImp.DoomBuilder.Config #region ================== Methods // This makes the path prefix for the given assembly - private string GetPluginPathPrefix(Assembly asm) + private static string GetPluginPathPrefix(Assembly asm) { Plugin p = General.Plugins.FindPluginByAssembly(asm); return GetPluginPathPrefix(p.Name); @@ -557,7 +557,8 @@ namespace CodeImp.DoomBuilder.Config //mxd. Set default arguments ThingTypeInfo tti = General.Map.Data.GetThingInfoEx(t.Type); - if (tti != null) { + if (tti != null) + { t.Args[0] = (int)tti.Args[0].DefaultValue; t.Args[1] = (int)tti.Args[1].DefaultValue; t.Args[2] = (int)tti.Args[2].DefaultValue; diff --git a/Source/Core/Config/ScriptConfiguration.cs b/Source/Core/Config/ScriptConfiguration.cs index bf567703..5cfb8f0f 100644 --- a/Source/Core/Config/ScriptConfiguration.cs +++ b/Source/Core/Config/ScriptConfiguration.cs @@ -200,20 +200,29 @@ namespace CodeImp.DoomBuilder.Config //mxd. Load Snippets string snippetsdir = cfg.ReadSetting("snippetsdir", ""); - if (!string.IsNullOrEmpty(snippetsdir)) { + if (!string.IsNullOrEmpty(snippetsdir)) + { string snippetspath = Path.Combine(General.SnippetsPath, snippetsdir); - if (Directory.Exists(snippetspath)) { + if (Directory.Exists(snippetspath)) + { string[] files = Directory.GetFiles(snippetspath, "*.txt", SearchOption.TopDirectoryOnly); - foreach (string file in files) { + foreach (string file in files) + { string name = Path.GetFileNameWithoutExtension(file); - if (name.Contains(" ")) { + if (name.Contains(" ")) + { General.ErrorLogger.Add(ErrorType.Warning, "Failed to load snippet '" + file + "' for '" + description + "' script configuration: snippet file name must not contain spaces!"); - } else { + } + else + { string[] lines = File.ReadAllLines(file); - if (lines.Length > 0) { + if (lines.Length > 0) + { snippets.Add(name, lines); - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Warning, "Failed to load snippet '" + file + "' for '" + description + "' script configuration: file is empty!"); } } diff --git a/Source/Core/Controls/ArgumentBox.cs b/Source/Core/Controls/ArgumentBox.cs index 5e0119dc..bf87bc83 100644 --- a/Source/Core/Controls/ArgumentBox.cs +++ b/Source/Core/Controls/ArgumentBox.cs @@ -90,7 +90,8 @@ namespace CodeImp.DoomBuilder.Controls private void combobox_Validating(object sender, CancelEventArgs e) { //mxd - if(gotTagArgument && combobox.SelectedItem != null) { + if(gotTagArgument && combobox.SelectedItem != null) + { typehandler.SetValue(((TagInfo)combobox.SelectedItem).Tag); return; } @@ -200,7 +201,8 @@ namespace CodeImp.DoomBuilder.Controls List tags = new List(); List infos = new List(); - foreach(Thing t in General.Map.Map.Things) { + foreach(Thing t in General.Map.Map.Things) + { if(t.Tag == 0 || tags.Contains(t.Tag)) continue; tags.Add(t.Tag); } @@ -209,7 +211,8 @@ namespace CodeImp.DoomBuilder.Controls tags.Sort(); //create tag infos - foreach(int tag in tags) { + foreach(int tag in tags) + { if(General.Map.Options.TagLabels.ContainsKey(tag)) //tag labels infos.Add(new TagInfo(tag, General.Map.Options.TagLabels[tag])); else @@ -234,7 +237,8 @@ namespace CodeImp.DoomBuilder.Controls List tags = new List(); List infos = new List(); - foreach(Linedef t in General.Map.Map.Linedefs) { + foreach(Linedef t in General.Map.Map.Linedefs) + { if(t.Tag == 0 || tags.Contains(t.Tag)) continue; tags.Add(t.Tag); } @@ -243,7 +247,8 @@ namespace CodeImp.DoomBuilder.Controls tags.Sort(); //create tag infos - foreach(int tag in tags) { + foreach(int tag in tags) + { if(General.Map.Options.TagLabels.ContainsKey(tag)) //tag labels infos.Add(new TagInfo(tag, General.Map.Options.TagLabels[tag])); else @@ -268,7 +273,8 @@ namespace CodeImp.DoomBuilder.Controls List tags = new List(); List infos = new List(); - foreach(Sector t in General.Map.Map.Sectors) { + foreach(Sector t in General.Map.Map.Sectors) + { if(t.Tag == 0 || tags.Contains(t.Tag)) continue; tags.Add(t.Tag); } @@ -277,7 +283,8 @@ namespace CodeImp.DoomBuilder.Controls tags.Sort(); //create tag infos - foreach(int tag in tags) { + foreach(int tag in tags) + { if(General.Map.Options.TagLabels.ContainsKey(tag)) //tag labels infos.Add(new TagInfo(tag, General.Map.Options.TagLabels[tag])); else @@ -295,7 +302,8 @@ namespace CodeImp.DoomBuilder.Controls combobox.DropDownWidth = Tools.GetDropDownWidth(combobox); } // Check if this supports enumerated options - else if(typehandler.IsEnumerable) { + else if(typehandler.IsEnumerable) + { // Show the combobox gotTagArgument = false; //mxd button.Visible = false; @@ -324,10 +332,13 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - if(gotTagArgument) { + if(gotTagArgument) + { combobox.AutoCompleteMode = AutoCompleteMode.Suggest; combobox.AutoCompleteSource = AutoCompleteSource.ListItems; - } else { + } + else + { combobox.AutoCompleteMode = AutoCompleteMode.None; combobox.AutoCompleteSource = AutoCompleteSource.None; } @@ -344,11 +355,13 @@ namespace CodeImp.DoomBuilder.Controls { typehandler.SetValue(value); - if(gotTagArgument) { //mxd - foreach(object item in combobox.Items) { + if(gotTagArgument) //mxd + { + foreach(object item in combobox.Items) + { TagInfo info = (TagInfo)item; - - if(info.Tag == value) { + if(info.Tag == value) + { combobox.SelectedItem = item; return; } @@ -361,7 +374,8 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. this sets default value - public void SetDefaultValue() { + public void SetDefaultValue() + { if(gotTagArgument) return; //default tag sounds a bit silly typehandler.SetDefaultValue(); @@ -432,8 +446,11 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. Very tricky way to close parent control by pressing ENTER or ESCAPE key when combobox.DropDownStyle == ComboBoxStyle.Simple - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if(this.ActiveControl == combobox && combobox.DropDownStyle == ComboBoxStyle.Simple && (keyData == Keys.Return || keyData == Keys.Escape)) { + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if(this.ActiveControl == combobox && combobox.DropDownStyle == ComboBoxStyle.Simple + && (keyData == Keys.Return || keyData == Keys.Escape)) + { combobox.DropDownStyle = ComboBoxStyle.DropDown; return false; } diff --git a/Source/Core/Controls/CheckboxArrayControl.cs b/Source/Core/Controls/CheckboxArrayControl.cs index 6911716a..653ddb22 100644 --- a/Source/Core/Controls/CheckboxArrayControl.cs +++ b/Source/Core/Controls/CheckboxArrayControl.cs @@ -130,7 +130,7 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - private int CheckboxesComparison(CheckBox cb1, CheckBox cb2) + private static int CheckboxesComparison(CheckBox cb1, CheckBox cb2) { return String.Compare(cb1.Text, cb2.Text, StringComparison.Ordinal); } diff --git a/Source/Core/Controls/DebugConsole.cs b/Source/Core/Controls/DebugConsole.cs index dd5a9393..4b4d02bc 100644 --- a/Source/Core/Controls/DebugConsole.cs +++ b/Source/Core/Controls/DebugConsole.cs @@ -14,11 +14,11 @@ namespace CodeImp.DoomBuilder [Flags] public enum DebugMessageType { - Log = 1, - Info = 2, - Warning = 4, - Error = 8, - Special = 16, + LOG = 1, + INFO = 2, + WARNING = 4, + ERROR = 8, + SPECIAL = 16, } #endregion @@ -61,20 +61,20 @@ namespace CodeImp.DoomBuilder // Setup colors textcolors = new Dictionary { - { DebugMessageType.Log, SystemColors.WindowText }, - { DebugMessageType.Info, Color.DarkGreen }, - { DebugMessageType.Warning, Color.DarkOrange }, - { DebugMessageType.Error, Color.DarkRed }, - { DebugMessageType.Special, Color.DarkMagenta } + { DebugMessageType.LOG, SystemColors.WindowText }, + { DebugMessageType.INFO, Color.DarkGreen }, + { DebugMessageType.WARNING, Color.DarkOrange }, + { DebugMessageType.ERROR, Color.DarkRed }, + { DebugMessageType.SPECIAL, Color.DarkMagenta } }; // Setup headers textheaders = new Dictionary { - { DebugMessageType.Log, string.Empty}, - { DebugMessageType.Info, string.Empty}, - { DebugMessageType.Warning, "Warning: "}, - { DebugMessageType.Error, "ERROR: "}, - { DebugMessageType.Special, string.Empty} + { DebugMessageType.LOG, string.Empty}, + { DebugMessageType.INFO, string.Empty}, + { DebugMessageType.WARNING, "Warning: "}, + { DebugMessageType.ERROR, "ERROR: "}, + { DebugMessageType.SPECIAL, string.Empty} }; // Word wrap? @@ -90,12 +90,12 @@ namespace CodeImp.DoomBuilder public static void Write(string text) { - Write(DebugMessageType.Info, text); + Write(DebugMessageType.INFO, text); } public static void WriteLine(string text) { - Write(DebugMessageType.Info, text + Environment.NewLine); + Write(DebugMessageType.INFO, text + Environment.NewLine); } public static void Write(DebugMessageType type, string text) @@ -142,7 +142,7 @@ namespace CodeImp.DoomBuilder { if (starttime == -1) { - Write(DebugMessageType.Warning, "Call General.Console.StartTimer before General.Console.StopTimer!"); + Write(DebugMessageType.WARNING, "Call General.Console.StartTimer before General.Console.StopTimer!"); } else { @@ -153,7 +153,7 @@ namespace CodeImp.DoomBuilder else message = message.TrimEnd() + " " + (endtime - starttime) + " ms."; - Write(DebugMessageType.Special, message); + Write(DebugMessageType.SPECIAL, message); } starttime = -1; @@ -199,7 +199,7 @@ namespace CodeImp.DoomBuilder } // Should we display this message? - private bool CheckTextFilter(string text, string filter) + private static bool CheckTextFilter(string text, string filter) { if (string.IsNullOrEmpty(filter) || filter.Length < 3) return true; return text.ToUpperInvariant().Contains(filter.ToUpperInvariant()); diff --git a/Source/Core/Controls/DebugConsole.designer.cs b/Source/Core/Controls/DebugConsole.designer.cs index 55fedebd..7c85afcf 100644 --- a/Source/Core/Controls/DebugConsole.designer.cs +++ b/Source/Core/Controls/DebugConsole.designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); diff --git a/Source/Core/Controls/DockersControl.cs b/Source/Core/Controls/DockersControl.cs index 89e6b49b..ee50244d 100644 --- a/Source/Core/Controls/DockersControl.cs +++ b/Source/Core/Controls/DockersControl.cs @@ -257,10 +257,10 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. This checks if given docker exists in this control - public bool Contains(Docker d) { - foreach (TabPage page in tabs.TabPages) { + public bool Contains(Docker d) + { + foreach (TabPage page in tabs.TabPages) if ((page.Tag as Docker) == d) return true; - } return false; } @@ -440,13 +440,13 @@ namespace CodeImp.DoomBuilder.Controls General.MainWindow.Update(); // Raise event - if(UserResize != null) - UserResize(this, EventArgs.Empty); + if(UserResize != null) UserResize(this, EventArgs.Empty); } } //mxd - private void buttonTogglePinning_Click(object sender, EventArgs e) { + private void buttonTogglePinning_Click(object sender, EventArgs e) + { General.Settings.CollapseDockers = !General.Settings.CollapseDockers; General.MainWindow.SetupInterface(); buttonTogglePinning.Image = General.Settings.CollapseDockers ? Properties.Resources.Unpin : Properties.Resources.Pin; diff --git a/Source/Core/Controls/FieldsEditorControl.cs b/Source/Core/Controls/FieldsEditorControl.cs index 2452b15c..4b47c9b4 100644 --- a/Source/Core/Controls/FieldsEditorControl.cs +++ b/Source/Core/Controls/FieldsEditorControl.cs @@ -121,7 +121,8 @@ namespace CodeImp.DoomBuilder.Controls public void ListFixedFields(List list) { // Add all fields - foreach(UniversalFieldInfo uf in list) { + foreach(UniversalFieldInfo uf in list) + { if(uifields.ContainsKey(uf.Name)) continue; //mxd fieldslist.Rows.Add(new FieldsEditorRow(fieldslist, uf)); } @@ -237,48 +238,6 @@ namespace CodeImp.DoomBuilder.Controls // Sort fields Sort(); } - - //mxd - /*public object GetValue(string name) { - //have required row? - foreach (DataGridViewRow row in fieldslist.Rows) { - // Row is a field? - if (row is FieldsEditorRow) { - FieldsEditorRow frow = row as FieldsEditorRow; - // Row name matches with field - if (frow.Name == name) { - // Apply value of field to row - if (frow.IsDefined && !frow.IsEmpty) - return frow.GetResult(null); - return null; - } - } - } - - return null; - }*/ - - //mxd - /*public void SetValue(string name, object value, UniversalType type) { - //have required row? - foreach (DataGridViewRow row in fieldslist.Rows) { - // Row is a field? - if (row is FieldsEditorRow) { - FieldsEditorRow frow = row as FieldsEditorRow; - // Row name matches with field - if (frow.Name == name) { - // Apply value of field to row - frow.Define(value); - return; - } - } - } - - //no such row... let's add it - FieldsEditorRow newfrow = new FieldsEditorRow(fieldslist, name, (int)type, value); - fieldslist.Rows.Insert(fieldslist.Rows.Count - 1, newfrow); - }*/ - // This applies the current fields to a UniFields object public void Apply(UniFields tofields) @@ -287,7 +246,8 @@ namespace CodeImp.DoomBuilder.Controls // Go for all the fields UniFields tempfields = new UniFields(tofields); - foreach(KeyValuePair f in tempfields) { + foreach(KeyValuePair f in tempfields) + { if (uifields.ContainsKey(f.Key)) continue; //mxd // Go for all rows @@ -544,15 +504,19 @@ namespace CodeImp.DoomBuilder.Controls string validname = UniValue.ValidateName(row.Cells[0].Value.ToString()); if(validname.Length > 0) { - if(uifields.ContainsKey(validname)) { //mxd + if(uifields.ContainsKey(validname)) //mxd + { MessageBox.Show("Please set this field's value via user interface."); - } else { + } + else + { // Check if no other row already has this name foreach (DataGridViewRow r in fieldslist.Rows) { // Name matches and not the same row? if ((r.Index != row.Index) && (r.Cells.Count > 0) && (r.Cells[0].Value != null) && - (r.Cells[0].Value.ToString().ToLowerInvariant() == validname)) { + (r.Cells[0].Value.ToString().ToLowerInvariant() == validname)) + { // Cannot have two rows with same name validname = ""; General.ShowWarningMessage("Fields must have unique names!", MessageBoxButtons.OK); diff --git a/Source/Core/Controls/HintsPanel.Designer.cs b/Source/Core/Controls/HintsPanel.Designer.cs index f9267e08..777c32ed 100644 --- a/Source/Core/Controls/HintsPanel.Designer.cs +++ b/Source/Core/Controls/HintsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HintsPanel)); this.label1 = new System.Windows.Forms.Label(); this.hints = new System.Windows.Forms.RichTextBox(); diff --git a/Source/Core/Controls/HintsPanel.cs b/Source/Core/Controls/HintsPanel.cs index 2731ce32..051ce099 100644 --- a/Source/Core/Controls/HintsPanel.cs +++ b/Source/Core/Controls/HintsPanel.cs @@ -5,23 +5,27 @@ namespace CodeImp.DoomBuilder.Controls { internal partial class HintsPanel : UserControl { - public HintsPanel() { + public HintsPanel() + { InitializeComponent(); hints.Clear(); } //hints should be in rtf markup! - internal void SetHints(string hintsText) { + internal void SetHints(string hintsText) + { hints.Clear(); hints.SelectedRtf = hintsText; } - internal void ClearHints() { + internal void ClearHints() + { hints.Clear(); } // Fight TextBoxes habit of not releasing the focus by using a carefully placed label - private void hints_Enter(object sender, EventArgs e) { + private void hints_Enter(object sender, EventArgs e) + { label1.Focus(); } } diff --git a/Source/Core/Controls/ImageBrowserControl.Designer.cs b/Source/Core/Controls/ImageBrowserControl.Designer.cs index c4bf8c88..eca74e59 100644 --- a/Source/Core/Controls/ImageBrowserControl.Designer.cs +++ b/Source/Core/Controls/ImageBrowserControl.Designer.cs @@ -123,7 +123,7 @@ namespace CodeImp.DoomBuilder.Controls this.showtexturesize.Location = new System.Drawing.Point(470, 9); this.showtexturesize.Name = "showtexturesize"; this.showtexturesize.Size = new System.Drawing.Size(109, 18); - this.showtexturesize.TabIndex = 2; + this.showtexturesize.TabIndex = 0; this.showtexturesize.Text = "Show image size"; this.showtexturesize.UseVisualStyleBackColor = true; this.showtexturesize.CheckedChanged += new System.EventHandler(this.showtexturesize_CheckedChanged); @@ -134,7 +134,7 @@ namespace CodeImp.DoomBuilder.Controls this.longtexturenames.Location = new System.Drawing.Point(585, 9); this.longtexturenames.Name = "longtexturenames"; this.longtexturenames.Size = new System.Drawing.Size(122, 18); - this.longtexturenames.TabIndex = 1; + this.longtexturenames.TabIndex = 0; this.longtexturenames.Text = "Long texture names"; this.longtexturenames.UseVisualStyleBackColor = true; this.longtexturenames.CheckedChanged += new System.EventHandler(this.longtexturenames_CheckedChanged); diff --git a/Source/Core/Controls/ImageBrowserControl.cs b/Source/Core/Controls/ImageBrowserControl.cs index 01991681..87a4bfa0 100644 --- a/Source/Core/Controls/ImageBrowserControl.cs +++ b/Source/Core/Controls/ImageBrowserControl.cs @@ -325,7 +325,7 @@ namespace CodeImp.DoomBuilder.Controls foreach(ListViewItem item in list.Items) { ImageBrowserItem curitem = item as ImageBrowserItem; - if(curitem != null && string.Compare(curitem.icon.Name, name, true) == 0) + if(curitem != null && string.Compare(curitem.Icon.Name, name, true) == 0) { lvi = curitem; if(item.Group == preferredgroup) break; @@ -536,9 +536,9 @@ namespace CodeImp.DoomBuilder.Controls //mxd. mixMode: 0 = All, 1 = Textures, 2 = Flats, 3 = Based on BrowseFlats if(!splitter.Panel2Collapsed) { - if(mixMode == 1 && i.icon.IsFlat) return false; - if(mixMode == 2 && !i.icon.IsFlat) return false; - if(mixMode == 3 && (browseFlats != i.icon.IsFlat)) return false; + if(mixMode == 1 && i.Icon.IsFlat) return false; + if(mixMode == 2 && !i.Icon.IsFlat) return false; + if(mixMode == 3 && (browseFlats != i.Icon.IsFlat)) return false; } return i.Text.ToUpperInvariant().Contains(objectname.Text.ToUpperInvariant()); @@ -547,9 +547,9 @@ namespace CodeImp.DoomBuilder.Controls //mxd. This validates an item's texture size private static bool ValidateItemSize(ImageBrowserItem i, int w, int h) { - if (!i.icon.IsPreviewLoaded) return true; - if (w > 0 && i.icon.Width != w) return false; - if (h > 0 && i.icon.Height != h) return false; + if (!i.Icon.IsPreviewLoaded) return true; + if (w > 0 && i.Icon.Width != w) return false; + if (h > 0 && i.Icon.Height != h) return false; return true; } diff --git a/Source/Core/Controls/ImageBrowserItem.cs b/Source/Core/Controls/ImageBrowserItem.cs index 3c9519ba..84a986c0 100644 --- a/Source/Core/Controls/ImageBrowserItem.cs +++ b/Source/Core/Controls/ImageBrowserItem.cs @@ -38,7 +38,7 @@ namespace CodeImp.DoomBuilder.Controls #region ================== Variables // Display image and text - public readonly ImageData icon; + public readonly ImageData Icon; private string imagesize; //mxd private bool showfullname; //mxd private static readonly StringFormat format = new StringFormat { Alignment = StringAlignment.Center }; //mxd @@ -56,7 +56,7 @@ namespace CodeImp.DoomBuilder.Controls public ListViewGroup ListGroup { get { return listgroup; } set { listgroup = value; } } public bool IsPreviewLoaded { get { return imageloaded; } } public bool ShowFullName { set { showfullname = value; UpdateName(); } } - public string TextureName { get { return showfullname ? icon.Name : icon.ShortName; } } + public string TextureName { get { return showfullname ? Icon.Name : Icon.ShortName; } } #endregion @@ -66,7 +66,7 @@ namespace CodeImp.DoomBuilder.Controls public ImageBrowserItem(ImageData icon, object tag, bool showfullname) { // Initialize - this.icon = icon; + this.Icon = icon; this.Tag = tag; this.showfullname = showfullname; //mxd UpdateName(); //mxd @@ -80,7 +80,7 @@ namespace CodeImp.DoomBuilder.Controls public bool CheckRedrawNeeded() { UpdateName(); //mxd. Update texture size if needed - return (icon.IsPreviewLoaded != imageloaded); + return (Icon.IsPreviewLoaded != imageloaded); } // This draws the images @@ -90,7 +90,7 @@ namespace CodeImp.DoomBuilder.Controls Brush backcolor; // Remember if the preview is loaded - imageloaded = icon.IsPreviewLoaded; + imageloaded = Icon.IsPreviewLoaded; // Drawing settings g.CompositingQuality = CompositingQuality.HighSpeed; @@ -123,7 +123,7 @@ namespace CodeImp.DoomBuilder.Controls // Draw! g.FillRectangle(backcolor, bounds); - icon.DrawPreview(g, imagerect.Location); + Icon.DrawPreview(g, imagerect.Location); g.DrawString(Text, this.ListView.Font, forecolor, textpos, format); //mxd. Draw size label? @@ -134,11 +134,11 @@ namespace CodeImp.DoomBuilder.Controls textsize = g.MeasureString(imagesize, sizefont, bounds.Width * 2); textpos = new PointF(bounds.Left + textsize.Width / 2, bounds.Top + 1); imagerect = new Rectangle(bounds.Left + 1, bounds.Top + 1, (int)textsize.Width, (int)textsize.Height); - SolidBrush labelbg = new SolidBrush(Color.FromArgb(196, base.ListView.BackColor)); + SolidBrush labelbg = new SolidBrush(Color.FromArgb(196, base.ListView.ForeColor)); // Draw g.FillRectangle(labelbg, imagerect); - g.DrawString(imagesize, sizefont, new SolidBrush(base.ListView.ForeColor), textpos, format); + g.DrawString(imagesize, sizefont, new SolidBrush(base.ListView.BackColor), textpos, format); } } @@ -165,9 +165,9 @@ namespace CodeImp.DoomBuilder.Controls //mxd private void UpdateName() { - Text = (showfullname ? icon.DisplayName : icon.ShortName); - if(General.Settings.ShowTextureSizes && icon.IsPreviewLoaded) - imagesize = icon.ScaledWidth + "x" + icon.ScaledHeight; + Text = (showfullname ? Icon.DisplayName : Icon.ShortName); + if(General.Settings.ShowTextureSizes && Icon.IsPreviewLoaded) + imagesize = Icon.ScaledWidth + "x" + Icon.ScaledHeight; } // Comparer diff --git a/Source/Core/Controls/RenderTargetControl.cs b/Source/Core/Controls/RenderTargetControl.cs index 2eb6c43c..dd5be07f 100644 --- a/Source/Core/Controls/RenderTargetControl.cs +++ b/Source/Core/Controls/RenderTargetControl.cs @@ -60,7 +60,8 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - protected override void OnKeyUp(KeyEventArgs e) { + protected override void OnKeyUp(KeyEventArgs e) + { if(OnKeyReleased != null) OnKeyReleased(this, e); } diff --git a/Source/Core/Controls/ResourceListView.cs b/Source/Core/Controls/ResourceListView.cs index 690c8e38..4b731b6a 100644 --- a/Source/Core/Controls/ResourceListView.cs +++ b/Source/Core/Controls/ResourceListView.cs @@ -121,7 +121,8 @@ namespace CodeImp.DoomBuilder.Controls Point cp; //mxd. Check if valid extenal data is present - if(e.Data.GetDataPresent(DataFormats.FileDrop)) { + if(e.Data.GetDataPresent(DataFormats.FileDrop)) + { e.Effect = DragDropEffects.Copy; return; } @@ -218,7 +219,8 @@ namespace CodeImp.DoomBuilder.Controls base.OnDragEnter(e); //mxd. Check if valid extenal data is present - if(e.Data.GetDataPresent(DataFormats.FileDrop)) { + if(e.Data.GetDataPresent(DataFormats.FileDrop)) + { e.Effect = DragDropEffects.Copy; return; } diff --git a/Source/Core/Controls/ScintillaControl.cs b/Source/Core/Controls/ScintillaControl.cs index 19535536..dbfc254b 100644 --- a/Source/Core/Controls/ScintillaControl.cs +++ b/Source/Core/Controls/ScintillaControl.cs @@ -2314,14 +2314,14 @@ namespace CodeImp.DoomBuilder.Controls this.ignoredkeys.Add((int)key + (int)modifier, (int)key + (int)modifier); } - private void addShortcuts(Menu m) + private void AddShortcuts(Menu m) { foreach(MenuItem mi in m.MenuItems) { if(mi.Shortcut != Shortcut.None) AddIgnoredKey(mi.Shortcut); if(mi.MenuItems.Count > 0) - addShortcuts(mi); + AddShortcuts(mi); } } @@ -2329,7 +2329,7 @@ namespace CodeImp.DoomBuilder.Controls { if((parentForm != null) && (parentForm.Menu != null)) { - addShortcuts(parentForm.Menu); + AddShortcuts(parentForm.Menu); } } diff --git a/Source/Core/Controls/ScriptDocumentTab.cs b/Source/Core/Controls/ScriptDocumentTab.cs index ac2c966e..c0c35abf 100644 --- a/Source/Core/Controls/ScriptDocumentTab.cs +++ b/Source/Core/Controls/ScriptDocumentTab.cs @@ -49,8 +49,7 @@ namespace CodeImp.DoomBuilder.Controls // The script edit control protected readonly ScriptEditorControl editor; - //mxd - protected readonly ComboBox navigator; + protected readonly ComboBox navigator; //mxd // Derived classes must set this! protected ScriptConfiguration config; @@ -198,7 +197,7 @@ namespace CodeImp.DoomBuilder.Controls // This changes the script configurations public virtual void ChangeScriptConfig(ScriptConfiguration newconfig) { - updateNavigator(); //mxd + UpdateNavigator(); //mxd } // Call this to set the tab title @@ -307,21 +306,23 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - protected void updateNavigator() + protected void UpdateNavigator() { //mxd. known script type? - if (config.ScriptType != ScriptType.UNKNOWN) { - switch(config.ScriptType) { + if (config.ScriptType != ScriptType.UNKNOWN) + { + switch(config.ScriptType) + { case ScriptType.ACS: - updateNavigatorAcs(new MemoryStream(editor.GetText())); + UpdateNavigatorAcs(new MemoryStream(editor.GetText())); break; case ScriptType.DECORATE: - updateNavigatorDecorate(new MemoryStream(editor.GetText())); + UpdateNavigatorDecorate(new MemoryStream(editor.GetText())); break; case ScriptType.MODELDEF: - updateNavigatorModeldef(new MemoryStream(editor.GetText())); + UpdateNavigatorModeldef(new MemoryStream(editor.GetText())); break; default: @@ -329,14 +330,16 @@ namespace CodeImp.DoomBuilder.Controls } navigator.Enabled = true; - }else{ + } + else + { navigator.Items.Clear(); navigator.Enabled = false; } } //mxd - private void updateNavigatorDecorate(MemoryStream stream) + private void UpdateNavigatorDecorate(MemoryStream stream) { if (stream == null) return; @@ -351,7 +354,7 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - private void updateNavigatorModeldef(MemoryStream stream) + private void UpdateNavigatorModeldef(MemoryStream stream) { if (stream == null) return; @@ -366,7 +369,7 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - private void updateNavigatorAcs(MemoryStream stream) + private void UpdateNavigatorAcs(MemoryStream stream) { if (stream == null) return; @@ -386,7 +389,8 @@ namespace CodeImp.DoomBuilder.Controls internal ScriptType VerifyScriptType() { ScriptTypeParserSE parser = new ScriptTypeParserSE(); - if (parser.Parse(new MemoryStream(editor.GetText()), config.Description)) { + if (parser.Parse(new MemoryStream(editor.GetText()), config.Description)) + { if (parser.ScriptType != ScriptType.UNKNOWN && config.ScriptType != parser.ScriptType) return parser.ScriptType; } @@ -424,8 +428,10 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - protected void navigator_SelectedIndexChanged(object sender, EventArgs e) { - if (navigator.SelectedItem is ScriptItem) { + private void navigator_SelectedIndexChanged(object sender, EventArgs e) + { + if (navigator.SelectedItem is ScriptItem) + { ScriptItem si = navigator.SelectedItem as ScriptItem; editor.EnsureLineVisible(editor.LineFromPosition(si.SelectionStart)); editor.SelectionStart = si.SelectionStart; @@ -438,8 +444,9 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - protected void navigator_DropDown(object sender, EventArgs e) { - if(editor.IsChanged) updateNavigator(); + private void navigator_DropDown(object sender, EventArgs e) + { + if(editor.IsChanged) UpdateNavigator(); } #endregion diff --git a/Source/Core/Controls/ScriptEditorControl.cs b/Source/Core/Controls/ScriptEditorControl.cs index 3054604b..0435146a 100644 --- a/Source/Core/Controls/ScriptEditorControl.cs +++ b/Source/Core/Controls/ScriptEditorControl.cs @@ -664,15 +664,18 @@ namespace CodeImp.DoomBuilder.Controls string spaces = new String(' ', General.Settings.ScriptTabWidth); int entrypos = -1; int entryline = -1; - string[] processedlines = processLineBreaks(lines); + string[] processedlines = ProcessLineBreaks(lines); - for (int i = 0; i < lines.Length; i++) { + for (int i = 0; i < lines.Length; i++) + { processedlines[i] = processedlines[i].Replace("\t", spaces); //check if we have the [EP] marker - if (entrypos == -1) { + if (entrypos == -1) + { int pos = processedlines[i].IndexOf("[EP]"); - if (pos != -1) { + if (pos != -1) + { entryline = curline + i; entrypos = pos + numtabs; processedlines[i] = processedlines[i].Remove(pos, 4); @@ -687,7 +690,8 @@ namespace CodeImp.DoomBuilder.Controls scriptedit.ReplaceSel(text); //move the cursor if we had the [EP] marker - if (entrypos != -1) { + if (entrypos != -1) + { MoveToLine(entryline); scriptedit.SelectionStart = scriptedit.PositionFromLine(entryline) + entrypos; scriptedit.SelectionEnd = scriptedit.PositionFromLine(entryline) + entrypos; @@ -695,19 +699,22 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. This converts [LB] markers to line breaks if necessary - private static string[] processLineBreaks(string[] lines) + private static string[] ProcessLineBreaks(string[] lines) { List result = new List(lines.Length); string[] separator = new[] { "[LB]" }; - foreach(string line in lines) { - if(line.IndexOf(separator[0]) != -1) { - if(General.Settings.SnippetsAllmanStyle) { + foreach(string line in lines) + { + if(line.IndexOf(separator[0]) != -1) + { + if(General.Settings.SnippetsAllmanStyle) result.AddRange(line.Split(separator, StringSplitOptions.RemoveEmptyEntries)); - } else { + else result.Add(line.Replace(separator[0], " ")); - } - } else { + } + else + { result.Add(line); } } @@ -912,11 +919,10 @@ namespace CodeImp.DoomBuilder.Controls int tippos; int funcline = scriptedit.LineFromPosition(curfunctionstartpos); int curline = scriptedit.LineFromPosition(scriptedit.CurrentPos); - if(curline > funcline) { + if(curline > funcline) tippos = scriptedit.PositionFromLine(curline) + scriptedit.GetLineIndentation(curline); //scriptedit.PositionFromLine(curline) /*+ (curfunctionstartpos - scriptedit.PositionFromLine(funcline))*/; - } else { + else tippos = curfunctionstartpos; - } // Show tip scriptedit.CallTipShow(tippos, functiondef); diff --git a/Source/Core/Controls/ScriptEditorPanel.cs b/Source/Core/Controls/ScriptEditorPanel.cs index b0fe6971..6919b468 100644 --- a/Source/Core/Controls/ScriptEditorPanel.cs +++ b/Source/Core/Controls/ScriptEditorPanel.cs @@ -134,13 +134,13 @@ namespace CodeImp.DoomBuilder.Controls } } - // Select the first tab - //if(tabs.TabPages.Count > 0) tabs.SelectedIndex = 0; - //mxd. Select "Scripts" tab, because that's what user will want 99% of time - if (tabs.TabPages.Count > 0) { - foreach (TabPage p in tabs.TabPages) { - if (p.Text == "SCRIPTS") { + if (tabs.TabPages.Count > 0) + { + foreach (TabPage p in tabs.TabPages) + { + if (p.Text == "SCRIPTS") + { tabs.SelectedTab = p; break; } @@ -494,10 +494,10 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. Add snippets - if(t.Config.Snippets.Count > 0) { - foreach(KeyValuePair group in t.Config.Snippets) { + if(t.Config.Snippets.Count > 0) + { + foreach(KeyValuePair group in t.Config.Snippets) buttonsnippets.DropDownItems.Add(group.Key).Click += OnInsertSnippetClick; - } } // Focus to script editor @@ -530,9 +530,12 @@ namespace CodeImp.DoomBuilder.Controls { //mxd ScriptType st = t.VerifyScriptType(); - if (st != ScriptType.UNKNOWN) { - foreach (ScriptConfiguration cfg in scriptconfigs) { - if (cfg.ScriptType == st) { + if (st != ScriptType.UNKNOWN) + { + foreach (ScriptConfiguration cfg in scriptconfigs) + { + if (cfg.ScriptType == st) + { t.ChangeScriptConfig(cfg); break; } @@ -540,8 +543,7 @@ namespace CodeImp.DoomBuilder.Controls } // Mark any errors this script may have - if(compilererrors != null) - t.MarkScriptErrors(compilererrors); + if(compilererrors != null) t.MarkScriptErrors(compilererrors); // Add to tabs tabs.TabPages.Add(t); @@ -579,7 +581,8 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. This launches keyword help website - public bool LaunchKeywordHelp() { + public bool LaunchKeywordHelp() + { // Get script ScriptDocumentTab t = (tabs.SelectedTab as ScriptDocumentTab); return t.LaunchKeywordHelp(); diff --git a/Source/Core/Controls/ScriptFileDocumentTab.cs b/Source/Core/Controls/ScriptFileDocumentTab.cs index 4964c933..735d1d6f 100644 --- a/Source/Core/Controls/ScriptFileDocumentTab.cs +++ b/Source/Core/Controls/ScriptFileDocumentTab.cs @@ -119,9 +119,8 @@ namespace CodeImp.DoomBuilder.Controls } //mxd. Should be called only if script is compiled successfully - if (compiler.Errors.Length == 0 && config.ScriptType == ScriptType.ACS) { + if (compiler.Errors.Length == 0 && config.ScriptType == ScriptType.ACS) General.Map.UpdateScriptNames(); - } } // Dispose compiler diff --git a/Source/Core/Controls/ScriptLumpDocumentTab.cs b/Source/Core/Controls/ScriptLumpDocumentTab.cs index e8bc43ab..18fe1ac6 100644 --- a/Source/Core/Controls/ScriptLumpDocumentTab.cs +++ b/Source/Core/Controls/ScriptLumpDocumentTab.cs @@ -74,7 +74,7 @@ namespace CodeImp.DoomBuilder.Controls editor.SetText(stream.ToArray()); editor.ClearUndoRedo(); //mxd - updateNavigator(); + UpdateNavigator(); } // Done diff --git a/Source/Core/Controls/SectorSlopeControl.Designer.cs b/Source/Core/Controls/SectorSlopeControl.Designer.cs index 9ccfed3a..ec8492d2 100644 --- a/Source/Core/Controls/SectorSlopeControl.Designer.cs +++ b/Source/Core/Controls/SectorSlopeControl.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.label23 = new System.Windows.Forms.Label(); this.label24 = new System.Windows.Forms.Label(); this.reset = new System.Windows.Forms.Button(); diff --git a/Source/Core/Controls/SplitButton.cs b/Source/Core/Controls/SplitButton.cs index 25bcf4d1..c4345275 100644 --- a/Source/Core/Controls/SplitButton.cs +++ b/Source/Core/Controls/SplitButton.cs @@ -10,9 +10,9 @@ namespace CodeImp.DoomBuilder.Controls { public class SplitButton : Button { - private PushButtonState _state; - private const int SplitSectionWidth = 18; - private static readonly int BorderSize = SystemInformation.Border3DSize.Width * 2; + private PushButtonState state; + private const int splitsectionwidth = 18; + private static readonly int borderSize = SystemInformation.Border3DSize.Width * 2; private bool skipNextOpen; private Rectangle dropDownRectangle; private bool showSplit; @@ -111,13 +111,13 @@ namespace CodeImp.DoomBuilder.Controls { get { - return _state; + return state; } set { - if (!_state.Equals(value)) + if (!state.Equals(value)) { - _state = value; + state = value; Invalidate(); } } @@ -127,9 +127,7 @@ namespace CodeImp.DoomBuilder.Controls protected override bool IsInputKey(Keys keyData) { - if (keyData.Equals(Keys.Down) && showSplit) - return true; - + if (keyData.Equals(Keys.Down) && showSplit) return true; return base.IsInputKey(keyData); } @@ -302,9 +300,9 @@ namespace CodeImp.DoomBuilder.Controls } // calculate the current dropdown rectangle. - dropDownRectangle = new Rectangle(bounds.Right - SplitSectionWidth, 0, SplitSectionWidth, bounds.Height); + dropDownRectangle = new Rectangle(bounds.Right - splitsectionwidth, 0, splitsectionwidth, bounds.Height); - int internalBorder = BorderSize; + int internalBorder = borderSize; Rectangle focusRect = new Rectangle(internalBorder - 1, internalBorder - 1, @@ -322,8 +320,8 @@ namespace CodeImp.DoomBuilder.Controls if (drawSplitLine) { // draw two lines at the edge of the dropdown button - g.DrawLine(SystemPens.ButtonShadow, bounds.Left + SplitSectionWidth, BorderSize, bounds.Left + SplitSectionWidth, bounds.Bottom - BorderSize); - g.DrawLine(SystemPens.ButtonFace, bounds.Left + SplitSectionWidth + 1, BorderSize, bounds.Left + SplitSectionWidth + 1, bounds.Bottom - BorderSize); + g.DrawLine(SystemPens.ButtonShadow, bounds.Left + splitsectionwidth, borderSize, bounds.Left + splitsectionwidth, bounds.Bottom - borderSize); + g.DrawLine(SystemPens.ButtonFace, bounds.Left + splitsectionwidth + 1, borderSize, bounds.Left + splitsectionwidth + 1, bounds.Bottom - borderSize); } } else @@ -331,8 +329,8 @@ namespace CodeImp.DoomBuilder.Controls if (drawSplitLine) { // draw two lines at the edge of the dropdown button - g.DrawLine(SystemPens.ButtonShadow, bounds.Right - SplitSectionWidth, BorderSize, bounds.Right - SplitSectionWidth, bounds.Bottom - BorderSize); - g.DrawLine(SystemPens.ButtonFace, bounds.Right - SplitSectionWidth - 1, BorderSize, bounds.Right - SplitSectionWidth - 1, bounds.Bottom - BorderSize); + g.DrawLine(SystemPens.ButtonShadow, bounds.Right - splitsectionwidth, borderSize, bounds.Right - splitsectionwidth, bounds.Bottom - borderSize); + g.DrawLine(SystemPens.ButtonFace, bounds.Right - splitsectionwidth - 1, borderSize, bounds.Right - splitsectionwidth - 1, bounds.Bottom - borderSize); } } @@ -402,8 +400,8 @@ namespace CodeImp.DoomBuilder.Controls { if (AutoSize) return CalculateButtonAutoSize(); - if (!string.IsNullOrEmpty(Text) && TextRenderer.MeasureText(Text, Font).Width + SplitSectionWidth > preferredSize.Width) - return preferredSize + new Size(SplitSectionWidth + BorderSize * 2, 0); + if (!string.IsNullOrEmpty(Text) && TextRenderer.MeasureText(Text, Font).Width + splitsectionwidth > preferredSize.Width) + return preferredSize + new Size(splitsectionwidth + borderSize * 2, 0); } return preferredSize; @@ -445,7 +443,7 @@ namespace CodeImp.DoomBuilder.Controls ret_size.Width += (Padding.Horizontal + 6); //pad the splitButton arrow region - if (showSplit) ret_size.Width += SplitSectionWidth; + if (showSplit) ret_size.Width += splitsectionwidth; return ret_size; } @@ -471,7 +469,7 @@ namespace CodeImp.DoomBuilder.Controls textRectangle = OverlayObjectRect(ref content_rect, ref text_size, TextAlign); // Rectangle.Inflate(content_rect, -4, -4); //Offset on Windows 98 style when button is pressed - if (_state == PushButtonState.Pressed && !Application.RenderWithVisualStyles) + if (state == PushButtonState.Pressed && !Application.RenderWithVisualStyles) textRectangle.Offset(1, 1); // Image is dependent on ImageAlign diff --git a/Source/Core/Controls/StatisticsControl.Designer.cs b/Source/Core/Controls/StatisticsControl.Designer.cs index be8df71b..ea9f19eb 100644 --- a/Source/Core/Controls/StatisticsControl.Designer.cs +++ b/Source/Core/Controls/StatisticsControl.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.thingscount = new System.Windows.Forms.Label(); this.sectorscount = new System.Windows.Forms.Label(); this.sidedefscount = new System.Windows.Forms.Label(); diff --git a/Source/Core/Controls/StatisticsControl.cs b/Source/Core/Controls/StatisticsControl.cs index 3842825e..0a7f762c 100644 --- a/Source/Core/Controls/StatisticsControl.cs +++ b/Source/Core/Controls/StatisticsControl.cs @@ -4,12 +4,14 @@ namespace CodeImp.DoomBuilder.Controls { public partial class StatisticsControl : UserControl { - public StatisticsControl() { + public StatisticsControl() + { InitializeComponent(); this.Visible = false; } - public void UpdateStatistics() { + public void UpdateStatistics() + { verticescount.Text = General.Map.Map.Vertices.Count.ToString(); linedefscount.Text = General.Map.Map.Linedefs.Count.ToString(); sidedefscount.Text = General.Map.Map.Sidedefs.Count.ToString(); diff --git a/Source/Core/Controls/ThingBrowserControl.cs b/Source/Core/Controls/ThingBrowserControl.cs index 658f67c2..400170e8 100644 --- a/Source/Core/Controls/ThingBrowserControl.cs +++ b/Source/Core/Controls/ThingBrowserControl.cs @@ -148,7 +148,7 @@ namespace CodeImp.DoomBuilder.Controls return new List(vn.Values); } - private void GetValidNodes(TreeNode root, ref Dictionary vn) + private static void GetValidNodes(TreeNode root, ref Dictionary vn) { if (root.Nodes.Count == 0) { diff --git a/Source/Core/Controls/ThingInfoPanel.cs b/Source/Core/Controls/ThingInfoPanel.cs index e0218dee..3a2abf25 100644 --- a/Source/Core/Controls/ThingInfoPanel.cs +++ b/Source/Core/Controls/ThingInfoPanel.cs @@ -171,20 +171,25 @@ namespace CodeImp.DoomBuilder.Controls arg5.Enabled = arginfo[4].Used; //mxd - if(hasArg0Str) { + if(hasArg0Str) + { arg1.Text = '"' + t.Fields["arg0str"].Value.ToString() + '"'; - } else { - setArgumentText(arginfo[0], arg1, t.Args[0]); + } + else + { + SetArgumentText(arginfo[0], arg1, t.Args[0]); } - setArgumentText(arginfo[1], arg2, t.Args[1]); - setArgumentText(arginfo[2], arg3, t.Args[2]); - setArgumentText(arginfo[3], arg4, t.Args[3]); - setArgumentText(arginfo[4], arg5, t.Args[4]); + SetArgumentText(arginfo[1], arg2, t.Args[1]); + SetArgumentText(arginfo[2], arg3, t.Args[2]); + SetArgumentText(arginfo[3], arg4, t.Args[3]); + SetArgumentText(arginfo[4], arg5, t.Args[4]); //mxd. Flags flags.Items.Clear(); - foreach(KeyValuePair group in t.Flags){ - if(group.Value) { + foreach(KeyValuePair group in t.Flags) + { + if(group.Value) + { ListViewItem item = new ListViewItem(General.Map.Config.ThingFlags.ContainsKey(group.Key) ? General.Map.Config.ThingFlags[group.Key] : group.Key); item.Checked = true; flags.Items.Add(item); @@ -193,7 +198,8 @@ namespace CodeImp.DoomBuilder.Controls //mxd. Flags panel visibility and size flagsPanel.Visible = (flags.Items.Count > 0); - if(flags.Items.Count > 0) { + if(flags.Items.Count > 0) + { int itemWidth = flags.Items[0].GetBounds(ItemBoundsPortion.Entire).Width; if(itemWidth == 0) itemWidth = 96; flags.Width = itemWidth * (int)Math.Ceiling(flags.Items.Count / 5.0f); @@ -206,7 +212,7 @@ namespace CodeImp.DoomBuilder.Controls } //mxd - private static void setArgumentText(ArgumentInfo info, Label label, int value) + private static void SetArgumentText(ArgumentInfo info, Label label, int value) { TypeHandler th = General.Types.GetArgumentHandler(info); th.SetValue(value); @@ -214,7 +220,8 @@ namespace CodeImp.DoomBuilder.Controls if(value < 1 || !General.Map.Options.TagLabels.ContainsKey(value)) return; - if (th is ThingTagHandler || th is LinedefTagHandler || th is SectorTagHandler) { + if (th is ThingTagHandler || th is LinedefTagHandler || th is SectorTagHandler) + { label.Text += " (" + General.Map.Options.TagLabels[value] + ")"; } } diff --git a/Source/Core/Controls/ToolStripCheckBox.cs b/Source/Core/Controls/ToolStripCheckBox.cs index b9058a6e..b9843846 100644 --- a/Source/Core/Controls/ToolStripCheckBox.cs +++ b/Source/Core/Controls/ToolStripCheckBox.cs @@ -15,18 +15,21 @@ namespace CodeImp.DoomBuilder.Controls public ToolStripCheckBox() : base(new CheckBox()) { } - protected override void OnSubscribeControlEvents(Control control) { + protected override void OnSubscribeControlEvents(Control control) + { base.OnSubscribeControlEvents(control); cb = control as CheckBox; cb.CheckedChanged += OnCheckedChanged; } - protected override void OnUnsubscribeControlEvents(Control control) { + protected override void OnUnsubscribeControlEvents(Control control) + { base.OnUnsubscribeControlEvents(control); cb.CheckedChanged -= OnCheckedChanged; } - public void OnCheckedChanged(object sender, EventArgs e) { + private void OnCheckedChanged(object sender, EventArgs e) + { if(CheckedChanged != null) CheckedChanged(this, e); } } diff --git a/Source/Core/Controls/VertexInfoPanel.cs b/Source/Core/Controls/VertexInfoPanel.cs index b0604640..d1d60252 100644 --- a/Source/Core/Controls/VertexInfoPanel.cs +++ b/Source/Core/Controls/VertexInfoPanel.cs @@ -40,20 +40,27 @@ namespace CodeImp.DoomBuilder.Controls position.Text = v.Position.x.ToString("0.##") + ", " + v.Position.y.ToString("0.##"); //mxd. Height offsets - if(General.Map.UDMF) { - if(!float.IsNaN(v.ZCeiling)) { + if(General.Map.UDMF) + { + if(!float.IsNaN(v.ZCeiling)) + { zceiling.Text = v.ZCeiling.ToString("0.##"); zceiling.Enabled = true; labelCeilingOffset.Enabled = true; - } else { + } + else + { zceiling.Text = "--"; } - if(!float.IsNaN(v.ZFloor)) { + if(!float.IsNaN(v.ZFloor)) + { zfloor.Text = v.ZFloor.ToString("0.##"); zfloor.Enabled = true; labelFloorOffset.Enabled = true; - } else { + } + else + { zfloor.Text = "--"; } diff --git a/Source/Core/Data/DataManager.cs b/Source/Core/Data/DataManager.cs index c00a02ed..104f737a 100644 --- a/Source/Core/Data/DataManager.cs +++ b/Source/Core/Data/DataManager.cs @@ -319,12 +319,12 @@ namespace CodeImp.DoomBuilder.Data LoadInternalSprites(); //mxd - loadMapInfo(); + LoadMapInfo(); ModelReader.Init(); - loadVoxels(); - Dictionary actorsByClass = createActorsByClassList(); - loadModeldefs(actorsByClass); - loadGldefs(actorsByClass); + LoadVoxels(); + Dictionary actorsByClass = CreateActorsByClassList(); + LoadModeldefs(actorsByClass); + LoadGldefs(actorsByClass); foreach (Thing t in General.Map.Map.Things) t.UpdateCache(); General.MainWindow.DisplayReady(); @@ -462,7 +462,8 @@ namespace CodeImp.DoomBuilder.Data palette = null; //mxd - if (modeldefEntries != null) { + if (modeldefEntries != null) + { foreach (KeyValuePair group in modeldefEntries) group.Value.Dispose(); } @@ -1469,19 +1470,22 @@ namespace CodeImp.DoomBuilder.Data #region ================== mxd. Modeldef, Voxeldef, Gldefs, Mapinfo //mxd. This creates dictionary. Should be called after all DECORATE actors are parsed - private Dictionary createActorsByClassList() { + private Dictionary CreateActorsByClassList() + { Dictionary actors = new Dictionary(StringComparer.Ordinal); Dictionary things = General.Map.Config.GetThingTypes(); //read our new shiny ClassNames for default game things - foreach (KeyValuePair ti in things) { + foreach (KeyValuePair ti in things) + { if (ti.Value.ClassName != null) actors.Add(ti.Value.ClassName, ti.Key); } //and for actors defined in DECORATE ICollection ac = decorate.Actors; - foreach (ActorStructure actor in ac) { + foreach (ActorStructure actor in ac) + { string className = actor.ClassName.ToLower(); if (!actors.ContainsKey(className)) actors.Add(className, actor.DoomEdNum); @@ -1494,22 +1498,25 @@ namespace CodeImp.DoomBuilder.Data } //mxd - public void ReloadModeldef() { - if (modeldefEntries != null) { + public void ReloadModeldef() + { + if (modeldefEntries != null) + { foreach (KeyValuePair group in modeldefEntries) group.Value.Dispose(); } General.MainWindow.DisplayStatus(StatusType.Busy, "Reloading model definitions..."); - loadModeldefs(createActorsByClassList()); + LoadModeldefs(CreateActorsByClassList()); General.MainWindow.DisplayStatus(StatusType.Busy, "Reloading voxel definitions..."); - loadVoxels(); + LoadVoxels(); foreach(Thing t in General.Map.Map.Things) t.UpdateCache(); //rebuild geometry if in Visual mode - if (General.Editing.Mode != null && General.Editing.Mode.GetType().Name == "BaseVisualMode") { + if (General.Editing.Mode != null && General.Editing.Mode.GetType().Name == "BaseVisualMode") + { General.Editing.Mode.OnReloadResources(); } @@ -1517,19 +1524,24 @@ namespace CodeImp.DoomBuilder.Data } //mxd - public void ReloadGldefs() { + public void ReloadGldefs() + { General.MainWindow.DisplayStatus(StatusType.Busy, "Reloading GLDEFS..."); - try { - loadGldefs(createActorsByClassList()); - } catch(ArgumentNullException) { + try + { + LoadGldefs(CreateActorsByClassList()); + } + catch(ArgumentNullException) + { MessageBox.Show("GLDEFS reload failed. Try using 'Reload Resources' instead.\nCheck 'Errors and Warnings' window for more details."); General.MainWindow.DisplayReady(); return; } //rebuild geometry if in Visual mode - if (General.Editing.Mode != null && General.Editing.Mode.GetType().Name == "BaseVisualMode") { + if (General.Editing.Mode != null && General.Editing.Mode.GetType().Name == "BaseVisualMode") + { General.Editing.Mode.OnReloadResources(); } @@ -1537,19 +1549,24 @@ namespace CodeImp.DoomBuilder.Data } //mxd - public void ReloadMapInfo() { + public void ReloadMapInfo() + { General.MainWindow.DisplayStatus(StatusType.Busy, "Reloading (Z)MAPINFO..."); - try { - loadMapInfo(); - } catch (ArgumentNullException) { + try + { + LoadMapInfo(); + } + catch (ArgumentNullException) + { MessageBox.Show("(Z)MAPINFO reload failed. Try using 'Reload Resources' instead.\nCheck 'Errors and Warnings' window for more details."); General.MainWindow.DisplayReady(); return; } //rebuild geometry if in Visual mode - if (General.Editing.Mode != null && General.Editing.Mode.GetType().Name == "BaseVisualMode") { + if (General.Editing.Mode != null && General.Editing.Mode.GetType().Name == "BaseVisualMode") + { General.Editing.Mode.OnReloadResources(); } @@ -1557,28 +1574,35 @@ namespace CodeImp.DoomBuilder.Data } //mxd. This parses modeldefs. Should be called after all DECORATE actors are parsed and actorsByClass dictionary created - private void loadModeldefs(Dictionary actorsByClass) { + private void LoadModeldefs(Dictionary actorsByClass) + { //if no actors defined in DECORATE or game config... if (actorsByClass == null || actorsByClass.Count == 0) return; Dictionary modelDefEntriesByName = new Dictionary(StringComparer.Ordinal); ModeldefParser parser = new ModeldefParser(); - foreach (DataReader dr in containers) { + foreach (DataReader dr in containers) + { currentreader = dr; Dictionary streams = dr.GetModeldefData(); - foreach (KeyValuePair group in streams) { + foreach (KeyValuePair group in streams) + { // Parse the data - if(parser.Parse(group.Value, currentreader.Location.location + "\\" + group.Key)) { - foreach(KeyValuePair g in parser.Entries) { - if (modelDefEntriesByName.ContainsKey(g.Key)) { + if(parser.Parse(group.Value, currentreader.Location.location + "\\" + group.Key)) + { + foreach(KeyValuePair g in parser.Entries) + { + if (modelDefEntriesByName.ContainsKey(g.Key)) + { General.ErrorLogger.Add(ErrorType.Warning, "Model definition for actor '" + g.Key + "' is double-defined in '" + group.Key + "'"); modelDefEntriesByName[g.Key] = g.Value; - } else { + } + else + { modelDefEntriesByName.Add(g.Key, g.Value); } - } } } @@ -1586,7 +1610,8 @@ namespace CodeImp.DoomBuilder.Data currentreader = null; - foreach (KeyValuePair e in modelDefEntriesByName) { + foreach (KeyValuePair e in modelDefEntriesByName) + { if (actorsByClass.ContainsKey(e.Key)) modeldefEntries[actorsByClass[e.Key]] = modelDefEntriesByName[e.Key]; else if(!invalidDecorateActors.Contains(e.Key)) @@ -1595,17 +1620,20 @@ namespace CodeImp.DoomBuilder.Data } //mxd - private void loadVoxels() { + private void LoadVoxels() + { //Get names of all voxel models, which can be used "as is" Dictionary voxelNames = new Dictionary(StringComparer.Ordinal); - foreach(DataReader dr in containers) { + foreach(DataReader dr in containers) + { currentreader = dr; string[] result = dr.GetVoxelNames(); if(result == null) continue; - foreach(string s in result) { + foreach(string s in result) + { if(!voxelNames.ContainsKey(s)) voxelNames.Add(s, false); } } @@ -1613,14 +1641,18 @@ namespace CodeImp.DoomBuilder.Data Dictionary> sprites = new Dictionary>(StringComparer.Ordinal); // Go for all things - foreach(ThingTypeInfo ti in thingtypes.Values) { + foreach(ThingTypeInfo ti in thingtypes.Values) + { // Valid sprite name? string sprite; - if(ti.Sprite.Length == 0 || ti.Sprite.Length > CLASIC_IMAGE_NAME_LENGTH) { + if(ti.Sprite.Length == 0 || ti.Sprite.Length > CLASIC_IMAGE_NAME_LENGTH) + { if(ti.Actor == null) continue; sprite = ti.Actor.FindSuitableVoxel(voxelNames); - } else { + } + else + { sprite = ti.Sprite; } @@ -1633,17 +1665,20 @@ namespace CodeImp.DoomBuilder.Data Dictionary processed = new Dictionary(StringComparer.Ordinal); //parse VOXLEDEF - foreach(DataReader dr in containers) { + foreach(DataReader dr in containers) + { currentreader = dr; KeyValuePair group = dr.GetVoxeldefData(); - if(group.Value != null && parser.Parse(group.Value, group.Key)) { - foreach(KeyValuePair entry in parser.Entries){ - foreach(KeyValuePair> sc in sprites) { - if (sc.Key.Contains(entry.Key)) { - foreach(int id in sc.Value) { - modeldefEntries[id] = entry.Value; - } + if(group.Value != null && parser.Parse(group.Value, group.Key)) + { + foreach(KeyValuePair entry in parser.Entries) + { + foreach(KeyValuePair> sc in sprites) + { + if (sc.Key.Contains(entry.Key)) + { + foreach(int id in sc.Value) modeldefEntries[id] = entry.Value; processed.Add(entry.Key, false); } } @@ -1654,32 +1689,34 @@ namespace CodeImp.DoomBuilder.Data currentreader = null; //get voxel models - foreach(KeyValuePair group in voxelNames) { + foreach(KeyValuePair group in voxelNames) + { if(processed.ContainsKey(group.Key)) continue; - foreach (KeyValuePair> sc in sprites) { - if(sc.Key.Contains(group.Key)) { + foreach (KeyValuePair> sc in sprites) + { + if(sc.Key.Contains(group.Key)) + { //it's a model without a definition, and it corresponds to a sprite we can display, so let's add it ModelData data = new ModelData { IsVoxel = true }; data.ModelNames.Add(group.Key); - foreach(int id in sprites[sc.Key]) { - modeldefEntries[id] = data; - } + foreach(int id in sprites[sc.Key]) modeldefEntries[id] = data; } } } } //mxd. This parses gldefs. Should be called after all DECORATE actors are parsed and actorsByClass dictionary created - private void loadGldefs(Dictionary actorsByClass) { + private void LoadGldefs(Dictionary actorsByClass) + { //if no actors defined in DECORATE or game config... if (actorsByClass == null || actorsByClass.Count == 0) return; - GldefsParser parser = new GldefsParser(); - parser.OnInclude = loadGldefsFromLocation; + GldefsParser parser = new GldefsParser { OnInclude = LoadGldefsFromLocation }; //load gldefs from resources - foreach (DataReader dr in containers) { + foreach (DataReader dr in containers) + { currentreader = dr; Dictionary streams = dr.GetGldefsData(General.Map.Config.GameType); @@ -1688,31 +1725,37 @@ namespace CodeImp.DoomBuilder.Data } //create gldefsEntries dictionary - foreach (KeyValuePair e in parser.Objects) { //ClassName, Light name + foreach (KeyValuePair e in parser.Objects) //ClassName, Light name + { //if we have decorate actor and light definition for given ClassName... - if (actorsByClass.ContainsKey(e.Key) && parser.LightsByName.ContainsKey(e.Value)) { + if (actorsByClass.ContainsKey(e.Key) && parser.LightsByName.ContainsKey(e.Value)) + { int thingType = actorsByClass[e.Key]; - if (gldefsEntries.ContainsKey(thingType)) { + if (gldefsEntries.ContainsKey(thingType)) gldefsEntries[thingType] = parser.LightsByName[e.Value]; - }else{ + else gldefsEntries.Add(thingType, parser.LightsByName[e.Value]); - } - } else if(!invalidDecorateActors.Contains(e.Key)) { + } + else if(!invalidDecorateActors.Contains(e.Key)) + { General.ErrorLogger.Add(ErrorType.Warning, "Got GLDEFS light for class '" + e.Key + "', but haven't found such class in DECORATE"); } } } //mxd. This loads (Z)MAPINFO - private void loadMapInfo() { + private void LoadMapInfo() + { MapinfoParser parser = new MapinfoParser(); - foreach (DataReader dr in containers) { + foreach (DataReader dr in containers) + { currentreader = dr; Dictionary streams = dr.GetMapinfoData(); - foreach (KeyValuePair group in streams) { + foreach (KeyValuePair group in streams) + { // Parse the data parser.Parse(group.Value, Path.Combine(currentreader.Location.location, group.Key), General.Map.Options.LevelName); } @@ -1721,7 +1764,8 @@ namespace CodeImp.DoomBuilder.Data mapInfo = parser.MapInfo ?? new MapInfo(); } - private void loadGldefsFromLocation(GldefsParser parser, string location) { + private void LoadGldefsFromLocation(GldefsParser parser, string location) + { Dictionary streams = currentreader.GetGldefsData(location); foreach (KeyValuePair group in streams) @@ -1729,11 +1773,10 @@ namespace CodeImp.DoomBuilder.Data } //mxd - internal MemoryStream LoadFile(string name) { - foreach (DataReader dr in containers) { - if (dr.FileExists(name)) - return dr.LoadFile(name); - } + internal MemoryStream LoadFile(string name) + { + foreach (DataReader dr in containers) + if (dr.FileExists(name)) return dr.LoadFile(name); return null; } diff --git a/Source/Core/Data/HighResImage.cs b/Source/Core/Data/HighResImage.cs index 3ee36885..2971cda2 100644 --- a/Source/Core/Data/HighResImage.cs +++ b/Source/Core/Data/HighResImage.cs @@ -156,17 +156,20 @@ namespace CodeImp.DoomBuilder.Data if(reader is UnknownImageReader) { //mxd. Probably that's a flat?.. - if (General.Map.Config.MixTexturesFlats) { + if (General.Map.Config.MixTexturesFlats) + { reader = ImageDataFormat.GetImageReader(mem, ImageDataFormat.DOOMFLAT, General.Map.Data.Palette); } - if (reader is UnknownImageReader) { + if (reader is UnknownImageReader) + { // Data is in an unknown format! General.ErrorLogger.Add(ErrorType.Error, "Patch lump '" + p.lumpname + "' data format could not be read, while loading texture '" + this.Name + "'"); failCount++; //mxd } } - if(!(reader is UnknownImageReader)) { + if(!(reader is UnknownImageReader)) + { // Get the patch mem.Seek(0, SeekOrigin.Begin); Bitmap patchbmp = null; @@ -180,7 +183,8 @@ namespace CodeImp.DoomBuilder.Data if(patchbmp != null) { //mxd. Flip - if(p.flipx || p.flipy) { + if(p.flipx || p.flipy) + { RotateFlipType flip; if(p.flipx && !p.flipy) flip = RotateFlipType.RotateNoneFlipX; @@ -192,7 +196,8 @@ namespace CodeImp.DoomBuilder.Data } //mxd. Then rotate. I do it this way because RotateFlip function rotates THEN flips, and GZDoom does it the other way around. - if(p.rotate != 0) { + if(p.rotate != 0) + { RotateFlipType rotate; if(p.rotate == 90) rotate = RotateFlipType.Rotate90FlipNone; @@ -224,36 +229,45 @@ namespace CodeImp.DoomBuilder.Data int patchalpha = (int)Math.Round(General.Clamp(p.alpha, 0f, 1f) * 255); //convert alpha to [0-255] range //mxd. Blend/Tint support - if(p.blendstyle == TexturePathBlendStyle.Blend) { - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) { + if(p.blendstyle == TexturePathBlendStyle.Blend) + { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) + { cp->r = (byte)((cp->r * p.blend.r) * PixelColor.BYTE_TO_FLOAT); cp->g = (byte)((cp->g * p.blend.g) * PixelColor.BYTE_TO_FLOAT); cp->b = (byte)((cp->b * p.blend.b) * PixelColor.BYTE_TO_FLOAT); } - } else if(p.blendstyle == TexturePathBlendStyle.Tint) { + } + else if(p.blendstyle == TexturePathBlendStyle.Tint) + { float tintammount = p.tintammount - 0.1f; - if(tintammount > 0) { + if(tintammount > 0) + { float br = p.blend.r * PixelColor.BYTE_TO_FLOAT * tintammount; float bg = p.blend.g * PixelColor.BYTE_TO_FLOAT * tintammount; float bb = p.blend.b * PixelColor.BYTE_TO_FLOAT * tintammount; float invTint = 1.0f - tintammount; - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) + { cp->r = (byte)(((cp->r * PixelColor.BYTE_TO_FLOAT) * invTint + br) * 255.0f); cp->g = (byte)(((cp->g * PixelColor.BYTE_TO_FLOAT) * invTint + bg) * 255.0f); cp->b = (byte)(((cp->b * PixelColor.BYTE_TO_FLOAT) * invTint + bb) * 255.0f); } } } - //mxd. apply RenderStyle - if(p.style == TexturePathRenderStyle.Blend) { + if(p.style == TexturePathRenderStyle.Blend) + { for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) cp->a = (byte)((cp->a * patchalpha) * PixelColor.BYTE_TO_FLOAT); + + } //mxd. we need a copy of underlying part of texture for these styles - } else if(p.style != TexturePathRenderStyle.Copy) { + else if(p.style != TexturePathRenderStyle.Copy) + { //copy portion of texture int lockWidth = (p.x + patchbmp.Size.Width > bitmap.Width) ? bitmap.Width - p.x : patchbmp.Size.Width; int lockHeight = (p.y + patchbmp.Size.Height > bitmap.Height) ? bitmap.Height - p.y : patchbmp.Size.Height; @@ -265,19 +279,25 @@ namespace CodeImp.DoomBuilder.Data //lock texture BitmapData texturebmpdata = null; - try { + try + { texturebmpdata = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); - } catch(Exception e) { + } + catch(Exception e) + { General.ErrorLogger.Add(ErrorType.Error, "Cannot lock texture '" + this.Name + "' to apply render style. " + e.GetType().Name + ": " + e.Message); } - if(texturebmpdata != null) { + if(texturebmpdata != null) + { PixelColor* texturepixels = (PixelColor*)(texturebmpdata.Scan0.ToPointer()); PixelColor* tcp = texturepixels + numpixels - 1; - switch(p.style) { + switch(p.style) + { case TexturePathRenderStyle.Add: - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) + { cp->r = (byte)Math.Min(255, cp->r + tcp->r); cp->g = (byte)Math.Min(255, cp->g + tcp->g); cp->b = (byte)Math.Min(255, cp->b + tcp->b); @@ -287,7 +307,8 @@ namespace CodeImp.DoomBuilder.Data break; case TexturePathRenderStyle.Subtract: - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) + { cp->r = (byte)Math.Max(0, tcp->r - cp->r); cp->g = (byte)Math.Max(0, tcp->g - cp->g); cp->b = (byte)Math.Max(0, tcp->b - cp->b); @@ -297,7 +318,8 @@ namespace CodeImp.DoomBuilder.Data break; case TexturePathRenderStyle.ReverseSubtract: - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) + { cp->r = (byte)Math.Max(0, cp->r - tcp->r); cp->g = (byte)Math.Max(0, cp->g - tcp->g); cp->b = (byte)Math.Max(0, cp->b - tcp->b); @@ -307,7 +329,8 @@ namespace CodeImp.DoomBuilder.Data break; case TexturePathRenderStyle.Modulate: - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--) + { cp->r = (byte)((cp->r * tcp->r) * PixelColor.BYTE_TO_FLOAT); cp->g = (byte)((cp->g * tcp->g) * PixelColor.BYTE_TO_FLOAT); cp->b = (byte)((cp->b * tcp->b) * PixelColor.BYTE_TO_FLOAT); diff --git a/Source/Core/Data/PK3StructuredReader.cs b/Source/Core/Data/PK3StructuredReader.cs index ef19d633..f9c9d306 100644 --- a/Source/Core/Data/PK3StructuredReader.cs +++ b/Source/Core/Data/PK3StructuredReader.cs @@ -470,11 +470,12 @@ namespace CodeImp.DoomBuilder.Data // Error when suspended if (issuspended) throw new Exception("Data reader is suspended"); - //modedef should be in root folder + // Modedef should be in root folder string[] files = GetAllFiles("", false); Dictionary streams = new Dictionary(StringComparer.Ordinal); - foreach (string s in files) { + foreach (string s in files) + { if (s.ToLowerInvariant().IndexOf("modeldef") != -1) streams.Add(s, LoadFile(s)); } diff --git a/Source/Core/Data/ResourceImage.cs b/Source/Core/Data/ResourceImage.cs index 6660b203..fffd7ae5 100644 --- a/Source/Core/Data/ResourceImage.cs +++ b/Source/Core/Data/ResourceImage.cs @@ -90,7 +90,8 @@ namespace CodeImp.DoomBuilder.Data } //mxd - public override Image GetPreview() { + public override Image GetPreview() + { return base.GetBitmap(); } diff --git a/Source/Core/Data/TextureImage.cs b/Source/Core/Data/TextureImage.cs index 69c0a216..7f62230a 100644 --- a/Source/Core/Data/TextureImage.cs +++ b/Source/Core/Data/TextureImage.cs @@ -121,10 +121,12 @@ namespace CodeImp.DoomBuilder.Data if(reader is UnknownImageReader) { //mxd. Probably that's a flat?.. - if (General.Map.Config.MixTexturesFlats) { + if (General.Map.Config.MixTexturesFlats) + { reader = ImageDataFormat.GetImageReader(mem, ImageDataFormat.DOOMFLAT, General.Map.Data.Palette); } - if (reader is UnknownImageReader) { + if (reader is UnknownImageReader) + { // Data is in an unknown format! General.ErrorLogger.Add(ErrorType.Error, "Patch lump '" + p.lumpname + "' data format could not be read, while loading texture '" + this.Name + "'. Does this lump contain valid picture data at all?"); loadfailed = true; @@ -132,7 +134,8 @@ namespace CodeImp.DoomBuilder.Data } } - if(!(reader is UnknownImageReader)) { + if(!(reader is UnknownImageReader)) + { // Draw the patch mem.Seek(0, SeekOrigin.Begin); try { reader.DrawToPixelData(mem, pixels, width, height, p.x, p.y); } diff --git a/Source/Core/Data/TexturePatch.cs b/Source/Core/Data/TexturePatch.cs index 77a86d9c..dbc0c9e9 100644 --- a/Source/Core/Data/TexturePatch.cs +++ b/Source/Core/Data/TexturePatch.cs @@ -78,7 +78,8 @@ namespace CodeImp.DoomBuilder.Data } //mxd. Constructor for hires patches - public TexturePatch(PatchStructure patch) { + public TexturePatch(PatchStructure patch) + { // Initialize this.lumpname = patch.Name.ToUpperInvariant(); this.x = patch.OffsetX; @@ -96,13 +97,15 @@ namespace CodeImp.DoomBuilder.Data //mxd. Check data so we don't perform unneeded operations later on if(this.alpha == 1.0f) { - if(this.style == TexturePathRenderStyle.Blend || this.style == TexturePathRenderStyle.CopyAlpha || this.style == TexturePathRenderStyle.CopyNewAlpha || this.style == TexturePathRenderStyle.Overlay) + if(this.style == TexturePathRenderStyle.Blend + || this.style == TexturePathRenderStyle.CopyAlpha + || this.style == TexturePathRenderStyle.CopyNewAlpha + || this.style == TexturePathRenderStyle.Overlay) this.style = TexturePathRenderStyle.Copy; } //mxd. and get rid of render styles we don't support - if(this.style == TexturePathRenderStyle.Overlay) - this.style = TexturePathRenderStyle.Copy; + if(this.style == TexturePathRenderStyle.Overlay) this.style = TexturePathRenderStyle.Copy; } } } diff --git a/Source/Core/Data/WADReader.cs b/Source/Core/Data/WADReader.cs index b9d686a0..87418307 100644 --- a/Source/Core/Data/WADReader.cs +++ b/Source/Core/Data/WADReader.cs @@ -101,25 +101,31 @@ namespace CodeImp.DoomBuilder.Data //mxd invertedflatranges = new List(); - if(flatranges.Count > 0) { + if(flatranges.Count > 0) + { //add range before the first flatrange - if (flatranges[0].start > 0) { + if (flatranges[0].start > 0) + { LumpRange range = new LumpRange {start = 0, end = flatranges[0].start - 1}; invertedflatranges.Add(range); } //add ranges between flatranges - for(int i = 1; i < flatranges.Count; i++) { + for(int i = 1; i < flatranges.Count; i++) + { LumpRange range = new LumpRange { start = flatranges[i - 1].end + 1, end = flatranges[i].start - 1 }; invertedflatranges.Add(range); } //add range after the last flatrange - if(flatranges[flatranges.Count - 1].end < file.Lumps.Count - 1) { + if(flatranges[flatranges.Count - 1].end < file.Lumps.Count - 1) + { LumpRange range = new LumpRange { start = flatranges[flatranges.Count - 1].end + 1, end = file.Lumps.Count - 1 }; invertedflatranges.Add(range); } - } else { // No flat ranges? Make one giant range then... + } + else // No flat ranges? Make one giant range then... + { LumpRange range = new LumpRange {start = 0, end = file.Lumps.Count - 1}; invertedflatranges.Add(range); } @@ -356,15 +362,19 @@ namespace CodeImp.DoomBuilder.Data foreach(LumpRange range in textureranges) { // Go for all lumps between start and end exclusive - for(int i = range.start + 1; i < range.end; i++) { + for(int i = range.start + 1; i < range.end; i++) + { // Lump not zero length? - if(file.Lumps[i].Length > 0) { + if(file.Lumps[i].Length > 0) + { // Make the image SimpleTextureImage image = new SimpleTextureImage(file.Lumps[i].Name, file.Lumps[i].Name, defaultscale, defaultscale); // Add image to collection images.Add(image); - } else { + } + else + { // Can't load image without size General.ErrorLogger.Add(ErrorType.Error, "Can't load texture '" + file.Lumps[i].Name + "' because it doesn't contain any data."); } @@ -773,17 +783,20 @@ namespace CodeImp.DoomBuilder.Data #region ================== Voxels (mxd) //mxd. This returns the list of voxels, which can be used without VOXELDEF definition - public override string[] GetVoxelNames() { + public override string[] GetVoxelNames() + { // Error when suspended if(issuspended) throw new Exception("Data reader is suspended"); List voxels = new List(); Regex spriteName = new Regex(SPRITE_NAME_PATTERN); - foreach(LumpRange range in voxelranges) { + foreach(LumpRange range in voxelranges) + { if(range.start == range.end) continue; - for(int i = range.start + 1; i < range.end; i++) { + for(int i = range.start + 1; i < range.end; i++) + { if(spriteName.IsMatch(file.Lumps[i].Name)) voxels.Add(file.Lumps[i].Name); } } @@ -792,20 +805,23 @@ namespace CodeImp.DoomBuilder.Data } //mxd - public override KeyValuePair GetVoxeldefData() { + public override KeyValuePair GetVoxeldefData() + { Lump lump = file.FindLump("VOXELDEF"); if(lump != null) return new KeyValuePair("VOXELDEF", lump.Stream); return new KeyValuePair(); } //mxd. This finds and returns a voxel stream or null if no voxel was found - public override Stream GetVoxelData(string name) { + public override Stream GetVoxelData(string name) + { // Error when suspended if(issuspended) throw new Exception("Data reader is suspended"); Lump lump; - foreach(LumpRange range in voxelranges) { + foreach(LumpRange range in voxelranges) + { if(range.start == range.end) continue; lump = file.FindLump(name, range.start, range.end); if(lump != null) return lump.Stream; @@ -841,7 +857,8 @@ namespace CodeImp.DoomBuilder.Data } //mxd - public override Dictionary GetMapinfoData() { + public override Dictionary GetMapinfoData() + { if (issuspended) throw new Exception("Data reader is suspended"); Dictionary streams = new Dictionary(StringComparer.Ordinal); @@ -852,26 +869,27 @@ namespace CodeImp.DoomBuilder.Data int lumpindex = file.FindLumpIndex(src); //then for MAPINFO - if (lumpindex == -1) { + if (lumpindex == -1) + { src = "MAPINFO"; lumpindex = file.FindLumpIndex(src); } - if(lumpindex != -1) - streams.Add(src, file.Lumps[lumpindex].Stream); - + if(lumpindex != -1) streams.Add(src, file.Lumps[lumpindex].Stream); return streams; } //mxd - public override Dictionary GetGldefsData(GameType gameType) { + public override Dictionary GetGldefsData(GameType gameType) + { if (issuspended) throw new Exception("Data reader is suspended"); Dictionary streams = new Dictionary(StringComparer.Ordinal); int lumpindex; //try to load game specific GLDEFS first - if (gameType != GameType.UNKNOWN) { + if (gameType != GameType.UNKNOWN) + { string lumpName = Gldefs.GLDEFS_LUMPS_PER_GAME[(int)gameType]; lumpindex = file.FindLumpIndex(lumpName); @@ -882,35 +900,35 @@ namespace CodeImp.DoomBuilder.Data //should be only one entry per wad lumpindex = file.FindLumpIndex("GLDEFS"); - if (lumpindex != -1) - streams.Add("GLDEFS", file.Lumps[lumpindex].Stream); - + if (lumpindex != -1) streams.Add("GLDEFS", file.Lumps[lumpindex].Stream); return streams; } //mxd - public override Dictionary GetGldefsData(string location) { + public override Dictionary GetGldefsData(string location) + { if (issuspended) throw new Exception("Data reader is suspended"); Dictionary streams = new Dictionary(StringComparer.Ordinal); int lumpindex = file.FindLumpIndex(location); - if (lumpindex != -1) - streams.Add(location, file.Lumps[lumpindex].Stream); - + if (lumpindex != -1) streams.Add(location, file.Lumps[lumpindex].Stream); return streams; } //mxd - public override Dictionary GetModeldefData() { + public override Dictionary GetModeldefData() + { return GetGldefsData("MODELDEF"); } //mxd - internal override MemoryStream LoadFile(string name) { + internal override MemoryStream LoadFile(string name) + { Lump l = file.FindLump(name); - if (l != null) { + if (l != null) + { l.Stream.Seek(0, SeekOrigin.Begin); return new MemoryStream(l.Stream.ReadAllBytes()); } @@ -919,7 +937,8 @@ namespace CodeImp.DoomBuilder.Data } //mxd - internal override bool FileExists(string name) { + internal override bool FileExists(string name) + { return file.FindLumpIndex(name) != -1; } diff --git a/Source/Core/Editing/ClassicMode.cs b/Source/Core/Editing/ClassicMode.cs index a7565514..01421ca4 100644 --- a/Source/Core/Editing/ClassicMode.cs +++ b/Source/Core/Editing/ClassicMode.cs @@ -607,9 +607,12 @@ namespace CodeImp.DoomBuilder.Editing } //mxd - public override bool OnMapTestBegin(bool testFromCurrentPosition) { - if(testFromCurrentPosition) { - if(!mouseinside){ + public override bool OnMapTestBegin(bool testFromCurrentPosition) + { + if(testFromCurrentPosition) + { + if(!mouseinside) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: mouse is outside editing vindow!"); return false; } @@ -617,18 +620,25 @@ namespace CodeImp.DoomBuilder.Editing //find Single Player Start. Should be type 1 in all games Thing start = null; - foreach (Thing t in General.Map.Map.Things) { - if (t.Type == 1) { + foreach (Thing t in General.Map.Map.Things) + { + if (t.Type == 1) + { //store thing and position - if (start == null) { + if (start == null) + { + start = t; + } + else if(t.Index > start.Index) + { + //if there are several Player Start 1 things, GZDoom uses one with the biggest index. start = t; - } else if(t.Index > start.Index) { - start = t; //if there are several Player Start 1 things, GZDoom uses one with the biggest index. } } } - if (start == null) { + if (start == null) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: no Player 1 start found!"); return false; } @@ -636,13 +646,15 @@ namespace CodeImp.DoomBuilder.Editing //now check if cursor is located inside a sector Sector s = General.Map.Map.GetSectorByCoordinates(mousemappos); - if(s == null){ + if(s == null) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: cursor is not inside sector!"); return false; } //41 = player's height in Doom. Is that so in all other games as well? - if (s.CeilHeight - s.FloorHeight < 41) { + if (s.CeilHeight - s.FloorHeight < 41) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: sector is too low!"); return false; } @@ -658,8 +670,10 @@ namespace CodeImp.DoomBuilder.Editing return true; } - public override void OnMapTestEnd(bool testFromCurrentPosition) { - if (testFromCurrentPosition) { + public override void OnMapTestEnd(bool testFromCurrentPosition) + { + if (testFromCurrentPosition) + { //restore position playerStart.Move(playerStartPosition); playerStart = null; @@ -759,7 +773,8 @@ namespace CodeImp.DoomBuilder.Editing //mxd PixelColor marqueColor; - switch(marqueSelectionMode) { + switch(marqueSelectionMode) + { case MarqueSelectionMode.SELECT: marqueColor = General.Colors.Selection.WithAlpha(SELECTION_ALPHA); break; @@ -800,7 +815,8 @@ namespace CodeImp.DoomBuilder.Editing /// /// This selects given map element (mxd) /// - public virtual void SelectMapElement(SelectableElement element) { + public virtual void SelectMapElement(SelectableElement element) + { element.Selected = true; } @@ -811,7 +827,7 @@ namespace CodeImp.DoomBuilder.Editing [BeginAction("gridsetup", BaseAction = true)] protected void ShowGridSetup() { - General.Map.Grid.ShowGridSetup(); + GridSetup.ShowGridSetup(); } [BeginAction("pan_view", BaseAction = true)] @@ -852,10 +868,12 @@ namespace CodeImp.DoomBuilder.Editing //mxd [BeginAction("centeroncoordinates", BaseAction = true)] - protected virtual void CenterOnCoordinates() { + protected virtual void CenterOnCoordinates() + { //show form... CenterOnCoordinatesForm form = new CenterOnCoordinatesForm(); - if (form.ShowDialog() == DialogResult.OK) { + if (form.ShowDialog() == DialogResult.OK) + { //center view renderer2d.PositionView(form.Coordinates.x, form.Coordinates.y); General.Interface.RedrawDisplay(); diff --git a/Source/Core/Editing/CopyPasteManager.cs b/Source/Core/Editing/CopyPasteManager.cs index 8b9f68d6..676dd3fa 100644 --- a/Source/Core/Editing/CopyPasteManager.cs +++ b/Source/Core/Editing/CopyPasteManager.cs @@ -90,7 +90,7 @@ namespace CodeImp.DoomBuilder.Editing #region ================== Methods // This makes a prefab of the selection. Returns null when cancelled. - internal MemoryStream MakePrefab() + private static MemoryStream MakePrefab() { // Let the plugins know if(General.Plugins.OnCopyBegin()) @@ -155,7 +155,7 @@ namespace CodeImp.DoomBuilder.Editing } // This pastes a prefab. Returns false when paste was cancelled. - internal void PastePrefab(Stream filedata, PasteOptions options) + private static void PastePrefab(Stream filedata, PasteOptions options) { // Create undo General.MainWindow.DisplayStatus(StatusType.Action, "Inserted prefab."); @@ -165,10 +165,13 @@ namespace CodeImp.DoomBuilder.Editing MemoryStream memstream; //mxd filedata.Seek(0, SeekOrigin.Begin); - try { + try + { memstream = SharpCompressHelper.DecompressStream(filedata); //mxd memstream.Seek(0, SeekOrigin.Begin); - }catch(Exception e){ + } + catch(Exception e) + { General.ErrorLogger.Add(ErrorType.Error, e.GetType().Name + " while reading prefab from file: " + e.Message); General.WriteLogLine(e.StackTrace); General.ShowErrorMessage("Unable to load prefab. See log file for error details.", MessageBoxButtons.OK); @@ -205,7 +208,7 @@ namespace CodeImp.DoomBuilder.Editing } // This performs the copy. Returns false when copy was cancelled. - private bool DoCopySelection(string desc) + private static bool DoCopySelection(string desc) { // Check if possible to copy/paste if(General.Editing.Mode.Attributes.AllowCopyPaste) @@ -254,7 +257,7 @@ namespace CodeImp.DoomBuilder.Editing } // This performs the paste. Returns false when paste was cancelled. - private bool DoPasteSelection(PasteOptions options) + private static void DoPasteSelection(PasteOptions options) { // Check if possible to copy/paste if(General.Editing.Mode.Attributes.AllowCopyPaste) @@ -320,25 +323,20 @@ namespace CodeImp.DoomBuilder.Editing General.Editing.Mode.OnPasteEnd(options.Copy()); General.Plugins.OnPasteEnd(options); } - return true; + return; } } - - // Aborted - return false; } else { // Nothing usefull on the clipboard General.MessageBeep(MessageBeepType.Warning); - return false; } } else { // Paste not allowed General.MessageBeep(MessageBeepType.Warning); - return false; } } diff --git a/Source/Core/Editing/GridSetup.cs b/Source/Core/Editing/GridSetup.cs index be4f484c..5a266738 100644 --- a/Source/Core/Editing/GridSetup.cs +++ b/Source/Core/Editing/GridSetup.cs @@ -269,7 +269,7 @@ namespace CodeImp.DoomBuilder.Editing #region ================== Actions // This shows the grid setup dialog - internal void ShowGridSetup() + internal static void ShowGridSetup() { // Show preferences dialog GridSetupForm gridform = new GridSetupForm(); diff --git a/Source/Core/Editing/ThingsFilter.cs b/Source/Core/Editing/ThingsFilter.cs index 43a031a7..293971ab 100644 --- a/Source/Core/Editing/ThingsFilter.cs +++ b/Source/Core/Editing/ThingsFilter.cs @@ -217,25 +217,30 @@ namespace CodeImp.DoomBuilder.Editing if(!General.Map.FormatInterface.HasCustomFields) customfields.Clear(); //mxd. We don't want to keep unknown flags (like flags from different map format) - if(General.Map.Config != null && General.Map.Config.ThingFlags != null) { + if(General.Map.Config != null && General.Map.Config.ThingFlags != null) + { List unknownfields = new List(); - foreach(String s in forbiddenfields) { + foreach(String s in forbiddenfields) + { if(!General.Map.Config.ThingFlags.ContainsKey(s)) unknownfields.Add(s); } - if(unknownfields.Count > 0) { + if(unknownfields.Count > 0) + { foreach(String s in unknownfields) forbiddenfields.Remove(s); } unknownfields = new List(); - foreach(String s in requiredfields) { + foreach(String s in requiredfields) + { if(!General.Map.Config.ThingFlags.ContainsKey(s)) unknownfields.Add(s); } - if(unknownfields.Count > 0) { + if(unknownfields.Count > 0) + { foreach(String s in unknownfields) requiredfields.Remove(s); } @@ -244,13 +249,15 @@ namespace CodeImp.DoomBuilder.Editing } //mxd - public void Validate() { + public void Validate() + { AdjustForMapFormat(); //Integrity check if(string.IsNullOrEmpty(categoryname) && thingtype == -1 && thingangle == -1 && thingzheight == int.MinValue && thingaction == -1 && thingtag == -1 - && requiredfields.Count == 0 && forbiddenfields.Count == 0 && customfields.Count == 0) { + && requiredfields.Count == 0 && forbiddenfields.Count == 0 && customfields.Count == 0) + { General.ErrorLogger.Add(ErrorType.Warning, "Things filter '" + name + "' has invalid properties. Configure the thing filter to fix this!"); } } diff --git a/Source/Core/Editing/UndoManager.cs b/Source/Core/Editing/UndoManager.cs index d1de403f..9877a929 100644 --- a/Source/Core/Editing/UndoManager.cs +++ b/Source/Core/Editing/UndoManager.cs @@ -876,7 +876,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayAddVertex(DeserializerStream ds) + private void PlayAddVertex(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Removing vertex " + index); @@ -898,7 +898,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRemVertex(DeserializerStream ds) + private void PlayRemVertex(DeserializerStream ds) { int index; ds.rInt(out index); Vector2D pos; ds.rVector2D(out pos); @@ -921,7 +921,7 @@ namespace CodeImp.DoomBuilder.Editing } } - internal void PlayPrpVertex(DeserializerStream ds) + private void PlayPrpVertex(DeserializerStream ds) { int index; ds.rInt(out index); Vertex v = General.Map.Map.GetVertexByIndex(index); @@ -940,7 +940,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayAddLinedef(DeserializerStream ds) + private void PlayAddLinedef(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Removing linedef " + index); @@ -964,7 +964,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRemLinedef(DeserializerStream ds) + private void PlayRemLinedef(DeserializerStream ds) { int index; ds.rInt(out index); int sindex; ds.rInt(out sindex); @@ -990,7 +990,7 @@ namespace CodeImp.DoomBuilder.Editing } } - internal void PlayPrpLinedef(DeserializerStream ds) + private static void PlayPrpLinedef(DeserializerStream ds) { int index; ds.rInt(out index); Linedef l = General.Map.Map.GetLinedefByIndex(index); @@ -1009,7 +1009,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRefLinedefStart(DeserializerStream ds) + private void PlayRefLinedefStart(DeserializerStream ds) { int index; ds.rInt(out index); Linedef l = General.Map.Map.GetLinedefByIndex(index); @@ -1033,7 +1033,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRefLinedefEnd(DeserializerStream ds) + private void PlayRefLinedefEnd(DeserializerStream ds) { int index; ds.rInt(out index); Linedef l = General.Map.Map.GetLinedefByIndex(index); @@ -1057,7 +1057,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRefLinedefFront(DeserializerStream ds) + private void PlayRefLinedefFront(DeserializerStream ds) { int index; ds.rInt(out index); Linedef l = General.Map.Map.GetLinedefByIndex(index); @@ -1081,7 +1081,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRefLinedefBack(DeserializerStream ds) + private void PlayRefLinedefBack(DeserializerStream ds) { int index; ds.rInt(out index); Linedef l = General.Map.Map.GetLinedefByIndex(index); @@ -1104,7 +1104,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayAddSidedef(DeserializerStream ds) + private void PlayAddSidedef(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Removing sidedef " + index); @@ -1128,7 +1128,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRemSidedef(DeserializerStream ds) + private void PlayRemSidedef(DeserializerStream ds) { int index; ds.rInt(out index); int dindex; ds.rInt(out dindex); @@ -1155,7 +1155,7 @@ namespace CodeImp.DoomBuilder.Editing } } - internal void PlayPrpSidedef(DeserializerStream ds) + private static void PlayPrpSidedef(DeserializerStream ds) { int index; ds.rInt(out index); Sidedef s = General.Map.Map.GetSidedefByIndex(index); @@ -1174,7 +1174,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRefSidedefSector(DeserializerStream ds) + private void PlayRefSidedefSector(DeserializerStream ds) { int index; ds.rInt(out index); Sidedef sd = General.Map.Map.GetSidedefByIndex(index); @@ -1197,7 +1197,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayAddSector(DeserializerStream ds) + private void PlayAddSector(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Removing sector " + index); @@ -1217,7 +1217,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRemSector(DeserializerStream ds) + private void PlayRemSector(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Adding sector " + index); @@ -1239,7 +1239,7 @@ namespace CodeImp.DoomBuilder.Editing } } - internal void PlayPrpSector(DeserializerStream ds) + private static void PlayPrpSector(DeserializerStream ds) { int index; ds.rInt(out index); Sector s = General.Map.Map.GetSectorByIndex(index); @@ -1257,7 +1257,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayAddThing(DeserializerStream ds) + private void PlayAddThing(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Removing thing " + index); @@ -1277,7 +1277,7 @@ namespace CodeImp.DoomBuilder.Editing propsrecorded = null; } - internal void PlayRemThing(DeserializerStream ds) + private void PlayRemThing(DeserializerStream ds) { int index; ds.rInt(out index); //LogRecordInfo("PLY: Adding thing " + index); @@ -1299,7 +1299,7 @@ namespace CodeImp.DoomBuilder.Editing } } - internal void PlayPrpThing(DeserializerStream ds) + private static void PlayPrpThing(DeserializerStream ds) { int index; ds.rInt(out index); Thing t = General.Map.Map.GetThingByIndex(index); diff --git a/Source/Core/GZBuilder/Controls/AngleControl.Designer.cs b/Source/Core/GZBuilder/Controls/AngleControl.Designer.cs index 35282759..0ad7193b 100644 --- a/Source/Core/GZBuilder/Controls/AngleControl.Designer.cs +++ b/Source/Core/GZBuilder/Controls/AngleControl.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.SuspendLayout(); diff --git a/Source/Core/GZBuilder/Controls/AngleControl.cs b/Source/Core/GZBuilder/Controls/AngleControl.cs index 7ea21054..0858d065 100644 --- a/Source/Core/GZBuilder/Controls/AngleControl.cs +++ b/Source/Core/GZBuilder/Controls/AngleControl.cs @@ -57,7 +57,7 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls #region Methods - private void setDrawRegion() + private void SetDrawRegion() { drawRegion = new Rectangle(0, 0, this.Width, this.Height); drawRegion.X += 2; @@ -94,13 +94,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls private void AngleSelector_Load(object sender, EventArgs e) { - setDrawRegion(); + SetDrawRegion(); } private void AngleSelector_SizeChanged(object sender, EventArgs e) { this.Height = this.Width; // Keep it there and keep it square! - setDrawRegion(); + SetDrawRegion(); } protected override void OnPaint(PaintEventArgs e) diff --git a/Source/Core/GZBuilder/Controls/ColorFieldsControl.Designer.cs b/Source/Core/GZBuilder/Controls/ColorFieldsControl.Designer.cs index 3f571e2c..cdc94183 100644 --- a/Source/Core/GZBuilder/Controls/ColorFieldsControl.Designer.cs +++ b/Source/Core/GZBuilder/Controls/ColorFieldsControl.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.bReset = new System.Windows.Forms.Button(); this.cpColor = new CodeImp.DoomBuilder.Controls.ColorControl(); this.tbColor = new CodeImp.DoomBuilder.Controls.AutoSelectTextbox(); diff --git a/Source/Core/GZBuilder/Controls/ColorFieldsControl.cs b/Source/Core/GZBuilder/Controls/ColorFieldsControl.cs index 95208e17..17ffe035 100644 --- a/Source/Core/GZBuilder/Controls/ColorFieldsControl.cs +++ b/Source/Core/GZBuilder/Controls/ColorFieldsControl.cs @@ -1,4 +1,6 @@ -using System; +#region ================== Namespaces + +using System; using System.Drawing; using System.Windows.Forms; using System.Globalization; @@ -6,6 +8,8 @@ using CodeImp.DoomBuilder.Rendering; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.GZBuilder.Tools; +#endregion + namespace CodeImp.DoomBuilder.GZBuilder.Controls { public partial class ColorFieldsControl : UserControl @@ -32,25 +36,32 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls #endregion - public ColorFieldsControl() { + public ColorFieldsControl() + { InitializeComponent(); } - public void SetValueFrom(UniFields fields) { + public void SetValueFrom(UniFields fields) + { string newValue = String.Format("{0:X6}", UDMFTools.GetInteger(fields, field, defaultValue)); tbColor.Text = ((!string.IsNullOrEmpty(tbColor.Text) && tbColor.Text != newValue) ? "" : newValue); - checkColor(); + CheckColor(); } - public void ApplyTo(UniFields fields, int oldValue) { - if(string.IsNullOrEmpty(tbColor.Text)) { + public void ApplyTo(UniFields fields, int oldValue) + { + if(string.IsNullOrEmpty(tbColor.Text)) + { UDMFTools.SetInteger(fields, field, oldValue, defaultValue); - } else { + } + else + { UDMFTools.SetInteger(fields, field, (cpColor.Color.ToInt() & 0x00ffffff), defaultValue); } } - private void checkColor() { + private void CheckColor() + { bool changed = string.IsNullOrEmpty(tbColor.Text) || (cpColor.Color.ToInt() & 0x00ffffff) != defaultValue; bReset.Visible = changed; tbColor.ForeColor = changed ? SystemColors.WindowText : SystemColors.GrayText; @@ -58,27 +69,31 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls #region ================== Events - private void bReset_Click(object sender, EventArgs e) { + private void bReset_Click(object sender, EventArgs e) + { cpColor.Color = PixelColor.FromInt(defaultValue).WithAlpha(255); cpColor_ColorChanged(this, EventArgs.Empty); } - private void cpColor_ColorChanged(object sender, EventArgs e) { + private void cpColor_ColorChanged(object sender, EventArgs e) + { if(blockUpdate) return; blockUpdate = true; tbColor.Text = String.Format("{0:X6}", (cpColor.Color.ToInt() & 0x00ffffff)); blockUpdate = false; - checkColor(); + CheckColor(); if(OnValueChanged != null) OnValueChanged(this, EventArgs.Empty); } - private void tbColor_TextChanged(object sender, EventArgs e) { + private void tbColor_TextChanged(object sender, EventArgs e) + { if(blockUpdate) return; int colorVal; - if(int.TryParse(tbColor.Text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out colorVal)){ + if(int.TryParse(tbColor.Text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out colorVal)) + { colorVal = General.Clamp(colorVal, 0, 16777215); blockUpdate = true; @@ -86,7 +101,7 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls blockUpdate = false; } - checkColor(); + CheckColor(); if(OnValueChanged != null) OnValueChanged(this, EventArgs.Empty); } diff --git a/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.cs b/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.cs index f55d380f..ffc5bec7 100644 --- a/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.cs +++ b/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.cs @@ -27,17 +27,20 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls public string Flag { get { return flag; } } private string flag; - public FlagData(string title, string flag) { + public FlagData(string title, string flag) + { this.title = title; this.flag = flag; } - public override string ToString() { + public override string ToString() + { return Title; } } - public CustomLinedefColorProperties() { + public CustomLinedefColorProperties() + { InitializeComponent(); defaultColor = lineColor.Color; @@ -47,7 +50,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls labelErrors.Text = ""; } - public void Setup(GameConfiguration config) { + public void Setup(GameConfiguration config) + { udmf = (config.FormatInterface == "UniversalMapSetIO"); presetUpdating = true; @@ -75,19 +79,25 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls //get activates List activations = config.LinedefActivates; - if(activations.Count > 0) { + if(activations.Count > 0) + { activations.Insert(0, new LinedefActivateInfo("-1", "Any activation")); - if(udmf) { + if(udmf) + { foreach(LinedefActivateInfo ai in config.LinedefActivates) udmfactivates.Items.Add(new FlagData(ai.Title, ai.Key), CheckState.Indeterminate); - } else { + } + else + { activation.Items.AddRange(activations.ToArray()); } if(!tcLineSettings.TabPages.Contains(tabActivation)) tcLineSettings.TabPages.Add(tabActivation); - } else { + } + else + { tcLineSettings.TabPages.Remove(tabActivation); } @@ -100,7 +110,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls presetUpdating = false; } - public void SetPreset(LinedefColorPreset preset) { + public void SetPreset(LinedefColorPreset preset) + { this.Enabled = true; presetUpdating = true; @@ -110,19 +121,27 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls lineColor.Color = this.preset.Color; //set flags - applyFlagsToControl(flags, cbUseFlags); + ApplyFlagsToControl(flags, cbUseFlags); //set activation - if(udmf) { - applyFlagsToControl(udmfactivates, cbUseActivation); - } else if(tcLineSettings.TabPages.Contains(tabActivation)) { - if(this.preset.Activation == 0) { + if(udmf) + { + ApplyFlagsToControl(udmfactivates, cbUseActivation); + } + else if(tcLineSettings.TabPages.Contains(tabActivation)) + { + if(this.preset.Activation == 0) + { activation.SelectedIndex = 1; cbUseActivation.Checked = false; activation.Enabled = false; - } else { - for(int i = 0; i < activation.Items.Count; i++) { - if(((LinedefActivateInfo)activation.Items[i]).Index == this.preset.Activation) { + } + else + { + for(int i = 0; i < activation.Items.Count; i++) + { + if(((LinedefActivateInfo)activation.Items[i]).Index == this.preset.Activation) + { activation.SelectedIndex = i; cbUseActivation.Checked = true; activation.Enabled = true; @@ -143,53 +162,63 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls presetUpdating = false; } - public LinedefColorPreset GetPreset() { + /*public LinedefColorPreset GetPreset() + { return preset; - } + }*/ - public void UpdateMessages() { + public void UpdateMessages() + { //warnings/errors? List errors = new List(); - - if(!preset.Valid) - errors.Add(preset.ErrorDescription); - - if(!string.IsNullOrEmpty(preset.WarningDescription)) - errors.Add(preset.WarningDescription); - + if(!preset.Valid) errors.Add(preset.ErrorDescription); + if(!string.IsNullOrEmpty(preset.WarningDescription)) errors.Add(preset.WarningDescription); labelErrors.Text = (errors.Count > 0 ? string.Join(Environment.NewLine, errors.ToArray()) : ""); } - private void raiseEvent() { - if(PresetChanged != null) - PresetChanged(this, EventArgs.Empty); + private void RaiseEvent() + { + if(PresetChanged != null) PresetChanged(this, EventArgs.Empty); } - private void applyFlagsToPreset(CheckedListBox source) { - if(source.Enabled) { - for(int i = 0; i < source.Items.Count; i++) { + private void ApplyFlagsToPreset(CheckedListBox source) + { + if(source.Enabled) + { + for(int i = 0; i < source.Items.Count; i++) + { string flag = ((FlagData)source.Items[i]).Flag; CheckState state = source.GetItemCheckState(i); - if(state == CheckState.Checked) { - if(!preset.Flags.Contains(flag)) - preset.Flags.Add(flag); - if(preset.RestrictedFlags.Contains(flag)) - preset.RestrictedFlags.Remove(flag); - } else if(state == CheckState.Unchecked) { - if(preset.Flags.Contains(flag)) - preset.Flags.Remove(flag); - if(!preset.RestrictedFlags.Contains(flag)) - preset.RestrictedFlags.Add(flag); - } else { - if(preset.Flags.Contains(flag)) - preset.Flags.Remove(flag); - if(preset.RestrictedFlags.Contains(flag)) - preset.RestrictedFlags.Remove(flag); + switch (state) + { + case CheckState.Checked: + if(!preset.Flags.Contains(flag)) + preset.Flags.Add(flag); + if(preset.RestrictedFlags.Contains(flag)) + preset.RestrictedFlags.Remove(flag); + break; + + case CheckState.Unchecked: + if(preset.Flags.Contains(flag)) + preset.Flags.Remove(flag); + if(!preset.RestrictedFlags.Contains(flag)) + preset.RestrictedFlags.Add(flag); + break; + + default: + if(preset.Flags.Contains(flag)) + preset.Flags.Remove(flag); + if(preset.RestrictedFlags.Contains(flag)) + preset.RestrictedFlags.Remove(flag); + break; } } - } else { - for(int i = 0; i < source.Items.Count; i++) { + } + else + { + for(int i = 0; i < source.Items.Count; i++) + { string flag = ((FlagData)source.Items[i]).Flag; if(preset.Flags.Contains(flag)) @@ -200,18 +229,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls } } - private void applyFlagsToControl(CheckedListBox target, CheckBox cb) { - if(preset.Flags.Count == 0 && preset.RestrictedFlags.Count == 0) { + private void ApplyFlagsToControl(CheckedListBox target, CheckBox cb) + { + if(preset.Flags.Count == 0 && preset.RestrictedFlags.Count == 0) + { cb.Checked = false; target.Enabled = false; for(int i = 0; i < target.Items.Count; i++) target.SetItemCheckState(i, CheckState.Indeterminate); - } else { + } + else + { bool hasFlags = false; CheckState flagState; - for(int i = 0; i < target.Items.Count; i++) { + for(int i = 0; i < target.Items.Count; i++) + { string flag = ((FlagData)target.Items[i]).Flag; if(preset.Flags.Contains(flag)) @@ -231,79 +265,85 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls } //EVENTS - private void cbUseFlags_CheckedChanged(object sender, EventArgs e) { + private void cbUseFlags_CheckedChanged(object sender, EventArgs e) + { if(presetUpdating) return; flags.Enabled = cbUseFlags.Checked; - applyFlagsToPreset(flags); + ApplyFlagsToPreset(flags); - if(!flags.Enabled) raiseEvent(); + if(!flags.Enabled) RaiseEvent(); } - private void flags_SelectedValueChanged(object sender, EventArgs e) { + private void flags_SelectedValueChanged(object sender, EventArgs e) + { if(presetUpdating) return; - applyFlagsToPreset(flags); + ApplyFlagsToPreset(flags); - raiseEvent(); + RaiseEvent(); } - private void cbUseAction_CheckedChanged(object sender, EventArgs e) { + private void cbUseAction_CheckedChanged(object sender, EventArgs e) + { if(presetUpdating) return; - action.Enabled = cbUseAction.Checked; action.Value = 0; - //raiseEvent(); } - private void action_ValueChanges(object sender, EventArgs e) { + private void action_ValueChanges(object sender, EventArgs e) + { if(presetUpdating) return; preset.Action = action.Value; - raiseEvent(); + RaiseEvent(); } - private void cbUseActivation_CheckedChanged(object sender, EventArgs e) { + private void cbUseActivation_CheckedChanged(object sender, EventArgs e) + { if(presetUpdating) return; activation.Enabled = cbUseActivation.Checked; udmfactivates.Enabled = cbUseActivation.Checked; - if(udmf) { - applyFlagsToPreset(udmfactivates); - } else { - if(!cbUseActivation.Checked) - activation.SelectedIndex = 1; - } + if(udmf) ApplyFlagsToPreset(udmfactivates); + else if(!cbUseActivation.Checked) activation.SelectedIndex = 1; - if(!cbUseActivation.Checked) raiseEvent(); + if(!cbUseActivation.Checked) RaiseEvent(); } - private void activation_SelectedIndexChanged(object sender, EventArgs e) { + private void activation_SelectedIndexChanged(object sender, EventArgs e) + { if(presetUpdating) return; - preset.Activation = ((LinedefActivateInfo)activation.SelectedItem).Index; - raiseEvent(); + RaiseEvent(); } - private void udmfactivates_SelectedValueChanged(object sender, EventArgs e) { + private void udmfactivates_SelectedValueChanged(object sender, EventArgs e) + { if(presetUpdating) return; - applyFlagsToPreset(udmfactivates); - raiseEvent(); + ApplyFlagsToPreset(udmfactivates); + RaiseEvent(); } - private void lineColor_ColorChanged(object sender, EventArgs e) { + private void lineColor_ColorChanged(object sender, EventArgs e) + { if(presetUpdating) return; - preset.Color = lineColor.Color; - raiseEvent(); + RaiseEvent(); } - private void flags_ItemCheck(object sender, ItemCheckEventArgs e) { + private void flags_ItemCheck(object sender, ItemCheckEventArgs e) + { if(presetUpdating) return; - - if(e.CurrentValue == CheckState.Checked) - e.NewValue = CheckState.Indeterminate; - else if(e.CurrentValue == CheckState.Indeterminate) - e.NewValue = CheckState.Unchecked; - else - e.NewValue = CheckState.Checked; + switch (e.CurrentValue) + { + case CheckState.Checked: + e.NewValue = CheckState.Indeterminate; + break; + case CheckState.Indeterminate: + e.NewValue = CheckState.Unchecked; + break; + default: + e.NewValue = CheckState.Checked; + break; + } } } } diff --git a/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.designer.cs b/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.designer.cs index 6939a1c9..1edb900a 100644 --- a/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.designer.cs +++ b/Source/Core/GZBuilder/Controls/CustomLinedefColorProperties.designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.gbLineColor = new System.Windows.Forms.GroupBox(); this.labelErrors = new System.Windows.Forms.Label(); this.tcLineSettings = new System.Windows.Forms.TabControl(); diff --git a/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.cs b/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.cs index b9a5d0e4..4489dac6 100644 --- a/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.cs +++ b/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.cs @@ -14,7 +14,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls private const string DEFAULT_PRESET_NAME = "Enter preset name"; private const string NO_PRESET_NAME = "ENTER PRESET NAME!"; - public CustomLinedefColorsControl() { + public CustomLinedefColorsControl() + { InitializeComponent(); colorProperties.PresetChanged += colorProperties_PresetChanged; @@ -22,26 +23,30 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls gbPresets.Enabled = false; } - public void Setup(GameConfiguration config, ConfigurationInfo configInfo) { + public void Setup(GameConfiguration config, ConfigurationInfo configInfo) + { colorProperties.Setup(config); lbColorPresets.Items.Clear(); - if(configInfo.LinedefColorPresets.Length > 0) { + if(configInfo.LinedefColorPresets.Length > 0) + { //validate - for(int i = 0; i < configInfo.LinedefColorPresets.Length; i++) { - validatePreset(configInfo.LinedefColorPresets[i]); - checkDuplicates(configInfo.LinedefColorPresets[i]); + for(int i = 0; i < configInfo.LinedefColorPresets.Length; i++) + { + ValidatePreset(configInfo.LinedefColorPresets[i]); + CheckDuplicates(configInfo.LinedefColorPresets[i]); } lbColorPresets.Items.AddRange(configInfo.LinedefColorPresets); lbColorPresets.SelectedIndex = 0; } - updatePresetListControls(); + UpdatePresetListControls(); gbPresets.Enabled = true; } - public LinedefColorPreset[] GetPresets() { + public LinedefColorPreset[] GetPresets() + { List presets = new List(); foreach(LinedefColorPreset preset in lbColorPresets.Items) @@ -50,33 +55,38 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls return presets.ToArray(); } - private void validatePreset(LinedefColorPreset preset) { + private void ValidatePreset(LinedefColorPreset preset) + { bool hasAction = preset.Action != 0; bool hasFlags = preset.Flags.Count > 0 || preset.RestrictedFlags.Count > 0; bool hasActivation = preset.Activation != 0; //validate - if(!hasAction && !hasFlags && !hasActivation) { - if(colorProperties.UDMF) { + if(!hasAction && !hasFlags && !hasActivation) + { + if(colorProperties.UDMF) preset.SetInvalid("Invalid preset: no flags, action or activation type selected!"); - } else { + else preset.SetInvalid("Invalid preset: no flags or action selected!"); - } return; } preset.SetValid(); } - private bool validatePresetName() { - if(string.IsNullOrEmpty(tbNewPresetName.Text) || tbNewPresetName.Text == DEFAULT_PRESET_NAME || tbNewPresetName.Text == NO_PRESET_NAME) { + private bool ValidatePresetName() + { + if(string.IsNullOrEmpty(tbNewPresetName.Text) || tbNewPresetName.Text == DEFAULT_PRESET_NAME || tbNewPresetName.Text == NO_PRESET_NAME) + { tbNewPresetName.ForeColor = Color.DarkRed; tbNewPresetName.Text = string.IsNullOrEmpty(tbNewPresetName.Text) ? DEFAULT_PRESET_NAME : NO_PRESET_NAME; return false; } - foreach(LinedefColorPreset preset in lbColorPresets.Items) { - if(preset.Name.ToLowerInvariant() == tbNewPresetName.Text.ToLowerInvariant()) { + foreach(LinedefColorPreset preset in lbColorPresets.Items) + { + if(preset.Name.ToLowerInvariant() == tbNewPresetName.Text.ToLowerInvariant()) + { General.ShowWarningMessage("Preset with this name already exists!", MessageBoxButtons.OK); return false; } @@ -86,9 +96,10 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls return true; } - private void checkDuplicates(LinedefColorPreset preset) + private void CheckDuplicates(LinedefColorPreset preset) { - foreach(LinedefColorPreset p in lbColorPresets.Items) { + foreach(LinedefColorPreset p in lbColorPresets.Items) + { if(preset.Name == p.Name) continue; if(p.Action != preset.Action) continue; if(p.Activation != preset.Activation) continue; @@ -96,15 +107,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls if(p.RestrictedFlags.Count != preset.RestrictedFlags.Count) continue; bool gotMismatch = false; - foreach(string flag in p.Flags) { - if(!preset.Flags.Contains(flag)) { + foreach(string flag in p.Flags) + { + if(!preset.Flags.Contains(flag)) + { gotMismatch = true; break; } } - foreach(string flag in p.RestrictedFlags) { - if(!preset.RestrictedFlags.Contains(flag)) { + foreach(string flag in p.RestrictedFlags) + { + if(!preset.RestrictedFlags.Contains(flag)) + { gotMismatch = true; break; } @@ -118,23 +133,28 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls } } - private void updatePresetListControls() { + private void UpdatePresetListControls() + { int c = lbColorPresets.Items.Count; bRemovePreset.Enabled = c > 0; colorProperties.Enabled = c > 0; - if(c < 2) { + if(c < 2) + { bMoveDown.Enabled = false; bMoveUp.Enabled = false; - } else { + } + else + { bMoveDown.Enabled = lbColorPresets.SelectedIndex < c - 1; bMoveUp.Enabled = lbColorPresets.SelectedIndex > 0; } } //EVENTS - private void bMoveDown_Click(object sender, EventArgs e) { + private void bMoveDown_Click(object sender, EventArgs e) + { if(lbColorPresets.SelectedIndex == -1) return; //I like to move it, move it! @@ -144,11 +164,11 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls lbColorPresets.SelectedIndex++; - if(PresetsChanged != null) - PresetsChanged(this, EventArgs.Empty); + if(PresetsChanged != null) PresetsChanged(this, EventArgs.Empty); } - private void bMoveUp_Click(object sender, EventArgs e) { + private void bMoveUp_Click(object sender, EventArgs e) + { if(lbColorPresets.SelectedIndex == -1) return; LinedefColorPreset preset = (LinedefColorPreset)lbColorPresets.SelectedItem; @@ -157,12 +177,12 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls lbColorPresets.SelectedIndex--; - if(PresetsChanged != null) - PresetsChanged(this, EventArgs.Empty); + if(PresetsChanged != null) PresetsChanged(this, EventArgs.Empty); } - private void bAddPreset_Click(object sender, EventArgs e) { - if(!validatePresetName()) return; + private void bAddPreset_Click(object sender, EventArgs e) + { + if(!ValidatePresetName()) return; //add new item lbColorPresets.Items.Insert(0, new LinedefColorPreset(tbNewPresetName.Text, colorProperties.DefaultColor)); @@ -174,13 +194,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls else lbColorPresets_SelectedIndexChanged(this, EventArgs.Empty); - updatePresetListControls(); + UpdatePresetListControls(); - if(PresetsChanged != null) - PresetsChanged(this, EventArgs.Empty); + if(PresetsChanged != null) PresetsChanged(this, EventArgs.Empty); } - private void bRemovePreset_Click(object sender, EventArgs e) { + private void bRemovePreset_Click(object sender, EventArgs e) + { if(lbColorPresets.Items.Count == 0 || lbColorPresets.SelectedIndex == -1) return; //sanity check //remove item @@ -188,43 +208,48 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls lbColorPresets.Items.RemoveAt(index); lbColorPresets.SelectedIndex = (index >= lbColorPresets.Items.Count ? lbColorPresets.Items.Count - 1 : index); - updatePresetListControls(); + UpdatePresetListControls(); - if(PresetsChanged != null) - PresetsChanged(this, EventArgs.Empty); + if(PresetsChanged != null) PresetsChanged(this, EventArgs.Empty); } - private void lbColorPresets_SelectedIndexChanged(object sender, EventArgs e) { - if(lbColorPresets.SelectedIndex == -1) { + private void lbColorPresets_SelectedIndexChanged(object sender, EventArgs e) + { + if(lbColorPresets.SelectedIndex == -1) + { colorProperties.Enabled = false; return; } colorProperties.SetPreset((LinedefColorPreset)lbColorPresets.SelectedItem); - updatePresetListControls(); + UpdatePresetListControls(); } - private void colorProperties_PresetChanged(object sender, EventArgs e) { + private void colorProperties_PresetChanged(object sender, EventArgs e) + { LinedefColorPreset preset = (LinedefColorPreset)lbColorPresets.SelectedItem; preset.SetValid(); //clear error/warning messages - validatePreset(preset); //validate it - checkDuplicates(preset); + ValidatePreset(preset); //validate it + CheckDuplicates(preset); colorProperties.UpdateMessages(); //update error/warning messages lbColorPresets.Invalidate(); //redraw icons - if(PresetsChanged != null) - PresetsChanged(this, EventArgs.Empty); + if(PresetsChanged != null) PresetsChanged(this, EventArgs.Empty); } - private void tbNewPresetName_Click(object sender, EventArgs e) { - if(tbNewPresetName.Text == DEFAULT_PRESET_NAME || tbNewPresetName.Text == NO_PRESET_NAME) { + private void tbNewPresetName_Click(object sender, EventArgs e) + { + if(tbNewPresetName.Text == DEFAULT_PRESET_NAME || tbNewPresetName.Text == NO_PRESET_NAME) + { tbNewPresetName.Text = ""; tbNewPresetName.ForeColor = Color.Black; } } - private void tbNewPresetName_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { - if(e.KeyCode == Keys.Enter) { + private void tbNewPresetName_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) + { + if(e.KeyCode == Keys.Enter) + { bAddPreset_Click(this, EventArgs.Empty); e.IsInputKey = true; } diff --git a/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.designer.cs b/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.designer.cs index 59c98a03..44f21368 100644 --- a/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.designer.cs +++ b/Source/Core/GZBuilder/Controls/CustomLinedefColorsControl.designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.gbPresets = new System.Windows.Forms.GroupBox(); this.bMoveUp = new System.Windows.Forms.Button(); this.bMoveDown = new System.Windows.Forms.Button(); diff --git a/Source/Core/GZBuilder/Controls/IconListBox.cs b/Source/Core/GZBuilder/Controls/IconListBox.cs index 1c3633d6..2a7f34fd 100644 --- a/Source/Core/GZBuilder/Controls/IconListBox.cs +++ b/Source/Core/GZBuilder/Controls/IconListBox.cs @@ -6,11 +6,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls { internal class IconListBox : ListBox { - public IconListBox() { + public IconListBox() + { this.DrawMode = DrawMode.OwnerDrawFixed; } - protected override void OnDrawItem(DrawItemEventArgs e) { + protected override void OnDrawItem(DrawItemEventArgs e) + { e.DrawBackground(); e.DrawFocusRectangle(); diff --git a/Source/Core/GZBuilder/Controls/MultiSelectTreeview.cs b/Source/Core/GZBuilder/Controls/MultiSelectTreeview.cs index 03c2c7ae..ee7d00ba 100644 --- a/Source/Core/GZBuilder/Controls/MultiSelectTreeview.cs +++ b/Source/Core/GZBuilder/Controls/MultiSelectTreeview.cs @@ -706,10 +706,9 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls /// TreeNode to check. /// MouseEventArgs. /// True is mouse was clicked inside the node bounds, false if it was clicked ouside the node bounds. - private bool IsClickOnNode(TreeNode tn, MouseEventArgs e) + private static bool IsClickOnNode(TreeNode tn, MouseEventArgs e) { - if (tn == null) - return false; + if (tn == null) return false; // GKM // Determine the rightmost position we'll process clicks (so that the click has to be on the node's bounds, @@ -737,7 +736,7 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls /// Node to check. /// Parent node. /// True if specified node is a direct or indirect child of parent node, false if not. - private bool IsChildOf(TreeNode child, TreeNode parent) + private static bool IsChildOf(TreeNode child, TreeNode parent) { bool blnChild = false; @@ -821,7 +820,7 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls /// True to go down, false to go up. /// Number of nodes to go down or up. /// Next node. - private TreeNode GetNextTreeNode(TreeNode start, bool down, int intNumber) + private static TreeNode GetNextTreeNode(TreeNode start, bool down, int intNumber) { int intCounter = 0; TreeNode tnTemp = start; diff --git a/Source/Core/GZBuilder/Controls/PairedFieldsControl.Designer.cs b/Source/Core/GZBuilder/Controls/PairedFieldsControl.Designer.cs index 28261ab5..21727656 100644 --- a/Source/Core/GZBuilder/Controls/PairedFieldsControl.Designer.cs +++ b/Source/Core/GZBuilder/Controls/PairedFieldsControl.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.label = new System.Windows.Forms.Label(); this.bReset = new System.Windows.Forms.Button(); this.bLink = new System.Windows.Forms.Button(); diff --git a/Source/Core/GZBuilder/Controls/PairedFieldsControl.cs b/Source/Core/GZBuilder/Controls/PairedFieldsControl.cs index e4be4857..23eeab6f 100644 --- a/Source/Core/GZBuilder/Controls/PairedFieldsControl.cs +++ b/Source/Core/GZBuilder/Controls/PairedFieldsControl.cs @@ -39,14 +39,15 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls public bool AllowDecimal { get { return value1.AllowDecimal; } set { value1.AllowDecimal = value; value2.AllowDecimal = value; } } public int ButtonStep { get { return value1.ButtonStep; } set { value1.ButtonStep = value; value2.ButtonStep = value; } } public float ButtonStepFloat { get { return value1.ButtonStepFloat; } set { value1.ButtonStepFloat = value; value2.ButtonStepFloat = value; } } - public bool AllowValueLinking { get { return allowValueLinking; } set { allowValueLinking = value; updateButtons(); } } - public bool LinkValues { get { return linkValues; } set { linkValues = value; updateButtons(); } } + public bool AllowValueLinking { get { return allowValueLinking; } set { allowValueLinking = value; UpdateButtons(); } } + public bool LinkValues { get { return linkValues; } set { linkValues = value; UpdateButtons(); } } #endregion #region ================== Constructor - public PairedFieldsControl() { + public PairedFieldsControl() + { InitializeComponent(); bResetOffsetX = this.Width - bReset.Left; } @@ -55,36 +56,44 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls #region ================== Methods - public void SetValuesFrom(UniFields fields, bool first) { + public void SetValuesFrom(UniFields fields, bool first) + { blockUpdate = true; string newValue1; string newValue2; - if(AllowDecimal) { + if(AllowDecimal) + { float val1 = UDMFTools.GetFloat(fields, field1, defaultValue); newValue1 = (val1 == Math.Round(val1) ? val1.ToString("0.0") : val1.ToString()); float val2 = UDMFTools.GetFloat(fields, field2, defaultValue); newValue2 = (val2 == Math.Round(val2) ? val2.ToString("0.0") : val2.ToString()); - } else { + } + else + { newValue1 = UDMFTools.GetFloat(fields, field1, defaultValue).ToString(); newValue2 = UDMFTools.GetFloat(fields, field2, defaultValue).ToString(); } - if(first) { + if(first) + { value1.Text = newValue1; value2.Text = newValue2; - } else { + } + else + { value1.Text = ((!string.IsNullOrEmpty(value1.Text) && value1.Text != newValue1) ? string.Empty : newValue1); value2.Text = ((!string.IsNullOrEmpty(value2.Text) && value2.Text != newValue2) ? string.Empty : newValue2); } - checkValues(); + CheckValues(); blockUpdate = false; } - public void ApplyTo(UniFields fields, int min, int max, float oldValue1, float oldValue2) { + public void ApplyTo(UniFields fields, int min, int max, float oldValue1, float oldValue2) + { if(value1.Text != string.Empty) UDMFTools.SetFloat(fields, field1, General.Clamp(value1.GetResultFloat(defaultValue), min, max), defaultValue); else @@ -96,7 +105,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls UDMFTools.SetFloat(fields, field2, oldValue2, defaultValue); } - private void checkValues() { + private void CheckValues() + { bool changed = string.IsNullOrEmpty(value1.Text) || string.IsNullOrEmpty(value2.Text) || value1.GetResultFloat(defaultValue) != defaultValue || value2.GetResultFloat(defaultValue) != defaultValue; label.Enabled = changed; @@ -105,12 +115,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls if(!blockUpdate && OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void updateButtons() { + private void UpdateButtons() + { bLink.Visible = allowValueLinking; - if(!allowValueLinking) { + if(!allowValueLinking) + { bReset.Left = bLink.Left; - } else { + } + else + { bReset.Left = this.Width - bResetOffsetX; bLink.Image = (linkValues ? Resources.Link : Resources.Unlink); } @@ -120,40 +134,46 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls #region ================== Events - private void bLink_Click(object sender, EventArgs e) { + private void bLink_Click(object sender, EventArgs e) + { linkValues = !linkValues; bLink.Image = (linkValues ? Resources.Link : Resources.Unlink); } - private void bReset_Click(object sender, EventArgs e) { + private void bReset_Click(object sender, EventArgs e) + { string newValue = value1.AllowDecimal ? String.Format("{0:0.0}", defaultValue) : defaultValue.ToString(); value1.Text = newValue; value2.Text = newValue; - checkValues(); + CheckValues(); } - private void value1_WhenTextChanged(object sender, EventArgs e) { + private void value1_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; - if(linkValues) { + if(linkValues) + { blockUpdate = true; value2.Text = value1.Text; blockUpdate = false; } - checkValues(); + CheckValues(); } - private void value2_WhenTextChanged(object sender, EventArgs e) { + private void value2_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; - if(linkValues) { + if(linkValues) + { blockUpdate = true; value1.Text = value2.Text; blockUpdate = false; } - checkValues(); + CheckValues(); } #endregion diff --git a/Source/Core/GZBuilder/Controls/PairedFloatControl.cs b/Source/Core/GZBuilder/Controls/PairedFloatControl.cs index 37da4d39..c0a4ba77 100644 --- a/Source/Core/GZBuilder/Controls/PairedFloatControl.cs +++ b/Source/Core/GZBuilder/Controls/PairedFloatControl.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Windows.Forms; using CodeImp.DoomBuilder.Properties; @@ -37,18 +38,21 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls { blockUpdate = true; - if (first) { - value1.Text = val1.ToString(); - value2.Text = val2.ToString(); - } else { - if (!string.IsNullOrEmpty(value1.Text) && value1.Text != val1.ToString()) + if (first) + { + value1.Text = val1.ToString(CultureInfo.InvariantCulture); + value2.Text = val2.ToString(CultureInfo.InvariantCulture); + } + else + { + if (!string.IsNullOrEmpty(value1.Text) && value1.Text != val1.ToString(CultureInfo.InvariantCulture)) value1.Text = string.Empty; - if (!string.IsNullOrEmpty(value2.Text) && value2.Text != val2.ToString()) + if (!string.IsNullOrEmpty(value2.Text) && value2.Text != val2.ToString(CultureInfo.InvariantCulture)) value2.Text = string.Empty; } - checkValues(); + CheckValues(); blockUpdate = false; } @@ -63,10 +67,10 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls return value2.GetResultFloat(original); } - private void checkValues() + private void CheckValues() { - bool changed = string.IsNullOrEmpty(value1.Text) || string.IsNullOrEmpty(value2.Text) - || value1.GetResultFloat(defaultValue) != defaultValue || value2.GetResultFloat(defaultValue) != defaultValue; + bool changed = (string.IsNullOrEmpty(value1.Text) || string.IsNullOrEmpty(value2.Text) + || value1.GetResultFloat(defaultValue) != defaultValue || value2.GetResultFloat(defaultValue) != defaultValue); label.Enabled = changed; bReset.Visible = changed; @@ -78,7 +82,7 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls string newValue = String.Format("{0:0.0}", defaultValue); value1.Text = newValue; value2.Text = newValue; - checkValues(); + CheckValues(); } private void bLink_Click(object sender, EventArgs e) @@ -91,26 +95,28 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls { if (blockUpdate) return; - if (linkValues) { + if (linkValues) + { blockUpdate = true; value2.Text = value1.Text; blockUpdate = false; } - checkValues(); + CheckValues(); } private void value2_WhenTextChanged(object sender, EventArgs e) { if (blockUpdate) return; - if (linkValues) { + if (linkValues) + { blockUpdate = true; value1.Text = value2.Text; blockUpdate = false; } - checkValues(); + CheckValues(); } } } diff --git a/Source/Core/GZBuilder/Controls/PairedIntControl.Designer.cs b/Source/Core/GZBuilder/Controls/PairedIntControl.Designer.cs index da2d6128..3ad5617a 100644 --- a/Source/Core/GZBuilder/Controls/PairedIntControl.Designer.cs +++ b/Source/Core/GZBuilder/Controls/PairedIntControl.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.label = new System.Windows.Forms.Label(); this.bReset = new System.Windows.Forms.Button(); this.value1 = new CodeImp.DoomBuilder.Controls.ButtonsNumericTextbox(); diff --git a/Source/Core/GZBuilder/Controls/PairedIntControl.cs b/Source/Core/GZBuilder/Controls/PairedIntControl.cs index b60ec7d0..087c8a25 100644 --- a/Source/Core/GZBuilder/Controls/PairedIntControl.cs +++ b/Source/Core/GZBuilder/Controls/PairedIntControl.cs @@ -1,6 +1,7 @@ #region ================== Namespaces using System; +using System.Globalization; using System.Windows.Forms; #endregion @@ -30,36 +31,44 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls #endregion - public PairedIntControl() { + public PairedIntControl() + { InitializeComponent(); } - public void SetValues(int val1, int val2, bool first) { + public void SetValues(int val1, int val2, bool first) + { blockUpdate = true; - if (first) { - value1.Text = val1.ToString(); - value2.Text = val2.ToString(); - } else { - if (!string.IsNullOrEmpty(value1.Text) && value1.Text != val1.ToString()) + if (first) + { + value1.Text = val1.ToString(CultureInfo.InvariantCulture); + value2.Text = val2.ToString(CultureInfo.InvariantCulture); + } + else + { + if (!string.IsNullOrEmpty(value1.Text) && value1.Text != val1.ToString(CultureInfo.InvariantCulture)) value1.Text = string.Empty; - if (!string.IsNullOrEmpty(value2.Text) && value2.Text != val2.ToString()) + if (!string.IsNullOrEmpty(value2.Text) && value2.Text != val2.ToString(CultureInfo.InvariantCulture)) value2.Text = string.Empty; } blockUpdate = false; } - public int GetValue1(int original) { + public int GetValue1(int original) + { return value1.GetResult(original); } - public int GetValue2(int original) { + public int GetValue2(int original) + { return value2.GetResult(original); } - private void checkValues() { + private void CheckValues() + { bool changed = string.IsNullOrEmpty(value1.Text) || string.IsNullOrEmpty(value2.Text) || value1.GetResult(defaultValue) != defaultValue || value2.GetResult(defaultValue) != defaultValue; label.Enabled = changed; @@ -68,14 +77,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls if(!blockUpdate && OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void bReset_Click(object sender, EventArgs e) { - value1.Text = defaultValue.ToString(); - value2.Text = defaultValue.ToString(); - checkValues(); + private void bReset_Click(object sender, EventArgs e) + { + value1.Text = defaultValue.ToString(CultureInfo.InvariantCulture); + value2.Text = defaultValue.ToString(CultureInfo.InvariantCulture); + CheckValues(); } - private void value1_WhenTextChanged(object sender, EventArgs e) { - checkValues(); + private void value1_WhenTextChanged(object sender, EventArgs e) + { + CheckValues(); } } } diff --git a/Source/Core/GZBuilder/Controls/TagSelector.Designer.cs b/Source/Core/GZBuilder/Controls/TagSelector.Designer.cs index f62f73c6..2b250cbf 100644 --- a/Source/Core/GZBuilder/Controls/TagSelector.Designer.cs +++ b/Source/Core/GZBuilder/Controls/TagSelector.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.cbTagPicker = new System.Windows.Forms.ComboBox(); diff --git a/Source/Core/GZBuilder/Controls/TagSelector.cs b/Source/Core/GZBuilder/Controls/TagSelector.cs index 1d7df831..78de3fdc 100644 --- a/Source/Core/GZBuilder/Controls/TagSelector.cs +++ b/Source/Core/GZBuilder/Controls/TagSelector.cs @@ -1,10 +1,14 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; using System.Windows.Forms; using CodeImp.DoomBuilder.Map; using System.Globalization; using CodeImp.DoomBuilder.Types; +#endregion + namespace CodeImp.DoomBuilder.GZBuilder.Controls { internal struct TagInfo @@ -12,52 +16,71 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls public readonly string Label; public readonly int Tag; - public TagInfo(int tag, string label) { + public TagInfo(int tag, string label) + { Label = (string.IsNullOrEmpty(label) ? tag.ToString() : tag + " (" + label + ")"); Tag = tag; } - public override string ToString() { + public override string ToString() + { return Label; } } public partial class TagSelector : UserControl { + #region ================== Variables + private List tags; private List infos; private bool valid; private int tag; private UniversalType elementType; private int rangemode; //0 - none, 1 - positive (>=), -1 - negative (<=) - private int offsetmode = 0; //0 - none, 1 - positive (++), -1 - negative (--) - - public TagSelector() { + private int offsetmode; //0 - none, 1 - positive (++), -1 - negative (--) + + #endregion + + #region ================== Constructor + + public TagSelector() + { InitializeComponent(); } - public void Setup(UniversalType elementType) { + #endregion + + #region ================== Methods + + public void Setup(UniversalType elementType) + { tags = new List(); infos = new List(); this.elementType = elementType; //collect used tags from sectors... - foreach(Sector s in General.Map.Map.Sectors) { + foreach(Sector s in General.Map.Map.Sectors) + { if(s.Tag == 0 || tags.Contains(s.Tag)) continue; tags.Add(s.Tag); } //...and linedefs... - if(General.Map.FormatInterface.HasLinedefTag) { - foreach(Linedef l in General.Map.Map.Linedefs) { + if(General.Map.FormatInterface.HasLinedefTag) + { + foreach(Linedef l in General.Map.Map.Linedefs) + { if(l.Tag == 0 || tags.Contains(l.Tag)) continue; tags.Add(l.Tag); } } //...and things... - if(General.Map.FormatInterface.HasThingTag) { - foreach(Thing t in General.Map.Map.Things) { + if(General.Map.FormatInterface.HasThingTag) + { + foreach(Thing t in General.Map.Map.Things) + { if(t.Tag == 0 || tags.Contains(t.Tag)) continue; tags.Add(t.Tag); } @@ -67,23 +90,26 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls tags.Sort(); //create tag infos - foreach(int tag in tags){ + foreach(int tag in tags) + { if(General.Map.Options.TagLabels.ContainsKey(tag)) //tag labels infos.Add(new TagInfo(tag, General.Map.Options.TagLabels[tag])); else infos.Add(new TagInfo(tag, string.Empty)); } - foreach(TagInfo info in infos) - cbTagPicker.Items.Add(info); - + foreach(TagInfo info in infos) cbTagPicker.Items.Add(info); cbTagPicker.DropDownWidth = DoomBuilder.Geometry.Tools.GetDropDownWidth(cbTagPicker); } - public void SetTag(int newTag) { - if(tags.Contains(newTag)) { + public void SetTag(int newTag) + { + if(tags.Contains(newTag)) + { cbTagPicker.SelectedIndex = tags.IndexOf(newTag); - } else { + } + else + { cbTagPicker.SelectedIndex = -1; cbTagPicker.Text = newTag.ToString(); } @@ -91,7 +117,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls valid = true; } - public void ClearTag() { + public void ClearTag() + { cbTagPicker.SelectedIndex = -1; cbTagPicker.Text = string.Empty; rangemode = 0; @@ -99,22 +126,26 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls valid = false; } - public int GetTag(int original) { + public int GetTag(int original) + { return (valid ? tag : original); } - public int GetSmartTag(int original, int offset) { + public int GetSmartTag(int original, int offset) + { if (!valid) return original; if (rangemode != 0) return tag + offset * rangemode; if (offsetmode != 0) return original + tag * offsetmode; return tag; } - public void ValidateTag() { + public void ValidateTag() + { rangemode = 0; offsetmode = 0; - if(cbTagPicker.SelectedIndex != -1) { + if(cbTagPicker.SelectedIndex != -1) + { tag = infos[cbTagPicker.SelectedIndex].Tag; valid = true; return; @@ -122,32 +153,44 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls //check text string text = cbTagPicker.Text.Trim().ToLowerInvariant(); - if(string.IsNullOrEmpty(text)) { + if(string.IsNullOrEmpty(text)) + { valid = false; return; } //incremental? - if(text.Length > 2){ - if(text.StartsWith(">=")) { //range up + if(text.Length > 2) + { + if(text.StartsWith(">=")) //range up + { rangemode = 1; text = text.Substring(2, text.Length - 2); - } else if (text.StartsWith("<=")) { //range down + } + else if(text.StartsWith("<=")) //range down + { rangemode = -1; text = text.Substring(2, text.Length - 2); - } else if(text.StartsWith("++")) { //relative up + } + else if(text.StartsWith("++")) //relative up + { offsetmode = 1; text = text.Substring(2, text.Length - 2); - } else if(text.StartsWith("--")) { //relative down + } + else if(text.StartsWith("--")) //relative down + { offsetmode = -1; text = text.Substring(2, text.Length - 2); } } - if(!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out tag)) { + if(!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out tag)) + { //maybe it's user-pasted label? - foreach(TagInfo info in infos) { - if(info.Label.ToLowerInvariant().Contains(text)) { + foreach(TagInfo info in infos) + { + if(info.Label.ToLowerInvariant().Contains(text)) + { tag = info.Tag; valid = true; return; @@ -166,7 +209,12 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls valid = true; } - private void newTag_Click(object sender, EventArgs e) { + #endregion + + #region ================== Events + + private void newTag_Click(object sender, EventArgs e) + { //todo: check tag labels? tag = General.Map.Map.GetNewTag(); cbTagPicker.SelectedIndex = -1; @@ -174,18 +222,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.Controls valid = true; } - private void unusedTag_Click(object sender, EventArgs e) { + private void unusedTag_Click(object sender, EventArgs e) + { tag = General.Map.Map.GetNewTag(elementType); cbTagPicker.SelectedIndex = -1; cbTagPicker.Text = tag.ToString(); valid = true; } - private void clear_Click(object sender, EventArgs e) { + private void clear_Click(object sender, EventArgs e) + { tag = 0; cbTagPicker.SelectedIndex = -1; cbTagPicker.Text = tag.ToString(); valid = true; } + + #endregion } } diff --git a/Source/Core/GZBuilder/Data/BoundingBox.cs b/Source/Core/GZBuilder/Data/BoundingBox.cs index 21aaad14..b9629393 100644 --- a/Source/Core/GZBuilder/Data/BoundingBox.cs +++ b/Source/Core/GZBuilder/Data/BoundingBox.cs @@ -13,7 +13,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data public short MaxZ; //we need some reference here - public BoundingBoxSizes(WorldVertex v) { + public BoundingBoxSizes(WorldVertex v) + { MinX = MaxX = (short)v.x; MinY = MaxY = (short)v.y; MinZ = MaxZ = (short)v.z; @@ -23,7 +24,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data public static class BoundingBoxTools { //this creates array of vectors resembling bounding box - public static Vector3[] CalculateBoundingBox(BoundingBoxSizes bbs) { + public static Vector3[] CalculateBoundingBox(BoundingBoxSizes bbs) + { //center Vector3 v0 = new Vector3(bbs.MinX + (bbs.MaxX - bbs.MinX) / 2, bbs.MinY + (bbs.MaxY - bbs.MinY) / 2, bbs.MinZ + (bbs.MaxZ - bbs.MinZ) / 2); @@ -40,7 +42,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data return new[] { v0, v1, v2, v3, v4, v5, v6, v7, v8 }; } - public static Vector3[] CalculateBoundingPlane(BoundingBoxSizes bbs) { + public static Vector3[] CalculateBoundingPlane(BoundingBoxSizes bbs) + { //mxd. looks like I need only these 2 points, so... //center Vector3 v0 = new Vector3(bbs.MinX + (bbs.MaxX - bbs.MinX) / 2, bbs.MinY + (bbs.MaxY - bbs.MinY) / 2, bbs.MinZ + (bbs.MaxZ - bbs.MinZ) / 2); @@ -48,21 +51,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data return new[] { v0, v1 }; } - public static void UpdateBoundingBoxSizes(ref BoundingBoxSizes bbs, WorldVertex v) { - if (v.x < bbs.MinX) - bbs.MinX = (short)v.x; - else if (v.x > bbs.MaxX) - bbs.MaxX = (short)v.x; + public static void UpdateBoundingBoxSizes(ref BoundingBoxSizes bbs, WorldVertex v) + { + if (v.x < bbs.MinX) bbs.MinX = (short)v.x; + else if (v.x > bbs.MaxX) bbs.MaxX = (short)v.x; - if (v.z < bbs.MinZ) - bbs.MinZ = (short)v.z; - else if (v.z > bbs.MaxZ) - bbs.MaxZ = (short)v.z; + if (v.z < bbs.MinZ) bbs.MinZ = (short)v.z; + else if (v.z > bbs.MaxZ) bbs.MaxZ = (short)v.z; - if (v.y < bbs.MinY) - bbs.MinY = (short)v.y; - else if (v.y > bbs.MaxY) - bbs.MaxY = (short)v.y; + if (v.y < bbs.MinY) bbs.MinY = (short)v.y; + else if (v.y > bbs.MaxY) bbs.MaxY = (short)v.y; } } } diff --git a/Source/Core/GZBuilder/Data/DynamicLight.cs b/Source/Core/GZBuilder/Data/DynamicLight.cs index 0951ff33..c8b7878c 100644 --- a/Source/Core/GZBuilder/Data/DynamicLight.cs +++ b/Source/Core/GZBuilder/Data/DynamicLight.cs @@ -2,7 +2,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { - public sealed class DynamicLightData { + public sealed class DynamicLightData + { public DynamicLightType Type; //holds DynamicLightType public Color3 Color; public int PrimaryRadius; @@ -12,7 +13,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data public bool Subtractive; public bool DontLightSelf; - public DynamicLightData() { + public DynamicLightData() + { Color = new Color3(); Offset = new Vector3(); } diff --git a/Source/Core/GZBuilder/Data/EngineInfo.cs b/Source/Core/GZBuilder/Data/EngineInfo.cs index a76ea819..327e378f 100644 --- a/Source/Core/GZBuilder/Data/EngineInfo.cs +++ b/Source/Core/GZBuilder/Data/EngineInfo.cs @@ -1,8 +1,10 @@ using System; using System.IO; -namespace CodeImp.DoomBuilder.GZBuilder.Data { - public class EngineInfo { +namespace CodeImp.DoomBuilder.GZBuilder.Data +{ + public class EngineInfo + { public const string DEFAULT_ENGINE_NAME = "Engine with no name"; public string TestProgramName; @@ -12,11 +14,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { public int TestSkill; public bool TestShortPaths; - public EngineInfo() { + public EngineInfo() + { TestProgramName = DEFAULT_ENGINE_NAME; } - public EngineInfo(EngineInfo other) { + public EngineInfo(EngineInfo other) + { TestProgramName = other.TestProgramName; TestProgram = other.TestProgram; TestParameters = other.TestParameters; @@ -25,8 +29,10 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { TestShortPaths = other.TestShortPaths; } - public void CheckProgramName(bool forced) { - if ((forced || TestProgramName == DEFAULT_ENGINE_NAME) && !String.IsNullOrEmpty(TestProgram)) { + public void CheckProgramName(bool forced) + { + if ((forced || TestProgramName == DEFAULT_ENGINE_NAME) && !String.IsNullOrEmpty(TestProgram)) + { //get engine name from folder name TestProgramName = Path.GetFileNameWithoutExtension(TestProgram); } diff --git a/Source/Core/GZBuilder/Data/LinedefColorPreset.cs b/Source/Core/GZBuilder/Data/LinedefColorPreset.cs index faaba209..84ba0b03 100644 --- a/Source/Core/GZBuilder/Data/LinedefColorPreset.cs +++ b/Source/Core/GZBuilder/Data/LinedefColorPreset.cs @@ -22,14 +22,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data private const string NOT_VALID = "invalid"; private const string DUPLICATE = "duplicate"; - public LinedefColorPreset(string name, PixelColor lineColor) { + public LinedefColorPreset(string name, PixelColor lineColor) + { Name = name; Color = lineColor; Flags = new List(); RestrictedFlags = new List(); } - public LinedefColorPreset(string name, PixelColor lineColor, int action, int activation, List flags, List restrictedFlags) { + public LinedefColorPreset(string name, PixelColor lineColor, int action, int activation, List flags, List restrictedFlags) + { Name = name; Color = lineColor; Action = action; @@ -38,7 +40,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data RestrictedFlags = restrictedFlags; } - public LinedefColorPreset(LinedefColorPreset copyFrom) { + public LinedefColorPreset(LinedefColorPreset copyFrom) + { Name = copyFrom.Name; Color = copyFrom.Color; Action = copyFrom.Action; @@ -51,60 +54,62 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data RestrictedFlags.AddRange(copyFrom.RestrictedFlags); } - public bool Matches(Linedef l) { + public bool Matches(Linedef l) + { //check action; -1 means Any Action - if(Action != 0) { + if(Action != 0) + { if((Action == -1 && l.Action == 0) || (Action != -1 && l.Action != Action)) return false; } //check activation; -1 means Any Activation - if(Activation != 0) { + if(Activation != 0) + { if(!General.Map.UDMF && (l.Activate != Activation || (Activation == -1 && l.Activate == 0))) return false; } //check flags - if(Flags.Count > 0) { - foreach(string s in Flags) { - if(!l.IsFlagSet(s)) - return false; + if(Flags.Count > 0) + { + foreach(string s in Flags) + { + if(!l.IsFlagSet(s)) return false; } } //check flags, which should be disabled - if(RestrictedFlags.Count > 0) { - foreach(string s in RestrictedFlags) { - if(l.IsFlagSet(s)) - return false; + if(RestrictedFlags.Count > 0) + { + foreach(string s in RestrictedFlags) + { + if(l.IsFlagSet(s)) return false; } } return true; } - public void SetValid() { + public void SetValid() + { valid = true; errorDescription = ""; WarningDescription = ""; } - public void SetInvalid(string reason) { + public void SetInvalid(string reason) + { valid = false; errorDescription = reason; } - public override string ToString() { + public override string ToString() + { List rest = new List(); - - if(!valid) - rest.Add(NOT_VALID); - - if(!string.IsNullOrEmpty(WarningDescription)) - rest.Add(DUPLICATE); - - if(rest.Count > 0) - return Name + " (" + string.Join(", ", rest.ToArray()) + ")"; + if(!valid) rest.Add(NOT_VALID); + if(!string.IsNullOrEmpty(WarningDescription)) rest.Add(DUPLICATE); + if(rest.Count > 0) return Name + " (" + string.Join(", ", rest.ToArray()) + ")"; return Name; } } diff --git a/Source/Core/GZBuilder/Data/LinksCollector.cs b/Source/Core/GZBuilder/Data/LinksCollector.cs index e6925d93..7cfdd175 100644 --- a/Source/Core/GZBuilder/Data/LinksCollector.cs +++ b/Source/Core/GZBuilder/Data/LinksCollector.cs @@ -5,10 +5,12 @@ using CodeImp.DoomBuilder.GZBuilder.Geometry; using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.Config; -namespace CodeImp.DoomBuilder.GZBuilder.Data { - - public static class LinksCollector { - private struct ThingsCheckResult { +namespace CodeImp.DoomBuilder.GZBuilder.Data +{ + public static class LinksCollector + { + private struct ThingsCheckResult + { public bool ProcessPathNodes; public bool ProcessInterpolationPoints; public bool ProcessThingsWithGoal; @@ -16,27 +18,31 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { public bool ProcessActorMovers; } - public static List GetThingLinks(ICollection visualThings) { + public static List GetThingLinks(ICollection visualThings) + { List things = new List(); foreach (VisualThing vt in visualThings) things.Add(vt.Thing); - ThingsCheckResult result = checkThings(things); + ThingsCheckResult result = CheckThings(things); if (result.ProcessPathNodes || result.ProcessInterpolationPoints || result.ProcessThingsWithGoal || result.ProcessCameras) - return getThingLinks(result, true); + return GetThingLinks(result, true); return new List(); } - public static List GetThingLinks(ICollection things) { - ThingsCheckResult result = checkThings(things); + public static List GetThingLinks(ICollection things) + { + ThingsCheckResult result = CheckThings(things); if (result.ProcessPathNodes || result.ProcessInterpolationPoints || result.ProcessThingsWithGoal || result.ProcessCameras) - return getThingLinks(result, false); + return GetThingLinks(result, false); return new List(); } - private static ThingsCheckResult checkThings(ICollection things) { + private static ThingsCheckResult CheckThings(ICollection things) + { ThingsCheckResult result = new ThingsCheckResult(); - foreach (Thing t in things) { + foreach (Thing t in things) + { if(t.Type == 9024) //zdoom path node result.ProcessPathNodes = true; else if(t.Type == 9070) //zdoom camera interpolation point @@ -58,7 +64,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { return result; } - private static List getThingLinks(ThingsCheckResult result, bool correctHeight) { + private static List GetThingLinks(ThingsCheckResult result, bool correctHeight) + { List lines = new List(); Dictionary> pathNodes = new Dictionary>(); Dictionary> interpolationPoints = new Dictionary>(); @@ -68,37 +75,36 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { Dictionary> actorMoverTargets = new Dictionary>(); //collect relevant things - foreach (Thing t in General.Map.Map.Things) { - if(result.ProcessPathNodes && t.Type == 9024) { + foreach (Thing t in General.Map.Map.Things) + { + if(result.ProcessPathNodes && t.Type == 9024) + { if(!pathNodes.ContainsKey(t.Tag)) pathNodes[t.Tag] = new List(); pathNodes[t.Tag].Add(t); } - if(result.ProcessInterpolationPoints && t.Type == 9070) { + if(result.ProcessInterpolationPoints && t.Type == 9070) + { if(!interpolationPoints.ContainsKey(t.Tag)) interpolationPoints[t.Tag] = new List(); interpolationPoints[t.Tag].Add(t); } - if (result.ProcessThingsWithGoal && t.Action == 229 && t.Args[1] != 0) { + if (result.ProcessThingsWithGoal && t.Action == 229 && t.Args[1] != 0) thingsWithGoal.Add(t); - } - if (result.ProcessCameras && t.Type == 9072 && (t.Args[0] != 0 || t.Args[1] != 0)) { + if (result.ProcessCameras && t.Type == 9072 && (t.Args[0] != 0 || t.Args[1] != 0)) cameras.Add(t); - } - if(result.ProcessActorMovers && t.Type == 9074 && (t.Args[0] != 0 || t.Args[1] != 0) && t.Args[3] != 0) { + if(result.ProcessActorMovers && t.Type == 9074 && (t.Args[0] != 0 || t.Args[1] != 0) && t.Args[3] != 0) actorMovers.Add(t); - } } - if(actorMovers.Count > 0) { + if(actorMovers.Count > 0) + { List targetedTags = new List(); - - foreach(Thing t in actorMovers) { - targetedTags.Add(t.Args[3]); - } - - foreach(Thing t in General.Map.Map.Things) { - if(targetedTags.Contains(t.Tag)) { + foreach(Thing t in actorMovers) targetedTags.Add(t.Args[3]); + foreach(Thing t in General.Map.Map.Things) + { + if(targetedTags.Contains(t.Tag)) + { if(!actorMoverTargets.ContainsKey(t.Tag)) actorMoverTargets[t.Tag] = new List(); actorMoverTargets[t.Tag].Add(t); @@ -109,18 +115,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { Vector3D start, end; //process path nodes - if (result.ProcessPathNodes) { - foreach (KeyValuePair> group in pathNodes) { - foreach(Thing t in group.Value) { + if (result.ProcessPathNodes) + { + foreach (KeyValuePair> group in pathNodes) + { + foreach(Thing t in group.Value) + { if(t.Args[0] == 0) continue; //no goal - if(pathNodes.ContainsKey(t.Args[0])) { + if(pathNodes.ContainsKey(t.Args[0])) + { start = t.Position; - if(correctHeight) start.z += getCorrectHeight(t); + if(correctHeight) start.z += GetCorrectHeight(t); - foreach(Thing tt in pathNodes[t.Args[0]]) { + foreach(Thing tt in pathNodes[t.Args[0]]) + { end = tt.Position; - if(correctHeight) end.z += getCorrectHeight(tt); + if(correctHeight) end.z += GetCorrectHeight(tt); lines.Add(new Line3D(start, end)); } } @@ -129,16 +140,21 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { } //process things with Thing_SetGoal - if (result.ProcessThingsWithGoal) { - foreach (Thing t in thingsWithGoal) { - if (pathNodes.ContainsKey(t.Args[1])) { - if (t.Args[0] == 0 || t.Args[0] == t.Tag) { + if (result.ProcessThingsWithGoal) + { + foreach (Thing t in thingsWithGoal) + { + if (pathNodes.ContainsKey(t.Args[1])) + { + if (t.Args[0] == 0 || t.Args[0] == t.Tag) + { start = t.Position; - if (correctHeight) start.z += getCorrectHeight(t); + if (correctHeight) start.z += GetCorrectHeight(t); - foreach(Thing tt in pathNodes[t.Args[1]]) { + foreach(Thing tt in pathNodes[t.Args[1]]) + { end = tt.Position; - if(correctHeight) end.z += getCorrectHeight(tt); + if(correctHeight) end.z += GetCorrectHeight(tt); lines.Add(new Line3D(start, end, Line3DType.ACTIVATOR)); } @@ -148,19 +164,24 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { } //process interpolation points - if (result.ProcessInterpolationPoints) { - foreach (KeyValuePair> group in interpolationPoints) { - foreach(Thing t in group.Value) { + if (result.ProcessInterpolationPoints) + { + foreach (KeyValuePair> group in interpolationPoints) + { + foreach(Thing t in group.Value) + { int targetTag = t.Args[3] + (t.Args[4] << 8); if(targetTag == 0) continue; //no goal - if(interpolationPoints.ContainsKey(targetTag)) { + if(interpolationPoints.ContainsKey(targetTag)) + { start = t.Position; - if(correctHeight) start.z += getCorrectHeight(t); + if(correctHeight) start.z += GetCorrectHeight(t); - foreach(Thing tt in interpolationPoints[targetTag]) { + foreach(Thing tt in interpolationPoints[targetTag]) + { end = tt.Position; - if(correctHeight) end.z += getCorrectHeight(tt); + if(correctHeight) end.z += GetCorrectHeight(tt); lines.Add(new Line3D(start, end)); } } @@ -169,18 +190,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { } //process cameras - if (result.ProcessCameras) { - foreach (Thing t in cameras) { + if (result.ProcessCameras) + { + foreach (Thing t in cameras) + { int targetTag = t.Args[0] + (t.Args[1] << 8); if (targetTag == 0) continue; //no goal - if(interpolationPoints.ContainsKey(targetTag)) { + if(interpolationPoints.ContainsKey(targetTag)) + { start = t.Position; - if(correctHeight) start.z += getCorrectHeight(t); + if(correctHeight) start.z += GetCorrectHeight(t); - foreach(Thing tt in interpolationPoints[targetTag]) { + foreach(Thing tt in interpolationPoints[targetTag]) + { end = tt.Position; - if(correctHeight) end.z += getCorrectHeight(tt); + if(correctHeight) end.z += GetCorrectHeight(tt); lines.Add(new Line3D(start, end, Line3DType.ACTIVATOR)); } } @@ -188,31 +213,37 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { } //process actor movers - if(result.ProcessActorMovers) { - foreach(Thing t in actorMovers) { + if(result.ProcessActorMovers) + { + foreach(Thing t in actorMovers) + { int targetTag = t.Args[0] + (t.Args[1] << 8); if(targetTag == 0) continue; //no goal //add interpolation point target - if(interpolationPoints.ContainsKey(targetTag)) { + if(interpolationPoints.ContainsKey(targetTag)) + { start = t.Position; - if(correctHeight) start.z += getCorrectHeight(t); + if(correctHeight) start.z += GetCorrectHeight(t); - foreach(Thing tt in interpolationPoints[targetTag]) { + foreach(Thing tt in interpolationPoints[targetTag]) + { end = tt.Position; - if(correctHeight) end.z += getCorrectHeight(tt); + if(correctHeight) end.z += GetCorrectHeight(tt); lines.Add(new Line3D(start, end, Line3DType.ACTIVATOR)); } } //add thing-to-move target - if(actorMoverTargets.ContainsKey(t.Args[3])) { + if(actorMoverTargets.ContainsKey(t.Args[3])) + { start = t.Position; - if(correctHeight) start.z += getCorrectHeight(t); + if(correctHeight) start.z += GetCorrectHeight(t); - foreach(Thing tt in actorMoverTargets[t.Args[3]]) { + foreach(Thing tt in actorMoverTargets[t.Args[3]]) + { end = tt.Position; - if(correctHeight) end.z += getCorrectHeight(tt); + if(correctHeight) end.z += GetCorrectHeight(tt); lines.Add(new Line3D(start, end, Line3DType.ACTIVATOR)); } } @@ -222,7 +253,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { return lines; } - private static float getCorrectHeight(Thing thing) { + private static float GetCorrectHeight(Thing thing) + { ThingTypeInfo tti = General.Map.Data.GetThingInfo(thing.Type); float height = tti.Height / 2f; if (thing.Sector != null) height += thing.Sector.FloorHeight; diff --git a/Source/Core/GZBuilder/Data/MapInfo.cs b/Source/Core/GZBuilder/Data/MapInfo.cs index f01c9b1c..f3aa1378 100644 --- a/Source/Core/GZBuilder/Data/MapInfo.cs +++ b/Source/Core/GZBuilder/Data/MapInfo.cs @@ -1,7 +1,9 @@ using SlimDX; -namespace CodeImp.DoomBuilder.GZBuilder.Data { - public sealed class MapInfo { +namespace CodeImp.DoomBuilder.GZBuilder.Data +{ + public sealed class MapInfo + { public string Sky1; public float Sky1ScrollSpeed; public string Sky2; @@ -19,7 +21,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { public int VertWallShade; public int HorizWallShade; - public MapInfo() { + public MapInfo() + { VertWallShade = 16; HorizWallShade = -16; } diff --git a/Source/Core/GZBuilder/Data/ModelData.cs b/Source/Core/GZBuilder/Data/ModelData.cs index 4d786165..5e6e29c3 100644 --- a/Source/Core/GZBuilder/Data/ModelData.cs +++ b/Source/Core/GZBuilder/Data/ModelData.cs @@ -26,20 +26,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data internal bool InheritActorPitch; internal bool InheritActorRoll; - internal ModelData() { + internal ModelData() + { ModelNames = new List(); TextureNames = new List(); Scale = new Vector3(1, 1, 1); } - internal void Dispose() { - if (Model != null) { - foreach (Mesh mesh in Model.Meshes) - mesh.Dispose(); - - foreach (Texture t in Model.Textures) - t.Dispose(); - + internal void Dispose() + { + if (Model != null) + { + foreach (Mesh mesh in Model.Meshes) mesh.Dispose(); + foreach (Texture t in Model.Textures) t.Dispose(); loadstate = ModelLoadState.None; } } diff --git a/Source/Core/GZBuilder/Data/ScriptItem.cs b/Source/Core/GZBuilder/Data/ScriptItem.cs index 06fe363d..2e7a4f9d 100644 --- a/Source/Core/GZBuilder/Data/ScriptItem.cs +++ b/Source/Core/GZBuilder/Data/ScriptItem.cs @@ -1,7 +1,9 @@ using System; -namespace CodeImp.DoomBuilder.GZBuilder.Data { - internal sealed class ScriptItem : Object { +namespace CodeImp.DoomBuilder.GZBuilder.Data +{ + internal sealed class ScriptItem : Object + { private string name; private int index; private int selectionStart; @@ -12,42 +14,47 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { internal int SelectionStart { get { return selectionStart; } } internal int SelectionEnd { get { return selectionEnd; } } - internal ScriptItem(int index, string name, int selectionStart, int selectionEnd) { + internal ScriptItem(int index, string name, int selectionStart, int selectionEnd) + { this.name = name; this.index = index; this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; } - internal ScriptItem(int index, string name) { + internal ScriptItem(int index, string name) + { this.name = name; this.index = index; } - internal static int SortByIndex(ScriptItem i1, ScriptItem i2) { + internal static int SortByIndex(ScriptItem i1, ScriptItem i2) + { if (i1.Index > i2.Index) return 1; if (i1.Index == i2.Index) return 0; return -1; } - internal static int SortByName(ScriptItem i1, ScriptItem i2) { + internal static int SortByName(ScriptItem i1, ScriptItem i2) + { if (i1.Name == i2.Name) return 0; - if (i1.Name.ToUpper()[0] > i2.Name.ToUpper()[0]) return 1; - if (i1.Name.ToUpper()[0] == i2.Name.ToUpper()[0]) { + if (i1.Name.ToUpper()[0] == i2.Name.ToUpper()[0]) + { int len = Math.Min(i1.Name.Length, i2.Name.Length); - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { if (i1.Name.ToUpper()[i] > i2.Name.ToUpper()[i]) return 1; if (i1.Name.ToUpper()[i] < i2.Name.ToUpper()[i]) return -1; } - if (i1.Name.Length > i2.Name.Length) return 1; return -1; } return -1; } - public override string ToString() { + public override string ToString() + { return name; } } diff --git a/Source/Core/GZBuilder/Data/SharpCompressHelper.cs b/Source/Core/GZBuilder/Data/SharpCompressHelper.cs index 9b0a98b2..e881a800 100644 --- a/Source/Core/GZBuilder/Data/SharpCompressHelper.cs +++ b/Source/Core/GZBuilder/Data/SharpCompressHelper.cs @@ -6,7 +6,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { internal static class SharpCompressHelper { - internal static MemoryStream CompressStream(Stream stream) { + internal static MemoryStream CompressStream(Stream stream) + { byte[] arr = new byte[stream.Length]; stream.Read(arr, 0, (int)stream.Length); @@ -19,7 +20,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data return ms; } - internal static MemoryStream DecompressStream(Stream stream) { + internal static MemoryStream DecompressStream(Stream stream) + { BZip2Stream bzip = new BZip2Stream(stream, CompressionMode.Decompress, false); byte[] buffer = new byte[16 * 1024]; diff --git a/Source/Core/GZBuilder/Data/ThingCopyData.cs b/Source/Core/GZBuilder/Data/ThingCopyData.cs index 9eb75423..cfb50414 100644 --- a/Source/Core/GZBuilder/Data/ThingCopyData.cs +++ b/Source/Core/GZBuilder/Data/ThingCopyData.cs @@ -2,8 +2,10 @@ using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Geometry; -namespace CodeImp.DoomBuilder.GZBuilder.Data { - public sealed class ThingCopyData { +namespace CodeImp.DoomBuilder.GZBuilder.Data +{ + public sealed class ThingCopyData + { // Properties private readonly int type; private readonly Vector3D pos; @@ -16,7 +18,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { public Vector3D Position { get { return pos; } } - public ThingCopyData(Thing t) { + public ThingCopyData(Thing t) + { type = t.Type; angledoom = t.AngleDoom; pos = t.Position; @@ -27,7 +30,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { fields = new UniFields(t, t.Fields); } - public void ApplyTo(Thing t) { + public void ApplyTo(Thing t) + { t.Type = type; t.Rotate(angledoom); t.Move(pos); @@ -41,7 +45,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Data { for(int i = 0; i < args.Length; i++) t.Args[i] = args[i]; - foreach (KeyValuePair group in fields) { + foreach (KeyValuePair group in fields) + { if (t.Fields.ContainsKey(group.Key)) t.Fields[group.Key] = group.Value; else diff --git a/Source/Core/GZBuilder/GZDoom/AcsParserSE.cs b/Source/Core/GZBuilder/GZDoom/AcsParserSE.cs index 8f3efed4..6b0f2700 100644 --- a/Source/Core/GZBuilder/GZDoom/AcsParserSE.cs +++ b/Source/Core/GZBuilder/GZDoom/AcsParserSE.cs @@ -23,7 +23,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom internal List NumberedScripts { get { return numberedScripts; } } internal List Functions { get { return functions; } } - internal AcsParserSE() { + internal AcsParserSE() + { namedScripts = new List(); numberedScripts = new List(); functions = new List(); @@ -31,15 +32,18 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom includes = new List(); } - internal List Includes { + internal List Includes + { get { return includes; } } - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { return Parse(stream, sourcefilename, false, false); } - public bool Parse(Stream stream, string sourcefilename, bool processIncludes, bool isinclude) { + public bool Parse(Stream stream, string sourcefilename, bool processIncludes, bool isinclude) + { base.Parse(stream, sourcefilename); //already parsed this? @@ -53,19 +57,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom BinaryReader localreader = datareader; // Continue until at the end of the stream - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = token.ToLowerInvariant(); - if (token == "script") { + if (token == "script") + { int startPos = (int)stream.Position - 7; SkipWhitespace(true); token = ReadToken(); //is it named script? - if (token.IndexOf('"') != -1) { + if (token.IndexOf('"') != -1) + { //check if we have something like '"mycoolscript"(void)' as a token if(token.LastIndexOf('"') != token.Length - 1) token = token.Substring(0, token.LastIndexOf('"')); @@ -73,16 +81,20 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom token = StripTokenQuotes(token); ScriptItem i = new ScriptItem(0, token, startPos, (int)stream.Position-1); namedScripts.Add(i); - } else { //should be numbered script + } + else //should be numbered script + { //check if we have something like "999(void)" as a token if (token.Contains("(")) token = token.Substring(0, token.IndexOf("(")); int n; - if (int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) { + if (int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) + { int endPos = (int)stream.Position - 1; //now find opening brace - do { + do + { SkipWhitespace(true); token = ReadToken(); } while (token != "{"); @@ -90,9 +102,11 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom token = ReadLine(); string name = ""; - if (token.Length > 0) { + if (token.Length > 0) + { int commentStart = token.IndexOf("//"); - if (commentStart != -1) { //found comment + if (commentStart != -1) //found comment + { commentStart += 2; name = token.Substring(commentStart, token.Length - commentStart).Trim(); } @@ -103,8 +117,9 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom numberedScripts.Add(i); } } - - } else if(token == "function") { + } + else if(token == "function") + { int startPos = (int)stream.Position - 9; SkipWhitespace(true); string funcname = ReadToken(); //read return type @@ -112,16 +127,21 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom funcname += " " + ReadToken(); //read function name //look for opening brace - if (!funcname.Contains("(")) { + if (!funcname.Contains("(")) + { SkipWhitespace(true); funcname += " " + ReadToken(); - } else { + } + else + { funcname = funcname.Replace("(", " ("); } //look for closing brace - if(!funcname.Contains(")")) { - do { + if(!funcname.Contains(")")) + { + do + { SkipWhitespace(true); token = ReadToken(); funcname += " " + token; @@ -130,12 +150,14 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom ScriptItem i = new ScriptItem(0, funcname, startPos, (int)stream.Position - 1); functions.Add(i); - - } else if (processIncludes && (token == "#include" || token == "#import")) { + } + else if (processIncludes && (token == "#include" || token == "#import")) + { SkipWhitespace(true); string includeLump = StripTokenQuotes(ReadToken()).ToLowerInvariant(); - if (!string.IsNullOrEmpty(includeLump)) { + if (!string.IsNullOrEmpty(includeLump)) + { string includeName = Path.GetFileName(includeLump); if (includeName == "zcommon.acs" || includeName == "common.acs" || includes.Contains(includeName)) @@ -148,7 +170,9 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom datastream = localstream; datareader = localreader; sourcename = localsourcename; - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": got #include directive without include path!"); } } diff --git a/Source/Core/GZBuilder/GZDoom/DecorateParserSE.cs b/Source/Core/GZBuilder/GZDoom/DecorateParserSE.cs index ff57d7ba..d0e5f9a3 100644 --- a/Source/Core/GZBuilder/GZDoom/DecorateParserSE.cs +++ b/Source/Core/GZBuilder/GZDoom/DecorateParserSE.cs @@ -11,35 +11,39 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom private List actors; public List Actors { get { return actors; } } - public DecorateParserSE() { + public DecorateParserSE() + { actors = new List(); } - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { base.Parse(stream, sourcefilename); // Continue until at the end of the stream - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = token.ToLowerInvariant(); - if (token == "actor") { + if (token == "actor") + { int startPos = (int)stream.Position - 6; SkipWhitespace(true); List definition = new List(); - while ((token = ReadToken()) != "{") { + while ((token = ReadToken()) != "{") + { definition.Add(token); SkipWhitespace(true); } string name = ""; - foreach (string s in definition) - name += s + " "; - + foreach (string s in definition) name += s + " "; actors.Add(new ScriptItem(0, name.TrimEnd(), startPos, (int)stream.Position - 2)); } } diff --git a/Source/Core/GZBuilder/GZDoom/GldefsParser.cs b/Source/Core/GZBuilder/GZDoom/GldefsParser.cs index a50e2007..aa59e3ea 100644 --- a/Source/Core/GZBuilder/GZDoom/GldefsParser.cs +++ b/Source/Core/GZBuilder/GZDoom/GldefsParser.cs @@ -20,7 +20,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { private List parsedLumps; - private struct GldefsLightType { + private struct GldefsLightType + { public const string POINT = "pointlight"; public const string PULSE = "pulselight"; public const string FLICKER = "flickerlight"; @@ -30,16 +31,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { public static Dictionary GLDEFS_TO_GZDOOM_LIGHT_TYPE = new Dictionary(StringComparer.Ordinal) { { POINT, DynamicLightType.NORMAL }, { PULSE, DynamicLightType.PULSE }, { FLICKER, DynamicLightType.FLICKER }, { FLICKER2, DynamicLightType.RANDOM }, { SECTOR, DynamicLightType.SECTOR } }; } - public GldefsParser() { + public GldefsParser() + { parsedLumps = new List(); lightsByName = new Dictionary(StringComparer.Ordinal); //LightName, Light params objects = new Dictionary(StringComparer.Ordinal); //ClassName, LightName } - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { base.Parse(stream, sourcefilename); - if (parsedLumps.IndexOf(sourcefilename) != -1) { + if (parsedLumps.IndexOf(sourcefilename) != -1) + { General.ErrorLogger.Add(ErrorType.Error, "Error: already parsed '" + sourcefilename + "'. Check your #include directives!"); return false; } @@ -51,13 +55,17 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { BinaryReader localreader = datareader; // Continue until at the end of the stream - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = StripTokenQuotes(token.ToLowerInvariant()); //Quotes can be anywhere! ANYWHERE!!! And GZDoom will still parse data correctly //got light structure - if (token == GldefsLightType.POINT || token == GldefsLightType.PULSE || token == GldefsLightType.FLICKER || token == GldefsLightType.FLICKER2 || token == GldefsLightType.SECTOR) { + if (token == GldefsLightType.POINT || token == GldefsLightType.PULSE || token == GldefsLightType.FLICKER + || token == GldefsLightType.FLICKER2 || token == GldefsLightType.SECTOR) + { bool gotErrors = false; string lightType = token; @@ -68,27 +76,32 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); string lightName = StripTokenQuotes(ReadToken()).ToLowerInvariant(); - if (!string.IsNullOrEmpty(lightName)) { + if (!string.IsNullOrEmpty(lightName)) + { //now find opening brace SkipWhitespace(true); token = ReadToken(); - if (token != "{") { + if (token != "{") + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected '{', but got '" + token + "'"); continue; //something wrong with gldefs declaration, continue to next one } //read gldefs light structure - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { token = ReadToken(); - - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = token.ToLowerInvariant(); //color - if (token == "color") { + if (token == "color") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out light.Color.Red)) { + if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out light.Color.Red)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Red Color value, but got '" + token + "'"); gotErrors = true; @@ -98,7 +111,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out light.Color.Green)) { + if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out light.Color.Green)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Green Color value, but got '" + token + "'"); gotErrors = true; @@ -108,19 +122,24 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out light.Color.Blue)) { + if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out light.Color.Blue)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Blue Color value, but got '" + token + "'"); gotErrors = true; break; } //size - } else if (token == "size") { - if (lightType != GldefsLightType.SECTOR) { + } + else if (token == "size") + { + if (lightType != GldefsLightType.SECTOR) + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out light.PrimaryRadius)) { + if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out light.PrimaryRadius)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Size value, but got '" + token + "'"); gotErrors = true; @@ -128,17 +147,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { } light.PrimaryRadius *= 2; - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": '" + token + "' is not valid property for " + lightType); gotErrors = true; break; } //offset - } else if (token == "offset") { + } + else if (token == "offset") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!ReadSignedFloat(token, ref light.Offset.X)) { + if (!ReadSignedFloat(token, ref light.Offset.X)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Offset X value, but got '" + token + "'"); gotErrors = true; @@ -148,7 +172,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!ReadSignedFloat(token, ref light.Offset.Z)) { + if (!ReadSignedFloat(token, ref light.Offset.Z)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Offset Y value, but got '" + token + "'"); gotErrors = true; @@ -158,19 +183,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!ReadSignedFloat(token, ref light.Offset.Y)) { + if (!ReadSignedFloat(token, ref light.Offset.Y)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Offset Z value, but got '" + token + "'"); gotErrors = true; break; } //subtractive - } else if (token == "subtractive") { + } + else if (token == "subtractive") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); int i; - if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) { + if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Subtractive value, but got '" + token + "'"); gotErrors = true; @@ -179,12 +208,15 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { light.Subtractive = i == 1; //dontlightself - } else if (token == "dontlightself") { + } + else if (token == "dontlightself") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); int i; - if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) { + if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Dontlightself value, but got '" + token + "'"); gotErrors = true; @@ -193,61 +225,78 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { light.DontLightSelf = (i == 1); //interval - } else if (token == "interval") { - if (lightType == GldefsLightType.PULSE || lightType == GldefsLightType.FLICKER2) { + } + else if (token == "interval") + { + if (lightType == GldefsLightType.PULSE || lightType == GldefsLightType.FLICKER2) + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); float interval; - if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out interval)) { + if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out interval)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Interval value, but got '" + token + "'"); gotErrors = true; break; } - if(interval == 0) { + if(interval == 0) General.ErrorLogger.Add(ErrorType.Warning, "Warning in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": Interval value should be greater than zero"); - } //I wrote logic for dynamic lights animation first, so here I modify gldefs settings to fit in existing logic - if (lightType == GldefsLightType.PULSE) { + if (lightType == GldefsLightType.PULSE) + { light.Interval = (int)(interval * 35); //measured in tics (35 per second) in PointLightPulse, measured in seconds in gldefs' PulseLight - } else { //FLICKER2. Seems like PointLightFlickerRandom to me + } + else //FLICKER2. Seems like PointLightFlickerRandom to me + { light.Interval = (int)(interval * 350); //0.1 is one second for FlickerLight2 } - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": '"+token+"' is not valid property for " + lightType); gotErrors = true; break; } //secondarysize - } else if (token == "secondarysize") { - if (lightType == GldefsLightType.PULSE || lightType == GldefsLightType.FLICKER || lightType == GldefsLightType.FLICKER2) { + } + else if (token == "secondarysize") + { + if (lightType == GldefsLightType.PULSE || lightType == GldefsLightType.FLICKER || lightType == GldefsLightType.FLICKER2) + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out light.SecondaryRadius)) { + if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out light.SecondaryRadius)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected SecondarySize value, but got '" + token + "'"); gotErrors = true; break; } light.SecondaryRadius *= 2; - - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": '" + token + "' is not valid property for " + lightType); gotErrors = true; break; } //chance - } else if (token == "chance") { - if (lightType == GldefsLightType.FLICKER) { + } + else if (token == "chance") + { + if (lightType == GldefsLightType.FLICKER) + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); float chance; - if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out chance)) { + if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out chance)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Chance value, but got '" + token + "'"); gotErrors = true; @@ -256,26 +305,33 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //transforming from 0.0 .. 1.0 to 0 .. 359 to fit in existing logic light.Interval = (int)(chance * 359.0f); - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": '" + token + "' is not valid property for " + lightType); gotErrors = true; break; } //scale - } else if (token == "scale") { - if (lightType == GldefsLightType.SECTOR) { + } + else if (token == "scale") + { + if (lightType == GldefsLightType.SECTOR) + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); float scale; - if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale)) { + if (!float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out scale)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected Scale value, but got '" + token + "'"); gotErrors = true; break; } - if (scale > 1.0f) { + if (scale > 1.0f) + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": scale must be in 0.0 - 1.0 range, but is " + scale); gotErrors = true; break; @@ -284,46 +340,51 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //sector light doesn't have animation, so we will store it's size in Interval //transforming from 0.0 .. 1.0 to 0 .. 10 to preserve value. light.Interval = (int)(scale * 10.0f); - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": '" + token + "' is not valid property for " + lightType); gotErrors = true; break; } - - //end of structure - } else if (token == "}") { - if (!gotErrors) { + } + //end of structure + else if (token == "}") + { + if (!gotErrors) + { //general checks - if (light.Color.Red == 0.0f && light.Color.Green == 0.0f && light.Color.Blue == 0.0f) { + if (light.Color.Red == 0.0f && light.Color.Green == 0.0f && light.Color.Blue == 0.0f) + { General.ErrorLogger.Add(ErrorType.Warning, "'" + sourcefilename + "', line " + GetCurrentLineNumber() + ": light Color is " + light.Color.Red + "," + light.Color.Green + "," + light.Color.Blue + ". It won't be shown in GZDoom!"); gotErrors = true; } //light-type specific checks - if (light.Type == DynamicLightType.NORMAL) { - if (light.PrimaryRadius == 0) { - General.ErrorLogger.Add(ErrorType.Warning, "'" + sourcefilename + "', line " + GetCurrentLineNumber() + ": light Size is 0. It won't be shown in GZDoom!"); - gotErrors = true; - } + if (light.Type == DynamicLightType.NORMAL && light.PrimaryRadius == 0) + { + General.ErrorLogger.Add(ErrorType.Warning, "'" + sourcefilename + "', line " + GetCurrentLineNumber() + ": light Size is 0. It won't be shown in GZDoom!"); + gotErrors = true; } - if (light.Type == DynamicLightType.FLICKER || light.Type == DynamicLightType.PULSE || light.Type == DynamicLightType.RANDOM) { - if (light.PrimaryRadius == 0 && light.SecondaryRadius == 0) { + if (light.Type == DynamicLightType.FLICKER || light.Type == DynamicLightType.PULSE || light.Type == DynamicLightType.RANDOM) + { + if (light.PrimaryRadius == 0 && light.SecondaryRadius == 0) + { General.ErrorLogger.Add(ErrorType.Warning, "'" + sourcefilename + "', line " + GetCurrentLineNumber() + ": 'Size' and 'SecondarySize' are 0. This light won't be shown in GZDoom!"); gotErrors = true; } } //offset it slightly to avoid shading glitches - if (light.Offset.Z == 0.0f) - light.Offset.Z = 0.1f; + if (light.Offset.Z == 0.0f) light.Offset.Z = 0.1f; - if (!gotErrors) { - if (lightsByName.ContainsKey(lightName)) { + if (!gotErrors) + { + if (lightsByName.ContainsKey(lightName)) lightsByName[lightName] = light; - } else { + else lightsByName.Add(lightName, light); - } } } break; //break out of this parsing loop @@ -331,19 +392,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { } } } - - } else if (token == "object") { + } + else if (token == "object") + { SkipWhitespace(true); //read object class string objectClass = StripTokenQuotes(ReadToken()).ToLowerInvariant(); - if (!string.IsNullOrEmpty(objectClass)) { + if (!string.IsNullOrEmpty(objectClass)) + { //now find opening brace SkipWhitespace(true); token = ReadToken(); - if (token != "{") { + if (token != "{") + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": expected '{', but got '" + token + "'"); continue; } @@ -353,48 +417,59 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { bool foundFrame = false; //read frames structure - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { token = ReadToken(); - - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = StripTokenQuotes(token).ToLowerInvariant(); - - if(!foundLight && !foundFrame && token == "frame") { + if(!foundLight && !foundFrame && token == "frame") + { SkipWhitespace(true); token = ReadToken().ToLowerInvariant(); //should be frame name //use this frame if it's 4 characters long or it's the first frame foundFrame = (token.Length == 4 || (token.Length > 4 && token[4] == 'a')); - } else if(!foundLight && foundFrame && token == "light") { //just use first light and be done with it + } + else if(!foundLight && foundFrame && token == "light") //just use first light and be done with it + { SkipWhitespace(true); token = ReadToken().ToLowerInvariant(); //should be light name - if (!string.IsNullOrEmpty(token)) { - if (lightsByName.ContainsKey(token)) { + if (!string.IsNullOrEmpty(token)) + { + if (lightsByName.ContainsKey(token)) + { if (objects.ContainsKey(objectClass)) objects[objectClass] = token; else objects.Add(objectClass, token); foundLight = true; - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Warning, "Light declaration not found for light '" + token + "' ('" + sourcefilename + "', line " + GetCurrentLineNumber()+")"); } } - } else if (token == "{") { //continue in this loop until object structure ends + } + else if (token == "{") //continue in this loop until object structure ends + { bracesCount++; - } else if (token == "}") { - if (--bracesCount < 1) - break; //This was Cave Johnson. And we are done here. + } + else if (token == "}") + { + if (--bracesCount < 1) break; //This was Cave Johnson. And we are done here. } } } } - - } else if (token == "#include") { + } + else if (token == "#include") + { SkipWhitespace(true); string includeLump = StripTokenQuotes(ReadToken()).ToLowerInvariant(); - - if (!string.IsNullOrEmpty(includeLump)) { + if (!string.IsNullOrEmpty(includeLump)) + { // Callback to parse this file if (OnInclude != null) OnInclude(this, includeLump.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); @@ -403,21 +478,26 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { datastream = localstream; datareader = localreader; sourcename = localsourcename; - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Error in '" + sourcefilename + "' at line " + GetCurrentLineNumber() + ": got #include directive with missing or incorrect path: '" + includeLump + "'"); } - - } else { + } + else + { // Unknown structure! string token2; - do { + do + { if (!SkipWhitespace(true)) break; token2 = ReadToken(); if (token2 == null) break; } while (token2 != "{"); int scopelevel = 1; - do { + do + { if (!SkipWhitespace(true)) break; token2 = ReadToken(); if (token2 == null) break; diff --git a/Source/Core/GZBuilder/GZDoom/MapinfoParser.cs b/Source/Core/GZBuilder/GZDoom/MapinfoParser.cs index b7161e8e..9bc1a32c 100644 --- a/Source/Core/GZBuilder/GZDoom/MapinfoParser.cs +++ b/Source/Core/GZBuilder/GZDoom/MapinfoParser.cs @@ -11,19 +11,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { private MapInfo mapInfo; public MapInfo MapInfo { get { return mapInfo; } } - public bool Parse(Stream stream, string sourcefilename, string mapName) { + public bool Parse(Stream stream, string sourcefilename, string mapName) + { base.Parse(stream, sourcefilename); - mapName = mapName.ToLowerInvariant(); mapInfo = new MapInfo(); - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - if (token != null) { + if (token != null) + { token = token.ToLowerInvariant(); - - if (parseBlock(token, mapName)) - break; + if (ParseBlock(token, mapName)) break; } } @@ -39,36 +39,40 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { } //returns true if parsing is finished - private bool parseBlock(string token, string mapName) { + private bool ParseBlock(string token, string mapName) + { string curBlockName; - - if (token == "map" || token == "defaultmap" || token == "adddefaultmap") { + if (token == "map" || token == "defaultmap" || token == "adddefaultmap") + { curBlockName = token; - - if (token == "map") { //check map name + if (token == "map") //check map name + { //get map name SkipWhitespace(true); token = ReadToken().ToLowerInvariant(); - if (token != mapName) - return false; //not finished, search for next "map", "defaultmap" or "adddefaultmap" block - } else if (token == "defaultmap") { + if (token != mapName) return false; //not finished, search for next "map", "defaultmap" or "adddefaultmap" block + } + else if (token == "defaultmap") + { //reset MapInfo mapInfo = new MapInfo(); } //search for required keys - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { token = ReadToken().ToLowerInvariant(); - //sky1 or sky2 - if (token == "sky1" || token == "sky2") { + if (token == "sky1" || token == "sky2") + { string skyType = token; SkipWhitespace(true); token = StripTokenQuotes(ReadToken()).ToLowerInvariant(); //new format - if (token == "=") { + if (token == "=") + { SkipWhitespace(true); //should be sky texture name @@ -77,7 +81,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { if (gotComma) token = token.Replace(",", ""); string skyTexture = StripTokenQuotes(token).ToLowerInvariant(); - if (!string.IsNullOrEmpty(skyTexture)) { + if (!string.IsNullOrEmpty(skyTexture)) + { if (skyType == "sky1") mapInfo.Sky1 = skyTexture; else @@ -87,16 +92,18 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if (!gotComma && token == ",") { + if (!gotComma && token == ",") + { gotComma = true; SkipWhitespace(true); token = ReadToken(); } - if (gotComma) { + if (gotComma) + { float scrollSpeed = 0; - - if (!ReadSignedFloat(token, ref scrollSpeed)) { + if (!ReadSignedFloat(token, ref scrollSpeed)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Warning, "Unexpected token found in '" + sourcename + "' at line " + GetCurrentLineNumber() + ": expected " + skyType + " scroll speed value, but got '" + token + "'"); datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again @@ -107,17 +114,24 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { mapInfo.Sky1ScrollSpeed = scrollSpeed; else mapInfo.Sky2ScrollSpeed = scrollSpeed; - } else { + } + else + { datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again } - } else { + } + else + { datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again General.ErrorLogger.Add(ErrorType.Error, "Unexpected token found in '" + sourcename + "' at line " + GetCurrentLineNumber() + ": expected " + skyType + " texture name."); } - //old format - } else { + } + //old format + else + { //token should be sky1/2 name - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { if (skyType == "sky1") mapInfo.Sky1 = token; else @@ -128,7 +142,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { token = StripTokenQuotes(ReadToken()); float scrollSpeed = 0; - if (!ReadSignedFloat(token, ref scrollSpeed)) { + if (!ReadSignedFloat(token, ref scrollSpeed)) + { // Not numeric! datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again continue; @@ -139,56 +154,70 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { else mapInfo.Sky2ScrollSpeed = scrollSpeed; - } else { + } + else + { datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again General.ErrorLogger.Add(ErrorType.Error, "Unexpected token found in '" + sourcename + "' at line " + GetCurrentLineNumber() + ": expected " + skyType + " texture name."); } } + } //fade or outsidefog - } else if (token == "fade" || token == "outsidefog") { + else if (token == "fade" || token == "outsidefog") + { string fadeType = token; SkipWhitespace(true); token = StripTokenQuotes(ReadToken()).ToLowerInvariant(); //new format? - if (token == "=") { + if (token == "=") + { SkipWhitespace(true); token = ReadToken(); } //get the color value string colorVal = StripTokenQuotes(token).ToLowerInvariant().Replace(" ", ""); - if(!string.IsNullOrEmpty(colorVal)) { + if(!string.IsNullOrEmpty(colorVal)) + { Color4 color = new Color4(); - //try to get the color... - if(getColor(colorVal, ref color)) { + if(GetColor(colorVal, ref color)) + { if(fadeType == "fade") mapInfo.FadeColor = color; else mapInfo.OutsideFogColor = color; - } else { //...or not + } + else //...or not + { General.ErrorLogger.Add(ErrorType.Error, "Failed to parse " + fadeType + " value from string '" + colorVal + "' in '" + sourcename + "' at line " + GetCurrentLineNumber()); datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again } - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Error, "Unexpected token found in '" + sourcename + "' at line " + GetCurrentLineNumber() + ": expected " + fadeType + " color value."); datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again } + } //vertwallshade or horizwallshade - } else if (token == "vertwallshade" || token == "horizwallshade") { + else if (token == "vertwallshade" || token == "horizwallshade") + { string shadeType = token; SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); //new format - if(token == "=") { + if(token == "=") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); } int val = 0; - if(!ReadSignedInt(token, ref val)) { + if(!ReadSignedInt(token, ref val)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Unexpected token found in '" + sourcename + "' at line " + GetCurrentLineNumber() + ": expected " + shadeType + " value, but got '" + token + "'"); datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again @@ -199,62 +228,77 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { mapInfo.VertWallShade = General.Clamp(val, -255, 255); else mapInfo.HorizWallShade = General.Clamp(val, -255, 255); + } //fogdensity or outsidefogdensity - } else if(token == "fogdensity" || token == "outsidefogdensity") { + else if(token == "fogdensity" || token == "outsidefogdensity") + { string densityType = token; SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); //new format - if(token == "=") { + if(token == "=") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); } int val; - if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) { + if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Unexpected token found in '" + sourcename + "' at line " + GetCurrentLineNumber() + ": expected " + densityType + " value, but got '" + token + "'"); datastream.Seek(-token.Length - 1, SeekOrigin.Current); //step back and try parsing this token again continue; } - if (densityType == "fogdensity") { + if (densityType == "fogdensity") mapInfo.FogDensity = (int)(1024 * (256.0f / val)); - } else { + else mapInfo.OutsideFogDensity = (int)(1024 * (256.0f / val)); - } - //doublesky - } else if (token == "doublesky") { + } +//doublesky + else if (token == "doublesky") + { mapInfo.DoubleSky = true; + + } //evenlighting - } else if (token == "evenlighting") { + else if (token == "evenlighting") + { mapInfo.EvenLighting = true; + } //smoothlighting - } else if (token == "smoothlighting") { + else if (token == "smoothlighting") + { mapInfo.SmoothLighting = true; - //block end - } else if (token == "}") { - return (curBlockName == "map" || parseBlock(token, mapName)); + } +//block end + else if (token == "}") + { + return (curBlockName == "map" || ParseBlock(token, mapName)); } } } return false; } - private static bool getColor(string name, ref Color4 color) { + private static bool GetColor(string name, ref Color4 color) + { if (name == "black") return true; //probably it's a hex color (like FFCC11)? int ci; - if (int.TryParse(name, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ci)) { + if (int.TryParse(name, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ci)) + { color = new Color4(ci) {Alpha = 1.0f}; return true; } //probably it's a color name? Color c = Color.FromName(name); //should be similar to C++ color name detection, I suppose - if (c.IsKnownColor) { + if (c.IsKnownColor) + { color = new Color4(c); return true; } diff --git a/Source/Core/GZBuilder/GZDoom/ModeldefParser.cs b/Source/Core/GZBuilder/GZDoom/ModeldefParser.cs index 75813b3e..8c526f7e 100644 --- a/Source/Core/GZBuilder/GZDoom/ModeldefParser.cs +++ b/Source/Core/GZBuilder/GZDoom/ModeldefParser.cs @@ -4,54 +4,60 @@ using System.IO; using CodeImp.DoomBuilder.ZDoom; using CodeImp.DoomBuilder.GZBuilder.Data; -namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { - - internal class ModeldefParser : ZDTextParser { +namespace CodeImp.DoomBuilder.GZBuilder.GZDoom +{ + internal class ModeldefParser : ZDTextParser + { private Dictionary entries; //classname, entry internal Dictionary Entries { get { return entries; } } internal string Source { get { return sourcename; } } - internal ModeldefParser() { + internal ModeldefParser() + { entries = new Dictionary(StringComparer.Ordinal); } //should be called after all decorate actors are parsed - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { base.Parse(stream, sourcefilename); entries = new Dictionary(StringComparer.Ordinal); // Continue until at the end of the stream - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - - if (token != null) { + if (token != null) + { token = StripTokenQuotes(token).ToLowerInvariant(); - - if (token == "model") { //model structure start + if (token == "model") //model structure start + { //find classname SkipWhitespace(true); string className = StripTokenQuotes(ReadToken(ActorStructure.ACTOR_CLASS_SPECIAL_TOKENS)).ToLowerInvariant(); - if(!string.IsNullOrEmpty(className) && !entries.ContainsKey(className)) { + if(!string.IsNullOrEmpty(className) && !entries.ContainsKey(className)) + { //now find opening brace SkipWhitespace(true); token = ReadToken(); - if (token != "{") { + if (token != "{") + { General.ErrorLogger.Add(ErrorType.Error, "Unexpected token found in '"+sourcefilename+"' at line "+GetCurrentLineNumber()+": expected '{', but got '" + token + "'"); continue; //something wrong with modeldef declaration, continue to next one } ModeldefStructure mds = new ModeldefStructure(); ModelData mde = mds.Parse(this); - if (mde != null) { - entries.Add(className, mde); - } + if (mde != null) entries.Add(className, mde); } - - } else { + } + else + { // Unknown structure! string token2; - if (token != "{") { + if (token != "{") + { do { if (!SkipWhitespace(true)) break; @@ -62,7 +68,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { } int scopelevel = 1; - do { + do + { if (!SkipWhitespace(true)) break; token2 = ReadToken(); if (token2 == null) break; diff --git a/Source/Core/GZBuilder/GZDoom/ModeldefParserSE.cs b/Source/Core/GZBuilder/GZDoom/ModeldefParserSE.cs index 3c3f57a1..d3c737ea 100644 --- a/Source/Core/GZBuilder/GZDoom/ModeldefParserSE.cs +++ b/Source/Core/GZBuilder/GZDoom/ModeldefParserSE.cs @@ -1,36 +1,48 @@ -using System.IO; +#region ================== Namespaces + +using System.IO; using System.Collections.Generic; using CodeImp.DoomBuilder.ZDoom; using CodeImp.DoomBuilder.GZBuilder.Data; +#endregion + //mxd. Modeldef parser used to create ScriptItems for use in script editor's navigator -namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { - internal sealed class ModeldefParserSE : ZDTextParser { - private List models; +namespace CodeImp.DoomBuilder.GZBuilder.GZDoom +{ + internal sealed class ModeldefParserSE : ZDTextParser + { + private readonly List models; internal List Models { get { return models; } } - public ModeldefParserSE() { + public ModeldefParserSE() + { models = new List(); } - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { base.Parse(stream, sourcefilename); // Continue until at the end of the stream - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = token.ToUpperInvariant(); - if(token == "MODEL"){ + if(token == "MODEL") + { int startPos = (int)stream.Position - 6; SkipWhitespace(true); string modelName = ReadToken(); SkipWhitespace(true); token = ReadToken(); //this should be "{" - if (token == "{") { + if (token == "{") + { ScriptItem i = new ScriptItem(0, modelName, startPos, (int)stream.Position - 2); models.Add(i); } diff --git a/Source/Core/GZBuilder/GZDoom/ModeldefStructure.cs b/Source/Core/GZBuilder/GZDoom/ModeldefStructure.cs index bce6f9f5..bceb9982 100644 --- a/Source/Core/GZBuilder/GZDoom/ModeldefStructure.cs +++ b/Source/Core/GZBuilder/GZDoom/ModeldefStructure.cs @@ -1,15 +1,22 @@ -using System; +#region ================== Namespaces + +using System; using System.IO; using System.Globalization; using SlimDX; using CodeImp.DoomBuilder.GZBuilder.Data; using CodeImp.DoomBuilder.Geometry; -namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { - internal sealed class ModeldefStructure { +#endregion + +namespace CodeImp.DoomBuilder.GZBuilder.GZDoom +{ + internal sealed class ModeldefStructure + { private const int MAX_MODELS = 4; //maximum models per modeldef entry, zero-based - internal ModelData Parse(ModeldefParser parser) { + internal ModelData Parse(ModeldefParser parser) + { string[] textureNames = new string[4]; string[] modelNames = new string[4]; string path = ""; @@ -26,18 +33,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { bool allParsed = false; //read modeldef structure contents - while(!gotErrors && !allParsed && parser.SkipWhitespace(true)) { + while(!gotErrors && !allParsed && parser.SkipWhitespace(true)) + { token = parser.ReadToken(); - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = parser.StripTokenQuotes(token).ToLowerInvariant(); //ANYTHING can be quoted... -//path - switch (token) { + + switch (token) + { case "path": parser.SkipWhitespace(true); path = parser.StripTokenQuotes(parser.ReadToken()).Replace("/", "\\"); - if(string.IsNullOrEmpty(path)) { + if(string.IsNullOrEmpty(path)) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected path to model, but got '" + token + "'"); gotErrors = true; } @@ -49,14 +60,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //model index int index; token = parser.StripTokenQuotes(parser.ReadToken()); - if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out index)) { + if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out index)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected model index, but got '" + token + "'"); gotErrors = true; break; } - if(index >= MAX_MODELS) { + if(index >= MAX_MODELS) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": GZDoom doesn't allow more than " + MAX_MODELS + " models per MODELDEF entry!"); gotErrors = true; break; @@ -66,18 +79,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //model path token = parser.StripTokenQuotes(parser.ReadToken()).ToLowerInvariant(); - if(string.IsNullOrEmpty(token)) { + if(string.IsNullOrEmpty(token)) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected model name, but got '" + token + "'"); gotErrors = true; - } else { + } + else + { //check extension string fileExt = Path.GetExtension(token); - if(string.IsNullOrEmpty(fileExt)) { + if(string.IsNullOrEmpty(fileExt)) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": model '" + token + "' won't be loaded. Models without extension are not supported by GZDoom."); gotErrors = true; break; } - if(fileExt != ".md3" && fileExt != ".md2") { + if(fileExt != ".md3" && fileExt != ".md2") + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": model '" + token + "' won't be loaded. Only MD2 and MD3 models are supported."); gotErrors = true; break; @@ -94,14 +112,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //skin index int skinIndex; token = parser.StripTokenQuotes(parser.ReadToken()); - if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out skinIndex)) { + if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out skinIndex)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected skin index, but got '" + token + "'"); gotErrors = true; break; } - if(skinIndex >= MAX_MODELS) { + if(skinIndex >= MAX_MODELS) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": GZDoom doesn't allow more than " + MAX_MODELS + " skins per MODELDEF entry!"); gotErrors = true; break; @@ -111,16 +131,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //skin path token = parser.StripTokenQuotes(parser.ReadToken()).ToLowerInvariant(); - if(string.IsNullOrEmpty(token)) { + if(string.IsNullOrEmpty(token)) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected skin name, but got '" + token + "'"); gotErrors = true; - } else { + } + else + { //check extension string ext = Path.GetExtension(token); - if(Array.IndexOf(TextureData.SUPPORTED_TEXTURE_EXTENSIONS, ext) == -1) { + if(Array.IndexOf(TextureData.SUPPORTED_TEXTURE_EXTENSIONS, ext) == -1) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": image format '" + ext + "' is not supported!"); textureNames[skinIndex] = TextureData.INVALID_TEXTURE; - } else { + } + else + { //GZDoom allows skins with identical modelIndex, it uses the last one encountered textureNames[skinIndex] = Path.Combine(path, token); } @@ -131,7 +157,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref scale.X)) { + if(!parser.ReadSignedFloat(token, ref scale.X)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected scale X value, but got '" + token + "'"); gotErrors = true; @@ -141,7 +168,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref scale.Y)) { + if(!parser.ReadSignedFloat(token, ref scale.Y)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected scale Y value, but got '" + token + "'"); gotErrors = true; @@ -151,7 +179,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref scale.Z)) { + if(!parser.ReadSignedFloat(token, ref scale.Z)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected scale Z value, but got '" + token + "'"); gotErrors = true; @@ -162,7 +191,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref zOffset)) { + if(!parser.ReadSignedFloat(token, ref zOffset)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected ZOffset value, but got '" + token + "'"); gotErrors = true; @@ -173,7 +203,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref angleOffset)) { + if(!parser.ReadSignedFloat(token, ref angleOffset)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected AngleOffset value, but got '" + token + "'"); gotErrors = true; @@ -184,7 +215,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref pitchOffset)) { + if(!parser.ReadSignedFloat(token, ref pitchOffset)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected PitchOffset value, but got '" + token + "'"); gotErrors = true; @@ -195,7 +227,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.SkipWhitespace(true); token = parser.StripTokenQuotes(parser.ReadToken()); - if(!parser.ReadSignedFloat(token, ref rollOffset)) { + if(!parser.ReadSignedFloat(token, ref rollOffset)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected RollOffset value, but got '" + token + "'"); gotErrors = true; @@ -214,7 +247,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { case "frame": //parsed all required fields. if got more than one model - find which one(s) should be displayed int len = modelNames.GetLength(0); - if(!gotErrors && len > 1) { + if(!gotErrors && len > 1) + { string spriteLump = null; string spriteFrame = null; bool[] modelsUsed = new bool[MAX_MODELS]; @@ -223,21 +257,28 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { parser.DataStream.Seek(-token.Length - 1, SeekOrigin.Current); //here we check which models are used in first encountered lump and frame - while(parser.SkipWhitespace(true)) { + while(parser.SkipWhitespace(true)) + { token = parser.StripTokenQuotes(parser.ReadToken()).ToLowerInvariant(); - if(token == "frameindex" || token == "frame") { + if(token == "frameindex" || token == "frame") + { bool frameIndex = (token == "frameindex"); parser.SkipWhitespace(true); //should be sprite lump token = parser.StripTokenQuotes(parser.ReadToken()).ToLowerInvariant(); - if(string.IsNullOrEmpty(spriteLump)) { + if(string.IsNullOrEmpty(spriteLump)) + { spriteLump = token; - } else if(spriteLump != token) { //got another lump - for(int i = 0; i < modelsUsed.Length; i++) { - if(!modelsUsed[i]) { + } + else if(spriteLump != token) //got another lump + { + for(int i = 0; i < modelsUsed.Length; i++) + { + if(!modelsUsed[i]) + { modelNames[i] = null; textureNames[i] = null; } @@ -250,11 +291,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //should be sprite frame token = parser.StripTokenQuotes(parser.ReadToken()).ToLowerInvariant(); - if(string.IsNullOrEmpty(spriteFrame)) { + if(string.IsNullOrEmpty(spriteFrame)) + { spriteFrame = token; - } else if(spriteFrame != token) { //got another frame - for(int i = 0; i < modelsUsed.Length; i++) { - if(!modelsUsed[i]) { + } + else if(spriteFrame != token) //got another frame + { + for(int i = 0; i < modelsUsed.Length; i++) + { + if(!modelsUsed[i]) + { modelNames[i] = null; textureNames[i] = null; } @@ -268,20 +314,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { token = parser.StripTokenQuotes(parser.ReadToken()); int modelIndex; - if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out modelIndex)) { + if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out modelIndex)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected model index, but got '" + token + "'"); gotErrors = true; break; } - if(modelIndex >= MAX_MODELS) { + if(modelIndex >= MAX_MODELS) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": GZDoom doesn't allow more than " + MAX_MODELS + " models per MODELDEF entry!"); gotErrors = true; break; } - if(modelNames[modelIndex] == null) { + if(modelNames[modelIndex] == null) + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": got model index, which doesn't correspond to any defined model!"); gotErrors = true; break; @@ -294,9 +343,11 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { //should be frame name or index. Currently I have no use for it token = parser.StripTokenQuotes(parser.ReadToken()); - if(frameIndex) { + if(frameIndex) + { int frame; - if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out frame)) { + if(!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out frame)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + parser.Source + " at line " + parser.GetCurrentLineNumber() + ": expected model frame, but got '" + token + "'"); gotErrors = true; @@ -304,7 +355,9 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { } } - } else { + } + else + { //must be "}", step back parser.DataStream.Seek(-token.Length - 1, SeekOrigin.Current); break; @@ -318,7 +371,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { } //find closing brace, then quit; - while (parser.SkipWhitespace(true)) { + while (parser.SkipWhitespace(true)) + { token = parser.ReadToken(); if (token == "}") break; } @@ -335,8 +389,10 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { mde.InheritActorPitch = inheritactorpitch; mde.InheritActorRoll = inheritactorroll; - for(int i = 0; i < modelNames.Length; i++) { - if (!string.IsNullOrEmpty(modelNames[i])) { + for(int i = 0; i < modelNames.Length; i++) + { + if (!string.IsNullOrEmpty(modelNames[i])) + { mde.TextureNames.Add(string.IsNullOrEmpty(textureNames[i]) ? textureNames[i] : textureNames[i].ToLowerInvariant()); mde.ModelNames.Add(modelNames[i].ToLowerInvariant()); } diff --git a/Source/Core/GZBuilder/GZDoom/ScriptTypeParserSE.cs b/Source/Core/GZBuilder/GZDoom/ScriptTypeParserSE.cs index 11f61cd8..64e36725 100644 --- a/Source/Core/GZBuilder/GZDoom/ScriptTypeParserSE.cs +++ b/Source/Core/GZBuilder/GZDoom/ScriptTypeParserSE.cs @@ -1,39 +1,53 @@ -using System.IO; +#region ================== Namespaces + +using System.IO; using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.ZDoom; +#endregion + //mxd. Parser used to determine which script type given text is. -namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { - internal sealed class ScriptTypeParserSE :ZDTextParser { +namespace CodeImp.DoomBuilder.GZBuilder.GZDoom +{ + internal sealed class ScriptTypeParserSE :ZDTextParser + { private ScriptType scriptType; internal ScriptType ScriptType { get { return scriptType; } } - internal ScriptTypeParserSE() { + internal ScriptTypeParserSE() + { scriptType = ScriptType.UNKNOWN; } - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { base.Parse(stream, sourcefilename); // Continue until at the end of the stream - while (SkipWhitespace(true)) { + while (SkipWhitespace(true)) + { string token = ReadToken(); - if (!string.IsNullOrEmpty(token)) { + if (!string.IsNullOrEmpty(token)) + { token = token.ToUpperInvariant(); - if (token == "MODEL") { + if (token == "MODEL") + { SkipWhitespace(true); ReadToken(); //should be model name SkipWhitespace(true); token = ReadToken();//should be opening brace - if (token == "{") { + if (token == "{") + { scriptType = ScriptType.MODELDEF; return true; } - }else if(token == "SCRIPT"){ + } + else if(token == "SCRIPT") + { SkipWhitespace(true); ReadToken(); //should be script name or number SkipWhitespace(true); @@ -41,19 +55,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = ReadToken(); //should be opening brace - if (token == "{") { + if (token == "{") + { scriptType = ScriptType.ACS; return true; } - }else if(token == "ACTOR"){ + } + else if(token == "ACTOR") + { SkipWhitespace(true); ReadToken(); //should be actor name SkipWhitespace(true); token = ReadToken(); - if (token == ":" || token == "{" || token == "REPLACES") { + if (token == ":" || token == "{" || token == "REPLACES") + { scriptType = ScriptType.DECORATE; return true; } @@ -61,7 +79,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.GZDoom { SkipWhitespace(true); token = ReadToken(); //should be actor name - if (token == "{") { + if (token == "{") + { scriptType = ScriptType.DECORATE; return true; } diff --git a/Source/Core/GZBuilder/Geometry/Line3D.cs b/Source/Core/GZBuilder/Geometry/Line3D.cs index d436e317..5d666f14 100644 --- a/Source/Core/GZBuilder/Geometry/Line3D.cs +++ b/Source/Core/GZBuilder/Geometry/Line3D.cs @@ -1,14 +1,16 @@ using System; using CodeImp.DoomBuilder.Geometry; -namespace CodeImp.DoomBuilder.GZBuilder.Geometry { +namespace CodeImp.DoomBuilder.GZBuilder.Geometry +{ public enum Line3DType { DEFAULT, ACTIVATOR, } - public class Line3D { + public class Line3D + { // Coordinates public Vector3D v1; public Vector3D v2; @@ -16,13 +18,15 @@ namespace CodeImp.DoomBuilder.GZBuilder.Geometry { private Line3DType lineType; // Constructors - public Line3D(Vector3D v1, Vector3D v2) { + public Line3D(Vector3D v1, Vector3D v2) + { this.v1 = v1; this.v2 = v2; this.lineType = Line3DType.DEFAULT; } - public Line3D(Vector3D v1, Vector3D v2, Line3DType lineType) { + public Line3D(Vector3D v1, Vector3D v2, Line3DType lineType) + { this.v1 = v1; this.v2 = v2; this.lineType = lineType; @@ -31,7 +35,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Geometry { public Vector3D GetDelta() { return v2 - v1; } // This calculates the angle - public float GetAngle() { + public float GetAngle() + { // Calculate and return the angle Vector2D d = GetDelta(); return -(float)Math.Atan2(-d.y, d.x) + Angle2D.PIHALF;//mxd // (float)Math.PI * 0.5f; diff --git a/Source/Core/GZBuilder/Tools/UDMFTools.cs b/Source/Core/GZBuilder/Tools/UDMFTools.cs index 5c29dd01..0f1c8032 100644 --- a/Source/Core/GZBuilder/Tools/UDMFTools.cs +++ b/Source/Core/GZBuilder/Tools/UDMFTools.cs @@ -8,88 +8,111 @@ namespace CodeImp.DoomBuilder.GZBuilder.Tools public static class UDMFTools { //float - public static void SetFloat(UniFields fields, string key, float value) { + public static void SetFloat(UniFields fields, string key, float value) + { SetFloat(fields, key, value, 0f); } - public static void SetFloat(UniFields fields, string key, float value, float defaultValue) { + public static void SetFloat(UniFields fields, string key, float value, float defaultValue) + { if(fields == null) return; - if(value != defaultValue) { + if(value != defaultValue) + { if(!fields.ContainsKey(key)) fields.Add(key, new UniValue(UniversalType.Float, value)); else fields[key].Value = value; - } else if(fields.ContainsKey(key)) { //don't save default value + } + else if(fields.ContainsKey(key)) //don't save default value + { fields.Remove(key); } } - public static float GetFloat(UniFields fields, string key) { + public static float GetFloat(UniFields fields, string key) + { return GetFloat(fields, key, 0f); } - public static float GetFloat(UniFields fields, string key, float defaultValue) { + public static float GetFloat(UniFields fields, string key, float defaultValue) + { if(fields == null) return defaultValue; return fields.GetValue(key, defaultValue); } //int - public static void SetInteger(UniFields fields, string key, int value) { + public static void SetInteger(UniFields fields, string key, int value) + { SetInteger(fields, key, value, 0); } - public static void SetInteger(UniFields fields, string key, int value, int defaultValue) { + public static void SetInteger(UniFields fields, string key, int value, int defaultValue) + { if(fields == null) return; - if(value != defaultValue) { + if(value != defaultValue) + { if(!fields.ContainsKey(key)) fields.Add(key, new UniValue(UniversalType.Integer, value)); else fields[key].Value = value; - } else if(fields.ContainsKey(key)) { //don't save default value + } + else if(fields.ContainsKey(key)) //don't save default value + { fields.Remove(key); } } - public static int GetInteger(UniFields fields, string key) { + public static int GetInteger(UniFields fields, string key) + { return GetInteger(fields, key, 0); } - public static int GetInteger(UniFields fields, string key, int defaultValue) { + public static int GetInteger(UniFields fields, string key, int defaultValue) + { if(fields == null) return defaultValue; return fields.GetValue(key, defaultValue); } - public static void SetString(UniFields fields, string key, string value, string defaultValue) { + public static void SetString(UniFields fields, string key, string value, string defaultValue) + { if(fields == null) return; - if(value != defaultValue) { + if(value != defaultValue) + { if(!fields.ContainsKey(key)) fields.Add(key, new UniValue(UniversalType.String, value)); else fields[key].Value = value; - } else if(fields.ContainsKey(key)) { //don't save default value + } + else if(fields.ContainsKey(key)) //don't save default value + { fields.Remove(key); } } - public static void ClearFields(UniFields fields, string[] keys) { + public static void ClearFields(UniFields fields, string[] keys) + { if(fields == null) return; - foreach(string key in keys){ + foreach(string key in keys) + { if(fields.ContainsKey(key)) fields.Remove(key); } } - public static void ClearField(UniFields fields, string key) { + public static void ClearField(UniFields fields, string key) + { if(fields == null || !fields.ContainsKey(key)) return; fields.Remove(key); } - public static bool FieldsMatch(UniFields fields1, UniFields fields2) { + public static bool FieldsMatch(UniFields fields1, UniFields fields2) + { if (fields1.Keys.Count != fields2.Keys.Count) return false; - foreach(KeyValuePair group in fields1) { + foreach(KeyValuePair group in fields1) + { if (!fields2.ContainsKey(group.Key)) return false; if (fields2[group.Key].Type != fields1[group.Key].Type) return false; diff --git a/Source/Core/GZBuilder/Windows/ExceptionDialog.cs b/Source/Core/GZBuilder/Windows/ExceptionDialog.cs index 181804ed..626c495a 100644 --- a/Source/Core/GZBuilder/Windows/ExceptionDialog.cs +++ b/Source/Core/GZBuilder/Windows/ExceptionDialog.cs @@ -1,8 +1,12 @@ -using System; +#region ================== Namespaces + +using System; using System.IO; using System.Windows.Forms; using System.Threading; +#endregion + namespace CodeImp.DoomBuilder.GZBuilder.Windows { public partial class ExceptionDialog : Form @@ -10,33 +14,38 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows private readonly bool cannotContinue; private readonly string logPath; - public ExceptionDialog(UnhandledExceptionEventArgs e) { + public ExceptionDialog(UnhandledExceptionEventArgs e) + { InitializeComponent(); logPath = Path.Combine(General.SettingsPath, @"GZCrash.txt"); Exception ex = (Exception)e.ExceptionObject; errorDescription.Text = "Error in " + ex.Source + ":"; - using(StreamWriter sw = File.CreateText(logPath)) { - sw.Write(getExceptionDescription(ex)); + using(StreamWriter sw = File.CreateText(logPath)) + { + sw.Write(GetExceptionDescription(ex)); } errorMessage.Text = ex.Message + Environment.NewLine + ex.StackTrace; cannotContinue = true; //cannot recover from this... } - public ExceptionDialog(ThreadExceptionEventArgs e) { + public ExceptionDialog(ThreadExceptionEventArgs e) + { InitializeComponent(); logPath = Path.Combine(General.SettingsPath, @"GZCrash.txt"); errorDescription.Text = "Error in " + e.Exception.Source + ":"; - using(StreamWriter sw = File.CreateText(logPath)) { - sw.Write(getExceptionDescription(e.Exception)); + using(StreamWriter sw = File.CreateText(logPath)) + { + sw.Write(GetExceptionDescription(e.Exception)); } errorMessage.Text = e.Exception.Message + Environment.NewLine + e.Exception.StackTrace; } - public void Setup() { + public void Setup() + { bContinue.Enabled = !cannotContinue; string[] titles = { @@ -107,18 +116,21 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows this.Text = titles[new Random().Next(0, titles.Length - 1)]; } - private string getExceptionDescription(Exception ex) { + private static string GetExceptionDescription(Exception ex) + { //add to error logger General.ErrorLogger.Add(ErrorType.Error, "**** " + ex.Source + ": " + ex.Message + " ****"); string message = "********EXCEPTION DETAILS********" + Environment.NewLine + ex.Source + ": " + ex.Message + Environment.NewLine + ex.StackTrace; - if(File.Exists(General.LogFile)) { - try { + if(File.Exists(General.LogFile)) + { + try + { string[] lines = File.ReadAllLines(General.LogFile); message += Environment.NewLine + Environment.NewLine + "***********ACTIONS LOG***********"; - for(int i = lines.Length - 1; i > -1; i--) + for(int i = lines.Length - 1; i > -1; i--) message += Environment.NewLine + lines[i]; } catch(Exception) { } } @@ -126,28 +138,35 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows return message; } - private void reportLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { + private void reportLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { if(!File.Exists(logPath)) return; System.Diagnostics.Process.Start("explorer.exe", @"/select, " + logPath); reportLink.LinkVisited = true; } - private void threadLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { - try { + private void threadLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { + try + { System.Diagnostics.Process.Start("http://forum.zdoom.org/viewtopic.php?f=3&t=32392&start=9999999"); - } catch(Exception) { + } + catch(Exception) + { MessageBox.Show("Unable to open URL..."); } threadLink.LinkVisited = true; } - private void bContinue_Click(object sender, EventArgs e) { + private void bContinue_Click(object sender, EventArgs e) + { this.DialogResult = DialogResult.OK; this.Close(); } - private void bToClipboard_Click(object sender, EventArgs e) { + private void bToClipboard_Click(object sender, EventArgs e) + { errorMessage.SelectAll(); errorMessage.Copy(); errorMessage.DeselectAll(); diff --git a/Source/Core/GZBuilder/Windows/ExceptionDialog.designer.cs b/Source/Core/GZBuilder/Windows/ExceptionDialog.designer.cs index 5ff17a38..ad5dd1d6 100644 --- a/Source/Core/GZBuilder/Windows/ExceptionDialog.designer.cs +++ b/Source/Core/GZBuilder/Windows/ExceptionDialog.designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.bQuit = new System.Windows.Forms.Button(); this.bContinue = new System.Windows.Forms.Button(); this.errorMessage = new System.Windows.Forms.TextBox(); diff --git a/Source/Core/GZBuilder/Windows/TagStatisticsForm.Designer.cs b/Source/Core/GZBuilder/Windows/TagStatisticsForm.Designer.cs index 456c90a7..4f73d59e 100644 --- a/Source/Core/GZBuilder/Windows/TagStatisticsForm.Designer.cs +++ b/Source/Core/GZBuilder/Windows/TagStatisticsForm.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); diff --git a/Source/Core/GZBuilder/Windows/TagStatisticsForm.cs b/Source/Core/GZBuilder/Windows/TagStatisticsForm.cs index c1482004..e9328c2a 100644 --- a/Source/Core/GZBuilder/Windows/TagStatisticsForm.cs +++ b/Source/Core/GZBuilder/Windows/TagStatisticsForm.cs @@ -1,4 +1,6 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; @@ -8,27 +10,38 @@ using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Windows; +#endregion + namespace CodeImp.DoomBuilder.GZBuilder.Windows { public partial class TagStatisticsForm : DelayedForm { private static Size size = Size.Empty; private static Point location = Point.Empty; - - public TagStatisticsForm() { + + #region ================== Constructor + + public TagStatisticsForm() + { InitializeComponent(); //apply window size and location - if(!size.IsEmpty && !location.IsEmpty){ + if(!size.IsEmpty && !location.IsEmpty) + { this.StartPosition = FormStartPosition.Manual; this.Size = size; this.Location = location; } - setup(); + Setup(); } - private void setup() { + #endregion + + #region ================== Methods + + private void Setup() + { //collect all tags List tags = new List(); Dictionary sectorsCountByTag = new Dictionary(); @@ -36,7 +49,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows Dictionary thingsCountByTag = new Dictionary(); //collect used tags from sectors... - foreach(Sector s in General.Map.Map.Sectors) { + foreach(Sector s in General.Map.Map.Sectors) + { if(s.Tag == 0) continue; if(!tags.Contains(s.Tag)) tags.Add(s.Tag); @@ -47,8 +61,10 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows } //...and linedefs... - if(General.Map.FormatInterface.HasLinedefTag) { - foreach(Linedef l in General.Map.Map.Linedefs) { + if(General.Map.FormatInterface.HasLinedefTag) + { + foreach(Linedef l in General.Map.Map.Linedefs) + { if(l.Tag == 0) continue; if(!tags.Contains(l.Tag)) tags.Add(l.Tag); @@ -57,13 +73,17 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows else linedefsCountByTag[l.Tag] += 1; } - } else { + } + else + { Linedefs.Visible = false; } //...and things... - if(General.Map.FormatInterface.HasThingTag) { - foreach(Thing t in General.Map.Map.Things) { + if(General.Map.FormatInterface.HasThingTag) + { + foreach(Thing t in General.Map.Map.Things) + { if(t.Tag == 0) continue; if(!tags.Contains(t.Tag)) tags.Add(t.Tag); @@ -72,14 +92,17 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows else thingsCountByTag[t.Tag] += 1; } - } else { + } + else + { Things.Visible = false; } //create rows dataGridView.Rows.Clear(); - foreach(int tag in tags) { - addRow(tag, + foreach(int tag in tags) + { + AddRow(tag, General.Map.Options.TagLabels.ContainsKey(tag) ? General.Map.Options.TagLabels[tag] : string.Empty, sectorsCountByTag.ContainsKey(tag) ? sectorsCountByTag[tag] : 0, linedefsCountByTag.ContainsKey(tag) ? linedefsCountByTag[tag] : 0, @@ -89,7 +112,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows dataGridView.Sort(TagColumn, ListSortDirection.Ascending); } - private void addRow(int tag, string label, int sectorsCount, int linesCount, int thingsCount) { + private void AddRow(int tag, string label, int sectorsCount, int linesCount, int thingsCount) + { DataGridViewRow row = new DataGridViewRow(); row.Cells.Add(new DataGridViewTextBoxCell { Value = tag }); @@ -101,10 +125,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows dataGridView.Rows.Add(row); } - private static List getSectorsWithTag(int tag, int count) { + private static List GetSectorsWithTag(int tag, int count) + { List list = new List(); - foreach(Sector s in General.Map.Map.Sectors) { - if(s.Tag == tag) { + foreach(Sector s in General.Map.Map.Sectors) + { + if(s.Tag == tag) + { list.Add(s); if(list.Count == count) break; } @@ -113,10 +140,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows return list; } - private static List getLinedefsWithTag(int tag, int count) { + private static List GetLinedefsWithTag(int tag, int count) + { List list = new List(); - foreach(Linedef l in General.Map.Map.Linedefs) { - if(l.Tag == tag) { + foreach(Linedef l in General.Map.Map.Linedefs) + { + if(l.Tag == tag) + { list.Add(l); if(list.Count == count) break; } @@ -125,10 +155,13 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows return list; } - private static List getThingsWithTag(int tag, int count) { + private static List GetThingsWithTag(int tag, int count) + { List list = new List(); - foreach(Thing t in General.Map.Map.Things) { - if(t.Tag == tag) { + foreach(Thing t in General.Map.Map.Things) + { + if(t.Tag == tag) + { list.Add(t); if(list.Count == count) break; } @@ -137,18 +170,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows return list; } - private static void showSelection(List points) { + private static void ShowSelection(List points) + { RectangleF area = MapSet.CreateEmptyArea(); // Make a view area from the points foreach(Vector2D p in points) area = MapSet.IncreaseArea(area, p); // Make the area square, using the largest side - if(area.Width > area.Height) { + if(area.Width > area.Height) + { float delta = area.Width - area.Height; area.Y -= delta * 0.5f; area.Height += delta; - } else { + } + else + { float delta = area.Height - area.Width; area.X -= delta * 0.5f; area.Width += delta; @@ -158,17 +195,25 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows area.Inflate(100f, 100f); // Zoom to area - ClassicMode editmode = (General.Editing.Mode as ClassicMode); - editmode.CenterOnArea(area, 0.6f); + if (General.Editing.Mode is ClassicMode) + { + ClassicMode editmode = (General.Editing.Mode as ClassicMode); + editmode.CenterOnArea(area, 0.6f); + } } -//events - private void apply_Click(object sender, EventArgs e) { + #endregion + + #region ================== Events + + private void apply_Click(object sender, EventArgs e) + { //refill TagLabels with table data dataGridView.Sort(TagColumn, ListSortDirection.Ascending); General.Map.Options.TagLabels.Clear(); - foreach(DataGridViewRow row in dataGridView.Rows) { + foreach(DataGridViewRow row in dataGridView.Rows) + { string label = row.Cells[1].Value.ToString(); if(!string.IsNullOrEmpty(label)) General.Map.Options.TagLabels.Add((int)row.Cells[0].Value, label); @@ -177,20 +222,25 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows this.Close(); } - private void cancel_Click(object sender, EventArgs e) { + private void cancel_Click(object sender, EventArgs e) + { this.Close(); } - private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { + private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) + { if(e.ColumnIndex < 2 || e.RowIndex == -1) return; //select - if (e.Button == MouseButtons.Left) { + if (e.Button == MouseButtons.Left) + { int tag = (int)dataGridView.Rows[e.RowIndex].Cells[0].Value; - if(e.ColumnIndex == 2) { //sectors - List list = getSectorsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[2].Value); - if(list.Count > 0) { + if(e.ColumnIndex == 2) //sectors + { + List list = GetSectorsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[2].Value); + if(list.Count > 0) + { General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); @@ -198,25 +248,31 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Editing.ChangeMode("SectorsMode"); ClassicMode mode = (ClassicMode)General.Editing.Mode; - foreach(Sector s in list) { + foreach(Sector s in list) + { mode.SelectMapElement(s); - foreach(Sidedef sd in s.Sidedefs) { + foreach(Sidedef sd in s.Sidedefs) + { points.Add(sd.Line.Start.Position); points.Add(sd.Line.End.Position); } } - showSelection(points); + ShowSelection(points); } - } else if(e.ColumnIndex == 3) { //linedefs - List list = getLinedefsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[3].Value); - if(list.Count > 0) { + } + else if(e.ColumnIndex == 3) //linedefs + { + List list = GetLinedefsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[3].Value); + if(list.Count > 0) + { General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); List points = new List(); - foreach(Linedef l in list) { + foreach(Linedef l in list) + { l.Selected = true; points.Add(l.Start.Position); points.Add(l.End.Position); @@ -224,15 +280,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Map.Map.Update(); General.Editing.ChangeMode("LinedefsMode"); - showSelection(points); + ShowSelection(points); } - } else if(e.ColumnIndex == 4) { //things - List list = getThingsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[4].Value); - if(list.Count > 0) { + } + else if(e.ColumnIndex == 4) //things + { + List list = GetThingsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[4].Value); + if(list.Count > 0) + { General.Map.Map.ClearSelectedThings(); List points = new List(); - foreach(Thing t in list) { + foreach(Thing t in list) + { t.Selected = true; Vector2D p = t.Position; @@ -245,55 +305,70 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Map.Map.Update(); General.Editing.ChangeMode("ThingsMode"); - showSelection(points); + ShowSelection(points); } } - //open properties window - } else if(e.Button == MouseButtons.Right) { + + } + else if(e.Button == MouseButtons.Right) //open properties window + { dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true; int tag = (int)dataGridView.Rows[e.RowIndex].Cells[0].Value; - if(e.ColumnIndex == 2) { //sectors - List list = getSectorsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[2].Value); - if(list.Count > 0) { + if(e.ColumnIndex == 2) //sectors + { + List list = GetSectorsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[2].Value); + if(list.Count > 0) + { General.MainWindow.ShowEditSectors(list); General.Map.Map.Update(); - setup(); + Setup(); } - } else if(e.ColumnIndex == 3) { //linedefs - List list = getLinedefsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[3].Value); - if(list.Count > 0) { + } + else if(e.ColumnIndex == 3) //linedefs + { + List list = GetLinedefsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[3].Value); + if(list.Count > 0) + { General.MainWindow.ShowEditLinedefs(list); General.Map.Map.Update(); - setup(); + Setup(); } - } else if(e.ColumnIndex == 4) { //things - List list = getThingsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[4].Value); - if(list.Count > 0) { + } + else if(e.ColumnIndex == 4) //things + { + List list = GetThingsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[4].Value); + if(list.Count > 0) + { General.MainWindow.ShowEditThings(list); General.Map.Map.Update(); - setup(); + Setup(); } } } } - private void dataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { + private void dataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) + { if(e.ColumnIndex < 2 || e.RowIndex == -1) return; int tag = (int)dataGridView.Rows[e.RowIndex].Cells[0].Value; - if(e.ColumnIndex == 2) { //sectors - List list = getSectorsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[2].Value); - if(list.Count > 0) { + if(e.ColumnIndex == 2) //sectors + { + List list = GetSectorsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[2].Value); + if(list.Count > 0) + { General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); List points = new List(); - foreach(Sector s in list) { + foreach(Sector s in list) + { s.Selected = true; - foreach(Sidedef sd in s.Sidedefs) { + foreach(Sidedef sd in s.Sidedefs) + { points.Add(sd.Line.Start.Position); points.Add(sd.Line.End.Position); } @@ -301,16 +376,20 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Map.Map.Update(); General.Editing.ChangeMode("SectorsMode"); - showSelection(points); + ShowSelection(points); } - } else if(e.ColumnIndex == 3) { //linedefs - List list = getLinedefsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[3].Value); - if(list.Count > 0) { + } + else if(e.ColumnIndex == 3) //linedefs + { + List list = GetLinedefsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[3].Value); + if(list.Count > 0) + { General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); List points = new List(); - foreach(Linedef l in list) { + foreach(Linedef l in list) + { l.Selected = true; points.Add(l.Start.Position); points.Add(l.End.Position); @@ -318,15 +397,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Map.Map.Update(); General.Editing.ChangeMode("LinedefsMode"); - showSelection(points); + ShowSelection(points); } - } else if(e.ColumnIndex == 4) { //things - List list = getThingsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[4].Value); - if(list.Count > 0) { + } + else if(e.ColumnIndex == 4) //things + { + List list = GetThingsWithTag(tag, (int)dataGridView.Rows[e.RowIndex].Cells[4].Value); + if(list.Count > 0) + { General.Map.Map.ClearSelectedThings(); List points = new List(); - foreach(Thing t in list) { + foreach(Thing t in list) + { t.Selected = true; Vector2D p = t.Position; @@ -339,14 +422,17 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Map.Map.Update(); General.Editing.ChangeMode("ThingsMode"); - showSelection(points); + ShowSelection(points); } } } - private void TagStatisticsForm_FormClosing(object sender, FormClosingEventArgs e) { + private void TagStatisticsForm_FormClosing(object sender, FormClosingEventArgs e) + { size = this.Size; location = this.Location; } + + #endregion } } diff --git a/Source/Core/GZBuilder/Windows/ThingStatisticsForm.cs b/Source/Core/GZBuilder/Windows/ThingStatisticsForm.cs index 89817827..9255cdfa 100644 --- a/Source/Core/GZBuilder/Windows/ThingStatisticsForm.cs +++ b/Source/Core/GZBuilder/Windows/ThingStatisticsForm.cs @@ -16,36 +16,43 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows private static Size size = Size.Empty; private static Point location = Point.Empty; - public ThingStatisticsForm() { + public ThingStatisticsForm() + { InitializeComponent(); //apply window size and location - if (!size.IsEmpty && !location.IsEmpty) { + if (!size.IsEmpty && !location.IsEmpty) + { this.StartPosition = FormStartPosition.Manual; this.Size = size; this.Location = location; } - setup(); + Setup(); } - private void setup() { + private void Setup() + { Dictionary thingcounts = new Dictionary(); Dictionary thingtitles = new Dictionary(); Dictionary thingclasses = new Dictionary(); - dataGridView.Rows.Clear(); - foreach(ThingTypeInfo ti in General.Map.Data.ThingTypes) { + foreach(ThingTypeInfo ti in General.Map.Data.ThingTypes) + { thingcounts.Add(ti.Index, 0); thingtitles.Add(ti.Index, ti.Title); thingclasses.Add(ti.Index, ti.ClassName); } - foreach(Thing t in General.Map.Map.Things) { - if (thingcounts.ContainsKey(t.Type)) { + foreach(Thing t in General.Map.Map.Things) + { + if (thingcounts.ContainsKey(t.Type)) + { thingcounts[t.Type]++; - } else { + } + else + { thingcounts.Add(t.Type, 1); thingtitles.Add(t.Type, "Unknown thing"); thingclasses.Add(t.Type, "-"); @@ -53,7 +60,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows } //add rows - foreach (KeyValuePair group in thingcounts) { + foreach (KeyValuePair group in thingcounts) + { if (hideUnused.Checked && group.Value == 0) continue; DataGridViewRow row = new DataGridViewRow(); @@ -69,27 +77,31 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows dataGridView.Sort(ThingType, ListSortDirection.Ascending); } - private static List getThingsByType(int type) { + private static List GetThingsByType(int type) + { List list = new List(); - foreach (Thing t in General.Map.Map.Things) { + foreach (Thing t in General.Map.Map.Things) if (t.Type == type) list.Add(t); - } return list; } - private static void showSelection(List points) { + private static void ShowSelection(List points) + { RectangleF area = MapSet.CreateEmptyArea(); // Make a view area from the points foreach (Vector2D p in points) area = MapSet.IncreaseArea(area, p); // Make the area square, using the largest side - if (area.Width > area.Height) { + if (area.Width > area.Height) + { float delta = area.Width - area.Height; area.Y -= delta * 0.5f; area.Height += delta; - } else { + } + else + { float delta = area.Height - area.Width; area.X -= delta * 0.5f; area.Width += delta; @@ -99,19 +111,26 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows area.Inflate(100f, 100f); // Zoom to area - ClassicMode editmode = (General.Editing.Mode as ClassicMode); - editmode.CenterOnArea(area, 0.6f); + if (General.Editing.Mode is ClassicMode) + { + ClassicMode editmode = (General.Editing.Mode as ClassicMode); + editmode.CenterOnArea(area, 0.6f); + } } - private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { + private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) + { if (e.RowIndex == -1) return; - if (e.Button == MouseButtons.Left) { //select - List list = getThingsByType((int)dataGridView.Rows[e.RowIndex].Cells[0].Value); - if (list.Count > 0) { + if (e.Button == MouseButtons.Left) //select + { + List list = GetThingsByType((int)dataGridView.Rows[e.RowIndex].Cells[0].Value); + if (list.Count > 0) + { General.Map.Map.ClearSelectedThings(); List points = new List(); - foreach (Thing t in list) { + foreach (Thing t in list) + { t.Selected = true; Vector2D p = t.Position; @@ -124,31 +143,35 @@ namespace CodeImp.DoomBuilder.GZBuilder.Windows General.Map.Map.Update(); General.Editing.ChangeMode("ThingsMode"); - showSelection(points); + ShowSelection(points); } - } else if (e.Button == MouseButtons.Right) { //edit - List list = getThingsByType((int)dataGridView.Rows[e.RowIndex].Cells[0].Value); - if (list.Count > 0) { + } + else if (e.Button == MouseButtons.Right) //edit + { + List list = GetThingsByType((int)dataGridView.Rows[e.RowIndex].Cells[0].Value); + if (list.Count > 0) + { General.MainWindow.ShowEditThings(list); General.Map.Map.Update(); - setup(); + Setup(); } } } private void hideUnused_CheckedChanged(object sender, EventArgs e) { - setup(); + Setup(); } - private void apply_Click(object sender, EventArgs e) { + private void apply_Click(object sender, EventArgs e) + { this.Close(); } - private void ThingStatisticsForm_FormClosing(object sender, FormClosingEventArgs e) { + private void ThingStatisticsForm_FormClosing(object sender, FormClosingEventArgs e) + { size = this.Size; location = this.Location; } - } } diff --git a/Source/Core/GZBuilder/md3/GZModel.cs b/Source/Core/GZBuilder/md3/GZModel.cs index e997bae4..966a6f78 100644 --- a/Source/Core/GZBuilder/md3/GZModel.cs +++ b/Source/Core/GZBuilder/md3/GZModel.cs @@ -4,15 +4,16 @@ using SlimDX.Direct3D9; namespace CodeImp.DoomBuilder.GZBuilder.MD3 { - internal class GZModel { + internal class GZModel + { internal List Meshes; internal List Textures; internal Vector3[] BoundingBox; - internal GZModel() { + internal GZModel() + { Meshes = new List(); Textures = new List(); } } - } \ No newline at end of file diff --git a/Source/Core/GZBuilder/md3/ModelReader.cs b/Source/Core/GZBuilder/md3/ModelReader.cs index dc688ff8..ed9197e1 100644 --- a/Source/Core/GZBuilder/md3/ModelReader.cs +++ b/Source/Core/GZBuilder/md3/ModelReader.cs @@ -29,7 +29,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 public List Meshes; public string Errors; - public MD3LoadResult() { + public MD3LoadResult() + { Skins = new List(); Meshes = new List(); } @@ -41,9 +42,12 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 #region ================== Init - internal static void Init() { - if(vertexElements == null) { - vertexElements = new[] { + internal static void Init() + { + if(vertexElements == null) + { + vertexElements = new[] + { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), new VertexElement(0, 16, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), @@ -57,35 +61,31 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 #region ================== Load - public static void Load(ModelData mde, List containers, Device device) { - if(mde.IsVoxel) { - loadKVX(mde, containers, device); - } else { - loadModel(mde, containers, device); - } + public static void Load(ModelData mde, List containers, Device device) + { + if(mde.IsVoxel) + LoadKVX(mde, containers, device); + else + LoadModel(mde, containers, device); } - private static void loadKVX(ModelData mde, List containers, Device device) { + private static void LoadKVX(ModelData mde, List containers, Device device) + { mde.Model = new GZModel(); - //prepare WhiteTexture... just in case :) - //if(General.Map.Data.WhiteTexture.Texture == null || General.Map.Data.WhiteTexture.Texture.Disposed) - //General.Map.Data.WhiteTexture.CreateTexture(); - - for(int i = 0; i < mde.ModelNames.Count; i++) { + for(int i = 0; i < mde.ModelNames.Count; i++) + { //find the model Stream ms; - foreach(DataReader dr in containers) { + foreach(DataReader dr in containers) + { ms = dr.GetVoxelData(mde.ModelNames[i]); if(ms == null) continue; //load kvx ReadKVX(mde, ms, device); - //add texture - //mde.Model.Textures.Add(General.Map.Data.WhiteTexture.Texture); - //done ms.Close(); ms.Dispose(); @@ -97,24 +97,28 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 mde.TextureNames = null; mde.ModelNames = null; - if(mde.Model.Meshes == null || mde.Model.Meshes.Count == 0) { + if(mde.Model.Meshes == null || mde.Model.Meshes.Count == 0) + { mde.Model = null; } } - private static void loadModel(ModelData mde, List containers, Device device) { + private static void LoadModel(ModelData mde, List containers, Device device) + { mde.Model = new GZModel(); BoundingBoxSizes bbs = new BoundingBoxSizes(); MD3LoadResult result = new MD3LoadResult(); //load models and textures - for(int i = 0; i < mde.ModelNames.Count; i++) { + for(int i = 0; i < mde.ModelNames.Count; i++) + { //need to use model skins? bool useSkins = string.IsNullOrEmpty(mde.TextureNames[i]); //load mesh MemoryStream ms = LoadFile(containers, mde.ModelNames[i], true); - if (ms == null) { + if (ms == null) + { General.ErrorLogger.Add(ErrorType.Error, "Error while loading '" + mde.ModelNames[i] + "': unable to find file."); continue; } @@ -132,9 +136,12 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 ms.Dispose(); //got errors? - if(!String.IsNullOrEmpty(result.Errors)) { + if(!String.IsNullOrEmpty(result.Errors)) + { General.ErrorLogger.Add(ErrorType.Error, "Error while loading '" + mde.ModelNames[i] + "': " + result.Errors); - } else { + } + else + { //add loaded data to ModeldefEntry mde.Model.Meshes.AddRange(result.Meshes); @@ -146,15 +153,20 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 List errors = new List(); //texture has unsupported extension? - if(mde.TextureNames[i] == TextureData.INVALID_TEXTURE) { + if(mde.TextureNames[i] == TextureData.INVALID_TEXTURE) + { for (int c = 0; c < result.Meshes.Count; c++) mde.Model.Textures.Add(General.Map.Data.UnknownTexture3D.Texture); //texture not defined in MODELDEF? - } else if(useSkins) { + } + else if(useSkins) + { //try to use model's own skins - for(int m = 0; m < result.Meshes.Count; m++) { - if(string.IsNullOrEmpty(result.Skins[m])) { + for(int m = 0; m < result.Meshes.Count; m++) + { + if(string.IsNullOrEmpty(result.Skins[m])) + { mde.Model.Textures.Add(General.Map.Data.UnknownTexture3D.Texture); errors.Add("texture not found in MODELDEF or model skin."); continue; @@ -163,7 +175,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 string path = result.Skins[m].Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); ext = Path.GetExtension(path); - if(Array.IndexOf(TextureData.SUPPORTED_TEXTURE_EXTENSIONS, ext) == -1) { + if(Array.IndexOf(TextureData.SUPPORTED_TEXTURE_EXTENSIONS, ext) == -1) + { mde.Model.Textures.Add(General.Map.Data.UnknownTexture3D.Texture); errors.Add("image format '" + ext + "' is not supported!"); continue; @@ -175,7 +188,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 Texture t = LoadTexture(containers, path, device); - if(t == null) { + if(t == null) + { mde.Model.Textures.Add(General.Map.Data.UnknownTexture3D.Texture); errors.Add("unable to load skin '" + result.Skins[m] + "'"); continue; @@ -183,20 +197,24 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 mde.Model.Textures.Add(t); } - - //try to use texture loaded from MODELDEFS - } else { + } + else //try to use texture loaded from MODELDEFS + { Texture t = LoadTexture(containers, mde.TextureNames[i], device); - if(t == null) { + if(t == null) + { mde.Model.Textures.Add(General.Map.Data.UnknownTexture3D.Texture); errors.Add("unable to load texture '" + mde.TextureNames[i] + "'"); - } else { + } + else + { mde.Model.Textures.Add(t); } } //report errors - if(errors.Count > 0) { + if(errors.Count > 0) + { foreach(string e in errors) General.ErrorLogger.Add(ErrorType.Error, "Error while loading '" + mde.ModelNames[i] + "': " + e); } @@ -207,7 +225,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 mde.TextureNames = null; mde.ModelNames = null; - if(mde.Model.Meshes == null || mde.Model.Meshes.Count == 0) { + if(mde.Model.Meshes == null || mde.Model.Meshes.Count == 0) + { mde.Model = null; return; } @@ -219,13 +238,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 #region ================== MD3 - private static MD3LoadResult ReadMD3Model(ref BoundingBoxSizes bbs, ModelData mde, bool useSkins, MemoryStream s, Device device) { + private static MD3LoadResult ReadMD3Model(ref BoundingBoxSizes bbs, ModelData mde, bool useSkins, MemoryStream s, Device device) + { long start = s.Position; MD3LoadResult result = new MD3LoadResult(); - using (var br = new BinaryReader(s, Encoding.ASCII)) { + using (var br = new BinaryReader(s, Encoding.ASCII)) + { string magic = ReadString(br, 4); - if (magic != "IDP3"){ + if (magic != "IDP3") + { result.Errors = "magic should be 'IDP3', not '" + magic + "'"; return result; } @@ -245,24 +267,30 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 Dictionary> vertexOffsets = new Dictionary>(StringComparer.Ordinal); string error; - for (int c = 0; c < numSurfaces; c++) { + for (int c = 0; c < numSurfaces; c++) + { string skin = ""; error = ReadSurface(ref bbs, ref skin, br, polyIndecesList, vertList, mde); - if(!string.IsNullOrEmpty(error)) { + if(!string.IsNullOrEmpty(error)) + { result.Errors = error; return result; } - if(useSkins) { - if(polyIndecesListsPerTexture.ContainsKey(skin)) { + if(useSkins) + { + if(polyIndecesListsPerTexture.ContainsKey(skin)) + { polyIndecesListsPerTexture[skin].Add(polyIndecesList); vertListsPerTexture[skin].AddRange(vertList.ToArray()); vertexOffsets[skin].Add(vertList.Count); - } else { - polyIndecesListsPerTexture.Add(skin, new List>() { polyIndecesList } ); + } + else + { + polyIndecesListsPerTexture.Add(skin, new List> { polyIndecesList } ); vertListsPerTexture.Add(skin, vertList); - vertexOffsets.Add(skin, new List() { vertList.Count }); + vertexOffsets.Add(skin, new List { vertList.Count }); } //reset lists @@ -271,20 +299,27 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 } } - if(!useSkins) { //create mesh + if(!useSkins) + { + //create mesh CreateMesh(device, ref result, vertList, polyIndecesList); result.Skins.Add(""); - } else { + } + else + { //create a mesh for each surface texture - foreach(KeyValuePair>> group in polyIndecesListsPerTexture) { + foreach(KeyValuePair>> group in polyIndecesListsPerTexture) + { polyIndecesList = new List(); int offset = 0; //collect indices, fix vertex offsets - for(int i = 0; i < group.Value.Count; i++) { - if(i > 0) { - offset += vertexOffsets[group.Key][i - 1]; //Damn I need to rewrite all of this stuff from scratch... - + for(int i = 0; i < group.Value.Count; i++) + { + if(i > 0) + { + //TODO: Damn I need to rewrite all of this stuff from scratch... + offset += vertexOffsets[group.Key][i - 1]; for(int c = 0; c < group.Value[i].Count; c++) group.Value[i][c] += offset; } @@ -300,7 +335,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 return result; } - private static string ReadSurface(ref BoundingBoxSizes bbs, ref string skin, BinaryReader br, List polyIndecesList, List vertList, ModelData mde) { + private static string ReadSurface(ref BoundingBoxSizes bbs, ref string skin, BinaryReader br, List polyIndecesList, List vertList, ModelData mde) + { int vertexOffset = vertList.Count; long start = br.BaseStream.Position; string magic = ReadString(br, 4); @@ -333,7 +369,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 if (start + ofsST != br.BaseStream.Position) br.BaseStream.Position = start + ofsST; - for (int i = 0; i < numVerts; i++) { + for (int i = 0; i < numVerts; i++) + { WorldVertex v = new WorldVertex(); v.c = -1; //white v.u = br.ReadSingle(); @@ -350,7 +387,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 float angleOfsetCos = (float)Math.Cos(mde.AngleOffset); float angleOfsetSin = (float)Math.Sin(mde.AngleOffset); - for (int i = vertexOffset; i < vertexOffset + numVerts; i++) { + for (int i = vertexOffset; i < vertexOffset + numVerts; i++) + { WorldVertex v = vertList[i]; //read vertex @@ -359,7 +397,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 v.z = (float)br.ReadInt16() / 64; //rotate it - if (mde.AngleOffset != 0) { + if (mde.AngleOffset != 0) + { float rx = angleOfsetCos * v.x - angleOfsetSin * v.y; float ry = angleOfsetSin * v.x + angleOfsetCos * v.y; v.y = ry; @@ -392,16 +431,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 return ""; } - private static void CreateMesh(Device device, ref MD3LoadResult result, List verts, List indices) { + private static void CreateMesh(Device device, ref MD3LoadResult result, List verts, List indices) + { //create mesh Mesh mesh = new Mesh(device, indices.Count / 3, verts.Count, MeshFlags.Use32Bit | MeshFlags.IndexBufferManaged | MeshFlags.VertexBufferManaged, vertexElements); - using(DataStream stream = mesh.LockVertexBuffer(LockFlags.None)) { + using(DataStream stream = mesh.LockVertexBuffer(LockFlags.None)) + { stream.WriteRange(verts.ToArray()); } mesh.UnlockVertexBuffer(); - using(DataStream stream = mesh.LockIndexBuffer(LockFlags.None)) { + using(DataStream stream = mesh.LockIndexBuffer(LockFlags.None)) + { stream.WriteRange(indices.ToArray()); } mesh.UnlockIndexBuffer(); @@ -416,19 +458,23 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 #region ================== MD2 - private static MD3LoadResult ReadMD2Model(ref BoundingBoxSizes bbs, ModelData mde, MemoryStream s, Device device) { + private static MD3LoadResult ReadMD2Model(ref BoundingBoxSizes bbs, ModelData mde, MemoryStream s, Device device) + { long start = s.Position; MD3LoadResult result = new MD3LoadResult(); - using (var br = new BinaryReader(s, Encoding.ASCII)) { + using (var br = new BinaryReader(s, Encoding.ASCII)) + { string magic = ReadString(br, 4); - if(magic != "IDP2") { //magic number: "IDP2" + if(magic != "IDP2") //magic number: "IDP2" + { result.Errors = "magic should be 'IDP2', not '" + magic + "'"; return result; } int modelVersion = br.ReadInt32(); - if(modelVersion != 8) { //MD2 version. Must be equal to 8 + if(modelVersion != 8) //MD2 version. Must be equal to 8 + { result.Errors = "MD2 version must be 8 but is " + modelVersion; return result; } @@ -442,8 +488,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 int num_tris = br.ReadInt32(); //Number of triangles s.Position += 4; //Number of OpenGL commands - if(br.ReadInt32() == 0) { //Total number of frames - //General.ErrorLogger.Add(ErrorType.Error, "Unable to load model '" + path + "': model has 0 frames."); + if(br.ReadInt32() == 0) //Total number of frames + { result.Errors = "model has 0 frames."; return result; } @@ -461,7 +507,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 //polygons s.Position = ofs_tris + start; - for (int i = 0; i < num_tris; i++) { + for (int i = 0; i < num_tris; i++) + { polyIndecesList.Add(br.ReadUInt16()); polyIndecesList.Add(br.ReadUInt16()); polyIndecesList.Add(br.ReadUInt16()); @@ -492,7 +539,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 float angleOfsetSin = (float)Math.Sin(angle); //verts - for (int i = 0; i < num_verts; i++) { + for (int i = 0; i < num_verts; i++) + { WorldVertex v = new WorldVertex(); v.x = (br.ReadByte() * scale.X + translate.X); @@ -500,7 +548,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 v.z = (br.ReadByte() * scale.Z + translate.Z); //rotate it - if (angle != 0) { + if (angle != 0) + { float rx = angleOfsetCos * v.x - angleOfsetSin * v.y; float ry = angleOfsetSin * v.x + angleOfsetCos * v.y; v.y = ry; @@ -519,7 +568,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 s.Position += 1; //vertex normal } - for (int i = 0; i < polyIndecesList.Count; i++) { + for (int i = 0; i < polyIndecesList.Count; i++) + { WorldVertex v = vertList[polyIndecesList[i]]; //bounding box @@ -530,11 +580,14 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 float tv = uvCoordsList[uvIndecesList[i]].Y; //uv-coordinates already set? - if(v.c == -1 && (v.u != tu || v.v != tv)) { + if(v.c == -1 && (v.u != tu || v.v != tv)) + { //add a new vertex vertList.Add(new WorldVertex(v.x, v.y, v.z, -1, tu, tv)); polyIndecesList[i] = vertList.Count - 1; - } else { + } + else + { v.u = tu; v.v = tv; v.c = -1; //set color to white @@ -547,12 +600,14 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 //mesh Mesh mesh = new Mesh(device, polyIndecesList.Count / 3, vertList.Count, MeshFlags.Use32Bit | MeshFlags.IndexBufferManaged | MeshFlags.VertexBufferManaged, vertexElements); - using (DataStream stream = mesh.LockVertexBuffer(LockFlags.None)) { + using (DataStream stream = mesh.LockVertexBuffer(LockFlags.None)) + { stream.WriteRange(vertList.ToArray()); } mesh.UnlockVertexBuffer(); - using (DataStream stream = mesh.LockIndexBuffer(LockFlags.None)) { + using (DataStream stream = mesh.LockIndexBuffer(LockFlags.None)) + { stream.WriteRange(polyIndecesList.ToArray()); } mesh.UnlockIndexBuffer(); @@ -571,13 +626,15 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 #region ================== KVX - private static void ReadKVX(ModelData mde, Stream stream, Device device) { + private static void ReadKVX(ModelData mde, Stream stream, Device device) + { PixelColor[] palette = new PixelColor[256]; List verts = new List(); int xsize, ysize, zsize; Vector3D pivot; - using(BinaryReader reader = new BinaryReader(stream, Encoding.ASCII)) { + using(BinaryReader reader = new BinaryReader(stream, Encoding.ASCII)) + { reader.ReadInt32(); //numbytes, we don't use that xsize = reader.ReadInt32(); ysize = reader.ReadInt32(); @@ -592,20 +649,25 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 int[] xoffset = new int[xsize + 1]; //why is it xsize + 1, not xsize?.. short[,] xyoffset = new short[xsize, ysize + 1]; //why is it ysize + 1, not ysize?.. - for(int i = 0; i < xoffset.Length; i++) { + for(int i = 0; i < xoffset.Length; i++) + { xoffset[i] = reader.ReadInt32(); } - for(int x = 0; x < xsize; x++) { - for(int y = 0; y < ysize + 1; y++) { + for(int x = 0; x < xsize; x++) + { + for(int y = 0; y < ysize + 1; y++) + { xyoffset[x, y] = reader.ReadInt16(); } } //read slabs List offsets = new List(xsize * ysize); - for(int x = 0; x < xsize; x++) { - for(int y = 0; y < ysize; y++) { + for(int x = 0; x < xsize; x++) + { + for(int y = 0; y < ysize; y++) + { offsets.Add(xoffset[x] + xyoffset[x, y] + 28); //for some reason offsets are counted from start of xoffset[]... } } @@ -614,58 +676,74 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 int slabsEnd = (int)(reader.BaseStream.Length - 768); //read palette - if(!mde.OverridePalette) { + if(!mde.OverridePalette) + { reader.BaseStream.Position = slabsEnd; - for(int i = 0; i < 256; i++) { + for(int i = 0; i < 256; i++) + { byte r = (byte)(reader.ReadByte() * 4); byte g = (byte)(reader.ReadByte() * 4); byte b = (byte)(reader.ReadByte() * 4); palette[i] = new PixelColor(255, r, g, b); } - } else { - for(int i = 0; i < 256; i++ ) { + } + else + { + for(int i = 0; i < 256; i++ ) + { palette[i] = General.Map.Data.Palette[i]; } } - for(int x = 0; x < xsize; x++) { - for(int y = 0; y < ysize; y++) { + for(int x = 0; x < xsize; x++) + { + for(int y = 0; y < ysize; y++) + { reader.BaseStream.Position = offsets[counter]; int next = (counter < offsets.Count - 1 ? offsets[counter + 1] : slabsEnd); //read slab - while(reader.BaseStream.Position < next) { + while(reader.BaseStream.Position < next) + { int ztop = reader.ReadByte(); int zleng = reader.ReadByte(); if(ztop + zleng > zsize) break; int flags = reader.ReadByte(); - if(zleng > 0) { + if(zleng > 0) + { List colorIndices = new List(zleng); - for(int i = 0; i < zleng; i++) { + for(int i = 0; i < zleng; i++) + { colorIndices.Add(reader.ReadByte()); } - if((flags & 16) != 0) { + if((flags & 16) != 0) + { AddFace(verts, new Vector3D(x, y, ztop), new Vector3D(x + 1, y, ztop), new Vector3D(x, y + 1, ztop), new Vector3D(x + 1, y + 1, ztop), pivot, colorIndices[0], mde.AngleOffset, mde.Scale.X); } int z = ztop; int cstart = 0; - while(z < ztop + zleng) { + while(z < ztop + zleng) + { int c = 0; while(z + c < ztop + zleng && colorIndices[cstart + c] == colorIndices[cstart]) c++; - if((flags & 1) != 0) { + if((flags & 1) != 0) + { AddFace(verts, new Vector3D(x, y, z), new Vector3D(x, y + 1, z), new Vector3D(x, y, z + c), new Vector3D(x, y + 1, z + c), pivot, colorIndices[cstart], mde.AngleOffset, mde.Scale.X); } - if((flags & 2) != 0) { + if((flags & 2) != 0) + { AddFace(verts, new Vector3D(x + 1, y + 1, z), new Vector3D(x + 1, y, z), new Vector3D(x + 1, y + 1, z + c), new Vector3D(x + 1, y, z + c), pivot, colorIndices[cstart], mde.AngleOffset, mde.Scale.X); } - if((flags & 4) != 0) { + if((flags & 4) != 0) + { AddFace(verts, new Vector3D(x + 1, y, z), new Vector3D(x, y, z), new Vector3D(x + 1, y, z + c), new Vector3D(x, y, z + c), pivot, colorIndices[cstart], mde.AngleOffset, mde.Scale.X); } - if((flags & 8) != 0) { + if((flags & 8) != 0) + { AddFace(verts, new Vector3D(x, y + 1, z), new Vector3D(x + 1, y + 1, z), new Vector3D(x, y + 1, z + c), new Vector3D(x + 1, y + 1, z + c), pivot, colorIndices[cstart], mde.AngleOffset, mde.Scale.X); } @@ -674,7 +752,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 cstart += c; } - if((flags & 32) != 0) { + if((flags & 32) != 0) + { z = ztop + zleng - 1; AddFace(verts, new Vector3D(x + 1, y, z + 1), new Vector3D(x, y, z + 1), new Vector3D(x + 1, y + 1, z + 1), new Vector3D(x, y + 1, z + 1), pivot, colorIndices[zleng - 1], mde.AngleOffset, mde.Scale.X); } @@ -698,7 +777,7 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 mde.Model.BoundingBox = BoundingBoxTools.CalculateBoundingBox(bbs); //create bitmap - Bitmap bmp = createVoxelTexture(palette); + Bitmap bmp = CreateVoxelTexture(palette); //create texture MemoryStream memstream = new MemoryStream((4096 * 4) + 4096); @@ -713,7 +792,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 //create mesh int[] indices = new int[verts.Count]; - for(int i = 0; i < verts.Count; i++) { + for(int i = 0; i < verts.Count; i++) + { indices[i] = i; } @@ -734,7 +814,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 } // Shameless GZDoom rip-off - private static void AddFace(List verts, Vector3D v1, Vector3D v2, Vector3D v3, Vector3D v4, Vector3D pivot, int colorIndex, float angle, float scale) { + private static void AddFace(List verts, Vector3D v1, Vector3D v2, Vector3D v3, Vector3D v4, Vector3D pivot, int colorIndex, float angle, float scale) + { float pu0 = (colorIndex % 16) / 16f; float pu1 = pu0 + 0.0001f; float pv0 = (colorIndex / 16) / 16f; @@ -780,8 +861,10 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 verts.Add(wv4); } - private static WorldVertex TransformVertex(WorldVertex v, float angle, float scale) { - if (angle != 0) { + private static WorldVertex TransformVertex(WorldVertex v, float angle, float scale) + { + if (angle != 0) + { float angleOfsetCos = (float) Math.Cos(angle); float angleOfsetSin = (float) Math.Sin(angle); @@ -791,7 +874,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 v.x = rx1; } - if (scale != 1.0f) { + if (scale != 1.0f) + { v.x *= scale; v.y *= scale; v.z *= scale; @@ -800,16 +884,19 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 return v; } - private unsafe static Bitmap createVoxelTexture(PixelColor[] palette) { + private unsafe static Bitmap CreateVoxelTexture(PixelColor[] palette) + { Bitmap bmp = new Bitmap(16, 16); BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - if(bmpdata != null) { + if(bmpdata != null) + { PixelColor* pixels = (PixelColor*)(bmpdata.Scan0.ToPointer()); const int numpixels = 256; int i = 255; - for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--, i--) { + for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--, i--) + { cp->r = palette[i].r; cp->g = palette[i].g; cp->b = palette[i].b; @@ -820,7 +907,8 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 //scale bitmap, so colors stay (almost) the same when bilinear filtering is enabled Bitmap scaled = new Bitmap(64, 64); - using(Graphics gs = Graphics.FromImage(scaled)) { + using(Graphics gs = Graphics.FromImage(scaled)) + { gs.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; gs.DrawImage(bmp, new Rectangle(0, 0, 64, 64), new Rectangle(0, 0, 16, 16), GraphicsUnit.Pixel); } @@ -832,18 +920,20 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 #region ================== Utility - private static MemoryStream LoadFile(List containers, string path, bool isModel) { - foreach(DataReader dr in containers) { + private static MemoryStream LoadFile(List containers, string path, bool isModel) + { + foreach(DataReader dr in containers) + { if(isModel && dr is WADReader) continue; //models cannot be stored in WADs //load file - if(dr.FileExists(path)) - return dr.LoadFile(path); + if(dr.FileExists(path)) return dr.LoadFile(path); } return null; } - private static Texture LoadTexture(List containers, string path, Device device) { + private static Texture LoadTexture(List containers, string path, Device device) + { if(string.IsNullOrEmpty(path)) return null; MemoryStream ms = LoadFile(containers, path, false); @@ -852,14 +942,16 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 Texture texture = null; //create texture - if(Path.GetExtension(path) == ".pcx") { //pcx format requires special handling... + if(Path.GetExtension(path) == ".pcx") //pcx format requires special handling... + { FileImageReader fir = new FileImageReader(); Bitmap bitmap = fir.ReadAsBitmap(ms); ms.Close(); ms.Dispose(); - if(bitmap != null) { + if(bitmap != null) + { BitmapData bmlock = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); texture = new Texture(device, bitmap.Width, bitmap.Height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed); @@ -869,7 +961,9 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 bitmap.UnlockBits(bmlock); texture.UnlockRectangle(0); } - } else { + } + else + { texture = Texture.FromStream(device, ms); ms.Close(); @@ -879,18 +973,22 @@ namespace CodeImp.DoomBuilder.GZBuilder.MD3 return texture; } - private static string ReadString(BinaryReader br, int len) { + private static string ReadString(BinaryReader br, int len) + { var NAME = string.Empty; int i; - for (i = 0; i < len; ++i) { + for (i = 0; i < len; ++i) + { var c = br.ReadChar(); - if (c == '\0') { + if (c == '\0') + { ++i; break; } NAME += c; } - for (; i < len; ++i) { + for (; i < len; ++i) + { br.ReadChar(); } return NAME; diff --git a/Source/Core/General/CRC.cs b/Source/Core/General/CRC.cs index eaa9d5b6..63ae7d3e 100644 --- a/Source/Core/General/CRC.cs +++ b/Source/Core/General/CRC.cs @@ -84,9 +84,9 @@ namespace CodeImp.DoomBuilder #region ================== Crc32 sealed class Crc32 { - const uint CrcSeed = 0xFFFFFFFF; + const uint CRC_SEED = 0xFFFFFFFF; - readonly static uint[] CrcTable = new uint[] { + readonly static uint[] CRC_TABLE = new uint[] { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, @@ -139,11 +139,12 @@ namespace CodeImp.DoomBuilder 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; + }; - internal static uint ComputeCrc32(uint oldCrc, byte value) { + /*internal static uint ComputeCrc32(uint oldCrc, byte value) + { return (Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8)); - } + }*/ /// /// The crc data checksum so far. @@ -153,21 +154,12 @@ namespace CodeImp.DoomBuilder /// /// Returns the CRC32 data checksum computed so far. /// - public long Value { - get { - return crc; - } - set { - crc = (uint)value; - } - } + public long Value { get { return crc; } set { crc = (uint)value; } } /// /// Resets the CRC32 data checksum as if no update was ever called. /// - public void Reset() { - crc = 0; - } + public void Reset() { crc = 0; } /// /// Updates the checksum with the int bval. @@ -175,10 +167,11 @@ namespace CodeImp.DoomBuilder /// /// the byte is taken as the lower 8 bits of value /// - public void Update(int value) { - crc ^= CrcSeed; - crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8); - crc ^= CrcSeed; + public void Update(int value) + { + crc ^= CRC_SEED; + crc = CRC_TABLE[(crc ^ value) & 0xFF] ^ (crc >> 8); + crc ^= CRC_SEED; } /// @@ -187,11 +180,9 @@ namespace CodeImp.DoomBuilder /// /// buffer an array of bytes /// - public void Update(byte[] buffer) { - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - + public void Update(byte[] buffer) + { + if (buffer == null) throw new ArgumentNullException("buffer"); Update(buffer, 0, buffer.Length); } @@ -207,26 +198,20 @@ namespace CodeImp.DoomBuilder /// /// The number of data bytes to update the CRC with. /// - public void Update(byte[] buffer, int offset, int count) { - if (buffer == null) { - throw new ArgumentNullException("buffer"); + public void Update(byte[] buffer, int offset, int count) + { + if (buffer == null) throw new ArgumentNullException("buffer"); + if (count < 0) throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero"); + if (offset < 0 || offset + count > buffer.Length) throw new ArgumentOutOfRangeException("offset"); + + crc ^= CRC_SEED; + + while (--count >= 0) + { + crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8); } - if (count < 0) { - throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero"); - } - - if (offset < 0 || offset + count > buffer.Length) { - throw new ArgumentOutOfRangeException("offset"); - } - - crc ^= CrcSeed; - - while (--count >= 0) { - crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8); - } - - crc ^= CrcSeed; + crc ^= CRC_SEED; } } #endregion diff --git a/Source/Core/General/ErrorLogger.cs b/Source/Core/General/ErrorLogger.cs index f93b1f12..a4e0c80e 100644 --- a/Source/Core/General/ErrorLogger.cs +++ b/Source/Core/General/ErrorLogger.cs @@ -88,7 +88,7 @@ namespace CodeImp.DoomBuilder erroradded = true; prefix = "ERROR: "; #if DEBUG - DebugConsole.WriteLine(DebugMessageType.Error, message); + DebugConsole.WriteLine(DebugMessageType.ERROR, message); #endif break; @@ -96,7 +96,7 @@ namespace CodeImp.DoomBuilder warningadded = true; prefix = "WARNING: "; #if DEBUG - DebugConsole.WriteLine(DebugMessageType.Warning, message); + DebugConsole.WriteLine(DebugMessageType.WARNING, message); #endif break; } diff --git a/Source/Core/General/General.cs b/Source/Core/General/General.cs index 3a6d632b..6e41aca7 100644 --- a/Source/Core/General/General.cs +++ b/Source/Core/General/General.cs @@ -262,7 +262,7 @@ namespace CodeImp.DoomBuilder } // This loads and returns a game configuration - private static Configuration loadGameConfiguration(string filename) + private static Configuration LoadGameConfiguration(string filename) { // Make the full filepathname string filepathname = Path.Combine(configspath, filename); @@ -320,7 +320,7 @@ namespace CodeImp.DoomBuilder foreach(string filepath in filenames) { // Check if it can be loaded - cfg = loadGameConfiguration(Path.GetFileName(filepath)); + cfg = LoadGameConfiguration(Path.GetFileName(filepath)); if(cfg != null) { fullfilename = Path.GetFileName(filepath); @@ -710,17 +710,19 @@ namespace CodeImp.DoomBuilder //mxd. Check enabled game configuration bool noneenabled = true; - for(int i = 0; i < configs.Count; i++) { - if(configs[i].Enabled) { + for(int i = 0; i < configs.Count; i++) + { + if(configs[i].Enabled) + { noneenabled = false; break; } } - if(noneenabled) { - if(MessageBox.Show("No game configurations are currently enabled.\nPlease enable at least one game configuration", "Warning", MessageBoxButtons.OK) == DialogResult.OK) { + if(noneenabled) + { + if(MessageBox.Show("No game configurations are currently enabled.\nPlease enable at least one game configuration", "Warning", MessageBoxButtons.OK) == DialogResult.OK) mainwindow.ShowConfiguration(); - } } // Run application from the main window @@ -1132,8 +1134,8 @@ namespace CodeImp.DoomBuilder [BeginAction("openmap")] internal static void OpenMap() { - //mxd - if(map != null && map.Launcher.GameEngineRunning) { + if(map != null && map.Launcher.GameEngineRunning) //mxd + { ShowWarningMessage("Cannot open a map while game engine is running" + Environment.NewLine + "Please close '" + map.ConfigSettings.TestProgram + "' first.", MessageBoxButtons.OK); return; } @@ -1641,7 +1643,7 @@ namespace CodeImp.DoomBuilder #if DEBUG // Output to consoles Console.WriteLine(line); - DebugConsole.WriteLine(DebugMessageType.Log, line); //mxd + DebugConsole.WriteLine(DebugMessageType.LOG, line); //mxd #endif // Write to log file try { File.AppendAllText(logfile, line + Environment.NewLine); } @@ -1654,7 +1656,7 @@ namespace CodeImp.DoomBuilder #if DEBUG // Output to consoles Console.Write(text); - DebugConsole.Write(DebugMessageType.Log, text); + DebugConsole.Write(DebugMessageType.LOG, text); #endif // Write to log file diff --git a/Source/Core/General/Launcher.cs b/Source/Core/General/Launcher.cs index fe25f397..96846f35 100644 --- a/Source/Core/General/Launcher.cs +++ b/Source/Core/General/Launcher.cs @@ -75,7 +75,8 @@ namespace CodeImp.DoomBuilder General.Actions.UnbindMethods(this); //mxd. Terminate process? - if (process != null) { + if (process != null) + { process.CloseMainWindow(); process.Close(); } @@ -243,7 +244,8 @@ namespace CodeImp.DoomBuilder //mxd [BeginAction("testmapfromview")] - public void TestFromView() { + public void TestFromView() + { if(!General.Editing.Mode.OnMapTestBegin(true)) return; TestAtSkill(General.Map.ConfigSettings.TestSkill); General.Editing.Mode.OnMapTestEnd(true); @@ -253,7 +255,8 @@ namespace CodeImp.DoomBuilder public void TestAtSkill(int skill) { //mxd - if (process != null) { + if (process != null) + { General.ShowWarningMessage("Game engine is already running." + Environment.NewLine + " Please close '" + General.Map.ConfigSettings.TestProgram + "' before testing again", MessageBoxButtons.OK); return; } @@ -342,7 +345,8 @@ namespace CodeImp.DoomBuilder } //mxd - private void testingFinished() { + private void TestingFinished() + { //Done TimeSpan deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks); process = null; @@ -359,9 +363,11 @@ namespace CodeImp.DoomBuilder } //mxd - public void StopGameEngine() { + public void StopGameEngine() + { //mxd. Terminate process? - if(process != null) { + if(process != null) + { process.CloseMainWindow(); process.Close(); process = null; @@ -372,8 +378,9 @@ namespace CodeImp.DoomBuilder } //mxd - private void ProcessOnExited(object sender, EventArgs eventArgs) { - General.MainWindow.Invoke(new EngineExitedCallback(testingFinished)); + private void ProcessOnExited(object sender, EventArgs eventArgs) + { + General.MainWindow.Invoke(new EngineExitedCallback(TestingFinished)); } // This deletes the previous temp file and creates a new, empty temp file diff --git a/Source/Core/General/MapManager.cs b/Source/Core/General/MapManager.cs index 41de3a62..5b2bc65c 100644 --- a/Source/Core/General/MapManager.cs +++ b/Source/Core/General/MapManager.cs @@ -553,12 +553,14 @@ namespace CodeImp.DoomBuilder { /// /// This exports the structures from memory into a WAD file with the current map format. /// - public bool ExportToFile(string filepathname) { + public bool ExportToFile(string filepathname) + { return SaveMap(filepathname, SavePurpose.Testing); } // Initializes for an existing map - internal bool SaveMap(string newfilepathname, SavePurpose purpose) { + internal bool SaveMap(string newfilepathname, SavePurpose purpose) + { MapSet outputset; string nodebuildername, settingsfile; StatusInfo oldstatus; @@ -577,14 +579,13 @@ namespace CodeImp.DoomBuilder { // Only recompile scripts when the scripts have changed // (not when only the map changed) - if (localscriptschanged) { - if (!CompileScriptLumps()) { - // Compiler failure - if (errors.Count > 0) - General.ShowErrorMessage("Error while compiling scripts: " + errors[0].description, MessageBoxButtons.OK); - else - General.ShowErrorMessage("Unknown compiler error while compiling scripts!", MessageBoxButtons.OK); - } + if(localscriptschanged && !CompileScriptLumps()) + { + // Compiler failure + if(errors.Count > 0) + General.ShowErrorMessage("Error while compiling scripts: " + errors[0].description, MessageBoxButtons.OK); + else + General.ShowErrorMessage("Unknown compiler error while compiling scripts!", MessageBoxButtons.OK); } // Show script window if there are any errors and we are going to test the map @@ -594,13 +595,16 @@ namespace CodeImp.DoomBuilder { // Only write the map and rebuild nodes when the actual map has changed // (not when only scripts have changed) - if (changed) { + if (changed) + { // Make a copy of the map data outputset = map.Clone(); // Remove all flags from all 3D Start things - foreach (Thing t in outputset.Things) { - if (t.Type == config.Start3DModeThingType) { + foreach (Thing t in outputset.Things) + { + if (t.Type == config.Start3DModeThingType) + { // We're not using SetFlag here, this doesn't have to be undone. // Please note that this is totally exceptional! List flagkeys = new List(t.Flags.Keys); @@ -609,7 +613,8 @@ namespace CodeImp.DoomBuilder { } // Do we need sidedefs compression? - if (map.Sidedefs.Count > io.MaxSidedefs) { + if (map.Sidedefs.Count > io.MaxSidedefs) + { // Compress sidedefs oldstatus = General.MainWindow.Status; General.MainWindow.DisplayStatus(StatusType.Busy, "Compressing sidedefs..."); @@ -617,7 +622,8 @@ namespace CodeImp.DoomBuilder { General.MainWindow.DisplayStatus(oldstatus); // Check if it still doesnt fit - if (outputset.Sidedefs.Count > io.MaxSidedefs) { + if (outputset.Sidedefs.Count > io.MaxSidedefs) + { // Problem! Can't save the map like this! General.ShowErrorMessage("Unable to save the map: There are too many unique sidedefs!", MessageBoxButtons.OK); return false; @@ -625,25 +631,29 @@ namespace CodeImp.DoomBuilder { } // Check things - if (map.Things.Count > io.MaxThings) { + if (map.Things.Count > io.MaxThings) + { General.ShowErrorMessage("Unable to save the map: There are too many things!", MessageBoxButtons.OK); return false; } // Check sectors - if (map.Sectors.Count > io.MaxSectors) { + if (map.Sectors.Count > io.MaxSectors) + { General.ShowErrorMessage("Unable to save the map: There are too many sectors!", MessageBoxButtons.OK); return false; } // Check linedefs - if (map.Linedefs.Count > io.MaxLinedefs) { + if (map.Linedefs.Count > io.MaxLinedefs) + { General.ShowErrorMessage("Unable to save the map: There are too many linedefs!", MessageBoxButtons.OK); return false; } // Check vertices - if (map.Vertices.Count > io.MaxVertices) { + if (map.Vertices.Count > io.MaxVertices) + { General.ShowErrorMessage("Unable to save the map: There are too many vertices!", MessageBoxButtons.OK); return false; } @@ -681,15 +691,19 @@ namespace CodeImp.DoomBuilder { // Determine original map name origmapname = (options.PreviousName != "" && purpose != SavePurpose.IntoFile) ? options.PreviousName : options.CurrentName; - try { - if (File.Exists(newfilepathname)) { + try + { + if (File.Exists(newfilepathname)) + { // mxd. Check if target wad already has a map with the same name - if (purpose == SavePurpose.IntoFile) { + if (purpose == SavePurpose.IntoFile) + { WAD wad = new WAD(newfilepathname, true); int mapindex = wad.FindLumpIndex(origmapname); wad.Dispose(); - if(mapindex != -1 && MessageBox.Show(General.MainWindow, "Target file already contains map '" + origmapname + "'\nDo you want to replace it?", "Map already exists!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) { + if(mapindex != -1 && MessageBox.Show(General.MainWindow, "Target file already contains map '" + origmapname + "'\nDo you want to replace it?", "Map already exists!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) + { data.Resume(); General.WriteLogLine("Map saving cancelled..."); return false; @@ -705,7 +719,8 @@ namespace CodeImp.DoomBuilder { // Except when saving INTO another file, // kill the target file if it is different from source file - if ((purpose != SavePurpose.IntoFile) && (newfilepathname != filepathname)) { + if ((purpose != SavePurpose.IntoFile) && (newfilepathname != filepathname)) + { // Kill target file if (File.Exists(newfilepathname)) File.Delete(newfilepathname); @@ -715,13 +730,15 @@ namespace CodeImp.DoomBuilder { } // On Save AS we have to copy the previous file to the new file - if ((purpose == SavePurpose.AsNewFile) && (filepathname != "")) { + if ((purpose == SavePurpose.AsNewFile) && (filepathname != "")) + { // Copy if original file still exists if (File.Exists(filepathname)) File.Copy(filepathname, newfilepathname, true); } // If the target file exists, we need to rebuild it - if (File.Exists(newfilepathname)) { + if (File.Exists(newfilepathname)) + { // Move the target file aside string origwadfile = newfilepathname + ".temp"; File.Move(newfilepathname, origwadfile); @@ -734,9 +751,12 @@ namespace CodeImp.DoomBuilder { // Copy all lumps, except the original map GameConfiguration origcfg; //mxd - if (origmapconfigname == configinfo.Filename) { + if (origmapconfigname == configinfo.Filename) + { origcfg = config; - } else { + } + else + { ConfigurationInfo ci = General.GetConfigurationInfo(origmapconfigname); origcfg = new GameConfiguration(ci.Configuration); } @@ -752,12 +772,16 @@ namespace CodeImp.DoomBuilder { // Create new target file targetwad = new WAD(newfilepathname); } - } catch (IOException) { + } + catch (IOException) + { General.ShowErrorMessage("IO Error while writing target file: " + newfilepathname + ". Please make sure the location is accessible and not in use by another program.", MessageBoxButtons.OK); data.Resume(); General.WriteLogLine("Map saving failed"); return false; - } catch (UnauthorizedAccessException) { + } + catch (UnauthorizedAccessException) + { General.ShowErrorMessage("Error while accessing target file: " + newfilepathname + ". Please make sure the location is accessible and not in use by another program.", MessageBoxButtons.OK); data.Resume(); General.WriteLogLine("Map saving failed"); @@ -776,10 +800,13 @@ namespace CodeImp.DoomBuilder { // Find the map header in target index = targetwad.FindLumpIndex(options.PreviousName); - if (index > -1) { + if (index > -1) + { // Rename the map lump name targetwad.Lumps[index].Rename(options.CurrentName); - } else { + } + else + { // Houston, we've got a problem! General.ShowErrorMessage("Error renaming map lump name: the original map lump could not be found!", MessageBoxButtons.OK); options.CurrentName = options.PreviousName; @@ -796,9 +823,11 @@ namespace CodeImp.DoomBuilder { data.Resume(); // Not saved for testing purpose? - if (purpose != SavePurpose.Testing) { + if (purpose != SavePurpose.Testing) + { // Saved in a different file? - if (newfilepathname != filepathname) { + if (newfilepathname != filepathname) + { // Keep new filename filepathname = newfilepathname; filetitle = Path.GetFileName(filepathname); @@ -807,11 +836,14 @@ namespace CodeImp.DoomBuilder { ReloadResources(); } - try { + try + { // Open or create the map settings settingsfile = newfilepathname.Substring(0, newfilepathname.Length - 4) + ".dbs"; options.WriteConfiguration(settingsfile); - } catch (Exception e) { + } + catch (Exception e) + { // Warning only General.ErrorLogger.Add(ErrorType.Warning, "Could not write the map settings configuration file. " + e.GetType().Name + ": " + e.Message); } @@ -1234,7 +1266,8 @@ namespace CodeImp.DoomBuilder { { // Check if this is a known lump name if (maplumps.ContainsKey(source.Lumps[mapheaderindex + i].Name) || - (maplumps.ContainsKey(CONFIG_MAP_HEADER) && (source.Lumps[mapheaderindex + i].Name == mapheadername))) { + (maplumps.ContainsKey(CONFIG_MAP_HEADER) && (source.Lumps[mapheaderindex + i].Name == mapheadername))) + { // Is this the lump we are looking for? if (source.Lumps[mapheaderindex + i].Name == lumpname) { @@ -1648,7 +1681,7 @@ namespace CodeImp.DoomBuilder { if (stream != null) { AcsParserSE parser = new AcsParserSE(); - parser.OnInclude = updateScriptsFromLocation; + parser.OnInclude = UpdateScriptsFromLocation; parser.Parse(stream, "SCRIPTS", true, false); if(parser.NamedScripts.Count > 0 && (FormatInterface is DoomMapSetIO || FormatInterface is HexenMapSetIO)) @@ -1675,7 +1708,7 @@ namespace CodeImp.DoomBuilder { } //mxd - private static void updateScriptsFromLocation(AcsParserSE parser, string path) + private static void UpdateScriptsFromLocation(AcsParserSE parser, string path) { MemoryStream s = General.Map.Data.LoadFile(path); if(s != null && s.Length > 0) parser.Parse(s, path, true, true); @@ -1954,7 +1987,7 @@ namespace CodeImp.DoomBuilder { //snap vertices? if (verts.Count > 0) { - snapVertices(verts); + SnapVertices(verts); return; } @@ -1966,12 +1999,12 @@ namespace CodeImp.DoomBuilder { } else { - snapThings(things); + SnapThings(things); } } //mxd - private void snapVertices(ICollection verts) + private void SnapVertices(ICollection verts) { //we are terribly busy... Cursor.Current = Cursors.AppStarting; @@ -2091,7 +2124,7 @@ namespace CodeImp.DoomBuilder { } //mxd - private static void snapThings(IEnumerable things) + private static void SnapThings(IEnumerable things) { //we are terribly busy... Cursor.Current = Cursors.AppStarting; diff --git a/Source/Core/Geometry/CurveTools.cs b/Source/Core/Geometry/CurveTools.cs index 777925d0..e13b0851 100644 --- a/Source/Core/Geometry/CurveTools.cs +++ b/Source/Core/Geometry/CurveTools.cs @@ -10,63 +10,59 @@ namespace CodeImp.DoomBuilder.Geometry { //mxd. Ported from Cubic Bezier curve tools by Andy Woodruff (http://cartogrammar.com/source/CubicBezier.as) //"default" values: z = 0.5, angleFactor = 0.75; if targetSegmentLength <= 0, will return lines - public static Curve CurveThroughPoints(List points, float z, float angleFactor, int targetSegmentLength) { + public static Curve CurveThroughPoints(List points, float z, float angleFactor, int targetSegmentLength) + { Curve result = new Curve(); // First calculate all the curve control points // None of this junk will do any good if there are only two points - if(points.Count > 2 && targetSegmentLength > 0) { + if(points.Count > 2 && targetSegmentLength > 0) + { List> controlPts = new List>(); // An array to store the two control points (of a cubic Bézier curve) for each point // Make sure z is between 0 and 1 (too messy otherwise) - if(z <= 0) - z = 0.1f; - else if(z > 1) - z = 1; + if(z <= 0) z = 0.1f; + else if(z > 1) z = 1; // Make sure angleFactor is between 0 and 1 - if(angleFactor < 0) - angleFactor = 0; - else if(angleFactor > 1) - angleFactor = 1; + if(angleFactor < 0) angleFactor = 0; + else if(angleFactor > 1) angleFactor = 1; // Ordinarily, curve calculations will start with the second point and go through the second-to-last point int firstPt = 1; int lastPt = points.Count - 1; // Check if this is a closed line (the first and last points are the same) - if(points[0].x == points[points.Count - 1].x && points[0].y == points[points.Count - 1].y) { + if(points[0].x == points[points.Count - 1].x && points[0].y == points[points.Count - 1].y) + { // Include first and last points in curve calculations firstPt = 0; lastPt = points.Count; - } else { + } + else + { controlPts.Add(new List()); //add a dummy entry } // Loop through all the points (except the first and last if not a closed line) to get curve control points for each. - for(int i = firstPt; i < lastPt; i++) { - + for(int i = firstPt; i < lastPt; i++) + { // The previous, current, and next points Vector2D p0 = (i - 1 < 0) ? points[points.Count - 2] : points[i - 1]; // If the first point (of a closed line), use the second-to-last point as the previous point Vector2D p1 = points[i]; Vector2D p2 = (i + 1 == points.Count) ? points[1] : points[i + 1]; // If the last point (of a closed line), use the second point as the next point float a = Vector2D.Distance(p0, p1); // Distance from previous point to current point - if(a < 0.001) - a = 0.001f; // Correct for near-zero distances, a cheap way to prevent division by zero + if(a < 0.001) a = 0.001f; // Correct for near-zero distances, a cheap way to prevent division by zero float b = Vector2D.Distance(p1, p2); // Distance from current point to next point - if(b < 0.001) - b = 0.001f; + if(b < 0.001) b = 0.001f; float c = Vector2D.Distance(p0, p2); // Distance from previous point to next point - if(c < 0.001) - c = 0.001f; + if(c < 0.001) c = 0.001f; float cos = (b * b + a * a - c * c) / (2 * b * a); // Make sure above value is between -1 and 1 so that Math.acos will work - if(cos < -1) - cos = -1; - else if(cos > 1) - cos = 1; + if(cos < -1) cos = -1; + else if(cos > 1) cos = 1; float C = (float)Math.Acos(cos); // Angle formed by the two sides of the triangle (described by the three points above) adjacent to the current point @@ -83,10 +79,8 @@ namespace CodeImp.DoomBuilder.Geometry (defined above) and the perpendicular to this is nice for the line tangent to the curve. The curve control points will be along that tangent line. */ - if(a > b) - aPt = aPt.GetNormal() * b; // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter. - else if(b > a) - cPt = cPt.GetNormal() * a; // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter. + if(a > b) aPt = aPt.GetNormal() * b; // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter. + else if(b > a) cPt = cPt.GetNormal() * a; // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter. // Offset aPt and cPt by the current point to get them back to their absolute position. aPt += p1; @@ -101,16 +95,20 @@ namespace CodeImp.DoomBuilder.Geometry float ry = ay + by; // Correct for three points in a line by finding the angle between just two of them - if(rx == 0 && ry == 0) { + if(rx == 0 && ry == 0) + { rx = -bx; // Really not sure why this seems to have to be negative ry = by; } // Switch rx and ry when y or x difference is 0. This seems to prevent the angle from being perpendicular to what it should be. - if(ay == 0 && by == 0) { + if(ay == 0 && by == 0) + { rx = 0; ry = 1; - } else if(ax == 0 && bx == 0) { + } + else if(ax == 0 && bx == 0) + { rx = 1; ry = 0; } @@ -138,13 +136,14 @@ namespace CodeImp.DoomBuilder.Geometry Check for that and switch them if it's true. */ if(Vector2D.Distance(controlPoint2, p2) > Vector2D.Distance(controlPoint1, p2)) - controlPts.Add(new List() { controlPoint2, controlPoint1 }); + controlPts.Add(new List { controlPoint2, controlPoint1 }); else - controlPts.Add(new List() { controlPoint1, controlPoint2 }); + controlPts.Add(new List { controlPoint1, controlPoint2 }); } // If this isn't a closed line, draw a regular quadratic Bézier curve from the first to second points, using the first control point of the second point - if(firstPt == 1) { + if(firstPt == 1) + { float length = (points[1] - points[0]).GetLength(); int numSteps = Math.Max(1, (int)Math.Round(length / targetSegmentLength)); CurveSegment segment = new CurveSegment(); @@ -157,7 +156,8 @@ namespace CodeImp.DoomBuilder.Geometry } // Loop through points to draw cubic Bézier curves through the penultimate point, or through the last point if the line is closed. - for(int i = firstPt; i < lastPt - 1; i++) { + for(int i = firstPt; i < lastPt - 1; i++) + { float length = (points[i + 1] - points[i]).GetLength(); int numSteps = Math.Max(1, (int)Math.Round(length / targetSegmentLength)); @@ -172,7 +172,8 @@ namespace CodeImp.DoomBuilder.Geometry } // If this isn't a closed line, curve to the last point using the second control point of the penultimate point. - if(lastPt == points.Count - 1) { + if(lastPt == points.Count - 1) + { float length = (points[lastPt] - points[lastPt - 1]).GetLength(); int numSteps = Math.Max(1, (int)Math.Round(length / targetSegmentLength)); @@ -186,12 +187,15 @@ namespace CodeImp.DoomBuilder.Geometry } // create lines - } else if(points.Count >= 2) { - for(int i = 0; i < points.Count - 1; i++) { + } + else if(points.Count >= 2) + { + for(int i = 0; i < points.Count - 1; i++) + { CurveSegment segment = new CurveSegment(); segment.Start = points[i]; segment.End = points[i + 1]; - segment.Points = new Vector2D[] { segment.Start, segment.End }; + segment.Points = new[] { segment.Start, segment.End }; segment.UpdateLength(); result.Segments.Add(segment); } @@ -201,23 +205,25 @@ namespace CodeImp.DoomBuilder.Geometry return result; } - public static void CreateQuadraticCurve(CurveSegment segment, int steps) { + public static void CreateQuadraticCurve(CurveSegment segment, int steps) + { segment.CurveType = CurveSegmentType.QUADRATIC; segment.Points = GetQuadraticCurve(segment.Start, segment.CPMid, segment.End, steps); segment.UpdateLength(); } //this returns array of Vector2D to draw 3-point bezier curve - public static Vector2D[] GetQuadraticCurve(Vector2D p1, Vector2D p2, Vector2D p3, int steps) { - if(steps < 0) - return null; + public static Vector2D[] GetQuadraticCurve(Vector2D p1, Vector2D p2, Vector2D p3, int steps) + { + if(steps < 0) return null; int totalSteps = steps + 1; Vector2D[] points = new Vector2D[totalSteps]; float step = 1f / steps; float curStep = 0f; - for(int i = 0; i < totalSteps; i++) { + for(int i = 0; i < totalSteps; i++) + { points[i] = GetPointOnQuadraticCurve(p1, p2, p3, curStep); curStep += step; } @@ -225,30 +231,33 @@ namespace CodeImp.DoomBuilder.Geometry return points; } - public static void CreateCubicCurve(CurveSegment segment, int steps) { + public static void CreateCubicCurve(CurveSegment segment, int steps) + { segment.CurveType = CurveSegmentType.CUBIC; segment.Points = GetCubicCurve(segment.Start, segment.End, segment.CPStart, segment.CPEnd, steps); segment.UpdateLength(); } //this returns array of Vector2D to draw 4-point bezier curve - public static Vector2D[] GetCubicCurve(Vector2D p1, Vector2D p2, Vector2D cp1, Vector2D cp2, int steps) { - if(steps < 0) - return null; + public static Vector2D[] GetCubicCurve(Vector2D p1, Vector2D p2, Vector2D cp1, Vector2D cp2, int steps) + { + if(steps < 0) return null; int totalSteps = steps + 1; Vector2D[] points = new Vector2D[totalSteps]; float step = 1f / steps; float curStep = 0f; - for(int i = 0; i < totalSteps; i++) { + for(int i = 0; i < totalSteps; i++) + { points[i] = GetPointOnCubicCurve(p1, p2, cp1, cp2, curStep); curStep += step; } return points; } - public static Vector2D GetPointOnCurve(CurveSegment segment, float delta) { + public static Vector2D GetPointOnCurve(CurveSegment segment, float delta) + { if(segment.CurveType == CurveSegmentType.QUADRATIC) return GetPointOnQuadraticCurve(segment.Start, segment.CPMid, segment.End, delta); @@ -261,7 +270,8 @@ namespace CodeImp.DoomBuilder.Geometry throw new Exception("GetPointOnCurve: got unknown curve type: " + segment.CurveType); } - public static Vector2D GetPointOnQuadraticCurve(Vector2D p1, Vector2D p2, Vector2D p3, float delta) { + public static Vector2D GetPointOnQuadraticCurve(Vector2D p1, Vector2D p2, Vector2D p3, float delta) + { float invDelta = 1f - delta; float m1 = invDelta * invDelta; @@ -274,7 +284,8 @@ namespace CodeImp.DoomBuilder.Geometry return new Vector2D(px, py); } - public static Vector2D GetPointOnCubicCurve(Vector2D p1, Vector2D p2, Vector2D cp1, Vector2D cp2, float delta) { + public static Vector2D GetPointOnCubicCurve(Vector2D p1, Vector2D p2, Vector2D cp1, Vector2D cp2, float delta) + { float invDelta = 1f - delta; float m1 = invDelta * invDelta * invDelta; @@ -289,7 +300,8 @@ namespace CodeImp.DoomBuilder.Geometry } //it's basically 2-point bezier curve - public static Vector2D GetPointOnLine(Vector2D p1, Vector2D p2, float delta) { + public static Vector2D GetPointOnLine(Vector2D p1, Vector2D p2, float delta) + { return new Vector2D((int)((1f - delta) * p1.x + delta * p2.x), (int)((1f - delta) * p1.y + delta * p2.y)); } } @@ -300,29 +312,34 @@ namespace CodeImp.DoomBuilder.Geometry public List Shape; public float Length; - public Curve() { + public Curve() + { Segments = new List(); } - public void UpdateShape() { + public void UpdateShape() + { Shape = new List(); Length = 0; - foreach(CurveSegment segment in Segments) { + foreach(CurveSegment segment in Segments) + { Length += segment.Length; - foreach(Vector2D point in segment.Points) { + foreach(Vector2D point in segment.Points) + { if(Shape.Count == 0 || point != Shape[Shape.Count - 1]) Shape.Add(point); } } - float curDelta = 0; - for(int i = 0; i < Segments.Count; i++) { + /*float curDelta = 0; + for(int i = 0; i < Segments.Count; i++) + { Segments[i].Delta = Segments[i].Length / Length; curDelta += Segments[i].Delta; Segments[i].GlobalDelta = curDelta; - } + }*/ } } @@ -335,11 +352,12 @@ namespace CodeImp.DoomBuilder.Geometry public Vector2D CPMid; public Vector2D CPEnd; public float Length; - public float Delta; //length of this segment / total curve length - public float GlobalDelta; //length of this segment / total curve length + deltas of previous segments + //public float Delta; //length of this segment / total curve length + //public float GlobalDelta; //length of this segment / total curve length + deltas of previous segments public CurveSegmentType CurveType; - public void UpdateLength() { + public void UpdateLength() + { if(Points.Length < 2) return; diff --git a/Source/Core/Geometry/Line2D.cs b/Source/Core/Geometry/Line2D.cs index 8d6a1927..fe983a18 100644 --- a/Source/Core/Geometry/Line2D.cs +++ b/Source/Core/Geometry/Line2D.cs @@ -91,7 +91,8 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. This tests if given lines intersects - public static bool GetIntersection(Line2D line1, Line2D line2) { + public static bool GetIntersection(Line2D line1, Line2D line2) + { return GetIntersection(line1.v1, line1.v2, line2.v1.x, line2.v1.y, line2.v2.x, line2.v2.y); } diff --git a/Source/Core/Geometry/LinedefSide.cs b/Source/Core/Geometry/LinedefSide.cs index 04de4d61..8d797b4f 100644 --- a/Source/Core/Geometry/LinedefSide.cs +++ b/Source/Core/Geometry/LinedefSide.cs @@ -104,14 +104,15 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. Addeed to make compiler a bit more happy... - public override int GetHashCode() { + public override int GetHashCode() + { return base.GetHashCode(); } //mxd. Addeed to make compiler a bit more happy... - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if(object.Equals(obj, null)) return false; - LinedefSide other = (LinedefSide)obj; return (this.line == other.line) && (this.front == other.front); } diff --git a/Source/Core/Geometry/ProjectedFrustum2D.cs b/Source/Core/Geometry/ProjectedFrustum2D.cs index 61e680d1..a19f617e 100644 --- a/Source/Core/Geometry/ProjectedFrustum2D.cs +++ b/Source/Core/Geometry/ProjectedFrustum2D.cs @@ -146,15 +146,6 @@ namespace CodeImp.DoomBuilder.Geometry return true; } - //mxd - /*public bool IntersectPoint(Vector2D point) { - for (int i = 0; i < lines.Length; i++) { - if (lines[i].GetSideOfLine(point) < 0) - return false; - } - return true; - }*/ - #endregion } } diff --git a/Source/Core/Geometry/Tools.cs b/Source/Core/Geometry/Tools.cs index e4fbc58f..74709ecf 100644 --- a/Source/Core/Geometry/Tools.cs +++ b/Source/Core/Geometry/Tools.cs @@ -291,11 +291,15 @@ namespace CodeImp.DoomBuilder.Geometry float px = foundv.Position.x; //mxd float py = foundv.Position.y; //mxd - foreach(Linedef ld in General.Map.Map.Linedefs) { + foreach(Linedef ld in General.Map.Map.Linedefs) + { // Line to the right of start point? - if((ld.Start.Position.x > px) || (ld.End.Position.x > px)) { + if((ld.Start.Position.x > px) || (ld.End.Position.x > px)) + { // Line intersecting the y axis? - if((ld.Start.Position.y >= py && ld.End.Position.y <= py) || (ld.Start.Position.y <= py && ld.End.Position.y >= py)) { //mxd + if((ld.Start.Position.y >= py && ld.End.Position.y <= py) + || (ld.Start.Position.y <= py && ld.End.Position.y >= py)) //mxd + { // Check if this linedef intersects our test line at a closer range float thisu; ld.Line.GetIntersection(testline, out thisu); @@ -519,7 +523,8 @@ namespace CodeImp.DoomBuilder.Geometry sourcesector.CopyPropertiesTo(newsector); //mxd. Apply overrides - if(useOverrides) { + if(useOverrides) + { if (General.Map.Options.OverrideCeilingTexture) newsector.SetCeilTexture(General.Map.Options.DefaultCeilingTexture); if (General.Map.Options.OverrideFloorTexture) newsector.SetFloorTexture(General.Map.Options.DefaultFloorTexture); if (General.Map.Options.OverrideCeilingHeight) newsector.CeilHeight = General.Map.Options.CustomCeilingHeight; @@ -636,29 +641,35 @@ namespace CodeImp.DoomBuilder.Geometry //Most of the logic is taken from MakeSectorsMode. //Vector2D is sector's center BEFORE sides were removed. //See VerticesMode.DeleteItem() for usage example - public static void MergeInvalidSectors(Dictionary toMerge) { - foreach(KeyValuePair group in toMerge) { - if(!group.Key.IsDisposed && group.Key.Sidedefs.Count > 0 && group.Key.Sidedefs.Count < 3) { + public static void MergeInvalidSectors(Dictionary toMerge) + { + foreach(KeyValuePair group in toMerge) + { + if(!group.Key.IsDisposed && group.Key.Sidedefs.Count > 0 && group.Key.Sidedefs.Count < 3) + { group.Key.Dispose(); List sides = Tools.FindPotentialSectorAt(group.Value); - if(sides != null) { + if(sides != null) + { // Mark the lines we are going to use for this sector General.Map.Map.ClearAllMarks(true); - foreach(LinedefSide ls in sides) - ls.Line.Marked = false; + foreach(LinedefSide ls in sides) ls.Line.Marked = false; List oldlines = General.Map.Map.GetMarkedLinedefs(true); // Make the sector Sector s = Tools.MakeSector(sides, oldlines, false); - if(s != null) { + if(s != null) + { // Now we go for all the lines along the sector to // see if they only have a back side. In that case we want // to flip the linedef to that it only has a front side. - foreach(Sidedef sd in s.Sidedefs) { - if((sd.Line.Front == null) && (sd.Line.Back != null)) { + foreach(Sidedef sd in s.Sidedefs) + { + if((sd.Line.Front == null) && (sd.Line.Back != null)) + { // Flip linedef sd.Line.FlipVertices(); sd.Line.FlipSidedefs(); @@ -711,7 +722,8 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. This applies overrides to a sidedef - private static void ApplyOverridesToSidedef(Sidedef sd) { + private static void ApplyOverridesToSidedef(Sidedef sd) + { if (General.Map.Options.OverrideTopTexture) sd.SetTextureHigh(General.Map.Options.DefaultTopTexture); if(sd.MiddleRequired() && General.Map.Options.OverrideMiddleTexture) sd.SetTextureMid(General.Map.Options.DefaultWallTexture); if(General.Map.Options.OverrideBottomTexture) sd.SetTextureLow(General.Map.Options.DefaultBottomTexture); @@ -917,15 +929,19 @@ namespace CodeImp.DoomBuilder.Geometry Dictionary processed = new Dictionary(); //mxd //mxd - foreach (Sector s in map.Sectors) { + foreach (Sector s in map.Sectors) + { //line intersects with sector's bounding box? - if((MapSet.GetCSFieldBits(measureline.v1, s.BBox) & MapSet.GetCSFieldBits(measureline.v2, s.BBox)) == 0) { - foreach (Sidedef side in s.Sidedefs) { + if((MapSet.GetCSFieldBits(measureline.v1, s.BBox) & MapSet.GetCSFieldBits(measureline.v2, s.BBox)) == 0) + { + foreach (Sidedef side in s.Sidedefs) + { if(processed.ContainsKey(side.Line)) continue; if(side.Line == ld) continue; float u; - if(side.Line.Line.GetIntersection(measureline, out u)) { + if(side.Line.Line.GetIntersection(measureline, out u)) + { if(float.IsNaN(u) || (u <= 0.0f) || (u >= 1.0f)) continue; intersections.Add(u); } @@ -1433,14 +1449,17 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. Apply texture overrides - if (useOverrides && !General.Settings.AutoClearSidedefTextures) { + if (useOverrides && !General.Settings.AutoClearSidedefTextures) + { //if new sectors are created, apply overrides to the sides of these sectors, otherwise, apply overrides to all new lines - if (insidesides.Count > 0) { - foreach(Sidedef side in insidesides) { - ApplyOverridesToSidedef(side); - } - } else { - foreach(Linedef l in newlines) { + if (insidesides.Count > 0) + { + foreach(Sidedef side in insidesides) ApplyOverridesToSidedef(side); + } + else + { + foreach(Linedef l in newlines) + { if(l.IsDisposed) continue; if(!newverts.Contains(l.Start) || !newverts.Contains(l.End)) continue; ApplyOverridesToSidedef(l.Front); @@ -1450,26 +1469,31 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. Auto-align new lines - if(autoAlignTextureOffsets && newlines.Count > 1 && !splittingonly) { + if(autoAlignTextureOffsets && newlines.Count > 1 && !splittingonly) + { List> strips = new List>(); strips.Add(new List { newlines[0] }); - for(int i = 1; i < newlines.Count; i++) { + for(int i = 1; i < newlines.Count; i++) + { //skip double-sided line if it doesn't have lower or upper parts or they are not part of newly created sectors - if(newlines[i].Back != null && - (((!newlines[i].Front.LowRequired() && !newlines[i].Front.HighRequired()) || !insidesides.Contains(newlines[i].Front)) - && ((!newlines[i].Back.LowRequired() && !newlines[i].Back.HighRequired()) || !insidesides.Contains(newlines[i].Back)))) + if(newlines[i].Back != null + && (((!newlines[i].Front.LowRequired() && !newlines[i].Front.HighRequired()) || !insidesides.Contains(newlines[i].Front)) + && ((!newlines[i].Back.LowRequired() && !newlines[i].Back.HighRequired()) || !insidesides.Contains(newlines[i].Back)))) continue; bool added = false; - foreach(List strip in strips) { - if(newlines[i].Start == strip[0].Start || newlines[i].End == strip[0].Start) { + foreach(List strip in strips) + { + if(newlines[i].Start == strip[0].Start || newlines[i].End == strip[0].Start) + { strip.Insert(0, newlines[i]); added = true; break; } - if(newlines[i].Start == strip[strip.Count - 1].End || newlines[i].End == strip[strip.Count - 1].End) { + if(newlines[i].Start == strip[strip.Count - 1].End || newlines[i].End == strip[strip.Count - 1].End) + { strip.Add(newlines[i]); added = true; break; @@ -1479,9 +1503,10 @@ namespace CodeImp.DoomBuilder.Geometry if(!added) strips.Add(new List { newlines[i] }); } - foreach(List strip in strips) { + foreach(List strip in strips) + { if(strip.Count < 2) continue; - autoAlignLinedefStrip(strip); + AutoAlignLinedefStrip(strip); } } } @@ -1497,48 +1522,51 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd - private static void autoAlignLinedefStrip(List strip) { + private static void AutoAlignLinedefStrip(List strip) + { if (strip.Count < 2) return; float totalLength = 0f; foreach(Linedef l in strip) totalLength += l.Length; if(General.Map.UDMF) - autoAlignTexturesOnSidesUDMF(strip, totalLength, (strip[0].End != strip[1].Start)); + AutoAlignTexturesOnSidesUdmf(strip, totalLength, (strip[0].End != strip[1].Start)); else - autoAlignTexturesOnSides(strip, totalLength, (strip[0].End != strip[1].Start)); + AutoAlignTexturesOnSides(strip, totalLength, (strip[0].End != strip[1].Start)); } //mxd - private static void autoAlignTexturesOnSides(List lines, float totalLength, bool reversed) { + private static void AutoAlignTexturesOnSides(List lines, float totalLength, bool reversed) + { float curLength = 0f; - foreach(Linedef l in lines) { - if(l.Front != null) { + foreach(Linedef l in lines) + { + if(l.Front != null) + { ImageData texture = null; - if(l.Front.MiddleRequired() && l.Front.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongMiddleTexture)) { + if(l.Front.MiddleRequired() && l.Front.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongMiddleTexture)) texture = General.Map.Data.GetTextureImage(l.Front.LongMiddleTexture); - } else if(l.Front.HighRequired() && l.Front.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongHighTexture)) { + else if(l.Front.HighRequired() && l.Front.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongHighTexture)) texture = General.Map.Data.GetTextureImage(l.Front.LongHighTexture); - } else if(l.Front.LowRequired() && l.Front.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongLowTexture)) { + else if(l.Front.LowRequired() && l.Front.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongLowTexture)) texture = General.Map.Data.GetTextureImage(l.Front.LongLowTexture); - } if(texture != null) l.Front.OffsetX = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; } - if(l.Back != null) { + if(l.Back != null) + { ImageData texture = null; - if(l.Back.MiddleRequired() && l.Back.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongMiddleTexture)) { + if(l.Back.MiddleRequired() && l.Back.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongMiddleTexture)) texture = General.Map.Data.GetTextureImage(l.Back.LongMiddleTexture); - } else if(l.Back.HighRequired() && l.Back.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongHighTexture)) { + else if(l.Back.HighRequired() && l.Back.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongHighTexture)) texture = General.Map.Data.GetTextureImage(l.Back.LongHighTexture); - } else if(l.Back.LowRequired() && l.Back.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongLowTexture)) { + else if(l.Back.LowRequired() && l.Back.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongLowTexture)) texture = General.Map.Data.GetTextureImage(l.Back.LongLowTexture); - } if(texture != null) l.Back.OffsetX = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; @@ -1549,26 +1577,32 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd - private static void autoAlignTexturesOnSidesUDMF(List lines, float totalLength, bool reversed) { + private static void AutoAlignTexturesOnSidesUdmf(List lines, float totalLength, bool reversed) + { float curLength = 0f; - foreach(Linedef l in lines) { - if(l.Front != null) { - if(l.Front.MiddleRequired() && l.Front.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongMiddleTexture)) { + foreach(Linedef l in lines) + { + if(l.Front != null) + { + if(l.Front.MiddleRequired() && l.Front.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongMiddleTexture)) + { ImageData texture = General.Map.Data.GetTextureImage(l.Front.LongMiddleTexture); float offset = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; if(offset > 0) UDMFTools.SetFloat(l.Front.Fields, "offsetx_mid", offset); } - if(l.Front.HighRequired() && l.Front.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongHighTexture)) { + if(l.Front.HighRequired() && l.Front.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongHighTexture)) + { ImageData texture = General.Map.Data.GetTextureImage(l.Front.LongHighTexture); float offset = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; if(offset > 0) UDMFTools.SetFloat(l.Front.Fields, "offsetx_top", offset); } - if(l.Front.LowRequired() && l.Front.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongLowTexture)) { + if(l.Front.LowRequired() && l.Front.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Front.LongLowTexture)) + { ImageData texture = General.Map.Data.GetTextureImage(l.Front.LongLowTexture); float offset = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; @@ -1576,22 +1610,26 @@ namespace CodeImp.DoomBuilder.Geometry } } - if(l.Back != null) { - if(l.Back.MiddleRequired() && l.Back.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongMiddleTexture)) { + if(l.Back != null) + { + if(l.Back.MiddleRequired() && l.Back.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongMiddleTexture)) + { ImageData texture = General.Map.Data.GetTextureImage(l.Back.LongMiddleTexture); float offset = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; if(offset > 0) UDMFTools.SetFloat(l.Back.Fields, "offsetx_mid", offset); } - if(l.Back.HighRequired() && l.Back.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongHighTexture)) { + if(l.Back.HighRequired() && l.Back.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongHighTexture)) + { ImageData texture = General.Map.Data.GetTextureImage(l.Back.LongHighTexture); float offset = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; if(offset > 0) UDMFTools.SetFloat(l.Back.Fields, "offsetx_top", offset); } - if(l.Back.LowRequired() && l.Back.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongLowTexture)) { + if(l.Back.LowRequired() && l.Back.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(l.Back.LongLowTexture)) + { ImageData texture = General.Map.Data.GetTextureImage(l.Back.LongLowTexture); float offset = (int)Math.Round((reversed ? totalLength - curLength - l.Length : curLength)) % texture.Width; @@ -1896,18 +1934,23 @@ namespace CodeImp.DoomBuilder.Geometry #region ================== Thing Alignment (mxd) - public static bool TryAlignThingToLine(Thing t, Linedef l) { - if(l.Back == null) { - if(canAlignThingTo(t, l.Front.Sector)){ - alignThingToLine(t, l, true); + public static bool TryAlignThingToLine(Thing t, Linedef l) + { + if(l.Back == null) + { + if(CanAlignThingTo(t, l.Front.Sector)) + { + AlignThingToLine(t, l, true); return true; } return false; } - if(l.Front == null ) { - if(canAlignThingTo(t, l.Back.Sector)) { - alignThingToLine(t, l, false); + if(l.Front == null ) + { + if(CanAlignThingTo(t, l.Back.Sector)) + { + AlignThingToLine(t, l, false); return true; } return false; @@ -1915,15 +1958,20 @@ namespace CodeImp.DoomBuilder.Geometry float side = l.SideOfLine(t.Position); - if(side == 0) { //already on line + //already on line + if(side == 0) + { t.Rotate(General.ClampAngle(180 + l.AngleDeg)); return true; } - if(side < 0) { //thing is on front side of the line + //thing is on front side of the line + if(side < 0) + { //got any walls to align to? - if(canAlignThingTo(t, l.Front.Sector, l.Back.Sector)) { - alignThingToLine(t, l, true); + if(CanAlignThingTo(t, l.Front.Sector, l.Back.Sector)) + { + AlignThingToLine(t, l, true); return true; } @@ -1932,8 +1980,9 @@ namespace CodeImp.DoomBuilder.Geometry //thing is on back side of the line //got any walls to align to? - if(canAlignThingTo(t, l.Back.Sector, l.Front.Sector)) { - alignThingToLine(t, l, false); + if(CanAlignThingTo(t, l.Back.Sector, l.Front.Sector)) + { + AlignThingToLine(t, l, false); return true; } @@ -1941,18 +1990,21 @@ namespace CodeImp.DoomBuilder.Geometry } // Checks if there's a wall at appropriate height to align thing to - private static bool canAlignThingTo(Thing t, Sector front, Sector back) { + private static bool CanAlignThingTo(Thing t, Sector front, Sector back) + { ThingTypeInfo ti = General.Map.Data.GetThingInfo(t.Type); int absz = GetThingAbsoluteZ(t, ti); int height = ti.Height == 0 ? 1 : (int)ti.Height; Rectangle thing = new Rectangle(0, ti.Hangs ? absz - height : absz, 1, height); - if(front.FloorHeight < back.FloorHeight) { + if(front.FloorHeight < back.FloorHeight) + { Rectangle lower = new Rectangle(0, front.FloorHeight, 1, back.FloorHeight - front.FloorHeight); if(thing.IntersectsWith(lower)) return true; } - if(front.CeilHeight > back.CeilHeight) { + if(front.CeilHeight > back.CeilHeight) + { Rectangle upper = new Rectangle(0, back.CeilHeight, 1, front.CeilHeight - back.CeilHeight); if(thing.IntersectsWith(upper)) return true; } @@ -1961,7 +2013,8 @@ namespace CodeImp.DoomBuilder.Geometry } // Checks if there's a wall at appropriate height to align thing to - private static bool canAlignThingTo(Thing t, Sector sector) { + private static bool CanAlignThingTo(Thing t, Sector sector) + { ThingTypeInfo ti = General.Map.Data.GetThingInfo(t.Type); int absz = GetThingAbsoluteZ(t, ti); Rectangle thing = new Rectangle(0, absz, 1, ti.Height == 0 ? 1 : (int)ti.Height); @@ -1970,7 +2023,8 @@ namespace CodeImp.DoomBuilder.Geometry return thing.IntersectsWith(middle); } - private static void alignThingToLine(Thing t, Linedef l, bool front) { + private static void AlignThingToLine(Thing t, Linedef l, bool front) + { //get aligned position Vector2D pos = l.NearestOnLine(t.Position); Sector initialSector = t.Sector; @@ -1987,11 +2041,13 @@ namespace CodeImp.DoomBuilder.Geometry t.Rotate(General.ClampAngle(front ? 180 + l.AngleDeg : l.AngleDeg)); //keep thing height constant - if(initialSector != t.Sector && General.Map.FormatInterface.HasThingHeight) { + if(initialSector != t.Sector && General.Map.FormatInterface.HasThingHeight) + { ThingTypeInfo ti = General.Map.Data.GetThingInfo(t.Type); if(ti.AbsoluteZ) return; - if(ti.Hangs && initialSector.CeilHeight != t.Sector.CeilHeight) { + if(ti.Hangs && initialSector.CeilHeight != t.Sector.CeilHeight) + { t.Move(t.Position.x, t.Position.y, t.Position.z - (initialSector.CeilHeight - t.Sector.CeilHeight)); return; } @@ -2001,11 +2057,13 @@ namespace CodeImp.DoomBuilder.Geometry } } - public static int GetThingAbsoluteZ(Thing t, ThingTypeInfo ti) { + public static int GetThingAbsoluteZ(Thing t, ThingTypeInfo ti) + { // Determine z info if(ti.AbsoluteZ) return (int)t.Position.z; - if(t.Sector != null) { + if(t.Sector != null) + { // Hangs from ceiling? if(ti.Hangs) return (int)(t.Sector.CeilHeight - t.Position.z - ti.Height); @@ -2085,9 +2143,11 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd - public static int GetDropDownWidth(ComboBox cb) { + public static int GetDropDownWidth(ComboBox cb) + { int maxWidth = 0, temp; - foreach(var obj in cb.Items) { + foreach(var obj in cb.Items) + { temp = TextRenderer.MeasureText(obj.ToString(), cb.Font).Width; if(temp > maxWidth) maxWidth = temp; } diff --git a/Source/Core/Geometry/Triangulation.cs b/Source/Core/Geometry/Triangulation.cs index 1ceb8f32..a9a3614d 100644 --- a/Source/Core/Geometry/Triangulation.cs +++ b/Source/Core/Geometry/Triangulation.cs @@ -439,7 +439,7 @@ namespace CodeImp.DoomBuilder.Geometry } // This takes an outer polygon and a set of inner polygons to start cutting on - private void MergeInnerPolys(EarClipPolygon p) + private static void MergeInnerPolys(EarClipPolygon p) { LinkedList todo = new LinkedList(p.Children); LinkedListNode start; @@ -795,7 +795,7 @@ namespace CodeImp.DoomBuilder.Geometry } // This checks if a given ear is a valid (no intersections from reflex vertices) - private bool CheckValidEar(EarClipVertex[] t, LinkedList reflexes) + private static bool CheckValidEar(EarClipVertex[] t, LinkedList reflexes) { // Go for all reflex vertices foreach(EarClipVertex rv in reflexes) diff --git a/Source/Core/Geometry/Vector2D.cs b/Source/Core/Geometry/Vector2D.cs index d7068c14..b23f2bf2 100644 --- a/Source/Core/Geometry/Vector2D.cs +++ b/Source/Core/Geometry/Vector2D.cs @@ -348,12 +348,14 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. Addeed to make compiler a bit more happy... - public override int GetHashCode() { + public override int GetHashCode() + { return base.GetHashCode(); } //mxd. Addeed to make compiler a bit more happy... - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if (!(obj is Vector2D)) return false; Vector2D other = (Vector2D)obj; diff --git a/Source/Core/Geometry/Vector3D.cs b/Source/Core/Geometry/Vector3D.cs index b4535349..cdd2fa30 100644 --- a/Source/Core/Geometry/Vector3D.cs +++ b/Source/Core/Geometry/Vector3D.cs @@ -325,12 +325,14 @@ namespace CodeImp.DoomBuilder.Geometry } //mxd. Addeed to make compiler a bit more happy... - public override int GetHashCode() { + public override int GetHashCode() + { return base.GetHashCode(); } //mxd. Addeed to make compiler a bit more happy... - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if (!(obj is Vector3D)) return false; Vector3D other = (Vector3D)obj; diff --git a/Source/Core/IO/ClipboardStreamReader.cs b/Source/Core/IO/ClipboardStreamReader.cs index a7cc5f1c..4330e23b 100644 --- a/Source/Core/IO/ClipboardStreamReader.cs +++ b/Source/Core/IO/ClipboardStreamReader.cs @@ -42,7 +42,8 @@ namespace CodeImp.DoomBuilder.IO #region ================== Reading // This reads from a stream - public MapSet Read(MapSet map, Stream stream) { + public MapSet Read(MapSet map, Stream stream) + { BinaryReader reader = new BinaryReader(stream); // Read the map @@ -56,7 +57,8 @@ namespace CodeImp.DoomBuilder.IO return map; } - private Dictionary ReadVertices(MapSet map, BinaryReader reader) { + private static Dictionary ReadVertices(MapSet map, BinaryReader reader) + { int count = reader.ReadInt32(); // Create lookup table @@ -64,7 +66,8 @@ namespace CodeImp.DoomBuilder.IO // Go for all collections map.SetCapacity(map.Vertices.Count + count, 0, 0, 0, 0); - for(int i = 0; i < count; i++) { + for(int i = 0; i < count; i++) + { float x = reader.ReadSingle(); float y = reader.ReadSingle(); float zc = reader.ReadSingle(); @@ -73,14 +76,16 @@ namespace CodeImp.DoomBuilder.IO // Create new item Dictionary fields = ReadCustomFields(reader); Vertex v = map.CreateVertex(new Vector2D(x, y)); - if(v != null) { + if(v != null) + { //zoffsets v.ZCeiling = zc; v.ZFloor = zf; // Add custom fields v.Fields.BeforeFieldsChange(); - foreach (KeyValuePair group in fields) { + foreach (KeyValuePair group in fields) + { v.Fields.Add(group.Key, group.Value); } @@ -93,7 +98,8 @@ namespace CodeImp.DoomBuilder.IO return link; } - private Dictionary ReadSectors(MapSet map, BinaryReader reader) { + private static Dictionary ReadSectors(MapSet map, BinaryReader reader) + { int count = reader.ReadInt32(); // Create lookup table @@ -102,7 +108,8 @@ namespace CodeImp.DoomBuilder.IO // Go for all collections map.SetCapacity(0, 0, 0, map.Sectors.Count + count, 0); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { int tag = reader.ReadInt32(); int effect = reader.ReadInt32(); int hfloor = reader.ReadInt32(); @@ -120,11 +127,11 @@ namespace CodeImp.DoomBuilder.IO //flags Dictionary stringflags = new Dictionary(StringComparer.Ordinal); int numFlags = reader.ReadInt32(); - for(int f = 0; f < numFlags; f++) - stringflags.Add(ReadString(reader), true); + for(int f = 0; f < numFlags; f++) stringflags.Add(ReadString(reader), true); //add missing flags - foreach (KeyValuePair flag in General.Map.Config.SectorFlags) { + foreach (KeyValuePair flag in General.Map.Config.SectorFlags) + { if(stringflags.ContainsKey(flag.Key)) continue; stringflags.Add(flag.Key, false); } @@ -132,12 +139,14 @@ namespace CodeImp.DoomBuilder.IO // Create new item Dictionary fields = ReadCustomFields(reader); Sector s = map.CreateSector(); - if(s != null) { + if(s != null) + { s.Update(hfloor, hceil, tfloor, tceil, effect, stringflags, tag, bright, foffset, fslope, coffset, cslope); // Add custom fields s.Fields.BeforeFieldsChange(); - foreach(KeyValuePair group in fields) { + foreach(KeyValuePair group in fields) + { s.Fields.Add(group.Key, group.Value); } @@ -151,12 +160,14 @@ namespace CodeImp.DoomBuilder.IO } // This reads the linedefs and sidedefs - private void ReadLinedefs(MapSet map, BinaryReader reader, Dictionary vertexlink, Dictionary sectorlink, Dictionary sidedeflink) { + private static void ReadLinedefs(MapSet map, BinaryReader reader, Dictionary vertexlink, Dictionary sectorlink, Dictionary sidedeflink) + { int count = reader.ReadInt32(); // Go for all lines map.SetCapacity(0, map.Linedefs.Count + count, map.Sidedefs.Count + sidedeflink.Count, 0, 0); - for(int i = 0; i < count; i++) { + for(int i = 0; i < count; i++) + { int[] args = new int[Linedef.NUM_ARGS]; int tag = reader.ReadInt32(); int v1 = reader.ReadInt32(); @@ -164,24 +175,23 @@ namespace CodeImp.DoomBuilder.IO int s1 = reader.ReadInt32(); int s2 = reader.ReadInt32(); int special = reader.ReadInt32(); - for(int a = 0; a < Linedef.NUM_ARGS; a++) { - args[a] = reader.ReadInt32(); - } + for(int a = 0; a < Linedef.NUM_ARGS; a++) args[a] = reader.ReadInt32(); //flags Dictionary stringflags = new Dictionary(StringComparer.Ordinal); int numFlags = reader.ReadInt32(); - for(int f = 0; f < numFlags; f++) - stringflags.Add(ReadString(reader), true); + for(int f = 0; f < numFlags; f++) stringflags.Add(ReadString(reader), true); //add missing flags - foreach(KeyValuePair flag in General.Map.Config.LinedefFlags) { + foreach(KeyValuePair flag in General.Map.Config.LinedefFlags) + { if(stringflags.ContainsKey(flag.Key)) continue; stringflags.Add(flag.Key, false); } //add missing activations - foreach (LinedefActivateInfo activate in General.Map.Config.LinedefActivates) { + foreach (LinedefActivateInfo activate in General.Map.Config.LinedefActivates) + { if(stringflags.ContainsKey(activate.Key)) continue; stringflags.Add(activate.Key, false); } @@ -190,62 +200,77 @@ namespace CodeImp.DoomBuilder.IO Dictionary fields = ReadCustomFields(reader); // Check if not zero-length - if (Vector2D.ManhattanDistance(vertexlink[v1].Position, vertexlink[v2].Position) > 0.0001f) { + if (Vector2D.ManhattanDistance(vertexlink[v1].Position, vertexlink[v2].Position) > 0.0001f) + { // Create new linedef Linedef l = map.CreateLinedef(vertexlink[v1], vertexlink[v2]); - if (l != null) { + if (l != null) + { l.Update(stringflags, 0, tag, special, args); l.UpdateCache(); // Add custom fields l.Fields.BeforeFieldsChange(); - foreach(KeyValuePair group in fields) { + foreach(KeyValuePair group in fields) + { l.Fields.Add(group.Key, group.Value); } // Connect sidedefs to the line - if(s1 > -1) { + if(s1 > -1) + { if(s1 < sidedeflink.Count) AddSidedef(map, sidedeflink[s1], l, true, sectorlink); else General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references invalid front sidedef " + s1 + ". Sidedef has been removed."); } - if(s2 > -1) { + if(s2 > -1) + { if(s2 < sidedeflink.Count) AddSidedef(map, sidedeflink[s2], l, false, sectorlink); else General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references invalid back sidedef " + s1 + ". Sidedef has been removed."); } } - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " is zero-length. Linedef has been removed."); } } } - private static void AddSidedef(MapSet map, SidedefData data, Linedef ld, bool front, Dictionary sectorlink) { + private static void AddSidedef(MapSet map, SidedefData data, Linedef ld, bool front, Dictionary sectorlink) + { // Create sidedef - if(sectorlink.ContainsKey(data.SectorID)) { + if(sectorlink.ContainsKey(data.SectorID)) + { Sidedef s = map.CreateSidedef(ld, front, sectorlink[data.SectorID]); - if(s != null) { + if(s != null) + { s.Update(data.OffsetX, data.OffsetY, data.HighTexture, data.MiddleTexture, data.LowTexture, data.Flags); // Add custom fields - foreach (KeyValuePair group in data.Fields) { + foreach (KeyValuePair group in data.Fields) + { s.Fields.Add(group.Key, group.Value); } } - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Warning, "Sidedef references invalid sector " + data.SectorID + ". Sidedef has been removed."); } } - private Dictionary ReadSidedefs(BinaryReader reader) { + private static Dictionary ReadSidedefs(BinaryReader reader) + { Dictionary sidedeflink = new Dictionary(); int count = reader.ReadInt32(); - for(int i = 0; i < count; i++) { + for(int i = 0; i < count; i++) + { SidedefData data = new SidedefData(); data.OffsetX = reader.ReadInt32(); data.OffsetY = reader.ReadInt32(); @@ -262,26 +287,28 @@ namespace CodeImp.DoomBuilder.IO data.Flags.Add(ReadString(reader), true); //add missing flags - foreach(KeyValuePair flag in General.Map.Config.SidedefFlags) { + foreach(KeyValuePair flag in General.Map.Config.SidedefFlags) + { if(data.Flags.ContainsKey(flag.Key)) continue; data.Flags.Add(flag.Key, false); } //custom fields data.Fields = ReadCustomFields(reader); - sidedeflink.Add(i, data); } return sidedeflink; } - private void ReadThings(MapSet map, BinaryReader reader) { + private static void ReadThings(MapSet map, BinaryReader reader) + { int count = reader.ReadInt32(); // Go for all collections map.SetCapacity(0, 0, 0, 0, map.Things.Count + count); - for(int i = 0; i < count; i++) { + for(int i = 0; i < count; i++) + { int[] args = new int[Linedef.NUM_ARGS]; int tag = reader.ReadInt32(); float x = reader.ReadSingle(); @@ -294,18 +321,16 @@ namespace CodeImp.DoomBuilder.IO float scaleY = reader.ReadSingle(); //mxd int type = reader.ReadInt32(); int special = reader.ReadInt32(); - for(int a = 0; a < Linedef.NUM_ARGS; a++) { - args[a] = reader.ReadInt32(); - } + for(int a = 0; a < Linedef.NUM_ARGS; a++) args[a] = reader.ReadInt32(); //flags Dictionary stringflags = new Dictionary(StringComparer.Ordinal); int numFlags = reader.ReadInt32(); - for(int f = 0; f < numFlags; f++) - stringflags.Add(ReadString(reader), true); + for(int f = 0; f < numFlags; f++) stringflags.Add(ReadString(reader), true); //add missing flags - foreach(KeyValuePair flag in General.Map.Config.ThingFlags) { + foreach(KeyValuePair flag in General.Map.Config.ThingFlags) + { if(stringflags.ContainsKey(flag.Key)) continue; stringflags.Add(flag.Key, false); } @@ -313,28 +338,33 @@ namespace CodeImp.DoomBuilder.IO // Create new item Dictionary fields = ReadCustomFields(reader); Thing t = map.CreateThing(); - if(t != null) { + if(t != null) + { t.Update(type, x, y, height, angledeg, pitch, roll, scaleX, scaleY, stringflags, tag, special, args); // Add custom fields t.Fields.BeforeFieldsChange(); - foreach(KeyValuePair group in fields) { + foreach(KeyValuePair group in fields) + { t.Fields.Add(group.Key, group.Value); } } } } - private Dictionary ReadCustomFields(BinaryReader reader) { + private static Dictionary ReadCustomFields(BinaryReader reader) + { Dictionary fields = new Dictionary(StringComparer.Ordinal); int fieldscount = reader.ReadInt32(); - for(int f = 0; f < fieldscount; f++) { + for(int f = 0; f < fieldscount; f++) + { string name = ReadString(reader); UniversalType type = (UniversalType)reader.ReadInt32(); UniversalType valueType = (UniversalType)reader.ReadInt32(); - switch(valueType) { + switch(valueType) + { case UniversalType.Float: fields.Add(name, new UniValue(type, reader.ReadSingle())); break; @@ -359,7 +389,8 @@ namespace CodeImp.DoomBuilder.IO return fields; } - private static string ReadString(BinaryReader reader) { + private static string ReadString(BinaryReader reader) + { int len = reader.ReadInt32(); if (len == 0) return string.Empty; char[] chars = new char[len]; diff --git a/Source/Core/IO/ClipboardStreamWriter.cs b/Source/Core/IO/ClipboardStreamWriter.cs index 20876b41..71ee848f 100644 --- a/Source/Core/IO/ClipboardStreamWriter.cs +++ b/Source/Core/IO/ClipboardStreamWriter.cs @@ -28,15 +28,18 @@ namespace CodeImp.DoomBuilder.IO #region ================== Constructor / Disposer - public ClipboardStreamWriter() { + public ClipboardStreamWriter() + { // Make configurations config = new Configuration(); // Find a resource named UDMF.cfg string[] resnames = General.ThisAssembly.GetManifestResourceNames(); - foreach(string rn in resnames) { + foreach(string rn in resnames) + { // Found it? - if(rn.EndsWith(UDMF_CONFIG_NAME, StringComparison.InvariantCultureIgnoreCase)) { + if(rn.EndsWith(UDMF_CONFIG_NAME, StringComparison.InvariantCultureIgnoreCase)) + { // Get a stream from the resource Stream udmfcfg = General.ThisAssembly.GetManifestResourceStream(rn); StreamReader udmfcfgreader = new StreamReader(udmfcfg, Encoding.ASCII); @@ -80,12 +83,14 @@ namespace CodeImp.DoomBuilder.IO #region ================== Writing - public void Write(MapSet map, Stream stream, bool longtexturenames) { + public void Write(MapSet map, Stream stream, bool longtexturenames) + { Write(map.Vertices, map.Linedefs, map.Sidedefs, map.Sectors, map.Things, stream, longtexturenames); } public void Write(ICollection vertices, ICollection linedefs, ICollection sidedefs, - ICollection sectors, ICollection things, Stream stream, bool longtexturenames) { + ICollection sectors, ICollection things, Stream stream, bool longtexturenames) + { // Create collections Dictionary vertexids = new Dictionary(); Dictionary sidedefids = new Dictionary(); @@ -97,6 +102,7 @@ namespace CodeImp.DoomBuilder.IO foreach(Sector s in sectors) sectorids.Add(s, sectorids.Count); BinaryWriter writer = new BinaryWriter(stream); + // Write the data structures to stream writer.Write(longtexturenames); //mxd WriteVertices(vertices, writer); @@ -107,10 +113,12 @@ namespace CodeImp.DoomBuilder.IO writer.Flush(); } - private void WriteVertices(ICollection vertices, BinaryWriter writer) { + private void WriteVertices(ICollection vertices, BinaryWriter writer) + { writer.Write(vertices.Count); - foreach(Vertex v in vertices) { + foreach(Vertex v in vertices) + { //write "static" properties writer.Write(v.Position.x); writer.Write(v.Position.y); @@ -123,11 +131,13 @@ namespace CodeImp.DoomBuilder.IO } // This adds linedefs - private void WriteLinedefs(ICollection linedefs, BinaryWriter writer, IDictionary sidedefids, IDictionary vertexids) { + private void WriteLinedefs(ICollection linedefs, BinaryWriter writer, IDictionary sidedefids, IDictionary vertexids) + { writer.Write(linedefs.Count); // Go for all linedefs - foreach(Linedef l in linedefs) { + foreach(Linedef l in linedefs) + { //write "static" properties writer.Write(l.Tag); writer.Write(vertexids[l.Start]); @@ -147,11 +157,13 @@ namespace CodeImp.DoomBuilder.IO } // This adds sidedefs - private void WriteSidedefs(ICollection sidedefs, BinaryWriter writer, IDictionary sectorids) { + private void WriteSidedefs(ICollection sidedefs, BinaryWriter writer, IDictionary sectorids) + { writer.Write(sidedefs.Count); // Go for all sidedefs - foreach(Sidedef s in sidedefs) { + foreach(Sidedef s in sidedefs) + { //write "static" properties writer.Write(s.OffsetX); writer.Write(s.OffsetY); @@ -171,11 +183,13 @@ namespace CodeImp.DoomBuilder.IO } // This adds sectors - private void WriteSectors(ICollection sectors, BinaryWriter writer) { + private void WriteSectors(ICollection sectors, BinaryWriter writer) + { writer.Write(sectors.Count); // Go for all sectors - foreach(Sector s in sectors) { + foreach(Sector s in sectors) + { //write "static" properties writer.Write(s.Tag); writer.Write(s.Effect); @@ -205,11 +219,13 @@ namespace CodeImp.DoomBuilder.IO } // This adds things - private void WriteThings(ICollection things, BinaryWriter writer) { + private void WriteThings(ICollection things, BinaryWriter writer) + { writer.Write(things.Count); // Go for all things - foreach(Thing t in things) { + foreach(Thing t in things) + { //write "static" properties writer.Write(t.Tag); writer.Write(t.Position.x); @@ -229,52 +245,67 @@ namespace CodeImp.DoomBuilder.IO } } - private void AddCustomFields(UniFields elementFields, string elementname, BinaryWriter writer) { + private void AddCustomFields(UniFields elementFields, string elementname, BinaryWriter writer) + { Dictionary fields = new Dictionary(StringComparer.Ordinal); - foreach(KeyValuePair f in elementFields) { + foreach(KeyValuePair f in elementFields) + { if(config.SettingExists("managedfields." + elementname + "." + f.Key)) continue; fields.Add(f.Key, f.Value); } writer.Write(fields.Count); - foreach(KeyValuePair f in fields) { + foreach(KeyValuePair f in fields) + { writer.Write(f.Key.Length); writer.Write(f.Key.ToCharArray()); writer.Write(f.Value.Type); - if(f.Value.Value is bool) { + if(f.Value.Value is bool) + { writer.Write((int)UniversalType.Boolean); writer.Write((bool)f.Value.Value); - } else if(f.Value.Value is float) { + } + else if(f.Value.Value is float) + { writer.Write((int)UniversalType.Float); writer.Write((float)f.Value.Value); - } else if(f.Value.Value.GetType().IsPrimitive) { + } + else if(f.Value.Value.GetType().IsPrimitive) + { writer.Write((int)UniversalType.Integer); writer.Write((int)f.Value.Value); - } else if(f.Value.Value is string) { + } + else if(f.Value.Value is string) + { writer.Write((int)UniversalType.String); string s = (string)f.Value.Value; writer.Write(s.Length); writer.Write(s.ToCharArray()); - } else { //WOLOLO! ERRORS! + } + else //WOLOLO! ERRORS! + { General.ErrorLogger.Add(ErrorType.Error, "Unable to copy Universal Field '" + f.Key + "' to clipboard: unknown value type '" + f.Value.Type + "'!"); } } } - private static void AddFlags(Dictionary elementFlags, BinaryWriter writer) { + private static void AddFlags(Dictionary elementFlags, BinaryWriter writer) + { List flags = new List(); - foreach(KeyValuePair f in elementFlags) { + foreach(KeyValuePair f in elementFlags) + { if(!f.Value) continue; flags.Add(f.Key); } writer.Write(flags.Count); - foreach(string s in flags) { + foreach(string s in flags) + { writer.Write(s.Length); writer.Write(s.ToCharArray()); } diff --git a/Source/Core/IO/Configuration.cs b/Source/Core/IO/Configuration.cs index b3e77b25..3e9c7bc6 100644 --- a/Source/Core/IO/Configuration.cs +++ b/Source/Core/IO/Configuration.cs @@ -845,16 +845,21 @@ namespace CodeImp.DoomBuilder.IO string includefile = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar + args[0]; //mxd. Caching - if(cfgcache.ContainsKey(includefile)) { + if(cfgcache.ContainsKey(includefile)) + { IDictionary cinc = cfgcache[includefile]; // Check if a path is given - if((args.Count > 1) && !string.IsNullOrEmpty(args[1].ToString())) { + if((args.Count > 1) && !string.IsNullOrEmpty(args[1].ToString())) + { IDictionary def; if(cs is ListDictionary) def = new ListDictionary(); else def = new Hashtable(); - if(CheckSetting(cinc, args[1].ToString(), DEFAULT_SEPERATOR)) { + if(CheckSetting(cinc, args[1].ToString(), DEFAULT_SEPERATOR)) + { cinc = (IDictionary)ReadAnySetting(cinc, file, line, args[1].ToString(), def, DEFAULT_SEPERATOR); - } else { + } + else + { RaiseError(file, line, "Include missing structure '" + args[1] + "' in file '" + includefile + "'"); return; } @@ -1155,7 +1160,7 @@ namespace CodeImp.DoomBuilder.IO #region ================== Writing // This will create a data structure from the given object - private string OutputStructure(IDictionary cs, int level, string newline, bool whitespace) + private static string OutputStructure(IDictionary cs, int level, string newline, bool whitespace) { string leveltabs = ""; string spacing = ""; diff --git a/Source/Core/IO/DoomColormapReader.cs b/Source/Core/IO/DoomColormapReader.cs index ee735750..a625b751 100644 --- a/Source/Core/IO/DoomColormapReader.cs +++ b/Source/Core/IO/DoomColormapReader.cs @@ -55,10 +55,8 @@ namespace CodeImp.DoomBuilder.IO // This validates the data as doom flat public bool Validate(Stream stream) { - int remainder; - // Check if the data can be divided by 256 (each palette is 256 bytes) - remainder = (int)stream.Length % 256; + int remainder = (int)stream.Length % 256; if(remainder == 0) { // Success when not 0 @@ -83,13 +81,12 @@ namespace CodeImp.DoomBuilder.IO public unsafe Bitmap ReadAsBitmap(Stream stream) { BitmapData bitmapdata; - PixelColorBlock pixeldata; PixelColor* targetdata; int width, height; Bitmap bmp; // Read pixel data - pixeldata = ReadAsPixelData(stream, out width, out height); + PixelColorBlock pixeldata = ReadAsPixelData(stream, out width, out height); if(pixeldata != null) { try @@ -126,20 +123,16 @@ namespace CodeImp.DoomBuilder.IO // Throws exception on failure public unsafe void DrawToPixelData(Stream stream, PixelColor* target, int targetwidth, int targetheight, int x, int y) { - Bitmap bmp; - BitmapData bmpdata; - PixelColor* pixels; int ox, oy, tx, ty; - int width, height; // Get bitmap - bmp = ReadAsBitmap(stream); - width = bmp.Size.Width; - height = bmp.Size.Height; + Bitmap bmp = ReadAsBitmap(stream); + int width = bmp.Size.Width; + int height = bmp.Size.Height; // Lock bitmap pixels - bmpdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - pixels = (PixelColor*)bmpdata.Scan0.ToPointer(); + BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + PixelColor* pixels = (PixelColor*)bmpdata.Scan0.ToPointer(); // Go for all pixels in the original image for(ox = 0; ox < width; ox++) @@ -167,9 +160,6 @@ namespace CodeImp.DoomBuilder.IO // Returns null on failure private unsafe PixelColorBlock ReadAsPixelData(Stream stream, out int width, out int height) { - PixelColorBlock pixeldata; - byte[] bytes; - // Image will be 128x128 width = 128; height = 128; @@ -180,11 +170,11 @@ namespace CodeImp.DoomBuilder.IO #endif // Allocate memory - pixeldata = new PixelColorBlock(width, height); + PixelColorBlock pixeldata = new PixelColorBlock(width, height); pixeldata.Clear(); // Read flat bytes from stream - bytes = new byte[width * height]; + byte[] bytes = new byte[width * height]; stream.Read(bytes, 0, width * height); // Draw blocks using the palette diff --git a/Source/Core/IO/UniversalEntry.cs b/Source/Core/IO/UniversalEntry.cs index 21a86507..5d56675a 100644 --- a/Source/Core/IO/UniversalEntry.cs +++ b/Source/Core/IO/UniversalEntry.cs @@ -64,7 +64,8 @@ namespace CodeImp.DoomBuilder.IO } //mxd - public bool IsValidType(Type t) { + public bool IsValidType(Type t) + { return value.GetType() == t; } diff --git a/Source/Core/IO/UniversalParser.cs b/Source/Core/IO/UniversalParser.cs index 6ca60ef0..a26c4617 100644 --- a/Source/Core/IO/UniversalParser.cs +++ b/Source/Core/IO/UniversalParser.cs @@ -112,7 +112,7 @@ namespace CodeImp.DoomBuilder.IO #region ================== Private Methods // This returns a string added with escape characters - private string EscapedString(string str) + private static string EscapedString(string str) { // Replace the \ with \\ first! str = str.Replace("\\", "\\\\"); diff --git a/Source/Core/IO/UniversalStreamReader.cs b/Source/Core/IO/UniversalStreamReader.cs index 91dc3d99..bfb362ea 100644 --- a/Source/Core/IO/UniversalStreamReader.cs +++ b/Source/Core/IO/UniversalStreamReader.cs @@ -190,23 +190,23 @@ namespace CodeImp.DoomBuilder.IO UniversalCollection c = collections[i]; int[] args = new int[Linedef.NUM_ARGS]; string where = "thing " + i; - float x = GetCollectionEntry(c, "x", true, 0.0f, where); - float y = GetCollectionEntry(c, "y", true, 0.0f, where); - float height = GetCollectionEntry(c, "height", false, 0.0f, where); - int tag = GetCollectionEntry(c, "id", false, 0, where); - int angledeg = GetCollectionEntry(c, "angle", false, 0, where); - int pitch = GetCollectionEntry(c, "pitch", false, 0, where); //mxd - int roll = GetCollectionEntry(c, "roll", false, 0, where); //mxd - float scaleX = GetCollectionEntry(c, "scalex", false, 1.0f, where); //mxd - float scaleY = GetCollectionEntry(c, "scaley", false, 1.0f, where); //mxd - float scale = GetCollectionEntry(c, "scale", false, 0f, where); //mxd - int type = GetCollectionEntry(c, "type", true, 0, where); - int special = GetCollectionEntry(c, "special", false, 0, where); - args[0] = GetCollectionEntry(c, "arg0", false, 0, where); - args[1] = GetCollectionEntry(c, "arg1", false, 0, where); - args[2] = GetCollectionEntry(c, "arg2", false, 0, where); - args[3] = GetCollectionEntry(c, "arg3", false, 0, where); - args[4] = GetCollectionEntry(c, "arg4", false, 0, where); + float x = GetCollectionEntry(c, "x", true, 0.0f, where); + float y = GetCollectionEntry(c, "y", true, 0.0f, where); + float height = GetCollectionEntry(c, "height", false, 0.0f, where); + int tag = GetCollectionEntry(c, "id", false, 0, where); + int angledeg = GetCollectionEntry(c, "angle", false, 0, where); + int pitch = GetCollectionEntry(c, "pitch", false, 0, where); //mxd + int roll = GetCollectionEntry(c, "roll", false, 0, where); //mxd + float scaleX = GetCollectionEntry(c, "scalex", false, 1.0f, where); //mxd + float scaleY = GetCollectionEntry(c, "scaley", false, 1.0f, where); //mxd + float scale = GetCollectionEntry(c, "scale", false, 0f, where); //mxd + int type = GetCollectionEntry(c, "type", true, 0, where); + int special = GetCollectionEntry(c, "special", false, 0, where); + args[0] = GetCollectionEntry(c, "arg0", false, 0, where); + args[1] = GetCollectionEntry(c, "arg1", false, 0, where); + args[2] = GetCollectionEntry(c, "arg2", false, 0, where); + args[3] = GetCollectionEntry(c, "arg3", false, 0, where); + args[4] = GetCollectionEntry(c, "arg4", false, 0, where); if (scale != 0) //mxd { @@ -217,11 +217,11 @@ namespace CodeImp.DoomBuilder.IO // Flags Dictionary stringflags = new Dictionary(StringComparer.Ordinal); foreach(KeyValuePair flag in General.Map.Config.ThingFlags) - stringflags[flag.Key] = GetCollectionEntry(c, flag.Key, false, false, where); + stringflags[flag.Key] = GetCollectionEntry(c, flag.Key, false, false, where); foreach(FlagTranslation ft in General.Map.Config.ThingFlagsTranslation) { foreach(string field in ft.Fields) - stringflags[field] = GetCollectionEntry(c, field, false, false, where); + stringflags[field] = GetCollectionEntry(c, field, false, false, where); } // Create new item @@ -252,37 +252,37 @@ namespace CodeImp.DoomBuilder.IO UniversalCollection lc = linescolls[i]; int[] args = new int[Linedef.NUM_ARGS]; string where = "linedef " + i; - int v1 = GetCollectionEntry(lc, "v1", true, 0, where); - int v2 = GetCollectionEntry(lc, "v2", true, 0, where); + int v1 = GetCollectionEntry(lc, "v1", true, 0, where); + int v2 = GetCollectionEntry(lc, "v2", true, 0, where); if (!vertexlink.ContainsKey(v1) || !vertexlink.ContainsKey(v2)) { //mxd General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references one or more invalid vertices. Linedef has been removed."); continue; } - int tag = GetCollectionEntry(lc, "id", false, 0, where); - int special = GetCollectionEntry(lc, "special", false, 0, where); - args[0] = GetCollectionEntry(lc, "arg0", false, 0, where); - args[1] = GetCollectionEntry(lc, "arg1", false, 0, where); - args[2] = GetCollectionEntry(lc, "arg2", false, 0, where); - args[3] = GetCollectionEntry(lc, "arg3", false, 0, where); - args[4] = GetCollectionEntry(lc, "arg4", false, 0, where); - int s1 = GetCollectionEntry(lc, "sidefront", true, -1, where); - int s2 = GetCollectionEntry(lc, "sideback", false, -1, where); + int tag = GetCollectionEntry(lc, "id", false, 0, where); + int special = GetCollectionEntry(lc, "special", false, 0, where); + args[0] = GetCollectionEntry(lc, "arg0", false, 0, where); + args[1] = GetCollectionEntry(lc, "arg1", false, 0, where); + args[2] = GetCollectionEntry(lc, "arg2", false, 0, where); + args[3] = GetCollectionEntry(lc, "arg3", false, 0, where); + args[4] = GetCollectionEntry(lc, "arg4", false, 0, where); + int s1 = GetCollectionEntry(lc, "sidefront", true, -1, where); + int s2 = GetCollectionEntry(lc, "sideback", false, -1, where); // Flags Dictionary stringflags = new Dictionary(StringComparer.Ordinal); foreach(KeyValuePair flag in General.Map.Config.LinedefFlags) - stringflags[flag.Key] = GetCollectionEntry(lc, flag.Key, false, false, where); + stringflags[flag.Key] = GetCollectionEntry(lc, flag.Key, false, false, where); foreach(FlagTranslation ft in General.Map.Config.LinedefFlagsTranslation) { foreach(string field in ft.Fields) - stringflags[field] = GetCollectionEntry(lc, field, false, false, where); + stringflags[field] = GetCollectionEntry(lc, field, false, false, where); } // Activations foreach(LinedefActivateInfo activate in General.Map.Config.LinedefActivates) - stringflags[activate.Key] = GetCollectionEntry(lc, activate.Key, false, false, where); + stringflags[activate.Key] = GetCollectionEntry(lc, activate.Key, false, false, where); // Check if not zero-length if(Vector2D.ManhattanDistance(vertexlink[v1].Position, vertexlink[v2].Position) > 0.0001f) @@ -338,7 +338,7 @@ namespace CodeImp.DoomBuilder.IO //mxd. Flags Dictionary stringflags = new Dictionary(StringComparer.Ordinal); foreach(KeyValuePair flag in General.Map.Config.SidedefFlags) - stringflags[flag.Key] = GetCollectionEntry(sc, flag.Key, false, false, where); + stringflags[flag.Key] = GetCollectionEntry(sc, flag.Key, false, false, where); // Create sidedef if(sectorlink.ContainsKey(sector)) @@ -432,16 +432,16 @@ namespace CodeImp.DoomBuilder.IO // Read fields UniversalCollection c = collections[i]; string where = "vertex " + i; - float x = GetCollectionEntry(c, "x", true, 0.0f, where); - float y = GetCollectionEntry(c, "y", true, 0.0f, where); + float x = GetCollectionEntry(c, "x", true, 0.0f, where); + float y = GetCollectionEntry(c, "y", true, 0.0f, where); // Create new item Vertex v = map.CreateVertex(new Vector2D(x, y)); if(v != null) { //mxd. zoffsets - v.ZCeiling = GetCollectionEntry(c, "zceiling", false, float.NaN, where); //mxd - v.ZFloor = GetCollectionEntry(c, "zfloor", false, float.NaN, where); //mxd + v.ZCeiling = GetCollectionEntry(c, "zceiling", false, float.NaN, where); //mxd + v.ZFloor = GetCollectionEntry(c, "zfloor", false, float.NaN, where); //mxd // Custom fields ReadCustomFields(c, v, "vertex"); @@ -464,16 +464,20 @@ namespace CodeImp.DoomBuilder.IO foreach(UniversalEntry e in collection) { // mxd. Check if uifield - if(uifields.ContainsKey(elementname) && uifields[elementname].ContainsKey(e.Key)) { + if(uifields.ContainsKey(elementname) && uifields[elementname].ContainsKey(e.Key)) + { int type = (int)uifields[elementname][e.Key]; //mxd. Check type object value = e.Value; // Let's be kind and cast any int to a float if needed - if(type == (int)UniversalType.Float && e.Value is int) { + if(type == (int)UniversalType.Float && e.Value is int) + { value = (float)(int)e.Value; - } else if(!e.IsValidType(e.Value.GetType())) { + } + else if(!e.IsValidType(e.Value.GetType())) + { General.ErrorLogger.Add(ErrorType.Warning, element + ": the value of entry '" + e.Key + "' is of incompatible type (expected " + e.GetType().Name + ", but got " + e.Value.GetType().Name + "). If you save the map, this value will be ignored."); continue; } @@ -487,16 +491,21 @@ namespace CodeImp.DoomBuilder.IO int type = (int)UniversalType.Integer; //mxd. Try to find the type from configuration - if(setknowncustomtypes) { + if(setknowncustomtypes) + { type = General.Map.Config.ReadSetting("universalfields." + elementname + "." + e.Key + ".type", -1); - if(type != -1) { + if(type != -1) + { object value = e.Value; // Let's be kind and cast any int to a float if needed - if(type == (int)UniversalType.Float && e.Value is int) { + if(type == (int)UniversalType.Float && e.Value is int) + { value = (float)(int)e.Value; - } else if(!e.IsValidType(e.Value.GetType())) { + } + else if(!e.IsValidType(e.Value.GetType())) + { General.ErrorLogger.Add(ErrorType.Warning, element + ": the value of entry '" + e.Key + "' is of incompatible type (expected " + e.GetType().Name + ", but got " + e.Value.GetType().Name + "). If you save the map, this value will be ignored."); continue; } @@ -520,7 +529,7 @@ namespace CodeImp.DoomBuilder.IO } // This validates and returns an entry - private T GetCollectionEntry(UniversalCollection c, string entryname, bool required, T defaultvalue, string where) + private static T GetCollectionEntry(UniversalCollection c, string entryname, bool required, T defaultvalue, string where) { T result = default(T); bool found = false; @@ -568,12 +577,13 @@ namespace CodeImp.DoomBuilder.IO } // This makes a list of all collections with the given name - private List GetNamedCollections(UniversalCollection collection, string entryname) + private static List GetNamedCollections(UniversalCollection collection, string entryname) { List list = new List(); // Make list - foreach (UniversalEntry e in collection) { + foreach (UniversalEntry e in collection) + { if (!(e.Value is UniversalCollection) || (e.Key != entryname)) continue; //mxd list.Add(e.Value as UniversalCollection); } diff --git a/Source/Core/Map/BlockMap.cs b/Source/Core/Map/BlockMap.cs index 4d1f1d44..b0544441 100644 --- a/Source/Core/Map/BlockMap.cs +++ b/Source/Core/Map/BlockMap.cs @@ -336,12 +336,14 @@ namespace CodeImp.DoomBuilder.Map } //mxd. This puts vertices in the blockmap - public virtual void AddVerticesSet(ICollection verts) { + public virtual void AddVerticesSet(ICollection verts) + { foreach(Vertex v in verts) AddVertex(v); } //mxd. This puts a vertex in the blockmap - public virtual void AddVertex(Vertex v) { + public virtual void AddVertex(Vertex v) + { Point p = GetBlockCoordinates(v.Position); if(IsInRange(p)) blockmap[p.X, p.Y].Vertices.Add(v); } diff --git a/Source/Core/Map/GroupInfo.cs b/Source/Core/Map/GroupInfo.cs index 82079c4d..2236a311 100644 --- a/Source/Core/Map/GroupInfo.cs +++ b/Source/Core/Map/GroupInfo.cs @@ -15,7 +15,8 @@ namespace CodeImp.DoomBuilder.Map public bool Empty { get { return empty; } } public int Index { get { return index; } } - public GroupInfo(int index, int numSectors, int numLines, int numVerts, int numThings) { + public GroupInfo(int index, int numSectors, int numLines, int numVerts, int numThings) + { this.index = index; this.numSectors = numSectors; this.numLines = numLines; @@ -25,7 +26,8 @@ namespace CodeImp.DoomBuilder.Map empty = (numSectors == 0 && numLines == 0 && numVerts == 0 && numThings == 0); } - public override string ToString() { + public override string ToString() + { if (empty) return index + ": Empty"; List result = new List(); diff --git a/Source/Core/Map/Linedef.cs b/Source/Core/Map/Linedef.cs index 294965ab..06352e19 100644 --- a/Source/Core/Map/Linedef.cs +++ b/Source/Core/Map/Linedef.cs @@ -424,7 +424,8 @@ namespace CodeImp.DoomBuilder.Map else { // Add fields with inverted value - for(int i = 0; i < f.Fields.Count; i++) { + for(int i = 0; i < f.Fields.Count; i++) + { if(!flags.ContainsKey(f.Fields[i])) //mxd flags[f.Fields[i]] = !f.FieldValues[i]; } @@ -1051,9 +1052,12 @@ namespace CodeImp.DoomBuilder.Map } //mxd - internal void UpdateColorPreset() { - for(int i = 0; i < General.Map.ConfigSettings.LinedefColorPresets.Length; i++) { - if(General.Map.ConfigSettings.LinedefColorPresets[i].Matches(this)) { + internal void UpdateColorPreset() + { + for(int i = 0; i < General.Map.ConfigSettings.LinedefColorPresets.Length; i++) + { + if(General.Map.ConfigSettings.LinedefColorPresets[i].Matches(this)) + { colorPresetIndex = i; return; } @@ -1088,59 +1092,69 @@ namespace CodeImp.DoomBuilder.Map // mxd. Moved here from BuilderModes.BuilderPlug // This adjusts texture coordinates for splitted lines according to the user preferences - private static void AdjustSplitCoordinates(Linedef oldline, Linedef newline, SplitLineBehavior splitlinebehavior) { - - switch(splitlinebehavior) { + private static void AdjustSplitCoordinates(Linedef oldline, Linedef newline, SplitLineBehavior splitlinebehavior) + { + switch(splitlinebehavior) + { case SplitLineBehavior.Interpolate: //Make texture offset adjustments - if(oldline.back != null) { - if((oldline.back.MiddleRequired() && oldline.back.LongMiddleTexture != MapSet.EmptyLongName) || oldline.back.HighRequired() || oldline.back.LowRequired()) { + if(oldline.back != null) + { + if((oldline.back.MiddleRequired() && oldline.back.LongMiddleTexture != MapSet.EmptyLongName) || oldline.back.HighRequired() || oldline.back.LowRequired()) + { int distance = (int)Vector2D.Distance(newline.start.Position, newline.end.Position); - if (General.Map.UDMF) { + if (General.Map.UDMF) + { if(distance != 0) oldline.back.SetUdmfTextureOffsetX(distance); - } else { + } + else + { oldline.back.OffsetX += distance; } } } - if(newline.front != null && ((newline.front.MiddleRequired() || newline.front.LongMiddleTexture != MapSet.EmptyLongName) || newline.front.HighRequired() || newline.front.LowRequired())) { + if(newline.front != null && ((newline.front.MiddleRequired() || newline.front.LongMiddleTexture != MapSet.EmptyLongName) || newline.front.HighRequired() || newline.front.LowRequired())) + { int distance = (int)Vector2D.Distance(oldline.start.Position, oldline.end.Position); - if(General.Map.UDMF) { + if(General.Map.UDMF) + { if(distance != 0) newline.front.SetUdmfTextureOffsetX(distance); - } else { + } + else + { newline.front.OffsetX += distance; } } //Clamp texture coordinates - if((oldline.front != null) && (newline.front != null)) { + if((oldline.front != null) && (newline.front != null)) + { //get texture ImageData texture = null; - if(newline.front.MiddleRequired() && newline.front.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.front.LongMiddleTexture)) { + if(newline.front.MiddleRequired() && newline.front.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.front.LongMiddleTexture)) texture = General.Map.Data.GetTextureImage(newline.front.MiddleTexture); - } else if(newline.front.HighRequired() && newline.front.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.front.LongHighTexture)) { + else if(newline.front.HighRequired() && newline.front.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.front.LongHighTexture)) texture = General.Map.Data.GetTextureImage(newline.front.HighTexture); - } else if(newline.front.LowRequired() && newline.front.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.front.LongLowTexture)) { + else if(newline.front.LowRequired() && newline.front.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.front.LongLowTexture)) texture = General.Map.Data.GetTextureImage(newline.front.LowTexture); - } //clamp offsetX if(texture != null) newline.front.OffsetX %= texture.Width; } - if((oldline.back != null) && (newline.back != null)) { + if((oldline.back != null) && (newline.back != null)) + { //get texture ImageData texture = null; - if(newline.back.MiddleRequired() && newline.back.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.back.LongMiddleTexture)) { + if(newline.back.MiddleRequired() && newline.back.LongMiddleTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.back.LongMiddleTexture)) texture = General.Map.Data.GetTextureImage(newline.back.MiddleTexture); - } else if(newline.back.HighRequired() && newline.back.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.back.LongHighTexture)) { + else if(newline.back.HighRequired() && newline.back.LongHighTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.back.LongHighTexture)) texture = General.Map.Data.GetTextureImage(newline.back.HighTexture); - } else if(newline.back.LowRequired() && newline.back.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.back.LongLowTexture)) { + else if(newline.back.LowRequired() && newline.back.LongLowTexture != MapSet.EmptyLongName && General.Map.Data.GetTextureExists(newline.back.LongLowTexture)) texture = General.Map.Data.GetTextureImage(newline.back.LowTexture); - } //clamp offsetX if(texture != null) newline.back.OffsetX %= texture.Width; @@ -1149,12 +1163,14 @@ namespace CodeImp.DoomBuilder.Map break; case SplitLineBehavior.CopyXY: - if((oldline.front != null) && (newline.front != null)) { + if((oldline.front != null) && (newline.front != null)) + { newline.front.OffsetX = oldline.front.OffsetX; newline.front.OffsetY = oldline.front.OffsetY; //mxd. Copy UDMF offsets as well - if(General.Map.UDMF) { + if(General.Map.UDMF) + { UDMFTools.SetFloat(newline.front.Fields, "offsetx_top", oldline.front.Fields.GetValue("offsetx_top", 0f)); UDMFTools.SetFloat(newline.front.Fields, "offsetx_mid", oldline.front.Fields.GetValue("offsetx_mid", 0f)); UDMFTools.SetFloat(newline.front.Fields, "offsetx_bottom", oldline.front.Fields.GetValue("offsetx_bottom", 0f)); @@ -1165,12 +1181,14 @@ namespace CodeImp.DoomBuilder.Map } } - if((oldline.back != null) && (newline.back != null)) { + if((oldline.back != null) && (newline.back != null)) + { newline.back.OffsetX = oldline.back.OffsetX; newline.back.OffsetY = oldline.back.OffsetY; //mxd. Copy UDMF offsets as well - if(General.Map.UDMF) { + if(General.Map.UDMF) + { UDMFTools.SetFloat(newline.back.Fields, "offsetx_top", oldline.back.Fields.GetValue("offsetx_top", 0f)); UDMFTools.SetFloat(newline.back.Fields, "offsetx_mid", oldline.back.Fields.GetValue("offsetx_mid", 0f)); UDMFTools.SetFloat(newline.back.Fields, "offsetx_bottom", oldline.back.Fields.GetValue("offsetx_bottom", 0f)); @@ -1183,24 +1201,28 @@ namespace CodeImp.DoomBuilder.Map break; case SplitLineBehavior.ResetXCopyY: - if((oldline.front != null) && (newline.front != null)) { + if((oldline.front != null) && (newline.front != null)) + { newline.front.OffsetX = 0; newline.front.OffsetY = oldline.front.OffsetY; //mxd. Reset UDMF X offset as well - if(General.Map.UDMF) { + if(General.Map.UDMF) + { UDMFTools.SetFloat(newline.front.Fields, "offsetx_top", 0f); UDMFTools.SetFloat(newline.front.Fields, "offsetx_mid", 0f); UDMFTools.SetFloat(newline.front.Fields, "offsetx_bottom", 0f); } } - if((oldline.back != null) && (newline.back != null)) { + if((oldline.back != null) && (newline.back != null)) + { newline.back.OffsetX = 0; newline.back.OffsetY = oldline.back.OffsetY; //mxd. Reset UDMF X offset and copy Y offset as well - if(General.Map.UDMF) { + if(General.Map.UDMF) + { UDMFTools.SetFloat(newline.back.Fields, "offsetx_top", 0f); UDMFTools.SetFloat(newline.back.Fields, "offsetx_mid", 0f); UDMFTools.SetFloat(newline.back.Fields, "offsetx_bottom", 0f); @@ -1213,11 +1235,13 @@ namespace CodeImp.DoomBuilder.Map break; case SplitLineBehavior.ResetXY: - if(newline.front != null) { + if(newline.front != null) + { newline.front.OffsetX = 0; newline.front.OffsetY = 0; - if(General.Map.UDMF) { + if(General.Map.UDMF) + { UDMFTools.SetFloat(newline.front.Fields, "offsetx_top", 0f); UDMFTools.SetFloat(newline.front.Fields, "offsetx_mid", 0f); UDMFTools.SetFloat(newline.front.Fields, "offsetx_bottom", 0f); @@ -1228,11 +1252,13 @@ namespace CodeImp.DoomBuilder.Map } } - if(newline.back != null) { + if(newline.back != null) + { newline.back.OffsetX = 0; newline.back.OffsetY = 0; - if(General.Map.UDMF) { + if(General.Map.UDMF) + { UDMFTools.SetFloat(newline.back.Fields, "offsetx_top", 0f); UDMFTools.SetFloat(newline.back.Fields, "offsetx_mid", 0f); UDMFTools.SetFloat(newline.back.Fields, "offsetx_bottom", 0f); diff --git a/Source/Core/Map/MapSet.cs b/Source/Core/Map/MapSet.cs index 2762ec84..a952a1dd 100644 --- a/Source/Core/Map/MapSet.cs +++ b/Source/Core/Map/MapSet.cs @@ -1428,9 +1428,11 @@ namespace CodeImp.DoomBuilder.Map IDictionary grouplist = cfg.ReadSetting(SELECTION_GROUPS_PATH, new Hashtable()); IDictionary groupinfo; - foreach(DictionaryEntry mp in grouplist) { + foreach(DictionaryEntry mp in grouplist) + { // Item is a structure? - if(mp.Value is IDictionary) { + if(mp.Value is IDictionary) + { //get group number int groupnum; if(!int.TryParse(mp.Key as string, out groupnum)) continue; @@ -1443,7 +1445,7 @@ namespace CodeImp.DoomBuilder.Map string s = groupinfo["vertices"] as string; if (!string.IsNullOrEmpty(s)) { - List indices = getIndices(groupinfo["vertices"] as string); + List indices = GetIndices(groupinfo["vertices"] as string); foreach (int index in indices) { @@ -1458,7 +1460,7 @@ namespace CodeImp.DoomBuilder.Map string s = groupinfo["linedefs"] as string; if(!string.IsNullOrEmpty(s)) { - List indices = getIndices(groupinfo["linedefs"] as string); + List indices = GetIndices(groupinfo["linedefs"] as string); foreach(int index in indices) { @@ -1473,7 +1475,7 @@ namespace CodeImp.DoomBuilder.Map string s = groupinfo["sectors"] as string; if(!string.IsNullOrEmpty(s)) { - List indices = getIndices(groupinfo["sectors"] as string); + List indices = GetIndices(groupinfo["sectors"] as string); foreach(int index in indices) { @@ -1488,7 +1490,7 @@ namespace CodeImp.DoomBuilder.Map string s = groupinfo["things"] as string; if(!string.IsNullOrEmpty(s)) { - List indices = getIndices(groupinfo["things"] as string); + List indices = GetIndices(groupinfo["things"] as string); foreach(int index in indices) { @@ -1502,7 +1504,7 @@ namespace CodeImp.DoomBuilder.Map } //mxd - private List getIndices(string input) + private static List GetIndices(string input) { string[] parts = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); int index; @@ -2369,26 +2371,32 @@ namespace CodeImp.DoomBuilder.Map } /// This joins nearby vertices in the same collection - public static int JoinVertices(List set, float joindist) { + public static int JoinVertices(List set, float joindist) + { float joindist2 = joindist * joindist; int joinsdone = 0; bool joined; Vertex v1, v2; - do { + do + { // No joins yet joined = false; // Go for all vertices in the first set - for(int i = 0; i < set.Count - 1; i++) { - for(int c = i + 1; c < set.Count; c++) { + for(int i = 0; i < set.Count - 1; i++) + { + for(int c = i + 1; c < set.Count; c++) + { v1 = set[i]; v2 = set[c]; // Check if vertices are close enough - if (v1.DistanceToSq(v2.Position) <= joindist2) { + if (v1.DistanceToSq(v2.Position) <= joindist2) + { // Check if not the same vertex - if (v1.Index != v2.Index) { + if (v1.Index != v2.Index) + { // Move the second vertex to match the first v2.Move(v1.Position); @@ -2458,22 +2466,28 @@ namespace CodeImp.DoomBuilder.Map // No split yet splitted = false; - for(w = 0; w < bmWidth; w++) { - for(h = 0; h < bmHeight; h++) { + for(w = 0; w < bmWidth; w++) + { + for(h = 0; h < bmHeight; h++) + { block = bmap[w, h]; if(block.Vertices.Count == 0 || block.Lines.Count == 0) continue; // Go for all the lines - foreach(Linedef l in block.Lines) { + foreach(Linedef l in block.Lines) + { // Go for all the vertices - foreach(Vertex v in block.Vertices) { + foreach(Vertex v in block.Vertices) + { // Check if v is close enough to l for splitting - if(l.DistanceToSq(v.Position, true) <= splitdist2) { + if(l.DistanceToSq(v.Position, true) <= splitdist2) + { // Line is not already referencing v? Vector2D deltastart = l.Start.Position - v.Position; Vector2D deltaend = l.End.Position - v.Position; if(((Math.Abs(deltastart.x) > 0.001f) || (Math.Abs(deltastart.y) > 0.001f)) && - ((Math.Abs(deltaend.x) > 0.001f) || (Math.Abs(deltaend.y) > 0.001f))) { + ((Math.Abs(deltaend.x) > 0.001f) || (Math.Abs(deltaend.y) > 0.001f))) + { // Split line l with vertex v Linedef nl = l.Split(v); if(nl == null) return false; @@ -2488,7 +2502,8 @@ namespace CodeImp.DoomBuilder.Map nl.UpdateCache(); // Add both lines to changedlines - if(changedlines != null) { + if(changedlines != null) + { changedlines.Add(l); changedlines.Add(nl); } @@ -2595,16 +2610,19 @@ namespace CodeImp.DoomBuilder.Map } /// mxd. This finds the line closest to the specified position excluding given list of linedefs. - public Linedef NearestLinedef(Vector2D pos, List linesToExclude) { + public Linedef NearestLinedef(Vector2D pos, List linesToExclude) + { Linedef closest = null; float distance = float.MaxValue; // Go for all linedefs in selection - foreach(Linedef l in linedefs) { + foreach(Linedef l in linedefs) + { if(linesToExclude.Contains(l)) continue; // Calculate distance and check if closer than previous find float d = l.SafeDistanceToSq(pos, true); - if(d < distance) { + if(d < distance) + { // This one is closer closest = l; distance = d; @@ -2664,18 +2682,21 @@ namespace CodeImp.DoomBuilder.Map } /// mxd. This finds the thing closest to the specified thing. - public static Thing NearestThing(ICollection selection, Thing thing) { + public static Thing NearestThing(ICollection selection, Thing thing) + { Thing closest = null; float distance = float.MaxValue; float d; // Go for all things in selection - foreach(Thing t in selection) { + foreach(Thing t in selection) + { if(t == thing) continue; // Calculate distance and check if closer than previous find d = t.DistanceToSq(thing.Position); - if(d < distance) { + if(d < distance) + { // This one is closer closest = t; distance = d; @@ -2782,23 +2803,27 @@ namespace CodeImp.DoomBuilder.Map { Dictionary usedtags = new Dictionary(); - switch(elementType) { + switch(elementType) + { case UniversalType.ThingTag: - for(int i = 0; i < things.Length; i++) { + for(int i = 0; i < things.Length; i++) + { if(things[i].Tag > 0 && !usedtags.ContainsKey(things[i].Tag)) usedtags.Add(things[i].Tag, false); } break; case UniversalType.LinedefTag: - for(int i = 0; i < linedefs.Length; i++) { + for(int i = 0; i < linedefs.Length; i++) + { if(linedefs[i].Tag > 0 && !usedtags.ContainsKey(linedefs[i].Tag)) usedtags.Add(linedefs[i].Tag, false); } break; case UniversalType.SectorTag: - for(int i = 0; i < sectors.Length; i++) { + for(int i = 0; i < sectors.Length; i++) + { if(sectors[i].Tag > 0 && !usedtags.ContainsKey(sectors[i].Tag)) usedtags.Add(sectors[i].Tag, false); } @@ -3223,7 +3248,7 @@ namespace CodeImp.DoomBuilder.Map } //mxd - private bool TranslateToLongTextureNames(IEnumerable sectors, IEnumerable sidedefs) + private static bool TranslateToLongTextureNames(IEnumerable sectors, IEnumerable sidedefs) { bool changed = false; @@ -3283,7 +3308,7 @@ namespace CodeImp.DoomBuilder.Map return changed; } - private bool TranslateToShortTextureNames(IEnumerable sectors, IEnumerable sidedefs) + private static bool TranslateToShortTextureNames(IEnumerable sectors, IEnumerable sidedefs) { bool changed = false; diff --git a/Source/Core/Map/Sector.cs b/Source/Core/Map/Sector.cs index 126eaa2c..903b45ce 100644 --- a/Source/Core/Map/Sector.cs +++ b/Source/Core/Map/Sector.cs @@ -545,9 +545,11 @@ namespace CodeImp.DoomBuilder.Map Dictionary processed = new Dictionary(); //mxd //mxd. This way bbox will be created even if triangulation failed (sector with 2 or less sidedefs and 2 vertices) - foreach (Sidedef s in sidedefs) { + foreach (Sidedef s in sidedefs) + { //start... - if (!processed.ContainsKey(s.Line.Start)) { + if (!processed.ContainsKey(s.Line.Start)) + { if (s.Line.Start.Position.x < left) left = s.Line.Start.Position.x; if (s.Line.Start.Position.x > right) right = s.Line.Start.Position.x; if (s.Line.Start.Position.y < top) top = s.Line.Start.Position.y; @@ -556,7 +558,8 @@ namespace CodeImp.DoomBuilder.Map } //end... - if(!processed.ContainsKey(s.Line.End)) { + if(!processed.ContainsKey(s.Line.End)) + { if(s.Line.End.Position.x < left) left = s.Line.End.Position.x; if(s.Line.End.Position.x > right) right = s.Line.End.Position.x; if(s.Line.End.Position.y < top) top = s.Line.End.Position.y; diff --git a/Source/Core/Map/Sidedef.cs b/Source/Core/Map/Sidedef.cs index 6912fbb2..3c29a847 100644 --- a/Source/Core/Map/Sidedef.cs +++ b/Source/Core/Map/Sidedef.cs @@ -559,7 +559,8 @@ namespace CodeImp.DoomBuilder.Map #region ================== Changes // This updates all properties - public void Update(int offsetx, int offsety, string thigh, string tmid, string tlow) { + public void Update(int offsetx, int offsety, string thigh, string tmid, string tlow) + { Update(offsetx, offsety, thigh, tmid, tlow, new Dictionary(StringComparer.Ordinal)); } @@ -650,11 +651,13 @@ namespace CodeImp.DoomBuilder.Map } // This sets udmf texture offset - public void SetUdmfTextureOffsetX(int offset) { + public void SetUdmfTextureOffsetX(int offset) + { this.Fields.BeforeFieldsChange(); //top - if(longtexnamehigh != MapSet.EmptyLongName && General.Map.Data.GetFlatExists(texnamehigh)) { + if(longtexnamehigh != MapSet.EmptyLongName && General.Map.Data.GetFlatExists(texnamehigh)) + { ImageData texture = General.Map.Data.GetFlatImage(texnamehigh); float scaleTop = Fields.GetValue("scalex_top", 1.0f); @@ -664,7 +667,8 @@ namespace CodeImp.DoomBuilder.Map } //middle - if(longtexnamemid != MapSet.EmptyLongName && General.Map.Data.GetFlatExists(texnamemid)) { + if(longtexnamemid != MapSet.EmptyLongName && General.Map.Data.GetFlatExists(texnamemid)) + { ImageData texture = General.Map.Data.GetFlatImage(texnamemid); float scaleMid = Fields.GetValue("scalex_mid", 1.0f); @@ -674,7 +678,8 @@ namespace CodeImp.DoomBuilder.Map } //bottom - if(longtexnamelow != MapSet.EmptyLongName && General.Map.Data.GetFlatExists(texnamelow)) { + if(longtexnamelow != MapSet.EmptyLongName && General.Map.Data.GetFlatExists(texnamelow)) + { ImageData texture = General.Map.Data.GetFlatImage(texnamelow); float scaleLow = Fields.GetValue("scalex_bottom", 1.0f); diff --git a/Source/Core/Map/Thing.cs b/Source/Core/Map/Thing.cs index 52902731..ed386c01 100644 --- a/Source/Core/Map/Thing.cs +++ b/Source/Core/Map/Thing.cs @@ -199,7 +199,8 @@ namespace CodeImp.DoomBuilder.Map s.rwInt(ref action); for(int i = 0; i < NUM_ARGS; i++) s.rwInt(ref args[i]); - if(!s.IsWriting) { + if(!s.IsWriting) + { anglerad = Angle2D.DoomToReal(angledoom); UpdateCache(); //mxd } @@ -524,10 +525,13 @@ namespace CodeImp.DoomBuilder.Map if (isModel && General.Map.Data.ModeldefEntries[type].LoadState == ModelLoadState.None) isModel = General.Map.Data.ProcessModel(type); - if (isModel) { + if (isModel) + { rollrad = (General.Map.Data.ModeldefEntries[type].InheritActorRoll ? Angle2D.DegToRad(roll) : 0); pitchrad = (General.Map.Data.ModeldefEntries[type].InheritActorPitch ? Angle2D.DegToRad(pitch) : 0); - } else { + } + else + { rollrad = 0; pitchrad = 0; } diff --git a/Source/Core/Map/Vertex.cs b/Source/Core/Map/Vertex.cs index c7222839..e5727ea9 100644 --- a/Source/Core/Map/Vertex.cs +++ b/Source/Core/Map/Vertex.cs @@ -68,7 +68,8 @@ namespace CodeImp.DoomBuilder.Map public float ZCeiling { //mxd get { return zceiling; } set { - if(zceiling != value) { + if(zceiling != value) + { BeforeFieldsChange(); zceiling = value; } @@ -77,7 +78,8 @@ namespace CodeImp.DoomBuilder.Map public float ZFloor { //mxd get { return zfloor; } set { - if(zfloor != value) { + if(zfloor != value) + { BeforeFieldsChange(); zfloor = value; } diff --git a/Source/Core/Rendering/Plotter.cs b/Source/Core/Rendering/Plotter.cs index 084dcad1..ee64fa17 100644 --- a/Source/Core/Rendering/Plotter.cs +++ b/Source/Core/Rendering/Plotter.cs @@ -334,13 +334,17 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - public void DrawLine3DFloor(Vector2D start, Vector2D end, ref PixelColor c, PixelColor c2) { + public void DrawLine3DFloor(Vector2D start, Vector2D end, ref PixelColor c, PixelColor c2) + { Vector2D delta = end - start; float length = delta.GetLength(); - if(length < DASH_INTERVAL * 2) { + if(length < DASH_INTERVAL * 2) + { DrawLineSolid((int)start.x, (int)start.y, (int)end.x, (int)end.y, ref c2); - } else { + } + else + { float d1 = DASH_INTERVAL / length; float d2 = 1.0f - d1; diff --git a/Source/Core/Rendering/Renderer.cs b/Source/Core/Rendering/Renderer.cs index ca9883e5..7ab9361d 100644 --- a/Source/Core/Rendering/Renderer.cs +++ b/Source/Core/Rendering/Renderer.cs @@ -100,16 +100,22 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd. This calculates wall brightness level with doom-style shading - public int CalculateBrightness(int level, Sidedef sd) { - if(level < 253 && sd != null) { + public int CalculateBrightness(int level, Sidedef sd) + { + if(level < 253 && sd != null) + { bool evenlighting = General.Map.Data.MapInfo.EvenLighting; bool smoothlighting = General.Map.Data.MapInfo.SmoothLighting; //check for possiburu UDMF overrides - if(General.Map.UDMF) { - if(sd.IsFlagSet("lightabsolute") && sd.Fields.ContainsKey("light")) { + if(General.Map.UDMF) + { + if(sd.IsFlagSet("lightabsolute") && sd.Fields.ContainsKey("light")) + { evenlighting = true; - } else { + } + else + { if(sd.IsFlagSet("nofakecontrast")) evenlighting = true; if(sd.IsFlagSet("smoothlighting")) @@ -117,22 +123,29 @@ namespace CodeImp.DoomBuilder.Rendering } } - if(!evenlighting) { + if(!evenlighting) + { //all walls are shaded by their angle - if(smoothlighting) { + if(smoothlighting) + { float ammount = Math.Abs((float)Math.Sin(sd.Angle)); int hAmmount = (int)((1.0f - ammount) * General.Map.Data.MapInfo.HorizWallShade); int vAmmount = (int)(ammount * General.Map.Data.MapInfo.VertWallShade); level = General.Clamp(level - hAmmount - vAmmount, 0, 255); - } else { //only horizontal/verticel walls are shaded + } + else //only horizontal/verticel walls are shaded + { int angle = (int)Angle2D.RadToDeg(sd.Angle); //horizontal wall - if(angle == 270 || angle == 90) { + if(angle == 270 || angle == 90) + { level = General.Clamp(level + General.Map.Data.MapInfo.HorizWallShade, 0, 255); - //vertical wall - } else if(angle == 0 || angle == 180) { + } + //vertical wall + else if(angle == 0 || angle == 180) + { level = General.Clamp(level + General.Map.Data.MapInfo.VertWallShade, 0, 255); } } diff --git a/Source/Core/Rendering/Renderer2D.cs b/Source/Core/Rendering/Renderer2D.cs index 9dd71504..b7618fa3 100644 --- a/Source/Core/Rendering/Renderer2D.cs +++ b/Source/Core/Rendering/Renderer2D.cs @@ -576,7 +576,8 @@ namespace CodeImp.DoomBuilder.Rendering if (t.Selected) return General.Colors.Selection; //mxd. if thing is light, set it's color to light color: - if(Array.IndexOf(GZBuilder.GZGeneral.GZ_LIGHTS, t.Type) != -1){ + if(Array.IndexOf(GZBuilder.GZGeneral.GZ_LIGHTS, t.Type) != -1) + { if (t.Type == 1502) //vavoom light return new PixelColor(255, 255, 255, 255); if (t.Type == 1503) //vavoom colored light @@ -601,7 +602,8 @@ namespace CodeImp.DoomBuilder.Rendering if(l.Selected) return General.Colors.Selection; //mxd. Impassable lines - if(l.ImpassableFlag) { + if(l.ImpassableFlag) + { if(l.ColorPresetIndex != -1) return General.Map.ConfigSettings.LinedefColorPresets[l.ColorPresetIndex].Color; return General.Colors.Linedefs; @@ -614,12 +616,15 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd. This collects indices of linedefs, which are parts of sectors with 3d floors - public void UpdateExtraFloorFlag() { + public void UpdateExtraFloorFlag() + { List tagList = new List(); //find lines with 3d floor action and collect sector tags - foreach(Linedef l in General.Map.Map.Linedefs){ - if(l.Action == 160) { + foreach(Linedef l in General.Map.Map.Linedefs) + { + if(l.Action == 160) + { int sectortag = (l.Args[1] & 8) != 0 ? l.Args[0] : l.Args[0] + (l.Args[4] << 8); if(sectortag != 0) tagList.Add(sectortag); } @@ -629,12 +634,15 @@ namespace CodeImp.DoomBuilder.Rendering int[] tags = tagList.ToArray(); //find lines, which are related to sectors with 3d floors, and collect their valuable indices - foreach(Linedef l in General.Map.Map.Linedefs) { - if(l.Front != null && l.Front.Sector != null && l.Front.Sector.Tag != 0 && Array.BinarySearch(tags, l.Front.Sector.Tag) > -1) { + foreach(Linedef l in General.Map.Map.Linedefs) + { + if(l.Front != null && l.Front.Sector != null && l.Front.Sector.Tag != 0 && Array.BinarySearch(tags, l.Front.Sector.Tag) > -1) + { l.ExtraFloorFlag = true; continue; } - if(l.Back != null && l.Back.Sector != null && l.Back.Sector.Tag != 0 && Array.BinarySearch(tags, l.Back.Sector.Tag) > -1) { + if(l.Back != null && l.Back.Sector != null && l.Back.Sector.Tag != 0 && Array.BinarySearch(tags, l.Back.Sector.Tag) > -1) + { l.ExtraFloorFlag = true; continue; } @@ -988,7 +996,8 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private void CreateThingArrowVerts(Thing t, ref FlatVertex[] verts, Vector2D screenpos, int offset) { + private void CreateThingArrowVerts(Thing t, ref FlatVertex[] verts, Vector2D screenpos, int offset) + { // Determine size float arrowsize = (t.FixedSize && (scale > 1.0f) ? (t.Size - THING_ARROW_SHRINK) * THING_ARROW_SIZE : (t.Size - THING_ARROW_SHRINK) * scale * THING_ARROW_SIZE); @@ -1108,14 +1117,16 @@ namespace CodeImp.DoomBuilder.Rendering foreach(Thing t in things) { //collect models - if (t.IsModel) { + if (t.IsModel) + { if(!modelsByType.ContainsKey(t.Type)) modelsByType.Add(t.Type, new List()); modelsByType[t.Type].Add(t); } // Create vertices tc = fixedcolor ? c : DetermineThingColor(t); - if(CreateThingBoxVerts(t, ref verts, thingsByPosition, buffercount * 6, tc)) { + if(CreateThingBoxVerts(t, ref verts, thingsByPosition, buffercount * 6, tc)) + { buffercount++; //mxd @@ -1486,7 +1497,8 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - public void RenderHighlight(FlatVertex[] vertices, int color) { + public void RenderHighlight(FlatVertex[] vertices, int color) + { if(vertices.Length < 3) return; // Set renderstates for rendering @@ -1679,7 +1691,8 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - public void RenderArrow(Line3D line, PixelColor c) { + public void RenderArrow(Line3D line, PixelColor c) + { float scaler = 20f / scale; RenderLine(line.v1, line.v2, 0.8f, c, true); @@ -1690,7 +1703,8 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - public void PlotArrow(Line3D line, PixelColor c) { + public void PlotArrow(Line3D line, PixelColor c) + { float scaler = 16f / scale; PlotLine(line.v1, line.v2, c); @@ -1807,11 +1821,10 @@ namespace CodeImp.DoomBuilder.Rendering Vector2D v2 = l.End.Position.GetTransformed(translatex, translatey, scale, -scale); // Draw line. mxd: added 3d-floor indication - if(l.ExtraFloorFlag && General.Settings.GZMarkExtraFloors) { + if(l.ExtraFloorFlag && General.Settings.GZMarkExtraFloors) plotter.DrawLine3DFloor(v1, v2, ref c, General.Colors.ThreeDFloor); - } else { + else plotter.DrawLineSolid((int)v1.x, (int)v1.y, (int)v2.x, (int)v2.y, ref c); - } // Calculate normal indicator float mx = (v2.x - v1.x) * 0.5f; diff --git a/Source/Core/Rendering/Renderer3D.cs b/Source/Core/Rendering/Renderer3D.cs index 37fa184f..4621fa52 100644 --- a/Source/Core/Rendering/Renderer3D.cs +++ b/Source/Core/Rendering/Renderer3D.cs @@ -425,7 +425,7 @@ namespace CodeImp.DoomBuilder.Rendering { //mxd. sort lights if(General.Settings.GZDrawLightsMode != LightRenderMode.NONE && !fullbrightness && thingsWithLight.Count > 0) - updateLights(); + UpdateLights(); // Initial renderstates graphics.Device.SetRenderState(RenderState.CullMode, Cull.Counterclockwise); @@ -469,14 +469,17 @@ namespace CodeImp.DoomBuilder.Rendering RenderVertices(); //mxd. LINKS - if (General.Settings.GZShowEventLines) { + if (General.Settings.GZShowEventLines) + { //mxd. gather links List lines = LinksCollector.GetThingLinks(thingsbydistance); - if(lines.Count > 0) { + if(lines.Count > 0) + { List normalLines = new List(); List activatorLines = new List(); - foreach(Line3D l in lines){ + foreach(Line3D l in lines) + { if(l.LineType == Line3DType.DEFAULT) normalLines.Add(l); else @@ -484,9 +487,9 @@ namespace CodeImp.DoomBuilder.Rendering } if(normalLines.Count > 0) - renderArrows(normalLines, General.Colors.InfoLine.ToColorValue()); + RenderArrows(normalLines, General.Colors.InfoLine.ToColorValue()); if(activatorLines.Count > 0) - renderArrows(activatorLines, General.Colors.Selection3D.ToColorValue()); + RenderArrows(activatorLines, General.Colors.Selection3D.ToColorValue()); } } @@ -512,20 +515,24 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private void updateLights() { - thingsWithLight.Sort(sortThingsByCameraDistance); - if (thingsWithLight.Count > General.Settings.GZMaxDynamicLights) { + private void UpdateLights() + { + thingsWithLight.Sort(SortThingsByCameraDistance); + if (thingsWithLight.Count > General.Settings.GZMaxDynamicLights) + { List tl = new List(); for (int i = 0; i < General.Settings.GZMaxDynamicLights; i++) tl.Add(thingsWithLight[i]); thingsWithLight = tl; } - thingsWithLight.Sort(sortThingsByLightRenderStyle); + thingsWithLight.Sort(SortThingsByLightRenderStyle); lightOffsets = new int[3]; - foreach (VisualThing t in thingsWithLight) { + foreach (VisualThing t in thingsWithLight) + { //add light to apropriate array. - switch(t.LightRenderStyle) { + switch(t.LightRenderStyle) + { case DynamicLightRenderStyle.NORMAL: case DynamicLightRenderStyle.VAVOOM: lightOffsets[0]++; @@ -543,7 +550,7 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private static int sortThingsByCameraDistance(VisualThing t1, VisualThing t2) + private static int SortThingsByCameraDistance(VisualThing t1, VisualThing t2) { if (t1.CameraDistance3D == t2.CameraDistance3D) return 0; if (t1.CameraDistance3D > t2.CameraDistance3D) return 1; @@ -551,7 +558,7 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private static int sortThingsByLightRenderStyle(VisualThing t1, VisualThing t2) + private static int SortThingsByLightRenderStyle(VisualThing t1, VisualThing t2) { if (t1.LightRenderStyle == t2.LightRenderStyle) return 0; if (t1.LightRenderStyle > t2.LightRenderStyle) return 1; @@ -561,7 +568,8 @@ namespace CodeImp.DoomBuilder.Rendering //mxd. //I never particularly liked old ThingCages, so I wrote this instead. //It should render faster and it has fancy arrow! :) - private void RenderThingCages() { + private void RenderThingCages() + { graphics.Device.SetRenderState(RenderState.AlphaBlendEnable, true); graphics.Device.SetRenderState(RenderState.AlphaTestEnable, false); graphics.Device.SetRenderState(RenderState.ZWriteEnable, false); @@ -570,16 +578,20 @@ namespace CodeImp.DoomBuilder.Rendering graphics.Shaders.World3D.BeginPass(16); - foreach (VisualThing t in thingsbydistance) { + foreach (VisualThing t in thingsbydistance) + { // Setup matrix world = Matrix.Multiply(t.CageScales, t.Position); ApplyMatrices3D(); // Setup color Color4 thingColor; - if (t.Selected && showselection) { + if (t.Selected && showselection) + { thingColor = General.Colors.Selection3D.ToColorValue(); - } else { + } + else + { thingColor = t.Thing.Color.ToColorValue(); if (t != highlighted) thingColor.Alpha = 0.6f; } @@ -588,21 +600,28 @@ namespace CodeImp.DoomBuilder.Rendering //Render cage graphics.Shaders.World3D.ApplySettings(); - if(t.Sizeless) { + if(t.Sizeless) + { graphics.Device.SetStreamSource(0, sizelessThingHandle.Shape, 0, WorldVertex.Stride); graphics.Device.DrawPrimitives(PrimitiveType.LineList, 0, 3); - } else { + } + else + { graphics.Device.SetStreamSource(0, bbox.Cage, 0, WorldVertex.Stride); graphics.Device.DrawPrimitives(PrimitiveType.LineList, 0, 12); } //and arrow - if (t.Thing.IsDirectional) { + if (t.Thing.IsDirectional) + { float sx = t.CageScales.M11; Matrix arrowScaler = Matrix.Scaling(sx, sx, sx); //scale arrow evenly based on thing width\depth - if (t.Sizeless) { + if (t.Sizeless) + { world = Matrix.Multiply(arrowScaler, t.Position); - } else { + } + else + { world = Matrix.Multiply(arrowScaler, t.Position * Matrix.Translation(0.0f, 0.0f, t.CageScales.M33 / 2)); } Matrix rot = Matrix.RotationZ(t.Thing.Angle - Angle2D.PI / 2); @@ -622,7 +641,8 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private void RenderVertices() { + private void RenderVertices() + { if(visualvertices == null) return; graphics.Device.SetRenderState(RenderState.AlphaBlendEnable, true); @@ -633,15 +653,19 @@ namespace CodeImp.DoomBuilder.Rendering graphics.Shaders.World3D.BeginPass(16); - foreach(VisualVertex v in visualvertices) { + foreach(VisualVertex v in visualvertices) + { world = v.Position; ApplyMatrices3D(); // Setup color Color4 color; - if(v.Selected && showselection) { + if(v.Selected && showselection) + { color = General.Colors.Selection3D.ToColorValue(); - } else { + } + else + { color = v.HaveHeightOffset ? General.Colors.InfoLine.ToColorValue() : General.Colors.Vertices.ToColorValue(); if(v != highlighted) color.Alpha = 0.6f; } @@ -660,12 +684,14 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private void renderArrows(List lines, Color4 color) { + private void RenderArrows(List lines, Color4 color) + { //create vertices WorldVertex[] verts = new WorldVertex[lines.Count * 6]; - float scaler = 20f; + const float scaler = 20f; - for (int i = 0; i < lines.Count; i++) { + for (int i = 0; i < lines.Count; i++) + { WorldVertex endPoint = new WorldVertex(lines[i].v2); float nz = lines[i].GetDelta().GetNormal().z * scaler; float angle = lines[i].GetAngle(); @@ -679,7 +705,7 @@ namespace CodeImp.DoomBuilder.Rendering VertexBuffer vb = new VertexBuffer(General.Map.Graphics.Device, WorldVertex.Stride * verts.Length, Usage.WriteOnly | Usage.Dynamic, VertexFormat.None, Pool.Default); DataStream s = vb.Lock(0, WorldVertex.Stride * verts.Length, LockFlags.Discard); - s.WriteRange(verts); + s.WriteRange(verts); vb.Unlock(); s.Dispose(); @@ -780,8 +806,10 @@ namespace CodeImp.DoomBuilder.Rendering wantedshaderpass += 8; //mxd. Seems that lines rendered with RenderPass.Alpha or RenderPass.Additive aren't affected by dynamic lights in GZDoom - if ( !(g.RenderPass == RenderPass.Alpha || g.RenderPass == RenderPass.Additive || General.Settings.GZDrawLightsMode == LightRenderMode.NONE || fullbrightness || thingsWithLight.Count == 0) ) { - if (curtexture.Texture != null) { + if ( !(g.RenderPass == RenderPass.Alpha || g.RenderPass == RenderPass.Additive || General.Settings.GZDrawLightsMode == LightRenderMode.NONE || fullbrightness || thingsWithLight.Count == 0) ) + { + if (curtexture.Texture != null) + { if (!litGeometry.ContainsKey(curtexture.Texture)) litGeometry[curtexture.Texture] = new List(); litGeometry[curtexture.Texture].Add(g); @@ -805,10 +833,11 @@ namespace CodeImp.DoomBuilder.Rendering else { //mxd. set variables for fog rendering - if (wantedshaderpass > 7) { + if (wantedshaderpass > 7) + { graphics.Shaders.World3D.World = world; graphics.Shaders.World3D.LightColor = sector.Sector.FogColor; - graphics.Shaders.World3D.CameraPosition = new Vector4(cameraposition.x, cameraposition.y, cameraposition.z, getFogEnd(sector.Sector)); + graphics.Shaders.World3D.CameraPosition = new Vector4(cameraposition.x, cameraposition.y, cameraposition.z, GetFogEnd(sector.Sector)); } graphics.Shaders.World3D.SetHighlightColor(CalculateHighlightColor((g == highlighted) && showhighlight, (g.Selected && showselection)).ToArgb()); @@ -881,7 +910,7 @@ namespace CodeImp.DoomBuilder.Rendering } else if (General.Settings.GZDrawLightsMode != LightRenderMode.NONE && !fullbrightness && thingsWithLight.Count > 0) { - Color4 litColor = getLitColorForThing(t); + Color4 litColor = GetLitColorForThing(t); if (litColor.ToArgb() != 0) { wantedshaderpass += 4; //render using one of passes, which uses World3D.VertexColor @@ -921,7 +950,7 @@ namespace CodeImp.DoomBuilder.Rendering graphics.Shaders.World3D.World = world; graphics.Shaders.World3D.LightColor = t.Thing.Sector.FogColor; - graphics.Shaders.World3D.CameraPosition = new Vector4(cameraposition.x, cameraposition.y, cameraposition.z, getFogEnd(t.Thing.Sector)); + graphics.Shaders.World3D.CameraPosition = new Vector4(cameraposition.x, cameraposition.y, cameraposition.z, GetFogEnd(t.Thing.Sector)); } graphics.Shaders.World3D.ApplySettings(); @@ -948,7 +977,8 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd. Dynamic lights pass! - private void RenderLights(Dictionary> geometry_to_lit, List lights) { + private void RenderLights(Dictionary> geometrytolit, List lights) + { graphics.Shaders.World3D.World = Matrix.Identity; graphics.Shaders.World3D.BeginPass(17); @@ -958,19 +988,24 @@ namespace CodeImp.DoomBuilder.Rendering graphics.Device.SetRenderState(RenderState.SourceBlend, Blend.One); graphics.Device.SetRenderState(RenderState.DestinationBlend, Blend.BlendFactor); - foreach (KeyValuePair> group in geometry_to_lit) { + foreach (KeyValuePair> group in geometrytolit) + { graphics.Shaders.World3D.Texture1 = group.Key; - foreach (VisualGeometry g in group.Value) { + foreach (VisualGeometry g in group.Value) + { graphics.Device.SetStreamSource(0, g.Sector.GeometryBuffer, 0, WorldVertex.Stride); //normal lights count = lightOffsets[0]; - if (lightOffsets[0] > 0) { + if (lightOffsets[0] > 0) + { graphics.Device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add); - for (i = 0; i < count; i++) { - if (checkBBoxIntersection(g.BoundingBox, lights[i].BoundingBox)) { + for (i = 0; i < count; i++) + { + if (BoundingBoxesIntersect(g.BoundingBox, lights[i].BoundingBox)) + { lpr = new Vector4(lights[i].Center, lights[i].LightRadius); if (lpr.W == 0) continue; graphics.Shaders.World3D.LightColor = lights[i].LightColor; @@ -982,12 +1017,15 @@ namespace CodeImp.DoomBuilder.Rendering } //additive lights - if (lightOffsets[1] > 0) { + if (lightOffsets[1] > 0) + { count += lightOffsets[1]; graphics.Device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add); - for (i = lightOffsets[0]; i < count; i++) { - if (checkBBoxIntersection(g.BoundingBox, lights[i].BoundingBox)) { + for (i = lightOffsets[0]; i < count; i++) + { + if (BoundingBoxesIntersect(g.BoundingBox, lights[i].BoundingBox)) + { lpr = new Vector4(lights[i].Center, lights[i].LightRadius); if (lpr.W == 0) continue; graphics.Shaders.World3D.LightColor = lights[i].LightColor; @@ -999,12 +1037,15 @@ namespace CodeImp.DoomBuilder.Rendering } //negative lights - if (lightOffsets[2] > 0) { + if (lightOffsets[2] > 0) + { count += lightOffsets[2]; graphics.Device.SetRenderState(RenderState.BlendOperation, BlendOperation.ReverseSubtract); - for (i = lightOffsets[0] + lightOffsets[1]; i < count; i++) { - if (checkBBoxIntersection(g.BoundingBox, lights[i].BoundingBox)) { + for (i = lightOffsets[0] + lightOffsets[1]; i < count; i++) + { + if (BoundingBoxesIntersect(g.BoundingBox, lights[i].BoundingBox)) + { lpr = new Vector4(lights[i].Center, lights[i].LightRadius); if (lpr.W == 0) continue; Color4 lc = lights[i].LightColor; @@ -1044,7 +1085,7 @@ namespace CodeImp.DoomBuilder.Rendering //check if model is affected by dynamic lights and set color accordingly if (General.Settings.GZDrawLightsMode != LightRenderMode.NONE && !fullbrightness && thingsWithLight.Count > 0) { - Color4 litColor = getLitColorForThing(t); + Color4 litColor = GetLitColorForThing(t); graphics.Shaders.World3D.VertexColor = vertexColor + litColor; } else @@ -1094,7 +1135,7 @@ namespace CodeImp.DoomBuilder.Rendering graphics.Shaders.World3D.World = world; graphics.Shaders.World3D.LightColor = t.Thing.Sector.FogColor; - graphics.Shaders.World3D.CameraPosition = new Vector4(cameraposition.x, cameraposition.y, cameraposition.z, getFogEnd(t.Thing.Sector)); + graphics.Shaders.World3D.CameraPosition = new Vector4(cameraposition.x, cameraposition.y, cameraposition.z, GetFogEnd(t.Thing.Sector)); } for(int i = 0; i < group.Key.Model.Meshes.Count; i++) @@ -1114,21 +1155,23 @@ namespace CodeImp.DoomBuilder.Rendering //mxd. This gets color from dynamic lights based on distance to thing. //thing position must be in absolute cordinates //(thing.Position.Z value is relative to floor of the sector the thing is in) - private Color4 getLitColorForThing(VisualThing t) { + private Color4 GetLitColorForThing(VisualThing t) + { Color4 litColor = new Color4(); float radius, radiusSquared, distSquared, scaler; int sign; - for (int i = 0; i < thingsWithLight.Count; i++ ) { + for (int i = 0; i < thingsWithLight.Count; i++ ) + { //don't light self - if (General.Map.Data.GldefsEntries.ContainsKey(t.Thing.Type) && General.Map.Data.GldefsEntries[t.Thing.Type].DontLightSelf && t.Thing.Index == thingsWithLight[i].Thing.Index) { + if (General.Map.Data.GldefsEntries.ContainsKey(t.Thing.Type) && General.Map.Data.GldefsEntries[t.Thing.Type].DontLightSelf && t.Thing.Index == thingsWithLight[i].Thing.Index) continue; - } distSquared = Vector3.DistanceSquared(thingsWithLight[i].Center, t.PositionV3); radius = thingsWithLight[i].LightRadius; radiusSquared = radius * radius; - if (distSquared < radiusSquared) { + if (distSquared < radiusSquared) + { sign = thingsWithLight[i].LightRenderStyle == DynamicLightRenderStyle.NEGATIVE ? -1 : 1; scaler = 1 - distSquared / radiusSquared * thingsWithLight[i].LightColor.Alpha; litColor.Red += thingsWithLight[i].LightColor.Red * scaler * sign; @@ -1140,11 +1183,12 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd. This returns distance, at which fog color completely replaces texture color for given sector - private static float getFogEnd(Sector s) + private static float GetFogEnd(Sector s) { float brightness = Math.Max(30, s.Brightness); - if (s.HasFogColor) { + if (s.HasFogColor) + { if(s.UsesOutsideFog && General.Map.Data.MapInfo.OutsideFogDensity > 0) return General.Map.Data.MapInfo.OutsideFogDensity; if(!s.UsesOutsideFog && General.Map.Data.MapInfo.FogDensity > 0) @@ -1156,7 +1200,7 @@ namespace CodeImp.DoomBuilder.Rendering } // This calculates the highlight/selection color - public Color4 CalculateHighlightColor(bool ishighlighted, bool isselected) + private Color4 CalculateHighlightColor(bool ishighlighted, bool isselected) { Color4 highlightcolor = isselected ? General.Colors.Selection.ToColorValue() : General.Colors.Highlight.ToColorValue(); highlightcolor.Alpha = ishighlighted ? highlightglowinv : highlightglow; @@ -1214,7 +1258,7 @@ namespace CodeImp.DoomBuilder.Rendering { t.CalculateCameraDistance3D(D3DDevice.V3(cameraposition)); //t.CameraDistance3D is actually squared distance, hence (t.LightRadius * t.LightRadius) - if(t.CameraDistance3D < (t.LightRadius * t.LightRadius) || isThingOnScreen(t.BoundingBox)) //always render light if camera is within it's radius + if(t.CameraDistance3D < (t.LightRadius * t.LightRadius) || IsThingOnScreen(t.BoundingBox)) //always render light if camera is within it's radius { if (Array.IndexOf(GZBuilder.GZGeneral.GZ_ANIMATED_LIGHT_TYPES, t.LightType) != -1) t.UpdateBoundingBox(); @@ -1223,7 +1267,7 @@ namespace CodeImp.DoomBuilder.Rendering } } - if (!isThingOnScreen(t.BoundingBox)) return; + if (!IsThingOnScreen(t.BoundingBox)) return; //mxd. gather models if(t.Thing.IsModel && General.Settings.GZDrawModelsMode != ModelRenderMode.NONE && (General.Settings.GZDrawModelsMode == ModelRenderMode.ALL || t.Selected)) @@ -1261,7 +1305,7 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private bool isThingOnScreen(Vector3[] bbox) + private bool IsThingOnScreen(Vector3[] bbox) { Vector3D camNormal = Vector3D.FromAngleXYZ(General.Map.VisualCamera.AngleXY, General.Map.VisualCamera.AngleZ); Vector3D thingNormal = D3DDevice.V3D(bbox[0]) - cameraposition; //bbox[0] is always thing center @@ -1284,8 +1328,7 @@ namespace CodeImp.DoomBuilder.Rendering if (screenPos.X > 0 && screenPos.X < 1 && screenPos.Y > 0 && screenPos.Y < 1) return true; - if (screenPos.Z < 0) - behindCount++; + if (screenPos.Z < 0) behindCount++; if (screenPos.X < 0) leftCount++; @@ -1302,16 +1345,14 @@ namespace CodeImp.DoomBuilder.Rendering } //mxd - private static bool checkBBoxIntersection(Vector3[] bbox1, Vector3[] bbox2) + private static bool BoundingBoxesIntersect(Vector3[] bbox1, Vector3[] bbox2) { Vector3 dist = bbox1[0] - bbox2[0]; Vector3 halfSize1 = bbox1[0] - bbox1[1]; Vector3 halfSize2 = bbox2[0] - bbox2[1]; - if (halfSize1.X + halfSize2.X >= Math.Abs(dist.X) && halfSize1.Y + halfSize2.Y >= Math.Abs(dist.Y) && halfSize1.Z + halfSize2.Z >= Math.Abs(dist.Z)) - return true; - return false; + return (halfSize1.X + halfSize2.X >= Math.Abs(dist.X) && halfSize1.Y + halfSize2.Y >= Math.Abs(dist.Y) && halfSize1.Z + halfSize2.Z >= Math.Abs(dist.Z)); } // This renders the crosshair @@ -1363,19 +1404,6 @@ namespace CodeImp.DoomBuilder.Rendering { crosshairbusy = busy; } - - //mxd. dbg - //private int lastTick, lastFrameRate, frameRate; - - /*private int calculateFrameRate() { - if (System.Environment.TickCount - lastTick >= 1000) { - lastFrameRate = frameRate; - frameRate = 0; - lastTick = System.Environment.TickCount; - } - frameRate++; - return lastFrameRate; - }*/ #endregion } diff --git a/Source/Core/Rendering/Things2DShader.cs b/Source/Core/Rendering/Things2DShader.cs index 4b021517..4af674c1 100644 --- a/Source/Core/Rendering/Things2DShader.cs +++ b/Source/Core/Rendering/Things2DShader.cs @@ -116,7 +116,8 @@ namespace CodeImp.DoomBuilder.Rendering //mxd. Used to render models public void SetTransformSettings(Matrix world) { - if (manager.Enabled) { + if (manager.Enabled) + { Matrix view = manager.D3DDevice.Device.GetTransform(TransformState.View); effect.SetValue(transformsettings, Matrix.Multiply(world, view)); } diff --git a/Source/Core/Rendering/World3DShader.cs b/Source/Core/Rendering/World3DShader.cs index b9a60766..d3e41cab 100644 --- a/Source/Core/Rendering/World3DShader.cs +++ b/Source/Core/Rendering/World3DShader.cs @@ -103,16 +103,21 @@ namespace CodeImp.DoomBuilder.Rendering } // Initialize world vertex declaration - if (manager.Enabled){ //mxd - vertexElements = new VertexElement[] { + if(manager.Enabled) //mxd + { + vertexElements = new[] + { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), new VertexElement(0, 16, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 24, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), //mxd VertexElement.VertexDeclarationEnd }; - } else { - vertexElements = new VertexElement[] { + } + else + { + vertexElements = new[] + { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), new VertexElement(0, 16, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), diff --git a/Source/Core/Resources/things2d.fx b/Source/Core/Resources/things2d.fx index 7cf62437..7177b77d 100644 --- a/Source/Core/Resources/things2d.fx +++ b/Source/Core/Resources/things2d.fx @@ -75,7 +75,8 @@ float4 ps_sprite(PixelData pd) : COLOR float4 c = tex2D(texture1sprite, pd.uv); // Modulate it by selection color - if(pd.color.a > 0){ + if(pd.color.a > 0) + { return float4((c.r + pd.color.r) / 2.0f, (c.g + pd.color.g) / 2.0f, (c.b + pd.color.b) / 2.0f, c.a * rendersettings.w * pd.color.a); } @@ -92,7 +93,8 @@ float4 ps_thing(PixelData pd) : COLOR } //mxd. Pretty darn simple pixel shader for wireframe rendering :) -float4 ps_fill(PixelData pd) : COLOR { +float4 ps_fill(PixelData pd) : COLOR +{ return fillColor; } diff --git a/Source/Core/Resources/world3d.fx b/Source/Core/Resources/world3d.fx index 6fcbca92..8e755401 100644 --- a/Source/Core/Resources/world3d.fx +++ b/Source/Core/Resources/world3d.fx @@ -68,7 +68,8 @@ sampler2D texturesamp = sampler_state }; // Vertex shader -PixelData vs_main(VertexData vd) { +PixelData vs_main(VertexData vd) +{ PixelData pd; // Fill pixel data input pd.pos = mul(float4(vd.pos, 1.0f), worldviewproj); @@ -79,7 +80,8 @@ PixelData vs_main(VertexData vd) { } //mxd. same as vs_main, but uses vertexColor var instead of actual vertex color. used in models rendering -PixelData vs_customvertexcolor(VertexData vd) { +PixelData vs_customvertexcolor(VertexData vd) +{ PixelData pd; // Fill pixel data input pd.pos = mul(float4(vd.pos, 1.0f), worldviewproj); @@ -90,7 +92,8 @@ PixelData vs_customvertexcolor(VertexData vd) { return pd; } -LitPixelData vs_customvertexcolor_fog(VertexData vd) { +LitPixelData vs_customvertexcolor_fog(VertexData vd) +{ LitPixelData pd; // Fill pixel data input pd.pos = mul(float4(vd.pos, 1.0f), worldviewproj); @@ -104,7 +107,8 @@ LitPixelData vs_customvertexcolor_fog(VertexData vd) { } //mxd. light pass vertex shader -LitPixelData vs_lightpass(VertexData vd) { +LitPixelData vs_lightpass(VertexData vd) +{ LitPixelData pd; pd.pos = mul(float4(vd.pos, 1.0f), worldviewproj); //pd.pos_w = mul(vd.pos, (float3x3)world); @@ -161,7 +165,8 @@ float4 ps_fullbright_highlight(PixelData pd) : COLOR } //mxd. This adds fog color to current pixel color -float4 getFogColor(LitPixelData pd, float4 color){ +float4 getFogColor(LitPixelData pd, float4 color) +{ float fogdist = max(16.0f, distance(pd.pos_w, cameraPos.xyz)); float fogfactor = min(1.0f, fogdist / cameraPos.w); //float fogfactor = exp2(cameraPos.w * fogdist); @@ -172,13 +177,15 @@ float4 getFogColor(LitPixelData pd, float4 color){ //mxd. Shaders with fog calculation // Normal pixel shader -float4 ps_main_fog(LitPixelData pd) : COLOR { +float4 ps_main_fog(LitPixelData pd) : COLOR +{ float4 tcolor = tex2D(texturesamp, pd.uv); return getFogColor(pd, tcolor * pd.color * modulatecolor); } // Normal pixel shader with highlight -float4 ps_main_highlight_fog(LitPixelData pd) : COLOR { +float4 ps_main_highlight_fog(LitPixelData pd) : COLOR +{ float4 tcolor = tex2D(texturesamp, pd.uv); // Blend texture color, vertex color and modulation color @@ -188,12 +195,14 @@ float4 ps_main_highlight_fog(LitPixelData pd) : COLOR { } //mxd: used to draw bounding boxes -float4 ps_constant_color(PixelData pd) : COLOR { +float4 ps_constant_color(PixelData pd) : COLOR +{ return vertexColor; } //mxd. dynamic light pixel shader pass, dood! -float4 ps_lightpass(LitPixelData pd) : COLOR { +float4 ps_lightpass(LitPixelData pd) : COLOR +{ //is face facing away from light source? if(dot(pd.normal, (lightPosAndRadius.xyz - pd.pos_w)) < -0.1f) // (lightPosAndRadius.xyz - pd.pos_w) == direction from light to current pixel clip(-1); @@ -212,7 +221,8 @@ float4 ps_lightpass(LitPixelData pd) : COLOR { float4 lightColorMod = float4(0.0f, 0.0f, 0.0f, 0.0f); lightColorMod.rgb = lightColor.rgb * max(lightPosAndRadius.w - dist, 0.0f) / lightPosAndRadius.w; - if(lightColorMod.r > 0.0f || lightColorMod.g > 0.0f || lightColorMod.b > 0.0f){ + if(lightColorMod.r > 0.0f || lightColorMod.g > 0.0f || lightColorMod.b > 0.0f) + { lightColorMod.rgb *= lightColor.a; if(lightColor.a > 0.4f) //Normal, vavoom or negative light return tcolor * lightColorMod; @@ -223,34 +233,40 @@ float4 ps_lightpass(LitPixelData pd) : COLOR { } // Technique for shader model 2.0 -technique SM20 { +technique SM20 +{ // Normal - pass p0 { + pass p0 + { VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_main(); } // Full brightness mode - pass p1 { + pass p1 + { VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_fullbright(); } // Normal with highlight - pass p2 { + pass p2 + { VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_main_highlight(); } // Full brightness mode with highlight - pass p3 { + pass p3 + { VertexShader = compile vs_2_0 vs_main(); PixelShader = compile ps_2_0 ps_fullbright_highlight(); } //mxd. same as p0-p3, but using vertexColor variable // Normal - pass p4 { + pass p4 + { VertexShader = compile vs_2_0 vs_customvertexcolor(); PixelShader = compile ps_2_0 ps_main(); } @@ -258,7 +274,8 @@ technique SM20 { pass p5 {} //mxd. need this only to maintain offset // Normal with highlight - pass p6 { + pass p6 + { VertexShader = compile vs_2_0 vs_customvertexcolor(); PixelShader = compile ps_2_0 ps_main_highlight(); } @@ -267,7 +284,8 @@ technique SM20 { //mxd. same as p0-p3, but with fog calculation // Normal - pass p8 { + pass p8 + { VertexShader = compile vs_2_0 vs_lightpass(); PixelShader = compile ps_2_0 ps_main_fog(); } @@ -275,7 +293,8 @@ technique SM20 { pass p9 {} //mxd. need this only to maintain offset // Normal with highlight - pass p10 { + pass p10 + { VertexShader = compile vs_2_0 vs_lightpass(); PixelShader = compile ps_2_0 ps_main_highlight_fog(); } @@ -284,7 +303,8 @@ technique SM20 { //mxd. same as p4-p7, but with fog calculation // Normal - pass p12 { + pass p12 + { VertexShader = compile vs_2_0 vs_customvertexcolor_fog(); PixelShader = compile ps_2_0 ps_main_fog(); } @@ -292,7 +312,8 @@ technique SM20 { pass p13 {} //mxd. need this only to maintain offset // Normal with highlight - pass p14 { + pass p14 + { VertexShader = compile vs_2_0 vs_customvertexcolor_fog(); PixelShader = compile ps_2_0 ps_main_highlight_fog(); } @@ -301,13 +322,15 @@ technique SM20 { pass p15 {} //mxd. need this only to maintain offset //mxd. Just fills everything with vertexColor. Used in ThingCage rendering. - pass p16 { + pass p16 + { VertexShader = compile vs_2_0 vs_customvertexcolor(); PixelShader = compile ps_2_0 ps_constant_color(); } //mxd. Light pass - pass p17 { + pass p17 + { VertexShader = compile vs_2_0 vs_lightpass(); PixelShader = compile ps_2_0 ps_lightpass(); AlphaBlendEnable = true; diff --git a/Source/Core/Types/EnumBitsHandler.cs b/Source/Core/Types/EnumBitsHandler.cs index 3ccc3220..fde60ef9 100644 --- a/Source/Core/Types/EnumBitsHandler.cs +++ b/Source/Core/Types/EnumBitsHandler.cs @@ -100,7 +100,8 @@ namespace CodeImp.DoomBuilder.Types } //mxd - public override void SetDefaultValue() { + public override void SetDefaultValue() + { value = defaultValue; } diff --git a/Source/Core/Types/EnumStringsHandler.cs b/Source/Core/Types/EnumStringsHandler.cs index 6bac9ec5..68336e38 100644 --- a/Source/Core/Types/EnumStringsHandler.cs +++ b/Source/Core/Types/EnumStringsHandler.cs @@ -121,7 +121,8 @@ namespace CodeImp.DoomBuilder.Types } //mxd - public override void SetDefaultValue() { + public override void SetDefaultValue() + { value = defaultValue; } diff --git a/Source/Core/Types/IntegerHandler.cs b/Source/Core/Types/IntegerHandler.cs index eec668f6..c3b13aef 100644 --- a/Source/Core/Types/IntegerHandler.cs +++ b/Source/Core/Types/IntegerHandler.cs @@ -45,7 +45,8 @@ namespace CodeImp.DoomBuilder.Types #region ================== Methods //mxd - public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo) { + public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo) + { defaultValue = (int)arginfo.DefaultValue; base.SetupArgument(attr, arginfo); } @@ -84,7 +85,8 @@ namespace CodeImp.DoomBuilder.Types } //mxd - public override void SetDefaultValue() { + public override void SetDefaultValue() + { value = defaultValue; } diff --git a/Source/Core/Types/RandomFloatHandler.cs b/Source/Core/Types/RandomFloatHandler.cs index 9f6b063b..62f818ba 100644 --- a/Source/Core/Types/RandomFloatHandler.cs +++ b/Source/Core/Types/RandomFloatHandler.cs @@ -30,48 +30,58 @@ namespace CodeImp.DoomBuilder.Types #region ================== Methods - public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo) { + public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo) + { base.SetupArgument(attr, arginfo); //mxd. We don't want to store this type index = (int)UniversalType.Float; } - public override void SetupField(TypeHandlerAttribute attr, UniversalFieldInfo fieldinfo) { + public override void SetupField(TypeHandlerAttribute attr, UniversalFieldInfo fieldinfo) + { base.SetupField(attr, fieldinfo); //mxd. We don't want to store this type index = (int)UniversalType.Float; } - public override void SetValue(object value) { + public override void SetValue(object value) + { float result; // Null? - if(value == null) { + if(value == null) + { this.value = 0.0f; } - // Compatible type? - else if((value is int) || (value is float) || (value is bool)) { + // Compatible type? + else if((value is int) || (value is float) || (value is bool)) + { // Set directly this.value = Convert.ToSingle(value); - } else { + } + else + { // Try parsing as string - if(float.TryParse(value.ToString(), NumberStyles.Float, CultureInfo.CurrentCulture, out result)) { + if(float.TryParse(value.ToString(), NumberStyles.Float, CultureInfo.CurrentCulture, out result)) + { this.value = result; - } else { + } + else + { //mxd. Try to parse value as random range string[] parts = value.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); - if(parts.Length == 2) { + if(parts.Length == 2) + { if(float.TryParse(parts[0], NumberStyles.Float, CultureInfo.CurrentCulture, out min) && - float.TryParse(parts[1], NumberStyles.Float, CultureInfo.CurrentCulture, out max)) { + float.TryParse(parts[1], NumberStyles.Float, CultureInfo.CurrentCulture, out max)) + { randomValue = (min != max); - if(min == max) - this.value = min; - else if(min > max) - General.Swap(ref min, ref max); + if(min == max) this.value = min; + else if(min > max) General.Swap(ref min, ref max); } } @@ -80,19 +90,22 @@ namespace CodeImp.DoomBuilder.Types } } - public override object GetValue() { + public override object GetValue() + { if(randomValue) return General.Random(min, max); //mxd return this.value; } - public override int GetIntValue() { + public override int GetIntValue() + { if(randomValue) return (int)General.Random(min, max); //mxd return (int)this.value; } - public override string GetStringValue() { - if(randomValue) return General.Random(min, max).ToString(); //mxd - return this.value.ToString(); + public override string GetStringValue() + { + if(randomValue) return General.Random(min, max).ToString(CultureInfo.InvariantCulture); //mxd + return this.value.ToString(CultureInfo.InvariantCulture); } #endregion diff --git a/Source/Core/Types/RandomIntegerHandler.cs b/Source/Core/Types/RandomIntegerHandler.cs index c318f92f..490e19ea 100644 --- a/Source/Core/Types/RandomIntegerHandler.cs +++ b/Source/Core/Types/RandomIntegerHandler.cs @@ -27,7 +27,8 @@ namespace CodeImp.DoomBuilder.Types #region ================== Methods - public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo) { + public override void SetupArgument(TypeHandlerAttribute attr, ArgumentInfo arginfo) + { defaultValue = (int)arginfo.DefaultValue; base.SetupArgument(attr, arginfo); @@ -35,41 +36,48 @@ namespace CodeImp.DoomBuilder.Types index = (int)UniversalType.Integer; } - public override void SetupField(TypeHandlerAttribute attr, UniversalFieldInfo fieldinfo) { + public override void SetupField(TypeHandlerAttribute attr, UniversalFieldInfo fieldinfo) + { base.SetupField(attr, fieldinfo); //mxd. We don't want to store this type index = (int)UniversalType.Integer; } - public override void SetValue(object value) { + public override void SetValue(object value) + { int result; // Null? - if(value == null) { + if(value == null) + { this.value = 0; } // Compatible type? - else if((value is int) || (value is float) || (value is bool)) { + else if((value is int) || (value is float) || (value is bool)) + { // Set directly this.value = Convert.ToInt32(value); - } else { + } + else + { // Try parsing as string - if(int.TryParse(value.ToString(), NumberStyles.Integer, CultureInfo.CurrentCulture, out result)) { + if(int.TryParse(value.ToString(), NumberStyles.Integer, CultureInfo.CurrentCulture, out result)) + { this.value = result; - } else { + } + else + { //mxd. Try to parse value as random range string[] parts = value.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); - - if(parts.Length == 2) { + if(parts.Length == 2) + { if(int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.CurrentCulture, out min) && - int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.CurrentCulture, out max)) { + int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.CurrentCulture, out max)) + { randomValue = (min != max); - - if(min == max) - this.value = min; - else if(min > max) - General.Swap(ref min, ref max); + if(min == max) this.value = min; + else if(min > max) General.Swap(ref min, ref max); } } @@ -77,29 +85,32 @@ namespace CodeImp.DoomBuilder.Types } } - if(forargument) { + if(forargument) this.value = General.Clamp(this.value, General.Map.FormatInterface.MinArgument, General.Map.FormatInterface.MaxArgument); - } } //mxd - public override void SetDefaultValue() { + public override void SetDefaultValue() + { value = defaultValue; } - public override object GetValue() { + public override object GetValue() + { if(randomValue) return General.Random(min, max); //mxd return this.value; } - public override int GetIntValue() { + public override int GetIntValue() + { if(randomValue) return General.Random(min, max); //mxd return this.value; } - public override string GetStringValue() { - if(randomValue) return General.Random(min, max).ToString(); //mxd - return this.value.ToString(); + public override string GetStringValue() + { + if(randomValue) return General.Random(min, max).ToString(CultureInfo.InvariantCulture); //mxd + return this.value.ToString(CultureInfo.InvariantCulture); } #endregion diff --git a/Source/Core/VisualModes/VisualCamera.cs b/Source/Core/VisualModes/VisualCamera.cs index 5b1123df..66af0f51 100644 --- a/Source/Core/VisualModes/VisualCamera.cs +++ b/Source/Core/VisualModes/VisualCamera.cs @@ -40,7 +40,7 @@ namespace CodeImp.DoomBuilder.VisualModes public Vector3D Target { get { return target; } } public float AngleXY { get { return anglexy; } set { anglexy = value; } } public float AngleZ { get { return anglez; } set { anglez = value; } } - public Sector Sector { get { return sector; } internal set { sector = value; updateGravity(); } } //mxd + public Sector Sector { get { return sector; } internal set { sector = value; UpdateGravity(); } } //mxd public Vector3D MoveMultiplier { get { return movemultiplier; } set { movemultiplier = value; } } public float Gravity { get { return gravity; } } //mxd @@ -148,8 +148,7 @@ namespace CodeImp.DoomBuilder.VisualModes if(modething != null) { int z = 0; - if(sector != null) - z = (int)position.z - sector.FloorHeight; + if(sector != null) z = (int)position.z - sector.FloorHeight; // Position the thing to match camera modething.Move((int)position.x, (int)position.y, z - THING_Z_OFFSET); @@ -161,7 +160,8 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd - private void updateGravity() { + private void UpdateGravity() + { if(!udmf || sector == null) return; gravity = sector.Fields.GetValue("gravity", 1.0f); } diff --git a/Source/Core/VisualModes/VisualMode.cs b/Source/Core/VisualModes/VisualMode.cs index 509a8b6e..2b308324 100644 --- a/Source/Core/VisualModes/VisualMode.cs +++ b/Source/Core/VisualModes/VisualMode.cs @@ -112,7 +112,8 @@ namespace CodeImp.DoomBuilder.VisualModes this.vertices = new Dictionary(); //mxd //mxd. Synch camera position to cursor position or center of the screen in 2d-mode - if (General.Settings.GZSynchCameras && General.Editing.Mode is ClassicMode) { + if (General.Settings.GZSynchCameras && General.Editing.Mode is ClassicMode) + { ClassicMode oldmode = General.Editing.Mode as ClassicMode; if(oldmode.IsMouseInside) @@ -270,20 +271,24 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd - public override bool OnMapTestBegin(bool testFromCurrentPosition) { - if (testFromCurrentPosition) { + public override bool OnMapTestBegin(bool testFromCurrentPosition) + { + if (testFromCurrentPosition) + { //find Single Player Start. Should have Type 1 in all games Thing start = null; - - foreach (Thing t in General.Map.Map.Things) { - if (t.Type == 1) { + foreach (Thing t in General.Map.Map.Things) + { + if (t.Type == 1) + { //store thing and position start = t; break; } } - if (start == null) { + if (start == null) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: no Player 1 start found!"); return false; } @@ -292,13 +297,15 @@ namespace CodeImp.DoomBuilder.VisualModes Vector3D camPos = General.Map.VisualCamera.Position; Sector s = General.Map.Map.GetSectorByCoordinates(new Vector2D(camPos.x, camPos.y), blockmap); - if (s == null) { + if (s == null) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: cursor is not inside sector!"); return false; } //41 = player's height in Doom. Is that so in all other games as well? - if (s.CeilHeight - s.FloorHeight < 41) { + if (s.CeilHeight - s.FloorHeight < 41) + { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: sector is too low!"); return false; } @@ -322,8 +329,10 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd - public override void OnMapTestEnd(bool testFromCurrentPosition) { - if (testFromCurrentPosition) { + public override void OnMapTestEnd(bool testFromCurrentPosition) + { + if (testFromCurrentPosition) + { //restore position playerStart.Move(playerStartPosition); playerStart.Rotate(playerStartAngle); @@ -467,20 +476,20 @@ namespace CodeImp.DoomBuilder.VisualModes if (target.picked is VisualGeometry) { VisualGeometry vg = target.picked as VisualGeometry; - return getIntersection(start, start + delta, new Vector3D(vg.BoundingBox[0].X, vg.BoundingBox[0].Y, vg.BoundingBox[0].Z), new Vector3D(vg.Vertices[0].nx, vg.Vertices[0].ny, vg.Vertices[0].nz)); + return GetIntersection(start, start + delta, new Vector3D(vg.BoundingBox[0].X, vg.BoundingBox[0].Y, vg.BoundingBox[0].Z), new Vector3D(vg.Vertices[0].nx, vg.Vertices[0].ny, vg.Vertices[0].nz)); } if (target.picked is VisualThing) { VisualThing vt = target.picked as VisualThing; - return getIntersection(start, start + delta, new Vector3D(vt.BoundingBox[0].X, vt.BoundingBox[0].Y, vt.BoundingBox[0].Z), D3DDevice.V3D(vt.Center - vt.PositionV3)); + return GetIntersection(start, start + delta, new Vector3D(vt.BoundingBox[0].X, vt.BoundingBox[0].Y, vt.BoundingBox[0].Z), D3DDevice.V3D(vt.Center - vt.PositionV3)); } return new Vector2D(float.NaN, float.NaN); } //mxd. This checks intersection between line and plane - protected Vector2D getIntersection(Vector3D start, Vector3D end, Vector3D planeCenter, Vector3D planeNormal) + private static Vector2D GetIntersection(Vector3D start, Vector3D end, Vector3D planeCenter, Vector3D planeNormal) { Vector3D delta = new Vector3D(planeCenter.x - start.x, planeCenter.y - start.y, planeCenter.z - start.z); return start + Vector3D.DotProduct(planeNormal, delta) / Vector3D.DotProduct(planeNormal, end - start) * (end - start); @@ -788,11 +797,11 @@ namespace CodeImp.DoomBuilder.VisualModes } // Add all the visible things - foreach(VisualThing vt in visiblethings) - pickables.Add(vt); + foreach(VisualThing vt in visiblethings) pickables.Add(vt); //mxd. And all visual vertices - if(General.Map.UDMF && General.Settings.GZShowVisualVertices) { + if(General.Map.UDMF && General.Settings.GZShowVisualVertices) + { foreach(KeyValuePair pair in vertices) pickables.AddRange(pair.Value.Vertices); } @@ -953,7 +962,8 @@ namespace CodeImp.DoomBuilder.VisualModes /// /// This returns the VisualSector for the given Sector. /// - public VisualSector GetVisualSector(Sector s) { + public VisualSector GetVisualSector(Sector s) + { if(!allsectors.ContainsKey(s)) return CreateVisualSector(s); //mxd return allsectors[s]; } @@ -966,15 +976,18 @@ namespace CodeImp.DoomBuilder.VisualModes //mxd public List GetSelectedVisualThings(bool refreshSelection) { - if (refreshSelection || selectedVisualThings == null) { + if (refreshSelection || selectedVisualThings == null) + { selectedVisualThings = new List(); - foreach (KeyValuePair group in allthings) { + foreach (KeyValuePair group in allthings) + { if (group.Value != null && group.Value.Selected) selectedVisualThings.Add(group.Value); } //if nothing is selected - try to get thing from hilighted object - if (selectedVisualThings.Count == 0) { + if (selectedVisualThings.Count == 0) + { Vector3D start = General.Map.VisualCamera.Position; Vector3D delta = General.Map.VisualCamera.Target - General.Map.VisualCamera.Position; delta = delta.GetFixedLength(General.Settings.ViewDistance * 0.98f); @@ -994,11 +1007,15 @@ namespace CodeImp.DoomBuilder.VisualModes /// public List GetSelectedVisualSectors(bool refreshSelection) { - if (refreshSelection || selectedVisualSectors == null) { + if (refreshSelection || selectedVisualSectors == null) + { selectedVisualSectors = new List(); - foreach (KeyValuePair group in allsectors) { - foreach (VisualGeometry vg in group.Value.AllGeometry) { - if (vg.Selected) { + foreach (KeyValuePair group in allsectors) + { + foreach (VisualGeometry vg in group.Value.AllGeometry) + { + if (vg.Selected) + { selectedVisualSectors.Add(group.Value); break; } @@ -1006,8 +1023,9 @@ namespace CodeImp.DoomBuilder.VisualModes } //if nothing is selected - try to get sector from hilighted object - if (selectedVisualSectors.Count == 0) { - VisualGeometry vg = getHilightedSurface(); + if (selectedVisualSectors.Count == 0) + { + VisualGeometry vg = GetHilightedSurface(); if (vg != null) selectedVisualSectors.Add(vg.Sector); } } @@ -1020,29 +1038,33 @@ namespace CodeImp.DoomBuilder.VisualModes public List GetSelectedSurfaces() { List selectedSurfaces = new List(); - foreach (KeyValuePair group in allsectors) { - foreach (VisualGeometry vg in group.Value.AllGeometry) { + foreach (KeyValuePair group in allsectors) + { + foreach (VisualGeometry vg in group.Value.AllGeometry) + { if (vg.Selected) selectedSurfaces.Add(vg); } } //if nothing is selected - try to get hilighted surface - if (selectedSurfaces.Count == 0) { - VisualGeometry vg = getHilightedSurface(); + if (selectedSurfaces.Count == 0) + { + VisualGeometry vg = GetHilightedSurface(); if (vg != null) selectedSurfaces.Add(vg); } return selectedSurfaces; } //mxd - private VisualGeometry getHilightedSurface() + private VisualGeometry GetHilightedSurface() { Vector3D start = General.Map.VisualCamera.Position; Vector3D delta = General.Map.VisualCamera.Target - General.Map.VisualCamera.Position; delta = delta.GetFixedLength(General.Settings.ViewDistance * 0.98f); VisualPickResult target = PickObject(start, start + delta); - if(target.picked is VisualGeometry) { + if(target.picked is VisualGeometry) + { VisualGeometry vg = (VisualGeometry)target.picked; if (vg.Sector != null) return vg; } @@ -1119,17 +1141,18 @@ namespace CodeImp.DoomBuilder.VisualModes //mxd [BeginAction("centeroncoordinates", BaseAction = true)] - protected virtual void CenterOnCoordinates() { + protected virtual void CenterOnCoordinates() + { //show form... CenterOnCoordinatesForm form = new CenterOnCoordinatesForm(); - if(form.ShowDialog() == DialogResult.OK) { + if(form.ShowDialog() == DialogResult.OK) + { Sector s = General.Map.Map.GetSectorByCoordinates(form.Coordinates, blockmap); - if (s == null) { + if (s == null) General.Map.VisualCamera.Position = form.Coordinates; - } else { + else General.Map.VisualCamera.Position = new Vector3D(form.Coordinates.x, form.Coordinates.y, s.FloorHeight + 54); - } General.Map.VisualCamera.Sector = s; } } diff --git a/Source/Core/VisualModes/VisualThing.cs b/Source/Core/VisualModes/VisualThing.cs index 99f4a3e3..ae9b4d37 100644 --- a/Source/Core/VisualModes/VisualThing.cs +++ b/Source/Core/VisualModes/VisualThing.cs @@ -198,7 +198,8 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd - internal void CalculateCameraDistance3D(Vector3 campos) { + internal void CalculateCameraDistance3D(Vector3 campos) + { cameraDistance3D = (int)Vector3.DistanceSquared(PositionV3, campos); } @@ -249,12 +250,17 @@ namespace CodeImp.DoomBuilder.VisualModes position = Matrix.Translation(position_v3); //mxd. update bounding box - if (thing.IsModel) { - updateBoundingBoxForModel(); - } else if (lightType != DynamicLightType.NONE && lightRadius > thing.Size) { - updateBoundingBox(lightRadius, lightRadius * 2); - } else { - updateBoundingBox((int)thing.Size, thingHeight); + if (thing.IsModel) + { + UpdateBoundingBoxForModel(); + } + else if (lightType != DynamicLightType.NONE && lightRadius > thing.Size) + { + UpdateBoundingBox(lightRadius, lightRadius * 2); + } + else + { + UpdateBoundingBox((int)thing.Size, thingHeight); } } @@ -279,7 +285,8 @@ namespace CodeImp.DoomBuilder.VisualModes geobuffer = null; // Any vertics? - if (vertices.Length > 0) { + if (vertices.Length > 0) + { // Make a new buffer geobuffer = new VertexBuffer(General.Map.Graphics.Device, WorldVertex.Stride * vertices.Length, Usage.WriteOnly | Usage.Dynamic, VertexFormat.None, Pool.Default); @@ -292,7 +299,7 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd. Check if thing is light - checkLightState(); + CheckLightState(); // Done updategeo = false; @@ -300,26 +307,31 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd - protected void checkLightState() { + protected void CheckLightState() + { //mxd. Check if thing is light int light_id = Array.IndexOf(GZBuilder.GZGeneral.GZ_LIGHTS, thing.Type); - if (light_id != -1) { + if (light_id != -1) + { isGldefsLight = false; lightInterval = -1; - updateLight(light_id); - updateBoundingBox(lightRadius, lightRadius * 2); - - //check if we have light from GLDEFS - } else if (General.Map.Data.GldefsEntries.ContainsKey(thing.Type)) { + UpdateLight(light_id); + UpdateBoundingBox(lightRadius, lightRadius * 2); + } + //check if we have light from GLDEFS + else if (General.Map.Data.GldefsEntries.ContainsKey(thing.Type)) + { isGldefsLight = true; - updateGldefsLight(); - updateBoundingBox(lightRadius, lightRadius * 2); - } else { - if (thing.IsModel) { - updateBoundingBoxForModel(); - } else { - updateBoundingBox((int)thing.Size, thingHeight); - } + UpdateGldefsLight(); + UpdateBoundingBox(lightRadius, lightRadius * 2); + } + else + { + if (thing.IsModel) + UpdateBoundingBoxForModel(); + else + UpdateBoundingBox((int)thing.Size, thingHeight); + lightType = DynamicLightType.NONE; lightRadius = -1; lightPrimaryRadius = -1; @@ -331,47 +343,58 @@ namespace CodeImp.DoomBuilder.VisualModes } //used in ColorPicker to update light - public void UpdateLight() { + public void UpdateLight() + { int light_id = Array.IndexOf(GZBuilder.GZGeneral.GZ_LIGHTS, thing.Type); - if (light_id != -1) { - updateLight(light_id); - updateBoundingBox(lightRadius, lightRadius * 2); + if (light_id != -1) + { + UpdateLight(light_id); + UpdateBoundingBox(lightRadius, lightRadius * 2); } } //mxd update light info - private void updateLight(int light_id) { + private void UpdateLight(int lightId) + { float scaled_intensity = 255.0f / General.Settings.GZDynamicLightIntensity; - if (light_id < GZBuilder.GZGeneral.GZ_LIGHT_TYPES[2]) { //if it's gzdoom light + if (lightId < GZBuilder.GZGeneral.GZ_LIGHT_TYPES[2]) //if it's gzdoom light + { int n; - if (light_id < GZBuilder.GZGeneral.GZ_LIGHT_TYPES[0]) { + if (lightId < GZBuilder.GZGeneral.GZ_LIGHT_TYPES[0]) + { n = 0; lightRenderStyle = DynamicLightRenderStyle.NORMAL; //lightColor.Alpha used in shader to perform some calculations based on light type lightColor = new Color4((float)lightRenderStyle / 100.0f, thing.Args[0] / scaled_intensity, thing.Args[1] / scaled_intensity, thing.Args[2] / scaled_intensity); - } else if (light_id < GZBuilder.GZGeneral.GZ_LIGHT_TYPES[1]) { + } + else if (lightId < GZBuilder.GZGeneral.GZ_LIGHT_TYPES[1]) + { n = 10; lightRenderStyle = DynamicLightRenderStyle.ADDITIVE; lightColor = new Color4((float)lightRenderStyle / 100.0f, thing.Args[0] / scaled_intensity, thing.Args[1] / scaled_intensity, thing.Args[2] / scaled_intensity); - } else { + } + else + { n = 20; lightRenderStyle = DynamicLightRenderStyle.NEGATIVE; lightColor = new Color4((float)lightRenderStyle / 100.0f, thing.Args[0] / scaled_intensity, thing.Args[1] / scaled_intensity, thing.Args[2] / scaled_intensity); } lightType = (DynamicLightType)(thing.Type - 9800 - n); - if (lightType == DynamicLightType.SECTOR) { + if (lightType == DynamicLightType.SECTOR) + { int scaler = 1; - if (thing.Sector != null) - scaler = thing.Sector.Brightness / 4; + if (thing.Sector != null) scaler = thing.Sector.Brightness / 4; lightPrimaryRadius = (thing.Args[3] * scaler) * General.Settings.GZDynamicLightRadius; - } else { + } + else + { lightPrimaryRadius = (thing.Args[3] * 2) * General.Settings.GZDynamicLightRadius; //works... that.. way in GZDoom - if (lightType > 0) - lightSecondaryRadius = (thing.Args[4] * 2) * General.Settings.GZDynamicLightRadius; + if (lightType > 0) lightSecondaryRadius = (thing.Args[4] * 2) * General.Settings.GZDynamicLightRadius; } - } else { //it's one of vavoom lights + } else //it's one of vavoom lights + { lightRenderStyle = DynamicLightRenderStyle.VAVOOM; lightType = (DynamicLightType)thing.Type; if (lightType == DynamicLightType.VAVOOM_COLORED) @@ -384,7 +407,8 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd - private void updateGldefsLight() { + private void UpdateGldefsLight() + { DynamicLightData light = General.Map.Data.GldefsEntries[thing.Type]; float intensity_mod = General.Settings.GZDynamicLightIntensity; float scale_mod = General.Settings.GZDynamicLightRadius; @@ -395,35 +419,43 @@ namespace CodeImp.DoomBuilder.VisualModes lightOffset = light.Offset; lightType = light.Type; - if (lightType == DynamicLightType.SECTOR) { + if (lightType == DynamicLightType.SECTOR) + { lightPrimaryRadius = light.Interval * thing.Sector.Brightness / 5; - } else { + } + else + { lightPrimaryRadius = light.PrimaryRadius * scale_mod; lightSecondaryRadius = light.SecondaryRadius * scale_mod; } lightInterval = light.Interval; - updateLightRadius(lightInterval); + UpdateLightRadius(lightInterval); } //mxd - public void UpdateLightRadius() { - updateLightRadius( (lightInterval != -1 ? lightInterval : thing.AngleDoom) ); + public void UpdateLightRadius() + { + UpdateLightRadius( (lightInterval != -1 ? lightInterval : thing.AngleDoom) ); } //mxd - private void updateLightRadius(int interval) { - if (lightType == DynamicLightType.NONE) { + private void UpdateLightRadius(int interval) + { + if (lightType == DynamicLightType.NONE) + { General.ErrorLogger.Add(ErrorType.Error, "Please check that thing is light before accessing it's PositionAndRadius! You can use lightType, which is -1 if thing isn't light"); return; } - if (General.Settings.GZDrawLightsMode == LightRenderMode.ALL || Array.IndexOf(GZBuilder.GZGeneral.GZ_ANIMATED_LIGHT_TYPES, lightType) == -1) { + if (General.Settings.GZDrawLightsMode == LightRenderMode.ALL || Array.IndexOf(GZBuilder.GZGeneral.GZ_ANIMATED_LIGHT_TYPES, lightType) == -1) + { lightRadius = lightPrimaryRadius; return; } - if(interval == 0) { + if(interval == 0) + { lightRadius = 0; return; } @@ -433,7 +465,8 @@ namespace CodeImp.DoomBuilder.VisualModes float rMax = Math.Max(lightPrimaryRadius, lightSecondaryRadius); float diff = rMax - rMin; - switch (lightType) { + switch (lightType) + { case DynamicLightType.PULSE: lightDelta = ((float)Math.Sin(time / (interval * 4.0f)) + 1.0f) / 2.0f; //just playing by the eye here... in [0.0 ... 1.0] interval lightRadius = rMin + diff * lightDelta; @@ -441,7 +474,8 @@ namespace CodeImp.DoomBuilder.VisualModes case DynamicLightType.FLICKER: float fdelta = (float)Math.Sin(time / 0.1f); //just playing by the eye here... - if (Math.Sign(fdelta) != Math.Sign(lightDelta)) { + if (Math.Sign(fdelta) != Math.Sign(lightDelta)) + { lightDelta = fdelta; lightRadius = (General.Random(0, 359) < interval ? rMax : rMin); } @@ -449,7 +483,8 @@ namespace CodeImp.DoomBuilder.VisualModes case DynamicLightType.RANDOM: float rdelta = (float)Math.Sin(time / (interval * 9.0f)); //just playing by the eye here... - if (Math.Sign(rdelta) != Math.Sign(lightDelta)) { + if (Math.Sign(rdelta) != Math.Sign(lightDelta)) + { lightRadius = rMin + (General.Random(0, (int) (diff * 10))) / 10.0f; } lightDelta = rdelta; @@ -458,17 +493,18 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd. update bounding box - public void UpdateBoundingBox() { - if (thing.IsModel) { - updateBoundingBoxForModel(); - } else if (lightType != DynamicLightType.NONE && lightRadius > thing.Size) { - updateBoundingBox(lightRadius, lightRadius * 2); - } else { - updateBoundingBox((int)thing.Size, thingHeight); - } + public void UpdateBoundingBox() + { + if (thing.IsModel) + UpdateBoundingBoxForModel(); + else if (lightType != DynamicLightType.NONE && lightRadius > thing.Size) + UpdateBoundingBox(lightRadius, lightRadius * 2); + else + UpdateBoundingBox((int)thing.Size, thingHeight); } - private void updateBoundingBox(float width, float height) { + private void UpdateBoundingBox(float width, float height) + { boundingBox = new Vector3[9]; boundingBox[0] = Center; float h2 = height / 2.0f; @@ -485,11 +521,13 @@ namespace CodeImp.DoomBuilder.VisualModes } //mxd. update bounding box from model bounding box - private void updateBoundingBoxForModel() { + private void UpdateBoundingBoxForModel() + { ModelData mde = General.Map.Data.ModeldefEntries[thing.Type]; int len = mde.Model.BoundingBox.Length; boundingBox = new Vector3[len]; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { Vector3 v = mde.Model.BoundingBox[i]; boundingBox[i] = new Vector3(v.X + position_v3.X, v.Y + position_v3.Y, v.Z + position_v3.Z); } diff --git a/Source/Core/VisualModes/VisualVertex.cs b/Source/Core/VisualModes/VisualVertex.cs index 5847351f..d0780682 100644 --- a/Source/Core/VisualModes/VisualVertex.cs +++ b/Source/Core/VisualModes/VisualVertex.cs @@ -15,7 +15,8 @@ namespace CodeImp.DoomBuilder.VisualModes public VisualVertex CeilingVertex { get { return ceilvert; } } public bool Changed { set { floorvert.Changed = value; ceilvert.Changed = value; } } - public VisualVertexPair(VisualVertex floorvert, VisualVertex ceilvert) { + public VisualVertexPair(VisualVertex floorvert, VisualVertex ceilvert) + { if(floorvert.CeilingVertex == ceilvert.CeilingVertex) throw new Exception("VisualVertexPair: both verts have the same alignment! We cannot tolerate this!"); @@ -23,12 +24,14 @@ namespace CodeImp.DoomBuilder.VisualModes this.ceilvert = ceilvert; } - public void Update() { + public void Update() + { if(floorvert.Changed) floorvert.Update(); if(ceilvert.Changed) ceilvert.Update(); } - public void Deselect() { + public void Deselect() + { floorvert.Selected = false; ceilvert.Selected = false; } @@ -56,18 +59,21 @@ namespace CodeImp.DoomBuilder.VisualModes public bool CeilingVertex { get { return ceilingVertex; } } public bool HaveHeightOffset { get { return haveOffset; } } - public VisualVertex(Vertex v, bool ceilingVertex) { + public VisualVertex(Vertex v, bool ceilingVertex) + { vertex = v; position = Matrix.Identity; this.ceilingVertex = ceilingVertex; } // This sets the distance from the camera - internal void CalculateCameraDistance(Vector2D campos) { + internal void CalculateCameraDistance(Vector2D campos) + { cameradistance = Vector2D.DistanceSq(vertex.Position, campos); } - public void SetPosition(Vector3D pos) { + public void SetPosition(Vector3D pos) + { position = Matrix.Translation(pos.x, pos.y, pos.z); } @@ -77,7 +83,8 @@ namespace CodeImp.DoomBuilder.VisualModes /// This is called when the thing must be tested for line intersection. This should reject /// as fast as possible to rule out all geometry that certainly does not touch the line. /// - public virtual bool PickFastReject(Vector3D from, Vector3D to, Vector3D dir) { + public virtual bool PickFastReject(Vector3D from, Vector3D to, Vector3D dir) + { return false; } @@ -85,14 +92,16 @@ namespace CodeImp.DoomBuilder.VisualModes /// This is called when the thing must be tested for line intersection. This should perform /// accurate hit detection and set u_ray to the position on the ray where this hits the geometry. /// - public virtual bool PickAccurate(Vector3D from, Vector3D to, Vector3D dir, ref float u_ray) { + public virtual bool PickAccurate(Vector3D from, Vector3D to, Vector3D dir, ref float u_ray) + { return false; } /// /// This sorts things by distance from the camera. Farthest first. /// - public int CompareTo(VisualVertex other) { + public int CompareTo(VisualVertex other) + { return Math.Sign(other.cameradistance - this.cameradistance); } } diff --git a/Source/Core/Windows/AboutForm.cs b/Source/Core/Windows/AboutForm.cs index 6259e998..43e4b5ed 100644 --- a/Source/Core/Windows/AboutForm.cs +++ b/Source/Core/Windows/AboutForm.cs @@ -48,7 +48,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void gzdbLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { + private void gzdbLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { General.OpenWebsite("http://forum.zdoom.org/viewtopic.php?f=3&t=32392"); } diff --git a/Source/Core/Windows/ActionBrowserForm.cs b/Source/Core/Windows/ActionBrowserForm.cs index 18568633..2732465b 100644 --- a/Source/Core/Windows/ActionBrowserForm.cs +++ b/Source/Core/Windows/ActionBrowserForm.cs @@ -61,7 +61,7 @@ namespace CodeImp.DoomBuilder.Windows } // Go for all predefined categories - createActionCategories(action); + CreateActionCategories(action); allNodes = new TreeNode[actions.Nodes.Count]; actions.Nodes.CopyTo(allNodes, 0); @@ -123,33 +123,41 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void createActionCategories(int action) { + private void CreateActionCategories(int action) + { TreeNode cn, n; actions.BeginUpdate(); actions.ShowLines = true; - foreach (LinedefActionCategory ac in General.Map.Config.ActionCategories) { + foreach (LinedefActionCategory ac in General.Map.Config.ActionCategories) + { // Empty category names will not be created // (those actions will go in the root of the tree) - if (ac.Title.Length > 0) { + if (ac.Title.Length > 0) + { // Create category cn = actions.Nodes.Add(ac.Title); - foreach (LinedefActionInfo ai in ac.Actions) { + foreach (LinedefActionInfo ai in ac.Actions) + { // Create action n = cn.Nodes.Add(ai.Title); n.Tag = ai; // This is the given action? - if (ai.Index == action) { + if (ai.Index == action) + { // Select this and expand the category cn.Expand(); actions.SelectedNode = n; n.EnsureVisible(); } } - } else { + } + else + { // Put actions in the tree root - foreach (LinedefActionInfo ai in ac.Actions) { + foreach (LinedefActionInfo ai in ac.Actions) + { // Create action n = actions.Nodes.Add(ai.Title); n.Tag = ai; @@ -160,13 +168,15 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void filterActions(string p) { + private void FilterActions(string p) + { List filteredNodes = new List(); - foreach (TreeNode n in allNodes) { - foreach (TreeNode cn in n.Nodes) { + foreach (TreeNode n in allNodes) + { + foreach (TreeNode cn in n.Nodes) + { LinedefActionInfo ai = cn.Tag as LinedefActionInfo; - if (ai.Title.ToLowerInvariant().IndexOf(p) != -1) filteredNodes.Add(cn); } @@ -288,22 +298,28 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void tbFilter_TextChanged(object sender, EventArgs e) { - if (tbFilter.Text.Length > 1) { - filterActions(tbFilter.Text); - } else if (String.IsNullOrEmpty(tbFilter.Text.ToLowerInvariant())) { + private void tbFilter_TextChanged(object sender, EventArgs e) + { + if (tbFilter.Text.Length > 1) + { + FilterActions(tbFilter.Text); + } + else if (String.IsNullOrEmpty(tbFilter.Text.ToLowerInvariant())) + { actions.Nodes.Clear(); - createActionCategories(actions.SelectedNode != null ? ((LinedefActionInfo)actions.SelectedNode.Tag).Index : 0); + CreateActionCategories(actions.SelectedNode != null ? ((LinedefActionInfo)actions.SelectedNode.Tag).Index : 0); } } //mxd - private void btnClearFilter_Click(object sender, EventArgs e) { + private void btnClearFilter_Click(object sender, EventArgs e) + { tbFilter.Clear(); } //mxd - private void ActionBrowserForm_Shown(object sender, EventArgs e) { + private void ActionBrowserForm_Shown(object sender, EventArgs e) + { tbFilter.Focus(); } } diff --git a/Source/Core/Windows/CenterOnCoordinatesForm.Designer.cs b/Source/Core/Windows/CenterOnCoordinatesForm.Designer.cs index 75e38741..4caaed7f 100644 --- a/Source/Core/Windows/CenterOnCoordinatesForm.Designer.cs +++ b/Source/Core/Windows/CenterOnCoordinatesForm.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.accept = new System.Windows.Forms.Button(); diff --git a/Source/Core/Windows/ChangeMapForm.Designer.cs b/Source/Core/Windows/ChangeMapForm.Designer.cs index ebcd5c69..24a6d27f 100644 --- a/Source/Core/Windows/ChangeMapForm.Designer.cs +++ b/Source/Core/Windows/ChangeMapForm.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { System.Windows.Forms.Label label2; System.Windows.Forms.ColumnHeader columnHeader1; this.mapslist = new System.Windows.Forms.ListView(); diff --git a/Source/Core/Windows/ConfigForm.cs b/Source/Core/Windows/ConfigForm.cs index cd5cbc7d..fcfcda10 100644 --- a/Source/Core/Windows/ConfigForm.cs +++ b/Source/Core/Windows/ConfigForm.cs @@ -341,7 +341,8 @@ namespace CodeImp.DoomBuilder.Windows private void ApplyTestEngineNameChange() { int index = (int)cbEngineSelector.Tag; - if(index != -1 && cbEngineSelector.Text != cbEngineSelector.Items[index].ToString()) { + if(index != -1 && cbEngineSelector.Text != cbEngineSelector.Items[index].ToString()) + { cbEngineSelector.Items[index] = cbEngineSelector.Text; configinfo.TestProgramName = cbEngineSelector.Text; configinfo.Changed = true; //mxd @@ -358,7 +359,8 @@ namespace CodeImp.DoomBuilder.Windows if(configinfo != null) ApplyTestEngineNameChange(); //mxd. Apply configuration items. They should be in the same order, riiiight? - for(int i = 0; i < listconfigs.Items.Count; i++) { + for(int i = 0; i < listconfigs.Items.Count; i++) + { // Get configuration item ci = listconfigs.Items[i].Tag as ConfigurationInfo; ci.Enabled = listconfigs.Items[i].Checked; @@ -668,7 +670,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void btnNewEngine_Click(object sender, EventArgs e) { + private void btnNewEngine_Click(object sender, EventArgs e) + { EngineInfo newInfo = new EngineInfo(); newInfo.TestSkill = (int)Math.Ceiling(gameconfig.Skills.Count / 2f); //set Medium skill level configinfo.TestEngines.Add(newInfo); @@ -689,7 +692,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void btnRemoveEngine_Click(object sender, EventArgs e) { + private void btnRemoveEngine_Click(object sender, EventArgs e) + { //remove params int index = cbEngineSelector.SelectedIndex; cbEngineSelector.SelectedIndex = -1; @@ -711,7 +715,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void cbEngineSelector_SelectedIndexChanged(object sender, EventArgs e) { + private void cbEngineSelector_SelectedIndexChanged(object sender, EventArgs e) + { if(cbEngineSelector.SelectedIndex == -1) return; //set new values @@ -738,22 +743,23 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void cbEngineSelector_DropDown(object sender, EventArgs e) { + private void cbEngineSelector_DropDown(object sender, EventArgs e) + { ApplyTestEngineNameChange(); } //mxd - private void colorsControl_PresetsChanged(object sender, EventArgs e) { + private void colorsControl_PresetsChanged(object sender, EventArgs e) + { if(configinfo == null) return; configinfo.LinedefColorPresets = colorsControl.GetPresets(); configinfo.Changed = true; //mxd } //mxd - private void ConfigForm_Shown(object sender, EventArgs e) { - if (listconfigs.SelectedItems.Count > 0) { - listconfigs.SelectedItems[0].EnsureVisible(); - } + private void ConfigForm_Shown(object sender, EventArgs e) + { + if (listconfigs.SelectedItems.Count > 0) listconfigs.SelectedItems[0].EnsureVisible(); } #region ============= Copy/Paste context menu (mxd) diff --git a/Source/Core/Windows/EffectBrowserForm.cs b/Source/Core/Windows/EffectBrowserForm.cs index 0eeb4124..ad9f0eaf 100644 --- a/Source/Core/Windows/EffectBrowserForm.cs +++ b/Source/Core/Windows/EffectBrowserForm.cs @@ -55,7 +55,7 @@ namespace CodeImp.DoomBuilder.Windows option5label, option6label, option7label }; // Go for all predefined effects - selected = createEffects(effect); //mxd + selected = CreateEffects(effect); //mxd allItems = new ListViewItem[effects.Items.Count]; //mxd effects.Items.CopyTo(allItems, 0); //mxd @@ -118,16 +118,19 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private bool createEffects(int effect) { + private bool CreateEffects(int effect) + { bool selected = false; ListViewItem n; - foreach (SectorEffectInfo si in General.Map.Config.SortedSectorEffects) { + foreach (SectorEffectInfo si in General.Map.Config.SortedSectorEffects) + { // Create effect n = effects.Items.Add(si.Index.ToString()); n.SubItems.Add(si.Title); n.Tag = si; - if (si.Index == effect) { + if (si.Index == effect) + { selected = true; n.Selected = true; } @@ -136,12 +139,13 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void filterEffects(string p) { + private void FilterEffects(string p) + { List filteredItems = new List(); - foreach (ListViewItem i in allItems) { + foreach (ListViewItem i in allItems) + { SectorEffectInfo si = i.Tag as SectorEffectInfo; - if (si.Title.ToLowerInvariant().IndexOf(p) != -1) filteredItems.Add(i); } @@ -208,17 +212,22 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void tbFilter_TextChanged(object sender, EventArgs e) { - if (tbFilter.Text.Length > 1) { - filterEffects(tbFilter.Text); - } else if (String.IsNullOrEmpty(tbFilter.Text.ToLowerInvariant())) { + private void tbFilter_TextChanged(object sender, EventArgs e) + { + if (tbFilter.Text.Length > 1) + { + FilterEffects(tbFilter.Text); + } + else if (String.IsNullOrEmpty(tbFilter.Text.ToLowerInvariant())) + { effects.Items.Clear(); - createEffects(effects.SelectedItems.Count > 0 ? ((SectorEffectInfo)effects.SelectedItems[0].Tag).Index : 0); + CreateEffects(effects.SelectedItems.Count > 0 ? ((SectorEffectInfo)effects.SelectedItems[0].Tag).Index : 0); } } //mxd - private void btnClearFilter_Click(object sender, EventArgs e) { + private void btnClearFilter_Click(object sender, EventArgs e) + { tbFilter.Clear(); } } diff --git a/Source/Core/Windows/ErrorsForm.cs b/Source/Core/Windows/ErrorsForm.cs index 683eb25c..463a64b6 100644 --- a/Source/Core/Windows/ErrorsForm.cs +++ b/Source/Core/Windows/ErrorsForm.cs @@ -122,9 +122,12 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - try { + try + { Clipboard.SetDataObject(str.ToString(), true); - } catch(ExternalException) { + } + catch(ExternalException) + { General.Interface.DisplayStatus(StatusType.Warning, "Failed to perform a Clipboard operation..."); } } @@ -141,12 +144,12 @@ namespace CodeImp.DoomBuilder.Windows private void ErrorsForm_Shown(object sender, EventArgs e) { - if(grid.Rows.Count > 0) - grid.Rows[0].Selected = false; + if(grid.Rows.Count > 0) grid.Rows[0].Selected = false; } - private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e) { + private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e) + { copyselected.Enabled = true; } } diff --git a/Source/Core/Windows/LinedefEditForm.cs b/Source/Core/Windows/LinedefEditForm.cs index a0c59814..77461318 100644 --- a/Source/Core/Windows/LinedefEditForm.cs +++ b/Source/Core/Windows/LinedefEditForm.cs @@ -361,7 +361,7 @@ namespace CodeImp.DoomBuilder.Windows preventchanges = false; - updateScriptControls(); //mxd + UpdateScriptControls(); //mxd //mxd. Set intial script-related values, if required if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) @@ -396,7 +396,7 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void updateScriptControls() + private void UpdateScriptControls() { scriptNumbers.Visible = (Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1); } @@ -614,7 +614,7 @@ namespace CodeImp.DoomBuilder.Windows } } - if(!preventchanges) updateScriptControls(); //mxd + if(!preventchanges) UpdateScriptControls(); //mxd } // Browse Action clicked @@ -640,7 +640,8 @@ namespace CodeImp.DoomBuilder.Windows #region ================== Linedef realtime events (mxd) - private void flags_OnValueChanged(object sender, EventArgs e) { + private void flags_OnValueChanged(object sender, EventArgs e) + { if(preventchanges) return; int i = 0; diff --git a/Source/Core/Windows/LinedefEditFormUDMF.cs b/Source/Core/Windows/LinedefEditFormUDMF.cs index 325dee3e..7c609bd1 100644 --- a/Source/Core/Windows/LinedefEditFormUDMF.cs +++ b/Source/Core/Windows/LinedefEditFormUDMF.cs @@ -586,7 +586,8 @@ namespace CodeImp.DoomBuilder.Windows backmid.MultipleTextures = true; //mxd backmid.TextureName = string.Empty; } - if (backlow.TextureName != l.Back.LowTexture) { + if (backlow.TextureName != l.Back.LowTexture) + { if(!backlow.Required && l.Back.LowRequired()) backlow.Required = true; backlow.MultipleTextures = true; //mxd backlow.TextureName = string.Empty; @@ -641,7 +642,7 @@ namespace CodeImp.DoomBuilder.Windows preventchanges = false; - updateScriptControls(); //mxd + UpdateScriptControls(); //mxd CheckActivationFlagsRequired(); //mxd //mxd. Set intial script-related values, if required @@ -685,7 +686,7 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void updateScriptControls() + private void UpdateScriptControls() { if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) { @@ -746,7 +747,8 @@ namespace CodeImp.DoomBuilder.Windows if(General.Map.FormatInterface.HasLinedefTag) { tagSelector.ValidateTag(); //mxd - if(((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag))) { + if(((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag))) + { General.ShowWarningMessage("Linedef tag must be between " + General.Map.FormatInterface.MinTag + " and " + General.Map.FormatInterface.MaxTag + ".", MessageBoxButtons.OK); return; } @@ -995,7 +997,7 @@ namespace CodeImp.DoomBuilder.Windows //mxd if(!preventchanges) { - updateScriptControls(); + UpdateScriptControls(); CheckActivationFlagsRequired(); } } @@ -1353,7 +1355,8 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void backmid_OnValueChanged(object sender, EventArgs e) { + private void backmid_OnValueChanged(object sender, EventArgs e) + { if(preventchanges) return; //restore values @@ -1380,7 +1383,8 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void backlow_OnValueChanged(object sender, EventArgs e) { + private void backlow_OnValueChanged(object sender, EventArgs e) + { if(preventchanges) return; //restore values diff --git a/Source/Core/Windows/MainForm.cs b/Source/Core/Windows/MainForm.cs index 35104f5c..5ac64f1d 100644 --- a/Source/Core/Windows/MainForm.cs +++ b/Source/Core/Windows/MainForm.cs @@ -640,30 +640,39 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void OnDragEnter(object sender, DragEventArgs e) { - if(e.Data.GetDataPresent(DataFormats.FileDrop)) { + private void OnDragEnter(object sender, DragEventArgs e) + { + if(e.Data.GetDataPresent(DataFormats.FileDrop)) + { e.Effect = DragDropEffects.Copy; - } else { + } + else + { e.Effect = DragDropEffects.None; } } //mxd - private void OnDragDrop(object sender, DragEventArgs e) { - if (e.Data.GetDataPresent(DataFormats.FileDrop)) { + private void OnDragDrop(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.FileDrop)) + { string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); - if (filePaths.Length != 1) { + if (filePaths.Length != 1) + { General.Interface.DisplayStatus(StatusType.Warning, "Cannot open multiple files at once!"); return; } - if (!File.Exists(filePaths[0])) { + if (!File.Exists(filePaths[0])) + { General.Interface.DisplayStatus(StatusType.Warning, "Cannot open '" + filePaths[0] + "': file does not exist!"); return; } string ext = Path.GetExtension(filePaths[0]); - if(string.IsNullOrEmpty(ext) || ext.ToLower() != ".wad") { + if(string.IsNullOrEmpty(ext) || ext.ToLower() != ".wad") + { General.Interface.DisplayStatus(StatusType.Warning, "Cannot open '" + filePaths[0] + "': only WAD files can be loaded this way!"); return; } @@ -748,15 +757,19 @@ namespace CodeImp.DoomBuilder.Windows // When no particular information is to be displayed. // The messages displayed depends on running background processes. case StatusType.Ready: - if ((General.Map != null) && (General.Map.Data != null)) { + if ((General.Map != null) && (General.Map.Data != null)) + { newstatus.message = General.Map.Data.IsLoading ? STATUS_LOADING_TEXT : selectionInfo; - } else { + } + else + { newstatus.message = STATUS_READY_TEXT; } break; case StatusType.Selection: //mxd - if (statusresetter.Enabled) { //don't change the message right now if info or warning is displayed + if (statusresetter.Enabled) //don't change the message right now if info or warning is displayed + { selectionInfo = (string.IsNullOrEmpty(newstatus.message) ? STATUS_NO_SELECTION_TEXT : newstatus.message); return; } @@ -961,7 +974,7 @@ namespace CodeImp.DoomBuilder.Windows { if(General.Map == null) return; - General.Map.Grid.ShowGridSetup(); + GridSetup.ShowGridSetup(); } #endregion @@ -1679,7 +1692,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - public void AddModesButton(ToolStripItem button, string group) { + public void AddModesButton(ToolStripItem button, string group) + { // Set proper styling button.Padding = new Padding(0, 1, 0, 1); button.Margin = new Padding(); @@ -1698,8 +1712,10 @@ namespace CodeImp.DoomBuilder.Windows button.VisibleChanged += buttonvisiblechangedhandler; //find the separator we need - for(int i = 0; i < modestoolbar.Items.Count; i++) { - if(modestoolbar.Items[i] is ToolStripSeparator && modestoolbar.Items[i].Text == group) { + for(int i = 0; i < modestoolbar.Items.Count; i++) + { + if(modestoolbar.Items[i] is ToolStripSeparator && modestoolbar.Items[i].Text == group) + { modestoolbar.Items.Insert(i + 1, button); break; } @@ -1729,7 +1745,8 @@ namespace CodeImp.DoomBuilder.Windows if(!(button is ToolStripSeparator)) button.VisibleChanged -= buttonvisiblechangedhandler; //mxd. Remove button from toolbars - switch (buttoninfo.section) { + switch (buttoninfo.section) + { case ToolbarSection.Modes: modestoolbar.Items.Remove(button); break; @@ -1999,7 +2016,8 @@ namespace CodeImp.DoomBuilder.Windows #region ================== Toolbar context menu (mxd) - private void toolbarContextMenu_Opening(object sender, CancelEventArgs e) { + private void toolbarContextMenu_Opening(object sender, CancelEventArgs e) + { toggleFile.Image = General.Settings.ToolbarFile ? Resources.Check : null; toggleScript.Image = General.Settings.ToolbarScript ? Resources.Check : null; toggleUndo.Image = General.Settings.ToolbarUndo ? Resources.Check : null; @@ -2012,19 +2030,23 @@ namespace CodeImp.DoomBuilder.Windows toggleRendering.Image = General.Settings.GZToolbarGZDoom ? Resources.Check : null; } - private void toolbarContextMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e) { + private void toolbarContextMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e) + { e.Cancel = toolbarContextMenuShiftPressed; } - private void toolbarContextMenu_KeyDown(object sender, KeyEventArgs e) { + private void toolbarContextMenu_KeyDown(object sender, KeyEventArgs e) + { toolbarContextMenuShiftPressed = (e.KeyCode == Keys.ShiftKey); } - private void toolbarContextMenu_KeyUp(object sender, KeyEventArgs e) { + private void toolbarContextMenu_KeyUp(object sender, KeyEventArgs e) + { toolbarContextMenuShiftPressed = (e.KeyCode != Keys.ShiftKey); } - private void toggleFile_Click(object sender, EventArgs e) { + private void toggleFile_Click(object sender, EventArgs e) + { General.Settings.ToolbarFile = !General.Settings.ToolbarFile; UpdateToolbar(); @@ -2032,7 +2054,8 @@ namespace CodeImp.DoomBuilder.Windows toggleFile.Image = General.Settings.ToolbarFile ? Resources.Check : null; } - private void toggleScript_Click(object sender, EventArgs e) { + private void toggleScript_Click(object sender, EventArgs e) + { General.Settings.ToolbarScript = !General.Settings.ToolbarScript; UpdateToolbar(); @@ -2040,7 +2063,8 @@ namespace CodeImp.DoomBuilder.Windows toggleScript.Image = General.Settings.ToolbarScript ? Resources.Check : null; } - private void toggleUndo_Click(object sender, EventArgs e) { + private void toggleUndo_Click(object sender, EventArgs e) + { General.Settings.ToolbarUndo = !General.Settings.ToolbarUndo; UpdateToolbar(); @@ -2048,7 +2072,8 @@ namespace CodeImp.DoomBuilder.Windows toggleUndo.Image = General.Settings.ToolbarUndo ? Resources.Check : null; } - private void toggleCopy_Click(object sender, EventArgs e) { + private void toggleCopy_Click(object sender, EventArgs e) + { General.Settings.ToolbarCopy = !General.Settings.ToolbarCopy; UpdateToolbar(); @@ -2056,7 +2081,8 @@ namespace CodeImp.DoomBuilder.Windows toggleCopy.Image = General.Settings.ToolbarCopy ? Resources.Check : null; } - private void togglePrefabs_Click(object sender, EventArgs e) { + private void togglePrefabs_Click(object sender, EventArgs e) + { General.Settings.ToolbarPrefabs = !General.Settings.ToolbarPrefabs; UpdateToolbar(); @@ -2064,7 +2090,8 @@ namespace CodeImp.DoomBuilder.Windows togglePrefabs.Image = General.Settings.ToolbarPrefabs ? Resources.Check : null; } - private void toggleFilter_Click(object sender, EventArgs e) { + private void toggleFilter_Click(object sender, EventArgs e) + { General.Settings.ToolbarFilter = !General.Settings.ToolbarFilter; UpdateToolbar(); @@ -2072,7 +2099,8 @@ namespace CodeImp.DoomBuilder.Windows toggleFilter.Image = General.Settings.ToolbarFilter ? Resources.Check : null; } - private void toggleViewModes_Click(object sender, EventArgs e) { + private void toggleViewModes_Click(object sender, EventArgs e) + { General.Settings.ToolbarViewModes = !General.Settings.ToolbarViewModes; UpdateToolbar(); @@ -2080,7 +2108,8 @@ namespace CodeImp.DoomBuilder.Windows toggleViewModes.Image = General.Settings.ToolbarViewModes ? Resources.Check : null; } - private void toggleGeometry_Click(object sender, EventArgs e) { + private void toggleGeometry_Click(object sender, EventArgs e) + { General.Settings.ToolbarGeometry = !General.Settings.ToolbarGeometry; UpdateToolbar(); @@ -2088,7 +2117,8 @@ namespace CodeImp.DoomBuilder.Windows toggleGeometry.Image = General.Settings.ToolbarGeometry ? Resources.Check : null; } - private void toggleTesting_Click(object sender, EventArgs e) { + private void toggleTesting_Click(object sender, EventArgs e) + { General.Settings.ToolbarTesting = !General.Settings.ToolbarTesting; UpdateToolbar(); @@ -2096,7 +2126,8 @@ namespace CodeImp.DoomBuilder.Windows toggleTesting.Image = General.Settings.ToolbarTesting ? Resources.Check : null; } - private void toggleRendering_Click(object sender, EventArgs e) { + private void toggleRendering_Click(object sender, EventArgs e) + { General.Settings.GZToolbarGZDoom = !General.Settings.GZToolbarGZDoom; UpdateToolbar(); @@ -2150,15 +2181,18 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - public void AddModesMenu(ToolStripMenuItem menu, string group) { + public void AddModesMenu(ToolStripMenuItem menu, string group) + { // Fix tags to full action names ToolStripItemCollection items = new ToolStripItemCollection(this.menumain, new ToolStripItem[0]); items.Add(menu); RenameTagsToFullActions(items, General.Plugins.FindPluginByAssembly(Assembly.GetCallingAssembly())); //find the separator we need - for(int i = 0; i < menumode.DropDownItems.Count; i++) { - if(menumode.DropDownItems[i] is ToolStripSeparator && menumode.DropDownItems[i].Text == group) { + for(int i = 0; i < menumode.DropDownItems.Count; i++) + { + if(menumode.DropDownItems[i] is ToolStripSeparator && menumode.DropDownItems[i].Text == group) + { menumode.DropDownItems.Insert(i + 1, menu); break; } @@ -2345,7 +2379,8 @@ namespace CodeImp.DoomBuilder.Windows internal void AddRecentFile(string filename) { //mxd. Recreate recent files list - if (recentitems.Length != General.Settings.MaxRecentFiles) { + if (recentitems.Length != General.Settings.MaxRecentFiles) + { foreach(ToolStripMenuItem item in recentitems) menufile.DropDownItems.Remove(item); @@ -2519,7 +2554,8 @@ namespace CodeImp.DoomBuilder.Windows //update "Select group" menu selectGroup.DropDownItems.Clear(); - foreach (GroupInfo gi in infos) { + foreach (GroupInfo gi in infos) + { if(gi.Empty) continue; item = selectGroup.DropDownItems.Add(gi.ToString()); item.Tag = "builder_selectgroup" + gi.Index; @@ -2528,7 +2564,8 @@ namespace CodeImp.DoomBuilder.Windows //update "Clear group" menu clearGroup.DropDownItems.Clear(); - foreach(GroupInfo gi in infos) { + foreach(GroupInfo gi in infos) + { if(gi.Empty) continue; item = clearGroup.DropDownItems.Add(gi.ToString()); item.Tag = "builder_cleargroup" + gi.Index; @@ -2559,7 +2596,8 @@ namespace CodeImp.DoomBuilder.Windows //mxd [BeginAction("togglebrightness")] - internal void ToggleBrightness() { + internal void ToggleBrightness() + { Renderer.FullBrightness = !Renderer.FullBrightness; buttonfullbrightness.Checked = Renderer.FullBrightness; menufullbrightness.Checked = Renderer.FullBrightness; @@ -2571,7 +2609,8 @@ namespace CodeImp.DoomBuilder.Windows //mxd [BeginAction("toggleautoclearsidetextures")] - internal void ToggleAutoClearSideTextures() { + internal void ToggleAutoClearSideTextures() + { buttonautoclearsidetextures.Checked = !buttonautoclearsidetextures.Checked; itemautoclearsidetextures.Checked = buttonautoclearsidetextures.Checked; General.Settings.AutoClearSidedefTextures = buttonautoclearsidetextures.Checked; @@ -2580,7 +2619,8 @@ namespace CodeImp.DoomBuilder.Windows //mxd [BeginAction("viewusedtags")] - internal void ViewUsedTags() { + internal void ViewUsedTags() + { TagStatisticsForm f = new TagStatisticsForm(); f.ShowDialog(this); } @@ -2680,7 +2720,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void itemShortcutReference_Click(object sender, EventArgs e) { + private void itemShortcutReference_Click(object sender, EventArgs e) + { const string columnLabels = "Action
Shortcut
Modifiers
Description"; const string categoryPadding = ""; const string categoryStart = ""; @@ -2690,7 +2731,8 @@ namespace CodeImp.DoomBuilder.Windows Actions.Action[] actions = General.Actions.GetAllActions(); Dictionary> sortedActions = new Dictionary>(StringComparer.Ordinal); - foreach(Actions.Action action in actions) { + foreach(Actions.Action action in actions) + { if(!sortedActions.ContainsKey(action.Category)) sortedActions.Add(action.Category, new List()); sortedActions[action.Category].Add(action); @@ -2713,7 +2755,8 @@ namespace CodeImp.DoomBuilder.Windows List catnames = new List(sortedActions.Count); int counter = 0; int numActions = 0; - foreach(KeyValuePair> category in sortedActions) { + foreach(KeyValuePair> category in sortedActions) + { catnames.Add("" + General.Actions.Categories[category.Key] + ""); numActions += category.Value.Count; } @@ -2724,7 +2767,8 @@ namespace CodeImp.DoomBuilder.Windows //add descriptions counter = 0; - foreach(KeyValuePair> category in sortedActions) { + foreach(KeyValuePair> category in sortedActions) + { //add category title html.AppendLine(categoryPadding); html.AppendLine(categoryStart + "" + General.Actions.Categories[category.Key] + categoryEnd); @@ -2734,7 +2778,8 @@ namespace CodeImp.DoomBuilder.Windows Dictionary actionsByTitle = new Dictionary(StringComparer.Ordinal); List actionTitles = new List(); - foreach(Actions.Action action in category.Value) { + foreach(Actions.Action action in category.Value) + { actionsByTitle.Add(action.Title, action); actionTitles.Add(action.Title); } @@ -2742,7 +2787,8 @@ namespace CodeImp.DoomBuilder.Windows actionTitles.Sort(); Actions.Action a; - foreach(string title in actionTitles) { + foreach(string title in actionTitles) + { a = actionsByTitle[title]; List modifiers = new List(); @@ -2765,15 +2811,20 @@ namespace CodeImp.DoomBuilder.Windows //write string path; - try { + try + { path = Path.Combine(General.AppPath, fileName); - using(StreamWriter writer = File.CreateText(path)) { + using(StreamWriter writer = File.CreateText(path)) + { writer.Write(html.ToString()); } - } catch (Exception) { + } + catch (Exception) + { //Configurtions path SHOULD be accessible and not read-only, right? path = Path.Combine(General.SettingsPath, fileName); - using(StreamWriter writer = File.CreateText(path)) { + using(StreamWriter writer = File.CreateText(path)) + { writer.Write(html.ToString()); } } @@ -2973,9 +3024,12 @@ namespace CodeImp.DoomBuilder.Windows Vector2D pos = ((ClassicMode) General.Editing.Mode).MouseMapPos; //mouse inside the view? - if (pos.IsFinite()) { + if (pos.IsFinite()) + { info += "X:" + Math.Round(pos.x) + " Y:" + Math.Round(pos.y); - } else { + } + else + { info += "X:" + Math.Round(General.Map.Renderer2D.TranslateX) + " Y:" + Math.Round(General.Map.Renderer2D.TranslateY); } } @@ -3134,7 +3188,8 @@ namespace CodeImp.DoomBuilder.Windows // This displays the current mode name internal void DisplayModeName(string name) { - if(lastinfoobject == null) { + if(lastinfoobject == null) + { labelcollapsedinfo.Text = name; labelcollapsedinfo.Refresh(); } @@ -3236,13 +3291,19 @@ namespace CodeImp.DoomBuilder.Windows if(IsInfoPanelExpanded) linedefinfo.ShowInfo(l); // Show info on collapsed label - if(General.Map.Config.LinedefActions.ContainsKey(l.Action)) { + if(General.Map.Config.LinedefActions.ContainsKey(l.Action)) + { LinedefActionInfo act = General.Map.Config.LinedefActions[l.Action]; labelcollapsedinfo.Text = act.ToString(); - } else if(l.Action == 0) + } + else if (l.Action == 0) + { labelcollapsedinfo.Text = l.Action + " - None"; + } else + { labelcollapsedinfo.Text = l.Action + " - Unknown"; + } labelcollapsedinfo.Refresh(); @@ -3251,8 +3312,10 @@ namespace CodeImp.DoomBuilder.Windows } // Show vertex info - public void ShowVertexInfo(Vertex v) { - if (v.IsDisposed) { + public void ShowVertexInfo(Vertex v) + { + if (v.IsDisposed) + { HideInfo(); return; } @@ -3277,8 +3340,10 @@ namespace CodeImp.DoomBuilder.Windows } // Show sector info - public void ShowSectorInfo(Sector s) { - if (s.IsDisposed) { + public void ShowSectorInfo(Sector s) + { + if (s.IsDisposed) + { HideInfo(); return; } @@ -3555,10 +3620,14 @@ namespace CodeImp.DoomBuilder.Windows } //mxd. Warnings panel - internal void SetWarningsCount(int count, bool blink) { - if(count > 0) { + internal void SetWarningsCount(int count, bool blink) + { + if(count > 0) + { if (warnsLabel.Image != Resources.Warning) warnsLabel.Image = Resources.Warning; - } else { + } + else + { warnsLabel.Image = Resources.WarningOff; warnsLabel.BackColor = SystemColors.Control; } @@ -3566,28 +3635,35 @@ namespace CodeImp.DoomBuilder.Windows warnsLabel.Text = count.ToString(); //start annoying blinking! - if (blink) { + if (blink) + { if(!blinkTimer.Enabled) blinkTimer.Start(); - } else { + } + else + { blinkTimer.Stop(); warnsLabel.BackColor = SystemColors.Control; } } //mxd. Bliks warnings indicator - private void blink() { + private void Blink() + { warnsLabel.BackColor = (warnsLabel.BackColor == Color.Red ? SystemColors.Control : Color.Red); } //mxd - private void warnsLabel_Click(object sender, EventArgs e) { + private void warnsLabel_Click(object sender, EventArgs e) + { ShowErrors(); } //mxd - private void blinkTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { - try { - this.Invoke(new CallBlink(blink)); + private void blinkTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + try + { + this.Invoke(new CallBlink(Blink)); } catch(ObjectDisposedException) { } //la-la-la. We don't care. } diff --git a/Source/Core/Windows/PreferencesForm.cs b/Source/Core/Windows/PreferencesForm.cs index cffd6fdd..704c89bb 100644 --- a/Source/Core/Windows/PreferencesForm.cs +++ b/Source/Core/Windows/PreferencesForm.cs @@ -148,10 +148,13 @@ namespace CodeImp.DoomBuilder.Windows item.SubItems[1].Tag = a.ShortcutKey; // Put in category, if the category exists - if(General.Actions.Categories.ContainsKey(a.Category)) { + if(General.Actions.Categories.ContainsKey(a.Category)) + { item.Group = listactions.Groups[a.Category]; actionListItemsGroupIndices.Add(listactions.Groups.IndexOf(item.Group)); - }else{ //mxd + } + else //mxd + { actionListItemsGroupIndices.Add(-1); } @@ -189,7 +192,7 @@ namespace CodeImp.DoomBuilder.Windows // Paste options pasteoptions.Setup(General.Settings.PasteOptions.Copy()); - updateScriptFontPreview(); //mxd + UpdateScriptFontPreview(); //mxd // Allow plugins to add tabs this.SuspendLayout(); @@ -430,12 +433,13 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void recentFiles_ValueChanged(object sender, EventArgs e) { + private void recentFiles_ValueChanged(object sender, EventArgs e) + { labelRecentFiles.Text = recentFiles.Value.ToString(); } // This updates the script font preview label - private void updateScriptFontPreview() + private void UpdateScriptFontPreview() { if((scriptfontname.SelectedIndex > -1) && (scriptfontsize.SelectedIndex > -1)) @@ -587,20 +591,23 @@ namespace CodeImp.DoomBuilder.Windows } //mxd. Alt - if(a.AllowMouse && !a.DisregardAlt) { + if(a.AllowMouse && !a.DisregardAlt) + { actioncontrol.Items.Add(new KeyControl(Keys.LButton | Keys.Alt, "Alt+LButton")); actioncontrol.Items.Add(new KeyControl(Keys.MButton | Keys.Alt, "Alt+MButton")); actioncontrol.Items.Add(new KeyControl(Keys.RButton | Keys.Alt, "Alt+RButton")); actioncontrol.Items.Add(new KeyControl(Keys.XButton1 | Keys.Alt, "Alt+XButton1")); actioncontrol.Items.Add(new KeyControl(Keys.XButton2 | Keys.Alt, "Alt+XButton2")); } - if(a.AllowScroll && !a.DisregardAlt) { + if(a.AllowScroll && !a.DisregardAlt) + { actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollUp | (int)Keys.Alt, "Alt+ScrollUp")); actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollDown | (int)Keys.Alt, "Alt+ScrollDown")); } //Ctrl - if(a.AllowMouse && !a.DisregardControl) { + if(a.AllowMouse && !a.DisregardControl) + { actioncontrol.Items.Add(new KeyControl(Keys.LButton | Keys.Control, "Ctrl+LButton")); actioncontrol.Items.Add(new KeyControl(Keys.MButton | Keys.Control, "Ctrl+MButton")); actioncontrol.Items.Add(new KeyControl(Keys.RButton | Keys.Control, "Ctrl+RButton")); @@ -608,7 +615,8 @@ namespace CodeImp.DoomBuilder.Windows actioncontrol.Items.Add(new KeyControl(Keys.XButton2 | Keys.Control, "Ctrl+XButton2")); } - if(a.AllowScroll && !a.DisregardControl) { + if(a.AllowScroll && !a.DisregardControl) + { actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollUp | (int)Keys.Control, "Ctrl+ScrollUp")); actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollDown | (int)Keys.Control, "Ctrl+ScrollDown")); } @@ -629,27 +637,31 @@ namespace CodeImp.DoomBuilder.Windows } //mxd. Alt-Shift - if(a.AllowMouse && !a.DisregardShift && !a.DisregardAlt) { + if(a.AllowMouse && !a.DisregardShift && !a.DisregardAlt) + { actioncontrol.Items.Add(new KeyControl(Keys.LButton | Keys.Shift | Keys.Alt, "Alt+Shift+LButton")); actioncontrol.Items.Add(new KeyControl(Keys.MButton | Keys.Shift | Keys.Alt, "Alt+Shift+MButton")); actioncontrol.Items.Add(new KeyControl(Keys.RButton | Keys.Shift | Keys.Alt, "Alt+Shift+RButton")); actioncontrol.Items.Add(new KeyControl(Keys.XButton1 | Keys.Shift | Keys.Alt, "Alt+Shift+XButton1")); actioncontrol.Items.Add(new KeyControl(Keys.XButton2 | Keys.Shift | Keys.Alt, "Alt+Shift+XButton2")); } - if(a.AllowScroll && !a.DisregardShift && !a.DisregardAlt) { + if(a.AllowScroll && !a.DisregardShift && !a.DisregardAlt) + { actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollUp | (int)Keys.Shift | (int)Keys.Alt, "Alt+Shift+ScrollUp")); actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollDown | (int)Keys.Shift | (int)Keys.Alt, "Alt+Shift+ScrollDown")); } //mxd. Ctrl-Alt - if(a.AllowMouse && !a.DisregardAlt && !a.DisregardControl) { + if(a.AllowMouse && !a.DisregardAlt && !a.DisregardControl) + { actioncontrol.Items.Add(new KeyControl(Keys.LButton | Keys.Alt | Keys.Control, "Ctrl+Alt+LButton")); actioncontrol.Items.Add(new KeyControl(Keys.MButton | Keys.Alt | Keys.Control, "Ctrl+Alt+MButton")); actioncontrol.Items.Add(new KeyControl(Keys.RButton | Keys.Alt | Keys.Control, "Ctrl+Alt+RButton")); actioncontrol.Items.Add(new KeyControl(Keys.XButton1 | Keys.Alt | Keys.Control, "Ctrl+Alt+XButton1")); actioncontrol.Items.Add(new KeyControl(Keys.XButton2 | Keys.Alt | Keys.Control, "Ctrl+Alt+XButton2")); } - if(a.AllowScroll && !a.DisregardAlt && !a.DisregardControl) { + if(a.AllowScroll && !a.DisregardAlt && !a.DisregardControl) + { actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollUp | (int)Keys.Control | (int)Keys.Alt, "Ctrl+Alt+ScrollUp")); actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollDown | (int)Keys.Control | (int)Keys.Alt, "Ctrl+Alt+ScrollDown")); } @@ -670,14 +682,16 @@ namespace CodeImp.DoomBuilder.Windows } //mxd. Ctrl-Alt-Shift - if(a.AllowMouse && !a.DisregardShift && !a.DisregardControl && !a.DisregardAlt) { + if(a.AllowMouse && !a.DisregardShift && !a.DisregardControl && !a.DisregardAlt) + { actioncontrol.Items.Add(new KeyControl(Keys.LButton | Keys.Shift | Keys.Control | Keys.Alt, "Ctrl+Alt+Shift+LButton")); actioncontrol.Items.Add(new KeyControl(Keys.MButton | Keys.Shift | Keys.Control | Keys.Alt, "Ctrl+Alt+Shift+MButton")); actioncontrol.Items.Add(new KeyControl(Keys.RButton | Keys.Shift | Keys.Control | Keys.Alt, "Ctrl+Alt+Shift+RButton")); actioncontrol.Items.Add(new KeyControl(Keys.XButton1 | Keys.Shift | Keys.Control | Keys.Alt, "Ctrl+Alt+Shift+XButton1")); actioncontrol.Items.Add(new KeyControl(Keys.XButton2 | Keys.Shift | Keys.Control | Keys.Alt, "Ctrl+Alt+Shift+XButton2")); } - if(a.AllowScroll && !a.DisregardShift && !a.DisregardControl && !a.DisregardAlt) { + if(a.AllowScroll && !a.DisregardShift && !a.DisregardControl && !a.DisregardAlt) + { actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollUp | (int)Keys.Shift | (int)Keys.Control | (int)Keys.Alt, "Ctrl+Alt+Shift+ScrollUp")); actioncontrol.Items.Add(new KeyControl((int)SpecialKeys.MScrollDown | (int)Keys.Shift | (int)Keys.Control | (int)Keys.Alt, "Ctrl+Alt+Shift+ScrollDown")); } @@ -865,39 +879,49 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void bClearActionFilter_Click(object sender, EventArgs e) { + private void bClearActionFilter_Click(object sender, EventArgs e) + { tbFilterActions.Clear(); } //mxd - private void tbFilterActions_TextChanged(object sender, EventArgs e) { + private void tbFilterActions_TextChanged(object sender, EventArgs e) + { listactions.BeginUpdate(); //restore everything - if(string.IsNullOrEmpty(tbFilterActions.Text)) { + if(string.IsNullOrEmpty(tbFilterActions.Text)) + { //restore items listactions.Items.Clear(); listactions.Items.AddRange(actionListItems.ToArray()); //restore groups - for(int i = 0; i < actionListItems.Count; i++) { + for(int i = 0; i < actionListItems.Count; i++) + { if(actionListItemsGroupIndices[i] != -1) actionListItems[i].Group = listactions.Groups[actionListItemsGroupIndices[i]]; } - } else { //apply filtering + } + else //apply filtering + { string match = tbFilterActions.Text.ToUpperInvariant(); - - for(int i = 0; i < actionListItems.Count; i++) { - if(actionListItems[i].Text.ToUpperInvariant().Contains(match)) { + for(int i = 0; i < actionListItems.Count; i++) + { + if(actionListItems[i].Text.ToUpperInvariant().Contains(match)) + { //ensure visible - if(!listactions.Items.Contains(actionListItems[i])) { + if(!listactions.Items.Contains(actionListItems[i])) + { listactions.Items.Add(actionListItems[i]); //restore group if(actionListItemsGroupIndices[i] != -1) actionListItems[i].Group = listactions.Groups[actionListItemsGroupIndices[i]]; } - } else if(listactions.Items.Contains(actionListItems[i])) { + } + else if(listactions.Items.Contains(actionListItems[i])) + { //ensure invisible listactions.Items.Remove(actionListItems[i]); } @@ -924,38 +948,45 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void tbDynLightCount_ValueChanged(object sender, EventArgs e) { + private void tbDynLightCount_ValueChanged(object sender, EventArgs e) + { labelDynLightCount.Text = tbDynLightCount.Value.ToString(); } //mxd - private void tbDynLightSize_ValueChanged(object sender, EventArgs e) { + private void tbDynLightSize_ValueChanged(object sender, EventArgs e) + { labelDynLightSize.Text = ((float)tbDynLightSize.Value / 10).ToString(); } //mxd - private void tbDynLightIntensity_ValueChanged(object sender, EventArgs e) { + private void tbDynLightIntensity_ValueChanged(object sender, EventArgs e) + { labelDynLightIntensity.Text = ((float)tbDynLightIntensity.Value / 10).ToString(); } //mxd - private void scriptfontbold_CheckedChanged(object sender, EventArgs e) { - updateScriptFontPreview(); + private void scriptfontbold_CheckedChanged(object sender, EventArgs e) + { + UpdateScriptFontPreview(); } //mxd - private void scriptfontsize_SelectedIndexChanged(object sender, EventArgs e) { - updateScriptFontPreview(); + private void scriptfontsize_SelectedIndexChanged(object sender, EventArgs e) + { + UpdateScriptFontPreview(); } //mxd - private void scriptfontname_SelectedIndexChanged(object sender, EventArgs e) { - updateScriptFontPreview(); + private void scriptfontname_SelectedIndexChanged(object sender, EventArgs e) + { + UpdateScriptFontPreview(); } //mxd - private void scriptcolor_ColorChanged(object sender, EventArgs e) { - updateScriptFontPreview(); + private void scriptcolor_ColorChanged(object sender, EventArgs e) + { + UpdateScriptFontPreview(); } #endregion diff --git a/Source/Core/Windows/ResourceOptionsForm.cs b/Source/Core/Windows/ResourceOptionsForm.cs index 53472e3d..98935aef 100644 --- a/Source/Core/Windows/ResourceOptionsForm.cs +++ b/Source/Core/Windows/ResourceOptionsForm.cs @@ -72,7 +72,8 @@ namespace CodeImp.DoomBuilder.Windows notfortesting.Checked = res.notfortesting; //mxd - if(!string.IsNullOrEmpty(startPath)) { + if(!string.IsNullOrEmpty(startPath)) + { string startDir = Path.GetDirectoryName(startPath); if(Directory.Exists(startDir)) dirdialog.SelectedPath = startDir; } diff --git a/Source/Core/Windows/SectorEditForm.cs b/Source/Core/Windows/SectorEditForm.cs index e29935b9..1f7e1f62 100644 --- a/Source/Core/Windows/SectorEditForm.cs +++ b/Source/Core/Windows/SectorEditForm.cs @@ -52,7 +52,8 @@ namespace CodeImp.DoomBuilder.Windows public readonly string FloorTexture; public readonly string CeilTexture; - public SectorProperties(Sector s) { + public SectorProperties(Sector s) + { Brightness = s.Brightness; FloorHeight = s.FloorHeight; CeilHeight = s.CeilHeight; @@ -72,7 +73,8 @@ namespace CodeImp.DoomBuilder.Windows InitializeComponent(); //mxd. Widow setup - if(location != Point.Empty) { + if(location != Point.Empty) + { this.StartPosition = FormStartPosition.Manual; this.Location = location; } @@ -146,11 +148,13 @@ namespace CodeImp.DoomBuilder.Windows // Floor/Ceiling if(s.FloorHeight.ToString() != floorheight.Text) floorheight.Text = ""; if(s.CeilHeight.ToString() != ceilingheight.Text) ceilingheight.Text = ""; - if (s.FloorTexture != floortex.TextureName) { + if (s.FloorTexture != floortex.TextureName) + { floortex.MultipleTextures = true; //mxd floortex.TextureName = ""; } - if (s.CeilTexture != ceilingtex.TextureName) { + if (s.CeilTexture != ceilingtex.TextureName) + { ceilingtex.MultipleTextures = true; //mxd ceilingtex.TextureName = ""; } @@ -176,12 +180,16 @@ namespace CodeImp.DoomBuilder.Windows int i = 0; //mxd // Check all selected sectors - foreach(Sector s in sectors) { - if(index == -1) { + foreach(Sector s in sectors) + { + if(index == -1) + { // First sector in list delta = s.CeilHeight - s.FloorHeight; index = i; //mxd - } else if(delta != (s.CeilHeight - s.FloorHeight)) { + } + else if(delta != (s.CeilHeight - s.FloorHeight)) + { // We can't show heights because the delta // heights for the sectors is different index = -1; @@ -191,14 +199,17 @@ namespace CodeImp.DoomBuilder.Windows i++; } - if(index > -1) { + if(index > -1) + { int fh = floorheight.GetResult(sectorProps[index].FloorHeight); //mxd int ch = ceilingheight.GetResult(sectorProps[index].CeilHeight); //mxd int height = ch - fh; sectorheight.Text = height.ToString(); sectorheight.Visible = true; sectorheightlabel.Visible = true; - } else { + } + else + { sectorheight.Visible = false; sectorheightlabel.Visible = false; } @@ -211,7 +222,8 @@ namespace CodeImp.DoomBuilder.Windows int offset = heightoffset.GetResult(0); //restore values - if(string.IsNullOrEmpty(ceilingheight.Text)) { + if(string.IsNullOrEmpty(ceilingheight.Text)) + { foreach(Sector s in sectors) s.CeilHeight = sectorProps[i++].CeilHeight + offset; @@ -230,7 +242,8 @@ namespace CodeImp.DoomBuilder.Windows int offset = heightoffset.GetResult(0); //restore values - if(string.IsNullOrEmpty(floorheight.Text)) { + if(string.IsNullOrEmpty(floorheight.Text)) + { foreach(Sector s in sectors) s.FloorHeight = sectorProps[i++].FloorHeight + offset; @@ -252,20 +265,23 @@ namespace CodeImp.DoomBuilder.Windows //mxd. Apply "Static" properties // Verify the tag tagSelector.ValidateTag(); //mxd - if((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag)) { + if((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag)) + { General.ShowWarningMessage("Sector tag must be between " + General.Map.FormatInterface.MinTag + " and " + General.Map.FormatInterface.MaxTag + ".", MessageBoxButtons.OK); return; } // Verify the effect - if((effect.Value < General.Map.FormatInterface.MinEffect) || (effect.Value > General.Map.FormatInterface.MaxEffect)) { + if((effect.Value < General.Map.FormatInterface.MinEffect) || (effect.Value > General.Map.FormatInterface.MaxEffect)) + { General.ShowWarningMessage("Sector effect must be between " + General.Map.FormatInterface.MinEffect + " and " + General.Map.FormatInterface.MaxEffect + ".", MessageBoxButtons.OK); return; } // Go for all sectors int tagoffset = 0; //mxd - foreach(Sector s in sectors) { + foreach(Sector s in sectors) + { // Effects if(!effect.Empty) s.Effect = effect.Value; @@ -299,12 +315,14 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void SectorEditForm_FormClosing(object sender, FormClosingEventArgs e) { + private void SectorEditForm_FormClosing(object sender, FormClosingEventArgs e) + { location = this.Location; } // Help - private void SectorEditForm_HelpRequested(object sender, HelpEventArgs hlpevent) { + private void SectorEditForm_HelpRequested(object sender, HelpEventArgs hlpevent) + { General.ShowHelp("w_sectoredit.html"); hlpevent.Handled = true; } @@ -350,19 +368,20 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void floortex_OnValueChanged(object sender, EventArgs e) { + private void floortex_OnValueChanged(object sender, EventArgs e) + { if(blockUpdate) return; //restore values - if(string.IsNullOrEmpty(floortex.TextureName)) { + if(string.IsNullOrEmpty(floortex.TextureName)) + { int i = 0; - - foreach(Sector s in sectors) - s.SetFloorTexture(sectorProps[i++].FloorTexture); - //update values - } else { - foreach(Sector s in sectors) - s.SetFloorTexture(floortex.GetResult(s.FloorTexture)); + foreach(Sector s in sectors) s.SetFloorTexture(sectorProps[i++].FloorTexture); + + } + else //update values + { + foreach(Sector s in sectors) s.SetFloorTexture(floortex.GetResult(s.FloorTexture)); } // Update the used textures @@ -372,19 +391,20 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void ceilingtex_OnValueChanged(object sender, EventArgs e) { + private void ceilingtex_OnValueChanged(object sender, EventArgs e) + { if(blockUpdate) return; //restore values - if(string.IsNullOrEmpty(ceilingtex.TextureName)) { + if(string.IsNullOrEmpty(ceilingtex.TextureName)) + { int i = 0; - - foreach(Sector s in sectors) - s.SetCeilTexture(sectorProps[i++].CeilTexture); - //update values - } else { - foreach(Sector s in sectors) - s.SetCeilTexture(ceilingtex.GetResult(s.CeilTexture)); + foreach(Sector s in sectors) s.SetCeilTexture(sectorProps[i++].CeilTexture); + + } + else //update values + { + foreach(Sector s in sectors) s.SetCeilTexture(ceilingtex.GetResult(s.CeilTexture)); } // Update the used textures @@ -394,16 +414,19 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void brightness_WhenTextChanged(object sender, EventArgs e) { + private void brightness_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; int i = 0; //restore values - if(string.IsNullOrEmpty(brightness.Text)) { - foreach(Sector s in sectors) - s.Brightness = sectorProps[i++].Brightness; - //update values - } else { + if(string.IsNullOrEmpty(brightness.Text)) + { + foreach(Sector s in sectors) s.Brightness = sectorProps[i++].Brightness; + + } + else //update values + { foreach(Sector s in sectors) s.Brightness = General.Clamp(brightness.GetResult(sectorProps[i++].Brightness), General.Map.FormatInterface.MinBrightness, General.Map.FormatInterface.MaxBrightness); } diff --git a/Source/Core/Windows/SectorEditFormUDMF.Designer.cs b/Source/Core/Windows/SectorEditFormUDMF.Designer.cs index 56b2cfb2..fa57f8d5 100644 --- a/Source/Core/Windows/SectorEditFormUDMF.Designer.cs +++ b/Source/Core/Windows/SectorEditFormUDMF.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); System.Windows.Forms.GroupBox groupaction; System.Windows.Forms.GroupBox groupeffect; diff --git a/Source/Core/Windows/SectorEditFormUDMF.cs b/Source/Core/Windows/SectorEditFormUDMF.cs index 1868ff65..b87d743a 100644 --- a/Source/Core/Windows/SectorEditFormUDMF.cs +++ b/Source/Core/Windows/SectorEditFormUDMF.cs @@ -793,7 +793,8 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void brightness_WhenTextChanged(object sender, EventArgs e) { + private void brightness_WhenTextChanged(object sender, EventArgs e) + { if(blockupdate) return; //restore values diff --git a/Source/Core/Windows/TextureBrowserForm.cs b/Source/Core/Windows/TextureBrowserForm.cs index a6dac01b..abfdba9d 100644 --- a/Source/Core/Windows/TextureBrowserForm.cs +++ b/Source/Core/Windows/TextureBrowserForm.cs @@ -50,6 +50,7 @@ namespace CodeImp.DoomBuilder.Windows Cursor.Current = Cursors.WaitCursor; TreeNode item; //mxd long longname = Lump.MakeLongName(selecttexture ?? ""); + longname = (browseFlats ? General.Map.Data.GetFullLongFlatName(longname) : General.Map.Data.GetFullLongTextureName(longname)); //mxd int count; //mxd selectedset = null; //mxd this.browseFlats = browseFlats; @@ -104,7 +105,7 @@ namespace CodeImp.DoomBuilder.Windows if (ts.Location.type != DataLocation.RESOURCE_WAD) { - createNodes(item); + CreateNodes(item); item.Expand(); } } @@ -127,7 +128,7 @@ namespace CodeImp.DoomBuilder.Windows } else { - match = findNodeByName(tvTextureSets.Nodes, selectname); + match = FindNodeByName(tvTextureSets.Nodes, selectname); } if (match != null) @@ -148,7 +149,7 @@ namespace CodeImp.DoomBuilder.Windows { foreach (TreeNode n in tvTextureSets.Nodes) { - selectedset = findTextureByLongName(n, longname); + selectedset = FindTextureByLongName(n, longname); if (selectedset != null) break; } } @@ -195,20 +196,20 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private static int sortImageData(ImageData img1, ImageData img2) + private static int SortImageData(ImageData img1, ImageData img2) { return img1.FullName.CompareTo(img2.FullName); } //mxd - private TreeNode findTextureByLongName(TreeNode node, long longname) + private TreeNode FindTextureByLongName(TreeNode node, long longname) { //first search in child nodes TreeNode match; foreach(TreeNode n in node.Nodes) { - match = findTextureByLongName(n, longname); + match = FindTextureByLongName(n, longname); if(match != null) return match; } @@ -230,20 +231,20 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private static TreeNode findNodeByName(TreeNodeCollection nodes, string selectname) + private static TreeNode FindNodeByName(TreeNodeCollection nodes, string selectname) { foreach (TreeNode n in nodes) { if (n.Name == selectname) return n; - TreeNode match = findNodeByName(n.Nodes, selectname); + TreeNode match = FindNodeByName(n.Nodes, selectname); if(match != null) return match; } return null; } //mxd - private void createNodes(TreeNode root) + private void CreateNodes(TreeNode root) { ResourceTextureSet set = root.Tag as ResourceTextureSet; if (set == null) @@ -266,7 +267,7 @@ namespace CodeImp.DoomBuilder.Windows images = new ImageData[set.Textures.Count]; set.Textures.CopyTo(images, 0); } - Array.Sort(images, sortImageData); + Array.Sort(images, SortImageData); foreach(ImageData image in images) { diff --git a/Source/Core/Windows/TextureSetForm.cs b/Source/Core/Windows/TextureSetForm.cs index 92494d1d..b6fea829 100644 --- a/Source/Core/Windows/TextureSetForm.cs +++ b/Source/Core/Windows/TextureSetForm.cs @@ -98,9 +98,9 @@ namespace CodeImp.DoomBuilder.Windows foreach(ListViewItem i in filters.SelectedItems) i.Remove(); //mxd - if(filters.Items.Count > 0){ - if(index >= filters.Items.Count) - index = filters.Items.Count - 1; + if(filters.Items.Count > 0) + { + if(index >= filters.Items.Count) index = filters.Items.Count - 1; filters.Items[index].Selected = true; } diff --git a/Source/Core/Windows/ThingEditForm.cs b/Source/Core/Windows/ThingEditForm.cs index 9a632774..0f2fcfa6 100644 --- a/Source/Core/Windows/ThingEditForm.cs +++ b/Source/Core/Windows/ThingEditForm.cs @@ -84,12 +84,16 @@ namespace CodeImp.DoomBuilder.Windows InitializeComponent(); //mxd. Widow setup - if(location != Point.Empty) { + if(location != Point.Empty) + { this.StartPosition = FormStartPosition.Manual; this.Location = location; - if(activeTab > 0 && activeTab < tabs.TabCount) { + if(activeTab > 0 && activeTab < tabs.TabCount) + { tabs.SelectTab(activeTab); - } else { + } + else + { activeTab = 0; } } @@ -103,9 +107,12 @@ namespace CodeImp.DoomBuilder.Windows action.AddInfo(General.Map.Config.SortedLinedefActions.ToArray()); // Tag/Effects? - if(!General.Map.FormatInterface.HasThingAction && !General.Map.FormatInterface.HasThingTag){ + if(!General.Map.FormatInterface.HasThingAction && !General.Map.FormatInterface.HasThingTag) + { tabs.TabPages.Remove(tabeffects); - } else { //mxd. Setup script numbers + } + else //mxd. Setup script numbers + { scriptNumbers.Location = arg0.Location; foreach(ScriptItem si in General.Map.NumberedScripts) @@ -120,7 +127,8 @@ namespace CodeImp.DoomBuilder.Windows cbAbsoluteHeight.Visible = General.Map.FormatInterface.HasThingHeight; //mxd //mxd. Decimals allowed? - if(General.Map.FormatInterface.VertexDecimals > 0) { + if(General.Map.FormatInterface.VertexDecimals > 0) + { posX.AllowDecimal = true; posY.AllowDecimal = true; posZ.AllowDecimal = true; @@ -177,7 +185,8 @@ namespace CodeImp.DoomBuilder.Windows // Action/tags action.Value = ft.Action; - if(General.Map.FormatInterface.HasThingTag) {//mxd + if(General.Map.FormatInterface.HasThingTag) //mxd + { tagSelector.Setup(UniversalType.ThingTag); tagSelector.SetTag(ft.Tag); } @@ -222,9 +231,12 @@ namespace CodeImp.DoomBuilder.Windows //mxd. Position if(((int)t.Position.x).ToString() != posX.Text) posX.Text = ""; if(((int)t.Position.y).ToString() != posY.Text) posY.Text = ""; - if (useAbsoluteHeight && t.Sector != null) { + if (useAbsoluteHeight && t.Sector != null) + { if(((int)t.Position.z + t.Sector.FloorHeight).ToString() != posZ.Text) posZ.Text = ""; - } else if(((int)t.Position.z).ToString() != posZ.Text){ + } + else if(((int)t.Position.z).ToString() != posZ.Text) + { posZ.Text = ""; } @@ -247,33 +259,42 @@ namespace CodeImp.DoomBuilder.Windows angle_WhenTextChanged(angle, EventArgs.Empty); flags_OnValueChanged(flags, EventArgs.Empty); - updateScriptControls(); //mxd + UpdateScriptControls(); //mxd //mxd. Set intial script-related values, if required - if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) { + if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) + { int a0 = arg0.GetResult(0); - if(a0 > 0) { - for(int i = 0; i < General.Map.NumberedScripts.Count; i++) { - if(General.Map.NumberedScripts[i].Index == a0) { + if(a0 > 0) + { + for(int i = 0; i < General.Map.NumberedScripts.Count; i++) + { + if(General.Map.NumberedScripts[i].Index == a0) + { scriptNumbers.SelectedIndex = i; break; } } - if(scriptNumbers.SelectedIndex == -1) { + if(scriptNumbers.SelectedIndex == -1) + { scriptNumbers.Items.Add(new ScriptItem(a0, "Script " + a0)); scriptNumbers.SelectedIndex = scriptNumbers.Items.Count - 1; } - } else { + } + else + { scriptNumbers.Text = arg0.Text; } - } else { + } + else + { scriptNumbers.Text = "0"; } } //mxd - private void updateScriptControls() + private void UpdateScriptControls() { scriptNumbers.Visible = (Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1); } @@ -331,7 +352,7 @@ namespace CodeImp.DoomBuilder.Windows arg4.SetDefaultValue(); } - if(!preventchanges) updateScriptControls(); //mxd + if(!preventchanges) UpdateScriptControls(); //mxd } // Browse Action clicked @@ -347,7 +368,7 @@ namespace CodeImp.DoomBuilder.Windows preventchanges = true; anglecontrol.Angle = angle.GetResult(GZBuilder.Controls.AngleControl.NO_ANGLE); preventchanges = false; - updateAngle(); //mxd + UpdateAngle(); //mxd } //mxd. Angle control clicked @@ -355,7 +376,7 @@ namespace CodeImp.DoomBuilder.Windows { if(preventchanges) return; angle.Text = anglecontrol.Angle.ToString(); - updateAngle(); + UpdateAngle(); } // Apply clicked @@ -367,7 +388,8 @@ namespace CodeImp.DoomBuilder.Windows if(General.Map.FormatInterface.HasThingTag) //mxd { tagSelector.ValidateTag();//mxd - if(((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag))) { + if(((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag))) + { General.ShowWarningMessage("Thing tag must be between " + General.Map.FormatInterface.MinTag + " and " + General.Map.FormatInterface.MaxTag + ".", MessageBoxButtons.OK); return; } @@ -410,25 +432,31 @@ namespace CodeImp.DoomBuilder.Windows // Action/tags t.Tag = General.Clamp(tagSelector.GetSmartTag(t.Tag, tagoffset++), General.Map.FormatInterface.MinTag, General.Map.FormatInterface.MaxTag); //mxd - if (!action.Empty) { + if (!action.Empty) + { t.Action = action.Value; //mxd. Script number handling - if(hasAcs) { - if(!string.IsNullOrEmpty(scriptNumbers.Text)) { + if(hasAcs) + { + if(!string.IsNullOrEmpty(scriptNumbers.Text)) + { if(scriptNumbers.SelectedItem != null) t.Args[0] = ((ScriptItem)scriptNumbers.SelectedItem).Index; else if(!int.TryParse(scriptNumbers.Text.Trim(), out t.Args[0])) t.Args[0] = 0; - if(t.Fields.ContainsKey("arg0str")) - t.Fields.Remove("arg0str"); + if(t.Fields.ContainsKey("arg0str")) t.Fields.Remove("arg0str"); } - } else { + } + else + { t.Args[0] = arg0.GetResult(t.Args[0]); if(t.Fields.ContainsKey("arg0str")) t.Fields.Remove("arg0str"); } - }else{ + } + else + { t.Args[0] = arg0.GetResult(t.Args[0]); } @@ -481,10 +509,12 @@ namespace CodeImp.DoomBuilder.Windows if(useAbsoluteHeight && ft.Sector != null) z += ft.Sector.FloorHeight; posZ.Text = z.ToString(); - foreach(Thing t in things) { + foreach(Thing t in things) + { z = t.Position.z; if(useAbsoluteHeight && t.Sector != null) z += t.Sector.FloorHeight; - if (posZ.Text != z.ToString()) { + if (posZ.Text != z.ToString()) + { posZ.Text = ""; break; } @@ -549,13 +579,17 @@ namespace CodeImp.DoomBuilder.Windows if(preventchanges) return; int i = 0; - if(string.IsNullOrEmpty(posZ.Text)) { + if(string.IsNullOrEmpty(posZ.Text)) + { // Restore values foreach(Thing t in things) t.Move(new Vector3D(t.Position.x, t.Position.y, thingProps[i++].Z)); - } else { + } + else + { // Update values - foreach(Thing t in things) { + foreach(Thing t in things) + { float z = posZ.GetResultFloat(thingProps[i++].Z); if(useAbsoluteHeight && !posZ.CheckIsRelative() && t.Sector != null) z -= t.Sector.FloorHeight; @@ -580,7 +614,8 @@ namespace CodeImp.DoomBuilder.Windows if(((thingtype.GetResult(0) < General.Map.FormatInterface.MinThingType) || (thingtype.GetResult(0) > General.Map.FormatInterface.MaxThingType))) return; - foreach(Thing t in things) { + foreach(Thing t in things) + { //Set type t.Type = thingtype.GetResult(t.Type); @@ -593,17 +628,20 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void updateAngle() + private void UpdateAngle() { if(preventchanges) return; int i = 0; //restore values - if(string.IsNullOrEmpty(angle.Text)) { + if(string.IsNullOrEmpty(angle.Text)) + { // Apply rotation foreach(Thing t in things) t.Rotate(thingProps[i++].AngleDoom); - } else { //update values + } + else + { //update values // Apply rotation foreach(Thing t in things) t.Rotate(angle.GetResult(thingProps[i++].AngleDoom)); diff --git a/Source/Core/Windows/ThingEditFormUDMF.Designer.cs b/Source/Core/Windows/ThingEditFormUDMF.Designer.cs index 32df0650..8ba85ed1 100644 --- a/Source/Core/Windows/ThingEditFormUDMF.Designer.cs +++ b/Source/Core/Windows/ThingEditFormUDMF.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.thingtype = new CodeImp.DoomBuilder.Controls.ThingBrowserControl(); diff --git a/Source/Core/Windows/ThingEditFormUDMF.cs b/Source/Core/Windows/ThingEditFormUDMF.cs index 9b90471e..4342b592 100644 --- a/Source/Core/Windows/ThingEditFormUDMF.cs +++ b/Source/Core/Windows/ThingEditFormUDMF.cs @@ -94,12 +94,16 @@ namespace CodeImp.DoomBuilder.Windows InitializeComponent(); //mxd. Widow setup - if(location != Point.Empty) { + if(location != Point.Empty) + { this.StartPosition = FormStartPosition.Manual; this.Location = location; - if(activeTab > 0 && activeTab < tabs.TabCount) { + if(activeTab > 0 && activeTab < tabs.TabCount) + { tabs.SelectTab(activeTab); - } else { + } + else + { activeTab = 0; } } @@ -116,7 +120,8 @@ namespace CodeImp.DoomBuilder.Windows action.GeneralizedCategories = General.Map.Config.GenActionCategories; action.AddInfo(General.Map.Config.SortedLinedefActions.ToArray()); - if (General.Map.FormatInterface.HasCustomFields) { + if (General.Map.FormatInterface.HasCustomFields) + { // Initialize custom fields editor fieldslist.Setup("thing"); @@ -144,7 +149,8 @@ namespace CodeImp.DoomBuilder.Windows cbAbsoluteHeight.Visible = General.Map.FormatInterface.HasThingHeight; //mxd //mxd. Decimals allowed? - if(General.Map.FormatInterface.VertexDecimals > 0) { + if(General.Map.FormatInterface.VertexDecimals > 0) + { posX.AllowDecimal = true; posY.AllowDecimal = true; posZ.AllowDecimal = true; @@ -181,9 +187,9 @@ namespace CodeImp.DoomBuilder.Windows thingtype.SelectType(ft.Type); // Flags - foreach (CheckBox c in flags.Checkboxes) { - if (ft.Flags.ContainsKey(c.Tag.ToString())) - c.Checked = ft.Flags[c.Tag.ToString()]; + foreach (CheckBox c in flags.Checkboxes) + { + if (ft.Flags.ContainsKey(c.Tag.ToString())) c.Checked = ft.Flags[c.Tag.ToString()]; } // Coordination @@ -203,7 +209,8 @@ namespace CodeImp.DoomBuilder.Windows // Custom fields string[] rskeys = null; - if (General.Map.FormatInterface.HasCustomFields) { + if (General.Map.FormatInterface.HasCustomFields) + { fieldslist.SetValues(ft.Fields, true); conversationID.Text = ft.Fields.GetValue("conversation", 0).ToString(); gravity.Text = ft.Fields.GetValue("gravity", 1.0f).ToString(); @@ -218,11 +225,14 @@ namespace CodeImp.DoomBuilder.Windows roll.Text = ft.Roll.ToString(); //Render style - if(General.Map.Config.ThingRenderStyles.Count > 0) { + if(General.Map.Config.ThingRenderStyles.Count > 0) + { rskeys = new string[General.Map.Config.ThingRenderStyles.Count]; General.Map.Config.ThingRenderStyles.Keys.CopyTo(rskeys, 0); renderStyle.SelectedIndex = Array.IndexOf(rskeys, ft.Fields.GetValue("renderstyle", "normal")); - } else { + } + else + { renderStyle.Enabled = false; } } @@ -244,7 +254,8 @@ namespace CodeImp.DoomBuilder.Windows thingProps = new List(); // Go for all things - foreach(Thing t in things) { + foreach(Thing t in things) + { //mxd. Update sector info t.DetermineSector(); @@ -253,7 +264,8 @@ namespace CodeImp.DoomBuilder.Windows if(info != null && info.Index != t.Type) thingtype.ClearSelectedType(); // Flags - foreach(CheckBox c in flags.Checkboxes) { + foreach(CheckBox c in flags.Checkboxes) + { if(c.CheckState == CheckState.Indeterminate) continue; //mxd if(t.IsFlagSet(c.Tag.ToString()) != c.Checked) { @@ -268,9 +280,12 @@ namespace CodeImp.DoomBuilder.Windows //mxd. Position if((t.Position.x).ToString() != posX.Text) posX.Text = ""; if((t.Position.y).ToString() != posY.Text) posY.Text = ""; - if(useAbsoluteHeight && t.Sector != null) { + if(useAbsoluteHeight && t.Sector != null) + { if((t.Position.z + t.Sector.FloorHeight).ToString() != posZ.Text) posZ.Text = ""; - } else if((t.Position.z).ToString() != posZ.Text) { + } + else if((t.Position.z).ToString() != posZ.Text) + { posZ.Text = ""; } @@ -284,7 +299,8 @@ namespace CodeImp.DoomBuilder.Windows if(t.Args[4] != arg4.GetResult(-1)) arg4.ClearValue(); //mxd. Custom fields - if (General.Map.FormatInterface.HasCustomFields) { + if (General.Map.FormatInterface.HasCustomFields) + { t.Fields.BeforeFieldsChange(); //mxd fieldslist.SetValues(t.Fields, false); @@ -310,12 +326,14 @@ namespace CodeImp.DoomBuilder.Windows if (t.Roll.ToString() != roll.Text) roll.Text = ""; //Render style - if(rskeys != null) { + if(rskeys != null) + { if(renderStyle.SelectedIndex > -1 && renderStyle.SelectedIndex != Array.IndexOf(rskeys, t.Fields.GetValue("renderstyle", "normal"))) renderStyle.SelectedIndex = -1; } - if (arg0str != t.Fields.GetValue("arg0str", string.Empty)) { + if (arg0str != t.Fields.GetValue("arg0str", string.Empty)) + { haveArg0Str = true; arg0str = string.Empty; } @@ -325,8 +343,10 @@ namespace CodeImp.DoomBuilder.Windows thingProps.Add(new ThingProperties(t)); //mxd. add user vars - /*if(info != null && info.Actor != null && info.Actor.UserVars.Count > 0) { - foreach(string s in info.Actor.UserVars) { + /*if(info != null && info.Actor != null && info.Actor.UserVars.Count > 0) + { + foreach(string s in info.Actor.UserVars) + { if(!t.Fields.ContainsKey(s)) fieldslist.SetValue(s, 0, CodeImp.DoomBuilder.Types.UniversalType.Integer); } @@ -341,46 +361,61 @@ namespace CodeImp.DoomBuilder.Windows roll_WhenTextChanged(roll, EventArgs.Empty); flags_OnValueChanged(flags, EventArgs.Empty); - updateScriptControls(); //mxd + UpdateScriptControls(); //mxd //mxd. Set intial script-related values, if required - if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) { - if(haveArg0Str) { + if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) + { + if(haveArg0Str) + { scriptNames.Text = arg0str; arg0label.Text = "Script Name:"; - } else { + } + else + { int a0 = arg0.GetResult(0); - if(a0 > 0) { - for(int i = 0; i < General.Map.NumberedScripts.Count; i++) { - if(General.Map.NumberedScripts[i].Index == a0) { + if(a0 > 0) + { + for(int i = 0; i < General.Map.NumberedScripts.Count; i++) + { + if(General.Map.NumberedScripts[i].Index == a0) + { scriptNumbers.SelectedIndex = i; break; } } - if(scriptNumbers.SelectedIndex == -1) { + if(scriptNumbers.SelectedIndex == -1) + { scriptNumbers.Items.Add(new ScriptItem(a0, "Script " + a0)); scriptNumbers.SelectedIndex = scriptNumbers.Items.Count - 1; } - } else { + } + else + { scriptNumbers.Text = arg0.Text; } } - } else { + } + else + { scriptNumbers.Text = "0"; } } //mxd - private void updateScriptControls() + private void UpdateScriptControls() { - if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) { + if(Array.IndexOf(GZBuilder.GZGeneral.ACS_SPECIALS, action.Value) != -1) + { bool showNamedScripts = haveArg0Str; cbArgStr.Visible = true; cbArgStr.Checked = showNamedScripts; scriptNames.Visible = showNamedScripts; scriptNumbers.Visible = !showNamedScripts; - } else { + } + else + { cbArgStr.Visible = false; scriptNames.Visible = false; scriptNumbers.Visible = false; @@ -432,7 +467,8 @@ namespace CodeImp.DoomBuilder.Windows arg4.Setup(arginfo[4]); // Zero all arguments when linedef action 0 (normal) is chosen - if(!preventchanges && (showaction == 0)) { + if(!preventchanges && (showaction == 0)) + { //mxd arg0.SetDefaultValue(); arg1.SetDefaultValue(); @@ -441,7 +477,7 @@ namespace CodeImp.DoomBuilder.Windows arg4.SetDefaultValue(); } - if(!preventchanges) updateScriptControls(); //mxd + if(!preventchanges) UpdateScriptControls(); //mxd } // Browse Action clicked @@ -457,7 +493,7 @@ namespace CodeImp.DoomBuilder.Windows preventchanges = true; anglecontrol.Angle = angle.GetResult(GZBuilder.Controls.AngleControl.NO_ANGLE); preventchanges = false; - updateAngle(); //mxd + UpdateAngle(); //mxd } //mxd. Angle control clicked @@ -465,7 +501,7 @@ namespace CodeImp.DoomBuilder.Windows { if(preventchanges) return; angle.Text = anglecontrol.Angle.ToString(); - updateAngle(); + UpdateAngle(); } private void pitch_WhenTextChanged(object sender, EventArgs e) @@ -475,14 +511,14 @@ namespace CodeImp.DoomBuilder.Windows preventchanges = true; pitchControl.Angle = (p == GZBuilder.Controls.AngleControl.NO_ANGLE ? p : p + 90); preventchanges = false; - updatePitch(); + UpdatePitch(); } private void pitchControl_AngleChanged() { if(preventchanges) return; pitch.Text = (General.ClampAngle(pitchControl.Angle - 90)).ToString(); - updatePitch(); + UpdatePitch(); } private void roll_WhenTextChanged(object sender, EventArgs e) @@ -492,14 +528,14 @@ namespace CodeImp.DoomBuilder.Windows preventchanges = true; rollControl.Angle = (r == GZBuilder.Controls.AngleControl.NO_ANGLE ? r : r + 90); preventchanges = false; - updateRoll(); + UpdateRoll(); } private void rollControl_AngleChanged() { if(preventchanges) return; roll.Text = (General.ClampAngle(rollControl.Angle - 90)).ToString(); - updateRoll(); + UpdateRoll(); } // Apply clicked @@ -511,20 +547,23 @@ namespace CodeImp.DoomBuilder.Windows if(General.Map.FormatInterface.HasThingTag) //mxd { tagSelector.ValidateTag();//mxd - if(((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag))) { + if(((tagSelector.GetTag(0) < General.Map.FormatInterface.MinTag) || (tagSelector.GetTag(0) > General.Map.FormatInterface.MaxTag))) + { General.ShowWarningMessage("Thing tag must be between " + General.Map.FormatInterface.MinTag + " and " + General.Map.FormatInterface.MaxTag + ".", MessageBoxButtons.OK); return; } } // Verify the type - if(((thingtype.GetResult(0) < General.Map.FormatInterface.MinThingType) || (thingtype.GetResult(0) > General.Map.FormatInterface.MaxThingType))) { + if(((thingtype.GetResult(0) < General.Map.FormatInterface.MinThingType) || (thingtype.GetResult(0) > General.Map.FormatInterface.MaxThingType))) + { General.ShowWarningMessage("Thing type must be between " + General.Map.FormatInterface.MinThingType + " and " + General.Map.FormatInterface.MaxThingType + ".", MessageBoxButtons.OK); return; } // Verify the action - if(General.Map.FormatInterface.HasThingAction && ((action.Value < General.Map.FormatInterface.MinAction) || (action.Value > General.Map.FormatInterface.MaxAction))) { + if(General.Map.FormatInterface.HasThingAction && ((action.Value < General.Map.FormatInterface.MinAction) || (action.Value > General.Map.FormatInterface.MaxAction))) + { General.ShowWarningMessage("Thing action must be between " + General.Map.FormatInterface.MinAction + " and " + General.Map.FormatInterface.MaxAction + ".", MessageBoxButtons.OK); return; } @@ -533,14 +572,16 @@ namespace CodeImp.DoomBuilder.Windows //mxd string[] rskeys = null; - if(General.Map.Config.ThingRenderStyles.Count > 0) { + if(General.Map.Config.ThingRenderStyles.Count > 0) + { rskeys = new string[General.Map.Config.ThingRenderStyles.Count]; General.Map.Config.ThingRenderStyles.Keys.CopyTo(rskeys, 0); } // Go for all the things int tagoffset = 0; //mxd - foreach(Thing t in things) { + foreach(Thing t in things) + { // Coordination //mxd. Check position float px = General.Clamp(t.Position.x, General.Map.Config.LeftBoundary, General.Map.Config.RightBoundary); @@ -548,7 +589,8 @@ namespace CodeImp.DoomBuilder.Windows if(t.Position.x != px || t.Position.y != py) t.Move(new Vector2D(px, py)); // Apply all flags - foreach(CheckBox c in flags.Checkboxes) { + foreach(CheckBox c in flags.Checkboxes) + { if(c.CheckState == CheckState.Checked) t.SetFlag(c.Tag.ToString(), true); else if(c.CheckState == CheckState.Unchecked) @@ -557,13 +599,17 @@ namespace CodeImp.DoomBuilder.Windows // Action/tags t.Tag = General.Clamp(tagSelector.GetSmartTag(t.Tag, tagoffset++), General.Map.FormatInterface.MinTag, General.Map.FormatInterface.MaxTag); //mxd - if(!action.Empty) { + if(!action.Empty) + { t.Action = action.Value; //mxd. Script name/number handling - if(hasAcs) { - if(!cbArgStr.Checked) { //apply script number - if(!string.IsNullOrEmpty(scriptNumbers.Text)) { + if(hasAcs) + { + if(!cbArgStr.Checked) //apply script number + { + if(!string.IsNullOrEmpty(scriptNumbers.Text)) + { if(scriptNumbers.SelectedItem != null) t.Args[0] = ((ScriptItem)scriptNumbers.SelectedItem).Index; else if(!int.TryParse(scriptNumbers.Text.Trim(), out t.Args[0])) @@ -572,16 +618,22 @@ namespace CodeImp.DoomBuilder.Windows if(General.Map.FormatInterface.HasCustomFields && t.Fields.ContainsKey("arg0str")) t.Fields.Remove("arg0str"); } - } else { //apply arg0str + } + else //apply arg0str + { if(!string.IsNullOrEmpty(scriptNames.Text)) t.Fields["arg0str"] = new UniValue(UniversalType.String, scriptNames.Text); } - } else { + } + else + { t.Args[0] = arg0.GetResult(t.Args[0]); if(General.Map.FormatInterface.HasCustomFields && t.Fields.ContainsKey("arg0str")) t.Fields.Remove("arg0str"); } - } else { + } + else + { t.Args[0] = arg0.GetResult(t.Args[0]); } @@ -591,7 +643,8 @@ namespace CodeImp.DoomBuilder.Windows t.Args[4] = arg4.GetResult(t.Args[4]); //mxd. Custom fields - if (General.Map.FormatInterface.HasCustomFields) { + if (General.Map.FormatInterface.HasCustomFields) + { fieldslist.Apply(t.Fields); if (!string.IsNullOrEmpty(conversationID.Text)) UDMFTools.SetInteger(t.Fields, "conversation", conversationID.GetResult(t.Fields.GetValue("conversation", 0)), 0); @@ -614,9 +667,9 @@ namespace CodeImp.DoomBuilder.Windows } // Set as defaults - foreach (CheckBox c in flags.Checkboxes) { - if (c.CheckState == CheckState.Checked) - defaultflags.Add(c.Tag.ToString()); + foreach (CheckBox c in flags.Checkboxes) + { + if (c.CheckState == CheckState.Checked) defaultflags.Add(c.Tag.ToString()); } General.Settings.DefaultThingType = thingtype.GetResult(General.Settings.DefaultThingType); General.Settings.DefaultThingAngle = Angle2D.DegToRad((float)angle.GetResult((int)Angle2D.RadToDeg(General.Settings.DefaultThingAngle) - 90) + 90); @@ -664,10 +717,12 @@ namespace CodeImp.DoomBuilder.Windows if(useAbsoluteHeight && ft.Sector != null) z += ft.Sector.FloorHeight; posZ.Text = z.ToString(); - foreach(Thing t in things) { + foreach(Thing t in things) + { z = t.Position.z; if(useAbsoluteHeight && t.Sector != null) z += t.Sector.FloorHeight; - if(posZ.Text != z.ToString()) { + if(posZ.Text != z.ToString()) + { posZ.Text = ""; break; } @@ -683,7 +738,8 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void ThingEditForm_FormClosing(object sender, FormClosingEventArgs e) { + private void ThingEditForm_FormClosing(object sender, FormClosingEventArgs e) + { location = this.Location; activeTab = tabs.SelectedIndex; } @@ -730,13 +786,17 @@ namespace CodeImp.DoomBuilder.Windows if(preventchanges) return; int i = 0; - if(string.IsNullOrEmpty(posZ.Text)) { + if(string.IsNullOrEmpty(posZ.Text)) + { // Restore values foreach(Thing t in things) t.Move(new Vector3D(t.Position.x, t.Position.y, thingProps[i++].Z)); - } else { + } + else + { // Update values - foreach(Thing t in things) { + foreach(Thing t in things) + { float z = posZ.GetResultFloat(thingProps[i++].Z); if(useAbsoluteHeight && !posZ.CheckIsRelative() && t.Sector != null) z -= t.Sector.FloorHeight; @@ -753,7 +813,8 @@ namespace CodeImp.DoomBuilder.Windows if (preventchanges) return; int i = 0; - foreach (Thing t in things){ + foreach (Thing t in things) + { float sx = scale.GetValue1(thingProps[i].ScaleX); float sy = scale.GetValue2(thingProps[i].ScaleY); t.SetScale((sx == 0 ? 1.0f : sx), (sy == 0 ? 1.0f : sy)); @@ -778,7 +839,8 @@ namespace CodeImp.DoomBuilder.Windows || (thingtype.GetResult(0) > General.Map.FormatInterface.MaxThingType)) return; - foreach(Thing t in things) { + foreach(Thing t in things) + { //Set type t.Type = thingtype.GetResult(t.Type); @@ -791,16 +853,18 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void updateAngle() + private void UpdateAngle() { if(preventchanges) return; int i = 0; //restore values - if(string.IsNullOrEmpty(angle.Text)) { - foreach(Thing t in things) - t.Rotate(thingProps[i++].AngleDoom); - } else { //update values + if(string.IsNullOrEmpty(angle.Text)) + { + foreach(Thing t in things) t.Rotate(thingProps[i++].AngleDoom); + } + else //update values + { foreach(Thing t in things) t.Rotate(angle.GetResult(thingProps[i++].AngleDoom)); } @@ -809,16 +873,18 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void updatePitch() + private void UpdatePitch() { if (preventchanges) return; int i = 0; //restore values - if (string.IsNullOrEmpty(pitch.Text)) { - foreach (Thing t in things) - t.SetPitch(thingProps[i++].Pitch); - } else { //update values + if (string.IsNullOrEmpty(pitch.Text)) + { + foreach (Thing t in things) t.SetPitch(thingProps[i++].Pitch); + } + else //update values + { foreach (Thing t in things) t.SetPitch(pitch.GetResult(thingProps[i++].Pitch)); } @@ -827,16 +893,19 @@ namespace CodeImp.DoomBuilder.Windows if (OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void updateRoll() + //mxd + private void UpdateRoll() { if (preventchanges) return; int i = 0; //restore values - if (string.IsNullOrEmpty(roll.Text)) { - foreach (Thing t in things) - t.SetRoll(thingProps[i++].Roll); - } else { //update values + if (string.IsNullOrEmpty(roll.Text)) + { + foreach (Thing t in things) t.SetRoll(thingProps[i++].Roll); + } + else //update values + { foreach (Thing t in things) t.SetRoll(roll.GetResult(thingProps[i++].Roll)); } diff --git a/Source/Core/Windows/VertexEditForm.cs b/Source/Core/Windows/VertexEditForm.cs index 99f020f7..076ecdfc 100644 --- a/Source/Core/Windows/VertexEditForm.cs +++ b/Source/Core/Windows/VertexEditForm.cs @@ -58,7 +58,8 @@ namespace CodeImp.DoomBuilder.Windows public float ZCeiling; public float ZFloor; - public VertexProperties(Vertex v) { + public VertexProperties(Vertex v) + { X = v.Position.x; Y = v.Position.y; ZCeiling = v.ZCeiling; @@ -76,23 +77,30 @@ namespace CodeImp.DoomBuilder.Windows InitializeComponent(); //mxd. Widow setup - if(location != Point.Empty) { + if(location != Point.Empty) + { this.StartPosition = FormStartPosition.Manual; this.Location = location; - if(activeTab > 0 && activeTab < tabs.TabCount) { + if(activeTab > 0 && activeTab < tabs.TabCount) + { tabs.SelectTab(activeTab); - } else { + } + else + { activeTab = 0; } } - if(General.Map.FormatInterface.HasCustomFields) { //mxd + if(General.Map.FormatInterface.HasCustomFields) //mxd + { // Initialize custom fields editor fieldslist.Setup("vertex"); // Fill universal fields list fieldslist.ListFixedFields(General.Map.Config.VertexFields); - } else { + } + else + { tabs.TabPages.Remove(tabcustom); panelHeightControls.Visible = false; } @@ -169,11 +177,13 @@ namespace CodeImp.DoomBuilder.Windows } //mxd. Height offsets - if(General.Map.UDMF) { + if(General.Map.UDMF) + { zceiling.Text = (float.IsNaN(vc.ZCeiling) ? CLEAR_VALUE : vc.ZCeiling.ToString()); zfloor.Text = (float.IsNaN(vc.ZFloor) ? CLEAR_VALUE : vc.ZFloor.ToString()); - foreach(Vertex v in vertices) { + foreach(Vertex v in vertices) + { string zc = (float.IsNaN(v.ZCeiling) ? CLEAR_VALUE : v.ZCeiling.ToString()); string zf = (float.IsNaN(v.ZFloor) ? CLEAR_VALUE : v.ZFloor.ToString()); @@ -189,82 +199,94 @@ namespace CodeImp.DoomBuilder.Windows #region ================== mxd. Realtime Events - private void positionx_WhenTextChanged(object sender, EventArgs e) { + private void positionx_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; int i = 0; //restore values - if(string.IsNullOrEmpty(positionx.Text)) { + if(string.IsNullOrEmpty(positionx.Text)) + { // Apply position - foreach(Vertex v in vertices) - v.Move(new Vector2D(vertexProps[i++].X, v.Position.y)); - } else { //update values + foreach(Vertex v in vertices) v.Move(new Vector2D(vertexProps[i++].X, v.Position.y)); + } + else //update values + { // Verify the coordinates float px = positionx.GetResultFloat(vertexProps[i].X); - if(px < General.Map.FormatInterface.MinCoordinate) { + if(px < General.Map.FormatInterface.MinCoordinate) + { positionx.Text = General.Map.FormatInterface.MinCoordinate.ToString(); return; } - if(px > General.Map.FormatInterface.MaxCoordinate) { + if(px > General.Map.FormatInterface.MaxCoordinate) + { positionx.Text = General.Map.FormatInterface.MaxCoordinate.ToString(); return; } // Apply position - foreach(Vertex v in vertices) - v.Move(new Vector2D(px, v.Position.y)); + foreach(Vertex v in vertices) v.Move(new Vector2D(px, v.Position.y)); } General.Map.IsChanged = true; if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void positiony_WhenTextChanged(object sender, EventArgs e) { + private void positiony_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; int i = 0; //restore values - if(string.IsNullOrEmpty(positiony.Text)) { + if(string.IsNullOrEmpty(positiony.Text)) + { // Apply position - foreach(Vertex v in vertices) - v.Move(new Vector2D(v.Position.x, vertexProps[i++].Y)); - } else { //update values + foreach(Vertex v in vertices) v.Move(new Vector2D(v.Position.x, vertexProps[i++].Y)); + } + else //update values + { // Verify the coordinates float py = positiony.GetResultFloat(vertexProps[i].Y); - if(py < General.Map.FormatInterface.MinCoordinate) { + if(py < General.Map.FormatInterface.MinCoordinate) + { positiony.Text = General.Map.FormatInterface.MinCoordinate.ToString(); return; } - if(py > General.Map.FormatInterface.MaxCoordinate) { + if(py > General.Map.FormatInterface.MaxCoordinate) + { positiony.Text = General.Map.FormatInterface.MaxCoordinate.ToString(); return; } // Apply position - foreach(Vertex v in vertices) - v.Move(new Vector2D(v.Position.x, py)); + foreach(Vertex v in vertices) v.Move(new Vector2D(v.Position.x, py)); } General.Map.IsChanged = true; if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void zceiling_WhenTextChanged(object sender, EventArgs e) { + private void zceiling_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; int i = 0; //restore values - if(string.IsNullOrEmpty(zceiling.Text)) { - foreach(Vertex v in vertices) - v.ZCeiling = vertexProps[i++].ZCeiling; - //clear values - } else if(zceiling.Text == CLEAR_VALUE) { - foreach(Vertex v in vertices) - v.ZCeiling = float.NaN; - //update values - } else { + if(string.IsNullOrEmpty(zceiling.Text)) + { + foreach(Vertex v in vertices) v.ZCeiling = vertexProps[i++].ZCeiling; + + } + else if(zceiling.Text == CLEAR_VALUE) //clear values + { + foreach(Vertex v in vertices) v.ZCeiling = float.NaN; + + } + else //update values + { foreach(Vertex v in vertices) v.ZCeiling = zceiling.GetResultFloat(vertexProps[i++].ZCeiling); } @@ -273,20 +295,24 @@ namespace CodeImp.DoomBuilder.Windows if(OnValuesChanged != null) OnValuesChanged(this, EventArgs.Empty); } - private void zfloor_WhenTextChanged(object sender, EventArgs e) { + private void zfloor_WhenTextChanged(object sender, EventArgs e) + { if(blockUpdate) return; int i = 0; //restore values - if(string.IsNullOrEmpty(zfloor.Text)) { + if(string.IsNullOrEmpty(zfloor.Text)) + { foreach(Vertex v in vertices) v.ZFloor = vertexProps[i++].ZFloor; - //clear values - }else if(zfloor.Text == CLEAR_VALUE){ - foreach(Vertex v in vertices) - v.ZFloor = float.NaN; - //update values - } else { + + } + else if(zfloor.Text == CLEAR_VALUE) //clear values + { + foreach(Vertex v in vertices) v.ZFloor = float.NaN; + } + else //update values + { foreach(Vertex v in vertices) v.ZFloor = zfloor.GetResultFloat(vertexProps[i++].ZFloor); } @@ -296,12 +322,14 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void clearZFloor_Click(object sender, EventArgs e) { + private void clearZFloor_Click(object sender, EventArgs e) + { zfloor.Text = CLEAR_VALUE; } //mxd - private void clearZCeiling_Click(object sender, EventArgs e) { + private void clearZCeiling_Click(object sender, EventArgs e) + { zceiling.Text = CLEAR_VALUE; } @@ -313,8 +341,9 @@ namespace CodeImp.DoomBuilder.Windows private void apply_Click(object sender, EventArgs e) { //apply custom fields - if(General.Map.FormatInterface.HasCustomFields) { //mxd - foreach(Vertex v in vertices) fieldslist.Apply(v.Fields); + if(General.Map.FormatInterface.HasCustomFields) + { + foreach(Vertex v in vertices) fieldslist.Apply(v.Fields); //mxd } General.Map.IsChanged = true; @@ -337,12 +366,14 @@ namespace CodeImp.DoomBuilder.Windows } //mxd - private void tabcustom_MouseEnter(object sender, EventArgs e) { + private void tabcustom_MouseEnter(object sender, EventArgs e) + { fieldslist.Focus(); } //mxd - private void VertexEditForm_FormClosing(object sender, FormClosingEventArgs e) { + private void VertexEditForm_FormClosing(object sender, FormClosingEventArgs e) + { location = this.Location; activeTab = tabs.SelectedIndex; } diff --git a/Source/Core/ZDoom/ActorStructure.cs b/Source/Core/ZDoom/ActorStructure.cs index 52a7677b..ba5f5602 100644 --- a/Source/Core/ZDoom/ActorStructure.cs +++ b/Source/Core/ZDoom/ActorStructure.cs @@ -109,12 +109,14 @@ namespace CodeImp.DoomBuilder.ZDoom { token = token.ToLowerInvariant(); - switch (token) { + switch (token) + { case ":": // The next token must be the class to inherit from parser.SkipWhitespace(true); inheritclass = parser.StripTokenQuotes(parser.ReadToken()); - if(string.IsNullOrEmpty(inheritclass) || parser.IsSpecialToken(inheritclass)) { + if(string.IsNullOrEmpty(inheritclass) || parser.IsSpecialToken(inheritclass)) + { parser.ReportError("Expected class name to inherit from"); return; } @@ -127,7 +129,8 @@ namespace CodeImp.DoomBuilder.ZDoom // The next token must be the class to replace parser.SkipWhitespace(true); replaceclass = parser.StripTokenQuotes(parser.ReadToken()); - if(string.IsNullOrEmpty(replaceclass) || parser.IsSpecialToken(replaceclass)) { + if(string.IsNullOrEmpty(replaceclass) || parser.IsSpecialToken(replaceclass)) + { parser.ReportError("Expected class name to replace"); return; } @@ -182,18 +185,22 @@ namespace CodeImp.DoomBuilder.ZDoom string token = parser.ReadToken(); token = token.ToLowerInvariant(); - switch (token) { + switch (token) + { case "+": case "-": // Next token is a flag (option) to set or remove bool flagvalue = (token == "+"); parser.SkipWhitespace(true); string flagname = parser.ReadToken(); - if (!string.IsNullOrEmpty(flagname)) { + if (!string.IsNullOrEmpty(flagname)) + { // Add the flag with its value flagname = flagname.ToLowerInvariant(); flags[flagname] = flagvalue; - } else { + } + else + { parser.ReportError("Expected flag name"); return; } @@ -202,7 +209,8 @@ namespace CodeImp.DoomBuilder.ZDoom case "action": case "native": // We don't need this, ignore up to the first next ; - while (parser.SkipWhitespace(true)) { + while (parser.SkipWhitespace(true)) + { string t = parser.ReadToken(); if ((t == ";") || (t == null)) break; @@ -215,36 +223,47 @@ namespace CodeImp.DoomBuilder.ZDoom case "states": // Now parse actor states until we reach the end of the states structure - while (parser.SkipWhitespace(true)) { + while (parser.SkipWhitespace(true)) + { string statetoken = parser.ReadToken(); - if (!string.IsNullOrEmpty(statetoken)) { + if (!string.IsNullOrEmpty(statetoken)) + { // Start of scope? - if (statetoken == "{") { + if (statetoken == "{") + { // This is fine } - // End of scope? - else if (statetoken == "}") { + // End of scope? + else if (statetoken == "}") + { // Done with the states, // break out of this parse loop break; } - // State label? - else if (statetoken == ":") { - if (!string.IsNullOrEmpty(previoustoken)) { + // State label? + else if (statetoken == ":") + { + if (!string.IsNullOrEmpty(previoustoken)) + { // Parse actor state StateStructure st = new StateStructure(this, parser); - if (parser.HasError) - return; + if (parser.HasError) return; states[previoustoken.ToLowerInvariant()] = st; - } else { + } + else + { parser.ReportError("Unexpected end of structure"); return; } - } else { + } + else + { // Keep token previoustoken = statetoken; } - } else { + } + else + { parser.ReportError("Unexpected end of structure"); return; } @@ -252,7 +271,8 @@ namespace CodeImp.DoomBuilder.ZDoom break; case "var": //mxd - while (parser.SkipWhitespace(true)) { + while (parser.SkipWhitespace(true)) + { string t = parser.ReadToken(); if ((t == ";") || (t == null)) break; if (t.StartsWith("user_") && !userVars.Contains(t)) @@ -301,9 +321,11 @@ namespace CodeImp.DoomBuilder.ZDoom case "game": // Include all tokens on the same line List games = new List(); - while (parser.SkipWhitespace(false)) { + while (parser.SkipWhitespace(false)) + { string v = parser.ReadToken(); - if (v == null) { + if (v == null) + { parser.ReportError("Unexpected end of structure"); return; } @@ -317,15 +339,20 @@ namespace CodeImp.DoomBuilder.ZDoom // Property default: // Property begins with $? Then the whole line is a single value - if (token.StartsWith("$")) { + if (token.StartsWith("$")) + { // This is for editor-only properties such as $sprite and $category props[token] = new List { (parser.SkipWhitespace(false) ? parser.ReadLine() : "") }; - } else { + } + else + { // Next tokens up until the next newline are values List values = new List(); - while (parser.SkipWhitespace(false)) { + while (parser.SkipWhitespace(false)) + { string v = parser.ReadToken(); - if (v == null) { + if (v == null) + { parser.ReportError("Unexpected end of structure"); return; } @@ -345,13 +372,16 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd. Check if baseclass is valid - if(inheritclass != "actor" && doomednum > -1 && baseclass == null) { + if(inheritclass != "actor" && doomednum > -1 && baseclass == null) + { //check if this class inherits from a class defined in game configuration Dictionary things = General.Map.Config.GetThingTypes(); inheritclass = inheritclass.ToLowerInvariant(); - foreach(KeyValuePair ti in things) { - if(ti.Value.ClassName == inheritclass) { + foreach(KeyValuePair ti in things) + { + if(ti.Value.ClassName == inheritclass) + { //states if(states.Count == 0 && !string.IsNullOrEmpty(ti.Value.Sprite)) states.Add("spawn", new StateStructure(ti.Value.Sprite.Substring(0, 4))); @@ -631,60 +661,64 @@ namespace CodeImp.DoomBuilder.ZDoom //mxd. ///TODO: rewrite this - public string FindSuitableVoxel(Dictionary voxels) { + public string FindSuitableVoxel(Dictionary voxels) + { string result = string.Empty; // Try the idle state - if(HasState("idle")) { + if(HasState("idle")) + { StateStructure s = GetState("idle"); string spritename = s.GetSprite(0); - if(!string.IsNullOrEmpty(spritename)) - result = spritename; + if(!string.IsNullOrEmpty(spritename)) result = spritename; } // Try the see state - if(string.IsNullOrEmpty(result) && HasState("see")) { + if(string.IsNullOrEmpty(result) && HasState("see")) + { StateStructure s = GetState("see"); string spritename = s.GetSprite(0); - if(!string.IsNullOrEmpty(spritename)) - result = spritename; + if(!string.IsNullOrEmpty(spritename)) result = spritename; } // Try the inactive state - if(string.IsNullOrEmpty(result) && HasState("inactive")) { + if(string.IsNullOrEmpty(result) && HasState("inactive")) + { StateStructure s = GetState("inactive"); string spritename = s.GetSprite(0); - if(!string.IsNullOrEmpty(spritename)) - result = spritename; + if(!string.IsNullOrEmpty(spritename)) result = spritename; } // Try the spawn state - if(string.IsNullOrEmpty(result) && HasState("spawn")) { + if(string.IsNullOrEmpty(result) && HasState("spawn")) + { StateStructure s = GetState("spawn"); string spritename = s.GetSprite(0); - if(!string.IsNullOrEmpty(spritename)) - result = spritename; + if(!string.IsNullOrEmpty(spritename)) result = spritename; } // Still no sprite found? then just pick the first we can find - if(string.IsNullOrEmpty(result)) { + if(string.IsNullOrEmpty(result)) + { Dictionary list = GetAllStates(); - foreach(StateStructure s in list.Values) { + foreach(StateStructure s in list.Values) + { string spritename = s.GetSprite(0); - if(!string.IsNullOrEmpty(spritename)) { + if(!string.IsNullOrEmpty(spritename)) + { result = spritename; break; } } } - if(!string.IsNullOrEmpty(result)) { + if(!string.IsNullOrEmpty(result)) + { if (voxels.ContainsKey(result)) return result; // The sprite name may be incomplete. Find an existing sprite with direction. - foreach(string postfix in SPRITE_POSTFIXES) { + foreach(string postfix in SPRITE_POSTFIXES) if(voxels.ContainsKey(result + postfix)) return result + postfix; - } } diff --git a/Source/Core/ZDoom/PatchStructure.cs b/Source/Core/ZDoom/PatchStructure.cs index 3fa6e847..02df607c 100644 --- a/Source/Core/ZDoom/PatchStructure.cs +++ b/Source/Core/ZDoom/PatchStructure.cs @@ -147,7 +147,8 @@ namespace CodeImp.DoomBuilder.ZDoom string token = parser.ReadToken(); token = token.ToLowerInvariant(); - switch (token) { + switch (token) + { case "flipx": flipx = true; break; @@ -166,7 +167,8 @@ namespace CodeImp.DoomBuilder.ZDoom rotation = rotation % 360; //Coalesce multiples if (rotation < 0) rotation += 360; //Force positive - if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) { + if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) + { General.ErrorLogger.Add(ErrorType.Warning, "Got unsupported rotation (" + rotation + ") in patch " + name); rotation = 0; } @@ -187,12 +189,15 @@ namespace CodeImp.DoomBuilder.ZDoom parser.SkipWhitespace(false); token = parser.ReadToken(); - if (token == ",") { //read tint ammount + if (token == ",") //read tint ammount + { parser.SkipWhitespace(false); if (!ReadTokenFloat(parser, token, out tintAmmount)) return; tintAmmount = General.Clamp(tintAmmount, 0.0f, 1.0f); blendStyle = TexturePathBlendStyle.Tint; - } else { + } + else + { blendStyle = TexturePathBlendStyle.Blend; // Rewind so this structure can be read again parser.DataStream.Seek(-token.Length - 1, SeekOrigin.Current); @@ -262,11 +267,13 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd. This reads the next token and sets a string value, returns false when failed - private static bool ReadTokenString(TexturesParser parser, string propertyname, out string value) { + private static bool ReadTokenString(TexturesParser parser, string propertyname, out string value) + { parser.SkipWhitespace(true); value = parser.StripTokenQuotes(parser.ReadToken()); - if(string.IsNullOrEmpty(value)) { + if(string.IsNullOrEmpty(value)) + { // Can't find the property value! parser.ReportError("Expected a value for property '" + propertyname + "'"); return false; @@ -275,24 +282,28 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd. This reads the next token and sets a PixelColor value, returns false when failed - private static bool ReadTokenColor(TexturesParser parser, string propertyname, out int value) { + private static bool ReadTokenColor(TexturesParser parser, string propertyname, out int value) + { parser.SkipWhitespace(true); string strvalue = parser.StripTokenQuotes(parser.ReadToken()); value = 0; - if(string.IsNullOrEmpty(strvalue)) { + if(string.IsNullOrEmpty(strvalue)) + { // Can't find the property value! parser.ReportError("Expected a value for property '" + propertyname + "'"); return false; } - if(strvalue[0] != '#') { + if(strvalue[0] != '#') + { parser.ReportError("Expected color value for property '" + propertyname + "'"); return false; } // Try parsing as value - if(!int.TryParse(strvalue.Remove(0, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value)) { + if(!int.TryParse(strvalue.Remove(0, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value)) + { parser.ReportError("Expected color value for property '" + propertyname + "'"); return false; } diff --git a/Source/Core/ZDoom/StateStructure.cs b/Source/Core/ZDoom/StateStructure.cs index 001104fd..2d779903 100644 --- a/Source/Core/ZDoom/StateStructure.cs +++ b/Source/Core/ZDoom/StateStructure.cs @@ -142,7 +142,8 @@ namespace CodeImp.DoomBuilder.ZDoom t = parser.ReadToken(); //mxd. Because stuff like this is also valid: "Actor Oneliner { States { Spawn: WOOT A 1 A_FadeOut(0.1) Loop }}" - if(t == "}") { + if(t == "}") + { // Rewind so that this scope end can be read again parser.DataStream.Seek(-1, SeekOrigin.Current); @@ -157,7 +158,8 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd - internal StateStructure(string spriteName) { + internal StateStructure(string spriteName) + { this.gotostate = null; this.sprites = new List() { spriteName }; } diff --git a/Source/Core/ZDoom/TextureStructure.cs b/Source/Core/ZDoom/TextureStructure.cs index df2e6f55..05402503 100644 --- a/Source/Core/ZDoom/TextureStructure.cs +++ b/Source/Core/ZDoom/TextureStructure.cs @@ -140,7 +140,8 @@ namespace CodeImp.DoomBuilder.ZDoom string token = parser.ReadToken(); token = token.ToLowerInvariant(); - switch (token) { + switch (token) + { case "xscale": if (!ReadTokenFloat(parser, token, out xscale)) return; break; @@ -160,7 +161,8 @@ namespace CodeImp.DoomBuilder.ZDoom // Now we should find a comma parser.SkipWhitespace(true); tokenstr = parser.ReadToken(); - if (tokenstr != ",") { + if (tokenstr != ",") + { parser.ReportError("Expected a comma"); return; } diff --git a/Source/Core/ZDoom/VoxeldefParser.cs b/Source/Core/ZDoom/VoxeldefParser.cs index b88121d4..5206943d 100644 --- a/Source/Core/ZDoom/VoxeldefParser.cs +++ b/Source/Core/ZDoom/VoxeldefParser.cs @@ -1,10 +1,14 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; using System.IO; using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.GZBuilder.Data; using SlimDX; +#endregion + namespace CodeImp.DoomBuilder.ZDoom { public sealed class VoxeldefParser : ZDTextParser @@ -12,7 +16,8 @@ namespace CodeImp.DoomBuilder.ZDoom private Dictionary entries; //sprite name, entry internal Dictionary Entries { get { return entries; } } - public override bool Parse(Stream stream, string sourcefilename) { + public override bool Parse(Stream stream, string sourcefilename) + { base.Parse(stream, sourcefilename); entries = new Dictionary(StringComparer.Ordinal); string prevToken = string.Empty; @@ -21,55 +26,69 @@ namespace CodeImp.DoomBuilder.ZDoom string modelName = string.Empty; // Continue until at the end of the stream - while(SkipWhitespace(true)) { + while(SkipWhitespace(true)) + { string token = ReadToken(); - if(token != null) { + if(token != null) + { token = StripTokenQuotes(token).ToLowerInvariant(); - if(token == ",") { //previous token was a sprite name - if(!string.IsNullOrEmpty(prevToken)) { - //if(prevToken.Length > 4) prevToken = prevToken.Substring(0, 4); + if(token == ",") //previous token was a sprite name + { + if(!string.IsNullOrEmpty(prevToken)) + { if(!spriteNames.Contains(prevToken)) spriteNames.Add(prevToken); } prevToken = token.ToUpperInvariant(); - } else if(token == "=") { //next token should be a voxel model name - if(!string.IsNullOrEmpty(prevToken)) { - //if(prevToken.Length > 4) prevToken = prevToken.Substring(0, 4); + } + else if(token == "=") //next token should be a voxel model name + { + if(!string.IsNullOrEmpty(prevToken)) + { if(!spriteNames.Contains(prevToken)) spriteNames.Add(prevToken); } SkipWhitespace(true); token = ReadToken(); - if(string.IsNullOrEmpty(token)) { + if(string.IsNullOrEmpty(token)) + { General.ErrorLogger.Add(ErrorType.Error, "Unable to get voxel model name from '" + sourcefilename + "', line " + GetCurrentLineNumber()); spriteNames.Clear(); continue; } modelName = StripTokenQuotes(token).ToLowerInvariant(); - - //read the settings - } else if(token == "{") { + } + else if(token == "{") //read the settings + { ModelData data = new ModelData(); data.IsVoxel = true; - while(SkipWhitespace(true)) { + while(SkipWhitespace(true)) + { token = ReadToken(); - if(!string.IsNullOrEmpty(token)) { + if(!string.IsNullOrEmpty(token)) + { token = StripTokenQuotes(token).ToLowerInvariant(); - if(token == "}") { //store data - if(!string.IsNullOrEmpty(modelName) && spriteNames.Count > 0) { + if(token == "}") //store data + { + if(!string.IsNullOrEmpty(modelName) && spriteNames.Count > 0) + { data.ModelNames.Add(modelName); - foreach(string s in spriteNames){ - if(entries.ContainsKey(s)) { //TODO: is this a proper behaviour? + foreach(string s in spriteNames) + { + if(entries.ContainsKey(s)) //TODO: is this a proper behaviour? + { entries[s] = data; - } else { + } + else + { entries.Add(s, data); } } @@ -81,38 +100,47 @@ namespace CodeImp.DoomBuilder.ZDoom } break; - } else if(token == "overridepalette") { + } + else if(token == "overridepalette") + { data.OverridePalette = true; - - } else if(token == "angleoffset") { + } + else if(token == "angleoffset") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if(token != "=") { + if(token != "=") + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + sourcefilename + " at line " + GetCurrentLineNumber() + ": expected '=', but got '" + token + "'"); break; } float angleOffset = 0; //90? token = StripTokenQuotes(ReadToken()); - if(!ReadSignedFloat(token, ref angleOffset)) { + if(!ReadSignedFloat(token, ref angleOffset)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + sourcefilename + " at line " + GetCurrentLineNumber() + ": expected AngleOffset value, but got '" + token + "'"); } data.AngleOffset = Angle2D.DegToRad(angleOffset); - } else if(token == "scale") { + } + else if(token == "scale") + { SkipWhitespace(true); token = StripTokenQuotes(ReadToken()); - if(token != "=") { + if(token != "=") + { General.ErrorLogger.Add(ErrorType.Error, "Error in " + sourcefilename + " at line " + GetCurrentLineNumber() + ": expected '=', but got '" + token + "'"); break; } float scale = 1.0f; token = StripTokenQuotes(ReadToken()); - if(!ReadSignedFloat(token, ref scale)) { + if(!ReadSignedFloat(token, ref scale)) + { // Not numeric! General.ErrorLogger.Add(ErrorType.Error, "Error in " + sourcefilename + " at line " + GetCurrentLineNumber() + ": expected Scale value, but got '" + token + "'"); } @@ -122,7 +150,9 @@ namespace CodeImp.DoomBuilder.ZDoom prevToken = token.ToUpperInvariant(); } } - } else { + } + else + { prevToken = token.ToUpperInvariant(); } } diff --git a/Source/Core/ZDoom/ZDTextParser.cs b/Source/Core/ZDoom/ZDTextParser.cs index 4a8a1adb..5a5252c0 100644 --- a/Source/Core/ZDoom/ZDTextParser.cs +++ b/Source/Core/ZDoom/ZDTextParser.cs @@ -277,7 +277,8 @@ namespace CodeImp.DoomBuilder.ZDoom // This reads a token (all sequential non-whitespace characters or a single character) using custom set of special tokens // Returns null when the end of the stream has been reached (mxd) - protected internal string ReadToken(string specialTokens) { + protected internal string ReadToken(string specialTokens) + { // Return null when the end of the stream has been reached if(datastream.Position == datastream.Length) return null; @@ -286,11 +287,14 @@ namespace CodeImp.DoomBuilder.ZDoom // Start reading char c = (char)datareader.ReadByte(); - while(!IsWhitespace(c) || quotedstring || specialTokens.IndexOf(c) != -1) { + while(!IsWhitespace(c) || quotedstring || specialTokens.IndexOf(c) != -1) + { // Special token? - if(!quotedstring && specialTokens.IndexOf(c) != -1) { + if(!quotedstring && specialTokens.IndexOf(c) != -1) + { // Not reading a token yet? - if(token.Length == 0) { + if(token.Length == 0) + { // This is our whole token token += c; break; @@ -300,9 +304,12 @@ namespace CodeImp.DoomBuilder.ZDoom // Go one character back so we can read this token again datastream.Seek(-1, SeekOrigin.Current); break; - } else { + } + else + { // Quote? - if(c == '"') { + if(c == '"') + { // Quote to end the string? if(quotedstring) quotedstring = false; @@ -311,23 +318,29 @@ namespace CodeImp.DoomBuilder.ZDoom token += c; } - // Potential comment? - else if((c == '/') && !quotedstring) { + // Potential comment? + else if((c == '/') && !quotedstring) + { // Check the next byte if(datastream.Position == datastream.Length) return token; char c2 = (char)datareader.ReadByte(); - if((c2 == '/') || (c2 == '*')) { + if((c2 == '/') || (c2 == '*')) + { // This is a comment start, so the token ends here // Go two characters back so we can read this comment again datastream.Seek(-2, SeekOrigin.Current); break; - } else { + } + else + { // Not a comment // Go one character back so we can read this char again datastream.Seek(-1, SeekOrigin.Current); token += c; } - } else { + } + else + { token += c; } } @@ -368,9 +381,11 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd - protected internal bool ReadSignedFloat(string token, ref float value) { + protected internal bool ReadSignedFloat(string token, ref float value) + { int sign = 1; - if (token == "-") { + if (token == "-") + { sign = -1; token = StripTokenQuotes(ReadToken()); } @@ -382,9 +397,11 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd - protected internal bool ReadSignedInt(string token, ref int value) { + protected bool ReadSignedInt(string token, ref int value) + { int sign = 1; - if (token == "-") { + if (token == "-") + { sign = -1; token = StripTokenQuotes(ReadToken()); } @@ -405,7 +422,8 @@ namespace CodeImp.DoomBuilder.ZDoom } //mxd - protected internal int GetCurrentLineNumber() { + protected internal int GetCurrentLineNumber() + { long position = datastream.Position; long readpos = 0; int linenumber = 1; @@ -413,7 +431,8 @@ namespace CodeImp.DoomBuilder.ZDoom // Find the line on which we found this error datastream.Seek(0, SeekOrigin.Begin); StreamReader textreader = new StreamReader(datastream, Encoding.ASCII); - while (readpos < position) { + while (readpos < position) + { string line = textreader.ReadLine(); if (line == null) break; readpos += line.Length + 2; diff --git a/Source/Plugins/BuilderEffects/BuilderPlug.cs b/Source/Plugins/BuilderEffects/BuilderPlug.cs index c400d18c..7fc0aba8 100644 --- a/Source/Plugins/BuilderEffects/BuilderPlug.cs +++ b/Source/Plugins/BuilderEffects/BuilderPlug.cs @@ -1,10 +1,14 @@ -using System.Collections.Generic; +#region ================== Namespaces + +using System.Collections.Generic; +using System.Drawing; using System.Windows.Forms; -using CodeImp.DoomBuilder.Plugins; using CodeImp.DoomBuilder.Actions; +using CodeImp.DoomBuilder.Plugins; using CodeImp.DoomBuilder.VisualModes; using CodeImp.DoomBuilder.Windows; -using System.Drawing; + +#endregion namespace CodeImp.DoomBuilder.BuilderEffects { @@ -23,7 +27,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects public static BuilderPlug Me { get { return me; } } // When plugin is initialized - public override void OnInitialize() { + public override void OnInitialize() + { // Setup base.OnInitialize(); me = this; @@ -35,9 +40,11 @@ namespace CodeImp.DoomBuilder.BuilderEffects } // Disposer - public override void Dispose() { + public override void Dispose() + { // Not already disposed? - if(!IsDisposed) { + if(!IsDisposed) + { menusForm.Unregister(); menusForm.Dispose(); menusForm = null; @@ -48,94 +55,117 @@ namespace CodeImp.DoomBuilder.BuilderEffects } } - public override void OnMapNewEnd() { + public override void OnMapNewEnd() + { base.OnMapNewEnd(); menusForm.Register(); } - public override void OnMapOpenEnd() { + public override void OnMapOpenEnd() + { base.OnMapOpenEnd(); menusForm.Register(); } - public override void OnMapCloseEnd() { + public override void OnMapCloseEnd() + { base.OnMapCloseEnd(); menusForm.Unregister(); } - public override void OnReloadResources() { + public override void OnReloadResources() + { base.OnReloadResources(); menusForm.Register(); } //actions [BeginAction("applyjitter")] - private void applyJitterTransform() { - if(General.Editing.Mode == null) - return; - + private void ApplyJitterTransform() + { + if(General.Editing.Mode == null) return; string currentModeName = General.Editing.Mode.GetType().Name; //display one of colorPickers or tell the user why we can't do that - if(currentModeName == "ThingsMode") { - if(General.Map.Map.SelectedThingsCount == 0) { + if(currentModeName == "ThingsMode") + { + if(General.Map.Map.SelectedThingsCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Select some things first!"); return; } form = new JitterThingsForm(currentModeName); - - } else if(currentModeName == "SectorsMode") { - if(General.Map.Map.SelectedSectorsCount == 0) { + } + else if(currentModeName == "SectorsMode") + { + if(General.Map.Map.SelectedSectorsCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Select some sectors first!"); return; } form = new JitterSectorsForm(currentModeName); - - } else if(currentModeName == "LinedefsMode"){ - if(General.Map.Map.SelectedLinedefsCount == 0) { + } + else if(currentModeName == "LinedefsMode") + { + if(General.Map.Map.SelectedLinedefsCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Select some linedefs first!"); return; } form = new JitterVerticesForm(currentModeName); - - } else if(currentModeName == "VerticesMode"){ - if(General.Map.Map.SelectedVerticessCount == 0) { + } + else if(currentModeName == "VerticesMode") + { + if(General.Map.Map.SelectedVerticessCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Select some vertices first!"); return; } form = new JitterVerticesForm(currentModeName); - - } else if(currentModeName == "BaseVisualMode") { + } + else if(currentModeName == "BaseVisualMode") + { //no visual things selected in visual mode? - if(((VisualMode)General.Editing.Mode).GetSelectedVisualThings(true).Count == 0) { + if(((VisualMode)General.Editing.Mode).GetSelectedVisualThings(true).Count == 0) + { //check selected geometry List list = ((VisualMode)General.Editing.Mode).GetSelectedSurfaces(); - if(list.Count > 0) { - foreach(VisualGeometry vg in list) { - if(vg.GeometryType == VisualGeometryType.CEILING || vg.GeometryType == VisualGeometryType.FLOOR) { + if(list.Count > 0) + { + foreach(VisualGeometry vg in list) + { + if(vg.GeometryType == VisualGeometryType.CEILING + || vg.GeometryType == VisualGeometryType.FLOOR) + { form = new JitterSectorsForm(currentModeName); break; } } - if(form == null) - form = new JitterVerticesForm(currentModeName); - } else { + if(form == null) form = new JitterVerticesForm(currentModeName); + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Select some things, sectors or surfaces first!"); return; } - } else { + } + else + { form = new JitterThingsForm(currentModeName); } - } else { //wrong mode + } + else //wrong mode + { General.Interface.DisplayStatus(StatusType.Warning, "Switch to Sectors, Things, Vertices, Linedefs or Visual mode first!"); return; } //position and show form - if(formLocation.X == 0 && formLocation.Y == 0) { - Size displaySize = Plug.DisplaySize; - Point displayLocation = Plug.DisplayLocationAbs; + if(formLocation.X == 0 && formLocation.Y == 0) + { + Size displaySize = DisplaySize; + Point displayLocation = DisplayLocationAbs; formLocation = new Point(displayLocation.X + displaySize.Width - form.Width - 16, displayLocation.Y + 32); } @@ -145,7 +175,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects } //events - private void form_FormClosed(object sender, FormClosedEventArgs e) { + private void form_FormClosed(object sender, FormClosedEventArgs e) + { formLocation = form.Location; form.Dispose(); form = null; diff --git a/Source/Plugins/BuilderEffects/Controls/IntControl.cs b/Source/Plugins/BuilderEffects/Controls/IntControl.cs index 7f3081ed..7d2cba12 100644 --- a/Source/Plugins/BuilderEffects/Controls/IntControl.cs +++ b/Source/Plugins/BuilderEffects/Controls/IntControl.cs @@ -1,7 +1,11 @@ -using System; +#region ================== Namespaces + +using System; using System.ComponentModel; using System.Windows.Forms; +#endregion + namespace CodeImp.DoomBuilder.BuilderEffects { [DesignerCategory("code")] @@ -11,11 +15,11 @@ namespace CodeImp.DoomBuilder.BuilderEffects public event EventHandler OnValueChanged; private int previousValue; - public int Value { - get { - return (int)numericUpDown1.Value; - } - set { + public int Value + { + get { return (int)numericUpDown1.Value; } + set + { blockEvents = true; previousValue = General.Clamp(value, (int)numericUpDown1.Minimum, (int)numericUpDown1.Maximum); numericUpDown1.Value = previousValue; @@ -29,55 +33,61 @@ namespace CodeImp.DoomBuilder.BuilderEffects public string Label { get { return label1.Text; } set { label1.Text = value; } } - public bool ExtendedLimits { + public bool ExtendedLimits + { get { return extendedLimits; } set { extendedLimits = value; - updateLimits(); + UpdateLimits(); } } private bool extendedLimits; - public bool AllowNegative { + public bool AllowNegative + { get { return allowNegative; } set { allowNegative = value; - if(!allowNegative){ - if(minimum < 0 && maximum < 0) { + if(!allowNegative) + { + if(minimum < 0 && maximum < 0) + { int diff = Math.Abs(maximum - minimum); minimum = 0; maximum = diff; - } else { + } + else + { if(minimum < 0) minimum = 0; if(maximum < 0) maximum = 0; } } - updateLimits(); + UpdateLimits(); } } private bool allowNegative; - public int Minimum { - get { - return minimum; - } - set { + public int Minimum + { + get { return minimum; } + set + { minimum = value; - updateLimits(); + UpdateLimits(); } } private int minimum; - - public int Maximum { - get { - return maximum; - } - set { + + public int Maximum + { + get { return maximum; } + set + { maximum = value; - updateLimits(); + UpdateLimits(); } } private int maximum; @@ -85,12 +95,14 @@ namespace CodeImp.DoomBuilder.BuilderEffects private bool blockEvents; private bool valueChanged; - internal IntControl() { + internal IntControl() + { InitializeComponent(); numericUpDown1.MouseLeave += numericUpDown1_MouseLeave; } - private void updateLimits() { + private void UpdateLimits() + { blockEvents = true; trackBar1.Value = General.Clamp(trackBar1.Value, minimum, maximum); @@ -100,10 +112,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects numericUpDown1.Value = General.Clamp((int)numericUpDown1.Value, minimum, maximum); - if (extendedLimits) { + if (extendedLimits) + { numericUpDown1.Minimum = minimum * 32; numericUpDown1.Maximum = maximum * 32; - } else { + } + else + { numericUpDown1.Minimum = minimum; numericUpDown1.Maximum = maximum; } @@ -112,11 +127,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects } //events - private void trackBar1_ValueChanged(object sender, EventArgs e) { + private void trackBar1_ValueChanged(object sender, EventArgs e) + { if (!blockEvents) numericUpDown1.Value = ((TrackBar)sender).Value; } - private void numericUpDown1_ValueChanged(object sender, EventArgs e) { + private void numericUpDown1_ValueChanged(object sender, EventArgs e) + { int value = (int)((NumericUpDown)sender).Value; if (value == previousValue) return; @@ -132,15 +149,19 @@ namespace CodeImp.DoomBuilder.BuilderEffects blockEvents = false; } - private void trackBar1_MouseLeave(object sender, EventArgs e) { - if (valueChanged && OnValueChanged != null) { + private void trackBar1_MouseLeave(object sender, EventArgs e) + { + if (valueChanged && OnValueChanged != null) + { OnValueChanged(this, EventArgs.Empty); valueChanged = false; } } - private void numericUpDown1_MouseLeave(object sender, EventArgs e) { - if (valueChanged && OnValueChanged != null) { + private void numericUpDown1_MouseLeave(object sender, EventArgs e) + { + if (valueChanged && OnValueChanged != null) + { OnValueChanged(this, EventArgs.Empty); valueChanged = false; } diff --git a/Source/Plugins/BuilderEffects/Controls/IntControl.designer.cs b/Source/Plugins/BuilderEffects/Controls/IntControl.designer.cs index c3f44b5c..398bd200 100644 --- a/Source/Plugins/BuilderEffects/Controls/IntControl.designer.cs +++ b/Source/Plugins/BuilderEffects/Controls/IntControl.designer.cs @@ -10,8 +10,10 @@ /// Освободить все используемые ресурсы. /// /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) { - if (disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -23,7 +25,8 @@ /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.trackBar1 = new Dotnetrix.Controls.TrackBar(); this.label1 = new System.Windows.Forms.Label(); this.numericUpDown1 = new CodeImp.DoomBuilder.BuilderEffects.NumericUpDownEx(); diff --git a/Source/Plugins/BuilderEffects/Controls/NumericUpDownEx.cs b/Source/Plugins/BuilderEffects/Controls/NumericUpDownEx.cs index 83226739..75e64ca2 100644 --- a/Source/Plugins/BuilderEffects/Controls/NumericUpDownEx.cs +++ b/Source/Plugins/BuilderEffects/Controls/NumericUpDownEx.cs @@ -308,28 +308,36 @@ namespace CodeImp.DoomBuilder.BuilderEffects public override void DownButton() { CancelEventArgs e = new CancelEventArgs(); - if (BeforeValueDecrement != null) { + if (BeforeValueDecrement != null) + { BeforeValueDecrement(this, e); } if (e.Cancel) return; - if (_wrapValue && Value - Increment < Minimum) { + if (_wrapValue && Value - Increment < Minimum) + { Value = Maximum; - } else { + } + else + { base.DownButton(); } } public override void UpButton() { CancelEventArgs e = new CancelEventArgs(); - if (BeforeValueIncrement != null) { + if (BeforeValueIncrement != null) + { BeforeValueIncrement(this, e); } if (e.Cancel) return; - if (_wrapValue && Value + Increment > Maximum) { + if (_wrapValue && Value + Increment > Maximum) + { Value = Minimum; - } else { + } + else + { base.UpButton(); } } diff --git a/Source/Plugins/BuilderEffects/Interface/JitterSectorsForm.cs b/Source/Plugins/BuilderEffects/Interface/JitterSectorsForm.cs index af7fdb31..af80214f 100644 --- a/Source/Plugins/BuilderEffects/Interface/JitterSectorsForm.cs +++ b/Source/Plugins/BuilderEffects/Interface/JitterSectorsForm.cs @@ -1,4 +1,6 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; using System.Windows.Forms; using CodeImp.DoomBuilder.Geometry; @@ -6,10 +8,14 @@ using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.VisualModes; using CodeImp.DoomBuilder.Windows; +#endregion + namespace CodeImp.DoomBuilder.BuilderEffects { public partial class JitterSectorsForm : DelayedForm { + #region ================== Variables + private readonly string editingModeName; private readonly List visualSectors; private readonly List visualVerts; @@ -26,6 +32,10 @@ namespace CodeImp.DoomBuilder.BuilderEffects private static int storedceiloffsetmode; private static int storedflooroffsetmode; + #endregion + + #region ================== Structs + private struct TranslationOffsetVertexData { public Vertex Vertex; @@ -68,8 +78,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects public bool PegBottom; public bool UpdateTextureOnOtherSide; } - - public JitterSectorsForm(string editingModeName) { + + #endregion + + #region ================== Constructor / Setup + + public JitterSectorsForm(string editingModeName) + { this.editingModeName = editingModeName; InitializeComponent(); @@ -78,18 +93,22 @@ namespace CodeImp.DoomBuilder.BuilderEffects List verts = new List(); List sectors = new List(); - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { VisualMode vm = (VisualMode)General.Editing.Mode; List visualGeometry = vm.GetSelectedSurfaces(); visualSectors = new List(); //get selected visual and regular sectors - foreach(VisualGeometry vg in visualGeometry) { + foreach(VisualGeometry vg in visualGeometry) + { if(vg.GeometryType != VisualGeometryType.CEILING && vg.GeometryType != VisualGeometryType.FLOOR) continue; - if(vg.Sector != null && vg.Sector.Sector != null) { - foreach(Sidedef sd in vg.Sector.Sector.Sidedefs) { + if(vg.Sector != null && vg.Sector.Sector != null) + { + foreach(Sidedef sd in vg.Sector.Sector.Sidedefs) + { if(!verts.Contains(sd.Line.Start)) verts.Add(sd.Line.Start); if(!verts.Contains(sd.Line.End)) @@ -104,8 +123,10 @@ namespace CodeImp.DoomBuilder.BuilderEffects //also get visual sectors around selected ones (because they also may be affected) List affectedVerts = new List(); - foreach(Sector s in sectors) { - foreach(Sidedef sd in s.Sidedefs) { + foreach(Sector s in sectors) + { + foreach(Sidedef sd in s.Sidedefs) + { if(!affectedVerts.Contains(sd.Line.Start)) affectedVerts.Add(sd.Line.Start); if(!affectedVerts.Contains(sd.Line.End)) @@ -114,13 +135,21 @@ namespace CodeImp.DoomBuilder.BuilderEffects } List affectedSectors = new List(); - foreach(Vertex v in affectedVerts) { - foreach(Linedef l in v.Linedefs) { - if(l.Front != null && !sectors.Contains(l.Front.Sector) && !affectedSectors.Contains(l.Front.Sector) && vm.VisualSectorExists(l.Front.Sector)) { + foreach(Vertex v in affectedVerts) + { + foreach(Linedef l in v.Linedefs) + { + if(l.Front != null && !sectors.Contains(l.Front.Sector) + && !affectedSectors.Contains(l.Front.Sector) + && vm.VisualSectorExists(l.Front.Sector)) + { visualSectors.Add(vm.GetVisualSector(l.Front.Sector)); affectedSectors.Add(l.Front.Sector); } - if(l.Back != null && !sectors.Contains(l.Back.Sector) && !affectedSectors.Contains(l.Back.Sector) && vm.VisualSectorExists(l.Back.Sector)) { + if(l.Back != null && !sectors.Contains(l.Back.Sector) + && !affectedSectors.Contains(l.Back.Sector) + && vm.VisualSectorExists(l.Back.Sector)) + { visualSectors.Add(vm.GetVisualSector(l.Back.Sector)); affectedSectors.Add(l.Back.Sector); } @@ -132,12 +161,15 @@ namespace CodeImp.DoomBuilder.BuilderEffects { if(vm.VisualVertices.ContainsKey(vert)) visualVerts.Add(vm.VisualVertices[vert]); } - - } else if(editingModeName == "SectorsMode") { + } + else if(editingModeName == "SectorsMode") + { ICollection list = General.Map.Map.GetSelectedSectors(true); - foreach(Sector s in list) { - foreach(Sidedef sd in s.Sidedefs) { + foreach(Sector s in list) + { + foreach(Sidedef sd in s.Sidedefs) + { if(!verts.Contains(sd.Line.Start)) verts.Add(sd.Line.Start); if(!verts.Contains(sd.Line.End)) @@ -145,10 +177,10 @@ namespace CodeImp.DoomBuilder.BuilderEffects } sectors.Add(s); } - } - if(verts.Count == 0 || sectors.Count == 0) { + if(verts.Count == 0 || sectors.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to get sectors from selection!"); return; } @@ -164,14 +196,16 @@ namespace CodeImp.DoomBuilder.BuilderEffects //process verts... Dictionary data = new Dictionary(); - foreach(Vertex v in verts) { + foreach(Vertex v in verts) + { TranslationOffsetVertexData vd = new TranslationOffsetVertexData(); vd.Vertex = v; vd.InitialPosition = v.Position; data.Add(v, vd); } - foreach(Vertex v in verts) { + foreach(Vertex v in verts) + { if(v.Linedefs == null) continue; //get nearest linedef @@ -179,12 +213,14 @@ namespace CodeImp.DoomBuilder.BuilderEffects float distance = float.MaxValue; // Go for all linedefs in selection - foreach(Linedef l in General.Map.Map.Linedefs) { + foreach(Linedef l in General.Map.Map.Linedefs) + { if(v.Linedefs.Contains(l)) continue; // Calculate distance and check if closer than previous find float d = l.SafeDistanceToSq(v.Position, true); - if(d < distance) { + if(d < distance) + { // This one is closer closestLine = l; distance = d; @@ -196,12 +232,16 @@ namespace CodeImp.DoomBuilder.BuilderEffects float closestLineDistance = Vector2D.Distance(v.Position, closestLine.NearestOnLine(v.Position)); //check SafeDistance of closest line - if(data.ContainsKey(closestLine.Start) && data[closestLine.Start].SafeDistance > closestLineDistance) { + if(data.ContainsKey(closestLine.Start) + && data[closestLine.Start].SafeDistance > closestLineDistance) + { TranslationOffsetVertexData vd = data[closestLine.Start]; vd.SafeDistance = (int)Math.Floor(closestLineDistance); data[closestLine.Start] = vd; } - if(data.ContainsKey(closestLine.End) && data[closestLine.End].SafeDistance > closestLineDistance) { + if(data.ContainsKey(closestLine.End) + && data[closestLine.End].SafeDistance > closestLineDistance) + { TranslationOffsetVertexData vd = data[closestLine.End]; vd.SafeDistance = (int)Math.Floor(closestLineDistance); data[closestLine.End] = vd; @@ -209,7 +249,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects //save SafeDistance int dist = (int)Math.Floor(closestLineDistance); - if(data[v].SafeDistance == 0 || data[v].SafeDistance > dist) { + if(data[v].SafeDistance == 0 || data[v].SafeDistance > dist) + { TranslationOffsetVertexData vd = data[v]; vd.SafeDistance = dist; data[v] = vd; @@ -220,7 +261,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects vertexData = new TranslationOffsetVertexData[data.Values.Count]; data.Values.CopyTo(vertexData, 0); - for(int i = 0; i < data.Count; i++) { + for(int i = 0; i < data.Count; i++) + { if(vertexData[i].SafeDistance > 0) vertexData[i].SafeDistance /= 2; if(MaxSafeDistance < vertexData[i].SafeDistance) @@ -231,7 +273,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects sectorData = new List(); sidedefData = new List(); - foreach(Sector s in sectors){ + foreach(Sector s in sectors) + { SectorData sd = new SectorData(); sd.Sector = s; @@ -258,7 +301,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects if(sd.SafeDistance > MaxSafeHeightDistance) MaxSafeHeightDistance = sd.SafeDistance; sectorData.Add(sd); - foreach(Sidedef side in s.Sidedefs) { + foreach(Sidedef side in s.Sidedefs) + { //store initial sidedef properties SidedefData sdd = new SidedefData(); @@ -268,7 +312,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects sdd.PegBottom = side.Line.IsFlagSet(General.Map.Config.LowerUnpeggedFlag); sdd.PegTop = side.Line.IsFlagSet(General.Map.Config.UpperUnpeggedFlag); - if(side.Other != null && !sectors.Contains(side.Other.Sector)) { + if(side.Other != null && !sectors.Contains(side.Other.Sector)) + { sdd.UpdateTextureOnOtherSide = true; sdd.OtherHighTexture = side.Other.HighTexture; sdd.OtherLowTexture = side.Other.LowTexture; @@ -288,10 +333,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects flooroffsetmode.SelectedIndex = storedflooroffsetmode; //vertex heights can not be set in non-UDMF maps - if (General.Map.UDMF) { + if (General.Map.UDMF) + { cbUseFloorVertexHeights.Checked = useFloorVertexHeights; cbUseCeilingVertexHeights.Checked = useCeilingVertexHeights; - } else { + } + else + { useFloorVertexHeights = false; cbUseFloorVertexHeights.Checked = false; cbUseFloorVertexHeights.Enabled = false; @@ -321,21 +369,27 @@ namespace CodeImp.DoomBuilder.BuilderEffects cbUpperTexStyle.SelectedIndex = 0; cbLowerTexStyle.SelectedIndex = 0; - updateTextureSelectors(); //update interface + UpdateTextureSelectors(); //update interface //create random values - updateAngles(); - updateFloorHeights(); - updateCeilingHeights(); + UpdateAngles(); + UpdateFloorHeights(); + UpdateCeilingHeights(); } - private float GetLowestCeiling(Vertex v) { + #endregion + + #region ================== Methods + + private static float GetLowestCeiling(Vertex v) + { if (v.Linedefs.Count == 0) return float.NaN; List sectors = GetSectors(v); if (sectors.Count == 0) return float.NaN; float target = sectors[0].CeilHeight; - for(int i = 1; i < sectors.Count; i++) { + for(int i = 1; i < sectors.Count; i++) + { if(target > sectors[i].CeilHeight && sectors[i].Sidedefs.Count == 3) target = sectors[i].CeilHeight; } @@ -343,13 +397,15 @@ namespace CodeImp.DoomBuilder.BuilderEffects return target; } - private float GetHighestFloor(Vertex v) { + private static float GetHighestFloor(Vertex v) + { if(v.Linedefs.Count == 0) return float.NaN; List sectors = GetSectors(v); if(sectors.Count == 0) return float.NaN; float target = sectors[0].FloorHeight; - for(int i = 1; i < sectors.Count; i++) { + for(int i = 1; i < sectors.Count; i++) + { if(target < sectors[i].FloorHeight && sectors[i].Sidedefs.Count == 3) target = sectors[i].FloorHeight; } @@ -357,9 +413,11 @@ namespace CodeImp.DoomBuilder.BuilderEffects return target; } - private List GetSectors(Vertex v) { + private static List GetSectors(Vertex v) + { List result = new List(); - foreach (Linedef l in v.Linedefs) { + foreach (Linedef l in v.Linedefs) + { if(l.Front != null && l.Front.Sector != null && !result.Contains(l.Front.Sector)) result.Add(l.Front.Sector); if(l.Back != null && l.Back.Sector != null && !result.Contains(l.Back.Sector)) @@ -368,9 +426,11 @@ namespace CodeImp.DoomBuilder.BuilderEffects return result; } - private Vertex[] GetSectorVerts(Sector s) { + private static Vertex[] GetSectorVerts(Sector s) + { List result = new List(); - foreach (Sidedef side in s.Sidedefs) { + foreach (Sidedef side in s.Sidedefs) + { if(side.Line == null) continue; if(!result.Contains(side.Line.Start)) result.Add(side.Line.Start); if(!result.Contains(side.Line.End)) result.Add(side.Line.End); @@ -379,80 +439,102 @@ namespace CodeImp.DoomBuilder.BuilderEffects return result.ToArray(); } -//utility - private void applyTranslationJitter(int ammount) { + #endregion + + #region ================== Utility + + private void ApplyTranslationJitter(int ammount) + { int curAmmount; - for(int i = 0; i < vertexData.Length; i++) { + for(int i = 0; i < vertexData.Length; i++) + { curAmmount = ammount > vertexData[i].SafeDistance ? vertexData[i].SafeDistance : ammount; vertexData[i].Vertex.Move(new Vector2D(vertexData[i].InitialPosition.x + (int)(Math.Sin(vertexData[i].JitterAngle) * curAmmount), vertexData[i].InitialPosition.y + (int)(Math.Cos(vertexData[i].JitterAngle) * curAmmount))); } //update view - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { General.Map.Map.Update(); General.Map.IsChanged = true; - updateVisualGeometry(); - } else { + UpdateVisualGeometry(); + } + else + { General.Interface.RedrawDisplay(); } } - private void applyCeilingHeightJitter(int ammount) { + private void ApplyCeilingHeightJitter(int ammount) + { int curAmmount; - for(int i = 0; i < sectorData.Count; i++) { + for(int i = 0; i < sectorData.Count; i++) + { curAmmount = ammount > sectorData[i].SafeDistance ? sectorData[i].SafeDistance : ammount; - if (sectorData[i].Triangular && cbUseCeilingVertexHeights.Checked) { - foreach(HeightOffsetVertexData vd in sectorData[i].Verts) { + if (sectorData[i].Triangular && cbUseCeilingVertexHeights.Checked) + { + foreach(HeightOffsetVertexData vd in sectorData[i].Verts) + { vd.Vertex.ZCeiling = vd.InitialCeilingHeight - (float)Math.Floor(curAmmount * ModifyByOffsetMode(vd.JitterCeilingHeight, ceiloffsetmode.SelectedIndex)); } - } else { + } + else + { sectorData[i].Sector.CeilHeight = sectorData[i].InitialCeilingHeight - (int)Math.Floor(curAmmount * ModifyByOffsetMode(sectorData[i].JitterCeilingHeight, ceiloffsetmode.SelectedIndex)); } } //update view - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { General.Map.Map.Update(); General.Map.IsChanged = true; - updateVisualGeometry(); + UpdateVisualGeometry(); } - updateUpperTextures(cbUpperTexStyle.SelectedIndex, false); + UpdateUpperTextures(cbUpperTexStyle.SelectedIndex, false); } - private void applyFloorHeightJitter(int ammount) { + private void ApplyFloorHeightJitter(int ammount) + { int curAmmount; - for(int i = 0; i < sectorData.Count; i++) { + for(int i = 0; i < sectorData.Count; i++) + { curAmmount = ammount > sectorData[i].SafeDistance ? sectorData[i].SafeDistance : ammount; - if (sectorData[i].Triangular && cbUseFloorVertexHeights.Checked) { - foreach(HeightOffsetVertexData vd in sectorData[i].Verts) { + if (sectorData[i].Triangular && cbUseFloorVertexHeights.Checked) + { + foreach(HeightOffsetVertexData vd in sectorData[i].Verts) + { vd.Vertex.ZFloor = vd.InitialFloorHeight + (float)Math.Floor(curAmmount * ModifyByOffsetMode(vd.JitterFloorHeight, flooroffsetmode.SelectedIndex)); } - } else { + } + else + { sectorData[i].Sector.FloorHeight = sectorData[i].InitialFloorHeight + (int)Math.Floor(curAmmount * ModifyByOffsetMode(sectorData[i].JitterFloorHeight, flooroffsetmode.SelectedIndex)); } } //update view - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { General.Map.Map.Update(); General.Map.IsChanged = true; - updateVisualGeometry(); + UpdateVisualGeometry(); } - updateLowerTextures(cbLowerTexStyle.SelectedIndex, false); + UpdateLowerTextures(cbLowerTexStyle.SelectedIndex, false); } - private float ModifyByOffsetMode(float value, int mode) + private static float ModifyByOffsetMode(float value, int mode) { switch (mode) { @@ -470,7 +552,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects } } - private void updateVisualGeometry() { + private void UpdateVisualGeometry() + { foreach(VisualSector vs in visualSectors) vs.UpdateSectorGeometry(true); foreach(VisualSector vs in visualSectors) vs.UpdateSectorData(); foreach(VisualSector vs in visualSectors) vs.UpdateSectorData(); @@ -481,7 +564,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects } } - private void updateTextureSelectors() { + private void UpdateTextureSelectors() + { cbLowerTexStyle.Enabled = floorHeightAmmount.Value > 0; cbUpperTexStyle.Enabled = ceilingHeightAmmount.Value > 0; gbLowerTexture.Enabled = floorHeightAmmount.Value > 0 && cbLowerTexStyle.SelectedIndex > 0; @@ -490,14 +574,14 @@ namespace CodeImp.DoomBuilder.BuilderEffects textureUpper.Enabled = ceilingHeightAmmount.Value > 0 && cbUpperTexStyle.SelectedIndex == 2; } - private void updateUpperTextures(int index, bool updateGeometry) + private void UpdateUpperTextures(int index, bool updateGeometry) { if(index == -1) return; - if(index == 0) - { //revert + if(index == 0) //revert + { foreach(SidedefData sd in sidedefData) - setUpperTexture(sd, sd.HighTexture); + SetUpperTexture(sd, sd.HighTexture); } else if(index == 1) //use ceiling or default texture { @@ -508,34 +592,34 @@ namespace CodeImp.DoomBuilder.BuilderEffects { if(sd.Side.Sector != null) { - if (sd.UpdateTextureOnOtherSide && sd.Side.Other.Sector != null) setUpperTexture(sd, sd.Side.Sector.CeilTexture, sd.Side.Other.Sector.CeilTexture); - else setUpperTexture(sd, sd.Side.Sector.CeilTexture); + if (sd.UpdateTextureOnOtherSide && sd.Side.Other.Sector != null) SetUpperTexture(sd, sd.Side.Sector.CeilTexture, sd.Side.Other.Sector.CeilTexture); + else SetUpperTexture(sd, sd.Side.Sector.CeilTexture); } } } else { - foreach(SidedefData sd in sidedefData) setUpperTexture(sd, General.Settings.DefaultTexture); + foreach(SidedefData sd in sidedefData) SetUpperTexture(sd, General.Settings.DefaultTexture); } } else if(index == 2) //use given texture { foreach(SidedefData sd in sidedefData) - setUpperTexture(sd, textureUpper.TextureName); + SetUpperTexture(sd, textureUpper.TextureName); } General.Map.Data.UpdateUsedTextures(); - if(updateGeometry && editingModeName == "BaseVisualMode") updateVisualGeometry(); + if(updateGeometry && editingModeName == "BaseVisualMode") UpdateVisualGeometry(); } - private void updateLowerTextures(int index, bool updateGeometry) + private void UpdateLowerTextures(int index, bool updateGeometry) { if(index == -1) return; - if(index == 0) - { //revert + if(index == 0) //revert + { foreach(SidedefData sd in sidedefData) - setLowerTexture(sd, sd.LowTexture); + SetLowerTexture(sd, sd.LowTexture); } else if(index == 1) //use floor or default texture { @@ -545,32 +629,37 @@ namespace CodeImp.DoomBuilder.BuilderEffects { if(sd.Side.Sector != null) { - if (sd.UpdateTextureOnOtherSide && sd.Side.Other.Sector != null) setLowerTexture(sd, sd.Side.Sector.FloorTexture, sd.Side.Other.Sector.FloorTexture); - else setLowerTexture(sd, sd.Side.Sector.FloorTexture); + if (sd.UpdateTextureOnOtherSide && sd.Side.Other.Sector != null) SetLowerTexture(sd, sd.Side.Sector.FloorTexture, sd.Side.Other.Sector.FloorTexture); + else SetLowerTexture(sd, sd.Side.Sector.FloorTexture); } } } else { - foreach (SidedefData sd in sidedefData) setLowerTexture(sd, General.Settings.DefaultTexture); + foreach (SidedefData sd in sidedefData) SetLowerTexture(sd, General.Settings.DefaultTexture); } } else if(index == 2) //use given texture { foreach(SidedefData sd in sidedefData) - setLowerTexture(sd, textureLower.TextureName); + SetLowerTexture(sd, textureLower.TextureName); } General.Map.Data.UpdateUsedTextures(); - if(updateGeometry && editingModeName == "BaseVisualMode") updateVisualGeometry(); + if(updateGeometry && editingModeName == "BaseVisualMode") UpdateVisualGeometry(); } -//set textures - private void setUpperTexture(SidedefData sd, string textureName) { - setUpperTexture(sd, textureName, textureName); + #endregion + + #region ================== Set Textures + + private void SetUpperTexture(SidedefData sd, string textureName) + { + SetUpperTexture(sd, textureName, textureName); } - private void setUpperTexture(SidedefData sd, string textureName, string otherTextureName) { + private void SetUpperTexture(SidedefData sd, string textureName, string otherTextureName) + { if(!cbKeepExistingTextures.Checked || string.IsNullOrEmpty(sd.HighTexture) || sd.HighTexture == "-") sd.Side.SetTextureHigh(textureName); @@ -578,11 +667,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects sd.Side.Other.SetTextureHigh(otherTextureName); } - private void setLowerTexture(SidedefData sd, string textureName) { - setLowerTexture(sd, textureName, textureName); + private void SetLowerTexture(SidedefData sd, string textureName) + { + SetLowerTexture(sd, textureName, textureName); } - private void setLowerTexture(SidedefData sd, string textureName, string otherTextureName) { + private void SetLowerTexture(SidedefData sd, string textureName, string otherTextureName) + { if(!cbKeepExistingTextures.Checked || string.IsNullOrEmpty(sd.LowTexture) || sd.LowTexture == "-") sd.Side.SetTextureLow(textureName); @@ -590,21 +681,30 @@ namespace CodeImp.DoomBuilder.BuilderEffects sd.Side.Other.SetTextureLow(otherTextureName); } -//jitter generation - private void updateAngles() { - for(int i = 0; i < vertexData.Length; i++) { + #endregion + + #region ================== Jitter generation + + private void UpdateAngles() + { + for(int i = 0; i < vertexData.Length; i++) + { TranslationOffsetVertexData vd = vertexData[i]; vd.JitterAngle = (float)(General.Random(0, 359) * Math.PI / 180f); vertexData[i] = vd; } } - private void updateFloorHeights() { - for(int i = 0; i < sectorData.Count; i++) { + private void UpdateFloorHeights() + { + for(int i = 0; i < sectorData.Count; i++) + { SectorData sd = sectorData[i]; - if (sd.Triangular) { - for(int c = 0; c < 3; c++) { + if (sd.Triangular) + { + for(int c = 0; c < 3; c++) + { HeightOffsetVertexData vd = sd.Verts[c]; vd.JitterFloorHeight = General.Random(-100, 100) / 100f; sd.Verts[c] = vd; @@ -616,11 +716,14 @@ namespace CodeImp.DoomBuilder.BuilderEffects } } - private void updateCeilingHeights() { - for(int i = 0; i < sectorData.Count; i++) { + private void UpdateCeilingHeights() + { + for(int i = 0; i < sectorData.Count; i++) + { SectorData sd = sectorData[i]; - if(sd.Triangular) { + if(sd.Triangular) + { for(int c = 0; c < 3; c++) { HeightOffsetVertexData vd = sd.Verts[c]; @@ -634,8 +737,12 @@ namespace CodeImp.DoomBuilder.BuilderEffects } } -//EVENTS - private void bApply_Click(object sender, EventArgs e) { + #endregion + + #region ================== Events + + private void bApply_Click(object sender, EventArgs e) + { //store settings keepExistingSideTextures = cbKeepExistingTextures.Checked; useFloorVertexHeights = cbUseFloorVertexHeights.Checked; @@ -644,7 +751,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects storedflooroffsetmode = flooroffsetmode.SelectedIndex; // Clean unused sidedef textures - foreach(SidedefData sd in sidedefData) { + foreach(SidedefData sd in sidedefData) + { sd.Side.RemoveUnneededTextures(false); if(sd.UpdateTextureOnOtherSide) @@ -662,34 +770,42 @@ namespace CodeImp.DoomBuilder.BuilderEffects Close(); } - private void bCancel_Click(object sender, EventArgs e) { + private void bCancel_Click(object sender, EventArgs e) + { this.DialogResult = DialogResult.Cancel; Close(); } - private void JitterSectorsForm_FormClosing(object sender, FormClosingEventArgs e) { + private void JitterSectorsForm_FormClosing(object sender, FormClosingEventArgs e) + { if(this.DialogResult == DialogResult.Cancel) General.Map.UndoRedo.WithdrawUndo(); //undo changes } - private void positionJitterAmmount_OnValueChanging(object sender, EventArgs e) { - applyTranslationJitter(positionJitterAmmount.Value); + private void positionJitterAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyTranslationJitter(positionJitterAmmount.Value); } - private void ceilingHeightAmmount_OnValueChanging(object sender, EventArgs e) { - applyCeilingHeightJitter(ceilingHeightAmmount.Value); - updateTextureSelectors(); + private void ceilingHeightAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyCeilingHeightJitter(ceilingHeightAmmount.Value); + UpdateTextureSelectors(); } - private void floorHeightAmmount_OnValueChanging(object sender, EventArgs e) { - applyFloorHeightJitter(floorHeightAmmount.Value); - updateTextureSelectors(); + private void floorHeightAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyFloorHeightJitter(floorHeightAmmount.Value); + UpdateTextureSelectors(); } - private void cbKeepExistingTextures_CheckedChanged(object sender, EventArgs e) { + private void cbKeepExistingTextures_CheckedChanged(object sender, EventArgs e) + { //revert possible changes - if(cbKeepExistingTextures.Checked) { - foreach(SidedefData sd in sidedefData) { + if(cbKeepExistingTextures.Checked) + { + foreach(SidedefData sd in sidedefData) + { if(!string.IsNullOrEmpty(sd.HighTexture)) sd.Side.SetTextureHigh(sd.HighTexture); @@ -697,10 +813,12 @@ namespace CodeImp.DoomBuilder.BuilderEffects sd.Side.Other.SetTextureHigh(sd.OtherHighTexture); } - if(editingModeName == "BaseVisualMode") updateVisualGeometry(); - } else { - updateLowerTextures(cbLowerTexStyle.SelectedIndex, false); - updateUpperTextures(cbUpperTexStyle.SelectedIndex, true); + if(editingModeName == "BaseVisualMode") UpdateVisualGeometry(); + } + else + { + UpdateLowerTextures(cbLowerTexStyle.SelectedIndex, false); + UpdateUpperTextures(cbUpperTexStyle.SelectedIndex, true); } } @@ -717,8 +835,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects } //update changes - applyFloorHeightJitter(floorHeightAmmount.Value); - updateTextureSelectors(); + ApplyFloorHeightJitter(floorHeightAmmount.Value); + UpdateTextureSelectors(); } private void cbUseCeilingVertexHeights_CheckedChanged(object sender, EventArgs e) @@ -734,92 +852,129 @@ namespace CodeImp.DoomBuilder.BuilderEffects } //update changes - applyCeilingHeightJitter(ceilingHeightAmmount.Value); - updateTextureSelectors(); + ApplyCeilingHeightJitter(ceilingHeightAmmount.Value); + UpdateTextureSelectors(); } -//update buttons - private void bUpdateTranslation_Click(object sender, EventArgs e) { - updateAngles(); - applyTranslationJitter(positionJitterAmmount.Value); + #region ================== Update Events + + private void bUpdateTranslation_Click(object sender, EventArgs e) + { + UpdateAngles(); + ApplyTranslationJitter(positionJitterAmmount.Value); } - private void bUpdateCeilingHeight_Click(object sender, EventArgs e) { - updateCeilingHeights(); - applyCeilingHeightJitter(ceilingHeightAmmount.Value); + private void bUpdateCeilingHeight_Click(object sender, EventArgs e) + { + UpdateCeilingHeights(); + ApplyCeilingHeightJitter(ceilingHeightAmmount.Value); } - private void bUpdateFloorHeight_Click(object sender, EventArgs e) { - updateFloorHeights(); - applyFloorHeightJitter(floorHeightAmmount.Value); + private void bUpdateFloorHeight_Click(object sender, EventArgs e) + { + UpdateFloorHeights(); + ApplyFloorHeightJitter(floorHeightAmmount.Value); } -//height offset modes + #endregion + + #region ================== Height Offset Mode Events + private void ceiloffsetmode_SelectedIndexChanged(object sender, EventArgs e) { - applyCeilingHeightJitter(ceilingHeightAmmount.Value); + ApplyCeilingHeightJitter(ceilingHeightAmmount.Value); } private void flooroffsetmode_SelectedIndexChanged(object sender, EventArgs e) { - applyFloorHeightJitter(floorHeightAmmount.Value); + ApplyFloorHeightJitter(floorHeightAmmount.Value); } -//texture pegging - private void cbPegTop_CheckedChanged(object sender, EventArgs e) { - if(cbPegTop.Checked) { //apply flag + #endregion + + #region ================== Texture Pegging Events + + private void cbPegTop_CheckedChanged(object sender, EventArgs e) + { + if(cbPegTop.Checked) //apply flag + { foreach(SidedefData sd in sidedefData) sd.Side.Line.SetFlag(General.Map.Config.UpperUnpeggedFlag, true); - } else { //revert to initial setting + } + else //revert to initial setting + { foreach(SidedefData sd in sidedefData) sd.Side.Line.SetFlag(General.Map.Config.UpperUnpeggedFlag, sd.PegTop); } - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { General.Map.Data.UpdateUsedTextures(); - updateVisualGeometry(); + UpdateVisualGeometry(); } } - private void cbPegBottom_CheckedChanged(object sender, EventArgs e) { - if(cbPegBottom.Checked) { //apply flag + private void cbPegBottom_CheckedChanged(object sender, EventArgs e) + { + if(cbPegBottom.Checked) //apply flag + { foreach(SidedefData sd in sidedefData) sd.Side.Line.SetFlag(General.Map.Config.LowerUnpeggedFlag, true); - } else { //revert to initial setting + } + else //revert to initial setting + { foreach(SidedefData sd in sidedefData) sd.Side.Line.SetFlag(General.Map.Config.LowerUnpeggedFlag, sd.PegBottom); } - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { General.Map.Data.UpdateUsedTextures(); - updateVisualGeometry(); + UpdateVisualGeometry(); } } -//texture pickers - private void textureLower_OnValueChanged(object sender, EventArgs e) { - updateLowerTextures(cbLowerTexStyle.SelectedIndex, true); + #endregion + + #region ================== Texture Picker Events + + //texture pickers + private void textureLower_OnValueChanged(object sender, EventArgs e) + { + UpdateLowerTextures(cbLowerTexStyle.SelectedIndex, true); } - private void textureUpper_OnValueChanged(object sender, EventArgs e) { - updateUpperTextures(cbUpperTexStyle.SelectedIndex, true); + private void textureUpper_OnValueChanged(object sender, EventArgs e) + { + UpdateUpperTextures(cbUpperTexStyle.SelectedIndex, true); } -//texture style selectors - private void cbUpperTexStyle_SelectedIndexChanged(object sender, EventArgs e) { - updateUpperTextures(cbUpperTexStyle.SelectedIndex, true); - updateTextureSelectors(); + #endregion + + #region ================== Texture Style Selector Events + + //texture style selectors + private void cbUpperTexStyle_SelectedIndexChanged(object sender, EventArgs e) + { + UpdateUpperTextures(cbUpperTexStyle.SelectedIndex, true); + UpdateTextureSelectors(); } - private void cbLowerTexStyle_SelectedIndexChanged(object sender, EventArgs e) { - updateLowerTextures(cbLowerTexStyle.SelectedIndex, true); - updateTextureSelectors(); + private void cbLowerTexStyle_SelectedIndexChanged(object sender, EventArgs e) + { + UpdateLowerTextures(cbLowerTexStyle.SelectedIndex, true); + UpdateTextureSelectors(); } -//HALP! - private void JitterSectorsForm_HelpRequested(object sender, HelpEventArgs hlpevent) { + #endregion + + //HALP! + private void JitterSectorsForm_HelpRequested(object sender, HelpEventArgs hlpevent) + { General.ShowHelp("gzdb/features/all_modes/jitter.html"); hlpevent.Handled = true; } + + #endregion } } diff --git a/Source/Plugins/BuilderEffects/Interface/JitterThingsForm.cs b/Source/Plugins/BuilderEffects/Interface/JitterThingsForm.cs index 1a8a8255..7f9aeff5 100644 --- a/Source/Plugins/BuilderEffects/Interface/JitterThingsForm.cs +++ b/Source/Plugins/BuilderEffects/Interface/JitterThingsForm.cs @@ -32,7 +32,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects private static bool allowNegativeScaleY; private static bool uniformScale; - private struct ThingData { + private struct ThingData + { public Vector3D Position; public int Angle; public int Pitch; @@ -55,7 +56,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region Constructor - public JitterThingsForm(string editingModeName) { + public JitterThingsForm(string editingModeName) + { this.editingModeName = editingModeName; this.HelpRequested += JitterThingsForm_HelpRequested; @@ -66,7 +68,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects bUpdateHeight.Enabled = General.Map.FormatInterface.HasThingHeight; //disable pitch/roll/scale? - if (!General.Map.UDMF) { + if (!General.Map.UDMF) + { pitchAmmount.Enabled = false; rollAmmount.Enabled = false; bUpdatePitch.Enabled = false; @@ -81,10 +84,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects //get selection selection = new List(); - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { visualSelection = ((VisualMode)General.Editing.Mode).GetSelectedVisualThings(false); foreach(VisualThing t in visualSelection) selection.Add(t.Thing); - } else { + } + else + { ICollection list = General.Map.Map.GetSelectedThings(true); foreach(Thing t in list) selection.Add(t); } @@ -95,14 +101,18 @@ namespace CodeImp.DoomBuilder.BuilderEffects //store intial properties thingData = new List(); - foreach(Thing t in selection){ + foreach(Thing t in selection) + { ThingData d = new ThingData(); Thing closest = MapSet.NearestThing(General.Map.Map.Things, t); - if(closest != null){ + if(closest != null) + { d.SafeDistance = (int)Math.Round(Vector2D.Distance(t.Position, closest.Position)); - }else{ + } + else + { d.SafeDistance = 512; } @@ -115,7 +125,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects d.ScaleX = t.ScaleX; d.ScaleY = t.ScaleY; - if(General.Map.FormatInterface.HasThingHeight) { + if(General.Map.FormatInterface.HasThingHeight) + { if(t.Sector == null) t.DetermineSector(); if(t.Sector == null) continue; @@ -135,13 +146,13 @@ namespace CodeImp.DoomBuilder.BuilderEffects General.Map.UndoRedo.CreateUndo("Randomize " + selection.Count + (selection.Count > 1 ? " things" : " thing")); //update controls - updateOffsetAngles(); - updateHeights(); - updateRotationAngles(); - updatePitchAngles(); - updateRollAngles(); - updateScaleX(); - updateScaleY(); + UpdateOffsetAngles(); + UpdateHeights(); + UpdateRotationAngles(); + UpdatePitchAngles(); + UpdateRollAngles(); + UpdateScaleX(); + UpdateScaleY(); //apply settings cbRelativeScale.Checked = relativeScale; @@ -175,17 +186,20 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region Apply logic - private void applyTranslation(int ammount) { - for(int i = 0; i < selection.Count; i++) { + private void ApplyTranslation(int ammount) + { + for(int i = 0; i < selection.Count; i++) + { int curAmmount = ammount > thingData[i].SafeDistance ? thingData[i].SafeDistance : ammount; selection[i].Move(new Vector2D(thingData[i].Position.x + (int)(Math.Sin(thingData[i].OffsetAngle) * curAmmount), thingData[i].Position.y + (int)(Math.Cos(thingData[i].OffsetAngle) * curAmmount))); selection[i].DetermineSector(); } - updateGeometry(); + UpdateGeometry(); } - private void applyRotation(int ammount) { + private void ApplyRotation(int ammount) + { for(int i = 0; i < selection.Count; i++) selection[i].Rotate((int)((thingData[i].Angle + ammount * thingData[i].JitterRotation) % 360)); @@ -193,13 +207,18 @@ namespace CodeImp.DoomBuilder.BuilderEffects if(editingModeName == "ThingsMode") General.Interface.RedrawDisplay(); } - private void applyPitch(int ammount) { + private void ApplyPitch(int ammount) + { int p; - for(int i = 0; i < selection.Count; i++) { - if (cbRelativePitch.Checked) { + for(int i = 0; i < selection.Count; i++) + { + if (cbRelativePitch.Checked) + { p = (int)((thingData[i].Pitch + ammount * thingData[i].JitterPitch) % 360); - } else { + } + else + { p = (int)((ammount * thingData[i].JitterPitch) % 360); } @@ -210,13 +229,18 @@ namespace CodeImp.DoomBuilder.BuilderEffects if(editingModeName == "ThingsMode") General.Interface.RedrawDisplay(); } - private void applyRoll(int ammount) { + private void ApplyRoll(int ammount) + { int r; - for (int i = 0; i < selection.Count; i++) { - if (cbRelativeRoll.Checked) { + for (int i = 0; i < selection.Count; i++) + { + if (cbRelativeRoll.Checked) + { r = (int)((thingData[i].Roll + ammount * thingData[i].JitterRoll) % 360); - } else { + } + else + { r = (int)((ammount * thingData[i].JitterRoll) % 360); } @@ -227,27 +251,34 @@ namespace CodeImp.DoomBuilder.BuilderEffects if(editingModeName == "ThingsMode") General.Interface.RedrawDisplay(); } - private void applyHeight(int ammount) { - for(int i = 0; i < selection.Count; i++) { + private void ApplyHeight(int ammount) + { + for(int i = 0; i < selection.Count; i++) + { int curAmmount = Math.Min(thingData[i].SectorHeight, Math.Max(0, thingData[i].ZOffset + ammount)); selection[i].Move(selection[i].Position.x, selection[i].Position.y, curAmmount * thingData[i].JitterHeight); } - updateGeometry(); + UpdateGeometry(); } - private void applyScale() { - if(cbUniformScale.Checked) { - applyScale((float)minScaleX.Value, (float)maxScaleX.Value, (float)minScaleX.Value, (float)maxScaleX.Value); - } else { - applyScale((float)minScaleX.Value, (float)maxScaleX.Value, (float)minScaleY.Value, (float)maxScaleY.Value); + private void ApplyScale() + { + if(cbUniformScale.Checked) + { + ApplyScale((float)minScaleX.Value, (float)maxScaleX.Value, (float)minScaleX.Value, (float)maxScaleX.Value); + } + else + { + ApplyScale((float)minScaleX.Value, (float)maxScaleX.Value, (float)minScaleY.Value, (float)maxScaleY.Value); } //update view if(editingModeName == "ThingsMode") General.Interface.RedrawDisplay(); } - private void applyScale(float minX, float maxX, float minY, float maxY) { + private void ApplyScale(float minX, float maxX, float minY, float maxY) + { if(minX > maxX) General.Swap(ref minX, ref maxX); if(minY > maxY) General.Swap(ref minY, ref maxY); @@ -255,11 +286,15 @@ namespace CodeImp.DoomBuilder.BuilderEffects float diffX = maxX - minX; float diffY = maxY - minY; - for(int i = 0; i < selection.Count; i++) { - if (cbRelativeScale.Checked) { + for(int i = 0; i < selection.Count; i++) + { + if (cbRelativeScale.Checked) + { sx = thingData[i].ScaleX + minX + diffX * thingData[i].JitterScaleX; sy = thingData[i].ScaleY + minY + diffY * thingData[i].JitterScaleY; - } else { + } + else + { sx = minX + diffX * thingData[i].JitterScaleX; sy = minY + diffY * thingData[i].JitterScaleY; } @@ -272,77 +307,96 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region Update logic - private void updateGeometry() { + private void UpdateGeometry() + { // Update what must be updated - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { VisualMode vm = ((VisualMode)General.Editing.Mode); - for(int i = 0; i < selection.Count; i++) { + for(int i = 0; i < selection.Count; i++) + { visualSelection[i].SetPosition(new Vector3D(selection[i].Position.x, selection[i].Position.y, selection[i].Sector.FloorHeight + selection[i].Position.z)); if(vm.VisualSectorExists(visualSelection[i].Thing.Sector)) vm.GetVisualSector(visualSelection[i].Thing.Sector).UpdateSectorGeometry(true); } - } else { + } + else + { //update view General.Interface.RedrawDisplay(); } } - private void updateOffsetAngles() { - for(int i = 0; i < thingData.Count; i++) { + private void UpdateOffsetAngles() + { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.OffsetAngle = General.Random(0, 359); thingData[i] = td; } } - private void updateHeights() { - for(int i = 0; i < thingData.Count; i++) { + private void UpdateHeights() + { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.JitterHeight = (General.Random(0, 100) / 100f); thingData[i] = td; } } - private void updateRotationAngles() { - for(int i = 0; i < thingData.Count; i++) { + private void UpdateRotationAngles() + { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.JitterRotation = (General.Random(-100, 100) / 100f); thingData[i] = td; } } - private void updatePitchAngles() { + private void UpdatePitchAngles() + { int min = (cbNegativePitch.Checked ? -100 : 0); - for(int i = 0; i < thingData.Count; i++) { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.JitterPitch = (General.Random(min, 100) / 100f); thingData[i] = td; } } - private void updateRollAngles() { + private void UpdateRollAngles() + { int min = (cbNegativeRoll.Checked ? -100 : 0); - for(int i = 0; i < thingData.Count; i++) { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.JitterRoll = (General.Random(min, 100) / 100f); thingData[i] = td; } } - private void updateScaleX() { + private void UpdateScaleX() + { int min = (cbNegativeScaleX.Checked ? -100 : 0); - for(int i = 0; i < thingData.Count; i++) { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.JitterScaleX = (General.Random(min, 100) / 100f); thingData[i] = td; } } - private void updateScaleY() { + private void UpdateScaleY() + { int min = (cbNegativeScaleY.Checked ? -100 : 0); - for(int i = 0; i < thingData.Count; i++) { + for(int i = 0; i < thingData.Count; i++) + { ThingData td = thingData[i]; td.JitterScaleY = (General.Random(min, 100) / 100f); thingData[i] = td; @@ -353,7 +407,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region Events - private void bApply_Click(object sender, EventArgs e) { + private void bApply_Click(object sender, EventArgs e) + { // Store settings relativePitch = cbRelativePitch.Checked; relativeRoll = cbRelativeRoll.Checked; @@ -374,130 +429,155 @@ namespace CodeImp.DoomBuilder.BuilderEffects Close(); } - private void bCancel_Click(object sender, EventArgs e) { + private void bCancel_Click(object sender, EventArgs e) + { this.DialogResult = DialogResult.Cancel; Close(); } - private void JitterThingsForm_FormClosing(object sender, FormClosingEventArgs e) { + private void JitterThingsForm_FormClosing(object sender, FormClosingEventArgs e) + { if (this.DialogResult == DialogResult.Cancel) General.Map.UndoRedo.WithdrawUndo(); //undo changes } - private void positionJitterAmmount_OnValueChanged(object sender, EventArgs e) { - applyTranslation(positionJitterAmmount.Value); + private void positionJitterAmmount_OnValueChanged(object sender, EventArgs e) + { + ApplyTranslation(positionJitterAmmount.Value); } - private void rotationJitterAmmount_OnValueChanged(object sender, EventArgs e) { - applyRotation(rotationJitterAmmount.Value); + private void rotationJitterAmmount_OnValueChanged(object sender, EventArgs e) + { + ApplyRotation(rotationJitterAmmount.Value); } - private void heightJitterAmmount_OnValueChanging(object sender, EventArgs e) { - applyHeight(heightJitterAmmount.Value); + private void heightJitterAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyHeight(heightJitterAmmount.Value); } - private void pitchAmmount_OnValueChanging(object sender, EventArgs e) { - applyPitch(pitchAmmount.Value); + private void pitchAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyPitch(pitchAmmount.Value); } - private void rollAmmount_OnValueChanging(object sender, EventArgs e) { - applyRoll(rollAmmount.Value); + private void rollAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyRoll(rollAmmount.Value); } - private void minScaleX_ValueChanged(object sender, EventArgs e) { - applyScale(); + private void minScaleX_ValueChanged(object sender, EventArgs e) + { + ApplyScale(); } - private void minScaleY_ValueChanged(object sender, EventArgs e) { - applyScale(); + private void minScaleY_ValueChanged(object sender, EventArgs e) + { + ApplyScale(); } #endregion #region Buttons & checkboxes events - private void bUpdateTranslation_Click(object sender, EventArgs e) { - updateOffsetAngles(); - applyTranslation(positionJitterAmmount.Value); + private void bUpdateTranslation_Click(object sender, EventArgs e) + { + UpdateOffsetAngles(); + ApplyTranslation(positionJitterAmmount.Value); } - private void bUpdateHeight_Click(object sender, EventArgs e) { - updateHeights(); - applyHeight(heightJitterAmmount.Value); + private void bUpdateHeight_Click(object sender, EventArgs e) + { + UpdateHeights(); + ApplyHeight(heightJitterAmmount.Value); } - private void bUpdateAngle_Click(object sender, EventArgs e) { - updateRotationAngles(); - applyRotation(rotationJitterAmmount.Value); + private void bUpdateAngle_Click(object sender, EventArgs e) + { + UpdateRotationAngles(); + ApplyRotation(rotationJitterAmmount.Value); } - private void bUpdatePitch_Click(object sender, EventArgs e) { - updatePitchAngles(); - applyPitch(pitchAmmount.Value); + private void bUpdatePitch_Click(object sender, EventArgs e) + { + UpdatePitchAngles(); + ApplyPitch(pitchAmmount.Value); } - private void bUpdateRoll_Click(object sender, EventArgs e) { - updateRollAngles(); - applyRoll(rollAmmount.Value); + private void bUpdateRoll_Click(object sender, EventArgs e) + { + UpdateRollAngles(); + ApplyRoll(rollAmmount.Value); } - private void bUpdateScaleX_Click(object sender, EventArgs e) { - updateScaleX(); - applyScale(); + private void bUpdateScaleX_Click(object sender, EventArgs e) + { + UpdateScaleX(); + ApplyScale(); } - private void bUpdateScaleY_Click(object sender, EventArgs e) { - updateScaleY(); - applyScale(); + private void bUpdateScaleY_Click(object sender, EventArgs e) + { + UpdateScaleY(); + ApplyScale(); } - private void cbRelativePitch_CheckedChanged(object sender, EventArgs e) { - updatePitchAngles(); - applyPitch(pitchAmmount.Value); + private void cbRelativePitch_CheckedChanged(object sender, EventArgs e) + { + UpdatePitchAngles(); + ApplyPitch(pitchAmmount.Value); } - private void cbRelativeRoll_CheckedChanged(object sender, EventArgs e) { - updateRollAngles(); - applyRoll(rollAmmount.Value); + private void cbRelativeRoll_CheckedChanged(object sender, EventArgs e) + { + UpdateRollAngles(); + ApplyRoll(rollAmmount.Value); } - private void cbNegativePitch_CheckedChanged(object sender, EventArgs e) { - updatePitchAngles(); - applyPitch(pitchAmmount.Value); + private void cbNegativePitch_CheckedChanged(object sender, EventArgs e) + { + UpdatePitchAngles(); + ApplyPitch(pitchAmmount.Value); } - private void cbNegativeRoll_CheckedChanged(object sender, EventArgs e) { - updateRollAngles(); - applyRoll(rollAmmount.Value); + private void cbNegativeRoll_CheckedChanged(object sender, EventArgs e) + { + UpdateRollAngles(); + ApplyRoll(rollAmmount.Value); } - private void cbRelativeScale_CheckedChanged(object sender, EventArgs e) { - applyScale(); + private void cbRelativeScale_CheckedChanged(object sender, EventArgs e) + { + ApplyScale(); } - private void cbUniformScale_CheckedChanged(object sender, EventArgs e) { + private void cbUniformScale_CheckedChanged(object sender, EventArgs e) + { bUpdateScaleY.Enabled = !cbUniformScale.Checked; minScaleY.Enabled = !cbUniformScale.Checked; maxScaleY.Enabled = !cbUniformScale.Checked; minScaleYLabel.Enabled = !cbUniformScale.Checked; maxScaleYLabel.Enabled = !cbUniformScale.Checked; - applyScale(); + ApplyScale(); } - private void cbNegativeScaleX_CheckedChanged(object sender, EventArgs e) { - updateScaleX(); - applyScale(); + private void cbNegativeScaleX_CheckedChanged(object sender, EventArgs e) + { + UpdateScaleX(); + ApplyScale(); } - private void cbNegativeScaleY_CheckedChanged(object sender, EventArgs e) { - updateScaleY(); - applyScale(); + private void cbNegativeScaleY_CheckedChanged(object sender, EventArgs e) + { + UpdateScaleY(); + ApplyScale(); } #endregion //HALP! - private void JitterThingsForm_HelpRequested(object sender, HelpEventArgs hlpevent) { + private void JitterThingsForm_HelpRequested(object sender, HelpEventArgs hlpevent) + { General.ShowHelp("gzdb/features/all_modes/jitter.html"); hlpevent.Handled = true; } diff --git a/Source/Plugins/BuilderEffects/Interface/JitterVerticesForm.cs b/Source/Plugins/BuilderEffects/Interface/JitterVerticesForm.cs index 10fd1008..28d1d446 100644 --- a/Source/Plugins/BuilderEffects/Interface/JitterVerticesForm.cs +++ b/Source/Plugins/BuilderEffects/Interface/JitterVerticesForm.cs @@ -1,4 +1,6 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; using System.Windows.Forms; using CodeImp.DoomBuilder.Map; @@ -6,10 +8,14 @@ using CodeImp.DoomBuilder.VisualModes; using CodeImp.DoomBuilder.Windows; using CodeImp.DoomBuilder.Geometry; +#endregion + namespace CodeImp.DoomBuilder.BuilderEffects { public partial class JitterVerticesForm : DelayedForm { + #region ================== Variables + private readonly string editingModeName; private readonly List selection; private readonly List visualSectors; @@ -17,14 +23,23 @@ namespace CodeImp.DoomBuilder.BuilderEffects private readonly VertexData[] vertexData; private readonly int MaxSafeDistance; + #endregion + + #region ================== Structs + private struct VertexData { public Vector2D Position; public int SafeDistance; public float JitterAngle; } - - public JitterVerticesForm(string editingModeName) { + + #endregion + + #region ================== Constructor / Setup + + public JitterVerticesForm(string editingModeName) + { this.editingModeName = editingModeName; this.HelpRequested += JitterVerticesForm_HelpRequested; @@ -33,14 +48,17 @@ namespace CodeImp.DoomBuilder.BuilderEffects //get selection selection = new List(); - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { VisualMode vm = (VisualMode)General.Editing.Mode; List visualSelection = vm.GetSelectedSurfaces(); visualSectors = new List(); int linesCount = 0; - foreach(VisualGeometry vg in visualSelection) { - if(vg.Sidedef != null && vm.VisualSectorExists(vg.Sidedef.Sector)) { + foreach(VisualGeometry vg in visualSelection) + { + if(vg.Sidedef != null && vm.VisualSectorExists(vg.Sidedef.Sector)) + { if(!selection.Contains(vg.Sidedef.Line.Start)) selection.Add(vg.Sidedef.Line.Start); if(!selection.Contains(vg.Sidedef.Line.End)) @@ -63,31 +81,33 @@ namespace CodeImp.DoomBuilder.BuilderEffects //update window header this.Text = "Randomize " + linesCount + (linesCount > 1 ? " linedefs" : " linedef"); - } else if(editingModeName == "LinedefsMode") { + } + else if(editingModeName == "LinedefsMode") + { ICollection list = General.Map.Map.GetSelectedLinedefs(true); int linesCount = 0; - foreach(Linedef l in list) { - if(!selection.Contains(l.Start)) - selection.Add(l.Start); - if(!selection.Contains(l.End)) - selection.Add(l.End); + foreach(Linedef l in list) + { + if(!selection.Contains(l.Start)) selection.Add(l.Start); + if(!selection.Contains(l.End)) selection.Add(l.End); linesCount++; } //update window header this.Text = "Randomize " + linesCount + (linesCount > 1 ? " linedefs" : " linedef"); - } else { + } + else + { ICollection list = General.Map.Map.GetSelectedVertices(true); - - foreach(Vertex v in list) - selection.Add(v); + foreach(Vertex v in list) selection.Add(v); //update window header this.Text = "Randomize " + selection.Count + (selection.Count > 1 ? " vertices" : " vertex"); } - if(selection.Count == 0) { + if(selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to get vertices from selection!"); return; } @@ -98,12 +118,14 @@ namespace CodeImp.DoomBuilder.BuilderEffects Dictionary data = new Dictionary(); - foreach(Vertex v in selection) { + foreach(Vertex v in selection) + { VertexData vd = new VertexData {Position = v.Position}; data.Add(v, vd); } - foreach(Vertex v in selection){ + foreach(Vertex v in selection) + { if(v.Linedefs == null) continue; //get nearest linedef @@ -111,12 +133,14 @@ namespace CodeImp.DoomBuilder.BuilderEffects float distance = float.MaxValue; // Go for all linedefs in selection - foreach(Linedef l in General.Map.Map.Linedefs) { + foreach(Linedef l in General.Map.Map.Linedefs) + { if(v.Linedefs.Contains(l)) continue; // Calculate distance and check if closer than previous find float d = l.SafeDistanceToSq(v.Position, true); - if(d < distance) { + if(d < distance) + { // This one is closer closestLine = l; distance = d; @@ -128,12 +152,16 @@ namespace CodeImp.DoomBuilder.BuilderEffects float closestLineDistance = Vector2D.Distance(v.Position, closestLine.NearestOnLine(v.Position)); //check SafeDistance of closest line - if(data.ContainsKey(closestLine.Start) && data[closestLine.Start].SafeDistance > closestLineDistance) { + if(data.ContainsKey(closestLine.Start) + && data[closestLine.Start].SafeDistance > closestLineDistance) + { VertexData vd = data[closestLine.Start]; vd.SafeDistance = (int)Math.Floor(closestLineDistance); data[closestLine.Start] = vd; } - if(data.ContainsKey(closestLine.End) && data[closestLine.End].SafeDistance > closestLineDistance) { + if(data.ContainsKey(closestLine.End) + && data[closestLine.End].SafeDistance > closestLineDistance) + { VertexData vd = data[closestLine.End]; vd.SafeDistance = (int)Math.Floor(closestLineDistance); data[closestLine.End] = vd; @@ -141,7 +169,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects //save SafeDistance int dist = (int)Math.Floor(closestLineDistance); - if(data[v].SafeDistance == 0 || data[v].SafeDistance > dist) { + if(data[v].SafeDistance == 0 || data[v].SafeDistance > dist) + { VertexData vd = data[v]; vd.SafeDistance = dist; data[v] = vd; @@ -152,7 +181,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects vertexData = new VertexData[data.Values.Count]; data.Values.CopyTo(vertexData, 0); - for(int i = 0; i < vertexData.Length; i++) { + for(int i = 0; i < vertexData.Length; i++) + { if(vertexData[i].SafeDistance > 0) vertexData[i].SafeDistance /= 2; if(MaxSafeDistance < vertexData[i].SafeDistance) @@ -161,20 +191,26 @@ namespace CodeImp.DoomBuilder.BuilderEffects positionJitterAmmount.Maximum = MaxSafeDistance; - updateAngles(); + UpdateAngles(); } -//utility - private void applyTranslationJitter(int ammount) { + #endregion + + #region ================== Utility + + private void ApplyTranslationJitter(int ammount) + { int curAmmount; - for(int i = 0; i < selection.Count; i++) { + for(int i = 0; i < selection.Count; i++) + { curAmmount = ammount > vertexData[i].SafeDistance ? vertexData[i].SafeDistance : ammount; selection[i].Move(new Vector2D(vertexData[i].Position.x + (int)(Math.Sin(vertexData[i].JitterAngle) * curAmmount), vertexData[i].Position.y + (int)(Math.Cos(vertexData[i].JitterAngle) * curAmmount))); } //update view - if(editingModeName == "BaseVisualMode") { + if(editingModeName == "BaseVisualMode") + { General.Map.Map.Update(); General.Map.IsChanged = true; @@ -185,21 +221,29 @@ namespace CodeImp.DoomBuilder.BuilderEffects pair.Changed = true; pair.Update(); } - } else { + } + else + { General.Interface.RedrawDisplay(); } } - private void updateAngles() { - for(int i = 0; i < vertexData.Length; i++) { + private void UpdateAngles() + { + for(int i = 0; i < vertexData.Length; i++) + { VertexData vd = vertexData[i]; vd.JitterAngle = (float)(General.Random(0, 359) * Math.PI / 180f); vertexData[i] = vd; } } -//EVENTS - private void bApply_Click(object sender, EventArgs e) { +#endregion + + #region ================== Events + + private void bApply_Click(object sender, EventArgs e) + { // Update cached values General.Map.Map.Update(); General.Map.IsChanged = true; @@ -211,28 +255,35 @@ namespace CodeImp.DoomBuilder.BuilderEffects Close(); } - private void bCancel_Click(object sender, EventArgs e) { + private void bCancel_Click(object sender, EventArgs e) + { this.DialogResult = DialogResult.Cancel; Close(); } - private void JitterVerticesForm_FormClosing(object sender, FormClosingEventArgs e) { + private void JitterVerticesForm_FormClosing(object sender, FormClosingEventArgs e) + { if(this.DialogResult == DialogResult.Cancel) General.Map.UndoRedo.WithdrawUndo(); //undo changes } - private void positionJitterAmmount_OnValueChanging(object sender, EventArgs e) { - applyTranslationJitter(positionJitterAmmount.Value); + private void positionJitterAmmount_OnValueChanging(object sender, EventArgs e) + { + ApplyTranslationJitter(positionJitterAmmount.Value); } - private void bUpdateTranslation_Click(object sender, EventArgs e) { - updateAngles(); - applyTranslationJitter(positionJitterAmmount.Value); + private void bUpdateTranslation_Click(object sender, EventArgs e) + { + UpdateAngles(); + ApplyTranslationJitter(positionJitterAmmount.Value); } - private void JitterVerticesForm_HelpRequested(object sender, HelpEventArgs hlpevent) { + private void JitterVerticesForm_HelpRequested(object sender, HelpEventArgs hlpevent) + { General.ShowHelp("gzdb/features/all_modes/jitter.html"); hlpevent.Handled = true; } + + #endregion } } diff --git a/Source/Plugins/BuilderEffects/Interface/MenusForm.cs b/Source/Plugins/BuilderEffects/Interface/MenusForm.cs index 8044dd27..1dfc903e 100644 --- a/Source/Plugins/BuilderEffects/Interface/MenusForm.cs +++ b/Source/Plugins/BuilderEffects/Interface/MenusForm.cs @@ -6,35 +6,37 @@ namespace CodeImp.DoomBuilder.BuilderEffects { public partial class MenusForm : Form { - public MenusForm() { + public MenusForm() + { InitializeComponent(); } // This invokes an action from control event - private void InvokeTaggedAction(object sender, EventArgs e) { + private void InvokeTaggedAction(object sender, EventArgs e) + { General.Interface.InvokeTaggedAction(sender, e); } // This registers with the core - public void Register() { + public void Register() + { // Add the menus to the core General.Interface.AddModesMenu(jitterItem, "002_modify"); General.Interface.AddModesButton(jitterButton, "002_modify"); - for(int i = 0; i < importStripMenuItem.DropDownItems.Count; i++) { + for(int i = 0; i < importStripMenuItem.DropDownItems.Count; i++) General.Interface.AddMenu(importStripMenuItem.DropDownItems[i] as ToolStripMenuItem, MenuSection.FileImport); - } } // This unregisters from the core - public void Unregister() { + public void Unregister() + { // Remove the menus from the core General.Interface.RemoveMenu(jitterItem); General.Interface.RemoveButton(jitterButton); - for (int i = 0; i < importStripMenuItem.DropDownItems.Count; i++) { + for (int i = 0; i < importStripMenuItem.DropDownItems.Count; i++) General.Interface.RemoveMenu(importStripMenuItem.DropDownItems[i] as ToolStripMenuItem); - } } } } diff --git a/Source/Plugins/BuilderEffects/Interface/ObjImportSettingsForm.cs b/Source/Plugins/BuilderEffects/Interface/ObjImportSettingsForm.cs index 1ef3583d..94156cce 100644 --- a/Source/Plugins/BuilderEffects/Interface/ObjImportSettingsForm.cs +++ b/Source/Plugins/BuilderEffects/Interface/ObjImportSettingsForm.cs @@ -27,14 +27,16 @@ namespace CodeImp.DoomBuilder.BuilderEffects #endregion - public ObjImportSettingsForm() { + public ObjImportSettingsForm() + { InitializeComponent(); //restore settings axis = (ImportObjAsTerrainMode.UpAxis)General.Settings.ReadPluginSetting("objexportupaxis", 0); nudScale.Value = (decimal)General.Settings.ReadPluginSetting("objexportscale", 1.0f); - switch(axis) { + switch(axis) + { case ImportObjAsTerrainMode.UpAxis.X: axisx.Checked = true; break; case ImportObjAsTerrainMode.UpAxis.Y: axisy.Checked = true; break; case ImportObjAsTerrainMode.UpAxis.Z: axisz.Checked = true; break; @@ -44,18 +46,20 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region ================== Events - private void browse_Click(object sender, EventArgs e) { - if(openFileDialog.ShowDialog() == DialogResult.OK) { - tbImportPath.Text = openFileDialog.FileName; - } + private void browse_Click(object sender, EventArgs e) + { + if(openFileDialog.ShowDialog() == DialogResult.OK) tbImportPath.Text = openFileDialog.FileName; } - private void import_Click(object sender, EventArgs e) { - if(nudScale.Value == 0) { + private void import_Click(object sender, EventArgs e) + { + if(nudScale.Value == 0) + { MessageBox.Show("Scale should not be zero!"); return; } - if(!File.Exists(tbImportPath.Text)) { + if(!File.Exists(tbImportPath.Text)) + { MessageBox.Show("Selected path does not exist!"); return; } @@ -70,7 +74,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects this.Close(); } - private void cancel_Click(object sender, EventArgs e) { + private void cancel_Click(object sender, EventArgs e) + { this.Close(); } diff --git a/Source/Plugins/BuilderEffects/Modes/ImportObjAsTerrainMode.cs b/Source/Plugins/BuilderEffects/Modes/ImportObjAsTerrainMode.cs index a4cf3969..b432b5f4 100644 --- a/Source/Plugins/BuilderEffects/Modes/ImportObjAsTerrainMode.cs +++ b/Source/Plugins/BuilderEffects/Modes/ImportObjAsTerrainMode.cs @@ -36,7 +36,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects public readonly Vector3D V2; public readonly Vector3D V3; - public Face(Vector3D v1, Vector3D v2, Vector3D v3) { + public Face(Vector3D v1, Vector3D v2, Vector3D v3) + { V1 = v1; V2 = v2; V3 = v3; @@ -60,7 +61,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region ================== Constructor - public ImportObjAsTerrainMode() { + public ImportObjAsTerrainMode() + { form = new ObjImportSettingsForm(); } @@ -68,8 +70,10 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region ================== Methods - public override void OnEngage() { - if(!General.Map.UDMF) { + public override void OnEngage() + { + if(!General.Map.UDMF) + { General.Interface.DisplayStatus(StatusType.Warning, "Terrain importer works only in UDMF map format!"); OnCancel(); } @@ -78,14 +82,18 @@ namespace CodeImp.DoomBuilder.BuilderEffects General.Map.Map.ClearAllSelected(); //show interface - if(form.ShowDialog() == DialogResult.OK && File.Exists(form.FilePath)) { + if(form.ShowDialog() == DialogResult.OK && File.Exists(form.FilePath)) + { OnAccept(); - } else { + } + else + { OnCancel(); } } - public override void OnAccept() { + public override void OnAccept() + { Cursor.Current = Cursors.AppStarting; General.Interface.DisplayStatus(StatusType.Busy, "Creating geometry..."); @@ -96,7 +104,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects int maxZ = int.MinValue; // Read .obj, create and select sectors - if(!readGeometry(form.FilePath, form.ObjScale, form.UpAxis, verts, faces, ref minZ, ref maxZ) || !createGeometry(verts, faces, minZ, maxZ + (maxZ - minZ)/2)) { + if(!ReadGeometry(form.FilePath, form.ObjScale, form.UpAxis, verts, faces, ref minZ, ref maxZ) || !CreateGeometry(verts, faces, minZ, maxZ + (maxZ - minZ)/2)) + { // Fial! Cursor.Current = Cursors.Default; @@ -115,7 +124,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects General.Editing.ChangeMode("EditSelectionMode", true); } - public override void OnCancel() { + public override void OnCancel() + { // Cancel base class base.OnCancel(); @@ -127,7 +137,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region ================== Geometry creation - private bool createGeometry(List verts, List faces, int minZ, int maxZ) { + private static bool CreateGeometry(List verts, List faces, int minZ, int maxZ) + { //make undo General.Map.UndoRedo.CreateUndo("Import Terrain"); @@ -139,7 +150,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects //terrain has many faces... let's create them Dictionary newverts = new Dictionary(); - foreach(Face face in faces){ + foreach(Face face in faces) + { Sector s = map.CreateSector(); s.Selected = true; s.FloorHeight = minZ; @@ -148,49 +160,53 @@ namespace CodeImp.DoomBuilder.BuilderEffects s.SetCeilTexture(General.Map.Config.SkyFlatName); s.SetFloorTexture(General.Map.Options.DefaultFloorTexture); //todo: allow user to change this - Linedef newline = getLine(newverts, s, face.V1, face.V2); + Linedef newline = GetLine(newverts, s, face.V1, face.V2); if(newline != null) newlines.Add(newline); - newline = getLine(newverts, s, face.V2, face.V3); + newline = GetLine(newverts, s, face.V2, face.V3); if(newline != null) newlines.Add(newline); - newline = getLine(newverts, s, face.V3, face.V1); + newline = GetLine(newverts, s, face.V3, face.V1); if(newline != null) newlines.Add(newline); s.UpdateCache(); } //update new lines - foreach(Linedef l in newlines){ - l.ApplySidedFlags(); - } + foreach(Linedef l in newlines) l.ApplySidedFlags(); map.EndAddRemove(); return true; } - private Linedef getLine(Dictionary verts, Sector sector, Vector3D v1, Vector3D v2) { + private static Linedef GetLine(Dictionary verts, Sector sector, Vector3D v1, Vector3D v2) + { Linedef line = null; //get start and end verts - Vertex start = getVertex(verts, v1); - Vertex end = getVertex(verts, v2); + Vertex start = GetVertex(verts, v1); + Vertex end = GetVertex(verts, v2); //check if the line is already created - foreach(Linedef l in start.Linedefs){ - if(l.End == end || l.Start == end) { + foreach(Linedef l in start.Linedefs) + { + if(l.End == end || l.Start == end) + { line = l; break; } } //create a new line? - if(line == null) { + if(line == null) + { line = General.Map.Map.CreateLinedef(start, end); //create front sidedef and attach sector to it General.Map.Map.CreateSidedef(line, true, sector); - } else { + } + else + { //create back sidedef and attach sector to it General.Map.Map.CreateSidedef(line, false, sector); } @@ -199,7 +215,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects return line; } - private static Vertex getVertex(Dictionary verts, Vector3D pos) { + private static Vertex GetVertex(Dictionary verts, Vector3D pos) + { //already there? if(verts.ContainsKey(pos)) return verts[pos]; @@ -214,28 +231,34 @@ namespace CodeImp.DoomBuilder.BuilderEffects #region ================== .obj import - private static bool readGeometry(string path, float scale, UpAxis axis, List verts, List faces, ref int minZ, ref int maxZ) { - using(StreamReader reader = File.OpenText(path)) { + private static bool ReadGeometry(string path, float scale, UpAxis axis, List verts, List faces, ref int minZ, ref int maxZ) + { + using(StreamReader reader = File.OpenText(path)) + { string line; float x, y, z; int px, py, pz; int counter = 0; - while((line = reader.ReadLine()) != null) { + while((line = reader.ReadLine()) != null) + { counter++; - if(line.StartsWith("v ")) { + if(line.StartsWith("v ")) + { string[] parts = line.Split(space); if(parts.Length != 4 || !float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out x) || !float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out y) || - !float.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out z)) { + !float.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out z)) + { MessageBox.Show("Failed to parse vertex definition at line " + counter + "!", "Terrain Importer", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } //apply up axis - switch (axis) { + switch (axis) + { case UpAxis.Y: px = (int)Math.Round(x * scale); py = (int)Math.Round(-z * scale); @@ -265,19 +288,21 @@ namespace CodeImp.DoomBuilder.BuilderEffects if(minZ > pz) minZ = pz; verts.Add(new Vector3D(px, py, pz)); - - } else if(line.StartsWith("f ")) { + } + else if(line.StartsWith("f ")) + { string[] parts = line.Split(space); - if(parts.Length != 4) { + if(parts.Length != 4) + { MessageBox.Show("Failed to parse face definition at line " + counter + ": only triangle faces are supported!", "Terrain Importer", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } //.obj vertex indices are 1-based - int v1 = readVertexIndex(parts[1]) - 1; - int v2 = readVertexIndex(parts[2]) - 1; - int v3 = readVertexIndex(parts[3]) - 1; + int v1 = ReadVertexIndex(parts[1]) - 1; + int v2 = ReadVertexIndex(parts[2]) - 1; + int v3 = ReadVertexIndex(parts[3]) - 1; if(verts[v1] == verts[v2] || verts[v1] == verts[v3] || verts[v2] == verts[v3]) continue; faces.Add(new Face(verts[v3], verts[v2], verts[v1])); @@ -288,7 +313,8 @@ namespace CodeImp.DoomBuilder.BuilderEffects return true; } - private static int readVertexIndex(string def) { + private static int ReadVertexIndex(string def) + { int slashpos = def.IndexOf(slash); if(slashpos != -1) def = def.Substring(0, slashpos); return int.Parse(def); diff --git a/Source/Plugins/BuilderModes/ClassicModes/BaseClassicMode.cs b/Source/Plugins/BuilderModes/ClassicModes/BaseClassicMode.cs index 29a88a8d..a5f74563 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/BaseClassicMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/BaseClassicMode.cs @@ -131,7 +131,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void OnUpdateMultiSelection() { + protected override void OnUpdateMultiSelection() + { base.OnUpdateMultiSelection(); if(General.Interface.CtrlState && General.Interface.ShiftState) @@ -147,33 +148,39 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnUndoEnd() { + public override void OnUndoEnd() + { General.Map.Renderer2D.UpdateExtraFloorFlag(); base.OnUndoEnd(); UpdateSelectionInfo(); } //mxd - public override void OnRedoEnd() { + public override void OnRedoEnd() + { General.Map.Renderer2D.UpdateExtraFloorFlag(); base.OnRedoEnd(); UpdateSelectionInfo(); } //mxd - public override void OnMapTestEnd(bool testFromCurrentPosition) { + public override void OnMapTestEnd(bool testFromCurrentPosition) + { base.OnMapTestEnd(testFromCurrentPosition); General.Interface.RedrawDisplay(); // Redraw display to hide changes :) } //mxd - public virtual void UpdateSelectionInfo() { + public virtual void UpdateSelectionInfo() + { General.Interface.DisplayStatus(StatusType.Selection, string.Empty); } //mxd - protected void placeThingsAtPositions(List positions) { - if (positions.Count < 1) { + protected void PlaceThingsAtPositions(List positions) + { + if (positions.Count < 1) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires selection of some description!"); return; } @@ -182,9 +189,11 @@ namespace CodeImp.DoomBuilder.BuilderModes List things = new List(); // Create things - foreach (Vector2D pos in positions) { + foreach (Vector2D pos in positions) + { Thing t = General.Map.Map.CreateThing(); - if(t != null) { + if(t != null) + { General.Settings.ApplyDefaultThingSettings(t); t.Move(pos); t.UpdateConfiguration(); @@ -195,7 +204,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //Operation failed?.. - if (things.Count < 1) { + if (things.Count < 1) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires selection of some description!"); General.Map.UndoRedo.WithdrawUndo(); return; @@ -203,9 +213,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //Show realtime thing edit dialog General.Interface.OnEditFormValuesChanged += thingEditForm_OnValuesChanged; - if (General.Interface.ShowEditThings(things) == DialogResult.Cancel) { + if (General.Interface.ShowEditThings(things) == DialogResult.Cancel) + { General.Map.UndoRedo.WithdrawUndo(); - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Info, "Placed " + things.Count + " things."); } General.Interface.OnEditFormValuesChanged -= thingEditForm_OnValuesChanged; @@ -216,7 +229,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Events (mxd) //mxd - private void thingEditForm_OnValuesChanged(object sender, EventArgs e) { + private void thingEditForm_OnValuesChanged(object sender, EventArgs e) + { // Update things filter General.Map.ThingsFilter.Update(); @@ -298,19 +312,22 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("classicpaintselect")] - protected virtual void OnPaintSelectBegin() { + protected virtual void OnPaintSelectBegin() + { paintselectpressed = true; } //mxd [EndAction("classicpaintselect")] - protected virtual void OnPaintSelectEnd() { + protected virtual void OnPaintSelectEnd() + { paintselectpressed = false; } //mxd [BeginAction("togglehighlight")] - public void ToggleHighlight() { + public void ToggleHighlight() + { BuilderPlug.Me.UseHighlight = !BuilderPlug.Me.UseHighlight; General.Interface.DisplayStatus(StatusType.Action, "Highlight is now " + (BuilderPlug.Me.UseHighlight ? "ON" : "OFF") + "."); @@ -320,10 +337,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("thingsselectinsectors")] - public void SelectThingsInSelectedSectors() { + public void SelectThingsInSelectedSectors() + { General.Map.Map.ConvertSelection(SelectionType.Sectors); - if(General.Map.Map.SelectedSectorsCount == 0) { + if(General.Map.Map.SelectedSectorsCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "No Sectors are Selected!"); General.Map.Map.ConvertSelection(SelectionType.Linedefs); return; @@ -332,10 +351,12 @@ namespace CodeImp.DoomBuilder.BuilderModes int selectedCount = 0; ICollection sectors = General.Map.Map.GetSelectedSectors(true); - foreach(Thing t in General.Map.Map.Things) { + foreach(Thing t in General.Map.Map.Things) + { t.DetermineSector(); - if(!t.Selected && t.Sector != null && sectors.Contains(t.Sector)) { + if(!t.Selected && t.Sector != null && sectors.Contains(t.Sector)) + { t.Selected = true; selectedCount++; } diff --git a/Source/Plugins/BuilderModes/ClassicModes/BridgeMode.cs b/Source/Plugins/BuilderModes/ClassicModes/BridgeMode.cs index 3ede4314..0f717a57 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/BridgeMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/BridgeMode.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Rendering; using CodeImp.DoomBuilder.Geometry; @@ -14,7 +15,8 @@ using CodeImp.DoomBuilder.BuilderModes.Interface; #endregion -namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { +namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes +{ [EditMode(DisplayName = "Bridge Mode", SwitchAction = "bridgemode", ButtonImage = "BridgeMode.png", @@ -56,7 +58,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { private int segmentsCount; // Options - protected bool snaptogrid; // SHIFT to toggle + private bool snaptogrid; // SHIFT to toggle //tools form private BridgeModeForm form; @@ -65,7 +67,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Constructor / Disposer - public BridgeMode() { + public BridgeMode() + { // We have no destructor GC.SuppressFinalize(this); } @@ -75,7 +78,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Methods // Engaging - public override void OnEngage() { + public override void OnEngage() + { base.OnEngage(); renderer.SetPresentation(Presentation.Standard); @@ -84,13 +88,15 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { ICollection selection = General.Map.Map.GetSelectedLinedefs(true); List lines = new List(); - foreach (Linedef ld in selection) { + foreach (Linedef ld in selection) + { Line l = new Line(ld); lines.Add(l); } //do we have valid selection? - if (!setup(lines)) { + if (!Setup(lines)) + { FinishDraw(); return; } @@ -105,16 +111,22 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { General.Interface.FocusDisplay(); handleColor = General.Colors.BrightColors[new Random().Next(General.Colors.BrightColors.Length - 1)]; - update(); + Update(); } // When select button is pressed - protected override void OnSelectBegin() { + protected override void OnSelectBegin() + { base.OnSelectBegin(); //check if control handle is selected - for (int i = 0; i < 4; i++) { - if (mousemappos.x <= controlHandles[i].Position.x + GRIP_SIZE && mousemappos.x >= controlHandles[i].Position.x - GRIP_SIZE && mousemappos.y <= controlHandles[i].Position.y + GRIP_SIZE && mousemappos.y >= controlHandles[i].Position.y - GRIP_SIZE) { + for (int i = 0; i < 4; i++) + { + if (mousemappos.x <= controlHandles[i].Position.x + GRIP_SIZE + && mousemappos.x >= controlHandles[i].Position.x - GRIP_SIZE + && mousemappos.y <= controlHandles[i].Position.y + GRIP_SIZE + && mousemappos.y >= controlHandles[i].Position.y - GRIP_SIZE) + { curControlHandle = i; General.Interface.SetCursor(Cursors.Cross); return; @@ -124,27 +136,27 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } // When select button is released - protected override void OnSelectEnd() { + protected override void OnSelectEnd() + { base.OnSelectEnd(); General.Interface.SetCursor(Cursors.Default); curControlHandle = -1; } // Mouse moves - public override void OnMouseMove(MouseEventArgs e) { + public override void OnMouseMove(MouseEventArgs e) + { base.OnMouseMove(e); if(panning) return; //mxd. Skip all this jass while panning - if (curControlHandle != -1) { + if (curControlHandle != -1) + { ControlHandle handle = controlHandles[curControlHandle]; - if (snaptogrid) { - handle.Position = General.Map.Grid.SnappedToGrid(mousemappos); - } else { - handle.Position = mousemappos; - } + handle.Position = (snaptogrid ? General.Map.Grid.SnappedToGrid(mousemappos) : mousemappos); - if (form.MirrorMode) { + if (form.MirrorMode) + { Vector2D pos = handle.RelativePosition; //handle angle float angle = (float)Math.Atan2(-pos.y, -pos.x) + Angle2D.PIHALF; @@ -154,21 +166,23 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { float mirroredAngle = angle + dirAngle * 2.0f; handle.Pair.RelativePosition = new Vector2D((float)Math.Sin(mirroredAngle) * length, (float)Math.Cos(mirroredAngle) * length); - } else if (form.CopyMode) { + } + else if (form.CopyMode) + { handle.Pair.RelativePosition = handle.RelativePosition; } - update(); + Update(); } } // Accepted - public override void OnAccept() { + public override void OnAccept() + { Cursor.Current = Cursors.AppStarting; - General.Settings.FindDefaultDrawSettings(); //get vertices - List> shapes = getShapes(); + List> shapes = GetShapes(); List>> drawShapes = new List>>(); List> shapesRow; List points; @@ -177,9 +191,11 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { float stitchrange = BuilderPlug.Me.StitchRange; BuilderPlug.Me.StitchRange = 0.1f; - for (int i = 0; i < shapes.Count; i++) { + for (int i = 0; i < shapes.Count; i++) + { shapesRow = new List>(); - for (int c = 0; c < shapes[i].Count; c++) { + for (int c = 0; c < shapes[i].Count; c++) + { points = new List(); for (int p = 0; p < shapes[i][c].Length; p++) points.Add(DrawGeometryMode.GetCurrentPosition(shapes[i][c][p], true, false, renderer, points)); @@ -192,7 +208,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { BuilderPlug.Me.StitchRange = stitchrange; //draw lines - if (drawShapes.Count > 0) { + if (drawShapes.Count > 0) + { // Make undo for the draw General.Map.UndoRedo.CreateUndo("Bridge ("+form.Subdivisions+" subdivisions)"); @@ -201,22 +218,26 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { //create sector properties collection //sector row - for (int i = 0; i < drawShapes.Count; i++) { + for (int i = 0; i < drawShapes.Count; i++) + { sectorProps.Add(new List()); //sector in row for (int c = 0; c < drawShapes[i].Count; c++) - sectorProps[i].Add(getSectorProperties(i, c)); + sectorProps[i].Add(GetSectorProperties(i, c)); } // Make the drawing //sector row - for (int i = 0; i < drawShapes.Count; i++) { + for (int i = 0; i < drawShapes.Count; i++) + { newSectors.Add(new List>()); //sector in row - for (int c = 0; c < drawShapes[i].Count; c++) { - if(!Tools.DrawLines(drawShapes[i][c], false, true)) { + for (int c = 0; c < drawShapes[i].Count; c++) + { + if(!Tools.DrawLines(drawShapes[i][c], false, true)) + { // Drawing failed // NOTE: I have to call this twice, because the first time only cancels this volatile mode General.Interface.DisplayStatus(StatusType.Warning, "Failed to create a Bezier Path..."); @@ -229,7 +250,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { newSectors[i].Add(newsectors); //set floor/ceiling heights and brightness - foreach (Sector s in newsectors) { + foreach (Sector s in newsectors) + { SectorProperties sp = sectorProps[i][c]; s.Brightness = sp.Brightness; s.FloorHeight = sp.FloorHeight; @@ -240,11 +262,15 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { //apply textures //sector row - for (int i = 0; i < newSectors.Count; i++) { + for (int i = 0; i < newSectors.Count; i++) + { //sector in row - for (int c = 0; c < newSectors[i].Count; c++) { - foreach (Sector s in newSectors[i][c]) { - foreach(Sidedef sd in s.Sidedefs){ + for (int c = 0; c < newSectors[i].Count; c++) + { + foreach (Sector s in newSectors[i][c]) + { + foreach(Sidedef sd in s.Sidedefs) + { if (sd.LowRequired()) sd.SetTextureLow(sectorProps[i][c].LowTexture); if (sd.HighRequired()) @@ -256,12 +282,17 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { //apply textures to front/back sides of shape //sector row - for (int i = 0; i < newSectors.Count; i++) { + for (int i = 0; i < newSectors.Count; i++) + { //first/last sector in row - for (int c = 0; c < newSectors[i].Count; c += newSectors[i].Count-1) { - foreach (Sector s in newSectors[i][c]) { - foreach (Sidedef sd in s.Sidedefs) { - if (sd.Other != null) { + for (int c = 0; c < newSectors[i].Count; c += newSectors[i].Count-1) + { + foreach (Sector s in newSectors[i][c]) + { + foreach (Sidedef sd in s.Sidedefs) + { + if (sd.Other != null) + { if (sd.Other.LowRequired() && sd.Other.LowTexture == "-") sd.Other.SetTextureLow(sectorProps[i][c].LowTexture); if (sd.Other.HighRequired() && sd.Other.HighTexture == "-") @@ -301,7 +332,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } // Cancelled - public override void OnCancel() { + public override void OnCancel() + { // Cancel base class base.OnCancel(); @@ -313,39 +345,45 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } // When a key is released - public override void OnKeyUp(KeyEventArgs e) { + public override void OnKeyUp(KeyEventArgs e) + { base.OnKeyUp(e); - if (snaptogrid != (General.Interface.ShiftState ^ General.Interface.SnapToGrid)) update(); + if (snaptogrid != (General.Interface.ShiftState ^ General.Interface.SnapToGrid)) Update(); } // When a key is pressed - public override void OnKeyDown(KeyEventArgs e) { + public override void OnKeyDown(KeyEventArgs e) + { base.OnKeyDown(e); - if (snaptogrid != (General.Interface.ShiftState ^ General.Interface.SnapToGrid)) update(); + if (snaptogrid != (General.Interface.ShiftState ^ General.Interface.SnapToGrid)) Update(); } // This redraws the display - public override void OnRedrawDisplay() { + public override void OnRedrawDisplay() + { renderer.RedrawSurface(); // Render lines - if (renderer.StartPlotter(true)) { + if (renderer.StartPlotter(true)) + { renderer.PlotLinedefSet(General.Map.Map.Linedefs); renderer.PlotVerticesSet(General.Map.Map.Vertices); renderer.Finish(); } // Render things - if (renderer.StartThings(true)) { + if (renderer.StartThings(true)) + { renderer.RenderThingSet(General.Map.Map.Things, 1.0f); renderer.Finish(); } // Normal update - update(); + Update(); } - public override void OnHelp() { + public override void OnHelp() + { General.ShowHelp("/gzdb/features/classic_modes/mode_drawbridge.html"); } @@ -354,32 +392,21 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Setup/Update/Utility //this checks if initial data is valid - private bool setup(List lines) { - if (!setupPointGroups(lines)) - return false; + private bool Setup(List lines) + { + if (!SetupPointGroups(lines)) return false; //setup control handles Vector2D center1 = CurveTools.GetPointOnLine(pointGroup1[0], pointGroup1[segmentsCount - 1], 0.5f); Vector2D center2 = CurveTools.GetPointOnLine(pointGroup2[0], pointGroup2[segmentsCount - 1], 0.5f); - Vector2D loc1 = getHandleLocation(pointGroup1[0], pointGroup1[segmentsCount - 1], center2); - Vector2D loc2 = getHandleLocation(pointGroup2[0], pointGroup2[segmentsCount - 1], center1); + Vector2D loc1 = GetHandleLocation(pointGroup1[0], pointGroup1[segmentsCount - 1], center2); + Vector2D loc2 = GetHandleLocation(pointGroup2[0], pointGroup2[segmentsCount - 1], center1); - ControlHandle ch1 = new ControlHandle(); - ch1.ControlledPoint = pointGroup1[0]; - ch1.RelativePosition = loc1; - - ControlHandle ch2 = new ControlHandle(); - ch2.ControlledPoint = pointGroup2[0]; - ch2.RelativePosition = loc2; - - ControlHandle ch3 = new ControlHandle(); - ch3.ControlledPoint = pointGroup1[segmentsCount - 1]; - ch3.RelativePosition = loc1; - - ControlHandle ch4 = new ControlHandle(); - ch4.ControlledPoint = pointGroup2[segmentsCount - 1]; - ch4.RelativePosition = loc2; + ControlHandle ch1 = new ControlHandle {ControlledPoint = pointGroup1[0], RelativePosition = loc1}; + ControlHandle ch2 = new ControlHandle {ControlledPoint = pointGroup2[0], RelativePosition = loc2}; + ControlHandle ch3 = new ControlHandle {ControlledPoint = pointGroup1[segmentsCount - 1], RelativePosition = loc1}; + ControlHandle ch4 = new ControlHandle {ControlledPoint = pointGroup2[segmentsCount - 1], RelativePosition = loc2}; ch1.Pair = ch3; ch2.Pair = ch4; @@ -389,14 +416,16 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { controlHandles = new[] {ch1, ch2, ch3, ch4}; //setup relative segments lengths - relLenGroup1 = getRelativeLengths(pointGroup1); - relLenGroup2 = getRelativeLengths(pointGroup2); + relLenGroup1 = GetRelativeLengths(pointGroup1); + relLenGroup2 = GetRelativeLengths(pointGroup2); return true; } - private void update() { - if (renderer.StartOverlay(true)) { + private void Update() + { + if (renderer.StartOverlay(true)) + { snaptogrid = General.Interface.ShiftState ^ General.Interface.SnapToGrid; PixelColor linesColor = snaptogrid ? General.Colors.Selection : General.Colors.Highlight; @@ -405,19 +434,23 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { Vector2D cp1, cp2; curves = new List(); - for (int i = 0; i < segmentsCount; i++) { + for (int i = 0; i < segmentsCount; i++) + { cp1 = CurveTools.GetPointOnLine(controlHandles[0].Position, controlHandles[2].Position, relLenGroup1[i]); cp2 = CurveTools.GetPointOnLine(controlHandles[1].Position, controlHandles[3].Position, relLenGroup2[i]); curves.Add(CurveTools.GetCubicCurve(pointGroup1[i], pointGroup2[i], cp1, cp2, form.Subdivisions)); - for (int c = 1; c < curves[i].Length; c++ ) + for (int c = 1; c < curves[i].Length; c++) renderer.RenderLine(curves[i][c - 1], curves[i][c], LINE_THICKNESS, linesColor, true); } //draw connecting lines - if (form.Subdivisions > 1) { - for (int i = 1; i < segmentsCount; i++) { - for (int c = 1; c < form.Subdivisions; c++) { + if (form.Subdivisions > 1) + { + for (int i = 1; i < segmentsCount; i++) + { + for (int c = 1; c < form.Subdivisions; c++) + { renderer.RenderLine(curves[i-1][c], curves[i][c], LINE_THICKNESS, linesColor, true); } } @@ -426,8 +459,10 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { //draw vertices float vsize = (renderer.VertexSize + 1.0f) / renderer.Scale; - foreach(Vector2D[] points in curves){ - for (int i = 1; i < points.Length - 1; i++ ) { + foreach(Vector2D[] points in curves) + { + for (int i = 1; i < points.Length - 1; i++ ) + { renderer.RenderRectangleFilled(new RectangleF(points[i].x - vsize, points[i].y - vsize, vsize * 2.0f, vsize * 2.0f), linesColor, true); } } @@ -441,7 +476,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { //draw handles float gripsize = GRIP_SIZE / renderer.Scale; - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) + { RectangleF handleRect = new RectangleF(controlHandles[i].Position.x - gripsize * 0.5f, controlHandles[i].Position.y - gripsize * 0.5f, gripsize, gripsize); renderer.RenderRectangleFilled(handleRect, General.Colors.Background, true); renderer.RenderRectangle(handleRect, 2, General.Colors.Highlight, true); @@ -451,14 +487,15 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { renderer.Present(); } - private SectorProperties getSectorProperties(int lineIndex, int sectorIndex) { + private SectorProperties GetSectorProperties(int lineIndex, int sectorIndex) + { float delta = sectorIndex / (float)form.Subdivisions; delta += (1.0f - delta) / form.Subdivisions; SectorProperties sp = new SectorProperties(); - sp.Brightness = intepolateValue(sectorProps1[lineIndex].Brightness, sectorProps2[lineIndex].Brightness, delta, form.BrightnessMode); - sp.FloorHeight = intepolateValue(sectorProps1[lineIndex].FloorHeight, sectorProps2[lineIndex].FloorHeight, delta, form.FloorAlignMode); - sp.CeilingHeight = intepolateValue(sectorProps1[lineIndex].CeilingHeight, sectorProps2[lineIndex].CeilingHeight, delta, form.CeilingAlignMode); + sp.Brightness = IntepolateValue(sectorProps1[lineIndex].Brightness, sectorProps2[lineIndex].Brightness, delta, form.BrightnessMode); + sp.FloorHeight = IntepolateValue(sectorProps1[lineIndex].FloorHeight, sectorProps2[lineIndex].FloorHeight, delta, form.FloorAlignMode); + sp.CeilingHeight = IntepolateValue(sectorProps1[lineIndex].CeilingHeight, sectorProps2[lineIndex].CeilingHeight, delta, form.CeilingAlignMode); //textures sp.LowTexture = sectorProps1[lineIndex].LowTexture != "-" ? sectorProps1[lineIndex].LowTexture : sectorProps2[lineIndex].LowTexture; @@ -468,13 +505,16 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } //this returns a list of shapes to draw - private List> getShapes() { + private List> GetShapes() + { List> shapes = new List>(); - for (int i = 1; i < segmentsCount; i++) { + for (int i = 1; i < segmentsCount; i++) + { List segShapes = new List(); - for (int c = 1; c <= form.Subdivisions; c++) { + for (int c = 1; c <= form.Subdivisions; c++) + { Vector2D p0 = curves[i - 1][c - 1]; Vector2D p1 = curves[i - 1][c]; Vector2D p2 = curves[i][c]; @@ -492,19 +532,21 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Point ops //this returns an array of linedef lengths relative to total segment length - private float[] getRelativeLengths(Vector2D[] pointGroup) { + private float[] GetRelativeLengths(Vector2D[] pointGroup) + { float[] relLenGroup = new float[pointGroup.Length]; relLenGroup[0] = 0.0f; //get length and angle of line, which defines the shape - float length = Vector2D.Distance(pointGroup[0], pointGroup[segmentsCount - 1]);// getLineLength(pointGroup[0], pointGroup[segmentsCount - 1]); + float length = Vector2D.Distance(pointGroup[0], pointGroup[segmentsCount - 1]); float angle = (float)Math.Atan2(pointGroup[0].y - pointGroup[segmentsCount - 1].y, pointGroup[0].x - pointGroup[segmentsCount - 1].x); float curAngle, diff, segLen; Vector2D p0, p1; //get relative length of every line - for (int i = 1; i < pointGroup.Length - 1; i++) { + for (int i = 1; i < pointGroup.Length - 1; i++) + { p0 = pointGroup[i - 1]; p1 = pointGroup[i]; curAngle = (float)Math.Atan2(p0.y - p1.y, p0.x - p1.x); @@ -519,21 +561,22 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } //this returns relative handle location - private static Vector2D getHandleLocation(Vector2D start, Vector2D end, Vector2D direction) { + private static Vector2D GetHandleLocation(Vector2D start, Vector2D end, Vector2D direction) + { float angle = -(float)Math.Atan2(start.y - end.y, start.x - end.x); float dirAngle = -(float)Math.Atan2(direction.y - start.y, direction.x - start.x); float length = (float)Math.Sqrt(Math.Pow(Math.Abs(start.x - end.x), 2.0) + Math.Pow(Math.Abs(start.y - end.y), 2.0)) * 0.3f; float diff = (angle + Angle2D.PI) - (dirAngle + Angle2D.PI); - if(diff > Angle2D.PI || (diff < 0 && diff > -Angle2D.PI)) - angle += Angle2D.PI; + if(diff > Angle2D.PI || (diff < 0 && diff > -Angle2D.PI)) angle += Angle2D.PI; return new Vector2D((float)(Math.Sin(angle) * length), (float)(Math.Cos(angle) * length)); } //LINE DRAWING //returns true if 2 lines intersect - private static bool linesIntersect(Line line1, Line line2) { + private static bool LinesIntersect(Line line1, Line line2) + { float zn = (line2.End.y - line2.Start.y) * (line1.End.x - line1.Start.x) - (line2.End.x - line2.Start.x) * (line1.End.y - line1.Start.y); float ch1 = (line2.End.x - line2.Start.x) * (line1.Start.y - line2.Start.y) - (line2.End.y - line2.Start.y) * (line1.Start.x - line2.Start.x); float ch2 = (line1.End.x - line1.Start.x) * (line1.Start.y - line2.Start.y) - (line1.End.y - line1.Start.y) * (line1.Start.x - line2.Start.x); @@ -547,25 +590,36 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Line sorting //this gets two arrays of connected points from given lines. Returns true if all went well. - private bool setupPointGroups(List linesList) { + private bool SetupPointGroups(List linesList) + { //find prev/next lines for each line - for (int i = 0; i < linesList.Count; i++) { + for (int i = 0; i < linesList.Count; i++) + { Line curLine = linesList[i]; - for (int c = 0; c < linesList.Count; c++) { - if (c != i) {//don't wanna play with ourselves :) + for (int c = 0; c < linesList.Count; c++) + { + if (c != i) //don't wanna play with ourselves :) + { Line line = linesList[c]; //check start and end points - if (curLine.Start == line.Start) { + if (curLine.Start == line.Start) + { line.Invert(); curLine.Previous = line; - } else if (curLine.Start == line.End) { + } + else if (curLine.Start == line.End) + { curLine.Previous = line; - } else if (curLine.End == line.End) { + } + else if (curLine.End == line.End) + { line.Invert(); curLine.Next = line; - } else if (curLine.End == line.Start) { + } + else if (curLine.End == line.Start) + { curLine.Next = line; } } @@ -576,17 +630,20 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { List> sortedLines = new List>(); //now find start lines - for (int i = 0; i < linesList.Count; i++) { + for (int i = 0; i < linesList.Count; i++) + { Line curLine = linesList[i]; - if (curLine.Previous == null) { //found start + if (curLine.Previous == null) //found start + { //collect points Line l = curLine; List points = new List(); List lines = new List(); points.Add(l.Start); - do { + do + { points.Add(l.End); lines.Add(l); } while ((l = l.Next) != null); @@ -596,20 +653,25 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } } - if (pointGroups.Count != 2) { + if (pointGroups.Count != 2) + { General.Interface.DisplayStatus(StatusType.Warning, "Incorrect number of linedef groups! Expected 2, but got " + pointGroups.Count); return false; } - if (pointGroups[0].Count != pointGroups[1].Count) { + if (pointGroups[0].Count != pointGroups[1].Count) + { General.Interface.DisplayStatus(StatusType.Warning, "Linedefs groups must have equal length! Got " + pointGroups[0].Count + " in first group and " + pointGroups[1].Count + " in second."); return false; } //check if lines from first group intersect with lines from second group - foreach (Line l1 in sortedLines[0]) { - foreach (Line l2 in sortedLines[1]) { - if (linesIntersect(l1, l2)) { + foreach (Line l1 in sortedLines[0]) + { + foreach (Line l2 in sortedLines[1]) + { + if (LinesIntersect(l1, l2)) + { General.Interface.DisplayStatus(StatusType.Warning, "One or more lines from first group intersect with one or more lines from second group!"); return false; } @@ -621,11 +683,13 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { //collect sector properties sectorProps1 = new SectorProperties[sortedLines[0].Count]; - for (int i = 0; i < sortedLines[0].Count; i++ ) { + for (int i = 0; i < sortedLines[0].Count; i++ ) + { sectorProps1[i] = sortedLines[0][i].SectorProperties; } sectorProps2 = new SectorProperties[sortedLines[1].Count]; - for (int i = 0; i < sortedLines[1].Count; i++) { + for (int i = 0; i < sortedLines[1].Count; i++) + { sectorProps2[i] = sortedLines[1][i].SectorProperties; } @@ -633,7 +697,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { Line line1 = new Line(pointGroups[0][0], pointGroups[1][0]); Line line2 = new Line(pointGroups[0][segmentsCount - 1], pointGroups[1][segmentsCount - 1]); - if (linesIntersect(line1, line2)) { + if (LinesIntersect(line1, line2)) + { pointGroups[0].Reverse(); Array.Reverse(sectorProps1); } @@ -655,7 +720,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { /** * Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. */ - private static int easeInSine(int val1, int val2, float delta) { + private static int EaseInSine(int val1, int val2, float delta) + { float f_val1 = val1; float f_val2 = val2 - f_val1; return (int)(-f_val2 * Math.Cos(delta * Angle2D.PIHALF) + f_val2 + f_val1); @@ -664,7 +730,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { /** * Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. */ - private static int easeOutSine(int val1, int val2, float delta) { + private static int EaseOutSine(int val1, int val2, float delta) + { float f_val1 = val1; float f_val2 = val2; return (int)((f_val2 - f_val1) * Math.Sin(delta * Angle2D.PIHALF) + f_val1); @@ -673,14 +740,17 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { /** * Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. */ - private static int easeInOutSine(int val1, int val2, float delta) { + private static int EaseInOutSine(int val1, int val2, float delta) + { float f_val1 = val1; float f_val2 = val2; return (int)(-f_val2 / 2.0f * (Math.Cos(Angle2D.PI * delta) - 1.0f) + f_val1); } - private int intepolateValue(int val1, int val2, float delta, string mode) { - switch (mode) { + private static int IntepolateValue(int val1, int val2, float delta, string mode) + { + switch (mode) + { case BridgeInterpolationMode.HIGHEST: case BridgeInterpolationMode.BRIGHTNESS_HIGHEST: return Math.Max(val1, val2); @@ -693,13 +763,13 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { return (int)(delta * val2 + (1.0f - delta) * val1); case BridgeInterpolationMode.IN_SINE: - return easeInSine(val1, val2, delta); + return EaseInSine(val1, val2, delta); case BridgeInterpolationMode.OUT_SINE: - return easeOutSine(val1, val2, delta); + return EaseOutSine(val1, val2, delta); case BridgeInterpolationMode.IN_OUT_SINE: - return easeInOutSine(val1, val2, delta); + return EaseInOutSine(val1, val2, delta); default: throw new Exception("DrawBezierPathMode.intepolateValue: got unknown mode: '" + mode + "'"); @@ -710,19 +780,23 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Events - private void form_OnSubdivisionChanged(object sender, EventArgs e) { - update(); + private void form_OnSubdivisionChanged(object sender, EventArgs e) + { + Update(); } - private void form_OnOkClick(object sender, EventArgs e) { + private void form_OnOkClick(object sender, EventArgs e) + { FinishDraw(); } - private void form_OnCancelClick(object sender, EventArgs e) { + private void form_OnCancelClick(object sender, EventArgs e) + { OnCancel(); } - private void form_OnFlipClick(object sender, EventArgs e) { + private void form_OnFlipClick(object sender, EventArgs e) + { Array.Reverse(pointGroup1); Array.Reverse(sectorProps1); @@ -731,7 +805,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { controlHandles[0].Position = controlHandles[2].Position; controlHandles[2].Position = p; - update(); + Update(); } #endregion @@ -740,21 +814,22 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { // Finish drawing [BeginAction("finishdraw")] - public void FinishDraw() { + private void FinishDraw() + { // Accept the changes General.Editing.AcceptMode(); } [BeginAction("increasesubdivlevel")] - private void increaseSubdivLevel() { - if (form != null && form.Subdivisions < MAX_SUBDIVISIONS) - form.Subdivisions++; + private void IncreaseSubdivLevel() + { + if (form != null && form.Subdivisions < MAX_SUBDIVISIONS) form.Subdivisions++; } [BeginAction("decreasesubdivlevel")] - private void decreaseSubdivLevel() { - if (form != null && form.Subdivisions > MIN_SUBDIVISIONS) - form.Subdivisions--; + private void DecreaseSubdivLevel() + { + if (form != null && form.Subdivisions > MIN_SUBDIVISIONS) form.Subdivisions--; } #endregion @@ -762,7 +837,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { #region ================== Helper classes - internal struct SectorProperties { + internal struct SectorProperties + { public int FloorHeight; public int CeilingHeight; public int Brightness; @@ -774,18 +850,22 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { { public Vector2D Position; public Vector2D ControlledPoint; //point, to which this handle is assigned - public Vector2D RelativePosition { - get { + public Vector2D RelativePosition + { + get + { return new Vector2D(Position.x - ControlledPoint.x, Position.y - ControlledPoint.y); } - set { + set + { Position = new Vector2D(ControlledPoint.x + value.x, ControlledPoint.y + value.y); } } public ControlHandle Pair; //second handle, to which this handle is paired } - internal class Line { + internal class Line + { public Vector2D Start { get { return start; } } private Vector2D start; @@ -797,24 +877,30 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { public Line Previous; public Line Next; - public Line(Linedef ld) { + public Line(Linedef ld) + { start = new Vector2D((int)ld.Start.Position.x, (int)ld.Start.Position.y); end = new Vector2D((int)ld.End.Position.x, (int)ld.End.Position.y); SectorProperties = new SectorProperties(); - if (ld.Back != null) { + if (ld.Back != null) + { SectorProperties.CeilingHeight = ld.Back.Sector.CeilHeight; SectorProperties.FloorHeight = ld.Back.Sector.FloorHeight; SectorProperties.Brightness = ld.Back.Sector.Brightness; SectorProperties.HighTexture = ld.Back.HighTexture != "-" ? ld.Back.HighTexture : ld.Back.MiddleTexture; SectorProperties.LowTexture = ld.Back.LowTexture != "-" ? ld.Back.LowTexture : ld.Back.MiddleTexture; - }else if(ld.Front != null){ + } + else if(ld.Front != null) + { SectorProperties.CeilingHeight = ld.Front.Sector.CeilHeight; SectorProperties.FloorHeight = ld.Front.Sector.FloorHeight; SectorProperties.Brightness = ld.Front.Sector.Brightness; SectorProperties.HighTexture = ld.Front.HighTexture != "-" ? ld.Front.HighTexture : ld.Front.MiddleTexture; SectorProperties.LowTexture = ld.Front.LowTexture != "-" ? ld.Front.LowTexture : ld.Front.MiddleTexture; - }else{ + } + else + { SectorProperties.CeilingHeight = 128; SectorProperties.FloorHeight = 0; SectorProperties.Brightness = 192; @@ -823,12 +909,14 @@ namespace CodeImp.DoomBuilder.BuilderModes.ClassicModes { } } - public Line(Vector2D start, Vector2D end) { + public Line(Vector2D start, Vector2D end) + { this.start = start; this.end = end; } - public void Invert() { + public void Invert() + { Vector2D s = start; start = end; end = s; diff --git a/Source/Plugins/BuilderModes/ClassicModes/DragGeometryMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DragGeometryMode.cs index 61a93cd4..c1103a21 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DragGeometryMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DragGeometryMode.cs @@ -175,11 +175,12 @@ namespace CodeImp.DoomBuilder.BuilderModes unstableLinesInitialLengths.Add(l.Length); //mxd. Collect selected sectors - if(General.Map.UDMF) { + if(General.Map.UDMF) + { ICollection selectedLines = General.Map.Map.LinedefsFromMarkedVertices(false, true, false); - List affectedSectors = new List(); - foreach(Linedef l in selectedLines) { + foreach(Linedef l in selectedLines) + { if(l.Front != null && l.Front.Sector != null && !affectedSectors.Contains(l.Front.Sector)) affectedSectors.Add(l.Front.Sector); if(l.Back != null && l.Back.Sector != null && !affectedSectors.Contains(l.Back.Sector)) @@ -187,18 +188,19 @@ namespace CodeImp.DoomBuilder.BuilderModes } selectedSectors = new List(); - foreach(Sector s in affectedSectors) { + foreach(Sector s in affectedSectors) + { bool selected = true; - - foreach(Sidedef side in s.Sidedefs) { - if(!selectedLines.Contains(side.Line)) { + foreach(Sidedef side in s.Sidedefs) + { + if(!selectedLines.Contains(side.Line)) + { selected = false; break; } } - if(selected) - selectedSectors.Add(s); + if(selected) selectedSectors.Add(s); } } @@ -428,21 +430,25 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.Map.SnapAllToAccuracy(); //mxd. Update floor/ceiling texture offsets - if(General.Map.UDMF && BuilderPlug.Me.LockSectorTextureOffsetsWhileDragging && selectedSectors.Count > 0) { + if(General.Map.UDMF && BuilderPlug.Me.LockSectorTextureOffsetsWhileDragging && selectedSectors.Count > 0) + { Vector2D offset = dragitemposition - dragitem.Position; - - foreach(Sector s in selectedSectors) { + foreach(Sector s in selectedSectors) + { s.Fields.BeforeFieldsChange(); //update ceiling offset - if(s.LongCeilTexture != MapSet.EmptyLongName) { + if(s.LongCeilTexture != MapSet.EmptyLongName) + { ImageData texture = General.Map.Data.GetFlatImage(s.CeilTexture); - if(texture != null) { + if(texture != null) + { float scaleX = s.Fields.GetValue("xscaleceiling", 1.0f); float scaleY = s.Fields.GetValue("yscaleceiling", 1.0f); - if(scaleX != 0 && scaleY != 0) { + if(scaleX != 0 && scaleY != 0) + { Vector2D ceilOffset = new Vector2D(offset.x, -offset.y).GetRotated(-Angle2D.DegToRad((int)s.Fields.GetValue("rotationceiling", 0f))); ceilOffset.x += s.Fields.GetValue("xpanningceiling", 0f); ceilOffset.y += s.Fields.GetValue("ypanningceiling", 0f); @@ -464,14 +470,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } //update floor offset - if(s.LongFloorTexture != MapSet.EmptyLongName) { + if(s.LongFloorTexture != MapSet.EmptyLongName) + { ImageData texture = General.Map.Data.GetFlatImage(s.FloorTexture); - - if(texture != null) { + if(texture != null) + { float scaleX = s.Fields.GetValue("xscalefloor", 1.0f); float scaleY = s.Fields.GetValue("yscalefloor", 1.0f); - - if(scaleX != 0 && scaleY != 0) { + if(scaleX != 0 && scaleY != 0) + { Vector2D floorOffset = new Vector2D(offset.x, -offset.y).GetRotated(-Angle2D.DegToRad((int)s.Fields.GetValue("rotationfloor", 0f))); floorOffset.x += s.Fields.GetValue("xpanningfloor", 0f); floorOffset.y += s.Fields.GetValue("ypanningfloor", 0f); diff --git a/Source/Plugins/BuilderModes/ClassicModes/DragLinedefsMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DragLinedefsMode.cs index 06c28312..a91970a6 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DragLinedefsMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DragLinedefsMode.cs @@ -156,7 +156,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Render things - if(renderer.StartThings(true)) { + if(renderer.StartThings(true)) + { renderer.RenderThingSet(General.Map.ThingsFilter.HiddenThings, Presentation.THINGS_HIDDEN_ALPHA); renderer.RenderThingSet(unselectedthings, 1.0f); renderer.RenderThingSet(selectedthings, 1.0f); diff --git a/Source/Plugins/BuilderModes/ClassicModes/DragSectorsMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DragSectorsMode.cs index ac0c8e2e..4cf86004 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DragSectorsMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DragSectorsMode.cs @@ -168,7 +168,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Render things - if(renderer.StartThings(true)) { + if(renderer.StartThings(true)) + { renderer.RenderThingSet(General.Map.ThingsFilter.HiddenThings, Presentation.THINGS_HIDDEN_ALPHA); renderer.RenderThingSet(unselectedthings, 1.0f); renderer.RenderThingSet(selectedthings, 1.0f); diff --git a/Source/Plugins/BuilderModes/ClassicModes/DragThingsMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DragThingsMode.cs index c6133b6e..ea5fd248 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DragThingsMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DragThingsMode.cs @@ -73,7 +73,8 @@ namespace CodeImp.DoomBuilder.BuilderModes public PointF Position = PointF.Empty; public bool Active; - public AlignData(Thing t){ + public AlignData(Thing t) + { InitialAngle = t.AngleDoom; InitialHeight = t.Position.z; } @@ -354,7 +355,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Move geometry back to original position MoveThingsRelative(new Vector2D(0f, 0f), false, false, false); - if(alignData != null && alignData.Active){ + if(alignData != null && alignData.Active) + { alignData.CurrentAngle = dragitem.AngleDoom; //mxd dragitem.Rotate(alignData.InitialAngle); alignData.CurrentHeight = dragitem.Position.z; //mxd @@ -365,13 +367,16 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Drag things"); // Move selected geometry to final position - if(alignData != null && alignData.Active){//mxd + if(alignData != null && alignData.Active) //mxd + { if(!alignData.Position.IsEmpty) dragitem.Move(alignData.Position.X, alignData.Position.Y, alignData.CurrentHeight); else dragitem.Move(dragitem.Position.x, dragitem.Position.y, alignData.CurrentHeight); dragitem.Rotate(alignData.CurrentAngle); - } else { + } + else + { MoveThingsRelative(mousemappos - dragstartmappos, snaptogrid, snaptogridincrement, snaptonearest); } @@ -415,27 +420,34 @@ namespace CodeImp.DoomBuilder.BuilderModes snaptogridincrement = General.Interface.AltState; //mxd //mxd. Snap to nearest linedef - if(selectedthings.Count == 1 && dragitem.IsModel && snaptonearest && MoveThingsRelative(mousemappos - dragstartmappos, snaptogrid, snaptogridincrement, false)) { + if(selectedthings.Count == 1 && dragitem.IsModel && snaptonearest && MoveThingsRelative(mousemappos - dragstartmappos, snaptogrid, snaptogridincrement, false)) + { Linedef l = General.Map.Map.NearestLinedefRange(oldpositions[0] + mousemappos - dragstartmappos, BuilderPlug.Me.StitchRange / renderer.Scale); bool restoreSettings = false; - if(alignData == null) - alignData = new AlignData(dragitem); + if(alignData == null) alignData = new AlignData(dragitem); - if(l != null) { - if(Tools.TryAlignThingToLine(dragitem, l)) { + if(l != null) + { + if(Tools.TryAlignThingToLine(dragitem, l)) + { dragitem.SnapToAccuracy(); alignData.Position = new PointF(dragitem.Position.x, dragitem.Position.y); alignData.Active = true; - } else if(dragitem.AngleDoom != alignData.InitialAngle) { //restore initial angle? + } + else if(dragitem.AngleDoom != alignData.InitialAngle) //restore initial angle? + { restoreSettings = true; } - } else if(dragitem.AngleDoom != alignData.InitialAngle) { //restore initial angle? + } + else if(dragitem.AngleDoom != alignData.InitialAngle) //restore initial angle? + { restoreSettings = true; } - if(restoreSettings) { + if(restoreSettings) + { alignData.Position = PointF.Empty; alignData.Active = false; dragitem.Rotate(alignData.InitialAngle); diff --git a/Source/Plugins/BuilderModes/ClassicModes/DragVerticesMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DragVerticesMode.cs index 30544a41..3004eb97 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DragVerticesMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DragVerticesMode.cs @@ -144,7 +144,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Render things - if(renderer.StartThings(true)) { + if(renderer.StartThings(true)) + { renderer.RenderThingSet(General.Map.ThingsFilter.HiddenThings, Presentation.THINGS_HIDDEN_ALPHA); renderer.RenderThingSet(unselectedthings, 1.0f); renderer.RenderThingSet(selectedthings, 1.0f); diff --git a/Source/Plugins/BuilderModes/ClassicModes/DrawCurveMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DrawCurveMode.cs index 214b473b..55ebd3d1 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DrawCurveMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DrawCurveMode.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using CodeImp.DoomBuilder.Actions; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.Map; @@ -41,7 +42,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Constructor/Disposer - public DrawCurveMode() { + public DrawCurveMode() + { hintLabel = new HintLabel(); //Options docker @@ -49,10 +51,9 @@ namespace CodeImp.DoomBuilder.BuilderModes panel.OnValueChanged += OptionsPanelOnValueChanged; } - public override void Dispose() { - if(!isdisposed && hintLabel != null) - hintLabel.Dispose(); - + public override void Dispose() + { + if(!isdisposed && hintLabel != null) hintLabel.Dispose(); base.Dispose(); } @@ -60,7 +61,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods - protected override void Update() { + protected override void Update() + { PixelColor stitchcolor = General.Colors.Highlight; PixelColor losecolor = General.Colors.Selection; PixelColor color; @@ -76,22 +78,20 @@ namespace CodeImp.DoomBuilder.BuilderModes SetLabelPosition(labels[labels.Count - 1], points[points.Count - 1].pos, curp.pos); // Render drawing lines - if(renderer.StartOverlay(true)) { + if(renderer.StartOverlay(true)) + { // Go for all points to draw lines - if(points.Count > 0) { + if(points.Count > 0) + { //update curve List verts = new List(); - - for(int i = 0; i < points.Count; i++) - verts.Add(points[i].pos); - - if(curp.pos != verts[verts.Count-1]) - verts.Add(curp.pos); - + for(int i = 0; i < points.Count; i++) verts.Add(points[i].pos); + if(curp.pos != verts[verts.Count-1]) verts.Add(curp.pos); curve = CurveTools.CurveThroughPoints(verts, 0.5f, 0.75f, segmentLength); // Render lines - for(int i = 1; i < curve.Shape.Count; i++) { + for(int i = 1; i < curve.Shape.Count; i++) + { // Determine line color color = snaptonearest ? stitchcolor : losecolor; @@ -100,7 +100,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //render "inactive" vertices - for(int i = 1; i < curve.Shape.Count - 1; i++) { + for(int i = 1; i < curve.Shape.Count - 1; i++) + { // Determine vertex color color = !snaptonearest ? stitchcolor : losecolor; @@ -109,9 +110,11 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(points.Count > 0) { + if(points.Count > 0) + { // Render vertices - for(int i = 0; i < points.Count; i++) { + for(int i = 0; i < points.Count; i++) + { // Determine vertex color color = points[i].stitch ? stitchcolor : losecolor; @@ -127,8 +130,7 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.RenderRectangleFilled(new RectangleF(curp.pos.x - vsize, curp.pos.y - vsize, vsize * 2.0f, vsize * 2.0f), color, true); // Go for all labels - foreach(LineLengthLabel l in labels) - renderer.RenderText(l.TextLabel); + foreach(LineLengthLabel l in labels) renderer.RenderText(l.TextLabel); //Render info label hintLabel.Start = new Vector2D(mousemappos.x + (32 / renderer.Scale), mousemappos.y - (16 / renderer.Scale)); @@ -148,7 +150,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Events - public override void OnEngage() { + public override void OnEngage() + { base.OnEngage(); //setup settings panel @@ -156,18 +159,20 @@ namespace CodeImp.DoomBuilder.BuilderModes panel.Register(); } - public override void OnAccept() { + public override void OnAccept() + { Cursor.Current = Cursors.AppStarting; - General.Settings.FindDefaultDrawSettings(); // When points have been drawn - if(points.Count > 0) { + if(points.Count > 0) + { // Make undo for the draw General.Map.UndoRedo.CreateUndo("Curve draw"); // Make an analysis and show info - string[] adjectives = new[] { + string[] adjectives = new[] + { "beautiful", "lovely", "romantic", "stylish", "cheerful", "comical", "awesome", "accurate", "adorable", "adventurous", "attractive", "cute", "elegant", "glamorous", "gorgeous", "handsome", "magnificent", "unusual", @@ -181,22 +186,28 @@ namespace CodeImp.DoomBuilder.BuilderModes List verts = new List(); //if we have a curve... - if(points.Count > 2){ + if(points.Count > 2) + { //is it a closed curve? int lastPoint; - if(points[0].pos == points[points.Count - 1].pos) { + if(points[0].pos == points[points.Count - 1].pos) + { lastPoint = curve.Segments.Count; - } else { + } + else + { lastPoint = curve.Segments.Count - 1; } - for(int i = 0; i < lastPoint; i++) { + for(int i = 0; i < lastPoint; i++) + { int next = (i == curve.Segments.Count - 1 ? 0 : i + 1); bool stitch = points[i].stitch && points[next].stitch; bool stitchline = points[i].stitchline && points[next].stitchline; //add segment points except the last one - for(int c = 0; c < curve.Segments[i].Points.Length - 1; c++) { + for(int c = 0; c < curve.Segments[i].Points.Length - 1; c++) + { DrawnVertex dv = new DrawnVertex(); dv.pos = curve.Segments[i].Points[c]; dv.stitch = stitch; @@ -211,7 +222,9 @@ namespace CodeImp.DoomBuilder.BuilderModes end.stitch = verts[verts.Count - 1].stitch; end.stitchline = verts[verts.Count - 1].stitchline; verts.Add(end); - }else{ + } + else + { verts = points; } @@ -253,17 +266,20 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Editing.ChangeMode(General.Editing.PreviousStableMode.Name); } - public override void OnDisengage() { + public override void OnDisengage() + { base.OnDisengage(); panel.Unregister(); } - private void OptionsPanelOnValueChanged(object sender, EventArgs eventArgs) { + private void OptionsPanelOnValueChanged(object sender, EventArgs eventArgs) + { segmentLength = panel.SegmentLength; Update(); } - public override void OnHelp() { + public override void OnHelp() + { General.ShowHelp("/gzdb/features/classic_modes/mode_drawcurve.html"); } @@ -272,26 +288,28 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Actions [BeginAction("increasesubdivlevel")] - protected virtual void increaseSubdivLevel() { - if(segmentLength < maxSegmentLength) { + protected virtual void IncreaseSubdivLevel() + { + if(segmentLength < maxSegmentLength) + { int increment = Math.Max(minSegmentLength, segmentLength / 32 * 16); segmentLength += increment; - if(segmentLength > maxSegmentLength) - segmentLength = maxSegmentLength; + if(segmentLength > maxSegmentLength) segmentLength = maxSegmentLength; panel.SegmentLength = segmentLength; Update(); } } [BeginAction("decreasesubdivlevel")] - protected virtual void decreaseSubdivLevel() { - if(segmentLength > minSegmentLength) { + protected virtual void DecreaseSubdivLevel() + { + if(segmentLength > minSegmentLength) + { int increment = Math.Max(minSegmentLength, segmentLength / 32 * 16); segmentLength -= increment; - if(segmentLength < minSegmentLength) - segmentLength = minSegmentLength; + if(segmentLength < minSegmentLength) segmentLength = minSegmentLength; panel.SegmentLength = segmentLength; Update(); } diff --git a/Source/Plugins/BuilderModes/ClassicModes/DrawEllipseMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DrawEllipseMode.cs index 6980981c..1e6eaf57 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DrawEllipseMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DrawEllipseMode.cs @@ -28,7 +28,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Constructor - public DrawEllipseMode() { + public DrawEllipseMode() + { undoName = "Ellipse draw"; shapeName = "ellipse"; } @@ -37,7 +38,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Settings panel - override protected void setupInterface() { + override protected void SetupInterface() + { maxSubdivisions = 512; minSubdivisions = 6; @@ -50,13 +52,15 @@ namespace CodeImp.DoomBuilder.BuilderModes panel.OnValueChanged += OptionsPanelOnValueChanged; } - override protected void addInterface() { + override protected void AddInterface() + { panel.Register(); bevelWidth = panel.Spikiness; subdivisions = panel.Subdivisions; } - override protected void removeInterface() { + override protected void RemoveInterface() + { panel.Unregister(); } @@ -64,7 +68,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods - override protected Vector2D[] getShape(Vector2D pStart, Vector2D pEnd) { + override protected Vector2D[] GetShape(Vector2D pStart, Vector2D pEnd) + { //no shape if (pEnd.x == pStart.x && pEnd.y == pStart.y) return new Vector2D[0]; @@ -72,9 +77,12 @@ namespace CodeImp.DoomBuilder.BuilderModes if(pEnd.x == pStart.x || pEnd.y == pStart.y) return new[] { pStart, pEnd }; //got shape - if (bevelWidth < 0) { + if (bevelWidth < 0) + { currentBevelWidth = -Math.Min(Math.Abs(bevelWidth), Math.Min(width, height) / 2) + 1; - } else { + } + else + { currentBevelWidth = bevelWidth; } @@ -89,11 +97,15 @@ namespace CodeImp.DoomBuilder.BuilderModes float angleStep = -Angle2D.PI / subdivisions * 2; int px, py; - for (int i = 0; i < subdivisions; i++) { - if (doBevel) { + for (int i = 0; i < subdivisions; i++) + { + if (doBevel) + { px = (int)(center.x - (float)Math.Sin(curAngle) * (hw + currentBevelWidth)); py = (int)(center.y - (float)Math.Cos(curAngle) * (hh + currentBevelWidth)); - } else { + } + else + { px = (int)(center.x - (float)Math.Sin(curAngle) * hw); py = (int)(center.y - (float)Math.Cos(curAngle) * hh); } @@ -106,7 +118,8 @@ namespace CodeImp.DoomBuilder.BuilderModes return shape; } - protected override string getHintText() { + protected override string GetHintText() + { return "BVL: " + bevelWidth + "; VERTS: " + subdivisions; } @@ -114,13 +127,15 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Events - private void OptionsPanelOnValueChanged(object sender, EventArgs eventArgs) { + private void OptionsPanelOnValueChanged(object sender, EventArgs eventArgs) + { bevelWidth = panel.Spikiness; subdivisions = Math.Min(maxSubdivisions, panel.Subdivisions); Update(); } - public override void OnHelp() { + public override void OnHelp() + { General.ShowHelp("/gzdb/features/classic_modes/mode_drawellipse.html"); } @@ -128,32 +143,40 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Actions - override protected void increaseSubdivLevel() { - if(maxSubdivisions - subdivisions > 1) { + override protected void IncreaseSubdivLevel() + { + if(maxSubdivisions - subdivisions > 1) + { subdivisions += 2; panel.Subdivisions = subdivisions; Update(); } } - override protected void decreaseSubdivLevel() { - if (subdivisions - minSubdivisions > 1) { + override protected void DecreaseSubdivLevel() + { + if (subdivisions - minSubdivisions > 1) + { subdivisions -= 2; panel.Subdivisions = subdivisions; Update(); } } - protected override void increaseBevel() { - if(points.Count < 2 || currentBevelWidth == bevelWidth || bevelWidth < 0) { + protected override void IncreaseBevel() + { + if(points.Count < 2 || currentBevelWidth == bevelWidth || bevelWidth < 0) + { bevelWidth = Math.Min(bevelWidth + General.Map.Grid.GridSize, panel.MaxSpikiness); panel.Spikiness = bevelWidth; Update(); } } - protected override void decreaseBevel() { - if(bevelWidth > 0 || currentBevelWidth <= bevelWidth + 1) { + protected override void DecreaseBevel() + { + if(bevelWidth > 0 || currentBevelWidth <= bevelWidth + 1) + { bevelWidth = Math.Max(bevelWidth - General.Map.Grid.GridSize, panel.MinSpikiness); panel.Spikiness = bevelWidth; Update(); diff --git a/Source/Plugins/BuilderModes/ClassicModes/DrawGeometryMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DrawGeometryMode.cs index 08b43653..2023ac8f 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DrawGeometryMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DrawGeometryMode.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Windows.Forms; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Windows; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Rendering; @@ -408,7 +409,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if((Math.Abs(delta.x) <= 0.001f) && (Math.Abs(delta.y) <= 0.001f)) { //mxd. Seems... logical? - if (points.Count == 2) { + if (points.Count == 2) + { OnCancel(); return true; } @@ -462,7 +464,6 @@ namespace CodeImp.DoomBuilder.BuilderModes public override void OnAccept() { Cursor.Current = Cursors.AppStarting; - General.Settings.FindDefaultDrawSettings(); // When points have been drawn @@ -472,7 +473,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Line draw"); // Make an analysis and show info - string[] adjectives = new string[] + string[] adjectives = new[] { "beautiful", "lovely", "romantic", "stylish", "cheerful", "comical", "awesome", "accurate", "adorable", "adventurous", "attractive", "cute", "elegant", "glamorous", "gorgeous", "handsome", "magnificent", "unusual", diff --git a/Source/Plugins/BuilderModes/ClassicModes/DrawGridMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DrawGridMode.cs index c8d84be8..8565b4a2 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DrawGridMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DrawGridMode.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using CodeImp.DoomBuilder.Actions; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.Map; @@ -200,8 +201,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if(points.Count == 1) { - updateReferencePoints(points[0], curp); - List shapes = getShapes(start, end); + UpdateReferencePoints(points[0], curp); + List shapes = GetShapes(start, end); //render shape foreach (Vector2D[] shape in shapes) @@ -285,8 +286,8 @@ namespace CodeImp.DoomBuilder.BuilderModes newpoint.pos -= gridoffset; // Create vertices for final shape. - updateReferencePoints(points[0], newpoint); - List shapes = getShapes(start, end); + UpdateReferencePoints(points[0], newpoint); + List shapes = GetShapes(start, end); foreach (Vector2D[] shape in shapes) { @@ -308,7 +309,7 @@ namespace CodeImp.DoomBuilder.BuilderModes return true; } - private List getShapes(Vector2D s, Vector2D e) + private List GetShapes(Vector2D s, Vector2D e) { //no shape if(s == e) return new List(); @@ -422,7 +423,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //update bottom-left and top-right points, which define drawing shape - private void updateReferencePoints(DrawnVertex p1, DrawnVertex p2) + private void UpdateReferencePoints(DrawnVertex p1, DrawnVertex p2) { if(!p1.pos.IsFinite() || !p2.pos.IsFinite()) return; @@ -457,7 +458,7 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Actions [BeginAction("increasebevel")] - protected void increaseBevel() + protected void IncreaseBevel() { if(!gridlock && (points.Count < 2 || horizontalSlices < width - 2) && horizontalSlices - 1 < panel.MaxHorizontalSlices) { @@ -468,7 +469,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("decreasebevel")] - protected void decreaseBevel() + protected void DecreaseBevel() { if(!gridlock && horizontalSlices > 1) { @@ -479,7 +480,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("increasesubdivlevel")] - protected void increaseSubdivLevel() + protected void IncreaseSubdivLevel() { if(!gridlock && (points.Count < 2 || verticalSlices < height - 2) && verticalSlices - 1 < panel.MaxVerticalSlices) { @@ -490,7 +491,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("decreasesubdivlevel")] - protected void decreaseSubdivLevel() + protected void DecreaseSubdivLevel() { if(!gridlock && verticalSlices > 1) { diff --git a/Source/Plugins/BuilderModes/ClassicModes/DrawRectangleMode.cs b/Source/Plugins/BuilderModes/ClassicModes/DrawRectangleMode.cs index 3bfa25b6..f66b8b02 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/DrawRectangleMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/DrawRectangleMode.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Rendering; using CodeImp.DoomBuilder.Geometry; @@ -51,12 +52,14 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Constructor/Disposer - public DrawRectangleMode() { + public DrawRectangleMode() + { snaptogrid = true; - setupInterface(); + SetupInterface(); } - public override void Dispose() { + public override void Dispose() + { if (!isdisposed && hintLabel != null) hintLabel.Dispose(); @@ -67,7 +70,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Settings panel - protected virtual void setupInterface() { + protected virtual void SetupInterface() + { maxSubdivisions = 16; //Add options docker @@ -79,13 +83,15 @@ namespace CodeImp.DoomBuilder.BuilderModes panel.OnValueChanged += OptionsPanelOnValueChanged; } - protected virtual void addInterface() { + protected virtual void AddInterface() + { panel.Register(); bevelWidth = panel.BevelWidth; subdivisions = panel.Subdivisions; } - protected virtual void removeInterface() { + protected virtual void RemoveInterface() + { panel.Unregister(); } @@ -93,7 +99,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods - override protected void Update() { + override protected void Update() + { PixelColor stitchcolor = General.Colors.Highlight; PixelColor losecolor = General.Colors.Selection; @@ -104,12 +111,14 @@ namespace CodeImp.DoomBuilder.BuilderModes float vsize = (renderer.VertexSize + 1.0f) / renderer.Scale; // Render drawing lines - if (renderer.StartOverlay(true)) { + if (renderer.StartOverlay(true)) + { PixelColor color = snaptonearest ? stitchcolor : losecolor; - if (points.Count == 1) { - updateReferencePoints(points[0], curp); - Vector2D[] shape = getShape(start, end); + if (points.Count == 1) + { + UpdateReferencePoints(points[0], curp); + Vector2D[] shape = GetShape(start, end); //render shape for (int i = 1; i < shape.Length; i++) @@ -121,19 +130,22 @@ namespace CodeImp.DoomBuilder.BuilderModes //and labels Vector2D[] labelCoords = new[] { start, new Vector2D(end.x, start.y), end, new Vector2D(start.x, end.y), start }; - for (int i = 1; i < 5; i++) { + for (int i = 1; i < 5; i++) + { SetLabelPosition(labels[i - 1], labelCoords[i], labelCoords[i - 1]); renderer.RenderText(labels[i - 1].TextLabel); } //got beveled corners? - if (shape.Length > 5) { + if (shape.Length > 5) + { //render hint - if (width > 64 * vsize && height > 16 * vsize) { + if (width > 64 * vsize && height > 16 * vsize) + { float vPos = start.y + height / 2.0f; hintLabel.Start = new Vector2D(start.x, vPos); hintLabel.End = new Vector2D(end.x, vPos); - hintLabel.Text = getHintText(); + hintLabel.Text = GetHintText(); renderer.RenderText(hintLabel.TextLabel); } @@ -141,7 +153,9 @@ namespace CodeImp.DoomBuilder.BuilderModes for (int i = 0; i < 4; i++) renderer.RenderRectangleFilled(new RectangleF(labelCoords[i].x - vsize, labelCoords[i].y - vsize, vsize * 2.0f, vsize * 2.0f), General.Colors.InfoLine, true); } - } else { + } + else + { // Render vertex at cursor renderer.RenderRectangleFilled(new RectangleF(curp.pos.x - vsize, curp.pos.y - vsize, vsize * 2.0f, vsize * 2.0f), color, true); } @@ -154,21 +168,25 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.Present(); } - protected virtual Vector2D[] getShape(Vector2D pStart, Vector2D pEnd) { + protected virtual Vector2D[] GetShape(Vector2D pStart, Vector2D pEnd) + { //no shape - if (pStart == pEnd) { + if (pStart == pEnd) + { currentBevelWidth = 0; return new Vector2D[0]; } //line - if(pEnd.x == pStart.x || pEnd.y == pStart.y) { + if(pEnd.x == pStart.x || pEnd.y == pStart.y) + { currentBevelWidth = 0; return new[] { pStart, pEnd }; } //no corners - if (bevelWidth == 0) { + if (bevelWidth == 0) + { currentBevelWidth = 0; return new[] { pStart, new Vector2D((int)pStart.x, (int)pEnd.y), pEnd, new Vector2D((int)pEnd.x, (int)pStart.y), pStart }; } @@ -177,7 +195,8 @@ namespace CodeImp.DoomBuilder.BuilderModes bool reverse = false; currentBevelWidth = Math.Min(Math.Abs(bevelWidth), Math.Min(width, height) / 2); - if (bevelWidth < 0) { + if (bevelWidth < 0) + { currentBevelWidth *= -1; reverse = true; } @@ -185,16 +204,16 @@ namespace CodeImp.DoomBuilder.BuilderModes List shape = new List(); //top-left corner - shape.AddRange(getCornerPoints(pStart, currentBevelWidth, currentBevelWidth, !reverse)); + shape.AddRange(GetCornerPoints(pStart, currentBevelWidth, currentBevelWidth, !reverse)); //top-right corner - shape.AddRange(getCornerPoints(new Vector2D(pEnd.x, pStart.y), -currentBevelWidth, currentBevelWidth, reverse)); + shape.AddRange(GetCornerPoints(new Vector2D(pEnd.x, pStart.y), -currentBevelWidth, currentBevelWidth, reverse)); //bottom-right corner - shape.AddRange(getCornerPoints(pEnd, -currentBevelWidth, -currentBevelWidth, !reverse)); + shape.AddRange(GetCornerPoints(pEnd, -currentBevelWidth, -currentBevelWidth, !reverse)); //bottom-left corner - shape.AddRange(getCornerPoints(new Vector2D(pStart.x, pEnd.y), currentBevelWidth, -currentBevelWidth, reverse)); + shape.AddRange(GetCornerPoints(new Vector2D(pStart.x, pEnd.y), currentBevelWidth, -currentBevelWidth, reverse)); //closing point shape.Add(shape[0]); @@ -202,7 +221,8 @@ namespace CodeImp.DoomBuilder.BuilderModes return shape.ToArray(); } - private Vector2D[] getCornerPoints(Vector2D startPoint, int bevel_width, int bevel_height, bool reverse) { + private Vector2D[] GetCornerPoints(Vector2D startPoint, int bevel_width, int bevel_height, bool reverse) + { Vector2D[] points; Vector2D center = (bevelWidth > 0 ? new Vector2D(startPoint.x + bevel_width, startPoint.y + bevel_height) : startPoint); float curAngle = Angle2D.PI; @@ -211,7 +231,8 @@ namespace CodeImp.DoomBuilder.BuilderModes points = new Vector2D[steps]; float stepAngle = Angle2D.PIHALF / (subdivisions + 1); - for (int i = 0; i < steps; i++) { + for (int i = 0; i < steps; i++) + { points[i] = new Vector2D(center.x + (float)Math.Sin(curAngle) * bevel_width, center.y + (float)Math.Cos(curAngle) * bevel_height); curAngle += stepAngle; } @@ -220,26 +241,34 @@ namespace CodeImp.DoomBuilder.BuilderModes return points; } - protected virtual string getHintText() { + protected virtual string GetHintText() + { return "BVL: " + bevelWidth + "; SUB: " + subdivisions; } //update top-left and bottom-right points, which define drawing shape - protected void updateReferencePoints(DrawnVertex p1, DrawnVertex p2) { + private void UpdateReferencePoints(DrawnVertex p1, DrawnVertex p2) + { if(!p1.pos.IsFinite() || !p2.pos.IsFinite()) return; - if (p1.pos.x < p2.pos.x) { + if (p1.pos.x < p2.pos.x) + { start.x = p1.pos.x; end.x = p2.pos.x; - } else { + } + else + { start.x = p2.pos.x; end.x = p1.pos.x; } - if (p1.pos.y < p2.pos.y) { + if (p1.pos.y < p2.pos.y) + { start.y = p1.pos.y; end.y = p2.pos.y; - } else { + } + else + { start.y = p2.pos.y; end.y = p1.pos.y; } @@ -249,7 +278,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This draws a point at a specific location - override public bool DrawPointAt(Vector2D pos, bool stitch, bool stitchline) { + override public bool DrawPointAt(Vector2D pos, bool stitch, bool stitchline) + { if (pos.x < General.Map.Config.LeftBoundary || pos.x > General.Map.Config.RightBoundary || pos.y > General.Map.Config.TopBoundary || pos.y < General.Map.Config.BottomBoundary) return false; @@ -260,28 +290,33 @@ namespace CodeImp.DoomBuilder.BuilderModes newpoint.stitchline = stitchline; points.Add(newpoint); - if (points.Count == 1) { //add point and labels + if (points.Count == 1) //add point and labels + { labels.AddRange(new[] { new LineLengthLabel(false), new LineLengthLabel(false), new LineLengthLabel(false), new LineLengthLabel(false) }); hintLabel = new HintLabel(); Update(); - } else if (points[0].pos == points[1].pos) { //nothing is drawn + } + else if (points[0].pos == points[1].pos) //nothing is drawn + { points = new List(); FinishDraw(); - } else { + } + else + { //create vertices for final shape. - updateReferencePoints(points[0], newpoint); + UpdateReferencePoints(points[0], newpoint); points = new List(); //clear points - Vector2D[] shape = getShape(start, end); + Vector2D[] shape = GetShape(start, end); - for (int i = 0; i < shape.Length; i++) - base.DrawPointAt(shape[i], true, true); + foreach (Vector2D t in shape) base.DrawPointAt(t, true, true); FinishDraw(); } return true; } - override public void RemovePoint() { + override public void RemovePoint() + { if (points.Count > 0) points.RemoveAt(points.Count - 1); if (labels.Count > 0) labels = new List(); Update(); @@ -291,22 +326,26 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Events - public override void OnEngage() { + public override void OnEngage() + { base.OnEngage(); - addInterface(); + AddInterface(); } - public override void OnDisengage() { - removeInterface(); + public override void OnDisengage() + { + RemoveInterface(); base.OnDisengage(); } - override public void OnAccept() { + override public void OnAccept() + { Cursor.Current = Cursors.AppStarting; General.Settings.FindDefaultDrawSettings(); // When we have a rectangle or a line - if(points.Count > 4 || points.Count == 2) { + if(points.Count > 4 || points.Count == 2) + { // Make undo for the draw General.Map.UndoRedo.CreateUndo(undoName); @@ -315,10 +354,11 @@ namespace CodeImp.DoomBuilder.BuilderModes string word = adjectives[new Random().Next(adjectives.Length - 1)]; string a = (word[0] == 'u' ? "an " : "a "); - General.Interface.DisplayStatus(StatusType.Action, "Created " + a + word + " " + shapeName+"."); + General.Interface.DisplayStatus(StatusType.Action, "Created " + a + word + " " + shapeName + "."); // Make the drawing - if (!Tools.DrawLines(points, true, BuilderPlug.Me.AutoAlignTextureOffsetsOnCreate)) { + if (!Tools.DrawLines(points, true, BuilderPlug.Me.AutoAlignTextureOffsetsOnCreate)) + { // Drawing failed // NOTE: I have to call this twice, because the first time only cancels this volatile mode General.Map.UndoRedo.WithdrawUndo(); @@ -354,11 +394,13 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Editing.ChangeMode(General.Editing.PreviousStableMode.Name); } - public override void OnHelp() { + public override void OnHelp() + { General.ShowHelp("/gzdb/features/classic_modes/mode_drawrect.html"); } - private void OptionsPanelOnValueChanged(object sender, EventArgs eventArgs) { + private void OptionsPanelOnValueChanged(object sender, EventArgs eventArgs) + { bevelWidth = panel.BevelWidth; subdivisions = panel.Subdivisions; Update(); @@ -369,8 +411,10 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Actions [BeginAction("increasesubdivlevel")] - protected virtual void increaseSubdivLevel() { - if (subdivisions < maxSubdivisions) { + protected virtual void IncreaseSubdivLevel() + { + if (subdivisions < maxSubdivisions) + { subdivisions++; panel.Subdivisions = subdivisions; Update(); @@ -378,8 +422,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("decreasesubdivlevel")] - protected virtual void decreaseSubdivLevel() { - if (subdivisions > minSubdivisions) { + protected virtual void DecreaseSubdivLevel() + { + if (subdivisions > minSubdivisions) + { subdivisions--; panel.Subdivisions = subdivisions; Update(); @@ -387,8 +433,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("increasebevel")] - protected virtual void increaseBevel() { - if (points.Count < 2 || currentBevelWidth == bevelWidth || bevelWidth < 0) { + protected virtual void IncreaseBevel() + { + if (points.Count < 2 || currentBevelWidth == bevelWidth || bevelWidth < 0) + { bevelWidth = Math.Min(bevelWidth + General.Map.Grid.GridSize, panel.MaxBevelWidth); panel.BevelWidth = bevelWidth; Update(); @@ -396,8 +444,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("decreasebevel")] - protected virtual void decreaseBevel() { - if (currentBevelWidth == bevelWidth || bevelWidth > 0) { + protected virtual void DecreaseBevel() + { + if (currentBevelWidth == bevelWidth || bevelWidth > 0) + { bevelWidth = Math.Max(bevelWidth - General.Map.Grid.GridSize, panel.MinBevelWidth); panel.BevelWidth = bevelWidth; Update(); diff --git a/Source/Plugins/BuilderModes/ClassicModes/EditSelectionMode.cs b/Source/Plugins/BuilderModes/ClassicModes/EditSelectionMode.cs index df4ffee6..d53c86b3 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/EditSelectionMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/EditSelectionMode.cs @@ -158,7 +158,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Another constructor - public EditSelectionMode(bool pasting) { + public EditSelectionMode(bool pasting) + { // Initialize this.pasting = pasting; this.mode = ModifyMode.None; @@ -962,8 +963,9 @@ namespace CodeImp.DoomBuilder.BuilderModes if((t.Position.x + t.Size) > right.x) right.x = t.Position.x + t.Size; if((t.Position.y + t.Size) > right.y) right.y = t.Position.y + t.Size; - //mxd - if (!fixedrotationthingtypes.Contains(t.Type)) { + + if (!fixedrotationthingtypes.Contains(t.Type)) //mxd + { ThingTypeInfo tti = General.Map.Data.GetThingInfoEx(t.Type); if (tti != null && tti.FixedRotation) fixedrotationthingtypes.Add(t.Type); } @@ -1189,7 +1191,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Go for all sidedes in the new geometry List newsides = General.Map.Map.GetMarkedSidedefs(true); - foreach (Sidedef s in newsides) { + foreach (Sidedef s in newsides) + { // Connected to a virtual sector? if(s.Marked && s.Sector.Fields.ContainsKey(MapSet.VirtualSectorField)) { @@ -1207,7 +1210,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Find out in which sector this was pasted Vector2D testpoint = s.Line.GetSidePoint(!s.IsFront); Linedef nl = MapSet.NearestLinedef(General.Map.Map.GetMarkedLinedefs(false), testpoint); - if(nl != null) { + if(nl != null) + { Sidedef joinsidedef = (nl.SideOfLine(testpoint) <= 0 ? nl.Front : nl.Back); // Join? diff --git a/Source/Plugins/BuilderModes/ClassicModes/LinedefsMode.cs b/Source/Plugins/BuilderModes/ClassicModes/LinedefsMode.cs index 13e099f2..54d3acaf 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/LinedefsMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/LinedefsMode.cs @@ -180,13 +180,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void alignTextureToLine(bool alignFloors, bool alignToFrontSide) { + private void AlignTextureToLine(bool alignFloors, bool alignToFrontSide) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0 && highlighted != null && !highlighted.IsDisposed) lines.Add(highlighted); - if(lines.Count == 0) { + if(lines.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection"); return; } @@ -196,12 +198,16 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Align " + rest); int counter = 0; - foreach(Linedef l in lines){ + foreach(Linedef l in lines) + { Sector s = null; - if(alignToFrontSide) { + if(alignToFrontSide) + { if(l.Front != null && l.Front.Sector != null) s = l.Front.Sector; - } else { + } + else + { if(l.Back != null && l.Back.Sector != null) s = l.Back.Sector; } @@ -221,8 +227,12 @@ namespace CodeImp.DoomBuilder.BuilderModes ImageData texture = General.Map.Data.GetFlatImage(s.LongFloorTexture); if((texture == null) || (texture == General.Map.Data.WhiteTexture) || - (texture.Width <= 0) || (texture.Height <= 0) || !texture.IsImageLoaded) { - }else{ + (texture.Width <= 0) || (texture.Height <= 0) || !texture.IsImageLoaded) + { + //meh... + } + else + { offset.x %= texture.Width / s.Fields.GetValue((alignFloors ? "xscalefloor" : "xscaleceiling"), 1.0f); offset.y %= texture.Height / s.Fields.GetValue((alignFloors ? "yscalefloor" : "yscaleceiling"), 1.0f); } @@ -245,15 +255,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private bool isInSelectionRect(Linedef l, List selectionOutline) { - if(BuilderPlug.Me.MarqueSelectTouching) { + private bool IsInSelectionRect(Linedef l, List selectionOutline) + { + if(BuilderPlug.Me.MarqueSelectTouching) + { bool selected = selectionrect.Contains(l.Start.Position.x, l.Start.Position.y) || selectionrect.Contains(l.End.Position.x, l.End.Position.y); //check intersections with outline - if(!selected) { - foreach(Line2D line in selectionOutline) { - if(Line2D.GetIntersection(l.Line, line)) - return true; + if(!selected) + { + foreach(Line2D line in selectionOutline) + { + if(Line2D.GetIntersection(l.Line, line)) return true; } } return selected; @@ -368,7 +381,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Render selection if(renderer.StartOverlay(true)) { - if(!panning && !selecting) { //mxd + if(!panning && !selecting) //mxd + { for (int i = 0; i < Linedef.NUM_ARGS; i++) BuilderPlug.Me.RenderAssociations(renderer, association[i]); if ((highlighted != null) && !highlighted.IsDisposed) BuilderPlug.Me.RenderReverseAssociations(renderer, highlightasso); //mxd } @@ -422,8 +436,10 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.Finish(); renderer.Present(); } - //mxd - } else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedLinedefsCount > 0) { + + } + else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedLinedefsCount > 0) //mxd + { General.Map.Map.ClearSelectedLinedefs(); General.Interface.RedrawDisplay(); } @@ -498,9 +514,12 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.Map.Update(); // When a single line was selected, deselect it now - if (selected.Count == 1) { + if (selected.Count == 1) + { General.Map.Map.ClearSelectedLinedefs(); - } else if(result == DialogResult.Cancel) { //mxd. Restore selection... + } + else if(result == DialogResult.Cancel) //mxd. Restore selection... + { foreach (Linedef l in selected) l.Selected = true; } @@ -524,11 +543,13 @@ namespace CodeImp.DoomBuilder.BuilderModes if(panning) return; //mxd. Skip all this jass while panning //mxd - if(selectpressed && !editpressed && !selecting) { + if(selectpressed && !editpressed && !selecting) + { // Check if moved enough pixels for multiselect Vector2D delta = mousedownpos - mousepos; if((Math.Abs(delta.x) > MULTISELECT_START_MOVE_PIXELS) || - (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) { + (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) + { // Start multiselecting StartMultiSelection(); } @@ -538,8 +559,10 @@ namespace CodeImp.DoomBuilder.BuilderModes // Find the nearest thing within highlight range Linedef l = General.Map.Map.NearestLinedefRange(mousemappos, BuilderPlug.Me.HighlightRange / renderer.Scale); - if(l != null) { - if(l != highlighted) { + if(l != null) + { + if(l != highlighted) + { //toggle selected state if(General.Interface.ShiftState ^ BuilderPlug.Me.AdditiveSelect) l.Selected = true; @@ -554,7 +577,9 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update entire display General.Interface.RedrawDisplay(); } - } else if(highlighted != null) { + } + else if(highlighted != null) + { highlighted = null; Highlight(null); @@ -568,14 +593,17 @@ namespace CodeImp.DoomBuilder.BuilderModes Linedef l = General.Map.Map.NearestLinedefRange(mousemappos, BuilderPlug.Me.StitchRange / renderer.Scale); //mxd. Render insert vertex preview - if(l != null) { + if(l != null) + { bool snaptogrid = General.Interface.ShiftState ^ General.Interface.SnapToGrid; bool snaptonearest = General.Interface.CtrlState ^ General.Interface.AutoMerge; insertPreview = DrawGeometryMode.GetCurrentPosition(mousemappos, snaptonearest, snaptogrid, renderer, new List()).pos; //render preview - if(renderer.StartOverlay(true)) { - if(!panning) { + if(renderer.StartOverlay(true)) + { + if(!panning) + { for(int i = 0; i < Linedef.NUM_ARGS; i++) BuilderPlug.Me.RenderAssociations(renderer, association[i]); if((highlighted != null) && !highlighted.IsDisposed) BuilderPlug.Me.RenderReverseAssociations(renderer, highlightasso); //mxd } @@ -586,12 +614,16 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.Finish(); renderer.Present(); } - } else if(insertPreview.IsFinite()) { + } + else if(insertPreview.IsFinite()) + { insertPreview.x = float.NaN; //undraw preveiw - if(renderer.StartOverlay(true)) { - if(!panning) { + if(renderer.StartOverlay(true)) + { + if(!panning) + { for(int i = 0; i < Linedef.NUM_ARGS; i++) BuilderPlug.Me.RenderAssociations(renderer, association[i]); if((highlighted != null) && !highlighted.IsDisposed) BuilderPlug.Me.RenderReverseAssociations(renderer, highlightasso); //mxd } @@ -615,12 +647,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void BeginViewPan() { - if(insertPreview.IsFinite()) { + protected override void BeginViewPan() + { + if(insertPreview.IsFinite()) + { insertPreview.x = float.NaN; //undraw preveiw - if(renderer.StartOverlay(true)) { + if(renderer.StartOverlay(true)) + { renderer.Finish(); renderer.Present(); } @@ -630,7 +665,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void OnPaintSelectBegin() { + protected override void OnPaintSelectBegin() + { highlighted = null; base.OnPaintSelectBegin(); } @@ -655,31 +691,34 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Start dragging the selection - if(!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || canDrag()) //mxd + if(!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || CanDrag()) //mxd General.Editing.ChangeMode(new DragLinedefsMode(mousedownmappos)); } } } //mxd. Check if any selected linedef is outside of map boundary - private static bool canDrag() + private static bool CanDrag() { ICollection selectedlines = General.Map.Map.GetSelectedLinedefs(true); int unaffectedCount = 0; - foreach(Linedef l in selectedlines) { + foreach(Linedef l in selectedlines) + { // Make sure the linedef is inside the map boundary if(l.Start.Position.x < General.Map.Config.LeftBoundary || l.Start.Position.x > General.Map.Config.RightBoundary || l.Start.Position.y > General.Map.Config.TopBoundary || l.Start.Position.y < General.Map.Config.BottomBoundary || l.End.Position.x < General.Map.Config.LeftBoundary || l.End.Position.x > General.Map.Config.RightBoundary - || l.End.Position.y > General.Map.Config.TopBoundary || l.End.Position.y < General.Map.Config.BottomBoundary) { + || l.End.Position.y > General.Map.Config.TopBoundary || l.End.Position.y < General.Map.Config.BottomBoundary) + { l.Selected = false; unaffectedCount++; } } - if(unaffectedCount == selectedlines.Count) { + if(unaffectedCount == selectedlines.Count) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to drag selection: " + (selectedlines.Count == 1 ? "selected linedef is" : "all of selected linedefs are") + " outside of map boundary!"); General.Interface.RedrawDisplay(); return false; @@ -698,33 +737,35 @@ namespace CodeImp.DoomBuilder.BuilderModes if(selectionvolume) { - List selectionOutline = new List() { + List selectionOutline = new List + { new Line2D(selectionrect.Left, selectionrect.Top, selectionrect.Right, selectionrect.Top), new Line2D(selectionrect.Right, selectionrect.Top, selectionrect.Right, selectionrect.Bottom), new Line2D(selectionrect.Left, selectionrect.Bottom, selectionrect.Right, selectionrect.Bottom), new Line2D(selectionrect.Left, selectionrect.Bottom, selectionrect.Left, selectionrect.Top) - }; + }; //mxd - switch(marqueSelectionMode) { + switch(marqueSelectionMode) + { case MarqueSelectionMode.SELECT: foreach(Linedef l in General.Map.Map.Linedefs) - l.Selected = isInSelectionRect(l, selectionOutline); + l.Selected = IsInSelectionRect(l, selectionOutline); break; case MarqueSelectionMode.ADD: foreach(Linedef l in General.Map.Map.Linedefs) - l.Selected |= isInSelectionRect(l, selectionOutline); + l.Selected |= IsInSelectionRect(l, selectionOutline); break; case MarqueSelectionMode.SUBTRACT: foreach(Linedef l in General.Map.Map.Linedefs) - if(isInSelectionRect(l, selectionOutline)) l.Selected = false; + if(IsInSelectionRect(l, selectionOutline)) l.Selected = false; break; default: foreach(Linedef l in General.Map.Map.Linedefs) - if(!isInSelectionRect(l, selectionOutline)) l.Selected = false; + if(!IsInSelectionRect(l, selectionOutline)) l.Selected = false; break; } @@ -769,7 +810,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void UpdateSelectionInfo() { + public override void UpdateSelectionInfo() + { if(General.Map.Map.SelectedLinedefsCount > 0) General.Interface.DisplayStatus(StatusType.Selection, General.Map.Map.SelectedLinedefsCount + (General.Map.Map.SelectedLinedefsCount == 1 ? " linedef" : " linedefs") + " selected."); else @@ -902,17 +944,21 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("deleteitem", BaseAction = true)] - public void DeleteItem() { + public void DeleteItem() + { // Make list of selected linedefs ICollection selected = General.Map.Map.GetSelectedLinedefs(true); if((selected.Count == 0) && (highlighted != null) && !highlighted.IsDisposed) selected.Add(highlighted); if(selected.Count == 0) return; // Make undo - if(selected.Count > 1) { + if(selected.Count > 1) + { General.Map.UndoRedo.CreateUndo("Delete " + selected.Count + " linedefs"); General.Interface.DisplayStatus(StatusType.Action, "Deleted " + selected.Count + " linedefs."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Delete linedef"); General.Interface.DisplayStatus(StatusType.Action, "Deleted a linedef."); } @@ -957,7 +1003,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Find sectors, which will become invalid after linedefs removal. Dictionary toMerge = new Dictionary(); - foreach(Linedef l in selected) { + foreach(Linedef l in selected) + { if(l.Front != null && l.Front.Sector.Sidedefs.Count < 4 && !toMerge.ContainsKey(l.Front.Sector)) toMerge.Add(l.Front.Sector, new Vector2D(l.Front.Sector.BBox.Location.X + l.Front.Sector.BBox.Width / 2, l.Front.Sector.BBox.Location.Y + l.Front.Sector.BBox.Height / 2)); @@ -968,9 +1015,12 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.Map.BeginAddRemove(); //mxd // Dispose selected linedefs - foreach(Linedef ld in selected) { + foreach(Linedef ld in selected) + { //mxd. If there are different sectors on both sides, join them - if(ld.Front != null && ld.Front.Sector != null && ld.Back != null && ld.Back.Sector != null && ld.Front.Sector.Index != ld.Back.Sector.Index) { + if(ld.Front != null && ld.Front.Sector != null && ld.Back != null + && ld.Back.Sector != null && ld.Front.Sector.Index != ld.Back.Sector.Index) + { if(ld.Front.Sector.BBox.Width * ld.Front.Sector.BBox.Height > ld.Back.Sector.BBox.Width * ld.Back.Sector.BBox.Height) ld.Back.Sector.Join(ld.Front.Sector); else @@ -1208,13 +1258,15 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Make gradient brightness [BeginAction("gradientbrightness")] - public void MakeGradientBrightness() { + public void MakeGradientBrightness() + { if(!General.Map.UDMF) return; // Need at least 3 selected linedefs // The first and last are not modified ICollection orderedselection = General.Map.Map.GetSelectedLinedefs(true); - if(orderedselection.Count > 2) { + if(orderedselection.Count > 2) + { General.Interface.DisplayStatus(StatusType.Action, "Created gradient brightness over selected linedefs."); General.Map.UndoRedo.CreateUndo("Linedefs gradient brightness"); @@ -1227,20 +1279,28 @@ namespace CodeImp.DoomBuilder.BuilderModes float endbrightness = float.NaN; //get total brightness of start sidedef(s) - if(start.Front != null) { - if(start.Front.Fields.GetValue(lightAbsKey, false)) { + if(start.Front != null) + { + if(start.Front.Fields.GetValue(lightAbsKey, false)) + { startbrightness = start.Front.Fields.GetValue(lightKey, 0); - } else { + } + else + { startbrightness = Math.Min(255, Math.Max(0, (float)start.Front.Sector.Brightness + start.Front.Fields.GetValue(lightKey, 0))); } } - if(start.Back != null) { + if(start.Back != null) + { float b; - if(start.Back.Fields.GetValue(lightAbsKey, false)) { + if(start.Back.Fields.GetValue(lightAbsKey, false)) + { b = start.Back.Fields.GetValue(lightKey, 0); - } else { + } + else + { b = Math.Min(255, Math.Max(0, (float)start.Back.Sector.Brightness + start.Back.Fields.GetValue(lightKey, 0))); } @@ -1248,20 +1308,28 @@ namespace CodeImp.DoomBuilder.BuilderModes } //get total brightness of end sidedef(s) - if(end.Front != null) { - if(end.Front.Fields.GetValue(lightAbsKey, false)) { + if(end.Front != null) + { + if(end.Front.Fields.GetValue(lightAbsKey, false)) + { endbrightness = end.Front.Fields.GetValue(lightKey, 0); - } else { + } + else + { endbrightness = Math.Min(255, Math.Max(0, (float)end.Front.Sector.Brightness + end.Front.Fields.GetValue(lightKey, 0))); } } - if(end.Back != null) { + if(end.Back != null) + { float b; - if(end.Back.Fields.GetValue(lightAbsKey, false)) { + if(end.Back.Fields.GetValue(lightAbsKey, false)) + { b = end.Back.Fields.GetValue(lightKey, 0); - } else { + } + else + { b = Math.Min(255, Math.Max(0, (float)end.Back.Sector.Brightness + end.Back.Fields.GetValue(lightKey, 0))); } @@ -1272,20 +1340,25 @@ namespace CodeImp.DoomBuilder.BuilderModes // Go for all sectors in between first and last int index = 0; - foreach(Linedef l in orderedselection) { + foreach(Linedef l in orderedselection) + { float u = index / (float)(orderedselection.Count - 1); float b = startbrightness + delta * u; - if(l.Front != null) { + if(l.Front != null) + { l.Front.Fields.BeforeFieldsChange(); //absolute flag set? - if(l.Front.Fields.GetValue(lightAbsKey, false)) { + if(l.Front.Fields.GetValue(lightAbsKey, false)) + { if(l.Front.Fields.ContainsKey(lightKey)) l.Front.Fields[lightKey].Value = (int)b; else l.Front.Fields.Add(lightKey, new UniValue(UniversalType.Integer, (int)b)); - } else { + } + else + { if(l.Front.Fields.ContainsKey(lightKey)) l.Front.Fields[lightKey].Value = (int)b - l.Front.Sector.Brightness; else @@ -1293,16 +1366,20 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(l.Back != null) { + if(l.Back != null) + { l.Back.Fields.BeforeFieldsChange(); //absolute flag set? - if(l.Back.Fields.GetValue(lightAbsKey, false)) { + if(l.Back.Fields.GetValue(lightAbsKey, false)) + { if(l.Back.Fields.ContainsKey(lightKey)) l.Back.Fields[lightKey].Value = (int)b; else l.Back.Fields.Add(lightKey, new UniValue(UniversalType.Integer, (int)b)); - } else { + } + else + { if(l.Back.Fields.ContainsKey(lightKey)) l.Back.Fields[lightKey].Value = (int)b - l.Back.Sector.Brightness; else @@ -1318,74 +1395,89 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.RedrawDisplay(); General.Interface.RefreshInfo(); General.Map.IsChanged = true; - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Select at least 3 linedefs first!"); } } [BeginAction("placethings")] //mxd - public void PlaceThings() { + public void PlaceThings() + { // Make list of selected linedefs ICollection lines = General.Map.Map.GetSelectedLinedefs(true); List positions = new List(); - if(lines.Count == 0) { - if (highlighted != null && !highlighted.IsDisposed) { + if(lines.Count == 0) + { + if (highlighted != null && !highlighted.IsDisposed) + { lines.Add(highlighted); - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires selection of some description!"); return; } } // Make list of vertex positions - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(!positions.Contains(l.Start.Position)) positions.Add(l.Start.Position); if(!positions.Contains(l.End.Position)) positions.Add(l.End.Position); } - if(positions.Count < 1) { + if(positions.Count < 1) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to get vertex positions from selection!"); return; } - placeThingsAtPositions(positions); + PlaceThingsAtPositions(positions); } //mxd [BeginAction("alignfloortofront")] - public void AlignFloorToFront() { + public void AlignFloorToFront() + { if(!General.Map.UDMF) return; - alignTextureToLine(true, true); + AlignTextureToLine(true, true); } //mxd [BeginAction("alignfloortoback")] - public void AlignFloorToBack() { + public void AlignFloorToBack() + { if(!General.Map.UDMF) return; - alignTextureToLine(true, false); + AlignTextureToLine(true, false); } //mxd [BeginAction("alignceilingtofront")] - public void AlignCeilingToFront() { + public void AlignCeilingToFront() + { if(!General.Map.UDMF) return; - alignTextureToLine(false, true); + AlignTextureToLine(false, true); } //mxd [BeginAction("alignceilingtoback")] - public void AlignCeilingToBack() { + public void AlignCeilingToBack() + { if(!General.Map.UDMF) return; - alignTextureToLine(false, false); + AlignTextureToLine(false, false); } //mxd [BeginAction("selectsimilar")] - public void SelectSimilar() { + public void SelectSimilar() + { ICollection selection = General.Map.Map.GetSelectedLinedefs(true); - if(selection.Count == 0) { + if(selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } diff --git a/Source/Plugins/BuilderModes/ClassicModes/MakeSectorMode.cs b/Source/Plugins/BuilderModes/ClassicModes/MakeSectorMode.cs index b92ed5d5..f4d79cd4 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/MakeSectorMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/MakeSectorMode.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Windows.Forms; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Rendering; using CodeImp.DoomBuilder.Geometry; @@ -158,7 +159,8 @@ namespace CodeImp.DoomBuilder.BuilderModes else if(BuilderPlug.Me.UseHighlight) //mxd { int color = General.Colors.Indication.WithAlpha(64).ToInt(); - foreach(Sector s in associates.Keys){ + foreach(Sector s in associates.Keys) + { renderer.RenderHighlight(s.FlatVertices, color); } } @@ -168,7 +170,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This highlights a new region - protected void Highlight(bool buttonspressed) + private void Highlight(bool buttonspressed) { LinedefSide newnearest; @@ -540,10 +542,6 @@ namespace CodeImp.DoomBuilder.BuilderModes } #endregion - - #region ================== Actions - - #endregion } } diff --git a/Source/Plugins/BuilderModes/ClassicModes/SectorsMode.cs b/Source/Plugins/BuilderModes/ClassicModes/SectorsMode.cs index 4d5ebfa0..9ed70dd5 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/SectorsMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/SectorsMode.cs @@ -89,7 +89,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { //mxd effects = new Dictionary(); - foreach (SectorEffectInfo info in General.Map.Config.SortedSectorEffects) { + foreach (SectorEffectInfo info in General.Map.Config.SortedSectorEffects) + { string name = info.Index + ": " + info.Title; effects.Add(info.Index, new[] { name, "E" + info.Index }); } @@ -128,12 +129,11 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. This makes a CRC for given selection - public int CreateSelectionCRC(ICollection selection) { + private static int CreateSelectionCRC(ICollection selection) + { CRC crc = new CRC(); crc.Add(selection.Count); - foreach(Sector s in selection) { - crc.Add(s.FixedIndex); - } + foreach(Sector s in selection) crc.Add(s.FixedIndex); return (int)(crc.Value & 0xFFFFFFFF); } @@ -178,20 +178,25 @@ namespace CodeImp.DoomBuilder.BuilderModes ICollection orderedselection = General.Map.Map.GetSelectedSectors(true); //mxd. Render selected sectors - if (BuilderPlug.Me.UseHighlight) { + if (BuilderPlug.Me.UseHighlight) + { renderer.RenderHighlight(overlayGeometry, General.Colors.Selection.WithAlpha(64).ToInt()); } //mxd. Render highlighted sector - if(BuilderPlug.Me.UseHighlight && highlighted != null) { + if(BuilderPlug.Me.UseHighlight && highlighted != null) + { renderer.RenderHighlight(highlighted.FlatVertices, General.Colors.Highlight.WithAlpha(64).ToInt()); } - if (BuilderPlug.Me.ViewSelectionNumbers) { - foreach (Sector s in orderedselection) { + if (BuilderPlug.Me.ViewSelectionNumbers) + { + foreach (Sector s in orderedselection) + { // Render labels TextLabel[] labelarray = labels[s]; - for (int i = 0; i < s.Labels.Count; i++) { + for (int i = 0; i < s.Labels.Count; i++) + { TextLabel l = labelarray[i]; // Render only when enough space for the label to see @@ -202,9 +207,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Render effect labels - if (BuilderPlug.Me.ViewSelectionEffects) { - if(!BuilderPlug.Me.ViewSelectionNumbers) renderEffectLabels(selectedEffectLabels); - renderEffectLabels(unselectedEffectLabels); + if (BuilderPlug.Me.ViewSelectionEffects) + { + if(!BuilderPlug.Me.ViewSelectionNumbers) RenderEffectLabels(selectedEffectLabels); + RenderEffectLabels(unselectedEffectLabels); } renderer.Finish(); @@ -212,20 +218,26 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void renderEffectLabels(Dictionary labelsGroup) { - foreach(KeyValuePair group in labelsGroup) { + private void RenderEffectLabels(Dictionary labelsGroup) + { + foreach(KeyValuePair group in labelsGroup) + { // Render labels TextLabel[] labelarray = labels[group.Key]; - for(int i = 0; i < group.Key.Labels.Count; i++) { + for(int i = 0; i < group.Key.Labels.Count; i++) + { TextLabel l = labelarray[i]; l.Color = General.Colors.InfoLine; // Render only when enough space for the label to see float requiredsize = (General.Map.GetTextSize(group.Value[0], l.Scale).Width) / renderer.Scale; - if(requiredsize > group.Key.Labels[i].radius) { + if(requiredsize > group.Key.Labels[i].radius) + { requiredsize = (General.Map.GetTextSize(group.Value[1], l.Scale).Width) / renderer.Scale; l.Text = (requiredsize > group.Key.Labels[i].radius ? "+" : group.Value[1]); - } else { + } + else + { l.Text = group.Value[0]; } @@ -235,29 +247,42 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private string[] getEffectText(Sector s) { + private string[] GetEffectText(Sector s) + { string[] result = new []{string.Empty, string.Empty}; - if(s.Effect != 0) { - if(effects.ContainsKey(s.Effect)) { - if(s.Tag != 0) { + if(s.Effect != 0) + { + if(effects.ContainsKey(s.Effect)) + { + if(s.Tag != 0) + { result[0] = "Tag " + s.Tag + ", " + effects[s.Effect][0]; result[1] = "T" + s.Tag + " " + "E" + s.Effect; - } else { + } + else + { result[0] = effects[s.Effect][0]; result[1] = "E" + s.Effect; } - } else { + } + else + { string effect = s.Effect + " - " + General.Map.Config.GetGeneralizedSectorEffectName(s.Effect); - if(s.Tag != 0) { + if(s.Tag != 0) + { result[0] = "Tag " + s.Tag + ", Effect " + effect; result[1] = "T" + s.Tag + " " + "E" + s.Effect; - } else { + } + else + { result[0] = "Effect " + effect; result[1] = "E" + s.Effect; } } - } else if(s.Tag != 0) { + } + else if(s.Tag != 0) + { result[0] = "Tag " + s.Tag; result[1] = "T" + s.Tag; } @@ -266,7 +291,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void updateOverlaySurfaces() { + private void UpdateOverlaySurfaces() + { ICollection orderedselection = General.Map.Map.GetSelectedSectors(true); List vertsList = new List(); @@ -276,22 +302,25 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void updateEffectLabels() { + private void UpdateEffectLabels() + { selectedEffectLabels = new Dictionary(); unselectedEffectLabels = new Dictionary(); //update effect labels for selected sectors ICollection orderedselection = General.Map.Map.GetSelectedSectors(true); - foreach(Sector s in orderedselection) { - string[] labelText = getEffectText(s); + foreach(Sector s in orderedselection) + { + string[] labelText = GetEffectText(s); if(!string.IsNullOrEmpty(labelText[0])) selectedEffectLabels.Add(s, labelText); } //update effect labels for unselected sectors orderedselection = General.Map.Map.GetSelectedSectors(false); - foreach(Sector s in orderedselection) { - string[] labelText = getEffectText(s); + foreach(Sector s in orderedselection) + { + string[] labelText = GetEffectText(s); if(!string.IsNullOrEmpty(labelText[0])) unselectedEffectLabels.Add(s, labelText); } @@ -354,10 +383,13 @@ namespace CodeImp.DoomBuilder.BuilderModes bool completeredraw = (highlighted != null) && (highlighted.Tag > 0); // Set highlight association - if (s != null) { + if (s != null) + { Vector2D center = (s.Labels.Count > 0 ? s.Labels[0].position : new Vector2D(s.BBox.X + s.BBox.Width / 2, s.BBox.Y + s.BBox.Height / 2)); highlightasso.Set(center, s.Tag, UniversalType.SectorTag); - } else { + } + else + { highlightasso.Set(new Vector2D(), 0, 0); } @@ -445,15 +477,18 @@ namespace CodeImp.DoomBuilder.BuilderModes selectionchanged = true; // Setup labels - if(update) { //mxd + if(update) + { + //mxd string selectedCount = General.Map.Map.SelectedSectorsCount.ToString(); TextLabel[] labelarray = labels[s]; - foreach(TextLabel l in labelarray) { + foreach(TextLabel l in labelarray) + { l.Text = selectedCount; l.Color = General.Colors.Selection; } - updateEffectLabels(); + UpdateEffectLabels(); } } // Deselect the sector? @@ -463,7 +498,8 @@ namespace CodeImp.DoomBuilder.BuilderModes selectionchanged = true; // Clear labels - if(update) { + if(update) + { TextLabel[] labelarray = labels[s]; foreach(TextLabel l in labelarray) l.Text = ""; @@ -513,26 +549,30 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - updateEffectLabels(); + UpdateEffectLabels(); } //mxd - private bool isInSelectionRect(Sector s, List selectionOutline) { + private bool IsInSelectionRect(Sector s, List selectionOutline) + { if(selectionrect.Contains(s.BBox)) return true; - if(BuilderPlug.Me.MarqueSelectTouching && s.BBox.IntersectsWith(selectionrect)) { + if(BuilderPlug.Me.MarqueSelectTouching && s.BBox.IntersectsWith(selectionrect)) + { //check endpoints - foreach(Sidedef side in s.Sidedefs) { + foreach(Sidedef side in s.Sidedefs) + { if((selectionrect.Contains(side.Line.Start.Position.x, side.Line.Start.Position.y) || selectionrect.Contains(side.Line.End.Position.x, side.Line.End.Position.y))) return true; } //check line intersections - foreach(Sidedef side in s.Sidedefs) { - foreach(Line2D line in selectionOutline) { - if(Line2D.GetIntersection(side.Line.Line, line)) - return true; + foreach(Sidedef side in s.Sidedefs) + { + foreach(Line2D line in selectionOutline) + { + if(Line2D.GetIntersection(side.Line.Line, line)) return true; } } } @@ -541,12 +581,14 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void SelectMapElement(SelectableElement element) { - if(element is Sector) { + public override void SelectMapElement(SelectableElement element) + { + if(element is Sector) + { SelectSector(element as Sector, true, true); // Update overlay - updateOverlaySurfaces(); + UpdateOverlaySurfaces(); UpdateSelectionInfo(); } } @@ -600,7 +642,7 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update UpdateSelectedLabels(); - updateOverlaySurfaces();//mxd + UpdateOverlaySurfaces();//mxd UpdateSelectionInfo(); //mxd UpdateOverlay(); } @@ -734,14 +776,15 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update overlay TextLabel[] labelarray = labels[highlighted]; foreach(TextLabel l in labelarray) l.Color = General.Colors.Highlight; - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd UpdateOverlay(); renderer.Present(); - //mxd - } else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedSectorsCount > 0) { + } + else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedSectorsCount > 0) //mxd + { General.Map.Map.ClearSelectedLinedefs(); General.Map.Map.ClearSelectedSectors(); - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd General.Interface.RedrawDisplay(); } @@ -768,7 +811,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.Map.ClearSelectedLinedefs(); SelectSector(highlighted, true, false); UpdateSelectedLabels(); //mxd - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd General.Interface.RedrawDisplay(); } @@ -818,16 +861,19 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.Renderer2D.UpdateExtraFloorFlag(); //mxd // When a single sector was selected, deselect it now - if (selected.Count == 1) { + if (selected.Count == 1) + { General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); - updateEffectLabels(); //mxd - } else if(result == DialogResult.Cancel) { //mxd. Restore selection... + UpdateEffectLabels(); //mxd + } + else if(result == DialogResult.Cancel) //mxd. Restore selection... + { foreach (Sector s in selected) SelectSector(s, true, false); UpdateSelectedLabels(); //mxd } - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd General.Interface.RedrawDisplay(); } } @@ -840,7 +886,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void sectorEditForm_OnValuesChanged(object sender, EventArgs e) { + private void sectorEditForm_OnValuesChanged(object sender, EventArgs e) + { // Update entire display General.Map.Map.Update(); General.Interface.RedrawDisplay(); @@ -853,11 +900,13 @@ namespace CodeImp.DoomBuilder.BuilderModes if(panning) return; //mxd. Skip all this jazz while panning //mxd - if(selectpressed && !editpressed && !selecting) { + if(selectpressed && !editpressed && !selecting) + { // Check if moved enough pixels for multiselect Vector2D delta = mousedownpos - mousepos; if((Math.Abs(delta.x) > MULTISELECT_START_MOVE_PIXELS) || - (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) { + (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) + { // Start multiselecting StartMultiSelection(); } @@ -868,21 +917,25 @@ namespace CodeImp.DoomBuilder.BuilderModes Linedef l = General.Map.Map.NearestLinedefRange(mousemappos, BuilderPlug.Me.HighlightRange / renderer.Scale); Sector s = null; - if(l != null) { + if(l != null) + { // Check on which side of the linedef the mouse is float side = l.SideOfLine(mousemappos); - if(side > 0) { + if(side > 0) + { // Is there a sidedef here? - if(l.Back != null) - s = l.Back.Sector; - } else { + if(l.Back != null) s = l.Back.Sector; + } + else + { // Is there a sidedef here? - if(l.Front != null) - s = l.Front.Sector; + if(l.Front != null) s = l.Front.Sector; } - if(s != null) { - if(s != highlighted) { + if(s != null) + { + if(s != highlighted) + { //toggle selected state highlighted = s; if(General.Interface.ShiftState ^ BuilderPlug.Me.AdditiveSelect) @@ -893,10 +946,12 @@ namespace CodeImp.DoomBuilder.BuilderModes SelectSector(highlighted, !highlighted.Selected, true); // Update entire display - updateOverlaySurfaces();//mxd + UpdateOverlaySurfaces();//mxd General.Interface.RedrawDisplay(); } - } else if(highlighted != null) { + } + else if(highlighted != null) + { highlighted = null; Highlight(null); @@ -962,8 +1017,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void OnPaintSelectBegin() { - if(highlighted != null) { + protected override void OnPaintSelectBegin() + { + if(highlighted != null) + { if(General.Interface.ShiftState ^ BuilderPlug.Me.AdditiveSelect) SelectSector(highlighted, true, true); else if(General.Interface.CtrlState) @@ -972,7 +1029,7 @@ namespace CodeImp.DoomBuilder.BuilderModes SelectSector(highlighted, !highlighted.Selected, true); // Update entire display - updateOverlaySurfaces();//mxd + UpdateOverlaySurfaces();//mxd General.Interface.RedrawDisplay(); } @@ -996,29 +1053,32 @@ namespace CodeImp.DoomBuilder.BuilderModes // Select only this sector for dragging General.Map.Map.ClearSelectedSectors(); SelectSector(highlighted, true, true); - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd } // Start dragging the selection - if(!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || canDrag()) //mxd + if(!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || CanDrag()) //mxd General.Editing.ChangeMode(new DragSectorsMode(mousedownmappos)); } } } //mxd. Check if any selected sector is outside of map boundary - private bool canDrag() { + private bool CanDrag() + { ICollection selectedsectors = General.Map.Map.GetSelectedSectors(true); int unaffectedCount = 0; - foreach(Sector s in selectedsectors) { + foreach(Sector s in selectedsectors) + { // Make sure the sector is inside the map boundary - foreach(Sidedef sd in s.Sidedefs) { + foreach(Sidedef sd in s.Sidedefs) + { if(sd.Line.Start.Position.x < General.Map.Config.LeftBoundary || sd.Line.Start.Position.x > General.Map.Config.RightBoundary || sd.Line.Start.Position.y > General.Map.Config.TopBoundary || sd.Line.Start.Position.y < General.Map.Config.BottomBoundary || sd.Line.End.Position.x < General.Map.Config.LeftBoundary || sd.Line.End.Position.x > General.Map.Config.RightBoundary - || sd.Line.End.Position.y > General.Map.Config.TopBoundary || sd.Line.End.Position.y < General.Map.Config.BottomBoundary) { - + || sd.Line.End.Position.y > General.Map.Config.TopBoundary || sd.Line.End.Position.y < General.Map.Config.BottomBoundary) + { SelectSector(s, false, false); unaffectedCount++; break; @@ -1026,7 +1086,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(unaffectedCount == selectedsectors.Count) { + if(unaffectedCount == selectedsectors.Count) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to drag selection: " + (selectedsectors.Count == 1 ? "selected sector is" : "all of selected sectors are") + " outside of map boundary!"); General.Interface.RedrawDisplay(); return false; @@ -1046,27 +1107,31 @@ namespace CodeImp.DoomBuilder.BuilderModes if(selectionvolume) { - List selectionOutline = new List() { + List selectionOutline = new List { new Line2D(selectionrect.Left, selectionrect.Top, selectionrect.Right, selectionrect.Top), new Line2D(selectionrect.Right, selectionrect.Top, selectionrect.Right, selectionrect.Bottom), new Line2D(selectionrect.Left, selectionrect.Bottom, selectionrect.Right, selectionrect.Bottom), new Line2D(selectionrect.Left, selectionrect.Bottom, selectionrect.Left, selectionrect.Top) - }; + }; //mxd. collect changed sectors - switch(marqueSelectionMode) { + switch(marqueSelectionMode) + { case MarqueSelectionMode.SELECT: bool select; - foreach(Sector s in General.Map.Map.Sectors) { - select = isInSelectionRect(s, selectionOutline); + foreach(Sector s in General.Map.Map.Sectors) + { + select = IsInSelectionRect(s, selectionOutline); if(select && !s.Selected) SelectSector(s, true, false); else if(!select && s.Selected) SelectSector(s, false, false); } - if (marqueSelectionIncludesThings) { + if (marqueSelectionIncludesThings) + { ICollection selected = General.Map.Map.GetSelectedSectors(true); - foreach (Thing t in General.Map.ThingsFilter.VisibleThings) { + foreach (Thing t in General.Map.ThingsFilter.VisibleThings) + { t.DetermineSector(); if(t.Sector == null) continue; t.Selected = selectionrect.Contains(t.Position.x, t.Position.y) && selected.Contains(t.Sector); @@ -1075,14 +1140,17 @@ namespace CodeImp.DoomBuilder.BuilderModes break; case MarqueSelectionMode.ADD: - foreach(Sector s in General.Map.Map.Sectors) { - if(!s.Selected && isInSelectionRect(s, selectionOutline)) + foreach(Sector s in General.Map.Map.Sectors) + { + if(!s.Selected && IsInSelectionRect(s, selectionOutline)) SelectSector(s, true, false); } - if (marqueSelectionIncludesThings) { + if (marqueSelectionIncludesThings) + { ICollection selected = General.Map.Map.GetSelectedSectors(true); - foreach (Thing t in General.Map.ThingsFilter.VisibleThings) { + foreach (Thing t in General.Map.ThingsFilter.VisibleThings) + { t.DetermineSector(); if(t.Sector == null) continue; t.Selected |= selectionrect.Contains(t.Position.x, t.Position.y) && selected.Contains(t.Sector); @@ -1091,24 +1159,28 @@ namespace CodeImp.DoomBuilder.BuilderModes break; case MarqueSelectionMode.SUBTRACT: - foreach(Sector s in General.Map.Map.Sectors) { + foreach(Sector s in General.Map.Map.Sectors) + { if(!s.Selected) continue; - if(isInSelectionRect(s, selectionOutline)) + if(IsInSelectionRect(s, selectionOutline)) SelectSector(s, false, false); } - if (marqueSelectionIncludesThings) { + if (marqueSelectionIncludesThings) + { foreach (Thing t in General.Map.ThingsFilter.VisibleThings) if (selectionrect.Contains(t.Position.x, t.Position.y)) t.Selected = false; } break; default: //should be Intersect - foreach(Sector s in General.Map.Map.Sectors) { + foreach(Sector s in General.Map.Map.Sectors) + { if(!s.Selected) continue; - if(!isInSelectionRect(s, selectionOutline)) + if(!IsInSelectionRect(s, selectionOutline)) SelectSector(s, false, false); } - if (marqueSelectionIncludesThings) { + if (marqueSelectionIncludesThings) + { foreach(Thing t in General.Map.ThingsFilter.VisibleThings) if(!selectionrect.Contains(t.Position.x, t.Position.y)) t.Selected = false; } @@ -1120,9 +1192,11 @@ namespace CodeImp.DoomBuilder.BuilderModes sd.Line.Selected = sd.Sector.Selected || (sd.Other != null && sd.Other.Sector.Selected); //mxd. Clear labels for unselected sectors - if(marqueSelectionMode != MarqueSelectionMode.ADD) { + if(marqueSelectionMode != MarqueSelectionMode.ADD) + { ICollection orderedselection = General.Map.Map.GetSelectedSectors(false); - foreach(Sector s in orderedselection){ + foreach(Sector s in orderedselection) + { TextLabel[] labelarray = labels[s]; foreach(TextLabel l in labelarray) l.Text = ""; } @@ -1130,7 +1204,7 @@ namespace CodeImp.DoomBuilder.BuilderModes UpdateSelectedLabels(); //mxd UpdateSelectionInfo(); //mxd - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd } base.OnEndMultiSelection(); @@ -1160,7 +1234,7 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Make the highlight the selection SelectSector(highlighted, true, true); - updateOverlaySurfaces();//mxd + UpdateOverlaySurfaces();//mxd } return base.OnCopyBegin(); @@ -1180,8 +1254,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Clear labels SetupLabels(); - updateEffectLabels(); //mxd - updateOverlaySurfaces(); //mxd + UpdateEffectLabels(); //mxd + UpdateOverlaySurfaces(); //mxd base.OnUndoEnd(); //mxd } @@ -1199,13 +1273,14 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Clear labels SetupLabels(); - updateEffectLabels(); //mxd - updateOverlaySurfaces(); //mxd + UpdateEffectLabels(); //mxd + UpdateOverlaySurfaces(); //mxd base.OnRedoEnd(); //mxd } //mxd - public override void UpdateSelectionInfo() { + public override void UpdateSelectionInfo() + { if(General.Map.Map.SelectedSectorsCount > 0) General.Interface.DisplayStatus(StatusType.Selection, General.Map.Map.SelectedSectorsCount + (General.Map.Map.SelectedSectorsCount == 1 ? " sector" : " sectors") + " selected."); else @@ -1267,7 +1342,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.IsChanged = true; General.Interface.RefreshInfo(); General.Map.Renderer2D.UpdateExtraFloorFlag(); //mxd - updateEffectLabels(); //mxd + UpdateEffectLabels(); //mxd General.Interface.RedrawDisplay(); } } @@ -1299,7 +1374,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); SelectSector(highlighted, true, false); - updateOverlaySurfaces();//mxd + UpdateOverlaySurfaces();//mxd General.Interface.RedrawDisplay(); } @@ -1424,7 +1499,7 @@ namespace CodeImp.DoomBuilder.BuilderModes orderedselection.Clear(); General.Map.Map.ClearSelectedSectors(); General.Map.Map.ClearSelectedLinedefs(); - updateOverlaySurfaces();//mxd + UpdateOverlaySurfaces();//mxd } } @@ -1491,10 +1566,14 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Check textures. - if(lines[i].Front.MiddleRequired() && lines[i].Front.LongMiddleTexture == MapSet.EmptyLongName) { - if(lines[i].Front.LongHighTexture != MapSet.EmptyLongName) { + if(lines[i].Front.MiddleRequired() && lines[i].Front.LongMiddleTexture == MapSet.EmptyLongName) + { + if(lines[i].Front.LongHighTexture != MapSet.EmptyLongName) + { lines[i].Front.SetTextureMid(lines[i].Front.HighTexture); - } else if(lines[i].Front.LongLowTexture != MapSet.EmptyLongName) { + } + else if(lines[i].Front.LongLowTexture != MapSet.EmptyLongName) + { lines[i].Front.SetTextureMid(lines[i].Front.LowTexture); } } @@ -1513,7 +1592,7 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update cache values General.Map.IsChanged = true; General.Map.Map.Update(); - updateOverlaySurfaces(); //mxd + UpdateOverlaySurfaces(); //mxd // Make text labels for sectors SetupLabels(); @@ -1525,7 +1604,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("dissolveitem", BaseAction = true)] //mxd - public void DissolveItem() { + public void DissolveItem() + { //TODO handle this differently?.. DeleteItem(); } @@ -1587,7 +1667,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Need at least 3 selected sectors // The first and last are not modified ICollection orderedselection = General.Map.Map.GetSelectedSectors(true); - if(orderedselection.Count > 2) { + if(orderedselection.Count > 2) + { General.Interface.DisplayStatus(StatusType.Action, "Created gradient brightness over selected sectors."); General.Map.UndoRedo.CreateUndo("Gradient brightness"); @@ -1597,15 +1678,19 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Use UDMF light? string mode = (string)BuilderPlug.Me.MenusForm.BrightnessGradientMode.SelectedItem; - if(General.Map.UDMF && (mode == MenusForm.BrightnessGradientModes.Ceilings || mode == MenusForm.BrightnessGradientModes.Floors)) { + if(General.Map.UDMF && (mode == MenusForm.BrightnessGradientModes.Ceilings || mode == MenusForm.BrightnessGradientModes.Floors)) + { string lightKey; string lightAbsKey; float startbrightness, endbrightness; - if(mode == MenusForm.BrightnessGradientModes.Ceilings) { + if(mode == MenusForm.BrightnessGradientModes.Ceilings) + { lightKey = "lightceiling"; lightAbsKey = "lightceilingabsolute"; - } else { //should be floors... + } + else //should be floors... + { lightKey = "lightfloor"; lightAbsKey = "lightfloorabsolute"; } @@ -1626,38 +1711,51 @@ namespace CodeImp.DoomBuilder.BuilderModes // Go for all sectors in between first and last int index = 0; - foreach(Sector s in orderedselection) { + foreach(Sector s in orderedselection) + { s.Fields.BeforeFieldsChange(); float u = index / (float)(orderedselection.Count - 1); float b = startbrightness + delta * u; //absolute flag set? - if(s.Fields.GetValue(lightAbsKey, false)) { + if(s.Fields.GetValue(lightAbsKey, false)) + { if(s.Fields.ContainsKey(lightKey)) s.Fields[lightKey].Value = (int)b; else s.Fields.Add(lightKey, new UniValue(UniversalType.Integer, (int)b)); - } else { + } + else + { UDMFTools.SetInteger(s.Fields, lightKey, (int)b - s.Brightness, 0); } index++; } + + } //mxd. Use UDMF light/fade color? - } else if(General.Map.UDMF && (mode == MenusForm.BrightnessGradientModes.Fade || mode == MenusForm.BrightnessGradientModes.Light)) { + else if(General.Map.UDMF && (mode == MenusForm.BrightnessGradientModes.Fade || mode == MenusForm.BrightnessGradientModes.Light)) + { string key; int defaultValue = 0; - if(mode == MenusForm.BrightnessGradientModes.Light) { + if(mode == MenusForm.BrightnessGradientModes.Light) + { key = "lightcolor"; defaultValue = 0xFFFFFF; - } else { + } + else + { key = "fadecolor"; } - if(!start.Fields.ContainsKey(key) && !end.Fields.ContainsKey(key)) { + if(!start.Fields.ContainsKey(key) && !end.Fields.ContainsKey(key)) + { General.Interface.DisplayStatus(StatusType.Warning, "First or last sector must have " + key + "!"); - } else { + } + else + { Color startColor = PixelColor.FromInt(start.Fields.GetValue(key, defaultValue)).ToColor(); Color endColor = PixelColor.FromInt(end.Fields.GetValue(key, defaultValue)).ToColor(); int dr = endColor.R - startColor.R; @@ -1666,7 +1764,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Go for all sectors in between first and last int index = 0; - foreach(Sector s in orderedselection) { + foreach(Sector s in orderedselection) + { s.Fields.BeforeFieldsChange(); float u = index / (float)(orderedselection.Count - 1); Color c = Color.FromArgb(0, General.Clamp((int)(startColor.R + dr * u), 0, 255), General.Clamp((int)(startColor.G + dg * u), 0, 255), General.Clamp((int)(startColor.B + db * u), 0, 255)); @@ -1676,15 +1775,17 @@ namespace CodeImp.DoomBuilder.BuilderModes index++; } } - - } else { + } + else + { float startbrightness = start.Brightness; float endbrightness = end.Brightness; float delta = endbrightness - startbrightness; // Go for all sectors in between first and last int index = 0; - foreach(Sector s in orderedselection) { + foreach(Sector s in orderedselection) + { float u = index / (float)(orderedselection.Count - 1); float b = startbrightness + delta * u; s.Brightness = (int)b; @@ -1699,7 +1800,9 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.RedrawDisplay(); General.Interface.RefreshInfo(); General.Map.IsChanged = true; - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Select at least 3 sectors first!"); } } @@ -1711,7 +1814,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Need at least 3 selected sectors // The first and last are not modified ICollection orderedselection = General.Map.Map.GetSelectedSectors(true); - if(orderedselection.Count > 2) { + if(orderedselection.Count > 2) + { General.Interface.DisplayStatus(StatusType.Action, "Created gradient floor heights over selected sectors."); General.Map.UndoRedo.CreateUndo("Gradient floor heights"); @@ -1721,7 +1825,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Go for all sectors in between first and last int index = 0; - foreach(Sector s in orderedselection) { + foreach(Sector s in orderedselection) + { float u = index / (float)(orderedselection.Count - 1); float b = startlevel + delta * u; s.FloorHeight = (int)b; @@ -1731,7 +1836,9 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update General.Interface.RefreshInfo(); General.Map.IsChanged = true; - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Select at least 3 sectors first!"); } } @@ -1743,7 +1850,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Need at least 3 selected sectors // The first and last are not modified ICollection orderedselection = General.Map.Map.GetSelectedSectors(true); - if(orderedselection.Count > 2) { + if(orderedselection.Count > 2) + { General.Interface.DisplayStatus(StatusType.Action, "Created gradient ceiling heights over selected sectors."); General.Map.UndoRedo.CreateUndo("Gradient ceiling heights"); @@ -1753,7 +1861,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Go for all sectors in between first and last int index = 0; - foreach(Sector s in orderedselection) { + foreach(Sector s in orderedselection) + { float u = (float)index / (orderedselection.Count - 1); float b = startlevel + delta * u; s.CeilHeight = (int)b; @@ -1763,20 +1872,24 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update General.Interface.RefreshInfo(); General.Map.IsChanged = true; - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Select at least 3 sectors first!"); } } // Change heights [BeginAction("lowerfloor8")] - public void LowerFloors8() { + public void LowerFloors8() + { // Get selection ICollection selected = General.Map.Map.GetSelectedSectors(true); if(selected.Count == 0 && highlighted != null && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1786,9 +1899,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Floor heights change", this, UndoGroup.FloorHeightChange, CreateSelectionCRC(selected)); // Change heights - foreach(Sector s in selected) { - s.FloorHeight -= 8; - } + foreach(Sector s in selected) s.FloorHeight -= 8; // Update General.Interface.RefreshInfo(); @@ -1797,13 +1908,15 @@ namespace CodeImp.DoomBuilder.BuilderModes // Change heights [BeginAction("raisefloor8")] - public void RaiseFloors8() { + public void RaiseFloors8() + { // Get selection ICollection selected = General.Map.Map.GetSelectedSectors(true); if(selected.Count == 0 && highlighted != null && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1813,9 +1926,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Floor heights change", this, UndoGroup.FloorHeightChange, CreateSelectionCRC(selected)); // Change heights - foreach(Sector s in selected) { - s.FloorHeight += 8; - } + foreach(Sector s in selected) s.FloorHeight += 8; // Update General.Interface.RefreshInfo(); @@ -1824,13 +1935,15 @@ namespace CodeImp.DoomBuilder.BuilderModes // Change heights [BeginAction("lowerceiling8")] - public void LowerCeilings8() { + public void LowerCeilings8() + { // Get selection ICollection selected = General.Map.Map.GetSelectedSectors(true); if((selected.Count == 0) && (highlighted != null) && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1840,9 +1953,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Ceiling heights change", this, UndoGroup.CeilingHeightChange, CreateSelectionCRC(selected)); // Change heights - foreach(Sector s in selected) { - s.CeilHeight -= 8; - } + foreach(Sector s in selected) s.CeilHeight -= 8; // Update General.Interface.RefreshInfo(); @@ -1851,13 +1962,15 @@ namespace CodeImp.DoomBuilder.BuilderModes // Change heights [BeginAction("raiseceiling8")] - public void RaiseCeilings8() { + public void RaiseCeilings8() + { // Get selection ICollection selected = General.Map.Map.GetSelectedSectors(true); if(selected.Count == 0 && highlighted != null && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1867,9 +1980,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Ceiling heights change", this, UndoGroup.CeilingHeightChange, CreateSelectionCRC(selected)); // Change heights - foreach(Sector s in selected) { - s.CeilHeight += 8; - } + foreach(Sector s in selected) s.CeilHeight += 8; // Update General.Interface.RefreshInfo(); @@ -1878,13 +1989,15 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Raise brightness [BeginAction("raisebrightness8")] - public void RaiseBrightness8() { + public void RaiseBrightness8() + { // Get selection ICollection selected = General.Map.Map.GetSelectedSectors(true); if((selected.Count == 0) && (highlighted != null) && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1894,7 +2007,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Sector brightness change", this, UndoGroup.SectorBrightnessChange, CreateSelectionCRC(selected)); // Change heights - foreach(Sector s in selected) { + foreach(Sector s in selected) + { s.Brightness = General.Map.Config.BrightnessLevels.GetNextHigher(s.Brightness); s.UpdateNeeded = true; s.UpdateCache(); @@ -1910,13 +2024,15 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Lower brightness [BeginAction("lowerbrightness8")] - public void LowerBrightness8() { + public void LowerBrightness8() + { // Get selection ICollection selected = General.Map.Map.GetSelectedSectors(true); if(selected.Count == 0 && highlighted != null && !highlighted.IsDisposed) selected.Add(highlighted); - if (selected.Count == 0) { + if (selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1926,7 +2042,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Sector brightness change", this, UndoGroup.SectorBrightnessChange, CreateSelectionCRC(selected)); // Change heights - foreach(Sector s in selected) { + foreach(Sector s in selected) + { s.Brightness = General.Map.Config.BrightnessLevels.GetNextLower(s.Brightness); s.UpdateNeeded = true; s.UpdateCache(); @@ -1953,57 +2070,68 @@ namespace CodeImp.DoomBuilder.BuilderModes // Clear labels foreach(TextLabel[] labelarray in labels.Values) foreach(TextLabel l in labelarray) l.Text = ""; - updateOverlaySurfaces(); //mxd - updateEffectLabels(); //mxd + UpdateOverlaySurfaces(); //mxd + UpdateEffectLabels(); //mxd // Redraw General.Interface.RedrawDisplay(); } [BeginAction("placethings")] //mxd - public void PlaceThings() { + public void PlaceThings() + { // Make list of selected sectors ICollection sectors = General.Map.Map.GetSelectedSectors(true); List positions = new List(); - if(sectors.Count == 0) { - if(highlighted != null && !highlighted.IsDisposed) { + if(sectors.Count == 0) + { + if(highlighted != null && !highlighted.IsDisposed) + { sectors.Add(highlighted); - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires selection of some description!"); return; } } // Make list of suitable positions - foreach(Sector s in sectors) { + foreach(Sector s in sectors) + { Vector2D pos = (s.Labels.Count > 0 ? s.Labels[0].position : new Vector2D(s.BBox.X + s.BBox.Width / 2, s.BBox.Y + s.BBox.Height / 2)); if(!positions.Contains(pos)) positions.Add(pos); } - if(positions.Count < 1) { + if(positions.Count < 1) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to get vertex positions from selection!"); return; } - placeThingsAtPositions(positions); + PlaceThingsAtPositions(positions); } //mxd. rotate clockwise [BeginAction("rotateclockwise")] - public void RotateCW() { - rotateTextures(5); + public void RotateCW() + { + RotateTextures(5); } //mxd. rotate counterclockwise [BeginAction("rotatecounterclockwise")] - public void RotateCCW() { - rotateTextures(-5); + public void RotateCCW() + { + RotateTextures(-5); } //mxd - private void rotateTextures(float increment) { - if (!General.Map.UDMF) { + private void RotateTextures(float increment) + { + if (!General.Map.UDMF) + { General.Interface.DisplayStatus(StatusType.Warning, "This action works only in UDMF map format!"); return; } @@ -2014,14 +2142,16 @@ namespace CodeImp.DoomBuilder.BuilderModes if(sectors.Count == 0 && highlighted != null && !highlighted.IsDisposed) sectors.Add(highlighted); - if(sectors.Count == 0) { + if(sectors.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } string targets; string target; - switch (General.Map.Renderer2D.ViewMode) { + switch (General.Map.Renderer2D.ViewMode) + { case ViewMode.FloorTextures: target = " a floor"; targets = " floors"; @@ -2039,26 +2169,32 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Make undo - if(sectors.Count > 1) { + if(sectors.Count > 1) + { General.Map.UndoRedo.CreateUndo("Rotate " + sectors.Count + targets, this, UndoGroup.TextureRotationChange, CreateSelectionCRC(sectors)); General.Interface.DisplayStatus(StatusType.Action, "Rotated " + sectors.Count + targets + "."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Rotate" + target, this, UndoGroup.TextureRotationChange, CreateSelectionCRC(sectors)); General.Interface.DisplayStatus(StatusType.Action, "Rotated" + target + "."); } //rotate stuff - foreach (Sector s in sectors) { + foreach (Sector s in sectors) + { s.Fields.BeforeFieldsChange(); //floor - if(General.Map.Renderer2D.ViewMode == ViewMode.FloorTextures || General.Map.Renderer2D.ViewMode != ViewMode.CeilingTextures) { + if(General.Map.Renderer2D.ViewMode == ViewMode.FloorTextures || General.Map.Renderer2D.ViewMode != ViewMode.CeilingTextures) + { UDMFTools.SetFloat(s.Fields, "rotationfloor", General.ClampAngle(UDMFTools.GetFloat(s.Fields, "rotationfloor") + increment)); s.UpdateNeeded = true; } //ceiling - if(General.Map.Renderer2D.ViewMode == ViewMode.CeilingTextures || General.Map.Renderer2D.ViewMode != ViewMode.FloorTextures) { + if(General.Map.Renderer2D.ViewMode == ViewMode.CeilingTextures || General.Map.Renderer2D.ViewMode != ViewMode.FloorTextures) + { UDMFTools.SetFloat(s.Fields, "rotationceiling", General.ClampAngle(UDMFTools.GetFloat(s.Fields, "rotationceiling") + increment)); s.UpdateNeeded = true; } @@ -2072,10 +2208,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("selectsimilar")] - public void SelectSimilar() { + public void SelectSimilar() + { ICollection selection = General.Map.Map.GetSelectedSectors(true); - if(selection.Count == 0) { + if(selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } diff --git a/Source/Plugins/BuilderModes/ClassicModes/ThingsMode.cs b/Source/Plugins/BuilderModes/ClassicModes/ThingsMode.cs index d5e35cd5..dc28385c 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/ThingsMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/ThingsMode.cs @@ -19,15 +19,15 @@ using System; using System.Collections.Generic; using System.Windows.Forms; -using CodeImp.DoomBuilder.Windows; -using CodeImp.DoomBuilder.Map; -using CodeImp.DoomBuilder.Rendering; -using CodeImp.DoomBuilder.Geometry; -using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Actions; using CodeImp.DoomBuilder.Config; -using CodeImp.DoomBuilder.Types; +using CodeImp.DoomBuilder.Editing; +using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.GZBuilder.Geometry; +using CodeImp.DoomBuilder.Map; +using CodeImp.DoomBuilder.Rendering; +using CodeImp.DoomBuilder.Types; +using CodeImp.DoomBuilder.Windows; #endregion @@ -73,24 +73,12 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods - //mxd. This makes a CRC for the selection - public int CreateSelectionCRC() { - CRC crc = new CRC(); - ICollection orderedselection = General.Map.Map.GetSelectedThings(true); - crc.Add(orderedselection.Count); - foreach(Thing t in orderedselection) { - crc.Add(t.Index); - } - return (int)(crc.Value & 0xFFFFFFFF); - } - //mxd. This makes a CRC for given selection - public int CreateSelectionCRC(ICollection selection) { + private static int CreateSelectionCRC(ICollection selection) + { CRC crc = new CRC(); crc.Add(selection.Count); - foreach(Thing t in selection) { - crc.Add(t.Index); - } + foreach(Thing t in selection) crc.Add(t.Index); return (int)(crc.Value & 0xFFFFFFFF); } @@ -165,10 +153,12 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.RedrawSurface(); // Render lines and vertices - if (renderer.StartPlotter(true)) { + if (renderer.StartPlotter(true)) + { renderer.PlotLinedefSet(General.Map.Map.Linedefs); renderer.PlotVerticesSet(General.Map.Map.Vertices); - if(!panning) { //mxd + if(!panning) //mxd + { for(int i = 0; i < Thing.NUM_ARGS; i++) BuilderPlug.Me.PlotAssociations(renderer, association[i]); if((highlighted != null) && !highlighted.IsDisposed) BuilderPlug.Me.PlotReverseAssociations(renderer, highlightasso); } @@ -189,10 +179,12 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - if(!panning && General.Settings.GZShowEventLines) { + if(!panning && General.Settings.GZShowEventLines) + { List lines = GZBuilder.Data.LinksCollector.GetThingLinks(General.Map.ThingsFilter.VisibleThings); - foreach(Line3D l in lines) { + foreach(Line3D l in lines) + { renderer.RenderArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); } } @@ -304,7 +296,8 @@ namespace CodeImp.DoomBuilder.BuilderModes protected override void OnSelectBegin() { //mxd. Yep, it's kinda hackish... - if(awaitingMouseClick) { + if(awaitingMouseClick) + { awaitingMouseClick = false; ThingPointAtCursor(); return; @@ -346,8 +339,11 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.Finish(); renderer.Present(); } + + } //mxd - } else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedThingsCount > 0) { + else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedThingsCount > 0) + { General.Map.Map.ClearSelectedThings(); General.Interface.RedrawDisplay(); } @@ -397,9 +393,12 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Insert thing"); Thing t = InsertThing(mousemappos); - if(t == null) { + if(t == null) + { General.Map.UndoRedo.WithdrawUndo(); - } else { + } + else + { General.Map.Map.ClearSelectedThings(); t.Selected = true; Highlight(t); @@ -431,9 +430,12 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.OnEditFormValuesChanged -= thingEditForm_OnValuesChanged; // When a single thing was selected, deselect it now - if (selected.Count == 1) { + if (selected.Count == 1) + { General.Map.Map.ClearSelectedThings(); - } else if(result == DialogResult.Cancel) { //mxd. Restore selection... + } + else if(result == DialogResult.Cancel) //mxd. Restore selection... + { foreach (Thing t in selected) t.Selected = true; } General.Interface.RedrawDisplay(); @@ -449,7 +451,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void thingEditForm_OnValuesChanged(object sender, EventArgs e) { + private void thingEditForm_OnValuesChanged(object sender, EventArgs e) + { // Update things filter General.Map.ThingsFilter.Update(); @@ -464,22 +467,26 @@ namespace CodeImp.DoomBuilder.BuilderModes if(panning) return; //mxd. Skip all this jass while panning //mxd - if(selectpressed && !editpressed && !selecting) { + if(selectpressed && !editpressed && !selecting) + { // Check if moved enough pixels for multiselect Vector2D delta = mousedownpos - mousepos; if((Math.Abs(delta.x) > MULTISELECT_START_MOVE_PIXELS) || - (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) { + (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) + { // Start multiselecting StartMultiSelection(); } } - else if(paintselectpressed && !editpressed && !selecting) //mxd. Drag-select + else if(paintselectpressed && !editpressed && !selecting) //mxd. Drag-select { // Find the nearest thing within highlight range Thing t = MapSet.NearestThingSquareRange(General.Map.ThingsFilter.VisibleThings, mousemappos, BuilderPlug.Me.HighlightThingsRange / renderer.Scale); - if(t != null) { - if(t != highlighted) { + if(t != null) + { + if(t != highlighted) + { //toggle selected state if(General.Interface.ShiftState ^ BuilderPlug.Me.AdditiveSelect) t.Selected = true; @@ -494,7 +501,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update entire display General.Interface.RedrawDisplay(); } - } else if(highlighted != null) { + } else if(highlighted != null) + { highlighted = null; Highlight(null); @@ -508,8 +516,7 @@ namespace CodeImp.DoomBuilder.BuilderModes Thing t = MapSet.NearestThingSquareRange(General.Map.ThingsFilter.VisibleThings, mousemappos, BuilderPlug.Me.HighlightThingsRange / renderer.Scale); // Highlight if not the same - if(t != highlighted) - Highlight(t); + if(t != highlighted) Highlight(t); } } @@ -523,7 +530,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void OnPaintSelectBegin() { + protected override void OnPaintSelectBegin() + { highlighted = null; base.OnPaintSelectBegin(); } @@ -548,11 +556,14 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Start dragging the selection - if (!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || canDrag()) { //mxd + if (!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || CanDrag()) //mxd + { // Shift pressed? Clone things! - if (General.Interface.ShiftState) { + if (General.Interface.ShiftState) + { ICollection selection = General.Map.Map.GetSelectedThings(true); - foreach(Thing t in selection) { + foreach(Thing t in selection) + { Thing clone = InsertThing(t.Position); t.CopyPropertiesTo(clone); t.Selected = false; @@ -567,22 +578,24 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Check if any selected thing is outside of map boundary - private static bool canDrag() + private static bool CanDrag() { ICollection selectedthings = General.Map.Map.GetSelectedThings(true); int unaffectedCount = 0; - foreach(Thing t in selectedthings) { + foreach(Thing t in selectedthings) + { // Make sure the vertex is inside the map boundary if(t.Position.x < General.Map.Config.LeftBoundary || t.Position.x > General.Map.Config.RightBoundary - || t.Position.y > General.Map.Config.TopBoundary || t.Position.y < General.Map.Config.BottomBoundary) { - + || t.Position.y > General.Map.Config.TopBoundary || t.Position.y < General.Map.Config.BottomBoundary) + { t.Selected = false; unaffectedCount++; } } - if(unaffectedCount == selectedthings.Count) { + if(unaffectedCount == selectedthings.Count) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to drag selection: " + (selectedthings.Count == 1 ? "selected thing is" : "all of selected things are") + " outside of map boundary!"); General.Interface.RedrawDisplay(); return false; @@ -602,7 +615,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if(selectionvolume) { //mxd - switch(marqueSelectionMode) { + switch(marqueSelectionMode) + { case MarqueSelectionMode.SELECT: foreach(Thing t in General.Map.ThingsFilter.VisibleThings) t.Selected = selectionrect.Contains(t.Position.x, t.Position.y); @@ -664,7 +678,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void UpdateSelectionInfo() { + public override void UpdateSelectionInfo() + { if(General.Map.Map.SelectedThingsCount > 0) General.Interface.DisplayStatus(StatusType.Selection, General.Map.Map.SelectedThingsCount + (General.Map.Map.SelectedThingsCount == 1 ? " thing" : " things") + " selected."); else @@ -862,31 +877,36 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("thingaligntowall")] - public void AlignThingsToWall() { + public void AlignThingsToWall() + { // Make list of selected things List selected = new List(General.Map.Map.GetSelectedThings(true)); if((selected.Count == 0) && (highlighted != null) && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } List toAlign = new List(); - foreach(Thing t in selected) - if(t.IsModel) toAlign.Add(t); + foreach(Thing t in selected) if(t.IsModel) toAlign.Add(t); - if(toAlign.Count == 0) { + if(toAlign.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action only works for things with models!"); return; } // Make undo - if(toAlign.Count > 1) { + if(toAlign.Count > 1) + { General.Map.UndoRedo.CreateUndo("Align " + toAlign.Count + " things"); General.Interface.DisplayStatus(StatusType.Action, "Aligned " + toAlign.Count + " things."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Align thing"); General.Interface.DisplayStatus(StatusType.Action, "Aligned a thing."); } @@ -894,18 +914,21 @@ namespace CodeImp.DoomBuilder.BuilderModes //align things int thingsCount = General.Map.Map.Things.Count; - foreach(Thing t in toAlign) { + foreach(Thing t in toAlign) + { List excludedLines = new List(); bool aligned; - do{ + do + { Linedef l = General.Map.Map.NearestLinedef(t.Position, excludedLines); aligned = Tools.TryAlignThingToLine(t, l); - if(!aligned) { + if(!aligned) + { excludedLines.Add(l); - - if(excludedLines.Count == thingsCount) { + if(excludedLines.Count == thingsCount) + { ThingTypeInfo tti = General.Map.Data.GetThingInfo(t.Type); General.ErrorLogger.Add(ErrorType.Warning, "Unable to align Thing " + t.Index + " (" + tti.Title + ") to any linedef in a map!"); aligned = true; @@ -922,19 +945,22 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("thinglookatcursor")] - public void ThingPointAtCursor() { + public void ThingPointAtCursor() + { // Make list of selected things List selected = new List(General.Map.Map.GetSelectedThings(true)); if((selected.Count == 0) && (highlighted != null) && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } //check mouse position - if(!mousemappos.IsFinite()) { + if(!mousemappos.IsFinite()) + { awaitingMouseClick = true; General.Interface.DisplayStatus(StatusType.Warning, "Now click in the editing area!"); return; @@ -943,24 +969,32 @@ namespace CodeImp.DoomBuilder.BuilderModes awaitingMouseClick = false; // Make undo - if(selected.Count > 1) { + if(selected.Count > 1) + { General.Map.UndoRedo.CreateUndo("Rotate " + selected.Count + " things"); General.Interface.DisplayStatus(StatusType.Action, "Rotated " + selected.Count + " things."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Rotate thing"); General.Interface.DisplayStatus(StatusType.Action, "Rotated a thing."); } //change angle - if(General.Interface.CtrlState) { //point away - foreach(Thing t in selected) { + if(General.Interface.CtrlState) //point away + { + foreach(Thing t in selected) + { ThingTypeInfo info = General.Map.Data.GetThingInfo(t.Type); if(info == null || info.Category == null || info.Category.Arrow == 0) continue; t.Rotate(Vector2D.GetAngle(mousemappos, t.Position) + Angle2D.PI); } - } else { //point at - foreach(Thing t in selected) { + } + else //point at + { + foreach(Thing t in selected) + { ThingTypeInfo info = General.Map.Data.GetThingInfo(t.Type); if(info == null || info.Category == null || info.Category.Arrow == 0) continue; @@ -974,33 +1008,40 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. rotate clockwise [BeginAction("rotateclockwise")] - public void RotateCW() { - rotateThings(-5); + public void RotateCW() + { + RotateThings(-5); } //mxd. rotate counterclockwise [BeginAction("rotatecounterclockwise")] - public void RotateCCW() { - rotateThings(5); + public void RotateCCW() + { + RotateThings(5); } //mxd - private void rotateThings(int increment) { + private void RotateThings(int increment) + { // Make list of selected things List selected = new List(General.Map.Map.GetSelectedThings(true)); if(selected.Count == 0 && highlighted != null && !highlighted.IsDisposed) selected.Add(highlighted); - if(selected.Count == 0) { + if(selected.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } // Make undo - if(selected.Count > 1) { + if(selected.Count > 1) + { General.Map.UndoRedo.CreateUndo("Rotate " + selected.Count + " things", this, UndoGroup.ThingRotate, CreateSelectionCRC(selected)); General.Interface.DisplayStatus(StatusType.Action, "Rotated " + selected.Count + " things."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Rotate thing", this, UndoGroup.ThingRotate, CreateSelectionCRC(selected)); General.Interface.DisplayStatus(StatusType.Action, "Rotated a thing."); } @@ -1015,10 +1056,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("filterselectedthings")] - public void ShowFilterDialog() { + public void ShowFilterDialog() + { ICollection selection = General.Map.Map.GetSelectedThings(true); - if (selection.Count == 0) { + if (selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1028,10 +1071,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("selectsimilar")] - public void SelectSimilar() { + public void SelectSimilar() + { ICollection selection = General.Map.Map.GetSelectedThings(true); - if(selection.Count == 0) { + if(selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } diff --git a/Source/Plugins/BuilderModes/ClassicModes/VerticesMode.cs b/Source/Plugins/BuilderModes/ClassicModes/VerticesMode.cs index 519d06b3..023c27a1 100644 --- a/Source/Plugins/BuilderModes/ClassicModes/VerticesMode.cs +++ b/Source/Plugins/BuilderModes/ClassicModes/VerticesMode.cs @@ -89,7 +89,8 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.SetPresentation(Presentation.Standard); // Add toolbar buttons - if (General.Map.UDMF) { + if (General.Map.UDMF) + { General.Interface.AddButton(BuilderPlug.Me.MenusForm.CopyProperties); General.Interface.AddButton(BuilderPlug.Me.MenusForm.PasteProperties); General.Interface.AddButton(BuilderPlug.Me.MenusForm.PastePropertiesOptions); //mxd @@ -107,7 +108,8 @@ namespace CodeImp.DoomBuilder.BuilderModes base.OnDisengage(); // Remove toolbar buttons - if (General.Map.UDMF) { + if (General.Map.UDMF) + { General.Interface.RemoveButton(BuilderPlug.Me.MenusForm.CopyProperties); General.Interface.RemoveButton(BuilderPlug.Me.MenusForm.PasteProperties); General.Interface.RemoveButton(BuilderPlug.Me.MenusForm.PastePropertiesOptions); //mxd @@ -168,7 +170,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This highlights a new item - protected void Highlight(Vertex v) + private void Highlight(Vertex v) { // Update display if(renderer.StartPlotter(false)) @@ -233,8 +235,10 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.Finish(); renderer.Present(); } - //mxd - } else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedVerticessCount > 0) { + } + else if(BuilderPlug.Me.AutoClearSelection && General.Map.Map.SelectedVerticessCount > 0) + { + //mxd General.Map.Map.ClearSelectedVertices(); General.Interface.RedrawDisplay(); } @@ -376,9 +380,12 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.OnEditFormValuesChanged -= vertexEditForm_OnValuesChanged; // When a single vertex was selected, deselect it now - if (selected.Count == 1) { + if (selected.Count == 1) + { General.Map.Map.ClearSelectedVertices(); - } else if(result == DialogResult.Cancel) { //mxd. Restore selection... + } + else if(result == DialogResult.Cancel) //mxd. Restore selection... + { foreach (Vertex v in selected) v.Selected = true; } General.Interface.RedrawDisplay(); @@ -393,7 +400,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void vertexEditForm_OnValuesChanged(object sender, EventArgs e) { + private void vertexEditForm_OnValuesChanged(object sender, EventArgs e) + { // Update entire display General.Map.Map.Update(); General.Interface.RedrawDisplay(); @@ -406,11 +414,13 @@ namespace CodeImp.DoomBuilder.BuilderModes if(panning) return; //mxd. Skip all this jazz while panning //mxd - if(selectpressed && !editpressed && !selecting) { + if(selectpressed && !editpressed && !selecting) + { // Check if moved enough pixels for multiselect Vector2D delta = mousedownpos - mousepos; if((Math.Abs(delta.x) > MULTISELECT_START_MOVE_PIXELS) || - (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) { + (Math.Abs(delta.y) > MULTISELECT_START_MOVE_PIXELS)) + { // Start multiselecting StartMultiSelection(); } @@ -420,8 +430,10 @@ namespace CodeImp.DoomBuilder.BuilderModes // Find the nearest thing within highlight range Vertex v = General.Map.Map.NearestVertexSquareRange(mousemappos, BuilderPlug.Me.HighlightRange / renderer.Scale); - if(v != null) { - if(v != highlighted) { + if(v != null) + { + if(v != highlighted) + { //toggle selected state if(General.Interface.ShiftState ^ BuilderPlug.Me.AdditiveSelect) v.Selected = true; @@ -436,7 +448,9 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update entire display General.Interface.RedrawDisplay(); } - } else if(highlighted != null) { + } + else if(highlighted != null) + { highlighted = null; Highlight(null); @@ -449,31 +463,41 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Render insert vertex preview Linedef l = General.Map.Map.NearestLinedefRange(mousemappos, BuilderPlug.Me.SplitLinedefsRange / renderer.Scale); - if(l != null) { + if(l != null) + { // Snip to grid? - if(General.Interface.ShiftState ^ General.Interface.SnapToGrid) { + if(General.Interface.ShiftState ^ General.Interface.SnapToGrid) + { // Find all points where the grid intersects the line List points = l.GetGridIntersections(); - if(points.Count == 0) { + if(points.Count == 0) + { insertPreview = l.NearestOnLine(mousemappos); - } else { + } + else + { insertPreview = mousemappos; float distance = float.MaxValue; - foreach(Vector2D p in points) { + foreach(Vector2D p in points) + { float pdist = Vector2D.DistanceSq(p, mousemappos); - if(pdist < distance) { + if(pdist < distance) + { insertPreview = p; distance = pdist; } } } - } else { + } + else + { // Just use the nearest point on line insertPreview = l.NearestOnLine(mousemappos); } //render preview - if(renderer.StartOverlay(true)) { + if(renderer.StartOverlay(true)) + { float dist = Math.Min(Vector2D.Distance(mousemappos, insertPreview), BuilderPlug.Me.SplitLinedefsRange); byte alpha = (byte)(255 - (dist / BuilderPlug.Me.SplitLinedefsRange) * 128); float vsize = (renderer.VertexSize + 1.0f) / renderer.Scale; @@ -481,11 +505,14 @@ namespace CodeImp.DoomBuilder.BuilderModes renderer.Finish(); renderer.Present(); } - } else if(insertPreview.IsFinite()) { + } + else if(insertPreview.IsFinite()) + { insertPreview.x = float.NaN; //undraw preveiw - if(renderer.StartOverlay(true)) { + if(renderer.StartOverlay(true)) + { renderer.Finish(); renderer.Present(); } @@ -509,12 +536,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void BeginViewPan() { - if (insertPreview.IsFinite()) { + protected override void BeginViewPan() + { + if (insertPreview.IsFinite()) + { insertPreview.x = float.NaN; //undraw preveiw - if (renderer.StartOverlay(true)) { + if (renderer.StartOverlay(true)) + { renderer.Finish(); renderer.Present(); } @@ -524,7 +554,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void OnPaintSelectBegin() { + protected override void OnPaintSelectBegin() + { highlighted = null; base.OnPaintSelectBegin(); } @@ -549,29 +580,32 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Start dragging the selection - if(!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || canDrag()) //mxd + if(!BuilderPlug.Me.DontMoveGeometryOutsideMapBoundary || CanDrag()) //mxd General.Editing.ChangeMode(new DragVerticesMode(highlighted, mousedownmappos)); } } } //mxd. Check if any selected vertex is outside of map boundary - private static bool canDrag() + private static bool CanDrag() { ICollection selectedverts = General.Map.Map.GetSelectedVertices(true); int unaffectedCount = 0; - foreach(Vertex v in selectedverts) { + foreach(Vertex v in selectedverts) + { // Make sure the vertex is inside the map boundary if(v.Position.x < General.Map.Config.LeftBoundary || v.Position.x > General.Map.Config.RightBoundary - || v.Position.y > General.Map.Config.TopBoundary || v.Position.y < General.Map.Config.BottomBoundary) { + || v.Position.y > General.Map.Config.TopBoundary || v.Position.y < General.Map.Config.BottomBoundary) + { v.Selected = false; unaffectedCount++; } } - if(unaffectedCount == selectedverts.Count) { + if(unaffectedCount == selectedverts.Count) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to drag selection: " + (selectedverts.Count == 1 ? "selected vertex is" : "all of selected vertices are") + " outside of map boundary!"); General.Interface.RedrawDisplay(); return false; @@ -591,7 +625,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if(selectionvolume) { //mxd - switch(marqueSelectionMode) { + switch(marqueSelectionMode) + { case MarqueSelectionMode.SELECT: foreach(Vertex v in General.Map.Map.Vertices) v.Selected = selectionrect.Contains(v.Position.x, v.Position.y); @@ -654,7 +689,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void UpdateSelectionInfo() { + public override void UpdateSelectionInfo() + { if(General.Map.Map.SelectedVerticessCount > 0) General.Interface.DisplayStatus(StatusType.Selection, General.Map.Map.SelectedVerticessCount + (General.Map.Map.SelectedVerticessCount == 1 ? " vertex" : " vertices") + " selected."); else @@ -757,10 +793,13 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Find all points where the grid intersects the line List points = l.GetGridIntersections(); - if(points.Count == 0) { + if(points.Count == 0) + { //mxd. Just use the nearest point on line insertpos = l.NearestOnLine(mousemappos); - } else { + } + else + { insertpos = mousemappos; float distance = float.MaxValue; foreach(Vector2D p in points) @@ -809,9 +848,11 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Check if snapped vertex is still on top of a linedef l = General.Map.Map.NearestLinedefRange(v.Position, BuilderPlug.Me.SplitLinedefsRange / rendererscale); - if(l != null) { + if(l != null) + { //mxd - if(v.Position == l.Start.Position || v.Position == l.End.Position) { + if(v.Position == l.Start.Position || v.Position == l.End.Position) + { General.Interface.DisplayStatus(StatusType.Info, "There's already a vertex here."); General.Map.UndoRedo.WithdrawUndo(); return; @@ -819,7 +860,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.DisplayStatus(StatusType.Action, "Split a linedef."); Linedef sld = l.Split(v); - if(sld == null) { + if(sld == null) + { General.Map.UndoRedo.WithdrawUndo(); return; } @@ -848,23 +890,28 @@ namespace CodeImp.DoomBuilder.BuilderModes if(selected.Count == 0) return; // Make undo - if(selected.Count > 1) { + if(selected.Count > 1) + { General.Map.UndoRedo.CreateUndo("Delete " + selected.Count + " vertices"); General.Interface.DisplayStatus(StatusType.Action, "Deleted " + selected.Count + " vertices."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Delete vertex"); General.Interface.DisplayStatus(StatusType.Action, "Deleted a vertex."); } // Go for all vertices that need to be removed - foreach(Vertex v in selected) { + foreach(Vertex v in selected) + { // Not already removed automatically? - if(!v.IsDisposed) { + if(!v.IsDisposed) + { // If the vertex only has 2 linedefs attached, then merge the linedefs - if(v.Linedefs.Count == 2) { + if(v.Linedefs.Count == 2) + { Linedef ld1 = General.GetByIndex(v.Linedefs, 0); Linedef ld2 = General.GetByIndex(v.Linedefs, 1); - //Vertex v1 = (ld1.Start == v) ? ld1.End : ld1.Start; Vertex v2 = (ld2.Start == v) ? ld2.End : ld2.Start; if(ld1.Start == v) ld1.SetStartVertex(v2); else ld1.SetEndVertex(v2); ld2.Dispose(); @@ -892,40 +939,40 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Make list of selected vertices ICollection selected = General.Map.Map.GetSelectedVertices(true); - if(selected.Count == 0) { + if(selected.Count == 0) + { if(highlighted == null || highlighted.IsDisposed) return; selected.Add(highlighted); } // Make undo - if(selected.Count > 1) { + if(selected.Count > 1) + { General.Map.UndoRedo.CreateUndo("Dissolve " + selected.Count + " vertices"); General.Interface.DisplayStatus(StatusType.Action, "Dissolved " + selected.Count + " vertices."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Dissolve vertex"); General.Interface.DisplayStatus(StatusType.Action, "Dissolved a vertex."); } //collect linedefs count per vertex Dictionary linesPerVertex = new Dictionary(); - //List affectedSectors = new List(); - foreach(Vertex v in selected) { + foreach(Vertex v in selected) + { linesPerVertex.Add(v, v.Linedefs.Count); - - /*foreach(Linedef l in v.Linedefs) { - if(l.Front != null && l.Front.Sector != null && !affectedSectors.Contains(l.Front.Sector)) - affectedSectors.Add(l.Front.Sector); - if(l.Back != null && l.Back.Sector != null && !affectedSectors.Contains(l.Back.Sector)) - affectedSectors.Add(l.Back.Sector); - }*/ } // Go for all vertices that need to be removed - foreach(Vertex v in selected) { + foreach(Vertex v in selected) + { // Not already removed automatically? - if(!v.IsDisposed) { + if(!v.IsDisposed) + { // If the vertex only had 2 linedefs attached, then merge the linedefs - if(linesPerVertex[v] == 2) { + if(linesPerVertex[v] == 2) + { Linedef ld1 = General.GetByIndex(v.Linedefs, 0); Linedef ld2 = General.GetByIndex(v.Linedefs, 1); Vertex v1 = (ld1.Start == v) ? ld1.End : ld1.Start; @@ -933,16 +980,18 @@ namespace CodeImp.DoomBuilder.BuilderModes //don't merge if it will collapse 3-sided sector bool dontMerge = false; - foreach(Linedef l in v1.Linedefs) { + foreach(Linedef l in v1.Linedefs) + { if(l == ld2) continue; - if(l.Start == v2 || l.End == v2) { - tryJoinSectors(l); + if(l.Start == v2 || l.End == v2) + { + TryJoinSectors(l); dontMerge = true; break; } } - if(!dontMerge) mergeLines(selected, ld1, ld2, v); + if(!dontMerge) MergeLines(selected, ld1, ld2, v); } // Trash vertex @@ -968,10 +1017,14 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Make list of selected vertices ICollection selected = General.Map.Map.GetSelectedVertices(true); - if (selected.Count == 0) { - if (highlighted != null && !highlighted.IsDisposed){ + if (selected.Count == 0) + { + if (highlighted != null && !highlighted.IsDisposed) + { selected.Add(highlighted); - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires selection of some description!"); return; } @@ -980,7 +1033,7 @@ namespace CodeImp.DoomBuilder.BuilderModes List positions = new List(selected.Count); foreach (Vertex v in selected) if (!positions.Contains(v.Position)) positions.Add(v.Position); - placeThingsAtPositions(positions); + PlaceThingsAtPositions(positions); } //mxd @@ -989,7 +1042,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { ICollection selection = General.Map.Map.GetSelectedVertices(true); - if(selection.Count == 0) { + if(selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires a selection!"); return; } @@ -1003,7 +1057,7 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Action assist (mxd) //mxd - private void mergeLines(ICollection selected, Linedef ld1, Linedef ld2, Vertex v) + private static void MergeLines(ICollection selected, Linedef ld1, Linedef ld2, Vertex v) { Vertex v1 = (ld1.Start == v) ? ld1.End : ld1.Start; Vertex v2 = (ld2.Start == v) ? ld2.End : ld2.Start; @@ -1013,38 +1067,43 @@ namespace CodeImp.DoomBuilder.BuilderModes ld2.Dispose(); bool redraw = true; - if(!v2.IsDisposed && selected.Contains(v2) && v2.Linedefs.Count == 2) { + if(!v2.IsDisposed && selected.Contains(v2) && v2.Linedefs.Count == 2) + { Linedef[] lines = new Linedef[2]; v2.Linedefs.CopyTo(lines, 0); Linedef other = lines[0] == ld2 ? lines[1] :lines[0]; - mergeLines(selected, ld1, other, v2); + MergeLines(selected, ld1, other, v2); v2.Dispose(); redraw = false; } - if(!v1.IsDisposed && selected.Contains(v1) && v1.Linedefs.Count == 2) { + if(!v1.IsDisposed && selected.Contains(v1) && v1.Linedefs.Count == 2) + { Linedef[] lines = new Linedef[2]; v1.Linedefs.CopyTo(lines, 0); Linedef other = lines[0] == ld1 ? lines[1] : lines[0]; - mergeLines(selected, other, ld1, v1); + MergeLines(selected, other, ld1, v1); v1.Dispose(); redraw = false; } - if(redraw && ld1.Start != null && ld1.End != null) { + if(redraw && ld1.Start != null && ld1.End != null) + { Vector2D start = ld1.Start.Position; Vector2D end = ld1.End.Position; ld1.Dispose(); - drawLine(start, end); - } else { + DrawLine(start, end); + } + else + { ld1.Dispose(); } } //mxd - private static void drawLine(Vector2D start, Vector2D end) + private static void DrawLine(Vector2D start, Vector2D end) { DrawnVertex dv1 = new DrawnVertex(); DrawnVertex dv2 = new DrawnVertex(); @@ -1062,11 +1121,13 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. If there are different sectors on both sides of given linedef, join them - private void tryJoinSectors(Linedef ld) + private static void TryJoinSectors(Linedef ld) { if(ld.IsDisposed) return; - if(ld.Front != null && ld.Front.Sector != null && ld.Back != null && ld.Back.Sector != null && ld.Front.Sector.Index != ld.Back.Sector.Index) { + if(ld.Front != null && ld.Front.Sector != null && ld.Back != null + && ld.Back.Sector != null && ld.Front.Sector.Index != ld.Back.Sector.Index) + { if(ld.Front.Sector.BBox.Width * ld.Front.Sector.BBox.Height > ld.Back.Sector.BBox.Width * ld.Back.Sector.BBox.Height) ld.Back.Sector.Join(ld.Front.Sector); else diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckClosedSectors.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckClosedSectors.cs index b6799d72..5c9c9ae0 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckClosedSectors.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckClosedSectors.cs @@ -99,7 +99,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // This is from the sides point of view, where the side is always the "right" of line, // so start and end are flipped depending if the current side is the front of the // line or not - if(sd.IsFront) { + if(sd.IsFront) + { vertices[sd.Line.Start] |= 1; vertices[sd.Line.End] |= 2; } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckMissingFlats.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckMissingFlats.cs index 8fb57d0c..bff91906 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckMissingFlats.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckMissingFlats.cs @@ -19,7 +19,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Constructor / Destructor // Constructor - public CheckMissingFlats() { + public CheckMissingFlats() + { // Total progress is done when all sectors are checked SetTotalProgress(General.Map.Map.Sectors.Count / PROGRESS_STEP); } @@ -29,12 +30,14 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This runs the check - public override void Run() { + public override void Run() + { int progress = 0; int stepprogress = 0; // Go for all the sectors - foreach(Sector s in General.Map.Map.Sectors) { + foreach(Sector s in General.Map.Map.Sectors) + { // Check floor texture if(s.LongFloorTexture == MapSet.EmptyLongName) SubmitResult(new ResultMissingFlat(s, false)); @@ -45,7 +48,8 @@ namespace CodeImp.DoomBuilder.BuilderModes try { Thread.Sleep(0); } catch(ThreadInterruptedException) { return; } // We are making progress! - if((++progress / PROGRESS_STEP) > stepprogress) { + if((++progress / PROGRESS_STEP) > stepprogress) + { stepprogress = (progress / PROGRESS_STEP); AddProgress(1); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingLines.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingLines.cs index 8d50b436..aac629c0 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingLines.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingLines.cs @@ -75,7 +75,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. This can also happen. I suppose. Some people manage to do this. I dunno how, but they do... if((l.Start.Position == d.Start.Position && l.End.Position == d.End.Position) - || (l.Start.Position == d.End.Position && l.End.Position == d.Start.Position)) { + || (l.Start.Position == d.End.Position && l.End.Position == d.Start.Position)) + { SubmitResult(new ResultLineOverlapping(l, d)); donelines[d] = d; } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingVertices.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingVertices.cs index 1736532f..6988c052 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingVertices.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckOverlappingVertices.cs @@ -21,7 +21,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Constructor / Destructor // Constructor - public CheckOverlappingVertices() { + public CheckOverlappingVertices() + { // Total progress is done when all lines are checked SetTotalProgress(General.Map.Map.Vertices.Count / PROGRESS_STEP); } @@ -31,32 +32,31 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This runs the check - public override void Run() { + public override void Run() + { BlockMap blockmap = BuilderPlug.Me.ErrorCheckForm.BlockMap; Dictionary> doneverts = new Dictionary>(); int progress = 0; int stepprogress = 0; // Go for all the verts - foreach(Vertex v in General.Map.Map.Vertices) { + foreach(Vertex v in General.Map.Map.Vertices) + { BlockEntry block = blockmap.GetBlockAt(v.Position); // Go for all the linedefs that our vertex could overlap - foreach(Linedef l in block.Lines) { + foreach(Linedef l in block.Lines) + { if(v == l.Start || v == l.End) continue; - if((float)Math.Round(l.Line.GetDistanceToLine(v.Position, true), 3) == 0) { + if((float)Math.Round(l.Line.GetDistanceToLine(v.Position, true), 3) == 0) SubmitResult(new ResultVertexOverlappingLine(v, l)); - } } // Go for all the verts that our vertex could overlap - foreach(Vertex bv in block.Vertices) { + foreach(Vertex bv in block.Vertices) + { if(bv == v || (doneverts.ContainsKey(v) && doneverts[v].Contains(bv)) || (doneverts.ContainsKey(bv) && doneverts[bv].Contains(v))) continue; - - if(bv.Position == v.Position) { - SubmitResult(new ResultVertexOverlappingVertex(v, bv)); - } - + if(bv.Position == v.Position) SubmitResult(new ResultVertexOverlappingVertex(v, bv)); if (!doneverts.ContainsKey(v)) doneverts.Add(v, new List()); doneverts[v].Add(bv); } @@ -66,7 +66,8 @@ namespace CodeImp.DoomBuilder.BuilderModes catch(ThreadInterruptedException) { return; } // We are making progress! - if((++progress / PROGRESS_STEP) > stepprogress) { + if((++progress / PROGRESS_STEP) > stepprogress) + { stepprogress = (progress / PROGRESS_STEP); AddProgress(1); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckStrayVertices.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckStrayVertices.cs index 8fbddc8b..e93f7c7b 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckStrayVertices.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckStrayVertices.cs @@ -9,26 +9,29 @@ namespace CodeImp.DoomBuilder.BuilderModes private const int PROGRESS_STEP = 1000; // Constructor - public CheckStrayVertices() { + public CheckStrayVertices() + { // Total progress is done when all vertices are checked SetTotalProgress(General.Map.Map.Vertices.Count / PROGRESS_STEP); } // This runs the check - public override void Run() { + public override void Run() + { int progress = 0; int stepprogress = 0; // Go for all things - foreach(Vertex v in General.Map.Map.Vertices) { - if(v.Linedefs == null || v.Linedefs.Count == 0) - SubmitResult(new ResultStrayVertex(v)); + foreach(Vertex v in General.Map.Map.Vertices) + { + if(v.Linedefs == null || v.Linedefs.Count == 0) SubmitResult(new ResultStrayVertex(v)); // Handle thread interruption try { Thread.Sleep(0); } catch(ThreadInterruptedException) { return; } // We are making progress! - if((++progress / PROGRESS_STEP) > stepprogress) { + if((++progress / PROGRESS_STEP) > stepprogress) + { stepprogress = (progress / PROGRESS_STEP); AddProgress(1); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckTextureAlignment.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckTextureAlignment.cs index 775a5697..3de09ede 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckTextureAlignment.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckTextureAlignment.cs @@ -295,7 +295,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - private float GetSidedefValue(Sidedef target, VisualGeometryType targetparttype, string key, float defaultvalue) + private static float GetSidedefValue(Sidedef target, VisualGeometryType targetparttype, string key, float defaultvalue) { switch (targetparttype) { diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckUnknownThings.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckUnknownThings.cs index fddc85d4..bd7282c3 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckUnknownThings.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckUnknownThings.cs @@ -4,31 +4,35 @@ using CodeImp.DoomBuilder.Map; namespace CodeImp.DoomBuilder.BuilderModes { [ErrorChecker("Check unknown things", true, 50)] - public class CheckUnknownThings : ErrorChecker { + public class CheckUnknownThings : ErrorChecker + { private const int PROGRESS_STEP = 1000; // Constructor - public CheckUnknownThings() { + public CheckUnknownThings() + { // Total progress is done when all things are checked SetTotalProgress(General.Map.Map.Things.Count / PROGRESS_STEP); } // This runs the check - public override void Run() { + public override void Run() + { int progress = 0; int stepprogress = 0; // Go for all things - foreach (Thing t in General.Map.Map.Things) { - if (General.Map.Data.GetThingInfoEx(t.Type) == null) - SubmitResult(new ResultUnknownThing(t)); + foreach (Thing t in General.Map.Map.Things) + { + if (General.Map.Data.GetThingInfoEx(t.Type) == null) SubmitResult(new ResultUnknownThing(t)); // Handle thread interruption try { Thread.Sleep(0); } catch (ThreadInterruptedException) { return; } // We are making progress! - if ((++progress / PROGRESS_STEP) > stepprogress) { + if ((++progress / PROGRESS_STEP) > stepprogress) + { stepprogress = (progress / PROGRESS_STEP); AddProgress(1); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/CheckUnusedThings.cs b/Source/Plugins/BuilderModes/ErrorChecks/CheckUnusedThings.cs index 42094951..e127aaad 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/CheckUnusedThings.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/CheckUnusedThings.cs @@ -77,7 +77,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - private string GetDescription(string group) + private static string GetDescription(string group) { switch(group) { diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultLineOverlapping.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultLineOverlapping.cs index da7fb75e..5c9fa57b 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultLineOverlapping.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultLineOverlapping.cs @@ -58,10 +58,12 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This sets if this result is displayed in ErrorCheckForm (mxd) - internal override void Hide(bool hide) { + internal override void Hide(bool hide) + { hidden = hide; Type t = this.GetType(); - if (hide) { + if (hide) + { line1.IgnoredErrorChecks.Add(t); line2.IgnoredErrorChecks.Add(t); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingFlat.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingFlat.cs index 28bb6c55..12c98cd5 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingFlat.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingFlat.cs @@ -1,6 +1,7 @@ #region ================== Namespaces using System; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Rendering; @@ -65,7 +66,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. More rendering - public override void RenderOverlaySelection(IRenderer2D renderer) { + public override void RenderOverlaySelection(IRenderer2D renderer) + { if(!BuilderPlug.Me.UseHighlight) return; renderer.RenderHighlight(sector.FlatVertices, General.Colors.Selection.WithAlpha(64).ToInt()); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingTexture.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingTexture.cs index 2fd77c79..148977e7 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingTexture.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultMissingTexture.cs @@ -17,6 +17,7 @@ #region ================== Namespaces using System; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Rendering; diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultSectorInvalid.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultSectorInvalid.cs index 46b2b9f7..66cf349e 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultSectorInvalid.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultSectorInvalid.cs @@ -51,7 +51,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This must return the string that is displayed in the listbox - public override string ToString() { + public override string ToString() + { if (sector.Sidedefs != null && sector.Sidedefs.Count > 2) return "Area of sector " + sector.Index + " is 0"; return "Sector " + sector.Index + " has " + (sector.Sidedefs == null ? "no" : sector.Sidedefs.Count.ToString()) + " sidedefs"; @@ -64,12 +65,14 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Fix by merging with surrounding geometry/removing - public override bool Button1Click(bool batchMode) { + public override bool Button1Click(bool batchMode) + { if(!batchMode) General.Map.UndoRedo.CreateUndo("Invalid sector correction"); //collect the lines List lines = new List(); - foreach (Sidedef side in sector.Sidedefs) { + foreach (Sidedef side in sector.Sidedefs) + { if (!lines.Contains(side.Line) && !side.Line.IsDisposed) lines.Add(side.Line); } @@ -78,12 +81,17 @@ namespace CodeImp.DoomBuilder.BuilderModes foreach (Linedef line in lines) if (line.Length == 0) line.Dispose(); - if (lines.Count == 0) { + if (lines.Count == 0) + { sector.Dispose(); - } else if(lines.Count < 3) { //merge with surrounding geometry + } + else if(lines.Count < 3) //merge with surrounding geometry + { bool merged = false; - foreach(Sidedef side in sector.Sidedefs) { - if(side.Other != null && side.Other.Sector != null) { + foreach(Sidedef side in sector.Sidedefs) + { + if(side.Other != null && side.Other.Sector != null) + { sector.Join(side.Other.Sector); merged = true; break; @@ -92,8 +100,11 @@ namespace CodeImp.DoomBuilder.BuilderModes //oh well, I don't know what else I can do here... if(!merged) sector.Dispose(); - } else { //redraw the lines - foreach(Linedef line in lines) { + } + else //redraw the lines + { + foreach(Linedef line in lines) + { if(line.IsDisposed) continue; DrawnVertex start = new DrawnVertex { pos = line.Start.Position, stitch = true, stitchline = true }; DrawnVertex end = new DrawnVertex { pos = line.End.Position, stitch = true, stitchline = true }; diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultTexturesMisaligned.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultTexturesMisaligned.cs index 13e9e8d1..331bb5fa 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultTexturesMisaligned.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultTexturesMisaligned.cs @@ -58,7 +58,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This sets if this result is displayed in ErrorCheckForm (mxd) - internal override void Hide(bool hide) { + internal override void Hide(bool hide) + { hidden = hide; Type t = this.GetType(); if (hide) diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownFlat.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownFlat.cs index a52525a6..4fd24a70 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownFlat.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownFlat.cs @@ -17,6 +17,7 @@ #region ================== Namespaces using System; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Rendering; @@ -83,7 +84,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. More rendering - public override void RenderOverlaySelection(IRenderer2D renderer) { + public override void RenderOverlaySelection(IRenderer2D renderer) + { if(!BuilderPlug.Me.UseHighlight) return; renderer.RenderHighlight(sector.FlatVertices, General.Colors.Selection.WithAlpha(64).ToInt()); } diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownTexture.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownTexture.cs index f1ae9e3f..12fc6a2e 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownTexture.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultUnknownTexture.cs @@ -17,6 +17,7 @@ #region ================== Namespaces using System; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Map; using CodeImp.DoomBuilder.Rendering; diff --git a/Source/Plugins/BuilderModes/ErrorChecks/ResultVertexOverlappingLine.cs b/Source/Plugins/BuilderModes/ErrorChecks/ResultVertexOverlappingLine.cs index a0ae3fdd..8d4ef1d3 100644 --- a/Source/Plugins/BuilderModes/ErrorChecks/ResultVertexOverlappingLine.cs +++ b/Source/Plugins/BuilderModes/ErrorChecks/ResultVertexOverlappingLine.cs @@ -85,10 +85,13 @@ namespace CodeImp.DoomBuilder.BuilderModes //check that we don't have duplicate lines List lines = new List(vertex.Linedefs); - for(int i = 0; i < lines.Count - 1; i++) { - for(int c = i + 1; c < lines.Count; c++) { + for(int i = 0; i < lines.Count - 1; i++) + { + for(int c = i + 1; c < lines.Count; c++) + { if( (lines[i].Start == lines[c].Start && lines[i].End == lines[c].End) || - (lines[i].Start == lines[c].End && lines[i].End == lines[c].Start)) { + (lines[i].Start == lines[c].End && lines[i].End == lines[c].Start)) + { lines[c].Join(lines[i]); } } diff --git a/Source/Plugins/BuilderModes/FindReplace/BaseFindLinedef.cs b/Source/Plugins/BuilderModes/FindReplace/BaseFindLinedef.cs index 7a0d8846..c6087c6e 100644 --- a/Source/Plugins/BuilderModes/FindReplace/BaseFindLinedef.cs +++ b/Source/Plugins/BuilderModes/FindReplace/BaseFindLinedef.cs @@ -14,11 +14,15 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This is called when a specific object is selected from the list - public override void ObjectSelected(FindReplaceObject[] selection) { - if(selection.Length == 1) { + public override void ObjectSelected(FindReplaceObject[] selection) + { + if(selection.Length == 1) + { ZoomToSelection(selection); General.Interface.ShowLinedefInfo(selection[0].Linedef); - } else { + } + else + { General.Interface.HideInfo(); } @@ -27,14 +31,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Render selection - public override void PlotSelection(IRenderer2D renderer, FindReplaceObject[] selection) { - foreach(FindReplaceObject o in selection) { + public override void PlotSelection(IRenderer2D renderer, FindReplaceObject[] selection) + { + foreach(FindReplaceObject o in selection) renderer.PlotLinedef(o.Linedef, General.Colors.Selection); - } } // Edit objects - public override void EditObjects(FindReplaceObject[] selection) { + public override void EditObjects(FindReplaceObject[] selection) + { List linedefs = new List(selection.Length); foreach(FindReplaceObject o in selection) linedefs.Add(o.Linedef); General.Interface.ShowEditLinedefs(linedefs); diff --git a/Source/Plugins/BuilderModes/FindReplace/BaseFindSector.cs b/Source/Plugins/BuilderModes/FindReplace/BaseFindSector.cs index 351322c7..a5b06a7e 100644 --- a/Source/Plugins/BuilderModes/FindReplace/BaseFindSector.cs +++ b/Source/Plugins/BuilderModes/FindReplace/BaseFindSector.cs @@ -14,11 +14,15 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This is called when a specific object is selected from the list - public override void ObjectSelected(FindReplaceObject[] selection) { - if(selection.Length == 1) { + public override void ObjectSelected(FindReplaceObject[] selection) + { + if(selection.Length == 1) + { ZoomToSelection(selection); General.Interface.ShowSectorInfo(selection[0].Sector); - } else { + } + else + { General.Interface.HideInfo(); } @@ -27,26 +31,28 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Render selection - public override void PlotSelection(IRenderer2D renderer, FindReplaceObject[] selection) { - foreach(FindReplaceObject o in selection) { - foreach(Sidedef sd in o.Sector.Sidedefs) { + public override void PlotSelection(IRenderer2D renderer, FindReplaceObject[] selection) + { + foreach(FindReplaceObject o in selection) + { + foreach(Sidedef sd in o.Sector.Sidedefs) renderer.PlotLinedef(sd.Line, General.Colors.Selection); - } } } //mxd. Render selection highlight - public override void RenderOverlaySelection(IRenderer2D renderer, FindReplaceObject[] selection) { + public override void RenderOverlaySelection(IRenderer2D renderer, FindReplaceObject[] selection) + { if(!BuilderPlug.Me.UseHighlight) return; int color = General.Colors.Selection.WithAlpha(64).ToInt(); - foreach(FindReplaceObject o in selection) { + foreach(FindReplaceObject o in selection) renderer.RenderHighlight(o.Sector.FlatVertices, color); - } } // Edit objects - public override void EditObjects(FindReplaceObject[] selection) { + public override void EditObjects(FindReplaceObject[] selection) + { List sectors = new List(selection.Length); foreach(FindReplaceObject o in selection) sectors.Add(o.Sector); General.Interface.ShowEditSectors(sectors); diff --git a/Source/Plugins/BuilderModes/FindReplace/BaseFindSidedef.cs b/Source/Plugins/BuilderModes/FindReplace/BaseFindSidedef.cs index 60abeeef..047b06c0 100644 --- a/Source/Plugins/BuilderModes/FindReplace/BaseFindSidedef.cs +++ b/Source/Plugins/BuilderModes/FindReplace/BaseFindSidedef.cs @@ -33,9 +33,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Render selection public override void PlotSelection(IRenderer2D renderer, FindReplaceObject[] selection) { - foreach(FindReplaceObject o in selection) { + foreach(FindReplaceObject o in selection) renderer.PlotLinedef(o.Sidedef.Line, General.Colors.Selection); - } } // Edit objects diff --git a/Source/Plugins/BuilderModes/FindReplace/BaseFindThing.cs b/Source/Plugins/BuilderModes/FindReplace/BaseFindThing.cs index 61ce8974..5b399b37 100644 --- a/Source/Plugins/BuilderModes/FindReplace/BaseFindThing.cs +++ b/Source/Plugins/BuilderModes/FindReplace/BaseFindThing.cs @@ -14,11 +14,15 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Methods // This is called when a specific object is selected from the list - public override void ObjectSelected(FindReplaceObject[] selection) { - if(selection.Length == 1) { + public override void ObjectSelected(FindReplaceObject[] selection) + { + if(selection.Length == 1) + { ZoomToSelection(selection); General.Interface.ShowThingInfo(selection[0].Thing); - } else { + } + else + { General.Interface.HideInfo(); } @@ -27,14 +31,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Render selection - public override void RenderThingsSelection(IRenderer2D renderer, FindReplaceObject[] selection) { - foreach(FindReplaceObject o in selection) { + public override void RenderThingsSelection(IRenderer2D renderer, FindReplaceObject[] selection) + { + foreach(FindReplaceObject o in selection) renderer.RenderThing(o.Thing, General.Colors.Selection, 1.0f); - } } // Edit objects - public override void EditObjects(FindReplaceObject[] selection) { + public override void EditObjects(FindReplaceObject[] selection) + { List things = new List(selection.Length); foreach(FindReplaceObject o in selection) things.Add(o.Thing); General.Interface.ShowEditThings(things); diff --git a/Source/Plugins/BuilderModes/FindReplace/FindLinedefTypes.cs b/Source/Plugins/BuilderModes/FindReplace/FindLinedefTypes.cs index 2ffa9daf..c670bbf5 100644 --- a/Source/Plugins/BuilderModes/FindReplace/FindLinedefTypes.cs +++ b/Source/Plugins/BuilderModes/FindReplace/FindLinedefTypes.cs @@ -120,14 +120,14 @@ namespace CodeImp.DoomBuilder.BuilderModes if(int.TryParse(parts[0], out action)) { //parse the arg value out - if (parts.Length > 1) { + if (parts.Length > 1) + { args = new[] {0, 0, 0, 0, 0}; string[] argparts = parts[1].Split(','); int argout; - for(int i = 0; i < argparts.Length && i < args.Length; i++) { - if (int.TryParse(argparts[i], out argout)) { - args[i] = argout; - } + for(int i = 0; i < argparts.Length && i < args.Length; i++) + { + if (int.TryParse(argparts[i], out argout)) args[i] = argout; } } @@ -147,11 +147,13 @@ namespace CodeImp.DoomBuilder.BuilderModes argtext = ""; //if args were specified, then process them - if (args != null) { + if (args != null) + { argtext = " args: ("; for (int x = 0; x < args.Length; x++) { - if (args[x] != 0 && args[x] != l.Args[x]) { + if (args[x] != 0 && args[x] != l.Args[x]) + { match = false; break; } @@ -160,7 +162,8 @@ namespace CodeImp.DoomBuilder.BuilderModes argtext += ")"; } - if (match) { + if (match) + { // Replace if(replace) l.Action = replaceaction; @@ -179,7 +182,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private List GetGeneralizedBits(int effect) + private static List GetGeneralizedBits(int effect) { if(!General.Map.Config.GeneralizedActions) return new List(); List bits = new List(); @@ -200,7 +203,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private bool BitsMatch(int action, List expectedbits) + private static bool BitsMatch(int action, List expectedbits) { if(!General.Map.Config.GeneralizedActions) return false; diff --git a/Source/Plugins/BuilderModes/FindReplace/FindSectorBrightness.cs b/Source/Plugins/BuilderModes/FindReplace/FindSectorBrightness.cs index a88bd569..1ba6dc71 100644 --- a/Source/Plugins/BuilderModes/FindReplace/FindSectorBrightness.cs +++ b/Source/Plugins/BuilderModes/FindReplace/FindSectorBrightness.cs @@ -16,17 +16,20 @@ namespace CodeImp.DoomBuilder.BuilderModes // This is called to perform a search (and replace) // Returns a list of items to show in the results list // replacewith is null when not replacing - public override FindReplaceObject[] Find(string value, bool withinselection, bool replace, string replacewith, bool keepselection) { + public override FindReplaceObject[] Find(string value, bool withinselection, bool replace, string replacewith, bool keepselection) + { List objs = new List(); // Interpret the replacement int replacebrightness = 0; - if(replace) { + if(replace) + { // If it cannot be interpreted, set replacewith to null (not replacing at all) if(!int.TryParse(replacewith, out replacebrightness)) replacewith = null; if(replacebrightness < 0) replacewith = null; if(replacebrightness > 255) replacewith = null; - if(replacewith == null) { + if(replacewith == null) + { MessageBox.Show("Invalid replace value for this search type!", "Find and Replace", MessageBoxButtons.OK, MessageBoxIcon.Error); return objs.ToArray(); } @@ -34,14 +37,17 @@ namespace CodeImp.DoomBuilder.BuilderModes // Interpret the number given int brightness; - if(int.TryParse(value, out brightness)) { + if(int.TryParse(value, out brightness)) + { // Where to search? ICollection list = withinselection ? General.Map.Map.GetSelectedSectors(true) : General.Map.Map.Sectors; // Go for all sectors - foreach(Sector s in list) { + foreach(Sector s in list) + { // Brightness matches? - if(s.Brightness == brightness) { + if(s.Brightness == brightness) + { // Replace if(replace) s.Brightness = replacebrightness; @@ -51,7 +57,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //refresh map - if(replace) { + if(replace) + { General.Map.Map.Update(); General.Map.IsChanged = true; } diff --git a/Source/Plugins/BuilderModes/FindReplace/FindSectorCeilingHeight.cs b/Source/Plugins/BuilderModes/FindReplace/FindSectorCeilingHeight.cs index c9abe80a..ceecc742 100644 --- a/Source/Plugins/BuilderModes/FindReplace/FindSectorCeilingHeight.cs +++ b/Source/Plugins/BuilderModes/FindReplace/FindSectorCeilingHeight.cs @@ -16,15 +16,18 @@ namespace CodeImp.DoomBuilder.BuilderModes.FindReplace // This is called to perform a search (and replace) // Returns a list of items to show in the results list // replacewith is null when not replacing - public override FindReplaceObject[] Find(string value, bool withinselection, bool replace, string replacewith, bool keepselection) { + public override FindReplaceObject[] Find(string value, bool withinselection, bool replace, string replacewith, bool keepselection) + { List objs = new List(); // Interpret the replacement int replaceheight = 0; - if(replace) { + if(replace) + { // If it cannot be interpreted, set replacewith to null (not replacing at all) if(!int.TryParse(replacewith, out replaceheight)) replacewith = null; - if(replacewith == null) { + if(replacewith == null) + { MessageBox.Show("Invalid replace value for this search type!", "Find and Replace", MessageBoxButtons.OK, MessageBoxIcon.Error); return objs.ToArray(); } @@ -32,14 +35,17 @@ namespace CodeImp.DoomBuilder.BuilderModes.FindReplace // Interpret the number given int height; - if(int.TryParse(value, out height)) { + if(int.TryParse(value, out height)) + { // Where to search? ICollection list = withinselection ? General.Map.Map.GetSelectedSectors(true) : General.Map.Map.Sectors; // Go for all sectors - foreach(Sector s in list) { + foreach(Sector s in list) + { // Height matches? - if(s.CeilHeight == height) { + if(s.CeilHeight == height) + { // Replace if(replace) s.CeilHeight = replaceheight; @@ -49,7 +55,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.FindReplace } //refresh map - if(replace) { + if(replace) + { General.Map.Map.Update(); General.Map.IsChanged = true; } diff --git a/Source/Plugins/BuilderModes/FindReplace/FindSectorEffect.cs b/Source/Plugins/BuilderModes/FindReplace/FindSectorEffect.cs index 9172140c..4ca74c82 100644 --- a/Source/Plugins/BuilderModes/FindReplace/FindSectorEffect.cs +++ b/Source/Plugins/BuilderModes/FindReplace/FindSectorEffect.cs @@ -132,7 +132,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private List GetGeneralizedBits(int effect) + private static List GetGeneralizedBits(int effect) { if (!General.Map.Config.GeneralizedEffects) return new List(); List bits = new List(); @@ -150,7 +150,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private bool BitsMatch(int effect, List expectedbits) + private static bool BitsMatch(int effect, List expectedbits) { if (!General.Map.Config.GeneralizedEffects) return false; diff --git a/Source/Plugins/BuilderModes/FindReplace/FindSectorFloorHeight.cs b/Source/Plugins/BuilderModes/FindReplace/FindSectorFloorHeight.cs index 415d6940..d0e297fe 100644 --- a/Source/Plugins/BuilderModes/FindReplace/FindSectorFloorHeight.cs +++ b/Source/Plugins/BuilderModes/FindReplace/FindSectorFloorHeight.cs @@ -16,15 +16,18 @@ namespace CodeImp.DoomBuilder.BuilderModes.FindReplace // This is called to perform a search (and replace) // Returns a list of items to show in the results list // replacewith is null when not replacing - public override FindReplaceObject[] Find(string value, bool withinselection, bool replace, string replacewith, bool keepselection) { + public override FindReplaceObject[] Find(string value, bool withinselection, bool replace, string replacewith, bool keepselection) + { List objs = new List(); // Interpret the replacement int replaceheight = 0; - if(replace) { + if(replace) + { // If it cannot be interpreted, set replacewith to null (not replacing at all) if(!int.TryParse(replacewith, out replaceheight)) replacewith = null; - if(replacewith == null) { + if(replacewith == null) + { MessageBox.Show("Invalid replace value for this search type!", "Find and Replace", MessageBoxButtons.OK, MessageBoxIcon.Error); return objs.ToArray(); } @@ -32,14 +35,17 @@ namespace CodeImp.DoomBuilder.BuilderModes.FindReplace // Interpret the number given int height; - if(int.TryParse(value, out height)) { + if(int.TryParse(value, out height)) + { // Where to search? ICollection list = withinselection ? General.Map.Map.GetSelectedSectors(true) : General.Map.Map.Sectors; // Go for all sectors - foreach(Sector s in list) { + foreach(Sector s in list) + { // Height matches? - if(s.FloorHeight == height) { + if(s.FloorHeight == height) + { // Replace if(replace) s.FloorHeight = replaceheight; @@ -49,7 +55,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.FindReplace } //refresh map - if(replace) { + if(replace) + { General.Map.Map.Update(); General.Map.IsChanged = true; } diff --git a/Source/Plugins/BuilderModes/FindReplace/FindThingAction.cs b/Source/Plugins/BuilderModes/FindReplace/FindThingAction.cs index f07242c6..80adae48 100644 --- a/Source/Plugins/BuilderModes/FindReplace/FindThingAction.cs +++ b/Source/Plugins/BuilderModes/FindReplace/FindThingAction.cs @@ -135,11 +135,13 @@ namespace CodeImp.DoomBuilder.BuilderModes argtext = ""; //if args were specified, then process them - if (args != null) { + if (args != null) + { argtext = " args: ("; for (int x = 0; x < args.Length; x++) { - if (args[x] != 0 && args[x] != t.Args[x]) { + if (args[x] != 0 && args[x] != t.Args[x]) + { match = false; break; } diff --git a/Source/Plugins/BuilderModes/General/BuilderModesTools.cs b/Source/Plugins/BuilderModes/General/BuilderModesTools.cs index 9a136cf8..da2d0212 100644 --- a/Source/Plugins/BuilderModes/General/BuilderModesTools.cs +++ b/Source/Plugins/BuilderModes/General/BuilderModesTools.cs @@ -19,7 +19,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { Rectangle rect = new Rectangle(0, 0, 1, 0); Linedef cl = side.GetControlLinedef(); - if(cl.Front != null && cl.Front.Sector != null) { + if(cl.Front != null && cl.Front.Sector != null) + { // Use ceiling height for vavoom-type 3d floors. Also, FloorHeight is > CeilHeight for these... if (cl.Args[1] == 0) { @@ -32,7 +33,9 @@ namespace CodeImp.DoomBuilder.BuilderModes rect.Height = cl.Front.GetMiddleHeight(); } - } else { + } + else + { rect.Y = side.Sidedef.Sector.FloorHeight; rect.Height = side.Sidedef.GetMiddleHeight(); } diff --git a/Source/Plugins/BuilderModes/General/BuilderPlug.cs b/Source/Plugins/BuilderModes/General/BuilderPlug.cs index c522e8e7..be484e14 100644 --- a/Source/Plugins/BuilderModes/General/BuilderPlug.cs +++ b/Source/Plugins/BuilderModes/General/BuilderPlug.cs @@ -261,7 +261,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Save settings, which can be changed via UI - private void saveSettings() { + private void SaveSettings() + { General.Settings.WritePluginSetting("locktextureoffsets", lockSectorTextureOffsetsWhileDragging); General.Settings.WritePluginSetting("viewselectionnumbers", viewselectionnumbers); General.Settings.WritePluginSetting("viewselectioneffects", viewselectioneffects); @@ -279,7 +280,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if((img != null) && img.IsImageLoaded) { //mxd. Merged from GZDoomEditing plugin - if(General.Map.UDMF) { + if(General.Map.UDMF) + { // Fetch ZDoom fields Vector2D offset = new Vector2D(s.Fields.GetValue("xpanningfloor", 0.0f), s.Fields.GetValue("ypanningfloor", 0.0f)); @@ -292,13 +294,16 @@ namespace CodeImp.DoomBuilder.BuilderModes // Setup the vertices with the given settings SetupSurfaceVertices(vertices, s, img, offset, scale, rotate, color, light, absolute); - } else { + } + else + { // Make scalars float sw = 1.0f / img.ScaledWidth; float sh = 1.0f / img.ScaledHeight; // Make proper texture coordinates - for(int i = 0; i < vertices.Length; i++) { + for(int i = 0; i < vertices.Length; i++) + { vertices[i].u = vertices[i].u * sw; vertices[i].v = -vertices[i].v * sh; } @@ -313,7 +318,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if((img != null) && img.IsImageLoaded) { //mxd. Merged from GZDoomEditing plugin - if(General.Map.UDMF) { + if(General.Map.UDMF) + { // Fetch ZDoom fields Vector2D offset = new Vector2D(s.Fields.GetValue("xpanningceiling", 0.0f), s.Fields.GetValue("ypanningceiling", 0.0f)); @@ -326,13 +332,16 @@ namespace CodeImp.DoomBuilder.BuilderModes // Setup the vertices with the given settings SetupSurfaceVertices(vertices, s, img, offset, scale, rotate, color, light, absolute); - } else { + } + else + { // Make scalars float sw = 1.0f / img.ScaledWidth; float sh = 1.0f / img.ScaledHeight; // Make proper texture coordinates - for(int i = 0; i < vertices.Length; i++) { + for(int i = 0; i < vertices.Length; i++) + { vertices[i].u = vertices[i].u * sw; vertices[i].v = -vertices[i].v * sh; } @@ -407,7 +416,7 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.RemoveDocker(drawingOverridesDocker); //mxd. Save settings - saveSettings(); + SaveSettings(); } // Redo performed @@ -457,7 +466,8 @@ namespace CodeImp.DoomBuilder.BuilderModes color = finalcolor.WithAlpha(255).ToInt(); // Do the math for all vertices - for(int i = 0; i < vertices.Length; i++) { + for(int i = 0; i < vertices.Length; i++) + { Vector2D pos = new Vector2D(vertices[i].x, vertices[i].y); pos = pos.GetRotated(rotate); pos.y = -pos.y; @@ -495,17 +505,21 @@ namespace CodeImp.DoomBuilder.BuilderModes if(asso.type == UniversalType.SectorTag) { List lines = new List(); //mxd - foreach(Sector s in General.Map.Map.Sectors) { - if(s.Tag == asso.tag) { + foreach(Sector s in General.Map.Map.Sectors) + { + if(s.Tag == asso.tag) + { renderer.PlotSector(s, General.Colors.Indication); - if (General.Settings.GZShowEventLines) { + if (General.Settings.GZShowEventLines) + { Vector2D end = (s.Labels.Count > 0 ? s.Labels[0].position : new Vector2D(s.BBox.X + s.BBox.Width / 2, s.BBox.Y + s.BBox.Height / 2)); lines.Add(new Line3D(asso.Center, end)); //mxd } } } - if(General.Settings.GZShowEventLines) { //mxd + if(General.Settings.GZShowEventLines) //mxd + { foreach(Line3D l in lines) renderer.PlotArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); } @@ -514,15 +528,18 @@ namespace CodeImp.DoomBuilder.BuilderModes else if(asso.type == UniversalType.LinedefTag) { List lines = new List(); //mxd - foreach(Linedef l in General.Map.Map.Linedefs) { - if(l.Tag == asso.tag) { + foreach(Linedef l in General.Map.Map.Linedefs) + { + if(l.Tag == asso.tag) + { renderer.PlotLinedef(l, General.Colors.Indication); if(General.Settings.GZShowEventLines) lines.Add(new Line3D(asso.Center, l.GetCenterPoint()));//mxd } } - if(General.Settings.GZShowEventLines) { //mxd + if(General.Settings.GZShowEventLines) //mxd + { foreach(Line3D l in lines) renderer.PlotArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); } @@ -540,33 +557,36 @@ namespace CodeImp.DoomBuilder.BuilderModes if(asso.type == UniversalType.ThingTag) { List lines = new List(); //mxd - foreach(Thing t in General.Map.Map.Things){ - if(t.Tag == asso.tag) { + foreach(Thing t in General.Map.Map.Things) + { + if(t.Tag == asso.tag) + { renderer.RenderThing(t, General.Colors.Indication, 1.0f); if(General.Settings.GZShowEventLines) lines.Add(new Line3D(asso.Center, t.Position));//mxd } } - if(General.Settings.GZShowEventLines) { //mxd + if(General.Settings.GZShowEventLines) //mxd + { foreach(Line3D l in lines) renderer.RenderArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); } } else if(asso.type == UniversalType.SectorTag) //mxd. Render sector highlight { - foreach(Sector s in General.Map.Map.Sectors) { - if(s.Tag == asso.tag) { + foreach(Sector s in General.Map.Map.Sectors) + { + if(s.Tag == asso.tag) + { int highlightedColor = General.Colors.Highlight.WithAlpha(128).ToInt(); FlatVertex[] verts = new FlatVertex[s.FlatVertices.Length]; s.FlatVertices.CopyTo(verts, 0); - for(int i = 0; i < verts.Length; i++) - verts[i].c = highlightedColor; + for(int i = 0; i < verts.Length; i++) verts[i].c = highlightedColor; renderer.RenderGeometry(verts, null, true); } } } } - // This renders the associated sectors/linedefs with the indication color public void PlotReverseAssociations(IRenderer2D renderer, Association asso) @@ -585,7 +605,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Any action on this line? if(l.Action > 0) { - if(l.Tag == asso.tag) { + if(l.Tag == asso.tag) + { renderer.PlotLinedef(l, General.Colors.Indication); if(General.Settings.GZShowEventLines) //mxd @@ -593,7 +614,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } } } - if(General.Settings.GZShowEventLines) { //mxd + if(General.Settings.GZShowEventLines) //mxd + { foreach(Line3D l in lines) renderer.PlotArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); } @@ -611,7 +633,8 @@ namespace CodeImp.DoomBuilder.BuilderModes ((action.Args[1].Type == (int)asso.type) && (l.Args[1] == asso.tag)) || ((action.Args[2].Type == (int)asso.type) && (l.Args[2] == asso.tag)) || ((action.Args[3].Type == (int)asso.type) && (l.Args[3] == asso.tag)) || - ((action.Args[4].Type == (int)asso.type) && (l.Args[4] == asso.tag)) ){ + ((action.Args[4].Type == (int)asso.type) && (l.Args[4] == asso.tag)) ) + { renderer.PlotLinedef(l, General.Colors.Indication); @@ -621,10 +644,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(General.Settings.GZShowEventLines) { //mxd - foreach(Line3D l in lines) { + if(General.Settings.GZShowEventLines) //mxd + { + foreach(Line3D l in lines) renderer.PlotArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); - } } } } @@ -649,7 +672,8 @@ namespace CodeImp.DoomBuilder.BuilderModes ((action.Args[1].Type == (int)asso.type) && (t.Args[1] == asso.tag)) || ((action.Args[2].Type == (int)asso.type) && (t.Args[2] == asso.tag)) || ((action.Args[3].Type == (int)asso.type) && (t.Args[3] == asso.tag)) || - ((action.Args[4].Type == (int)asso.type) && (t.Args[4] == asso.tag)) ){ + ((action.Args[4].Type == (int)asso.type) && (t.Args[4] == asso.tag)) ) + { renderer.RenderThing(t, General.Colors.Indication, 1.0f); if(General.Settings.GZShowEventLines) //mxd lines.Add(new Line3D(t.Position, asso.Center)); @@ -657,10 +681,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(General.Settings.GZShowEventLines) {//mxd - foreach(Line3D l in lines) { + if(General.Settings.GZShowEventLines) //mxd + { + foreach(Line3D l in lines) renderer.RenderArrow(l, l.LineType == Line3DType.ACTIVATOR ? General.Colors.Selection : General.Colors.InfoLine); - } } } @@ -669,20 +693,23 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Actions (mxd) [BeginAction("exporttoobj")] - private void exportToObj() { + private void ExportToObj() + { // Convert geometry selection to sectors General.Map.Map.ConvertSelection(SelectionType.Sectors); //get sectors ICollection sectors = General.Map.Map.SelectedSectorsCount == 0 ? General.Map.Map.Sectors : General.Map.Map.GetSelectedSectors(true); - if(sectors.Count == 0) { + if(sectors.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "OBJ export failed. Map has no sectors!"); return; } //show settings form WavefrontSettingsForm form = new WavefrontSettingsForm(General.Map.Map.SelectedSectorsCount == 0 ? -1 : sectors.Count); - if(form.ShowDialog() == DialogResult.OK) { + if(form.ShowDialog() == DialogResult.OK) + { WavefrontExportSettings data = new WavefrontExportSettings(Path.GetFileNameWithoutExtension(form.FilePath), Path.GetDirectoryName(form.FilePath), form.ObjScale, form.UseGZDoomScale, form.ExportTextures); WavefrontExporter e = new WavefrontExporter(); e.Export(sectors, data); @@ -690,7 +717,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("pastepropertiesoptions")] - private void showPastePropertiesOptions() { + private void ShowPastePropertiesOptions() + { var form = new PastePropertiesOptionsForm(); form.ShowDialog(Form.ActiveForm); } diff --git a/Source/Plugins/BuilderModes/General/CopyStructures.cs b/Source/Plugins/BuilderModes/General/CopyStructures.cs index b8136320..8bd0a8c5 100644 --- a/Source/Plugins/BuilderModes/General/CopyStructures.cs +++ b/Source/Plugins/BuilderModes/General/CopyStructures.cs @@ -31,7 +31,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { public string Description { get; private set; } - public FieldDescription(string description) { + public FieldDescription(string description) + { this.Description = description; } } @@ -67,7 +68,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { if(CopySettings.ZCeiling) v.ZCeiling = zceiling; //mxd if(CopySettings.ZFloor) v.ZFloor = zfloor; //mxd - if(CopySettings.Fields) { + if(CopySettings.Fields) + { v.Fields.BeforeFieldsChange(); v.Fields.Clear(); foreach (KeyValuePair uv in fields) @@ -226,12 +228,14 @@ namespace CodeImp.DoomBuilder.BuilderModes if(CopySettings.LowerTexture) s.SetTextureLow(lowtexture); if(CopySettings.OffsetX) s.OffsetX = offsetx; if(CopySettings.OffsetY) s.OffsetY = offsety; - if(CopySettings.Flags) { + if(CopySettings.Flags) + { s.ClearFlags(); //mxd foreach (KeyValuePair f in flags) //mxd s.SetFlag(f.Key, f.Value); } - if(CopySettings.Fields) { + if(CopySettings.Fields) + { s.Fields.BeforeFieldsChange(); s.Fields.Clear(); foreach (KeyValuePair v in fields) @@ -289,11 +293,13 @@ namespace CodeImp.DoomBuilder.BuilderModes public void Apply(Linedef l) { - if(CopySettings.SidedefProperties) { + if(CopySettings.SidedefProperties) + { if ((front != null) && (l.Front != null)) front.Apply(l.Front); if ((back != null) && (l.Back != null)) back.Apply(l.Back); } - if(CopySettings.Flags) { + if(CopySettings.Flags) + { l.ClearFlags(); foreach (KeyValuePair f in flags) l.SetFlag(f.Key, f.Value); @@ -301,11 +307,13 @@ namespace CodeImp.DoomBuilder.BuilderModes if(CopySettings.Activation) l.Activate = activate; if(CopySettings.Tag) l.Tag = tag; if(CopySettings.Action) l.Action = action; - if(CopySettings.Arguments) { + if(CopySettings.Arguments) + { for(int i = 0; i < l.Args.Length; i++) l.Args[i] = args[i]; } - if(CopySettings.Fields) { + if(CopySettings.Fields) + { l.Fields.BeforeFieldsChange(); l.Fields.Clear(); foreach (KeyValuePair v in fields) @@ -379,18 +387,21 @@ namespace CodeImp.DoomBuilder.BuilderModes if(CopySettings.Pitch) t.SetPitch(pitch); if(CopySettings.Roll) t.SetRoll(roll); if(CopySettings.Scale) t.SetScale(scalex, scaley); - if(CopySettings.Flags) { + if(CopySettings.Flags) + { t.ClearFlags(); foreach (KeyValuePair f in flags) t.SetFlag(f.Key, f.Value); } if(CopySettings.Tag) t.Tag = tag; if(CopySettings.Action) t.Action = action; - if(CopySettings.Arguments) { + if(CopySettings.Arguments) + { for(int i = 0; i < t.Args.Length; i++) t.Args[i] = args[i]; } - if(CopySettings.Fields) { + if(CopySettings.Fields) + { t.Fields.BeforeFieldsChange(); t.Fields.Clear(); foreach (KeyValuePair v in fields) @@ -405,7 +416,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region Vertex - public static bool PropertiesMatch(VertexPropertiesCopySettings flags, Vertex source, Vertex target) { + public static bool PropertiesMatch(VertexPropertiesCopySettings flags, Vertex source, Vertex target) + { if(flags.ZCeiling && source.ZCeiling != target.ZCeiling) return false; if(flags.ZFloor && source.ZFloor != target.ZFloor) return false; return !flags.Fields || UDMFTools.FieldsMatch(source.Fields, target.Fields); @@ -415,7 +427,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region Sector - public static bool PropertiesMatch(SectorPropertiesCopySettings flags, Sector source, Sector target) { + public static bool PropertiesMatch(SectorPropertiesCopySettings flags, Sector source, Sector target) + { if(flags.FloorHeight && source.FloorHeight != target.FloorHeight) return false; if(flags.CeilingHeight && source.CeilHeight != target.CeilHeight) return false; if(flags.FloorTexture && source.FloorTexture != target.FloorTexture) return false; @@ -431,17 +444,19 @@ namespace CodeImp.DoomBuilder.BuilderModes #region Linedef - public static bool PropertiesMatch(LinedefPropertiesCopySettings linedefflags, SidedefPropertiesCopySettings sideflags, Linedef source, Linedef target) { + public static bool PropertiesMatch(LinedefPropertiesCopySettings linedefflags, SidedefPropertiesCopySettings sideflags, Linedef source, Linedef target) + { if(linedefflags.Action && source.Action != target.Action) return false; if(linedefflags.Activation && source.Activate != target.Activate) return false; if(linedefflags.Tag && source.Tag != target.Tag) return false; - if(linedefflags.Arguments) { - for(int i = 0; i < source.Args.Length; i++) { + if(linedefflags.Arguments) + { + for(int i = 0; i < source.Args.Length; i++) if(source.Args[i] != target.Args[i]) return false; - } } if(linedefflags.Flags && !FlagsMatch(source.GetFlags(), target.GetFlags())) return false; - if(linedefflags.SidedefProperties) { + if(linedefflags.SidedefProperties) + { if ((source.Front == null && target.Front != null) || (source.Front != null && target.Front == null) || (source.Back == null && target.Back != null) || (source.Back != null && target.Back == null)) return false; @@ -456,7 +471,8 @@ namespace CodeImp.DoomBuilder.BuilderModes #region Sidedef - public static bool PropertiesMatch(SidedefPropertiesCopySettings flags, Sidedef source, Sidedef target) { + public static bool PropertiesMatch(SidedefPropertiesCopySettings flags, Sidedef source, Sidedef target) + { if(flags.OffsetX && source.OffsetX != target.OffsetX) return false; if(flags.OffsetY && source.OffsetY != target.OffsetY) return false; if(flags.UpperTexture && source.HighTexture != target.HighTexture) return false; @@ -470,14 +486,15 @@ namespace CodeImp.DoomBuilder.BuilderModes #region Thing - public static bool PropertiesMatch(ThingPropertiesCopySettings flags, Thing source, Thing target) { + public static bool PropertiesMatch(ThingPropertiesCopySettings flags, Thing source, Thing target) + { if(flags.Type && source.Type != target.Type) return false; if(flags.Angle && source.AngleDoom != target.AngleDoom) return false; if(flags.Action && source.Action != target.Action) return false; - if (flags.Arguments) { - for(int i = 0; i < source.Args.Length; i++) { + if (flags.Arguments) + { + for(int i = 0; i < source.Args.Length; i++) if (source.Args[i] != target.Args[i]) return false; - } } if(flags.Tag && source.Tag != target.Tag) return false; if(flags.Pitch && source.Pitch != target.Pitch) return false; @@ -490,11 +507,11 @@ namespace CodeImp.DoomBuilder.BuilderModes #endregion - private static bool FlagsMatch(Dictionary flags1, Dictionary flags2) { + private static bool FlagsMatch(Dictionary flags1, Dictionary flags2) + { if (flags1.Count != flags2.Count) return false; - foreach (KeyValuePair group in flags1) { + foreach (KeyValuePair group in flags1) if (!flags2.ContainsKey(group.Key) || flags2[group.Key] != flags1[group.Key]) return false; - } return true; } } diff --git a/Source/Plugins/BuilderModes/General/HintLabel.cs b/Source/Plugins/BuilderModes/General/HintLabel.cs index c127ad64..36322fb8 100644 --- a/Source/Plugins/BuilderModes/General/HintLabel.cs +++ b/Source/Plugins/BuilderModes/General/HintLabel.cs @@ -8,11 +8,13 @@ namespace CodeImp.DoomBuilder.BuilderModes private string text = ""; public string Text { get { return text; } set { text = value; Update(); } } - public HintLabel() : base(false) { + public HintLabel() : base(false) + { label.Color = General.Colors.InfoLine; } - protected override void Update() { + protected override void Update() + { Vector2D delta = end - start; label.Text = text; label.Rectangle = new RectangleF(start.x + delta.x * 0.5f, start.y + delta.y * 0.5f, 0f, 0f); diff --git a/Source/Plugins/BuilderModes/IO/WavefrontExporter.cs b/Source/Plugins/BuilderModes/IO/WavefrontExporter.cs index 5b94e6f0..9badf311 100644 --- a/Source/Plugins/BuilderModes/IO/WavefrontExporter.cs +++ b/Source/Plugins/BuilderModes/IO/WavefrontExporter.cs @@ -1,4 +1,6 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; @@ -12,8 +14,12 @@ using CodeImp.DoomBuilder.Rendering; using CodeImp.DoomBuilder.Windows; using System.Windows.Forms; +#endregion + namespace CodeImp.DoomBuilder.BuilderModes.IO { + #region ================== Structs + internal struct WavefrontExportSettings { public string Obj; @@ -26,7 +32,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO public string[] Textures; public string[] Flats; - public WavefrontExportSettings(string name, string path, float scale, bool fixScale, bool exportTextures) { + public WavefrontExportSettings(string name, string path, float scale, bool fixScale, bool exportTextures) + { ObjName = name; ObjPath = path; Scale = scale; @@ -39,9 +46,14 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO Flats = null; } } - + + #endregion + internal class WavefrontExporter { + + #region ================== Variables and structs + private const string DEFAULT = "Default"; private struct VertexIndices @@ -51,22 +63,33 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO public int NormalIndex; } - public void Export(ICollection sectors, WavefrontExportSettings settings) { - createObjFromSelection(sectors, ref settings); + #endregion - if(!settings.Valid) { + #region ================== Export + + public void Export(ICollection sectors, WavefrontExportSettings settings) + { + CreateObjFromSelection(sectors, ref settings); + + if(!settings.Valid) + { General.Interface.DisplayStatus(StatusType.Warning, "OBJ creation failed. Check 'Errors and Warnings' window for details."); return; } - if(settings.ExportTextures) { + if(settings.ExportTextures) + { //save all used textures - if(settings.Textures != null) { - foreach(string s in settings.Textures) { + if(settings.Textures != null) + { + foreach(string s in settings.Textures) + { if(s == DEFAULT) continue; - if(General.Map.Data.GetTextureExists(s)) { + if(General.Map.Data.GetTextureExists(s)) + { ImageData id = General.Map.Data.GetTextureImage(s); - if(id.Width == 0 || id.Height == 0) { + if(id.Width == 0 || id.Height == 0) + { General.ErrorLogger.Add(ErrorType.Warning, "OBJ Exporter: texture '" + s + "' has invalid size (" + id.Width + "x" + id.Height + ")!"); continue; } @@ -74,18 +97,24 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO if(!id.IsImageLoaded) id.LoadImage(); Bitmap bmp = id.GetBitmap(); bmp.Save(Path.Combine(settings.ObjPath, s + ".PNG"), ImageFormat.Png); - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Warning, "OBJ Exporter: texture '" + s + "' does not exist!"); } } } - if (settings.Flats != null) { - foreach(string s in settings.Flats) { + if (settings.Flats != null) + { + foreach(string s in settings.Flats) + { if(s == DEFAULT) continue; - if(General.Map.Data.GetFlatExists(s)) { + if(General.Map.Data.GetFlatExists(s)) + { ImageData id = General.Map.Data.GetFlatImage(s); - if(id.Width == 0 || id.Height == 0) { + if(id.Width == 0 || id.Height == 0) + { General.ErrorLogger.Add(ErrorType.Warning, "OBJ Exporter: flat '" + s + "' has invalid size (" + id.Width + "x" + id.Height + ")!"); continue; } @@ -95,13 +124,14 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO // Handle duplicate names string flatname = s; - if(settings.Textures != null && Array.IndexOf(settings.Textures, s) != -1) { + if(settings.Textures != null && Array.IndexOf(settings.Textures, s) != -1) flatname += "_FLAT"; - } bmp.Save(Path.Combine(settings.ObjPath, flatname + ".PNG"), ImageFormat.Png); - } else { + } + else + { General.ErrorLogger.Add(ErrorType.Warning, "OBJ Exporter: flat '" + s + "' does not exist!"); } } @@ -118,8 +148,10 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO mtl.Append("# MTL for " + General.Map.FileTitle + ", map " + General.Map.Options.LevelName + Environment.NewLine); mtl.Append("# Created by GZDoom Builder " + Application.ProductVersion + Environment.NewLine + Environment.NewLine); - if (settings.Textures != null) { - foreach (string s in settings.Textures) { + if (settings.Textures != null) + { + foreach (string s in settings.Textures) + { if (s == DEFAULT) continue; mtl.Append("newmtl " + s.ToUpperInvariant() + Environment.NewLine); mtl.Append("Kd 1.0 1.0 1.0" + Environment.NewLine); @@ -128,17 +160,19 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO } } - if(settings.Flats != null) { - foreach (string s in settings.Flats) { + if(settings.Flats != null) + { + foreach (string s in settings.Flats) + { if (s == DEFAULT) continue; mtl.Append("newmtl " + s.ToUpperInvariant() + Environment.NewLine); mtl.Append("Kd 1.0 1.0 1.0" + Environment.NewLine); - if (settings.ExportTextures) { + if (settings.ExportTextures) + { // Handle duplicate names string flatname = s; - if(settings.Textures != null && Array.IndexOf(settings.Textures, s) != -1) { + if(settings.Textures != null && Array.IndexOf(settings.Textures, s) != -1) flatname += "_FLAT"; - } mtl.Append("map_Kd " + Path.Combine(settings.ObjPath, flatname.ToUpperInvariant() + ".PNG") + Environment.NewLine); } @@ -154,11 +188,17 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO General.Interface.DisplayStatus(StatusType.Warning, "Geometry exported to '" + savePath + ".obj'"); } - private void createObjFromSelection(ICollection sectors, ref WavefrontExportSettings data) { + #endregion + + #region ================== Utility + + private static void CreateObjFromSelection(ICollection sectors, ref WavefrontExportSettings data) + { BaseVisualMode mode = new BaseVisualMode(); bool renderingEffectsDisabled = false; - if(!BaseVisualMode.GZDoomRenderingEffects) { + if(!BaseVisualMode.GZDoomRenderingEffects) + { renderingEffectsDisabled = true; mode.ToggleGZDoomRenderingEffects(); } @@ -168,29 +208,30 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO List visualSectors = new List(); //create visual geometry - foreach(Sector s in sectors) { + foreach(Sector s in sectors) + { BaseVisualSector bvs = mode.CreateBaseVisualSector(s); if(bvs != null) visualSectors.Add(bvs); } - if(visualSectors.Count == 0) { + if(visualSectors.Count == 0) + { General.ErrorLogger.Add(ErrorType.Error, "OBJ Exporter: no visual sectors to export!"); return; } //sort geometry - List>> geometryByTexture = sortGeometry(visualSectors); + List>> geometryByTexture = SortGeometry(visualSectors); //restore vm settings - if(renderingEffectsDisabled) - mode.ToggleGZDoomRenderingEffects(); - + if(renderingEffectsDisabled) mode.ToggleGZDoomRenderingEffects(); mode.Dispose(); //create obj - StringBuilder obj = createObjGeometry(geometryByTexture, data); + StringBuilder obj = CreateObjGeometry(geometryByTexture, data); - if(obj.Length == 0) { + if(obj.Length == 0) + { General.ErrorLogger.Add(ErrorType.Error, "OBJ Exporter: failed to create geometry!"); return; } @@ -214,58 +255,69 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO data.Valid = true; } - private List>> sortGeometry(List visualSectors) { + private static List>> SortGeometry(List visualSectors) + { var texturegeo = new Dictionary>(StringComparer.Ordinal); texturegeo.Add(DEFAULT, new List()); var flatgeo = new Dictionary>(StringComparer.Ordinal); flatgeo.Add(DEFAULT, new List()); string texture; - foreach(BaseVisualSector vs in visualSectors) { + foreach(BaseVisualSector vs in visualSectors) + { //floor - if(vs.Floor != null) { + if(vs.Floor != null) + { texture = vs.Sector.FloorTexture; - checkTextureName(ref flatgeo, ref texture); + CheckTextureName(ref flatgeo, ref texture); flatgeo[texture].AddRange(OptimizeGeometry(vs.Floor.Vertices, vs.Floor.GeometryType, vs.Floor.Sector.Sector.Labels.Count > 1)); } //ceiling - if(vs.Ceiling != null) { + if(vs.Ceiling != null) + { texture = vs.Sector.CeilTexture; - checkTextureName(ref flatgeo, ref texture); + CheckTextureName(ref flatgeo, ref texture); flatgeo[texture].AddRange(OptimizeGeometry(vs.Ceiling.Vertices, vs.Ceiling.GeometryType, vs.Ceiling.Sector.Sector.Labels.Count > 1)); } //walls - if(vs.Sides != null) { - foreach(VisualSidedefParts part in vs.Sides.Values) { + if(vs.Sides != null) + { + foreach(VisualSidedefParts part in vs.Sides.Values) + { //upper - if(part.upper != null && part.upper.Vertices != null) { + if(part.upper != null && part.upper.Vertices != null) + { texture = part.upper.Sidedef.HighTexture; - checkTextureName(ref texturegeo, ref texture); + CheckTextureName(ref texturegeo, ref texture); texturegeo[texture].AddRange(OptimizeGeometry(part.upper.Vertices, part.upper.GeometryType)); } //middle single - if(part.middlesingle != null && part.middlesingle.Vertices != null) { + if(part.middlesingle != null && part.middlesingle.Vertices != null) + { texture = part.middlesingle.Sidedef.MiddleTexture; - checkTextureName(ref texturegeo, ref texture); + CheckTextureName(ref texturegeo, ref texture); texturegeo[texture].AddRange(OptimizeGeometry(part.middlesingle.Vertices, part.middlesingle.GeometryType)); } //middle double - if(part.middledouble != null && part.middledouble.Vertices != null) { + if(part.middledouble != null && part.middledouble.Vertices != null) + { texture = part.middledouble.Sidedef.MiddleTexture; - checkTextureName(ref texturegeo, ref texture); + CheckTextureName(ref texturegeo, ref texture); texturegeo[texture].AddRange(OptimizeGeometry(part.middledouble.Vertices, part.middledouble.GeometryType)); } //middle3d - if(part.middle3d != null && part.middle3d.Count > 0) { - foreach(VisualMiddle3D m3d in part.middle3d) { + if(part.middle3d != null && part.middle3d.Count > 0) + { + foreach(VisualMiddle3D m3d in part.middle3d) + { if(m3d.Vertices == null) continue; texture = m3d.GetControlLinedef().Front.MiddleTexture; - checkTextureName(ref texturegeo, ref texture); + CheckTextureName(ref texturegeo, ref texture); texturegeo[texture].AddRange(OptimizeGeometry(m3d.Vertices, m3d.GeometryType)); } } @@ -273,25 +325,28 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO //backsides(?) //lower - if(part.lower != null && part.lower.Vertices != null) { + if(part.lower != null && part.lower.Vertices != null) + { texture = part.lower.Sidedef.LowTexture; - checkTextureName(ref texturegeo, ref texture); + CheckTextureName(ref texturegeo, ref texture); texturegeo[texture].AddRange(OptimizeGeometry(part.lower.Vertices, part.lower.GeometryType)); } } } //3d ceilings - foreach(VisualCeiling vc in vs.ExtraCeilings) { + foreach(VisualCeiling vc in vs.ExtraCeilings) + { texture = vc.GetControlSector().CeilTexture; - checkTextureName(ref flatgeo, ref texture); + CheckTextureName(ref flatgeo, ref texture); flatgeo[texture].AddRange(OptimizeGeometry(vc.Vertices, (vc.ExtraFloor.VavoomType ? vc.GeometryType : VisualModes.VisualGeometryType.FLOOR))); } //3d floors - foreach(VisualFloor vf in vs.ExtraFloors) { + foreach(VisualFloor vf in vs.ExtraFloors) + { texture = vf.GetControlSector().FloorTexture; - checkTextureName(ref flatgeo, ref texture); + CheckTextureName(ref flatgeo, ref texture); flatgeo[texture].AddRange(OptimizeGeometry(vf.Vertices, (vf.ExtraFloor.VavoomType ? vf.GeometryType : VisualModes.VisualGeometryType.CEILING))); } @@ -301,33 +356,47 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO return new List>> { texturegeo, flatgeo }; } - private static void checkTextureName(ref Dictionary> geo, ref string texture) { - if(!string.IsNullOrEmpty(texture) && texture != "-") { - if(!geo.ContainsKey(texture)) - geo.Add(texture, new List()); - } else { + private static void CheckTextureName(ref Dictionary> geo, ref string texture) + { + if(!string.IsNullOrEmpty(texture) && texture != "-") + { + if(!geo.ContainsKey(texture)) geo.Add(texture, new List()); + } + else + { texture = DEFAULT; } } -//SURFACE OPTIMIZATION + #endregion + + #region ================== Surface optimization + private static List OptimizeGeometry(WorldVertex[] verts, VisualModes.VisualGeometryType geotype) { return OptimizeGeometry(verts, geotype, false); } - private static List OptimizeGeometry(WorldVertex[] verts, VisualModes.VisualGeometryType geotype, bool skiprectoptimization) { + private static List OptimizeGeometry(WorldVertex[] verts, VisualModes.VisualGeometryType geotype, bool skiprectoptimization) + { List groups = new List(); - if(!skiprectoptimization && verts.Length == 6) { //rectangular surface - if(geotype == VisualModes.VisualGeometryType.CEILING) { + if(!skiprectoptimization && verts.Length == 6) //rectangular surface + { + if(geotype == VisualModes.VisualGeometryType.CEILING) + { verts = new[] { verts[2], verts[5], verts[1], verts[0] }; - } else { + } + else + { verts = new[] { verts[5], verts[2], verts[1], verts[0] }; } groups.Add(verts); - } else { - for (int i = 0; i < verts.Length; i += 3) { + } + else + { + for (int i = 0; i < verts.Length; i += 3) + { groups.Add(new[] { verts[i + 2], verts[i + 1], verts[i] }); } } @@ -335,8 +404,12 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO return groups; } -//OBJ Creation - private static StringBuilder createObjGeometry(List>> geometryByTexture, WavefrontExportSettings data) { + #endregion + + #region ================== OBJ Creation + + private static StringBuilder CreateObjGeometry(List>> geometryByTexture, WavefrontExportSettings data) + { StringBuilder obj = new StringBuilder(); const string vertexFormatter = "{0} {2} {1}\n"; @@ -351,38 +424,51 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO int uvc = 0; //optimize geometry - foreach(Dictionary> dictionary in geometryByTexture) { - foreach(KeyValuePair> group in dictionary) { + foreach(Dictionary> dictionary in geometryByTexture) + { + foreach(KeyValuePair> group in dictionary) + { Dictionary vertsData = new Dictionary(); - foreach(WorldVertex[] verts in group.Value) { + foreach(WorldVertex[] verts in group.Value) + { //vertex normals Vector3D n = new Vector3D(verts[0].nx, verts[0].ny, verts[0].nz).GetNormal(); - if (uniqueNormals.ContainsKey(n)) { + if (uniqueNormals.ContainsKey(n)) + { ni = uniqueNormals[n]; - } else { + } + else + { uniqueNormals.Add(n, ++nc); ni = nc; } - foreach(WorldVertex v in verts) { + foreach(WorldVertex v in verts) + { if (vertsData.ContainsKey(v)) continue; VertexIndices indices = new VertexIndices(); indices.NormalIndex = ni; //vertex coords Vector3D vc = new Vector3D(v.x, v.y, v.z); - if (uniqueVerts.ContainsKey(vc)) { + if (uniqueVerts.ContainsKey(vc)) + { indices.PositionIndex = uniqueVerts[vc]; - } else { + } + else + { uniqueVerts.Add(vc, ++pc); indices.PositionIndex = pc; } //uv PointF uv = new PointF(v.u, v.v); - if (uniqueUVs.ContainsKey(uv)) { + if (uniqueUVs.ContainsKey(uv)) + { indices.UVIndex = uniqueUVs[uv]; - } else { + } + else + { uniqueUVs.Add(uv, ++uvc); indices.UVIndex = uvc; } @@ -391,12 +477,15 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO } } - if(vertsData.Count > 0) { - if(vertexDataByTexture.ContainsKey(group.Key)) { - foreach(KeyValuePair g in vertsData) { + if(vertsData.Count > 0) + { + if(vertexDataByTexture.ContainsKey(group.Key)) + { + foreach(KeyValuePair g in vertsData) vertexDataByTexture[group.Key].Add(g.Key, g.Value); - } - } else { + } + else + { vertexDataByTexture.Add(group.Key, vertsData); } } @@ -405,10 +494,13 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO //write geometry //write vertices - if(data.FixScale) { + if(data.FixScale) + { foreach(KeyValuePair group in uniqueVerts) obj.Append(string.Format(CultureInfo.InvariantCulture, "v " + vertexFormatter, -group.Key.x * data.Scale, group.Key.y * data.Scale, group.Key.z * data.Scale * 1.2f)); - } else { + } + else + { foreach(KeyValuePair group in uniqueVerts) obj.Append(string.Format(CultureInfo.InvariantCulture, "v " + vertexFormatter, -group.Key.x * data.Scale, group.Key.y * data.Scale, group.Key.z * data.Scale)); } @@ -425,15 +517,19 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO obj.Append("mtllib ").Append(data.ObjName + ".mtl").Append("\n"); //write materials and surface indices - foreach(Dictionary> dictionary in geometryByTexture) { - foreach(KeyValuePair> group in dictionary) { + foreach(Dictionary> dictionary in geometryByTexture) + { + foreach(KeyValuePair> group in dictionary) + { //material obj.Append("usemtl ").Append(group.Key).Append("\n"); - foreach(WorldVertex[] verts in group.Value) { + foreach(WorldVertex[] verts in group.Value) + { //surface indices obj.Append("f"); - foreach(WorldVertex v in verts) { + foreach(WorldVertex v in verts) + { VertexIndices vi = vertexDataByTexture[group.Key][v]; obj.Append(" " + vi.PositionIndex + "/" + vi.UVIndex + "/" + vi.NormalIndex); } @@ -444,5 +540,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.IO return obj; } + + #endregion } } diff --git a/Source/Plugins/BuilderModes/Interface/BridgeModeForm.Designer.cs b/Source/Plugins/BuilderModes/Interface/BridgeModeForm.Designer.cs index eb7f4815..da69e2d9 100644 --- a/Source/Plugins/BuilderModes/Interface/BridgeModeForm.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/BridgeModeForm.Designer.cs @@ -9,8 +9,10 @@ /// Освободить все используемые ресурсы. /// /// истинно, если управляемый ресурс должен быть удален; иначе ложно. - protected override void Dispose(bool disposing) { - if (disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -22,7 +24,8 @@ /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.cbFloorAlign = new System.Windows.Forms.ComboBox(); diff --git a/Source/Plugins/BuilderModes/Interface/BridgeModeForm.cs b/Source/Plugins/BuilderModes/Interface/BridgeModeForm.cs index 94888c44..fec2efd2 100644 --- a/Source/Plugins/BuilderModes/Interface/BridgeModeForm.cs +++ b/Source/Plugins/BuilderModes/Interface/BridgeModeForm.cs @@ -23,15 +23,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface { public partial class BridgeModeForm : DelayedForm { - internal int Subdivisions { - get { - return (int)nudSubdivisions.Value; - } - set { - nudSubdivisions.Value = value; - } - } - + internal int Subdivisions { get { return (int)nudSubdivisions.Value; } set { nudSubdivisions.Value = value; } } internal string FloorAlignMode { get { return (string)cbFloorAlign.SelectedItem; } } internal string CeilingAlignMode { get { return (string)cbCeilingAlign.SelectedItem; } } internal string BrightnessMode { get { return (string)cbBrightness.SelectedItem; } } @@ -44,7 +36,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface { internal event EventHandler OnCancelClick; internal event EventHandler OnFlipClick; - public BridgeModeForm() { + public BridgeModeForm() + { InitializeComponent(); cbBrightness.Items.AddRange(BridgeInterpolationMode.BRIGHTNESS_INTERPOLATION_MODES); @@ -60,47 +53,44 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface { } //events - private void BezierPathForm_FormClosed(object sender, FormClosedEventArgs e) { - if (OnCancelClick != null) - OnCancelClick(this, EventArgs.Empty); + private void BezierPathForm_FormClosed(object sender, FormClosedEventArgs e) + { + if (OnCancelClick != null) OnCancelClick(this, EventArgs.Empty); } - private void buttonCancel_Click(object sender, EventArgs e) { - if (OnCancelClick != null) - OnCancelClick(this, EventArgs.Empty); + private void buttonCancel_Click(object sender, EventArgs e) + { + if (OnCancelClick != null) OnCancelClick(this, EventArgs.Empty); } - private void buttonOK_Click(object sender, EventArgs e) { - if (OnOkClick != null) - OnOkClick(this, EventArgs.Empty); + private void buttonOK_Click(object sender, EventArgs e) + { + if (OnOkClick != null) OnOkClick(this, EventArgs.Empty); } - private void nudSubdivisions_ValueChanged(object sender, EventArgs e) { - if (OnSubdivisionChanged != null) - OnSubdivisionChanged(this, EventArgs.Empty); + private void nudSubdivisions_ValueChanged(object sender, EventArgs e) + { + if (OnSubdivisionChanged != null) OnSubdivisionChanged(this, EventArgs.Empty); } - private void BezierPathForm_MouseEnter(object sender, EventArgs e) { - this.Focus(); - } - - private void BezierPathForm_MouseLeave(object sender, EventArgs e) { + private void BezierPathForm_MouseLeave(object sender, EventArgs e) + { General.Interface.FocusDisplay(); } - private void buttonFlip_Click(object sender, EventArgs e) { - if (OnFlipClick != null) - OnFlipClick(this, EventArgs.Empty); + private void buttonFlip_Click(object sender, EventArgs e) + { + if (OnFlipClick != null) OnFlipClick(this, EventArgs.Empty); } - private void cbCopy_CheckedChanged(object sender, EventArgs e) { - if (cbMirror.Checked && cbCopy.Checked) - cbMirror.Checked = false; + private void cbCopy_CheckedChanged(object sender, EventArgs e) + { + if (cbMirror.Checked && cbCopy.Checked) cbMirror.Checked = false; } - private void cbMirror_CheckStateChanged(object sender, EventArgs e) { - if (cbMirror.Checked && cbCopy.Checked) - cbCopy.Checked = false; + private void cbMirror_CheckStateChanged(object sender, EventArgs e) + { + if (cbMirror.Checked && cbCopy.Checked) cbCopy.Checked = false; } } } diff --git a/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.Designer.cs b/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.Designer.cs index d7f86515..86bb70c6 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.toolstrip = new System.Windows.Forms.ToolStrip(); this.seglabel = new System.Windows.Forms.ToolStripLabel(); this.seglen = new CodeImp.DoomBuilder.Controls.ToolStripNumericUpDown(); diff --git a/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.cs b/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.cs index e6bf38ec..875db67d 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawCurveOptionsPanel.cs @@ -10,7 +10,8 @@ namespace CodeImp.DoomBuilder.BuilderModes public int SegmentLength { get { return (int)seglen.Value; } set { blockEvents = true; seglen.Value = value; blockEvents = false; } } - public DrawCurveOptionsPanel(int minLength, int maxLength) { + public DrawCurveOptionsPanel(int minLength, int maxLength) + { InitializeComponent(); seglen.Minimum = minLength; @@ -19,23 +20,27 @@ namespace CodeImp.DoomBuilder.BuilderModes private DrawCurveOptionsPanel() { InitializeComponent(); } - public void Register() { + public void Register() + { General.Interface.AddButton(seglabel); General.Interface.AddButton(seglen); General.Interface.AddButton(reset); } - public void Unregister() { + public void Unregister() + { General.Interface.RemoveButton(reset); General.Interface.RemoveButton(seglen); General.Interface.RemoveButton(seglabel); } - private void seglen_ValueChanged(object sender, EventArgs e) { + private void seglen_ValueChanged(object sender, EventArgs e) + { if(!blockEvents && OnValueChanged != null) OnValueChanged(this, EventArgs.Empty); } - private void reset_Click(object sender, EventArgs e) { + private void reset_Click(object sender, EventArgs e) + { seglen.Value = seglen.Minimum; } } diff --git a/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.Designer.cs b/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.Designer.cs index d823aaf8..29310b16 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.subdivslabel = new System.Windows.Forms.ToolStripLabel(); this.subdivs = new CodeImp.DoomBuilder.Controls.ToolStripNumericUpDown(); diff --git a/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.cs b/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.cs index 5952f6eb..0d5d1986 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawEllipseOptionsPanel.cs @@ -18,11 +18,13 @@ namespace CodeImp.DoomBuilder.BuilderModes public int MaxSpikiness { get { return (int)spikiness.Maximum; } set { spikiness.Maximum = value; } } public int MinSpikiness { get { return (int)spikiness.Minimum; } set { spikiness.Minimum = value; } } - public DrawEllipseOptionsPanel() { + public DrawEllipseOptionsPanel() + { InitializeComponent(); } - public void Register() { + public void Register() + { spikiness.Value = aquityValue; subdivs.Value = subdivsValue; spikiness.ValueChanged += ValueChanged; @@ -35,7 +37,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.AddButton(reset); } - public void Unregister() { + public void Unregister() + { General.Interface.RemoveButton(reset); General.Interface.RemoveButton(spikiness); General.Interface.RemoveButton(spikinesslabel); @@ -43,13 +46,15 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.RemoveButton(subdivslabel); } - private void ValueChanged(object sender, EventArgs e) { + private void ValueChanged(object sender, EventArgs e) + { aquityValue = (int)spikiness.Value; subdivsValue = (int)subdivs.Value; if(!blockEvents && OnValueChanged != null) OnValueChanged(this, EventArgs.Empty); } - private void reset_Click(object sender, EventArgs e) { + private void reset_Click(object sender, EventArgs e) + { blockEvents = true; spikiness.Value = 0; blockEvents = false; diff --git a/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.Designer.cs b/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.Designer.cs index 506a8cb4..0a728380 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.sliceshlabel = new System.Windows.Forms.ToolStripLabel(); this.slicesH = new CodeImp.DoomBuilder.Controls.ToolStripNumericUpDown(); diff --git a/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.cs b/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.cs index 3299d270..449c2195 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawGridOptionsPanel.cs @@ -16,11 +16,13 @@ namespace CodeImp.DoomBuilder.BuilderModes public int VerticalSlices { get { return (int)slicesV.Value; } set { blockEvents = true; slicesV.Value = value; blockEvents = false; } } public int MaxVerticalSlices { get { return (int)slicesV.Maximum; } set { slicesV.Maximum = value; } } - public DrawGridOptionsPanel() { + public DrawGridOptionsPanel() + { InitializeComponent(); } - public void Register() { + public void Register() + { General.Interface.AddButton(sliceshlabel); General.Interface.AddButton(slicesH); General.Interface.AddButton(slicesvlabel); @@ -31,7 +33,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.AddButton(triangulate); } - public void Unregister() { + public void Unregister() + { General.Interface.RemoveButton(triangulate); General.Interface.RemoveButton(gridlock); General.Interface.RemoveButton(cbseparator); @@ -42,11 +45,13 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.RemoveButton(sliceshlabel); } - private void ValueChanged(object sender, EventArgs e) { + private void ValueChanged(object sender, EventArgs e) + { if(!blockEvents && OnValueChanged != null) OnValueChanged(this, EventArgs.Empty); } - private void gridlock_CheckedChanged(object sender, EventArgs e) { + private void gridlock_CheckedChanged(object sender, EventArgs e) + { slicesH.Enabled = !gridlock.Checked; slicesV.Enabled = !gridlock.Checked; if(!blockEvents && OnGridLockChanged != null) OnGridLockChanged(this, EventArgs.Empty); diff --git a/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.Designer.cs b/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.Designer.cs index 14b3ad12..08cb4e55 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.radiuslabel = new System.Windows.Forms.ToolStripLabel(); this.radius = new CodeImp.DoomBuilder.Controls.ToolStripNumericUpDown(); diff --git a/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.cs b/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.cs index c4fbb581..2c1d8f94 100644 --- a/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.cs +++ b/Source/Plugins/BuilderModes/Interface/DrawRectangleOptionsPanel.cs @@ -18,11 +18,13 @@ namespace CodeImp.DoomBuilder.BuilderModes public int MaxSubdivisions { get { return (int)subdivs.Maximum; } set { subdivs.Maximum = value; } } public int MinSubdivisions { get { return (int)subdivs.Minimum; } set { subdivs.Minimum = value; } } - public DrawRectangleOptionsPanel() { + public DrawRectangleOptionsPanel() + { InitializeComponent(); } - public void Register() { + public void Register() + { radius.Value = radiusValue; subdivs.Value = subdivsValue; radius.ValueChanged += ValueChanged; @@ -35,7 +37,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.AddButton(reset); } - public void Unregister() { + public void Unregister() + { General.Interface.RemoveButton(reset); General.Interface.RemoveButton(subdivs); General.Interface.RemoveButton(subdivslabel); @@ -43,13 +46,15 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.RemoveButton(radiuslabel); } - private void ValueChanged(object sender, EventArgs e) { + private void ValueChanged(object sender, EventArgs e) + { radiusValue = (int)radius.Value; subdivsValue = (int)subdivs.Value; if(!blockEvents && OnValueChanged != null) OnValueChanged(this, EventArgs.Empty); } - private void reset_Click(object sender, EventArgs e) { + private void reset_Click(object sender, EventArgs e) + { blockEvents = true; radius.Value = 0; blockEvents = false; diff --git a/Source/Plugins/BuilderModes/Interface/ErrorCheckForm.cs b/Source/Plugins/BuilderModes/Interface/ErrorCheckForm.cs index 0b8d4693..978c1d02 100644 --- a/Source/Plugins/BuilderModes/Interface/ErrorCheckForm.cs +++ b/Source/Plugins/BuilderModes/Interface/ErrorCheckForm.cs @@ -203,11 +203,14 @@ namespace CodeImp.DoomBuilder.BuilderModes UpdateTitle(); //mxd // When no results found, show "no results" and disable the list - if(resultslist.Count == 0) { + if(resultslist.Count == 0) + { results.Items.Add(new ResultNoErrors()); results.Enabled = false; exportresults.Enabled = false; //mxd - } else { + } + else + { exportresults.Enabled = true; //mxd ClearSelectedResult(); //mxd } @@ -233,7 +236,8 @@ namespace CodeImp.DoomBuilder.BuilderModes blockmap.AddVerticesSet(General.Map.Map.Vertices); //mxd //mxd. Open the results panel - if (!resultspanel.Visible) { + if (!resultspanel.Visible) + { this.MinimumSize = new Size(); this.MaximumSize = new Size(); this.Size = initialsize; @@ -490,10 +494,13 @@ namespace CodeImp.DoomBuilder.BuilderModes else { ErrorResult r = (results.SelectedItem as ErrorResult); - if (r.Button1Click(false)) { - if (cbApplyToAll.Checked) fixSimilarErrors(r.GetType(), 1); //mxd + if (r.Button1Click(false)) + { + if (cbApplyToAll.Checked) FixSimilarErrors(r.GetType(), 1); //mxd StartChecking(); - } else { + } + else + { General.Interface.RedrawDisplay(); } } @@ -513,10 +520,13 @@ namespace CodeImp.DoomBuilder.BuilderModes else { ErrorResult r = (results.SelectedItem as ErrorResult); - if (r.Button2Click(false)) { - if (cbApplyToAll.Checked) fixSimilarErrors(r.GetType(), 2); //mxd + if (r.Button2Click(false)) + { + if (cbApplyToAll.Checked) FixSimilarErrors(r.GetType(), 2); //mxd StartChecking(); - } else { + } + else + { General.Interface.RedrawDisplay(); } } @@ -536,10 +546,13 @@ namespace CodeImp.DoomBuilder.BuilderModes else { ErrorResult r = (results.SelectedItem as ErrorResult); - if (r.Button3Click(false)) { - if (cbApplyToAll.Checked) fixSimilarErrors(r.GetType(), 3); //mxd + if (r.Button3Click(false)) + { + if (cbApplyToAll.Checked) FixSimilarErrors(r.GetType(), 3); //mxd StartChecking(); - } else { + } + else + { General.Interface.RedrawDisplay(); } } @@ -547,8 +560,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void fixSimilarErrors(Type type, int fixIndex) { - foreach (Object item in results.Items) { + private void FixSimilarErrors(Type type, int fixIndex) + { + foreach (Object item in results.Items) + { if (item == results.SelectedItem) continue; if (item.GetType() != type) continue; diff --git a/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.Designer.cs b/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.Designer.cs index b1485908..327f3bd4 100644 --- a/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); diff --git a/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.cs b/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.cs index 3fdf918f..ad8df542 100644 --- a/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.cs +++ b/Source/Plugins/BuilderModes/Interface/FilterSelectedThingsForm.cs @@ -16,39 +16,47 @@ namespace CodeImp.DoomBuilder.BuilderModes private ICollection selection; private ThingsMode mode; - public FilterSelectedThingsForm(ICollection selection, ThingsMode mode) { + public FilterSelectedThingsForm(ICollection selection, ThingsMode mode) + { InitializeComponent(); this.mode = mode; //apply window size and location - if(!size.IsEmpty && !location.IsEmpty) { + if(!size.IsEmpty && !location.IsEmpty) + { this.StartPosition = FormStartPosition.Manual; this.Size = size; this.Location = location; } - setup(selection); + Setup(selection); } - private void setup(ICollection selection) { + private void Setup(ICollection selection) + { this.selection = selection; //get thing types Dictionary thingcounts = new Dictionary(); Dictionary thingtitles = new Dictionary(); - foreach(Thing t in selection) { - if (!thingcounts.ContainsKey(t.Type)) { + foreach(Thing t in selection) + { + if (!thingcounts.ContainsKey(t.Type)) + { thingcounts.Add(t.Type, 1); ThingTypeInfo ti = General.Map.Data.GetThingInfo(t.Type); thingtitles.Add(t.Type, ti.Title); - } else { + } + else + { thingcounts[t.Type]++; } } //add data - foreach(KeyValuePair group in thingcounts) { + foreach(KeyValuePair group in thingcounts) + { DataGridViewRow row = new DataGridViewRow(); row.Cells.Add(new DataGridViewTextBoxCell { Value = group.Key }); //type @@ -61,20 +69,20 @@ namespace CodeImp.DoomBuilder.BuilderModes dataGridView.Sort(ThingType, ListSortDirection.Ascending); } - private void apply_Click(object sender, EventArgs e) { + private void apply_Click(object sender, EventArgs e) + { //get selected types List selectedtypes = new List(); - foreach(DataGridViewRow row in dataGridView.Rows) { + foreach(DataGridViewRow row in dataGridView.Rows) if (row.Selected) selectedtypes.Add((int)row.Cells[0].Value); - } //apply selection - if (selectedtypes.Count > 0) { - foreach (Thing t in selection) { - if (!selectedtypes.Contains(t.Type)) { - t.Selected = false; - } + if (selectedtypes.Count > 0) + { + foreach (Thing t in selection) + { + if (!selectedtypes.Contains(t.Type)) t.Selected = false; } //update display @@ -85,11 +93,13 @@ namespace CodeImp.DoomBuilder.BuilderModes this.Close(); } - private void cancel_Click(object sender, EventArgs e) { + private void cancel_Click(object sender, EventArgs e) + { this.Close(); } - private void FilterSelectedThingsForm_FormClosing(object sender, FormClosingEventArgs e) { + private void FilterSelectedThingsForm_FormClosing(object sender, FormClosingEventArgs e) + { size = this.Size; location = this.Location; } diff --git a/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.Designer.cs b/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.Designer.cs index 91a372bf..b68292fc 100644 --- a/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.tabControl = new System.Windows.Forms.TabControl(); this.sectors = new System.Windows.Forms.TabPage(); this.sectorflags = new CodeImp.DoomBuilder.Controls.CheckboxArrayControl(); diff --git a/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.cs b/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.cs index e11501da..e62b2418 100644 --- a/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.cs +++ b/Source/Plugins/BuilderModes/Interface/PastePropertiesOptionsForm.cs @@ -14,18 +14,21 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface private static Point location = Point.Empty; private readonly Dictionary typecontrols; - public PastePropertiesOptionsForm() { + public PastePropertiesOptionsForm() + { InitializeComponent(); //apply window size and location - if(!size.IsEmpty && !location.IsEmpty) { + if(!size.IsEmpty && !location.IsEmpty) + { this.StartPosition = FormStartPosition.Manual; this.Size = size; this.Location = location; } //create a collection - typecontrols = new Dictionary { + typecontrols = new Dictionary + { {SectorProperties.CopySettings, sectorflags}, {LinedefProperties.CopySettings, lineflags}, {SidedefProperties.CopySettings, sideflags}, @@ -34,12 +37,16 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface }; //fill flags - foreach(KeyValuePair group in typecontrols) { + foreach(KeyValuePair group in typecontrols) + { FieldInfo[] props = group.Key.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); string title = ""; - foreach(var prop in props) { - foreach(Attribute attr in Attribute.GetCustomAttributes(prop)) { - if(attr.GetType() == typeof(FieldDescription)) { + foreach(var prop in props) + { + foreach(Attribute attr in Attribute.GetCustomAttributes(prop)) + { + if(attr.GetType() == typeof(FieldDescription)) + { title = ((FieldDescription)attr).Description; break; } @@ -52,42 +59,41 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface } //select proper tab - if (General.Editing.Mode is ThingsMode) { + if (General.Editing.Mode is ThingsMode) tabControl.SelectTab(things); - }else if (General.Editing.Mode is VerticesMode) { + else if (General.Editing.Mode is VerticesMode) tabControl.SelectTab(vertices); - }else if (General.Editing.Mode is LinedefsMode) { + else if (General.Editing.Mode is LinedefsMode) tabControl.SelectTab(linedefs); - } } - private void apply_Click(object sender, EventArgs e) { - foreach (KeyValuePair group in typecontrols) { + private void apply_Click(object sender, EventArgs e) + { + foreach (KeyValuePair group in typecontrols) + { FieldInfo[] props = group.Key.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); var fields = new Dictionary(props.Length); - for(int i = 0; i < props.Length; i++) { - fields[props[i].Name] = props[i]; - } - - foreach(CheckBox cb in group.Value.Checkboxes) { - fields[cb.Tag.ToString()].SetValue(group.Key, cb.Checked); - } + for(int i = 0; i < props.Length; i++) fields[props[i].Name] = props[i]; + foreach(CheckBox cb in group.Value.Checkboxes) fields[cb.Tag.ToString()].SetValue(group.Key, cb.Checked); } this.Close(); } - private void cancel_Click(object sender, EventArgs e) { + private void cancel_Click(object sender, EventArgs e) + { this.Close(); } - private void enableall_Click(object sender, EventArgs e) { + private void enableall_Click(object sender, EventArgs e) + { CheckboxArrayControl curControl = tabControl.SelectedTab.Controls[0] as CheckboxArrayControl; if(curControl == null) return; //just a piece of boilerplate... bool enable = !curControl.Checkboxes[0].Checked; foreach(var cb in curControl.Checkboxes) cb.Checked = enable; } - private void PastePropertiesOptionsForm_FormClosing(object sender, FormClosingEventArgs e) { + private void PastePropertiesOptionsForm_FormClosing(object sender, FormClosingEventArgs e) + { size = this.Size; location = this.Location; } diff --git a/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.Designer.cs b/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.Designer.cs index cc378b53..3f938e71 100644 --- a/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.ceiling = new CodeImp.DoomBuilder.Controls.FlatSelectorControl(); diff --git a/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.cs b/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.cs index 3c6f605f..a6d5c7c8 100644 --- a/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.cs +++ b/Source/Plugins/BuilderModes/Interface/SectorDrawingOptionsPanel.cs @@ -1,4 +1,4 @@ -#region Namespaces +#region ================== Namespaces using System; using System.Windows.Forms; @@ -11,13 +11,15 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface { public partial class SectorDrawingOptionsPanel : UserControl { - #region Constructor / Setup + #region ================== Constructor / Setup - public SectorDrawingOptionsPanel() { + public SectorDrawingOptionsPanel() + { InitializeComponent(); } - public void Setup() { + public void Setup() + { ceilHeight.Text = General.Map.Options.CustomCeilingHeight.ToString(); floorHeight.Text = General.Map.Options.CustomFloorHeight.ToString(); brightness.StepValues = General.Map.Config.BrightnessLevels; @@ -49,89 +51,106 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface #endregion - #region Checkbox Events + #region ================== Checkbox Events - private void cbOverrideCeilingTexture_CheckedChanged(object sender, EventArgs e) { + private void cbOverrideCeilingTexture_CheckedChanged(object sender, EventArgs e) + { ceiling.Enabled = cbOverrideCeilingTexture.Checked; General.Map.Options.OverrideCeilingTexture = cbOverrideCeilingTexture.Checked; } - private void cbOverrideFloorTexture_CheckedChanged(object sender, EventArgs e) { + private void cbOverrideFloorTexture_CheckedChanged(object sender, EventArgs e) + { floor.Enabled = cbOverrideFloorTexture.Checked; General.Map.Options.OverrideFloorTexture = cbOverrideFloorTexture.Checked; } - private void cbOverrideTopTexture_CheckedChanged(object sender, EventArgs e) { + private void cbOverrideTopTexture_CheckedChanged(object sender, EventArgs e) + { top.Enabled = cbOverrideTopTexture.Checked; General.Map.Options.OverrideTopTexture = cbOverrideTopTexture.Checked; } - private void cbOverrideMiddleTexture_CheckedChanged(object sender, EventArgs e) { + private void cbOverrideMiddleTexture_CheckedChanged(object sender, EventArgs e) + { middle.Enabled = cbOverrideMiddleTexture.Checked; General.Map.Options.OverrideMiddleTexture = cbOverrideMiddleTexture.Checked; } - private void cbOverrideBottomTexture_CheckedChanged(object sender, EventArgs e) { + private void cbOverrideBottomTexture_CheckedChanged(object sender, EventArgs e) + { bottom.Enabled = cbOverrideBottomTexture.Checked; General.Map.Options.OverrideBottomTexture = cbOverrideBottomTexture.Checked; } - private void cbCeilHeight_CheckedChanged(object sender, EventArgs e) { + private void cbCeilHeight_CheckedChanged(object sender, EventArgs e) + { ceilHeight.Enabled = cbCeilHeight.Checked; General.Map.Options.OverrideCeilingHeight = cbCeilHeight.Checked; } - private void cbFloorHeight_CheckedChanged(object sender, EventArgs e) { + private void cbFloorHeight_CheckedChanged(object sender, EventArgs e) + { floorHeight.Enabled = cbFloorHeight.Checked; General.Map.Options.OverrideFloorHeight = cbFloorHeight.Checked; } - private void cbBrightness_CheckedChanged(object sender, EventArgs e) { + private void cbBrightness_CheckedChanged(object sender, EventArgs e) + { brightness.Enabled = cbBrightness.Checked; General.Map.Options.OverrideBrightness = cbBrightness.Checked; } #endregion - #region Inputs Events + #region ================== Inputs Events - private void ceilHeight_WhenTextChanged(object sender, EventArgs e) { + private void ceilHeight_WhenTextChanged(object sender, EventArgs e) + { General.Map.Options.CustomCeilingHeight = ceilHeight.GetResult(General.Map.Options.CustomCeilingHeight); } - private void floorHeight_WhenTextChanged(object sender, EventArgs e) { + private void floorHeight_WhenTextChanged(object sender, EventArgs e) + { General.Map.Options.CustomFloorHeight = floorHeight.GetResult(General.Map.Options.CustomFloorHeight); } - private void brightness_WhenTextChanged(object sender, EventArgs e) { + private void brightness_WhenTextChanged(object sender, EventArgs e) + { General.Map.Options.CustomBrightness = General.Clamp(brightness.GetResult(General.Map.Options.CustomBrightness), 0, 255); } - private void ceiling_OnValueChanged(object sender, EventArgs e) { + private void ceiling_OnValueChanged(object sender, EventArgs e) + { General.Map.Options.DefaultCeilingTexture = ceiling.TextureName; } - private void floor_OnValueChanged(object sender, EventArgs e) { + private void floor_OnValueChanged(object sender, EventArgs e) + { General.Map.Options.DefaultFloorTexture = floor.TextureName; } - private void top_OnValueChanged(object sender, EventArgs e) { + private void top_OnValueChanged(object sender, EventArgs e) + { General.Map.Options.DefaultTopTexture = top.TextureName; } - private void middle_OnValueChanged(object sender, EventArgs e) { + private void middle_OnValueChanged(object sender, EventArgs e) + { General.Map.Options.DefaultWallTexture = middle.TextureName; } - private void bottom_OnValueChanged(object sender, EventArgs e) { + private void bottom_OnValueChanged(object sender, EventArgs e) + { General.Map.Options.DefaultBottomTexture = bottom.TextureName; } #endregion - #region Texture Fill + #region ================== Texture Fill - private void fillceiling_Click(object sender, EventArgs e) { + private void fillceiling_Click(object sender, EventArgs e) + { ICollection sectors = General.Map.Map.GetSelectedSectors(true); if(sectors.Count == 0) return; @@ -139,9 +158,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(sectors.Count > 1) undodesc = sectors.Count + " sectors"; General.Map.UndoRedo.CreateUndo("Clear ceiling texture from " + undodesc); - foreach(Sector s in sectors) { - s.SetCeilTexture(ceiling.TextureName); - } + foreach(Sector s in sectors) s.SetCeilTexture(ceiling.TextureName); // Update the used textures General.Map.Data.UpdateUsedTextures(); @@ -151,7 +168,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Interface.RedrawDisplay(); } - private void fillfloor_Click(object sender, EventArgs e) { + private void fillfloor_Click(object sender, EventArgs e) + { ICollection sectors = General.Map.Map.GetSelectedSectors(true); if(sectors.Count == 0) return; @@ -159,9 +177,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(sectors.Count > 1) undodesc = sectors.Count + " sectors"; General.Map.UndoRedo.CreateUndo("Clear ceiling texture from " + undodesc); - foreach(Sector s in sectors) { - s.SetFloorTexture(floor.TextureName); - } + foreach(Sector s in sectors) s.SetFloorTexture(floor.TextureName); // Update the used textures General.Map.Data.UpdateUsedTextures(); @@ -171,7 +187,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Interface.RedrawDisplay(); } - private void fillupper_Click(object sender, EventArgs e) { + private void fillupper_Click(object sender, EventArgs e) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -179,7 +196,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(lines.Count > 1) undodesc = lines.Count + " linedefs"; General.Map.UndoRedo.CreateUndo("Fill upper texture for " + undodesc); - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(l.Front != null && l.Front.HighRequired()) l.Front.SetTextureHigh(top.TextureName); if(l.Back != null && l.Back.HighRequired()) l.Back.SetTextureHigh(top.TextureName); } @@ -189,7 +207,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.IsChanged = true; } - private void fillmiddle_Click(object sender, EventArgs e) { + private void fillmiddle_Click(object sender, EventArgs e) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -197,7 +216,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(lines.Count > 1) undodesc = lines.Count + " linedefs"; General.Map.UndoRedo.CreateUndo("Fill middle texture for " + undodesc); - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(l.Front != null && l.Front.MiddleRequired()) l.Front.SetTextureMid(middle.TextureName); if(l.Back != null && l.Back.MiddleRequired()) l.Back.SetTextureMid(middle.TextureName); } @@ -207,7 +227,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.IsChanged = true; } - private void filllower_Click(object sender, EventArgs e) { + private void filllower_Click(object sender, EventArgs e) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -215,7 +236,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(lines.Count > 1) undodesc = lines.Count + " linedefs"; General.Map.UndoRedo.CreateUndo("Fill lower texture for " + undodesc); - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(l.Front != null && l.Front.LowRequired()) l.Front.SetTextureLow(bottom.TextureName); if(l.Back != null && l.Back.LowRequired()) l.Back.SetTextureLow(bottom.TextureName); } @@ -225,17 +247,21 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.IsChanged = true; } - private void fillall_Click(object sender, EventArgs e) { + private void fillall_Click(object sender, EventArgs e) + { ICollection sectors = General.Map.Map.GetSelectedSectors(true); //if we have selected sectors - fill their textures - if (sectors.Count > 0) { + if (sectors.Count > 0) + { //make undo General.Map.UndoRedo.CreateUndo("Fill all texturs for " + sectors.Count + (sectors.Count > 1 ? " sectors" : " sector")); - foreach (Sector s in sectors) { + foreach (Sector s in sectors) + { //fill sidedefs - foreach(Sidedef side in s.Sidedefs) { + foreach(Sidedef side in s.Sidedefs) + { if(top.Enabled && side.HighRequired()) side.SetTextureHigh(top.TextureName); if(middle.Enabled && side.MiddleRequired()) side.SetTextureMid(middle.TextureName); if(bottom.Enabled && side.LowRequired()) side.SetTextureLow(bottom.TextureName); @@ -245,7 +271,9 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(floor.Enabled) s.SetFloorTexture(floor.TextureName); if(ceiling.Enabled) s.SetCeilTexture(ceiling.TextureName); } - } else { //if we don't - fill linedef textures + } + else //if we don't - fill linedef textures + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -253,16 +281,20 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.UndoRedo.CreateUndo("Fill all texturs for " + lines.Count + (lines.Count > 1 ? " linedefs" : " linedef")); //fill textures - foreach (Linedef l in lines) { - if(top.Enabled) { + foreach (Linedef l in lines) + { + if(top.Enabled) + { if(l.Front != null && l.Front.HighRequired()) l.Front.SetTextureHigh(top.TextureName); if(l.Back != null && l.Back.HighRequired()) l.Back.SetTextureHigh(top.TextureName); } - if(middle.Enabled) { + if(middle.Enabled) + { if(l.Front != null && l.Front.MiddleRequired()) l.Front.SetTextureMid(middle.TextureName); if(l.Back != null && l.Back.MiddleRequired()) l.Back.SetTextureMid(middle.TextureName); } - if(bottom.Enabled) { + if(bottom.Enabled) + { if(l.Front != null && l.Front.LowRequired()) l.Front.SetTextureLow(bottom.TextureName); if(l.Back != null && l.Back.LowRequired()) l.Back.SetTextureLow(bottom.TextureName); } @@ -280,9 +312,10 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface #endregion - #region Clear Textures + #region ================== Clear Textures - private void clearceiling_Click(object sender, EventArgs e) { + private void clearceiling_Click(object sender, EventArgs e) + { ICollection sectors = General.Map.Map.GetSelectedSectors(true); if(sectors.Count == 0) return; @@ -290,9 +323,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(sectors.Count > 1) undodesc = sectors.Count + " sectors"; General.Map.UndoRedo.CreateUndo("Clear ceiling texture from " + undodesc); - foreach(Sector s in sectors){ - s.SetCeilTexture("-"); - } + foreach(Sector s in sectors) s.SetCeilTexture("-"); // Update the used textures General.Map.Data.UpdateUsedTextures(); @@ -304,7 +335,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Interface.RedrawDisplay(); } - private void clearfloor_Click(object sender, EventArgs e) { + private void clearfloor_Click(object sender, EventArgs e) + { ICollection sectors = General.Map.Map.GetSelectedSectors(true); if(sectors.Count == 0) return; @@ -312,9 +344,7 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(sectors.Count > 1) undodesc = sectors.Count + " sectors"; General.Map.UndoRedo.CreateUndo("Clear floor texture from " + undodesc); - foreach(Sector s in sectors) { - s.SetFloorTexture("-"); - } + foreach(Sector s in sectors) s.SetFloorTexture("-"); // Update the used textures General.Map.Data.UpdateUsedTextures(); @@ -326,7 +356,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Interface.RedrawDisplay(); } - private void clearupper_Click(object sender, EventArgs e) { + private void clearupper_Click(object sender, EventArgs e) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -334,7 +365,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(lines.Count > 1) undodesc = lines.Count + " linedefs"; General.Map.UndoRedo.CreateUndo("Clear upper texture from " + undodesc); - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(l.Front != null && l.Front.HighTexture != "-") l.Front.SetTextureHigh("-"); if(l.Back != null && l.Back.HighTexture != "-") l.Back.SetTextureHigh("-"); } @@ -344,7 +376,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.IsChanged = true; } - private void clearmiddle_Click(object sender, EventArgs e) { + private void clearmiddle_Click(object sender, EventArgs e) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -352,7 +385,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(lines.Count > 1) undodesc = lines.Count + " linedefs"; General.Map.UndoRedo.CreateUndo("Clear middle texture from " + undodesc); - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(l.Front != null && l.Front.MiddleTexture != "-") l.Front.SetTextureMid("-"); if(l.Back != null && l.Back.MiddleTexture != "-") l.Back.SetTextureMid("-"); } @@ -362,7 +396,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.IsChanged = true; } - private void clearlower_Click(object sender, EventArgs e) { + private void clearlower_Click(object sender, EventArgs e) + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -370,7 +405,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface if(lines.Count > 1) undodesc = lines.Count + " linedefs"; General.Map.UndoRedo.CreateUndo("Clear lower texture from " + undodesc); - foreach(Linedef l in lines) { + foreach(Linedef l in lines) + { if(l.Front != null && l.Front.LowTexture != "-") l.Front.SetTextureLow("-"); if(l.Back != null && l.Back.LowTexture != "-") l.Back.SetTextureLow("-"); } @@ -380,18 +416,22 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.IsChanged = true; } - private void clearall_Click(object sender, EventArgs e) { + private void clearall_Click(object sender, EventArgs e) + { //if we have selected sectors - clear their textures ICollection sectors = General.Map.Map.GetSelectedSectors(true); - if (sectors.Count > 0) { + if (sectors.Count > 0) + { //make undo string undodesc = "sector"; if(sectors.Count > 1) undodesc = sectors.Count + " sectors"; General.Map.UndoRedo.CreateUndo("Clear all texture from " + undodesc); - foreach(Sector s in sectors) { + foreach(Sector s in sectors) + { //clear side textures - foreach (Sidedef side in s.Sidedefs) { + foreach (Sidedef side in s.Sidedefs) + { if(side.HighTexture != "-") side.SetTextureHigh("-"); if(side.MiddleTexture != "-") side.SetTextureMid("-"); if(side.LowTexture != "-") side.SetTextureLow("-"); @@ -402,7 +442,9 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface s.SetFloorTexture("-"); } - } else { //if we don't - clear linedef textures + } + else //if we don't - clear linedef textures + { ICollection lines = General.Map.Map.GetSelectedLinedefs(true); if(lines.Count == 0) return; @@ -412,13 +454,16 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface General.Map.UndoRedo.CreateUndo("Clear all texture from " + undodesc); //clear textures - foreach(Linedef l in lines) { - if(l.Front != null) { + foreach(Linedef l in lines) + { + if(l.Front != null) + { if(l.Front.HighTexture != "-") l.Front.SetTextureHigh("-"); if(l.Front.MiddleTexture != "-") l.Front.SetTextureMid("-"); if(l.Front.LowTexture != "-") l.Front.SetTextureLow("-"); } - if (l.Back != null) { + if (l.Back != null) + { if(l.Back.HighTexture != "-") l.Back.SetTextureHigh("-"); if(l.Back.MiddleTexture != "-") l.Back.SetTextureMid("-"); if(l.Back.LowTexture != "-") l.Back.SetTextureLow("-"); diff --git a/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.Designer.cs b/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.Designer.cs index 5c92dd35..34553f11 100644 --- a/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.enableall = new System.Windows.Forms.Button(); this.apply = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); diff --git a/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.cs b/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.cs index 78859a03..cac94cad 100644 --- a/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.cs +++ b/Source/Plugins/BuilderModes/Interface/SelectSimilarElementOptionsPanel.cs @@ -25,11 +25,13 @@ namespace CodeImp.DoomBuilder.BuilderModes private TabPage[] activeTabs; private readonly Dictionary typecontrols; - public SelectSimilarElementOptionsPanel() { + public SelectSimilarElementOptionsPanel() + { InitializeComponent(); //apply window size and location - if(!size.IsEmpty && !location.IsEmpty) { + if(!size.IsEmpty && !location.IsEmpty) + { this.StartPosition = FormStartPosition.Manual; this.Size = size; this.Location = location; @@ -45,33 +47,47 @@ namespace CodeImp.DoomBuilder.BuilderModes }; } - public bool Setup(BaseClassicMode mode) { + public bool Setup(BaseClassicMode mode) + { this.mode = mode; //which tabs should we display? - if(General.Editing.Mode is ThingsMode) { + if(General.Editing.Mode is ThingsMode) + { activeTabs = new[] {things}; - } else if(General.Editing.Mode is VerticesMode) { + } + else if(General.Editing.Mode is VerticesMode) + { activeTabs = new[] { vertices }; - } else if(General.Editing.Mode is LinedefsMode) { + } + else if(General.Editing.Mode is LinedefsMode) + { activeTabs = new[] { linedefs, sidedefs }; - } else if(mode is SectorsMode) { + } + else if(mode is SectorsMode) + { activeTabs = new[] { sectors }; - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "This action doesn't support current editing mode..."); return false; } //fill flags - foreach(TabPage page in activeTabs) { + foreach(TabPage page in activeTabs) + { CheckboxArrayControl curControl = page.Controls[0] as CheckboxArrayControl; if(curControl == null) continue; //just a piece of boilerplate... FieldInfo[] props = typecontrols[curControl].GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); string title = ""; - foreach(var prop in props) { - foreach(Attribute attr in Attribute.GetCustomAttributes(prop)) { - if(attr.GetType() == typeof(FieldDescription)) { + foreach(var prop in props) + { + foreach(Attribute attr in Attribute.GetCustomAttributes(prop)) + { + if(attr.GetType() == typeof(FieldDescription)) + { title = ((FieldDescription)attr).Description; break; } @@ -91,79 +107,92 @@ namespace CodeImp.DoomBuilder.BuilderModes return true; } - private void SelectSimilarElementOptionsPanel_FormClosing(object sender, FormClosingEventArgs e) { + private void SelectSimilarElementOptionsPanel_FormClosing(object sender, FormClosingEventArgs e) + { size = this.Size; location = this.Location; } - private void enableall_Click(object sender, EventArgs e) { + private void enableall_Click(object sender, EventArgs e) + { CheckboxArrayControl curControl = tabControl.SelectedTab.Controls[0] as CheckboxArrayControl; if(curControl == null) return; //just a piece of boilerplate... bool enable = !curControl.Checkboxes[0].Checked; foreach(var cb in curControl.Checkboxes) cb.Checked = enable; } - private void cancel_Click(object sender, EventArgs e) { + private void cancel_Click(object sender, EventArgs e) + { this.Close(); } - private void apply_Click(object sender, EventArgs e) { + private void apply_Click(object sender, EventArgs e) + { //save flags states - foreach (TabPage page in activeTabs) { + foreach (TabPage page in activeTabs) + { CheckboxArrayControl curControl = page.Controls[0] as CheckboxArrayControl; if(curControl == null) continue; //just a piece of boilerplate... FieldInfo[] props = typecontrols[curControl].GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); var fields = new Dictionary(props.Length); - for(int i = 0; i < props.Length; i++) { - fields[props[i].Name] = props[i]; - } - - foreach(CheckBox cb in curControl.Checkboxes) { - fields[cb.Tag.ToString()].SetValue(typecontrols[curControl], cb.Checked); - } + for(int i = 0; i < props.Length; i++) fields[props[i].Name] = props[i]; + foreach(CheckBox cb in curControl.Checkboxes) fields[cb.Tag.ToString()].SetValue(typecontrols[curControl], cb.Checked); } //perform selection - if(mode is ThingsMode) { + if(mode is ThingsMode) + { ICollection selected = General.Map.Map.GetSelectedThings(true); ICollection unselected = General.Map.Map.GetSelectedThings(false); - foreach (Thing target in unselected) { - foreach (Thing source in selected) { + foreach (Thing target in unselected) + { + foreach (Thing source in selected) + { if (PropertiesComparer.PropertiesMatch((ThingPropertiesCopySettings) typecontrols[thingflags], source, target)) mode.SelectMapElement(target); } } - } else if(mode is LinedefsMode) { + } + else if(mode is LinedefsMode) + { ICollection selected = General.Map.Map.GetSelectedLinedefs(true); ICollection unselected = General.Map.Map.GetSelectedLinedefs(false); - foreach(Linedef target in unselected) { - foreach(Linedef source in selected) { + foreach(Linedef target in unselected) + { + foreach(Linedef source in selected) + { if(PropertiesComparer.PropertiesMatch((LinedefPropertiesCopySettings)typecontrols[lineflags], (SidedefPropertiesCopySettings)typecontrols[sideflags], source, target)) mode.SelectMapElement(target); } } - - } else if(mode is SectorsMode) { + } + else if(mode is SectorsMode) + { ICollection selected = General.Map.Map.GetSelectedSectors(true); ICollection unselected = General.Map.Map.GetSelectedSectors(false); - foreach(Sector target in unselected) { - foreach(Sector source in selected) { + foreach(Sector target in unselected) + { + foreach(Sector source in selected) + { if(PropertiesComparer.PropertiesMatch((SectorPropertiesCopySettings)typecontrols[sectorflags], source, target)) mode.SelectMapElement(target); } } - - } else if(mode is VerticesMode) { + } + else if(mode is VerticesMode) + { ICollection selected = General.Map.Map.GetSelectedVertices(true); ICollection unselected = General.Map.Map.GetSelectedVertices(false); - foreach(Vertex target in unselected) { - foreach(Vertex source in selected) { + foreach(Vertex target in unselected) + { + foreach(Vertex source in selected) + { if(PropertiesComparer.PropertiesMatch((VertexPropertiesCopySettings)typecontrols[vertexflags], source, target)) mode.SelectMapElement(target); } diff --git a/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.Designer.cs b/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.Designer.cs index 86ccb86a..6daf225c 100644 --- a/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.Designer.cs +++ b/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.Designer.cs @@ -11,8 +11,10 @@ /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if(disposing && (components != null)) { + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { components.Dispose(); } base.Dispose(disposing); @@ -24,7 +26,8 @@ /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// - private void InitializeComponent() { + private void InitializeComponent() + { this.tbExportPath = new System.Windows.Forms.TextBox(); this.browse = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); diff --git a/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.cs b/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.cs index 18432b6c..59c14b56 100644 --- a/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.cs +++ b/Source/Plugins/BuilderModes/Interface/WavefrontSettingsForm.cs @@ -20,13 +20,17 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface #endregion - public WavefrontSettingsForm(int sectorsCount) { + public WavefrontSettingsForm(int sectorsCount) + { InitializeComponent(); string name = Path.GetFileNameWithoutExtension(General.Map.FileTitle) + "_" + General.Map.Options.LevelName + ".obj"; - if(string.IsNullOrEmpty(General.Map.FilePathName)) { + if(string.IsNullOrEmpty(General.Map.FilePathName)) + { saveFileDialog.FileName = name; - } else { + } + else + { saveFileDialog.InitialDirectory = General.Map.FilePathName; saveFileDialog.FileName = Path.GetDirectoryName(General.Map.FilePathName) + Path.DirectorySeparatorChar + name; tbExportPath.Text = saveFileDialog.FileName; @@ -42,19 +46,22 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface #region ================== Events - private void browse_Click(object sender, EventArgs e) { - if(saveFileDialog.ShowDialog() == DialogResult.OK) { + private void browse_Click(object sender, EventArgs e) + { + if(saveFileDialog.ShowDialog() == DialogResult.OK) tbExportPath.Text = saveFileDialog.FileName; - } } - private void export_Click(object sender, EventArgs e) { + private void export_Click(object sender, EventArgs e) + { //check settings - if(nudScale.Value == 0) { + if(nudScale.Value == 0) + { MessageBox.Show("Scale should not be zero!"); return; } - if(!Directory.Exists(Path.GetDirectoryName(tbExportPath.Text))) { + if(!Directory.Exists(Path.GetDirectoryName(tbExportPath.Text))) + { MessageBox.Show("Selected path does not exist!"); return; } @@ -68,7 +75,8 @@ namespace CodeImp.DoomBuilder.BuilderModes.Interface this.Close(); } - private void cancel_Click(object sender, EventArgs e) { + private void cancel_Click(object sender, EventArgs e) + { this.Close(); } diff --git a/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySector.cs b/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySector.cs index 2980b8fe..4126aa4e 100644 --- a/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySector.cs +++ b/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySector.cs @@ -128,19 +128,27 @@ namespace CodeImp.DoomBuilder.BuilderModes bool lockX = General.Interface.CtrlState && !General.Interface.ShiftState; bool lockY = !General.Interface.CtrlState && General.Interface.ShiftState; - if(lockX || lockY) { + if(lockX || lockY) + { float camAngle = Angle2D.RadToDeg(General.Map.VisualCamera.AngleXY); - if(camAngle > 315 || camAngle < 46) { + if(camAngle > 315 || camAngle < 46) + { if(lockX) offsetx = 0; if(lockY) offsety = 0; - } else if(camAngle > 225) { + } + else if(camAngle > 225) + { if(lockX) offsety = 0; if(lockY) offsetx = 0; - } else if(camAngle > 135) { + } + else if(camAngle > 135) + { if(lockX) offsetx = 0; if(lockY) offsety = 0; - } else { + } + else + { if(lockX) offsety = 0; if(lockY) offsetx = 0; } @@ -160,28 +168,38 @@ namespace CodeImp.DoomBuilder.BuilderModes offsety = (int)Math.Round(v.y); // Apply offsets - if(General.Interface.CtrlState && General.Interface.ShiftState) { //mxd. Clamp to grid size? + if(General.Interface.CtrlState && General.Interface.ShiftState) + { + //mxd. Clamp to grid size? int newoffsetx = startoffsetx - (int)Math.Round(offsetx); int newoffsety = startoffsety + (int)Math.Round(offsety); int dx = prevoffsetx - newoffsetx; int dy = prevoffsety - newoffsety; - if(Math.Abs(dx) >= General.Map.Grid.GridSize) { + if(Math.Abs(dx) >= General.Map.Grid.GridSize) + { dx = General.Map.Grid.GridSize * Math.Sign(dx); prevoffsetx = newoffsetx; - } else { + } + else + { dx = 0; } - if(Math.Abs(dy) >= General.Map.Grid.GridSize) { + if(Math.Abs(dy) >= General.Map.Grid.GridSize) + { dy = General.Map.Grid.GridSize * Math.Sign(dy); prevoffsety = newoffsety; - } else { + } + else + { dy = 0; } if(dx != 0 || dy != 0) mode.ApplyFlatOffsetChange(dx, dy); - } else { + } + else + { int newoffsetx = startoffsetx - (int)Math.Round(offsetx); int newoffsety = startoffsety + (int)Math.Round(offsety); mode.ApplyFlatOffsetChange(prevoffsetx - newoffsetx, prevoffsety - newoffsety); @@ -193,47 +211,59 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override Sector GetControlSector() { + public override Sector GetControlSector() + { return level.sector; } //mxd - protected void onTextureChanged() { - if(level.sector == this.Sector.Sector) { + protected void OnTextureChanged() + { + if(level.sector == this.Sector.Sector) + { this.Setup(); //check for 3d floors - foreach(Sidedef s in level.sector.Sidedefs) { - if(s.Line.Action == 160 && s.Line.Front != null) { + foreach(Sidedef s in level.sector.Sidedefs) + { + if(s.Line.Action == 160 && s.Line.Front != null) + { int sectortag = s.Line.Args[0] + (s.Line.Args[4] << 8); - foreach(Sector sector in General.Map.Map.Sectors) { - if(sector.Tag == sectortag) { + foreach(Sector sector in General.Map.Map.Sectors) + { + if(sector.Tag == sectortag) + { BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(sector); vs.UpdateSectorGeometry(false); } } } } - } else if(mode.VisualSectorExists(level.sector)) { + } + else if(mode.VisualSectorExists(level.sector)) + { BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(level.sector); vs.UpdateSectorGeometry(false); } } //mxd - public virtual bool IsSelected() { + public virtual bool IsSelected() + { return selected; } //mxd - protected void alignTextureToClosestLine(bool alignx, bool aligny) { + protected void AlignTextureToClosestLine(bool alignx, bool aligny) + { if(!(mode.HighlightedObject is BaseVisualSector)) return; //do we need to align this? (and also grab texture scale while we are at it) float scaleX, scaleY; bool isFloor = (geoType == VisualGeometryType.FLOOR); - if(mode.HighlightedTarget is VisualFloor) { + if(mode.HighlightedTarget is VisualFloor) + { VisualFloor target = mode.HighlightedTarget as VisualFloor; //check texture @@ -241,7 +271,9 @@ namespace CodeImp.DoomBuilder.BuilderModes scaleX = target.Sector.Sector.Fields.GetValue("xscalefloor", 1.0f); scaleY = target.Sector.Sector.Fields.GetValue("yscalefloor", 1.0f); - } else { + } + else + { VisualCeiling target = mode.HighlightedTarget as VisualCeiling; //check texture @@ -282,12 +314,14 @@ namespace CodeImp.DoomBuilder.BuilderModes float distToEnd = Vector2D.Distance(hitpos, targetLine.End.Position); Vector2D offset = (distToStart < distToEnd ? targetLine.Start.Position : targetLine.End.Position).GetRotated(Angle2D.DegToRad(sourceAngle)); - if(alignx) { + if(alignx) + { if(Texture != null) offset.x %= Texture.Width / scaleX; UDMFTools.SetFloat(Sector.Sector.Fields, (isFloor ? "xpanningfloor" : "xpanningceiling"), (float)Math.Round(-offset.x), 0f); } - if(aligny) { + if(aligny) + { if(Texture != null) offset.y %= Texture.Height / scaleY; UDMFTools.SetFloat(Sector.Sector.Fields, (isFloor ? "ypanningfloor" : "ypanningceiling"), (float)Math.Round(offset.y), 0f); } @@ -297,21 +331,25 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected void alignTextureToSlopeLine(Linedef slopeSource, float slopeAngle, bool isFront, bool alignx, bool aligny) { + protected void AlignTextureToSlopeLine(Linedef slopeSource, float slopeAngle, bool isFront, bool alignx, bool aligny) + { bool isFloor = (geoType == VisualGeometryType.FLOOR); - Sector.Sector.Fields.BeforeFieldsChange(); - float sourceAngle = (float)Math.Round(General.ClampAngle(isFront ? -Angle2D.RadToDeg(slopeSource.Angle) + 90 : -Angle2D.RadToDeg(slopeSource.Angle) - 90), 1); - if(isFloor) { + if(isFloor) + { if((isFront && slopeSource.Front.Sector.FloorHeight > slopeSource.Back.Sector.FloorHeight) || - (!isFront && slopeSource.Front.Sector.FloorHeight < slopeSource.Back.Sector.FloorHeight)) { + (!isFront && slopeSource.Front.Sector.FloorHeight < slopeSource.Back.Sector.FloorHeight)) + { sourceAngle = General.ClampAngle(sourceAngle + 180); } - } else { + } + else + { if((isFront && slopeSource.Front.Sector.CeilHeight < slopeSource.Back.Sector.CeilHeight) || - (!isFront && slopeSource.Front.Sector.CeilHeight > slopeSource.Back.Sector.CeilHeight)) { + (!isFront && slopeSource.Front.Sector.CeilHeight > slopeSource.Back.Sector.CeilHeight)) + { sourceAngle = General.ClampAngle(sourceAngle + 180); } } @@ -327,40 +365,53 @@ namespace CodeImp.DoomBuilder.BuilderModes float scaleY; //set scale - if(aligny) { + if(aligny) + { scaleY = (float)Math.Round(scaleX * (1 / (float)Math.Cos(slopeAngle)), 2); UDMFTools.SetFloat(Sector.Sector.Fields, yScaleKey, scaleY, 1.0f); - } else { + } + else + { scaleY = Sector.Sector.Fields.GetValue(yScaleKey, 1.0f); } //update texture offsets Vector2D offset; - - if(isFloor) { + if(isFloor) + { if((isFront && slopeSource.Front.Sector.FloorHeight < slopeSource.Back.Sector.FloorHeight) || - (!isFront && slopeSource.Front.Sector.FloorHeight > slopeSource.Back.Sector.FloorHeight)) { + (!isFront && slopeSource.Front.Sector.FloorHeight > slopeSource.Back.Sector.FloorHeight)) + { offset = slopeSource.End.Position; - } else { + } + else + { offset = slopeSource.Start.Position; } - } else { + } + else + { if((isFront && slopeSource.Front.Sector.CeilHeight > slopeSource.Back.Sector.CeilHeight) || - (!isFront && slopeSource.Front.Sector.CeilHeight < slopeSource.Back.Sector.CeilHeight)) { + (!isFront && slopeSource.Front.Sector.CeilHeight < slopeSource.Back.Sector.CeilHeight)) + { offset = slopeSource.End.Position; - } else { + } + else + { offset = slopeSource.Start.Position; } } offset = offset.GetRotated(Angle2D.DegToRad(sourceAngle)); - if(alignx) { + if(alignx) + { if(Texture != null) offset.x %= Texture.Width / scaleX; UDMFTools.SetFloat(Sector.Sector.Fields, (isFloor ? "xpanningfloor" : "xpanningceiling"), (float)Math.Round(-offset.x), 0f); } - if(aligny) { + if(aligny) + { if(Texture != null) offset.y %= Texture.Height / scaleY; UDMFTools.SetFloat(Sector.Sector.Fields, (isFloor ? "ypanningfloor" : "ypanningceiling"), (float)Math.Round(offset.y), 0f); } @@ -471,7 +522,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Delete texture - public virtual void OnDelete() { + public virtual void OnDelete() + { // Remove texture mode.CreateUndo("Delete texture"); mode.SetActionResult("Deleted a texture."); @@ -569,7 +621,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Auto-align texture offsets - public virtual void OnTextureAlign(bool alignx, bool aligny) { + public virtual void OnTextureAlign(bool alignx, bool aligny) + { if(!General.Map.UDMF) return; //create undo @@ -585,8 +638,10 @@ namespace CodeImp.DoomBuilder.BuilderModes List selection = mode.GetSelectedSurfaces(); //align textures on slopes - foreach(VisualGeometry vg in selection) { - if(vg.GeometryType == VisualGeometryType.FLOOR || vg.GeometryType == VisualGeometryType.CEILING) { + foreach(VisualGeometry vg in selection) + { + if(vg.GeometryType == VisualGeometryType.FLOOR || vg.GeometryType == VisualGeometryType.CEILING) + { if(vg.GeometryType == VisualGeometryType.FLOOR) ((VisualFloor)vg).AlignTexture(alignx, aligny); else @@ -646,7 +701,7 @@ namespace CodeImp.DoomBuilder.BuilderModes { mode.CreateUndo("Change flat '" + texture + "'"); SetTexture(texture); - onTextureChanged(); //mxd + OnTextureChanged(); //mxd } // Copy texture @@ -671,10 +726,10 @@ namespace CodeImp.DoomBuilder.BuilderModes List sectors = mode.GetSelectedSectors(); updateList = new List(); - foreach(Sector s in sectors) { - if(mode.VisualSectorExists(s)) { + foreach(Sector s in sectors) + { + if(mode.VisualSectorExists(s)) updateList.Add((BaseVisualSector)mode.GetVisualSector(s)); - } } General.Interface.OnEditFormValuesChanged += Interface_OnEditFormValuesChanged; //mxd @@ -689,9 +744,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void Interface_OnEditFormValuesChanged(object sender, EventArgs e) { - foreach(BaseVisualSector vs in updateList) - vs.UpdateSectorGeometry(true); + private void Interface_OnEditFormValuesChanged(object sender, EventArgs e) + { + foreach(BaseVisualSector vs in updateList) vs.UpdateSectorGeometry(true); } // Sector height change @@ -703,9 +758,14 @@ namespace CodeImp.DoomBuilder.BuilderModes // Rebuild sector BaseVisualSector vs; - if(mode.VisualSectorExists(level.sector)) { + if(mode.VisualSectorExists(level.sector)) + { vs = (BaseVisualSector)mode.GetVisualSector(level.sector); - } else {//mxd. Need this to apply changes to 3d-floor even if control sector doesn't exist as BaseVisualSector + } + else + { + //mxd. Need this to apply changes to 3d-floor even if control sector doesn't exist + //as BaseVisualSector vs = mode.CreateBaseVisualSector(level.sector); } @@ -736,7 +796,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if(horizontal == 0 && vertical == 0) return; //mxd //mxd - if (!General.Map.UDMF) { + if (!General.Map.UDMF) + { General.Interface.DisplayStatus(StatusType.Warning, "Floor/ceiling texture offsets cannot be changed in this map format!"); return; } @@ -745,25 +806,33 @@ namespace CodeImp.DoomBuilder.BuilderModes undoticket = mode.CreateUndo("Change texture offsets"); //mxd - if(doSurfaceAngleCorrection) { + if(doSurfaceAngleCorrection) + { Point p = new Point(horizontal, vertical); float angle = Angle2D.RadToDeg(General.Map.VisualCamera.AngleXY); - if(GeometryType == VisualGeometryType.CEILING) { + if(GeometryType == VisualGeometryType.CEILING) angle += level.sector.Fields.GetValue("rotationceiling", 0f); - } else + else angle += level.sector.Fields.GetValue("rotationfloor", 0f); angle = General.ClampAngle(angle); - if(angle > 315 || angle < 46) { - - } else if(angle > 225) { + if(angle > 315 || angle < 46) + { + //already correct + } + else if(angle > 225) + { vertical = p.X; horizontal = -p.Y; - } else if(angle > 135) { + } + else if(angle > 135) + { horizontal = -p.X; vertical = -p.Y; - } else { + } + else + { vertical = -p.X; horizontal = p.Y; } @@ -774,7 +843,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update sector geometry Sector s = GetControlSector(); - if(s.Index != Sector.Sector.Index) { + if(s.Index != Sector.Sector.Index) + { s.UpdateNeeded = true; s.UpdateCache(); mode.GetSectorData(s).Update(); @@ -789,7 +859,8 @@ namespace CodeImp.DoomBuilder.BuilderModes Sector.Rebuild(); } - public virtual void OnChangeTextureRotation(float angle) { + public virtual void OnChangeTextureRotation(float angle) + { if(!General.Map.UDMF) return; if((General.Map.UndoRedo.NextUndo == null) || (General.Map.UndoRedo.NextUndo.TicketID != undoticket)) @@ -803,7 +874,8 @@ namespace CodeImp.DoomBuilder.BuilderModes s.Fields.BeforeFieldsChange(); UDMFTools.SetFloat(s.Fields, key, angle, 0.0f); - if(s.Index != Sector.Sector.Index) { + if(s.Index != Sector.Sector.Index) + { s.UpdateNeeded = true; s.UpdateCache(); mode.GetSectorData(s).Update(); @@ -817,7 +889,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public virtual void OnChangeTextureScale(float incrementX, float incrementY) { + public virtual void OnChangeTextureScale(float incrementX, float incrementY) + { if(!General.Map.UDMF) return; if((General.Map.UndoRedo.NextUndo == null) || (General.Map.UndoRedo.NextUndo.TicketID != undoticket)) diff --git a/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySidedef.cs b/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySidedef.cs index 15ce3606..682bfd6e 100644 --- a/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySidedef.cs +++ b/Source/Plugins/BuilderModes/VisualModes/BaseVisualGeometrySidedef.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Windows.Forms; +using CodeImp.DoomBuilder.Config; using CodeImp.DoomBuilder.Data; using CodeImp.DoomBuilder.IO; using CodeImp.DoomBuilder.Map; @@ -85,7 +86,8 @@ namespace CodeImp.DoomBuilder.BuilderModes if(!sd.IsFront) this.deltaxy = -this.deltaxy; //mxd - if(mode.UseSelectionFromClassicMode && sd.Line.Selected) { + if(mode.UseSelectionFromClassicMode && sd.Line.Selected) + { this.selected = true; mode.AddSelectedObject(this); } @@ -370,7 +372,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected float getRoundedTextureOffset(float oldValue, float offset, float scale, float textureSize) { + protected float GetRoundedTextureOffset(float oldValue, float offset, float scale, float textureSize) + { if(offset == 0f) return oldValue; float scaledOffset = offset * scale; float result = (float)Math.Round(oldValue + scaledOffset); @@ -380,14 +383,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected void onTextureChanged() { + protected void OnTextureChanged() + { //check for 3d floors - if(Sidedef.Line.Action == 160) { + if(Sidedef.Line.Action == 160) + { int sectortag = Sidedef.Line.Args[0] + (Sidedef.Line.Args[4] << 8); if(sectortag == 0) return; - foreach(Sector sector in General.Map.Map.Sectors) { - if(sector.Tag == sectortag) { + foreach(Sector sector in General.Map.Map.Sectors) + { + if(sector.Tag == sectortag) + { BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(sector); vs.UpdateSectorGeometry(true); } @@ -397,7 +404,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected void selectNeighbours(string texture, bool select, bool withSameTexture, bool withSameHeight) + protected void SelectNeighbours(string texture, bool select, bool withSameTexture, bool withSameHeight) { if(Sidedef.Sector == null || (!withSameTexture && !withSameHeight)) return; @@ -449,12 +456,14 @@ namespace CodeImp.DoomBuilder.BuilderModes if (doublesided) { BaseVisualSector s = mode.GetVisualSector(line.Front.Sector) as BaseVisualSector; - if (s != null) { + if (s != null) + { extrasides.AddRange(s.GetSidedefParts(line.Front).middle3d.ToArray()); } s = mode.GetVisualSector(line.Back.Sector) as BaseVisualSector; - if(s != null) { + if(s != null) + { extrasides.AddRange(s.GetSidedefParts(line.Back).middle3d.ToArray()); } } @@ -587,7 +596,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public virtual bool IsSelected() { + public virtual bool IsSelected() + { return selected; } @@ -707,8 +717,10 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public virtual void OnResetLocalTextureOffset() { - if (!General.Map.UDMF) { + public virtual void OnResetLocalTextureOffset() + { + if (!General.Map.UDMF) + { OnResetTextureOffset(); return; } @@ -942,7 +954,7 @@ namespace CodeImp.DoomBuilder.BuilderModes { mode.CreateUndo("Change texture " + texture); SetTexture(texture); - onTextureChanged();//mxd + OnTextureChanged();//mxd } // Paste texture @@ -953,7 +965,7 @@ namespace CodeImp.DoomBuilder.BuilderModes mode.CreateUndo("Paste texture '" + BuilderPlug.Me.CopiedTexture + "'"); mode.SetActionResult("Pasted texture '" + BuilderPlug.Me.CopiedTexture + "'."); SetTexture(BuilderPlug.Me.CopiedTexture); - onTextureChanged();//mxd + OnTextureChanged();//mxd } } @@ -961,10 +973,13 @@ namespace CodeImp.DoomBuilder.BuilderModes public virtual void OnPasteTextureOffsets() { mode.CreateUndo("Paste texture offsets"); - if (General.Map.UDMF) { + if (General.Map.UDMF) + { SetTextureOffsetX(BuilderPlug.Me.CopiedOffsets.X); SetTextureOffsetY(BuilderPlug.Me.CopiedOffsets.Y); - } else { + } + else + { Sidedef.OffsetX = BuilderPlug.Me.CopiedOffsets.X; Sidedef.OffsetY = BuilderPlug.Me.CopiedOffsets.Y; } @@ -1069,7 +1084,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { List linedefs = mode.GetSelectedLinedefs(); updateList = new List(); //mxd - foreach(Linedef l in linedefs) { + foreach(Linedef l in linedefs) + { if(l.Front != null && mode.VisualSectorExists(l.Front.Sector)) updateList.Add((BaseVisualSector)mode.GetVisualSector(l.Front.Sector)); if(l.Back != null && mode.VisualSectorExists(l.Back.Sector)) @@ -1108,9 +1124,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void Interface_OnEditFormValuesChanged(object sender, EventArgs e) { - foreach(BaseVisualSector vs in updateList) - vs.UpdateSectorGeometry(false); + private void Interface_OnEditFormValuesChanged(object sender, EventArgs e) + { + foreach(BaseVisualSector vs in updateList) vs.UpdateSectorGeometry(false); } // Mouse moves @@ -1164,28 +1180,39 @@ namespace CodeImp.DoomBuilder.BuilderModes if((Math.Sign(dragdeltaz.x) < 0) || (Math.Sign(dragdeltaz.y) < 0) || (Math.Sign(dragdeltaz.z) < 0)) offsety = -offsety; // Apply offsets - if(General.Interface.CtrlState && General.Interface.ShiftState) { //mxd. Clamp to grid size? + if(General.Interface.CtrlState && General.Interface.ShiftState) + { + //mxd. Clamp to grid size? int newoffsetx = startoffsetx - (int)Math.Round(offsetx); int newoffsety = startoffsety + (int)Math.Round(offsety); int dx = prevoffsetx - newoffsetx; int dy = prevoffsety - newoffsety; - if(Math.Abs(dx) >= General.Map.Grid.GridSize) { + if(Math.Abs(dx) >= General.Map.Grid.GridSize) + { dx = General.Map.Grid.GridSize * Math.Sign(dx); prevoffsetx = newoffsetx; - } else { + } + else + { dx = 0; } - if(Math.Abs(dy) >= General.Map.Grid.GridSize) { + if(Math.Abs(dy) >= General.Map.Grid.GridSize) + { dy = General.Map.Grid.GridSize * Math.Sign(dy); prevoffsety = newoffsety; - } else { + } + else + { dy = 0; } if(dx != 0 || dy != 0) mode.ApplyTextureOffsetChange(dx, dy); - } else { //mxd. Constraint to axis? + } + else + { + //mxd. Constraint to axis? int newoffsetx = (General.Interface.CtrlState ? startoffsetx : startoffsetx - (int)Math.Round(offsetx)); //mxd int newoffsety = (General.Interface.ShiftState ? startoffsety : startoffsety + (int)Math.Round(offsety)); //mxd mode.ApplyTextureOffsetChange(prevoffsetx - newoffsetx, prevoffsety - newoffsety); @@ -1239,12 +1266,15 @@ namespace CodeImp.DoomBuilder.BuilderModes undoticket = mode.CreateUndo("Change texture offsets"); //mxd - if (General.Map.UDMF) { + if (General.Map.UDMF) + { // Apply UDMF offsets MoveTextureOffset(new Point(-horizontal, -vertical)); Point p = GetTextureOffset(); mode.SetActionResult("Changed texture offsets to " + p.X + ", " + p.Y + "."); - } else { + } + else + { //mxd. Apply classic offsets Sidedef.OffsetX = (Sidedef.OffsetX - horizontal); if (Texture != null) Sidedef.OffsetX %= Texture.Width; @@ -1260,7 +1290,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public virtual void OnChangeTextureScale(float incrementX, float incrementY) { + public virtual void OnChangeTextureScale(float incrementX, float incrementY) + { if(!General.Map.UDMF) return; if((General.Map.UndoRedo.NextUndo == null) || (General.Map.UndoRedo.NextUndo.TicketID != undoticket)) @@ -1269,7 +1300,8 @@ namespace CodeImp.DoomBuilder.BuilderModes string keyX; string keyY; - switch(GeometryType) { + switch(GeometryType) + { case VisualGeometryType.WALL_UPPER: keyX = "scalex_top"; keyY = "scaley_top"; @@ -1295,7 +1327,8 @@ namespace CodeImp.DoomBuilder.BuilderModes Sidedef.Fields.BeforeFieldsChange(); - if(incrementX != 0) { + if(incrementX != 0) + { if(scaleX + incrementX == 0) scaleX *= -1; else @@ -1303,7 +1336,8 @@ namespace CodeImp.DoomBuilder.BuilderModes UDMFTools.SetFloat(Sidedef.Fields, keyX, scaleX, 1.0f); } - if(incrementY != 0) { + if(incrementY != 0) + { if(scaleY + incrementY == 0) scaleY *= -1; else diff --git a/Source/Plugins/BuilderModes/VisualModes/BaseVisualMode.cs b/Source/Plugins/BuilderModes/VisualModes/BaseVisualMode.cs index e5fe266e..b35c9caa 100644 --- a/Source/Plugins/BuilderModes/VisualModes/BaseVisualMode.cs +++ b/Source/Plugins/BuilderModes/VisualModes/BaseVisualMode.cs @@ -531,7 +531,7 @@ namespace CodeImp.DoomBuilder.BuilderModes coords[i] = visualThings[i].Thing.Position; //move things... - Vector3D[] translatedCoords = translateCoordinates(coords, direction, absolutePosition); + Vector3D[] translatedCoords = TranslateCoordinates(coords, direction, absolutePosition); for (int i = 0; i < visualThings.Count; i++) { BaseVisualThing t = visualThings[i] as BaseVisualThing; @@ -542,7 +542,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private static Vector3D[] translateCoordinates(Vector3D[] coordinates, Vector2D direction, bool absolutePosition) + private static Vector3D[] TranslateCoordinates(Vector3D[] coordinates, Vector2D direction, bool absolutePosition) { if (coordinates.Length == 0) return null; @@ -552,7 +552,8 @@ namespace CodeImp.DoomBuilder.BuilderModes Vector3D[] translatedCoords = new Vector3D[coordinates.Length]; //move things... - if (!absolutePosition) { //...relatively (that's easy) + if (!absolutePosition) //...relatively (that's easy) + { int camAngle = (int)Math.Round(Angle2D.RadToDeg(General.Map.VisualCamera.AngleXY)); int sector = General.ClampAngle(camAngle - 45) / 90; direction = direction.GetRotated(sector * Angle2D.PIHALF); @@ -564,7 +565,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //...to specified location preserving relative positioning (that's harder) - if (coordinates.Length == 1) {//just move it there + if (coordinates.Length == 1) //just move it there + { translatedCoords[0] = new Vector3D(direction.x, direction.y, coordinates[0].z); return translatedCoords; } @@ -576,7 +578,8 @@ namespace CodeImp.DoomBuilder.BuilderModes float maxY = minY; //get bounding coordinates for selected things - for (int i = 1; i < coordinates.Length; i++) { + for (int i = 1; i < coordinates.Length; i++) + { if (coordinates[i].x < minX) minX = coordinates[i].x; else if (coordinates[i].x > maxX) @@ -598,26 +601,31 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - internal void SelectSideParts(Sidedef side, bool toggleTop, bool toggleMid, bool toggleBottom, bool select, bool withSameTexture, bool withSameHeight) { + internal void SelectSideParts(Sidedef side, bool toggleTop, bool toggleMid, bool toggleBottom, bool select, bool withSameTexture, bool withSameHeight) + { BaseVisualSector vs = GetVisualSector(side.Sector) as BaseVisualSector; if(toggleTop && vs.Sides[side].upper != null && - ((select && !vs.Sides[side].upper.Selected) || (!select && vs.Sides[side].upper.Selected))) { + ((select && !vs.Sides[side].upper.Selected) || (!select && vs.Sides[side].upper.Selected))) + { vs.Sides[side].upper.SelectNeighbours(select, withSameTexture, withSameHeight); } if(toggleMid && vs.Sides[side].middlesingle != null && - ((select && !vs.Sides[side].middlesingle.Selected) || (!select && vs.Sides[side].middlesingle.Selected))) { + ((select && !vs.Sides[side].middlesingle.Selected) || (!select && vs.Sides[side].middlesingle.Selected))) + { vs.Sides[side].middlesingle.SelectNeighbours(select, withSameTexture, withSameHeight); } if(toggleMid && vs.Sides[side].middledouble != null && - ((select && !vs.Sides[side].middledouble.Selected) || (!select && vs.Sides[side].middledouble.Selected))) { + ((select && !vs.Sides[side].middledouble.Selected) || (!select && vs.Sides[side].middledouble.Selected))) + { vs.Sides[side].middledouble.SelectNeighbours(select, withSameTexture, withSameHeight); } if(toggleBottom && vs.Sides[side].lower != null && - ((select && !vs.Sides[side].lower.Selected) || (!select && vs.Sides[side].lower.Selected))) { + ((select && !vs.Sides[side].lower.Selected) || (!select && vs.Sides[side].lower.Selected))) + { vs.Sides[side].lower.SelectNeighbours(select, withSameTexture, withSameHeight); } } @@ -722,13 +730,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - internal VertexData GetVertexData(Vertex v) { + internal VertexData GetVertexData(Vertex v) + { if(!vertexdata.ContainsKey(v)) vertexdata[v] = new VertexData(this, v); return vertexdata[v]; } - internal BaseVisualVertex GetVisualVertex(Vertex v, bool floor) { + internal BaseVisualVertex GetVisualVertex(Vertex v, bool floor) + { if(!vertices.ContainsKey(v)) vertices.Add(v, new VisualVertexPair(new BaseVisualVertex(this, v, false), new BaseVisualVertex(this, v, true))); @@ -736,7 +746,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - internal void UpdateVertexHandle(Vertex v) { + internal void UpdateVertexHandle(Vertex v) + { if(!vertices.ContainsKey(v)) vertices.Add(v, new VisualVertexPair(new BaseVisualVertex(this, v, false), new BaseVisualVertex(this, v, true))); else @@ -750,17 +761,21 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd Sector[] sectorsWithEffects = null; - if (!gzdoomRenderingEffects) { + if (!gzdoomRenderingEffects) + { //store all sectors with effects - if(sectordata != null && sectordata.Count > 0) { + if(sectordata != null && sectordata.Count > 0) + { sectorsWithEffects = new Sector[sectordata.Count]; sectordata.Keys.CopyTo(sectorsWithEffects, 0); } //remove all vertex handles from selection - if(vertices != null && vertices.Count > 0) { - foreach(IVisualEventReceiver i in selectedobjects){ + if(vertices != null && vertices.Count > 0) + { + foreach(IVisualEventReceiver i in selectedobjects) + { if(i is BaseVisualVertex) RemoveSelectedObject(i); } } @@ -771,17 +786,21 @@ namespace CodeImp.DoomBuilder.BuilderModes thingdata = new Dictionary(General.Map.Map.Things.Count); //mxd. rebuild all sectors with effects - if(sectorsWithEffects != null) { - for(int i = 0; i < sectorsWithEffects.Length; i++) { + if(sectorsWithEffects != null) + { + for(int i = 0; i < sectorsWithEffects.Length; i++) + { // The visual sector associated is now outdated - if(VisualSectorExists(sectorsWithEffects[i])) { + if(VisualSectorExists(sectorsWithEffects[i])) + { BaseVisualSector vs = GetVisualSector(sectorsWithEffects[i]) as BaseVisualSector; vs.UpdateSectorGeometry(true); } } } - if(General.Map.UDMF) { + if(General.Map.UDMF) + { vertexdata = new Dictionary(General.Map.Map.Vertices.Count); //mxd vertices.Clear(); } @@ -809,13 +828,16 @@ namespace CodeImp.DoomBuilder.BuilderModes List slopeceilingthings = new List(3); List slopefloorthings = new List(3); - foreach(Sidedef sd in s.Sidedefs) { + foreach(Sidedef sd in s.Sidedefs) + { Vertex v = sd.IsFront ? sd.Line.End : sd.Line.Start; // Check if a thing is at this vertex VisualBlockEntry b = blockmap.GetBlock(blockmap.GetBlockCoordinates(v.Position)); - foreach(Thing t in b.Things) { - if((Vector2D)t.Position == v.Position) { + foreach(Thing t in b.Things) + { + if((Vector2D)t.Position == v.Position) + { if(t.Type == 1504) slopefloorthings.Add(t); else if(t.Type == 1505) @@ -825,13 +847,15 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Slope any floor vertices? - if(slopefloorthings.Count > 0) { + if(slopefloorthings.Count > 0) + { SectorData sd = GetSectorData(s); sd.AddEffectThingVertexSlope(slopefloorthings, true); } // Slope any ceiling vertices? - if(slopeceilingthings.Count > 0) { + if(slopeceilingthings.Count > 0) + { SectorData sd = GetSectorData(s); sd.AddEffectThingVertexSlope(slopeceilingthings, false); } @@ -867,7 +891,8 @@ namespace CodeImp.DoomBuilder.BuilderModes bool ceilingCopyToBack = false; bool ceilingCopyToFront = false; - if(l.Args[4] > 0 && l.Args[4] != 3 && l.Args[4] != 12) { + if(l.Args[4] > 0 && l.Args[4] != 3 && l.Args[4] != 12) + { floorCopyToBack = (l.Args[4] & 1) == 1; floorCopyToFront = (l.Args[4] & 2) == 2; ceilingCopyToBack = (l.Args[4] & 4) == 4; @@ -875,16 +900,20 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Copy slope to front sector - if(l.Front != null) { - if( (l.Args[0] > 0 || l.Args[1] > 0) || (l.Back != null && (floorCopyToFront || ceilingCopyToFront)) ) { + if(l.Front != null) + { + if( (l.Args[0] > 0 || l.Args[1] > 0) || (l.Back != null && (floorCopyToFront || ceilingCopyToFront)) ) + { SectorData sd = GetSectorData(l.Front.Sector); sd.AddEffectPlaneClopySlope(l, true); } } // Copy slope to back sector - if(l.Back != null) { - if( (l.Args[2] > 0 || l.Args[3] > 0) || (l.Front != null && (floorCopyToBack || ceilingCopyToBack)) ) { + if(l.Back != null) + { + if( (l.Args[2] > 0 || l.Args[3] > 0) || (l.Front != null && (floorCopyToBack || ceilingCopyToBack)) ) + { SectorData sd = GetSectorData(l.Back.Sector); sd.AddEffectPlaneClopySlope(l, false); } @@ -1161,7 +1190,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - if(General.Map.UDMF && General.Settings.GZShowVisualVertices && vertices.Count > 0) { + if(General.Map.UDMF && General.Settings.GZShowVisualVertices && vertices.Count > 0) + { List verts = new List(); foreach(KeyValuePair pair in vertices) @@ -1341,7 +1371,8 @@ namespace CodeImp.DoomBuilder.BuilderModes RebuildElementData(); //mxd. As well as geometry... - foreach(KeyValuePair group in visiblesectors){ + foreach(KeyValuePair group in visiblesectors) + { if (group.Value is BaseVisualSector) (group.Value as BaseVisualSector).Rebuild(); } @@ -1362,9 +1393,9 @@ namespace CodeImp.DoomBuilder.BuilderModes RebuildElementData(); //mxd. As well as geometry... - foreach (KeyValuePair group in visiblesectors) { - if (group.Value is BaseVisualSector) - (group.Value as BaseVisualSector).Rebuild(); + foreach (KeyValuePair group in visiblesectors) + { + if (group.Value is BaseVisualSector) (group.Value as BaseVisualSector).Rebuild(); } RebuildSelectedObjectsList(); @@ -1396,12 +1427,16 @@ namespace CodeImp.DoomBuilder.BuilderModes { //update visual sectors, which are affected by certain things List things = GetSelectedThings(); - foreach(Thing t in things) { - if(thingdata.ContainsKey(t)) { + foreach(Thing t in things) + { + if(thingdata.ContainsKey(t)) + { // Update what must be updated ThingData td = GetThingData(t); - foreach(KeyValuePair s in td.UpdateAlso) { - if(VisualSectorExists(s.Key)) { + foreach(KeyValuePair s in td.UpdateAlso) + { + if(VisualSectorExists(s.Key)) + { BaseVisualSector vs = GetVisualSector(s.Key) as BaseVisualSector; vs.UpdateSectorGeometry(s.Value); } @@ -1440,10 +1475,12 @@ namespace CodeImp.DoomBuilder.BuilderModes { Dictionary donesides = new Dictionary(selectedobjects.Count); List objs = GetSelectedObjects(false, true, false, false); - foreach(IVisualEventReceiver i in objs) { + foreach(IVisualEventReceiver i in objs) + { BaseVisualGeometrySidedef vs = i as BaseVisualGeometrySidedef; //mxd - if(i is BaseVisualGeometrySidedef) { + if(i is BaseVisualGeometrySidedef) + { if(!donesides.ContainsKey(vs.Sidedef)) { //mxd. added scaling by texture scale @@ -1653,15 +1690,19 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. This returns all selected vertices, no doubles - public List GetSelectedVertices() { + public List GetSelectedVertices() + { Dictionary added = new Dictionary(); List verts = new List(); - foreach(IVisualEventReceiver i in selectedobjects) { - if(i is BaseVisualVertex) { + foreach(IVisualEventReceiver i in selectedobjects) + { + if(i is BaseVisualVertex) + { Vertex v = (i as BaseVisualVertex).Vertex; - if(!added.ContainsKey(v)) { + if(!added.ContainsKey(v)) + { verts.Add(v); added.Add(v, 0); } @@ -1669,7 +1710,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Add highlight? - if((selectedobjects.Count == 0) && (target.picked is BaseVisualVertex)) { + if((selectedobjects.Count == 0) && (target.picked is BaseVisualVertex)) + { Vertex v = (target.picked as BaseVisualVertex).Vertex; if(!added.ContainsKey(v)) verts.Add(v); @@ -1704,14 +1746,16 @@ namespace CodeImp.DoomBuilder.BuilderModes private static Thing CreateThing(Vector2D pos) { if (pos.x < General.Map.Config.LeftBoundary || pos.x > General.Map.Config.RightBoundary || - pos.y > General.Map.Config.TopBoundary || pos.y < General.Map.Config.BottomBoundary) { + pos.y > General.Map.Config.TopBoundary || pos.y < General.Map.Config.BottomBoundary) + { General.Interface.DisplayStatus(StatusType.Warning, "Failed to insert thing: outside of map boundaries."); return null; } // Create thing Thing t = General.Map.Map.CreateThing(); - if (t != null) { + if (t != null) + { General.Settings.ApplyDefaultThingSettings(t); t.Move(pos); t.UpdateConfiguration(); @@ -1721,10 +1765,13 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.ThingsFilter.Update(); // Snap to grid enabled? - if (General.Interface.SnapToGrid) { + if (General.Interface.SnapToGrid) + { // Snap to grid t.SnapToGrid(); - } else { + } + else + { // Snap to map format accuracy t.SnapToAccuracy(); } @@ -1772,10 +1819,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - if(General.Map.UDMF) { - foreach(KeyValuePair pair in vertices) { - pair.Value.Deselect(); - } + if(General.Map.UDMF) + { + foreach(KeyValuePair pair in vertices) pair.Value.Deselect(); } //mxd @@ -1798,7 +1844,8 @@ namespace CodeImp.DoomBuilder.BuilderModes target.OnSelectEnd(); //mxd - if((General.Interface.ShiftState || General.Interface.CtrlState) && selectedobjects.Count > 0) { + if((General.Interface.ShiftState || General.Interface.CtrlState) && selectedobjects.Count > 0) + { IVisualEventReceiver[] selection = new IVisualEventReceiver[selectedobjects.Count]; selectedobjects.CopyTo(selection); @@ -1865,55 +1912,74 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("raisesectortonearest")] - public void RaiseSectorToNearest() { + public void RaiseSectorToNearest() + { Dictionary floors = new Dictionary(); Dictionary ceilings = new Dictionary(); List things = new List(); bool withinSelection = General.Interface.CtrlState; //get selection - if(selectedobjects.Count == 0) { + if(selectedobjects.Count == 0) + { IVisualEventReceiver i = (target.picked as IVisualEventReceiver); - if(i is VisualFloor) { + if(i is VisualFloor) + { VisualFloor vf = i as VisualFloor; floors.Add(vf.Level.sector, vf); - } else if(i is VisualCeiling) { + } + else if(i is VisualCeiling) + { VisualCeiling vc = i as VisualCeiling; ceilings.Add(vc.Level.sector, vc); - } else if(i is BaseVisualThing) { + } + else if(i is BaseVisualThing) + { things.Add(i as BaseVisualThing); } - } else { - foreach(IVisualEventReceiver i in selectedobjects) { - if(i is VisualFloor) { + } + else + { + foreach(IVisualEventReceiver i in selectedobjects) + { + if(i is VisualFloor) + { VisualFloor vf = i as VisualFloor; floors.Add(vf.Level.sector, vf); - } else if(i is VisualCeiling) { + } + else if(i is VisualCeiling) + { VisualCeiling vc = i as VisualCeiling; ceilings.Add(vc.Level.sector, vc); - } else if(i is BaseVisualThing) { + } + else if(i is BaseVisualThing) + { things.Add(i as BaseVisualThing); } } } //check what we have - if(floors.Count + ceilings.Count == 0 && (things.Count == 0 || !General.Map.FormatInterface.HasThingHeight)) { + if(floors.Count + ceilings.Count == 0 && (things.Count == 0 || !General.Map.FormatInterface.HasThingHeight)) + { General.Interface.DisplayStatus(StatusType.Warning, "No suitable objects found!"); return; } - if(withinSelection) { + if(withinSelection) + { string s = string.Empty; if(floors.Count == 1) s = "floors"; - if(ceilings.Count == 1) { + if(ceilings.Count == 1) + { if(!string.IsNullOrEmpty(s)) s += " and "; s += "ceilings"; } - if(!string.IsNullOrEmpty(s)){ + if(!string.IsNullOrEmpty(s)) + { General.Interface.DisplayStatus(StatusType.Warning, "Can't do: at least 2 selected " + s + " are required!"); return; } @@ -1925,18 +1991,24 @@ namespace CodeImp.DoomBuilder.BuilderModes int targetCeilingHeight = int.MaxValue; //get highest ceiling height from selection - foreach(KeyValuePair group in ceilings) { + foreach(KeyValuePair group in ceilings) + { if(group.Key.CeilHeight > maxSelectedHeight) maxSelectedHeight = group.Key.CeilHeight; } - if(withinSelection) { + if(withinSelection) + { //we are raising, so we don't need to check anything targetCeilingHeight = maxSelectedHeight; - } else { + } + else + { //get next higher ceiling from surrounding unselected sectors - foreach(KeyValuePair group in ceilings) { - foreach(Sidedef side in group.Key.Sidedefs) { + foreach(KeyValuePair group in ceilings) + { + foreach(Sidedef side in group.Key.Sidedefs) + { if(side.Other == null || ceilings.ContainsKey(side.Other.Sector) || floors.ContainsKey(side.Other.Sector)) continue; if(side.Other.Sector.CeilHeight < targetCeilingHeight && side.Other.Sector.CeilHeight > maxSelectedHeight) @@ -1950,7 +2022,8 @@ namespace CodeImp.DoomBuilder.BuilderModes int targetFloorHeight = int.MaxValue; //get maximum floor and minimum ceiling heights from selection - foreach(KeyValuePair group in floors) { + foreach(KeyValuePair group in floors) + { if(group.Key.FloorHeight > maxSelectedHeight) maxSelectedHeight = group.Key.FloorHeight; @@ -1958,17 +2031,23 @@ namespace CodeImp.DoomBuilder.BuilderModes minSelectedCeilingHeight = group.Key.CeilHeight; } - if(withinSelection) { + if(withinSelection) + { //check heights - if(minSelectedCeilingHeight < maxSelectedHeight) { + if(minSelectedCeilingHeight < maxSelectedHeight) + { General.Interface.DisplayStatus(StatusType.Warning, "Can't do: lowest ceiling is lower than highest floor!"); return; } targetFloorHeight = maxSelectedHeight; - } else { + } + else + { //get next higher floor from surrounding unselected sectors - foreach(KeyValuePair group in floors) { - foreach(Sidedef side in group.Key.Sidedefs) { + foreach(KeyValuePair group in floors) + { + foreach(Sidedef side in group.Key.Sidedefs) + { if(side.Other == null || ceilings.ContainsKey(side.Other.Sector) || floors.ContainsKey(side.Other.Sector)) continue; if(side.Other.Sector.FloorHeight > maxSelectedHeight && side.Other.Sector.FloorHeight < targetFloorHeight && side.Other.Sector.FloorHeight <= minSelectedCeilingHeight) @@ -1980,23 +2059,29 @@ namespace CodeImp.DoomBuilder.BuilderModes //CHECK VALUES string alignFailDescription = string.Empty; - if (floors.Count > 0 && targetFloorHeight == int.MaxValue) { + if (floors.Count > 0 && targetFloorHeight == int.MaxValue) + { //raise to lowest ceiling? - if(!withinSelection && minSelectedCeilingHeight > maxSelectedHeight) { + if(!withinSelection && minSelectedCeilingHeight > maxSelectedHeight) + { targetFloorHeight = minSelectedCeilingHeight; - } else { + } + else + { alignFailDescription = floors.Count > 1 ? "floors" : "floor"; } } - if(ceilings.Count > 0 && targetCeilingHeight == int.MaxValue) { + if(ceilings.Count > 0 && targetCeilingHeight == int.MaxValue) + { if(!string.IsNullOrEmpty(alignFailDescription)) alignFailDescription += " and "; alignFailDescription += ceilings.Count > 1 ? "ceilings" : "ceiling"; } - if(!string.IsNullOrEmpty(alignFailDescription)) { + if(!string.IsNullOrEmpty(alignFailDescription)) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to align selected " + alignFailDescription + "!"); return; } @@ -2005,24 +2090,30 @@ namespace CodeImp.DoomBuilder.BuilderModes PreAction(UndoGroup.SectorHeightChange); //change floors heights - if(floors.Count > 0) { - foreach(KeyValuePair group in floors) { + if(floors.Count > 0) + { + foreach(KeyValuePair group in floors) + { if(targetFloorHeight != group.Key.FloorHeight) group.Value.OnChangeTargetHeight(targetFloorHeight - group.Key.FloorHeight); } } //change ceilings heights - if(ceilings.Count > 0) { - foreach(KeyValuePair group in ceilings) { + if(ceilings.Count > 0) + { + foreach(KeyValuePair group in ceilings) + { if(targetCeilingHeight != group.Key.CeilHeight) group.Value.OnChangeTargetHeight(targetCeilingHeight - group.Key.CeilHeight); } } //and things. Just align them to ceiling - if(General.Map.FormatInterface.HasThingHeight) { - foreach(BaseVisualThing vt in things) { + if(General.Map.FormatInterface.HasThingHeight) + { + foreach(BaseVisualThing vt in things) + { if(vt.Thing.Sector == null) continue; ThingTypeInfo ti = General.Map.Data.GetThingInfo(vt.Thing.Type); int zvalue = (int)(vt.Thing.Sector.FloorHeight + vt.Thing.Position.z); @@ -2037,55 +2128,74 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("lowersectortonearest")] - public void LowerSectorToNearest() { + public void LowerSectorToNearest() + { Dictionary floors = new Dictionary(); Dictionary ceilings = new Dictionary(); List things = new List(); bool withinSelection = General.Interface.CtrlState; //get selection - if(selectedobjects.Count == 0) { + if(selectedobjects.Count == 0) + { IVisualEventReceiver i = (target.picked as IVisualEventReceiver); - if(i is VisualFloor) { + if(i is VisualFloor) + { VisualFloor vf = i as VisualFloor; floors.Add(vf.Level.sector, vf); - } else if(i is VisualCeiling) { + } + else if(i is VisualCeiling) + { VisualCeiling vc = i as VisualCeiling; ceilings.Add(vc.Level.sector, vc); - } else if(i is BaseVisualThing) { + } + else if(i is BaseVisualThing) + { things.Add(i as BaseVisualThing); } - }else{ - foreach(IVisualEventReceiver i in selectedobjects) { - if(i is VisualFloor) { + } + else + { + foreach(IVisualEventReceiver i in selectedobjects) + { + if(i is VisualFloor) + { VisualFloor vf = i as VisualFloor; floors.Add(vf.Level.sector, vf); - } else if(i is VisualCeiling) { + } + else if(i is VisualCeiling) + { VisualCeiling vc = i as VisualCeiling; ceilings.Add(vc.Level.sector, vc); - } else if(i is BaseVisualThing) { + } + else if(i is BaseVisualThing) + { things.Add(i as BaseVisualThing); } } } //check what we have - if(floors.Count + ceilings.Count == 0 && (things.Count == 0 || !General.Map.FormatInterface.HasThingHeight)) { + if(floors.Count + ceilings.Count == 0 && (things.Count == 0 || !General.Map.FormatInterface.HasThingHeight)) + { General.Interface.DisplayStatus(StatusType.Warning, "No suitable objects found!"); return; } - if(withinSelection) { + if(withinSelection) + { string s = string.Empty; if(floors.Count == 1) s = "floors"; - if(ceilings.Count == 1) { + if(ceilings.Count == 1) + { if(!string.IsNullOrEmpty(s)) s += " and "; s += "ceilings"; } - if(!string.IsNullOrEmpty(s)) { + if(!string.IsNullOrEmpty(s)) + { General.Interface.DisplayStatus(StatusType.Warning, "Can't do: at least 2 selected " + s + " are required!"); return; } @@ -2096,18 +2206,24 @@ namespace CodeImp.DoomBuilder.BuilderModes int targetFloorHeight = int.MinValue; //get minimum floor height from selection - foreach(KeyValuePair group in floors) { + foreach(KeyValuePair group in floors) + { if(group.Key.FloorHeight < minSelectedHeight) minSelectedHeight = group.Key.FloorHeight; } - if(withinSelection) { + if(withinSelection) + { //we are lowering, so we don't need to check anything targetFloorHeight = minSelectedHeight; - } else { + } + else + { //get next floor lower height from surrounding unselected sectors - foreach(KeyValuePair group in floors) { - foreach(Sidedef side in group.Key.Sidedefs) { + foreach(KeyValuePair group in floors) + { + foreach(Sidedef side in group.Key.Sidedefs) + { if(side.Other == null || ceilings.ContainsKey(side.Other.Sector) || floors.ContainsKey(side.Other.Sector)) continue; if(side.Other.Sector.FloorHeight > targetFloorHeight && side.Other.Sector.FloorHeight < minSelectedHeight) @@ -2122,7 +2238,8 @@ namespace CodeImp.DoomBuilder.BuilderModes int targetCeilingHeight = int.MinValue; //get minimum ceiling and maximum floor heights from selection - foreach(KeyValuePair group in ceilings) { + foreach(KeyValuePair group in ceilings) + { if(group.Key.CeilHeight < minSelectedHeight) minSelectedHeight = group.Key.CeilHeight; @@ -2130,16 +2247,22 @@ namespace CodeImp.DoomBuilder.BuilderModes maxSelectedFloorHeight = group.Key.FloorHeight; } - if(withinSelection) { - if(minSelectedHeight < maxSelectedFloorHeight) { + if(withinSelection) + { + if(minSelectedHeight < maxSelectedFloorHeight) + { General.Interface.DisplayStatus(StatusType.Warning, "Can't do: lowest ceiling is lower than highest floor!"); return; } targetCeilingHeight = minSelectedHeight; - } else { + } + else + { //get next lower ceiling height from surrounding unselected sectors - foreach(KeyValuePair group in ceilings) { - foreach(Sidedef side in group.Key.Sidedefs) { + foreach(KeyValuePair group in ceilings) + { + foreach(Sidedef side in group.Key.Sidedefs) + { if(side.Other == null || ceilings.ContainsKey(side.Other.Sector) || floors.ContainsKey(side.Other.Sector)) continue; if(side.Other.Sector.CeilHeight > targetCeilingHeight && side.Other.Sector.CeilHeight < minSelectedHeight && side.Other.Sector.CeilHeight >= maxSelectedFloorHeight) @@ -2154,17 +2277,22 @@ namespace CodeImp.DoomBuilder.BuilderModes if(floors.Count > 0 && targetFloorHeight == int.MinValue) alignFailDescription = floors.Count > 1 ? "floors" : "floor"; - if(ceilings.Count > 0 && targetCeilingHeight == int.MinValue) { + if(ceilings.Count > 0 && targetCeilingHeight == int.MinValue) + { //drop to highest floor? - if(!withinSelection && maxSelectedFloorHeight < minSelectedHeight) { + if(!withinSelection && maxSelectedFloorHeight < minSelectedHeight) + { targetCeilingHeight = maxSelectedFloorHeight; - } else { + } + else + { if (!string.IsNullOrEmpty(alignFailDescription)) alignFailDescription += " and "; alignFailDescription += ceilings.Count > 1 ? "ceilings" : "ceiling"; } } - if(!string.IsNullOrEmpty(alignFailDescription)) { + if(!string.IsNullOrEmpty(alignFailDescription)) + { General.Interface.DisplayStatus(StatusType.Warning, "Unable to align selected " + alignFailDescription + "!"); return; } @@ -2173,24 +2301,30 @@ namespace CodeImp.DoomBuilder.BuilderModes PreAction(UndoGroup.SectorHeightChange); //change floor height - if(floors.Count > 0) { - foreach(KeyValuePair group in floors) { + if(floors.Count > 0) + { + foreach(KeyValuePair group in floors) + { if(targetFloorHeight != group.Key.FloorHeight) group.Value.OnChangeTargetHeight(targetFloorHeight - group.Key.FloorHeight); } } //change ceiling height - if(ceilings.Count > 0) { - foreach(KeyValuePair group in ceilings) { + if(ceilings.Count > 0) + { + foreach(KeyValuePair group in ceilings) + { if(targetCeilingHeight != group.Key.CeilHeight) group.Value.OnChangeTargetHeight(targetCeilingHeight - group.Key.CeilHeight); } } //process things. Just drop them to ground - if(General.Map.FormatInterface.HasThingHeight){ - foreach(BaseVisualThing vt in things) { + if(General.Map.FormatInterface.HasThingHeight) + { + foreach(BaseVisualThing vt in things) + { if(vt.Thing.Sector == null) continue; if(vt.Thing.Position.z != 0) @@ -2203,59 +2337,76 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("matchbrightness")] - public void MatchBrightness() { + public void MatchBrightness() + { //check input - if (!General.Map.UDMF) { + if (!General.Map.UDMF) + { General.Interface.DisplayStatus(StatusType.Warning, "'Match Brightness' action works only in UDMF map format!"); return; } - if (selectedobjects.Count == 0) { + if (selectedobjects.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "'Match Brightness' action requires a selection!"); return; } IVisualEventReceiver highlighted = (target.picked as IVisualEventReceiver); - if(highlighted is BaseVisualThing) { + if(highlighted is BaseVisualThing) + { General.Interface.DisplayStatus(StatusType.Warning, "Highlight a surface, to which you want to match the brightness."); return; } //get target brightness int targetBrightness; - if(highlighted is VisualFloor) { + if(highlighted is VisualFloor) + { VisualFloor v = highlighted as VisualFloor; targetBrightness = v.Level.sector.Fields.GetValue("lightfloor", 0); - if (!v.Level.sector.Fields.GetValue("lightfloorabsolute", false)) { + if (!v.Level.sector.Fields.GetValue("lightfloorabsolute", false)) + { targetBrightness += v.Level.sector.Brightness; } - } else if(highlighted is VisualCeiling) { + } + else if(highlighted is VisualCeiling) + { VisualCeiling v = highlighted as VisualCeiling; targetBrightness = v.Level.sector.Fields.GetValue("lightceiling", 0); - if(!v.Level.sector.Fields.GetValue("lightceilingabsolute", false)) { + if(!v.Level.sector.Fields.GetValue("lightceilingabsolute", false)) + { targetBrightness += v.Level.sector.Brightness; } - } else if(highlighted is VisualUpper || highlighted is VisualMiddleSingle || highlighted is VisualMiddleDouble || highlighted is VisualLower) { + } + else if(highlighted is VisualUpper || highlighted is VisualMiddleSingle || highlighted is VisualMiddleDouble || highlighted is VisualLower) + { BaseVisualGeometrySidedef v = highlighted as BaseVisualGeometrySidedef; targetBrightness = v.Sidedef.Fields.GetValue("light", 0); - if(!v.Sidedef.Fields.GetValue("lightabsolute", false)) { + if(!v.Sidedef.Fields.GetValue("lightabsolute", false)) + { targetBrightness += v.Sidedef.Sector.Brightness; } - } else if(highlighted is VisualMiddle3D) { + } + else if(highlighted is VisualMiddle3D) + { VisualMiddle3D v = highlighted as VisualMiddle3D; Sidedef sd = v.GetControlLinedef().Front; - - if (sd == null) { + if (sd == null) + { General.Interface.DisplayStatus(StatusType.Warning, "Highlight a surface, to which you want to match the brightness."); return; } targetBrightness = sd.Fields.GetValue("light", 0); - if(!sd.Fields.GetValue("lightabsolute", false)) { + if(!sd.Fields.GetValue("lightabsolute", false)) + { targetBrightness += sd.Sector.Brightness; } - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Highlight a surface, to which you want to match the brightness."); return; } @@ -2265,43 +2416,56 @@ namespace CodeImp.DoomBuilder.BuilderModes targetBrightness = General.Clamp(targetBrightness, 0, 255); //apply new brightness - foreach (IVisualEventReceiver obj in selectedobjects) { + foreach (IVisualEventReceiver obj in selectedobjects) + { if(obj == highlighted) continue; - if(obj is VisualFloor) { + if(obj is VisualFloor) + { VisualFloor v = obj as VisualFloor; v.Level.sector.Fields.BeforeFieldsChange(); v.Sector.Changed = true; - if (v.Level.sector.Fields.GetValue("lightfloorabsolute", false)) { + if (v.Level.sector.Fields.GetValue("lightfloorabsolute", false)) + { v.Level.sector.Fields["lightfloor"] = new UniValue(UniversalType.Integer, targetBrightness); - } else { + } + else + { v.Level.sector.Fields["lightfloor"] = new UniValue(UniversalType.Integer, targetBrightness - v.Level.sector.Brightness); } v.Sector.UpdateSectorGeometry(false); - - } else if(obj is VisualCeiling) { + } + else if(obj is VisualCeiling) + { VisualCeiling v = obj as VisualCeiling; v.Level.sector.Fields.BeforeFieldsChange(); v.Sector.Changed = true; - if(v.Level.sector.Fields.GetValue("lightceilingabsolute", false)) { + if(v.Level.sector.Fields.GetValue("lightceilingabsolute", false)) + { v.Level.sector.Fields["lightceiling"] = new UniValue(UniversalType.Integer, targetBrightness); - } else { + } + else + { v.Level.sector.Fields["lightceiling"] = new UniValue(UniversalType.Integer, targetBrightness - v.Level.sector.Brightness); } v.Sector.UpdateSectorGeometry(false); - - } else if(obj is VisualUpper || obj is VisualMiddleSingle || obj is VisualMiddleDouble || obj is VisualLower) { + } + else if(obj is VisualUpper || obj is VisualMiddleSingle || obj is VisualMiddleDouble || obj is VisualLower) + { BaseVisualGeometrySidedef v = obj as BaseVisualGeometrySidedef; v.Sidedef.Fields.BeforeFieldsChange(); v.Sector.Changed = true; - if (v.Sidedef.Fields.GetValue("lightabsolute", false)) { + if (v.Sidedef.Fields.GetValue("lightabsolute", false)) + { v.Sidedef.Fields["light"] = new UniValue(UniversalType.Integer, targetBrightness); - } else { + } + else + { v.Sidedef.Fields["light"] = new UniValue(UniversalType.Integer, targetBrightness - v.Sidedef.Sector.Brightness); } } @@ -2411,7 +2575,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("scaletextureupx")] - public void ScaleTextureUpX() { + public void ScaleTextureUpX() + { PreAction(UndoGroup.TextureScaleChange); List objs = GetSelectedObjects(true, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnChangeTextureScale(-0.1f, 0); @@ -2420,7 +2585,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("scaletexturedownx")] - public void ScaleTextureDownX() { + public void ScaleTextureDownX() + { PreAction(UndoGroup.TextureScaleChange); List objs = GetSelectedObjects(true, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnChangeTextureScale(0.1f, 0); @@ -2429,7 +2595,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("scaletextureupy")] - public void ScaleTextureUpY() { + public void ScaleTextureUpY() + { PreAction(UndoGroup.TextureScaleChange); List objs = GetSelectedObjects(true, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnChangeTextureScale(0, 0.1f); @@ -2438,7 +2605,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("scaletexturedowny")] - public void ScaleTextureDownY() { + public void ScaleTextureDownY() + { PreAction(UndoGroup.TextureScaleChange); List objs = GetSelectedObjects(true, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnChangeTextureScale(0, -0.1f); @@ -2476,7 +2644,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualautoalign")] - public void TextureAutoAlign() { + public void TextureAutoAlign() + { PreAction(UndoGroup.None); renderer.SetCrosshairBusy(true); General.Interface.RedrawDisplay(); @@ -2512,12 +2681,13 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualautoaligntoselection")] - public void TextureAlignToSelected() { + public void TextureAlignToSelected() + { PreAction(UndoGroup.None); renderer.SetCrosshairBusy(true); General.Interface.RedrawDisplay(); - autoAlignTexturesToSelected(true, true); + AutoAlignTexturesToSelected(true, true); UpdateChangedObjects(); renderer.SetCrosshairBusy(false); @@ -2526,12 +2696,13 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualautoaligntoselectionx")] - public void TextureAlignToSelectedX() { + public void TextureAlignToSelectedX() + { PreAction(UndoGroup.None); renderer.SetCrosshairBusy(true); General.Interface.RedrawDisplay(); - autoAlignTexturesToSelected(true, false); + AutoAlignTexturesToSelected(true, false); UpdateChangedObjects(); renderer.SetCrosshairBusy(false); @@ -2540,12 +2711,13 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualautoaligntoselectiony")] - public void TextureAlignToSelectedY() { + public void TextureAlignToSelectedY() + { PreAction(UndoGroup.None); renderer.SetCrosshairBusy(true); General.Interface.RedrawDisplay(); - autoAlignTexturesToSelected(false, true); + AutoAlignTexturesToSelected(false, true); UpdateChangedObjects(); renderer.SetCrosshairBusy(false); @@ -2553,7 +2725,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void autoAlignTexturesToSelected(bool alignX, bool alignY) { + private void AutoAlignTexturesToSelected(bool alignX, bool alignY) + { string rest; if(alignX && alignY) rest = "(X and Y)"; else if(alignX) rest = "(X)"; @@ -2569,7 +2742,8 @@ namespace CodeImp.DoomBuilder.BuilderModes List objs = GetSelectedObjects(false, true, false, false); //align - foreach(IVisualEventReceiver i in objs) { + foreach(IVisualEventReceiver i in objs) + { BaseVisualGeometrySidedef side = i as BaseVisualGeometrySidedef; // Make sure the texture is loaded (we need the texture size) @@ -2581,9 +2755,11 @@ namespace CodeImp.DoomBuilder.BuilderModes // Get the changed sidedefs List changes = General.Map.Map.GetMarkedSidedefs(true); - foreach(Sidedef sd in changes) { + foreach(Sidedef sd in changes) + { // Update the parts for this sidedef! - if(VisualSectorExists(sd.Sector)) { + if(VisualSectorExists(sd.Sector)) + { BaseVisualSector vs = (GetVisualSector(sd.Sector) as BaseVisualSector); VisualSidedefParts parts = vs.GetSidedefParts(sd); parts.SetupAllParts(); @@ -2594,7 +2770,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualfittextures")] - public void TextureFit() { + public void TextureFit() + { PreAction(UndoGroup.None); List objs = GetSelectedObjects(false, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnTextureFit(true, true); @@ -2603,7 +2780,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualfittexturesx")] - public void TextureFitX() { + public void TextureFitX() + { PreAction(UndoGroup.None); List objs = GetSelectedObjects(false, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnTextureFit(true, false); @@ -2612,7 +2790,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("visualfittexturesy")] - public void TextureFitY() { + public void TextureFitY() + { PreAction(UndoGroup.None); List objs = GetSelectedObjects(false, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnTextureFit(false, true); @@ -2661,7 +2840,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } [BeginAction("resettextureudmf")] - public void ResetLocalOffsets() { + public void ResetLocalOffsets() + { PreAction(UndoGroup.None); List objs = GetSelectedObjects(true, true, false, false); foreach(IVisualEventReceiver i in objs) i.OnResetLocalTextureOffset(); @@ -2716,7 +2896,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { Vector2D hitpos = GetHitPosition(); - if (!hitpos.IsFinite()) { + if (!hitpos.IsFinite()) + { General.Interface.DisplayStatus(StatusType.Warning, "Cannot insert thing here!"); return; } @@ -2728,7 +2909,8 @@ namespace CodeImp.DoomBuilder.BuilderModes Thing t = CreateThing(new Vector2D(hitpos.x, hitpos.y)); - if (t == null) { + if (t == null) + { General.Map.UndoRedo.WithdrawUndo(); return; } @@ -2758,12 +2940,14 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("copyselection", BaseAction = true)] - public void CopySelection() { + public void CopySelection() + { List objs = GetSelectedObjects(false, false, true, false); if (objs.Count == 0) return; copyBuffer.Clear(); - foreach (IVisualEventReceiver i in objs) { + foreach (IVisualEventReceiver i in objs) + { VisualThing vt = i as VisualThing; if (vt != null) copyBuffer.Add(new ThingCopyData(vt.Thing)); } @@ -2772,7 +2956,8 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("cutselection", BaseAction = true)] - public void CutSelection() { + public void CutSelection() + { CopySelection(); //Create undo @@ -2781,7 +2966,8 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Interface.DisplayStatus(StatusType.Info, "Cut " + rest); List objs = GetSelectedObjects(false, false, true, false); - foreach (IVisualEventReceiver i in objs) { + foreach (IVisualEventReceiver i in objs) + { BaseVisualThing thing = i as BaseVisualThing; thing.Thing.Fields.BeforeFieldsChange(); thing.Thing.Dispose(); @@ -2794,15 +2980,18 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. We'll just use currently selected objects [BeginAction("pasteselection", BaseAction = true)] - public void PasteSelection() { - if(copyBuffer.Count == 0){ + public void PasteSelection() + { + if(copyBuffer.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Nothing to paste, cut or copy some Things first!"); return; } Vector2D hitpos = GetHitPosition(); - if (!hitpos.IsFinite()) { + if (!hitpos.IsFinite()) + { General.Interface.DisplayStatus(StatusType.Warning, "Cannot paste here!"); return; } @@ -2819,12 +3008,14 @@ namespace CodeImp.DoomBuilder.BuilderModes for (int i = 0; i < copyBuffer.Count; i++ ) coords[i] = copyBuffer[i].Position; - Vector3D[] translatedCoords = translateCoordinates(coords, hitpos, true); + Vector3D[] translatedCoords = TranslateCoordinates(coords, hitpos, true); //create things from copyBuffer - for (int i = 0; i < copyBuffer.Count; i++) { + for (int i = 0; i < copyBuffer.Count; i++) + { Thing t = CreateThing(new Vector2D()); - if (t != null) { + if (t != null) + { copyBuffer[i].ApplyTo(t); t.Move(translatedCoords[i]); //add thing to blockmap @@ -2836,31 +3027,40 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. rotate clockwise [BeginAction("rotateclockwise")] - public void RotateCW() { - rotateThingsAndTextures(5); + public void RotateCW() + { + RotateThingsAndTextures(5); } //mxd. rotate counterclockwise [BeginAction("rotatecounterclockwise")] - public void RotateCCW() { - rotateThingsAndTextures(-5); + public void RotateCCW() + { + RotateThingsAndTextures(-5); } //mxd - private void rotateThingsAndTextures(int increment) { + private void RotateThingsAndTextures(int increment) + { PreAction(UndoGroup.ThingRotate); List selection = GetSelectedObjects(true, false, true, false); if(selection.Count == 0) return; - foreach(IVisualEventReceiver obj in selection) { - if(obj is BaseVisualThing) { + foreach(IVisualEventReceiver obj in selection) + { + if(obj is BaseVisualThing) + { BaseVisualThing t = obj as BaseVisualThing; t.Rotate(General.ClampAngle(t.Thing.AngleDoom + increment)); - }else if(obj is VisualFloor) { + } + else if(obj is VisualFloor) + { VisualFloor vf = obj as VisualFloor; vf.OnChangeTextureRotation(General.ClampAngle(vf.GetControlSector().Fields.GetValue("rotationfloor", 0.0f) + increment)); - } else if(obj is VisualCeiling) { + } + else if(obj is VisualCeiling) + { VisualCeiling vc = obj as VisualCeiling; vc.OnChangeTextureRotation(General.ClampAngle(vc.GetControlSector().Fields.GetValue("rotationceiling", 0.0f) + increment)); } @@ -2881,10 +3081,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("thingaligntowall")] - public void AlignThingsToWall() { + public void AlignThingsToWall() + { List visualThings = GetSelectedVisualThings(true); - if(visualThings.Count == 0) { + if(visualThings.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "This action requires selected Things!"); return; } @@ -2895,10 +3097,13 @@ namespace CodeImp.DoomBuilder.BuilderModes things.Add(vt.Thing); // Make undo - if(things.Count > 1) { + if(things.Count > 1) + { General.Map.UndoRedo.CreateUndo("Align " + things.Count + " things"); General.Interface.DisplayStatus(StatusType.Action, "Aligned " + things.Count + " things."); - } else { + } + else + { General.Map.UndoRedo.CreateUndo("Align thing"); General.Interface.DisplayStatus(StatusType.Action, "Aligned a thing."); } @@ -2906,18 +3111,22 @@ namespace CodeImp.DoomBuilder.BuilderModes //align things int thingsCount = General.Map.Map.Things.Count; - foreach(Thing t in things) { + foreach(Thing t in things) + { List excludedLines = new List(); bool aligned; - do { + do + { Linedef l = General.Map.Map.NearestLinedef(t.Position, excludedLines); aligned = Tools.TryAlignThingToLine(t, l); - if(!aligned) { + if(!aligned) + { excludedLines.Add(l); - if(excludedLines.Count == thingsCount) { + if(excludedLines.Count == thingsCount) + { ThingTypeInfo tti = General.Map.Data.GetThingInfo(t.Type); General.ErrorLogger.Add(ErrorType.Warning, "Unable to align Thing " + t.Index + " (" + tti.Title + ") to any linedef in a map!"); aligned = true; @@ -2927,14 +3136,17 @@ namespace CodeImp.DoomBuilder.BuilderModes } //apply changes to Visual Things - for(int i = 0; i < visualThings.Count; i++) { + for(int i = 0; i < visualThings.Count; i++) + { BaseVisualThing t = visualThings[i] as BaseVisualThing; t.Changed = true; // Update what must be updated ThingData td = GetThingData(t.Thing); - foreach(KeyValuePair s in td.UpdateAlso) { - if(VisualSectorExists(s.Key)) { + foreach(KeyValuePair s in td.UpdateAlso) + { + if(VisualSectorExists(s.Key)) + { BaseVisualSector vs = (BaseVisualSector)GetVisualSector(s.Key); vs.UpdateSectorGeometry(s.Value); } @@ -2947,71 +3159,92 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("lookthroughthing")] - public void LookThroughThing() { + public void LookThroughThing() + { List visualThings = GetSelectedVisualThings(true); - if(visualThings.Count != 1) { + if(visualThings.Count != 1) + { General.Interface.DisplayStatus(StatusType.Warning, "Look Through Selection action requires 1 selected Thing!"); return; } //set position and angles Thing t = visualThings[0].Thing; - if((t.Type == 9072 || t.Type == 9073) && t.Args[3] > 0) { //AimingCamera or MovingCamera with target? + if((t.Type == 9072 || t.Type == 9073) && t.Args[3] > 0) //AimingCamera or MovingCamera with target? + { //position - if(t.Type == 9072 && (t.Args[0] > 0 || t.Args[1] > 0)) { //positon MovingCamera at targeted interpolation point + if(t.Type == 9072 && (t.Args[0] > 0 || t.Args[1] > 0)) //positon MovingCamera at targeted interpolation point + { int ipTag = t.Args[0] + (t.Args[1] << 8); - Thing ip = null; //find interpolation point - foreach(Thing tgt in General.Map.Map.Things) { - if(tgt.Tag == ipTag && tgt.Type == 9070) { + foreach(Thing tgt in General.Map.Map.Things) + { + if(tgt.Tag == ipTag && tgt.Type == 9070) + { ip = tgt; break; } } - if(ip != null) { + if(ip != null) + { VisualThing vTarget = !VisualThingExists(ip) ? CreateVisualThing(ip) : GetVisualThing(ip); Vector3D targetPos; - if(vTarget == null) { + if(vTarget == null) + { targetPos = ip.Position; if(ip.Sector != null) targetPos.z += ip.Sector.FloorHeight; - } else { + } + else + { targetPos = vTarget.CenterV3D; } General.Map.VisualCamera.Position = targetPos; //position at interpolation point - } else { + } + else + { General.Map.VisualCamera.Position = visualThings[0].CenterV3D; //position at camera } - }else{ + } + else + { General.Map.VisualCamera.Position = visualThings[0].CenterV3D; //position at camera } //angle Thing target = null; - foreach(Thing tgt in General.Map.Map.Things) { - if(tgt.Tag == t.Args[3]) { + foreach(Thing tgt in General.Map.Map.Things) + { + if(tgt.Tag == t.Args[3]) + { target = tgt; break; } } - if (target == null) { + if (target == null) + { General.Interface.DisplayStatus(StatusType.Warning, "Camera target with Tag " + t.Args[3] + " does not exist!"); General.Map.VisualCamera.AngleXY = t.Angle - Angle2D.PI; General.Map.VisualCamera.AngleZ = Angle2D.PI; - } else { + } + else + { VisualThing vTarget = !VisualThingExists(target) ? CreateVisualThing(target) : GetVisualThing(target); Vector3D targetPos; - if(vTarget == null) { + if(vTarget == null) + { targetPos = target.Position; if(target.Sector != null) targetPos.z += target.Sector.FloorHeight; - } else { + } + else + { targetPos = vTarget.CenterV3D; } @@ -3020,11 +3253,15 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.VisualCamera.AngleXY = delta.GetAngleXY(); General.Map.VisualCamera.AngleZ = pitch ? -delta.GetAngleZ() : Angle2D.PI; } - } else if((t.Type == 9025 || t.Type == 9073 || t.Type == 9070) && t.Args[0] != 0) { //InterpolationPoint, SecurityCamera or AimingCamera with pitch? + } + else if((t.Type == 9025 || t.Type == 9073 || t.Type == 9070) && t.Args[0] != 0) //InterpolationPoint, SecurityCamera or AimingCamera with pitch? + { General.Map.VisualCamera.Position = visualThings[0].CenterV3D; //position at camera General.Map.VisualCamera.AngleXY = t.Angle - Angle2D.PI; General.Map.VisualCamera.AngleZ = Angle2D.PI + Angle2D.DegToRad(t.Args[0]); - } else { //nope, just a generic thing + } + else //nope, just a generic thing + { General.Map.VisualCamera.Position = visualThings[0].CenterV3D; //position at thing General.Map.VisualCamera.AngleXY = t.Angle - Angle2D.PI; General.Map.VisualCamera.AngleZ = Angle2D.PI; @@ -3033,10 +3270,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd [BeginAction("toggleslope")] - public void ToggleSlope() { + public void ToggleSlope() + { List selection = GetSelectedSurfaces(); - if(selection.Count == 0) { + if(selection.Count == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Toggle Slope action requires selected surfaces!"); return; } @@ -3046,19 +3285,24 @@ namespace CodeImp.DoomBuilder.BuilderModes General.Map.UndoRedo.CreateUndo("Toggle Slope"); //check selection - foreach(VisualGeometry vg in selection) { + foreach(VisualGeometry vg in selection) + { update = false; //assign/remove action - if(vg.GeometryType == VisualGeometryType.WALL_LOWER) { - if(vg.Sidedef.Line.Action == 0 || (vg.Sidedef.Line.Action == 181 && vg.Sidedef.Line.Args[0] == 0)) { + if(vg.GeometryType == VisualGeometryType.WALL_LOWER) + { + if(vg.Sidedef.Line.Action == 0 || (vg.Sidedef.Line.Action == 181 && vg.Sidedef.Line.Args[0] == 0)) + { //check if the sector already has floor slopes - foreach(Sidedef side in vg.Sidedef.Sector.Sidedefs) { + foreach(Sidedef side in vg.Sidedef.Sector.Sidedefs) + { if(side == vg.Sidedef || side.Line.Action != 181) continue; int arg = (side == side.Line.Front ? 1 : 2); - if(side.Line.Args[0] == arg) { + if(side.Line.Args[0] == arg) + { //if only floor is affected, remove action if(side.Line.Args[1] == 0) side.Line.Action = 0; @@ -3072,15 +3316,20 @@ namespace CodeImp.DoomBuilder.BuilderModes vg.Sidedef.Line.Args[0] = (vg.Sidedef == vg.Sidedef.Line.Front ? 1 : 2); update = true; } - } else if(vg.GeometryType == VisualGeometryType.WALL_UPPER) { - if(vg.Sidedef.Line.Action == 0 || (vg.Sidedef.Line.Action == 181 && vg.Sidedef.Line.Args[1] == 0)) { + } + else if(vg.GeometryType == VisualGeometryType.WALL_UPPER) + { + if(vg.Sidedef.Line.Action == 0 || (vg.Sidedef.Line.Action == 181 && vg.Sidedef.Line.Args[1] == 0)) + { //check if the sector already has ceiling slopes - foreach(Sidedef side in vg.Sidedef.Sector.Sidedefs) { + foreach(Sidedef side in vg.Sidedef.Sector.Sidedefs) + { if(side == vg.Sidedef || side.Line.Action != 181) continue; int arg = (side == side.Line.Front ? 1 : 2); - if(side.Line.Args[1] == arg) { + if(side.Line.Args[1] == arg) + { //if only ceiling is affected, remove action if(side.Line.Args[0] == 0) side.Line.Action = 0; @@ -3094,14 +3343,18 @@ namespace CodeImp.DoomBuilder.BuilderModes vg.Sidedef.Line.Args[1] = (vg.Sidedef == vg.Sidedef.Line.Front ? 1 : 2); update = true; } - } else if(vg.GeometryType == VisualGeometryType.CEILING) { + } + else if(vg.GeometryType == VisualGeometryType.CEILING) + { //check if the sector has ceiling slopes - foreach(Sidedef side in vg.Sector.Sector.Sidedefs) { + foreach(Sidedef side in vg.Sector.Sector.Sidedefs) + { if(side.Line.Action != 181) continue; int arg = (side == side.Line.Front ? 1 : 2); - if(side.Line.Args[1] == arg) { + if(side.Line.Args[1] == arg) + { //if only ceiling is affected, remove action if(side.Line.Args[0] == 0) side.Line.Action = 0; @@ -3111,14 +3364,18 @@ namespace CodeImp.DoomBuilder.BuilderModes update = true; } } - } else if(vg.GeometryType == VisualGeometryType.FLOOR) { + } + else if(vg.GeometryType == VisualGeometryType.FLOOR) + { //check if the sector has floor slopes - foreach(Sidedef side in vg.Sector.Sector.Sidedefs) { + foreach(Sidedef side in vg.Sector.Sector.Sidedefs) + { if(side.Line.Action != 181) continue; int arg = (side == side.Line.Front ? 1 : 2); - if(side.Line.Args[0] == arg) { + if(side.Line.Args[0] == arg) + { //if only floor is affected, remove action if(side.Line.Args[1] == 0) side.Line.Action = 0; @@ -3135,7 +3392,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //update changed geometry - if(toUpdate.Count > 0) { + if(toUpdate.Count > 0) + { RebuildElementData(); foreach(BaseVisualSector vs in toUpdate) @@ -3154,11 +3412,12 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Texture Alignment //mxd. If checkSelectedSidedefParts is set to true, only selected linedef parts will be aligned (when a sidedef has both top and bottom parts, but only bottom is selected, top texture won't be aligned) - internal void AutoAlignTextures(BaseVisualGeometrySidedef start, ImageData texture, bool alignx, bool aligny, bool resetsidemarks, bool checkSelectedSidedefParts) { + internal void AutoAlignTextures(BaseVisualGeometrySidedef start, ImageData texture, bool alignx, bool aligny, bool resetsidemarks, bool checkSelectedSidedefParts) + { if(General.Map.UDMF) - autoAlignTexturesUDMF(start, texture, alignx, aligny, resetsidemarks, checkSelectedSidedefParts); + AutoAlignTexturesUdmf(start, texture, alignx, aligny, resetsidemarks, checkSelectedSidedefParts); else - autoAlignTextures(start, texture, alignx, aligny, resetsidemarks); + AutoAlignTextures(start, texture, alignx, aligny, resetsidemarks); } //mxd. Moved here from Tools @@ -3167,7 +3426,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // When resetsidemarks is set to true, all sidedefs will first be marked false (not aligned). // Setting resetsidemarks to false is usefull to align only within a specific selection // (set the marked property to true for the sidedefs outside the selection) - private void autoAlignTextures(BaseVisualGeometrySidedef start, ImageData texture, bool alignx, bool aligny, bool resetsidemarks) { + private void AutoAlignTextures(BaseVisualGeometrySidedef start, ImageData texture, bool alignx, bool aligny, bool resetsidemarks) + { Stack todo = new Stack(50); float scalex = (General.Map.Config.ScaledTextureOffsets && !texture.WorldPanning) ? texture.Scale.x : 1.0f; float scaley = (General.Map.Config.ScaledTextureOffsets && !texture.WorldPanning) ? texture.Scale.y : 1.0f; @@ -3182,11 +3442,14 @@ namespace CodeImp.DoomBuilder.BuilderModes int ystartalign = start.Sidedef.OffsetY; //mxd //mxd - if(start.GeometryType == VisualGeometryType.WALL_MIDDLE_3D) { + if(start.GeometryType == VisualGeometryType.WALL_MIDDLE_3D) + { first.controlSide = start.GetControlLinedef().Front; first.offsetx += first.controlSide.OffsetX; ystartalign += first.controlSide.OffsetY; - } else { + } + else + { first.controlSide = start.Sidedef; } @@ -3194,16 +3457,16 @@ namespace CodeImp.DoomBuilder.BuilderModes todo.Push(first); // Continue until nothing more to align - while(todo.Count > 0) { + while(todo.Count > 0) + { // Get the align job to do SidedefAlignJob j = todo.Pop(); - if(j.forward) { + if(j.forward) + { // Apply alignment - if(alignx) - j.controlSide.OffsetX = (int)j.offsetx; - if(aligny) - j.sidedef.OffsetY = (int)Math.Round((first.ceilingHeight - j.ceilingHeight) / scaley) + ystartalign; + if(alignx) j.controlSide.OffsetX = (int)j.offsetx; + if(aligny) j.sidedef.OffsetY = (int)Math.Round((first.ceilingHeight - j.ceilingHeight) / scaley) + ystartalign; int forwardoffset = (int)j.offsetx + (int)Math.Round(j.sidedef.Line.Length / scalex); int backwardoffset = (int)j.offsetx; @@ -3211,7 +3474,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Wrap the value within the width of the texture (to prevent ridiculous values) // NOTE: We don't use ScaledWidth here because the texture offset is in pixels, not mappixels - if(texture.IsImageLoaded) { + if(texture.IsImageLoaded) + { if(alignx) j.sidedef.OffsetX %= texture.Width; if(aligny) j.sidedef.OffsetY %= texture.Height; } @@ -3223,12 +3487,12 @@ namespace CodeImp.DoomBuilder.BuilderModes // Add sidedefs backward (connected to the left vertex) v = j.sidedef.IsFront ? j.sidedef.Line.Start : j.sidedef.Line.End; AddSidedefsForAlignment(todo, v, false, backwardoffset, 1.0f, texture.LongName, false); - } else { + } + else + { // Apply alignment - if(alignx) - j.controlSide.OffsetX = (int)j.offsetx - (int)Math.Round(j.sidedef.Line.Length / scalex); - if(aligny) - j.sidedef.OffsetY = (int)Math.Round((first.ceilingHeight - j.ceilingHeight) / scaley) + ystartalign; + if(alignx) j.controlSide.OffsetX = (int)j.offsetx - (int)Math.Round(j.sidedef.Line.Length / scalex); + if(aligny) j.sidedef.OffsetY = (int)Math.Round((first.ceilingHeight - j.ceilingHeight) / scaley) + ystartalign; int forwardoffset = (int)j.offsetx; int backwardoffset = (int)j.offsetx - (int)Math.Round(j.sidedef.Line.Length / scalex); @@ -3236,7 +3500,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Wrap the value within the width of the texture (to prevent ridiculous values) // NOTE: We don't use ScaledWidth here because the texture offset is in pixels, not mappixels - if(texture.IsImageLoaded) { + if(texture.IsImageLoaded) + { if(alignx) j.sidedef.OffsetX %= texture.Width; if(aligny) j.sidedef.OffsetY %= texture.Height; } @@ -3258,7 +3523,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // When resetsidemarks is set to true, all sidedefs will first be marked false (not aligned). // Setting resetsidemarks to false is usefull to align only within a specific selection // (set the marked property to true for the sidedefs outside the selection) - private void autoAlignTexturesUDMF(BaseVisualGeometrySidedef start, ImageData texture, bool alignx, bool aligny, bool resetsidemarks, bool checkSelectedSidedefParts) { + private void AutoAlignTexturesUdmf(BaseVisualGeometrySidedef start, ImageData texture, bool alignx, bool aligny, bool resetsidemarks, bool checkSelectedSidedefParts) + { // Mark all sidedefs false (they will be marked true when the texture is aligned) if(resetsidemarks) General.Map.Map.ClearMarkedSidedefs(false); if(!texture.IsImageLoaded) return; @@ -3278,9 +3544,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd List selectedVisualSides = new List(); - if(checkSelectedSidedefParts && !singleselection) { - foreach(IVisualEventReceiver i in selectedobjects) { - if(i is BaseVisualGeometrySidedef) { + if(checkSelectedSidedefParts && !singleselection) + { + foreach(IVisualEventReceiver i in selectedobjects) + { + if(i is BaseVisualGeometrySidedef) + { BaseVisualGeometrySidedef sd = i as BaseVisualGeometrySidedef; if(!selectedVisualSides.Contains(sd)) selectedVisualSides.Add(sd); } @@ -3288,7 +3557,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. scaleY - switch(start.GeometryType) { + switch(start.GeometryType) + { case VisualGeometryType.WALL_UPPER: first.scaleY = start.Sidedef.Fields.GetValue("scaley_top", 1.0f); break; @@ -3303,7 +3573,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Determine the Y alignment float ystartalign = start.Sidedef.OffsetY; - switch(start.GeometryType) { + switch(start.GeometryType) + { case VisualGeometryType.WALL_UPPER: ystartalign += Tools.GetSidedefTopOffsetY(start.Sidedef, start.Sidedef.Fields.GetValue("offsety_top", 0.0f), first.scaleY, false);//mxd break; @@ -3321,7 +3592,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Begin with first sidedef - switch(start.GeometryType) { + switch(start.GeometryType) + { case VisualGeometryType.WALL_UPPER: first.offsetx += start.Sidedef.Fields.GetValue("offsetx_top", 0.0f); break; @@ -3341,7 +3613,8 @@ namespace CodeImp.DoomBuilder.BuilderModes todo.Push(first); // Continue until nothing more to align - while(todo.Count > 0) { + while(todo.Count > 0) + { Vertex v; float forwardoffset; float backwardoffset; @@ -3355,11 +3628,12 @@ namespace CodeImp.DoomBuilder.BuilderModes bool matchmid = ((j.controlSide.LongMiddleTexture == texture.LongName) && (j.controlSide.MiddleRequired() || j.controlSide.LongMiddleTexture != MapSet.EmptyLongName)); //mxd //mxd. If there's a selection, check if matched part is actually selected - if(checkSelectedSidedefParts && !singleselection) { - if(matchtop) matchtop = sidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_UPPER); - if(matchbottom) matchbottom = sidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_LOWER); - if(matchmid) matchmid = sidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_MIDDLE) || - sidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_MIDDLE_3D); + if(checkSelectedSidedefParts && !singleselection) + { + if(matchtop) matchtop = SidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_UPPER); + if(matchbottom) matchbottom = SidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_LOWER); + if(matchmid) matchmid = SidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_MIDDLE) || + SidePartIsSelected(selectedVisualSides, j.sidedef, VisualGeometryType.WALL_MIDDLE_3D); } if(!matchbottom && !matchtop && !matchmid) continue; //mxd @@ -3379,9 +3653,11 @@ namespace CodeImp.DoomBuilder.BuilderModes if(matchmid) UDMFTools.SetFloat(j.controlSide.Fields, "scaley_mid", j.scaleY, 1.0f); if(matchbottom) UDMFTools.SetFloat(j.sidedef.Fields, "scaley_bottom", j.scaleY, 1.0f); - if(j.forward) { + if(j.forward) + { // Apply alignment - if(alignx) { + if(alignx) + { float offset = j.offsetx; offset -= j.sidedef.OffsetX; @@ -3389,8 +3665,10 @@ namespace CodeImp.DoomBuilder.BuilderModes j.sidedef.Fields["offsetx_top"] = new UniValue(UniversalType.Float, offset % texture.Width); if(matchbottom) j.sidedef.Fields["offsetx_bottom"] = new UniValue(UniversalType.Float, offset % texture.Width); - if(matchmid) { - if(j.sidedef.Index != j.controlSide.Index) { //mxd. if it's a part of 3d-floor + if(matchmid) + { + if(j.sidedef.Index != j.controlSide.Index) //mxd. if it's a part of 3d-floor + { offset -= j.controlSide.OffsetX; offset -= j.controlSide.Fields.GetValue("offsetx_mid", 0.0f); } @@ -3399,7 +3677,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(aligny) { + if(aligny) + { float offset = ((start.Sidedef.Sector.CeilHeight - j.ceilingHeight) / scaley) * j.scaleY + ystartalign; //mxd offset -= j.sidedef.OffsetY; //mxd offset = (float)Math.Round(offset); //mxd @@ -3408,17 +3687,22 @@ namespace CodeImp.DoomBuilder.BuilderModes j.sidedef.Fields["offsety_top"] = new UniValue(UniversalType.Float, Tools.GetSidedefTopOffsetY(j.sidedef, offset, j.scaleY, true) % texture.Height); //mxd if(matchbottom) j.sidedef.Fields["offsety_bottom"] = new UniValue(UniversalType.Float, Tools.GetSidedefBottomOffsetY(j.sidedef, offset, j.scaleY, true) % texture.Height); //mxd - if(matchmid) { + if(matchmid) + { //mxd. Side is part of a 3D floor? - if(j.sidedef.Index != j.controlSide.Index) { + if(j.sidedef.Index != j.controlSide.Index) + { offset -= j.controlSide.OffsetY; offset -= j.controlSide.Fields.GetValue("offsety_mid", 0.0f); j.sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, offset % texture.Height); - } else { + } + else + { offset = Tools.GetSidedefMiddleOffsetY(j.sidedef, offset, j.scaleY, true); //mxd. Clamp offset if this part is middle single or wrapped middle double - if(j.sidedef.Other == null || j.sidedef.IsFlagSet("wrapmidtex") || j.sidedef.Line.IsFlagSet("wrapmidtex")) { + if(j.sidedef.Other == null || j.sidedef.IsFlagSet("wrapmidtex") || j.sidedef.Line.IsFlagSet("wrapmidtex")) + { offset %= texture.Height; } @@ -3441,9 +3725,12 @@ namespace CodeImp.DoomBuilder.BuilderModes // Add sidedefs forward (connected to the right vertex) v = j.sidedef.IsFront ? j.sidedef.Line.End : j.sidedef.Line.Start; AddSidedefsForAlignment(todo, v, true, forwardoffset, j.scaleY, texture.LongName, true); - } else { + } + else + { // Apply alignment - if(alignx) { + if(alignx) + { float offset = j.offsetx - (int)Math.Round(j.sidedef.Line.Length / scalex * offsetscalex); offset -= j.sidedef.OffsetX; @@ -3451,8 +3738,10 @@ namespace CodeImp.DoomBuilder.BuilderModes j.sidedef.Fields["offsetx_top"] = new UniValue(UniversalType.Float, offset % texture.Width); if(matchbottom) j.sidedef.Fields["offsetx_bottom"] = new UniValue(UniversalType.Float, offset % texture.Width); - if(matchmid) { - if(j.sidedef.Index != j.controlSide.Index) { //mxd + if(matchmid) + { + if(j.sidedef.Index != j.controlSide.Index) //mxd + { offset -= j.controlSide.OffsetX; offset -= j.controlSide.Fields.GetValue("offsetx_mid", 0.0f); } @@ -3460,7 +3749,8 @@ namespace CodeImp.DoomBuilder.BuilderModes j.sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, offset % texture.Width); } } - if(aligny) { + if(aligny) + { float offset = ((start.Sidedef.Sector.CeilHeight - j.ceilingHeight) / scaley) * j.scaleY + ystartalign; //mxd offset -= j.sidedef.OffsetY; //mxd offset = (float)Math.Round(offset); //mxd @@ -3469,13 +3759,17 @@ namespace CodeImp.DoomBuilder.BuilderModes j.sidedef.Fields["offsety_top"] = new UniValue(UniversalType.Float, Tools.GetSidedefTopOffsetY(j.sidedef, offset, j.scaleY, true) % texture.Height); //mxd if(matchbottom) j.sidedef.Fields["offsety_bottom"] = new UniValue(UniversalType.Float, Tools.GetSidedefBottomOffsetY(j.sidedef, offset, j.scaleY, true) % texture.Height); //mxd - if(matchmid) { + if(matchmid) + { //mxd. Side is part of a 3D floor? - if(j.sidedef.Index != j.controlSide.Index) { + if(j.sidedef.Index != j.controlSide.Index) + { offset -= j.controlSide.OffsetY; offset -= j.controlSide.Fields.GetValue("offsety_mid", 0.0f); j.sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, offset % texture.Height); //mxd - } else { + } + else + { j.sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, Tools.GetSidedefMiddleOffsetY(j.sidedef, offset, j.scaleY, true) % texture.Height); //mxd } } @@ -3499,16 +3793,21 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This adds the matching, unmarked sidedefs from a vertex for texture alignment - private void AddSidedefsForAlignment(Stack stack, Vertex v, bool forward, float offsetx, float scaleY, long texturelongname, bool udmf) { - foreach(Linedef ld in v.Linedefs) { + private void AddSidedefsForAlignment(Stack stack, Vertex v, bool forward, float offsetx, float scaleY, long texturelongname, bool udmf) + { + foreach(Linedef ld in v.Linedefs) + { Sidedef side1 = forward ? ld.Front : ld.Back; Sidedef side2 = forward ? ld.Back : ld.Front; - if((ld.Start == v) && (side1 != null) && !side1.Marked) { - List controlSides = getControlSides(side1, udmf);//mxd + if((ld.Start == v) && (side1 != null) && !side1.Marked) + { + List controlSides = GetControlSides(side1, udmf);//mxd - foreach(Sidedef s in controlSides) { - if(Tools.SidedefTextureMatch(s, texturelongname)) { + foreach(Sidedef s in controlSides) + { + if(Tools.SidedefTextureMatch(s, texturelongname)) + { SidedefAlignJob nj = new SidedefAlignJob(); nj.forward = forward; nj.offsetx = offsetx; @@ -3518,11 +3817,15 @@ namespace CodeImp.DoomBuilder.BuilderModes stack.Push(nj); } } - } else if((ld.End == v) && (side2 != null) && !side2.Marked) { - List controlSides = getControlSides(side2, udmf);//mxd + } + else if((ld.End == v) && (side2 != null) && !side2.Marked) + { + List controlSides = GetControlSides(side2, udmf);//mxd - foreach(Sidedef s in controlSides) { - if(Tools.SidedefTextureMatch(s, texturelongname)) { + foreach(Sidedef s in controlSides) + { + if(Tools.SidedefTextureMatch(s, texturelongname)) + { SidedefAlignJob nj = new SidedefAlignJob(); nj.forward = forward; nj.offsetx = offsetx; @@ -3537,7 +3840,7 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private static bool sidePartIsSelected(List selection, Sidedef side, VisualGeometryType geoType) + private static bool SidePartIsSelected(List selection, Sidedef side, VisualGeometryType geoType) { foreach(BaseVisualGeometrySidedef vs in selection) if(vs.GeometryType == geoType && vs.Sidedef.Index == side.Index) return true; @@ -3545,7 +3848,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private List getControlSides(Sidedef side, bool udmf) { + private List GetControlSides(Sidedef side, bool udmf) + { if(side.Other == null) return new List() { side }; if(side.Other.Sector.Tag == 0) return new List() { side }; diff --git a/Source/Plugins/BuilderModes/VisualModes/BaseVisualSector.cs b/Source/Plugins/BuilderModes/VisualModes/BaseVisualSector.cs index b62d713c..20cf8a8b 100644 --- a/Source/Plugins/BuilderModes/VisualModes/BaseVisualSector.cs +++ b/Source/Plugins/BuilderModes/VisualModes/BaseVisualSector.cs @@ -170,7 +170,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. call this to update sector and things in it when Sector.Fields are changed - override public void UpdateSectorData() { + override public void UpdateSectorData() + { //update sector data SectorData data = GetSectorData(); data.UpdateForced(); @@ -179,9 +180,12 @@ namespace CodeImp.DoomBuilder.BuilderModes Rebuild(); //update things in this sector - foreach (Thing t in General.Map.Map.Things) { - if (t.Sector == this.Sector) { - if (mode.VisualThingExists(t)) { + foreach (Thing t in General.Map.Map.Things) + { + if (t.Sector == this.Sector) + { + if (mode.VisualThingExists(t)) + { // Update thing BaseVisualThing vt = (mode.GetVisualThing(t) as BaseVisualThing); vt.Rebuild(); @@ -217,28 +221,37 @@ namespace CodeImp.DoomBuilder.BuilderModes bool floorRequired = ef.VavoomType; //mxd bool ceilingRequired = ef.VavoomType; //mxd - if(ef.VavoomType || !ef.IgnoreBottomHeight) { + if(ef.VavoomType || !ef.IgnoreBottomHeight) + { //mxd. check if 3d floor is between real floor and ceiling - if(!ef.VavoomType) { + if(!ef.VavoomType) + { if (ef.Ceiling.plane.GetInverted().Normal != floor.Level.plane.Normal - || ef.Ceiling.plane.Normal != ceiling.Level.plane.Normal) { + || ef.Ceiling.plane.Normal != ceiling.Level.plane.Normal) + { //mxd. check if at least one vertex of 3d floor is between floor and ceiling floorRequired = Check3dFloorPlane(floor.Vertices, ceiling.Vertices, ef.Ceiling.plane); + + } //if floor, ceiling and 3d floor are not sloped, compare offsets - } else if(-floor.Level.plane.Offset < ef.Ceiling.plane.Offset - && ceiling.Level.plane.Offset > ef.Ceiling.plane.Offset) { + else if(-floor.Level.plane.Offset < ef.Ceiling.plane.Offset + && ceiling.Level.plane.Offset > ef.Ceiling.plane.Offset) + { floorRequired = true; } } //mxd. Create a floor - if(floorRequired) { + if(floorRequired) + { VisualFloor vf = (i < extrafloors.Count) ? extrafloors[i] : new VisualFloor(mode, this); - if(vf.Setup(ef.Ceiling, ef)) { + if(vf.Setup(ef.Ceiling, ef)) + { base.AddGeometry(vf); //mxd. add backside as well - if(!ef.VavoomType && ef.RenderInside) { + if(!ef.VavoomType && ef.RenderInside) + { VisualFloor vfb = (i < extrabackfloors.Count) ? extrabackfloors[i] : new VisualFloor(mode, this); if(vfb.Setup(ef.Ceiling, ef, true)) base.AddGeometry(vfb); if(i >= extrabackfloors.Count) extrabackfloors.Add(vfb); @@ -249,26 +262,34 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. check if 3d ceiling is between real floor and ceiling - if(!ef.VavoomType) { + if(!ef.VavoomType) + { if (ef.Floor.plane.GetInverted().Normal != ceiling.Level.plane.Normal - || ef.Floor.plane.Normal != floor.Level.plane.Normal) { + || ef.Floor.plane.Normal != floor.Level.plane.Normal) + { //mxd. check if at least one vertex of 3d ceiling is between floor and ceiling ceilingRequired = Check3dFloorPlane(floor.Vertices, ceiling.Vertices, ef.Floor.plane); + + } //if floor, ceiling and 3d ceiling are not sloped, compare offsets - } else if(ceiling.Level.plane.Offset > -ef.Floor.plane.Offset - && floor.Level.plane.Offset > ef.Floor.plane.Offset) { + else if(ceiling.Level.plane.Offset > -ef.Floor.plane.Offset + && floor.Level.plane.Offset > ef.Floor.plane.Offset) + { ceilingRequired = true; } } //mxd. Create a ceiling - if(ceilingRequired) { + if(ceilingRequired) + { VisualCeiling vc = (i < extraceilings.Count) ? extraceilings[i] : new VisualCeiling(mode, this); - if(vc.Setup(ef.Floor, ef)) { + if(vc.Setup(ef.Floor, ef)) + { base.AddGeometry(vc); //mxd. add backside as well - if(!ef.VavoomType && (ef.RenderInside || ef.IgnoreBottomHeight)) { + if(!ef.VavoomType && (ef.RenderInside || ef.IgnoreBottomHeight)) + { VisualCeiling vcb = (i < extrabackceilings.Count) ? extrabackceilings[i] : new VisualCeiling(mode, this); if(vcb.Setup(ef.Floor, ef, true)) base.AddGeometry(vcb); if(i >= extrabackceilings.Count) extrabackceilings.Add(vcb); @@ -317,10 +338,12 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Create backsides List middlebacks = new List(); - for (int i = 0; i < data.ExtraFloors.Count; i++) { + for (int i = 0; i < data.ExtraFloors.Count; i++) + { Effect3DFloor ef = data.ExtraFloors[i]; - if (!ef.VavoomType && ef.RenderInside && !ef.IgnoreBottomHeight) { + if (!ef.VavoomType && ef.RenderInside && !ef.IgnoreBottomHeight) + { VisualMiddleBack vms = new VisualMiddleBack(mode, this, sd); if (vms.Setup(ef)) base.AddGeometry(vms); middlebacks.Add(vms); @@ -358,7 +381,8 @@ namespace CodeImp.DoomBuilder.BuilderModes bool show = false; //check floor - for(int c = 0; c < floorverts.Length; c++) { + for(int c = 0; c < floorverts.Length; c++) + { if (plane.GetZ(new Vector2D(floorverts[c].x, floorverts[c].y)) > Math.Round(floorverts[c].z, 3)) { show = true; diff --git a/Source/Plugins/BuilderModes/VisualModes/BaseVisualThing.cs b/Source/Plugins/BuilderModes/VisualModes/BaseVisualThing.cs index 61ab50b2..73b53de1 100644 --- a/Source/Plugins/BuilderModes/VisualModes/BaseVisualThing.cs +++ b/Source/Plugins/BuilderModes/VisualModes/BaseVisualThing.cs @@ -81,7 +81,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - if(mode.UseSelectionFromClassicMode && t.Selected){ + if(mode.UseSelectionFromClassicMode && t.Selected) + { this.selected = true; mode.AddSelectedObject(this); } @@ -97,11 +98,14 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. Check thing size float infoRadius, infoHeight; - if((info.Radius < 0.1f) || (info.Height < 0.1f)) { + if((info.Radius < 0.1f) || (info.Height < 0.1f)) + { infoRadius = FIXED_RADIUS; infoHeight = FIXED_RADIUS; sizeless = true; - } else { + } + else + { infoRadius = info.Radius; infoHeight = info.Height; sizeless = false; @@ -154,7 +158,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Make vertices WorldVertex[] verts = new WorldVertex[6]; - if(sizeless) { //mxd + if(sizeless) //mxd + { float hh = height / 2; verts[0] = new WorldVertex(-radius + offsetx, 0.0f, offsety - hh, sectorcolor, 0.0f, 1.0f); verts[1] = new WorldVertex(-radius + offsetx, 0.0f, hh + offsety, sectorcolor, 0.0f, 0.0f); @@ -162,7 +167,9 @@ namespace CodeImp.DoomBuilder.BuilderModes verts[3] = verts[0]; verts[4] = verts[2]; verts[5] = new WorldVertex(+radius + offsetx, 0.0f, offsety - hh, sectorcolor, 1.0f, 1.0f); - } else { + } + else + { verts[0] = new WorldVertex(-radius + offsetx, 0.0f, offsety, sectorcolor, 0.0f, 1.0f); verts[1] = new WorldVertex(-radius + offsetx, 0.0f, height + offsety, sectorcolor, 0.0f, 0.0f); verts[2] = new WorldVertex(+radius + offsetx, 0.0f, height + offsety, sectorcolor, 1.0f, 0.0f); @@ -196,7 +203,8 @@ namespace CodeImp.DoomBuilder.BuilderModes Vector3D pos = Thing.Position; if(Thing.Type == 9501) { - if(Thing.Sector != null) { //mxd + if(Thing.Sector != null) //mxd + { // This is a special thing that needs special positioning SectorData sd = mode.GetSectorData(Thing.Sector); pos.z = sd.Ceiling.sector.CeilHeight + Thing.Position.z; @@ -204,7 +212,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } else if(Thing.Type == 9500) { - if(Thing.Sector != null) { //mxd + if(Thing.Sector != null) //mxd + { // This is a special thing that needs special positioning SectorData sd = mode.GetSectorData(Thing.Sector); pos.z = sd.Floor.sector.FloorHeight + Thing.Position.z; @@ -270,10 +279,13 @@ namespace CodeImp.DoomBuilder.BuilderModes cageradius2 = cageradius2 * cageradius2; pos2d = pos; - if(sizeless) { //mxd + if(sizeless) //mxd + { boxp1 = new Vector3D(pos.x - infoRadius, pos.y - infoRadius, pos.z - infoRadius/2); boxp2 = new Vector3D(pos.x + infoRadius, pos.y + infoRadius, pos.z + infoRadius/2); - } else { + } + else + { boxp1 = new Vector3D(pos.x - infoRadius, pos.y - infoRadius, pos.z); boxp2 = new Vector3D(pos.x + infoRadius, pos.y + infoRadius, pos.z + infoHeight); } @@ -430,7 +442,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public virtual bool IsSelected() { + public virtual bool IsSelected() + { return selected; } @@ -483,7 +496,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Delete thing - public virtual void OnDelete() { + public virtual void OnDelete() + { mode.CreateUndo("Delete thing"); mode.SetActionResult("Deleted a thing."); @@ -525,10 +539,10 @@ namespace CodeImp.DoomBuilder.BuilderModes List things = mode.GetSelectedThings(); //mxd updateList = new List(); - foreach(Thing t in things) { + foreach(Thing t in things) + { VisualThing vt = mode.GetVisualThing(t); - if(vt != null) - updateList.Add(vt as BaseVisualThing); + if(vt != null) updateList.Add(vt as BaseVisualThing); } General.Interface.OnEditFormValuesChanged += Interface_OnEditFormValuesChanged; @@ -543,9 +557,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void Interface_OnEditFormValuesChanged(object sender, EventArgs e) { - foreach(BaseVisualThing vt in updateList) - vt.Changed = true; + private void Interface_OnEditFormValuesChanged(object sender, EventArgs e) + { + foreach(BaseVisualThing vt in updateList) vt.Changed = true; } // Raise/lower thing @@ -576,7 +590,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public void OnMove(Vector3D newPosition) { + public void OnMove(Vector3D newPosition) + { if ((General.Map.UndoRedo.NextUndo == null) || (General.Map.UndoRedo.NextUndo.TicketID != undoticket)) undoticket = mode.CreateUndo("Move thing"); Thing.Move(newPosition); @@ -584,8 +599,10 @@ namespace CodeImp.DoomBuilder.BuilderModes // Update what must be updated ThingData td = mode.GetThingData(this.Thing); - foreach (KeyValuePair s in td.UpdateAlso) { - if (mode.VisualSectorExists(s.Key)) { + foreach (KeyValuePair s in td.UpdateAlso) + { + if (mode.VisualSectorExists(s.Key)) + { BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(s.Key); vs.UpdateSectorGeometry(s.Value); } @@ -595,7 +612,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public void Rotate(int ammount) { + public void Rotate(int ammount) + { if ((General.Map.UndoRedo.NextUndo == null) || (General.Map.UndoRedo.NextUndo.TicketID != undoticket)) undoticket = mode.CreateUndo("Rotate thing"); Thing.Rotate(ammount); diff --git a/Source/Plugins/BuilderModes/VisualModes/BaseVisualVertex.cs b/Source/Plugins/BuilderModes/VisualModes/BaseVisualVertex.cs index 9bc8b472..72c33616 100644 --- a/Source/Plugins/BuilderModes/VisualModes/BaseVisualVertex.cs +++ b/Source/Plugins/BuilderModes/VisualModes/BaseVisualVertex.cs @@ -1,8 +1,12 @@ -using System.Collections.Generic; -using CodeImp.DoomBuilder.VisualModes; -using CodeImp.DoomBuilder.Map; -using CodeImp.DoomBuilder.Geometry; +#region ================== Namespaces + +using System.Collections.Generic; using System.Windows.Forms; +using CodeImp.DoomBuilder.Geometry; +using CodeImp.DoomBuilder.Map; +using CodeImp.DoomBuilder.VisualModes; + +#endregion namespace CodeImp.DoomBuilder.BuilderModes { @@ -25,7 +29,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Constructor public BaseVisualVertex(BaseVisualMode mode, Vertex v, bool ceilingVertex) - : base(v, ceilingVertex) { + : base(v, ceilingVertex) + { this.mode = mode; cageradius2 = DEFAULT_SIZE * General.Settings.GZVertexScale3D * Angle2D.SQRT2; @@ -36,14 +41,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //this updates the handle itself - public override void Update() { + public override void Update() + { if(!changed) return; float z = ceilingVertex ? vertex.ZCeiling : vertex.ZFloor; - if(!float.IsNaN(z)) { + if(!float.IsNaN(z)) + { haveOffset = true; - } else { - z = getSectorHeight(); + } + else + { + z = GetSectorHeight(); haveOffset = false; } @@ -57,10 +66,13 @@ namespace CodeImp.DoomBuilder.BuilderModes changed = false; } - private void updateGeometry(Vertex v) { + private void UpdateGeometry(Vertex v) + { VertexData vd = mode.GetVertexData(v); - foreach(KeyValuePair s in vd.UpdateAlso) { - if(mode.VisualSectorExists(s.Key)) { + foreach(KeyValuePair s in vd.UpdateAlso) + { + if(mode.VisualSectorExists(s.Key)) + { BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(s.Key); vs.UpdateSectorGeometry(s.Value); } @@ -68,22 +80,28 @@ namespace CodeImp.DoomBuilder.BuilderModes } //get the most appropriate height from sectors - private int getSectorHeight() { + private int GetSectorHeight() + { int height; VertexData vd = mode.GetVertexData(vertex); Sector[] sectors = new Sector[vd.UpdateAlso.Keys.Count]; vd.UpdateAlso.Keys.CopyTo(sectors, 0); - if(ceilingVertex) { + if(ceilingVertex) + { height = sectors[0].CeilHeight; - for(int i = 1; i < sectors.Length; i++) { + for(int i = 1; i < sectors.Length; i++) + { if(sectors[i].CeilHeight < height) height = sectors[i].CeilHeight; } - } else { + } + else + { height = sectors[0].FloorHeight; - for(int i = 1; i < sectors.Length; i++) { + for(int i = 1; i < sectors.Length; i++) + { if(sectors[i].FloorHeight > height) height = sectors[i].FloorHeight; } @@ -93,20 +111,23 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public virtual bool IsSelected() { + public virtual bool IsSelected() + { return selected; } #region ================== Object picking // This performs a fast test in object picking - public override bool PickFastReject(Vector3D from, Vector3D to, Vector3D dir) { + public override bool PickFastReject(Vector3D from, Vector3D to, Vector3D dir) + { float distance2 = Line2D.GetDistanceToLineSq(from, to, vertex.Position, false); return (distance2 <= cageradius2); } // This performs an accurate test for object picking - public override bool PickAccurate(Vector3D from, Vector3D to, Vector3D dir, ref float u_ray) { + public override bool PickAccurate(Vector3D from, Vector3D to, Vector3D dir, ref float u_ray) + { Vector3D delta = to - from; float tfar = float.MaxValue; float tnear = float.MinValue; @@ -115,12 +136,16 @@ namespace CodeImp.DoomBuilder.BuilderModes // See http://www.masm32.com/board/index.php?topic=9941.0 // Check X slab - if(delta.x == 0.0f) { - if(from.x > boxp2.x || from.x < boxp1.x) { + if(delta.x == 0.0f) + { + if(from.x > boxp2.x || from.x < boxp1.x) + { // Ray is parallel to the planes & outside slab return false; } - } else { + } + else + { float tmp = 1.0f / delta.x; float t1 = (boxp1.x - from.x) * tmp; float t2 = (boxp2.x - from.x) * tmp; @@ -130,19 +155,24 @@ namespace CodeImp.DoomBuilder.BuilderModes tnear = t1; if(t2 < tfar) tfar = t2; - if(tnear > tfar || tfar < 0.0f) { + if(tnear > tfar || tfar < 0.0f) + { // Ray missed box or box is behind ray return false; } } // Check Y slab - if(delta.y == 0.0f) { - if(from.y > boxp2.y || from.y < boxp1.y) { + if(delta.y == 0.0f) + { + if(from.y > boxp2.y || from.y < boxp1.y) + { // Ray is parallel to the planes & outside slab return false; } - } else { + } + else + { float tmp = 1.0f / delta.y; float t1 = (boxp1.y - from.y) * tmp; float t2 = (boxp2.y - from.y) * tmp; @@ -152,19 +182,24 @@ namespace CodeImp.DoomBuilder.BuilderModes tnear = t1; if(t2 < tfar) tfar = t2; - if(tnear > tfar || tfar < 0.0f) { + if(tnear > tfar || tfar < 0.0f) + { // Ray missed box or box is behind ray return false; } } // Check Z slab - if(delta.z == 0.0f) { - if(from.z > boxp2.z || from.z < boxp1.z) { + if(delta.z == 0.0f) + { + if(from.z > boxp2.z || from.z < boxp1.z) + { // Ray is parallel to the planes & outside slab return false; } - } else { + } + else + { float tmp = 1.0f / delta.z; float t1 = (boxp1.z - from.z) * tmp; float t2 = (boxp2.z - from.z) * tmp; @@ -174,7 +209,8 @@ namespace CodeImp.DoomBuilder.BuilderModes tnear = t1; if(t2 < tfar) tfar = t2; - if(tnear > tfar || tfar < 0.0f) { + if(tnear > tfar || tfar < 0.0f) + { // Ray missed box or box is behind ray return false; } @@ -221,70 +257,86 @@ namespace CodeImp.DoomBuilder.BuilderModes #region ================== Events // Select or deselect - public virtual void OnSelectEnd() { - if(this.selected) { + public virtual void OnSelectEnd() + { + if(this.selected) + { this.selected = false; mode.RemoveSelectedObject(this); - } else { + } + else + { this.selected = true; mode.AddSelectedObject(this); } } // Copy properties - public virtual void OnCopyProperties() { + public virtual void OnCopyProperties() + { BuilderPlug.Me.CopiedVertexProps = new VertexProperties(vertex); mode.SetActionResult("Copied vertex properties."); } // Paste properties - public virtual void OnPasteProperties() { - if(BuilderPlug.Me.CopiedVertexProps != null) { + public virtual void OnPasteProperties() + { + if(BuilderPlug.Me.CopiedVertexProps != null) + { mode.CreateUndo("Paste vertex properties"); mode.SetActionResult("Pasted vertex properties."); BuilderPlug.Me.CopiedVertexProps.Apply(vertex); //update affected sectors - updateGeometry(vertex); + UpdateGeometry(vertex); changed = true; mode.ShowTargetInfo(); } } //Delete key pressed - remove zoffset field - public virtual void OnDelete() { + public virtual void OnDelete() + { mode.CreateUndo("Clear vertex height offset"); mode.SetActionResult("Cleared vertex height offset."); - if(ceilingVertex) { + if(ceilingVertex) + { if(float.IsNaN(vertex.ZCeiling)) return; vertex.ZCeiling = float.NaN; //update affected sectors - updateGeometry(vertex); + UpdateGeometry(vertex); changed = true; mode.ShowTargetInfo(); - } else { + } + else + { if(float.IsNaN(vertex.ZFloor)) return; vertex.ZFloor = float.NaN; //update affected sectors - updateGeometry(vertex); + UpdateGeometry(vertex); changed = true; mode.ShowTargetInfo(); } } // Edit button released - public virtual void OnEditEnd() { - if(General.Interface.IsActiveWindow) { + public virtual void OnEditEnd() + { + if(General.Interface.IsActiveWindow) + { List verts = mode.GetSelectedVertices(); updateList = new Dictionary(); - foreach(Vertex v in verts){ + foreach(Vertex v in verts) + { VertexData vd = mode.GetVertexData(v); - foreach(KeyValuePair s in vd.UpdateAlso) { - if(mode.VisualSectorExists(s.Key)) { + foreach(KeyValuePair s in vd.UpdateAlso) + { + if(mode.VisualSectorExists(s.Key)) + { BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(s.Key); updateList.Add(vs, s.Value); } @@ -303,7 +355,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - private void Interface_OnEditFormValuesChanged(object sender, System.EventArgs e) { + private void Interface_OnEditFormValuesChanged(object sender, System.EventArgs e) + { foreach(KeyValuePair group in updateList) group.Key.UpdateSectorGeometry(group.Value); @@ -312,20 +365,24 @@ namespace CodeImp.DoomBuilder.BuilderModes } // Raise/lower thing - public virtual void OnChangeTargetHeight(int amount) { + public virtual void OnChangeTargetHeight(int amount) + { if((General.Map.UndoRedo.NextUndo == null) || (General.Map.UndoRedo.NextUndo.TicketID != undoticket)) undoticket = mode.CreateUndo("Change vertex height"); - if(ceilingVertex) { - vertex.ZCeiling = (float.IsNaN(vertex.ZCeiling) ? getSectorHeight() + amount : vertex.ZCeiling + amount); + if(ceilingVertex) + { + vertex.ZCeiling = (float.IsNaN(vertex.ZCeiling) ? GetSectorHeight() + amount : vertex.ZCeiling + amount); mode.SetActionResult("Changed vertex height to " + vertex.ZCeiling + "."); - } else { - vertex.ZFloor = (float.IsNaN(vertex.ZFloor) ? getSectorHeight() + amount : vertex.ZFloor + amount); + } + else + { + vertex.ZFloor = (float.IsNaN(vertex.ZFloor) ? GetSectorHeight() + amount : vertex.ZFloor + amount); mode.SetActionResult("Changed vertex height to " + vertex.ZFloor + "."); } // Update what must be updated - updateGeometry(vertex); + UpdateGeometry(vertex); changed = true; } diff --git a/Source/Plugins/BuilderModes/VisualModes/EffectPlaneCopySlope.cs b/Source/Plugins/BuilderModes/VisualModes/EffectPlaneCopySlope.cs index da06f84d..d7c7a5a6 100644 --- a/Source/Plugins/BuilderModes/VisualModes/EffectPlaneCopySlope.cs +++ b/Source/Plugins/BuilderModes/VisualModes/EffectPlaneCopySlope.cs @@ -8,19 +8,22 @@ namespace CodeImp.DoomBuilder.BuilderModes private readonly Linedef linedef; private readonly bool front; - public EffectPlaneCopySlope(SectorData data, Linedef sourcelinedef, bool front) : base(data) { + public EffectPlaneCopySlope(SectorData data, Linedef sourcelinedef, bool front) : base(data) + { this.linedef = sourcelinedef; this.front = front; // New effect added: This sector needs an update! - if(data.Mode.VisualSectorExists(data.Sector)) { + if(data.Mode.VisualSectorExists(data.Sector)) + { BaseVisualSector vs = (BaseVisualSector)data.Mode.GetVisualSector(data.Sector); vs.UpdateSectorGeometry(true); } } // This makes sure we are updated with the source linedef information - public override void Update() { + public override void Update() + { Sector sourcesector = null; SectorData sourcesectordata = null; @@ -30,15 +33,19 @@ namespace CodeImp.DoomBuilder.BuilderModes int ceilingArg = (front ? 1 : 3); //find sector to align floor to - if(linedef.Args[floorArg] > 0) { - foreach(Sector s in General.Map.Map.Sectors) { - if(s.Tag == linedef.Args[floorArg]) { + if(linedef.Args[floorArg] > 0) + { + foreach(Sector s in General.Map.Map.Sectors) + { + if(s.Tag == linedef.Args[floorArg]) + { sourcesector = s; break; } } - if(sourcesector != null) { + if(sourcesector != null) + { sourcesectordata = data.Mode.GetSectorData(sourcesector); if(!sourcesectordata.Updated) sourcesectordata.Update(); @@ -47,19 +54,24 @@ namespace CodeImp.DoomBuilder.BuilderModes } } - if(linedef.Args[ceilingArg] > 0) { + if(linedef.Args[ceilingArg] > 0) + { //find sector to align ceiling to - if(linedef.Args[ceilingArg] != linedef.Args[floorArg]) { + if(linedef.Args[ceilingArg] != linedef.Args[floorArg]) + { sourcesector = null; - foreach(Sector s in General.Map.Map.Sectors) { - if(s.Tag == linedef.Args[ceilingArg]) { + foreach(Sector s in General.Map.Map.Sectors) + { + if(s.Tag == linedef.Args[ceilingArg]) + { sourcesector = s; break; } } - if(sourcesector != null) { + if(sourcesector != null) + { sourcesectordata = data.Mode.GetSectorData(sourcesector); if(!sourcesectordata.Updated) sourcesectordata.Update(); @@ -67,7 +79,9 @@ namespace CodeImp.DoomBuilder.BuilderModes sourcesectordata.AddUpdateSector(data.Sector, true); } - } else if(sourcesector != null) { //ceiling uses the same sector as floor + } + else if(sourcesector != null) //ceiling uses the same sector as floor + { data.Ceiling.plane = sourcesectordata.Ceiling.plane; } } @@ -76,11 +90,15 @@ namespace CodeImp.DoomBuilder.BuilderModes bool copyFloor = false; bool copyCeiling = false; - if(linedef.Args[4] > 0 && linedef.Args[4] != 3 && linedef.Args[4] != 12) { - if (front) { + if(linedef.Args[4] > 0 && linedef.Args[4] != 3 && linedef.Args[4] != 12) + { + if (front) + { copyFloor = (linedef.Args[4] & 2) == 2; copyCeiling = (linedef.Args[4] & 8) == 8; - } else { + } + else + { copyFloor = (linedef.Args[4] & 1) == 1; copyCeiling = (linedef.Args[4] & 4) == 4; } @@ -94,13 +112,15 @@ namespace CodeImp.DoomBuilder.BuilderModes if(!sourcesectordata.Updated) sourcesectordata.Update(); //copy floor slope? - if(copyFloor) { + if(copyFloor) + { data.Floor.plane = sourcesectordata.Floor.plane; sourcesectordata.AddUpdateSector(data.Sector, true); } //copy ceiling slope? - if(copyCeiling) { + if(copyCeiling) + { data.Ceiling.plane = sourcesectordata.Ceiling.plane; sourcesectordata.AddUpdateSector(data.Sector, true); } diff --git a/Source/Plugins/BuilderModes/VisualModes/EffectThingSlope.cs b/Source/Plugins/BuilderModes/VisualModes/EffectThingSlope.cs index 2f5b1a51..0b0f3a9a 100644 --- a/Source/Plugins/BuilderModes/VisualModes/EffectThingSlope.cs +++ b/Source/Plugins/BuilderModes/VisualModes/EffectThingSlope.cs @@ -40,8 +40,10 @@ namespace CodeImp.DoomBuilder.BuilderModes if (t.Sector != null) { //mxd. Vertex zheight overrides this effect - if (General.Map.UDMF && t.Sector.Sidedefs.Count == 3) { - foreach(Sidedef side in t.Sector.Sidedefs) { + if (General.Map.UDMF && t.Sector.Sidedefs.Count == 3) + { + foreach(Sidedef side in t.Sector.Sidedefs) + { if(!float.IsNaN(side.Line.Start.ZFloor) || !float.IsNaN(side.Line.End.ZFloor)) return; } @@ -80,8 +82,10 @@ namespace CodeImp.DoomBuilder.BuilderModes if (t.Sector != null) { //mxd. Vertex zheight overrides this effect - if(General.Map.UDMF && t.Sector.Sidedefs.Count == 3) { - foreach(Sidedef side in t.Sector.Sidedefs) { + if(General.Map.UDMF && t.Sector.Sidedefs.Count == 3) + { + foreach(Sidedef side in t.Sector.Sidedefs) + { if(!float.IsNaN(side.Line.Start.ZCeiling) || !float.IsNaN(side.Line.End.ZCeiling)) return; } diff --git a/Source/Plugins/BuilderModes/VisualModes/EffectThingVertexSlope.cs b/Source/Plugins/BuilderModes/VisualModes/EffectThingVertexSlope.cs index abc92d12..8aa77c25 100644 --- a/Source/Plugins/BuilderModes/VisualModes/EffectThingVertexSlope.cs +++ b/Source/Plugins/BuilderModes/VisualModes/EffectThingVertexSlope.cs @@ -49,8 +49,10 @@ namespace CodeImp.DoomBuilder.BuilderModes verts[index] = new Vector3D(v.Position.x, v.Position.y, data.Ceiling.plane.GetZ(v.Position)); //mxd. UDMF vertex offset overrides this effect - if(General.Map.UDMF) { - if((slopefloor && !float.IsNaN(v.ZFloor)) || !float.IsNaN(v.ZCeiling)) { + if(General.Map.UDMF) + { + if((slopefloor && !float.IsNaN(v.ZFloor)) || !float.IsNaN(v.ZCeiling)) + { index++; continue; } diff --git a/Source/Plugins/BuilderModes/VisualModes/SectorData.cs b/Source/Plugins/BuilderModes/VisualModes/SectorData.cs index c20c0668..4ef4e7c7 100644 --- a/Source/Plugins/BuilderModes/VisualModes/SectorData.cs +++ b/Source/Plugins/BuilderModes/VisualModes/SectorData.cs @@ -248,7 +248,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public void UpdateForced() { + public void UpdateForced() + { updated = false; Update(); } diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualCeiling.cs b/Source/Plugins/BuilderModes/VisualModes/VisualCeiling.cs index 76836401..60aff033 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualCeiling.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualCeiling.cs @@ -57,7 +57,8 @@ namespace CodeImp.DoomBuilder.BuilderModes geoType = VisualGeometryType.CEILING; //mxd - if(mode.UseSelectionFromClassicMode && vs != null && vs.Sector.Selected && (General.Map.ViewMode == ViewMode.CeilingTextures || General.Map.ViewMode == ViewMode.Normal)) { + if(mode.UseSelectionFromClassicMode && vs != null && vs.Sector.Selected && (General.Map.ViewMode == ViewMode.CeilingTextures || General.Map.ViewMode == ViewMode.Normal)) + { this.selected = true; mode.AddSelectedObject(this); } @@ -67,7 +68,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This builds the geometry. Returns false when no geometry created. - public override bool Setup(SectorLevel level, Effect3DFloor extrafloor) { + public override bool Setup(SectorLevel level, Effect3DFloor extrafloor) + { return Setup(level, extrafloor, innerSide); } @@ -88,17 +90,21 @@ namespace CodeImp.DoomBuilder.BuilderModes s.Fields.GetValue("yscaleceiling", 1.0f)); //Load ceiling texture - if(s.LongCeilTexture != MapSet.EmptyLongName) { + if(s.LongCeilTexture != MapSet.EmptyLongName) + { base.Texture = General.Map.Data.GetFlatImage(s.LongCeilTexture); - if(base.Texture == null || base.Texture is UnknownImage) { + if(base.Texture == null || base.Texture is UnknownImage) + { base.Texture = General.Map.Data.UnknownTexture3D; setuponloadedtexture = s.LongCeilTexture; - } else { - if(!base.Texture.IsImageLoaded) { - setuponloadedtexture = s.LongCeilTexture; - } + } + else + { + if(!base.Texture.IsImageLoaded) setuponloadedtexture = s.LongCeilTexture; } - } else { + } + else + { // Use missing texture base.Texture = General.Map.Data.MissingTexture3D; setuponloadedtexture = 0; @@ -188,14 +194,16 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Texture scale change - protected override void ChangeTextureScale(float incrementX, float incrementY) { + protected override void ChangeTextureScale(float incrementX, float incrementY) + { Sector s = GetControlSector(); float scaleX = s.Fields.GetValue("xscaleceiling", 1.0f); float scaleY = s.Fields.GetValue("yscaleceiling", 1.0f); s.Fields.BeforeFieldsChange(); - if(incrementX != 0) { + if(incrementX != 0) + { if(scaleX + incrementX == 0) scaleX *= -1; else @@ -203,7 +211,8 @@ namespace CodeImp.DoomBuilder.BuilderModes UDMFTools.SetFloat(s.Fields, "xscaleceiling", scaleX, 1.0f); } - if(incrementY != 0) { + if(incrementY != 0) + { if(scaleY + incrementY == 0) scaleY *= -1; else @@ -212,11 +221,12 @@ namespace CodeImp.DoomBuilder.BuilderModes } //update geometry - onTextureChanged(); + OnTextureChanged(); s.UpdateNeeded = true; s.UpdateCache(); - if(s.Index != Sector.Sector.Index) { + if(s.Index != Sector.Sector.Index) + { Sector.Sector.UpdateNeeded = true; Sector.Sector.UpdateCache(); } @@ -225,17 +235,20 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnResetTextureOffset() { + public override void OnResetTextureOffset() + { if(!General.Map.UDMF) return; mode.CreateUndo("Reset texture offsets"); mode.SetActionResult("Texture offsets reset."); Sector.Sector.Fields.BeforeFieldsChange(); - string[] keys = new string[] { "xpanningceiling", "ypanningceiling", "xscaleceiling", "yscaleceiling", "rotationceiling" }; + string[] keys = new[] { "xpanningceiling", "ypanningceiling", "xscaleceiling", "yscaleceiling", "rotationceiling" }; - foreach(string key in keys){ - if(Sector.Sector.Fields.ContainsKey(key)) { + foreach(string key in keys) + { + if(Sector.Sector.Fields.ContainsKey(key)) + { Sector.Sector.Fields.Remove(key); Sector.Sector.UpdateNeeded = true; } @@ -246,7 +259,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnResetLocalTextureOffset() { + public override void OnResetLocalTextureOffset() + { OnResetTextureOffset(); } @@ -260,7 +274,7 @@ namespace CodeImp.DoomBuilder.BuilderModes SetTexture(BuilderPlug.Me.CopiedFlat); //mxd. 3D floors may need updating... - onTextureChanged(); + OnTextureChanged(); } } @@ -328,24 +342,30 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Sector brightness change - public override void OnChangeTargetBrightness(bool up) { - if (level != null && level.sector != Sector.Sector) { + public override void OnChangeTargetBrightness(bool up) + { + if (level != null && level.sector != Sector.Sector) + { int index = -1; - for (int i = 0; i < Sector.ExtraCeilings.Count; i++) { - if (Sector.ExtraCeilings[i] == this) { + for (int i = 0; i < Sector.ExtraCeilings.Count; i++) + { + if (Sector.ExtraCeilings[i] == this) + { index = i + 1; break; } } - if (index > -1 && index < Sector.ExtraCeilings.Count) { + if (index > -1 && index < Sector.ExtraCeilings.Count) ((BaseVisualSector)mode.GetVisualSector(Sector.ExtraCeilings[index].level.sector)).Floor.OnChangeTargetBrightness(up); - } else { + else base.OnChangeTargetBrightness(up); - } - } else { + } + else + { //if a map is not in UDMF format, or this ceiling is part of 3D-floor... - if(!General.Map.UDMF || Sector.Sector != level.sector) { + if(!General.Map.UDMF || Sector.Sector != level.sector) + { base.OnChangeTargetBrightness(up); return; } @@ -535,25 +555,34 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public void AlignTexture(bool alignx, bool aligny) { + public void AlignTexture(bool alignx, bool aligny) + { if(!General.Map.UDMF) return; //is is a surface with line slope? float slopeAngle = level.plane.Normal.GetAngleZ() - Angle2D.PIHALF; - if(slopeAngle == 0) {//it's a horizontal plane - alignTextureToClosestLine(alignx, aligny); - } else { //it can be a surface with line slope + if(slopeAngle == 0) //it's a horizontal plane + { + AlignTextureToClosestLine(alignx, aligny); + } + else //it can be a surface with line slope + { Linedef slopeSource = null; bool isFront = false; - foreach(Sidedef side in Sector.Sector.Sidedefs) { - if(side.Line.Action == 181) { - if(side.Line.Args[1] == 1 && side.Line.Front != null && side.Line.Front == side) { + foreach(Sidedef side in Sector.Sector.Sidedefs) + { + if(side.Line.Action == 181) + { + if(side.Line.Args[1] == 1 && side.Line.Front != null && side.Line.Front == side) + { slopeSource = side.Line; isFront = true; break; - } else if(side.Line.Args[1] == 2 && side.Line.Back != null && side.Line.Back == side) { + } + else if(side.Line.Args[1] == 2 && side.Line.Back != null && side.Line.Back == side) + { slopeSource = side.Line; break; } @@ -561,9 +590,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } if(slopeSource != null && slopeSource.Front != null && slopeSource.Front.Sector != null && slopeSource.Back != null && slopeSource.Back.Sector != null) - alignTextureToSlopeLine(slopeSource, slopeAngle, isFront, alignx, aligny); + AlignTextureToSlopeLine(slopeSource, slopeAngle, isFront, alignx, aligny); else - alignTextureToClosestLine(alignx, aligny); + AlignTextureToClosestLine(alignx, aligny); } } diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualFloor.cs b/Source/Plugins/BuilderModes/VisualModes/VisualFloor.cs index 3ae722d1..e4021098 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualFloor.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualFloor.cs @@ -57,7 +57,9 @@ namespace CodeImp.DoomBuilder.BuilderModes geoType = VisualGeometryType.FLOOR; //mxd - if(mode.UseSelectionFromClassicMode && vs != null && vs.Sector.Selected && (General.Map.ViewMode == ViewMode.FloorTextures || General.Map.ViewMode == ViewMode.Normal)) { + if(mode.UseSelectionFromClassicMode && vs != null && vs.Sector.Selected + && (General.Map.ViewMode == ViewMode.FloorTextures || General.Map.ViewMode == ViewMode.Normal)) + { this.selected = true; mode.AddSelectedObject(this); } @@ -67,7 +69,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // This builds the geometry. Returns false when no geometry created. - public override bool Setup(SectorLevel level, Effect3DFloor extrafloor) { + public override bool Setup(SectorLevel level, Effect3DFloor extrafloor) + { return Setup(level, extrafloor, innerSide); } @@ -191,14 +194,16 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Texture scale change - protected override void ChangeTextureScale(float incrementX, float incrementY) { + protected override void ChangeTextureScale(float incrementX, float incrementY) + { Sector s = GetControlSector(); float scaleX = s.Fields.GetValue("xscalefloor", 1.0f); float scaleY = s.Fields.GetValue("yscalefloor", 1.0f); s.Fields.BeforeFieldsChange(); - if(incrementX != 0) { + if(incrementX != 0) + { if(scaleX + incrementX == 0) scaleX *= -1; else @@ -206,7 +211,8 @@ namespace CodeImp.DoomBuilder.BuilderModes UDMFTools.SetFloat(s.Fields, "xscalefloor", scaleX, 1.0f); } - if(incrementY != 0) { + if(incrementY != 0) + { if(scaleY + incrementY == 0) scaleY *= -1; else @@ -215,11 +221,12 @@ namespace CodeImp.DoomBuilder.BuilderModes } //update geometry - onTextureChanged(); + OnTextureChanged(); s.UpdateNeeded = true; s.UpdateCache(); - if(s.Index != Sector.Sector.Index) { + if(s.Index != Sector.Sector.Index) + { Sector.Sector.UpdateNeeded = true; Sector.Sector.UpdateCache(); } @@ -228,7 +235,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnResetTextureOffset() { + public override void OnResetTextureOffset() + { if(!General.Map.UDMF) return; mode.CreateUndo("Reset texture offsets"); @@ -237,8 +245,10 @@ namespace CodeImp.DoomBuilder.BuilderModes string[] keys = new string[] { "xpanningfloor", "ypanningfloor", "xscalefloor", "yscalefloor", "rotationfloor" }; - foreach(string key in keys) { - if(Sector.Sector.Fields.ContainsKey(key)) { + foreach(string key in keys) + { + if(Sector.Sector.Fields.ContainsKey(key)) + { Sector.Sector.Fields.Remove(key); Sector.Sector.UpdateNeeded = true; } @@ -249,7 +259,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnResetLocalTextureOffset() { + public override void OnResetLocalTextureOffset() + { OnResetTextureOffset(); } @@ -263,7 +274,7 @@ namespace CodeImp.DoomBuilder.BuilderModes SetTexture(BuilderPlug.Me.CopiedFlat); //mxd. 3D floors may need updating... - onTextureChanged(); + OnTextureChanged(); } } @@ -331,15 +342,19 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd. Sector brightness change - public override void OnChangeTargetBrightness(bool up) { - if (level != null) { + public override void OnChangeTargetBrightness(bool up) + { + if (level != null) + { if (level.sector != Sector.Sector) //this floor is part of 3D-floor ((BaseVisualSector)mode.GetVisualSector(level.sector)).Floor.OnChangeTargetBrightness(up); else if (Sector.ExtraFloors.Count > 0) //this is actual floor of a sector with extrafloors Sector.ExtraFloors[0].OnChangeTargetBrightness(up); else base.OnChangeTargetBrightness(up); - } else { + } + else + { base.OnChangeTargetBrightness(up); } } @@ -464,7 +479,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } // (De)select adjacent extra floors - foreach(VisualFloor ef in vs.ExtraFloors) { + foreach(VisualFloor ef in vs.ExtraFloors) + { if (select == ef.Selected || ef.extrafloor.VavoomType != regularorvavoom) continue; add = (withSameTexture && level.sector.FloorTexture == ef.level.sector.FloorTexture); @@ -502,25 +518,34 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public void AlignTexture(bool alignx, bool aligny) { + public void AlignTexture(bool alignx, bool aligny) + { if(!General.Map.UDMF) return; //is is a surface with line slope? float slopeAngle = level.plane.Normal.GetAngleZ() - Angle2D.PIHALF; - if(slopeAngle == 0) {//it's a horizontal plane - alignTextureToClosestLine(alignx, aligny); - } else { //it can be a surface with line slope + if(slopeAngle == 0) //it's a horizontal plane + { + AlignTextureToClosestLine(alignx, aligny); + } + else //it can be a surface with line slope + { Linedef slopeSource = null; bool isFront = false; - foreach(Sidedef side in Sector.Sector.Sidedefs) { - if(side.Line.Action == 181) { - if(side.Line.Args[0] == 1 && side.Line.Front != null && side.Line.Front == side) { + foreach(Sidedef side in Sector.Sector.Sidedefs) + { + if(side.Line.Action == 181) + { + if(side.Line.Args[0] == 1 && side.Line.Front != null && side.Line.Front == side) + { slopeSource = side.Line; isFront = true; break; - } else if(side.Line.Args[0] == 2 && side.Line.Back != null && side.Line.Back == side) { + } + else if(side.Line.Args[0] == 2 && side.Line.Back != null && side.Line.Back == side) + { slopeSource = side.Line; break; } @@ -528,9 +553,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } if(slopeSource != null && slopeSource.Front != null && slopeSource.Front.Sector != null && slopeSource.Back != null && slopeSource.Back.Sector != null) - alignTextureToSlopeLine(slopeSource, slopeAngle, isFront, alignx, aligny); + AlignTextureToSlopeLine(slopeSource, slopeAngle, isFront, alignx, aligny); else - alignTextureToClosestLine(alignx, aligny); + AlignTextureToClosestLine(alignx, aligny); } } diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualLower.cs b/Source/Plugins/BuilderModes/VisualModes/VisualLower.cs index c7bc41cd..4211f1ce 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualLower.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualLower.cs @@ -134,10 +134,13 @@ namespace CodeImp.DoomBuilder.BuilderModes float floorbias = (Sidedef.Other.Sector.FloorHeight == Sidedef.Sector.FloorHeight) ? 1.0f : 0.0f; if(Sidedef.Line.IsFlagSet(General.Map.Config.LowerUnpeggedFlag)) { - if(Sidedef.Sector.CeilTexture == General.Map.Config.SkyFlatName && Sidedef.Other.Sector.CeilTexture == General.Map.Config.SkyFlatName) { + if(Sidedef.Sector.CeilTexture == General.Map.Config.SkyFlatName && Sidedef.Other.Sector.CeilTexture == General.Map.Config.SkyFlatName) + { // mxd. Replicate Doom texture offset glitch when front and back sector's ceilings are sky tp.tlt.y = (float)Sidedef.Other.Sector.CeilHeight - Sidedef.Other.Sector.FloorHeight; - } else { + } + else + { // When lower unpegged is set, the lower texture is bound to the bottom tp.tlt.y = (float) Sidedef.Sector.CeilHeight - Sidedef.Other.Sector.FloorHeight; } @@ -182,27 +185,36 @@ namespace CodeImp.DoomBuilder.BuilderModes // Cut out pieces that overlap 3D floors in this sector List polygons = new List(1); polygons.Add(poly); - foreach(Effect3DFloor ef in sd.ExtraFloors) { + foreach(Effect3DFloor ef in sd.ExtraFloors) + { //mxd. Walls should be clipped by solid 3D floors - if(!ef.RenderInside && ef.Alpha == 255) { + if(!ef.RenderInside && ef.Alpha == 255) + { int num = polygons.Count; - for(int pi = 0; pi < num; pi++) { + for(int pi = 0; pi < num; pi++) + { // Split by floor plane of 3D floor WallPolygon p = polygons[pi]; WallPolygon np = SplitPoly(ref p, ef.Ceiling.plane, true); - if(np.Count > 0) { + if(np.Count > 0) + { // Split part below floor by the ceiling plane of 3D floor // and keep only the part below the ceiling (front) SplitPoly(ref np, ef.Floor.plane, true); - if(p.Count == 0) { + if(p.Count == 0) + { polygons[pi] = np; - } else { + } + else + { polygons[pi] = p; polygons.Add(np); } - } else { + } + else + { polygons[pi] = p; } } @@ -270,8 +282,8 @@ namespace CodeImp.DoomBuilder.BuilderModes float oldy = Sidedef.Fields.GetValue("offsety_bottom", 0.0f); float scalex = Sidedef.Fields.GetValue("scalex_bottom", 1.0f); float scaley = Sidedef.Fields.GetValue("scaley_bottom", 1.0f); - Sidedef.Fields["offsetx_bottom"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd - Sidedef.Fields["offsety_bottom"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldy, xy.Y, scaley, Texture != null ? Texture.Height : -1)); //mxd + Sidedef.Fields["offsetx_bottom"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd + Sidedef.Fields["offsety_bottom"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldy, xy.Y, scaley, Texture != null ? Texture.Height : -1)); //mxd } protected override Point GetTextureOffset() @@ -282,15 +294,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void ResetTextureScale() { + protected override void ResetTextureScale() + { Sidedef.Fields.BeforeFieldsChange(); if(Sidedef.Fields.ContainsKey("scalex_bottom")) Sidedef.Fields.Remove("scalex_bottom"); if(Sidedef.Fields.ContainsKey("scaley_bottom")) Sidedef.Fields.Remove("scaley_bottom"); } //mxd - public override void OnChangeTargetBrightness(bool up) { - if(!General.Map.UDMF) { + public override void OnChangeTargetBrightness(bool up) + { + if(!General.Map.UDMF) + { base.OnChangeTargetBrightness(up); return; } @@ -320,7 +335,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnTextureFit(bool fitWidth, bool fitHeight) { + public override void OnTextureFit(bool fitWidth, bool fitHeight) + { if(!General.Map.UDMF) return; if(!Sidedef.LowRequired() || string.IsNullOrEmpty(Sidedef.LowTexture) || Sidedef.LowTexture == "-" || !Texture.IsImageLoaded) return; @@ -333,13 +349,15 @@ namespace CodeImp.DoomBuilder.BuilderModes mode.CreateUndo("Fit texture (" + s + ")", UndoGroup.TextureOffsetChange, Sector.Sector.FixedIndex); Sidedef.Fields.BeforeFieldsChange(); - if(fitWidth) { + if(fitWidth) + { float scaleX = Texture.ScaledWidth / Sidedef.Line.Length; UDMFTools.SetFloat(Sidedef.Fields, "scalex_bottom", scaleX, 1.0f); UDMFTools.SetFloat(Sidedef.Fields, "offsetx_bottom", -Sidedef.OffsetX, 0.0f); } - if(fitHeight && Sidedef.Sector != null && Sidedef.Other.Sector != null) { + if(fitHeight && Sidedef.Sector != null && Sidedef.Other.Sector != null) + { float scaleY = (float)Texture.Height / (Sidedef.Other.Sector.FloorHeight - Sidedef.Sector.FloorHeight); UDMFTools.SetFloat(Sidedef.Fields, "scaley_bottom", scaleY, 1.0f); @@ -351,8 +369,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) { - selectNeighbours(Sidedef.LowTexture, select, withSameTexture, withSameHeight); + public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) + { + SelectNeighbours(Sidedef.LowTexture, select, withSameTexture, withSameHeight); } #endregion diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualMiddle3D.cs b/Source/Plugins/BuilderModes/VisualModes/VisualMiddle3D.cs index e4888d4a..e99ea39d 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualMiddle3D.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualMiddle3D.cs @@ -96,13 +96,18 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd. which texture we must use? long textureLong = 0; - if((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseUpperTexture) != 0) { + if((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseUpperTexture) != 0) + { if(Sidedef.LongHighTexture != MapSet.EmptyLongName) textureLong = Sidedef.LongHighTexture; - } else if((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseLowerTexture) != 0) { + } + else if((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseLowerTexture) != 0) + { if(Sidedef.LongLowTexture != MapSet.EmptyLongName) textureLong = Sidedef.LongLowTexture; - } else if(sourceside.LongMiddleTexture != MapSet.EmptyLongName) { + } + else if(sourceside.LongMiddleTexture != MapSet.EmptyLongName) + { textureLong = sourceside.LongMiddleTexture; } @@ -222,7 +227,8 @@ namespace CodeImp.DoomBuilder.BuilderModes foreach(Effect3DFloor ef in sd.ExtraFloors) { //mxd. Walls of solid 3D floors shouldn't be clipped by translucent 3D floors - if(extrafloor.Alpha < 255 || (!extrafloor.RenderInside && !ef.RenderInside && extrafloor.Alpha == 255 & ef.Alpha == 255)) { + if(extrafloor.Alpha < 255 || (!extrafloor.RenderInside && !ef.RenderInside && extrafloor.Alpha == 255 & ef.Alpha == 255)) + { int num = polygons.Count; for(int pi = 0; pi < num; pi++) { @@ -377,7 +383,7 @@ namespace CodeImp.DoomBuilder.BuilderModes //mxd public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) { - selectNeighbours(extrafloor.Linedef.Front.MiddleTexture, select, withSameTexture, withSameHeight); + SelectNeighbours(extrafloor.Linedef.Front.MiddleTexture, select, withSameTexture, withSameHeight); } #endregion diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualMiddleBack.cs b/Source/Plugins/BuilderModes/VisualModes/VisualMiddleBack.cs index f63c60d7..2fe1c2aa 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualMiddleBack.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualMiddleBack.cs @@ -74,27 +74,38 @@ namespace CodeImp.DoomBuilder.BuilderModes { //mxd. which texture we must use? long textureLong = 0; - if ((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseUpperTexture) != 0) { + if ((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseUpperTexture) != 0) + { if (Sidedef.Other.LongHighTexture != MapSet.EmptyLongName) textureLong = Sidedef.Other.LongHighTexture; - } else if ((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseLowerTexture) != 0) { + } + else if ((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.UseLowerTexture) != 0) + { if(Sidedef.Other.LongLowTexture != MapSet.EmptyLongName) textureLong = Sidedef.Other.LongLowTexture; - } else if ((sourceside.LongMiddleTexture != MapSet.EmptyLongName)) { + } + else if ((sourceside.LongMiddleTexture != MapSet.EmptyLongName)) + { textureLong = sourceside.LongMiddleTexture; } // Texture given? - if (textureLong != 0) { + if (textureLong != 0) + { // Load texture base.Texture = General.Map.Data.GetTextureImage(textureLong); - if(base.Texture == null || base.Texture is UnknownImage) { + if(base.Texture == null || base.Texture is UnknownImage) + { base.Texture = General.Map.Data.UnknownTexture3D; setuponloadedtexture = textureLong; - } else if (!base.Texture.IsImageLoaded) { + } + else if (!base.Texture.IsImageLoaded) + { setuponloadedtexture = textureLong; } - } else { + } + else + { // Use missing texture base.Texture = General.Map.Data.MissingTexture3D; setuponloadedtexture = 0; @@ -176,11 +187,11 @@ namespace CodeImp.DoomBuilder.BuilderModes { // Determine initial color int lightlevel; - if(((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.DisableLighting) != 0)) { + if(((sourceside.Line.Args[2] & (int)Effect3DFloor.Flags.DisableLighting) != 0)) lightlevel = lightabsolute ? lightvalue : sd.Ceiling.brightnessbelow + lightvalue; - }else{ + else lightlevel = lightabsolute ? lightvalue : sourceside.Sector.Brightness + lightvalue; - } + //mxd PixelColor wallbrightness = PixelColor.FromInt(mode.CalculateBrightness(lightlevel, Sidedef)); PixelColor wallcolor = PixelColor.Modulate(sd.Ceiling.colorbelow, wallbrightness); @@ -194,25 +205,33 @@ namespace CodeImp.DoomBuilder.BuilderModes { List polygons = new List(1); polygons.Add(poly); - foreach(Effect3DFloor ef in sd.ExtraFloors) { + foreach(Effect3DFloor ef in sd.ExtraFloors) + { int num = polygons.Count; - for(int pi = 0; pi < num; pi++) { + for(int pi = 0; pi < num; pi++) + { // Split by floor plane of 3D floor WallPolygon p = polygons[pi]; WallPolygon np = SplitPoly(ref p, ef.Ceiling.plane, true); - if(np.Count > 0) { + if(np.Count > 0) + { // Split part below floor by the ceiling plane of 3D floor // and keep only the part below the ceiling (front) SplitPoly(ref np, ef.Floor.plane, true); - if(p.Count == 0) { + if(p.Count == 0) + { polygons[pi] = np; - } else { + } + else + { polygons[pi] = p; polygons.Add(np); } - } else { + } + else + { polygons[pi] = p; } } @@ -262,7 +281,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { #region ================== Methods // Return texture name - public override string GetTextureName() { + public override string GetTextureName() + { //mxd if ((extrafloor.Linedef.Args[2] & (int)Effect3DFloor.Flags.UseUpperTexture) != 0) return Sidedef.HighTexture; @@ -272,7 +292,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { } // This changes the texture - protected override void SetTexture(string texturename) { + protected override void SetTexture(string texturename) + { //mxd if ((extrafloor.Linedef.Args[2] & (int)Effect3DFloor.Flags.UseUpperTexture) != 0) Sidedef.Other.SetTextureHigh(texturename); @@ -310,11 +331,11 @@ namespace CodeImp.DoomBuilder.BuilderModes { float oldy = Sidedef.Fields.GetValue("offsety_mid", 0.0f); float scalex = Sidedef.Fields.GetValue("scalex_mid", 1.0f); float scaley = Sidedef.Fields.GetValue("scaley_mid", 1.0f); - Sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd + Sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd //mxd. Don't clamp offsetY of clipped mid textures bool dontClamp = (Texture == null || Sidedef.IsFlagSet("clipmidtex") || Sidedef.Line.IsFlagSet("clipmidtex")); - Sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldy, xy.Y, scaley, dontClamp ? -1 : Texture.Height)); + Sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldy, xy.Y, scaley, dontClamp ? -1 : Texture.Height)); } protected override Point GetTextureOffset() @@ -325,8 +346,10 @@ namespace CodeImp.DoomBuilder.BuilderModes { } //mxd - public override void OnChangeTargetBrightness(bool up) { - if(!General.Map.UDMF) { + public override void OnChangeTargetBrightness(bool up) + { + if(!General.Map.UDMF) + { base.OnChangeTargetBrightness(up); return; } @@ -356,7 +379,8 @@ namespace CodeImp.DoomBuilder.BuilderModes { } //mxd - public override Linedef GetControlLinedef() { + public override Linedef GetControlLinedef() + { return extrafloor.Linedef; } diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualMiddleDouble.cs b/Source/Plugins/BuilderModes/VisualModes/VisualMiddleDouble.cs index 67c17e91..d2fb3b20 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualMiddleDouble.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualMiddleDouble.cs @@ -84,10 +84,13 @@ namespace CodeImp.DoomBuilder.BuilderModes Sidedef.Fields.GetValue("offsety_mid", 0.0f)); // Left and right vertices for this sidedef - if(Sidedef.IsFront) { + if(Sidedef.IsFront) + { vl = new Vector2D(Sidedef.Line.Start.Position.x, Sidedef.Line.Start.Position.y); vr = new Vector2D(Sidedef.Line.End.Position.x, Sidedef.Line.End.Position.y); - } else { + } + else + { vl = new Vector2D(Sidedef.Line.End.Position.x, Sidedef.Line.End.Position.y); vr = new Vector2D(Sidedef.Line.Start.Position.x, Sidedef.Line.Start.Position.y); } @@ -98,15 +101,21 @@ namespace CodeImp.DoomBuilder.BuilderModes if(!osd.Updated) osd.Update(); // Load texture - if(Sidedef.LongMiddleTexture != MapSet.EmptyLongName) { + if(Sidedef.LongMiddleTexture != MapSet.EmptyLongName) + { base.Texture = General.Map.Data.GetTextureImage(Sidedef.LongMiddleTexture); - if(base.Texture == null || base.Texture is UnknownImage) { + if(base.Texture == null || base.Texture is UnknownImage) + { base.Texture = General.Map.Data.UnknownTexture3D; setuponloadedtexture = Sidedef.LongMiddleTexture; - } else if (!base.Texture.IsImageLoaded) { + } + else if (!base.Texture.IsImageLoaded) + { setuponloadedtexture = Sidedef.LongMiddleTexture; } - } else { + } + else + { // Use missing texture base.Texture = General.Map.Data.MissingTexture3D; setuponloadedtexture = 0; @@ -183,8 +192,8 @@ namespace CodeImp.DoomBuilder.BuilderModes // Determine if we should repeat the middle texture repeatmidtex = Sidedef.IsFlagSet("wrapmidtex") || Sidedef.Line.IsFlagSet("wrapmidtex"); //mxd - - if(!repeatmidtex) { + if(!repeatmidtex) + { // First determine the visible portion of the texture float textop, texbottom; @@ -209,45 +218,58 @@ namespace CodeImp.DoomBuilder.BuilderModes // Cut out pieces that overlap 3D floors in this sector List polygons = new List(1); polygons.Add(poly); - foreach(Effect3DFloor ef in sd.ExtraFloors) { + foreach(Effect3DFloor ef in sd.ExtraFloors) + { //mxd. Walls should be clipped by solid 3D floors - if(!ef.RenderInside && ef.Alpha == 255) { + if(!ef.RenderInside && ef.Alpha == 255) + { int num = polygons.Count; - for(int pi = 0; pi < num; pi++) { + for(int pi = 0; pi < num; pi++) + { // Split by floor plane of 3D floor WallPolygon p = polygons[pi]; WallPolygon np = SplitPoly(ref p, ef.Ceiling.plane, true); - if(np.Count > 0) { + if(np.Count > 0) + { // Split part below floor by the ceiling plane of 3D floor // and keep only the part below the ceiling (front) SplitPoly(ref np, ef.Floor.plane, true); - if(p.Count == 0) { + if(p.Count == 0) + { polygons[pi] = np; - } else { + } + else + { polygons[pi] = p; polygons.Add(np); } - } else { + } + else + { polygons[pi] = p; } } } } - if(polygons.Count > 0) { + if(polygons.Count > 0) + { // Keep top and bottom planes for intersection testing top = osd.Ceiling.plane; bottom = osd.Floor.plane; // Process the polygon and create vertices List verts = CreatePolygonVertices(polygons, tp, sd, lightvalue, lightabsolute); - if(verts.Count > 2) { + if(verts.Count > 2) + { // Apply alpha to vertices byte alpha = SetLinedefRenderstyle(true); - if(alpha < 255) { - for(int i = 0; i < verts.Count; i++) { + if(alpha < 255) + { + for(int i = 0; i < verts.Count; i++) + { WorldVertex v = verts[i]; PixelColor c = PixelColor.FromInt(v.c); v.c = c.WithAlpha(alpha).ToInt(); @@ -315,11 +337,11 @@ namespace CodeImp.DoomBuilder.BuilderModes float oldy = Sidedef.Fields.GetValue("offsety_mid", 0.0f); float scalex = Sidedef.Fields.GetValue("scalex_mid", 1.0f); float scaley = Sidedef.Fields.GetValue("scaley_mid", 1.0f); - Sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd + Sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd //mxd. Don't clamp offsetY of clipped mid textures bool dontClamp = (Texture == null || (!Sidedef.IsFlagSet("wrapmidtex") && !Sidedef.Line.IsFlagSet("wrapmidtex"))); - Sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldy, xy.Y, scaley, dontClamp ? -1 : Texture.Height)); + Sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldy, xy.Y, scaley, dontClamp ? -1 : Texture.Height)); } protected override Point GetTextureOffset() @@ -330,15 +352,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void ResetTextureScale() { + protected override void ResetTextureScale() + { Sidedef.Fields.BeforeFieldsChange(); if(Sidedef.Fields.ContainsKey("scalex_mid")) Sidedef.Fields.Remove("scalex_mid"); if(Sidedef.Fields.ContainsKey("scaley_mid")) Sidedef.Fields.Remove("scaley_mid"); } //mxd - public override void OnChangeTargetBrightness(bool up) { - if(!General.Map.UDMF) { + public override void OnChangeTargetBrightness(bool up) + { + if(!General.Map.UDMF) + { base.OnChangeTargetBrightness(up); return; } @@ -368,7 +393,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnTextureFit(bool fitWidth, bool fitHeight) { + public override void OnTextureFit(bool fitWidth, bool fitHeight) + { if(!General.Map.UDMF) return; if(string.IsNullOrEmpty(Sidedef.MiddleTexture) || Sidedef.MiddleTexture == "-" || !Texture.IsImageLoaded) return; @@ -381,13 +407,15 @@ namespace CodeImp.DoomBuilder.BuilderModes mode.CreateUndo("Fit texture (" + s + ")", UndoGroup.TextureOffsetChange, Sector.Sector.FixedIndex); Sidedef.Fields.BeforeFieldsChange(); - if(fitWidth) { + if(fitWidth) + { float scaleX = Texture.ScaledWidth / Sidedef.Line.Length; UDMFTools.SetFloat(Sidedef.Fields, "scalex_mid", scaleX, 1.0f); UDMFTools.SetFloat(Sidedef.Fields, "offsetx_mid", -Sidedef.OffsetX, 0.0f); } - if(fitHeight && Sidedef.Sector != null) { + if(fitHeight && Sidedef.Sector != null) + { float scaleY = Texture.ScaledHeight / (Sidedef.Sector.CeilHeight - Sidedef.Sector.FloorHeight); UDMFTools.SetFloat(Sidedef.Fields, "scaley_mid", scaleY, 1.0f); @@ -399,8 +427,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) { - selectNeighbours(Sidedef.MiddleTexture, select, withSameTexture, withSameHeight); + public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) + { + SelectNeighbours(Sidedef.MiddleTexture, select, withSameTexture, withSameHeight); } #endregion diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualMiddleSingle.cs b/Source/Plugins/BuilderModes/VisualModes/VisualMiddleSingle.cs index f8eb270c..cdca8e46 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualMiddleSingle.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualMiddleSingle.cs @@ -184,27 +184,36 @@ namespace CodeImp.DoomBuilder.BuilderModes // Cut out pieces that overlap 3D floors in this sector List polygons = new List(1); polygons.Add(poly); - foreach(Effect3DFloor ef in sd.ExtraFloors) { + foreach(Effect3DFloor ef in sd.ExtraFloors) + { //mxd. Walls should be clipped by solid 3D floors - if(!ef.RenderInside && ef.Alpha == 255) { + if(!ef.RenderInside && ef.Alpha == 255) + { int num = polygons.Count; - for(int pi = 0; pi < num; pi++) { + for(int pi = 0; pi < num; pi++) + { // Split by floor plane of 3D floor WallPolygon p = polygons[pi]; WallPolygon np = SplitPoly(ref p, ef.Ceiling.plane, true); - if(np.Count > 0) { + if(np.Count > 0) + { // Split part below floor by the ceiling plane of 3D floor // and keep only the part below the ceiling (front) SplitPoly(ref np, ef.Floor.plane, true); - if(p.Count == 0) { + if(p.Count == 0) + { polygons[pi] = np; - } else { + } + else + { polygons[pi] = p; polygons.Add(np); } - } else { + } + else + { polygons[pi] = p; } } @@ -264,8 +273,8 @@ namespace CodeImp.DoomBuilder.BuilderModes float oldy = Sidedef.Fields.GetValue("offsety_mid", 0.0f); float scalex = Sidedef.Fields.GetValue("scalex_mid", 1.0f); float scaley = Sidedef.Fields.GetValue("scaley_mid", 1.0f); - Sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldx, xy.X, scalex, Texture.Width)); //mxd - Sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldy, xy.Y, scaley, Texture.Height)); //mxd + Sidedef.Fields["offsetx_mid"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldx, xy.X, scalex, Texture.Width)); //mxd + Sidedef.Fields["offsety_mid"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldy, xy.Y, scaley, Texture.Height)); //mxd } protected override Point GetTextureOffset() @@ -276,15 +285,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void ResetTextureScale() { + protected override void ResetTextureScale() + { Sidedef.Fields.BeforeFieldsChange(); if(Sidedef.Fields.ContainsKey("scalex_mid")) Sidedef.Fields.Remove("scalex_mid"); if(Sidedef.Fields.ContainsKey("scaley_mid")) Sidedef.Fields.Remove("scaley_mid"); } //mxd - public override void OnChangeTargetBrightness(bool up) { - if(!General.Map.UDMF) { + public override void OnChangeTargetBrightness(bool up) + { + if(!General.Map.UDMF) + { base.OnChangeTargetBrightness(up); return; } @@ -314,7 +326,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnTextureFit(bool fitWidth, bool fitHeight) { + public override void OnTextureFit(bool fitWidth, bool fitHeight) + { if(!General.Map.UDMF) return; if(string.IsNullOrEmpty(Sidedef.MiddleTexture) || Sidedef.MiddleTexture == "-" || !Texture.IsImageLoaded) return; @@ -327,13 +340,15 @@ namespace CodeImp.DoomBuilder.BuilderModes mode.CreateUndo("Fit texture (" + s + ")", UndoGroup.TextureOffsetChange, Sector.Sector.FixedIndex); Sidedef.Fields.BeforeFieldsChange(); - if(fitWidth) { + if(fitWidth) + { float scaleX = Texture.ScaledWidth / Sidedef.Line.Length; UDMFTools.SetFloat(Sidedef.Fields, "scalex_mid", scaleX, 1.0f); UDMFTools.SetFloat(Sidedef.Fields, "offsetx_mid", -Sidedef.OffsetX, 0.0f); } - if(fitHeight && Sidedef.Sector != null){ + if(fitHeight && Sidedef.Sector != null) + { float scaleY = Texture.ScaledHeight / (Sidedef.Sector.CeilHeight - Sidedef.Sector.FloorHeight); UDMFTools.SetFloat(Sidedef.Fields, "scaley_mid", scaleY, 1.0f); @@ -345,8 +360,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) { - selectNeighbours(Sidedef.MiddleTexture, select, withSameTexture, withSameHeight); + public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) + { + SelectNeighbours(Sidedef.MiddleTexture, select, withSameTexture, withSameHeight); } #endregion diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualSidedefParts.cs b/Source/Plugins/BuilderModes/VisualModes/VisualSidedefParts.cs index 9388e800..b8a7e10c 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualSidedefParts.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualSidedefParts.cs @@ -66,23 +66,27 @@ namespace CodeImp.DoomBuilder.BuilderModes foreach(VisualMiddle3D m in middle3d) m.Setup(); } - if(middleback != null) { + if(middleback != null) + { foreach(VisualMiddleBack m in middleback) m.Setup(); } } //mxd - public void DeselectAllParts() { + public void DeselectAllParts() + { if(lower != null) lower.Selected = false; if(middledouble != null) middledouble.Selected = false; if(middlesingle != null) middlesingle.Selected = false; if(upper != null) upper.Selected = false; - if(middle3d != null) { + if(middle3d != null) + { foreach(VisualMiddle3D m in middle3d) m.Selected = false; } - if(middleback != null) { + if(middleback != null) + { foreach(VisualMiddleBack m in middleback) m.Selected = false; } diff --git a/Source/Plugins/BuilderModes/VisualModes/VisualUpper.cs b/Source/Plugins/BuilderModes/VisualModes/VisualUpper.cs index 2c1dc471..4f6074cb 100644 --- a/Source/Plugins/BuilderModes/VisualModes/VisualUpper.cs +++ b/Source/Plugins/BuilderModes/VisualModes/VisualUpper.cs @@ -176,27 +176,36 @@ namespace CodeImp.DoomBuilder.BuilderModes // Cut out pieces that overlap 3D floors in this sector List polygons = new List(1); polygons.Add(poly); - foreach(Effect3DFloor ef in sd.ExtraFloors) { + foreach(Effect3DFloor ef in sd.ExtraFloors) + { //mxd. Walls should be clipped by solid 3D floors - if(!ef.RenderInside && ef.Alpha == 255) { + if(!ef.RenderInside && ef.Alpha == 255) + { int num = polygons.Count; - for(int pi = 0; pi < num; pi++) { + for(int pi = 0; pi < num; pi++) + { // Split by floor plane of 3D floor WallPolygon p = polygons[pi]; WallPolygon np = SplitPoly(ref p, ef.Ceiling.plane, true); - if(np.Count > 0) { + if(np.Count > 0) + { // Split part below floor by the ceiling plane of 3D floor // and keep only the part below the ceiling (front) SplitPoly(ref np, ef.Floor.plane, true); - if(p.Count == 0) { + if(p.Count == 0) + { polygons[pi] = np; - } else { + } + else + { polygons[pi] = p; polygons.Add(np); } - } else { + } + else + { polygons[pi] = p; } } @@ -264,8 +273,8 @@ namespace CodeImp.DoomBuilder.BuilderModes float oldy = Sidedef.Fields.GetValue("offsety_top", 0.0f); float scalex = Sidedef.Fields.GetValue("scalex_top", 1.0f); float scaley = Sidedef.Fields.GetValue("scaley_top", 1.0f); - Sidedef.Fields["offsetx_top"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd - Sidedef.Fields["offsety_top"] = new UniValue(UniversalType.Float, getRoundedTextureOffset(oldy, xy.Y, scaley, Texture != null ? Texture.Height : -1)); //mxd + Sidedef.Fields["offsetx_top"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldx, xy.X, scalex, Texture != null ? Texture.Width : -1)); //mxd + Sidedef.Fields["offsety_top"] = new UniValue(UniversalType.Float, GetRoundedTextureOffset(oldy, xy.Y, scaley, Texture != null ? Texture.Height : -1)); //mxd } protected override Point GetTextureOffset() @@ -276,15 +285,18 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - protected override void ResetTextureScale() { + protected override void ResetTextureScale() + { Sidedef.Fields.BeforeFieldsChange(); if(Sidedef.Fields.ContainsKey("scalex_top")) Sidedef.Fields.Remove("scalex_top"); if(Sidedef.Fields.ContainsKey("scaley_top")) Sidedef.Fields.Remove("scaley_top"); } //mxd - public override void OnChangeTargetBrightness(bool up) { - if(!General.Map.UDMF) { + public override void OnChangeTargetBrightness(bool up) + { + if(!General.Map.UDMF) + { base.OnChangeTargetBrightness(up); return; } @@ -314,7 +326,8 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void OnTextureFit(bool fitWidth, bool fitHeight) { + public override void OnTextureFit(bool fitWidth, bool fitHeight) + { if(!General.Map.UDMF) return; if(!Sidedef.HighRequired() || string.IsNullOrEmpty(Sidedef.HighTexture) || Sidedef.HighTexture == "-" || !Texture.IsImageLoaded) return; @@ -327,13 +340,15 @@ namespace CodeImp.DoomBuilder.BuilderModes mode.CreateUndo("Fit texture (" + s + ")", UndoGroup.TextureOffsetChange, Sector.Sector.FixedIndex); Sidedef.Fields.BeforeFieldsChange(); - if(fitWidth) { + if(fitWidth) + { float scaleX = Texture.ScaledWidth / Sidedef.Line.Length; UDMFTools.SetFloat(Sidedef.Fields, "scalex_top", scaleX, 1.0f); UDMFTools.SetFloat(Sidedef.Fields, "offsetx_top", -Sidedef.OffsetX, 0.0f); } - if(fitHeight && Sidedef.Sector != null && Sidedef.Other.Sector != null) { + if(fitHeight && Sidedef.Sector != null && Sidedef.Other.Sector != null) + { float scaleY = (float)Texture.Height / (Sidedef.Sector.CeilHeight - Sidedef.Other.Sector.CeilHeight); UDMFTools.SetFloat(Sidedef.Fields, "scaley_top", scaleY, 1.0f); @@ -345,8 +360,9 @@ namespace CodeImp.DoomBuilder.BuilderModes } //mxd - public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) { - selectNeighbours(Sidedef.HighTexture, select, withSameTexture, withSameHeight); + public override void SelectNeighbours(bool select, bool withSameTexture, bool withSameHeight) + { + SelectNeighbours(Sidedef.HighTexture, select, withSameTexture, withSameHeight); } #endregion diff --git a/Source/Plugins/ColorPicker/BuilderPlug.cs b/Source/Plugins/ColorPicker/BuilderPlug.cs index a943cd0d..34141a5a 100644 --- a/Source/Plugins/ColorPicker/BuilderPlug.cs +++ b/Source/Plugins/ColorPicker/BuilderPlug.cs @@ -1,10 +1,14 @@ -using System.Drawing; +#region ================== Namespaces + +using System.Drawing; using System.Windows.Forms; -using CodeImp.DoomBuilder.Windows; -using CodeImp.DoomBuilder.Plugins; using CodeImp.DoomBuilder.Actions; -using CodeImp.DoomBuilder.VisualModes; using CodeImp.DoomBuilder.ColorPicker.Windows; +using CodeImp.DoomBuilder.Plugins; +using CodeImp.DoomBuilder.VisualModes; +using CodeImp.DoomBuilder.Windows; + +#endregion namespace CodeImp.DoomBuilder.ColorPicker { @@ -22,7 +26,8 @@ namespace CodeImp.DoomBuilder.ColorPicker private Point formLocation; //used to keep form's location constant - public override void OnInitialize() { + public override void OnInitialize() + { base.OnInitialize(); me = this; @@ -32,34 +37,40 @@ namespace CodeImp.DoomBuilder.ColorPicker General.Actions.BindMethods(this); } - public override void OnMapOpenEnd() { + public override void OnMapOpenEnd() + { base.OnMapOpenEnd(); toolsform.Register(); } - public override void OnMapNewEnd() { + public override void OnMapNewEnd() + { base.OnMapNewEnd(); toolsform.Register(); } - public override void OnMapCloseEnd() { + public override void OnMapCloseEnd() + { base.OnMapCloseEnd(); toolsform.Unregister(); } - public override void OnReloadResources() { + public override void OnReloadResources() + { base.OnReloadResources(); toolsform.Register(); } - public override void Dispose() { + public override void Dispose() + { base.Dispose(); General.Actions.UnbindMethods(this); if (form != null) form.Close(); form = null; - if (toolsform != null) { + if (toolsform != null) + { toolsform.Unregister(); toolsform.Dispose(); toolsform = null; @@ -67,67 +78,87 @@ namespace CodeImp.DoomBuilder.ColorPicker } [BeginAction("togglelightpannel")] - private void toggleLightPannel() { - if (General.Editing.Mode == null) - return; - + private void ToggleLightPannel() + { + if (General.Editing.Mode == null) return; string currentModeName = General.Editing.Mode.GetType().Name; //display one of colorPickers or tell the user why we can't do that - if (currentModeName == "ThingsMode") { - if(General.Map.Map.SelectedThingsCount == 0){ + if (currentModeName == "ThingsMode") + { + if(General.Map.Map.SelectedThingsCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Select some lights first!"); return; } form = new LightColorPicker(); - - } else if (currentModeName == "SectorsMode") { - if (General.Map.UDMF) { - if (General.Map.Map.SelectedSectorsCount == 0) { + } + else if (currentModeName == "SectorsMode") + { + if (General.Map.UDMF) + { + if (General.Map.Map.SelectedSectorsCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "Select some sectors first!"); return; } form = new SectorColorPicker(); - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Sector colors can only be set if map is in UDMF format!"); return; } - - } else if (currentModeName == "BaseVisualMode") { + } + else if (currentModeName == "BaseVisualMode") + { //nothing selected in visual mode? - if ( ((VisualMode)General.Editing.Mode).GetSelectedVisualThings(true).Count == 0 ) { + if ( ((VisualMode)General.Editing.Mode).GetSelectedVisualThings(true).Count == 0 ) + { //check sectors int selectedSectorsCount = ((VisualMode)General.Editing.Mode).GetSelectedVisualSectors(true).Count; - if (General.Map.UDMF && (selectedSectorsCount > 0 || General.Map.Map.SelectedSectorsCount > 0)) { + if (General.Map.UDMF && (selectedSectorsCount > 0 || General.Map.Map.SelectedSectorsCount > 0)) + { form = new SectorColorPicker(); - } else { + } + else + { General.Interface.DisplayStatus(StatusType.Warning, "Select some lights " + (General.Map.UDMF ? ", sectors or surfaces " : "") + "first!"); return; } - } else { + } + else + { form = new LightColorPicker(); } - } else { //wrong mode + } + else //wrong mode + { General.Interface.DisplayStatus(StatusType.Warning, "Switch to" + (General.Map.UDMF ? " Sectors," : "") + " Things or GZDoom Visual Mode first!"); return; } - if (form.Setup(currentModeName)) { - if (formLocation.X == 0 && formLocation.Y == 0) { - Size displaySize = Plug.DisplaySize; - Point displayLocation = Plug.DisplayLocationAbs; + if (form.Setup(currentModeName)) + { + if (formLocation.X == 0 && formLocation.Y == 0) + { + Size displaySize = DisplaySize; + Point displayLocation = DisplayLocationAbs; formLocation = new Point(displayLocation.X + displaySize.Width - form.Width - 16, displayLocation.Y + 32); } form.Location = formLocation; form.FormClosed += form_FormClosed; form.ShowDialog(Form.ActiveForm); - } else { + } + else + { form.Dispose(); form = null; } } - private void form_FormClosed(object sender, FormClosedEventArgs e) { + private void form_FormClosed(object sender, FormClosedEventArgs e) + { formLocation = form.Location; form.Dispose(); form = null; diff --git a/Source/Plugins/ColorPicker/ColorChangedEventArgs.cs b/Source/Plugins/ColorPicker/ColorChangedEventArgs.cs index 5912b9e9..f78fe798 100644 --- a/Source/Plugins/ColorPicker/ColorChangedEventArgs.cs +++ b/Source/Plugins/ColorPicker/ColorChangedEventArgs.cs @@ -2,11 +2,13 @@ using System; namespace CodeImp.DoomBuilder.ColorPicker { - public class ColorChangedEventArgs : EventArgs { + public class ColorChangedEventArgs : EventArgs + { private ColorHandler.RGB mRGB; private ColorHandler.HSV mHSV; - public ColorChangedEventArgs(ColorHandler.RGB RGB, ColorHandler.HSV HSV) { + public ColorChangedEventArgs(ColorHandler.RGB RGB, ColorHandler.HSV HSV) + { mRGB = RGB; mHSV = HSV; } diff --git a/Source/Plugins/ColorPicker/ColorHandler.cs b/Source/Plugins/ColorPicker/ColorHandler.cs index ace87fec..77318467 100644 --- a/Source/Plugins/ColorPicker/ColorHandler.cs +++ b/Source/Plugins/ColorPicker/ColorHandler.cs @@ -3,59 +3,69 @@ using System.Drawing; namespace CodeImp.DoomBuilder.ColorPicker { - public class ColorHandler { + public class ColorHandler + { // Handle conversions between RGB and HSV // (and Color types, as well). - public struct RGB { + public struct RGB + { // All values are between 0 and 255. public int Red; public int Green; public int Blue; - public RGB(int R, int G, int B) { + public RGB(int R, int G, int B) + { Red = R; Green = G; Blue = B; } - } - public struct HSV { + public struct HSV + { // All values are between 0 and 255. public int Hue; public int Saturation; public int value; - public HSV(int H, int S, int V) { + public HSV(int H, int S, int V) + { Hue = H; Saturation = S; value = V; } - public override string ToString() { + public override string ToString() + { return String.Format("({0}, {1}, {2})", Hue, Saturation, value); } } - public static RGB HSVtoRGB(int H, int S, int V) { + public static RGB HSVtoRGB(int H, int S, int V) + { // H, S, and V must all be between 0 and 255. return HSVtoRGB(new HSV(H, S, V)); } - public static Color HSVtoColor(HSV hsv) { + public static Color HSVtoColor(HSV hsv) + { RGB RGB = HSVtoRGB(hsv); return Color.FromArgb(RGB.Red, RGB.Green, RGB.Blue); } - public static Color HSVtoColor(int H, int S, int V) { + public static Color HSVtoColor(int H, int S, int V) + { return HSVtoColor(new HSV(H, S, V)); } - public static Color RGBtoColor(RGB rgb) { + public static Color RGBtoColor(RGB rgb) + { return Color.FromArgb(rgb.Red, rgb.Green, rgb.Blue); } - public static RGB HSVtoRGB(HSV HSV) { + public static RGB HSVtoRGB(HSV HSV) + { // HSV contains values scaled as in the color wheel: // that is, all from 0 to 255. @@ -78,13 +88,16 @@ namespace CodeImp.DoomBuilder.ColorPicker s = (float)HSV.Saturation / 255; v = (float)HSV.value / 255; - if (s == 0) { + if (s == 0) + { // If s is 0, all colors are the same. // This is some flavor of gray. r = v; g = v; b = v; - } else { + } + else + { float p; float q; float t; @@ -111,7 +124,8 @@ namespace CodeImp.DoomBuilder.ColorPicker // Assign the fractional colors to r, g, and b // based on the sector the angle is in. - switch (sectorNumber) { + switch (sectorNumber) + { case 0: r = v; g = t; @@ -154,7 +168,8 @@ namespace CodeImp.DoomBuilder.ColorPicker return new RGB((int)(r * 255), (int)(g * 255), (int)(b * 255)); } - public static HSV RGBtoHSV(RGB RGB) { + public static HSV RGBtoHSV(RGB RGB) + { // In this function, R, G, and B values must be scaled // to be between 0 and 1. // HSV.Hue will be a value between 0 and 360, and @@ -178,20 +193,28 @@ namespace CodeImp.DoomBuilder.ColorPicker max = Math.Max(Math.Max(r, g), b); v = max; delta = max - min; - if (max == 0 || delta == 0) { + if (max == 0 || delta == 0) + { // R, G, and B must be 0, or all the same. In this case, S is 0, and H is undefined. // Using H = 0 is as good as any... s = 0; h = 0; - } else { + } + else + { s = delta / max; - if (r == max) { + if (r == max) + { // Between Yellow and Magenta h = (g - b) / delta; - } else if (g == max) { + } + else if (g == max) + { // Between Cyan and Yellow h = 2 + (b - r) / delta; - } else { + } + else + { // Between Magenta and Cyan h = 4 + (r - g) / delta; } @@ -200,9 +223,7 @@ namespace CodeImp.DoomBuilder.ColorPicker // Scale h to be between 0 and 360. // This may require adding 360, if the value is negative. h *= 60; - if (h < 0) { - h += 360; - } + if (h < 0) h += 360; // Scale to the requirements of this application. All values are between 0 and 255. return new HSV((int)(h / 360 * 255), (int)(s * 255), (int)(v * 255)); diff --git a/Source/Plugins/ColorPicker/ColorWheel.cs b/Source/Plugins/ColorPicker/ColorWheel.cs index 28261561..fbdb7477 100644 --- a/Source/Plugins/ColorPicker/ColorWheel.cs +++ b/Source/Plugins/ColorPicker/ColorWheel.cs @@ -3,8 +3,10 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; -namespace CodeImp.DoomBuilder.ColorPicker { - public sealed class ColorWheel : IDisposable { +namespace CodeImp.DoomBuilder.ColorPicker +{ + public sealed class ColorWheel : IDisposable + { // These resources should be disposed // of when you're done with them. @@ -17,7 +19,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { public ColorChangedEventHandler ColorChanged; // Keep track of the current mouse state. - public enum MouseState { + private enum MouseState + { MouseUp, ClickOnColor, DragInColor, @@ -71,13 +74,15 @@ namespace CodeImp.DoomBuilder.ColorPicker { public Color Color { get { return selectedColor; } } - public ColorWheel(Rectangle colorRectangle, Rectangle brightnessRectangle) { + public ColorWheel(Rectangle colorRectangle, Rectangle brightnessRectangle) + { // Caller must provide locations for color wheel // (colorRectangle), brightness "strip" (brightnessRectangle) // and location to display selected color (selectedColorRectangle). - using (GraphicsPath path = new GraphicsPath()) { + using (GraphicsPath path = new GraphicsPath()) + { // Store away locations for later use. this.colorRectangle = colorRectangle; this.brightnessRectangle = brightnessRectangle; @@ -132,30 +137,30 @@ namespace CodeImp.DoomBuilder.ColorPicker { } } - private void OnColorChanged(ColorHandler.RGB RGB, ColorHandler.HSV HSV) { + private void OnColorChanged(ColorHandler.RGB RGB, ColorHandler.HSV HSV) + { ColorChangedEventArgs e = new ColorChangedEventArgs(RGB, HSV); ColorChanged(this, e); } - void IDisposable.Dispose() { + void IDisposable.Dispose() + { // Dispose of graphic resources - if (colorImage != null) - colorImage.Dispose(); - if (colorRegion != null) - colorRegion.Dispose(); - if (brightnessRegion != null) - brightnessRegion.Dispose(); - if (g != null) - g.Dispose(); + if (colorImage != null) colorImage.Dispose(); + if (colorRegion != null) colorRegion.Dispose(); + if (brightnessRegion != null) brightnessRegion.Dispose(); + if (g != null) g.Dispose(); } - public void SetMouseUp() { + public void SetMouseUp() + { // Indicate that the user has // released the mouse. currentState = MouseState.MouseUp; } - public void Draw(Graphics g, ColorHandler.RGB RGB) { + public void Draw(Graphics g, ColorHandler.RGB RGB) + { // Given RGB values, calculate HSV and then update the screen. this.g = g; this.HSV = ColorHandler.RGBtoHSV(RGB); @@ -163,7 +168,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { UpdateDisplay(); } - public void Draw(Graphics g, Point mousePoint) { + public void Draw(Graphics g, Point mousePoint) + { // You've moved the mouse. // Now update the screen to match. float distance; @@ -182,17 +188,24 @@ namespace CodeImp.DoomBuilder.ColorPicker { // Store this away for later use. this.g = g; - if (currentState == MouseState.MouseUp) { - if (!mousePoint.IsEmpty) { - if (colorRegion.IsVisible(mousePoint)) { + if (currentState == MouseState.MouseUp) + { + if (!mousePoint.IsEmpty) + { + if (colorRegion.IsVisible(mousePoint)) + { // Is the mouse point within the color circle? // If so, you just clicked on the color wheel. currentState = MouseState.ClickOnColor; - } else if (brightnessRegion.IsVisible(mousePoint)) { + } + else if (brightnessRegion.IsVisible(mousePoint)) + { // Is the mouse point within the brightness area? // You clicked on the brightness area. currentState = MouseState.ClickOnBrightness; - } else { + } + else + { // Clicked outside the color and the brightness // regions. In that case, just put the // pointers back where they were. @@ -201,15 +214,19 @@ namespace CodeImp.DoomBuilder.ColorPicker { } } - switch (currentState) { + switch (currentState) + { case MouseState.ClickOnBrightness: case MouseState.DragInBrightness: // Calculate new color information // based on the brightness, which may have changed. newPoint = mousePoint; - if (newPoint.Y < brightnessMin) { + if (newPoint.Y < brightnessMin) + { newPoint.Y = brightnessMin; - } else if (newPoint.Y > brightnessMax) { + } + else if (newPoint.Y > brightnessMax) + { newPoint.Y = brightnessMax; } newBrightnessPoint = new Point(brightnessX, newPoint.Y); @@ -227,8 +244,7 @@ namespace CodeImp.DoomBuilder.ColorPicker { // Calculate x and y distance from the center, // and then calculate the angle corresponding to the // new location. - delta = new Point( - mousePoint.X - centerPoint.X, mousePoint.Y - centerPoint.Y); + delta = new Point(mousePoint.X - centerPoint.X, mousePoint.Y - centerPoint.Y); degrees = CalcDegrees(delta); // Calculate distance from the center to the new point @@ -236,8 +252,10 @@ namespace CodeImp.DoomBuilder.ColorPicker { // the Pythagorean theorem, to calculate this value. distance = (float)Math.Sqrt(delta.X * delta.X + delta.Y * delta.Y) / radius; - if (currentState == MouseState.DragInColor) { - if (distance > 1) { + if (currentState == MouseState.DragInColor) + { + if (distance > 1) + { // Mouse is down, and outside the circle, but you // were previously dragging in the color circle. // What to do? @@ -264,7 +282,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { OnColorChanged(RGB, HSV); // On the way out, set the new state. - switch (currentState) { + switch (currentState) + { case MouseState.ClickOnBrightness: currentState = MouseState.DragInBrightness; break; @@ -284,7 +303,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { UpdateDisplay(); } - private Point CalcBrightnessPoint(int brightness) { + private Point CalcBrightnessPoint(int brightness) + { // Take the value for brightness (0 to 255), scale to the // scaling used in the brightness bar, then add the value // to the bottom of the bar. return the correct point at which @@ -292,12 +312,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { return new Point(brightnessX, (int)(brightnessMax - brightness / brightnessScaling)); } - /*public void SetColor(Color c) { - fullColor = c; - UpdateDisplay(); - }*/ - - private void UpdateDisplay() { + private void UpdateDisplay() + { // Update the gradients, and place the pointers correctly based on colors and // brightness. CreateGradient(); @@ -312,7 +328,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { DrawBrightnessPointer(brightnessPoint); } - private void CalcCoordsAndUpdate(ColorHandler.HSV HSV) { + private void CalcCoordsAndUpdate(ColorHandler.HSV HSV) + { // Convert color to real-world coordinates and then calculate // the various points. HSV.Hue represents the degrees (0 to 360), // HSV.Saturation represents the radius. @@ -325,8 +342,7 @@ namespace CodeImp.DoomBuilder.ColorPicker { // calculate the point corresponding to // the selected color, on the color wheel. colorPoint = GetPoint((float)HSV.Hue / 255 * 360, - (float)HSV.Saturation / 255 * radius, - centerPoint); + (float)HSV.Saturation / 255 * radius, centerPoint); // Given the brightness (HSV.value), calculate the // point corresponding to the brightness indicator. @@ -343,30 +359,31 @@ namespace CodeImp.DoomBuilder.ColorPicker { fullColor = ColorHandler.HSVtoColor(HSV.Hue, HSV.Saturation, 255); } - private void DrawLinearGradient(Color TopColor) { + private void DrawLinearGradient(Color TopColor) + { // Given the top color, draw a linear gradient // ranging from black to the top color. Use the // brightness rectangle as the area to fill. - using (LinearGradientBrush lgb = - new LinearGradientBrush(brightnessRectangle, TopColor, - Color.Black, LinearGradientMode.Vertical)) { + using (LinearGradientBrush lgb = new LinearGradientBrush(brightnessRectangle, TopColor, + Color.Black, LinearGradientMode.Vertical)) + { g.FillRectangle(lgb, brightnessRectangle); } } - private static int CalcDegrees(Point pt) { + private static int CalcDegrees(Point pt) + { int degrees; - if (pt.X == 0) { + if (pt.X == 0) + { // The point is on the y-axis. Determine whether it's above or below the x-axis, and return the // corresponding angle. Note that the orientation of the y-coordinate is backwards. That is, // A positive Y value indicates a point BELOW the x-axis. - if (pt.Y > 0) { - degrees = 270; - } else { - degrees = 90; - } - } else { + degrees = pt.Y > 0 ? 270 : 90; + } + else + { // This value needs to be multiplied by -1 because the y-coordinate // is opposite from the normal direction here. // That is, a y-coordinate that's "higher" on the form has a lower y-value, in this coordinate @@ -376,9 +393,7 @@ namespace CodeImp.DoomBuilder.ColorPicker { // If the x-coordinate of the selected point is to the left of the center of the circle, you // need to add 180 degrees to the angle. ArcTan only gives you a value on the right-hand side // of the circle. - if (pt.X < 0) { - degrees += 180; - } + if (pt.X < 0) degrees += 180; // Ensure that the return value is between 0 and 360. degrees = (degrees + 360) % 360; @@ -386,11 +401,12 @@ namespace CodeImp.DoomBuilder.ColorPicker { return degrees; } - private void CreateGradient() { + private void CreateGradient() + { // Create a new PathGradientBrush, supplying an array of points created by calling // the GetPoints method. - using (PathGradientBrush pgb = - new PathGradientBrush(GetPoints(radius, new Point(radius, radius)))) { + using (PathGradientBrush pgb = new PathGradientBrush(GetPoints(radius, new Point(radius, radius)))) + { // Set the various properties. Note the SurroundColors property, which contains an array of points, // in a one-to-one relationship with the points that created the gradient. pgb.CenterColor = Color.White; @@ -400,19 +416,17 @@ namespace CodeImp.DoomBuilder.ColorPicker { // Create a new bitmap containing the color wheel gradient, so the // code only needs to do all this work once. Later code uses the bitmap // rather than recreating the gradient. - colorImage = new Bitmap( - colorRectangle.Width, colorRectangle.Height, - PixelFormat.Format32bppArgb); + colorImage = new Bitmap(colorRectangle.Width, colorRectangle.Height, PixelFormat.Format32bppArgb); - using (Graphics newGraphics = - Graphics.FromImage(colorImage)) { - newGraphics.FillEllipse(pgb, 0, 0, - colorRectangle.Width, colorRectangle.Height); + using (Graphics newGraphics = Graphics.FromImage(colorImage)) + { + newGraphics.FillEllipse(pgb, 0, 0, colorRectangle.Width, colorRectangle.Height); } } } - private Color[] GetColors() { + private Color[] GetColors() + { // Create an array of COLOR_COUNT colors, looping through all the hues between 0 and 255, broken // into COLOR_COUNT intervals. HSV is particularly well-suited for this, because the only value // that changes as you create colors is the Hue. @@ -423,7 +437,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { return Colors; } - private Point[] GetPoints(float radius, Point centerPoint) { + private static Point[] GetPoints(float radius, Point centerPoint) + { // Generate the array of points that describe the locations of the COLOR_COUNT colors to be // displayed on the color wheel. Point[] Points = new Point[COLOR_COUNT]; @@ -433,7 +448,8 @@ namespace CodeImp.DoomBuilder.ColorPicker { return Points; } - private static Point GetPoint(float degrees, float radius, Point centerPoint) { + private static Point GetPoint(float degrees, float radius, Point centerPoint) + { // Given the center of a circle and its radius, along // with the angle corresponding to the point, find the coordinates. // In other words, conver t from polar to rectangular coordinates. @@ -443,15 +459,16 @@ namespace CodeImp.DoomBuilder.ColorPicker { (int)(centerPoint.Y - Math.Floor(radius * Math.Sin(radians)))); } - private void DrawColorPointer(Point pt) { + private void DrawColorPointer(Point pt) + { // Given a point, draw the color selector. The constant SIZE represents half // the width -- the square will be twice this value in width and height. const int SIZE = 3; - g.DrawRectangle(Pens.Black, - pt.X - SIZE, pt.Y - SIZE, SIZE * 2, SIZE * 2); + g.DrawRectangle(Pens.Black, pt.X - SIZE, pt.Y - SIZE, SIZE * 2, SIZE * 2); } - private void DrawBrightnessPointer(Point pt) { + private void DrawBrightnessPointer(Point pt) + { // Draw a triangle for the brightness indicator that "points" at the provided point. const int HEIGHT = 10; const int WIDTH = 7; diff --git a/Source/Plugins/ColorPicker/Controls/ColorPickerControl.cs b/Source/Plugins/ColorPicker/Controls/ColorPickerControl.cs index b00f2852..4e88a6bc 100644 --- a/Source/Plugins/ColorPicker/Controls/ColorPickerControl.cs +++ b/Source/Plugins/ColorPicker/Controls/ColorPickerControl.cs @@ -1,12 +1,18 @@ -using System; +#region ================== Namespaces + +using System; using System.Drawing; using System.Windows.Forms; using System.Globalization; -namespace CodeImp.DoomBuilder.ColorPicker.Controls { - public partial class ColorPickerControl : UserControl { - - private enum ChangeStyle { +#endregion + +namespace CodeImp.DoomBuilder.ColorPicker.Controls +{ + public partial class ColorPickerControl : UserControl + { + private enum ChangeStyle + { MouseMove, RGB, None @@ -31,14 +37,15 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { private Color startColor; //events - public event EventHandler ColorChanged; + public event EventHandler OnColorChanged; public event EventHandler OnOkPressed; public event EventHandler OnCancelPressed; public Button OkButton { get { return btnOK; } } public Button CancelButton { get { return btnCancel; } } - public void Initialize(Color startColor){ + public void Initialize(Color startColor) + { this.startColor = startColor; isInUpdate = true; @@ -49,37 +56,42 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { cbColorInfo.SelectedIndex = colorInfoMode; } - private void nudValueChanged(object sender, EventArgs e) { + private void NudValueChanged(object sender, EventArgs e) + { // If the R, G, or B values change, use this code to update the HSV values and invalidate // the color wheel (so it updates the pointers). // Check the isInUpdate flag to avoid recursive events when you update the NumericUpdownControls. - if (!isInUpdate) { + if (!isInUpdate) + { changeType = ChangeStyle.RGB; RGB = new ColorHandler.RGB((int)nudRed.Value, (int)nudGreen.Value, (int)nudBlue.Value); - updateColorInfo(RGB); + UpdateColorInfo(RGB); this.Invalidate(); } } - private void setRGB(ColorHandler.RGB RGB) { + private void SetRGB(ColorHandler.RGB RGB) + { // Update the RGB values on the form, but don't trigger the ValueChanged event of the form. The isInUpdate // variable ensures that the event procedures exit without doing anything. isInUpdate = true; - updateColorInfo(RGB); + UpdateColorInfo(RGB); isInUpdate = false; } - private void updateColorInfo(ColorHandler.RGB RGB) { + private void UpdateColorInfo(ColorHandler.RGB RGB) + { this.RGB = RGB; btnOK.BackColor = ColorHandler.RGBtoColor(RGB); btnOK.ForeColor = (RGB.Red < 180 && RGB.Green < 180) ? Color.White : Color.Black; //update color info - switch (cbColorInfo.SelectedItem.ToString()) { + switch (cbColorInfo.SelectedItem.ToString()) + { case COLOR_INFO_RGB: - refreshNudValue(nudRed, RGB.Red); - refreshNudValue(nudBlue, RGB.Blue); - refreshNudValue(nudGreen, RGB.Green); + RefreshNudValue(nudRed, RGB.Red); + RefreshNudValue(nudBlue, RGB.Blue); + RefreshNudValue(nudGreen, RGB.Green); break; case COLOR_INFO_HEX: @@ -110,41 +122,47 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { } //dispatch event further - EventHandler handler = ColorChanged; + EventHandler handler = OnColorChanged; if (handler != null) handler(this, new ColorChangedEventArgs(RGB, ColorHandler.RGBtoHSV(RGB))); } - private void updateCancelButton(ColorHandler.RGB RGB) { + private void UpdateCancelButton(ColorHandler.RGB RGB) + { btnCancel.BackColor = ColorHandler.RGBtoColor(RGB); btnCancel.ForeColor = (RGB.Red < 180 && RGB.Green < 180) ? Color.White : Color.Black; } - private static void refreshNudValue(NumericUpDown nud, int value) { + private static void RefreshNudValue(NumericUpDown nud, int value) + { // Update the value of the NumericUpDown control, if the value is different than the current value. // Refresh the control, causing an immediate repaint. - if (nud.Value != value) { + if (nud.Value != value) + { nud.Value = value; nud.Refresh(); } } - public void SetCurrentColor(Color c) { + public void SetCurrentColor(Color c) + { isInUpdate = true; changeType = ChangeStyle.RGB; RGB = new ColorHandler.RGB(c.R, c.G, c.B); - updateColorInfo(RGB); + UpdateColorInfo(RGB); isInUpdate = false; this.Invalidate(); } - public void SetInitialColor(Color c) { - updateCancelButton(new ColorHandler.RGB(c.R, c.G, c.B)); + public void SetInitialColor(Color c) + { + UpdateCancelButton(new ColorHandler.RGB(c.R, c.G, c.B)); } //events - private void ColorPickerControl_Load(object sender, EventArgs e) { + private void ColorPickerControl_Load(object sender, EventArgs e) + { // Turn on double-buffering, so the form looks better. this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.UserPaint, true); @@ -156,28 +174,33 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { // Create the new ColorWheel class, indicating the locations of the color wheel itself, the // brightness area, and the position of the selected color. colorWheel = new ColorWheel(ColorRectangle, BrightnessRectangle); - colorWheel.ColorChanged += colorChanged; + colorWheel.ColorChanged += ColorChanged; //set initial colors SetCurrentColor(startColor); - updateCancelButton(RGB); + UpdateCancelButton(RGB); } - private void ColorPickerControl_MouseDown(object sender, MouseEventArgs e) { - if (e.Button == MouseButtons.Left) { + private void ColorPickerControl_MouseDown(object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { changeType = ChangeStyle.MouseMove; selectedPoint = new Point(e.X, e.Y); this.Invalidate(); } } - private void colorChanged(object sender, ColorChangedEventArgs e) { - setRGB(e.RGB); + private void ColorChanged(object sender, ColorChangedEventArgs e) + { + SetRGB(e.RGB); } - private void onPaint(object sender, PaintEventArgs e) { + private void OnPaint(object sender, PaintEventArgs e) + { // Depending on the circumstances, force a repaint of the color wheel passing different information. - switch (changeType) { + switch (changeType) + { case ChangeStyle.MouseMove: case ChangeStyle.None: colorWheel.Draw(e.Graphics, selectedPoint); @@ -188,55 +211,65 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { } } - private void handleMouse(object sender, MouseEventArgs e) { - if (e.Button == MouseButtons.Left) { + private void HandleMouse(object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { changeType = ChangeStyle.MouseMove; selectedPoint = new Point(e.X, e.Y); this.Invalidate(); } } - private void onMouseUp(object sender, MouseEventArgs e) { + private void OnMouseUp(object sender, MouseEventArgs e) + { colorWheel.SetMouseUp(); changeType = ChangeStyle.None; } - private void onMouseUp(object sender, EventArgs e) { + private void OnMouseUp(object sender, EventArgs e) + { colorWheel.SetMouseUp(); changeType = ChangeStyle.None; } - private void btnOK_Click(object sender, EventArgs e) { + private void btnOK_Click(object sender, EventArgs e) + { //dispatch event further EventHandler handler = OnOkPressed; - if (handler != null) - handler(this, e); + if (handler != null) handler(this, e); } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object sender, EventArgs e) + { //dispatch event further EventHandler handler = OnCancelPressed; - if (handler != null) - handler(this, e); + if (handler != null) handler(this, e); } - private void cbColorInfo_SelectedIndexChanged(object sender, EventArgs e) { - if (cbColorInfo.SelectedItem.ToString() == COLOR_INFO_RGB) { + private void cbColorInfo_SelectedIndexChanged(object sender, EventArgs e) + { + if (cbColorInfo.SelectedItem.ToString() == COLOR_INFO_RGB) + { pRGB.Visible = true; tbFloatVals.Visible = false; - } else { + } + else + { pRGB.Visible = false; tbFloatVals.Visible = true; } colorInfoMode = cbColorInfo.SelectedIndex; - updateColorInfo(RGB); + UpdateColorInfo(RGB); } - private void tbFloatVals_TextChanged(object sender, EventArgs e) { + private void tbFloatVals_TextChanged(object sender, EventArgs e) + { if (isInUpdate) return; - if (COLOR_INFO[colorInfoMode].ToString() == COLOR_INFO_FLOAT) { - string[] parts = tbFloatVals.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + if (COLOR_INFO[colorInfoMode].ToString() == COLOR_INFO_FLOAT) + { + string[] parts = tbFloatVals.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 3) return; ColorHandler.RGB rgb = new ColorHandler.RGB(); @@ -252,9 +285,11 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { rgb.Blue = (int)(General.Clamp(Math.Abs(c), 0.0f, 1.0f) * 255); changeType = ChangeStyle.RGB; - updateColorInfo(rgb); + UpdateColorInfo(rgb); this.Invalidate(); - } else if (COLOR_INFO[colorInfoMode].ToString() == COLOR_INFO_HEX) { + } + else if (COLOR_INFO[colorInfoMode].ToString() == COLOR_INFO_HEX) + { string hexColor = tbFloatVals.Text.Trim().Replace("-", ""); if (hexColor.Length != 6) return; @@ -274,7 +309,7 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { rgb.Blue = color; changeType = ChangeStyle.RGB; - updateColorInfo(rgb); + UpdateColorInfo(rgb); this.Invalidate(); } } diff --git a/Source/Plugins/ColorPicker/Controls/ColorPickerControl.designer.cs b/Source/Plugins/ColorPicker/Controls/ColorPickerControl.designer.cs index c118b392..a3a91762 100644 --- a/Source/Plugins/ColorPicker/Controls/ColorPickerControl.designer.cs +++ b/Source/Plugins/ColorPicker/Controls/ColorPickerControl.designer.cs @@ -91,7 +91,7 @@ this.nudRed.Name = "nudRed"; this.nudRed.Size = new System.Drawing.Size(48, 20); this.nudRed.TabIndex = 55; - this.nudRed.ValueChanged += new System.EventHandler(this.nudValueChanged); + this.nudRed.ValueChanged += new System.EventHandler(this.NudValueChanged); // // pnlColor // @@ -131,7 +131,7 @@ this.nudBlue.Name = "nudBlue"; this.nudBlue.Size = new System.Drawing.Size(48, 20); this.nudBlue.TabIndex = 57; - this.nudBlue.ValueChanged += new System.EventHandler(this.nudValueChanged); + this.nudBlue.ValueChanged += new System.EventHandler(this.NudValueChanged); // // nudGreen // @@ -145,7 +145,7 @@ this.nudGreen.Name = "nudGreen"; this.nudGreen.Size = new System.Drawing.Size(48, 20); this.nudGreen.TabIndex = 56; - this.nudGreen.ValueChanged += new System.EventHandler(this.nudValueChanged); + this.nudGreen.ValueChanged += new System.EventHandler(this.NudValueChanged); // // Label2 // @@ -203,11 +203,11 @@ this.Name = "ColorPickerControl"; this.Size = new System.Drawing.Size(311, 183); this.Load += new System.EventHandler(this.ColorPickerControl_Load); - this.MouseLeave += new System.EventHandler(this.onMouseUp); - this.Paint += new System.Windows.Forms.PaintEventHandler(this.onPaint); - this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.handleMouse); + this.MouseLeave += new System.EventHandler(this.OnMouseUp); + this.Paint += new System.Windows.Forms.PaintEventHandler(this.OnPaint); + this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.HandleMouse); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ColorPickerControl_MouseDown); - this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.onMouseUp); + this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.OnMouseUp); ((System.ComponentModel.ISupportInitialize)(this.nudRed)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudBlue)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudGreen)).EndInit(); diff --git a/Source/Plugins/ColorPicker/Controls/ColorPickerSlider.cs b/Source/Plugins/ColorPicker/Controls/ColorPickerSlider.cs index ac4ac5e3..8e7a77fe 100644 --- a/Source/Plugins/ColorPicker/Controls/ColorPickerSlider.cs +++ b/Source/Plugins/ColorPicker/Controls/ColorPickerSlider.cs @@ -7,11 +7,9 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { private bool blockEvents; public event EventHandler OnValueChanged; - public int Value { - get - { - return (int)numericUpDown1.Value; - } + public int Value + { + get { return (int)numericUpDown1.Value; } set { blockEvents = true; @@ -21,11 +19,9 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { } private bool showLimits; - public bool ShowLimits { - get - { - return showLimits; - } + public bool ShowLimits + { + get { return showLimits; } set { showLimits = value; @@ -36,11 +32,13 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { public string Label { set { label1.Text = value; } } - public ColorPickerSlider() { + public ColorPickerSlider() + { InitializeComponent(); } - public void SetLimits(int tbMin, int tbMax, int nudMin, int nudMax) { + public void SetLimits(int tbMin, int tbMax, int nudMin, int nudMax) + { bool blockEventsStatus = blockEvents; blockEvents = true; @@ -59,19 +57,21 @@ namespace CodeImp.DoomBuilder.ColorPicker.Controls { } //events - private void trackBar1_ValueChanged(object sender, EventArgs e) { + private void trackBar1_ValueChanged(object sender, EventArgs e) + { numericUpDown1.Value = ((TrackBar)sender).Value; } - private void numericUpDown1_ValueChanged(object sender, EventArgs e) { + private void numericUpDown1_ValueChanged(object sender, EventArgs e) + { bool blockEventsStatus = blockEvents; int val = (int)((NumericUpDown)sender).Value; - if (!blockEventsStatus) { + if (!blockEventsStatus) + { EventHandler handler = OnValueChanged; - if (handler != null) - handler(this, new ColorPickerSliderEventArgs(val)); + if (handler != null) handler(this, new ColorPickerSliderEventArgs(val)); } blockEvents = true; diff --git a/Source/Plugins/ColorPicker/Controls/ColorPickerSliderEventArgs.cs b/Source/Plugins/ColorPicker/Controls/ColorPickerSliderEventArgs.cs index 9beb7347..09ebac32 100644 --- a/Source/Plugins/ColorPicker/Controls/ColorPickerSliderEventArgs.cs +++ b/Source/Plugins/ColorPicker/Controls/ColorPickerSliderEventArgs.cs @@ -1,11 +1,14 @@ using System; -namespace CodeImp.DoomBuilder.ColorPicker.Controls { - public class ColorPickerSliderEventArgs : EventArgs { +namespace CodeImp.DoomBuilder.ColorPicker.Controls +{ + public class ColorPickerSliderEventArgs : EventArgs + { private int value; public int Value { get { return value; } } - public ColorPickerSliderEventArgs(int value) { + public ColorPickerSliderEventArgs(int value) + { this.value = value; } } diff --git a/Source/Plugins/ColorPicker/Windows/LightColorPicker.cs b/Source/Plugins/ColorPicker/Windows/LightColorPicker.cs index b0a8af47..7a8d5db3 100644 --- a/Source/Plugins/ColorPicker/Windows/LightColorPicker.cs +++ b/Source/Plugins/ColorPicker/Windows/LightColorPicker.cs @@ -9,8 +9,10 @@ using CodeImp.DoomBuilder.GZBuilder; using CodeImp.DoomBuilder.VisualModes; using CodeImp.DoomBuilder.ColorPicker.Controls; -namespace CodeImp.DoomBuilder.ColorPicker.Windows { - public partial class LightColorPicker : DelayedForm, IColorPicker { +namespace CodeImp.DoomBuilder.ColorPicker.Windows +{ + public partial class LightColorPicker : DelayedForm, IColorPicker + { public ColorPickerType Type { get { return ColorPickerType.CP_LIGHT; } } private static bool RELATIVE_MODE; @@ -49,12 +51,14 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { private const int TB_ANGLE_REL_MAX = 180; //initialise pannel - public bool Setup(string editingModeName) { + public bool Setup(string editingModeName) + { this.editingModeName = editingModeName; - setupSelection(); + SetupSelection(); int selCount = selection.Count; - if (selCount == 0) { + if (selCount == 0) + { General.Interface.DisplayStatus(StatusType.Warning, "No lights found in selection!"); return false; } @@ -64,12 +68,12 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { //initialise InitializeComponent(); - setupSliders(selection[0]); - updateLightPropsFromThing(selection[0]); - setControlsMode(); + SetupSliders(selection[0]); + UpdateLightPropsFromThing(selection[0]); + SetControlsMode(); - colorPickerControl1.Initialize(getThingColor(selection[0])); - colorPickerControl1.ColorChanged += colorPickerControl1_ColorChanged; + colorPickerControl1.Initialize(GetThingColor(selection[0])); + colorPickerControl1.OnColorChanged += OnColorPickerControl1OnColorChanged; colorPickerControl1.OnOkPressed += colorPickerControl1_OnOkPressed; colorPickerControl1.OnCancelPressed += colorPickerControl1_OnCancelPressed; @@ -81,28 +85,35 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { this.Text = "Editing " + selCount + " light" + (selCount > 1 ? "s" : ""); //undo - makeUndo(this.Text); + MakeUndo(this.Text); return true; } //create selection of lights. This is called only once - private void setupSelection() { + private void SetupSelection() + { selection = new List(); //check things - if (editingModeName == "BaseVisualMode") { + if (editingModeName == "BaseVisualMode") + { visualSelection = new List(); List selectedVisualThings = ((VisualMode)General.Editing.Mode).GetSelectedVisualThings(false); - foreach (VisualThing t in selectedVisualThings) { - if (Array.IndexOf(GZGeneral.GZ_LIGHTS, t.Thing.Type) != -1) { + foreach (VisualThing t in selectedVisualThings) + { + if (Array.IndexOf(GZGeneral.GZ_LIGHTS, t.Thing.Type) != -1) + { selection.Add(t.Thing); visualSelection.Add(t); } } - } else { + } + else + { ICollection list = General.Map.Map.GetSelectedThings(true); - foreach (Thing t in list) { + foreach (Thing t in list) + { if (Array.IndexOf(GZGeneral.GZ_LIGHTS, t.Type) != -1) selection.Add(t); } @@ -111,7 +122,8 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { //set sliders count and labels based on given thing, set lightProps start values //this is called only once - private void setupSliders(Thing referenceThing) { + private void SetupSliders(Thing referenceThing) + { ThingTypeInfo typeInfo = General.Map.Data.GetThingInfoEx(referenceThing.Type); int firstArg = 3; if (referenceThing.Type == 1502 || referenceThing.Type == 1503) @@ -119,36 +131,39 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { //first slider is always used colorPickerSlider1.Label = typeInfo.Args[firstArg].Title + ":"; - colorPickerSlider1.OnValueChanged += onSliderValueChanged; + colorPickerSlider1.OnValueChanged += OnSliderValueChanged; //either both of them or none are used - if (Array.IndexOf(LIGHT_USES_ANGLE_VALUE, referenceThing.Type) != -1) { + if (Array.IndexOf(LIGHT_USES_ANGLE_VALUE, referenceThing.Type) != -1) + { showAllControls = true; colorPickerSlider2.Label = typeInfo.Args[4].Title + ":"; - colorPickerSlider2.OnValueChanged += onSliderValueChanged; + colorPickerSlider2.OnValueChanged += OnSliderValueChanged; colorPickerSlider3.Label = "Interval:"; - colorPickerSlider3.OnValueChanged += onSliderValueChanged; - } else { + colorPickerSlider3.OnValueChanged += OnSliderValueChanged; + } + else + { colorPickerSlider2.Visible = false; colorPickerSlider3.Visible = false; } //set window height int newHeight; - if (showAllControls) { + if (showAllControls) newHeight = colorPickerSlider3.Location.Y + colorPickerSlider3.Height + 8; - } else { + else newHeight = colorPickerSlider1.Location.Y + colorPickerSlider1.Height + 8; - } this.ClientSize = new Size(this.ClientSize.Width, newHeight); } //this sets lightProps values from given thing - private void updateLightPropsFromThing(Thing referenceThing) { + private void UpdateLightPropsFromThing(Thing referenceThing) + { //color - Color c = getThingColor(referenceThing); + Color c = GetThingColor(referenceThing); lightProps.Red = c.R; lightProps.Green = c.G; lightProps.Blue = c.B; @@ -161,18 +176,21 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { lightProps.PrimaryRadius = referenceThing.Args[firstArg]; //either both of them or none are used - if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, referenceThing.Type) != -1) { + if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, referenceThing.Type) != -1) + { lightProps.SecondaryRadius = referenceThing.Args[4]; lightProps.Interval = referenceThing.AngleDoom; } } //this sets lightProps values from sliders - private void updateLightPropsFromSliders() { + private void UpdateLightPropsFromSliders() + { ColorHandler.RGB curColor = colorPickerControl1.CurrentColor; bool colorChanged = false; //need this check to allow relative mode to work properly - if ((byte)curColor.Red != lightProps.Red || (byte)curColor.Green != lightProps.Green || (byte)curColor.Blue != lightProps.Blue) { + if ((byte)curColor.Red != lightProps.Red || (byte)curColor.Green != lightProps.Green || (byte)curColor.Blue != lightProps.Blue) + { lightProps.Red = (byte)curColor.Red; lightProps.Green = (byte)curColor.Green; lightProps.Blue = (byte)curColor.Blue; @@ -180,25 +198,32 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { } lightProps.PrimaryRadius = colorPickerSlider1.Value; - if (showAllControls) { + if (showAllControls) + { lightProps.SecondaryRadius = colorPickerSlider2.Value; lightProps.Interval = colorPickerSlider3.Value; } - updateSelection(colorChanged); + UpdateSelection(colorChanged); } //this sets values from lightProps to things in selection - private void updateSelection(bool colorChanged) { - for (int i = 0; i < selection.Count; i++) { + private void UpdateSelection(bool colorChanged) + { + for (int i = 0; i < selection.Count; i++) + { Thing t = selection[i]; //update color - if (colorChanged) { //need this check to allow relative mode to work properly - if (t.Type == 1503) { //Vavoom Light Color + if (colorChanged) //need this check to allow relative mode to work properly + { + if (t.Type == 1503) //Vavoom Light Color + { t.Args[1] = lightProps.Red; t.Args[2] = lightProps.Green; t.Args[3] = lightProps.Blue; - } else if (t.Type != 1502) { //vavoom light has no color settings + } + else if (t.Type != 1502) //vavoom light has no color settings + { t.Args[0] = lightProps.Red; t.Args[1] = lightProps.Green; t.Args[2] = lightProps.Blue; @@ -206,28 +231,31 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { } int firstArg = 3; - - if (t.Type == 1502 || t.Type == 1503) - firstArg = 0; + if (t.Type == 1502 || t.Type == 1503) firstArg = 0; //update radius and intensity - if (RELATIVE_MODE) { + if (RELATIVE_MODE) + { LightProps fixedVal = fixedValues[i]; t.Args[firstArg] = fixedVal.PrimaryRadius + lightProps.PrimaryRadius; if (t.Args[firstArg] < 0) t.Args[firstArg] = 0; - if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, t.Type) != -1) { + if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, t.Type) != -1) + { t.Args[4] = fixedVal.SecondaryRadius + lightProps.SecondaryRadius; if (t.Args[4] < 0) t.Args[4] = 0; t.Rotate(General.ClampAngle(fixedVal.Interval + lightProps.Interval)); } - } else { + } + else + { if (lightProps.PrimaryRadius != -1) t.Args[firstArg] = lightProps.PrimaryRadius; - if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, t.Type) != -1) { + if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, t.Type) != -1) + { t.Args[4] = lightProps.SecondaryRadius; t.Rotate(General.ClampAngle(lightProps.Interval)); } @@ -235,34 +263,39 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { } //update VisualThings - if (editingModeName == "BaseVisualMode") { + if (editingModeName == "BaseVisualMode") + { foreach (VisualThing t in visualSelection) t.UpdateLight(); } } //switch between absolute and relative mode - private void setControlsMode() { - if (RELATIVE_MODE) { - setFixedValues(); - + private void SetControlsMode() + { + if (RELATIVE_MODE) + { + SetFixedValues(); colorPickerSlider1.SetLimits(TB_REL_MIN, TB_REL_MAX, NUD_REL_MIN, NUD_REL_MAX); colorPickerSlider1.Value = 0; - if (showAllControls) { + if (showAllControls) + { colorPickerSlider2.SetLimits(TB_REL_MIN, TB_REL_MAX, NUD_REL_MIN, NUD_REL_MAX); colorPickerSlider2.Value = 0; colorPickerSlider3.SetLimits(TB_ANGLE_REL_MIN, TB_ANGLE_REL_MAX, NUD_REL_MIN, NUD_REL_MAX); colorPickerSlider3.Value = 0; } - } else { - updateLightPropsFromThing(selection[0]); - + } + else + { + UpdateLightPropsFromThing(selection[0]); colorPickerSlider1.SetLimits(TB_ABS_MIN, TB_ABS_MAX, NUD_ABS_MIN, NUD_ABS_MAX); colorPickerSlider1.Value = lightProps.PrimaryRadius; - if (showAllControls) { + if (showAllControls) + { colorPickerSlider2.SetLimits(TB_ABS_MIN, TB_ABS_MAX, NUD_ABS_MIN, NUD_ABS_MAX); colorPickerSlider2.Value = lightProps.SecondaryRadius; @@ -272,44 +305,38 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { } } - private void makeUndo(string description) { + private void MakeUndo(string description) + { General.Map.UndoRedo.CreateUndo(description); //tricky way to actually store undo information... - foreach (Thing t in selection) - t.Move(t.Position); + foreach (Thing t in selection) t.Move(t.Position); } //this is called only once - private static Color getThingColor(Thing thing) { - if (thing.Type == 1502) //vavoom light - return Color.White; - if (thing.Type == 1503) //vavoom colored light - return Color.FromArgb((byte)thing.Args[1], (byte)thing.Args[2], (byte)thing.Args[3]); + private static Color GetThingColor(Thing thing) + { + if (thing.Type == 1502) return Color.White; //vavoom light + if (thing.Type == 1503) return Color.FromArgb((byte)thing.Args[1], (byte)thing.Args[2], (byte)thing.Args[3]); //vavoom colored light return Color.FromArgb((byte)thing.Args[0], (byte)thing.Args[1], (byte)thing.Args[2]); } //this sets data to use as a reference for relative mode - private void setFixedValues() { + private void SetFixedValues() + { fixedValues = new List(); - for (int i = 0; i < selection.Count; i++) { + for (int i = 0; i < selection.Count; i++) + { Thing t = selection[i]; - //ThingTypeInfo typeInfo = General.Map.Data.GetThingInfoEx(t.Type); LightProps lp = new LightProps(); - int firstArg = 3; - if (t.Type == 1502 || t.Type == 1503) - firstArg = 0; - - //if(typeInfo.Args[firstArg].Used) - lp.PrimaryRadius = t.Args[firstArg]; - - //if(typeInfo.Args[4].Used) - //lp.SecondaryRadius = t.Args[4]; + if (t.Type == 1502 || t.Type == 1503) firstArg = 0; + lp.PrimaryRadius = t.Args[firstArg]; //either both of them or none are used - if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, t.Type) != -1) { + if (showAllControls && Array.IndexOf(LIGHT_USES_ANGLE_VALUE, t.Type) != -1) + { lp.SecondaryRadius = t.Args[4]; lp.Interval = t.AngleDoom; } @@ -319,45 +346,51 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows { } //events - private void colorPickerControl1_ColorChanged(object sender, ColorChangedEventArgs e) { + private void OnColorPickerControl1OnColorChanged(object sender, ColorChangedEventArgs e) + { //need this check to allow relative mode to work properly - if ((byte)e.RGB.Red != lightProps.Red || (byte)e.RGB.Green != lightProps.Green || (byte)e.RGB.Blue != lightProps.Blue) { - updateLightPropsFromSliders(); - } + if ((byte)e.RGB.Red != lightProps.Red || (byte)e.RGB.Green != lightProps.Green || (byte)e.RGB.Blue != lightProps.Blue) + UpdateLightPropsFromSliders(); } - private void colorPickerControl1_OnCancelPressed(object sender, EventArgs e) { + private void colorPickerControl1_OnCancelPressed(object sender, EventArgs e) + { this.DialogResult = DialogResult.Cancel; Close(); } - private void colorPickerControl1_OnOkPressed(object sender, EventArgs e) { + private void colorPickerControl1_OnOkPressed(object sender, EventArgs e) + { this.DialogResult = DialogResult.OK; General.Interface.RefreshInfo(); Close(); } - private void LightColorPicker_FormClosing(object sender, FormClosingEventArgs e) { - if(this.DialogResult == DialogResult.Cancel) - General.Map.UndoRedo.WithdrawUndo(); + private void LightColorPicker_FormClosing(object sender, FormClosingEventArgs e) + { + if(this.DialogResult == DialogResult.Cancel) General.Map.UndoRedo.WithdrawUndo(); } - private void cbRelativeMode_CheckStateChanged(object sender, EventArgs e) { + private void cbRelativeMode_CheckStateChanged(object sender, EventArgs e) + { RELATIVE_MODE = ((CheckBox)sender).Checked; - setControlsMode(); + SetControlsMode(); } - private void onSliderValueChanged(object sender, ColorPickerSliderEventArgs e) { - updateLightPropsFromSliders(); + private void OnSliderValueChanged(object sender, ColorPickerSliderEventArgs e) + { + UpdateLightPropsFromSliders(); } - private void LightColorPicker_HelpRequested(object sender, HelpEventArgs hlpevent) { + private void LightColorPicker_HelpRequested(object sender, HelpEventArgs hlpevent) + { General.ShowHelp("gzdb/features/all_modes/colorpicker.html"); hlpevent.Handled = true; } } - struct LightProps { + struct LightProps + { public byte Red; public byte Green; public byte Blue; diff --git a/Source/Plugins/ColorPicker/Windows/SectorColorPicker.cs b/Source/Plugins/ColorPicker/Windows/SectorColorPicker.cs index a67cd705..5c0462d2 100644 --- a/Source/Plugins/ColorPicker/Windows/SectorColorPicker.cs +++ b/Source/Plugins/ColorPicker/Windows/SectorColorPicker.cs @@ -27,24 +27,32 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows private static string currentColorTag = "lightcolor"; //lightcolor or fadecolor private string mode; - public bool Setup(string editingModeName) { + public bool Setup(string editingModeName) + { mode = editingModeName; - if (mode == "SectorsMode") { + if (mode == "SectorsMode") + { selection = (List)(General.Map.Map.GetSelectedSectors(true)); - } else { //should be Visual mode + } + else //should be Visual mode + { selection = new List(); VisualMode vm = (VisualMode)General.Editing.Mode; visualSelection = vm.GetSelectedVisualSectors(false); - if (visualSelection.Count > 0) { + if (visualSelection.Count > 0) + { foreach (VisualSector vs in visualSelection) selection.Add(vs.Sector); - } else { //should be some sectors selected in 2d-mode... + } + else //should be some sectors selected in 2d-mode... + { visualSelection = new List(); selection = (List)(General.Map.Map.GetSelectedSectors(true)); - foreach (Sector s in selection) { + foreach (Sector s in selection) + { if (vm.VisualSectorExists(s)) visualSelection.Add(vm.GetVisualSector(s)); } @@ -55,15 +63,15 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows string rest = selection.Count + " sector" + (selection.Count > 1 ? "s" : ""); General.Map.UndoRedo.CreateUndo("Edit color of " + rest); - foreach (Sector s in selection) - s.Fields.BeforeFieldsChange(); + foreach (Sector s in selection) s.Fields.BeforeFieldsChange(); //set colors curSectorColor = selection[0].Fields.GetValue("lightcolor", DEFAULT_LIGHT_COLOR); curFadeColor = selection[0].Fields.GetValue("fadecolor", DEFAULT_FADE_COLOR); //check that all sectors in selection have "lightcolor" and "fadecolor" fields - for (int i = 0; i < selection.Count; i++) { + for (int i = 0; i < selection.Count; i++) + { if (!selection[i].Fields.ContainsKey("lightcolor")) selection[i].Fields.Add("lightcolor", new UniValue(UniversalType.Color, curSectorColor)); @@ -77,7 +85,7 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows InitializeComponent(); colorPickerControl1.Initialize(Color.FromArgb(currentColorTag == "lightcolor" ? curSectorColor : curFadeColor)); - colorPickerControl1.ColorChanged += colorPickerControl1_ColorChanged; + colorPickerControl1.OnColorChanged += OnColorPickerControl1OnColorChanged; colorPickerControl1.OnOkPressed += colorPickerControl1_OnOkPressed; colorPickerControl1.OnCancelPressed += colorPickerControl1_OnCancelPressed; @@ -95,14 +103,17 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows return true; } - private void colorPickerControl1_OnCancelPressed(object sender, EventArgs e) { + private void colorPickerControl1_OnCancelPressed(object sender, EventArgs e) + { this.DialogResult = DialogResult.Cancel; Close(); } - private void colorPickerControl1_OnOkPressed(object sender, EventArgs e) { + private void colorPickerControl1_OnOkPressed(object sender, EventArgs e) + { //check if values are default - foreach (Sector s in selection) { + foreach (Sector s in selection) + { if((int)s.Fields["lightcolor"].Value == DEFAULT_LIGHT_COLOR) s.Fields.Remove("lightcolor"); @@ -114,30 +125,36 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows Close(); } - private void SectorColorPicker_FormClosing(object sender, FormClosingEventArgs e) { - if(this.DialogResult == DialogResult.Cancel) - General.Map.UndoRedo.WithdrawUndo(); + private void SectorColorPicker_FormClosing(object sender, FormClosingEventArgs e) + { + if(this.DialogResult == DialogResult.Cancel) General.Map.UndoRedo.WithdrawUndo(); } - private void colorPickerControl1_ColorChanged(object sender, ColorChangedEventArgs e) { - foreach (Sector s in selection) { + private void OnColorPickerControl1OnColorChanged(object sender, ColorChangedEventArgs e) + { + foreach (Sector s in selection) + { s.Fields[currentColorTag].Value = e.RGB.Red << 16 | e.RGB.Green << 8 | e.RGB.Blue; s.UpdateNeeded = true; s.UpdateCache(); } //update display - if (mode == "SectorsMode") { + if (mode == "SectorsMode") + { General.Interface.RedrawDisplay(); - } else { //should be visual mode - foreach (VisualSector vs in visualSelection) - vs.UpdateSectorData(); + } + else //should be visual mode + { + foreach (VisualSector vs in visualSelection) vs.UpdateSectorData(); } } - private void rbColor_CheckedChanged(object sender, EventArgs e) { + private void rbColor_CheckedChanged(object sender, EventArgs e) + { RadioButton b = (RadioButton)sender; - if (b.Checked) { + if (b.Checked) + { currentColorTag = (string)b.Tag; //update color picker @@ -149,7 +166,8 @@ namespace CodeImp.DoomBuilder.ColorPicker.Windows } } - private void SectorColorPicker_HelpRequested(object sender, HelpEventArgs hlpevent) { + private void SectorColorPicker_HelpRequested(object sender, HelpEventArgs hlpevent) + { General.ShowHelp("gzdb/features/all_modes/colorpicker.html"); hlpevent.Handled = true; } diff --git a/Source/Plugins/ColorPicker/Windows/ToolForm.cs b/Source/Plugins/ColorPicker/Windows/ToolForm.cs index 1743457f..61cd19b8 100644 --- a/Source/Plugins/ColorPicker/Windows/ToolForm.cs +++ b/Source/Plugins/ColorPicker/Windows/ToolForm.cs @@ -5,21 +5,25 @@ namespace CodeImp.DoomBuilder.ColorPicker { public partial class ToolsForm : Form { - public ToolsForm() { + public ToolsForm() + { InitializeComponent(); } - public void Register() { + public void Register() + { General.Interface.AddModesMenu(cpMenu, "002_modify"); General.Interface.AddModesButton(cpButton, "002_modify"); } - public void Unregister() { + public void Unregister() + { General.Interface.RemoveMenu(cpMenu); General.Interface.RemoveButton(cpButton); } - private void InvokeTaggedAction(object sender, EventArgs e) { + private void InvokeTaggedAction(object sender, EventArgs e) + { General.Interface.InvokeTaggedAction(sender, e); } } diff --git a/Source/Plugins/NodesViewer/NodesViewerMode.cs b/Source/Plugins/NodesViewer/NodesViewerMode.cs index 15c02cbf..b8da3c60 100644 --- a/Source/Plugins/NodesViewer/NodesViewerMode.cs +++ b/Source/Plugins/NodesViewer/NodesViewerMode.cs @@ -198,20 +198,24 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer } //mxd. This loads all data from the ZNODES lump - private bool LoadZNodes() { + private bool LoadZNodes() + { List supportedFormats = new List { "XNOD", "XGLN", "XGL2", "XGL3" }; - - using(MemoryStream stream = General.Map.GetLumpData("ZNODES")) { + using(MemoryStream stream = General.Map.GetLumpData("ZNODES")) + { //boilerplate... - if(stream.Length < 4) { + if(stream.Length < 4) + { MessageBox.Show("ZNODES lump is empty.", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } - using(BinaryReader reader = new BinaryReader(stream)) { + using(BinaryReader reader = new BinaryReader(stream)) + { //read signature nodesformat = new string(reader.ReadChars(4)); - if(!supportedFormats.Contains(nodesformat)) { + if(!supportedFormats.Contains(nodesformat)) + { MessageBox.Show("'" + nodesformat + "' node format is not supported.", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } @@ -220,7 +224,8 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer uint newVertsCount = reader.ReadUInt32(); //boilerplate... - if(vertsCount != General.Map.Map.Vertices.Count) { + if(vertsCount != General.Map.Map.Vertices.Count) + { MessageBox.Show("Error while reading ZNODES: vertices count in ZNODES lump (" + vertsCount + ") doesn't match with map's vertices count (" + General.Map.Map.Vertices.Count + ")!", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } @@ -228,12 +233,11 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer //add map vertices verts = new Vector2D[vertsCount + newVertsCount]; int counter = 0; - foreach(Vertex v in General.Map.Map.Vertices) { - verts[counter++] = v.Position; - } + foreach(Vertex v in General.Map.Map.Vertices) verts[counter++] = v.Position; //read extra vertices - for(int i = counter; i < counter + newVertsCount; i++) { + for(int i = counter; i < counter + newVertsCount; i++) + { verts[i].x = reader.ReadInt32() / 65536.0f; verts[i].y = reader.ReadInt32() / 65536.0f; } @@ -243,7 +247,8 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer ssectors = new Subsector[ssecCount]; int firstseg = 0; - for(int i = 0; i < ssectors.Length; i++) { + for(int i = 0; i < ssectors.Length; i++) + { ssectors[i].numsegs = (int)reader.ReadUInt32(); ssectors[i].firstseg = firstseg; firstseg += ssectors[i].numsegs; @@ -253,9 +258,11 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer uint segsCount = reader.ReadUInt32(); segs = new Seg[segsCount]; - switch(nodesformat) { + switch(nodesformat) + { case "XGLN": - for(int i = 0; i < segs.Length; i++) { + for(int i = 0; i < segs.Length; i++) + { segs[i].startvertex = (int)reader.ReadUInt32(); reader.BaseStream.Position += 4; //skip partner segs[i].lineindex = reader.ReadUInt16(); @@ -265,7 +272,8 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer case "XGL3": case "XGL2": - for(int i = 0; i < segs.Length; i++) { + for(int i = 0; i < segs.Length; i++) + { segs[i].startvertex = (int)reader.ReadUInt32(); reader.BaseStream.Position += 4; //skip partner uint lineindex = reader.ReadUInt32(); @@ -275,7 +283,8 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer break; case "XNOD": - for(int i = 0; i < segs.Length; i++) { + for(int i = 0; i < segs.Length; i++) + { segs[i].startvertex = (int)reader.ReadUInt32(); segs[i].endvertex = (int)reader.ReadUInt32(); segs[i].lineindex = reader.ReadUInt16(); @@ -285,20 +294,21 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer } //set second vertex, angle and reverse segs order - if(nodesformat == "XGLN" || nodesformat == "XGL2" || nodesformat == "XGL3") { + if(nodesformat == "XGLN" || nodesformat == "XGL2" || nodesformat == "XGL3") + { int index = 0; - foreach(Subsector ss in ssectors) { + foreach(Subsector ss in ssectors) + { //set the last vert int lastseg = ss.firstseg + ss.numsegs - 1; segs[lastseg].endvertex = segs[ss.firstseg].startvertex; //set the rest - for(int i = ss.firstseg + 1; i <= lastseg; i++) { - segs[i - 1].endvertex = segs[i].startvertex; - } + for(int i = ss.firstseg + 1; i <= lastseg; i++) segs[i - 1].endvertex = segs[i].startvertex; //set angle and subsector index - for (int i = ss.firstseg; i <= lastseg; i++) { + for (int i = ss.firstseg; i <= lastseg; i++) + { segs[i].angle = Vector2D.GetAngle(verts[segs[i].endvertex], verts[segs[i].startvertex]); segs[i].ssector = index; } @@ -311,20 +321,25 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer uint nodesCount = reader.ReadUInt32(); //boilerplate... - if(nodesCount < 1) { + if(nodesCount < 1) + { MessageBox.Show("The map has only one subsector.", "Why are you doing this, Stanley?..", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } nodes = new Node[nodesCount]; - for(int i = 0; i < nodes.Length; i++) { - if(nodesformat == "XGL3") { + for(int i = 0; i < nodes.Length; i++) + { + if(nodesformat == "XGL3") + { nodes[i].linestart.x = reader.ReadInt32() / 65536.0f; nodes[i].linestart.y = reader.ReadInt32() / 65536.0f; nodes[i].linedelta.x = reader.ReadInt32() / 65536.0f; nodes[i].linedelta.y = reader.ReadInt32() / 65536.0f; - } else { + } + else + { nodes[i].linestart.x = reader.ReadInt16(); nodes[i].linestart.y = reader.ReadInt16(); nodes[i].linedelta.x = reader.ReadInt16(); @@ -630,7 +645,8 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer /// /// This tests if the given coordinate is inside the specified subsector. /// - private bool PointInSubsector(int index, Vector2D p) { + private bool PointInSubsector(int index, Vector2D p) + { if (ssectors[index].points.Length == 0) return false; //mxd // Subsectors are convex, so we can simply test if the point is on the front side of all lines. @@ -770,32 +786,40 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer } //mxd - if(haveZnodes) { + if(haveZnodes) + { General.Interface.DisplayStatus(StatusType.Busy, "Reading map nodes..."); - if(!LoadZNodes()) { + if(!LoadZNodes()) + { General.Editing.CancelMode(); return; } - } else { - if(!haveNodes) { + } + else + { + if(!haveNodes) + { MessageBox.Show("Unable to find the NODES lump. It may be that the nodes could not be built correctly.", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); General.Editing.CancelMode(); return; } - if(!haveSectors) { + if(!haveSectors) + { MessageBox.Show("Unable to find the SSECTORS lump. It may be that the nodes could not be built correctly.", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); General.Editing.CancelMode(); return; } - if(!haveSegs) { + if(!haveSegs) + { MessageBox.Show("Unable to find the SEGS lump. It may be that the nodes could not be built correctly.", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); General.Editing.CancelMode(); return; } - if(!haveVerts) { + if(!haveVerts) + { MessageBox.Show("Unable to find the VERTEXES lump. It may be that the nodes could not be built correctly.", "Nodes Viewer mode", MessageBoxButtons.OK, MessageBoxIcon.Error); General.Editing.CancelMode(); return; @@ -805,7 +829,8 @@ namespace CodeImp.DoomBuilder.Plugins.NodesViewer LoadClassicStructures(); //mxd. More boilerplate - if (nodes.Length < 1) { + if (nodes.Length < 1) + { MessageBox.Show("The map has only one subsector.", "Why are you doing this, Stanley?..", MessageBoxButtons.OK, MessageBoxIcon.Error); General.Editing.CancelMode(); return; diff --git a/Source/Plugins/TagExplorer/BuilderPlug.cs b/Source/Plugins/TagExplorer/BuilderPlug.cs index a480dd74..6c92fd21 100644 --- a/Source/Plugins/TagExplorer/BuilderPlug.cs +++ b/Source/Plugins/TagExplorer/BuilderPlug.cs @@ -16,7 +16,8 @@ namespace CodeImp.DoomBuilder.TagExplorer public static BuilderPlug Me { get { return me; } } // This event is called when the plugin is initialized - public override void OnInitialize() { + public override void OnInitialize() + { base.OnInitialize(); // Keep a static reference @@ -24,13 +25,16 @@ namespace CodeImp.DoomBuilder.TagExplorer } // When a map is created - public override void OnMapNewEnd() { + public override void OnMapNewEnd() + { OnMapOpenEnd(); } // This is called after a map has been successfully opened - public override void OnMapOpenEnd() { - if (tagExplorer == null) { + public override void OnMapOpenEnd() + { + if (tagExplorer == null) + { tagExplorer = new TagExplorer(); docker = new Docker("tagexplorerdockerpanel", "Tag Explorer", tagExplorer); General.Interface.AddDocker(docker); @@ -39,9 +43,11 @@ namespace CodeImp.DoomBuilder.TagExplorer } // This is called after a map has been closed - public override void OnMapCloseBegin() { + public override void OnMapCloseBegin() + { // If we have a Tag Explorer panel, remove it - if (tagExplorer != null) { + if (tagExplorer != null) + { tagExplorer.Terminate(); General.Interface.RemoveDocker(docker); docker = null; @@ -51,24 +57,25 @@ namespace CodeImp.DoomBuilder.TagExplorer } // Geometry pasted - public override void OnPasteEnd(PasteOptions options) { - if (tagExplorer != null) - tagExplorer.UpdateTreeSoon(); + public override void OnPasteEnd(PasteOptions options) + { + if (tagExplorer != null) tagExplorer.UpdateTreeSoon(); } // Undo performed - public override void OnUndoEnd() { - if (tagExplorer != null) - tagExplorer.UpdateTreeSoon(); + public override void OnUndoEnd() + { + if (tagExplorer != null) tagExplorer.UpdateTreeSoon(); } // Redo performed - public override void OnRedoEnd() { - if (tagExplorer != null) - tagExplorer.UpdateTreeSoon(); + public override void OnRedoEnd() + { + if (tagExplorer != null) tagExplorer.UpdateTreeSoon(); } - public override void OnActionEnd(Actions.Action action) { + public override void OnActionEnd(Actions.Action action) + { if (tagExplorer != null && action.Name == "builder_deleteitem") tagExplorer.UpdateTreeSoon(); } diff --git a/Source/Plugins/TagExplorer/Controls/TagExplorer.cs b/Source/Plugins/TagExplorer/Controls/TagExplorer.cs index 9d4807fe..8067afe4 100644 --- a/Source/Plugins/TagExplorer/Controls/TagExplorer.cs +++ b/Source/Plugins/TagExplorer/Controls/TagExplorer.cs @@ -1,19 +1,41 @@ -using System; +#region ================== Namespaces + +using System; using System.Collections.Generic; -using System.Globalization; using System.Drawing; +using System.Globalization; +using System.IO; using System.Text; using System.Windows.Forms; -using System.IO; using CodeImp.DoomBuilder.Config; +using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Geometry; using CodeImp.DoomBuilder.IO; using CodeImp.DoomBuilder.Map; -using CodeImp.DoomBuilder.Editing; using CodeImp.DoomBuilder.Windows; +#endregion + namespace CodeImp.DoomBuilder.TagExplorer { + #region ================== Structs + + internal struct SortMode + { + public const string SORT_BY_INDEX = "By Index"; + public const string SORT_BY_TAG = "By Tag"; + public const string SORT_BY_ACTION = "By Action special"; + public static readonly object[] SORT_MODES = new object[] { SORT_BY_INDEX, SORT_BY_TAG, SORT_BY_ACTION }; + } + + internal struct SelectedNode + { + public NodeInfoType Type; + public int Index; + } + + #endregion + public sealed partial class TagExplorer : UserControl { private const string DISPLAY_TAGS_AND_ACTIONS = "Tags and Action specials"; @@ -32,9 +54,12 @@ namespace CodeImp.DoomBuilder.TagExplorer private SelectedNode selection; private static bool udmf; - internal static bool UDMF { get { return udmf; } } + internal static bool UDMF { get { return udmf; } } - public TagExplorer() { + #region ================== Constructor / Disposer + + public TagExplorer() + { InitializeComponent(); selection = new SelectedNode(); @@ -54,11 +79,14 @@ namespace CodeImp.DoomBuilder.TagExplorer udmf = (General.Map.Config.FormatInterface == "UniversalMapSetIO"); - if (udmf) { + if (udmf) + { cbCommentsOnly.Checked = General.Settings.ReadPluginSetting("commentsonly", false); toolTip1.SetToolTip(tbSearch, "Enter text to find comment\r\nEnter # + tag number to show only specified tag. Example: #667\r\nEnter $ + effect number to show only specified effect. Example: $80"); toolTip1.SetToolTip(treeView, "Double-click item to edit item's comment\r\nRight-click item to open item's Properties"); - } else { + } + else + { cbCommentsOnly.Enabled = false; toolTip1.SetToolTip(tbSearch, "Enter # + tag number to show only specified tag. Example: #667\r\nEnter $ + effect number to show only specified effect. Example: $80"); toolTip1.SetToolTip(treeView, "Right-click item to open item's Properties"); @@ -66,7 +94,8 @@ namespace CodeImp.DoomBuilder.TagExplorer } // Disposer - protected override void Dispose(bool disposing) { + protected override void Dispose(bool disposing) + { General.Settings.WritePluginSetting("sortmode", cbSortMode.SelectedIndex); General.Settings.WritePluginSetting("displaymode", cbDisplayMode.SelectedIndex); General.Settings.WritePluginSetting("centeronselected", cbCenterOnSelected.Checked); @@ -77,22 +106,30 @@ namespace CodeImp.DoomBuilder.TagExplorer base.Dispose(disposing); } - public void Setup() { + #endregion + + #region ================== Methods + + public void Setup() + { if (this.ParentForm != null) this.ParentForm.Activated += ParentForm_Activated; - updateTree(true); + UpdateTree(true); } - public void Terminate() { + public void Terminate() + { if (this.ParentForm != null) this.ParentForm.Activated -= ParentForm_Activated; } // This sets the timer to update the list very soon (because we'll have problems if we just call updateTree now) - public void UpdateTreeSoon() { + public void UpdateTreeSoon() + { updatetimer.Stop(); updatetimer.Start(); } - private void updateTree(bool focusDisplay) { + private void UpdateTree(bool focusDisplay) + { bool showTags = (currentDisplayMode == DISPLAY_TAGS || currentDisplayMode == DISPLAY_TAGS_AND_ACTIONS); bool showActions = (currentDisplayMode == DISPLAY_ACTIONS || currentDisplayMode == DISPLAY_TAGS_AND_ACTIONS); bool hasComment; @@ -101,7 +138,7 @@ namespace CodeImp.DoomBuilder.TagExplorer int filteredTag = -1; int filteredAction = -1; - getSpecialValues(serachStr, ref filteredTag, ref filteredAction); + GetSpecialValues(serachStr, ref filteredTag, ref filteredAction); if (!udmf || filteredTag != -1 || filteredAction != -1) serachStr = ""; @@ -113,25 +150,27 @@ namespace CodeImp.DoomBuilder.TagExplorer List nodes = new List(); //add things - if(General.Map.FormatInterface.HasThingAction || General.Map.FormatInterface.HasThingTag) { + if(General.Map.FormatInterface.HasThingAction || General.Map.FormatInterface.HasThingTag) + { ICollection things = General.Map.Map.Things; - if(!(things is MapElementCollection)) { //don't want to enumerate when array is locked - foreach(Thing t in things) { - if((showTags && t.Tag != 0) || (showActions && t.Action > 0)) { - if(filteredTag != -1 && t.Tag != filteredTag) - continue; - if(filteredAction != -1 && t.Action != filteredAction) - continue; + if(!(things is MapElementCollection)) //don't want to enumerate when array is locked + { + foreach(Thing t in things) + { + if((showTags && t.Tag != 0) || (showActions && t.Action > 0)) + { + if(filteredTag != -1 && t.Tag != filteredTag) continue; + if(filteredAction != -1 && t.Action != filteredAction) continue; NodeInfo info = new NodeInfo(t); string name = info.GetName(ref comment, currentSortMode); hasComment = comment.Length > 0; - if(!hasComment && cbCommentsOnly.Checked) - continue; + if(!hasComment && cbCommentsOnly.Checked) continue; - if(!udmf || serachStr.Length == 0 || (hasComment && comment.ToLowerInvariant().IndexOf(serachStr) != -1)) { + if(!udmf || serachStr.Length == 0 || (hasComment && comment.ToLowerInvariant().IndexOf(serachStr) != -1)) + { TreeNode node = new TreeNode(name, 1, 1); node.Tag = info; if(hasComment) node.ForeColor = commentColor; @@ -144,18 +183,22 @@ namespace CodeImp.DoomBuilder.TagExplorer } //sort nodes - sort(ref nodes, currentSortMode); + Sort(ref nodes, currentSortMode); //add "things" category - if(nodes.Count > 0) { - if(currentSortMode == SortMode.SORT_BY_ACTION) { //create action categories + if(nodes.Count > 0) + { + if(currentSortMode == SortMode.SORT_BY_ACTION) //create action categories + { Dictionary categories = new Dictionary(); TreeNode noAction = new TreeNode("No Action", 0, 0); - foreach(TreeNode node in nodes) { + foreach(TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; - if(nodeInfo.Action == 0) { + if(nodeInfo.Action == 0) + { noAction.Nodes.Add(node); continue; } @@ -172,23 +215,28 @@ namespace CodeImp.DoomBuilder.TagExplorer categories.Values.CopyTo(catNodes, 0); TreeNode category = new TreeNode(CAT_THINGS, 0, 0, catNodes); - if(noAction.Nodes.Count > 0) - category.Nodes.Add(noAction); + if(noAction.Nodes.Count > 0) category.Nodes.Add(noAction); treeView.Nodes.Add(category); - } else if(currentSortMode == SortMode.SORT_BY_INDEX) { //create thing categories + } + else if(currentSortMode == SortMode.SORT_BY_INDEX) //create thing categories + { Dictionary categories = new Dictionary(StringComparer.Ordinal); - foreach(TreeNode node in nodes) { + foreach(TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; ThingTypeInfo tti = General.Map.Data.GetThingInfoEx(General.Map.Map.GetThingByIndex(nodeInfo.Index).Type); - if(tti != null) { + if(tti != null) + { if(!categories.ContainsKey(tti.Category.Title)) categories.Add(tti.Category.Title, new TreeNode(tti.Category.Title, 0, 0, new[] { node })); else categories[tti.Category.Title].Nodes.Add(node); - } else { + } + else + { if(!categories.ContainsKey("UNKNOWN")) categories.Add("UNKNOWN", new TreeNode("UNKNOWN", 0, 0, new[] { node })); else @@ -200,25 +248,32 @@ namespace CodeImp.DoomBuilder.TagExplorer treeView.Nodes.Add(new TreeNode(CAT_THINGS, 0, 0, catNodes)); - } else { //sort by tag + } + else //sort by tag + { Dictionary categories = new Dictionary(); TreeNode noTag = new TreeNode("No Tag", 0, 0); - foreach(TreeNode node in nodes) { + foreach(TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; - if(nodeInfo.Tag == 0) { + if(nodeInfo.Tag == 0) + { noTag.Nodes.Add(node); continue; } - if(!categories.ContainsKey(nodeInfo.Tag)) { + if(!categories.ContainsKey(nodeInfo.Tag)) + { string title = "Tag " + nodeInfo.Tag; if(General.Map.Options.TagLabels.ContainsKey(nodeInfo.Tag)) title += ": " + General.Map.Options.TagLabels[nodeInfo.Tag]; categories.Add(nodeInfo.Tag, new TreeNode(title, 0, 0, new TreeNode[] { node })); - } else { + } + else + { categories[nodeInfo.Tag].Nodes.Add(node); } } @@ -227,8 +282,7 @@ namespace CodeImp.DoomBuilder.TagExplorer categories.Values.CopyTo(catNodes, 0); TreeNode category = new TreeNode(CAT_THINGS, 0, 0, catNodes); - if(noTag.Nodes.Count > 0) - category.Nodes.Add(noTag); + if(noTag.Nodes.Count > 0) category.Nodes.Add(noTag); treeView.Nodes.Add(category); } @@ -240,22 +294,23 @@ namespace CodeImp.DoomBuilder.TagExplorer nodes = new List(); ICollection sectors = General.Map.Map.Sectors; - if (!(sectors is MapElementCollection)) { //don't want to enumerate when array is locked - foreach (Sector s in sectors) { - if ((showTags && s.Tag != 0) || (showActions && s.Effect > 0)) { - if (filteredTag != -1 && s.Tag != filteredTag) - continue; - if (filteredAction != -1 && s.Effect != filteredAction) - continue; + if (!(sectors is MapElementCollection)) //don't want to enumerate when array is locked + { + foreach (Sector s in sectors) + { + if ((showTags && s.Tag != 0) || (showActions && s.Effect > 0)) + { + if (filteredTag != -1 && s.Tag != filteredTag) continue; + if (filteredAction != -1 && s.Effect != filteredAction) continue; NodeInfo info = new NodeInfo(s); string name = info.GetName(ref comment, currentSortMode); hasComment = comment.Length > 0; - if (!hasComment && cbCommentsOnly.Checked) - continue; + if (!hasComment && cbCommentsOnly.Checked) continue; - if (!udmf || serachStr.Length == 0 || (hasComment && comment.ToLowerInvariant().IndexOf(serachStr) != -1)) { + if (!udmf || serachStr.Length == 0 || (hasComment && comment.ToLowerInvariant().IndexOf(serachStr) != -1)) + { TreeNode node = new TreeNode(name, 3, 3); node.Tag = info; if (hasComment) node.ForeColor = commentColor; @@ -268,18 +323,22 @@ namespace CodeImp.DoomBuilder.TagExplorer } //sort nodes - sort(ref nodes, currentSortMode); + Sort(ref nodes, currentSortMode); //add category - if (nodes.Count > 0) { - if (currentSortMode == SortMode.SORT_BY_ACTION) { + if (nodes.Count > 0) + { + if (currentSortMode == SortMode.SORT_BY_ACTION) + { Dictionary categories = new Dictionary(); TreeNode noAction = new TreeNode("No Effect", 2, 2); - foreach (TreeNode node in nodes) { + foreach (TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; - if (nodeInfo.Action == 0) { + if (nodeInfo.Action == 0) + { noAction.Nodes.Add(node); continue; } @@ -295,29 +354,35 @@ namespace CodeImp.DoomBuilder.TagExplorer categories.Values.CopyTo(catNodes, 0); TreeNode category = new TreeNode(CAT_SECTORS, 2, 2, catNodes); - if (noAction.Nodes.Count > 0) - category.Nodes.Add(noAction); + if (noAction.Nodes.Count > 0) category.Nodes.Add(noAction); treeView.Nodes.Add(category); - } else if (currentSortMode == SortMode.SORT_BY_TAG) { + } + else if (currentSortMode == SortMode.SORT_BY_TAG) + { Dictionary categories = new Dictionary(); TreeNode noTag = new TreeNode("No Tag", 2, 2); - foreach (TreeNode node in nodes) { + foreach (TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; - if (nodeInfo.Tag == 0) { + if (nodeInfo.Tag == 0) + { noTag.Nodes.Add(node); continue; } - if(!categories.ContainsKey(nodeInfo.Tag)) { + if(!categories.ContainsKey(nodeInfo.Tag)) + { string title = "Tag " + nodeInfo.Tag; if(General.Map.Options.TagLabels.ContainsKey(nodeInfo.Tag)) title += ": " + General.Map.Options.TagLabels[nodeInfo.Tag]; categories.Add(nodeInfo.Tag, new TreeNode(title, 2, 2, new TreeNode[] { node })); - } else { + } + else + { categories[nodeInfo.Tag].Nodes.Add(node); } } @@ -325,11 +390,12 @@ namespace CodeImp.DoomBuilder.TagExplorer categories.Values.CopyTo(catNodes, 0); TreeNode category = new TreeNode(CAT_SECTORS, 2, 2, catNodes); - if (noTag.Nodes.Count > 0) - category.Nodes.Add(noTag); + if (noTag.Nodes.Count > 0) category.Nodes.Add(noTag); treeView.Nodes.Add(category); - } else {//just add them as they are + } + else //just add them as they are + { treeView.Nodes.Add(new TreeNode(CAT_SECTORS, 2, 2, nodes.ToArray())); } } @@ -339,22 +405,23 @@ namespace CodeImp.DoomBuilder.TagExplorer nodes = new List(); ICollection linedefs = General.Map.Map.Linedefs; - if (!(linedefs is MapElementCollection)) { //don't want to enumerate when array is locked - foreach (Linedef l in linedefs) { - if ((showTags && l.Tag != 0) || (showActions && l.Action > 0)) { - if (filteredTag != -1 && l.Tag != filteredTag) - continue; - if (filteredAction != -1 && l.Action != filteredAction) - continue; + if (!(linedefs is MapElementCollection)) //don't want to enumerate when array is locked + { + foreach (Linedef l in linedefs) + { + if ((showTags && l.Tag != 0) || (showActions && l.Action > 0)) + { + if (filteredTag != -1 && l.Tag != filteredTag) continue; + if (filteredAction != -1 && l.Action != filteredAction) continue; NodeInfo info = new NodeInfo(l); string name = info.GetName(ref comment, currentSortMode); hasComment = comment.Length > 0; - if (!hasComment && cbCommentsOnly.Checked) - continue; + if (!hasComment && cbCommentsOnly.Checked) continue; - if (!udmf || serachStr.Length == 0 || (hasComment && comment.ToLowerInvariant().IndexOf(serachStr) != -1)) { + if (!udmf || serachStr.Length == 0 || (hasComment && comment.ToLowerInvariant().IndexOf(serachStr) != -1)) + { TreeNode node = new TreeNode(name, 5, 5); node.Tag = info; if (hasComment) node.ForeColor = commentColor; @@ -367,18 +434,22 @@ namespace CodeImp.DoomBuilder.TagExplorer } //sort nodes - sort(ref nodes, currentSortMode); + Sort(ref nodes, currentSortMode); //add category - if (nodes.Count > 0) { - if (currentSortMode == SortMode.SORT_BY_ACTION) { + if (nodes.Count > 0) + { + if (currentSortMode == SortMode.SORT_BY_ACTION) + { Dictionary categories = new Dictionary(); TreeNode noAction = new TreeNode("No Action", 4, 4); - foreach (TreeNode node in nodes) { + foreach (TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; - if (nodeInfo.Action == 0) { + if (nodeInfo.Action == 0) + { noAction.Nodes.Add(node); continue; } @@ -394,30 +465,36 @@ namespace CodeImp.DoomBuilder.TagExplorer categories.Values.CopyTo(catNodes, 0); TreeNode category = new TreeNode(CAT_LINEDEFS, 4, 4, catNodes); - if (noAction.Nodes.Count > 0) - category.Nodes.Add(noAction); + if (noAction.Nodes.Count > 0) category.Nodes.Add(noAction); treeView.Nodes.Add(category); - } else if (currentSortMode == SortMode.SORT_BY_TAG) { + } + else if (currentSortMode == SortMode.SORT_BY_TAG) + { Dictionary categories = new Dictionary(); TreeNode noTag = new TreeNode("No Tag", 4, 4); - foreach (TreeNode node in nodes) { + foreach (TreeNode node in nodes) + { NodeInfo nodeInfo = node.Tag as NodeInfo; - if (nodeInfo.Tag == 0) { + if (nodeInfo.Tag == 0) + { noTag.Nodes.Add(node); continue; } - if(!categories.ContainsKey(nodeInfo.Tag)) { + if(!categories.ContainsKey(nodeInfo.Tag)) + { string title = "Tag " + nodeInfo.Tag; if(General.Map.Options.TagLabels.ContainsKey(nodeInfo.Tag)) title += ": " + General.Map.Options.TagLabels[nodeInfo.Tag]; categories.Add(nodeInfo.Tag, new TreeNode(title, 4, 4, new TreeNode[] { node })); - } else { + } + else + { categories[nodeInfo.Tag].Nodes.Add(node); } } @@ -425,19 +502,19 @@ namespace CodeImp.DoomBuilder.TagExplorer categories.Values.CopyTo(catNodes, 0); TreeNode category = new TreeNode(CAT_LINEDEFS, 4, 4, catNodes); - if (noTag.Nodes.Count > 0) - category.Nodes.Add(noTag); + if (noTag.Nodes.Count > 0) category.Nodes.Add(noTag); treeView.Nodes.Add(category); - } else { //just add them as they are + } + else //just add them as they are + { treeView.Nodes.Add(new TreeNode(CAT_LINEDEFS, 4, 4, nodes.ToArray())); } } } //expand top level nodes - foreach (TreeNode t in treeView.Nodes) - t.Expand(); + foreach (TreeNode t in treeView.Nodes) t.Expand(); if (selectedNode != null) treeView.SelectedNode = selectedNode; @@ -454,28 +531,30 @@ namespace CodeImp.DoomBuilder.TagExplorer } //tag/action search - private void getSpecialValues(string serachStr, ref int filteredTag, ref int filteredAction) { + private static void GetSpecialValues(string serachStr, ref int filteredTag, ref int filteredAction) + { if (serachStr.Length == 0) return; int pos = serachStr.IndexOf("#"); - if (pos != -1) - filteredTag = readNumber(serachStr, pos+1); + if (pos != -1) filteredTag = ReadNumber(serachStr, pos+1); pos = serachStr.IndexOf("$"); - if (pos != -1) - filteredAction = readNumber(serachStr, pos+1); + if (pos != -1) filteredAction = ReadNumber(serachStr, pos+1); } - private static int readNumber(string serachStr, int startPoition) { + private static int ReadNumber(string serachStr, int startPoition) + { string token = ""; int pos = startPoition; - while (pos < serachStr.Length && Configuration.NUMBERS.IndexOf(serachStr[pos]) != -1) { + while (pos < serachStr.Length && Configuration.NUMBERS.IndexOf(serachStr[pos]) != -1) + { token += serachStr[pos]; pos++; } - if (token.Length > 0) { + if (token.Length > 0) + { int result; if(int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)) return result; @@ -484,17 +563,22 @@ namespace CodeImp.DoomBuilder.TagExplorer return -1; } -//sorting - private void sort(ref List nodes, string sortMode) { + #endregion + + #region ================== Sorting + + private static void Sort(ref List nodes, string sortMode) + { if(sortMode == SortMode.SORT_BY_ACTION) - nodes.Sort(sortByAction); + nodes.Sort(SortByAction); else if (sortMode == SortMode.SORT_BY_TAG) - nodes.Sort(sortByTag); + nodes.Sort(SortByTag); else - nodes.Sort(sortByIndex); + nodes.Sort(SortByIndex); } - private static int sortByAction(TreeNode t1, TreeNode t2) { + private static int SortByAction(TreeNode t1, TreeNode t2) + { NodeInfo i1 = t1.Tag as NodeInfo; NodeInfo i2 = t2.Tag as NodeInfo; @@ -505,7 +589,8 @@ namespace CodeImp.DoomBuilder.TagExplorer return -1; //should be i1 < i2 } - private static int sortByTag(TreeNode t1, TreeNode t2) { + private static int SortByTag(TreeNode t1, TreeNode t2) + { NodeInfo i1 = t1.Tag as NodeInfo; NodeInfo i2 = t2.Tag as NodeInfo; @@ -516,7 +601,8 @@ namespace CodeImp.DoomBuilder.TagExplorer return -1; //should be i1 < i2 } - private static int sortByIndex(TreeNode t1, TreeNode t2) { + private static int SortByIndex(TreeNode t1, TreeNode t2) + { NodeInfo i1 = t1.Tag as NodeInfo; NodeInfo i2 = t2.Tag as NodeInfo; @@ -525,18 +611,24 @@ namespace CodeImp.DoomBuilder.TagExplorer return -1; } -//EVENTS - private void cbDisplayMode_SelectedIndexChanged(object sender, EventArgs e) { + #endregion + + #region ================== Events + + private void cbDisplayMode_SelectedIndexChanged(object sender, EventArgs e) + { currentDisplayMode = cbDisplayMode.SelectedItem.ToString(); - updateTree(true); + UpdateTree(true); } - private void cbSortMode_SelectedIndexChanged(object sender, EventArgs e) { + private void cbSortMode_SelectedIndexChanged(object sender, EventArgs e) + { currentSortMode = cbSortMode.SelectedItem.ToString(); - updateTree(true); + UpdateTree(true); } - private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { + private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) + { NodeInfo info = e.Node.Tag as NodeInfo; if (info == null) return; @@ -544,10 +636,12 @@ namespace CodeImp.DoomBuilder.TagExplorer selection.Type = info.Type; selection.Index = info.Index; - if (e.Button == MouseButtons.Right) { //open element properties + if (e.Button == MouseButtons.Right) //open element properties + { bool updateDisplay = false; - switch (info.Type) { + switch (info.Type) + { case NodeInfoType.THING: Thing t = General.Map.Map.GetThingByIndex(info.Index); updateDisplay = (t != null && General.Interface.ShowEditThings(new List() { t }) == DialogResult.OK); @@ -568,16 +662,20 @@ namespace CodeImp.DoomBuilder.TagExplorer break; } - if(updateDisplay) { + if(updateDisplay) + { // Update entire display General.Map.Map.Update(); General.Interface.RedrawDisplay(); - updateTree(true); + UpdateTree(true); } - } else { + } + else + { //select element? - if (cbSelectOnClick.Checked) { + if (cbSelectOnClick.Checked) + { // Leave any volatile mode General.Editing.CancelVolatileMode(); General.Map.Map.ClearAllSelected(); @@ -608,21 +706,28 @@ namespace CodeImp.DoomBuilder.TagExplorer } //focus on element? - if (cbCenterOnSelected.Checked) { + if (cbCenterOnSelected.Checked) + { List points = new List(); RectangleF area = MapSet.CreateEmptyArea(); - if (info.Type == NodeInfoType.LINEDEF) { + if (info.Type == NodeInfoType.LINEDEF) + { Linedef l = General.Map.Map.GetLinedefByIndex(info.Index); points.Add(l.Start.Position); points.Add(l.End.Position); - } else if (info.Type == NodeInfoType.SECTOR) { + } + else if (info.Type == NodeInfoType.SECTOR) + { Sector s = General.Map.Map.GetSectorByIndex(info.Index); - foreach (Sidedef sd in s.Sidedefs) { + foreach (Sidedef sd in s.Sidedefs) + { points.Add(sd.Line.Start.Position); points.Add(sd.Line.End.Position); } - } else if (info.Type == NodeInfoType.THING) { + } + else if (info.Type == NodeInfoType.THING) + { Thing t = General.Map.Map.GetThingByIndex(info.Index); Vector2D p = t.Position; points.Add(p); @@ -630,7 +735,9 @@ namespace CodeImp.DoomBuilder.TagExplorer points.Add(p + new Vector2D(t.Size * 2.0f, -t.Size * 2.0f)); points.Add(p + new Vector2D(-t.Size * 2.0f, t.Size * 2.0f)); points.Add(p + new Vector2D(-t.Size * 2.0f, -t.Size * 2.0f)); - } else { + } + else + { General.Fail("Tag Explorer: unknown object type given to zoom in on!"); } @@ -638,11 +745,14 @@ namespace CodeImp.DoomBuilder.TagExplorer foreach (Vector2D p in points) area = MapSet.IncreaseArea(area, p); // Make the area square, using the largest side - if (area.Width > area.Height) { + if (area.Width > area.Height) + { float delta = area.Width - area.Height; area.Y -= delta * 0.5f; area.Height += delta; - } else { + } + else + { float delta = area.Height - area.Width; area.X -= delta * 0.5f; area.Width += delta; @@ -661,9 +771,11 @@ namespace CodeImp.DoomBuilder.TagExplorer } } - private void treeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { + private void treeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) + { //edit comment - if (udmf) { + if (udmf) + { NodeInfo info = e.Node.Tag as NodeInfo; if (info == null) return; @@ -674,14 +786,14 @@ namespace CodeImp.DoomBuilder.TagExplorer } //we don't want to edit categories if we are in UDMF - private void treeView_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e) { - if (!udmf || !treeView.LabelEdit || e.Node.Tag == null) { - e.CancelEdit = true; - } + private void treeView_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e) + { + if (!udmf || !treeView.LabelEdit || e.Node.Tag == null) e.CancelEdit = true; } //map should be in UDMF format, or we wouldn't be here - private void treeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { + private void treeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) + { NodeInfo info = e.Node.Tag as NodeInfo; string comment = ""; @@ -697,28 +809,34 @@ namespace CodeImp.DoomBuilder.TagExplorer } //It is called every time a dialog window closes. - private void ParentForm_Activated(object sender, EventArgs e){ + private void ParentForm_Activated(object sender, EventArgs e) + { UpdateTreeSoon(); } - private void btnClearSearch_Click(object sender, EventArgs e) { + private void btnClearSearch_Click(object sender, EventArgs e) + { tbSearch.Clear(); } - private void tbSearch_TextChanged(object sender, EventArgs e) { - if (tbSearch.Text.Length > 1 || tbSearch.Text.Length == 0) updateTree(false); + private void tbSearch_TextChanged(object sender, EventArgs e) + { + if (tbSearch.Text.Length > 1 || tbSearch.Text.Length == 0) UpdateTree(false); } - private void cbCommentsOnly_CheckedChanged(object sender, EventArgs e) { - updateTree(true); + private void cbCommentsOnly_CheckedChanged(object sender, EventArgs e) + { + UpdateTree(true); } - private void updatetimer_Tick(object sender, EventArgs e) { + private void updatetimer_Tick(object sender, EventArgs e) + { updatetimer.Stop(); - updateTree(true); + UpdateTree(true); } - private void bExportToFile_Click(object sender, EventArgs e) { + private void bExportToFile_Click(object sender, EventArgs e) + { if(treeView.Nodes == null || treeView.Nodes.Count == 0) return; // Show save dialog @@ -731,21 +849,24 @@ namespace CodeImp.DoomBuilder.TagExplorer StringBuilder sb = new StringBuilder(); //top level - foreach(TreeNode n in treeView.Nodes) { + foreach(TreeNode n in treeView.Nodes) + { if(n.Nodes.Count == 0) continue; if(sb.Length > 0) sb.AppendLine(Environment.NewLine); sb.AppendLine(n.Text.Replace(":", " (" +currentSortMode.ToLowerInvariant()+ "):")); //second level - foreach(TreeNode cn in n.Nodes) { + foreach(TreeNode cn in n.Nodes) + { //third level - if(cn.Nodes.Count > 0) { + if(cn.Nodes.Count > 0) + { sb.AppendLine(" " + cn.Text + ":"); - - foreach(TreeNode ccn in cn.Nodes) - sb.AppendLine(" " + ccn.Text); - } else { + foreach(TreeNode ccn in cn.Nodes) sb.AppendLine(" " + ccn.Text); + } + else + { sb.AppendLine(" " + cn.Text); } } @@ -763,19 +884,8 @@ namespace CodeImp.DoomBuilder.TagExplorer General.Interface.DisplayStatus(StatusType.Info, "Failed to save tag info..."); } } + + #endregion } - internal struct SortMode - { - public const string SORT_BY_INDEX = "By Index"; - public const string SORT_BY_TAG = "By Tag"; - public const string SORT_BY_ACTION = "By Action special"; - public static readonly object[] SORT_MODES = new object[] { SORT_BY_INDEX, SORT_BY_TAG, SORT_BY_ACTION }; - } - - internal struct SelectedNode - { - public NodeInfoType Type; - public int Index; - } } diff --git a/Source/Plugins/TagExplorer/NodeInfo.cs b/Source/Plugins/TagExplorer/NodeInfo.cs index 939fe538..8d2c2b07 100644 --- a/Source/Plugins/TagExplorer/NodeInfo.cs +++ b/Source/Plugins/TagExplorer/NodeInfo.cs @@ -17,10 +17,11 @@ namespace CodeImp.DoomBuilder.TagExplorer public int Tag { get { return tag; } } public int Action { get { return action; } } public NodeInfoType Type { get { return type; } } - public string Comment { get { return getComment(); } set { setComment(value); } } + public string Comment { get { return GetComment(); } set { SetComment(value); } } //constructor - public NodeInfo(Thing t) { + public NodeInfo(Thing t) + { type = NodeInfoType.THING; index = t.Index; action = t.Action; @@ -29,14 +30,16 @@ namespace CodeImp.DoomBuilder.TagExplorer defaultName = (tti != null ? tti.Title : NodeInfoDefaultName.THING); } - public NodeInfo(Sector s) { + public NodeInfo(Sector s) + { type = NodeInfoType.SECTOR; index = s.Index; action = s.Effect; tag = s.Tag; } - public NodeInfo(Linedef l) { + public NodeInfo(Linedef l) + { type = NodeInfoType.LINEDEF; index = l.Index; action = l.Action; @@ -44,14 +47,17 @@ namespace CodeImp.DoomBuilder.TagExplorer } //methods - private UniFields getFields() { - if (type == NodeInfoType.THING) { + private UniFields GetFields() + { + if (type == NodeInfoType.THING) + { Thing t = General.Map.Map.GetThingByIndex(index); if (t == null) return null; return t.Fields; } - if (type == NodeInfoType.SECTOR) { + if (type == NodeInfoType.SECTOR) + { Sector s = General.Map.Map.GetSectorByIndex(index); if (s == null) return null; return s.Fields; @@ -63,11 +69,14 @@ namespace CodeImp.DoomBuilder.TagExplorer } //comment - private void setComment(string comment) { - UniFields fields = getFields(); + private void SetComment(string comment) + { + UniFields fields = GetFields(); - if (comment.Length == 0) { - if (fields.ContainsKey("comment")) { + if (comment.Length == 0) + { + if (fields.ContainsKey("comment")) + { General.Map.UndoRedo.CreateUndo("Remove comment"); fields.BeforeFieldsChange(); fields.Remove("comment"); @@ -85,64 +94,76 @@ namespace CodeImp.DoomBuilder.TagExplorer fields["comment"].Value = comment; } - private string getComment() { - UniFields fields = getFields(); + private string GetComment() + { + UniFields fields = GetFields(); if (fields == null) return ""; if (!fields.ContainsKey("comment")) return ""; return fields["comment"].Value.ToString(); } //naming - public string GetName(ref string comment, string sortMode) { - if (type == NodeInfoType.THING) { + public string GetName(ref string comment, string sortMode) + { + if (type == NodeInfoType.THING) + { Thing t = General.Map.Map.GetThingByIndex(index); if (t == null) return ""; - return getThingName(t, ref comment, sortMode); + return GetThingName(t, ref comment, sortMode); } - if (type == NodeInfoType.SECTOR) { + if (type == NodeInfoType.SECTOR) + { Sector s = General.Map.Map.GetSectorByIndex(index); if (s == null) return ""; - return getSectorName(s, ref comment, sortMode); + return GetSectorName(s, ref comment, sortMode); } Linedef l = General.Map.Map.GetLinedefByIndex(index); if (l == null) return ""; - return getLinedefName(l, ref comment, sortMode); + return GetLinedefName(l, ref comment, sortMode); } - private string getThingName(Thing t, ref string comment, string sortMode) { + private string GetThingName(Thing t, ref string comment, string sortMode) + { bool isDefaultName = true; comment = ""; - if (TagExplorer.UDMF && t.Fields.ContainsKey("comment")) { + if (TagExplorer.UDMF && t.Fields.ContainsKey("comment")) + { comment = t.Fields["comment"].Value.ToString(); isDefaultName = false; } - return combineName(comment.Length == 0 ? defaultName : comment, t.Tag, t.Action, t.Index, sortMode, isDefaultName); + return CombineName(comment.Length == 0 ? defaultName : comment, t.Tag, t.Action, t.Index, sortMode, isDefaultName); } - private static string getSectorName(Sector s, ref string comment, string sortMode) { + private static string GetSectorName(Sector s, ref string comment, string sortMode) + { bool isDefaultName = true; comment = ""; - if (TagExplorer.UDMF && s.Fields.ContainsKey("comment")) { + if (TagExplorer.UDMF && s.Fields.ContainsKey("comment")) + { comment = s.Fields["comment"].Value.ToString(); isDefaultName = false; } - return combineName(comment.Length == 0 ? NodeInfoDefaultName.SECTOR : comment, s.Tag, s.Effect, s.Index, sortMode, isDefaultName); + return CombineName(comment.Length == 0 ? NodeInfoDefaultName.SECTOR : comment, s.Tag, s.Effect, s.Index, sortMode, isDefaultName); } - private static string getLinedefName(Linedef l, ref string comment, string sortMode) { + private static string GetLinedefName(Linedef l, ref string comment, string sortMode) + { bool isDefaultName = true; comment = ""; - if (TagExplorer.UDMF && l.Fields.ContainsKey("comment")) { + if (TagExplorer.UDMF && l.Fields.ContainsKey("comment")) + { comment = l.Fields["comment"].Value.ToString(); isDefaultName = false; } - return combineName(comment.Length == 0 ? NodeInfoDefaultName.LINEDEF : comment, l.Tag, l.Action, l.Index, sortMode, isDefaultName); + return CombineName(comment.Length == 0 ? NodeInfoDefaultName.LINEDEF : comment, l.Tag, l.Action, l.Index, sortMode, isDefaultName); } - private static string combineName(string name, int tag, int action, int index, string sortMode, bool isDefaultName) { - switch (sortMode) { + private static string CombineName(string name, int tag, int action, int index, string sortMode, bool isDefaultName) + { + switch (sortMode) + { case SortMode.SORT_BY_ACTION: return (tag > 0 ? "Tag:" + tag + "; " : "") + name + (isDefaultName ? " " + index : ""); diff --git a/Source/Plugins/VisplaneExplorer/BuilderPlug.cs b/Source/Plugins/VisplaneExplorer/BuilderPlug.cs index 7ae006bf..5c7cb56a 100644 --- a/Source/Plugins/VisplaneExplorer/BuilderPlug.cs +++ b/Source/Plugins/VisplaneExplorer/BuilderPlug.cs @@ -71,7 +71,8 @@ namespace CodeImp.DoomBuilder.Plugins.VisplaneExplorer } //mxd. This, actually, can also happen - public override void OnMapNewBegin() { + public override void OnMapNewBegin() + { OnMapOpenBegin(); } diff --git a/Source/Plugins/VisplaneExplorer/Tile.cs b/Source/Plugins/VisplaneExplorer/Tile.cs index 12cdd78a..f7e22c5f 100644 --- a/Source/Plugins/VisplaneExplorer/Tile.cs +++ b/Source/Plugins/VisplaneExplorer/Tile.cs @@ -120,7 +120,7 @@ namespace CodeImp.DoomBuilder.Plugins.VisplaneExplorer } // Returns a position by index - public TilePoint PointByIndex(int index) + private static TilePoint PointByIndex(int index) { #if DEBUG if(index > (TILE_SIZE * TILE_SIZE)) diff --git a/Source/Plugins/VisplaneExplorer/VisplaneExplorerMode.cs b/Source/Plugins/VisplaneExplorer/VisplaneExplorerMode.cs index 2f662e28..2dc79061 100644 --- a/Source/Plugins/VisplaneExplorer/VisplaneExplorerMode.cs +++ b/Source/Plugins/VisplaneExplorer/VisplaneExplorerMode.cs @@ -273,13 +273,16 @@ namespace CodeImp.DoomBuilder.Plugins.VisplaneExplorer Point rb = TileForPoint(mapbounds.Right + Tile.TILE_SIZE, mapbounds.Bottom + Tile.TILE_SIZE); Rectangle tilesrect = new Rectangle(lt.X, lt.Y, rb.X - lt.X, rb.Y - lt.Y); NearestLineBlockmap blockmap = new NearestLineBlockmap(tilesrect); - for(int x = tilesrect.X; x <= tilesrect.Right; x += Tile.TILE_SIZE) { - for(int y = tilesrect.Y; y <= tilesrect.Bottom; y += Tile.TILE_SIZE) { + for(int x = tilesrect.X; x <= tilesrect.Right; x += Tile.TILE_SIZE) + { + for(int y = tilesrect.Y; y <= tilesrect.Bottom; y += Tile.TILE_SIZE) + { // If the tile is obviously outside the map, don't create it Vector2D pc = new Vector2D(x + (Tile.TILE_SIZE >> 1), y + (Tile.TILE_SIZE >> 1)); Linedef ld = MapSet.NearestLinedef(blockmap.GetBlockAt(pc).Lines, pc); float distancesq = ld.DistanceToSq(pc, true); - if(distancesq > (Tile.TILE_SIZE * Tile.TILE_SIZE)) { + if(distancesq > (Tile.TILE_SIZE * Tile.TILE_SIZE)) + { float side = ld.SideOfLine(pc); if((side > 0.0f) && (ld.Back == null)) continue;