diff --git a/Ultima/MultiComponentList.cs b/Ultima/MultiComponentList.cs index a599aea8..1d072142 100644 --- a/Ultima/MultiComponentList.cs +++ b/Ultima/MultiComponentList.cs @@ -203,6 +203,7 @@ public MultiComponentList(string fileName, Multis.ImportType type) _min = _max = Point.Empty; int itemCount; + List parsed = null; switch (type) { @@ -350,7 +351,17 @@ public MultiComponentList(string fileName, Multis.ImportType type) using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new BinaryReader(fs)) { - if (reader.ReadInt16() != 1) // Version check + // Version 1 holds one design; version 2 is a batch, of which the first + // design is read here (UoaDesignFile reads them all). + short uoaVersion = reader.ReadInt16(); + if (uoaVersion == 2) + { + if (reader.ReadInt16() < 1) + { + return; + } + } + else if (uoaVersion != 1) { return; } @@ -623,11 +634,264 @@ public MultiComponentList(string fileName, Multis.ImportType type) break; } + case Multis.ImportType.UOX3: + parsed = ReadUox3(fileName); + break; + case Multis.ImportType.XML: + parsed = ReadXml(fileName); + break; + case Multis.ImportType.UOH: + parsed = ReadUoh(fileName); + break; + case Multis.ImportType.WORLDFORGE: + parsed = ReadWorldForge(fileName); + break; + case Multis.ImportType.MULTIFORGE: + parsed = ReadMultiforge(fileName); + break; + } + + if (parsed != null) + { + // Formats read into a list: take the tiles and their bounds from it. + SortedTiles = parsed.ToArray(); + if (SortedTiles.Length > 0) + { + _min = new Point(int.MaxValue, int.MaxValue); + _max = new Point(int.MinValue, int.MinValue); + foreach (MultiTileEntry e in SortedTiles) + { + _min.X = Math.Min(_min.X, e.OffsetX); + _min.Y = Math.Min(_min.Y, e.OffsetY); + _max.X = Math.Max(_max.X, e.OffsetX); + _max.Y = Math.Max(_max.Y, e.OffsetY); + MaxHeight = Math.Max(MaxHeight, e.OffsetZ); + } + } } ConvertList(); } + private static MultiTileEntry Entry(int id, int x, int y, int z, int flags = 1, int unk1 = 0) + { + return new MultiTileEntry + { + ItemId = (ushort)id, + OffsetX = (short)x, + OffsetY = (short)y, + OffsetZ = (short)Math.Clamp(z, sbyte.MinValue, sbyte.MaxValue), + Flags = flags, + Unk1 = unk1 + }; + } + + /// + /// A number written as decimal or as 0x hex. + /// + private static int ParseNumber(string text) + { + text = text.Trim(); + return text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + ? int.Parse(text[2..], System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture) + : int.Parse(text, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// UOX3 house items, as writes them: + /// [HOUSE ITEM n] { ITEM=0x.. X=.. Y=.. Z=.. }. + /// + private static List ReadUox3(string fileName) + { + var list = new List(); + int id = -1, x = 0, y = 0, z = 0; + foreach (string raw in File.ReadLines(fileName, Encoding.GetEncoding(1252))) + { + string line = raw.Trim(); + if (line.StartsWith('[')) + { + id = -1; + x = y = z = 0; + continue; + } + + if (line == "}" && id >= 0) + { + list.Add(Entry(id, x, y, z)); + id = -1; + continue; + } + + int equals = line.IndexOf('='); + if (equals <= 0) + { + continue; + } + + string key = line[..equals].Trim().ToUpperInvariant(); + string value = line[(equals + 1)..]; + switch (key) + { + case "ITEM": + id = ParseNumber(value); + break; + case "X": + x = ParseNumber(value); + break; + case "Y": + y = ParseNumber(value); + break; + case "Z": + z = ParseNumber(value); + break; + } + } + + return list; + } + + /// + /// The XML writes: <Entry><Item X Y Z ID Flags Unk1 />. + /// + private static List ReadXml(string fileName) + { + var list = new List(); + var dom = new XmlDocument(); + dom.Load(fileName); + foreach (XmlElement item in dom.GetElementsByTagName("Item")) + { + string flags = item.GetAttribute("Flags"); + string unk1 = item.GetAttribute("Unk1"); + list.Add(Entry( + ParseNumber(item.GetAttribute("ID")), + ParseNumber(item.GetAttribute("X")), + ParseNumber(item.GetAttribute("Y")), + ParseNumber(item.GetAttribute("Z")), + flags.Length > 0 ? ParseNumber(flags) : 1, + unk1.Length > 0 ? ParseNumber(unk1) : 0)); + } + + return list; + } + + /// + /// A UO House Editor design: a header line ("UOHE File ver 1.00",width,height,base), then + /// one line per item: floor,x,y,altitude,item id (decimal). Floor 0 is the foundation with + /// altitudes from 0; floor 1 starts at the base height and every further floor 20 higher. + /// + private static List ReadUoh(string fileName) + { + var list = new List(); + string[] lines = File.ReadAllLines(fileName, Encoding.GetEncoding(1252)); + if (lines.Length == 0 || !lines[0].StartsWith("\"UOHE File", StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidDataException("Not a UOHE design file"); + } + + string[] header = lines[0].Split(','); + int baseHeight = header.Length > 3 ? ParseNumber(header[3]) : 7; + + for (int i = 1; i < lines.Length; ++i) + { + string[] parts = lines[i].Split(','); + if (parts.Length < 5) + { + continue; + } + + int floor = ParseNumber(parts[0]); + int altitude = ParseNumber(parts[3]); + int z = floor == 0 ? altitude : baseHeight + ((floor - 1) * 20) + altitude; + list.Add(Entry(ParseNumber(parts[4]), ParseNumber(parts[1]), ParseNumber(parts[2]), z)); + } + + return list; + } + + /// + /// A WorldForge export: <tile id x y z hue /> elements in world coordinates, moved so + /// the lowest X, Y and Z are 0. Hues are not part of a multi and are dropped. + /// + private static List ReadWorldForge(string fileName) + { + var dom = new XmlDocument(); + dom.Load(fileName); + var tiles = new List<(int Id, int X, int Y, int Z)>(); + foreach (XmlNode node in dom.GetElementsByTagName("*")) + { + if (node is XmlElement tile && tile.LocalName.Equals("tile", StringComparison.OrdinalIgnoreCase) && tile.HasAttribute("id")) + { + tiles.Add((ParseNumber(tile.GetAttribute("id")), ParseNumber(tile.GetAttribute("x")), + ParseNumber(tile.GetAttribute("y")), ParseNumber(tile.GetAttribute("z")))); + } + } + + var list = new List(tiles.Count); + if (tiles.Count == 0) + { + return list; + } + + int minX = int.MaxValue, minY = int.MaxValue, minZ = int.MaxValue; + foreach (var t in tiles) + { + minX = Math.Min(minX, t.X); + minY = Math.Min(minY, t.Y); + minZ = Math.Min(minZ, t.Z); + } + + foreach (var t in tiles) + { + list.Add(Entry(t.Id, t.X - minX, t.Y - minY, t.Z - minZ)); + } + + return list; + } + + /// + /// Text from the POL multiforge package, one item per line relative to the multi's centre: + /// id x y z hue [flag]. Its txtexport writes a hex id, a hex hue and the flag (1 part of the + /// multi, 0 a separate item); txtexport2 writes no flag, and older versions of it decimal ids. + /// A first line holding only a number is an item count. Hues are not part of a multi and are + /// dropped. Without a flag an item is part of the multi, except the 0x1 anchor. + /// + private static List ReadMultiforge(string fileName) + { + var list = new List(); + int lineNumber = 0; + bool first = true; + foreach (string raw in File.ReadLines(fileName, Encoding.GetEncoding(1252))) + { + ++lineNumber; + string[] parts = raw.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) + { + continue; + } + + if (first && parts.Length == 1) + { + // The item count some exports start with. + first = false; + _ = ParseNumber(parts[0]); + continue; + } + + first = false; + if (parts.Length < 5) + { + throw new InvalidDataException($"Line {lineNumber} has {parts.Length} values, expected id x y z hue [flag]"); + } + + int id = ParseNumber(parts[0]); + _ = ParseNumber(parts[4]); // hue + int flags = parts.Length > 5 ? (ParseNumber(parts[5]) != 0 ? 1 : 0) : (id == 1 ? 0 : 1); + list.Add(Entry(id, ParseNumber(parts[1]), ParseNumber(parts[2]), ParseNumber(parts[3]), flags)); + } + + return list; + } + public MultiComponentList(List arr) { _min = _max = Point.Empty; @@ -849,6 +1113,141 @@ private MultiComponentList() Tiles = Array.Empty(); } + // The exports below mirror what the matching imports read. Where an import skips a field + // (UO Architect's category, level and hue, the cache header's other numbers), the export + // writes a neutral value: only this reader's view of those formats is known here. + + private static void WriteUOAString(BinaryWriter writer, string value) + { + writer.Write((byte)(value == null ? 0 : 1)); + if (value != null) + { + writer.Write(value); + } + } + + /// UO Architect binary design (.uoa), version 1: one design with a name and its items. + public void ExportToUOABinaryFile(string fileName, string name) + { + using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) + using (var writer = new BinaryWriter(fs)) + { + writer.Write((short)1); // version + WriteUOAString(writer, name); + WriteUOAString(writer, null); // category + WriteUOAString(writer, null); // subsection + writer.Write(Width); + writer.Write(Height); + writer.Write(Width); // user width + writer.Write(Height); // user height + writer.Write(SortedTiles.Length); + for (int i = 0; i < SortedTiles.Length; ++i) + { + writer.Write((short)SortedTiles[i].ItemId); + writer.Write(SortedTiles[i].OffsetX); + writer.Write(SortedTiles[i].OffsetY); + writer.Write(SortedTiles[i].OffsetZ); + writer.Write((short)0); // level + writer.Write((short)0); // hue + } + } + } + + /// + /// UO Architect design set: name.idx and name.bin next to + /// , holding this one design (index version 0, item records of type 0). + /// + public void ExportToDesignerFiles(string fileName, string name) + { + string root = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(fileName)) ?? string.Empty, Path.GetFileNameWithoutExtension(fileName)); + using (var idxfs = new FileStream(root + ".idx", FileMode.Create, FileAccess.Write)) + using (var binfs = new FileStream(root + ".bin", FileMode.Create, FileAccess.Write)) + using (var idx = new BinaryWriter(idxfs)) + using (var bin = new BinaryWriter(binfs)) + { + idx.Write(1); // designs + idx.Write(0); // version + WriteUOAString(idx, name); + WriteUOAString(idx, null); // category + WriteUOAString(idx, null); // subsection + idx.Write(Width); + idx.Write(Height); + idx.Write(Width); // user width + idx.Write(Height); // user height + idx.Write(0L); // position of the first record in the bin + idx.Write(SortedTiles.Length); + + for (int i = 0; i < SortedTiles.Length; ++i) + { + bin.Write(0); // record type + bin.Write((int)SortedTiles[i].ItemId); + bin.Write((int)SortedTiles[i].OffsetX); + bin.Write((int)SortedTiles[i].OffsetY); + bin.Write((int)SortedTiles[i].OffsetZ); + bin.Write(0); // level + } + } + } + + /// + /// Client multi cache text (Multicache.dat) holding this one design: a header line whose third + /// number is the item count, then one line per item: id, flags, x, y, z. + /// + public void ExportToCacheFile(string fileName) + { + using (var tex = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite), Encoding.GetEncoding(1252))) + { + tex.WriteLine($"0 0 {SortedTiles.Length} 0 0 0 0"); + for (int i = 0; i < SortedTiles.Length; ++i) + { + tex.WriteLine( + $"{SortedTiles[i].ItemId} {SortedTiles[i].Flags} {SortedTiles[i].OffsetX} {SortedTiles[i].OffsetY} {SortedTiles[i].OffsetZ}"); + } + } + } + + /// + /// UO House Editor (UOHE) design: the header line, then floor, x, y, altitude, item id per item. + /// Items below are on floor 0 (the foundation) with their Z as + /// altitude; above it a floor is 20 high. X and Y start at 0. + /// + public void ExportToUohFile(string fileName, int baseHeight = 7) + { + using (var tex = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite), Encoding.GetEncoding(1252))) + { + tex.WriteLine($"\"UOHE File ver 1.00\",{Width},{Height},{baseHeight}"); + for (int i = 0; i < SortedTiles.Length; ++i) + { + int z = SortedTiles[i].OffsetZ; + int floor = z < baseHeight ? 0 : 1 + ((z - baseHeight) / 20); + int altitude = floor == 0 ? z : z - baseHeight - ((floor - 1) * 20); + tex.WriteLine($"{floor},{SortedTiles[i].OffsetX - _min.X},{SortedTiles[i].OffsetY - _min.Y},{altitude},{SortedTiles[i].ItemId}"); + } + } + } + + /// WorldForge tile list: one tile element per item with id, x, y, z and hue 0, from 0,0. + public void ExportToWorldForgeFile(string fileName) + { + var settings = new XmlWriterSettings { Indent = true }; + using (XmlWriter xml = XmlWriter.Create(fileName, settings)) + { + xml.WriteStartElement("tiles"); + for (int i = 0; i < SortedTiles.Length; ++i) + { + xml.WriteStartElement("tile"); + xml.WriteAttributeString("id", SortedTiles[i].ItemId.ToString(System.Globalization.CultureInfo.InvariantCulture)); + xml.WriteAttributeString("x", (SortedTiles[i].OffsetX - _min.X).ToString(System.Globalization.CultureInfo.InvariantCulture)); + xml.WriteAttributeString("y", (SortedTiles[i].OffsetY - _min.Y).ToString(System.Globalization.CultureInfo.InvariantCulture)); + xml.WriteAttributeString("z", SortedTiles[i].OffsetZ.ToString(System.Globalization.CultureInfo.InvariantCulture)); + xml.WriteAttributeString("hue", "0"); + xml.WriteEndElement(); + } + + xml.WriteEndElement(); + } + } + public void ExportToTextFile(string fileName) { using (var tex = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite), Encoding.GetEncoding(1252))) @@ -861,6 +1260,29 @@ public void ExportToTextFile(string fileName) } } + /// + /// Text for the POL multiforge package, as its txtexport writes it: the 0x1 anchor first, then + /// one item per line: hex id, x, y, z, hue (always 0x0, a multi has none) and the flag + /// (1 part of the multi, 0 a separate item). + /// + public void ExportToMultiforgeFile(string fileName) + { + using (var tex = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite), Encoding.GetEncoding(1252))) + { + tex.NewLine = "\r\n"; + bool hasAnchor = Array.Exists(SortedTiles, t => t.ItemId == 1 && t.OffsetX == 0 && t.OffsetY == 0 && t.OffsetZ == 0); + if (!hasAnchor) + { + tex.WriteLine("0x1 0 0 0 0x0 0"); + } + + foreach (MultiTileEntry tile in SortedTiles) + { + tex.WriteLine($"0x{tile.ItemId:X} {tile.OffsetX} {tile.OffsetY} {tile.OffsetZ} 0x0 {(tile.Flags != 0 ? 1 : 0)}"); + } + } + } + public void ExportToWscFile(string fileName) { using (var tex = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite), Encoding.GetEncoding(1252))) diff --git a/Ultima/Multis.cs b/Ultima/Multis.cs index ed2c2a0e..517bbcbb 100644 --- a/Ultima/Multis.cs +++ b/Ultima/Multis.cs @@ -58,7 +58,10 @@ public enum ImportType UOX3, MULTICACHE, UOADESIGN, - XML + XML, + UOH, // UO House Editor (UOHE) design + WORLDFORGE, // WorldForge tile export + MULTIFORGE // POL multiforge package text: id x y z hue [multi flag] } /// diff --git a/Ultima/UoaDesignFile.cs b/Ultima/UoaDesignFile.cs new file mode 100644 index 00000000..af3d238a --- /dev/null +++ b/Ultima/UoaDesignFile.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace Ultima +{ + /// + /// One design in a UO Architect file: what its header says, and where its items are. + /// + public sealed class UoaDesign + { + public string Name { get; internal set; } + + public string Category { get; internal set; } + + public string Subsection { get; internal set; } + + /// Size as UO Architect stored it; not always the extent of the items. + public int Width { get; internal set; } + + public int Height { get; internal set; } + + public int ItemCount { get; internal set; } + + /// The .uoa file, or the .idx of an idx + bin design set. + public string FileName { get; internal set; } + + /// Position of the design within its file, from 0. + public int Index { get; internal set; } + + /// Where the item records start: in the .uoa itself, or in the .bin of a design set. + internal long ItemsPosition { get; set; } + + internal bool InDesignSet { get; set; } + } + + /// + /// Reads and writes UO Architect designs. Layouts as in UO Architect 2.7: + /// + /// .uoa version 1: one design. Version 2: a count, then that many designs. + /// A design: name, category, subsection (each a flag byte, then a length-prefixed string + /// when the flag is 1), width, height, user width, user height, item count (int32 each), then + /// per item six int16: id, x, y, z, level, hue. + /// Design set (Designs.idx + Designs.bin): the idx holds a count, a version (0) and per + /// design the same header followed by the int64 position and int32 count of its records in + /// the bin; a bin record is int32 type (0 or 1), id, x, y, z, level, and hue when type is 1. + /// + /// A multi has no item hue or level, so reading drops them and writing stores 0. + /// + public static class UoaDesignFile + { + private const int _itemSize = 12; + + /// + /// The designs a file holds, without reading their items. Takes a .uoa (either version) or + /// the .idx of a design set. An unreadable or foreign file gives an empty list. + /// + public static List ReadHeaders(string fileName) + { + var designs = new List(); + try + { + using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var reader = new BinaryReader(fs)) + { + if (fileName.EndsWith(".idx", StringComparison.OrdinalIgnoreCase)) + { + int count = reader.ReadInt32(); + if (reader.ReadInt32() != 0 || count < 0) + { + return designs; + } + + for (int i = 0; i < count; ++i) + { + UoaDesign design = ReadHeader(reader, fileName, i, countFollows: false); + design.ItemsPosition = reader.ReadInt64(); + design.ItemCount = reader.ReadInt32(); + design.InDesignSet = true; + designs.Add(design); + } + + return designs; + } + + short version = reader.ReadInt16(); + int total = version == 1 ? 1 : version == 2 ? reader.ReadInt16() : 0; + for (int i = 0; i < total; ++i) + { + UoaDesign design = ReadHeader(reader, fileName, i, countFollows: true); + design.ItemsPosition = fs.Position; + fs.Seek((long)design.ItemCount * _itemSize, SeekOrigin.Current); + if (fs.Position > fs.Length) + { + break; // cut short: what was read so far stands + } + + designs.Add(design); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + // What was read before the file ran out is returned. + } + + return designs; + } + + private static UoaDesign ReadHeader(BinaryReader reader, string fileName, int index, bool countFollows) + { + var design = new UoaDesign + { + FileName = fileName, + Index = index, + Name = ReadString(reader), + Category = ReadString(reader), + Subsection = ReadString(reader), + Width = reader.ReadInt32(), + Height = reader.ReadInt32() + }; + reader.ReadInt32(); // user width + reader.ReadInt32(); // user height + if (countFollows) + { + design.ItemCount = reader.ReadInt32(); + if (design.ItemCount < 0) + { + throw new IOException("Negative item count"); + } + } + + return design; + } + + /// The items of a design as a multi. Hue and level are dropped; Z is kept within a multi's range. + public static MultiComponentList Load(UoaDesign design) + { + var entries = new List(Math.Max(0, design.ItemCount)); + string path = design.InDesignSet ? Path.ChangeExtension(design.FileName, ".bin") : design.FileName; + using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var reader = new BinaryReader(fs)) + { + fs.Seek(design.ItemsPosition, SeekOrigin.Begin); + for (int i = 0; i < design.ItemCount; ++i) + { + int id, x, y, z; + if (design.InDesignSet) + { + int type = reader.ReadInt32(); + id = reader.ReadInt32(); + x = reader.ReadInt32(); + y = reader.ReadInt32(); + z = reader.ReadInt32(); + reader.ReadInt32(); // level + if (type == 1) + { + reader.ReadInt32(); // hue + } + } + else + { + id = (ushort)reader.ReadInt16(); + x = reader.ReadInt16(); + y = reader.ReadInt16(); + z = reader.ReadInt16(); + reader.ReadInt16(); // level + reader.ReadInt16(); // hue + } + + entries.Add(new MultiComponentList.MultiTileEntry + { + ItemId = (ushort)id, + OffsetX = (short)x, + OffsetY = (short)y, + OffsetZ = (short)Math.Clamp(z, sbyte.MinValue, sbyte.MaxValue), + Flags = 1, + Unk1 = 0 + }); + } + } + + return entries.Count == 0 ? MultiComponentList.Empty : new MultiComponentList(entries); + } + + /// + /// Writes designs as a .uoa: version 1 for one design, version 2 (a batch) for several. + /// + public static void Write(string fileName, IReadOnlyList<(string Name, string Category, string Subsection, MultiComponentList Multi)> designs) + { + using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) + using (var writer = new BinaryWriter(fs)) + { + if (designs.Count == 1) + { + writer.Write((short)1); + } + else + { + writer.Write((short)2); + writer.Write((short)designs.Count); + } + + foreach ((string name, string category, string subsection, MultiComponentList multi) in designs) + { + WriteString(writer, name); + WriteString(writer, category); + WriteString(writer, subsection); + writer.Write(multi.Width); + writer.Write(multi.Height); + writer.Write(multi.Width); // user width + writer.Write(multi.Height); // user height + writer.Write(multi.SortedTiles.Length); + foreach (MultiComponentList.MultiTileEntry tile in multi.SortedTiles) + { + writer.Write((short)tile.ItemId); + writer.Write(tile.OffsetX); + writer.Write(tile.OffsetY); + writer.Write(tile.OffsetZ); + writer.Write((short)0); // level + writer.Write((short)0); // hue + } + } + } + } + + internal static string ReadString(BinaryReader reader) + { + return reader.ReadByte() == 0 ? null : reader.ReadString(); + } + + internal static void WriteString(BinaryWriter writer, string value) + { + writer.Write((byte)(value == null ? 0 : 1)); + if (value != null) + { + writer.Write(value); + } + } + } +} diff --git a/UoFiddler.Controls/Classes/Options.cs b/UoFiddler.Controls/Classes/Options.cs index a3ae8e72..26964eca 100644 --- a/UoFiddler.Controls/Classes/Options.cs +++ b/UoFiddler.Controls/Classes/Options.cs @@ -86,6 +86,12 @@ public static class Options /// public static List PluginsToLoad { get; set; } = new List(); + /// + /// Settings plugins keep in the profile, by name. A plugin prefixes its names with its own + /// (e.g. "MultiEditor.Grid"); the values are saved and loaded with the profile as text. + /// + public static Dictionary PluginSettings { get; set; } = new Dictionary(); + /// /// Defines which muls are loaded /// diff --git a/UoFiddler.Controls/Plugin/PluginEvents.cs b/UoFiddler.Controls/Plugin/PluginEvents.cs index 7c6ad53d..2934c768 100644 --- a/UoFiddler.Controls/Plugin/PluginEvents.cs +++ b/UoFiddler.Controls/Plugin/PluginEvents.cs @@ -9,7 +9,10 @@ * ***************************************************************************/ +using System; +using System.Drawing; using System.Windows.Forms; +using Ultima; namespace UoFiddler.Controls.Plugin { @@ -30,5 +33,21 @@ public static void FireModifyItemShowContextMenuEvent(ContextMenuStrip contextme { ModifyItemsControlContextMenuEvent?.Invoke(contextmenu); } + + /// + /// OnLoad called in MapControl to modify its context menu. gives + /// the shown map and the map location of the right click that opened the menu. + /// + public delegate void ModifyMapControlContextMenuHandler(ContextMenuStrip contextmenu, Func<(Map Map, Point Location)> clickedAt); + + /// + /// OnLoad called in MapControl to modify its context menu + /// + public static event ModifyMapControlContextMenuHandler ModifyMapControlContextMenuEvent; + + public static void FireModifyMapControlContextMenuEvent(ContextMenuStrip contextmenu, Func<(Map Map, Point Location)> clickedAt) + { + ModifyMapControlContextMenuEvent?.Invoke(contextmenu, clickedAt); + } } } \ No newline at end of file diff --git a/UoFiddler.Controls/Plugin/PluginServices.cs b/UoFiddler.Controls/Plugin/PluginServices.cs index c42178d1..2c7d47d0 100644 --- a/UoFiddler.Controls/Plugin/PluginServices.cs +++ b/UoFiddler.Controls/Plugin/PluginServices.cs @@ -12,6 +12,8 @@ using System; using System.IO; using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Loader; using Microsoft.Extensions.Logging; using UoFiddler.Controls.Classes; using UoFiddler.Controls.Plugin.Interfaces; @@ -53,6 +55,8 @@ public void FindPlugins(string path) return; } + RegisterDependencyResolver(path); + foreach (string fileOn in Directory.GetFiles(path, "*.dll")) { try @@ -86,6 +90,57 @@ public void ClosePlugins() AvailablePlugins.Clear(); } + private static string _dependencyRoot; + + /// + /// Lets a plugin ship third-party libraries in a subfolder of the plugin directory + /// (plugins\PluginName\). Files directly in the plugin directory are all loaded as plugins, + /// so dependencies cannot sit there. + /// + private static void RegisterDependencyResolver(string pluginDirectory) + { + bool first = _dependencyRoot == null; + _dependencyRoot = pluginDirectory; + if (!first) + { + return; + } + + AssemblyLoadContext.Default.Resolving += (context, name) => + { + string path = FindDependency(name.Name + ".dll"); + return path == null ? null : context.LoadFromAssemblyPath(path); + }; + + AssemblyLoadContext.Default.ResolvingUnmanagedDll += (_, libraryName) => + { + string path = FindDependency(libraryName) + ?? (libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + ? null + : FindDependency(libraryName + ".dll")); + return path != null && NativeLibrary.TryLoad(path, out IntPtr handle) ? handle : IntPtr.Zero; + }; + } + + private static string FindDependency(string fileName) + { + if (!Directory.Exists(_dependencyRoot)) + { + return null; + } + + foreach (string directory in Directory.GetDirectories(_dependencyRoot)) + { + string candidate = Path.Combine(directory, fileName); + if (File.Exists(candidate)) + { + return candidate; + } + } + + return null; + } + private void AddPlugin(string fileName) { Assembly pluginAssembly = Assembly.LoadFrom(fileName); diff --git a/UoFiddler.Controls/UserControls/MapControl.cs b/UoFiddler.Controls/UserControls/MapControl.cs index 563a5b54..6e83ab06 100644 --- a/UoFiddler.Controls/UserControls/MapControl.cs +++ b/UoFiddler.Controls/UserControls/MapControl.cs @@ -167,6 +167,7 @@ private void OnLoad(object sender, EventArgs e) ControlEvents.MapNameChangeEvent += OnMapNameChangeEvent; ControlEvents.MapSizeChangeEvent += OnMapSizeChangeEvent; ControlEvents.FilePathChangeEvent += OnFilePathChangeEvent; + Plugin.PluginEvents.FireModifyMapControlContextMenuEvent(contextMenuStrip1, () => (CurrentMap, _currentPoint)); } _loaded = true; } diff --git a/UoFiddler.Controls/UserControls/MultisControl.Designer.cs b/UoFiddler.Controls/UserControls/MultisControl.Designer.cs index ef5650a6..e7284868 100644 --- a/UoFiddler.Controls/UserControls/MultisControl.Designer.cs +++ b/UoFiddler.Controls/UserControls/MultisControl.Designer.cs @@ -225,7 +225,7 @@ private void InitializeComponent() listViewMultiColumn.Width = 240; listViewMulti.Columns.Add(listViewMultiColumn); listViewMulti.RetrieveVirtualItem += OnRetrieveMultiVirtualItem; - listViewMulti.SelectedIndexChanged += AfterSelect_Multi; + listViewMulti.SelectedIndexChanged += OnMulSelectionChanged; // // contextMenuStrip2 // @@ -811,7 +811,7 @@ private void InitializeComponent() listViewUopColumn.Width = 240; listViewUop.Columns.Add(listViewUopColumn); listViewUop.RetrieveVirtualItem += OnRetrieveUopVirtualItem; - listViewUop.SelectedIndexChanged += AfterSelect_UopMulti; + listViewUop.SelectedIndexChanged += OnUopSelectionChanged; // // contextMenuStripUop // diff --git a/UoFiddler.Controls/UserControls/MultisControl.cs b/UoFiddler.Controls/UserControls/MultisControl.cs index 714957c3..41225114 100644 --- a/UoFiddler.Controls/UserControls/MultisControl.cs +++ b/UoFiddler.Controls/UserControls/MultisControl.cs @@ -14,6 +14,7 @@ using System.Drawing; using System.Drawing.Imaging; using System.IO; +using System.Runtime.InteropServices; using System.Windows.Forms; using System.Xml; using Ultima; @@ -168,6 +169,9 @@ private void SelectUopRow(int rowPos) private bool _previewFitMode = true; private Bitmap _mulBitmap; private Bitmap _uopBitmap; + private bool _mulSelectPending; + private bool _uopSelectPending; + private Panel _redrawSuspendedPanel; private bool _isPanning; private Point _panStartScreen; private double _zoomLevel = 1.0; @@ -352,8 +356,28 @@ public void ChangeMulti(int id, MultiComponentList multi) ControlEvents.FireMultiChangeEvent(this, id); } + // A virtual ListView raises SelectedIndexChanged twice per click (deselect, then select). + // Defer to one update so the empty in-between state never reaches the preview. + private void OnMulSelectionChanged(object sender, EventArgs e) + { + if (_mulSelectPending) + { + return; + } + + _mulSelectPending = true; + BeginInvoke(() => + { + if (_mulSelectPending && !IsDisposed) + { + AfterSelect_Multi(this, EventArgs.Empty); + } + }); + } + private void AfterSelect_Multi(object sender, EventArgs e) { + _mulSelectPending = false; int id = GetSelectedMulId(); MultiComponentList multi = id >= 0 ? Multis.GetComponents(id) : MultiComponentList.Empty; if (multi == MultiComponentList.Empty) @@ -407,18 +431,57 @@ private void RebuildMulIds(bool includeEmpty) private void UpdateMulPictureBox() { - if (_previewFitMode || _mulBitmap == null) + WithoutPanelRedraw(panelMultiScroll, () => + { + if (_previewFitMode || _mulBitmap == null) + { + MultiPictureBox.Dock = DockStyle.Fill; + MultiPictureBox.Cursor = Cursors.Default; + } + else + { + MultiPictureBox.Dock = DockStyle.None; + CenterPictureBox(MultiPictureBox, panelMultiScroll, GetZoomedSize(_mulBitmap.Size)); + MultiPictureBox.Cursor = Cursors.Hand; + } + }); + MultiPictureBox.Invalidate(); + } + + private const int _wmSetRedraw = 0x000B; + private const uint _rdwInvalidate = 0x0001; + private const uint _rdwErase = 0x0004; + private const uint _rdwAllChildren = 0x0080; + private const uint _rdwFrame = 0x0400; + + [DllImport("user32.dll")] + private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll")] + private static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprcUpdate, IntPtr hrgnUpdate, uint flags); + + // Moving and resizing the preview takes several window moves (dock, size, location, panel + // auto-scroll), and each one shows on screen. Hold the panel's redraw until all are done. + private void WithoutPanelRedraw(Panel panel, Action change) + { + if (!panel.IsHandleCreated || _redrawSuspendedPanel == panel) { - MultiPictureBox.Dock = DockStyle.Fill; - MultiPictureBox.Cursor = Cursors.Default; + change(); + return; } - else + + _redrawSuspendedPanel = panel; + SendMessage(panel.Handle, _wmSetRedraw, IntPtr.Zero, IntPtr.Zero); + try { - MultiPictureBox.Dock = DockStyle.None; - CenterPictureBox(MultiPictureBox, panelMultiScroll, GetZoomedSize(_mulBitmap.Size)); - MultiPictureBox.Cursor = Cursors.Hand; + change(); + } + finally + { + SendMessage(panel.Handle, _wmSetRedraw, new IntPtr(1), IntPtr.Zero); + _redrawSuspendedPanel = null; + RedrawWindow(panel.Handle, IntPtr.Zero, IntPtr.Zero, _rdwInvalidate | _rdwErase | _rdwAllChildren | _rdwFrame); } - MultiPictureBox.Invalidate(); } private void OnPaint_MultiPic(object sender, PaintEventArgs e) @@ -991,8 +1054,26 @@ private void LoadUopTree() } } + private void OnUopSelectionChanged(object sender, EventArgs e) + { + if (_uopSelectPending) + { + return; + } + + _uopSelectPending = true; + BeginInvoke(() => + { + if (_uopSelectPending && !IsDisposed) + { + AfterSelect_UopMulti(this, EventArgs.Empty); + } + }); + } + private void AfterSelect_UopMulti(object sender, EventArgs e) { + _uopSelectPending = false; int id = GetSelectedUopId(); MultiComponentList multi = id >= 0 ? Multis.GetUopComponents(id) : MultiComponentList.Empty; if (multi == MultiComponentList.Empty) @@ -1031,17 +1112,20 @@ private void RefreshUopBitmap() private void UpdateUopPictureBox() { - if (_previewFitMode || _uopBitmap == null) - { - UopPictureBox.Dock = DockStyle.Fill; - UopPictureBox.Cursor = Cursors.Default; - } - else + WithoutPanelRedraw(panelUopScroll, () => { - UopPictureBox.Dock = DockStyle.None; - CenterPictureBox(UopPictureBox, panelUopScroll, GetZoomedSize(_uopBitmap.Size)); - UopPictureBox.Cursor = Cursors.Hand; - } + if (_previewFitMode || _uopBitmap == null) + { + UopPictureBox.Dock = DockStyle.Fill; + UopPictureBox.Cursor = Cursors.Default; + } + else + { + UopPictureBox.Dock = DockStyle.None; + CenterPictureBox(UopPictureBox, panelUopScroll, GetZoomedSize(_uopBitmap.Size)); + UopPictureBox.Cursor = Cursors.Hand; + } + }); UopPictureBox.Invalidate(); } @@ -1129,7 +1213,8 @@ private void OnPanelMultiScroll_Resize(object sender, EventArgs e) { if (!_previewFitMode && _mulBitmap != null) { - CenterPictureBox(MultiPictureBox, panelMultiScroll, GetZoomedSize(_mulBitmap.Size)); + WithoutPanelRedraw(panelMultiScroll, + () => CenterPictureBox(MultiPictureBox, panelMultiScroll, GetZoomedSize(_mulBitmap.Size))); } } @@ -1137,7 +1222,8 @@ private void OnPanelUopScroll_Resize(object sender, EventArgs e) { if (!_previewFitMode && _uopBitmap != null) { - CenterPictureBox(UopPictureBox, panelUopScroll, GetZoomedSize(_uopBitmap.Size)); + WithoutPanelRedraw(panelUopScroll, + () => CenterPictureBox(UopPictureBox, panelUopScroll, GetZoomedSize(_uopBitmap.Size))); } } diff --git a/UoFiddler.Controls/UserControls/ThemedTabControl.cs b/UoFiddler.Controls/UserControls/ThemedTabControl.cs new file mode 100644 index 00000000..8d9a83e0 --- /dev/null +++ b/UoFiddler.Controls/UserControls/ThemedTabControl.cs @@ -0,0 +1,196 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Controls.UserControls +{ + /// + /// A tab control for plugins: the wheel over the tab strip switches tabs, and in dark mode the + /// control paints the strip itself. .NET's dark mode does not reach owner drawn tabs (the native + /// control paints them and the strip light), so in dark mode owner drawn tabs get + /// raised from here and other tabs are drawn plainly. The native + /// control still sizes the tabs and handles the mouse. In light mode it is a native tab control. + /// + public class ThemedTabControl : TabControl + { + private static readonly Color _darkStrip = Color.FromArgb(32, 32, 32); + private static readonly Color _darkTab = Color.FromArgb(43, 43, 43); + private static readonly Color _darkSelectedTab = Color.FromArgb(60, 60, 60); + private static readonly Color _darkBorder = Color.FromArgb(75, 75, 75); + + public ThemedTabControl() + { + if (Dark) + { + SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | + ControlStyles.ResizeRedraw, true); + } + } + + /// The font handle given to the native control while it is user painted; ours to delete. + private IntPtr _fontHandle; + + private static bool Dark => Options.DarkMode; + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + SetNativeFont(); + } + + protected override void OnFontChanged(EventArgs e) + { + base.OnFontChanged(e); + SetNativeFont(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + // After the window is gone, so the font is no longer selected into it. + if (_fontHandle != IntPtr.Zero) + { + NativeMethods.DeleteObject(_fontHandle); + _fontHandle = IntPtr.Zero; + } + } + + /// + /// WinForms gives a user painted control's window no font, so the native control would size + /// the tabs with the system font, not the one the text is drawn in. + /// + private void SetNativeFont() + { + if (!IsHandleCreated || !GetStyle(ControlStyles.UserPaint)) + { + return; + } + + IntPtr previous = _fontHandle; + _fontHandle = Font.ToHfont(); + NativeMethods.SendMessage(Handle, NativeMethods.WM_SETFONT, _fontHandle, (IntPtr)1); + if (previous != IntPtr.Zero) + { + NativeMethods.DeleteObject(previous); + } + } + + private static class NativeMethods + { + public const int WM_SETFONT = 0x0030; + + [DllImport("user32.dll")] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); + + [DllImport("gdi32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool DeleteObject(IntPtr hObject); + } + + public Color TabBackColor(bool selected) => + Dark ? (selected ? _darkSelectedTab : _darkTab) : (selected ? SystemColors.Window : SystemColors.Control); + + public Color TabTextColor(bool selected) => + Dark ? (selected ? Color.FromArgb(240, 240, 240) : Color.FromArgb(200, 200, 200)) : (selected ? SystemColors.WindowText : SystemColors.ControlText); + + /// A glyph drawn on a tab (a close button's cross) when the mouse is not on it. + public Color GlyphColor(bool selected) => + Dark ? (selected ? Color.FromArgb(220, 220, 220) : Color.FromArgb(150, 150, 150)) : (selected ? SystemColors.WindowText : SystemColors.GrayText); + + /// + /// The wheel over the tab strip switches tabs: down (towards you) to the next tab, up to the + /// previous one. The wheel over a page, passed up from its content, is left alone. + /// + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); + if (TabCount < 2 || e.Delta == 0 || DisplayRectangle.Contains(e.Location)) + { + return; + } + + int index = Math.Clamp(SelectedIndex + (e.Delta < 0 ? 1 : -1), 0, TabCount - 1); + if (index == SelectedIndex) + { + return; + } + + SelectedIndex = index; + if (e is HandledMouseEventArgs handled) + { + handled.Handled = true; + } + } + + protected override void OnPaint(PaintEventArgs e) + { + // Only reached in dark mode, where UserPaint is set. + using (var strip = new SolidBrush(_darkStrip)) + { + e.Graphics.FillRectangle(strip, ClientRectangle); + } + + using var border = new Pen(_darkBorder); + int tabsBottom = 0; + for (int i = 0; i < TabCount; i++) + { + Rectangle tab = GetTabRect(i); + tabsBottom = Math.Max(tabsBottom, tab.Bottom); + if (!tab.IntersectsWith(e.ClipRectangle)) + { + continue; + } + + bool selected = i == SelectedIndex; + if (DrawMode == TabDrawMode.OwnerDrawFixed) + { + OnDrawItem(new DrawItemEventArgs(e.Graphics, Font, tab, i, selected ? DrawItemState.Selected : DrawItemState.None)); + } + else + { + DrawTab(e.Graphics, tab, i, selected); + } + + e.Graphics.DrawLine(border, tab.Left, tab.Top, tab.Right - 1, tab.Top); + e.Graphics.DrawLine(border, tab.Left, tab.Top, tab.Left, tab.Bottom - 1); + e.Graphics.DrawLine(border, tab.Right - 1, tab.Top, tab.Right - 1, tab.Bottom - 1); + } + + if (DisplayRectangle.Height > 0) + { + // A frame around the pages, its top edge along the bottom of the tabs. + e.Graphics.DrawRectangle(border, 0, tabsBottom, Width - 1, ClientRectangle.Bottom - tabsBottom - 1); + } + else + { + // A strip with no page area: the line along its bottom. + int y = ClientRectangle.Bottom - 1; + e.Graphics.DrawLine(border, 0, y, Width, y); + } + } + + private void DrawTab(Graphics graphics, Rectangle bounds, int index, bool selected) + { + using (var back = new SolidBrush(TabBackColor(selected))) + { + graphics.FillRectangle(back, bounds); + } + + TextRenderer.DrawText(graphics, TabPages[index].Text, Font, bounds, TabTextColor(selected), + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | + TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix); + } + } +} diff --git a/UoFiddler.Plugin.Compare/ComparePluginBase.cs b/UoFiddler.Plugin.Compare/ComparePluginBase.cs index dbb4f494..8784cc9a 100644 --- a/UoFiddler.Plugin.Compare/ComparePluginBase.cs +++ b/UoFiddler.Plugin.Compare/ComparePluginBase.cs @@ -13,6 +13,7 @@ using Ultima; using UoFiddler.Controls.Plugin; using UoFiddler.Controls.Plugin.Interfaces; +using UoFiddler.Controls.UserControls; using UoFiddler.Plugin.Compare.UserControls; namespace UoFiddler.Plugin.Compare @@ -36,7 +37,7 @@ public class ComparePluginBase : PluginBase + "Compares 2 Texture files\r\n" + "Compares 2 AnimData files\r\n" + "Compares 2 RadarCol files\r\n" - + "(Adds 9 new Tabs)"; + + "(Adds a Compare tab with 10 sub-tabs)"; /// /// Author of the plugin @@ -46,7 +47,7 @@ public class ComparePluginBase : PluginBase /// /// Version of the plugin /// - public override string Version { get; } = "1.8.0"; + public override string Version { get; } = "1.9.0"; /// /// Host of the plugin. @@ -64,125 +65,40 @@ public override void Unload() public override void ModifyTabPages(TabControl tabControl) { - TabPage page = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare Items" - }; - CompareItemControl compArt = new CompareItemControl - { - Dock = DockStyle.Fill - }; - page.Controls.Add(compArt); - tabControl.TabPages.Add(page); - - TabPage page2 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare Land" - }; - CompareLandControl compLandControl = new CompareLandControl - { - Dock = DockStyle.Fill - }; - page2.Controls.Add(compLandControl); - tabControl.TabPages.Add(page2); - - TabPage page3 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare CliLocs" - }; - CompareCliLocControl compCli = new CompareCliLocControl - { - Dock = DockStyle.Fill - }; - page3.Controls.Add(compCli); - tabControl.TabPages.Add(page3); - - TabPage page4 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare Hues" - }; - CompareHuesControl compH = new CompareHuesControl - { - Dock = DockStyle.Fill - }; - page4.Controls.Add(compH); - tabControl.TabPages.Add(page4); - - TabPage page5 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare Gumps" - }; - CompareGumpControl compG = new CompareGumpControl + ThemedTabControl compareTabs = new ThemedTabControl { Dock = DockStyle.Fill }; - page5.Controls.Add(compG); - tabControl.TabPages.Add(page5); + AddPage(compareTabs, "Items", new CompareItemControl()); + AddPage(compareTabs, "Land", new CompareLandControl()); + AddPage(compareTabs, "CliLocs", new CompareCliLocControl()); + AddPage(compareTabs, "Hues", new CompareHuesControl()); + AddPage(compareTabs, "Gumps", new CompareGumpControl()); + AddPage(compareTabs, "Map", new CompareMapControl()); + AddPage(compareTabs, "Texture", new CompareTextureControl()); + AddPage(compareTabs, "AnimData", new CompareAnimDataControl()); + AddPage(compareTabs, "RadarCol", new CompareRadarColControl()); + AddPage(compareTabs, "TileData", new CompareTileDataControl()); - TabPage page6 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare Map" - }; - CompareMapControl compM = new CompareMapControl - { - Dock = DockStyle.Fill - }; - page6.Controls.Add(compM); - tabControl.TabPages.Add(page6); - - TabPage page7 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare Texture" - }; - CompareTextureControl compTextureControl = new CompareTextureControl - { - Dock = DockStyle.Fill - }; - page7.Controls.Add(compTextureControl); - tabControl.TabPages.Add(page7); - - TabPage page8 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare AnimData" - }; - CompareAnimDataControl compAnimData = new CompareAnimDataControl - { - Dock = DockStyle.Fill - }; - page8.Controls.Add(compAnimData); - tabControl.TabPages.Add(page8); - - TabPage page9 = new TabPage + TabPage page = new TabPage { Tag = tabControl.TabCount + 1, - Text = "Compare RadarCol" - }; - CompareRadarColControl compRadarCol = new CompareRadarColControl - { - Dock = DockStyle.Fill + Text = "Compare" }; - page9.Controls.Add(compRadarCol); - tabControl.TabPages.Add(page9); + page.Controls.Add(compareTabs); + tabControl.TabPages.Add(page); + } - TabPage page10 = new TabPage - { - Tag = tabControl.TabCount + 1, - Text = "Compare TileData" - }; - CompareTileDataControl compTileDataControl = new CompareTileDataControl + private static void AddPage(TabControl tabs, string text, Control content) + { + TabPage page = new TabPage { - Dock = DockStyle.Fill + Text = text, + UseVisualStyleBackColor = true }; - page10.Controls.Add(compTileDataControl); - tabControl.TabPages.Add(page10); + content.Dock = DockStyle.Fill; + page.Controls.Add(content); + tabs.TabPages.Add(page); } public override void ModifyPluginToolStrip(ToolStripDropDownButton toolStrip) diff --git a/UoFiddler.Plugin.MultiEditor/Classes/ArtFacing.cs b/UoFiddler.Plugin.MultiEditor/Classes/ArtFacing.cs new file mode 100644 index 00000000..4d3b5019 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/ArtFacing.cs @@ -0,0 +1,399 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Rendering; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// Where a tile sits in its cell, which decides how it moves when a group is turned. + internal enum TilePlacement + { + /// Fills or stands in the cell (floors, roofs, furniture). + Cell, + + /// A wall along the cell's +Y edge. + SouthEdge, + + /// A wall along the cell's +X edge. + EastEdge, + + /// A post at the cell's +X/+Y corner. + Vertex, + + /// + /// A roof piece. Its art is drawn half a cell up the screen, so it covers the area around + /// the cell's -X/-Y corner: the official houses put their roofs one cell further +X/+Y + /// than the walls for that reason. + /// + Lifted + } + + /// + /// What the art itself says about a tile's facing. Swapping the world's X and Y axes mirrors + /// the screen left to right, so the tile that shows the same piece along the other axis is the + /// one whose art is the mirror image: a south wall and its east wall, a roof slope and the + /// slope a quarter turn on. That twin is looked for among the neighbouring ids. Nothing here + /// is a table: it is measured from the client's art, so it follows whatever art is loaded. + /// + internal static class ArtFacing + { + private const int _searchRange = 48; + private const double _sameShape = 0.90; + private const double _twinShape = 0.80; + + private sealed class Shape + { + public int Width; + public int Height; + public byte[] Rgba; + public int Left; + public int Right; + public int Opaque; + public int MinX; + public int MaxX; + public int MaxY; + public ulong Hash; + } + + private static readonly Dictionary _shapes = new Dictionary(); + private static readonly Dictionary _transposed = new Dictionary(); + + /// Forgets everything measured, for when the client files are loaded again. + public static void Clear() + { + _shapes.Clear(); + _transposed.Clear(); + } + + /// A hash of the tile's art, 0 when it has none. Equal art gives an equal hash. + public static ulong ArtHash(ushort id) => Load(id)?.Hash ?? 0; + + /// + /// The tile showing the same piece with the X and Y axes swapped, or the id itself when the + /// art is its own mirror image or no twin is found. + /// + public static ushort Transpose(ushort id) + { + if (_transposed.TryGetValue(id, out ushort known)) + { + return known; + } + + Shape shape = Load(id); + if (shape == null || shape.Opaque == 0 || (TileData.ItemTable[id].Flags & TileFlag.Animation) != 0) + { + // No art, or frames of an animation: neighbouring ids are the next frames, not twins. + return _transposed[id] = id; + } + + if (Compare(shape, shape).Shape >= _sameShape) + { + ushort other = FindPictureTwin(id); + if (other != id && FindPictureTwin(other) != id) + { + other = id; + } + + _transposed[id] = other; + _transposed[other] = id; + return other; + } + + PairUp(id); + return _transposed.TryGetValue(id, out known) ? known : _transposed[id] = id; + } + + /// + /// Where a tile sits. A wall-like tile is read from which half of its cell the art covers, + /// a roof tile from the empty rows under its art; everything else is in the cell. + /// + public static TilePlacement Placement(ushort id) + { + if (id >= TileData.ItemTable.Length) + { + return TilePlacement.Cell; + } + + TileFlag flags = TileData.ItemTable[id].Flags; + Shape shape = Load(id); + if (shape == null || shape.Opaque == 0) + { + return TilePlacement.Cell; + } + + if ((flags & TileFlag.Roof) != 0) + { + // Half a cell is 22 pixels of empty rows under the art. + return shape.Height - 1 - shape.MaxY >= 11 ? TilePlacement.Lifted : TilePlacement.Cell; + } + + if ((flags & (TileFlag.Wall | TileFlag.Window)) == 0) + { + return TilePlacement.Cell; + } + + // A wall on the +Y edge runs from the diamond's left corner to its bottom corner, so its + // art stays left of the right quarter; a +X edge wall right of the left quarter; a post + // is a column in the middle. + int quarter = shape.Width / 4; + bool reachesLeft = shape.MinX < quarter - 2; + bool reachesRight = shape.MaxX > shape.Width - quarter + 1; + if (!reachesLeft && !reachesRight) + { + return TilePlacement.Vertex; + } + + if (reachesLeft && !reachesRight && shape.Left > shape.Right) + { + return TilePlacement.SouthEdge; + } + + return reachesRight && !reachesLeft && shape.Right > shape.Left ? TilePlacement.EastEdge : TilePlacement.Cell; + } + + /// + /// Pairs the tiles around whose silhouettes mirror each other: every + /// possible pair is scored and the best ones are taken first, so three near-equal wall + /// pieces and their three twins pair off the same way whichever is asked for first. + /// + private static void PairUp(ushort id) + { + var group = new List { id }; + var seen = new HashSet { id }; + var pairs = new List<(ushort A, ushort B, double Score)>(); + for (int i = 0; i < group.Count && group.Count < 96; i++) + { + ushort a = group[i]; + foreach ((ushort b, double score) in Candidates(a)) + { + pairs.Add((a, b, score)); + if (seen.Add(b)) + { + group.Add(b); + } + } + } + + pairs.Sort((x, y) => y.Score != x.Score ? y.Score.CompareTo(x.Score) : (x.A + x.B).CompareTo(y.A + y.B)); + var taken = new HashSet(); + foreach (var pair in pairs) + { + if (taken.Contains(pair.A) || taken.Contains(pair.B) || _transposed.ContainsKey(pair.A) || _transposed.ContainsKey(pair.B)) + { + continue; + } + + taken.Add(pair.A); + taken.Add(pair.B); + _transposed[pair.A] = pair.B; + _transposed[pair.B] = pair.A; + } + + foreach (ushort member in group) + { + _transposed.TryAdd(member, member); + } + } + + /// The neighbouring tiles whose art could be the mirror image of this one, with a score. + private static IEnumerable<(ushort Id, double Score)> Candidates(ushort id) + { + Shape shape = Load(id); + if (shape == null || shape.Opaque == 0) + { + yield break; + } + + ItemData data = TileData.ItemTable[id]; + int from = Math.Max(0, id - _searchRange); + int to = Math.Min(TileData.ItemTable.Length - 1, id + _searchRange); + for (int other = from; other <= to; other++) + { + if (other == id) + { + continue; + } + + ItemData otherData = TileData.ItemTable[other]; + if (otherData.Height != data.Height || !SameKind(otherData.Flags, data.Flags) || !SameSet(otherData.Name, data.Name) || + (otherData.Flags & TileFlag.Animation) != 0) + { + continue; + } + + Shape candidate = Load((ushort)other); + if (candidate == null || candidate.Opaque == 0 || + Math.Abs(candidate.Width - shape.Width) > 4 || Math.Abs(candidate.Height - shape.Height) > 4 || + Compare(candidate, candidate).Shape >= _sameShape) + { + continue; + } + + var score = Compare(shape, candidate); + if (score.Shape >= _twinShape) + { + // Silhouette first, then colour, then how close the ids are. + yield return ((ushort)other, score.Shape - (score.Colour / 400.0) - (Math.Abs(other - id) / 2000.0)); + } + } + } + + /// + /// For a tile whose silhouette is its own mirror image (a floor): the neighbour with the same + /// silhouette whose picture is clearly the mirrored one, such as planks running the other way. + /// + private static ushort FindPictureTwin(ushort id) + { + Shape shape = Load(id); + double own = Compare(shape, shape).Colour; + if (own <= 12) + { + return id; + } + + ItemData data = TileData.ItemTable[id]; + ushort best = id; + double bestColour = own * 0.6; + int from = Math.Max(0, id - _searchRange); + int to = Math.Min(TileData.ItemTable.Length - 1, id + _searchRange); + for (int other = from; other <= to; other++) + { + ItemData otherData = TileData.ItemTable[other]; + Shape candidate = other == id || otherData.Height != data.Height || !SameKind(otherData.Flags, data.Flags) ? null : Load((ushort)other); + if (candidate == null || candidate.Width != shape.Width || candidate.Height != shape.Height) + { + continue; + } + + var score = Compare(shape, candidate); + if (score.Shape >= 0.98 && score.Colour < bestColour) + { + best = (ushort)other; + bestColour = score.Colour; + } + } + + return best; + } + + /// + /// Tiledata names of one set: equal, or one is the other with a letter more ("shingle", + /// "shingles"). A twin is always of the same set: a tile roof never turns into shingles. + /// + private static bool SameSet(string a, string b) + { + a ??= string.Empty; + b ??= string.Empty; + return Math.Abs(a.Length - b.Length) <= 1 && + (a.StartsWith(b, StringComparison.OrdinalIgnoreCase) || b.StartsWith(a, StringComparison.OrdinalIgnoreCase)); + } + + private static bool SameKind(TileFlag a, TileFlag b) + { + const TileFlag kind = TileFlag.Wall | TileFlag.Roof | TileFlag.Door | TileFlag.Window | TileFlag.Surface | TileFlag.Bridge; + return (a & kind) == (b & kind); + } + + /// + /// How well matches the mirror image of , both + /// standing on the same cell: shared part of the silhouettes, and the colour difference there. + /// + private static (double Shape, double Colour) Compare(Shape a, Shape b) + { + int width = Math.Max(a.Width, b.Width) + 2; + int height = Math.Max(a.Height, b.Height); + int offsetA = (width / 2) - (a.Width / 2); + int offsetB = (width / 2) - (b.Width / 2); + int inter = 0, union = 0; + long colour = 0; + for (int y = 0; y < height; y++) + { + int ay = y - (height - a.Height); + int by = y - (height - b.Height); + for (int x = 0; x < width; x++) + { + int ax = x - offsetA; + int bx = b.Width - 1 - (x - offsetB); + int ai = ay >= 0 && ax >= 0 && ax < a.Width ? ((ay * a.Width) + ax) * 4 : -1; + int bi = by >= 0 && bx >= 0 && bx < b.Width ? ((by * b.Width) + bx) * 4 : -1; + bool hasA = ai >= 0 && a.Rgba[ai + 3] != 0; + bool hasB = bi >= 0 && b.Rgba[bi + 3] != 0; + if (hasA || hasB) + { + union++; + } + + if (hasA && hasB) + { + inter++; + colour += Math.Abs(a.Rgba[ai] - b.Rgba[bi]) + Math.Abs(a.Rgba[ai + 1] - b.Rgba[bi + 1]) + Math.Abs(a.Rgba[ai + 2] - b.Rgba[bi + 2]); + } + } + } + + return (union == 0 ? 0 : (double)inter / union, inter == 0 ? 255 : colour / (3.0 * inter)); + } + + private static Shape Load(ushort id) + { + if (_shapes.TryGetValue(id, out Shape shape)) + { + return shape; + } + + int width = 0, height = 0; + byte[] rgba = Art.IsValidStatic(id) ? ArtPixels.LoadStatic(id, out width, out height) : null; + if (rgba == null) + { + _shapes[id] = null; + return null; + } + + shape = new Shape { Width = width, Height = height, Rgba = rgba, MinX = width, MaxX = -1 }; + int centre = width / 2; + ulong hash = 14695981039346656037UL ^ (ulong)((width << 16) | height); + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + int i = ((y * width) + x) * 4; + bool opaque = rgba[i + 3] != 0; + uint pixel = opaque ? (uint)((rgba[i] << 16) | (rgba[i + 1] << 8) | rgba[i + 2]) | 0xFF000000 : 0; + hash = (hash ^ pixel) * 1099511628211UL; + if (!opaque) + { + continue; + } + + shape.Opaque++; + shape.MinX = Math.Min(shape.MinX, x); + shape.MaxX = Math.Max(shape.MaxX, x); + shape.MaxY = y; + if (x < centre) + { + shape.Left++; + } + else + { + shape.Right++; + } + } + } + + shape.Hash = hash == 0 ? 1 : hash; + _shapes[id] = shape; + return shape; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/ArtMetrics.cs b/UoFiddler.Plugin.MultiEditor/Classes/ArtMetrics.cs new file mode 100644 index 00000000..d49a4689 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/ArtMetrics.cs @@ -0,0 +1,38 @@ +/*************************************************************************** + * + * $Author: MuadDib & Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + + +using System.Drawing; +using Ultima; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// Size of a static's art, which places a tile on the canvas. + /// + internal static class ArtMetrics + { + public static bool TryGetSize(ushort id, out int width, out int height) + { + Bitmap bmp = id != 0xFFFF ? Art.GetStatic(id) : null; + if (bmp == null) + { + width = 0; + height = 0; + return false; + } + + width = bmp.Width; + height = bmp.Height; + return true; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs b/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs new file mode 100644 index 00000000..e57ba7ff --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs @@ -0,0 +1,92 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Collections.Generic; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// The saved fields of a tile, used to put a changed tile back. + /// + internal readonly record struct TileState(ushort Id, int X, int Y, int Z, bool Invisible) + { + public static TileState Of(MultiTile tile) => new(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible); + + public void ApplyTo(MultiTile tile) + { + tile.Id = Id; + tile.Invisible = Invisible; + tile.X = X; + tile.Y = Y; + tile.Z = Z; + } + } + + /// + /// One undo step: the tiles an edit added, removed and changed, and the multi size before and + /// after. Tiles are kept as the same objects, so references to them survive undo and redo. + /// + internal sealed class EditCommand + { + public EditCommand(string action, int width, int height) + { + Action = action; + OldWidth = NewWidth = width; + OldHeight = NewHeight = height; + } + + public string Action { get; } + + public HashSet Added { get; } = new(); + + public HashSet Removed { get; } = new(); + + /// + /// State of each changed tile before the edit. Tiles added by the same edit are not listed. + /// + public Dictionary Before { get; } = new(); + + /// + /// State of each changed tile after the edit, filled in when the edit ends. + /// + public Dictionary After { get; } = new(); + + public int OldWidth { get; } + + public int OldHeight { get; } + + public int NewWidth { get; set; } + + public int NewHeight { get; set; } + + public bool IsEmpty => Added.Count == 0 && Removed.Count == 0 && Before.Count == 0 && + OldWidth == NewWidth && OldHeight == NewHeight; + + public void CaptureAfter() + { + After.Clear(); + foreach (MultiTile tile in new List(Before.Keys)) + { + TileState after = TileState.Of(tile); + + // A tile changed and changed back is no change at all. + if (after == Before[tile]) + { + Before.Remove(tile); + } + else + { + After[tile] = after; + } + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs b/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs new file mode 100644 index 00000000..cca7e3e2 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs @@ -0,0 +1,484 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + internal enum GroupTransformKind + { + RotateLeft, + RotateRight, + MirrorX, + MirrorY + } + + /// + /// Rotates or mirrors a group of tiles. Graphics in UO never turn, so a piece that faces a way + /// (a stair, roof slope, door) is swapped for the piece that faces the new way. + /// + /// Walls sit on cell edges, not in cells: they are turned into edges, the edges + /// transformed, and the wall pieces chosen again, so corners and posts come out right. + /// Pieces the client's house tables name by direction (roof slopes, stairs) take the + /// piece of their style for the new direction. Classic tiles that copy such a piece count too. + /// Everything else is turned by its art (): the twin with the + /// mirrored picture is the same piece along the other axis. The facing table is used where it + /// does not contradict the art. + /// + /// + internal static class GroupTransform + { + private static readonly Dictionary _directions = new Dictionary + { + ["North"] = (0, -1), ["East"] = (1, 0), ["South"] = (0, 1), ["West"] = (-1, 0) + }; + + // Door pieces: the end of the wall the hinge is at, and the swing. + private static readonly Dictionary _doors = new Dictionary + { + ["Piece3"] = ((-1, 0), true), ["Piece4"] = ((1, 0), false), ["Piece1"] = ((-1, 0), false), ["Piece2"] = ((1, 0), true), + ["Piece5"] = ((0, 1), true), ["Piece6"] = ((0, -1), false), ["Piece7"] = ((0, 1), false), ["Piece8"] = ((0, -1), true) + }; + + private static readonly string[] _southColumns = { "South1", "South2", "South3", "WindowS", "AltWindowS", "SecondAltWindowS" }; + private static readonly string[] _eastColumns = { "East3", "East2", "East1", "WindowE", "AltWindowE", "SecondAltWindowE" }; + + private static (int A, int B, int C, int D) Matrix(GroupTransformKind kind) => kind switch + { + // (x, y) -> (A*x + B*y, C*x + D*y) + GroupTransformKind.RotateLeft => (0, 1, -1, 0), + GroupTransformKind.RotateRight => (0, -1, 1, 0), + GroupTransformKind.MirrorX => (-1, 0, 0, 1), + _ => (1, 0, 0, -1) + }; + + public static bool SwapsAxes(GroupTransformKind kind) => kind is GroupTransformKind.RotateLeft or GroupTransformKind.RotateRight; + + /// + /// The tiles to add for the transformed group, placed so the group's box keeps its top-left + /// cell. Every tile of is replaced. + /// + public static List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> Apply( + IReadOnlyCollection group, HouseStyles styles, RotationTable table, GroupTransformKind kind) + { + var m = Matrix(kind); + bool mirror = (m.A * m.D) - (m.B * m.C) < 0; + bool swaps = SwapsAxes(kind); + + (double X, double Y) Map(double x, double y) => ((m.A * x) + (m.B * y), (m.C * x) + (m.D * y)); + (int X, int Y) MapCell(int x, int y) + { + var c = Map(x + 0.5, y + 0.5); + return ((int)Math.Floor(c.X), (int)Math.Floor(c.Y)); + } + + // An edge of cell (x, y): its midpoint and direction move; the result is a +Y edge (S) + // or a +X edge (E) of some cell. + (bool South, int X, int Y) MapEdge(bool south, int x, int y) + { + var mid = south ? Map(x + 0.5, y + 1) : Map(x + 1, y + 0.5); + var dir = south ? Map(1, 0) : Map(0, 1); + return Math.Abs(dir.X) > 0.5 + ? (true, (int)Math.Floor(mid.X), (int)Math.Round(mid.Y) - 1) + : (false, (int)Math.Round(mid.X) - 1, (int)Math.Floor(mid.Y)); + } + + // A post stands on the cell's +X/+Y corner: that point moves. + (int X, int Y) MapVertex(int x, int y) + { + var v = Map(x + 1, y + 1); + return ((int)Math.Round(v.X) - 1, (int)Math.Round(v.Y) - 1); + } + + // A roof piece covers the area around its cell's -X/-Y corner: that point moves. + (int X, int Y) MapLifted(int x, int y) + { + var v = Map(x, y); + return ((int)Math.Round(v.X), (int)Math.Round(v.Y)); + } + + string MapDirection(string label) + { + var d = _directions[label]; + var t = Map(d.X, d.Y); + return _directions.First(kv => kv.Value == ((int)Math.Round(t.X), (int)Math.Round(t.Y))).Key; + } + + // Keep the group's top-left: shift by the change of the cell box's corner. + int minX = group.Min(t => t.X), minY = group.Min(t => t.Y); + var mapped = group.Select(t => MapCell(t.X, t.Y)).ToList(); + int shiftX = minX - mapped.Min(c => c.X); + int shiftY = minY - mapped.Min(c => c.Y); + + var result = new List<(ushort, int, int, int, bool, int)>(); + var walls = new Dictionary<(HouseStyle Style, int Z), WallLayer>(); + var doorCells = new HashSet<(int, int, int)>(); + var doorEdges = new List<(int Z, bool South, int X, int Y)>(); + + WallLayer Layer(HouseStyle style, int z) + { + if (!walls.TryGetValue((style, z), out WallLayer layer)) + { + walls[(style, z)] = layer = new WallLayer(); + } + + return layer; + } + + foreach (MultiTile tile in group) + { + styles.TryGetRoleByArt(tile.Id, out HouseStyle style, out string slot, out bool exact); + + if (style?.Kind == HousePartKind.Wall && exact) + { + WallLayer layer = Layer(style, tile.Z); + if (slot == "Post") + { + // Posts are rebuilt from the edges; one standing alone is put back afterwards. + var v = MapVertex(tile.X, tile.Y); + layer.Posts.Add((v.X + shiftX, v.Y + shiftY, tile.Id)); + continue; + } + + bool isSouth = slot == "Corner" || Array.IndexOf(_southColumns, slot) >= 0; + bool isEast = slot == "Corner" || Array.IndexOf(_eastColumns, slot) >= 0; + foreach (bool south in new[] { true, false }) + { + if (south ? !isSouth : !isEast) + { + continue; + } + + var e = MapEdge(south, tile.X, tile.Y); + var cell = (e.X + shiftX, e.Y + shiftY); + (e.South ? layer.S : layer.E).Add(cell); + + if (slot is not ("Corner" or "South1" or "South2" or "South3" or "East1" or "East2" or "East3")) + { + // A window keeps its look: the same piece, or its twin along the other axis. + ushort keep = e.South == south ? tile.Id : WallTwin(styles, style, tile.Id, slot); + if (keep != 0) + { + (e.South ? layer.KeepS : layer.KeepE)[cell] = keep; + } + } + } + + continue; + } + + TilePlacement placement = ArtFacing.Placement(tile.Id); + var (nx, ny) = placement == TilePlacement.Lifted ? MapLifted(tile.X, tile.Y) : MapCell(tile.X, tile.Y); + ushort id = tile.Id; + + if (style?.Kind == HousePartKind.Door && exact && _doors.TryGetValue(slot, out var door)) + { + // A door is an edge too: it moves like one and swaps to the piece hinged the new way. + var e = MapEdge(WallPlanner.DoorAlongX(slot), tile.X, tile.Y); + (nx, ny) = (e.X, e.Y); + var h = Map(door.Hinge.X, door.Hinge.Y); + var hinge = ((int)Math.Round(h.X), (int)Math.Round(h.Y)); + bool clockwise = door.Clockwise ^ mirror; + string newSlot = _doors.First(kv => kv.Value == (hinge, clockwise)).Key; + id = style.Get(newSlot) is var doorId and not 0 ? doorId : id; + doorCells.Add((nx + shiftX, ny + shiftY, tile.Z)); + doorEdges.Add((tile.Z, e.South, nx + shiftX, ny + shiftY)); + result.Add((id, nx + shiftX, ny + shiftY, tile.Z, tile.Invisible, tile.Extra)); + continue; + } + + string turnedSlot = style?.Kind is HousePartKind.Roof or HousePartKind.Stair ? TurnSlot(slot, MapDirection, swaps) : null; + if (styles.TryGetStairCorner(tile.Id, out ushort[] corners, out int corner)) + { + // Corners go south-east, north-east, north-west, south-west on a left turn. + id = corners[kind switch + { + GroupTransformKind.RotateLeft => (corner + 1) % 4, + GroupTransformKind.RotateRight => (corner + 3) % 4, + GroupTransformKind.MirrorX => 3 - corner, + _ => corner ^ 1 + }]; + } + else if (turnedSlot != null && IsDirectional(slot)) + { + // Named by direction in the client's tables: the piece of the style for the new one. + if (turnedSlot != slot && style.Get(turnedSlot) is var turned and not 0) + { + id = exact ? turned : CopyOf(styles, turned, tile.Id); + } + } + else + { + // Turned by its art. Wall-like pieces sit on an edge or a corner of their cell. + if (placement is TilePlacement.SouthEdge or TilePlacement.EastEdge) + { + var e = MapEdge(placement == TilePlacement.SouthEdge, tile.X, tile.Y); + (nx, ny) = (e.X, e.Y); + } + else if (placement == TilePlacement.Vertex) + { + (nx, ny) = MapVertex(tile.X, tile.Y); + } + + id = TurnByArt(tile.Id, table, kind); + } + + result.Add((id, nx + shiftX, ny + shiftY, tile.Z, tile.Invisible, tile.Extra)); + } + + foreach (var ((style, z), layer) in walls) + { + // Doors count as wall edges, so the wall joins them; their cells keep the door. + foreach (var door in doorEdges.Where(d => d.Z == z)) + { + (door.South ? layer.S : layer.E).Add((door.X, door.Y)); + } + + var placed = new HashSet<(int, int)>(); + if (layer.S.Count + layer.E.Count > 0) + { + int x0 = layer.S.Concat(layer.E).Min(c => c.Item1) - 1; + int y0 = layer.S.Concat(layer.E).Min(c => c.Item2) - 1; + int x1 = layer.S.Concat(layer.E).Max(c => c.Item1); + int y1 = layer.S.Concat(layer.E).Max(c => c.Item2); + for (int x = x0; x <= x1; ++x) + { + for (int y = y0; y <= y1; ++y) + { + if (doorCells.Contains((x, y, z))) + { + continue; + } + + string column = WallPlanner.PieceFor(layer.S, layer.E, x, y); + if (column == null) + { + continue; + } + + ushort id = 0; + if (column.StartsWith("South", StringComparison.Ordinal)) + { + id = layer.KeepS.TryGetValue((x, y), out ushort keep) ? keep : FirstOf(style, column, "South2", "South1", "South3"); + } + else if (column.StartsWith("East", StringComparison.Ordinal)) + { + id = layer.KeepE.TryGetValue((x, y), out ushort keep) ? keep : FirstOf(style, column, "East2", "East1", "East3"); + } + else + { + id = style.Get(column); + } + + if (id != 0) + { + result.Add((id, x, y, z, false, 0)); + placed.Add((x, y)); + } + } + } + } + + foreach (var post in layer.Posts) + { + // A post no wall asked for (a pillar on its own) stays a post. + if (placed.Add((post.X, post.Y)) && !doorCells.Contains((post.X, post.Y, z))) + { + result.Add((post.Id, post.X, post.Y, z, false, 0)); + } + } + } + + return result; + } + + private sealed class WallLayer + { + public readonly HashSet<(int, int)> S = new HashSet<(int, int)>(); + public readonly HashSet<(int, int)> E = new HashSet<(int, int)>(); + public readonly Dictionary<(int, int), ushort> KeepS = new Dictionary<(int, int), ushort>(); + public readonly Dictionary<(int, int), ushort> KeepE = new Dictionary<(int, int), ushort>(); + public readonly List<(int X, int Y, ushort Id)> Posts = new List<(int, int, ushort)>(); + } + + private static ushort FirstOf(HouseStyle style, params string[] columns) + { + foreach (string column in columns) + { + ushort id = style.Get(column); + if (id != 0) + { + return id; + } + } + + return 0; + } + + /// + /// The piece that shows a window (or other wall variant) on a wall along the other axis: the + /// tile with the mirrored art when it is a wall piece of that axis, else the paired column + /// of the style, else 0 for a plain piece. + /// + private static ushort WallTwin(HouseStyles styles, HouseStyle style, ushort id, string slot) + { + bool south = Array.IndexOf(_southColumns, slot) >= 0; + string[] wanted = south ? _eastColumns : _southColumns; + + ushort twin = ArtFacing.Transpose(id); + if (twin != id && styles.TryGetRole(twin, out HouseStyle twinStyle, out string twinSlot) && + twinStyle.Kind == HousePartKind.Wall && Array.IndexOf(wanted, twinSlot) >= 0) + { + return twin; + } + + int index = Array.IndexOf(south ? _southColumns : _eastColumns, slot); + return index >= 0 ? style.Get(wanted[index]) : (ushort)0; + } + + /// + /// A tile turned without a named role. A quarter turn swaps the axes, so the art's mirror + /// twin is the turned piece for everything that looks the same from both ends (walls, + /// fences, tables). A piece with four facings needs the facing table for the other half of + /// its turns; the table is believed unless the art says otherwise. + /// + private static ushort TurnByArt(ushort id, RotationTable table, GroupTransformKind kind) + { + ushort twin = ArtFacing.Transpose(id); + ushort left = TableAgreesWithArt(id, table) ? table.TurnLeft(id) : id; + ushort right = left != id ? table.TurnRight(id) : id; + + switch (kind) + { + case GroupTransformKind.RotateLeft: + return left != id ? left : twin; + case GroupTransformKind.RotateRight: + return right != id ? right : twin; + case GroupTransformKind.MirrorX: + // Flips what faces east or west: of those, the twin is the piece a right turn gives. + return left != id && twin == right && twin != id ? table.TurnLeft(left) : id; + default: + return left != id && twin == left && twin != id ? table.TurnLeft(left) : id; + } + } + + /// + /// Whether the table's turns for a tile fit its art. Turning left goes south, east, north, + /// west; south/east and north/west are mirror twins. So a cycle of two must be twins, and + /// in a cycle of four every twin the art finds must be the next or the previous tile. + /// + private static bool TableAgreesWithArt(ushort id, RotationTable table) + { + var cycle = new List { id }; + for (ushort next = table.TurnLeft(id); next != id; next = table.TurnLeft(next)) + { + if (cycle.Count == 4 || cycle.Contains(next) || table.TurnLeft(next) == next) + { + return false; + } + + cycle.Add(next); + } + + if (cycle.Count == 1 || cycle.Count == 3) + { + return false; + } + + for (int i = 0; i < cycle.Count; i++) + { + ushort twin = ArtFacing.Transpose(cycle[i]); + if (twin == cycle[i]) + { + continue; + } + + ushort next = cycle[(i + 1) % cycle.Count]; + ushort previous = cycle[(i + cycle.Count - 1) % cycle.Count]; + if (twin != next && twin != previous) + { + return false; + } + } + + return true; + } + + /// + /// For a tile that copies a listed piece: the copy of closest to + /// , so a classic roof stays in its classic ids. + /// + private static ushort CopyOf(HouseStyles styles, ushort listed, ushort original) + { + for (int distance = 0; distance <= 32; distance++) + { + foreach (int candidate in new[] { original - distance, original + distance }) + { + if (candidate >= 0 && candidate <= ushort.MaxValue && + styles.TryGetListedTwin((ushort)candidate, out ushort twin) && twin == listed) + { + return (ushort)candidate; + } + } + } + + return listed; + } + + private static bool IsDirectional(string slot) + { + return _directions.ContainsKey(slot) || slot.EndsWith("Dent", StringComparison.Ordinal) || + slot.EndsWith("TPiece", StringComparison.Ordinal) || slot is "NSCrosspiece" or "EWCrosspiece"; + } + + /// + /// The column a direction-named piece moves to: North/East/South/West and their dents and + /// T pieces turn; crosspieces swap axes when the group turns a quarter. + /// + private static string TurnSlot(string slot, Func mapDirection, bool swapsAxes) + { + foreach (string direction in _directions.Keys) + { + if (slot == direction) + { + return mapDirection(direction); + } + } + + foreach (string suffix in new[] { "Dent", "TPiece" }) + { + // NDent, ETPiece ...: the first letter is the direction. + if (slot.Length == 1 + suffix.Length && slot.EndsWith(suffix, StringComparison.Ordinal)) + { + string direction = _directions.Keys.First(d => d[0] == slot[0]); + return mapDirection(direction)[0] + suffix; + } + } + + if (swapsAxes) + { + if (slot == "NSCrosspiece") + { + return "EWCrosspiece"; + } + + if (slot == "EWCrosspiece") + { + return "NSCrosspiece"; + } + } + + return slot; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs new file mode 100644 index 00000000..0d2d73d5 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs @@ -0,0 +1,442 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using UoFiddler.Controls.Classes.TilesInfo; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + internal enum HousePartKind + { + Wall, + Floor, + Door, + Stair, + Roof, + Misc, + Teleporter + } + + /// + /// One row of a client house design table (walls.txt, floors.txt ...): a named set of pieces, + /// each under the column label the client uses (South1, Corner, F3, MultiNorth ...). + /// + internal sealed class HouseStyle + { + private readonly Dictionary _slots = new Dictionary(); + + public HouseStyle(HousePartKind kind, string group, string name) + { + Kind = kind; + Group = group; + Name = name; + } + + public HousePartKind Kind { get; } + + /// The category name (the first style's comment), grouping a material's styles. + public string Group { get; } + + public string Name { get; } + + public IReadOnlyDictionary Slots => _slots; + + /// A piece to show for the style in lists. + public ushort IconId { get; private set; } + + /// The piece under a column label, or 0 when the style has none. + public ushort Get(string label) => _slots.TryGetValue(label, out ushort id) ? id : (ushort)0; + + internal void Add(string label, ushort id) + { + _slots[label] = id; + if (IconId == 0) + { + IconId = id; + } + } + + public override string ToString() => Name; + } + + /// + /// The client's house design tables, read once per client, with a lookup from tile id to the + /// style and column it belongs to. + /// + internal sealed class HouseStyles + { + private static readonly Dictionary _kinds = new Dictionary + { + ["Walls"] = HousePartKind.Wall, + ["Floors"] = HousePartKind.Floor, + ["Doors"] = HousePartKind.Door, + ["Stairs"] = HousePartKind.Stair, + ["Roof"] = HousePartKind.Roof, + ["Misc"] = HousePartKind.Misc, + ["Teleporters"] = HousePartKind.Teleporter + }; + + private readonly Dictionary _roles = new Dictionary(); + + // Listed pieces by art hash, for tiles that copy one under another id. Filled on first use. + private Dictionary _listedByArt; + + // Stair corner pieces: the set of four each belongs to and its place in it. Filled on first use. + private Dictionary _stairCorners; + + private HouseStyles() + { + } + + public List Styles { get; } = new List(); + + public List Errors { get; } = new List(); + + /// + /// Reads the tables. With a floors.txt row, which is a + /// palette of up to 16 tiles often in several colours, becomes one style per colour, so a + /// floor laid with a style does not mix them. + /// + public static HouseStyles Load(bool splitFloorsByColour = false) + { + // New tables mean the client files may have changed: measure the art again. + ArtFacing.Clear(); + + var result = new HouseStyles(); + List files = TileGroupRegistry.LoadAll(out List errors); + foreach (TileGroupFile file in files) + { + if (!_kinds.TryGetValue(file.DisplayName, out HousePartKind kind)) + { + continue; + } + + foreach (TileCategory category in file.Categories) + { + foreach (TileStyle tileStyle in category.Styles) + { + var style = new HouseStyle(kind, category.Name, tileStyle.Name); + foreach (TileSlot slot in tileStyle.Slots) + { + // Stairs list stair multis; they are multi ids, not art. + bool multiColumn = slot.Label.StartsWith("Multi", System.StringComparison.Ordinal); + if (slot.IsEmpty || slot.TileId > ushort.MaxValue || (!multiColumn && !slot.IsValid)) + { + continue; + } + + style.Add(slot.Label, (ushort)slot.TileId); + } + + if (style.Slots.Count == 0) + { + continue; + } + + IEnumerable parts = splitFloorsByColour && kind == HousePartKind.Floor + ? SplitByColour(style) + : new[] { style }; + foreach (HouseStyle part in parts) + { + result.Styles.Add(part); + foreach (KeyValuePair piece in part.Slots) + { + // Stair multi columns hold multi ids, not art. + if (!piece.Key.StartsWith("Multi", System.StringComparison.Ordinal)) + { + result._roles.TryAdd(piece.Value, (part, piece.Key)); + } + } + } + } + } + } + + result.Errors.AddRange(errors); + return result; + } + + /// How far apart two radar colours may be (RGB distance) and still count as one floor colour. + private const int _sameColour = 20; + + /// + /// Splits a floor row into styles of one colour each, by the tiles' radar colours. Pieces keep + /// their column labels; a tile listed twice counts once. Each part is named after its tiles' + /// tiledata name, numbered where a row has several of the same, and grouped under the row's name. + /// + private static List SplitByColour(HouseStyle style) + { + var clusters = new List<(System.Drawing.Color Colour, List> Pieces)>(); + var seen = new HashSet(); + foreach (KeyValuePair piece in style.Slots) + { + if (!seen.Add(piece.Value)) + { + continue; + } + + System.Drawing.Color colour = Ultima.Helpers.HueHelpers.HueToColor(Ultima.RadarCol.GetItemColor(piece.Value)); + int index = clusters.FindIndex(c => + { + int dr = c.Colour.R - colour.R, dg = c.Colour.G - colour.G, db = c.Colour.B - colour.B; + return (dr * dr) + (dg * dg) + (db * db) <= _sameColour * _sameColour; + }); + if (index < 0) + { + clusters.Add((colour, new List> { piece })); + } + else + { + clusters[index].Pieces.Add(piece); + } + } + + if (clusters.Count <= 1) + { + return new List { style }; + } + + var names = new List(); + foreach (var (_, pieces) in clusters) + { + string name = Ultima.TileData.ItemTable[pieces[0].Value].Name?.Trim(); + if (string.IsNullOrEmpty(name) || name.StartsWith("Missing", System.StringComparison.OrdinalIgnoreCase)) + { + name = style.Name; + } + + names.Add(char.ToUpperInvariant(name[0]) + name.Substring(1)); + } + + var result = new List(); + for (int i = 0; i < clusters.Count; i++) + { + string name = names[i]; + if (names.FindAll(n => n == name).Count > 1) + { + name += " " + (names.GetRange(0, i + 1).FindAll(n => n == names[i]).Count); + } + + var part = new HouseStyle(style.Kind, style.Name, name); + foreach (KeyValuePair piece in clusters[i].Pieces) + { + part.Add(piece.Key, piece.Value); + } + + result.Add(part); + } + + return result; + } + + /// The style and column a tile id is listed under, when any. + public bool TryGetRole(ushort id, out HouseStyle style, out string slot) + { + if (_roles.TryGetValue(id, out var role)) + { + style = role.Style; + slot = role.Slot; + return true; + } + + style = null; + slot = null; + return false; + } + + /// + /// The style and column of a tile, also when the tables list it under another id with the + /// same art: the classic roof and stair tiles are copies of the custom house pieces, which + /// is how their facing is known. tells the two cases apart. + /// + public bool TryGetRoleByArt(ushort id, out HouseStyle style, out string slot, out bool exact) + { + exact = TryGetRole(id, out style, out slot); + if (exact) + { + return true; + } + + return TryGetListedTwin(id, out ushort listed) && TryGetRole(listed, out style, out slot); + } + + /// + /// The listed piece a tile copies. Either the art is the same, or the tile sits in a run of + /// ids that copies a listed run piece by piece (the classic roof sets do; one or two of + /// their pieces were redrawn, and those are found by their place in the run). + /// + public bool TryGetListedTwin(ushort id, out ushort listed) + { + if (_roles.ContainsKey(id)) + { + listed = id; + return true; + } + + if (TryGetSameArt(id, out listed)) + { + return true; + } + + // Neighbours of the same kind that copy a listed piece say where this one's twin should be. + if (id >= Ultima.TileData.ItemTable.Length) + { + listed = 0; + return false; + } + + string name = Ultima.TileData.ItemTable[id].Name; + var votes = new Dictionary<(int Offset, HouseStyle Style), int>(); + for (int distance = 1; distance <= 6; distance++) + { + foreach (int neighbour in new[] { id - distance, id + distance }) + { + if (neighbour >= 0 && neighbour < Ultima.TileData.ItemTable.Length && !_roles.ContainsKey((ushort)neighbour) && + SameSet(Ultima.TileData.ItemTable[neighbour].Name, name) && + TryGetSameArt((ushort)neighbour, out ushort twin)) + { + var key = (twin - neighbour, _roles[twin].Style); + votes[key] = votes.TryGetValue(key, out int count) ? count + 1 : 1; + } + } + } + + foreach (KeyValuePair<(int Offset, HouseStyle Style), int> vote in votes) + { + int candidate = id + vote.Key.Offset; + if (vote.Value >= 3 && candidate >= 0 && candidate <= ushort.MaxValue && + _roles.TryGetValue((ushort)candidate, out (HouseStyle Style, string Slot) role) && + role.Style == vote.Key.Style) + { + listed = (ushort)candidate; + return true; + } + } + + listed = 0; + return false; + } + + /// + /// The four corner pieces of a stair set, in the order a left turn goes through them + /// (south-east, north-east, north-west, south-west), and where is in + /// it. stairs.txt names only the two front corners of a stair that climbs north: the one + /// that is its own mirror image is the south-east one, the mirror twin of the other is the + /// north-east one, and the fourth is the id next to those three. + /// + public bool TryGetStairCorner(ushort id, out ushort[] corners, out int index) + { + if (_stairCorners == null) + { + _stairCorners = new Dictionary(); + foreach (HouseStyle style in Styles) + { + if (style.Kind != HousePartKind.Stair) + { + continue; + } + + AddStairCorners(style.Get("Squared1"), style.Get("Squared2")); + AddStairCorners(style.Get("Rounded1"), style.Get("Rounded2")); + } + } + + if (_stairCorners.TryGetValue(id, out (ushort[] Corners, int Index) found)) + { + corners = found.Corners; + index = found.Index; + return true; + } + + corners = null; + index = -1; + return false; + } + + private void AddStairCorners(ushort first, ushort second) + { + if (first == 0 || second == 0) + { + return; + } + + bool firstSymmetric = ArtFacing.Transpose(first) == first; + bool secondSymmetric = ArtFacing.Transpose(second) == second; + if (firstSymmetric == secondSymmetric) + { + return; + } + + ushort southEast = firstSymmetric ? first : second; + ushort southWest = firstSymmetric ? second : first; + ushort northEast = ArtFacing.Transpose(southWest); + + int low = Math.Min(southEast, Math.Min(southWest, northEast)); + int high = Math.Max(southEast, Math.Max(southWest, northEast)); + if (high - low != 2) + { + return; + } + + foreach (int candidate in new[] { low - 1, high + 1 }) + { + if (candidate < 0 || candidate > ushort.MaxValue || _roles.ContainsKey((ushort)candidate) || + ArtFacing.ArtHash((ushort)candidate) == 0 || ArtFacing.Transpose((ushort)candidate) != candidate) + { + continue; + } + + ushort[] corners = { southEast, northEast, (ushort)candidate, southWest }; + for (int i = 0; i < corners.Length; i++) + { + _stairCorners.TryAdd(corners[i], (corners, i)); + } + + return; + } + } + + /// Tiledata names of one set: equal, or one is the other with a letter more ("shingle", "shingles"). + private static bool SameSet(string a, string b) + { + a ??= string.Empty; + b ??= string.Empty; + return Math.Abs(a.Length - b.Length) <= 1 && + (a.StartsWith(b, StringComparison.OrdinalIgnoreCase) || b.StartsWith(a, StringComparison.OrdinalIgnoreCase)); + } + + private bool TryGetSameArt(ushort id, out ushort listed) + { + if (_listedByArt == null) + { + _listedByArt = new Dictionary(); + foreach (KeyValuePair role in _roles) + { + if (role.Value.Style.Kind is not (HousePartKind.Roof or HousePartKind.Stair)) + { + continue; + } + + ulong roleHash = ArtFacing.ArtHash(role.Key); + if (roleHash != 0) + { + _listedByArt.TryAdd(roleHash, role.Key); + } + } + } + + ulong hash = ArtFacing.ArtHash(id); + listed = 0; + return hash != 0 && _listedByArt.TryGetValue(hash, out listed); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs b/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs new file mode 100644 index 00000000..599b017a --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs @@ -0,0 +1,27 @@ +/*************************************************************************** + * + * $Author: MuadDib & Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// The view options the edited multi depends on. + /// + internal interface IMultiViewSettings + { + /// Tiles flagged as walls are not shown, and so not removed by area edits. + bool HideWalls { get; } + + bool ShowWalkables { get; } + + bool ShowDoubleSurface { get; } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MapExtract.cs b/UoFiddler.Plugin.MultiEditor/Classes/MapExtract.cs new file mode 100644 index 00000000..2b8a4257 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/MapExtract.cs @@ -0,0 +1,92 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.UI; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// An area of a facet to copy statics from. + internal sealed record MapArea(Map Map, int X, int Y, int Width, int Height, int MinZ, int MaxZ, bool NewDesign); + + /// + /// Copies the statics of a map area into multi tiles, so a building on the map can be edited + /// as a design. Land tiles are not copied. + /// + internal static class MapExtract + { + public static readonly (string Name, Func Map)[] Facets = + { + ("Felucca", () => Map.Felucca), + ("Trammel", () => Map.Trammel), + ("Ilshenar", () => Map.Ilshenar), + ("Malas", () => Map.Malas), + ("Tokuno", () => Map.Tokuno), + ("Ter Mur", () => Map.TerMur) + }; + + /// + /// The statics in the area between the Z limits, placed relative to the area's corner + /// and lowered so the lowest one sits at Z 0. + /// + public static List Extract(MapArea area) + { + var found = new List<(ushort Id, int X, int Y, int Z)>(); + int x1 = Math.Min(area.Map.Width, area.X + area.Width); + int y1 = Math.Min(area.Map.Height, area.Y + area.Height); + for (int x = Math.Max(0, area.X); x < x1; ++x) + { + for (int y = Math.Max(0, area.Y); y < y1; ++y) + { + foreach (HuedTile tile in area.Map.Tiles.GetStaticTiles(x, y)) + { + if (tile.Z >= area.MinZ && tile.Z <= area.MaxZ) + { + found.Add((tile.Id, x - area.X, y - area.Y, tile.Z)); + } + } + } + } + + var result = new List(found.Count); + if (found.Count == 0) + { + return result; + } + + int minZ = int.MaxValue; + foreach (var t in found) + { + minZ = Math.Min(minZ, t.Z); + } + + foreach (var t in found) + { + result.Add(new ClipboardTile(t.Id, t.X, t.Y, t.Z - minZ, false, 0)); + } + + return result; + } + + /// + /// Asks for the area, starting from . Returns null when cancelled. + /// + public static MapArea Ask(IWin32Window owner, MapArea initial, bool canPlaceIntoDesign) + { + using var form = new MapExtractForm(initial, canPlaceIntoDesign); + return form.ShowDialog(owner) == DialogResult.OK ? form.Area : null; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs index a7dcfde2..f792c388 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs @@ -1,9 +1,9 @@ /*************************************************************************** * * $Author: MuadDib & Turley - * + * * "THE BEER-WARE LICENSE" - * As long as you retain this notice you can do whatever you want with + * As long as you retain this notice you can do whatever you want with * this stuff. If we meet some day, and you think this stuff is worth it, * you can buy me a beer in return. * @@ -11,97 +11,101 @@ using System; using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Imaging; using Ultima; using UoFiddler.Controls.Classes; -using UoFiddler.Plugin.MultiEditor.UserControls; namespace UoFiddler.Plugin.MultiEditor.Classes { - internal class MultiEditorComponentList + /// + /// The edited multi. Tiles are kept per cell, each cell sorted in draw order with its virtual + /// floor tile, so walking the cells x-major then y gives the draw order of the whole multi. + /// Every edit is recorded as an for undo and redo. + /// + internal partial class MultiEditorComponentList { - public const int DefaultUndoStackSize = 50; - private int _undoListMaxSize = DefaultUndoStackSize; - - private bool _modified; - private static MultiEditorControl _parent; - private static Rectangle _drawDestRectangle; + public const int DefaultUndoStackSize = 200; public const int GapXMod = 44; public const int GapYMod = 22; + private readonly IMultiViewSettings _parent; + private readonly List _undoList = new(); + private readonly List _redoList = new(); + private readonly List _scratch = new(); + + private List[] _cells; + private int _tileCount; + private long _solverCounter; + private EditCommand _current; + public int WalkableCount; public int DoubleSurfaceCount; /// /// Create a blank ComponentList /// - public MultiEditorComponentList(int width, int height, MultiEditorControl parent) + public MultiEditorComponentList(int width, int height, IMultiViewSettings parent) { _parent = parent; - Width = width; - Height = height; - Tiles = new List(); - for (int x = 0; x < Width; ++x) - { - for (int y = 0; y < Height; ++y) - { - Tiles.Add(new FloorTile(x, y, _parent.DrawFloorZ)); - } - } + RebuildGrid(width, height, Array.Empty()); - UndoList = new List(); - _modified = true; RecalculateMinMax(); } /// /// Create a ComponentList from UltimaSDK /// - public MultiEditorComponentList(MultiComponentList list, MultiEditorControl parent) + public MultiEditorComponentList(MultiComponentList list, IMultiViewSettings parent) { _parent = parent; - Width = list.Width; - Height = list.Height; - Tiles = new List(); - for (int x = 0; x < Width; ++x) + + var tiles = new List(); + for (int x = 0; x < list.Width; ++x) { - for (int y = 0; y < Height; ++y) + for (int y = 0; y < list.Height; ++y) { - for (int i = 0; i < list.Tiles[x][y].Length; ++i) + foreach (MTile mTile in list.Tiles[x][y]) { - Tiles.Add(new MultiTile( - list.Tiles[x][y][i].Id, - x, - y, - list.Tiles[x][y][i].Z, - list.Tiles[x][y][i].Flag) + tiles.Add(new MultiTile(mTile.Id, x, y, mTile.Z, mTile.Flag) { - Extra = list.Tiles[x][y][i].Unk1 + Extra = mTile.Unk1, + Solver = ++_solverCounter }); } - - Tiles.Add(new FloorTile(x, y, _parent.DrawFloorZ)); } } - CalcSolver(); - Tiles.Sort(); - UndoList = new List(); - _modified = true; + RebuildGrid(list.Width, list.Height, tiles); + RecalculateMinMax(); } public int Height { get; private set; } - public List Tiles { get; private set; } + public int Width { get; private set; } + + /// + /// Every tile, in draw order. + /// + public IEnumerable RealTiles + { + get + { + foreach (List cell in _cells) + { + foreach (MultiTile tile in cell) + { + yield return tile; + } + } + } + } - public List UndoList { get; private set; } + public int TileCount => _tileCount; - public List RedoList { get; private set; } = new List(); + public IReadOnlyList UndoList => _undoList; - public int Width { get; private set; } + public IReadOnlyList RedoList => _redoList; public int XMax { get; private set; } @@ -135,7 +139,6 @@ public void AddToSdkComponentList(int id) public MultiComponentList ConvertToSdk() { - int count = 0; var tiles = new MTileList[Width][]; for (int x = 0; x < Width; ++x) { @@ -146,298 +149,149 @@ public MultiComponentList ConvertToSdk() } } - foreach (MultiTile tile in Tiles) + foreach (MultiTile tile in RealTiles) { - if (tile.IsVirtualFloor) - { - continue; - } - tiles[tile.X][tile.Y].Add(tile.Id, (sbyte)tile.Z, tile.Invisible ? (sbyte)0 : (sbyte)1, tile.Extra); - ++count; } - return new MultiComponentList(tiles, count, Width, Height); + return new MultiComponentList(tiles, _tileCount, Width, Height); } + public bool InBounds(int x, int y) => x >= 0 && x < Width && y >= 0 && y < Height; + /// - /// Gets Bitmap of Multi and sets HoverTile + /// False for tiles hidden one by one and, while walls are hidden, for tiles flagged as walls. /// - public void GetImage(Graphics gfx, int xOff, int yOff, int maxHeight, Point mouseLoc, bool drawFloor) + public bool IsShown(MultiTile tile) { - if (Width == 0 || Height == 0) - { - return; - } - - if (_modified) - { - RecalculateMinMax(); - } - - XMin = XMinOrg; - XMax = XMaxOrg; - YMin = YMinOrg; - YMax = YMaxOrg; - - if (drawFloor) - { - int floorZMod = (-_parent.DrawFloorZ * 4) - 44; - if (YMin > floorZMod) - { - YMin = floorZMod; - } - - floorZMod = ((Width + Height) * 22) - (_parent.DrawFloorZ * 4); - if (YMaxOrg < floorZMod) - { - YMax = floorZMod; - } - } - - _parent.HoverTile = GetSelected(mouseLoc, maxHeight, drawFloor); - - Rectangle clipBounds = Rectangle.Round(gfx.ClipBounds); + return !tile.Hidden && !(_parent.HideWalls && (TileData.ItemTable[tile.Id].Flags & TileFlag.Wall) != 0); + } - foreach (MultiTile tile in Tiles) + public int HiddenCount + { + get { - if (!tile.IsVirtualFloor && tile.Z > maxHeight) - { - continue; - } - - Bitmap bmp = tile.GetBitmap(); - if (bmp == null) - { - continue; - } - - _drawDestRectangle.X = tile.XMod; - _drawDestRectangle.Y = tile.YMod; - _drawDestRectangle.X -= XMin + xOff; - _drawDestRectangle.Y -= YMin + yOff; - _drawDestRectangle.Width = bmp.Width; - _drawDestRectangle.Height = bmp.Height; - - if (!clipBounds.IntersectsWith(_drawDestRectangle)) - { - continue; - } - - if (tile.IsVirtualFloor) - { - if (drawFloor) - gfx.DrawImageUnscaled(bmp, _drawDestRectangle); - } - else + int count = 0; + foreach (MultiTile tile in RealTiles) { - if (_parent.HoverTile != null && _parent.HoverTile == tile) - { - gfx.DrawImage(bmp, _drawDestRectangle, 0, 0, _drawDestRectangle.Width, - _drawDestRectangle.Height, GraphicsUnit.Pixel, MultiTile.HoverColor); - } - else if (_parent.SelectedTile != null && _parent.SelectedTile == tile) - { - gfx.DrawImage(bmp, _drawDestRectangle, 0, 0, _drawDestRectangle.Width, - _drawDestRectangle.Height, GraphicsUnit.Pixel, MultiTile.SelectedColor); - } - else if (_parent.SelectedTiles.Count > 1 && _parent.SelectedTiles.Contains(tile)) - { - gfx.DrawImage(bmp, _drawDestRectangle, 0, 0, _drawDestRectangle.Width, - _drawDestRectangle.Height, GraphicsUnit.Pixel, MultiTile.MultiSelectedColor); - } - else if (tile.Transparent) - { - gfx.DrawImage(bmp, _drawDestRectangle, 0, 0, _drawDestRectangle.Width, - _drawDestRectangle.Height, GraphicsUnit.Pixel, MultiTile.TransColor); - } - else if (_parent.ShowWalkables && tile.Walkable) - { - gfx.DrawImage(bmp, _drawDestRectangle, 0, 0, _drawDestRectangle.Width, - _drawDestRectangle.Height, GraphicsUnit.Pixel, MultiTile.StandableColor); - } - else if (_parent.ShowDoubleSurface && tile.DoubleSurface) - { - gfx.DrawImage(bmp, _drawDestRectangle, 0, 0, _drawDestRectangle.Width, - _drawDestRectangle.Height, GraphicsUnit.Pixel, MultiTile.StandableColor); - } - else + if (tile.Hidden) { - gfx.DrawImageUnscaled(bmp, _drawDestRectangle); + ++count; } } + + return count; } } /// - /// Gets from given Pixel Location + /// True while the tile is part of the multi. A tile removed by an edit or undo keeps its + /// coordinates, so the lookup goes straight to its cell. /// - private MultiTile GetSelected(Point mouseLoc, int maxHeight, bool drawFloor) + public bool Contains(MultiTile tile) { - if (Width == 0 || Height == 0) - { - return null; - } - - if (mouseLoc == Point.Empty) - { - return null; - } - - MultiTile selected = null; - for (int i = Tiles.Count - 1; i >= 0; --i) // inverse for speedup - { - MultiTile tile = Tiles[i]; - if (tile.IsVirtualFloor) - { - continue; - } - - if (tile.Z > maxHeight) - { - continue; - } - - if (drawFloor && _parent.DrawFloorZ > tile.Z) - { - continue; - } - - Bitmap bmp = tile.GetBitmap(); - if (bmp == null) - { - continue; - } - - int px = tile.XMod; - int py = tile.YMod; - px -= XMin; - py -= YMin; - - if (mouseLoc.X <= px || mouseLoc.X >= px + bmp.Width || mouseLoc.Y <= py || mouseLoc.Y >= py + bmp.Height) - { - continue; - } - - // Check for transparent part - Color p = bmp.GetPixel(mouseLoc.X - px, mouseLoc.Y - py); - if (p.R == 0 && p.G == 0 && p.B == 0) - { - continue; - } - - selected = tile; - break; - } + return tile != null && InBounds(tile.X, tile.Y) && Cell(tile.X, tile.Y).Contains(tile); + } - return selected; + /// + /// The real tiles of one cell, bottom to top. + /// + public List GetTilesAt(int x, int y) + { + return InBounds(x, y) ? new List(Cell(x, y)) : new List(); } + // ---------------------------------------------------------------- edits + /// - /// Resizes Multi size + /// Resizes Multi size. Tiles outside the new size are removed. /// public void Resize(int width, int height) { - AddToUndoList("Resize"); - if (Width > width || Height > height) + if (width == Width && height == Height) { - for (int i = Tiles.Count - 1; i >= 0; --i) - { - MultiTile tile = Tiles[i]; - if (tile.X >= width) - { - Tiles.RemoveAt(i); - } - else if (tile.Y >= height) - { - Tiles.RemoveAt(i); - } - } + return; } - if (Width < width || Height < height) + BeginEdit("Resize"); + + var outside = new List(); + foreach (MultiTile tile in RealTiles) { - for (int x = 0; x < width; ++x) + if (tile.X >= width || tile.Y >= height) { - for (int y = 0; y < height; ++y) - { - if (x < Width && y < Height) - { - continue; - } - - Tiles.Add(new FloorTile(x, y, _parent.DrawFloorZ)); - } + outside.Add(tile); } } - Width = width; - Height = height; - _modified = true; - RecalculateMinMax(); - } - - public void SetFloorZ(int z) - { - foreach (MultiTile tile in Tiles) + foreach (MultiTile tile in outside) { - if (tile.IsVirtualFloor) - { - tile.Z = z; - } + RecordRemove(tile); } - Tiles.Sort(); + RebuildGrid(width, height, new List(RealTiles)); + EndEdit(); } /// /// Adds an to specific location /// - public void TileAdd(int x, int y, int z, ushort id) + public void TileAdd(int x, int y, int z, ushort id, bool replace = false) + { + BeginEdit("Add Tile"); + RecordNew(id, x, y, z, false, 0, replace); + EndEdit(); + } + + /// + /// Moves given + /// + public void TileMove(MultiTile tile, int newX, int newY) { - if (x > Width || y > Height) + // A tile from another multi is not in the list. + if (!InBounds(newX, newY) || !Contains(tile)) { return; } - AddToUndoList("Add Tile"); - MultiTile tile = new MultiTile(id, x, y, ClampZ(z), 1); - Tiles.Add(tile); - CalcSolver(x, y); - _modified = true; - Tiles.Sort(); - RecalculateMinMax(tile); + BeginEdit("Move Tile"); + RecordChange(tile, tile.Id, newX, newY, tile.Z, tile.Invisible); + EndEdit(); } /// - /// Z is saved as a signed byte; larger values would wrap around. - /// - private static int ClampZ(int z) => Math.Clamp(z, sbyte.MinValue, sbyte.MaxValue); - - /// - /// Moves given + /// Moves a group of tiles by an offset in one undo step. Nothing moves when any tile would + /// leave the multi. Returns true when the group moved. /// - public void TileMove(MultiTile tile, int newX, int newY) + public bool TileMoveBatch(IEnumerable tiles, int dx, int dy, int dz, string action = "Move Tiles") { - if (Width == 0 || Height == 0) + var group = new List(); + foreach (MultiTile tile in tiles) { - return; + if (Contains(tile)) + { + if (!InBounds(tile.X + dx, tile.Y + dy)) + { + return false; + } + + group.Add(tile); + } } - // A tile from before an undo or another multi is no longer in the list. - if (tile == null || newX < 0 || newX >= Width || newY < 0 || newY >= Height || !Tiles.Contains(tile)) + if (group.Count == 0 || (dx == 0 && dy == 0 && dz == 0)) { - return; + return false; } - AddToUndoList("Move Tile"); + BeginEdit(action); + foreach (MultiTile tile in group) + { + RecordChange(tile, tile.Id, tile.X + dx, tile.Y + dy, ClampZ(tile.Z + dz), tile.Invisible); + } - tile.X = newX; - tile.Y = newY; - CalcSolver(newX, newY); - Tiles.Sort(); - _modified = true; - RecalculateMinMax(tile); + EndEdit(); + return true; } /// @@ -445,17 +299,24 @@ public void TileMove(MultiTile tile, int newX, int newY) /// public void TileRemoveRect(int x0, int y0, int x1, int y1, int minZ, int maxZ = int.MaxValue) { - if (Width == 0 || Height == 0) + BeginEdit("Remove Rect"); + + for (int x = Math.Max(0, x0); x <= Math.Min(Width - 1, x1); ++x) { - return; + for (int y = Math.Max(0, y0); y <= Math.Min(Height - 1, y1); ++y) + { + foreach (MultiTile tile in GetTilesAt(x, y)) + { + // What is not shown is not removed. + if (tile.Z >= minZ && tile.Z <= maxZ && IsShown(tile)) + { + RecordRemove(tile); + } + } + } } - AddToUndoList("Remove Rect"); - - Tiles.RemoveAll(t => !t.IsVirtualFloor && t.X >= x0 && t.X <= x1 && t.Y >= y0 && t.Y <= y1 && t.Z >= minZ && t.Z <= maxZ); - - _modified = true; - RecalculateMinMax(); + EndEdit(); } /// @@ -463,20 +324,13 @@ public void TileRemoveRect(int x0, int y0, int x1, int y1, int minZ, int maxZ = /// public void TileRemoveBatch(IEnumerable tiles) { - if (Width == 0 || Height == 0) - { - return; - } - - AddToUndoList("Remove Tiles"); - - foreach (MultiTile tile in tiles) + BeginEdit("Remove Tiles"); + foreach (MultiTile tile in new List(tiles)) { - Tiles.Remove(tile); + RecordRemove(tile); } - _modified = true; - RecalculateMinMax(); + EndEdit(); } /// @@ -484,21 +338,14 @@ public void TileRemoveBatch(IEnumerable tiles) /// public void TileRemove(MultiTile tile) { - if (Width == 0 || Height == 0) - { - return; - } - - if (tile == null || !Tiles.Contains(tile)) + if (!Contains(tile)) { return; } - AddToUndoList("Remove Tile"); - - Tiles.Remove(tile); - _modified = true; - RecalculateMinMax(tile); + BeginEdit("Remove Tile"); + RecordRemove(tile); + EndEdit(); } /// @@ -506,22 +353,7 @@ public void TileRemove(MultiTile tile) /// public void TileZMod(MultiTile tile, int modZ) { - AddToUndoList("Modify Z"); - tile.Z += modZ; - if (tile.Z > 127) - { - tile.Z = 127; - } - - if (tile.Z < -128) - { - tile.Z = -128; - } - - CalcSolver(tile.X, tile.Y); - Tiles.Sort(); - _modified = true; - RecalculateMinMax(tile); + TileZMod(new[] { tile }, modZ, "Modify Z"); } /// @@ -529,104 +361,88 @@ public void TileZMod(MultiTile tile, int modZ) /// public void TileZSet(MultiTile tile, int setZ) { - AddToUndoList("Set Z"); - tile.Z = setZ; - if (tile.Z > 127) - { - tile.Z = 127; - } + TileZSet(new[] { tile }, setZ, "Set Z"); + } - if (tile.Z < -128) + /// + /// Adjusts Z for a group of tiles in a single undo step. + /// + public void TileZMod(IEnumerable tiles, int modZ, string action = "Group Modify Z") + { + BeginEdit(action); + foreach (MultiTile tile in new List(tiles)) { - tile.Z = -128; + if (Contains(tile)) + { + RecordChange(tile, tile.Id, tile.X, tile.Y, ClampZ(tile.Z + modZ), tile.Invisible); + } } - CalcSolver(tile.X, tile.Y); - Tiles.Sort(); - _modified = true; - RecalculateMinMax(tile); + EndEdit(); } /// - /// Adjusts Z for a group of tiles in a single undo step. + /// Sets Z for a group of tiles in a single undo step. /// - public void TileZMod(IEnumerable tiles, int modZ) + public void TileZSet(IEnumerable tiles, int setZ, string action = "Group Set Z") { - AddToUndoList("Group Modify Z"); - foreach (MultiTile tile in tiles) + BeginEdit(action); + int z = ClampZ(setZ); + foreach (MultiTile tile in new List(tiles)) { - tile.Z = Math.Clamp(tile.Z + modZ, -128, 127); - CalcSolver(tile.X, tile.Y); + if (Contains(tile)) + { + RecordChange(tile, tile.Id, tile.X, tile.Y, z, tile.Invisible); + } } - _modified = true; - Tiles.Sort(); - RecalculateMinMax(); + EndEdit(); } /// - /// Sets Z for a group of tiles in a single undo step. + /// Sets a tile's Dynamic (invisible) flag as an undoable change. /// - public void TileZSet(IEnumerable tiles, int setZ) + public void TileSetInvisible(MultiTile tile, bool invisible) { - AddToUndoList("Group Set Z"); - int clampedZ = Math.Clamp(setZ, -128, 127); - foreach (MultiTile tile in tiles) + if (!Contains(tile) || tile.Invisible == invisible) { - tile.Z = clampedZ; - CalcSolver(tile.X, tile.Y); + return; } - _modified = true; - Tiles.Sort(); - RecalculateMinMax(); + BeginEdit("Dynamic"); + RecordChange(tile, tile.Id, tile.X, tile.Y, tile.Z, invisible); + EndEdit(); } /// /// Fills a rectangular area with a tile at the given Z level. /// - public void TileAddRect(int x0, int y0, int x1, int y1, int z, ushort id) + public void TileAddRect(int x0, int y0, int x1, int y1, int z, ushort id, bool replace = false) { - AddToUndoList("Rectangle Fill"); + BeginEdit("Rectangle Fill"); for (int x = x0; x <= x1; x++) { for (int y = y0; y <= y1; y++) { - if (x < 0 || x >= Width || y < 0 || y >= Height) - { - continue; - } - - Tiles.Add(new MultiTile(id, x, y, ClampZ(z), 1)); - CalcSolver(x, y); + RecordNew(id, x, y, z, false, 0, replace); } } - _modified = true; - Tiles.Sort(); - RecalculateMinMax(); + EndEdit(); } /// /// Places tiles along a Bresenham line at the given Z level. /// - public void TileAddLine(int x0, int y0, int x1, int y1, int z, ushort id) + public void TileAddLine(int x0, int y0, int x1, int y1, int z, ushort id, bool replace = false) { - AddToUndoList("Line Draw"); + BeginEdit("Line Draw"); foreach (var (x, y) in BresenhamLine(x0, y0, x1, y1)) { - if (x < 0 || x >= Width || y < 0 || y >= Height) - { - continue; - } - - Tiles.Add(new MultiTile(id, x, y, ClampZ(z), 1)); - CalcSolver(x, y); + RecordNew(id, x, y, z, false, 0, replace); } - _modified = true; - Tiles.Sort(); - RecalculateMinMax(); + EndEdit(); } public static IEnumerable<(int x, int y)> BresenhamLinePublic(int x0, int y0, int x1, int y1) @@ -666,925 +482,477 @@ public void TileAddLine(int x0, int y0, int x1, int y1, int z, ushort id) /// /// Places an NxN brush of tiles centered on (cx, cy) at the given Z level. /// - public void TileAddBrush(int cx, int cy, int z, ushort id, int brushSize) + public void TileAddBrush(int cx, int cy, int z, ushort id, int brushSize, bool replace = false) { - AddToUndoList("Draw Brush"); + BeginEdit("Draw Brush"); int half = brushSize / 2; for (int dx = -half; dx <= half; dx++) { for (int dy = -half; dy <= half; dy++) { - int x = cx + dx; - int y = cy + dy; - if (x < 0 || x >= Width || y < 0 || y >= Height) - { - continue; - } - - Tiles.Add(new MultiTile(id, x, y, ClampZ(z), 1)); - CalcSolver(x, y); + RecordNew(id, cx + dx, cy + dy, z, false, 0, replace); } } - _modified = true; - Tiles.Sort(); - RecalculateMinMax(); + EndEdit(); } /// - /// Adds a batch of tiles in a single undo step (used by copy/paste). + /// Gives tiles new ids in one undo step; position, Z and flags stay. /// - public void TileAddBatch(List<(ushort id, int x, int y, int z, bool invisible, int extra)> tiles) + public void TileSetIds(IEnumerable<(MultiTile Tile, ushort Id)> changes, string action) { - AddToUndoList("Paste"); - foreach (var (id, x, y, z, invisible, extra) in tiles) + BeginEdit(action); + foreach (var (tile, id) in new List<(MultiTile, ushort)>(changes)) { - if (x < 0 || x >= Width || y < 0 || y >= Height) + if (Contains(tile)) { - continue; + RecordChange(tile, id, tile.X, tile.Y, tile.Z, tile.Invisible); } - - Tiles.Add(new MultiTile(id, x, y, ClampZ(z), invisible) { Extra = extra }); - CalcSolver(x, y); } - _modified = true; - Tiles.Sort(); - RecalculateMinMax(); + EndEdit(); } - private void RestoreSnapshot(UndoStruct entry) + /// + /// Removes some tiles and adds others in one undo step (wall and house part tools). + /// + public void ReplaceTiles(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z)> add, string action) { - Width = entry.Width; - Height = entry.Height; - Tiles = new List(); - foreach (MultiTile tile in entry.Tiles) + BeginEdit(action); + foreach (MultiTile tile in new List(remove)) { - Tiles.Add(tile.IsVirtualFloor - ? new FloorTile(tile.X, tile.Y, tile.Z) - : new MultiTile(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible) { Extra = tile.Extra }); + RecordRemove(tile); } - _modified = true; - RecalculateMinMax(); - } - - public void Undo(int index) - { - if (index < 0 || index >= UndoList.Count) + foreach (var (id, x, y, z) in add) { - return; + RecordNew(id, x, y, z, false, 0); } - // Step back one entry at a time, so every state passed over, the current one included, - // ends up on the redo stack and can be redone. - for (int i = 0; i <= index; ++i) - { - UndoStep(); - } + EndEdit(); } /// - /// Sets a tile's Dynamic (invisible) flag as an undoable change. + /// Replaces a group of tiles with new ones, optionally at a new multi size, in one undo + /// step (rotate and mirror). Returns the tiles added. /// - public void TileSetInvisible(MultiTile tile, bool invisible) + public List ReplaceTiles(IEnumerable remove, + IEnumerable<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> add, string action, int width, int height) { - if (tile == null || tile.Invisible == invisible || !Tiles.Contains(tile)) + BeginEdit(action); + foreach (MultiTile tile in new List(remove)) { - return; + RecordRemove(tile); } - AddToUndoList("Dynamic"); - tile.Invisible = invisible; - _modified = true; - } - - /// Single-step undo (Ctrl+Z). Pushes current state to redo stack. - public bool UndoStep() - { - if (UndoList.Count == 0) + if (width != Width || height != Height) { - return false; + foreach (MultiTile tile in new List(RealTiles)) + { + if (tile.X >= width || tile.Y >= height) + { + RecordRemove(tile); + } + } + + RebuildGrid(width, height, new List(RealTiles)); } - RedoList.Insert(0, SnapshotCurrent(UndoList[0].Action)); - if (RedoList.Count > _undoListMaxSize) + var added = new List(); + foreach (var (id, x, y, z, invisible, extra) in add) { - RedoList.RemoveAt(RedoList.Count - 1); + if (RecordNew(id, x, y, z, invisible, extra) is { } tile) + { + added.Add(tile); + } } - RestoreSnapshot(UndoList[0]); - UndoList.RemoveAt(0); - return true; + EndEdit(); + return added; } - /// Single-step redo (Ctrl+Y). Pushes current state back onto undo stack. - public bool RedoStep() + /// + /// Adds a batch of tiles in a single undo step (used by copy/paste). + /// + public void TileAddBatch(List<(ushort id, int x, int y, int z, bool invisible, int extra)> tiles) { - if (RedoList.Count == 0) - { - return false; - } - - UndoList.Insert(0, SnapshotCurrent(RedoList[0].Action)); - if (UndoList.Count > _undoListMaxSize) + BeginEdit("Paste"); + foreach (var (id, x, y, z, invisible, extra) in tiles) { - UndoList.RemoveAt(UndoList.Count - 1); + RecordNew(id, x, y, z, invisible, extra); } - RestoreSnapshot(RedoList[0]); - RedoList.RemoveAt(0); - return true; + EndEdit(); } - public void UndoClear() - { - UndoList.Clear(); - RedoList.Clear(); - } + // ---------------------------------------------------------------- undo / redo - public void CalcWalkable() + public void Undo(int index) { - const int lastX = -1; - const int lastY = -1; - - List xyArray = new List(); - WalkableCount = 0; - foreach (MultiTile tile in Tiles) + if (index < 0 || index >= _undoList.Count) { - if (tile.IsVirtualFloor) - { - continue; - } - - ItemData itemData = TileData.ItemTable[tile.Id]; - if ((itemData.Flags & TileFlag.Surface) == 0) - { - continue; - } - - if (tile.X != lastX && tile.Y != lastY) - { - xyArray = GetMultiTileLitAtCoordinate(tile.X, tile.Y); - } + return; + } - int start = tile.Z + itemData.CalcHeight; - if (tile.IsWalkable(start, xyArray)) - { - ++WalkableCount; - } + // Step back one entry at a time, so every state passed over, the current one included, + // ends up on the redo stack and can be redone. + for (int i = 0; i <= index; ++i) + { + UndoStep(); } } - public void CalcDoubleSurface() + /// Single-step undo (Ctrl+Z). Moves the step to the redo stack. + public bool UndoStep() { - const int lastX = -1; - const int lastY = -1; - List xyArray = new List(); - DoubleSurfaceCount = 0; - foreach (MultiTile tile in Tiles) + if (_undoList.Count == 0) { - if (tile.IsVirtualFloor) - { - continue; - } + return false; + } - ItemData itemData = TileData.ItemTable[tile.Id]; - if ((itemData.Flags & TileFlag.Surface) == 0) - { - continue; - } + EditCommand command = _undoList[0]; + _undoList.RemoveAt(0); + Apply(command, undo: true); - if (tile.X != lastX && tile.Y != lastY) - { - xyArray = GetMultiTileLitAtCoordinate(tile.X, tile.Y); - } - - if (tile.IsDoubleSurface(xyArray)) - { - ++DoubleSurfaceCount; - } - } + _redoList.Insert(0, command); + TrimToSize(_redoList); + return true; } - private void CalcSolver() + /// Single-step redo (Ctrl+Y). Moves the step back to the undo stack. + public bool RedoStep() { - for (int x = 0; x < Width; ++x) + if (_redoList.Count == 0) { - for (int y = 0; y < Height; ++y) - { - CalcSolver(x, y); - } + return false; } + + EditCommand command = _redoList[0]; + _redoList.RemoveAt(0); + Apply(command, undo: false); + + _undoList.Insert(0, command); + TrimToSize(_undoList); + return true; } - private void CalcSolver(int x, int y) + public void UndoClear() { - List multiTiles = GetMultiTileLitAtCoordinate(x, y); - for (int i = 0; i < multiTiles.Count; ++i) - { - multiTiles[i].Solver = i; - } + _undoList.Clear(); + _redoList.Clear(); } - public List GetMultiTileLitAtCoordinate(int x, int y) + private static void TrimToSize(List list) { - List multiTiles = new List(); - foreach (MultiTile tile in Tiles) + if (list.Count > DefaultUndoStackSize) { - if (tile.IsVirtualFloor) - { - continue; - } - - if (tile.X != x) - { - continue; - } - - if (tile.Y != y) - { - continue; - } - - multiTiles.Add(tile); + list.RemoveRange(DefaultUndoStackSize, list.Count - DefaultUndoStackSize); } - - return multiTiles; } - /// - /// Returns all tiles whose bitmaps overlap the given screen-space rectangle. - /// xOff/yOff are the current scrollbar values. - /// - public List GetTilesInScreenRect(Rectangle screenRect, int xOff, int yOff, int maxHeight, bool drawFloor) + private void Apply(EditCommand command, bool undo) { - var result = new List(); - foreach (MultiTile tile in Tiles) - { - if (tile.IsVirtualFloor) - { - continue; - } + HashSet toAdd = undo ? command.Removed : command.Added; + HashSet toRemove = undo ? command.Added : command.Removed; + Dictionary states = undo ? command.Before : command.After; + int width = undo ? command.OldWidth : command.NewWidth; + int height = undo ? command.OldHeight : command.NewHeight; - if (tile.Z > maxHeight) - { - continue; - } + foreach (MultiTile tile in toRemove) + { + GridRemove(tile); + } - if (drawFloor && _parent.DrawFloorZ > tile.Z) + if (width != Width || height != Height) + { + // Positions may only fit the other size, so set every tile and rebuild the grid. + var all = new List(RealTiles); + foreach (var (tile, state) in states) { - continue; + state.ApplyTo(tile); } - Bitmap bmp = tile.GetBitmap(); - if (bmp == null) + all.AddRange(toAdd); + RebuildGrid(width, height, all); + } + else + { + foreach (var (tile, state) in states) { - continue; + GridRemove(tile); + state.ApplyTo(tile); + GridInsert(tile); } - int px = tile.XMod - XMin - xOff; - int py = tile.YMod - YMin - yOff; - var tileBounds = new Rectangle(px, py, bmp.Width, bmp.Height); - if (tileBounds.IntersectsWith(screenRect)) + foreach (MultiTile tile in toAdd) { - result.Add(tile); + GridInsert(tile); } } - return result; + RecalculateMinMax(); } - private UndoStruct SnapshotCurrent(string action) + private void BeginEdit(string action) { - var entry = new UndoStruct - { - Action = action, - Tiles = new List(), - Width = Width, - Height = Height - }; - - foreach (MultiTile tile in Tiles) - { - entry.Tiles.Add(tile.IsVirtualFloor - ? new FloorTile(tile.X, tile.Y, tile.Z) - : new MultiTile(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible) { Extra = tile.Extra }); - } - - return entry; + _current = new EditCommand(action, Width, Height); } - private void AddToUndoList(string action) + private void EndEdit() { - UndoList.Insert(0, SnapshotCurrent(action)); - if (UndoList.Count > _undoListMaxSize) + EditCommand command = _current; + _current = null; + + command.NewWidth = Width; + command.NewHeight = Height; + command.CaptureAfter(); + if (command.IsEmpty) { - UndoList.RemoveAt(UndoList.Count - 1); + return; } - RedoList.Clear(); + _undoList.Insert(0, command); + TrimToSize(_undoList); + _redoList.Clear(); + + RecalculateMinMax(); } /// - /// Recalculates bitmap size + /// Adds a new tile unless it is out of bounds or the same id already sits at the same Z in + /// that cell. With , other tiles of the same kind at that Z go + /// first: a flat tile replaces flat tiles, a tile with height replaces tiles with height. /// - private void RecalculateMinMax() + private MultiTile RecordNew(ushort id, int x, int y, int z, bool invisible, int extra, bool replace = false) { - // CalcEdgeTiles - YMin = -44; // 0,0 - YMax = (Width + Height) * 22; // width,height - XMin = (-Height * 22) - 22; // 0,height - XMax = (Width * 22) + 22; // width,0 - ZMin = 127; - ZMax = -128; - - foreach (MultiTile tile in Tiles) + if (!InBounds(x, y)) { - if (tile.IsVirtualFloor) - { - continue; - } - - if (tile.GetBitmap() == null) - { - continue; - } - - int px = tile.XMod - GapXMod; - int py = tile.YMod - GapYMod; - - if (px < XMin) - { - XMin = px; - } + return null; + } - if (py < YMin) + z = ClampZ(z); + if (replace) + { + bool flat = TileData.ItemTable[id].Height == 0; + foreach (MultiTile other in GetTilesAt(x, y)) { - YMin = py; + if (other.Z == z && other.Id != id && (other.Height == 0) == flat) + { + RecordRemove(other); + } } - - px += tile.GetBitmap().Width; - py += tile.GetBitmap().Height; - - if (px > XMax) - XMax = px; - if (py > YMax) - YMax = py; - if (tile.Z > ZMax) - ZMax = tile.Z; - if (tile.Z < ZMin) - ZMin = tile.Z; } - _modified = false; - XMinOrg = XMin; - XMaxOrg = XMax; - YMinOrg = YMin; - YMaxOrg = YMax; - - if (_parent.ShowWalkables) + foreach (MultiTile other in Cell(x, y)) { - CalcWalkable(); + if (other.Id == id && other.Z == z) + { + return null; + } } - if (_parent.ShowDoubleSurface) - { - CalcDoubleSurface(); - } + var tile = new MultiTile(id, x, y, z, invisible) { Extra = extra, Solver = ++_solverCounter }; + GridInsert(tile); + _current.Added.Add(tile); + return tile; } - private void RecalculateMinMax(MultiTile tile) + private void RecordRemove(MultiTile tile) { - if (tile.IsVirtualFloor) + if (!GridRemove(tile)) { return; } - if (tile.GetBitmap() == null) + if (_current.Added.Remove(tile)) { return; } - int px = tile.XMod - GapXMod; - int py = tile.YMod - GapYMod; - - if (px < XMin) - { - XMin = px; - } - - if (py < YMin) - { - YMin = py; - } - - px += tile.GetBitmap().Width; - py += tile.GetBitmap().Height; - - if (px > XMax) - { - XMax = px; - } - - if (py > YMax) + if (_current.Before.Remove(tile, out TileState before)) { - YMax = py; + // Undo puts it back as it was before this edit, not as it was when removed. + before.ApplyTo(tile); } - if (tile.Z > ZMax) - { - ZMax = tile.Z; - } - - if (tile.Z < ZMin) - { - ZMin = tile.Z; - } - - _modified = false; - - XMinOrg = XMin; - XMaxOrg = XMax; - YMinOrg = YMin; - YMaxOrg = YMax; - - if (_parent.ShowWalkables) - { - CalcWalkable(); - } - - if (_parent.ShowDoubleSurface) - { - CalcDoubleSurface(); - } + _current.Removed.Add(tile); } - public struct UndoStruct + private void RecordChange(MultiTile tile, ushort id, int x, int y, int z, bool invisible) { - public string Action; - public int Height; - public List Tiles; - public int Width; - } - } - - public class FloorTile : MultiTile - { - private static Bitmap _floorBmp; - - public FloorTile(int x, int y, int z) - { - X = x; - Y = y; - Z = z; - } - - public override bool IsVirtualFloor => true; - - public override Bitmap GetBitmap() - { - if (_floorBmp != null) + var target = new TileState(id, x, y, z, invisible); + if (TileState.Of(tile) == target || !InBounds(x, y)) { - return _floorBmp; + return; } - _floorBmp = new Bitmap(44, 44); - - using (Graphics g = Graphics.FromImage(_floorBmp)) + if (!_current.Added.Contains(tile) && !_current.Before.ContainsKey(tile)) { - using (Brush floorBrush = new SolidBrush(Color.FromArgb(96, 32, 192, 32))) - { - Point[] drawFloorPoint = new Point[4]; - drawFloorPoint[0].X = 22; - drawFloorPoint[0].Y = 0; - drawFloorPoint[1].X = 44; - drawFloorPoint[1].Y = 22; - drawFloorPoint[2].X = 22; - drawFloorPoint[2].Y = 44; - drawFloorPoint[3].X = 0; - drawFloorPoint[3].Y = 22; - - g.FillPolygon(floorBrush, drawFloorPoint); - g.DrawPolygon(Pens.White, drawFloorPoint); - } + _current.Before[tile] = TileState.Of(tile); } - return _floorBmp; + GridRemove(tile); + target.ApplyTo(tile); + GridInsert(tile); } - } - public class MultiTile : IComparable - { - private static readonly ColorMatrix _removeHighlightMatrix = new ColorMatrix(new float[][] - { - new float[] {1, 0, 0, 0, 0}, - new float[] {0, 0, 0, 0, 0}, - new float[] {0, 0, 0, 0, 0}, - new float[] {0, 0, 0, .7f, 0}, - new float[] {.4f, 0, 0, 0, 1} - }); - - private static readonly ColorMatrix _multiSelectedMatrix = new ColorMatrix(new float[][] - { - new float[] {0, 0, 1, 0, 0}, - new float[] {0, 1, 0, 0, 0}, - new float[] {1, 0, 0, 0, 0}, - new float[] {0, 0, 0, 1, 0}, - new float[] {0, .4f, .4f, 0, 1} - }); - - private static readonly ColorMatrix _drawMatrix = new ColorMatrix(new float[][] - { - new float[] {0, 0, 0, 0, 0}, - new float[] {0, 0, 0, 0, 0}, - new float[] {0, 0, 0, 0, 0}, - new float[] {0, 0, 0, .5f, 0}, - new float[] {0, 0, 0, 0, 1} - }); - - private static readonly ColorMatrix _hoverMatrix = new ColorMatrix(new float[][] - { - new float[] {1, 0, 0, 0, 0}, - new float[] {0, 1, 0, 0, 0}, - new float[] {0, 0, 1, 0, 0}, - new float[] {0, 0, 0, 1, 0}, - new float[] {0, 0, .8f, 0, 1} - }); - - private static readonly ColorMatrix _selectedMatrix = new ColorMatrix(new float[][] - { - new float[] {0, 1, 0, 0, 0}, - new float[] {0, 0, 1, 0, 0}, - new float[] {1, 0, 0, 0, 0}, - new float[] {0, 0, 0, 1, 0}, - new float[] {.8f, 0, 0, 0, 1} - }); - - private static readonly ColorMatrix _transMatrix = new ColorMatrix(new float[][] - { - new float[] {1, 0, 0, 0, 0}, - new float[] {0, 1, 0, 0, 0}, - new float[] {0, 0, 1, 0, 0}, - new float[] {0, 0, 0, .3f, 0}, - new float[] {0, 0, 0, 0, 1} - }); - - private static readonly ColorMatrix _standableMatrix = new ColorMatrix(new float[][] - { - new float[] {0, 0, .5f, 0, 0}, - new float[] {0, .8f, 0, .8f, 0}, - new float[] {.8f, 0, 0, 0, .8f}, - new float[] {0, .8f, 0, .8f, 0}, - new float[] {0, 0, .5f, 0, 0} - }); - - private int _x; - private int _y; - private int _z; - - public MultiTile(ushort id, int x, int y, int z, int flag) - { - Id = id; - X = x; - Y = y; - Z = z; - Invisible = flag == 0; - Solver = 0; - } + // ---------------------------------------------------------------- grid - public MultiTile(ushort id, int x, int y, int z, bool flag) - { - Id = id; - X = x; - Y = y; - Z = z; - Invisible = flag; - Solver = 0; - } + private List Cell(int x, int y) => _cells[(x * Height) + y]; + + /// The tiles of one cell in draw order. Cells are drawn x by x, and y by y within each x. + public IReadOnlyList TilesIn(int x, int y) => Cell(x, y); - public MultiTile() + private void GridInsert(MultiTile tile) { - Id = 0xFFFF; + List cell = Cell(tile.X, tile.Y); + cell.Add(tile); + cell.Sort(); + ++_tileCount; } - static MultiTile() + private bool GridRemove(MultiTile tile) { - if (HoverColor == null) + if (!InBounds(tile.X, tile.Y) || !Cell(tile.X, tile.Y).Remove(tile)) { - HoverColor = new ImageAttributes(); - HoverColor.SetColorMatrix(_hoverMatrix); - } - - if (SelectedColor == null) - { - SelectedColor = new ImageAttributes(); - SelectedColor.SetColorMatrix(_selectedMatrix); - } - - if (MultiSelectedColor == null) - { - MultiSelectedColor = new ImageAttributes(); - MultiSelectedColor.SetColorMatrix(_multiSelectedMatrix); - } - - if (DrawColor == null) - { - DrawColor = new ImageAttributes(); - DrawColor.SetColorMatrix(_drawMatrix); - } - - if (TransColor == null) - { - TransColor = new ImageAttributes(); - TransColor.SetColorMatrix(_transMatrix); - } - - if (RemoveHighlightColor == null) - { - RemoveHighlightColor = new ImageAttributes(); - RemoveHighlightColor.SetColorMatrix(_removeHighlightMatrix); + return false; } - if (StandableColor == null) - { - StandableColor = new ImageAttributes(); - StandableColor.SetColorMatrix(_standableMatrix); - } + --_tileCount; + return true; } - public static ImageAttributes RemoveHighlightColor { get; private set; } - - public static ImageAttributes DrawColor { get; } - - public static ImageAttributes MultiSelectedColor { get; } - - public int Height => TileData.ItemTable[Id].Height; - - public static ImageAttributes HoverColor { get; } - - public ushort Id { get; private set; } - - public virtual bool IsVirtualFloor => false; - - public static ImageAttributes SelectedColor { get; } - - public static ImageAttributes TransColor { get; } - - public static ImageAttributes StandableColor { get; } - - public int X + private void RebuildGrid(int width, int height, IEnumerable tiles) { - get => _x; - set + Width = width; + Height = height; + _cells = new List[width * height]; + for (int x = 0; x < width; ++x) { - _x = value; - RecalculateMod(); + for (int y = 0; y < height; ++y) + { + _cells[(x * height) + y] = new List(); + } } - } - - public int XMod { get; private set; } - public int Y - { - get => _y; - set + _tileCount = 0; + foreach (MultiTile tile in tiles) { - _y = value; - RecalculateMod(); + if (InBounds(tile.X, tile.Y)) + { + Cell(tile.X, tile.Y).Add(tile); + ++_tileCount; + } } - } - - public int YMod { get; private set; } - public int Z - { - get => _z; - set + foreach (List cell in _cells) { - _z = value; - RecalculateMod(); + cell.Sort(); } } - public bool Invisible { get; set; } - /// - /// The multi.mul extra field (MultiTileEntry.Unk1), kept so a save writes it back. + /// Z is saved as a signed byte; larger values would wrap around. /// - public int Extra { get; set; } - - public bool Walkable { get; private set; } - - public bool DoubleSurface { get; private set; } - - public bool Transparent { get; set; } + private static int ClampZ(int z) => Math.Clamp(z, sbyte.MinValue, sbyte.MaxValue); - public int Solver { get; set; } + // ---------------------------------------------------------------- analysis - public int CompareTo(object obj) + public void CalcWalkable() { - if (obj == null) - { - return 1; - } - - if (obj is not MultiTile multiTile) - { - throw new ArgumentNullException(nameof(obj)); - } - - if (X > multiTile.X) - { - return 1; - } - - if (X < multiTile.X) - { - return -1; - } - - if (Y > multiTile.Y) - { - return 1; - } - - if (Y < multiTile.Y) - { - return -1; - } - - if (!multiTile.IsVirtualFloor && !IsVirtualFloor) + WalkableCount = 0; + foreach (List cell in _cells) { - ItemData ourData = TileData.ItemTable[Id]; - ItemData theirData = TileData.ItemTable[multiTile.Id]; - - int ourThreshold = 0; - if (ourData.Height > 0) - { - ++ourThreshold; - } - - if (!ourData.Background) + FillScratch(cell); + foreach (MultiTile tile in _scratch) { - ++ourThreshold; - } - - int ourZ = Z; - - int theirThreshold = 0; - if (theirData.Height > 0) - { - ++theirThreshold; - } - - if (!theirData.Background) - { - ++theirThreshold; - } - - int theirZ = multiTile.Z; - - ourZ += ourThreshold; - theirZ += theirThreshold; - - int res = ourZ - theirZ; - if (res == 0) - { - res = ourThreshold - theirThreshold; - } + ItemData itemData = TileData.ItemTable[tile.Id]; + if ((itemData.Flags & TileFlag.Surface) == 0) + { + continue; + } - if (res == 0) - { - res = Solver - multiTile.Solver; + if (tile.IsWalkable(tile.Z + itemData.CalcHeight, _scratch)) + { + ++WalkableCount; + } } - - return res; } - else - { - if (Z > multiTile.Z) - { - return 1; - } - - if (multiTile.Z > Z) - { - return -1; - } + } - if (multiTile.IsVirtualFloor) + public void CalcDoubleSurface() + { + DoubleSurfaceCount = 0; + foreach (List cell in _cells) + { + FillScratch(cell); + foreach (MultiTile tile in _scratch) { - return 1; - } + if ((TileData.ItemTable[tile.Id].Flags & TileFlag.Surface) == 0) + { + continue; + } - if (IsVirtualFloor) - { - return -1; + if (tile.IsDoubleSurface(_scratch)) + { + ++DoubleSurfaceCount; + } } } - - return 0; - } - - public virtual Bitmap GetBitmap() - { - return Id != 0xFFFF - ? Art.GetStatic(Id) - : null; - } - - public void Set(ushort id, int z) - { - Id = id; - Z = z; - - RecalculateMod(); } - private void RecalculateMod() + private void FillScratch(List cell) { - if (GetBitmap() != null) - { - XMod = (_x - _y) * 22; - XMod -= GetBitmap().Width / 2; - XMod += MultiEditorComponentList.GapXMod; - YMod = (_x + _y) * 22; - YMod -= _z * 4; - YMod -= GetBitmap().Height; - YMod += MultiEditorComponentList.GapYMod; - } - else if (IsVirtualFloor) - { - XMod = (_x - _y) * 22; - XMod -= 44 / 2; - XMod += MultiEditorComponentList.GapXMod; - YMod = (_x + _y) * 22; - YMod -= _z * 4; - YMod -= 44; - YMod += MultiEditorComponentList.GapYMod; - } + _scratch.Clear(); + _scratch.AddRange(cell); } - private const TileFlag _impassableOrSurface = TileFlag.Impassable | TileFlag.Surface; - - public bool IsWalkable(int z, List tiles) + /// + /// Recalculates bitmap size + /// + private void RecalculateMinMax() { - int top = z + 16; // Player Height + // CalcEdgeTiles + YMin = -44; // 0,0 + YMax = (Width + Height) * 22; // width,height + XMin = (-Height * 22) - 22; // 0,height + XMax = (Width * 22) + 22; // width,0 + ZMin = 127; + ZMax = -128; - foreach (MultiTile tile in tiles) + foreach (MultiTile tile in RealTiles) { - ItemData itemData = TileData.ItemTable[tile.Id]; - if ((itemData.Flags & _impassableOrSurface) == 0) + if (!ArtMetrics.TryGetSize(tile.Id, out int width, out int height)) { continue; } - if ((itemData.Flags & TileFlag.Door) != 0) - { - continue; - } - - int checkTop = tile.Z + itemData.CalcHeight; - if (checkTop <= z || tile.Z >= top) - { - continue; - } + int px = tile.XMod - GapXMod; + int py = tile.YMod - GapYMod; - Walkable = false; - return false; + XMin = Math.Min(XMin, px); + YMin = Math.Min(YMin, py); + XMax = Math.Max(XMax, px + width); + YMax = Math.Max(YMax, py + height); + ZMax = Math.Max(ZMax, tile.Z); + ZMin = Math.Min(ZMin, tile.Z); } - Walkable = true; - return true; - } + XMinOrg = XMin; + XMaxOrg = XMax; + YMinOrg = YMin; + YMaxOrg = YMax; - public bool IsDoubleSurface(List tiles) - { - foreach (MultiTile tile in tiles) + if (_parent.ShowWalkables) { - if (tile.Z != Z) - { - continue; - } - - ItemData itemData = TileData.ItemTable[tile.Id]; - if ((itemData.Flags & TileFlag.Surface) == 0) - { - continue; - } - - if (tile == this) - { - continue; - } - - DoubleSurface = true; - return true; + CalcWalkable(); } - DoubleSurface = false; - return false; + if (_parent.ShowDoubleSurface) + { + CalcDoubleSurface(); + } } } -} \ No newline at end of file +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs new file mode 100644 index 00000000..bdf71aec --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs @@ -0,0 +1,274 @@ +/*************************************************************************** + * + * $Author: MuadDib & Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using Ultima; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + public partial class MultiTile : IComparable + { + private int _x; + private int _y; + private int _z; + + public MultiTile(ushort id, int x, int y, int z, int flag) + { + Id = id; + X = x; + Y = y; + Z = z; + Invisible = flag == 0; + Solver = 0; + } + + public MultiTile(ushort id, int x, int y, int z, bool flag) + { + Id = id; + X = x; + Y = y; + Z = z; + Invisible = flag; + Solver = 0; + } + + public MultiTile() + { + Id = 0xFFFF; + } + + public int Height => TileData.ItemTable[Id].Height; + + public ushort Id { get; internal set; } + + public int X + { + get => _x; + set + { + _x = value; + RecalculateMod(); + } + } + + public int XMod { get; private set; } + + public int Y + { + get => _y; + set + { + _y = value; + RecalculateMod(); + } + } + + public int YMod { get; private set; } + + /// Size of the tile's art, at , ; 0 when it has none. + public int ArtWidth { get; private set; } + + public int ArtHeight { get; private set; } + + public int Z + { + get => _z; + set + { + _z = value; + RecalculateMod(); + } + } + + public bool Invisible { get; set; } + + /// + /// The multi.mul extra field (MultiTileEntry.Unk1), kept so a save writes it back. + /// + public int Extra { get; set; } + + public bool Walkable { get; private set; } + + public bool DoubleSurface { get; private set; } + + public bool Transparent { get; set; } + + /// + /// Hidden in the editor view (not drawn, hovered or selected). View only: not saved and + /// not an undo step. + /// + public bool Hidden { get; set; } + + /// + /// Draw order among tiles of one cell that sort equal. Unique and only ever assigned once, + /// so a tile restored by undo goes back to its old place in the stack. + /// + public long Solver { get; set; } + + public int CompareTo(object obj) + { + if (obj == null) + { + return 1; + } + + if (obj is not MultiTile multiTile) + { + throw new ArgumentNullException(nameof(obj)); + } + + if (X > multiTile.X) + { + return 1; + } + + if (X < multiTile.X) + { + return -1; + } + + if (Y > multiTile.Y) + { + return 1; + } + + if (Y < multiTile.Y) + { + return -1; + } + + // One key for every tile, so the order is transitive and a cell sorts the same whatever + // order its tiles were added in. + int ourThreshold = SortThreshold; + int theirThreshold = multiTile.SortThreshold; + + int res = (Z + ourThreshold).CompareTo(multiTile.Z + theirThreshold); + if (res == 0) + { + res = ourThreshold.CompareTo(theirThreshold); + } + + if (res == 0) + { + res = Solver.CompareTo(multiTile.Solver); + } + + return res; + } + + /// The height a tile sorts at in its cell's stack: its Z, raised for tall and non-background tiles. + public int SortKey => Z + SortThreshold; + + private int SortThreshold + { + get + { + ItemData data = TileData.ItemTable[Id]; + int threshold = 0; + if (data.Height > 0) + { + ++threshold; + } + + if (!data.Background) + { + ++threshold; + } + + return threshold; + } + } + + public void Set(ushort id, int z) + { + Id = id; + Z = z; + + RecalculateMod(); + } + + private void RecalculateMod() + { + if (!ArtMetrics.TryGetSize(Id, out int width, out int height)) + { + ArtWidth = ArtHeight = 0; + return; + } + + ArtWidth = width; + ArtHeight = height; + XMod = ((_x - _y) * 22) - (width / 2) + MultiEditorComponentList.GapXMod; + YMod = ((_x + _y) * 22) - (_z * 4) - height + MultiEditorComponentList.GapYMod; + } + + private const TileFlag _impassableOrSurface = TileFlag.Impassable | TileFlag.Surface; + + public bool IsWalkable(int z, List tiles) + { + int top = z + 16; // Player Height + + foreach (MultiTile tile in tiles) + { + ItemData itemData = TileData.ItemTable[tile.Id]; + if ((itemData.Flags & _impassableOrSurface) == 0) + { + continue; + } + + if ((itemData.Flags & TileFlag.Door) != 0) + { + continue; + } + + int checkTop = tile.Z + itemData.CalcHeight; + if (checkTop <= z || tile.Z >= top) + { + continue; + } + + Walkable = false; + return false; + } + + Walkable = true; + return true; + } + + public bool IsDoubleSurface(List tiles) + { + foreach (MultiTile tile in tiles) + { + if (tile.Z != Z) + { + continue; + } + + ItemData itemData = TileData.ItemTable[tile.Id]; + if ((itemData.Flags & TileFlag.Surface) == 0) + { + continue; + } + + if (tile == this) + { + continue; + } + + DoubleSurface = true; + return true; + } + + DoubleSurface = false; + return false; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/PlanView.cs b/UoFiddler.Plugin.MultiEditor/Classes/PlanView.cs new file mode 100644 index 00000000..c08c45b7 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/PlanView.cs @@ -0,0 +1,253 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using Ultima; +using Ultima.Helpers; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// How a tile shows in the plan view: as a wall on the cell's +Y (South) or +X (East) edge, + /// a post at the +X/+Y corner, a door in an edge, or none of these (the cell's fill). + /// + [Flags] + internal enum PlanShape + { + Fill = 0, + South = 1, + East = 2, + Post = 4, + Door = 8 + } + + /// + /// The top-down plan view: every cell a square in the radar colour of its top tile, walls as + /// lines on the edges they stand on. Uses the same filters as the isometric view (height + /// slider, level, hidden tiles), so the same tools work on it. + /// + internal sealed class PlanView + { + public const int Cell = 24; + public const int Margin = 22; + + private readonly MultiEditorComponentList _list; + private readonly Func _shape; + + public PlanView(MultiEditorComponentList list, Func shape) + { + _list = list; + _shape = shape; + } + + public static Size ContentSize(int width, int height) => new Size((width * Cell) + (2 * Margin), (height * Cell) + (2 * Margin)); + + /// Canvas position of the north-west corner of a cell. + public static Point CellOrigin(int x, int y) => new Point(Margin + (x * Cell), Margin + (y * Cell)); + + /// The cell under a canvas point (may be outside the multi). + public static (int X, int Y) CellAt(Point point) => + ((int)Math.Floor((point.X - Margin) / (double)Cell), (int)Math.Floor((point.Y - Margin) / (double)Cell)); + + /// + /// The top tile of a cell that the editor lets you work on: shown, not above + /// and not below . + /// + public MultiTile TopTile(int x, int y, int maxHeight, int minZ) + { + List cell = _list.GetTilesAt(x, y); + for (int i = cell.Count - 1; i >= 0; --i) + { + MultiTile tile = cell[i]; + if (tile.Z <= maxHeight && tile.Z >= minZ && _list.IsShown(tile)) + { + return tile; + } + } + + return null; + } + + /// Every tile you could work on in the cells a canvas rectangle touches. + public List TilesInRect(Rectangle canvasRect, int maxHeight, int minZ) + { + var result = new List(); + var (x0, y0) = CellAt(canvasRect.Location); + var (x1, y1) = CellAt(new Point(canvasRect.Right, canvasRect.Bottom)); + for (int x = Math.Max(0, x0); x <= Math.Min(_list.Width - 1, x1); ++x) + { + for (int y = Math.Max(0, y0); y <= Math.Min(_list.Height - 1, y1); ++y) + { + foreach (MultiTile tile in _list.GetTilesAt(x, y)) + { + if (tile.Z <= maxHeight && tile.Z >= minZ && _list.IsShown(tile)) + { + result.Add(tile); + } + } + } + } + + return result; + } + + public void Draw(Graphics gfx, int scrollX, int scrollY, int maxHeight, int minZ, MultiTile hover, ICollection selection, bool showFloorGrid) + { + gfx.TranslateTransform(-scrollX, -scrollY); + try + { + using var gridPen = new Pen(Color.FromArgb(60, 128, 128, 128)); + using var wallPen = new Pen(Color.FromArgb(40, 40, 40), 4) { StartCap = System.Drawing.Drawing2D.LineCap.Square, EndCap = System.Drawing.Drawing2D.LineCap.Square }; + using var doorPen = new Pen(Color.SaddleBrown, 4) { DashPattern = new[] { 1f, 0.6f } }; + using var selectedBrush = new SolidBrush(Color.FromArgb(110, 255, 215, 0)); + using var floorBrush = new SolidBrush(Color.FromArgb(70, 32, 192, 32)); + + for (int x = 0; x < _list.Width; ++x) + { + for (int y = 0; y < _list.Height; ++y) + { + Point o = CellOrigin(x, y); + var square = new Rectangle(o.X, o.Y, Cell, Cell); + List cell = _list.GetTilesAt(x, y); + + // Fill: the top tile that is not a wall, darker when below the floor. A plan is + // for the layout, so roofs and loose wall pieces (gable caps, windows) only fill + // cells with nothing else in them. + MultiTile fill = TopFill(cell, maxHeight, skipCovers: true) ?? TopFill(cell, maxHeight, skipCovers: false); + if (fill != null) + { + Color color = HueHelpers.HueToColor(RadarCol.GetItemColor(fill.Id)); + if (fill.Z < minZ) + { + color = Color.FromArgb(color.R / 2, color.G / 2, color.B / 2); + } + + using var brush = new SolidBrush(color); + gfx.FillRectangle(brush, square); + } + + if (showFloorGrid) + { + gfx.FillRectangle(floorBrush, square); + } + + gfx.DrawRectangle(gridPen, square); + + foreach (MultiTile tile in cell) + { + if (tile.Z > maxHeight || tile.Z < minZ || !_list.IsShown(tile)) + { + continue; + } + + PlanShape shape = _shape(tile.Id); + Pen pen = (shape & PlanShape.Door) != 0 ? doorPen : wallPen; + if ((shape & PlanShape.South) != 0) + { + gfx.DrawLine(pen, o.X, o.Y + Cell, o.X + Cell, o.Y + Cell); + } + + if ((shape & PlanShape.East) != 0) + { + gfx.DrawLine(pen, o.X + Cell, o.Y, o.X + Cell, o.Y + Cell); + } + + if ((shape & PlanShape.Post) != 0) + { + gfx.FillRectangle(Brushes.Black, o.X + Cell - 3, o.Y + Cell - 3, 6, 6); + } + + if (selection.Contains(tile)) + { + gfx.FillRectangle(selectedBrush, square); + } + } + } + } + + if (hover != null) + { + Point o = CellOrigin(hover.X, hover.Y); + using var hoverPen = new Pen(Color.DodgerBlue, 2); + gfx.DrawRectangle(hoverPen, o.X + 1, o.Y + 1, Cell - 2, Cell - 2); + } + } + finally + { + gfx.TranslateTransform(scrollX, scrollY); + } + } + + private MultiTile TopFill(List cell, int maxHeight, bool skipCovers) + { + for (int i = cell.Count - 1; i >= 0; --i) + { + MultiTile tile = cell[i]; + if (tile.Z > maxHeight || !_list.IsShown(tile) || _shape(tile.Id) != PlanShape.Fill || + (skipCovers && (TileData.ItemTable[tile.Id].Flags & (TileFlag.Roof | TileFlag.Wall)) != 0)) + { + continue; + } + + return tile; + } + + return null; + } + + /// A planned tile drawn faintly: its colour, or its wall line. + public void DrawGhost(Graphics gfx, int scrollX, int scrollY, ushort id, int x, int y) + { + if (!_list.InBounds(x, y)) + { + return; + } + + Point o = CellOrigin(x, y); + o.Offset(-scrollX, -scrollY); + PlanShape shape = _shape(id); + if (shape == PlanShape.Fill) + { + Color color = HueHelpers.HueToColor(RadarCol.GetItemColor(id)); + using var brush = new SolidBrush(Color.FromArgb(150, color)); + gfx.FillRectangle(brush, o.X, o.Y, Cell, Cell); + return; + } + + using var pen = new Pen(Color.FromArgb(150, 30, 30, 30), 4); + if ((shape & PlanShape.South) != 0) + { + gfx.DrawLine(pen, o.X, o.Y + Cell, o.X + Cell, o.Y + Cell); + } + + if ((shape & PlanShape.East) != 0) + { + gfx.DrawLine(pen, o.X + Cell, o.Y, o.X + Cell, o.Y + Cell); + } + + if ((shape & PlanShape.Post) != 0) + { + using var brush = new SolidBrush(Color.FromArgb(150, 0, 0, 0)); + gfx.FillRectangle(brush, o.X + Cell - 3, o.Y + Cell - 3, 6, 6); + } + } + + /// A tile marked, e.g. for removal: its cell washed in a colour. + public static void DrawMark(Graphics gfx, int scrollX, int scrollY, MultiTile tile, Color color) + { + Point o = CellOrigin(tile.X, tile.Y); + using var brush = new SolidBrush(Color.FromArgb(110, color)); + gfx.FillRectangle(brush, o.X - scrollX, o.Y - scrollY, Cell, Cell); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/Prefabs.cs b/UoFiddler.Plugin.MultiEditor/Classes/Prefabs.cs new file mode 100644 index 00000000..ad9a9449 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/Prefabs.cs @@ -0,0 +1,123 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using Ultima; +using UoFiddler.Controls.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// Saved groups of tiles to stamp again, one multi text file per prefab in the profile's + /// MultiEditorPrefabs folder (the same lines the clipboard uses). + /// + internal static class Prefabs + { + public static string Folder => Path.Combine(Options.AppDataPath, "MultiEditorPrefabs"); + + public static IEnumerable Names() + { + return Directory.Exists(Folder) + ? Directory.EnumerateFiles(Folder, "*.txt").Select(Path.GetFileNameWithoutExtension).OrderBy(n => n, StringComparer.OrdinalIgnoreCase) + : Enumerable.Empty(); + } + + public static List Load(string name) + { + string path = PathOf(name); + return File.Exists(path) ? ClipboardTile.Parse(File.ReadAllText(path)) : null; + } + + public static void Save(string name, IEnumerable tiles) + { + Directory.CreateDirectory(Folder); + File.WriteAllText(PathOf(name), ClipboardTile.Format(tiles)); + } + + public static void Delete(string name) + { + string path = PathOf(name); + if (File.Exists(path)) + { + File.Delete(path); + } + } + + /// A file name made safe from what the user typed. + public static string SafeName(string name) + { + foreach (char c in Path.GetInvalidFileNameChars()) + { + name = name.Replace(c, '_'); + } + + return name.Trim(); + } + + /// + /// A small picture of the prefab: its tiles drawn the way the editor draws them, scaled to fit. + /// + public static Bitmap Thumbnail(IReadOnlyList tiles, int size) + { + var placed = new List<(ClipboardTile Tile, Bitmap Art, int X, int Y)>(); + int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + foreach (ClipboardTile tile in tiles) + { + Bitmap art = Art.GetStatic(tile.Id); + if (art == null) + { + continue; + } + + int x = ((tile.Dx - tile.Dy) * 22) - (art.Width / 2); + int y = ((tile.Dx + tile.Dy) * 22) - (tile.Dz * 4) - art.Height; + placed.Add((tile, art, x, y)); + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x + art.Width); + maxY = Math.Max(maxY, y + art.Height); + } + + var thumb = new Bitmap(size, size); + if (placed.Count == 0) + { + return thumb; + } + + using var full = new Bitmap(Math.Max(1, maxX - minX), Math.Max(1, maxY - minY)); + using (Graphics g = Graphics.FromImage(full)) + { + foreach (var p in placed.OrderBy(p => p.Tile.Dx + p.Tile.Dy).ThenBy(p => p.Tile.Dz).ThenBy(p => TileData.ItemTable[p.Tile.Id].Height)) + { + g.DrawImageUnscaled(p.Art, p.X - minX, p.Y - minY); + } + } + + using (Graphics g = Graphics.FromImage(thumb)) + { + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + float scale = Math.Min(1f, Math.Min((float)size / full.Width, (float)size / full.Height)); + int w = Math.Max(1, (int)(full.Width * scale)); + int h = Math.Max(1, (int)(full.Height * scale)); + g.DrawImage(full, (size - w) / 2, (size - h) / 2, w, h); + } + + return thumb; + } + + private static string PathOf(string name) => Path.Combine(Folder, SafeName(name) + ".txt"); + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs b/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs new file mode 100644 index 00000000..c32c8280 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs @@ -0,0 +1,108 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Xml; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// Facing table for tiles the client's house tables do not list (classic stairs, signs, + /// furniture): which id is the same piece a quarter turn to the left. Read from + /// MultiRotationTable.xml (<Map from="0x0751" to="0x0752" /> rows), first from the + /// profile's plugins folder, then from beside the plugin. Ids not listed keep their graphic. + /// + internal sealed class RotationTable + { + private const string _fileName = "MultiRotationTable.xml"; + + private readonly Dictionary _left = new Dictionary(); + private readonly Dictionary _right = new Dictionary(); + + public int Count => _left.Count; + + public static RotationTable LoadDefault() + { + var candidates = new List(); + if (!string.IsNullOrEmpty(Options.AppDataPath)) + { + candidates.Add(Path.Combine(Options.AppDataPath, "plugins", _fileName)); + } + + string pluginDir = Path.GetDirectoryName(typeof(RotationTable).Assembly.Location); + if (!string.IsNullOrEmpty(pluginDir)) + { + candidates.Add(Path.Combine(pluginDir, _fileName)); + } + + foreach (string path in candidates) + { + if (!File.Exists(path)) + { + continue; + } + + try + { + return Load(path); + } + catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException) + { + // An unreadable table only means untabled pieces keep their graphic. + } + } + + return new RotationTable(); + } + + public static RotationTable Load(string path) + { + var table = new RotationTable(); + var dom = new XmlDocument(); + dom.Load(path); + + foreach (XmlNode node in dom.GetElementsByTagName("Map")) + { + if (TryParseId(node.Attributes?["from"]?.Value, out ushort from) && TryParseId(node.Attributes?["to"]?.Value, out ushort to)) + { + table._left[from] = to; + table._right[to] = from; + } + } + + return table; + } + + /// The id of the same piece turned a quarter left, or the id itself. + public ushort TurnLeft(ushort id) => _left.TryGetValue(id, out ushort to) ? to : id; + + /// The id of the same piece turned a quarter right, or the id itself. + public ushort TurnRight(ushort id) => _right.TryGetValue(id, out ushort to) ? to : id; + + private static bool TryParseId(string text, out ushort value) + { + value = 0; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + text = text.Trim(); + return text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + ? ushort.TryParse(text[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value) + : ushort.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/TileFavorites.cs b/UoFiddler.Plugin.MultiEditor/Classes/TileFavorites.cs new file mode 100644 index 00000000..f6ffd7f3 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/TileFavorites.cs @@ -0,0 +1,152 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Xml; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// A named page of favorite tiles. + internal sealed class FavoritePage + { + public FavoritePage(string name) + { + Name = name; + } + + public string Name { get; set; } + + /// Tile ids in the order they were added. The tile grid shows this list. + public List Tiles { get; } = new List(); + } + + /// + /// Favorite tiles on named pages, saved in the profile folder (MultiEditorFavorites.xml). + /// UOHE bookmark files (an [Page] header, then $hex ids one per line) can be imported. + /// + internal sealed class TileFavorites + { + private const string _fileName = "MultiEditorFavorites.xml"; + + public List Pages { get; } = new List(); + + private static string FilePath => Path.Combine(Options.AppDataPath, _fileName); + + public static TileFavorites Load() + { + var favorites = new TileFavorites(); + try + { + if (File.Exists(FilePath)) + { + var dom = new XmlDocument(); + dom.Load(FilePath); + foreach (XmlElement xPage in dom.GetElementsByTagName("Page")) + { + var page = new FavoritePage(xPage.GetAttribute("name")); + foreach (XmlElement xTile in xPage.GetElementsByTagName("Tile")) + { + if (TryParseId(xTile.GetAttribute("id"), out int id)) + { + page.Tiles.Add(id); + } + } + + favorites.Pages.Add(page); + } + } + } + catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException) + { + // A broken file starts the favorites over rather than stopping the editor. + favorites.Pages.Clear(); + } + + if (favorites.Pages.Count == 0) + { + favorites.Pages.Add(new FavoritePage("Favorites")); + } + + return favorites; + } + + public void Save() + { + var dom = new XmlDocument(); + dom.AppendChild(dom.CreateXmlDeclaration("1.0", "utf-8", null)); + XmlElement root = dom.CreateElement("Favorites"); + dom.AppendChild(root); + foreach (FavoritePage page in Pages) + { + XmlElement xPage = dom.CreateElement("Page"); + xPage.SetAttribute("name", page.Name); + foreach (int id in page.Tiles) + { + XmlElement xTile = dom.CreateElement("Tile"); + xTile.SetAttribute("id", $"0x{id:X4}"); + xPage.AppendChild(xTile); + } + + root.AppendChild(xPage); + } + + dom.Save(FilePath); + } + + /// + /// Reads a UOHE bookmark file (book_sys.ini, bookmark.ini): each [Section] becomes a page, + /// each $hex line a tile. Returns the number of pages added. + /// + public int ImportUoheBookmarks(string path) + { + var imported = new List(); + FavoritePage page = null; + foreach (string raw in File.ReadAllLines(path, Encoding.Latin1)) + { + string line = raw.Trim(); + if (line.StartsWith('[') && line.EndsWith(']')) + { + page = new FavoritePage(line[1..^1].Trim()); + imported.Add(page); + } + else if (page != null && line.StartsWith('$') && + int.TryParse(line[1..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int id) && + !page.Tiles.Contains(id)) + { + page.Tiles.Add(id); + } + } + + // Sections without tiles are not worth a page. + imported.RemoveAll(p => p.Tiles.Count == 0); + Pages.AddRange(imported); + return imported.Count; + } + + private static bool TryParseId(string text, out int id) + { + id = 0; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + return text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + ? int.TryParse(text[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id) + : int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out id); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs b/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs new file mode 100644 index 00000000..6dacbc84 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs @@ -0,0 +1,259 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// Builds walls from cell edges. A wall piece sits on the +Y edge of its cell (a "South" piece, + /// running along X), the +X edge (an "East" piece, running along Y), or both (Corner). A cell + /// with no wall of its own gets a Post where walls meet at its +X/+Y corner. This matches the + /// client's walls.txt columns and the official house multis. + /// + internal sealed class WallPlanner + { + private static readonly string[] _southColumns = { "South1", "South2", "South3", "WindowS", "AltWindowS", "SecondAltWindowS" }; + private static readonly string[] _eastColumns = { "East1", "East2", "East3", "WindowE", "AltWindowE", "SecondAltWindowE" }; + + private readonly HouseStyle _style; + private readonly HouseStyles _styles; + private readonly int _z; + + // Edges of the wall layer: cells with a wall on their +Y edge (S) and +X edge (E). + private readonly HashSet<(int X, int Y)> _south = new HashSet<(int, int)>(); + private readonly HashSet<(int X, int Y)> _east = new HashSet<(int, int)>(); + + // Existing pieces of this style at this Z, and door cells (doors count as wall edges). + private readonly Dictionary<(int X, int Y), MultiTile> _pieces = new Dictionary<(int, int), MultiTile>(); + private readonly HashSet<(int X, int Y)> _doors = new HashSet<(int, int)>(); + + public WallPlanner(MultiEditorComponentList list, HouseStyles styles, HouseStyle style, int z) + { + _style = style; + _styles = styles; + _z = z; + + foreach (MultiTile tile in list.RealTiles) + { + if (tile.Z != z || !styles.TryGetRole(tile.Id, out HouseStyle owner, out string slot)) + { + continue; + } + + var cell = (tile.X, tile.Y); + if (owner.Kind == HousePartKind.Door) + { + // Pieces 1-4 hang in walls along X, 5-8 in walls along Y. + _doors.Add(cell); + (DoorAlongX(slot) ? _south : _east).Add(cell); + continue; + } + + if (owner != style) + { + continue; + } + + _pieces[cell] = tile; + if (slot == "Corner" || Array.IndexOf(_southColumns, slot) >= 0) + { + _south.Add(cell); + } + + if (slot == "Corner" || Array.IndexOf(_eastColumns, slot) >= 0) + { + _east.Add(cell); + } + } + } + + public static bool DoorAlongX(string slot) => slot is "Piece1" or "Piece2" or "Piece3" or "Piece4"; + + /// + /// The wall edges a drag between two cells adds. Two cells in a row or column (or with + /// ) give a straight wall along the cells; otherwise the dragged + /// rectangle is the room's outer wall cells, as in the official houses. + /// + public static (List<(int X, int Y)> South, List<(int X, int Y)> East) DragEdges(int x0, int y0, int x1, int y1, bool line) + { + var south = new List<(int, int)>(); + var east = new List<(int, int)>(); + int minX = Math.Min(x0, x1), maxX = Math.Max(x0, x1); + int minY = Math.Min(y0, y1), maxY = Math.Max(y0, y1); + + if (line || minX == maxX || minY == maxY) + { + if (maxX - minX >= maxY - minY) + { + for (int x = minX; x <= maxX; ++x) + { + south.Add((x, y0)); + } + } + else + { + for (int y = minY; y <= maxY; ++y) + { + east.Add((x0, y)); + } + } + + return (south, east); + } + + for (int x = minX + 1; x <= maxX; ++x) + { + south.Add((x, minY)); + south.Add((x, maxY)); + } + + for (int y = minY + 1; y <= maxY; ++y) + { + east.Add((minX, y)); + east.Add((maxX, y)); + } + + return (south, east); + } + + /// + /// Adds (or with removes) edges and works out the tiles to change + /// in the cells around them. Doors are never touched; windows stay while their edge does. + /// + public (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + IEnumerable<(int X, int Y)> south, IEnumerable<(int X, int Y)> east, bool erase, int width, int height) + { + var touched = new HashSet<(int X, int Y)>(); + void Edit(HashSet<(int, int)> set, (int X, int Y) cell) + { + if (cell.X < 0 || cell.Y < 0 || cell.X >= width || cell.Y >= height || _doors.Contains(cell)) + { + return; + } + + if (erase ? set.Remove(cell) : set.Add(cell)) + { + // A piece's choice depends on its neighbours along both axes. + for (int dx = -1; dx <= 1; ++dx) + { + for (int dy = -1; dy <= 1; ++dy) + { + touched.Add((cell.X + dx, cell.Y + dy)); + } + } + } + } + + foreach (var cell in south) + { + Edit(_south, cell); + } + + foreach (var cell in east) + { + Edit(_east, cell); + } + + var remove = new List(); + var add = new List<(ushort, int, int, int)>(); + foreach (var cell in touched) + { + if (cell.X < 0 || cell.Y < 0 || cell.X >= width || cell.Y >= height || _doors.Contains(cell)) + { + continue; + } + + string column = PieceFor(cell.X, cell.Y); + ushort want = column != null ? _style.Get(column) : (ushort)0; + _pieces.TryGetValue(cell, out MultiTile have); + + if (have != null && KeepExisting(have, column)) + { + continue; + } + + if (have != null && have.Id == want) + { + continue; + } + + if (have != null) + { + remove.Add(have); + } + + if (want != 0) + { + add.Add((want, cell.X, cell.Y, _z)); + } + } + + return (remove, add); + } + + /// + /// The walls.txt column for a cell: Corner, a South or East variant by its place in the run, + /// Post where walls meet at the cell's corner, or null for no piece. + /// + public string PieceFor(int x, int y) => PieceFor(_south, _east, x, y); + + /// + /// The walls.txt column for a cell given the +Y edges () and + /// +X edges () of a wall layer. + /// + public static string PieceFor(HashSet<(int X, int Y)> southEdges, HashSet<(int X, int Y)> eastEdges, int x, int y) + { + bool s = southEdges.Contains((x, y)); + bool e = eastEdges.Contains((x, y)); + + if (s && e) + { + return "Corner"; + } + + if (s) + { + bool start = !southEdges.Contains((x - 1, y)); + bool end = !southEdges.Contains((x + 1, y)); + return start ? "South1" : end ? "South3" : "South2"; + } + + if (e) + { + bool start = !eastEdges.Contains((x, y - 1)); + bool end = !eastEdges.Contains((x, y + 1)); + return end ? "East1" : start ? "East3" : "East2"; + } + + return southEdges.Contains((x + 1, y)) || eastEdges.Contains((x, y + 1)) ? "Post" : null; + } + + /// + /// A window or other variant of the right direction stays, so redrawing a wall keeps its windows. + /// + private bool KeepExisting(MultiTile have, string column) + { + if (column == null || !_styles.TryGetRole(have.Id, out _, out string slot)) + { + return false; + } + + bool haveSouth = Array.IndexOf(_southColumns, slot) >= 0; + bool haveEast = Array.IndexOf(_eastColumns, slot) >= 0; + bool wantSouth = Array.IndexOf(_southColumns, column) >= 0; + bool wantEast = Array.IndexOf(_eastColumns, column) >= 0; + bool isPlain = slot is "South1" or "South2" or "South3" or "East1" or "East2" or "East3"; + return !isPlain && ((haveSouth && wantSouth) || (haveEast && wantEast)); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs new file mode 100644 index 00000000..dad30bb4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs @@ -0,0 +1,834 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + /// + /// A floor of the multi: tiles from Floor up to (not including) Ceiling. BaseZ is the Z new + /// tiles get on it. The lowest level also takes what lies below its base, the highest what + /// lies above. + /// + internal readonly record struct EditorLevel(string Name, string ShortName, int Floor, int Ceiling, int BaseZ) + { + public string Description => Ceiling > sbyte.MaxValue ? $"{Name} (Z {BaseZ} and up)" : $"{Name} (Z {BaseZ} to {Ceiling - 1})"; + } + + /// How the user splits a design into levels: a name and the Z the level starts at. + internal readonly record struct LevelDefinition(string Name, int StartZ); + + /// The ground a previewed multi stands on. + internal enum PreviewTerrain + { + None, + Grass, + Dirt, + Sand, + Snow + } + + /// + /// The edit commands of a session: clipboard, selection edits, group transforms and levels. + /// + internal sealed partial class EditorSession + { + // Shared by every open document, so a copy in one tab pastes into another. + private static List _clipboard; + private static RotationTable _rotationTable; + + private readonly List _levels = new List(); + private int _levelIndex; + private int _firstFloorZ; + private readonly List _levelDefinitions = new List(); + + /// Highest Z a first floor is looked for at; above that it is a second storey. + public const int MaxFirstFloorZ = 12; + + /// Storeys between the foundation and the roof, as in the client's house designer. + public const int FloorCount = 4; + + // ---------------------------------------------------------------- clipboard + + /// + /// Copies the selection, relative to its lowest X, Y and Z, for pasting in any document and + /// as multi text lines to the Windows clipboard, so another editor or a text file can take it. + /// + public bool Copy() + { + if (_selection.Count == 0) + { + return false; + } + + _clipboard = ToClipboard(_selection); + try + { + Clipboard.SetText(ClipboardTile.Format(_clipboard)); + } + catch (ExternalException) + { + // Clipboard busy in another program: the editor's own copy still works. + } + + return true; + } + + public void Cut() + { + if (Copy()) + { + DeleteSelection(); + } + } + + /// Starts placing the clipboard tiles with the mouse. + public void Paste() + { + BeginPaste(ReadClipboard()); + } + + public bool CanPaste => _clipboard != null || ClipboardHasTiles(); + + /// The selection as tiles relative to its lowest X, Y and Z (also used to save a prefab). + public List SelectionAsClipboard() + { + return _selection.Count == 0 ? null : ToClipboard(_selection); + } + + private static List ToClipboard(IReadOnlyCollection tiles) + { + int ox = tiles.Min(t => t.X); + int oy = tiles.Min(t => t.Y); + int oz = tiles.Min(t => t.Z); + return tiles + .OrderBy(t => t.X).ThenBy(t => t.Y).ThenBy(t => t.Z) + .Select(t => new ClipboardTile(t.Id, t.X - ox, t.Y - oy, t.Z - oz, t.Invisible, t.Extra)) + .ToList(); + } + + /// Tiles from the Windows clipboard when it holds multi text lines, else the editor's own copy. + private static List ReadClipboard() + { + try + { + if (Clipboard.ContainsText() && ClipboardTile.Parse(Clipboard.GetText()) is { } fromText) + { + return fromText; + } + } + catch (ExternalException) + { + // Clipboard busy: fall back to the editor's own copy. + } + + return _clipboard; + } + + private static bool ClipboardHasTiles() + { + try + { + return Clipboard.ContainsText(); + } + catch (ExternalException) + { + return false; + } + } + + // ---------------------------------------------------------------- selection edits + + public void SelectAll() + { + SetSelection(CompList.RealTiles.Where(IsEditable), add: false); + } + + public void InvertSelection() + { + SetSelection(CompList.RealTiles.Where(t => IsEditable(t) && !_selection.Contains(t)).ToList(), add: false); + } + + /// Selects every editable tile for which holds. + public void SelectWhere(Func match, bool add) + { + SetSelection(CompList.RealTiles.Where(t => IsEditable(t) && match(t)).ToList(), add); + } + + /// + /// Grows the selection to every tile of the same id connected to it through neighbouring + /// cells (the eight around), within the editable tiles. + /// + public void SelectConnected() + { + if (_selection.Count == 0) + { + return; + } + + var ids = new HashSet(_selection.Select(t => t.Id)); + var result = new HashSet(_selection); + var queue = new Queue(_selection); + while (queue.Count > 0) + { + MultiTile from = queue.Dequeue(); + for (int dx = -1; dx <= 1; dx++) + { + for (int dy = -1; dy <= 1; dy++) + { + foreach (MultiTile tile in CompList.GetTilesAt(from.X + dx, from.Y + dy)) + { + if (tile.Id == from.Id && ids.Contains(tile.Id) && IsEditable(tile) && result.Add(tile)) + { + queue.Enqueue(tile); + } + } + } + } + } + + SetSelection(result, add: false); + } + + public void DeleteSelection() + { + if (_selection.Count == 0) + { + return; + } + + CompList.TileRemoveBatch(_selection); + _selection.Clear(); + SelectionChanged?.Invoke(); + AfterEdit(); + } + + /// Moves the selection by cells and Z in one undo step. Nothing moves when a tile would leave the multi. + public void NudgeSelection(int dx, int dy, int dz) + { + if (_selection.Count == 0) + { + return; + } + + if (CompList.TileMoveBatch(_selection.ToList(), dx, dy, dz, "Nudge Selection")) + { + AfterEdit(dz > 0 ? _selection.Max(t => t.Z) : null); + SelectionChanged?.Invoke(); + } + } + + public void ShiftSelectionZ(int delta) + { + if (_selection.Count == 0) + { + return; + } + + CompList.TileZMod(_selection, delta); + AfterEdit(delta > 0 ? _selection.Max(t => t.Z) : null); + SelectionChanged?.Invoke(); + } + + /// Gives every selected tile with one of the ids a new id, in one undo step. Returns the number changed. + public int ReplaceTileId(ushort from, ushort to, bool selectionOnly) + { + IEnumerable scope = selectionOnly ? _selection : CompList.RealTiles; + List<(MultiTile, ushort)> changes = scope.Where(t => t.Id == from).Select(t => (t, to)).ToList(); + if (changes.Count == 0 || from == to) + { + return 0; + } + + CompList.TileSetIds(changes, $"Replace 0x{from:X4} with 0x{to:X4}"); + AfterEdit(); + SelectionChanged?.Invoke(); + return changes.Count; + } + + /// + /// Rotates or mirrors the selection in place, or the whole design (swapping width and + /// height on a quarter turn) when nothing is selected. Returns a message when it cannot. + /// + public string TransformGroup(GroupTransformKind kind) + { + bool whole = _selection.Count == 0; + List group = whole ? CompList.RealTiles.ToList() : _selection.ToList(); + if (group.Count == 0) + { + return null; + } + + _rotationTable ??= RotationTable.LoadDefault(); + var add = GroupTransform.Apply(group, HouseStyles, _rotationTable, kind); + int width = CompList.Width; + int height = CompList.Height; + + if (whole) + { + if (GroupTransform.SwapsAxes(kind)) + { + (width, height) = (height, width); + } + + // New wall posts may reach a cell past the old edge: keep everything inside. + int shiftX = Math.Max(0, -add.Min(t => t.X)); + int shiftY = Math.Max(0, -add.Min(t => t.Y)); + add = add.Select(t => (t.Id, t.X + shiftX, t.Y + shiftY, t.Z, t.Invisible, t.Extra)).ToList(); + width = Math.Max(width, add.Max(t => t.X) + 1); + height = Math.Max(height, add.Max(t => t.Y) + 1); + } + else if (add.Any(t => !CompList.InBounds(t.X, t.Y))) + { + return "The turned selection would not fit inside the multi. Move it away from the edge first."; + } + + string name = kind switch + { + GroupTransformKind.RotateLeft => "Rotate Left", + GroupTransformKind.RotateRight => "Rotate Right", + GroupTransformKind.MirrorX => "Mirror X", + _ => "Mirror Y" + }; + + List added = CompList.ReplaceTiles(group, add, name, width, height); + if (!whole) + { + _selection.Clear(); + foreach (MultiTile tile in added) + { + _selection.Add(tile); + } + + SelectionChanged?.Invoke(); + } + + AfterEdit(); + return null; + } + + /// + /// Swaps every selected piece of the chosen house style's kind to the same column of that + /// style (South2 stays South2, F7 stays F7). Windows the style lacks become plain walls. + /// + public void SwapSelectionToHouseStyle() + { + HouseStyle style = HouseStyle; + if (style == null || _selection.Count == 0) + { + return; + } + + var changes = new List<(MultiTile, ushort)>(); + foreach (MultiTile tile in _selection) + { + if (!HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out string slot) || owner.Kind != style.Kind || owner == style) + { + continue; + } + + ushort id = style.Get(slot); + if (id == 0) + { + string fallback = slot switch + { + "WindowS" or "AltWindowS" or "SecondAltWindowS" => "South2", + "WindowE" or "AltWindowE" or "SecondAltWindowE" => "East2", + _ when style.Kind == HousePartKind.Floor => "F1", + _ => null + }; + id = fallback != null ? style.Get(fallback) : (ushort)0; + + // Floor styles are one colour of a row each and need not hold F1: any piece will do. + if (id == 0 && style.Kind == HousePartKind.Floor) + { + id = style.IconId; + } + } + + if (id != 0 && id != tile.Id) + { + changes.Add((tile, id)); + } + } + + if (changes.Count == 0) + { + return; + } + + CompList.TileSetIds(changes, $"Swap to {style.Name}"); + AfterEdit(); + } + + public void Resize(int width, int height) + { + CompList.Resize(width, height); + AfterEdit(); + } + + // ---------------------------------------------------------------- preview and reference + + private bool _previewMode; + private MultiEditorComponentList _reference; + private (int X, int Y, int Z) _referenceOffset; + + /// + /// Shows the multi as the client would: no editor marks, translucent and animated tiles + /// live. Nothing can be edited while it is on. + /// + public bool PreviewMode + { + get => _previewMode; + set + { + if (_previewMode == value) + { + return; + } + + CancelTool(); + _previewMode = value; + OnViewChanged(); + } + } + + private PreviewTerrain _previewTerrain = PreviewTerrain.Grass; + + /// Land drawn under and around the multi in preview mode, to judge it as placed in the world. + public PreviewTerrain PreviewTerrain + { + get => _previewTerrain; + set => SetView(ref _previewTerrain, value); + } + + /// Another multi drawn faintly under this one, to build against. Not editable, not saved. + public MultiEditorComponentList Reference => _reference; + + /// Where the reference sits, in cells and Z, relative to this multi. + public (int X, int Y, int Z) ReferenceOffset + { + get => _referenceOffset; + set => SetView(ref _referenceOffset, value); + } + + public void SetReference(MultiEditorComponentList reference) + { + _reference = reference; + _referenceOffset = (0, 0, 0); + ViewChanged?.Invoke(); + Invalidated?.Invoke(); + } + + // ---------------------------------------------------------------- work plane + + private bool _showWorkPlane; + + /// + /// Shows the footprint of the multi as a green plane at , drawn among + /// the tiles at its height so the floors below show through it. Fixed Z placement draws on it. + /// + public bool ShowWorkPlane + { + get => _showWorkPlane; + set => SetView(ref _showWorkPlane, value); + } + + /// How far the work plane was moved from its floor's base; back to 0 when the floor changes. + private int _workPlaneOffset; + + /// + /// Z of the work plane: the active floor's base, or the first floor with all floors shown, + /// moved up or down by . + /// + public int WorkPlaneZ => Math.Clamp(WorkPlaneBaseZ + _workPlaneOffset, sbyte.MinValue, sbyte.MaxValue); + + /// How far the work plane stands above (or below) its floor's base. + public int WorkPlaneOffset => WorkPlaneZ - WorkPlaneBaseZ; + + private int WorkPlaneBaseZ => _levelIndex > 0 ? _levels[_levelIndex - 1].BaseZ : _firstFloorZ; + + /// + /// Moves the work plane up or down by , within the Z a multi can hold. + /// With a floor chosen, moving out of its Z range switches to the floor the plane moved + /// into; the plane stays where it was moved. + /// + public void MoveWorkPlane(int dz) + { + int z = Math.Clamp(WorkPlaneZ + dz, sbyte.MinValue, sbyte.MaxValue); + bool floorChanged = false; + if (_levelIndex > 0) + { + int level = _levels.FindIndex(l => z >= l.Floor && z < l.Ceiling) + 1; + if (level > 0 && level != _levelIndex) + { + _levelIndex = level; + _activeLevel = (_levels[level - 1].Floor, _levels[level - 1].Ceiling); + floorChanged = true; + } + } + + int offset = z - WorkPlaneBaseZ; + if (offset == _workPlaneOffset && !floorChanged) + { + return; + } + + _workPlaneOffset = offset; + OnViewChanged(); + } + + // ---------------------------------------------------------------- plan view + + private bool _planMode; + + /// + /// Top-down view: every cell a square in the colour of its top tile, walls and doors as + /// lines on the edges they stand on. The same tools work on it. + /// + public bool PlanMode + { + get => _planMode; + set + { + if (_planMode == value) + { + return; + } + + CancelTool(); + _planMode = value; + OnViewChanged(); + } + } + + /// Lowest Z you work on: the work plane's, once a floor is chosen or the plane was moved. + public int EditMinZ => WorkZ ?? int.MinValue; + + public PlanView Plan => new PlanView(CompList, PlanShapeOf); + + /// + /// How a tile shows in the plan view, from the client's house tables: walls and doors as + /// lines on the edges they stand on, posts at the corner, everything else as the cell fill. + /// + public PlanShape PlanShapeOf(ushort id) + { + if (HouseStyles == null || !HouseStyles.TryGetRole(id, out HouseStyle style, out string slot)) + { + return PlanShape.Fill; + } + + if (style.Kind == HousePartKind.Door) + { + return PlanShape.Door | (WallPlanner.DoorAlongX(slot) ? PlanShape.South : PlanShape.East); + } + + if (style.Kind != HousePartKind.Wall) + { + return PlanShape.Fill; + } + + return slot switch + { + "Corner" => PlanShape.South | PlanShape.East, + "Post" => PlanShape.Post, + _ when slot.StartsWith("South", StringComparison.Ordinal) || slot.EndsWith('S') => PlanShape.South, + _ when slot.StartsWith("East", StringComparison.Ordinal) || slot.EndsWith('E') => PlanShape.East, + _ => PlanShape.Fill + }; + } + + /// World point a tile is picked by in area selections: the middle of its cell. + public PointF TileAnchor(MultiTile tile) + { + if (_planMode) + { + Point origin = PlanView.CellOrigin(tile.X, tile.Y); + return new PointF(origin.X + (PlanView.Cell / 2f), origin.Y + (PlanView.Cell / 2f)); + } + + PointF corner = CellCorner(tile.X, tile.Y, tile.Z); + return new PointF(corner.X, corner.Y + 22); + } + + // ---------------------------------------------------------------- levels + + /// The floors of the multi, bottom to top. + public IReadOnlyList Levels => _levels; + + /// 0 shows all levels; n works on Levels[n - 1]. + public int LevelIndex + { + get => _levelIndex; + set + { + value = Math.Clamp(value, 0, _levels.Count); + if (value == _levelIndex) + { + return; + } + + _levelIndex = value; + ApplyLevel(); + } + } + + public void StepLevel(int step) + { + if (_levels.Count == 0) + { + return; + } + + // From "all levels", stepping up starts at the bottom level. + LevelIndex = _levelIndex == 0 && step > 0 ? 1 : _levelIndex + step; + } + + /// + /// Z of the first floor. 0 for a multi built from the ground; above 0 the multi stands on a + /// foundation, which is then a level of its own below the floors. Custom house foundations + /// and most classic houses use 7, some classic houses 4, 5, 6 or 8. Found from the tiles on + /// load. Setting it puts the levels back to the standard split from that Z. + /// + public int FirstFloorZ + { + get => _firstFloorZ; + set + { + value = Math.Clamp(value, 0, MaxFirstFloorZ); + if (_firstFloorZ == value && !CustomLevels) + { + return; + } + + _firstFloorZ = value; + ApplyLevelDefinitions(StandardLevels(value), custom: false); + } + } + + public bool HasFoundation => _firstFloorZ > 0; + + /// True when the user set the levels by hand, so they are no longer the standard split. + public bool CustomLevels { get; private set; } + + /// The levels as defined: name and starting Z, lowest first. + public IReadOnlyList LevelDefinitions => _levelDefinitions; + + /// + /// The standard split: an optional foundation below the first floor, four floors 20 high, + /// and a roof level above them. These are the client's house designer numbers. + /// + public static List StandardLevels(int firstFloorZ) + { + var levels = new List(); + if (firstFloorZ > 0) + { + levels.Add(new LevelDefinition("Foundation", 0)); + } + + for (int n = 1; n <= FloorCount; n++) + { + levels.Add(new LevelDefinition($"Floor {n}", firstFloorZ + ((n - 1) * 20))); + } + + levels.Add(new LevelDefinition("Roof", firstFloorZ + (FloorCount * 20))); + return levels; + } + + /// + /// A split fitted to this design: floors 20 high from the first floor up to where its roof + /// tiles begin, then the roof. Without roof tiles it is the standard split. + /// + public List FittedLevels() + { + int roof = int.MaxValue; + foreach (MultiTile tile in CompList.RealTiles) + { + if ((TileData.ItemTable[tile.Id].Flags & TileFlag.Roof) != 0 && tile.Z > _firstFloorZ) + { + roof = Math.Min(roof, tile.Z); + } + } + + if (roof == int.MaxValue) + { + return StandardLevels(_firstFloorZ); + } + + var levels = new List(); + if (_firstFloorZ > 0) + { + levels.Add(new LevelDefinition("Foundation", 0)); + } + + // A floor needs most of a storey below the roof to count; a roof starting a few Z into + // the next band still belongs over the floor below. + int n = 1; + for (int floor = _firstFloorZ; floor == _firstFloorZ || floor + 10 <= roof; floor += 20) + { + levels.Add(new LevelDefinition($"Floor {n++}", floor)); + } + + levels.Add(new LevelDefinition("Roof", Math.Max(roof, levels[^1].StartZ + 1))); + return levels; + } + + /// Sets the levels by hand. Starts are kept within a multi's Z range and must differ; at least one level stays. + public void SetLevelDefinitions(IEnumerable levels) + { + ApplyLevelDefinitions(levels, custom: true); + } + + private void ApplyLevelDefinitions(IEnumerable levels, bool custom) + { + var cleaned = new List(); + foreach (LevelDefinition level in levels.OrderBy(l => l.StartZ)) + { + int start = Math.Clamp(level.StartZ, sbyte.MinValue, sbyte.MaxValue); + string name = string.IsNullOrWhiteSpace(level.Name) ? $"Level {cleaned.Count + 1}" : level.Name.Trim(); + if (cleaned.Count == 0 || cleaned[^1].StartZ != start) + { + cleaned.Add(new LevelDefinition(name, start)); + } + } + + if (cleaned.Count == 0) + { + cleaned = StandardLevels(_firstFloorZ); + custom = false; + } + + _levelDefinitions.Clear(); + _levelDefinitions.AddRange(cleaned); + CustomLevels = custom; + RebuildLevels(); + if (_levelIndex > 0) + { + ApplyLevel(); + } + else + { + OnViewChanged(); + } + } + + /// + /// The first floor is the lowest Z, up to , that holds a real + /// share of the flat walkable tiles. One stray flat tile low down does not make a floor. + /// + private int DetectFirstFloorZ() + { + var flat = new SortedDictionary(); + foreach (MultiTile tile in CompList.RealTiles) + { + if (tile.Height == 0 && (TileData.ItemTable[tile.Id].Flags & TileFlag.Surface) != 0) + { + flat[tile.Z] = flat.GetValueOrDefault(tile.Z) + 1; + } + } + + if (flat.Count == 0) + { + return 0; + } + + int needed = Math.Max(4, flat.Values.Max() / 4); + foreach ((int z, int count) in flat) + { + if (z >= 0 && z <= MaxFirstFloorZ && count >= needed) + { + return z; + } + } + + return 0; + } + + /// A short label for a level's button: the number of "Floor 2", else the start of the name. + private static string ShortNameOf(string name) + { + if (name.StartsWith("Floor ", StringComparison.OrdinalIgnoreCase) && name.Length > 6) + { + return name.Substring(6); + } + + return name.Equals("Foundation", StringComparison.OrdinalIgnoreCase) ? "Fnd" : name.Length <= 5 ? name : name.Substring(0, 5); + } + + /// + /// Builds the levels from their definitions. Every level is there whether it holds tiles or + /// not, so an empty floor can be chosen and built on. + /// + public void RebuildLevels() + { + var levels = new List(); + if (HasDocument) + { + if (_levelDefinitions.Count == 0) + { + _levelDefinitions.AddRange(StandardLevels(_firstFloorZ)); + } + + for (int i = 0; i < _levelDefinitions.Count; i++) + { + LevelDefinition level = _levelDefinitions[i]; + int from = i == 0 ? sbyte.MinValue : level.StartZ; + int to = i + 1 < _levelDefinitions.Count ? _levelDefinitions[i + 1].StartZ : sbyte.MaxValue + 1; + levels.Add(new EditorLevel(level.Name, ShortNameOf(level.Name), from, to, level.StartZ)); + } + } + + if (levels.SequenceEqual(_levels)) + { + return; + } + + _levels.Clear(); + _levels.AddRange(levels); + if (_levelIndex > _levels.Count) + { + _levelIndex = 0; + ApplyLevel(); + } + else if (_levelIndex > 0) + { + // Same index, possibly a different Z band. + _activeLevel = (_levels[_levelIndex - 1].Floor, _levels[_levelIndex - 1].Ceiling); + } + } + + /// + /// Limits the view to the chosen level and puts the work plane on its base, where drawing + /// then lands (). + /// + private void ApplyLevel() + { + _workPlaneOffset = 0; + if (_levelIndex > 0) + { + EditorLevel level = _levels[_levelIndex - 1]; + _activeLevel = (level.Floor, level.Ceiling); + } + else + { + _activeLevel = null; + } + + OnViewChanged(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs new file mode 100644 index 00000000..af7dc356 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs @@ -0,0 +1,750 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.Rendering; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + /// + /// The tools of the editor, by the name the UI shows. + /// + internal enum ToolKind + { + Select, + Lasso, + Draw, + Remove, + Altitude, + Pipette, + Transparent, + RectFill, + Line, + Wall, + Floor, + Door, + Stair, + Roof, + Foundation, + + /// Lays a bordered floor pattern; chosen from the House page, not the palette. + FloorPattern + } + + /// + /// One multi being edited: the tiles, what is selected and hovered, the view options and the + /// active tool. It knows nothing about controls; the canvas feeds it pointer events and the + /// panels listen to its events. + /// + internal sealed partial class EditorSession : IEditorContext, IMultiViewSettings + { + private readonly HashSet _selection = new HashSet(); + private readonly Dictionary _tools = new Dictionary(); + private readonly ArtMasks _masks; + private readonly PasteTool _pasteTool; + + private EditorTool _temporaryTool; + private ToolKind _toolKind = ToolKind.Select; + private Point _mouseLoc; + private bool _mouseInside; + private (int X, int Y, int Z) _cursorCell = (int.MinValue, int.MinValue, int.MinValue); + private int? _heightLimit; + private (int Floor, int Ceiling)? _activeLevel; + private bool _hideAboveLevel = true; + private bool _hideWalls; + private bool _showWalkables; + private bool _showDoubleSurface; + private bool _showGrid; + private ushort _drawTileId; + + public EditorSession(ArtMasks masks, HouseStyles houseStyles) + { + _masks = masks; + HouseStyles = houseStyles; + + _tools[ToolKind.Select] = new SelectTool(this); + _tools[ToolKind.Lasso] = new LassoTool(this); + _tools[ToolKind.Draw] = new DrawTool(this); + _tools[ToolKind.Remove] = new RemoveTool(this); + _tools[ToolKind.Altitude] = new AltitudeTool(this); + _tools[ToolKind.Pipette] = new PipetteTool(this); + _tools[ToolKind.Transparent] = new TransparentTool(this); + _tools[ToolKind.RectFill] = new RectFillTool(this); + _tools[ToolKind.Line] = new LineTool(this); + _tools[ToolKind.Wall] = new WallTool(this); + _tools[ToolKind.Floor] = new FloorStyleTool(this); + _tools[ToolKind.Door] = new DoorTool(this); + _tools[ToolKind.Stair] = new StairTool(this); + _tools[ToolKind.Roof] = new RoofTool(this); + _tools[ToolKind.Foundation] = new FoundationTool(this); + _tools[ToolKind.FloorPattern] = new FloorPatternTool(this); + _pasteTool = new PasteTool(this); + + CompList = new MultiEditorComponentList(0, 0, this); + } + + /// Something on the canvas changed: repaint. + public event Action Invalidated; + + /// The tiles changed (edit, undo, redo, load). + public event Action DocumentChanged; + + public event Action SelectionChanged; + + public event Action HoverChanged; + + /// The cell under the cursor changed. + public event Action CursorCellChanged; + + public event Action ToolChanged; + + public event Action DrawTileChanged; + + /// A view option changed (floor, level, height limit, filters). + public event Action ViewChanged; + + /// A tile id was placed by a tool. + public event Action TileUsed; + + // ---------------------------------------------------------------- document + + public MultiEditorComponentList CompList { get; private set; } + + public bool HasDocument => CompList.Width > 0 && CompList.Height > 0; + + /// Name shown on the document tab. + public string Title { get; set; } = "Untitled"; + + /// True when there are edits since the last save or load. + public bool Modified { get; private set; } + + public void NewBlank(int width, int height, int firstFloorZ = 0) + { + SetDocument(new MultiEditorComponentList(width, height, this)); + FirstFloorZ = firstFloorZ; + } + + public void Load(MultiComponentList list) + { + SetDocument(new MultiEditorComponentList(list, this)); + } + + public void MarkSaved() + { + Modified = false; + DocumentChanged?.Invoke(); + } + + public bool Undo() + { + if (!CompList.UndoStep()) + { + return false; + } + + AfterEdit(); + return true; + } + + public bool Redo() + { + if (!CompList.RedoStep()) + { + return false; + } + + AfterEdit(); + return true; + } + + private void SetDocument(MultiEditorComponentList list) + { + CancelTool(); + CompList = list; + _selection.Clear(); + HoverTile = null; + _heightLimit = null; + _activeLevel = null; + _levelIndex = 0; + _workPlaneOffset = 0; + Modified = false; + _firstFloorZ = DetectFirstFloorZ(); + _levelDefinitions.Clear(); + CustomLevels = false; + RebuildLevels(); + + DocumentChanged?.Invoke(); + SelectionChanged?.Invoke(); + ViewChanged?.Invoke(); + Invalidated?.Invoke(); + } + + // ---------------------------------------------------------------- view options + + /// + /// The Z you build on: the work plane's, once a floor is chosen or the plane was moved. + /// Tiles below it cannot be edited, and drawing on an empty cell and the house tools land + /// on it. Null with all floors shown and the plane where it starts. + /// + public int? WorkZ => _levelIndex > 0 || _workPlaneOffset != 0 ? WorkPlaneZ : null; + + /// Highest Z drawn, or null to draw everything. + public int? HeightLimit + { + get => _heightLimit; + set => SetView(ref _heightLimit, value); + } + + /// The level being edited: tiles from Floor up to (not including) Ceiling. Null shows all. + public (int Floor, int Ceiling)? ActiveLevel + { + get => _activeLevel; + set => SetView(ref _activeLevel, value); + } + + /// Tiles above the active level are hidden instead of drawn faint. + public bool HideAboveLevel + { + get => _hideAboveLevel; + set => SetView(ref _hideAboveLevel, value); + } + + public bool HideWalls + { + get => _hideWalls; + set => SetView(ref _hideWalls, value); + } + + public bool ShowWalkables + { + get => _showWalkables; + set + { + if (SetView(ref _showWalkables, value) && value) + { + CompList.CalcWalkable(); + } + } + } + + public bool ShowDoubleSurface + { + get => _showDoubleSurface; + set + { + if (SetView(ref _showDoubleSurface, value) && value) + { + CompList.CalcDoubleSurface(); + } + } + } + + public bool ShowGrid + { + get => _showGrid; + set => SetView(ref _showGrid, value); + } + + /// + /// Highest Z you work on: the height limit, lowered to the active level's top. Tiles above + /// it can be seen (faint) but not hovered, selected or removed. + /// + public int EditMaxHeight + { + get + { + int limit = _heightLimit ?? sbyte.MaxValue; + return _activeLevel is { } level ? Math.Min(limit, level.Ceiling - 1) : limit; + } + } + + public void HideSelection() + { + if (_selection.Count == 0) + { + return; + } + + foreach (MultiTile tile in _selection) + { + tile.Hidden = true; + } + + _selection.Clear(); + SelectionChanged?.Invoke(); + OnViewChanged(); + } + + public void ShowHiddenTiles() + { + foreach (MultiTile tile in CompList.RealTiles) + { + tile.Hidden = false; + } + + OnViewChanged(); + } + + private bool SetView(ref T field, T value) + { + if (EqualityComparer.Default.Equals(field, value)) + { + return false; + } + + field = value; + OnViewChanged(); + return true; + } + + /// After a view option changed: drop selected tiles that can no longer be seen, refind hover. + private void OnViewChanged() + { + int removed = _selection.RemoveWhere(t => + !CompList.IsShown(t) || (_activeLevel is { } level && (t.Z >= level.Ceiling || t.Z < level.Floor))); + if (removed > 0) + { + SelectionChanged?.Invoke(); + } + + _cursorCell = (int.MinValue, int.MinValue, int.MinValue); + UpdateHover(); + UpdateCursorCell(); + ViewChanged?.Invoke(); + Invalidated?.Invoke(); + } + + // ---------------------------------------------------------------- tools + + public ToolKind Tool + { + get => _toolKind; + set + { + CancelTool(); + _toolKind = value; + ToolChanged?.Invoke(); + Invalidated?.Invoke(); + } + } + + public EditorTool ActiveTool => _temporaryTool ?? _tools[_toolKind]; + + /// The bordered floor laid by the floor pattern tool, or null. + public FloorPattern FloorPattern { get; set; } + + /// The roof tool, for its shape options (ridge, gables, gable fill). + public RoofTool Roof => (RoofTool)_tools[ToolKind.Roof]; + + /// Call after a tool option changed, so the preview under the cursor follows. + public void ToolOptionsChanged() + { + Invalidated?.Invoke(); + } + + /// True while a paste is waiting to be placed. + public bool Pasting => _temporaryTool != null; + + public ushort DrawTileId => _drawTileId; + + public int BrushSize { get; set; } = 1; + + public PlacementMode Placement { get; set; } = PlacementMode.Stack; + + public HouseStyles HouseStyles { get; } + + public HouseStyle HouseStyle { get; set; } + + public int ZStep { get; set; } = 1; + + /// Drops a drag, a pending paste or any other half-done tool action. + public void CancelTool() + { + _temporaryTool?.Cancel(); + _temporaryTool = null; + _tools[_toolKind].Cancel(); + Invalidated?.Invoke(); + } + + /// Starts placing a group of tiles with the mouse. + public void BeginPaste(List tiles) + { + if (tiles == null || tiles.Count == 0 || !HasDocument) + { + return; + } + + CancelTool(); + _pasteTool.Begin(tiles); + _temporaryTool = _pasteTool; + ToolChanged?.Invoke(); + Invalidated?.Invoke(); + } + + public void SetDrawTile(ushort id) + { + _drawTileId = id; + DrawTileChanged?.Invoke(); + Invalidated?.Invoke(); + } + + // ---------------------------------------------------------------- selection and hover + + public MultiTile HoverTile { get; private set; } + + public IReadOnlyCollection Selection => _selection; + + /// The selected tile when exactly one is selected. + public MultiTile SelectedTile => _selection.Count == 1 ? _selection.First() : null; + + public bool IsSelected(MultiTile tile) => _selection.Contains(tile); + + public (int X, int Y, int Z) CursorCell => _cursorCell; + + public bool MouseInside => _mouseInside; + + public void SetSelection(IEnumerable tiles, bool add) + { + if (!add) + { + _selection.Clear(); + } + + foreach (MultiTile tile in tiles) + { + _selection.Add(tile); + } + + SelectionChanged?.Invoke(); + Invalidated?.Invoke(); + } + + public void ToggleSelected(MultiTile tile) + { + if (!_selection.Remove(tile)) + { + _selection.Add(tile); + } + + SelectionChanged?.Invoke(); + Invalidated?.Invoke(); + } + + public void ClearSelection() + { + if (_selection.Count == 0) + { + return; + } + + _selection.Clear(); + SelectionChanged?.Invoke(); + Invalidated?.Invoke(); + } + + /// True when a tile can be hovered, selected and edited with the current view. + public bool IsEditable(MultiTile tile) + { + return tile.Z <= EditMaxHeight && !(WorkZ is { } baseZ && baseZ > tile.Z) && CompList.IsShown(tile); + } + + /// The topmost editable tile with a drawn pixel at a world point, or null. + public MultiTile HitTest(Point world) + { + if (_planMode) + { + (int cx, int cy) = PlanView.CellAt(world); + return CompList.InBounds(cx, cy) ? Plan.TopTile(cx, cy, EditMaxHeight, EditMinZ) : null; + } + + MultiTile hit = null; + + // Draw order: the last match is the one on top. Runs on every mouse move over every + // tile, so the point is first checked against the art's rectangle, which rules out + // almost all of them without a lookup. + foreach (MultiTile tile in CompList.RealTiles) + { + int px = world.X - tile.XMod; + int py = world.Y - tile.YMod; + if ((uint)px >= (uint)tile.ArtWidth || (uint)py >= (uint)tile.ArtHeight) + { + continue; + } + + if (IsEditable(tile) && _masks.Hit(tile.Id, px, py)) + { + hit = tile; + } + } + + return hit; + } + + /// How long the last hover update's hit test took, for the performance box. + public double LastHitTestMs { get; private set; } + + private bool UpdateHover() + { + long start = System.Diagnostics.Stopwatch.GetTimestamp(); + MultiTile hover = _mouseInside && HasDocument && !_previewMode ? HitTest(_mouseLoc) : null; + LastHitTestMs = System.Diagnostics.Stopwatch.GetElapsedTime(start).TotalMilliseconds; + if (hover == HoverTile) + { + return false; + } + + HoverTile = hover; + HoverChanged?.Invoke(); + return true; + } + + private bool UpdateCursorCell() + { + if (!_mouseInside || !HasDocument) + { + return false; + } + + ConvertCoords(_mouseLoc, out int x, out int y, out int z); + if ((x, y, z) == _cursorCell) + { + return false; + } + + _cursorCell = (x, y, z); + CursorCellChanged?.Invoke(); + return true; + } + + // ---------------------------------------------------------------- pointer input (world space) + + public void PointerMove(Point world, MouseEventArgs e) + { + _mouseLoc = world; + _mouseInside = true; + if (!HasDocument || _previewMode) + { + return; + } + + // Hover first: tools read the cell under the mouse, which depends on the hovered tile. + bool hoverChanged = UpdateHover(); + bool cellChanged = UpdateCursorCell(); + EditorTool tool = ActiveTool; + tool.OnMouseMove(e); + if (hoverChanged || tool.IsDragging || (cellChanged && tool.TracksCursorCell)) + { + Invalidated?.Invoke(); + } + } + + public void PointerLeave() + { + _mouseInside = false; + _cursorCell = (int.MinValue, int.MinValue, int.MinValue); + UpdateHover(); + CursorCellChanged?.Invoke(); + Invalidated?.Invoke(); + } + + public void PointerDown(Point world, MouseEventArgs e) + { + _mouseLoc = world; + _mouseInside = true; + if (HasDocument && !_previewMode && e.Button == MouseButtons.Left) + { + UpdateHover(); + UpdateCursorCell(); + ActiveTool.OnMouseDown(e); + Invalidated?.Invoke(); + } + } + + public void PointerUp(Point world, MouseEventArgs e) + { + _mouseLoc = world; + if (!HasDocument || _previewMode) + { + return; + } + + if (e.Button == MouseButtons.Middle) + { + // Selects the hovered tile with any tool, so the cell stack lists its cell. + if (HoverTile != null) + { + SetSelection(new[] { HoverTile }, add: false); + } + } + else if (e.Button == MouseButtons.Left) + { + ActiveTool.OnMouseUp(e); + } + + Invalidated?.Invoke(); + } + + // ---------------------------------------------------------------- IEditorContext + + Point IEditorContext.MouseLoc => _mouseLoc; + + int IEditorContext.MaxHeight => EditMaxHeight; + + // Canvas space is world space here: nothing is scrolled. + int IEditorContext.ScrollX => 0; + + int IEditorContext.ScrollY => 0; + + void IEditorContext.CellAt(Point canvasLoc, out int x, out int y, out int z) => ConvertCoords(canvasLoc, out x, out y, out z); + + void IEditorContext.PlaneCell(Point canvasLoc, int z, out int x, out int y) => CellOnPlane(canvasLoc, z, out x, out y); + + public List TilesInRect(Rectangle worldRect) + { + if (_planMode) + { + return Plan.TilesInRect(worldRect, EditMaxHeight, EditMinZ); + } + + var result = new List(); + foreach (MultiTile tile in CompList.RealTiles) + { + if (IsEditable(tile) && ArtMetrics.TryGetSize(tile.Id, out int width, out int height) && + worldRect.IntersectsWith(new Rectangle(tile.XMod, tile.YMod, width, height))) + { + result.Add(tile); + } + } + + return result; + } + + /// + /// Call after an edit. With a height limit is raised to show + /// tiles placed at that Z. + /// + public void AfterEdit(int? raiseTo = null) + { + if (_heightLimit is { } limit && raiseTo is { } raise && limit < raise) + { + _heightLimit = raise; + ViewChanged?.Invoke(); + } + + // Tiles removed by the edit (or by undo) are no longer selectable. + if (_selection.RemoveWhere(t => !CompList.Contains(t)) > 0) + { + SelectionChanged?.Invoke(); + } + + Modified = true; + RebuildLevels(); + if (_showWalkables) + { + CompList.CalcWalkable(); + } + + if (_showDoubleSurface) + { + CompList.CalcDoubleSurface(); + } + + UpdateHover(); + _cursorCell = (int.MinValue, int.MinValue, int.MinValue); + UpdateCursorCell(); + DocumentChanged?.Invoke(); + Invalidated?.Invoke(); + } + + void IEditorContext.RecordRecentTile(ushort id) => TileUsed?.Invoke(id); + + void IEditorContext.EndTemporaryTool() + { + _temporaryTool = null; + ToolChanged?.Invoke(); + Invalidated?.Invoke(); + } + + // ---------------------------------------------------------------- coordinates + + /// World position of the top corner of a cell's floor diamond at height z. + public static PointF CellCorner(int x, int y, int z) + { + return new PointF(((x - y) * 22) + MultiEditorComponentList.GapXMod, ((x + y) * 22) - (z * 4) - 22); + } + + /// The cell under a world point on the plane at height z, in the current view (isometric or plan). + public void CellOnPlane(Point world, int z, out int x, out int y) + { + if (_planMode) + { + (x, y) = PlanView.CellAt(world); + return; + } + + PlaneCell(world, z, out x, out y); + } + + /// The cell under a world point on the flat plane at height . + public static void PlaneCell(Point world, int z, out int x, out int y) + { + // Relative to the top corner of cell (0,0) at that height. + double mx = world.X - MultiEditorComponentList.GapXMod; + double my = world.Y + (z * 4) + 22; + + // Floor, not truncation, so cells left of or above the multi come out negative. + x = (int)Math.Floor((mx + my) / 44.0); + y = (int)Math.Floor((my - mx) / 44.0); + } + + /// + /// The cell under a world point and the Z a new tile gets there in the current placement mode. + /// + private void ConvertCoords(Point world, out int x, out int y, out int z) + { + if (Placement == PlacementMode.FixedZ) + { + z = WorkPlaneZ; + CellOnPlane(world, z, out x, out y); + return; + } + + MultiTile hover = HoverTile; + if (hover != null && (WorkZ is not { } baseZ || hover.Z >= baseZ)) + { + x = hover.X; + y = hover.Y; + if (Placement == PlacementMode.Replace) + { + z = hover.Z; + return; + } + + z = hover.Z + hover.Height; + if (_heightLimit is { } limit) + { + z = Math.Min(z, limit); + } + + return; + } + + // No tile under the mouse: the cell on the work plane, or on Z 0. + z = WorkZ ?? 0; + CellOnPlane(world, z, out x, out y); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs b/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs new file mode 100644 index 00000000..f052304e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs @@ -0,0 +1,576 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using System.Xml; +using Ultima; +using UoFiddler.Controls.Classes; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + /// + /// A floor with a border: four corner pieces, a run of pieces for each side and a block of + /// fill tiles for the inside. Laid over a rectangle of any size, the sides and the fill repeat. + /// Sides are named by the world: north is the low Y row, west the low X column. + /// + internal sealed class FloorPattern + { + public string Name { get; set; } + + /// Shipped with the editor, not saved to or deleted from the user's file. + public bool BuiltIn { get; set; } + + public ushort NorthWest { get; set; } + + public ushort NorthEast { get; set; } + + public ushort SouthWest { get; set; } + + public ushort SouthEast { get; set; } + + /// Pieces along each side between the corners, in order of rising X (north, south) or Y (west, east). + public List North { get; set; } = new List(); + + public List South { get; set; } = new List(); + + public List West { get; set; } = new List(); + + public List East { get; set; } = new List(); + + /// The inside as a block of tiles, row by row (Y major), wide. + public List Fill { get; set; } = new List(); + + public int FillWidth { get; set; } = 1; + + public int FillHeight => FillWidth > 0 ? Math.Max(1, Fill.Count / FillWidth) : 1; + + /// A tile to show for the pattern in lists. + public ushort IconId => NorthWest != 0 ? NorthWest : Fill.FirstOrDefault(); + + /// Every distinct tile of the pattern, corners first. + public IEnumerable Pieces() + { + var seen = new HashSet(); + foreach (ushort id in new[] { NorthWest, NorthEast, SouthWest, SouthEast }.Concat(North).Concat(East).Concat(South).Concat(West).Concat(Fill)) + { + if (id != 0 && seen.Add(id)) + { + yield return id; + } + } + } + + /// + /// The tile for each cell of a rectangle. A rectangle one cell wide or high has no room for + /// a border and gets fill only. + /// + public IEnumerable<(ushort Id, int X, int Y)> Layout(int x0, int y0, int x1, int y1) + { + bool border = x1 > x0 && y1 > y0; + for (int x = x0; x <= x1; x++) + { + for (int y = y0; y <= y1; y++) + { + ushort id = 0; + if (border) + { + bool west = x == x0, east = x == x1, north = y == y0, south = y == y1; + id = north && west ? NorthWest + : north && east ? NorthEast + : south && west ? SouthWest + : south && east ? SouthEast + : north ? At(North, x - x0 - 1) + : south ? At(South, x - x0 - 1) + : west ? At(West, y - y0 - 1) + : east ? At(East, y - y0 - 1) + : (ushort)0; + } + + if (id == 0 && Fill.Count > 0) + { + // The fill block starts at the first inner cell, so it sits the same way at any size. + int fx = Mod(x - x0 - (border ? 1 : 0), FillWidth); + int fy = Mod(y - y0 - (border ? 1 : 0), FillHeight); + id = Fill[Math.Min(Fill.Count - 1, (fy * FillWidth) + fx)]; + } + + if (id != 0) + { + yield return (id, x, y); + } + } + } + } + + private static ushort At(List run, int index) => run.Count == 0 ? (ushort)0 : run[Mod(index, run.Count)]; + + private static int Mod(int value, int by) => by <= 0 ? 0 : ((value % by) + by) % by; + + /// + /// Learns a pattern from a floor laid out by hand: the selected tiles must fill a rectangle + /// of at least 3 by 3 cells, one tile per cell (the highest selected one counts). Returns + /// null with a reason when they do not. + /// + public static FloorPattern Learn(IReadOnlyCollection selection, string name, out string problem) + { + problem = null; + if (selection.Count == 0) + { + problem = "Select the floor tiles of one bordered rectangle first."; + return null; + } + + int x0 = selection.Min(t => t.X), x1 = selection.Max(t => t.X); + int y0 = selection.Min(t => t.Y), y1 = selection.Max(t => t.Y); + if (x1 - x0 < 2 || y1 - y0 < 2) + { + problem = "The selection must be at least 3 by 3 cells: corners, sides and something inside."; + return null; + } + + var top = new Dictionary<(int, int), MultiTile>(); + foreach (MultiTile tile in selection) + { + if (!top.TryGetValue((tile.X, tile.Y), out MultiTile have) || tile.Z > have.Z) + { + top[(tile.X, tile.Y)] = tile; + } + } + + for (int x = x0; x <= x1; x++) + { + for (int y = y0; y <= y1; y++) + { + if (!top.ContainsKey((x, y))) + { + problem = $"The selection is not a full rectangle: cell {x}, {y} has no selected tile."; + return null; + } + } + } + + ushort Id(int x, int y) => top[(x, y)].Id; + var pattern = new FloorPattern + { + Name = name, + NorthWest = Id(x0, y0), + NorthEast = Id(x1, y0), + SouthWest = Id(x0, y1), + SouthEast = Id(x1, y1), + FillWidth = x1 - x0 - 1 + }; + + for (int x = x0 + 1; x < x1; x++) + { + pattern.North.Add(Id(x, y0)); + pattern.South.Add(Id(x, y1)); + } + + for (int y = y0 + 1; y < y1; y++) + { + pattern.West.Add(Id(x0, y)); + pattern.East.Add(Id(x1, y)); + } + + for (int y = y0 + 1; y < y1; y++) + { + for (int x = x0 + 1; x < x1; x++) + { + pattern.Fill.Add(Id(x, y)); + } + } + + pattern.Shrink(); + return pattern; + } + + /// Drops repeats: a side that is one piece over and over is stored as that piece, likewise the fill block. + private void Shrink() + { + North = Period(North); + South = Period(South); + West = Period(West); + East = Period(East); + + int width = FillWidth, height = FillHeight; + int pw = width, ph = height; + for (int w = 1; w <= width; w++) + { + if (Enumerable.Range(0, Fill.Count).All(i => Fill[i] == Fill[(i / width * width) + (i % width % w)])) + { + pw = w; + break; + } + } + + for (int h = 1; h <= height; h++) + { + if (Enumerable.Range(0, Fill.Count).All(i => Fill[i] == Fill[(i / width % h * width) + (i % width)])) + { + ph = h; + break; + } + } + + var block = new List(); + for (int y = 0; y < ph; y++) + { + for (int x = 0; x < pw; x++) + { + block.Add(Fill[(y * width) + x]); + } + } + + Fill = block; + FillWidth = pw; + } + + private static List Period(List run) + { + for (int length = 1; length < run.Count; length++) + { + if (Enumerable.Range(0, run.Count).All(i => run[i] == run[i % length])) + { + return run.GetRange(0, length); + } + } + + return run; + } + } + + /// + /// The floor patterns: a few shipped ones for tile sets whose border pieces are known, and the + /// ones the user saved (MultiEditorFloorPatterns.xml next to the other multi editor files). + /// + internal static class FloorPatterns + { + private static List _user; + + public static string FilePath => Path.Combine(Options.AppDataPath ?? string.Empty, "plugins", "MultiEditorFloorPatterns.xml"); + + /// User patterns first (newest last), then the shipped ones this client has the art for. + public static List All() + { + _user ??= LoadUser(); + var all = new List(_user); + foreach (FloorPattern pattern in BuiltIn()) + { + if (pattern.Pieces().All(id => Art.IsValidStatic(id)) && all.All(p => p.Name != pattern.Name)) + { + all.Add(pattern); + } + } + + return all; + } + + public static void Save(FloorPattern pattern) + { + _user ??= LoadUser(); + _user.RemoveAll(p => string.Equals(p.Name, pattern.Name, StringComparison.OrdinalIgnoreCase)); + _user.Add(pattern); + SaveUser(); + } + + public static void Delete(FloorPattern pattern) + { + _user ??= LoadUser(); + if (_user.Remove(pattern)) + { + SaveUser(); + } + } + + /// Forgets what was read, after the profile or client changed. + public static void Reset() + { + _user = null; + } + + /// + /// Sets read off the client's art: the piece with its band on a side goes on that side of + /// the floor. Checked by eye against the 7.0.114.4 art. + /// + private static IEnumerable BuiltIn() + { + yield return new FloorPattern + { + Name = "Gargish Green, bordered", + BuiltIn = true, + NorthWest = 16821, NorthEast = 16823, SouthWest = 16826, SouthEast = 16828, + North = { 16822 }, West = { 16824 }, East = { 16825 }, South = { 16827 }, + Fill = { 16815, 16816, 16817, 16818 }, + FillWidth = 2 + }; + yield return new FloorPattern + { + Name = "Gargish Motif, bordered", + BuiltIn = true, + NorthWest = 16860, NorthEast = 16862, SouthWest = 16866, SouthEast = 16868, + North = { 16861 }, West = { 16863 }, East = { 16865 }, South = { 16867 }, + Fill = { 16864 }, + FillWidth = 1 + }; + } + + private static List LoadUser() + { + var result = new List(); + try + { + if (!File.Exists(FilePath)) + { + return result; + } + + var dom = new XmlDocument(); + dom.Load(FilePath); + foreach (XmlElement node in dom.SelectNodes("/FloorPatterns/Pattern")) + { + var pattern = new FloorPattern + { + Name = node.GetAttribute("name"), + NorthWest = One(node, "nw"), + NorthEast = One(node, "ne"), + SouthWest = One(node, "sw"), + SouthEast = One(node, "se"), + North = Many(node, "north"), + South = Many(node, "south"), + West = Many(node, "west"), + East = Many(node, "east"), + Fill = Many(node, "fill"), + FillWidth = Math.Max(1, (int)One(node, "fillWidth")) + }; + if (!string.IsNullOrWhiteSpace(pattern.Name) && pattern.Pieces().Any()) + { + result.Add(pattern); + } + } + } + catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException) + { + // A damaged file must not keep the editor from opening; the patterns in it are skipped. + } + + return result; + } + + private static void SaveUser() + { + try + { + var dom = new XmlDocument(); + XmlElement root = dom.CreateElement("FloorPatterns"); + dom.AppendChild(root); + foreach (FloorPattern pattern in _user) + { + XmlElement node = dom.CreateElement("Pattern"); + node.SetAttribute("name", pattern.Name); + node.SetAttribute("nw", Text(pattern.NorthWest)); + node.SetAttribute("ne", Text(pattern.NorthEast)); + node.SetAttribute("sw", Text(pattern.SouthWest)); + node.SetAttribute("se", Text(pattern.SouthEast)); + node.SetAttribute("north", Text(pattern.North)); + node.SetAttribute("south", Text(pattern.South)); + node.SetAttribute("west", Text(pattern.West)); + node.SetAttribute("east", Text(pattern.East)); + node.SetAttribute("fillWidth", pattern.FillWidth.ToString(CultureInfo.InvariantCulture)); + node.SetAttribute("fill", Text(pattern.Fill)); + root.AppendChild(node); + } + + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); + dom.Save(FilePath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + MessageBox.Show("The floor patterns could not be saved: " + ex.Message, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + private static string Text(ushort id) => "0x" + id.ToString("X4", CultureInfo.InvariantCulture); + + private static string Text(IEnumerable ids) => string.Join(",", ids.Select(Text)); + + private static ushort One(XmlElement node, string attribute) => Many(node, attribute).FirstOrDefault(); + + private static List Many(XmlElement node, string attribute) + { + var result = new List(); + foreach (string part in node.GetAttribute(attribute).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + bool hex = part.StartsWith("0x", StringComparison.OrdinalIgnoreCase); + if (ushort.TryParse(hex ? part.AsSpan(2) : part.AsSpan(), hex ? NumberStyles.HexNumber : NumberStyles.Integer, + CultureInfo.InvariantCulture, out ushort id)) + { + result.Add(id); + } + } + + return result; + } + } + + /// + /// Lays the session's floor pattern over a dragged rectangle on the work plane (or on top of + /// what the mouse points at). Flat tiles already at that Z in those cells are replaced. + /// + internal sealed class FloorPatternTool : EditorTool + { + private readonly EditorSession _session; + private bool _dragging; + private int _z; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + + public FloorPatternTool(EditorSession session) : base(session) + { + _session = session; + } + + public override bool IsDragging => _dragging; + + public override bool TracksCursorCell => true; + + public override void OnMouseDown(MouseEventArgs e) + { + if (_session.FloorPattern == null) + { + return; + } + + BaseCell(out _startX, out _startY, out _z); + _endX = _startX; + _endY = _startY; + _dragging = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (_dragging) + { + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + var (remove, add) = Plan(_startX, _startY, _endX, _endY, _z); + if (remove.Count > 0 || add.Count > 0) + { + Context.CompList.ReplaceTiles(remove, add, "Floor pattern"); + Context.AfterEdit(_z); + } + } + + public override void Cancel() + { + _dragging = false; + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (_session.FloorPattern == null) + { + return; + } + + int sx, sy, ex, ey, z; + if (_dragging) + { + (sx, sy, ex, ey, z) = (_startX, _startY, _endX, _endY, _z); + } + else + { + BaseCell(out sx, out sy, out z); + (ex, ey) = (sx, sy); + } + + var (remove, add) = Plan(sx, sy, ex, ey, z); + foreach (MultiTile tile in remove) + { + overlay.Highlight(tile, TileHighlight.Remove); + } + + foreach ((ushort id, int x, int y, int tz) in add) + { + overlay.Ghost(id, x, y, tz); + } + } + + private void BaseCell(out int x, out int y, out int z) + { + Context.CellAt(Context.MouseLoc, out x, out y, out z); + if (Context.WorkZ is { } baseZ) + { + z = baseZ; + Context.PlaneCell(Context.MouseLoc, z, out x, out y); + } + } + + private (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan(int startX, int startY, int endX, int endY, int z) + { + var remove = new List(); + var add = new List<(ushort, int, int, int)>(); + MultiEditorComponentList list = Context.CompList; + int x0 = Math.Min(startX, endX), x1 = Math.Max(startX, endX); + int y0 = Math.Min(startY, endY), y1 = Math.Max(startY, endY); + + foreach ((ushort id, int x, int y) in _session.FloorPattern.Layout(x0, y0, x1, y1)) + { + if (!list.InBounds(x, y)) + { + continue; + } + + bool there = false; + foreach (MultiTile tile in list.GetTilesAt(x, y)) + { + if (tile.Z != z || tile.Height != 0) + { + continue; + } + + if (tile.Id == id) + { + there = true; + } + else + { + remove.Add(tile); + } + } + + if (!there) + { + add.Add((id, x, y, z)); + } + } + + return (remove, add); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/LassoTool.cs b/UoFiddler.Plugin.MultiEditor/Editing/LassoTool.cs new file mode 100644 index 00000000..d1078b9e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/LassoTool.cs @@ -0,0 +1,123 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + /// + /// Selects the tiles whose cell centre lies inside a freehand outline. Ctrl adds to the selection. + /// + internal sealed class LassoTool : EditorTool + { + private readonly List _points = new List(); + private bool _drawing; + + public LassoTool(IEditorContext context) : base(context) + { + } + + public override bool IsDragging => _drawing; + + public override void OnMouseDown(MouseEventArgs e) + { + _points.Clear(); + _points.Add(Context.MouseLoc); + _drawing = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (!_drawing) + { + return; + } + + Point last = _points[^1]; + Point now = Context.MouseLoc; + if (Math.Abs(now.X - last.X) + Math.Abs(now.Y - last.Y) >= 3) + { + _points.Add(now); + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_drawing) + { + return; + } + + _drawing = false; + if (_points.Count < 3) + { + // A click, not an outline: select the tile under it like the Select tool. + Context.SetSelection(Context.HoverTile != null ? new[] { Context.HoverTile } : Array.Empty(), CtrlHeld); + return; + } + + int left = int.MaxValue, top = int.MaxValue, right = int.MinValue, bottom = int.MinValue; + foreach (Point point in _points) + { + left = Math.Min(left, point.X); + top = Math.Min(top, point.Y); + right = Math.Max(right, point.X); + bottom = Math.Max(bottom, point.Y); + } + + var inside = new List(); + foreach (MultiTile tile in Context.TilesInRect(Rectangle.FromLTRB(left, top, right + 1, bottom + 1))) + { + PointF anchor = ((EditorSession)Context).TileAnchor(tile); + if (Contains(anchor.X, anchor.Y)) + { + inside.Add(tile); + } + } + + Context.SetSelection(inside, CtrlHeld); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (_drawing && _points.Count > 1) + { + overlay.Polyline(_points, closed: true); + } + } + + public override void Cancel() + { + _drawing = false; + _points.Clear(); + } + + /// Even-odd test of a point against the outline. + private bool Contains(float x, float y) + { + bool inside = false; + for (int i = 0, j = _points.Count - 1; i < _points.Count; j = i++) + { + Point a = _points[i]; + Point b = _points[j]; + if ((a.Y > y) != (b.Y > y) && x < ((b.X - a.X) * (y - a.Y) / (float)(b.Y - a.Y)) + a.X) + { + inside = !inside; + } + } + + return inside; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.Designer.cs b/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.Designer.cs deleted file mode 100644 index 9ee89d6d..00000000 --- a/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.Designer.cs +++ /dev/null @@ -1,99 +0,0 @@ -namespace UoFiddler.Plugin.MultiEditor.Forms -{ - partial class ShortcutsHelpForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// 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)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - _listView = new System.Windows.Forms.ListView(); - _columnKey = new System.Windows.Forms.ColumnHeader(); - _columnAction = new System.Windows.Forms.ColumnHeader(); - _btnClose = new System.Windows.Forms.Button(); - SuspendLayout(); - // - // _listView - // - _listView.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - _listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { _columnKey, _columnAction }); - _listView.FullRowSelect = true; - _listView.GridLines = true; - _listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; - _listView.Location = new System.Drawing.Point(8, 8); - _listView.MultiSelect = false; - _listView.Name = "_listView"; - _listView.Size = new System.Drawing.Size(388, 409); - _listView.TabIndex = 0; - _listView.UseCompatibleStateImageBehavior = false; - _listView.View = System.Windows.Forms.View.Details; - // - // _columnKey - // - _columnKey.Text = "Shortcut"; - _columnKey.Width = 130; - // - // _columnAction - // - _columnAction.Text = "Action"; - _columnAction.Width = 230; - // - // _btnClose - // - _btnClose.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - _btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; - _btnClose.Location = new System.Drawing.Point(321, 425); - _btnClose.Name = "_btnClose"; - _btnClose.Size = new System.Drawing.Size(75, 27); - _btnClose.TabIndex = 1; - _btnClose.Text = "Close"; - _btnClose.UseVisualStyleBackColor = true; - // - // ShortcutsHelpForm - // - AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - CancelButton = _btnClose; - ClientSize = new System.Drawing.Size(404, 461); - Controls.Add(_listView); - Controls.Add(_btnClose); - FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - MaximizeBox = false; - MinimizeBox = false; - Name = "ShortcutsHelpForm"; - Padding = new System.Windows.Forms.Padding(8); - ShowInTaskbar = false; - StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - Text = "Keyboard Shortcuts"; - ResumeLayout(false); - } - - #endregion - - private System.Windows.Forms.ListView _listView; - private System.Windows.Forms.ColumnHeader _columnKey; - private System.Windows.Forms.ColumnHeader _columnAction; - private System.Windows.Forms.Button _btnClose; - } -} \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.cs b/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.cs deleted file mode 100644 index 91277ccb..00000000 --- a/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.cs +++ /dev/null @@ -1,77 +0,0 @@ -/*************************************************************************** - * - * $Author: MuadDib & Turley - * - * "THE BEER-WARE LICENSE" - * As long as you retain this notice you can do whatever you want with - * this stuff. If we meet some day, and you think this stuff is worth it, - * you can buy me a beer in return. - * - ***************************************************************************/ - -using System.Drawing; -using System.Windows.Forms; -using UoFiddler.Controls.Classes; - -namespace UoFiddler.Plugin.MultiEditor.Forms -{ - public partial class ShortcutsHelpForm : Form - { - public ShortcutsHelpForm() - { - InitializeComponent(); - PopulateShortcuts(); - } - - private void PopulateShortcuts() - { - AddHeader("Tool Switches"); - Add("S", "Select Tool"); - Add("D", "Draw Tool"); - Add("R", "Remove Tool"); - Add("E", "Apply Z Level Tool"); - Add("F", "Toggle Virtual Floor"); - Add("P", "Pipette (Pick Tile)"); - Add("T", "Switch Transparent"); - Add("B", "Rectangle Fill Tool"); - Add("L", "Line Draw Tool"); - - AddHeader("Editing"); - Add("Ctrl+Z", "Undo"); - Add("Ctrl+Y / Ctrl+Shift+Z", "Redo"); - Add("Ctrl+C", "Copy Selection"); - Add("Ctrl+V", "Paste"); - Add("Escape", "Cancel Paste"); - Add("[", "Z Level -1"); - Add("]", "Z Level +1"); - - AddHeader("Navigation"); - Add("Arrow Keys", "Pan View"); - Add("Page Up", "Floor Z +5"); - Add("Page Down", "Floor Z -5"); - - AddHeader("Zoom"); - Add("+ / Shift+=", "Zoom In"); - Add("-", "Zoom Out"); - Add("Ctrl+0", "Reset Zoom to 100%"); - } - - private void AddHeader(string text) - { - var item = new ListViewItem(text) - { - Font = new Font(_listView.Font, FontStyle.Bold), - ForeColor = Options.DarkMode ? Color.OrangeRed : Color.MediumBlue, - }; - item.SubItems.Add(string.Empty); - _listView.Items.Add(item); - } - - private void Add(string key, string action) - { - var item = new ListViewItem(key); - item.SubItems.Add(action); - _listView.Items.Add(item); - } - } -} \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs b/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs index 954b8e9d..29ab8045 100644 --- a/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs +++ b/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs @@ -1,9 +1,7 @@ -/*************************************************************************** +/*************************************************************************** * - * $Author: MuadDib & Turley - * * "THE BEER-WARE LICENSE" - * As long as you retain this notice you can do whatever you want with + * As long as you retain this notice you can do whatever you want with * this stuff. If we meet some day, and you think this stuff is worth it, * you can buy me a beer in return. * @@ -14,93 +12,98 @@ using Ultima; using UoFiddler.Controls.Plugin; using UoFiddler.Controls.Plugin.Interfaces; +using UoFiddler.Plugin.MultiEditor.UI; namespace UoFiddler.Plugin.MultiEditor { public class MultiEditorPluginBase : PluginBase { - private UserControls.MultiEditorControl _multiEditorControl; + private MultiEditorControl _editor; - /// - /// Author of the plugin - /// public override string Author { get; } = "MuadDib & Turley"; - /// - /// Description of the Plugin's purpose - /// public override string Description { get; } = "Plugin to Edit Multis\r\n(Adds 1 new Tab)"; - /// - /// Host of the plugin. - /// - public override IPluginHost Host { get; set; } = null; + public override IPluginHost Host { get; set; } - /// - /// Name of the plugin - /// public override string Name { get; } = "MultiEditorPlugin"; - /// - /// Version of the plugin - /// - public override string Version { get; } = "1.7.0"; + public override string Version { get; } = "3.0.0"; - public override void Unload() + public override void Initialize() { - // fired in Fiddler OnClosing - PluginEvents.ModifyItemsControlContextMenuEvent -= EventsModifyItemsControlContextMenuEvent; + // The Manage Plugins form also constructs disabled plugins, so events are + // subscribed here and not in the constructor. + PluginEvents.ModifyItemsControlContextMenuEvent += OnItemsContextMenu; + PluginEvents.ModifyMapControlContextMenuEvent += OnMapContextMenu; } - public override void Initialize() + public override void Unload() { - // fired on fiddler startup; the Manage Plugins form also constructs disabled plugins, - // so events are subscribed here and not in the constructor - _ = Files.RootDir; - PluginEvents.ModifyItemsControlContextMenuEvent += EventsModifyItemsControlContextMenuEvent; + PluginEvents.ModifyItemsControlContextMenuEvent -= OnItemsContextMenu; + PluginEvents.ModifyMapControlContextMenuEvent -= OnMapContextMenu; } public override void ModifyPluginToolStrip(ToolStripDropDownButton toolStrip) { - // want an entry inside the plugin dropdown? } - // the magic add a new tab page at the end public override void ModifyTabPages(TabControl tabControl) { - TabPage page = new TabPage + var page = new TabPage { - Tag = tabControl.TabCount + 1, // at end used for undock/dock feature to define the order + Tag = tabControl.TabCount + 1, // dock/undock order Text = "Multi Editor" }; - _multiEditorControl = new UserControls.MultiEditorControl + _editor = new MultiEditorControl { Dock = DockStyle.Fill }; + page.Controls.Add(_editor); + tabControl.TabPages.Add(page); + + // Once, the first time the application has nothing to do. + EventHandler warmUp = null; + warmUp = (_, _) => { - Dock = DockStyle.Fill + Application.Idle -= warmUp; + MultiEditorControl.WarmUpOpenGl(); }; - page.Controls.Add(_multiEditorControl); - tabControl.TabPages.Add(page); + Application.Idle += warmUp; } - private void EventsModifyItemsControlContextMenuEvent(ContextMenuStrip strip) + private void OnItemsContextMenu(ContextMenuStrip strip) { - ToolStripMenuItem item = new ToolStripMenuItem + var item = new ToolStripMenuItem { Text = "MultiEditor: Draw with this item" }; + item.Click += (_, _) => { - Text = "MultiEditor: Select Item" + int selected = Host.GetSelectedIdFromItemsControl(); + if (selected > -1) + { + _editor?.SelectDrawTile((ushort)selected); + } }; - item.Click += ItemShowContextClicked; strip.Items.Add(item); } - private void ItemShowContextClicked(object sender, EventArgs e) + private void OnMapContextMenu(ContextMenuStrip strip, Func<(Map Map, System.Drawing.Point Location)> clickedAt) { - int currSelected = Host.GetSelectedIdFromItemsControl(); - if (currSelected <= -1) + var item = new ToolStripMenuItem { Text = "MultiEditor: Extract area here..." }; + item.Click += (_, _) => { - return; - } + if (_editor == null) + { + return; + } + + // Show the editor first, so it is built before the extract. + if (_editor.Parent is TabPage page && page.Parent is TabControl tabs) + { + tabs.SelectedTab = page; + } - _multiEditorControl?.SelectDrawTile((ushort)currSelected); + (Map map, System.Drawing.Point location) = clickedAt(); + _editor.ExtractFromMap(map, location); + }; + strip.Items.Add(item); } } } diff --git a/UoFiddler.Plugin.MultiEditor/MultiRotationTable.xml b/UoFiddler.Plugin.MultiEditor/MultiRotationTable.xml new file mode 100644 index 00000000..6bd41562 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/MultiRotationTable.xml @@ -0,0 +1,3927 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/UoFiddler.Plugin.MultiEditor/Properties/Resources.Designer.cs b/UoFiddler.Plugin.MultiEditor/Properties/Resources.Designer.cs deleted file mode 100644 index f9785810..00000000 --- a/UoFiddler.Plugin.MultiEditor/Properties/Resources.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace UoFiddler.Plugin.MultiEditor.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UoFiddler.Plugin.MultiEditor.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtAtlas.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtAtlas.cs new file mode 100644 index 00000000..636b15c0 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtAtlas.cs @@ -0,0 +1,199 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using OpenTK.Graphics.OpenGL4; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// Where a sprite sits in the atlas, in pixels. + internal readonly record struct AtlasSprite(int Layer, int X, int Y, int Width, int Height); + + /// + /// Static art packed into one texture array, filled as tiles are first drawn. One texture + /// means the whole multi draws in one call and keeps its draw order. + /// + internal sealed class ArtAtlas : IDisposable + { + public const int Size = 2048; + + /// A solid white block, for filled shapes. + public const int WhiteKey = -1; + + /// The work plane diamond. + public const int FloorKey = -2; + + private const int Padding = 2; + + /// Keys from here down are land tiles; see . + private const int _landBase = -1000; + + /// The atlas key of a land tile's art (ground under a previewed multi). + public static int LandKey(int landId) => _landBase - landId; + + private readonly Dictionary _sprites = new Dictionary(); + private readonly HashSet _missing = new HashSet(); + + private int _texture; + private int _layers; + private int _layer; + private int _shelfX; + private int _shelfY; + private int _shelfHeight; + + public ArtAtlas() + { + Allocate(2); + } + + public int Texture => _texture; + + /// The sprite for a static id or one of the special keys. Needs the GL context. + public bool TryGet(int key, out AtlasSprite sprite) + { + if (_sprites.TryGetValue(key, out sprite)) + { + return true; + } + + if (_missing.Contains(key)) + { + return false; + } + + byte[] pixels = Load(key, out int width, out int height); + if (pixels == null || width > Size - Padding || height > Size - Padding) + { + _missing.Add(key); + return false; + } + + sprite = Place(width, height); + Upload(sprite, pixels); + _sprites[key] = sprite; + return true; + } + + /// Forgets every sprite, after art changed on disk or in memory. + public void Clear() + { + _sprites.Clear(); + _missing.Clear(); + _layer = 0; + _shelfX = 0; + _shelfY = 0; + _shelfHeight = 0; + + // A fresh texture: old pixels next to new sprites would bleed in when zoomed out. + GL.DeleteTexture(_texture); + Allocate(_layers); + } + + public void Dispose() + { + GL.DeleteTexture(_texture); + _texture = 0; + } + + private static byte[] Load(int key, out int width, out int height) + { + switch (key) + { + case WhiteKey: + width = height = 4; + byte[] white = new byte[4 * 4 * 4]; + Array.Fill(white, (byte)255); + return white; + case FloorKey: + width = height = ArtPixels.FloorSize; + return ArtPixels.FloorDiamond(); + default: + return key <= _landBase + ? ArtPixels.LoadLand(_landBase - key, out width, out height) + : ArtPixels.LoadStatic((ushort)key, out width, out height); + } + } + + private AtlasSprite Place(int width, int height) + { + if (_shelfX + width + Padding > Size) + { + _shelfY += _shelfHeight; + _shelfX = 0; + _shelfHeight = 0; + } + + if (_shelfY + height + Padding > Size) + { + ++_layer; + _shelfX = 0; + _shelfY = 0; + _shelfHeight = 0; + } + + if (_layer >= _layers) + { + Grow(); + } + + var sprite = new AtlasSprite(_layer, _shelfX, _shelfY, width, height); + _shelfX += width + Padding; + _shelfHeight = Math.Max(_shelfHeight, height + Padding); + return sprite; + } + + /// + /// A texture array cannot grow, so a larger one is made and every sprite is uploaded again + /// at the place it already had. + /// + private void Grow() + { + GL.DeleteTexture(_texture); + Allocate(_layers * 2); + foreach (KeyValuePair entry in _sprites) + { + byte[] pixels = Load(entry.Key, out int width, out int height); + if (pixels != null && width == entry.Value.Width && height == entry.Value.Height) + { + Upload(entry.Value, pixels); + } + } + } + + private void Allocate(int layers) + { + _layers = layers; + _texture = GL.GenTexture(); + GL.BindTexture(TextureTarget.Texture2DArray, _texture); + GL.TexImage3D(TextureTarget.Texture2DArray, 0, PixelInternalFormat.Rgba8, Size, Size, layers, 0, + PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); + GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); + GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); + GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); + + // Unused space must be transparent: sprites are sampled next to it when zoomed out. + byte[] clear = new byte[Size * Size * 4]; + for (int layer = 0; layer < layers; layer++) + { + GL.TexSubImage3D(TextureTarget.Texture2DArray, 0, 0, 0, layer, Size, Size, 1, PixelFormat.Rgba, + PixelType.UnsignedByte, clear); + } + } + + private void Upload(AtlasSprite sprite, byte[] pixels) + { + GL.BindTexture(TextureTarget.Texture2DArray, _texture); + GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); + GL.TexSubImage3D(TextureTarget.Texture2DArray, 0, sprite.X, sprite.Y, sprite.Layer, sprite.Width, + sprite.Height, 1, PixelFormat.Rgba, PixelType.UnsignedByte, pixels); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs new file mode 100644 index 00000000..147270c6 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs @@ -0,0 +1,152 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using Ultima; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// + /// Static art as RGBA8 pixels, read from the art cache so replaced art shows. + /// + internal static class ArtPixels + { + public const int FloorSize = 44; + + /// Top-down RGBA8 pixels of a static, or null when it has no art. + public static byte[] LoadStatic(ushort id, out int width, out int height) + { + return ToRgba(id != 0xFFFF ? Art.GetStatic(id) : null, out width, out height); + } + + /// Top-down RGBA8 pixels of a land tile (a 44x44 diamond), or null when it has no art. + public static byte[] LoadLand(int id, out int width, out int height) + { + return ToRgba(Art.GetLand(id), out width, out height); + } + + private static unsafe byte[] ToRgba(Bitmap bitmap, out int width, out int height) + { + width = 0; + height = 0; + if (bitmap == null) + { + return null; + } + + width = bitmap.Width; + height = bitmap.Height; + byte[] rgba = new byte[width * height * 4]; + BitmapData data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, + PixelFormat.Format16bppArgb1555); + try + { + int i = 0; + for (int y = 0; y < height; y++) + { + ushort* row = (ushort*)((byte*)data.Scan0 + (y * data.Stride)); + for (int x = 0; x < width; x++) + { + ushort c = row[x]; + rgba[i++] = Expand5((c >> 10) & 0x1F); + rgba[i++] = Expand5((c >> 5) & 0x1F); + rgba[i++] = Expand5(c & 0x1F); + rgba[i++] = (c & 0x8000) != 0 ? (byte)255 : (byte)0; + } + } + } + finally + { + bitmap.UnlockBits(data); + } + + return rgba; + } + + /// A work plane cell: a translucent diamond with a stronger edge, coloured by its tint. + public static byte[] FloorDiamond() + { + const int half = FloorSize / 2; + byte[] rgba = new byte[FloorSize * FloorSize * 4]; + for (int y = 0; y < FloorSize; y++) + { + for (int x = 0; x < FloorSize; x++) + { + // Distance from the centre in diamond steps, measured at pixel centres. + float d = System.Math.Abs(x + 0.5f - half) + System.Math.Abs(y + 0.5f - half); + if (d > half) + { + continue; + } + + int i = ((y * FloorSize) + x) * 4; + bool edge = d > half - 1; + // Neutral, so a tint gives it any colour: a brighter, more solid edge around the fill. + byte value = edge ? (byte)255 : (byte)200; + rgba[i] = value; + rgba[i + 1] = value; + rgba[i + 2] = value; + rgba[i + 3] = edge ? (byte)255 : (byte)160; + } + } + + return rgba; + } + + private static byte Expand5(int value) + { + return (byte)((value << 3) | (value >> 2)); + } + } + + /// + /// Which pixels of a static are drawn, for picking the tile under the cursor. + /// + internal sealed class ArtMasks + { + private sealed class Mask + { + public int Width; + public int Height; + public bool[] Opaque; + } + + private readonly Dictionary _masks = new Dictionary(); + + /// True when the art has a drawn pixel at the given offset from its top left. + public bool Hit(ushort id, int x, int y) + { + if (x < 0 || y < 0) + { + return false; + } + + if (!_masks.TryGetValue(id, out Mask mask)) + { + byte[] rgba = ArtPixels.LoadStatic(id, out int width, out int height); + mask = new Mask { Width = width, Height = height, Opaque = new bool[width * height] }; + for (int i = 0; rgba != null && i < mask.Opaque.Length; i++) + { + mask.Opaque[i] = rgba[(i * 4) + 3] != 0; + } + + _masks[id] = mask; + } + + return x < mask.Width && y < mask.Height && mask.Opaque[(y * mask.Width) + x]; + } + + public void Clear() + { + _masks.Clear(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/Camera2D.cs b/UoFiddler.Plugin.MultiEditor/Rendering/Camera2D.cs new file mode 100644 index 00000000..2ade1cdc --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/Camera2D.cs @@ -0,0 +1,124 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// + /// Pan and zoom of the canvas. World space is the tile pixel space of the multi + /// (MultiTile.XMod/YMod); screen = (world - origin) * zoom. + /// + internal sealed class Camera2D + { + public const float MinZoom = 0.25f; + public const float MaxZoom = 8f; + + /// World position shown at the top left of the canvas. + public float OriginX { get; private set; } + + public float OriginY { get; private set; } + + public float Zoom { get; private set; } = 1f; + + /// + /// True while the view is the one chose: a new camera, or one not panned or + /// zoomed since. The canvas fits such a view again when its size changes. + /// + public bool ShowsFit { get; private set; } = true; + + public PointF ScreenToWorld(Point screen) + { + return new PointF(OriginX + (screen.X / Zoom), OriginY + (screen.Y / Zoom)); + } + + public PointF WorldToScreen(float x, float y) + { + return new PointF((x - OriginX) * Zoom, (y - OriginY) * Zoom); + } + + public RectangleF VisibleWorld(Size view) + { + return new RectangleF(OriginX, OriginY, view.Width / Zoom, view.Height / Zoom); + } + + public void Pan(int screenDx, int screenDy) + { + ShowsFit = false; + OriginX -= screenDx / Zoom; + OriginY -= screenDy / Zoom; + } + + /// Sets the zoom, keeping the world point under in place. + public void ZoomAt(Point anchor, float zoom) + { + ShowsFit = false; + zoom = Math.Clamp(zoom, MinZoom, MaxZoom); + PointF world = ScreenToWorld(anchor); + Zoom = zoom; + OriginX = world.X - (anchor.X / Zoom); + OriginY = world.Y - (anchor.Y / Zoom); + } + + /// + /// One wheel notch: whole steps above 100% so pixel art stays crisp, finer steps below. + /// + public void ZoomStep(Point anchor, int direction) + { + float zoom = Zoom; + if (direction > 0) + { + zoom = zoom < 1f ? Math.Min(1f, zoom + 0.25f) : (float)Math.Floor(zoom) + 1f; + } + else + { + zoom = zoom > 1f ? (float)Math.Ceiling(zoom) - 1f : zoom - 0.25f; + } + + ZoomAt(anchor, zoom); + } + + /// Puts the middle of a world rectangle in the middle of the view, keeping the zoom. + public void CenterOn(RectangleF world, Size view) + { + OriginX = world.X + (world.Width / 2f) - (view.Width / 2f / Zoom); + OriginY = world.Y + (world.Height / 2f) - (view.Height / 2f / Zoom); + } + + /// + /// Shows a world rectangle centred at the largest zoom step that fits: whole steps up to + /// , quarter steps below 100%. + /// + public void Fit(RectangleF world, Size view, float maxZoom = 2f, int margin = 24) + { + // Asked for even when the view has no size yet: the canvas fits again once it has one. + ShowsFit = true; + if (world.Width <= 0 || world.Height <= 0 || view.Width <= 0 || view.Height <= 0) + { + return; + } + + float fit = Math.Min((view.Width - (2f * margin)) / world.Width, (view.Height - (2f * margin)) / world.Height); + float zoom = (float)Math.Floor(Math.Min(fit, maxZoom)); + if (zoom < 1f) + { + zoom = 1f; + while (zoom > MinZoom && zoom > fit) + { + zoom -= 0.25f; + } + } + + Zoom = Math.Max(MinZoom, zoom); + OriginX = world.X + (world.Width / 2f) - (view.Width / 2f / Zoom); + OriginY = world.Y + (world.Height / 2f) - (view.Height / 2f / Zoom); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/FrameStats.cs b/UoFiddler.Plugin.MultiEditor/Rendering/FrameStats.cs new file mode 100644 index 00000000..83f26d22 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/FrameStats.cs @@ -0,0 +1,153 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// + /// Timings of the canvas for the performance box, summed per second: the box shows the last + /// whole second. Recording is a few additions, so it costs nothing worth measuring. + /// + internal sealed class FrameStats + { + private sealed class Measure + { + public int Count; + public double Sum; + public double Max; + + public void Add(double value) + { + Count++; + Sum += value; + Max = Math.Max(Max, value); + } + + public string Text => Count == 0 ? "-" : $"{Sum / Count,6:F2} ms avg {Max,6:F2} max"; + } + + private sealed class Second + { + public double Seconds = 1; + public int Sprites; + public readonly Measure Draw = new Measure(); + public readonly Measure Gpu = new Measure(); + public readonly Measure Swap = new Measure(); + public readonly Measure Frame = new Measure(); + public readonly Measure Move = new Measure(); + public readonly Measure Hit = new Measure(); + public readonly Measure Lag = new Measure(); + } + + /// One second of the history chart: averages in ms, and frames per second. + public readonly record struct Point(double Fps, double Frame, double Gpu, double Draw, double Lag); + + /// Seconds of history kept for the chart. + public const int HistorySeconds = 90; + + private readonly List _history = new List(HistorySeconds + 1); + private Second _current = new Second(); + private Second _last = new Second(); + private long _start = Stopwatch.GetTimestamp(); + + /// The last seconds, oldest first. + public IReadOnlyList History + { + get + { + Roll(); + return _history; + } + } + + public static double Ms(long from, long to) => (to - from) * 1000.0 / Stopwatch.Frequency; + + /// Building and submitting the scene (CPU). + /// SwapBuffers: waiting for the GPU and vertical sync. + /// The whole paint. + public void Frame(double draw, double swap, double frame, int sprites) + { + Roll(); + _current.Draw.Add(draw); + _current.Swap.Add(swap); + _current.Frame.Add(frame); + _current.Sprites = sprites; + } + + /// GPU time of a frame, from a timer query (it arrives a frame or two late). + public void Gpu(double ms) + { + Roll(); + _current.Gpu.Add(ms); + } + + /// The whole mouse move: hit test, tool, status bar. + /// Finding the tile under the cursor. + public void Move(double handler, double hitTest) + { + Roll(); + _current.Move.Add(handler); + _current.Hit.Add(hitTest); + } + + /// From the first mouse move not yet shown to the end of the frame that shows it. + public void Lag(double ms) + { + Roll(); + _current.Lag.Add(ms); + } + + public string Describe(int tiles) + { + Roll(); + Second s = _last; + int frames = s.Frame.Count; + var text = new StringBuilder(); + text.AppendLine($"Frames {frames / s.Seconds,5:F0}/s"); + text.AppendLine($"Draw {s.Draw.Text} CPU, scene"); + text.AppendLine($"GPU {s.Gpu.Text}"); + text.AppendLine($"Swap {s.Swap.Text} GPU + vsync wait"); + text.AppendLine($"Frame {s.Frame.Text}"); + text.AppendLine($"Mouse {s.Move.Count / s.Seconds,5:F0}/s"); + text.AppendLine($"Handler {s.Move.Text}"); + text.AppendLine($"HitTest {s.Hit.Text}"); + text.AppendLine($"Lag {s.Lag.Text} move to shown"); + text.Append($"Scene {s.Sprites:N0} sprites, {tiles:N0} tiles"); + return text.ToString(); + } + + private void Roll() + { + long now = Stopwatch.GetTimestamp(); + double seconds = Ms(_start, now) / 1000.0; + if (seconds < 1) + { + return; + } + + _current.Seconds = seconds; + _last = _current; + _current = new Second(); + _start = now; + + // An idle stretch (nothing recorded for a while) counts as one quiet second. + _history.Add(new Point(_last.Frame.Count / seconds, Avg(_last.Frame), Avg(_last.Gpu), Avg(_last.Draw), Avg(_last.Lag))); + if (_history.Count > HistorySeconds) + { + _history.RemoveAt(0); + } + } + + private static double Avg(Measure m) => m.Count == 0 ? 0 : m.Sum / m.Count; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs b/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs new file mode 100644 index 00000000..b6c2742b --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs @@ -0,0 +1,616 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Windows.Forms; +using OpenTK.GLControl; +using OpenTK.Graphics.OpenGL4; +using OpenTK.Windowing.Common; +using UoFiddler.Plugin.MultiEditor.Editing; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// + /// The editor canvas: an OpenGL 3.3 core surface that draws the session it is given, on + /// demand. It owns the camera gestures (pan, zoom) and passes the rest of the mouse to the + /// session in world coordinates. + /// + internal sealed class GlCanvas : GLControl + { + private bool _ready; + private bool _failed; + private SceneRenderer _renderer; + private EditorSession _session; + + private bool _panning; + private bool _panned; + private Point _panStart; + private Point _panLast; + private bool _spaceHeld; + private Timer _animationTimer; + private Timer _modifierTimer; + private Keys _lastModifiers; + + /// Raised once when the context cannot be used; the text is for the user. + public event Action ContextFailed; + + /// Raised on a right click that was not a pan, with the canvas position. + public event Action ContextRequested; + + /// Raised after pan or zoom changed. + public event Action CameraChanged; + + public GlCanvas() + : base(new GLControlSettings + { + API = ContextAPI.OpenGL, + APIVersion = new Version(3, 3), + Profile = ContextProfile.Core, + Flags = ContextFlags.ForwardCompatible + }) + { + } + + public Camera2D Camera { get; private set; } = new Camera2D(); + + /// The session shown. Each session keeps its own camera, passed in with it. + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public EditorSession Session => _session; + + public void Show(EditorSession session, Camera2D camera) + { + if (_session != null) + { + _session.Invalidated -= Invalidate; + } + + _session = session; + Camera = camera ?? new Camera2D(); + if (_session != null) + { + _session.Invalidated += Invalidate; + } + + // A design nobody has panned or zoomed yet is shown whole, for the canvas as it is now. + if (Camera.ShowsFit) + { + FitToView(); + } + + Invalidate(); + } + + protected override void OnInvalidated(InvalidateEventArgs e) + { + base.OnInvalidated(e); + + // A mouse move that asks for a frame starts the lag clock; moves that change nothing do not. + if (_inMouseMove && _unshownMove == 0) + { + _unshownMove = _moveStart; + } + } + + // ---------------------------------------------------------------- performance box + + /// Timings for the performance box. Only collected while is on. + public FrameStats Stats { get; } = new FrameStats(); + + /// Times frames, mouse moves and (with timer queries) the GPU. + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool CollectStats { get; set; } + + private long _moveStart; + private bool _inMouseMove; + + /// The first mouse move that asked for a frame not drawn yet; 0 when there is none. + private long _unshownMove; + + // GPU timer queries, read a frame or two later so the CPU never waits for them. + private const int GpuQueryCount = 4; + private readonly int[] _gpuQueries = new int[GpuQueryCount]; + private readonly bool[] _gpuPending = new bool[GpuQueryCount]; + private int _gpuNext; + + /// Collects finished GPU timings and starts a new query; -1 when all are still in flight. + private int BeginGpuQuery() + { + if (_gpuQueries[0] == 0) + { + GL.GenQueries(GpuQueryCount, _gpuQueries); + } + + for (int i = 0; i < GpuQueryCount; i++) + { + if (!_gpuPending[i]) + { + continue; + } + + GL.GetQueryObject(_gpuQueries[i], GetQueryObjectParam.QueryResultAvailable, out int available); + if (available != 0) + { + GL.GetQueryObject(_gpuQueries[i], GetQueryObjectParam.QueryResult, out long nanoseconds); + Stats.Gpu(nanoseconds / 1_000_000.0); + _gpuPending[i] = false; + } + } + + int next = _gpuNext; + if (_gpuPending[next]) + { + return -1; + } + + GL.BeginQuery(QueryTarget.TimeElapsed, _gpuQueries[next]); + _gpuPending[next] = true; + _gpuNext = (next + 1) % GpuQueryCount; + return next; + } + + /// Art changed: forget the uploaded sprites. + public void ResetArt() + { + if (_ready) + { + MakeCurrent(); + _renderer.Atlas.Clear(); + } + + Invalidate(); + } + + /// Centres the multi in the canvas. + public void FitToView() + { + if (_session == null || !_session.HasDocument) + { + return; + } + + Camera.Fit(SceneBounds(), ClientSize, _session.PlanMode ? 4f : 2f); + OnCameraChanged(); + } + + /// Centres the multi in the canvas at the current zoom. + public void CenterView() + { + if (_session == null || !_session.HasDocument) + { + return; + } + + Camera.CenterOn(SceneBounds(), ClientSize); + OnCameraChanged(); + } + + public void SetZoom(float zoom) + { + Camera.ZoomAt(new Point(ClientSize.Width / 2, ClientSize.Height / 2), zoom); + OnCameraChanged(); + } + + public void ZoomStep(int direction) + { + Camera.ZoomStep(new Point(ClientSize.Width / 2, ClientSize.Height / 2), direction); + OnCameraChanged(); + } + + /// Reads the frame just drawn, top-down BGRA, for screenshots and tests. + public Bitmap CaptureFrame() + { + if (!_ready) + { + return null; + } + + MakeCurrent(); + Size size = ClientSize; + Render(size); + var bitmap = new Bitmap(size.Width, size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + System.Drawing.Imaging.BitmapData data = bitmap.LockBits(new Rectangle(Point.Empty, size), + System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + GL.PixelStore(PixelStoreParameter.PackAlignment, 4); + GL.ReadBuffer(ReadBufferMode.Back); + GL.ReadPixels(0, 0, size.Width, size.Height, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); + bitmap.UnlockBits(data); + bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); + return bitmap; + } + + private RectangleF SceneBounds() + { + var list = _session.CompList; + if (_session.PlanMode) + { + Size plan = MultiEditor.Classes.PlanView.ContentSize(list.Width, list.Height); + return new RectangleF(0, 0, plan.Width, plan.Height); + } + + // The floor diamond of the whole multi at Z 0, grown by the tiles standing on it. + float left = EditorSession.CellCorner(0, list.Height, 0).X; + float right = EditorSession.CellCorner(list.Width, 0, 0).X; + float top = EditorSession.CellCorner(0, 0, 0).Y; + float bottom = EditorSession.CellCorner(list.Width, list.Height, 0).Y; + foreach (var tile in list.RealTiles) + { + if (!MultiEditor.Classes.ArtMetrics.TryGetSize(tile.Id, out int width, out int height)) + { + continue; + } + + left = Math.Min(left, tile.XMod); + top = Math.Min(top, tile.YMod); + right = Math.Max(right, tile.XMod + width); + bottom = Math.Max(bottom, tile.YMod + height); + } + + return RectangleF.FromLTRB(left, top, right, bottom); + } + + // ---------------------------------------------------------------- painting + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + + // Keeps a fitted design centred when the canvas changes size (layout, sidebars, window), + // until it is panned or zoomed by hand. + if (Camera.ShowsFit) + { + FitToView(); + } + + Invalidate(); + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + + Size size = ClientSize; + if (_failed || IsDesignMode || size.Width <= 0 || size.Height <= 0) + { + return; + } + + try + { + long start = Stopwatch.GetTimestamp(); + MakeCurrent(); + if (!_ready) + { + Initialize(); + } + + bool stats = CollectStats; + int query = stats ? BeginGpuQuery() : -1; + long drawStart = Stopwatch.GetTimestamp(); + Render(size); + long drawEnd = Stopwatch.GetTimestamp(); + if (query >= 0) + { + GL.EndQuery(QueryTarget.TimeElapsed); + } + + SwapBuffers(); + long end = Stopwatch.GetTimestamp(); + if (stats) + { + Stats.Frame(FrameStats.Ms(drawStart, drawEnd), FrameStats.Ms(drawEnd, end), + FrameStats.Ms(start, end), _renderer.LastSpriteCount); + if (_unshownMove != 0) + { + Stats.Lag(FrameStats.Ms(_unshownMove, end)); + } + } + + _unshownMove = 0; + } + catch (Exception ex) + { + _failed = true; + ContextFailed?.Invoke($"OpenGL rendering failed:\r\n{ex.Message}"); + } + } + + private void Initialize() + { + int major = GL.GetInteger(GetPName.MajorVersion); + int minor = GL.GetInteger(GetPName.MinorVersion); + if (major < 3 || (major == 3 && minor < 3)) + { + throw new NotSupportedException( + $"OpenGL 3.3 is required, this system offers {major}.{minor} ({GL.GetString(StringName.Renderer)})."); + } + + GL.Disable(EnableCap.DepthTest); + GL.Enable(EnableCap.Blend); + GL.BlendFuncSeparate(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha, + BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha); + + _renderer = new SceneRenderer(); + _ready = true; + } + + private void Render(Size size) + { + GL.Viewport(0, 0, size.Width, size.Height); + Color background = UI.EditorSettings.Current.EffectiveBackground; + GL.ClearColor(background.R / 255f, background.G / 255f, background.B / 255f, 1f); + GL.Clear(ClearBufferMask.ColorBufferBit); + + if (_session != null) + { + _renderer.Draw(_session, Camera, size); + } + + // Animated tiles only move in preview mode; the timer runs just while one is on screen. + bool animate = _session != null && _session.PreviewMode && _renderer.HasAnimation; + if (animate && _animationTimer == null) + { + _animationTimer = new Timer { Interval = 100 }; + _animationTimer.Tick += (_, _) => + { + ++_renderer.AnimationTick; + Invalidate(); + }; + } + + if (_animationTimer != null) + { + _animationTimer.Enabled = animate; + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _animationTimer?.Dispose(); + _modifierTimer?.Dispose(); + } + + if (disposing && _ready) + { + try + { + MakeCurrent(); + _renderer.Dispose(); + if (_gpuQueries[0] != 0) + { + GL.DeleteQueries(GpuQueryCount, _gpuQueries); + } + } + catch (Exception) + { + // The context is already gone when the window is torn down first. + } + + _ready = false; + } + + base.Dispose(disposing); + } + + // ---------------------------------------------------------------- input + + private Point World(Point screen) + { + PointF world = Camera.ScreenToWorld(screen); + return new Point((int)Math.Floor(world.X), (int)Math.Floor(world.Y)); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + + if (e.Button == MouseButtons.Right || e.Button == MouseButtons.Middle || + (e.Button == MouseButtons.Left && _spaceHeld)) + { + _panning = true; + _panned = false; + _panStart = _panLast = e.Location; + Cursor = Cursors.SizeAll; + return; + } + + _session?.PointerDown(World(e.Location), e); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + if (!CollectStats) + { + HandleMouseMove(e); + return; + } + + long start = Stopwatch.GetTimestamp(); + _moveStart = start; + _inMouseMove = true; + try + { + HandleMouseMove(e); + } + finally + { + _inMouseMove = false; + } + + if (!_panning && _session != null) + { + Stats.Move(FrameStats.Ms(start, Stopwatch.GetTimestamp()), _session.LastHitTestMs); + } + } + + private void HandleMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + + if (_panning) + { + if (Math.Abs(e.X - _panStart.X) > 3 || Math.Abs(e.Y - _panStart.Y) > 3) + { + _panned = true; + } + + if (_panned) + { + Camera.Pan(e.X - _panLast.X, e.Y - _panLast.Y); + _panLast = e.Location; + OnCameraChanged(); + } + + return; + } + + _session?.PointerMove(World(e.Location), e); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + + if (_panning) + { + _panning = false; + Cursor = Cursors.Default; + if (_panned) + { + return; + } + + // A click without a drag. Right: stops what the tool is in the middle of, else asks + // for the context menu. Middle: selects the hovered tile (below). + if (e.Button == MouseButtons.Right) + { + if (_session != null && (_session.Pasting || _session.ActiveTool.IsDragging)) + { + _session.CancelTool(); + } + else + { + ContextRequested?.Invoke(e.Location); + } + + return; + } + + if (e.Button == MouseButtons.Left) + { + return; + } + } + + _session?.PointerUp(World(e.Location), e); + } + + protected override void OnMouseEnter(EventArgs e) + { + base.OnMouseEnter(e); + + // Tools change what they would do with Shift or Ctrl held. Pressing a key moves no + // mouse and the canvas may not have the keyboard, so the keys are watched while the + // cursor is over it and the preview is redrawn when they change. + _lastModifiers = ModifierKeys; + if (_modifierTimer == null) + { + _modifierTimer = new Timer { Interval = 60 }; + _modifierTimer.Tick += (_, _) => + { + Keys now = ModifierKeys; + if (now != _lastModifiers) + { + _lastModifiers = now; + Invalidate(); + } + }; + } + + _modifierTimer.Start(); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _modifierTimer?.Stop(); + _session?.PointerLeave(); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); + if (e.Delta == 0) + { + return; + } + + if ((ModifierKeys & Keys.Shift) != 0) + { + // Shift+wheel walks through the floors. + _session?.StepLevel(Math.Sign(e.Delta)); + return; + } + + Camera.ZoomStep(e.Location, Math.Sign(e.Delta)); + OnCameraChanged(); + _session?.PointerMove(World(e.Location), e); + } + + protected override bool IsInputKey(Keys keyData) + { + // Arrow keys nudge the selection instead of moving focus. + switch (keyData & Keys.KeyCode) + { + case Keys.Left: + case Keys.Right: + case Keys.Up: + case Keys.Down: + return true; + default: + return base.IsInputKey(keyData); + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.KeyCode == Keys.Space) + { + _spaceHeld = true; + } + } + + protected override void OnKeyUp(KeyEventArgs e) + { + base.OnKeyUp(e); + if (e.KeyCode == Keys.Space) + { + _spaceHeld = false; + } + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + _spaceHeld = false; + } + + private void OnCameraChanged() + { + CameraChanged?.Invoke(); + Invalidate(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs new file mode 100644 index 00000000..401ed2d4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs @@ -0,0 +1,602 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.Editing; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// + /// Turns an editor session into sprites and lines: the multi in draw order with its view + /// highlights, the grid, then what the active tool shows. + /// + internal sealed class SceneRenderer : IDisposable, IToolOverlay + { + private static readonly SpriteTint _hover = new SpriteTint(0.85f, 0.9f, 1f, 1f, 0.05f, 0.15f, 0.5f); + private static readonly SpriteTint _selected = new SpriteTint(1f, 0.65f, 0.65f, 1f, 0.45f, 0.05f, 0f); + private static readonly SpriteTint _multiSelected = new SpriteTint(0.7f, 1f, 1f, 1f, 0f, 0.3f, 0.3f); + private static readonly SpriteTint _aboveLevel = SpriteTint.Alpha(0.2f); + private static readonly SpriteTint _belowLevel = new SpriteTint(0.55f, 0.55f, 0.55f, 1f, 0f, 0f, 0f); + private static readonly SpriteTint _transparent = SpriteTint.Alpha(0.3f); + private static readonly SpriteTint _standable = new SpriteTint(0.6f, 1f, 0.6f, 1f, 0f, 0.3f, 0f); + private static readonly SpriteTint _toolGhost = new SpriteTint(1f, 1f, 1f, 0.6f, 0f, 0.08f, 0.16f); + private static readonly SpriteTint _removeMark = new SpriteTint(1f, 0.3f, 0.3f, 0.85f, 0.45f, 0f, 0f); + + private static readonly SpriteTint _reference = new SpriteTint(0.7f, 0.8f, 1f, 0.4f, 0f, 0.05f, 0.15f); + private static readonly SpriteTint _translucent = SpriteTint.Alpha(0.55f); + + + // The user's colours, read once per frame. + private Color _gridColor; + private Color _boundsColor; + private Color _marqueeLine; + private Color _marqueeFill; + private SpriteTint _workPlane; + + private readonly ArtAtlas _atlas; + private readonly SpriteBatch _sprites; + private readonly LineBatch _lines; + + private EditorSession _session; + private RectangleF _visible; + + public SceneRenderer() + { + _atlas = new ArtAtlas(); + _sprites = new SpriteBatch(); + _lines = new LineBatch(); + } + + public ArtAtlas Atlas => _atlas; + + /// Advances animated tiles in preview mode (one step per 100 ms). + public int AnimationTick { get; set; } + + /// True when the last preview frame drew an animated tile. + public bool HasAnimation { get; private set; } + + /// Number of sprites drawn by the last frame. + public int LastSpriteCount { get; private set; } + + public void Draw(EditorSession session, Camera2D camera, Size viewport) + { + _session = session; + _visible = camera.VisibleWorld(viewport); + LastSpriteCount = 0; + HasAnimation = false; + + UI.EditorSettings settings = UI.EditorSettings.Current; + _gridColor = settings.Grid; + _boundsColor = settings.Outline; + _marqueeLine = settings.SelectionBox; + _marqueeFill = Color.FromArgb(40, settings.SelectionBox); + _workPlane = SpriteTint.Solid(settings.WorkPlane); + + if (!session.HasDocument) + { + return; + } + + if (session.PreviewMode) + { + AddPreviewTerrain(session); + } + + AddReference(session); + if (session.PreviewMode) + { + AddPreviewTiles(session); + LastSpriteCount += _sprites.Count; + _sprites.Flush(_atlas, camera, viewport); + return; + } + + if (session.PlanMode) + { + AddPlan(session); + } + else + { + AddTiles(session); + } + + LastSpriteCount += _sprites.Count; + _sprites.Flush(_atlas, camera, viewport); + + if (!session.PlanMode) + { + AddGrid(session); + } + + _lines.Flush(camera, viewport); + + // Tool overlay: sprites first (ghost tiles), then the lines on top of them. + session.ActiveTool.PaintOverlay(this); + LastSpriteCount += _sprites.Count; + _sprites.Flush(_atlas, camera, viewport); + _lines.Flush(camera, viewport); + } + + public void Dispose() + { + _atlas.Dispose(); + _sprites.Dispose(); + _lines.Dispose(); + } + + // ---------------------------------------------------------------- multi + + private void AddTiles(EditorSession session) + { + MultiEditorComponentList list = session.CompList; + int maxHeight = session.HeightLimit ?? int.MaxValue; + bool manySelected = session.Selection.Count > 1; + MultiTile selected = session.SelectedTile; + MultiTile hover = session.HoverTile; + (int Floor, int Ceiling)? level = session.ActiveLevel; + + // The work plane goes into each cell's stack where its tiles reach the plane's height, + // so what is below shows through it and what stands on it is drawn over it. + bool plane = session.ShowWorkPlane && _atlas.TryGet(ArtAtlas.FloorKey, out _planeSprite); + int planeZ = session.WorkPlaneZ; + + for (int x = 0; x < list.Width; ++x) + { + for (int y = 0; y < list.Height; ++y) + { + bool planeDrawn = !plane; + foreach (MultiTile tile in list.TilesIn(x, y)) + { + if (!planeDrawn && tile.SortKey >= planeZ) + { + AddPlaneCell(x, y, planeZ); + planeDrawn = true; + } + + AddTile(session, list, tile, maxHeight, manySelected, selected, hover, level); + } + + if (!planeDrawn) + { + AddPlaneCell(x, y, planeZ); + } + } + } + } + + private AtlasSprite _planeSprite; + + /// One cell of the work plane: a diamond at the plane's height, when on screen. + private void AddPlaneCell(int x, int y, int z) + { + PointF corner = EditorSession.CellCorner(x, y, z); + float left = corner.X - 22; + if (left < _visible.Right && left + _planeSprite.Width > _visible.Left && + corner.Y < _visible.Bottom && corner.Y + _planeSprite.Height > _visible.Top) + { + _sprites.Add(_planeSprite, left, corner.Y, _workPlane); + } + } + + private void AddTile(EditorSession session, MultiEditorComponentList list, MultiTile tile, int maxHeight, + bool manySelected, MultiTile selected, MultiTile hover, (int Floor, int Ceiling)? level) + { + if (tile.Z > maxHeight || !list.IsShown(tile)) + { + return; + } + + if (!_atlas.TryGet(tile.Id, out AtlasSprite sprite) || !IsVisible(tile, sprite)) + { + return; + } + + SpriteTint tint; + if (tile == hover) + { + tint = _hover; + } + else if (tile == selected) + { + tint = _selected; + } + else if (manySelected && session.IsSelected(tile)) + { + tint = _multiSelected; + } + else if (level is { } above && tile.Z >= above.Ceiling) + { + if (session.HideAboveLevel) + { + return; + } + + tint = _aboveLevel; + } + else if (level is { } below && tile.Z < below.Floor) + { + tint = _belowLevel; + } + else if (tile.Transparent) + { + tint = _transparent; + } + else if ((session.ShowWalkables && tile.Walkable) || (session.ShowDoubleSurface && tile.DoubleSurface)) + { + tint = _standable; + } + else + { + tint = SpriteTint.None; + } + + _sprites.Add(sprite, tile.XMod, tile.YMod, tint); + } + + /// The reference multi, faint and blue, under everything else. + private void AddReference(EditorSession session) + { + MultiEditorComponentList reference = session.Reference; + if (reference == null) + { + return; + } + + (int dx, int dy, int dz) = session.ReferenceOffset; + float offsetX = (dx - dy) * 22; + float offsetY = ((dx + dy) * 22) - (dz * 4); + foreach (MultiTile tile in reference.RealTiles) + { + if (_atlas.TryGet(tile.Id, out AtlasSprite sprite)) + { + _sprites.Add(sprite, tile.XMod + offsetX, tile.YMod + offsetY, _reference); + } + } + } + + /// The first of four land tile variants per terrain, as the client's maps use them. + private static int TerrainBase(PreviewTerrain terrain) => terrain switch + { + PreviewTerrain.Grass => 0x0003, + PreviewTerrain.Dirt => 0x0071, + PreviewTerrain.Sand => 0x0016, + PreviewTerrain.Snow => 0x011A, + _ => -1 + }; + + /// + /// Flat ground at Z 0 across the whole view, as if the multi stood in the world. The four + /// variants of the terrain are mixed by cell so it does not look tiled. + /// + private void AddPreviewTerrain(EditorSession session) + { + int land = TerrainBase(session.PreviewTerrain); + if (land < 0) + { + return; + } + + // The cells the view's corners fall in bound every cell that can be seen. + int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + foreach (PointF corner in new[] + { + new PointF(_visible.Left, _visible.Top), new PointF(_visible.Right, _visible.Top), + new PointF(_visible.Left, _visible.Bottom), new PointF(_visible.Right, _visible.Bottom) + }) + { + EditorSession.PlaneCell(Point.Round(corner), 0, out int cx, out int cy); + minX = Math.Min(minX, cx); + minY = Math.Min(minY, cy); + maxX = Math.Max(maxX, cx); + maxY = Math.Max(maxY, cy); + } + + for (int x = minX - 1; x <= maxX + 1; ++x) + { + for (int y = minY - 1; y <= maxY + 1; ++y) + { + int variant = (int)((((uint)x * 73856093u) ^ ((uint)y * 19349663u)) >> 4) & 3; + if (!_atlas.TryGet(ArtAtlas.LandKey(land + variant), out AtlasSprite sprite)) + { + continue; + } + + PointF corner = EditorSession.CellCorner(x, y, 0); + float px = corner.X - 22; + if (px < _visible.Right && px + sprite.Width > _visible.Left && corner.Y < _visible.Bottom && corner.Y + sprite.Height > _visible.Top) + { + _sprites.Add(sprite, px, corner.Y, SpriteTint.None); + } + } + } + } + + /// The multi as the client shows it: every tile, translucent ones see-through, animations running. + private void AddPreviewTiles(EditorSession session) + { + foreach (MultiTile tile in session.CompList.RealTiles) + { + ItemData data = TileData.ItemTable[tile.Id]; + int id = tile.Id; + if ((data.Flags & TileFlag.Animation) != 0 && Animdata.GetAnimData(id) is { FrameCount: > 0 } animation) + { + HasAnimation = true; + int interval = Math.Max(1, (int)animation.FrameInterval); + id += animation.FrameData[AnimationTick / interval % animation.FrameCount]; + } + + // Frames stand on the same cell as the base art: centred on it, bottoms aligned. + if (!_atlas.TryGet(id, out AtlasSprite sprite) || !ArtMetrics.TryGetSize(tile.Id, out int width, out int height)) + { + continue; + } + + float x = tile.XMod + ((width - sprite.Width) / 2); + float y = tile.YMod + height - sprite.Height; + bool translucent = (data.Flags & TileFlag.Translucent) != 0; + _sprites.Add(sprite, x, y, translucent ? _translucent : SpriteTint.None); + } + } + + private bool IsVisible(MultiTile tile, AtlasSprite sprite) + { + return tile.XMod < _visible.Right && tile.XMod + sprite.Width > _visible.Left && + tile.YMod < _visible.Bottom && tile.YMod + sprite.Height > _visible.Top; + } + + /// The outline of the multi at Z 0, and the cell grid when it is on. + private void AddGrid(EditorSession session) + { + MultiEditorComponentList list = session.CompList; + + // On the ground, whatever floor is chosen: the work plane is what moves with the floors. + const int z = 0; + int width = list.Width; + int height = list.Height; + + if (session.ShowGrid) + { + for (int x = 1; x < width; ++x) + { + Line(EditorSession.CellCorner(x, 0, z), EditorSession.CellCorner(x, height, z), _gridColor); + } + + for (int y = 1; y < height; ++y) + { + Line(EditorSession.CellCorner(0, y, z), EditorSession.CellCorner(width, y, z), _gridColor); + } + } + + PointF a = EditorSession.CellCorner(0, 0, z); + PointF b = EditorSession.CellCorner(width, 0, z); + PointF c = EditorSession.CellCorner(width, height, z); + PointF d = EditorSession.CellCorner(0, height, z); + Line(a, b, _boundsColor); + Line(b, c, _boundsColor); + Line(c, d, _boundsColor); + Line(d, a, _boundsColor); + } + + private void Line(PointF from, PointF to, Color color) + { + _lines.Add(from.X, from.Y, to.X, to.Y, color); + } + + // ---------------------------------------------------------------- plan view + + private static readonly Color _planGrid = Color.FromArgb(70, 128, 128, 128); + private static readonly Color _planWall = Color.FromArgb(235, 235, 235); + private static readonly Color _planDoor = Color.FromArgb(205, 133, 63); + private static readonly Color _planSelected = Color.FromArgb(110, 255, 215, 0); + private static readonly Color _planPlane = Color.FromArgb(70, 32, 192, 32); + + private void Fill(float x, float y, float width, float height, Color color) + { + if (_atlas.TryGet(ArtAtlas.WhiteKey, out AtlasSprite white)) + { + _sprites.Add(white, x, y, width, height, SpriteTint.Solid(color)); + } + } + + private static Color RadarColor(ushort id) + { + return Ultima.Helpers.HueHelpers.HueToColor(RadarCol.GetItemColor(id)); + } + + /// Wall and door lines of a tile on the edges of its cell. + private void AddPlanShape(PlanShape shape, Point o, Color wall, Color door) + { + const int cell = PlanView.Cell; + Color color = (shape & PlanShape.Door) != 0 ? door : wall; + if ((shape & PlanShape.South) != 0) + { + Fill(o.X - 2, o.Y + cell - 2, cell + 4, 4, color); + } + + if ((shape & PlanShape.East) != 0) + { + Fill(o.X + cell - 2, o.Y - 2, 4, cell + 4, color); + } + + if ((shape & PlanShape.Post) != 0) + { + Fill(o.X + cell - 3, o.Y + cell - 3, 6, 6, wall); + } + } + + private void AddPlan(EditorSession session) + { + const int cell = PlanView.Cell; + MultiEditorComponentList list = session.CompList; + int maxHeight = session.EditMaxHeight; + int minZ = session.EditMinZ; + + for (int x = 0; x < list.Width; ++x) + { + for (int y = 0; y < list.Height; ++y) + { + Point o = PlanView.CellOrigin(x, y); + var tiles = list.GetTilesAt(x, y); + + // Fill: the top tile that is not a wall, darker when below the work plane. A plan is + // for the layout, so roofs and loose wall pieces only fill cells with nothing else. + MultiTile fill = TopFill(session, tiles, maxHeight, skipCovers: true) ?? TopFill(session, tiles, maxHeight, skipCovers: false); + if (fill != null) + { + Color color = RadarColor(fill.Id); + if (fill.Z < minZ) + { + color = Color.FromArgb(color.R / 2, color.G / 2, color.B / 2); + } + + Fill(o.X, o.Y, cell, cell, color); + } + + if (session.ShowWorkPlane) + { + Fill(o.X, o.Y, cell, cell, _planPlane); + } + + bool selected = false; + foreach (MultiTile tile in tiles) + { + if (tile.Z > maxHeight || tile.Z < minZ || !list.IsShown(tile)) + { + continue; + } + + AddPlanShape(session.PlanShapeOf(tile.Id), o, _planWall, _planDoor); + selected |= session.IsSelected(tile); + } + + if (selected) + { + Fill(o.X, o.Y, cell, cell, _planSelected); + } + } + } + + int right = PlanView.CellOrigin(list.Width, 0).X; + int bottom = PlanView.CellOrigin(0, list.Height).Y; + Point origin = PlanView.CellOrigin(0, 0); + for (int x = 0; x <= list.Width; ++x) + { + int px = PlanView.CellOrigin(x, 0).X; + _lines.Add(px, origin.Y, px, bottom, _planGrid); + } + + for (int y = 0; y <= list.Height; ++y) + { + int py = PlanView.CellOrigin(0, y).Y; + _lines.Add(origin.X, py, right, py, _planGrid); + } + + if (session.HoverTile is { } hover) + { + Point o = PlanView.CellOrigin(hover.X, hover.Y); + _lines.Rectangle(new RectangleF(o.X + 1, o.Y + 1, cell - 2, cell - 2), _marqueeLine); + _lines.Rectangle(new RectangleF(o.X + 2, o.Y + 2, cell - 4, cell - 4), _marqueeLine); + } + } + + private static MultiTile TopFill(EditorSession session, System.Collections.Generic.List tiles, int maxHeight, bool skipCovers) + { + for (int i = tiles.Count - 1; i >= 0; --i) + { + MultiTile tile = tiles[i]; + if (tile.Z > maxHeight || !session.CompList.IsShown(tile) || session.PlanShapeOf(tile.Id) != PlanShape.Fill || + (skipCovers && (TileData.ItemTable[tile.Id].Flags & (TileFlag.Roof | TileFlag.Wall)) != 0)) + { + continue; + } + + return tile; + } + + return null; + } + + // ---------------------------------------------------------------- tool overlay + + void IToolOverlay.Ghost(ushort id, int x, int y, int z) + { + if (_session.PlanMode) + { + if (!_session.CompList.InBounds(x, y)) + { + return; + } + + Point o = PlanView.CellOrigin(x, y); + PlanShape shape = _session.PlanShapeOf(id); + if (shape == PlanShape.Fill) + { + Fill(o.X, o.Y, PlanView.Cell, PlanView.Cell, Color.FromArgb(150, RadarColor(id))); + } + else + { + AddPlanShape(shape, o, Color.FromArgb(150, _planWall), Color.FromArgb(150, _planDoor)); + } + + return; + } + + if (!_session.CompList.InBounds(x, y) || !_atlas.TryGet(id, out AtlasSprite sprite)) + { + return; + } + + float px = ((x - y) * 22) - (sprite.Width / 2) + MultiEditorComponentList.GapXMod; + float py = ((x + y) * 22) - (z * 4) - sprite.Height + MultiEditorComponentList.GapYMod; + _sprites.Add(sprite, px, py, _toolGhost); + } + + void IToolOverlay.Highlight(MultiTile tile, TileHighlight kind) + { + if (_session.PlanMode) + { + Point o = PlanView.CellOrigin(tile.X, tile.Y); + Fill(o.X, o.Y, PlanView.Cell, PlanView.Cell, Color.FromArgb(110, Color.Red)); + return; + } + + if (_atlas.TryGet(tile.Id, out AtlasSprite sprite)) + { + _sprites.Add(sprite, tile.XMod, tile.YMod, _removeMark); + } + } + + void IToolOverlay.Polyline(System.Collections.Generic.IReadOnlyList points, bool closed) + { + for (int i = 1; i < points.Count; i++) + { + _lines.Add(points[i - 1].X, points[i - 1].Y, points[i].X, points[i].Y, _marqueeLine); + } + + if (closed && points.Count > 2) + { + _lines.Add(points[^1].X, points[^1].Y, points[0].X, points[0].Y, _marqueeLine); + } + } + + void IToolOverlay.Marquee(Rectangle rect) + { + if (_atlas.TryGet(ArtAtlas.WhiteKey, out AtlasSprite white)) + { + _sprites.Add(white, rect.X, rect.Y, rect.Width, rect.Height, SpriteTint.Solid(_marqueeFill)); + } + + _lines.Rectangle(rect, _marqueeLine); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ShaderProgram.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ShaderProgram.cs new file mode 100644 index 00000000..572118de --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/ShaderProgram.cs @@ -0,0 +1,74 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using OpenTK.Graphics.OpenGL4; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + internal sealed class ShaderProgram : IDisposable + { + public int Handle { get; } + + public ShaderProgram(string vertexSource, string fragmentSource) + { + int vertex = Compile(ShaderType.VertexShader, vertexSource); + int fragment = Compile(ShaderType.FragmentShader, fragmentSource); + + Handle = GL.CreateProgram(); + GL.AttachShader(Handle, vertex); + GL.AttachShader(Handle, fragment); + GL.LinkProgram(Handle); + GL.GetProgram(Handle, GetProgramParameterName.LinkStatus, out int linked); + + GL.DetachShader(Handle, vertex); + GL.DetachShader(Handle, fragment); + GL.DeleteShader(vertex); + GL.DeleteShader(fragment); + + if (linked == 0) + { + string log = GL.GetProgramInfoLog(Handle); + GL.DeleteProgram(Handle); + throw new InvalidOperationException($"Shader link failed: {log}"); + } + } + + public void Use() + { + GL.UseProgram(Handle); + } + + public int Uniform(string name) + { + return GL.GetUniformLocation(Handle, name); + } + + public void Dispose() + { + GL.DeleteProgram(Handle); + } + + private static int Compile(ShaderType type, string source) + { + int shader = GL.CreateShader(type); + GL.ShaderSource(shader, source); + GL.CompileShader(shader); + GL.GetShader(shader, ShaderParameter.CompileStatus, out int compiled); + if (compiled != 0) + { + return shader; + } + + string log = GL.GetShaderInfoLog(shader); + GL.DeleteShader(shader); + throw new InvalidOperationException($"{type} compile failed: {log}"); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs new file mode 100644 index 00000000..fba6317f --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs @@ -0,0 +1,311 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using OpenTK.Graphics.OpenGL4; + +namespace UoFiddler.Plugin.MultiEditor.Rendering +{ + /// + /// Colour change of a sprite: rgb * Mul + Add, alpha * MulA. + /// + internal readonly record struct SpriteTint(float MulR, float MulG, float MulB, float MulA, float AddR, float AddG, float AddB) + { + public static readonly SpriteTint None = new SpriteTint(1f, 1f, 1f, 1f, 0f, 0f, 0f); + + public static SpriteTint Solid(Color color) + { + return new SpriteTint(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f, 0f, 0f, 0f); + } + + public static SpriteTint Alpha(float alpha) + { + return new SpriteTint(1f, 1f, 1f, alpha, 0f, 0f, 0f); + } + } + + /// + /// Draws atlas sprites as instanced quads, in the order they were added. + /// + internal sealed class SpriteBatch : IDisposable + { + private const int FloatsPerSprite = 16; + + private const string VertexSource = @"#version 330 core +layout(location = 0) in vec2 aCorner; +layout(location = 1) in vec4 aRect; +layout(location = 2) in vec4 aUv; +layout(location = 3) in float aLayer; +layout(location = 4) in vec4 aMul; +layout(location = 5) in vec3 aAdd; +uniform vec2 uViewport; +uniform vec2 uOrigin; +uniform float uZoom; +uniform float uAtlasSize; +out vec3 vUv; +out vec4 vMul; +out vec3 vAdd; +void main() +{ + vec2 world = aRect.xy + aCorner * aRect.zw; + // Whole pixels, so art stays sharp and neighbouring tiles meet without seams. + vec2 screen = floor((world - uOrigin) * uZoom + 0.5); + vec2 ndc = screen / uViewport * 2.0 - 1.0; + gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0); + vUv = vec3((aUv.xy + aCorner * aUv.zw) / uAtlasSize, aLayer); + vMul = aMul; + vAdd = aAdd; +}"; + + private const string FragmentSource = @"#version 330 core +in vec3 vUv; +in vec4 vMul; +in vec3 vAdd; +uniform sampler2DArray uAtlas; +out vec4 color; +void main() +{ + vec4 c = texture(uAtlas, vUv); + color = vec4(c.rgb * vMul.rgb + vAdd, c.a * vMul.a); +}"; + + private readonly ShaderProgram _shader; + private readonly int _vao; + private readonly int _cornerVbo; + private readonly int _instanceVbo; + private float[] _data = new float[FloatsPerSprite * 2048]; + private int _count; + private int _gpuCapacity; + + public SpriteBatch() + { + _shader = new ShaderProgram(VertexSource, FragmentSource); + _vao = GL.GenVertexArray(); + GL.BindVertexArray(_vao); + + _cornerVbo = GL.GenBuffer(); + GL.BindBuffer(BufferTarget.ArrayBuffer, _cornerVbo); + float[] corners = { 0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f }; + GL.BufferData(BufferTarget.ArrayBuffer, corners.Length * sizeof(float), corners, BufferUsageHint.StaticDraw); + GL.EnableVertexAttribArray(0); + GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, 0, 0); + + _instanceVbo = GL.GenBuffer(); + GL.BindBuffer(BufferTarget.ArrayBuffer, _instanceVbo); + const int stride = FloatsPerSprite * sizeof(float); + Attribute(1, 4, stride, 0); + Attribute(2, 4, stride, 4); + Attribute(3, 1, stride, 8); + Attribute(4, 4, stride, 9); + Attribute(5, 3, stride, 13); + GL.BindVertexArray(0); + } + + public int Count => _count; + + public void Add(in AtlasSprite sprite, float x, float y, in SpriteTint tint) + { + Add(sprite, x, y, sprite.Width, sprite.Height, tint); + } + + public void Add(in AtlasSprite sprite, float x, float y, float width, float height, in SpriteTint tint) + { + if ((_count + 1) * FloatsPerSprite > _data.Length) + { + Array.Resize(ref _data, _data.Length * 2); + } + + int i = _count * FloatsPerSprite; + _data[i] = x; + _data[i + 1] = y; + _data[i + 2] = width; + _data[i + 3] = height; + _data[i + 4] = sprite.X; + _data[i + 5] = sprite.Y; + _data[i + 6] = sprite.Width; + _data[i + 7] = sprite.Height; + _data[i + 8] = sprite.Layer; + _data[i + 9] = tint.MulR; + _data[i + 10] = tint.MulG; + _data[i + 11] = tint.MulB; + _data[i + 12] = tint.MulA; + _data[i + 13] = tint.AddR; + _data[i + 14] = tint.AddG; + _data[i + 15] = tint.AddB; + ++_count; + } + + /// Draws what was added and empties the batch. + public void Flush(ArtAtlas atlas, Camera2D camera, Size viewport) + { + if (_count == 0) + { + return; + } + + _shader.Use(); + GL.Uniform2(_shader.Uniform("uViewport"), (float)viewport.Width, viewport.Height); + GL.Uniform2(_shader.Uniform("uOrigin"), camera.OriginX, camera.OriginY); + GL.Uniform1(_shader.Uniform("uZoom"), camera.Zoom); + GL.Uniform1(_shader.Uniform("uAtlasSize"), (float)ArtAtlas.Size); + GL.Uniform1(_shader.Uniform("uAtlas"), 0); + + GL.ActiveTexture(TextureUnit.Texture0); + GL.BindTexture(TextureTarget.Texture2DArray, atlas.Texture); + + GL.BindVertexArray(_vao); + GL.BindBuffer(BufferTarget.ArrayBuffer, _instanceVbo); + int bytes = _count * FloatsPerSprite * sizeof(float); + if (bytes > _gpuCapacity) + { + _gpuCapacity = _data.Length * sizeof(float); + GL.BufferData(BufferTarget.ArrayBuffer, _gpuCapacity, IntPtr.Zero, BufferUsageHint.StreamDraw); + } + + GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, bytes, _data); + GL.DrawArraysInstanced(PrimitiveType.TriangleStrip, 0, 4, _count); + GL.BindVertexArray(0); + _count = 0; + } + + public void Dispose() + { + _shader.Dispose(); + GL.DeleteBuffer(_cornerVbo); + GL.DeleteBuffer(_instanceVbo); + GL.DeleteVertexArray(_vao); + } + + private static void Attribute(int index, int size, int stride, int offsetFloats) + { + GL.EnableVertexAttribArray(index); + GL.VertexAttribPointer(index, size, VertexAttribPointerType.Float, false, stride, offsetFloats * sizeof(float)); + GL.VertexAttribDivisor(index, 1); + } + } + + /// + /// Draws one pixel wide lines in world space (grid, outlines, selection box). + /// + internal sealed class LineBatch : IDisposable + { + private const int FloatsPerVertex = 6; + + private const string VertexSource = @"#version 330 core +layout(location = 0) in vec2 aPos; +layout(location = 1) in vec4 aColor; +uniform vec2 uViewport; +uniform vec2 uOrigin; +uniform float uZoom; +out vec4 vColor; +void main() +{ + vec2 screen = floor((aPos - uOrigin) * uZoom + 0.5) + 0.5; + vec2 ndc = screen / uViewport * 2.0 - 1.0; + gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0); + vColor = aColor; +}"; + + private const string FragmentSource = @"#version 330 core +in vec4 vColor; +out vec4 color; +void main() +{ + color = vColor; +}"; + + private readonly ShaderProgram _shader; + private readonly int _vao; + private readonly int _vbo; + private float[] _data = new float[FloatsPerVertex * 1024]; + private int _vertices; + private int _gpuCapacity; + + public LineBatch() + { + _shader = new ShaderProgram(VertexSource, FragmentSource); + _vao = GL.GenVertexArray(); + GL.BindVertexArray(_vao); + _vbo = GL.GenBuffer(); + GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo); + const int stride = FloatsPerVertex * sizeof(float); + GL.EnableVertexAttribArray(0); + GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, stride, 0); + GL.EnableVertexAttribArray(1); + GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, stride, 2 * sizeof(float)); + GL.BindVertexArray(0); + } + + public void Add(float x0, float y0, float x1, float y1, Color color) + { + if ((_vertices + 2) * FloatsPerVertex > _data.Length) + { + Array.Resize(ref _data, _data.Length * 2); + } + + Vertex(x0, y0, color); + Vertex(x1, y1, color); + } + + public void Rectangle(RectangleF rect, Color color) + { + Add(rect.Left, rect.Top, rect.Right, rect.Top, color); + Add(rect.Right, rect.Top, rect.Right, rect.Bottom, color); + Add(rect.Right, rect.Bottom, rect.Left, rect.Bottom, color); + Add(rect.Left, rect.Bottom, rect.Left, rect.Top, color); + } + + public void Flush(Camera2D camera, Size viewport) + { + if (_vertices == 0) + { + return; + } + + _shader.Use(); + GL.Uniform2(_shader.Uniform("uViewport"), (float)viewport.Width, viewport.Height); + GL.Uniform2(_shader.Uniform("uOrigin"), camera.OriginX, camera.OriginY); + GL.Uniform1(_shader.Uniform("uZoom"), camera.Zoom); + + GL.BindVertexArray(_vao); + GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo); + int bytes = _vertices * FloatsPerVertex * sizeof(float); + if (bytes > _gpuCapacity) + { + _gpuCapacity = _data.Length * sizeof(float); + GL.BufferData(BufferTarget.ArrayBuffer, _gpuCapacity, IntPtr.Zero, BufferUsageHint.StreamDraw); + } + + GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, bytes, _data); + GL.DrawArrays(PrimitiveType.Lines, 0, _vertices); + GL.BindVertexArray(0); + _vertices = 0; + } + + public void Dispose() + { + _shader.Dispose(); + GL.DeleteBuffer(_vbo); + GL.DeleteVertexArray(_vao); + } + + private void Vertex(float x, float y, Color color) + { + int i = _vertices * FloatsPerVertex; + _data[i] = x; + _data[i + 1] = y; + _data[i + 2] = color.R / 255f; + _data[i + 3] = color.G / 255f; + _data[i + 4] = color.B / 255f; + _data[i + 5] = color.A / 255f; + ++_vertices; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/DrawTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/DrawTool.cs new file mode 100644 index 00000000..2ac7aa33 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/DrawTool.cs @@ -0,0 +1,67 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Drawing; +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Places the draw tile on the hovered tile or an empty cell, with the chosen brush size. + /// + internal sealed class DrawTool : EditorTool + { + public DrawTool(IEditorContext context) : base(context) + { + } + + public override bool TracksCursorCell => true; + + public override void OnMouseUp(MouseEventArgs e) + { + Context.CellAt(Context.MouseLoc, out int x, out int y, out int z); + if (!Context.CompList.InBounds(x, y)) + { + return; + } + + if (Context.BrushSize <= 1) + { + Context.CompList.TileAdd(x, y, z, Context.DrawTileId, Replacing); + } + else + { + Context.CompList.TileAddBrush(x, y, z, Context.DrawTileId, Context.BrushSize, Replacing); + } + + Context.RecordRecentTile(Context.DrawTileId); + Context.AfterEdit(z); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + Context.CellAt(Context.MouseLoc, out int x, out int y, out int z); + if (!Context.CompList.InBounds(x, y)) + { + return; + } + + int half = Context.BrushSize / 2; + for (int dx = -half; dx <= half; dx++) + { + for (int dy = -half; dy <= half; dy++) + { + overlay.Ghost(Context.DrawTileId, x + dx, y + dy, z); + } + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs new file mode 100644 index 00000000..38c5bbe7 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs @@ -0,0 +1,242 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Where the draw tools put a new tile. + /// + internal enum PlacementMode + { + /// On top of the hovered tile, or on an empty cell on the work plane (Z 0 with all floors and the plane not moved). + Stack, + + /// At the hovered tile's own Z, replacing tiles of the same kind (flat or tall) there. + Replace, + + /// At the work plane's Z, in the cell under the cursor on that plane. + FixedZ + } + + /// + /// What a tool may see and do in the editor. Implemented by the editor control. + /// + internal interface IEditorContext + { + MultiEditorComponentList CompList { get; } + + /// Mouse position in scrolled (and unzoomed) canvas space. + Point MouseLoc { get; } + + MultiTile HoverTile { get; } + + IReadOnlyCollection Selection { get; } + + ushort DrawTileId { get; } + + int BrushSize { get; } + + PlacementMode Placement { get; } + + /// The client's house design tables (walls, floors, doors, stairs). + HouseStyles HouseStyles { get; } + + /// The house part style chosen in the House tab, or null. + HouseStyle HouseStyle { get; } + + /// Amount the altitude tool adds to Z. + int ZStep { get; } + + /// The work plane's Z once a floor is chosen or the plane was moved, where house parts go; otherwise null. + int? WorkZ { get; } + + /// Highest Z drawn (the height slider). + int MaxHeight { get; } + + int ScrollX { get; } + + int ScrollY { get; } + + /// The cell under a canvas point and the Z a new tile there would get. + void CellAt(Point canvasLoc, out int x, out int y, out int z); + + /// The cell under a canvas point on the flat plane at height . + void PlaneCell(Point canvasLoc, int z, out int x, out int y); + + /// The tiles you can work on inside a box drawn on the canvas (screen space). + List TilesInRect(Rectangle screenRect); + + void SetSelection(IEnumerable tiles, bool add); + + void ToggleSelected(MultiTile tile); + + void SetDrawTile(ushort id); + + /// + /// Call after an edit: refreshes the height slider, minimap and hover. With + /// the slider is raised to show tiles placed at that Z. + /// + void AfterEdit(int? raiseTo = null); + + void RecordRecentTile(ushort id); + + /// Leaves a temporary tool (paste) for the tool chosen before it. + void EndTemporaryTool(); + } + + /// + /// How a tool marks an existing tile. + /// + internal enum TileHighlight + { + /// The tile would be removed. + Remove + } + + /// + /// What a tool draws over the multi. The canvas decides how it looks. + /// + internal interface IToolOverlay + { + /// A translucent tile where a tool would place it. + void Ghost(ushort id, int x, int y, int z); + + /// An existing tile, marked. + void Highlight(MultiTile tile, TileHighlight kind); + + /// A selection box, in the canvas space of . + void Marquee(Rectangle rect); + + /// A line through canvas points, joined back to the start when closed. + void Polyline(IReadOnlyList points, bool closed); + } + + /// + /// A canvas tool. The editor forwards left mouse button events and paints the overlay after + /// the multi. Right button pans and cancels; middle button selects the hovered tile. + /// + internal abstract class EditorTool + { + protected EditorTool(IEditorContext context) + { + Context = context; + } + + protected IEditorContext Context { get; } + + /// True while a drag is in progress, so every mouse move repaints. + public virtual bool IsDragging => false; + + /// True when the overlay follows the cell under the cursor. + public virtual bool TracksCursorCell => false; + + public virtual void OnMouseDown(MouseEventArgs e) + { + } + + public virtual void OnMouseMove(MouseEventArgs e) + { + } + + public virtual void OnMouseUp(MouseEventArgs e) + { + } + + public virtual void PaintOverlay(IToolOverlay overlay) + { + } + + /// Drops a drag or pending action (Esc, right click, switching tools). + public virtual void Cancel() + { + } + + /// True when new tiles replace tiles of the same kind at their Z. + protected bool Replacing => Context.Placement == PlacementMode.Replace; + + protected static bool CtrlHeld => (Control.ModifierKeys & Keys.Control) != 0; + + protected static bool ShiftHeld => (Control.ModifierKeys & Keys.Shift) != 0; + } + + /// + /// Shared drag state for tools that span two cells (rectangle, line, area remove). + /// + internal abstract class CellDragTool : EditorTool + { + private bool _dragging; + + protected CellDragTool(IEditorContext context) : base(context) + { + } + + protected int StartX { get; private set; } + + protected int StartY { get; private set; } + + protected int EndX { get; private set; } + + protected int EndY { get; private set; } + + public override bool IsDragging => _dragging; + + protected bool Dragging => _dragging; + + public override void OnMouseDown(MouseEventArgs e) + { + Context.CellAt(Context.MouseLoc, out int x, out int y, out _); + StartX = EndX = x; + StartY = EndY = y; + _dragging = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + Context.CellAt(Context.MouseLoc, out int x, out int y, out _); + EndX = x; + EndY = y; + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + Context.CellAt(Context.MouseLoc, out int x, out int y, out int z); + EndX = x; + EndY = y; + Commit(z); + } + + public override void Cancel() + { + _dragging = false; + } + + protected abstract void Commit(int z); + + protected (int X0, int Y0, int X1, int Y1) Bounds => + (System.Math.Min(StartX, EndX), System.Math.Min(StartY, EndY), System.Math.Max(StartX, EndX), System.Math.Max(StartY, EndY)); + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs new file mode 100644 index 00000000..1706cb80 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs @@ -0,0 +1,625 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Linq; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Fills the dragged rectangle with a floor style, each cell a random piece of the style. + /// Flat tiles already at that Z in those cells are replaced. + /// + internal sealed class FloorStyleTool : PlaneDragTool + { + private int _seed = Environment.TickCount; + + public FloorStyleTool(IEditorContext context) : base(context) + { + } + + protected override HousePartKind Kind => HousePartKind.Floor; + + protected override string ActionName => "Floor"; + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final) + { + ushort[] pieces = Style.Slots.Values.Distinct().ToArray(); + var remove = new List(); + var add = new List<(ushort, int, int, int)>(); + MultiEditorComponentList list = Context.CompList; + + for (int x = Math.Min(startX, endX); x <= Math.Max(startX, endX); ++x) + { + for (int y = Math.Min(startY, endY); y <= Math.Max(startY, endY); ++y) + { + if (!list.InBounds(x, y)) + { + continue; + } + + // Same seed for preview and edit, so what is shown is what lands. + ushort id = pieces[(int)((uint)HashCode.Combine(x, y, _seed) % (uint)pieces.Length)]; + remove.AddRange(list.GetTilesAt(x, y).Where(t => t.Z == z && t.Height == 0 && list.IsShown(t))); + add.Add((id, x, y, z)); + } + } + + if (final) + { + _seed = Environment.TickCount ^ _seed; + } + + return (remove, add); + } + } + + /// Which way a gable roof's ridge runs. + internal enum RoofRidge + { + /// As the official houses: along the longer side, or so the ridge gets its crosspiece. + Auto, + AlongX, + AlongY + } + + /// Which gable ends of a roof are closed. + internal enum RoofGables + { + /// The south or east end, as the official houses do. + Front, + Both, + None + } + + /// What closes a gable. + internal enum RoofGableFill + { + /// 3 high cap pieces matching the walls. + Caps, + + /// Whole wall pieces as far as they fit under the slope, caps for the rest: for big, high roofs. + Walls + } + + /// + /// A gable roof over a house. A click on (or inside) a walled room fits the roof to its walls; + /// a drag over the wall cells sizes it by hand, as with the wall tool. The slopes rise 3 per + /// cell from the eaves, like the official house roofs: West pieces climb to an NS crosspiece + /// and East pieces come down (North / EW crosspiece / South the other way). Roof pieces + /// already in those cells are replaced. , and + /// choose the shape; Shift turns the ridge and Ctrl switches between + /// one and both gables for a single stroke. + /// + internal sealed class RoofTool : PlaneDragTool + { + private const int _rise = 3; + private const string _capStyles = "Miscellaneous Roof Pieces"; + + public RoofRidge Ridge { get; set; } = RoofRidge.Auto; + + public RoofGables Gables { get; set; } = RoofGables.Front; + + public RoofGableFill GableFill { get; set; } = RoofGableFill.Caps; + + public RoofTool(IEditorContext context) : base(context) + { + } + + protected override HousePartKind Kind => HousePartKind.Roof; + + protected override string ActionName => "Roof"; + + /// + /// The eaves go on the work plane, or on top of what the mouse points at (a wall top). + /// + protected override void BaseCell(out int x, out int y, out int z) + { + Context.CellAt(Context.MouseLoc, out x, out y, out z); + if (Context.WorkZ is { } baseZ) + { + z = baseZ; + Context.PlaneCell(Context.MouseLoc, z, out x, out y); + } + } + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final) + { + var remove = new List(); + var add = new List<(ushort, int, int, int)>(); + MultiEditorComponentList list = Context.CompList; + + // Dragged like the wall tool, over the wall cells. Walls sit on the +X/+Y edges of their + // cells, so the roof over them is the same box one cell further along X and Y (as in the + // official houses, which overhang their east and south walls by a cell). + int wallX0 = Math.Min(startX, endX), wallX1 = Math.Max(startX, endX); + int wallY0 = Math.Min(startY, endY), wallY1 = Math.Max(startY, endY); + + // A click, not a drag: take the walls of the room it points at. + if (startX == endX && startY == endY && FitToWalls(startX, startY, z, out var fitted)) + { + (wallX0, wallY0, wallX1, wallY1) = fitted; + } + + int x0 = wallX0 + 1, x1 = wallX1 + 1; + int y0 = wallY0 + 1, y1 = wallY1 + 1; + + // Like the official houses: the slopes go across the odd side, so the ridge gets its + // crosspiece; otherwise the ridge runs along the longer side, along Y when square. + int spanX = x1 - x0 + 1, spanY = y1 - y0 + 1; + bool ridgeAlongY = Ridge switch + { + RoofRidge.AlongX => false, + RoofRidge.AlongY => true, + _ => spanX % 2 != spanY % 2 ? spanX % 2 == 1 : spanY >= spanX + }; + ridgeAlongY ^= ShiftHeld; + int across0 = ridgeAlongY ? x0 : y0; + int across1 = ridgeAlongY ? x1 : y1; + int span = across1 - across0 + 1; + string low = ridgeAlongY ? "West" : "North"; + string high = ridgeAlongY ? "East" : "South"; + string ridge = ridgeAlongY ? "NSCrosspiece" : "EWCrosspiece"; + + for (int x = x0; x <= x1; ++x) + { + for (int y = y0; y <= y1; ++y) + { + if (!list.InBounds(x, y)) + { + continue; + } + + int a = ridgeAlongY ? x : y; + int fromLow = a - across0; + int fromHigh = across1 - a; + string column = span % 2 == 1 && fromLow == fromHigh ? ridge : fromLow < fromHigh ? low : high; + ushort id = Style.Get(column); + if (id == 0) + { + continue; + } + + foreach (MultiTile tile in list.GetTilesAt(x, y)) + { + if (Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Roof) + { + remove.Add(tile); + } + } + + add.Add((id, x, y, z + (_rise * Math.Min(fromLow, fromHigh)))); + } + } + + // Caps from an earlier roof over these walls go too, so a turned ridge leaves none behind. + for (int x = wallX0; x <= x1; ++x) + { + for (int y = wallY0; y <= y1; ++y) + { + foreach (MultiTile tile in list.GetTilesAt(x, y)) + { + if (IsCap(tile.Id)) + { + remove.Add(tile); + } + } + } + } + + // Gables: in the wall row at the gable end, filled up to where the slope has risen there. + RoofGables gables = Gables; + if (CtrlHeld) + { + gables = gables == RoofGables.Both ? RoofGables.Front : RoofGables.Both; + } + + var gableRows = new List(); + if (gables != RoofGables.None) + { + gableRows.Add(ridgeAlongY ? wallY1 : wallX1); + } + + if (gables == RoofGables.Both) + { + gableRows.Add(ridgeAlongY ? wallY0 : wallX0); + } + + foreach (int row in gableRows) + { + ushort wall = GableWall(row, ridgeAlongY, wallX0, wallX1, wallY0, wallY1, z); + ushort cap = wall != 0 ? CapFor(wall, ridgeAlongY) : (ushort)0; + + // Whole walls: the plain piece of the wall's own style that runs along the gable. + ushort block = 0; + int blockHeight = 0; + if (GableFill == RoofGableFill.Walls && wall != 0) + { + block = wall; + if (Context.HouseStyles.TryGetRole(wall, out HouseStyle wallStyle, out _) && + wallStyle.Get(ridgeAlongY ? "South2" : "East2") is var plain and not 0) + { + block = plain; + } + + blockHeight = TileData.ItemTable[block].Height; + } + + if (cap == 0 && blockHeight <= 0) + { + continue; + } + + for (int a = across0; a <= across1; ++a) + { + int top = _rise * Math.Min(a - across0, across1 - a); + int x = ridgeAlongY ? a : row; + int y = ridgeAlongY ? row : a; + if (!list.InBounds(x, y)) + { + continue; + } + + int filled = 0; + while (blockHeight > 0 && top - filled >= blockHeight) + { + add.Add((block, x, y, z + filled)); + filled += blockHeight; + } + + while (cap != 0 && top - filled >= _rise) + { + add.Add((cap, x, y, z + filled)); + filled += _rise; + } + } + } + + return (remove, add); + } + + /// + /// The walls a click means: the box of the connected run of wall cells, on the level just + /// below , that holds the clicked cell. A click inside a room takes the + /// smallest such box around it. False when there are no walls there. + /// + private bool FitToWalls(int cx, int cy, int z, out (int X0, int Y0, int X1, int Y1) box) + { + MultiEditorComponentList list = Context.CompList; + bool IsWall(int x, int y) + { + foreach (MultiTile tile in list.GetTilesAt(x, y)) + { + if (tile.Z < z && tile.Z >= z - 20 && + Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) + { + return true; + } + } + + return false; + } + + box = default; + long bestArea = long.MaxValue; + var seen = new HashSet<(int, int)>(); + var queue = new Queue<(int X, int Y)>(); + for (int sx = 0; sx < list.Width; ++sx) + { + for (int sy = 0; sy < list.Height; ++sy) + { + if (seen.Contains((sx, sy)) || !IsWall(sx, sy)) + { + continue; + } + + int x0 = sx, y0 = sy, x1 = sx, y1 = sy, cells = 0; + seen.Add((sx, sy)); + queue.Enqueue((sx, sy)); + while (queue.Count > 0) + { + (int x, int y) = queue.Dequeue(); + ++cells; + x0 = Math.Min(x0, x); + y0 = Math.Min(y0, y); + x1 = Math.Max(x1, x); + y1 = Math.Max(y1, y); + foreach ((int dx, int dy) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) }) + { + (int nx, int ny) = (x + dx, y + dy); + if (list.InBounds(nx, ny) && !seen.Contains((nx, ny)) && IsWall(nx, ny)) + { + seen.Add((nx, ny)); + queue.Enqueue((nx, ny)); + } + } + } + + long area = (long)(x1 - x0 + 1) * (y1 - y0 + 1); + if (cells > 1 && cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1 && area < bestArea) + { + bestArea = area; + box = (x0, y0, x1, y1); + } + } + } + + return bestArea != long.MaxValue; + } + + private bool IsCap(ushort id) + { + return Context.HouseStyles.TryGetRole(id, out HouseStyle owner, out _) && + owner.Kind == HousePartKind.Misc && owner.Group.StartsWith(_capStyles, StringComparison.Ordinal); + } + + /// A wall tile below the eaves in a gable wall row, or 0 when the row has none. + private ushort GableWall(int row, bool alongX, int wallX0, int wallX1, int wallY0, int wallY1, int z) + { + MultiEditorComponentList list = Context.CompList; + ushort wall = 0; + int from = alongX ? wallX0 : wallY0, to = alongX ? wallX1 : wallY1; + for (int a = from; a <= to && wall == 0; ++a) + { + foreach (MultiTile tile in list.GetTilesAt(alongX ? a : row, alongX ? row : a)) + { + if (tile.Z < z && Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) + { + wall = tile.Id; + break; + } + } + } + + return wall; + } + + /// + /// The cap for a gable over a wall: the misc.txt roof piece with the wall's tiledata name and + /// the id nearest its own. Odd pieces close walls along X, even pieces walls along Y (as + /// placed in the official multis). 0 when no cap matches. + /// + private ushort CapFor(ushort wall, bool alongX) + { + string name = TileData.ItemTable[wall].Name; + ushort best = 0; + foreach (HouseStyle style in Context.HouseStyles.Styles) + { + if (style.Kind != HousePartKind.Misc || !style.Group.StartsWith(_capStyles, StringComparison.Ordinal)) + { + continue; + } + + for (int pair = 1; pair <= 7; pair += 2) + { + ushort first = style.Get($"Piece{pair}"); + ushort second = style.Get($"Piece{pair + 1}"); + ushort cap = alongX ? first : second; + if (first == 0 || second == 0 || TileData.ItemTable[cap].Height > 4 || + !string.Equals(TileData.ItemTable[cap].Name, name, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (best == 0 || Math.Abs(cap - wall) < Math.Abs(best - wall)) + { + best = cap; + } + } + } + + return best; + } + } + + /// + /// A house foundation like the client's customizable house multis: the dragged rectangle gets + /// a ring of 5 high foundation walls at the base Z and a dirt floor 7 above it inside. + /// + internal sealed class FoundationTool : PlaneDragTool + { + // The foundation multis use Light Brick Quarter Walls (0x63-0x66) and the dirt floor. + public const ushort FoundationPost = 0x0066; + private const ushort _dirt = 0x31F4; + private const int _floorAbove = 7; + + public FoundationTool(IEditorContext context) : base(context) + { + } + + protected override HousePartKind Kind => HousePartKind.Wall; + + protected override string ActionName => "Foundation"; + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final) + { + var planner = new WallPlanner(Context.CompList, Context.HouseStyles, Style, z); + var (south, east) = WallPlanner.DragEdges(startX, startY, endX, endY, line: false); + var (remove, add) = planner.Plan(south, east, erase: false, Context.CompList.Width, Context.CompList.Height); + + // The foundation multis floor every cell with the same dirt piece. + for (int x = Math.Min(startX, endX) + 1; x <= Math.Max(startX, endX); ++x) + { + for (int y = Math.Min(startY, endY) + 1; y <= Math.Max(startY, endY); ++y) + { + if (Context.CompList.InBounds(x, y)) + { + add.Add((_dirt, x, y, z + _floorAbove)); + } + } + } + + return (remove, add); + } + } + + /// + /// Puts a door of the chosen style into the wall in the clicked cell, facing along the wall. + /// Clicking a door again turns it to its next hinge variant. + /// + internal sealed class DoorTool : PlaneDragTool + { + // Hinge variants per wall direction, in the order a click cycles through them. + private static readonly string[] _alongX = { "Piece3", "Piece1", "Piece4", "Piece2" }; + private static readonly string[] _alongY = { "Piece5", "Piece7", "Piece6", "Piece8" }; + + public DoorTool(IEditorContext context) : base(context) + { + } + + protected override HousePartKind Kind => HousePartKind.Door; + + protected override string ActionName => "Door"; + + /// + /// The hovered wall or door when there is one: a click on a wall means that wall, not the + /// floor cell behind it. + /// + protected override void BaseCell(out int x, out int y, out int z) + { + if (Context.HoverTile is { } hover && Context.HouseStyles.TryGetRole(hover.Id, out HouseStyle owner, out _) && + owner.Kind is HousePartKind.Wall or HousePartKind.Door) + { + (x, y, z) = (hover.X, hover.Y, hover.Z); + return; + } + + base.BaseCell(out x, out y, out z); + } + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final) + { + var remove = new List(); + var add = new List<(ushort, int, int, int)>(); + MultiEditorComponentList list = Context.CompList; + if (!list.InBounds(startX, startY)) + { + return (remove, add); + } + + // Default: a wall along X. A wall piece or door already in the cell decides the direction. + string[] variants = _alongX; + int next = 0; + foreach (MultiTile tile in list.GetTilesAt(startX, startY)) + { + if (tile.Z != z || !Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out string slot)) + { + continue; + } + + if (owner.Kind == HousePartKind.Door) + { + variants = WallPlanner.DoorAlongX(slot) ? _alongX : _alongY; + next = owner == Style ? (Array.IndexOf(variants, slot) + 1) % variants.Length : 0; + remove.Add(tile); + } + else if (owner.Kind == HousePartKind.Wall) + { + if (slot is "Corner" or "Post") + { + // No door fits a corner. + return (new List(), add); + } + + variants = slot.StartsWith("East", StringComparison.Ordinal) || slot.EndsWith('E') ? _alongY : _alongX; + remove.Add(tile); + } + } + + // Fall back to any piece the style has, in cycle order. + for (int i = 0; i < variants.Length; ++i) + { + ushort id = Style.Get(variants[(next + i) % variants.Length]); + if (id != 0) + { + add.Add((id, startX, startY, z)); + break; + } + } + + return (remove, add); + } + } + + /// + /// Places the chosen style's stair multi: press on the bottom step and drag the way the stairs + /// should climb (a click climbs north). The stairs rise one level (20). + /// + internal sealed class StairTool : PlaneDragTool + { + private const ushort _noDraw = 0x0001; + + public StairTool(IEditorContext context) : base(context) + { + } + + protected override HousePartKind Kind => HousePartKind.Stair; + + protected override string ActionName => "Stairs"; + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final) + { + var add = new List<(ushort, int, int, int)>(); + int dx = endX - startX; + int dy = endY - startY; + string column = Math.Abs(dx) > Math.Abs(dy) + ? (dx > 0 ? "MultiEast" : "MultiWest") + : (dy > 0 ? "MultiSouth" : "MultiNorth"); + + ushort multiId = Style.Get(column); + MultiComponentList stairs = multiId != 0 ? Multis.GetComponents(multiId) : MultiComponentList.Empty; + if (stairs == MultiComponentList.Empty || stairs.Width == 0) + { + return (new List(), add); + } + + // The lowest step goes under the cursor. + (int X, int Y) bottom = (0, 0); + int lowest = int.MaxValue; + for (int x = 0; x < stairs.Width; ++x) + { + for (int y = 0; y < stairs.Height; ++y) + { + int top = stairs.Tiles[x][y].Where(t => t.Id != _noDraw).Select(t => t.Z + TileData.ItemTable[t.Id].Height).DefaultIfEmpty(int.MaxValue).Max(); + if (top < lowest) + { + lowest = top; + bottom = (x, y); + } + } + } + + for (int x = 0; x < stairs.Width; ++x) + { + for (int y = 0; y < stairs.Height; ++y) + { + foreach (MTile tile in stairs.Tiles[x][y]) + { + if (tile.Id != _noDraw) + { + add.Add((tile.Id, startX + x - bottom.X, startY + y - bottom.Y, z + tile.Z)); + } + } + } + } + + return (new List(), add); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/LineTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/LineTool.cs new file mode 100644 index 00000000..bd417cf0 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/LineTool.cs @@ -0,0 +1,65 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Drag a line of draw tiles. Shift keeps it on the main axis. + /// + internal sealed class LineTool : CellDragTool + { + public LineTool(IEditorContext context) : base(context) + { + } + + protected override void Commit(int z) + { + var (ex, ey) = LineEnd(); + Context.CompList.TileAddLine(StartX, StartY, ex, ey, z, Context.DrawTileId, Replacing); + Context.RecordRecentTile(Context.DrawTileId); + Context.AfterEdit(z); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (!Dragging) + { + return; + } + + Context.CellAt(Context.MouseLoc, out _, out _, out int z); + var (ex, ey) = LineEnd(); + foreach (var (x, y) in MultiEditorComponentList.BresenhamLinePublic(StartX, StartY, ex, ey)) + { + overlay.Ghost(Context.DrawTileId, x, y, z); + } + } + + /// + /// The line end, kept on the dominant axis while Shift is held. + /// + private (int X, int Y) LineEnd() + { + if (!ShiftHeld) + { + return (EndX, EndY); + } + + return Math.Abs(EndX - StartX) >= Math.Abs(EndY - StartY) + ? (EndX, StartY) + : (StartX, EndY); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs new file mode 100644 index 00000000..c1ef7675 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs @@ -0,0 +1,136 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// A copied group of tiles, relative to its lowest X, Y and Z. The Dynamic flag and extra field + /// travel with each tile, so a paste matches what was copied. + /// + internal sealed record ClipboardTile(ushort Id, int Dx, int Dy, int Dz, bool Invisible, int Extra) + { + /// + /// Multi text lines (0xID x y z flag, as the TXT export writes them) with the extra + /// field appended, which the TXT import ignores. + /// + public static string Format(IEnumerable tiles) + { + var text = new StringBuilder(); + foreach (ClipboardTile t in tiles) + { + text.Append(CultureInfo.InvariantCulture, $"0x{t.Id:X4} {t.Dx} {t.Dy} {t.Dz} {(t.Invisible ? 0 : 1)} {t.Extra}").Append("\r\n"); + } + + return text.ToString(); + } + + /// + /// Reads multi text lines back, moved so the lowest X, Y and Z are 0. Returns null when any + /// non-empty line is not a tile line, so ordinary text on the clipboard is left alone. + /// + public static List Parse(string text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + + var tiles = new List(); + foreach (string raw in text.Split('\n')) + { + string line = raw.Trim(); + if (line.Length == 0) + { + continue; + } + + string[] parts = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length < 5 || parts.Length > 6) + { + return null; + } + + string idText = parts[0].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? parts[0][2..] : parts[0]; + if (!ushort.TryParse(idText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort id) || + !int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int x) || + !int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int y) || + !int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int z) || + !int.TryParse(parts[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out int flag)) + { + return null; + } + + int extra = 0; + if (parts.Length == 6 && !int.TryParse(parts[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out extra)) + { + return null; + } + + tiles.Add(new ClipboardTile(id, x, y, z, flag == 0, extra)); + } + + if (tiles.Count == 0) + { + return null; + } + + int minX = tiles.Min(t => t.Dx); + int minY = tiles.Min(t => t.Dy); + int minZ = tiles.Min(t => t.Dz); + return tiles.Select(t => t with { Dx = t.Dx - minX, Dy = t.Dy - minY, Dz = t.Dz - minZ }).ToList(); + } + } + + /// + /// Temporary tool after Ctrl+V: shows the clipboard under the cursor and places it on click. + /// Esc or a right click leaves it. + /// + internal sealed class PasteTool : EditorTool + { + private IReadOnlyList _tiles = new List(); + + public PasteTool(IEditorContext context) : base(context) + { + } + + public override bool TracksCursorCell => true; + + public void Begin(IReadOnlyList tiles) + { + _tiles = tiles; + } + + public override void OnMouseUp(MouseEventArgs e) + { + Context.CellAt(Context.MouseLoc, out int x, out int y, out int z); + Context.CompList.TileAddBatch(_tiles.Select(t => (t.Id, x + t.Dx, y + t.Dy, z + t.Dz, t.Invisible, t.Extra)).ToList()); + Context.AfterEdit(); + Context.EndTemporaryTool(); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + Context.CellAt(Context.MouseLoc, out int x, out int y, out int z); + foreach (ClipboardTile tile in _tiles) + { + overlay.Ghost(tile.Id, x + tile.Dx, y + tile.Dy, z + tile.Dz); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs new file mode 100644 index 00000000..323adc08 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs @@ -0,0 +1,145 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Base for the House tab tools. A press picks a cell and a base Z; dragging follows the cell + /// under the mouse on that Z's plane. The preview shows exactly what releasing would change. + /// + internal abstract class PlaneDragTool : EditorTool + { + private bool _dragging; + private int _z; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + + protected PlaneDragTool(IEditorContext context) : base(context) + { + } + + public override bool IsDragging => _dragging; + + public override bool TracksCursorCell => true; + + /// The House tab style this tool works with, when it is the chosen one. + protected abstract HousePartKind Kind { get; } + + protected HouseStyle Style => Context.HouseStyle?.Kind == Kind ? Context.HouseStyle : null; + + /// The edit's name in the undo list. + protected abstract string ActionName { get; } + + public override void OnMouseDown(MouseEventArgs e) + { + if (Style == null) + { + return; + } + + BaseCell(out _startX, out _startY, out _z); + _endX = _startX; + _endY = _startY; + _dragging = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (_dragging) + { + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + var (remove, add) = Plan(_startX, _startY, _endX, _endY, _z, final: true); + if (remove.Count > 0 || add.Count > 0) + { + Context.CompList.ReplaceTiles(remove, add, ActionName); + Context.AfterEdit(_z); + } + } + + public override void Cancel() + { + _dragging = false; + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (Style == null) + { + return; + } + + int sx, sy, ex, ey, z; + if (_dragging) + { + (sx, sy, ex, ey, z) = (_startX, _startY, _endX, _endY, _z); + } + else + { + BaseCell(out sx, out sy, out z); + (ex, ey) = (sx, sy); + } + + var (remove, add) = Plan(sx, sy, ex, ey, z, final: false); + foreach (MultiTile tile in remove) + { + overlay.Highlight(tile, TileHighlight.Remove); + } + + foreach (var (id, x, y, tz) in add) + { + overlay.Ghost(id, x, y, tz); + } + } + + /// + /// What releasing the mouse would change. is true for the real edit. + /// + protected abstract (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final); + + /// + /// The cell under the mouse and the base Z: the work plane, the hovered tall tile's own Z + /// (to stay on its level), or the top of the hovered flat tile. + /// + protected virtual void BaseCell(out int x, out int y, out int z) + { + Context.CellAt(Context.MouseLoc, out x, out y, out z); + if (Context.WorkZ is { } baseZ) + { + z = baseZ; + Context.PlaneCell(Context.MouseLoc, z, out x, out y); + } + else if (Context.HoverTile is { } hover && hover.Height >= 10) + { + z = hover.Z; + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/RectFillTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/RectFillTool.cs new file mode 100644 index 00000000..86f4771e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/RectFillTool.cs @@ -0,0 +1,51 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Drawing; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Drag a rectangle to fill it with the draw tile. + /// + internal sealed class RectFillTool : CellDragTool + { + public RectFillTool(IEditorContext context) : base(context) + { + } + + protected override void Commit(int z) + { + var (x0, y0, x1, y1) = Bounds; + Context.CompList.TileAddRect(x0, y0, x1, y1, z, Context.DrawTileId, Replacing); + Context.RecordRecentTile(Context.DrawTileId); + Context.AfterEdit(z); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (!Dragging) + { + return; + } + + Context.CellAt(Context.MouseLoc, out _, out _, out int z); + var (x0, y0, x1, y1) = Bounds; + for (int x = x0; x <= x1; x++) + { + for (int y = y0; y <= y1; y++) + { + overlay.Ghost(Context.DrawTileId, x, y, z); + } + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/RemoveTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/RemoveTool.cs new file mode 100644 index 00000000..05405d15 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/RemoveTool.cs @@ -0,0 +1,67 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Drawing; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Click removes the hovered tile. Dragging removes every shown tile in the rectangle between + /// the work plane (once a floor is chosen or it was moved) and the height slider. + /// + internal sealed class RemoveTool : CellDragTool + { + public RemoveTool(IEditorContext context) : base(context) + { + } + + private int MinZ => Context.WorkZ ?? sbyte.MinValue; + + protected override void Commit(int z) + { + if (EndX != StartX || EndY != StartY) + { + var (x0, y0, x1, y1) = Bounds; + Context.CompList.TileRemoveRect(x0, y0, x1, y1, MinZ, Context.MaxHeight); + } + else if (Context.HoverTile != null) + { + Context.CompList.TileRemove(Context.HoverTile); + } + + Context.AfterEdit(); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (!Dragging) + { + return; + } + + var (x0, y0, x1, y1) = Bounds; + for (int x = x0; x <= x1; ++x) + { + for (int y = y0; y <= y1; ++y) + { + foreach (MultiTile tile in Context.CompList.GetTilesAt(x, y)) + { + if (tile.Z >= MinZ && tile.Z <= Context.MaxHeight && Context.CompList.IsShown(tile)) + { + overlay.Highlight(tile, TileHighlight.Remove); + } + } + } + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/SelectTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/SelectTool.cs new file mode 100644 index 00000000..1afc6312 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/SelectTool.cs @@ -0,0 +1,153 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Click selects the hovered tile, Ctrl+click toggles it, dragging over empty space selects + /// every tile the box touches (Ctrl+drag adds to the selection). Dragging a selected tile + /// moves the whole selection. + /// + internal sealed class SelectTool : EditorTool + { + private bool _marquee; + private Point _start; + private Point _end; + + private MultiTile _moveAnchor; + private int _moveDx; + private int _moveDy; + + public SelectTool(IEditorContext context) : base(context) + { + } + + public override bool IsDragging => _marquee || _moveAnchor != null; + + public override void OnMouseDown(MouseEventArgs e) + { + MultiTile hover = Context.HoverTile; + if (hover != null && !CtrlHeld && Context.Selection.Contains(hover)) + { + _moveAnchor = hover; + _start = Context.MouseLoc; + _moveDx = _moveDy = 0; + } + else if (hover == null && !CtrlHeld) + { + _marquee = true; + _start = _end = Context.MouseLoc; + } + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (_moveAnchor != null) + { + // Measured on the anchor tile's own height, so the tile stays under the cursor. + Context.PlaneCell(_start, _moveAnchor.Z, out int x0, out int y0); + Context.PlaneCell(Context.MouseLoc, _moveAnchor.Z, out int x1, out int y1); + _moveDx = x1 - x0; + _moveDy = y1 - y0; + } + else if (_marquee) + { + // Same zoom-aware space as the tiles, so the rectangle selects what it covers. + _end = Context.MouseLoc; + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + MultiTile hover = Context.HoverTile; + MultiTile[] hovered = hover != null ? new[] { hover } : Array.Empty(); + + if (_moveAnchor != null) + { + _moveAnchor = null; + if (_moveDx != 0 || _moveDy != 0) + { + Context.CompList.TileMoveBatch(Context.Selection.ToList(), _moveDx, _moveDy, 0, "Move Selection"); + Context.AfterEdit(); + return; + } + + // No movement: an ordinary click on a selected tile. + Context.SetSelection(hovered, add: false); + } + else if (_marquee) + { + _marquee = false; + Rectangle rect = MarqueeRect(); + if (rect.Width > 3 && rect.Height > 3) + { + Context.SetSelection( + Context.TilesInRect(rect), + add: CtrlHeld); + } + else + { + // Tiny drag: a plain click. + Context.SetSelection(hovered, add: CtrlHeld); + } + } + else if (CtrlHeld && hover != null) + { + Context.ToggleSelected(hover); + } + else + { + Context.SetSelection(hovered, add: false); + } + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (_moveAnchor != null && (_moveDx != 0 || _moveDy != 0)) + { + foreach (MultiTile tile in Context.Selection) + { + overlay.Ghost(tile.Id, tile.X + _moveDx, tile.Y + _moveDy, tile.Z); + } + + return; + } + + if (!_marquee) + { + return; + } + + overlay.Marquee(MarqueeRect()); + } + + public override void Cancel() + { + _marquee = false; + _moveAnchor = null; + } + + private Rectangle MarqueeRect() + { + return new Rectangle( + Math.Min(_start.X, _end.X) - Context.ScrollX, + Math.Min(_start.Y, _end.Y) - Context.ScrollY, + Math.Abs(_end.X - _start.X), + Math.Abs(_end.Y - _start.Y)); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs new file mode 100644 index 00000000..7875ef69 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs @@ -0,0 +1,77 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Adds the Z step to the hovered tile, or to the whole selection when several are selected. + /// + internal sealed class AltitudeTool : EditorTool + { + public AltitudeTool(IEditorContext context) : base(context) + { + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (Context.Selection.Count > 1) + { + Context.CompList.TileZMod(Context.Selection, Context.ZStep); + Context.AfterEdit(); + } + else if (Context.HoverTile != null) + { + MultiTile tile = Context.HoverTile; + Context.CompList.TileZMod(tile, Context.ZStep); + Context.AfterEdit(tile.Z); + } + } + } + + /// + /// Makes the hovered tile the draw tile. + /// + internal sealed class PipetteTool : EditorTool + { + public PipetteTool(IEditorContext context) : base(context) + { + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (Context.HoverTile != null) + { + Context.SetDrawTile(Context.HoverTile.Id); + } + } + } + + /// + /// Shows the hovered tile see-through, to reach what is behind it. View only, not saved. + /// + internal sealed class TransparentTool : EditorTool + { + public TransparentTool(IEditorContext context) : base(context) + { + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (Context.HoverTile != null) + { + Context.HoverTile.Transparent = !Context.HoverTile.Transparent; + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/WallTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/WallTool.cs new file mode 100644 index 00000000..ae24f669 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/WallTool.cs @@ -0,0 +1,41 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Collections.Generic; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Draws walls of the chosen wall style. Dragging a rectangle walls in a room (the rectangle + /// is the outer wall cells); dragging along a row or column, or with Shift, draws one straight + /// wall. Ctrl erases walls of the style instead. Corners, posts and piece variants are chosen + /// from the surrounding walls, and existing windows and doors are kept. + /// + internal sealed class WallTool : PlaneDragTool + { + public WallTool(IEditorContext context) : base(context) + { + } + + protected override HousePartKind Kind => HousePartKind.Wall; + + protected override string ActionName => CtrlHeld ? "Erase Walls" : "Draw Walls"; + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( + int startX, int startY, int endX, int endY, int z, bool final) + { + var planner = new WallPlanner(Context.CompList, Context.HouseStyles, Style, z); + var (south, east) = WallPlanner.DragEdges(startX, startY, endX, endY, ShiftHeld); + return planner.Plan(south, east, CtrlHeld, Context.CompList.Width, Context.CompList.Height); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.Designer.cs new file mode 100644 index 00000000..c83b734c --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.Designer.cs @@ -0,0 +1,262 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class DesignLibraryPanel + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + _list = new System.Windows.Forms.ListView(); + columnDesign = new System.Windows.Forms.ColumnHeader(); + columnSize = new System.Windows.Forms.ColumnHeader(); + columnItems = new System.Windows.Forms.ColumnHeader(); + treeSplitter = new GripSplitter(); + _tree = new System.Windows.Forms.TreeView(); + previewSplitter = new GripSplitter(); + _preview = new System.Windows.Forms.PictureBox(); + _info = new System.Windows.Forms.Label(); + buttons = new System.Windows.Forms.FlowLayoutPanel(); + _open = new System.Windows.Forms.Button(); + _place = new System.Windows.Forms.Button(); + _filter = new System.Windows.Forms.TextBox(); + bar = new System.Windows.Forms.ToolStrip(); + chooseButton = new System.Windows.Forms.ToolStripButton(); + refreshButton = new System.Windows.Forms.ToolStripButton(); + _folderLabel = new System.Windows.Forms.ToolStripLabel(); + _previewTimer = new System.Windows.Forms.Timer(components); + ((System.ComponentModel.ISupportInitialize)_preview).BeginInit(); + buttons.SuspendLayout(); + bar.SuspendLayout(); + SuspendLayout(); + // + // _list + // + _list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnDesign, columnSize, columnItems }); + _list.Dock = System.Windows.Forms.DockStyle.Fill; + _list.FullRowSelect = true; + _list.Location = new System.Drawing.Point(0, 225); + _list.Name = "_list"; + _list.Size = new System.Drawing.Size(150, 0); + _list.TabIndex = 0; + _list.UseCompatibleStateImageBehavior = false; + _list.View = System.Windows.Forms.View.Details; + _list.VirtualMode = true; + _list.RetrieveVirtualItem += List_RetrieveVirtualItem; + _list.SelectedIndexChanged += List_SelectedIndexChanged; + _list.VirtualItemsSelectionRangeChanged += List_VirtualItemsSelectionRangeChanged; + _list.DoubleClick += List_DoubleClick; + _list.KeyDown += List_KeyDown; + // + // columnDesign + // + columnDesign.Text = "Design"; + columnDesign.Width = 170; + // + // columnSize + // + columnSize.Text = "Size"; + // + // columnItems + // + columnItems.Text = "Items"; + columnItems.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + columnItems.Width = 56; + // + // treeSplitter + // + treeSplitter.Dock = System.Windows.Forms.DockStyle.Top; + treeSplitter.Location = new System.Drawing.Point(0, 218); + treeSplitter.MinExtra = 80; + treeSplitter.MinSize = 60; + treeSplitter.Name = "treeSplitter"; + treeSplitter.Size = new System.Drawing.Size(150, 7); + treeSplitter.TabIndex = 1; + treeSplitter.TabStop = false; + // + // _tree + // + _tree.Dock = System.Windows.Forms.DockStyle.Top; + _tree.HideSelection = false; + _tree.Location = new System.Drawing.Point(0, 48); + _tree.Name = "_tree"; + _tree.Size = new System.Drawing.Size(150, 170); + _tree.TabIndex = 2; + _tree.AfterSelect += Tree_AfterSelect; + // + // previewSplitter + // + previewSplitter.Dock = System.Windows.Forms.DockStyle.Bottom; + previewSplitter.Location = new System.Drawing.Point(0, -143); + previewSplitter.MinExtra = 80; + previewSplitter.MinSize = 80; + previewSplitter.Name = "previewSplitter"; + previewSplitter.Size = new System.Drawing.Size(150, 7); + previewSplitter.TabIndex = 3; + previewSplitter.TabStop = false; + // + // _preview + // + _preview.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _preview.Dock = System.Windows.Forms.DockStyle.Bottom; + _preview.Location = new System.Drawing.Point(0, -136); + _preview.Name = "_preview"; + _preview.Size = new System.Drawing.Size(150, 220); + _preview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + _preview.TabIndex = 4; + _preview.TabStop = false; + // + // _info + // + _info.AutoEllipsis = true; + _info.Dock = System.Windows.Forms.DockStyle.Bottom; + _info.ForeColor = System.Drawing.SystemColors.GrayText; + _info.Location = new System.Drawing.Point(0, 84); + _info.Name = "_info"; + _info.Size = new System.Drawing.Size(150, 34); + _info.TabIndex = 5; + // + // buttons + // + buttons.Controls.Add(_open); + buttons.Controls.Add(_place); + buttons.Dock = System.Windows.Forms.DockStyle.Bottom; + buttons.Location = new System.Drawing.Point(0, 118); + buttons.Name = "buttons"; + buttons.Size = new System.Drawing.Size(150, 32); + buttons.TabIndex = 6; + // + // _open + // + _open.Enabled = false; + _open.Location = new System.Drawing.Point(3, 3); + _open.Name = "_open"; + _open.Size = new System.Drawing.Size(130, 26); + _open.TabIndex = 0; + _open.Text = "Open in a new tab"; + _open.UseVisualStyleBackColor = true; + _open.Click += Open_Click; + // + // _place + // + _place.Enabled = false; + _place.Location = new System.Drawing.Point(3, 35); + _place.Name = "_place"; + _place.Size = new System.Drawing.Size(130, 26); + _place.TabIndex = 1; + _place.Text = "Place in this multi"; + _place.UseVisualStyleBackColor = true; + _place.Click += Place_Click; + // + // _filter + // + _filter.Dock = System.Windows.Forms.DockStyle.Top; + _filter.Location = new System.Drawing.Point(0, 25); + _filter.Name = "_filter"; + _filter.PlaceholderText = "Filter designs by name"; + _filter.Size = new System.Drawing.Size(150, 23); + _filter.TabIndex = 7; + _filter.TextChanged += Filter_TextChanged; + // + // bar + // + bar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + bar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { chooseButton, refreshButton, _folderLabel }); + bar.Location = new System.Drawing.Point(0, 0); + bar.Name = "bar"; + bar.Size = new System.Drawing.Size(150, 25); + bar.TabIndex = 8; + // + // chooseButton + // + chooseButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + chooseButton.Name = "chooseButton"; + chooseButton.Size = new System.Drawing.Size(53, 22); + chooseButton.Text = "Folder..."; + chooseButton.ToolTipText = "Choose the folder that holds the UO Architect designs (.uoa files, also in subfolders)"; + chooseButton.Click += ChooseButton_Click; + // + // refreshButton + // + refreshButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + refreshButton.Name = "refreshButton"; + refreshButton.Size = new System.Drawing.Size(50, 22); + refreshButton.Text = "Refresh"; + refreshButton.ToolTipText = "Read the folder again"; + refreshButton.Click += RefreshButton_Click; + // + // _folderLabel + // + _folderLabel.ForeColor = System.Drawing.SystemColors.GrayText; + _folderLabel.Name = "_folderLabel"; + _folderLabel.Size = new System.Drawing.Size(0, 22); + // + // _previewTimer + // + _previewTimer.Interval = 180; + _previewTimer.Tick += PreviewTimer_Tick; + // + // DesignLibraryPanel + // + Controls.Add(_list); + Controls.Add(treeSplitter); + Controls.Add(_tree); + Controls.Add(previewSplitter); + Controls.Add(_preview); + Controls.Add(_info); + Controls.Add(buttons); + Controls.Add(_filter); + Controls.Add(bar); + Name = "DesignLibraryPanel"; + ((System.ComponentModel.ISupportInitialize)_preview).EndInit(); + buttons.ResumeLayout(false); + bar.ResumeLayout(false); + bar.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.ListView _list; + private System.Windows.Forms.ColumnHeader columnDesign; + private System.Windows.Forms.ColumnHeader columnSize; + private System.Windows.Forms.ColumnHeader columnItems; + private UoFiddler.Plugin.MultiEditor.UI.GripSplitter treeSplitter; + private System.Windows.Forms.TreeView _tree; + private UoFiddler.Plugin.MultiEditor.UI.GripSplitter previewSplitter; + private System.Windows.Forms.PictureBox _preview; + private System.Windows.Forms.Label _info; + private System.Windows.Forms.FlowLayoutPanel buttons; + private System.Windows.Forms.Button _open; + private System.Windows.Forms.Button _place; + private System.Windows.Forms.TextBox _filter; + private System.Windows.Forms.ToolStrip bar; + private System.Windows.Forms.ToolStripButton chooseButton; + private System.Windows.Forms.ToolStripButton refreshButton; + private System.Windows.Forms.ToolStripLabel _folderLabel; + private System.Windows.Forms.Timer _previewTimer; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.cs b/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.cs new file mode 100644 index 00000000..1859cbca --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.cs @@ -0,0 +1,368 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// A library of UO Architect designs: every .uoa file (single designs and batches) and design + /// set (Designs.idx + .bin) under a folder, listed by the category and subsection stored in + /// them, with a filter and a preview. A design can be opened as a new multi or placed into + /// the one being edited. + /// + internal sealed partial class DesignLibraryPanel : UserControl + { + /// Designs with more items than this are not drawn as a preview on selection: it would stall the list. + private const int _previewLimit = 8000; + + private const int _previewSize = 220; + + private readonly List _all = new List(); + private readonly List _shown = new List(); + private bool _loaded; + + /// The category and subsection chosen in the tree; null means any. + private string _category; + private string _subsection; + + public DesignLibraryPanel() + { + InitializeComponent(); + + Disposed += DesignLibraryPanel_Disposed; + } + + private void DesignLibraryPanel_Disposed(object sender, EventArgs e) + { + // The timer is disposed with the designer's components; the preview image is ours. + _preview.Image?.Dispose(); + } + + private void ChooseButton_Click(object sender, EventArgs e) + { + ChooseFolder(); + } + + private void RefreshButton_Click(object sender, EventArgs e) + { + LoadLibrary(); + } + + private void Filter_TextChanged(object sender, EventArgs e) + { + RebuildList(); + } + + private void Tree_AfterSelect(object sender, TreeViewEventArgs e) + { + (_category, _subsection) = e.Node?.Tag is ValueTuple key ? key : (null, null); + RebuildList(); + } + + private void List_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) + { + UoaDesign design = _shown[e.ItemIndex]; + e.Item = new ListViewItem(DocumentIO.DesignTitle(design)); + e.Item.SubItems.Add($"{design.Width}x{design.Height}"); + e.Item.SubItems.Add(design.ItemCount.ToString("N0")); + } + + private void List_SelectedIndexChanged(object sender, EventArgs e) + { + OnSelectionChanged(); + } + + // Shift ranges in a virtual list. + private void List_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e) + { + OnSelectionChanged(); + } + + private void List_DoubleClick(object sender, EventArgs e) + { + RaiseOpen(); + } + + private void List_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + RaiseOpen(); + e.Handled = e.SuppressKeyPress = true; + } + } + + private void Open_Click(object sender, EventArgs e) + { + RaiseOpen(); + } + + private void Place_Click(object sender, EventArgs e) + { + if (Selected is { } design) + { + PlaceRequested?.Invoke(design); + } + } + + private void PreviewTimer_Tick(object sender, EventArgs e) + { + _previewTimer.Stop(); + ShowPreview(); + } + + /// Open the designs, each as a new multi. + public event Action> OpenRequested; + + /// Place the design into the multi being edited. + public event Action PlaceRequested; + + private List SelectedDesigns + { + get + { + var designs = new List(); + foreach (int index in _list.SelectedIndices) + { + if (index < _shown.Count) + { + designs.Add(_shown[index]); + } + } + + return designs; + } + } + + private UoaDesign Selected => _list.SelectedIndices.Count > 0 && _list.SelectedIndices[0] < _shown.Count ? _shown[_list.SelectedIndices[0]] : null; + + /// A design's tiles for pasting: from the lowest X, Y and Z of its items. + public static List ToTiles(MultiComponentList multi) + { + var tiles = new List(multi.SortedTiles.Length); + if (multi.SortedTiles.Length == 0) + { + return tiles; + } + + int minX = multi.SortedTiles.Min(t => t.OffsetX), minY = multi.SortedTiles.Min(t => t.OffsetY), minZ = multi.SortedTiles.Min(t => t.OffsetZ); + foreach (MultiComponentList.MultiTileEntry tile in multi.SortedTiles) + { + tiles.Add(new ClipboardTile(tile.ItemId, tile.OffsetX - minX, tile.OffsetY - minY, tile.OffsetZ - minZ, false, 0)); + } + + return tiles; + } + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + if (Visible && !_loaded) + { + LoadLibrary(); + } + } + + private void ChooseFolder() + { + using var dialog = new FolderBrowserDialog + { + Description = "Folder with UO Architect designs (.uoa)", + UseDescriptionForTitle = true, + SelectedPath = EditorSettings.Current.DesignLibraryFolder + }; + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + EditorSettings settings = EditorSettings.Current.Clone(); + settings.DesignLibraryFolder = dialog.SelectedPath; + settings.Apply(); + LoadLibrary(); + } + + /// Reads the header of every design under the folder. The items are only read when a design is used. + private void LoadLibrary() + { + _loaded = true; + _all.Clear(); + string folder = EditorSettings.Current.DesignLibraryFolder; + _folderLabel.Text = string.IsNullOrEmpty(folder) ? "no folder chosen" : folder; + _folderLabel.ToolTipText = folder; + + if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder)) + { + Cursor previous = Cursor.Current; + Cursor.Current = Cursors.WaitCursor; + try + { + foreach (string pattern in new[] { "*.uoa", "*.idx" }) + { + foreach (string file in Directory.EnumerateFiles(folder, pattern, SearchOption.AllDirectories)) + { + // An .idx counts only with its .bin: other tools use the extension too. + if (pattern == "*.idx" && !File.Exists(Path.ChangeExtension(file, ".bin"))) + { + continue; + } + + _all.AddRange(UoaDesignFile.ReadHeaders(file).Where(d => d.ItemCount > 0)); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // What could be read is listed. + } + finally + { + Cursor.Current = previous; + } + } + + RebuildTree(); + RebuildList(); + } + + private static string CategoryOf(UoaDesign design) => string.IsNullOrWhiteSpace(design.Category) ? "(no category)" : design.Category.Trim(); + + private static string SubsectionOf(UoaDesign design) => string.IsNullOrWhiteSpace(design.Subsection) ? "(none)" : design.Subsection.Trim(); + + private void RebuildTree() + { + _tree.BeginUpdate(); + try + { + _tree.Nodes.Clear(); + _category = _subsection = null; + var root = new TreeNode($"All designs ({_all.Count:N0})") { Tag = ((string)null, (string)null) }; + _tree.Nodes.Add(root); + foreach (IGrouping category in _all.GroupBy(CategoryOf).OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase)) + { + var node = new TreeNode($"{category.Key} ({category.Count():N0})") { Tag = (category.Key, (string)null) }; + List> subsections = category.GroupBy(SubsectionOf).OrderBy(g => g.Key, StringComparer.OrdinalIgnoreCase).ToList(); + if (subsections.Count > 1) + { + foreach (IGrouping subsection in subsections) + { + node.Nodes.Add(new TreeNode($"{subsection.Key} ({subsection.Count():N0})") { Tag = (category.Key, subsection.Key) }); + } + } + + root.Nodes.Add(node); + } + + root.Expand(); + _tree.SelectedNode = root; + } + finally + { + _tree.EndUpdate(); + } + } + + private void RebuildList() + { + string filter = _filter.Text.Trim(); + _shown.Clear(); + foreach (UoaDesign design in _all) + { + if ((_category == null || CategoryOf(design) == _category) && + (_subsection == null || SubsectionOf(design) == _subsection) && + (filter.Length == 0 || DocumentIO.DesignTitle(design).Contains(filter, StringComparison.OrdinalIgnoreCase))) + { + _shown.Add(design); + } + } + + _shown.Sort((a, b) => string.Compare(DocumentIO.DesignTitle(a), DocumentIO.DesignTitle(b), StringComparison.OrdinalIgnoreCase)); + _list.SelectedIndices.Clear(); + _list.VirtualListSize = _shown.Count; + _list.Invalidate(); + OnSelectionChanged(); + } + + private void OnSelectionChanged() + { + UoaDesign design = Selected; + int count = _list.SelectedIndices.Count; + _open.Enabled = design != null; + _open.Text = count > 1 ? $"Open {count} in tabs" : "Open in a new tab"; + + // Placing is a paste under the cursor: one design at a time. + _place.Enabled = count == 1; + if (design == null) + { + SetPreview(null); + _info.Text = _all.Count == 0 + ? "Choose a folder with UO Architect designs (.uoa files)." + : $"{_shown.Count:N0} designs"; + return; + } + + _info.Text = count > 1 + ? $"{count} designs selected: each opens in its own tab" + : $"{CategoryOf(design)} / {SubsectionOf(design)}\r\n{Path.GetFileName(design.FileName)}"; + _previewTimer.Stop(); + _previewTimer.Start(); + } + + private void ShowPreview() + { + UoaDesign design = Selected; + if (design == null) + { + return; + } + + if (design.ItemCount > _previewLimit) + { + SetPreview(null); + _info.Text = $"{design.ItemCount:N0} items: too large to preview here. Open it to see it."; + return; + } + + try + { + MultiComponentList multi = UoaDesignFile.Load(design); + SetPreview(multi == MultiComponentList.Empty ? null : Prefabs.Thumbnail(ToTiles(multi), _previewSize)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + SetPreview(null); + } + } + + private void SetPreview(Image image) + { + Image old = _preview.Image; + _preview.Image = image; + old?.Dispose(); + } + + private void RaiseOpen() + { + List designs = SelectedDesigns; + if (designs.Count > 0) + { + OpenRequested?.Invoke(designs); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.resx b/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.resx new file mode 100644 index 00000000..ca91a2d4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DesignLibraryPanel.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 88, 17 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs b/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs new file mode 100644 index 00000000..b2b5ebbd --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs @@ -0,0 +1,456 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Windows.Forms; +using System.Xml; +using Ultima; +using UoFiddler.Controls.Classes; +using UoFiddler.Controls.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// What an open/import produced. + internal sealed record OpenedMulti(MultiComponentList Components, string Title, int? ClientId); + + /// What an import read, and what it could not. + internal sealed record ImportResult(List Opened, List Failures); + + /// Open, import, export, save-to-client and map-extract dialogs of the multi editor. + internal static class DocumentIO + { + private const string _caption = "Multi Editor"; + + private static readonly (Multis.ImportType Type, string Extension, string Description)[] _exportTypes = + { + // Every format that can be imported, in the import dialog's order. + (Multis.ImportType.TXT, "txt", "Multi text"), + (Multis.ImportType.UOA, "uoa.txt", "UO Architect text"), + (Multis.ImportType.UOAB, "uoa", "UOA binary file"), + (Multis.ImportType.WSC, "wsc", "WSC"), + (Multis.ImportType.MULTICACHE, "dat", "MultiCache file"), + (Multis.ImportType.UOADESIGN, "idx", "UOA design files, idx + bin"), + (Multis.ImportType.CSV, "csv", "CSV"), + (Multis.ImportType.UOX3, "uox3", "UOX3"), + (Multis.ImportType.XML, "xml", "XML"), + (Multis.ImportType.UOH, "uoh", "UO House Editor design"), + (Multis.ImportType.WORLDFORGE, "xml", "WorldForge export"), + (Multis.ImportType.MULTIFORGE, "txt", "Multiforge text (POL)") + }; + + /// + /// Lists the client's multis (multi.mul and the UOP collection when present) and returns the chosen one. + /// Null when cancelled. + /// + public static List OpenFromClient(IWin32Window owner) + { + Dictionary names = LoadNames(); + var entries = new List(); + + Cursor previous = Cursor.Current; + Cursor.Current = Cursors.WaitCursor; + try + { + for (int i = 0; i < Multis.MaximumMultiIndex; ++i) + { + MultiComponentList comp = Multis.GetComponents(i); + if (comp != MultiComponentList.Empty) + { + entries.Add(new MultiPickEntry(i, NameFor(names, i), "multi.mul", comp)); + } + } + + if (Multis.HasUopFile) + { + for (int i = 0; i < Multis.MaximumMultiIndex; ++i) + { + MultiComponentList comp = Multis.GetUopComponents(i); + if (comp != MultiComponentList.Empty) + { + entries.Add(new MultiPickEntry(i, NameFor(names, i), "UOP", comp)); + } + } + } + } + finally + { + Cursor.Current = previous; + } + + if (entries.Count == 0) + { + MessageBox.Show(owner, "The client has no multis loaded.", _caption, MessageBoxButtons.OK, MessageBoxIcon.Information); + return null; + } + + return Pick(owner, "Open multi from client", entries, true, true).ConvertAll(p => new OpenedMulti(p.Components, p.Name, p.Id)); + } + + /// + /// Asks for one or more files of a supported import type and reads them. A file that fails + /// is skipped and listed in the result; the multis of files that hold several are chosen + /// from a list. Null when cancelled. + /// + public static ImportResult ImportFromFile(IWin32Window owner) + { + var filters = new List(); + foreach ((_, string description, string pattern) in MultiFileImport.Formats) + { + filters.Add($"{description} ({pattern})|{pattern}"); + } + + using var dialog = new OpenFileDialog + { + Title = "Import multis from files", + Multiselect = true, + CheckFileExists = true, + Filter = string.Join("|", filters), + FilterIndex = 1 + }; + + if (dialog.ShowDialog(owner) != DialogResult.OK) + { + return null; + } + + // Formats share extensions, so the type is the selected filter entry's, for every file. + Multis.ImportType type = MultiFileImport.Formats[dialog.FilterIndex - 1].Type; + string[] files = dialog.FileNames; + var opened = new List(); + var failures = new List(); + var choices = new List(); + + Cursor previous = Cursor.Current; + Cursor.Current = Cursors.WaitCursor; + try + { + foreach (string file in files) + { + List multis; + try + { + multis = MultiFileImport.Load(file, type); + } + catch (Exception ex) + { + failures.Add(new ImportFailure(file, MultiFileImport.Reason(ex))); + continue; + } + + foreach (ImportedMulti multi in multis) + { + MultiComponentList components; + try + { + components = multi.Components; + } + catch (Exception ex) + { + failures.Add(new ImportFailure(file, $"{multi.Name}: {MultiFileImport.Reason(ex)}")); + continue; + } + + if (multis.Count == 1) + { + opened.Add(new OpenedMulti(components, multi.Name, null)); + } + else + { + choices.Add(new MultiPickEntry(null, multi.Name, Path.GetFileName(file), components)); + } + } + } + } + finally + { + Cursor.Current = previous; + } + + // Files holding several multis (MultiCache, UOA batches and design sets) share one list. + if (choices.Count > 0) + { + string title = files.Length == 1 ? $"Choose multis from {Path.GetFileName(files[0])}" : "Choose multis to import"; + opened.AddRange(Pick(owner, title, choices, files.Length > 1, false).ConvertAll(p => new OpenedMulti(p.Components, p.Name, null))); + } + + return new ImportResult(opened, failures); + } + + /// Lists the multis in every supported file under a folder and returns the chosen ones. Null when cancelled. + public static ImportResult ImportFromFolder(IWin32Window owner) + { + using var dialog = new FolderImportDialog(); + return dialog.ShowDialog(owner) == DialogResult.OK ? new ImportResult(dialog.Opened, dialog.Failures) : null; + } + + /// A UO Architect design as an opened multi, named after the design (or its file). Null when it holds no items. + public static OpenedMulti FromDesign(UoaDesign design) + { + MultiComponentList multi = UoaDesignFile.Load(design); + return multi == MultiComponentList.Empty ? null : new OpenedMulti(multi, DesignTitle(design), null); + } + + public static string DesignTitle(UoaDesign design) + { + return string.IsNullOrWhiteSpace(design.Name) ? Path.GetFileNameWithoutExtension(design.FileName) : design.Name.Trim(); + } + + /// Asks for a file name and format and writes the design. True when written. + /// Z of the design's first floor, written as the base height of a UO House Editor design. + public static bool ExportToFile(IWin32Window owner, MultiEditorComponentList list, string suggestedName, int firstFloorZ = 7) + { + if (list == null) + { + return false; + } + + var filters = new List(); + foreach ((_, string extension, string description) in _exportTypes) + { + filters.Add($"{description} (*.{extension})|*.{extension}"); + } + + filters.Add("All files (*.*)|*.*"); + + string designName = (suggestedName ?? string.Empty).Trim(); + using var dialog = new SaveFileDialog + { + Title = "Export multi", + InitialDirectory = Options.OutputPath, + FileName = designName.Length > 0 ? designName : "multi", + Filter = string.Join("|", filters), + FilterIndex = 1, + OverwritePrompt = true + }; + + if (dialog.ShowDialog(owner) != DialogResult.OK) + { + return false; + } + + // The "All files" entry has no format of its own; fall back to the first one (text). + int index = dialog.FilterIndex <= _exportTypes.Length ? dialog.FilterIndex - 1 : 0; + (Multis.ImportType type, string ext, _) = _exportTypes[index]; + + string fileName = dialog.FileName; + if (string.IsNullOrEmpty(Path.GetExtension(fileName))) + { + fileName += "." + ext; + } + + if (designName.Length == 0) + { + // The XML entry is named after the design; take it from the file name. + designName = Path.GetFileNameWithoutExtension(fileName); + } + + try + { + MultiComponentList sdkList = list.ConvertToSdk(); + switch (type) + { + case Multis.ImportType.TXT: + sdkList.ExportToTextFile(fileName); + break; + case Multis.ImportType.WSC: + sdkList.ExportToWscFile(fileName); + break; + case Multis.ImportType.UOA: + sdkList.ExportToUOAFile(fileName); + break; + case Multis.ImportType.CSV: + sdkList.ExportToCsvFile(fileName); + break; + case Multis.ImportType.UOX3: + sdkList.ExportToUox3File(fileName); + break; + case Multis.ImportType.XML: + sdkList.ExportToXmlFile(fileName, designName); + break; + case Multis.ImportType.UOAB: + sdkList.ExportToUOABinaryFile(fileName, designName); + break; + case Multis.ImportType.MULTICACHE: + sdkList.ExportToCacheFile(fileName); + break; + case Multis.ImportType.UOADESIGN: + sdkList.ExportToDesignerFiles(fileName, designName); + break; + case Multis.ImportType.UOH: + sdkList.ExportToUohFile(fileName, firstFloorZ); + break; + case Multis.ImportType.WORLDFORGE: + sdkList.ExportToWorldForgeFile(fileName); + break; + case Multis.ImportType.MULTIFORGE: + sdkList.ExportToMultiforgeFile(fileName); + break; + } + } + catch (Exception ex) + { + MessageBox.Show(owner, $"Export failed: {ex.Message}", _caption, MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + + FileSavedDialog.Show(owner, fileName, "Multi design saved successfully."); + return true; + } + + /// + /// Asks for the multi id and stores the design into the client table. Returns the id, or null when cancelled. + /// + public static int? SaveToClient(IWin32Window owner, MultiEditorComponentList list, int? suggestedId) + { + if (list == null) + { + return null; + } + + // Every slot is listed, free ones marked, so a free slot can be picked without guessing ids. + using var dialog = new DocumentIOSaveDialog(LoadNames(), suggestedId); + if (dialog.ShowDialog(owner) != DialogResult.OK) + { + return null; + } + + list.AddToSdkComponentList(dialog.SelectedId); // marks Multis changed and fires MultiChangeEvent + if (dialog.WriteFormat is { } format) + { + WriteMultiFiles(owner, format); + } + + return dialog.SelectedId; + } + + /// + /// Writes the client's multi table to the output folder in the chosen container, the way the + /// Multis tab's Save does: first anything the save would cost is confirmed, then the files are + /// written and the result shown. + /// + private static void WriteMultiFiles(IWin32Window owner, Ultima.Uop.ContainerFormat format) + { + try + { + IReadOnlyList concerns = Ultima.Uop.ClientFileSaver.Preflight(Ultima.Uop.FileType.MultiCollection, format); + if (concerns.Count > 0 && MessageBox.Show(owner, string.Join("\r\n\r\n", concerns) + "\r\n\r\nSave anyway?", _caption, + MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) != DialogResult.Yes) + { + return; + } + + Ultima.Uop.ClientFileSaveResult result = WriteMultiTable(format); + string message = "Saved " + string.Join(", ", result.FilesWritten) + "."; + foreach (string warning in result.Warnings) + { + message += "\r\n\r\n" + warning; + } + + FileSavedDialog.Show(owner, Options.OutputPath, message); + } + catch (Exception ex) + { + // The slot is already set in memory, so nothing is lost: the Multis tab can still save it. + MessageBox.Show(owner, "The multi was put into its slot, but writing the file failed:\r\n" + ex.Message + + "\r\n\r\nYou can save it from the Multis tab.", _caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + /// Writes the multi table to and clears its unsaved mark. + internal static Ultima.Uop.ClientFileSaveResult WriteMultiTable(Ultima.Uop.ContainerFormat format) + { + Ultima.Uop.ClientFileSaveResult result = Ultima.Uop.ClientFileSaver.Save( + Ultima.Uop.FileType.MultiCollection, Options.OutputPath, format, Multis.Save); + Options.ChangedUltimaClass["Multis"] = false; + return result; + } + + /// + /// Asks for the map area (facet, position, size, Z range) and returns the statics in it as tiles to paste. + /// Null when cancelled or the area holds no statics. + /// + public static List ExtractFromMap(IWin32Window owner, Map map, Point location) + { + const int defaultSize = 16; + var initial = new MapArea(map ?? Map.Felucca, Math.Max(0, location.X - (defaultSize / 2)), Math.Max(0, location.Y - (defaultSize / 2)), + defaultSize, defaultSize, sbyte.MinValue, sbyte.MaxValue, false); + + // The caller pastes the tiles, so the "open as new design" choice is not offered. + MapArea area = MapExtract.Ask(owner, initial, canPlaceIntoDesign: false); + if (area == null) + { + return null; + } + + List tiles = MapExtract.Extract(area); + if (tiles.Count == 0) + { + MessageBox.Show(owner, "There are no statics in that area.", _caption, MessageBoxButtons.OK, MessageBoxIcon.Information); + return null; + } + + return tiles; + } + + /// The rows picked in the list (several with Ctrl or Shift); empty when cancelled. + private static List Pick(IWin32Window owner, string title, List entries, bool showSource, bool clientSources) + { + using var dialog = new DocumentIOPickDialog(title, entries, showSource, clientSources); + return dialog.ShowDialog(owner) == DialogResult.OK ? new List(dialog.SelectedEntries) : new List(); + } + + private static string NameFor(Dictionary names, int id) + { + return names.TryGetValue(id, out string name) && !string.IsNullOrWhiteSpace(name) ? name : $"Multi 0x{id:X4}"; + } + + /// Multi names from Multilist.xml in the app data folder, the same file the old editor's list reads. + private static Dictionary LoadNames() + { + var names = new Dictionary(); + try + { + string fileName = Path.Combine(Options.AppDataPath ?? string.Empty, "Multilist.xml"); + if (!File.Exists(fileName)) + { + return names; + } + + var dom = new XmlDocument(); + dom.Load(fileName); + XmlNodeList nodes = dom.SelectNodes("/Multis/Multi"); + if (nodes == null) + { + return names; + } + + foreach (XmlNode node in nodes) + { + string idText = node.Attributes?["id"]?.Value; + string name = node.Attributes?["name"]?.Value; + if (name != null && int.TryParse(idText, out int id)) + { + names[id] = name; // last one wins, like the old list + } + } + } + catch (Exception) + { + // Names are cosmetic; a broken file falls back to "Multi 0xNNNN". + } + + return names; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.Designer.cs new file mode 100644 index 00000000..b08c9c8d --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.Designer.cs @@ -0,0 +1,217 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class DocumentIOPickDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + filterLabel = new System.Windows.Forms.Label(); + _filter = new System.Windows.Forms.TextBox(); + _list = new System.Windows.Forms.ListView(); + columnHeaderId = new System.Windows.Forms.ColumnHeader(); + columnHeaderName = new System.Windows.Forms.ColumnHeader(); + columnHeaderFile = new System.Windows.Forms.ColumnHeader(); + _preview = new System.Windows.Forms.PictureBox(); + _info = new System.Windows.Forms.Label(); + _ok = new System.Windows.Forms.Button(); + cancel = new System.Windows.Forms.Button(); + sourceAll = new System.Windows.Forms.RadioButton(); + sourceMul = new System.Windows.Forms.RadioButton(); + sourceUop = new System.Windows.Forms.RadioButton(); + ((System.ComponentModel.ISupportInitialize)_preview).BeginInit(); + SuspendLayout(); + // + // filterLabel + // + filterLabel.AutoSize = true; + filterLabel.Location = new System.Drawing.Point(10, 13); + filterLabel.Name = "filterLabel"; + filterLabel.Size = new System.Drawing.Size(154, 15); + filterLabel.TabIndex = 0; + filterLabel.Text = "Filter (name, id or 0x id):"; + // + // _filter + // + _filter.Location = new System.Drawing.Point(170, 10); + _filter.Name = "_filter"; + _filter.Size = new System.Drawing.Size(200, 23); + _filter.TabIndex = 1; + _filter.TextChanged += Filter_TextChanged; + // + // _list + // + _list.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left; + _list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnHeaderId, columnHeaderName, columnHeaderFile }); + _list.FullRowSelect = true; + _list.HideSelection = false; + _list.Location = new System.Drawing.Point(10, 40); + _list.Name = "_list"; + _list.Size = new System.Drawing.Size(380, 370); + _list.TabIndex = 2; + _list.UseCompatibleStateImageBehavior = false; + _list.View = System.Windows.Forms.View.Details; + _list.SelectedIndexChanged += List_SelectedIndexChanged; + _list.DoubleClick += List_DoubleClick; + _list.KeyDown += List_KeyDown; + // + // columnHeaderId + // + columnHeaderId.Text = "Id"; + columnHeaderId.Width = 90; + // + // columnHeaderName + // + columnHeaderName.Text = "Name"; + columnHeaderName.Width = 170; + // + // columnHeaderFile + // + columnHeaderFile.Text = "File"; + columnHeaderFile.Width = 90; + // + // _preview + // + _preview.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _preview.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _preview.Location = new System.Drawing.Point(400, 40); + _preview.Name = "_preview"; + _preview.Size = new System.Drawing.Size(350, 350); + _preview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + _preview.TabIndex = 3; + _preview.TabStop = false; + // + // _info + // + _info.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _info.Location = new System.Drawing.Point(400, 394); + _info.Name = "_info"; + _info.Size = new System.Drawing.Size(350, 18); + _info.TabIndex = 4; + // + // _ok + // + _ok.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + _ok.Location = new System.Drawing.Point(595, 425); + _ok.Name = "_ok"; + _ok.Size = new System.Drawing.Size(75, 23); + _ok.TabIndex = 5; + _ok.Text = "Open"; + _ok.UseVisualStyleBackColor = true; + _ok.Click += Ok_Click; + // + // cancel + // + cancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + cancel.Location = new System.Drawing.Point(675, 425); + cancel.Name = "cancel"; + cancel.Size = new System.Drawing.Size(75, 23); + cancel.TabIndex = 6; + cancel.Text = "Cancel"; + cancel.UseVisualStyleBackColor = true; + // + // sourceAll + // + sourceAll.Appearance = System.Windows.Forms.Appearance.Button; + sourceAll.Checked = true; + sourceAll.Location = new System.Drawing.Point(380, 8); + sourceAll.Name = "sourceAll"; + sourceAll.Size = new System.Drawing.Size(48, 24); + sourceAll.TabIndex = 7; + sourceAll.TabStop = true; + sourceAll.Text = "All"; + sourceAll.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + sourceAll.UseVisualStyleBackColor = true; + sourceAll.CheckedChanged += SourceButton_CheckedChanged; + // + // sourceMul + // + sourceMul.Appearance = System.Windows.Forms.Appearance.Button; + sourceMul.Location = new System.Drawing.Point(430, 8); + sourceMul.Name = "sourceMul"; + sourceMul.Size = new System.Drawing.Size(74, 24); + sourceMul.TabIndex = 8; + sourceMul.Tag = "multi.mul"; + sourceMul.Text = "multi.mul"; + sourceMul.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + sourceMul.UseVisualStyleBackColor = true; + sourceMul.CheckedChanged += SourceButton_CheckedChanged; + // + // sourceUop + // + sourceUop.Appearance = System.Windows.Forms.Appearance.Button; + sourceUop.Location = new System.Drawing.Point(506, 8); + sourceUop.Name = "sourceUop"; + sourceUop.Size = new System.Drawing.Size(48, 24); + sourceUop.TabIndex = 9; + sourceUop.Tag = "UOP"; + sourceUop.Text = "UOP"; + sourceUop.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + sourceUop.UseVisualStyleBackColor = true; + sourceUop.CheckedChanged += SourceButton_CheckedChanged; + // + // DocumentIOPickDialog + // + CancelButton = cancel; + ClientSize = new System.Drawing.Size(760, 460); + Controls.Add(filterLabel); + Controls.Add(_filter); + Controls.Add(_list); + Controls.Add(_preview); + Controls.Add(_info); + Controls.Add(_ok); + Controls.Add(cancel); + Controls.Add(sourceAll); + Controls.Add(sourceMul); + Controls.Add(sourceUop); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; + MinimizeBox = false; + MinimumSize = new System.Drawing.Size(560, 320); + Name = "DocumentIOPickDialog"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + ((System.ComponentModel.ISupportInitialize)_preview).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label filterLabel; + private System.Windows.Forms.TextBox _filter; + private System.Windows.Forms.ListView _list; + private System.Windows.Forms.ColumnHeader columnHeaderId; + private System.Windows.Forms.ColumnHeader columnHeaderName; + private System.Windows.Forms.ColumnHeader columnHeaderFile; + private System.Windows.Forms.PictureBox _preview; + private System.Windows.Forms.Label _info; + private System.Windows.Forms.Button _ok; + private System.Windows.Forms.Button cancel; + private System.Windows.Forms.RadioButton sourceAll; + private System.Windows.Forms.RadioButton sourceMul; + private System.Windows.Forms.RadioButton sourceUop; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.cs new file mode 100644 index 00000000..e0853de5 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.cs @@ -0,0 +1,255 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// One row of the pick list: a client multi (with id) or one multi inside a container file. + internal sealed record MultiPickEntry(int? Id, string Name, string Source, MultiComponentList Components); + + /// + /// Lists multis with a filter box and a preview of the highlighted one. + /// Double-click or Enter accepts. + /// + internal sealed partial class DocumentIOPickDialog : Form + { + private readonly List _entries; + private readonly List _sourceButtons = new List(); + private string _sourceFilter; + + /// Shows the File column: which file each multi comes from. + /// Adds the All / multi.mul / UOP buttons, for the client's multis. + public DocumentIOPickDialog(string title, List entries, bool showSource, bool clientSources) + { + _entries = entries; + + InitializeComponent(); + Text = title; + + // Which file the multis come from, as push buttons: all, multi.mul or the UOP collection. + // A client without MultiCollection.uop (or without multi.mul) has that button greyed out. + if (clientSources) + { + sourceMul.Enabled = entries.Exists(e => e.Source == "multi.mul"); + sourceUop.Enabled = entries.Exists(e => e.Source == "UOP"); + _sourceButtons.Add(sourceAll); + _sourceButtons.Add(sourceMul); + _sourceButtons.Add(sourceUop); + } + else + { + Controls.Remove(sourceAll); + Controls.Remove(sourceMul); + Controls.Remove(sourceUop); + sourceAll.Dispose(); + sourceMul.Dispose(); + sourceUop.Dispose(); + } + + if (!showSource) + { + _list.Columns.Remove(columnHeaderFile); + columnHeaderName.Width = 260; + } + else if (!clientSources) + { + // File names are longer than "multi.mul" or "UOP". + columnHeaderFile.Width = 140; + columnHeaderName.Width = 210; + columnHeaderId.Width = 0; + } + + Populate(); + } + + /// The accepted rows, in list order; empty when cancelled. + public List SelectedEntries { get; } = new List(); + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + _filter.Focus(); + } + + protected override void OnFormClosed(FormClosedEventArgs e) + { + _preview.Image?.Dispose(); + _preview.Image = null; + base.OnFormClosed(e); + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + // Arrow keys in the filter box move the list selection, so the list needs no focus. + if (_filter.Focused && (keyData == Keys.Down || keyData == Keys.Up) && _list.Items.Count > 0) + { + int index = _list.SelectedIndices.Count > 0 ? _list.SelectedIndices[0] : -1; + index = Math.Clamp(index + (keyData == Keys.Down ? 1 : -1), 0, _list.Items.Count - 1); + _list.Items[index].Selected = true; + _list.EnsureVisible(index); + return true; + } + + if (_filter.Focused && keyData == Keys.Enter) + { + Accept(); + return true; + } + + return base.ProcessCmdKey(ref msg, keyData); + } + + private void Filter_TextChanged(object sender, EventArgs e) + { + Populate(); + } + + private void SourceButton_CheckedChanged(object sender, EventArgs e) + { + var button = (RadioButton)sender; + if (button.Checked) + { + _sourceFilter = button.Tag as string; + Populate(); + } + } + + private void List_SelectedIndexChanged(object sender, EventArgs e) + { + ShowPreview(); + } + + private void List_DoubleClick(object sender, EventArgs e) + { + Accept(); + } + + private void List_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + e.Handled = true; + e.SuppressKeyPress = true; + Accept(); + } + } + + private void Ok_Click(object sender, EventArgs e) + { + Accept(); + } + + private void Populate() + { + string text = _filter.Text.Trim(); + int number = 0; + bool numeric = text.Length > 0 && Utils.ConvertStringToInt(text, out number); + string source = _sourceFilter; + + _list.BeginUpdate(); + try + { + _list.Items.Clear(); + foreach (MultiPickEntry entry in _entries) + { + bool match = text.Length == 0 + || entry.Name.Contains(text, StringComparison.OrdinalIgnoreCase) + || (numeric && entry.Id == number); + if (!match || (source != null && entry.Source != source)) + { + continue; + } + + string idText = entry.Id.HasValue ? $"{entry.Id.Value,5} (0x{entry.Id.Value:X})" : string.Empty; + var item = new ListViewItem(idText) { Tag = entry }; + item.SubItems.Add(entry.Name); + if (_list.Columns.Count > 2) + { + item.SubItems.Add(entry.Source ?? string.Empty); + } + + _list.Items.Add(item); + } + } + finally + { + _list.EndUpdate(); + } + + if (_list.Items.Count > 0) + { + _list.Items[0].Selected = true; + } + else + { + ShowPreview(); + } + } + + private void ShowPreview() + { + Image old = _preview.Image; + _preview.Image = null; + old?.Dispose(); + + MultiPickEntry entry = Current(); + _ok.Enabled = entry != null; + if (entry == null) + { + _info.Text = string.Empty; + return; + } + + MultiComponentList comp = entry.Components; + _info.Text = _list.SelectedItems.Count > 1 + ? $"{_list.SelectedItems.Count} selected: each opens in its own tab" + : $"{comp.Width}x{comp.Height}, {comp.SortedTiles.Length} tiles"; + _ok.Text = _list.SelectedItems.Count > 1 ? $"Open {_list.SelectedItems.Count}" : "Open"; + try + { + _preview.Image = comp.GetImage(); + } + catch (Exception) + { + // A broken multi must not take the dialog down; the preview just stays empty. + } + } + + private MultiPickEntry Current() + { + return _list.SelectedItems.Count > 0 ? _list.SelectedItems[0].Tag as MultiPickEntry : null; + } + + private void Accept() + { + if (_list.SelectedItems.Count == 0) + { + return; + } + + SelectedEntries.Clear(); + foreach (ListViewItem item in _list.SelectedItems) + { + if (item.Tag is MultiPickEntry entry) + { + SelectedEntries.Add(entry); + } + } + + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Properties/Resources.resx b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.resx similarity index 97% rename from UoFiddler.Plugin.MultiEditor/Properties/Resources.resx rename to UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.resx index 7080a7d1..1af7de15 100644 --- a/UoFiddler.Plugin.MultiEditor/Properties/Resources.resx +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOPickDialog.resx @@ -112,9 +112,9 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.Designer.cs new file mode 100644 index 00000000..6776a10e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.Designer.cs @@ -0,0 +1,295 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class DocumentIOSaveDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + idLabel = new System.Windows.Forms.Label(); + _id = new System.Windows.Forms.TextBox(); + nextFree = new System.Windows.Forms.Button(); + _list = new System.Windows.Forms.ListView(); + columnHeaderId = new System.Windows.Forms.ColumnHeader(); + columnHeaderName = new System.Windows.Forms.ColumnHeader(); + columnHeaderHolds = new System.Windows.Forms.ColumnHeader(); + _preview = new System.Windows.Forms.PictureBox(); + _info = new System.Windows.Forms.Label(); + _ok = new System.Windows.Forms.Button(); + cancel = new System.Windows.Forms.Button(); + writePanel = new System.Windows.Forms.Panel(); + writeLabel = new System.Windows.Forms.Label(); + _writeMul = new System.Windows.Forms.RadioButton(); + _writeUop = new System.Windows.Forms.RadioButton(); + _writeNone = new System.Windows.Forms.RadioButton(); + filterAll = new System.Windows.Forms.RadioButton(); + filterFree = new System.Windows.Forms.RadioButton(); + filterUsed = new System.Windows.Forms.RadioButton(); + ((System.ComponentModel.ISupportInitialize)_preview).BeginInit(); + writePanel.SuspendLayout(); + SuspendLayout(); + // + // idLabel + // + idLabel.AutoSize = true; + idLabel.Location = new System.Drawing.Point(10, 13); + idLabel.Name = "idLabel"; + idLabel.Size = new System.Drawing.Size(150, 15); + idLabel.TabIndex = 0; + idLabel.Text = "Slot id (decimal or 0x hex):"; + // + // _id + // + _id.Location = new System.Drawing.Point(170, 10); + _id.Name = "_id"; + _id.Size = new System.Drawing.Size(90, 23); + _id.TabIndex = 1; + _id.TextChanged += Id_TextChanged; + // + // nextFree + // + nextFree.Location = new System.Drawing.Point(266, 8); + nextFree.Name = "nextFree"; + nextFree.Size = new System.Drawing.Size(74, 24); + nextFree.TabIndex = 2; + nextFree.Text = "Next free"; + nextFree.UseVisualStyleBackColor = true; + nextFree.Click += NextFree_Click; + // + // _list + // + _list.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left; + _list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnHeaderId, columnHeaderName, columnHeaderHolds }); + _list.FullRowSelect = true; + _list.HideSelection = false; + _list.Location = new System.Drawing.Point(10, 40); + _list.MultiSelect = false; + _list.Name = "_list"; + _list.Size = new System.Drawing.Size(380, 362); + _list.TabIndex = 3; + _list.UseCompatibleStateImageBehavior = false; + _list.View = System.Windows.Forms.View.Details; + _list.VirtualMode = true; + _list.RetrieveVirtualItem += List_RetrieveVirtualItem; + _list.SelectedIndexChanged += List_SelectedIndexChanged; + _list.DoubleClick += List_DoubleClick; + // + // columnHeaderId + // + columnHeaderId.Text = "Id"; + columnHeaderId.Width = 100; + // + // columnHeaderName + // + columnHeaderName.Text = "Name"; + columnHeaderName.Width = 130; + // + // columnHeaderHolds + // + columnHeaderHolds.Text = "Holds"; + columnHeaderHolds.Width = 110; + // + // _preview + // + _preview.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _preview.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _preview.Location = new System.Drawing.Point(400, 40); + _preview.Name = "_preview"; + _preview.Size = new System.Drawing.Size(350, 338); + _preview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + _preview.TabIndex = 4; + _preview.TabStop = false; + // + // _info + // + _info.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _info.Location = new System.Drawing.Point(400, 380); + _info.Name = "_info"; + _info.Size = new System.Drawing.Size(350, 28); + _info.TabIndex = 5; + // + // _ok + // + _ok.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + _ok.Location = new System.Drawing.Point(585, 445); + _ok.Name = "_ok"; + _ok.Size = new System.Drawing.Size(84, 26); + _ok.TabIndex = 6; + _ok.Text = "Save here"; + _ok.UseVisualStyleBackColor = true; + _ok.Click += Ok_Click; + // + // cancel + // + cancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + cancel.Location = new System.Drawing.Point(675, 445); + cancel.Name = "cancel"; + cancel.Size = new System.Drawing.Size(76, 26); + cancel.TabIndex = 7; + cancel.Text = "Cancel"; + cancel.UseVisualStyleBackColor = true; + // + // writePanel + // + writePanel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left; + writePanel.Controls.Add(writeLabel); + writePanel.Controls.Add(_writeMul); + writePanel.Controls.Add(_writeUop); + writePanel.Controls.Add(_writeNone); + writePanel.Location = new System.Drawing.Point(10, 410); + writePanel.Name = "writePanel"; + writePanel.Size = new System.Drawing.Size(740, 26); + writePanel.TabIndex = 8; + // + // writeLabel + // + writeLabel.AutoSize = true; + writeLabel.Location = new System.Drawing.Point(0, 5); + writeLabel.Name = "writeLabel"; + writeLabel.Size = new System.Drawing.Size(54, 15); + writeLabel.TabIndex = 0; + writeLabel.Text = "Write to:"; + // + // _writeMul + // + _writeMul.AutoSize = true; + _writeMul.Location = new System.Drawing.Point(60, 3); + _writeMul.Name = "_writeMul"; + _writeMul.Size = new System.Drawing.Size(140, 19); + _writeMul.TabIndex = 1; + _writeMul.Text = "multi.mul + multi.idx"; + _writeMul.UseVisualStyleBackColor = true; + // + // _writeUop + // + _writeUop.AutoSize = true; + _writeUop.Location = new System.Drawing.Point(206, 3); + _writeUop.Name = "_writeUop"; + _writeUop.Size = new System.Drawing.Size(134, 19); + _writeUop.TabIndex = 2; + _writeUop.Text = "MultiCollection.uop"; + _writeUop.UseVisualStyleBackColor = true; + // + // _writeNone + // + _writeNone.AutoSize = true; + _writeNone.Location = new System.Drawing.Point(346, 3); + _writeNone.Name = "_writeNone"; + _writeNone.Size = new System.Drawing.Size(176, 19); + _writeNone.TabIndex = 3; + _writeNone.Text = "Not yet (Multis tab > Save)"; + _writeNone.UseVisualStyleBackColor = true; + // + // filterAll + // + filterAll.Appearance = System.Windows.Forms.Appearance.Button; + filterAll.Location = new System.Drawing.Point(352, 8); + filterAll.Name = "filterAll"; + filterAll.Size = new System.Drawing.Size(44, 24); + filterAll.TabIndex = 9; + filterAll.Text = "All"; + filterAll.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + filterAll.UseVisualStyleBackColor = true; + filterAll.CheckedChanged += FilterButton_CheckedChanged; + // + // filterFree + // + filterFree.Appearance = System.Windows.Forms.Appearance.Button; + filterFree.Location = new System.Drawing.Point(398, 8); + filterFree.Name = "filterFree"; + filterFree.Size = new System.Drawing.Size(96, 24); + filterFree.TabIndex = 10; + filterFree.Text = "Free"; + filterFree.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + filterFree.UseVisualStyleBackColor = true; + filterFree.CheckedChanged += FilterButton_CheckedChanged; + // + // filterUsed + // + filterUsed.Appearance = System.Windows.Forms.Appearance.Button; + filterUsed.Location = new System.Drawing.Point(496, 8); + filterUsed.Name = "filterUsed"; + filterUsed.Size = new System.Drawing.Size(96, 24); + filterUsed.TabIndex = 11; + filterUsed.Text = "Used"; + filterUsed.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + filterUsed.UseVisualStyleBackColor = true; + filterUsed.CheckedChanged += FilterButton_CheckedChanged; + // + // DocumentIOSaveDialog + // + AcceptButton = _ok; + CancelButton = cancel; + ClientSize = new System.Drawing.Size(760, 480); + Controls.Add(idLabel); + Controls.Add(_id); + Controls.Add(nextFree); + Controls.Add(_list); + Controls.Add(_preview); + Controls.Add(_info); + Controls.Add(_ok); + Controls.Add(cancel); + Controls.Add(writePanel); + Controls.Add(filterAll); + Controls.Add(filterFree); + Controls.Add(filterUsed); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; + MinimizeBox = false; + MinimumSize = new System.Drawing.Size(700, 340); + Name = "DocumentIOSaveDialog"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Save multi to client"; + ((System.ComponentModel.ISupportInitialize)_preview).EndInit(); + writePanel.ResumeLayout(false); + writePanel.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label idLabel; + private System.Windows.Forms.TextBox _id; + private System.Windows.Forms.Button nextFree; + private System.Windows.Forms.ListView _list; + private System.Windows.Forms.ColumnHeader columnHeaderId; + private System.Windows.Forms.ColumnHeader columnHeaderName; + private System.Windows.Forms.ColumnHeader columnHeaderHolds; + private System.Windows.Forms.PictureBox _preview; + private System.Windows.Forms.Label _info; + private System.Windows.Forms.Button _ok; + private System.Windows.Forms.Button cancel; + private System.Windows.Forms.Panel writePanel; + private System.Windows.Forms.Label writeLabel; + private System.Windows.Forms.RadioButton _writeMul; + private System.Windows.Forms.RadioButton _writeUop; + private System.Windows.Forms.RadioButton _writeNone; + private System.Windows.Forms.RadioButton filterAll; + private System.Windows.Forms.RadioButton filterFree; + private System.Windows.Forms.RadioButton filterUsed; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.cs new file mode 100644 index 00000000..9373fd75 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.cs @@ -0,0 +1,354 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using Ultima; +using Ultima.Uop; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Picks the multi slot to save into: every slot of the client's multi table is listed, free + /// ones marked as such, with a preview of what a used slot holds now. + /// + internal sealed partial class DocumentIOSaveDialog : Form + { + private readonly Dictionary _names; + private readonly bool[] _used; + + /// Slots the client's MultiCollection.uop holds a multi in (all false without that file). + private readonly bool[] _uop; + private readonly List _rows = new List(); + private readonly List _filters = new List(); + private int _filter; // 0 all, 1 free, 2 used + private bool _syncing; + + public DocumentIOSaveDialog(Dictionary names, int? suggestedId) + { + _names = names; + int count = Multis.MaximumMultiIndex; + _used = new bool[count]; + _uop = new bool[count]; + + // multi.mul and MultiCollection.uop do not hold the same multis, so a slot is only free + // when neither has one there. + bool hasUop = Multis.HasUopFile; + int free = 0; + for (int i = 0; i < count; i++) + { + _used[i] = Multis.GetComponents(i) != MultiComponentList.Empty; + _uop[i] = hasUop && Multis.GetUopComponents(i) != MultiComponentList.Empty; + if (IsFree(i)) + { + free++; + } + } + + InitializeComponent(); + + // Which slots are listed. A new design usually wants a free slot. + filterFree.Text = $"Free ({free})"; + filterUsed.Text = $"Used ({count - free})"; + _filters.Add(filterAll); + _filters.Add(filterFree); + _filters.Add(filterUsed); + + // Which file the multi table is written to. The slot itself always changes in memory; the + // files hold every multi, so writing one writes the whole table in that container. + // They sit in a panel of their own: radio buttons sharing a parent are one group, and the slot + // filter buttons are radio buttons too. + + // Preselected: the container this client keeps its multis in, unless writing it would drop + // multis. The editable table comes from multi.mul, and a modern client's MultiCollection.uop + // can hold more than that; then multi.mul is the safe choice and the UOP one says why. + bool clientUsesUop = ClientFileSaver.ClientUsesUop(FileType.MultiCollection); + bool uopLosesData = clientUsesUop && ClientFileSaver.Preflight(FileType.MultiCollection, ContainerFormat.Uop).Count > 0; + _writeUop.Checked = clientUsesUop && !uopLosesData; + _writeMul.Checked = !_writeUop.Checked; + if (uopLosesData) + { + _writeUop.Text += " (drops multis)"; + var tip = new ToolTip(); + tip.SetToolTip(_writeUop, "This client's MultiCollection.uop holds more multis than its multi.mul, which is what is edited here.\n" + + "Writing the UOP saves only the multi.mul ones. You are asked before it happens."); + _writeNone.Left += 90; + } + + // A design that came from a slot goes back to it by default; a new one to the first free slot. + _syncing = true; + _filter = suggestedId.HasValue ? 0 : 1; + _filters[_filter].Checked = true; + _syncing = false; + Populate(suggestedId ?? FirstFreeFrom(0)); + } + + /// The container to write the multi table to after the slot is set, or null to leave the files for later. + public ContainerFormat? WriteFormat => _writeNone.Checked ? null : _writeUop.Checked ? ContainerFormat.Uop : ContainerFormat.Mul; + + /// The slot chosen, valid after the dialog returned OK. + public int SelectedId { get; private set; } = -1; + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + + // The list can only scroll to the chosen slot once it has its window. + int id = CurrentId(); + if (id >= 0) + { + Select(id); + } + + _id.Focus(); + _id.SelectAll(); + } + + protected override void OnFormClosed(FormClosedEventArgs e) + { + _preview.Image?.Dispose(); + _preview.Image = null; + base.OnFormClosed(e); + } + + private void Id_TextChanged(object sender, EventArgs e) + { + OnIdTyped(); + } + + private void NextFree_Click(object sender, EventArgs e) + { + GoToNextFree(); + } + + private void FilterButton_CheckedChanged(object sender, EventArgs e) + { + var button = (RadioButton)sender; + if (button.Checked && !_syncing) + { + _filter = _filters.IndexOf(button); + Populate(CurrentId()); + } + } + + private void List_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) + { + e.Item = MakeItem(_rows[e.ItemIndex]); + } + + private void List_SelectedIndexChanged(object sender, EventArgs e) + { + OnRowSelected(); + } + + private void List_DoubleClick(object sender, EventArgs e) + { + Accept(); + } + + private void Ok_Click(object sender, EventArgs e) + { + Accept(); + } + + private bool IsFree(int id) => !_used[id] && !_uop[id]; + + private ListViewItem MakeItem(int id) + { + var item = new ListViewItem($"{id,5} (0x{id:X})"); + if (_used[id]) + { + MultiComponentList multi = Multis.GetComponents(id); + item.SubItems.Add(_names.TryGetValue(id, out string name) ? name : string.Empty); + item.SubItems.Add($"{multi.Width}x{multi.Height}, {multi.SortedTiles.Length} tiles"); + } + else if (_uop[id]) + { + MultiComponentList multi = Multis.GetUopComponents(id); + item.SubItems.Add(_names.TryGetValue(id, out string name) ? name : string.Empty); + item.SubItems.Add($"UOP only: {multi.Width}x{multi.Height}"); + } + else + { + item.SubItems.Add(string.Empty); + item.SubItems.Add("free"); + item.ForeColor = SystemColors.GrayText; + } + + return item; + } + + private int FirstFreeFrom(int start) + { + for (int i = Math.Max(0, start); i < _used.Length; i++) + { + if (IsFree(i)) + { + return i; + } + } + + return -1; + } + + private void GoToNextFree() + { + int next = FirstFreeFrom(CurrentId() + 1); + if (next < 0) + { + next = FirstFreeFrom(0); + } + + if (next >= 0) + { + Select(next); + } + } + + private int CurrentId() + { + return Utils.ConvertStringToInt(_id.Text.Trim(), out int id, 0, _used.Length - 1) ? id : -1; + } + + /// Fills the list for the chosen filter and selects a slot (the nearest listed one when it is filtered out). + private void Populate(int select) + { + _rows.Clear(); + for (int i = 0; i < _used.Length; i++) + { + if (_filter == 0 || (_filter == 1) == IsFree(i)) + { + _rows.Add(i); + } + } + + _list.VirtualListSize = _rows.Count; + _list.Invalidate(); + if (select >= 0) + { + Select(select); + } + else + { + ShowSlot(-1); + } + } + + private void Select(int id) + { + _syncing = true; + _id.Text = id.ToString(); + _syncing = false; + + int row = _rows.BinarySearch(id); + _list.SelectedIndices.Clear(); + if (row >= 0) + { + _list.SelectedIndices.Add(row); + _list.EnsureVisible(row); + } + + ShowSlot(id); + } + + private void OnIdTyped() + { + if (_syncing) + { + return; + } + + int id = CurrentId(); + int row = id >= 0 ? _rows.BinarySearch(id) : -1; + _syncing = true; + _list.SelectedIndices.Clear(); + if (row >= 0) + { + _list.SelectedIndices.Add(row); + _list.EnsureVisible(row); + } + + _syncing = false; + ShowSlot(id); + } + + private void OnRowSelected() + { + if (_syncing || _list.SelectedIndices.Count == 0) + { + return; + } + + int id = _rows[_list.SelectedIndices[0]]; + _syncing = true; + _id.Text = id.ToString(); + _syncing = false; + ShowSlot(id); + } + + private void ShowSlot(int id) + { + Image old = _preview.Image; + _preview.Image = null; + old?.Dispose(); + + _ok.Enabled = id >= 0; + if (id < 0) + { + _info.Text = $"Enter an id between 0 and {_used.Length - 1}."; + return; + } + + if (IsFree(id)) + { + _info.Text = $"Slot {id} (0x{id:X}) is free."; + return; + } + + MultiComponentList multi = _used[id] ? Multis.GetComponents(id) : Multis.GetUopComponents(id); + _info.Text = _used[id] + ? $"Slot {id} (0x{id:X}) holds a {multi.Width}x{multi.Height} multi: saving replaces it." + : $"Slot {id} (0x{id:X}) is empty in multi.mul, but MultiCollection.uop has a {multi.Width}x{multi.Height} multi there."; + try + { + _preview.Image = multi.GetImage(); + } + catch (Exception) + { + // A broken multi must not take the dialog down; the preview just stays empty. + } + } + + private void Accept() + { + int id = CurrentId(); + if (id < 0) + { + return; + } + + string question = _used[id] ? $"Multi {id} (0x{id:X}) already holds a design. Overwrite it?" + : _uop[id] ? $"Multi {id} (0x{id:X}) is empty in multi.mul, but the client's MultiCollection.uop has a multi with that id.\r\n" + + "Saving here gives the id a second meaning. Use it anyway?" + : null; + if (question != null && MessageBox.Show(this, question, "Multi Editor", + MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) != DialogResult.OK) + { + return; + } + + SelectedId = id; + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.resx b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.resx new file mode 100644 index 00000000..1af7de15 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIOSaveDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorCommands.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorCommands.cs new file mode 100644 index 00000000..8d651b88 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorCommands.cs @@ -0,0 +1,384 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// One thing the editor can do, with its name, keys and state. Menus, toolbar buttons, key + /// handling and the shortcut list are all made from these, so they cannot drift apart. + /// + internal sealed class EditorCommand + { + public EditorCommand(string group, string text, Action execute) + { + Group = group; + Text = text; + Execute = execute; + } + + public string Group { get; } + + public string Text { get; } + + public Action Execute { get; } + + public Keys Shortcut { get; init; } + + /// A second key for the same command. + public Keys AltShortcut { get; init; } + + /// Segoe MDL2 Assets glyph for the toolbar, or null for a text button. + public string Glyph { get; init; } + + public Func CanExecute { get; init; } + + public Func IsChecked { get; init; } + + public bool Enabled => CanExecute == null || CanExecute(); + + public string ShortcutText => Format(Shortcut) + (AltShortcut != Keys.None ? ", " + Format(AltShortcut) : string.Empty); + + public string ToolTip => Shortcut == Keys.None ? Text : $"{Text} ({Format(Shortcut)})"; + + private static string Format(Keys keys) + { + if (keys == Keys.None) + { + return string.Empty; + } + + string text = string.Empty; + if ((keys & Keys.Control) != 0) + { + text += "Ctrl+"; + } + + if ((keys & Keys.Shift) != 0) + { + text += "Shift+"; + } + + if ((keys & Keys.Alt) != 0) + { + text += "Alt+"; + } + + Keys code = keys & Keys.KeyCode; + string name = code switch + { + Keys.OemOpenBrackets => "[", + Keys.OemCloseBrackets => "]", + Keys.Oemcomma => ",", + Keys.OemPeriod => ".", + Keys.Oemplus or Keys.Add => "+", + Keys.OemMinus or Keys.Subtract => "-", + Keys.PageUp => "PgUp", + Keys.PageDown => "PgDn", + Keys.Delete => "Del", + Keys.Escape => "Esc", + >= Keys.D0 and <= Keys.D9 => ((int)(code - Keys.D0)).ToString(), + _ => code.ToString() + }; + + return text + name; + } + } + + internal sealed class CommandRegistry + { + private readonly List _commands = new List(); + private readonly Dictionary _byKey = new Dictionary(); + private readonly List<(ToolStripItem Item, EditorCommand Command)> _items = new List<(ToolStripItem, EditorCommand)>(); + + public IReadOnlyList Commands => _commands; + + public EditorCommand Add(EditorCommand command) + { + _commands.Add(command); + if (command.Shortcut != Keys.None) + { + _byKey[command.Shortcut] = command; + } + + if (command.AltShortcut != Keys.None) + { + _byKey[command.AltShortcut] = command; + } + + return command; + } + + /// Runs the command bound to a key. True when the key belongs to a command, also a disabled one. + public bool TryRun(Keys keyData) + { + if (!_byKey.TryGetValue(keyData, out EditorCommand command)) + { + return false; + } + + if (command.Enabled) + { + command.Execute(); + } + + return true; + } + + public ToolStripMenuItem MenuItem(EditorCommand command) + { + var item = new ToolStripMenuItem(command.Text) { ShortcutKeyDisplayString = command.ShortcutText }; + item.Click += (_, _) => Run(command); + _items.Add((item, command)); + return item; + } + + public ToolStripButton Button(EditorCommand command, bool showText = false) + { + var button = new ToolStripButton(command.Text) + { + ToolTipText = command.ToolTip, + AutoToolTip = false, + Image = command.Glyph != null ? Glyphs.Render(command.Glyph, 18, SystemColors.ControlText) : null + }; + button.DisplayStyle = button.Image == null + ? ToolStripItemDisplayStyle.Text + : showText ? ToolStripItemDisplayStyle.ImageAndText : ToolStripItemDisplayStyle.Image; + button.Click += (_, _) => Run(command); + _items.Add((button, command)); + return button; + } + + /// Brings every menu item and button in line with the editor state. + public void RefreshStates() + { + foreach ((ToolStripItem item, EditorCommand command) in _items) + { + item.Enabled = command.Enabled; + bool isChecked = command.IsChecked != null && command.IsChecked(); + switch (item) + { + case ToolStripMenuItem menu: + menu.Checked = isChecked; + break; + case ToolStripButton button: + button.Checked = isChecked; + break; + } + } + } + + private void Run(EditorCommand command) + { + if (command.Enabled) + { + command.Execute(); + } + + RefreshStates(); + } + } + + /// + /// A pick-one-of-a-few toolbar item: shows the chosen text and drops a menu of the choices. + /// Used instead of ToolStripComboBox, whose hosted combo box takes around 10 ms to repaint + /// and made resizing the window stutter. + /// + internal sealed class ToolStripChoice : ToolStripDropDownButton + { + private readonly string[] _choices; + private int _selectedIndex = -1; + + public ToolStripChoice(int width, params string[] choices) + { + _choices = choices; + DisplayStyle = ToolStripItemDisplayStyle.Text; + AutoSize = false; + Width = width; + TextAlign = ContentAlignment.MiddleLeft; + for (int i = 0; i < choices.Length; i++) + { + int index = i; + var item = new ToolStripMenuItem(choices[i]); + item.Click += (_, _) => SelectedIndex = index; + DropDownItems.Add(item); + } + + SelectedIndex = 0; + } + + public event EventHandler SelectedIndexChanged; + + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] + public int SelectedIndex + { + get => _selectedIndex; + set + { + value = Math.Clamp(value, 0, _choices.Length - 1); + if (value == _selectedIndex) + { + return; + } + + _selectedIndex = value; + Text = _choices[value]; + for (int i = 0; i < DropDownItems.Count; i++) + { + ((ToolStripMenuItem)DropDownItems[i]).Checked = i == value; + } + + SelectedIndexChanged?.Invoke(this, EventArgs.Empty); + } + } + + public int IndexOf(string choice) => Array.IndexOf(_choices, choice); + } + + /// + /// Toolbar icons drawn from the Windows icon font, so the plugin ships no image files. + /// + internal static class Glyphs + { + public const string Select = "\uE8B0"; + public const string Lasso = "\uF408"; + public const string Draw = "\uE70F"; + public const string Remove = "\uE75C"; + public const string Altitude = "\uE8CB"; + public const string Pipette = "\uEF3C"; + public const string Transparent = "\uE7B3"; + public const string RectFill = "\uE739"; + public const string Line = "\uE738"; + public const string Wall = "\uE80F"; + public const string Floor = "\uE80A"; + public const string Door = "\uE8A7"; + public const string Stair = "\uE9D5"; + public const string Roof = "\uE80F"; + public const string Foundation = "\uE7C4"; + public const string New = "\uE7C3"; + public const string Open = "\uE8E5"; + public const string Save = "\uE74E"; + public const string Undo = "\uE7A7"; + public const string Redo = "\uE7A6"; + public const string Cut = "\uE8C6"; + public const string Copy = "\uE8C8"; + public const string Paste = "\uE77F"; + public const string Delete = "\uE74D"; + public const string Grid = "\uE80A"; + public const string ZoomIn = "\uE8A3"; + public const string ZoomOut = "\uE71F"; + public const string Fit = "\uE9A6"; + public const string Center = "\uE81D"; + public const string RotateLeft = "\uE7AD"; + public const string RotateRight = "\uE7AD"; + public const string Help = "\uE897"; + + public static Bitmap Render(string glyph, int size, Color color) + { + var bitmap = new Bitmap(size, size); + using Graphics g = Graphics.FromImage(bitmap); + g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; + using var font = new Font("Segoe MDL2 Assets", size * 0.72f, GraphicsUnit.Pixel); + using var brush = new SolidBrush(color); + using var format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; + g.DrawString(glyph, font, brush, new RectangleF(0, 0, size, size), format); + return bitmap; + } + } + + /// + /// Makes splitters visible: a row of dots in the middle of the bar, the usual sign that it + /// can be dragged. A bare splitter is the same colour as the panels and easy to miss. + /// + internal static class SplitterGrip + { + public const int Thickness = 7; + + /// Draws the dots along the middle of a splitter bar. + public static void Draw(Graphics g, Rectangle bar) + { + bool wide = bar.Width >= bar.Height; + const int dots = 5, spacing = 6, size = 2; + int length = (dots - 1) * spacing; + int x = bar.X + (wide ? (bar.Width - length) / 2 : (bar.Width - size) / 2); + int y = bar.Y + (wide ? (bar.Height - size) / 2 : (bar.Height - length) / 2); + using var brush = new SolidBrush(SystemColors.GrayText); + for (int i = 0; i < dots; i++) + { + g.FillRectangle(brush, x + (wide ? i * spacing : 0), y + (wide ? 0 : i * spacing), size, size); + } + } + + /// Gives a split container's bar the dots. + public static void Attach(SplitContainer container) + { + container.SplitterWidth = Thickness; + container.Paint += (_, e) => Draw(e.Graphics, container.SplitterRectangle); + container.SplitterMoved += (_, _) => container.Invalidate(); + container.Resize += (_, _) => container.Invalidate(); + } + } + + /// A docked splitter that shows the dots. + internal sealed class GripSplitter : Splitter + { + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + SplitterGrip.Draw(e.Graphics, ClientRectangle); + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + Invalidate(); + } + } + + /// + /// Small input dialogs. + /// + internal static class Prompt + { + /// Asks for whole numbers. Returns null when cancelled. + public static int[] Numbers(IWin32Window owner, string title, params (string Label, int Value, int Min, int Max)[] fields) + { + using var form = new NumbersPromptForm(title, fields); + if (form.ShowDialog(owner) != DialogResult.OK) + { + return null; + } + + return form.Values; + } + + /// Asks for one line of text. Returns null when cancelled or left empty. + public static string Text(IWin32Window owner, string title, string label, string value = "") + { + using var form = new TextPromptForm(title, label, value); + return form.ShowDialog(owner) == DialogResult.OK && form.Value.Trim().Length > 0 ? form.Value.Trim() : null; + } + + /// Reads a tile id typed as decimal or 0x hex. + public static bool TryParseId(string text, out ushort id) + { + text = (text ?? string.Empty).Trim(); + if (text.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { + return ushort.TryParse(text.AsSpan(2), System.Globalization.NumberStyles.HexNumber, null, out id); + } + + return ushort.TryParse(text, out id); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs new file mode 100644 index 00000000..5abf696b --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs @@ -0,0 +1,171 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// What the user can customise in the multi editor. Kept in the profile + /// (), so each profile has its own. + /// + internal sealed class EditorSettings + { + private const string _prefix = "MultiEditor."; + + /// Prefix the settings were saved under while the editor was a separate plugin. + private const string _oldPrefix = "MultiEditorGL."; + + public static EditorSettings Current { get; private set; } = new EditorSettings(); + + /// Raised after settings were changed and stored. + public static event Action Changed; + + /// The background the editor shipped with before it followed the theme. + private static readonly Color _oldDefaultBackground = Color.FromArgb(30, 30, 34); + + // Colours. Alpha is the opacity of planes and lines over the tiles. + + /// The canvas background the user chose, or empty to follow the application's light or dark theme. + public Color Background { get; set; } = Color.Empty; + + /// The background to draw: the chosen one, else dark on a dark theme and light grey on a light one. + public Color EffectiveBackground => Background.A != 0 ? Background : ThemeBackground; + + /// Text colour that reads on . + public Color BackgroundText => EffectiveBackground.GetBrightness() < 0.5f ? Color.Gainsboro : Color.FromArgb(60, 60, 60); + + private static Color ThemeBackground => + SystemColors.Window.GetBrightness() < 0.5f ? _oldDefaultBackground : Color.FromArgb(206, 210, 216); + + public Color WorkPlane { get; set; } = Color.FromArgb(150, 40, 200, 40); + + public Color Grid { get; set; } = Color.FromArgb(150, 110, 110, 110); + + public Color Outline { get; set; } = Color.FromArgb(200, 150, 150, 150); + + public Color SelectionBox { get; set; } = Color.DodgerBlue; + + // How a new document starts. + public bool StartWithWorkPlane { get; set; } = true; + + public bool StartWithGrid { get; set; } + + public bool HideFloorsAbove { get; set; } = true; + + /// Ground under a previewed multi: 0 none, 1 grass, 2 dirt, 3 sand, 4 snow. + public int PreviewTerrain { get; set; } = 1; + + // Layout. + public bool ShowTileBrowser { get; set; } = true; + + public bool ShowInspector { get; set; } = true; + + public int TileBrowserWidth { get; set; } = 340; + + public int InspectorWidth { get; set; } = 300; + + /// Folder the Designs page lists UO Architect designs from. + public string DesignLibraryFolder { get; set; } = string.Empty; + + /// Folder the Import from folder window scans. + public string ImportFolder { get; set; } = string.Empty; + + /// Whether Import from folder also scans the folders below. + public bool ImportRecursive { get; set; } = true; + + /// Height of the pieces list under the House page's styles. + public int HousePiecesHeight { get; set; } = 250; + + public EditorSettings Clone() => (EditorSettings)MemberwiseClone(); + + /// Reads the profile's settings; anything missing or unreadable keeps its default. + public static void Load() + { + var settings = new EditorSettings(); + foreach (System.Reflection.PropertyInfo property in Properties()) + { + if (!Options.PluginSettings.TryGetValue(_prefix + property.Name, out string text) && + !Options.PluginSettings.TryGetValue(_oldPrefix + property.Name, out text)) + { + continue; + } + + if (property.PropertyType == typeof(string)) + { + property.SetValue(settings, text); + } + else if (property.PropertyType == typeof(Color)) + { + if (int.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int argb)) + { + property.SetValue(settings, Color.FromArgb(argb)); + } + } + else if (property.PropertyType == typeof(bool)) + { + if (bool.TryParse(text, out bool flag)) + { + property.SetValue(settings, flag); + } + } + else if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int number)) + { + property.SetValue(settings, number); + } + } + + // A profile saved before the background followed the theme holds the old dark default, + // which nobody chose. + if (settings.Background.ToArgb() == _oldDefaultBackground.ToArgb()) + { + settings.Background = Color.Empty; + } + + settings.TileBrowserWidth = Math.Clamp(settings.TileBrowserWidth, 200, 900); + settings.InspectorWidth = Math.Clamp(settings.InspectorWidth, 200, 600); + Current = settings; + } + + /// Makes these the current settings and puts them in the profile, which the application saves on exit. + public void Apply() + { + Current = this; + foreach (System.Reflection.PropertyInfo property in Properties()) + { + object value = property.GetValue(this); + string text = value switch + { + Color color => color.ToArgb().ToString("X8", CultureInfo.InvariantCulture), + bool flag => flag.ToString(), + _ => Convert.ToString(value, CultureInfo.InvariantCulture) + }; + Options.PluginSettings[_prefix + property.Name] = text; + } + + Changed?.Invoke(); + } + + private static IEnumerable Properties() + { + foreach (System.Reflection.PropertyInfo property in typeof(EditorSettings).GetProperties( + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)) + { + if (property.CanWrite) + { + yield return property; + } + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs new file mode 100644 index 00000000..0050485f --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs @@ -0,0 +1,371 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class EditorSettingsDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + headingColours = new System.Windows.Forms.Label(); + labelBackground = new System.Windows.Forms.Label(); + swatchBackground = new System.Windows.Forms.Button(); + labelWorkPlane = new System.Windows.Forms.Label(); + labelWorkPlaneOpacity = new System.Windows.Forms.Label(); + alphaWorkPlane = new System.Windows.Forms.NumericUpDown(); + swatchWorkPlane = new System.Windows.Forms.Button(); + labelGrid = new System.Windows.Forms.Label(); + labelGridOpacity = new System.Windows.Forms.Label(); + alphaGrid = new System.Windows.Forms.NumericUpDown(); + swatchGrid = new System.Windows.Forms.Button(); + labelOutline = new System.Windows.Forms.Label(); + labelOutlineOpacity = new System.Windows.Forms.Label(); + alphaOutline = new System.Windows.Forms.NumericUpDown(); + swatchOutline = new System.Windows.Forms.Button(); + labelSelection = new System.Windows.Forms.Label(); + swatchSelection = new System.Windows.Forms.Button(); + headingStart = new System.Windows.Forms.Label(); + checkWorkPlane = new System.Windows.Forms.CheckBox(); + checkGrid = new System.Windows.Forms.CheckBox(); + checkHideFloorsAbove = new System.Windows.Forms.CheckBox(); + buttonDefaults = new System.Windows.Forms.Button(); + buttonOk = new System.Windows.Forms.Button(); + buttonCancel = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)alphaWorkPlane).BeginInit(); + ((System.ComponentModel.ISupportInitialize)alphaGrid).BeginInit(); + ((System.ComponentModel.ISupportInitialize)alphaOutline).BeginInit(); + SuspendLayout(); + // + // headingColours + // + headingColours.AutoSize = true; + headingColours.Location = new System.Drawing.Point(12, 12); + headingColours.Name = "headingColours"; + headingColours.Size = new System.Drawing.Size(47, 15); + headingColours.TabIndex = 0; + headingColours.Text = "Colours"; + // + // labelBackground + // + labelBackground.AutoSize = true; + labelBackground.Location = new System.Drawing.Point(24, 40); + labelBackground.Name = "labelBackground"; + labelBackground.Size = new System.Drawing.Size(320, 15); + labelBackground.TabIndex = 1; + labelBackground.Text = "Canvas background (follows the theme until changed)"; + // + // swatchBackground + // + swatchBackground.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + swatchBackground.Location = new System.Drawing.Point(330, 36); + swatchBackground.Name = "swatchBackground"; + swatchBackground.Size = new System.Drawing.Size(60, 24); + swatchBackground.TabIndex = 2; + swatchBackground.UseVisualStyleBackColor = true; + swatchBackground.Click += SwatchBackground_Click; + // + // labelWorkPlane + // + labelWorkPlane.AutoSize = true; + labelWorkPlane.Location = new System.Drawing.Point(24, 70); + labelWorkPlane.Name = "labelWorkPlane"; + labelWorkPlane.Size = new System.Drawing.Size(72, 15); + labelWorkPlane.TabIndex = 7; + labelWorkPlane.Text = "Work plane"; + // + // labelWorkPlaneOpacity + // + labelWorkPlaneOpacity.AutoSize = true; + labelWorkPlaneOpacity.Location = new System.Drawing.Point(272, 70); + labelWorkPlaneOpacity.Name = "labelWorkPlaneOpacity"; + labelWorkPlaneOpacity.Size = new System.Drawing.Size(59, 15); + labelWorkPlaneOpacity.TabIndex = 8; + labelWorkPlaneOpacity.Text = "Opacity %"; + // + // alphaWorkPlane + // + alphaWorkPlane.Increment = new decimal(new int[] { 5, 0, 0, 0 }); + alphaWorkPlane.Location = new System.Drawing.Point(340, 67); + alphaWorkPlane.Maximum = new decimal(new int[] { 100, 0, 0, 0 }); + alphaWorkPlane.Minimum = new decimal(new int[] { 5, 0, 0, 0 }); + alphaWorkPlane.Name = "alphaWorkPlane"; + alphaWorkPlane.Size = new System.Drawing.Size(56, 23); + alphaWorkPlane.TabIndex = 9; + alphaWorkPlane.Value = new decimal(new int[] { 5, 0, 0, 0 }); + alphaWorkPlane.ValueChanged += AlphaWorkPlane_ValueChanged; + // + // swatchWorkPlane + // + swatchWorkPlane.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + swatchWorkPlane.Location = new System.Drawing.Point(200, 66); + swatchWorkPlane.Name = "swatchWorkPlane"; + swatchWorkPlane.Size = new System.Drawing.Size(60, 24); + swatchWorkPlane.TabIndex = 10; + swatchWorkPlane.UseVisualStyleBackColor = true; + swatchWorkPlane.Click += SwatchWorkPlane_Click; + // + // labelGrid + // + labelGrid.AutoSize = true; + labelGrid.Location = new System.Drawing.Point(24, 100); + labelGrid.Name = "labelGrid"; + labelGrid.Size = new System.Drawing.Size(66, 15); + labelGrid.TabIndex = 11; + labelGrid.Text = "Grid lines"; + // + // labelGridOpacity + // + labelGridOpacity.AutoSize = true; + labelGridOpacity.Location = new System.Drawing.Point(272, 100); + labelGridOpacity.Name = "labelGridOpacity"; + labelGridOpacity.Size = new System.Drawing.Size(59, 15); + labelGridOpacity.TabIndex = 12; + labelGridOpacity.Text = "Opacity %"; + // + // alphaGrid + // + alphaGrid.Increment = new decimal(new int[] { 5, 0, 0, 0 }); + alphaGrid.Location = new System.Drawing.Point(340, 97); + alphaGrid.Maximum = new decimal(new int[] { 100, 0, 0, 0 }); + alphaGrid.Minimum = new decimal(new int[] { 5, 0, 0, 0 }); + alphaGrid.Name = "alphaGrid"; + alphaGrid.Size = new System.Drawing.Size(56, 23); + alphaGrid.TabIndex = 13; + alphaGrid.Value = new decimal(new int[] { 5, 0, 0, 0 }); + alphaGrid.ValueChanged += AlphaGrid_ValueChanged; + // + // swatchGrid + // + swatchGrid.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + swatchGrid.Location = new System.Drawing.Point(200, 96); + swatchGrid.Name = "swatchGrid"; + swatchGrid.Size = new System.Drawing.Size(60, 24); + swatchGrid.TabIndex = 14; + swatchGrid.UseVisualStyleBackColor = true; + swatchGrid.Click += SwatchGrid_Click; + // + // labelOutline + // + labelOutline.AutoSize = true; + labelOutline.Location = new System.Drawing.Point(24, 130); + labelOutline.Name = "labelOutline"; + labelOutline.Size = new System.Drawing.Size(84, 15); + labelOutline.TabIndex = 15; + labelOutline.Text = "Multi outline"; + // + // labelOutlineOpacity + // + labelOutlineOpacity.AutoSize = true; + labelOutlineOpacity.Location = new System.Drawing.Point(272, 130); + labelOutlineOpacity.Name = "labelOutlineOpacity"; + labelOutlineOpacity.Size = new System.Drawing.Size(59, 15); + labelOutlineOpacity.TabIndex = 16; + labelOutlineOpacity.Text = "Opacity %"; + // + // alphaOutline + // + alphaOutline.Increment = new decimal(new int[] { 5, 0, 0, 0 }); + alphaOutline.Location = new System.Drawing.Point(340, 127); + alphaOutline.Maximum = new decimal(new int[] { 100, 0, 0, 0 }); + alphaOutline.Minimum = new decimal(new int[] { 5, 0, 0, 0 }); + alphaOutline.Name = "alphaOutline"; + alphaOutline.Size = new System.Drawing.Size(56, 23); + alphaOutline.TabIndex = 17; + alphaOutline.Value = new decimal(new int[] { 5, 0, 0, 0 }); + alphaOutline.ValueChanged += AlphaOutline_ValueChanged; + // + // swatchOutline + // + swatchOutline.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + swatchOutline.Location = new System.Drawing.Point(200, 126); + swatchOutline.Name = "swatchOutline"; + swatchOutline.Size = new System.Drawing.Size(60, 24); + swatchOutline.TabIndex = 18; + swatchOutline.UseVisualStyleBackColor = true; + swatchOutline.Click += SwatchOutline_Click; + // + // labelSelection + // + labelSelection.AutoSize = true; + labelSelection.Location = new System.Drawing.Point(24, 160); + labelSelection.Name = "labelSelection"; + labelSelection.Size = new System.Drawing.Size(146, 15); + labelSelection.TabIndex = 19; + labelSelection.Text = "Selection box and lasso"; + // + // swatchSelection + // + swatchSelection.FlatStyle = System.Windows.Forms.FlatStyle.Flat; + swatchSelection.Location = new System.Drawing.Point(330, 156); + swatchSelection.Name = "swatchSelection"; + swatchSelection.Size = new System.Drawing.Size(60, 24); + swatchSelection.TabIndex = 20; + swatchSelection.UseVisualStyleBackColor = true; + swatchSelection.Click += SwatchSelection_Click; + // + // headingStart + // + headingStart.AutoSize = true; + headingStart.Location = new System.Drawing.Point(12, 194); + headingStart.Name = "headingStart"; + headingStart.Size = new System.Drawing.Size(202, 15); + headingStart.TabIndex = 21; + headingStart.Text = "New and opened multis start with"; + // + // checkWorkPlane + // + checkWorkPlane.AutoSize = true; + checkWorkPlane.Location = new System.Drawing.Point(24, 218); + checkWorkPlane.Name = "checkWorkPlane"; + checkWorkPlane.Size = new System.Drawing.Size(129, 19); + checkWorkPlane.TabIndex = 23; + checkWorkPlane.Text = "Work plane shown"; + checkWorkPlane.UseVisualStyleBackColor = true; + checkWorkPlane.CheckedChanged += CheckWorkPlane_CheckedChanged; + // + // checkGrid + // + checkGrid.AutoSize = true; + checkGrid.Location = new System.Drawing.Point(24, 242); + checkGrid.Name = "checkGrid"; + checkGrid.Size = new System.Drawing.Size(86, 19); + checkGrid.TabIndex = 24; + checkGrid.Text = "Grid shown"; + checkGrid.UseVisualStyleBackColor = true; + checkGrid.CheckedChanged += CheckGrid_CheckedChanged; + // + // checkHideFloorsAbove + // + checkHideFloorsAbove.AutoSize = true; + checkHideFloorsAbove.Location = new System.Drawing.Point(24, 266); + checkHideFloorsAbove.Name = "checkHideFloorsAbove"; + checkHideFloorsAbove.Size = new System.Drawing.Size(365, 19); + checkHideFloorsAbove.TabIndex = 25; + checkHideFloorsAbove.Text = "Floors above the active one hidden (off: drawn faintly)"; + checkHideFloorsAbove.UseVisualStyleBackColor = true; + checkHideFloorsAbove.CheckedChanged += CheckHideFloorsAbove_CheckedChanged; + // + // buttonDefaults + // + buttonDefaults.Location = new System.Drawing.Point(12, 302); + buttonDefaults.Name = "buttonDefaults"; + buttonDefaults.Size = new System.Drawing.Size(80, 23); + buttonDefaults.TabIndex = 26; + buttonDefaults.Text = "Defaults"; + buttonDefaults.UseVisualStyleBackColor = true; + buttonDefaults.Click += Defaults_Click; + // + // buttonOk + // + buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + buttonOk.Location = new System.Drawing.Point(236, 302); + buttonOk.Name = "buttonOk"; + buttonOk.Size = new System.Drawing.Size(76, 23); + buttonOk.TabIndex = 27; + buttonOk.Text = "OK"; + buttonOk.UseVisualStyleBackColor = true; + // + // buttonCancel + // + buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + buttonCancel.Location = new System.Drawing.Point(320, 302); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new System.Drawing.Size(76, 23); + buttonCancel.TabIndex = 28; + buttonCancel.Text = "Cancel"; + buttonCancel.UseVisualStyleBackColor = true; + // + // EditorSettingsDialog + // + AcceptButton = buttonOk; + AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + CancelButton = buttonCancel; + ClientSize = new System.Drawing.Size(410, 340); + Controls.Add(headingColours); + Controls.Add(labelBackground); + Controls.Add(swatchBackground); + Controls.Add(labelWorkPlane); + Controls.Add(labelWorkPlaneOpacity); + Controls.Add(alphaWorkPlane); + Controls.Add(swatchWorkPlane); + Controls.Add(labelGrid); + Controls.Add(labelGridOpacity); + Controls.Add(alphaGrid); + Controls.Add(swatchGrid); + Controls.Add(labelOutline); + Controls.Add(labelOutlineOpacity); + Controls.Add(alphaOutline); + Controls.Add(swatchOutline); + Controls.Add(labelSelection); + Controls.Add(swatchSelection); + Controls.Add(headingStart); + Controls.Add(checkWorkPlane); + Controls.Add(checkGrid); + Controls.Add(checkHideFloorsAbove); + Controls.Add(buttonDefaults); + Controls.Add(buttonOk); + Controls.Add(buttonCancel); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "EditorSettingsDialog"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Multi Editor settings"; + ((System.ComponentModel.ISupportInitialize)alphaWorkPlane).EndInit(); + ((System.ComponentModel.ISupportInitialize)alphaGrid).EndInit(); + ((System.ComponentModel.ISupportInitialize)alphaOutline).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label headingColours; + private System.Windows.Forms.Label labelBackground; + private System.Windows.Forms.Button swatchBackground; + private System.Windows.Forms.Label labelWorkPlane; + private System.Windows.Forms.Label labelWorkPlaneOpacity; + private System.Windows.Forms.NumericUpDown alphaWorkPlane; + private System.Windows.Forms.Button swatchWorkPlane; + private System.Windows.Forms.Label labelGrid; + private System.Windows.Forms.Label labelGridOpacity; + private System.Windows.Forms.NumericUpDown alphaGrid; + private System.Windows.Forms.Button swatchGrid; + private System.Windows.Forms.Label labelOutline; + private System.Windows.Forms.Label labelOutlineOpacity; + private System.Windows.Forms.NumericUpDown alphaOutline; + private System.Windows.Forms.Button swatchOutline; + private System.Windows.Forms.Label labelSelection; + private System.Windows.Forms.Button swatchSelection; + private System.Windows.Forms.Label headingStart; + private System.Windows.Forms.CheckBox checkWorkPlane; + private System.Windows.Forms.CheckBox checkGrid; + private System.Windows.Forms.CheckBox checkHideFloorsAbove; + private System.Windows.Forms.Button buttonDefaults; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.Button buttonCancel; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs new file mode 100644 index 00000000..b8adf601 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs @@ -0,0 +1,170 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The settings dialog: colours with their opacity, and how new documents start. + /// + internal sealed partial class EditorSettingsDialog : Form + { + private readonly EditorSettings _settings; + private readonly List _refresh = new List(); + + public EditorSettingsDialog(EditorSettings current) + { + _settings = current.Clone(); + + InitializeComponent(); + + headingColours.Font = new Font(Font, FontStyle.Bold); + headingStart.Font = new Font(Font, FontStyle.Bold); + + ColorRow(swatchBackground, null, () => _settings.EffectiveBackground); + ColorRow(swatchWorkPlane, alphaWorkPlane, () => _settings.WorkPlane); + ColorRow(swatchGrid, alphaGrid, () => _settings.Grid); + ColorRow(swatchOutline, alphaOutline, () => _settings.Outline); + ColorRow(swatchSelection, null, () => _settings.SelectionBox); + + CheckRow(checkWorkPlane, () => _settings.StartWithWorkPlane); + CheckRow(checkGrid, () => _settings.StartWithGrid); + CheckRow(checkHideFloorsAbove, () => _settings.HideFloorsAbove); + } + + /// The edited copy; apply it when the dialog returns OK. + public EditorSettings Result => _settings; + + /// Shows the current value in a row's swatch and opacity box, now and again after a reset. + private void ColorRow(Button swatch, NumericUpDown alpha, Func get) + { + void Refresh() + { + Color c = get(); + swatch.BackColor = Color.FromArgb(c.R, c.G, c.B); + if (alpha != null) + { + alpha.Value = Math.Clamp((int)Math.Round(c.A / 2.55), 5, 100); + } + } + + Refresh(); + _refresh.Add(Refresh); + } + + private void CheckRow(CheckBox box, Func get) + { + box.Checked = get(); + _refresh.Add(() => box.Checked = get()); + } + + private void PickColor(Button swatch, Func get, Action set) + { + Color c = get(); + using var dialog = new ColorDialog { Color = Color.FromArgb(c.R, c.G, c.B), FullOpen = true }; + if (dialog.ShowDialog(this) == DialogResult.OK) + { + set(Color.FromArgb(c.A, dialog.Color.R, dialog.Color.G, dialog.Color.B)); + swatch.BackColor = Color.FromArgb(dialog.Color.R, dialog.Color.G, dialog.Color.B); + } + } + + private static void ChangeOpacity(NumericUpDown alpha, Func get, Action set) + { + Color c = get(); + set(Color.FromArgb((int)Math.Round((double)alpha.Value * 2.55), c.R, c.G, c.B)); + } + + private void SwatchBackground_Click(object sender, EventArgs e) + { + PickColor(swatchBackground, () => _settings.EffectiveBackground, c => _settings.Background = c); + } + + private void SwatchWorkPlane_Click(object sender, EventArgs e) + { + PickColor(swatchWorkPlane, () => _settings.WorkPlane, c => _settings.WorkPlane = c); + } + + private void SwatchGrid_Click(object sender, EventArgs e) + { + PickColor(swatchGrid, () => _settings.Grid, c => _settings.Grid = c); + } + + private void SwatchOutline_Click(object sender, EventArgs e) + { + PickColor(swatchOutline, () => _settings.Outline, c => _settings.Outline = c); + } + + private void SwatchSelection_Click(object sender, EventArgs e) + { + PickColor(swatchSelection, () => _settings.SelectionBox, c => _settings.SelectionBox = c); + } + + private void AlphaWorkPlane_ValueChanged(object sender, EventArgs e) + { + ChangeOpacity(alphaWorkPlane, () => _settings.WorkPlane, c => _settings.WorkPlane = c); + } + + private void AlphaGrid_ValueChanged(object sender, EventArgs e) + { + ChangeOpacity(alphaGrid, () => _settings.Grid, c => _settings.Grid = c); + } + + private void AlphaOutline_ValueChanged(object sender, EventArgs e) + { + ChangeOpacity(alphaOutline, () => _settings.Outline, c => _settings.Outline = c); + } + + private void CheckWorkPlane_CheckedChanged(object sender, EventArgs e) + { + _settings.StartWithWorkPlane = checkWorkPlane.Checked; + } + + private void CheckGrid_CheckedChanged(object sender, EventArgs e) + { + _settings.StartWithGrid = checkGrid.Checked; + } + + private void CheckHideFloorsAbove_CheckedChanged(object sender, EventArgs e) + { + _settings.HideFloorsAbove = checkHideFloorsAbove.Checked; + } + + private void Defaults_Click(object sender, EventArgs e) + { + var defaults = new EditorSettings + { + // The layout is not part of this dialog; a reset leaves it alone. + PreviewTerrain = _settings.PreviewTerrain, + ShowTileBrowser = _settings.ShowTileBrowser, + ShowInspector = _settings.ShowInspector, + TileBrowserWidth = _settings.TileBrowserWidth, + InspectorWidth = _settings.InspectorWidth, + HousePiecesHeight = _settings.HousePiecesHeight, + DesignLibraryFolder = _settings.DesignLibraryFolder + }; + foreach (System.Reflection.PropertyInfo property in typeof(EditorSettings).GetProperties()) + { + if (property.CanWrite && property.DeclaringType == typeof(EditorSettings)) + { + property.SetValue(_settings, property.GetValue(defaults)); + } + } + + foreach (Action refresh in _refresh) + { + refresh(); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.resx b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.resx new file mode 100644 index 00000000..1af7de15 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.Designer.cs new file mode 100644 index 00000000..6e2d9a11 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.Designer.cs @@ -0,0 +1,217 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class FloorsDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + hintLabel = new System.Windows.Forms.Label(); + _grid = new System.Windows.Forms.DataGridView(); + columnLevel = new System.Windows.Forms.DataGridViewTextBoxColumn(); + columnStart = new System.Windows.Forms.DataGridViewTextBoxColumn(); + buttonAdd = new System.Windows.Forms.Button(); + buttonRemove = new System.Windows.Forms.Button(); + presetsLabel = new System.Windows.Forms.Label(); + buttonGround = new System.Windows.Forms.Button(); + buttonFoundation = new System.Windows.Forms.Button(); + buttonDetected = new System.Windows.Forms.Button(); + buttonFitted = new System.Windows.Forms.Button(); + buttonOk = new System.Windows.Forms.Button(); + buttonCancel = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)_grid).BeginInit(); + SuspendLayout(); + // + // hintLabel + // + hintLabel.Location = new System.Drawing.Point(12, 10); + hintLabel.Name = "hintLabel"; + hintLabel.Size = new System.Drawing.Size(446, 34); + hintLabel.TabIndex = 0; + hintLabel.Text = "Each level starts at its Z and runs up to the next one. Floors in the client are 20 high; a house on a foundation has its first floor at Z 7."; + // + // _grid + // + _grid.AllowUserToAddRows = false; + _grid.AllowUserToDeleteRows = false; + _grid.AllowUserToResizeRows = false; + _grid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + _grid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { columnLevel, columnStart }); + _grid.Location = new System.Drawing.Point(12, 50); + _grid.MultiSelect = false; + _grid.Name = "_grid"; + _grid.RowHeadersVisible = false; + _grid.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + _grid.Size = new System.Drawing.Size(270, 280); + _grid.TabIndex = 1; + // + // columnLevel + // + columnLevel.FillWeight = 65F; + columnLevel.HeaderText = "Level"; + columnLevel.Name = "columnLevel"; + // + // columnStart + // + columnStart.FillWeight = 35F; + columnStart.HeaderText = "Starts at Z"; + columnStart.Name = "columnStart"; + // + // buttonAdd + // + buttonAdd.Location = new System.Drawing.Point(294, 50); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new System.Drawing.Size(164, 26); + buttonAdd.TabIndex = 2; + buttonAdd.Text = "Add a level above"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // buttonRemove + // + buttonRemove.Location = new System.Drawing.Point(294, 80); + buttonRemove.Name = "buttonRemove"; + buttonRemove.Size = new System.Drawing.Size(164, 26); + buttonRemove.TabIndex = 3; + buttonRemove.Text = "Remove the selected level"; + buttonRemove.UseVisualStyleBackColor = true; + buttonRemove.Click += ButtonRemove_Click; + // + // presetsLabel + // + presetsLabel.AutoSize = true; + presetsLabel.ForeColor = System.Drawing.SystemColors.GrayText; + presetsLabel.Location = new System.Drawing.Point(294, 122); + presetsLabel.Name = "presetsLabel"; + presetsLabel.Size = new System.Drawing.Size(45, 15); + presetsLabel.TabIndex = 4; + presetsLabel.Text = "Presets"; + // + // buttonGround + // + buttonGround.Location = new System.Drawing.Point(294, 142); + buttonGround.Name = "buttonGround"; + buttonGround.Size = new System.Drawing.Size(164, 26); + buttonGround.TabIndex = 5; + buttonGround.Text = "From the ground (Z 0)"; + buttonGround.UseVisualStyleBackColor = true; + buttonGround.Click += ButtonGround_Click; + // + // buttonFoundation + // + buttonFoundation.Location = new System.Drawing.Point(294, 172); + buttonFoundation.Name = "buttonFoundation"; + buttonFoundation.Size = new System.Drawing.Size(164, 26); + buttonFoundation.TabIndex = 6; + buttonFoundation.Text = "On a foundation (Z 7)"; + buttonFoundation.UseVisualStyleBackColor = true; + buttonFoundation.Click += ButtonFoundation_Click; + // + // buttonDetected + // + buttonDetected.Location = new System.Drawing.Point(294, 202); + buttonDetected.Name = "buttonDetected"; + buttonDetected.Size = new System.Drawing.Size(164, 26); + buttonDetected.TabIndex = 7; + buttonDetected.Text = "Detected first floor"; + buttonDetected.UseVisualStyleBackColor = true; + buttonDetected.Click += ButtonDetected_Click; + // + // buttonFitted + // + buttonFitted.Location = new System.Drawing.Point(294, 232); + buttonFitted.Name = "buttonFitted"; + buttonFitted.Size = new System.Drawing.Size(164, 26); + buttonFitted.TabIndex = 8; + buttonFitted.Text = "Fit to this design's roof"; + buttonFitted.UseVisualStyleBackColor = true; + buttonFitted.Click += ButtonFitted_Click; + // + // buttonOk + // + buttonOk.Location = new System.Drawing.Point(298, 342); + buttonOk.Name = "buttonOk"; + buttonOk.Size = new System.Drawing.Size(76, 23); + buttonOk.TabIndex = 9; + buttonOk.Text = "OK"; + buttonOk.UseVisualStyleBackColor = true; + buttonOk.Click += ButtonOk_Click; + // + // buttonCancel + // + buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + buttonCancel.Location = new System.Drawing.Point(382, 342); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new System.Drawing.Size(76, 23); + buttonCancel.TabIndex = 10; + buttonCancel.Text = "Cancel"; + buttonCancel.UseVisualStyleBackColor = true; + // + // FloorsDialog + // + AcceptButton = buttonOk; + AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + CancelButton = buttonCancel; + ClientSize = new System.Drawing.Size(470, 380); + Controls.Add(hintLabel); + Controls.Add(_grid); + Controls.Add(buttonAdd); + Controls.Add(buttonRemove); + Controls.Add(presetsLabel); + Controls.Add(buttonGround); + Controls.Add(buttonFoundation); + Controls.Add(buttonDetected); + Controls.Add(buttonFitted); + Controls.Add(buttonOk); + Controls.Add(buttonCancel); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "FloorsDialog"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Floors of this design"; + ((System.ComponentModel.ISupportInitialize)_grid).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.Label hintLabel; + private System.Windows.Forms.DataGridView _grid; + private System.Windows.Forms.DataGridViewTextBoxColumn columnLevel; + private System.Windows.Forms.DataGridViewTextBoxColumn columnStart; + private System.Windows.Forms.Button buttonAdd; + private System.Windows.Forms.Button buttonRemove; + private System.Windows.Forms.Label presetsLabel; + private System.Windows.Forms.Button buttonGround; + private System.Windows.Forms.Button buttonFoundation; + private System.Windows.Forms.Button buttonDetected; + private System.Windows.Forms.Button buttonFitted; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.Button buttonCancel; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.cs new file mode 100644 index 00000000..099408c9 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.cs @@ -0,0 +1,141 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Editing; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Lets the user split a design into levels: each row a name and the Z the level starts at. + /// A level runs up to where the next one starts; the lowest also takes what is below it and + /// the highest what is above. Presets fill in the usual splits. + /// + internal sealed partial class FloorsDialog : Form + { + private readonly EditorSession _session; + + public FloorsDialog(EditorSession session) + { + _session = session; + + InitializeComponent(); + + buttonDetected.Text = $"Detected first floor (Z {session.FirstFloorZ})"; + Fill(session.LevelDefinitions); + } + + /// The levels as edited, valid after the dialog returned OK. + public List Result { get; } = new List(); + + private void ButtonAdd_Click(object sender, EventArgs e) + { + AddAbove(); + } + + private void ButtonRemove_Click(object sender, EventArgs e) + { + RemoveSelected(); + } + + private void ButtonGround_Click(object sender, EventArgs e) + { + Fill(EditorSession.StandardLevels(0)); + } + + private void ButtonFoundation_Click(object sender, EventArgs e) + { + Fill(EditorSession.StandardLevels(7)); + } + + private void ButtonDetected_Click(object sender, EventArgs e) + { + Fill(EditorSession.StandardLevels(_session.FirstFloorZ)); + } + + private void ButtonFitted_Click(object sender, EventArgs e) + { + Fill(_session.FittedLevels()); + } + + private void ButtonOk_Click(object sender, EventArgs e) + { + Accept(); + } + + private void Fill(IEnumerable levels) + { + _grid.Rows.Clear(); + foreach (LevelDefinition level in levels) + { + _grid.Rows.Add(level.Name, level.StartZ.ToString()); + } + } + + /// Adds a level one storey (20) above the highest, named as the next floor. + private void AddAbove() + { + int top = int.MinValue; + foreach (DataGridViewRow row in _grid.Rows) + { + if (int.TryParse(Convert.ToString(row.Cells[1].Value), out int z)) + { + top = Math.Max(top, z); + } + } + + int start = top == int.MinValue ? 0 : Math.Min(sbyte.MaxValue, top + 20); + _grid.Rows.Add($"Level {_grid.Rows.Count + 1}", start.ToString()); + _grid.CurrentCell = _grid.Rows[^1].Cells[0]; + } + + private void RemoveSelected() + { + if (_grid.CurrentRow != null && _grid.Rows.Count > 1) + { + _grid.Rows.Remove(_grid.CurrentRow); + } + } + + private void Accept() + { + _grid.EndEdit(); + Result.Clear(); + var starts = new HashSet(); + foreach (DataGridViewRow row in _grid.Rows) + { + string name = Convert.ToString(row.Cells[0].Value)?.Trim(); + if (!int.TryParse(Convert.ToString(row.Cells[1].Value), out int z) || z < sbyte.MinValue || z > sbyte.MaxValue) + { + Complain(row, $"Enter a whole number from {sbyte.MinValue} to {sbyte.MaxValue} for where the level starts."); + return; + } + + if (!starts.Add(z)) + { + Complain(row, $"Two levels start at Z {z}. Each level needs its own start."); + return; + } + + Result.Add(new LevelDefinition(string.IsNullOrEmpty(name) ? $"Level {Result.Count + 1}" : name, z)); + } + + DialogResult = DialogResult.OK; + Close(); + } + + private void Complain(DataGridViewRow row, string message) + { + _grid.CurrentCell = row.Cells[1]; + MessageBox.Show(this, message, Text, MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.resx b/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.resx new file mode 100644 index 00000000..1af7de15 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/FloorsDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.Designer.cs new file mode 100644 index 00000000..1de665f5 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.Designer.cs @@ -0,0 +1,295 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class FolderImportDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + folderLabel = new System.Windows.Forms.Label(); + _folder = new System.Windows.Forms.TextBox(); + _browse = new System.Windows.Forms.Button(); + _recursive = new System.Windows.Forms.CheckBox(); + _scanButton = new System.Windows.Forms.Button(); + filterLabel = new System.Windows.Forms.Label(); + _filter = new System.Windows.Forms.TextBox(); + formatLabel = new System.Windows.Forms.Label(); + _format = new System.Windows.Forms.ComboBox(); + _list = new System.Windows.Forms.ListView(); + columnHeaderName = new System.Windows.Forms.ColumnHeader(); + columnHeaderFormat = new System.Windows.Forms.ColumnHeader(); + columnHeaderTiles = new System.Windows.Forms.ColumnHeader(); + columnHeaderFile = new System.Windows.Forms.ColumnHeader(); + _preview = new System.Windows.Forms.PictureBox(); + _info = new System.Windows.Forms.Label(); + _status = new System.Windows.Forms.Label(); + _ok = new System.Windows.Forms.Button(); + cancel = new System.Windows.Forms.Button(); + _previewTimer = new System.Windows.Forms.Timer(components); + ((System.ComponentModel.ISupportInitialize)_preview).BeginInit(); + SuspendLayout(); + // + // folderLabel + // + folderLabel.AutoSize = true; + folderLabel.Location = new System.Drawing.Point(10, 13); + folderLabel.Name = "folderLabel"; + folderLabel.Size = new System.Drawing.Size(43, 15); + folderLabel.TabIndex = 0; + folderLabel.Text = "Folder:"; + // + // _folder + // + _folder.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _folder.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; + _folder.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystemDirectories; + _folder.Location = new System.Drawing.Point(60, 10); + _folder.Name = "_folder"; + _folder.Size = new System.Drawing.Size(500, 23); + _folder.TabIndex = 1; + // + // _browse + // + _browse.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + _browse.Location = new System.Drawing.Point(566, 9); + _browse.Name = "_browse"; + _browse.Size = new System.Drawing.Size(80, 25); + _browse.TabIndex = 2; + _browse.Text = "Browse..."; + _browse.UseVisualStyleBackColor = true; + _browse.Click += Browse_Click; + // + // _recursive + // + _recursive.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + _recursive.AutoSize = true; + _recursive.Checked = true; + _recursive.CheckState = System.Windows.Forms.CheckState.Checked; + _recursive.Location = new System.Drawing.Point(656, 13); + _recursive.Name = "_recursive"; + _recursive.Size = new System.Drawing.Size(125, 19); + _recursive.TabIndex = 3; + _recursive.Text = "Include subfolders"; + _recursive.UseVisualStyleBackColor = true; + // + // _scanButton + // + _scanButton.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + _scanButton.Location = new System.Drawing.Point(805, 9); + _scanButton.Name = "_scanButton"; + _scanButton.Size = new System.Drawing.Size(85, 25); + _scanButton.TabIndex = 4; + _scanButton.Text = "Scan"; + _scanButton.UseVisualStyleBackColor = true; + _scanButton.Click += Scan_Click; + // + // filterLabel + // + filterLabel.AutoSize = true; + filterLabel.Location = new System.Drawing.Point(10, 46); + filterLabel.Name = "filterLabel"; + filterLabel.Size = new System.Drawing.Size(36, 15); + filterLabel.TabIndex = 5; + filterLabel.Text = "Filter:"; + // + // _filter + // + _filter.Location = new System.Drawing.Point(60, 43); + _filter.Name = "_filter"; + _filter.Size = new System.Drawing.Size(200, 23); + _filter.TabIndex = 6; + _filter.TextChanged += Filter_TextChanged; + // + // formatLabel + // + formatLabel.AutoSize = true; + formatLabel.Location = new System.Drawing.Point(275, 46); + formatLabel.Name = "formatLabel"; + formatLabel.Size = new System.Drawing.Size(48, 15); + formatLabel.TabIndex = 7; + formatLabel.Text = "Format:"; + // + // _format + // + _format.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _format.Location = new System.Drawing.Point(330, 43); + _format.MaxDropDownItems = 14; + _format.Name = "_format"; + _format.Size = new System.Drawing.Size(220, 23); + _format.TabIndex = 7; + _format.SelectedIndexChanged += Format_SelectedIndexChanged; + // + // _list + // + _list.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnHeaderName, columnHeaderFormat, columnHeaderTiles, columnHeaderFile }); + _list.FullRowSelect = true; + _list.HideSelection = false; + _list.Location = new System.Drawing.Point(10, 76); + _list.Name = "_list"; + _list.Size = new System.Drawing.Size(540, 434); + _list.TabIndex = 8; + _list.UseCompatibleStateImageBehavior = false; + _list.View = System.Windows.Forms.View.Details; + _list.VirtualMode = true; + _list.RetrieveVirtualItem += List_RetrieveVirtualItem; + _list.SelectedIndexChanged += List_SelectedIndexChanged; + _list.VirtualItemsSelectionRangeChanged += List_VirtualItemsSelectionRangeChanged; + _list.DoubleClick += List_DoubleClick; + _list.KeyDown += List_KeyDown; + // + // columnHeaderName + // + columnHeaderName.Text = "Name"; + columnHeaderName.Width = 200; + // + // columnHeaderFormat + // + columnHeaderFormat.Text = "Format"; + columnHeaderFormat.Width = 105; + // + // columnHeaderTiles + // + columnHeaderTiles.Text = "Tiles"; + columnHeaderTiles.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + columnHeaderTiles.Width = 55; + // + // columnHeaderFile + // + columnHeaderFile.Text = "File"; + columnHeaderFile.Width = 155; + // + // _preview + // + _preview.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + _preview.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _preview.Location = new System.Drawing.Point(560, 76); + _preview.Name = "_preview"; + _preview.Size = new System.Drawing.Size(330, 360); + _preview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + _preview.TabIndex = 9; + _preview.TabStop = false; + // + // _info + // + _info.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + _info.Location = new System.Drawing.Point(560, 442); + _info.Name = "_info"; + _info.Size = new System.Drawing.Size(330, 68); + _info.TabIndex = 10; + // + // _status + // + _status.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _status.AutoEllipsis = true; + _status.Location = new System.Drawing.Point(10, 524); + _status.Name = "_status"; + _status.Size = new System.Drawing.Size(700, 18); + _status.TabIndex = 11; + // + // _ok + // + _ok.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + _ok.Enabled = false; + _ok.Location = new System.Drawing.Point(720, 520); + _ok.Name = "_ok"; + _ok.Size = new System.Drawing.Size(85, 25); + _ok.TabIndex = 12; + _ok.Text = "Open"; + _ok.UseVisualStyleBackColor = true; + _ok.Click += Ok_Click; + // + // cancel + // + cancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + cancel.Location = new System.Drawing.Point(810, 520); + cancel.Name = "cancel"; + cancel.Size = new System.Drawing.Size(80, 25); + cancel.TabIndex = 13; + cancel.Text = "Cancel"; + cancel.UseVisualStyleBackColor = true; + // + // _previewTimer + // + _previewTimer.Interval = 120; + _previewTimer.Tick += PreviewTimer_Tick; + // + // FolderImportDialog + // + CancelButton = cancel; + ClientSize = new System.Drawing.Size(900, 556); + Controls.Add(folderLabel); + Controls.Add(_folder); + Controls.Add(_browse); + Controls.Add(_recursive); + Controls.Add(_scanButton); + Controls.Add(filterLabel); + Controls.Add(_filter); + Controls.Add(formatLabel); + Controls.Add(_format); + Controls.Add(_list); + Controls.Add(_preview); + Controls.Add(_info); + Controls.Add(_status); + Controls.Add(_ok); + Controls.Add(cancel); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; + MinimizeBox = false; + MinimumSize = new System.Drawing.Size(720, 400); + Name = "FolderImportDialog"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Import multis from folder"; + ((System.ComponentModel.ISupportInitialize)_preview).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label folderLabel; + private System.Windows.Forms.TextBox _folder; + private System.Windows.Forms.Button _browse; + private System.Windows.Forms.CheckBox _recursive; + private System.Windows.Forms.Button _scanButton; + private System.Windows.Forms.Label filterLabel; + private System.Windows.Forms.TextBox _filter; + private System.Windows.Forms.Label formatLabel; + private System.Windows.Forms.ComboBox _format; + private System.Windows.Forms.ListView _list; + private System.Windows.Forms.ColumnHeader columnHeaderName; + private System.Windows.Forms.ColumnHeader columnHeaderFormat; + private System.Windows.Forms.ColumnHeader columnHeaderTiles; + private System.Windows.Forms.ColumnHeader columnHeaderFile; + private System.Windows.Forms.PictureBox _preview; + private System.Windows.Forms.Label _info; + private System.Windows.Forms.Label _status; + private System.Windows.Forms.Button _ok; + private System.Windows.Forms.Button cancel; + private System.Windows.Forms.Timer _previewTimer; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.cs new file mode 100644 index 00000000..aa65b283 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.cs @@ -0,0 +1,647 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using Ultima; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Scans a folder (and the folders below it) for every file format the editor imports, lists + /// each multi with the format it was recognised as, and previews the highlighted one. Files + /// that could not be read are listed greyed out with the reason. + /// + internal sealed partial class FolderImportDialog : Form + { + /// Designs with more tiles than this are not drawn on selection: it would stall the list. + private const int _previewLimit = 8000; + + /// Format filter key for the rows that failed. + private const string _errorsKey = "\0errors"; + + private sealed class Row + { + public ImportedMulti Multi; + public string File; + public string RelativePath; + public string Error; + + public string Name => Multi?.Name ?? Path.GetFileName(File); + + public string FormatText => Multi != null ? MultiFileImport.FormatName(Multi.Format) : "error"; + + public string FilterKey => Multi != null ? FormatText : _errorsKey; + } + + private sealed record ScanBatch(List Rows, int FilesChecked); + + /// An entry of the format list; a null key means all formats. + private sealed record FormatChoice(string Key, string Text) + { + public override string ToString() => Text; + } + + private readonly List _all = new List(); + private readonly List _shown = new List(); + private readonly HashSet _filesWithMultis = new HashSet(StringComparer.OrdinalIgnoreCase); + private string _formatFilter; + private bool _syncingFormats; + private CancellationTokenSource _scan; + private int _filesChecked; + private int _multiCount; + private int _failedCount; + private bool _bulkSelecting; + + public FolderImportDialog() + { + InitializeComponent(); + + EditorSettings settings = EditorSettings.Current; + _folder.Text = settings.ImportFolder ?? string.Empty; + _recursive.Checked = settings.ImportRecursive; + RebuildFormatChoices(); + UpdateSelection(); + } + + /// The multis to open, read when Open was pressed. + public List Opened { get; } = new List(); + + /// Chosen multis whose items could not be read when Open was pressed. + public List Failures { get; } = new List(); + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + if (_folder.Text.Length > 0 && Directory.Exists(_folder.Text)) + { + StartScan(); + _filter.Focus(); + } + else + { + _status.Text = "Choose a folder to look for multi files in."; + _folder.Focus(); + } + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + _scan?.Cancel(); + base.OnFormClosing(e); + } + + protected override void OnFormClosed(FormClosedEventArgs e) + { + _previewTimer.Stop(); + SetPreview(null); + base.OnFormClosed(e); + } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (_folder.Focused && keyData == Keys.Enter) + { + if (_scan == null) + { + StartScan(); + } + + return true; + } + + // Arrow keys in the filter box move the list selection, so the list needs no focus. + if (_filter.Focused && (keyData == Keys.Down || keyData == Keys.Up) && _shown.Count > 0) + { + int index = _list.SelectedIndices.Count > 0 ? _list.SelectedIndices[0] : -1; + index = Math.Clamp(index + (keyData == Keys.Down ? 1 : -1), 0, _shown.Count - 1); + _list.SelectedIndices.Clear(); + _list.SelectedIndices.Add(index); + _list.EnsureVisible(index); + return true; + } + + if (_filter.Focused && keyData == Keys.Enter) + { + Accept(); + return true; + } + + return base.ProcessCmdKey(ref msg, keyData); + } + + private void Browse_Click(object sender, EventArgs e) + { + using var dialog = new FolderBrowserDialog + { + Description = "Folder with multi files to import", + UseDescriptionForTitle = true, + SelectedPath = _folder.Text + }; + if (dialog.ShowDialog(this) == DialogResult.OK) + { + _folder.Text = dialog.SelectedPath; + StartScan(); + } + } + + private void Scan_Click(object sender, EventArgs e) + { + if (_scan != null) + { + _scan.Cancel(); + } + else + { + StartScan(); + } + } + + private void Filter_TextChanged(object sender, EventArgs e) + { + RebuildList(); + } + + private void Format_SelectedIndexChanged(object sender, EventArgs e) + { + if (_syncingFormats || _format.SelectedItem is not FormatChoice choice || choice.Key == _formatFilter) + { + return; + } + + _formatFilter = choice.Key; + RebuildList(); + } + + private void List_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) + { + // A virtual list must always get an item, even one it asks for while it shrinks. + if (e.ItemIndex < 0 || e.ItemIndex >= _shown.Count) + { + e.Item = new ListViewItem(new[] { string.Empty, string.Empty, string.Empty, string.Empty }); + return; + } + + Row row = _shown[e.ItemIndex]; + e.Item = new ListViewItem(row.Name); + e.Item.SubItems.Add(row.FormatText); + e.Item.SubItems.Add(row.Multi != null ? row.Multi.TileCount.ToString("N0") : string.Empty); + e.Item.SubItems.Add(row.RelativePath); + if (row.Multi == null) + { + e.Item.ForeColor = SystemColors.GrayText; + } + } + + private void List_SelectedIndexChanged(object sender, EventArgs e) + { + UpdateSelection(); + } + + // Shift ranges in a virtual list. + private void List_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e) + { + UpdateSelection(); + } + + private void List_DoubleClick(object sender, EventArgs e) + { + Accept(); + } + + private void List_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + e.Handled = e.SuppressKeyPress = true; + Accept(); + } + else if (e.KeyCode == Keys.A && e.Control) + { + // Select all shown rows; a virtual list has no built-in Ctrl+A. + e.Handled = e.SuppressKeyPress = true; + _bulkSelecting = true; + try + { + for (int i = 0; i < _shown.Count; i++) + { + _list.SelectedIndices.Add(i); + } + } + finally + { + _bulkSelecting = false; + } + + UpdateSelection(); + } + } + + private void Ok_Click(object sender, EventArgs e) + { + Accept(); + } + + private void PreviewTimer_Tick(object sender, EventArgs e) + { + _previewTimer.Stop(); + ShowPreview(); + } + + // ---------------------------------------------------------------- scanning + + private async void StartScan() + { + string folder = _folder.Text.Trim(); + if (folder.Length == 0 || !Directory.Exists(folder)) + { + _status.Text = "The folder does not exist."; + return; + } + + bool recursive = _recursive.Checked; + EditorSettings settings = EditorSettings.Current; + if (settings.ImportFolder != folder || settings.ImportRecursive != recursive) + { + settings = settings.Clone(); + settings.ImportFolder = folder; + settings.ImportRecursive = recursive; + settings.Apply(); + } + + _all.Clear(); + _filesWithMultis.Clear(); + _filesChecked = _multiCount = _failedCount = 0; + _formatFilter = null; + RebuildFormatChoices(); + RebuildList(); + + var scan = new CancellationTokenSource(); + _scan = scan; + SetScanning(true); + UpdateStatus(scanning: true, stopped: false); + + bool stopped = false; + var progress = new Progress(OnBatch); + try + { + await Task.Run(() => Scan(folder, recursive, progress, scan.Token)); + } + catch (OperationCanceledException) + { + stopped = true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The folder went away or could not be listed; what was found stays. + stopped = true; + } + finally + { + scan.Dispose(); + } + + if (IsDisposed) + { + return; + } + + _scan = null; + SetScanning(false); + UpdateStatus(scanning: false, stopped); + } + + /// Runs off the UI thread: reads every candidate file and reports the rows in batches. + private static void Scan(string folder, bool recursive, IProgress progress, CancellationToken token) + { + var rows = new List(); + int files = 0; + var clock = Stopwatch.StartNew(); + foreach (string file in MultiFileImport.CandidateFiles(folder, recursive)) + { + token.ThrowIfCancellationRequested(); + files++; + + Multis.ImportType? type = MultiFileImport.Detect(file); + if (type != null) + { + string relative = Path.GetRelativePath(folder, file); + try + { + foreach (ImportedMulti multi in MultiFileImport.Load(file, type.Value)) + { + rows.Add(new Row { Multi = multi, File = file, RelativePath = relative }); + } + } + catch (Exception ex) + { + rows.Add(new Row { File = file, RelativePath = relative, Error = $"{MultiFileImport.FormatName(type.Value)}: {MultiFileImport.Reason(ex)}" }); + } + } + + if (clock.ElapsedMilliseconds > 150) + { + progress.Report(new ScanBatch(rows, files)); + rows = new List(); + clock.Restart(); + } + } + + progress.Report(new ScanBatch(rows, files)); + } + + private void OnBatch(ScanBatch batch) + { + if (IsDisposed) + { + return; + } + + _filesChecked = batch.FilesChecked; + _all.AddRange(batch.Rows); + foreach (Row row in batch.Rows) + { + if (row.Multi != null) + { + _multiCount++; + _filesWithMultis.Add(row.File); + } + else + { + _failedCount++; + } + } + + RebuildFormatChoices(); + + // New rows go on the end, so the selection and scroll position stay put. + int before = _shown.Count; + _shown.AddRange(batch.Rows.Where(Matches)); + if (_shown.Count != before) + { + _list.VirtualListSize = _shown.Count; + } + + UpdateStatus(scanning: _scan != null, stopped: false); + } + + private void SetScanning(bool scanning) + { + _scanButton.Text = scanning ? "Stop" : "Scan"; + _folder.Enabled = _browse.Enabled = _recursive.Enabled = !scanning; + } + + private void UpdateStatus(bool scanning, bool stopped) + { + if (scanning) + { + _status.Text = $"Scanning... {_filesChecked:N0} files checked, {_multiCount:N0} multis found"; + return; + } + + if (_all.Count == 0) + { + _status.Text = stopped ? "Stopped. No multis found so far." : "No multi files found in this folder."; + return; + } + + string text = $"{_multiCount:N0} multis in {_filesWithMultis.Count:N0} files"; + if (_failedCount > 0) + { + text += _failedCount == 1 ? ", 1 file could not be read" : $", {_failedCount:N0} files could not be read"; + } + + _status.Text = stopped ? text + " (stopped)" : text; + } + + // ---------------------------------------------------------------- list + + private bool Matches(Row row) + { + if (_formatFilter != null && row.FilterKey != _formatFilter) + { + return false; + } + + string text = _filter.Text.Trim(); + return text.Length == 0 + || row.Name.Contains(text, StringComparison.OrdinalIgnoreCase) + || row.RelativePath.Contains(text, StringComparison.OrdinalIgnoreCase); + } + + private void RebuildList() + { + // Empty the list before its rows change: clearing the selection repaints and asks for + // items, which must still be there. + _list.SelectedIndices.Clear(); + _list.VirtualListSize = 0; + _shown.Clear(); + _shown.AddRange(_all.Where(Matches)); + _list.VirtualListSize = _shown.Count; + _list.Invalidate(); + UpdateSelection(); + } + + /// + /// The format choices: All, each format found (in the import dialog's order) and the files + /// that failed, each with its count. + /// + private void RebuildFormatChoices() + { + var counts = new Dictionary(); + foreach (Row row in _all) + { + counts[row.FilterKey] = counts.TryGetValue(row.FilterKey, out int n) ? n + 1 : 1; + } + + var choices = new List { new FormatChoice(null, _all.Count == 0 ? "All" : $"All ({_all.Count:N0})") }; + foreach (string name in MultiFileImport.Formats.Select(f => MultiFileImport.FormatName(f.Type)).Distinct()) + { + if (counts.TryGetValue(name, out int count)) + { + choices.Add(new FormatChoice(name, $"{name} ({count:N0})")); + } + } + + if (counts.TryGetValue(_errorsKey, out int errors)) + { + choices.Add(new FormatChoice(_errorsKey, $"Could not be read ({errors:N0})")); + } + + _syncingFormats = true; + _format.BeginUpdate(); + try + { + _format.Items.Clear(); + _format.Items.AddRange(choices.ToArray()); + int selected = choices.FindIndex(c => c.Key == _formatFilter); + _format.SelectedIndex = Math.Max(0, selected); + } + finally + { + _format.EndUpdate(); + _syncingFormats = false; + } + } + + private List SelectedRows() + { + var rows = new List(); + foreach (int index in _list.SelectedIndices) + { + if (index < _shown.Count) + { + rows.Add(_shown[index]); + } + } + + return rows; + } + + private Row FocusedRow() + { + int index = _list.FocusedItem?.Index ?? -1; + if (index >= 0 && index < _shown.Count && _list.SelectedIndices.Contains(index)) + { + return _shown[index]; + } + + return _list.SelectedIndices.Count > 0 && _list.SelectedIndices[0] < _shown.Count ? _shown[_list.SelectedIndices[0]] : null; + } + + private void UpdateSelection() + { + if (_bulkSelecting) + { + return; + } + + List rows = SelectedRows(); + int openable = rows.Count(r => r.Multi != null); + _ok.Enabled = openable > 0; + _ok.Text = openable > 1 ? $"Open {openable:N0}" : "Open"; + + if (rows.Count > 1) + { + _info.Text = openable == rows.Count + ? $"{rows.Count:N0} selected: each opens in its own tab" + : $"{rows.Count:N0} selected, {openable:N0} can be opened: each opens in its own tab"; + } + else if (rows.Count == 1) + { + Row row = rows[0]; + _info.Text = row.Multi != null + ? $"{row.FormatText}, {row.Multi.TileCount:N0} tiles\r\n{row.RelativePath}" + : $"Could not be read.\r\n{row.Error}\r\n{row.RelativePath}"; + } + else + { + _info.Text = string.Empty; + } + + _previewTimer.Stop(); + _previewTimer.Start(); + } + + private void ShowPreview() + { + Row row = FocusedRow(); + if (row?.Multi == null) + { + SetPreview(null); + return; + } + + if (row.Multi.TileCount > _previewLimit) + { + SetPreview(null); + _info.Text = $"{row.FormatText}, {row.Multi.TileCount:N0} tiles: too large to preview here. Open it to see it.\r\n{row.RelativePath}"; + return; + } + + MultiComponentList multi; + try + { + multi = row.Multi.Components; + } + catch (Exception ex) + { + SetPreview(null); + _info.Text = $"Could not be read.\r\n{MultiFileImport.Reason(ex)}\r\n{row.RelativePath}"; + return; + } + + if (_list.SelectedIndices.Count == 1) + { + _info.Text = $"{row.FormatText}, {multi.Width}x{multi.Height}, {row.Multi.TileCount:N0} tiles\r\n{row.RelativePath}"; + } + + try + { + SetPreview(multi.GetImage()); + } + catch (Exception) + { + // A multi that cannot be drawn must not take the dialog down; it just has no preview. + SetPreview(null); + } + } + + private void SetPreview(Image image) + { + Image old = _preview.Image; + _preview.Image = image; + old?.Dispose(); + } + + private void Accept() + { + List rows = SelectedRows().Where(r => r.Multi != null).ToList(); + if (rows.Count == 0) + { + return; + } + + _scan?.Cancel(); + Opened.Clear(); + Failures.Clear(); + + Cursor previous = Cursor.Current; + Cursor.Current = Cursors.WaitCursor; + try + { + foreach (Row row in rows) + { + try + { + Opened.Add(new OpenedMulti(row.Multi.Components, row.Multi.Name, null)); + } + catch (Exception ex) + { + Failures.Add(new ImportFailure(row.File, $"{row.Multi.Name}: {MultiFileImport.Reason(ex)}")); + } + } + } + finally + { + Cursor.Current = previous; + } + + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.resx b/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.resx new file mode 100644 index 00000000..44e9f972 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/FolderImportDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + diff --git a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs new file mode 100644 index 00000000..48b6957f --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs @@ -0,0 +1,671 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class InspectorPanel + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + floorsBox = new System.Windows.Forms.GroupBox(); + floorsPage = new System.Windows.Forms.Panel(); + _firstFloor = new System.Windows.Forms.NumericUpDown(); + firstFloorLabel = new System.Windows.Forms.Label(); + _showHidden = new System.Windows.Forms.Button(); + _editFloors = new System.Windows.Forms.Button(); + _limitBar = new System.Windows.Forms.TrackBar(); + _limitLabel = new System.Windows.Forms.Label(); + _limit = new System.Windows.Forms.CheckBox(); + _hideWalls = new System.Windows.Forms.CheckBox(); + _hideAbove = new System.Windows.Forms.CheckBox(); + _floorList = new System.Windows.Forms.ListBox(); + selectionBox = new System.Windows.Forms.GroupBox(); + selectionPage = new System.Windows.Forms.Panel(); + _single = new System.Windows.Forms.Panel(); + _stack = new System.Windows.Forms.ListView(); + columnId = new System.Windows.Forms.ColumnHeader(); + columnZ = new System.Windows.Forms.ColumnHeader(); + columnName = new System.Windows.Forms.ColumnHeader(); + _icons = new System.Windows.Forms.ImageList(components); + stackButtons = new System.Windows.Forms.FlowLayoutPanel(); + stackZPlusButton = new System.Windows.Forms.Button(); + stackZMinusButton = new System.Windows.Forms.Button(); + stackDeleteButton = new System.Windows.Forms.Button(); + stackPickButton = new System.Windows.Forms.Button(); + tilesInCellLabel = new System.Windows.Forms.Label(); + _dynamic = new System.Windows.Forms.CheckBox(); + xLabel = new System.Windows.Forms.Label(); + yLabel = new System.Windows.Forms.Label(); + zLabel = new System.Windows.Forms.Label(); + _x = new System.Windows.Forms.NumericUpDown(); + _y = new System.Windows.Forms.NumericUpDown(); + _z = new System.Windows.Forms.NumericUpDown(); + _infoLabel = new System.Windows.Forms.Label(); + _idLabel = new System.Windows.Forms.Label(); + _thumb = new System.Windows.Forms.PictureBox(); + _group = new System.Windows.Forms.Panel(); + _groupLabel = new System.Windows.Forms.Label(); + groupZMinus5Button = new System.Windows.Forms.Button(); + groupZMinus1Button = new System.Windows.Forms.Button(); + groupZPlus1Button = new System.Windows.Forms.Button(); + groupZPlus5Button = new System.Windows.Forms.Button(); + groupZEqualsLabel = new System.Windows.Forms.Label(); + _groupZ = new System.Windows.Forms.NumericUpDown(); + groupSetZButton = new System.Windows.Forms.Button(); + groupDeleteButton = new System.Windows.Forms.Button(); + groupHideButton = new System.Windows.Forms.Button(); + _hint = new System.Windows.Forms.Label(); + floorsBox.SuspendLayout(); + floorsPage.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_firstFloor).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_limitBar).BeginInit(); + selectionBox.SuspendLayout(); + selectionPage.SuspendLayout(); + _single.SuspendLayout(); + stackButtons.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_x).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_y).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_z).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_thumb).BeginInit(); + _group.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_groupZ).BeginInit(); + SuspendLayout(); + // + // floorsBox + // + floorsBox.Controls.Add(floorsPage); + floorsBox.Dock = System.Windows.Forms.DockStyle.Top; + floorsBox.Location = new System.Drawing.Point(0, 0); + floorsBox.Name = "floorsBox"; + floorsBox.Size = new System.Drawing.Size(150, 316); + floorsBox.TabIndex = 1; + floorsBox.TabStop = false; + floorsBox.Text = "Floors (PgUp / PgDn)"; + // + // floorsPage + // + floorsPage.Controls.Add(_firstFloor); + floorsPage.Controls.Add(firstFloorLabel); + floorsPage.Controls.Add(_showHidden); + floorsPage.Controls.Add(_editFloors); + floorsPage.Controls.Add(_limitBar); + floorsPage.Controls.Add(_limitLabel); + floorsPage.Controls.Add(_limit); + floorsPage.Controls.Add(_hideWalls); + floorsPage.Controls.Add(_hideAbove); + floorsPage.Controls.Add(_floorList); + floorsPage.Dock = System.Windows.Forms.DockStyle.Fill; + floorsPage.Location = new System.Drawing.Point(3, 19); + floorsPage.Name = "floorsPage"; + floorsPage.Size = new System.Drawing.Size(144, 294); + floorsPage.TabIndex = 0; + // + // _firstFloor + // + _firstFloor.Location = new System.Drawing.Point(224, 162); + _firstFloor.Name = "_firstFloor"; + _firstFloor.Size = new System.Drawing.Size(52, 23); + _firstFloor.TabIndex = 0; + _firstFloor.ValueChanged += FirstFloor_ValueChanged; + // + // firstFloorLabel + // + firstFloorLabel.AutoSize = true; + firstFloorLabel.Location = new System.Drawing.Point(4, 165); + firstFloorLabel.Name = "firstFloorLabel"; + firstFloorLabel.Size = new System.Drawing.Size(172, 15); + firstFloorLabel.TabIndex = 1; + firstFloorLabel.Text = "First floor Z (7 on a foundation)"; + // + // _showHidden + // + _showHidden.Location = new System.Drawing.Point(4, 240); + _showHidden.Name = "_showHidden"; + _showHidden.Size = new System.Drawing.Size(160, 26); + _showHidden.TabIndex = 2; + _showHidden.Text = "Show hidden tiles"; + _showHidden.UseVisualStyleBackColor = true; + _showHidden.Click += ShowHidden_Click; + // + // _editFloors + // + _editFloors.Location = new System.Drawing.Point(170, 240); + _editFloors.Name = "_editFloors"; + _editFloors.Size = new System.Drawing.Size(106, 26); + _editFloors.TabIndex = 3; + _editFloors.Text = "Edit floors..."; + _editFloors.UseVisualStyleBackColor = true; + _editFloors.Click += EditFloors_Click; + // + // _limitBar + // + _limitBar.AutoSize = false; + _limitBar.Location = new System.Drawing.Point(4, 210); + _limitBar.Name = "_limitBar"; + _limitBar.Size = new System.Drawing.Size(276, 26); + _limitBar.TabIndex = 4; + _limitBar.TickStyle = System.Windows.Forms.TickStyle.None; + _limitBar.ValueChanged += LimitBar_ValueChanged; + // + // _limitLabel + // + _limitLabel.Location = new System.Drawing.Point(224, 190); + _limitLabel.Name = "_limitLabel"; + _limitLabel.Size = new System.Drawing.Size(52, 18); + _limitLabel.TabIndex = 5; + _limitLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // _limit + // + _limit.AutoSize = true; + _limit.Location = new System.Drawing.Point(4, 188); + _limit.Name = "_limit"; + _limit.Size = new System.Drawing.Size(90, 19); + _limit.TabIndex = 6; + _limit.Text = "Limit height"; + _limit.UseVisualStyleBackColor = true; + _limit.CheckedChanged += Limit_CheckedChanged; + // + // _hideWalls + // + _hideWalls.AutoSize = true; + _hideWalls.Location = new System.Drawing.Point(150, 140); + _hideWalls.Name = "_hideWalls"; + _hideWalls.Size = new System.Drawing.Size(80, 19); + _hideWalls.TabIndex = 9; + _hideWalls.Text = "Hide walls"; + _hideWalls.UseVisualStyleBackColor = true; + _hideWalls.CheckedChanged += HideWalls_CheckedChanged; + // + // _hideAbove + // + _hideAbove.AutoSize = true; + _hideAbove.Location = new System.Drawing.Point(4, 140); + _hideAbove.Name = "_hideAbove"; + _hideAbove.Size = new System.Drawing.Size(119, 19); + _hideAbove.TabIndex = 10; + _hideAbove.Text = "Hide floors above"; + _hideAbove.UseVisualStyleBackColor = true; + _hideAbove.CheckedChanged += HideAbove_CheckedChanged; + // + // _floorList + // + _floorList.Dock = System.Windows.Forms.DockStyle.Top; + _floorList.IntegralHeight = false; + _floorList.Location = new System.Drawing.Point(0, 0); + _floorList.Name = "_floorList"; + _floorList.Size = new System.Drawing.Size(144, 134); + _floorList.TabIndex = 11; + _floorList.SelectedIndexChanged += FloorList_SelectedIndexChanged; + // + // selectionBox + // + selectionBox.Controls.Add(selectionPage); + selectionBox.Dock = System.Windows.Forms.DockStyle.Fill; + selectionBox.Location = new System.Drawing.Point(0, 316); + selectionBox.Name = "selectionBox"; + selectionBox.Size = new System.Drawing.Size(150, 0); + selectionBox.TabIndex = 0; + selectionBox.TabStop = false; + selectionBox.Text = "Selection"; + // + // selectionPage + // + selectionPage.Controls.Add(_single); + selectionPage.Controls.Add(_group); + selectionPage.Controls.Add(_hint); + selectionPage.Dock = System.Windows.Forms.DockStyle.Fill; + selectionPage.Location = new System.Drawing.Point(3, 19); + selectionPage.Name = "selectionPage"; + selectionPage.Size = new System.Drawing.Size(144, 0); + selectionPage.TabIndex = 0; + // + // _single + // + _single.Controls.Add(_stack); + _single.Controls.Add(stackButtons); + _single.Controls.Add(tilesInCellLabel); + _single.Controls.Add(_dynamic); + _single.Controls.Add(xLabel); + _single.Controls.Add(yLabel); + _single.Controls.Add(zLabel); + _single.Controls.Add(_x); + _single.Controls.Add(_y); + _single.Controls.Add(_z); + _single.Controls.Add(_infoLabel); + _single.Controls.Add(_idLabel); + _single.Controls.Add(_thumb); + _single.Dock = System.Windows.Forms.DockStyle.Fill; + _single.Location = new System.Drawing.Point(0, 0); + _single.Name = "_single"; + _single.Size = new System.Drawing.Size(144, 0); + _single.TabIndex = 0; + _single.Visible = false; + // + // _stack + // + _stack.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _stack.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnId, columnZ, columnName }); + _stack.FullRowSelect = true; + _stack.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + _stack.Location = new System.Drawing.Point(4, 154); + _stack.MultiSelect = false; + _stack.Name = "_stack"; + _stack.Size = new System.Drawing.Size(280, 100); + _stack.SmallImageList = _icons; + _stack.TabIndex = 0; + _stack.UseCompatibleStateImageBehavior = false; + _stack.View = System.Windows.Forms.View.Details; + _stack.SelectedIndexChanged += Stack_SelectedIndexChanged; + // + // columnId + // + columnId.Text = "Id"; + columnId.Width = 90; + // + // columnZ + // + columnZ.Text = "Z"; + columnZ.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + columnZ.Width = 40; + // + // columnName + // + columnName.Text = "Name"; + columnName.Width = 120; + // + // _icons + // + _icons.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; + _icons.ImageSize = new System.Drawing.Size(32, 32); + _icons.TransparentColor = System.Drawing.Color.Transparent; + // + // stackButtons + // + stackButtons.Controls.Add(stackZPlusButton); + stackButtons.Controls.Add(stackZMinusButton); + stackButtons.Controls.Add(stackDeleteButton); + stackButtons.Controls.Add(stackPickButton); + stackButtons.Dock = System.Windows.Forms.DockStyle.Bottom; + stackButtons.Location = new System.Drawing.Point(0, -30); + stackButtons.Name = "stackButtons"; + stackButtons.Size = new System.Drawing.Size(144, 30); + stackButtons.TabIndex = 1; + // + // stackZPlusButton + // + stackZPlusButton.Location = new System.Drawing.Point(1, 1); + stackZPlusButton.Margin = new System.Windows.Forms.Padding(1); + stackZPlusButton.Name = "stackZPlusButton"; + stackZPlusButton.Size = new System.Drawing.Size(56, 26); + stackZPlusButton.TabIndex = 0; + stackZPlusButton.Text = "Z +1"; + stackZPlusButton.UseVisualStyleBackColor = true; + stackZPlusButton.Click += StackZPlusButton_Click; + // + // stackZMinusButton + // + stackZMinusButton.Location = new System.Drawing.Point(59, 1); + stackZMinusButton.Margin = new System.Windows.Forms.Padding(1); + stackZMinusButton.Name = "stackZMinusButton"; + stackZMinusButton.Size = new System.Drawing.Size(56, 26); + stackZMinusButton.TabIndex = 1; + stackZMinusButton.Text = "Z -1"; + stackZMinusButton.UseVisualStyleBackColor = true; + stackZMinusButton.Click += StackZMinusButton_Click; + // + // stackDeleteButton + // + stackDeleteButton.Location = new System.Drawing.Point(1, 29); + stackDeleteButton.Margin = new System.Windows.Forms.Padding(1); + stackDeleteButton.Name = "stackDeleteButton"; + stackDeleteButton.Size = new System.Drawing.Size(56, 26); + stackDeleteButton.TabIndex = 2; + stackDeleteButton.Text = "Delete"; + stackDeleteButton.UseVisualStyleBackColor = true; + stackDeleteButton.Click += StackDeleteButton_Click; + // + // stackPickButton + // + stackPickButton.Location = new System.Drawing.Point(59, 29); + stackPickButton.Margin = new System.Windows.Forms.Padding(1); + stackPickButton.Name = "stackPickButton"; + stackPickButton.Size = new System.Drawing.Size(56, 26); + stackPickButton.TabIndex = 3; + stackPickButton.Text = "Pick"; + stackPickButton.UseVisualStyleBackColor = true; + stackPickButton.Click += StackPickButton_Click; + // + // tilesInCellLabel + // + tilesInCellLabel.AutoSize = true; + tilesInCellLabel.Location = new System.Drawing.Point(4, 134); + tilesInCellLabel.Name = "tilesInCellLabel"; + tilesInCellLabel.Size = new System.Drawing.Size(138, 15); + tilesInCellLabel.TabIndex = 2; + tilesInCellLabel.Text = "Tiles in this cell (top first)"; + // + // _dynamic + // + _dynamic.AutoSize = true; + _dynamic.Location = new System.Drawing.Point(4, 104); + _dynamic.Name = "_dynamic"; + _dynamic.Size = new System.Drawing.Size(127, 19); + _dynamic.TabIndex = 3; + _dynamic.Text = "Dynamic (invisible)"; + _dynamic.UseVisualStyleBackColor = true; + _dynamic.CheckedChanged += Dynamic_CheckedChanged; + // + // xLabel + // + xLabel.AutoSize = true; + xLabel.Location = new System.Drawing.Point(4, 80); + xLabel.Name = "xLabel"; + xLabel.Size = new System.Drawing.Size(14, 15); + xLabel.TabIndex = 4; + xLabel.Text = "X"; + // + // yLabel + // + yLabel.AutoSize = true; + yLabel.Location = new System.Drawing.Point(96, 80); + yLabel.Name = "yLabel"; + yLabel.Size = new System.Drawing.Size(14, 15); + yLabel.TabIndex = 5; + yLabel.Text = "Y"; + // + // zLabel + // + zLabel.AutoSize = true; + zLabel.Location = new System.Drawing.Point(188, 80); + zLabel.Name = "zLabel"; + zLabel.Size = new System.Drawing.Size(14, 15); + zLabel.TabIndex = 6; + zLabel.Text = "Z"; + // + // _x + // + _x.Location = new System.Drawing.Point(18, 76); + _x.Maximum = new decimal(new int[] { 0, 0, 0, 0 }); + _x.Name = "_x"; + _x.Size = new System.Drawing.Size(52, 23); + _x.TabIndex = 7; + _x.ValueChanged += X_ValueChanged; + // + // _y + // + _y.Location = new System.Drawing.Point(110, 76); + _y.Maximum = new decimal(new int[] { 0, 0, 0, 0 }); + _y.Name = "_y"; + _y.Size = new System.Drawing.Size(52, 23); + _y.TabIndex = 8; + _y.ValueChanged += Y_ValueChanged; + // + // _z + // + _z.Location = new System.Drawing.Point(202, 76); + _z.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); + _z.Minimum = new decimal(new int[] { 128, 0, 0, int.MinValue }); + _z.Name = "_z"; + _z.Size = new System.Drawing.Size(52, 23); + _z.TabIndex = 9; + _z.ValueChanged += Z_ValueChanged; + // + // _infoLabel + // + _infoLabel.AutoEllipsis = true; + _infoLabel.Location = new System.Drawing.Point(74, 24); + _infoLabel.Name = "_infoLabel"; + _infoLabel.Size = new System.Drawing.Size(210, 44); + _infoLabel.TabIndex = 10; + // + // _idLabel + // + _idLabel.AutoEllipsis = true; + _idLabel.Location = new System.Drawing.Point(74, 4); + _idLabel.Name = "_idLabel"; + _idLabel.Size = new System.Drawing.Size(210, 18); + _idLabel.TabIndex = 11; + // + // _thumb + // + _thumb.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + _thumb.Location = new System.Drawing.Point(4, 4); + _thumb.Name = "_thumb"; + _thumb.Size = new System.Drawing.Size(64, 64); + _thumb.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + _thumb.TabIndex = 12; + _thumb.TabStop = false; + // + // _group + // + _group.Controls.Add(_groupLabel); + _group.Controls.Add(groupZMinus5Button); + _group.Controls.Add(groupZMinus1Button); + _group.Controls.Add(groupZPlus1Button); + _group.Controls.Add(groupZPlus5Button); + _group.Controls.Add(groupZEqualsLabel); + _group.Controls.Add(_groupZ); + _group.Controls.Add(groupSetZButton); + _group.Controls.Add(groupDeleteButton); + _group.Controls.Add(groupHideButton); + _group.Dock = System.Windows.Forms.DockStyle.Fill; + _group.Location = new System.Drawing.Point(0, 0); + _group.Name = "_group"; + _group.Size = new System.Drawing.Size(144, 0); + _group.TabIndex = 1; + _group.Visible = false; + // + // _groupLabel + // + _groupLabel.AutoEllipsis = true; + _groupLabel.Location = new System.Drawing.Point(4, 6); + _groupLabel.Name = "_groupLabel"; + _groupLabel.Size = new System.Drawing.Size(280, 36); + _groupLabel.TabIndex = 0; + // + // groupZMinus5Button + // + groupZMinus5Button.Location = new System.Drawing.Point(4, 48); + groupZMinus5Button.Margin = new System.Windows.Forms.Padding(1); + groupZMinus5Button.Name = "groupZMinus5Button"; + groupZMinus5Button.Size = new System.Drawing.Size(56, 26); + groupZMinus5Button.TabIndex = 1; + groupZMinus5Button.Text = "Z -5"; + groupZMinus5Button.UseVisualStyleBackColor = true; + groupZMinus5Button.Click += GroupZMinus5Button_Click; + // + // groupZMinus1Button + // + groupZMinus1Button.Location = new System.Drawing.Point(64, 48); + groupZMinus1Button.Margin = new System.Windows.Forms.Padding(1); + groupZMinus1Button.Name = "groupZMinus1Button"; + groupZMinus1Button.Size = new System.Drawing.Size(56, 26); + groupZMinus1Button.TabIndex = 2; + groupZMinus1Button.Text = "Z -1"; + groupZMinus1Button.UseVisualStyleBackColor = true; + groupZMinus1Button.Click += GroupZMinus1Button_Click; + // + // groupZPlus1Button + // + groupZPlus1Button.Location = new System.Drawing.Point(124, 48); + groupZPlus1Button.Margin = new System.Windows.Forms.Padding(1); + groupZPlus1Button.Name = "groupZPlus1Button"; + groupZPlus1Button.Size = new System.Drawing.Size(56, 26); + groupZPlus1Button.TabIndex = 3; + groupZPlus1Button.Text = "Z +1"; + groupZPlus1Button.UseVisualStyleBackColor = true; + groupZPlus1Button.Click += GroupZPlus1Button_Click; + // + // groupZPlus5Button + // + groupZPlus5Button.Location = new System.Drawing.Point(184, 48); + groupZPlus5Button.Margin = new System.Windows.Forms.Padding(1); + groupZPlus5Button.Name = "groupZPlus5Button"; + groupZPlus5Button.Size = new System.Drawing.Size(56, 26); + groupZPlus5Button.TabIndex = 4; + groupZPlus5Button.Text = "Z +5"; + groupZPlus5Button.UseVisualStyleBackColor = true; + groupZPlus5Button.Click += GroupZPlus5Button_Click; + // + // groupZEqualsLabel + // + groupZEqualsLabel.AutoSize = true; + groupZEqualsLabel.Location = new System.Drawing.Point(4, 112); + groupZEqualsLabel.Name = "groupZEqualsLabel"; + groupZEqualsLabel.Size = new System.Drawing.Size(25, 15); + groupZEqualsLabel.TabIndex = 5; + groupZEqualsLabel.Text = "Z ="; + // + // _groupZ + // + _groupZ.Location = new System.Drawing.Point(70, 108); + _groupZ.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); + _groupZ.Minimum = new decimal(new int[] { 128, 0, 0, int.MinValue }); + _groupZ.Name = "_groupZ"; + _groupZ.Size = new System.Drawing.Size(52, 23); + _groupZ.TabIndex = 6; + // + // groupSetZButton + // + groupSetZButton.Location = new System.Drawing.Point(128, 106); + groupSetZButton.Margin = new System.Windows.Forms.Padding(1); + groupSetZButton.Name = "groupSetZButton"; + groupSetZButton.Size = new System.Drawing.Size(56, 26); + groupSetZButton.TabIndex = 7; + groupSetZButton.Text = "Set Z"; + groupSetZButton.UseVisualStyleBackColor = true; + groupSetZButton.Click += GroupSetZButton_Click; + // + // groupDeleteButton + // + groupDeleteButton.Location = new System.Drawing.Point(4, 146); + groupDeleteButton.Margin = new System.Windows.Forms.Padding(1); + groupDeleteButton.Name = "groupDeleteButton"; + groupDeleteButton.Size = new System.Drawing.Size(56, 26); + groupDeleteButton.TabIndex = 8; + groupDeleteButton.Text = "Delete"; + groupDeleteButton.UseVisualStyleBackColor = true; + groupDeleteButton.Click += GroupDeleteButton_Click; + // + // groupHideButton + // + groupHideButton.Location = new System.Drawing.Point(64, 146); + groupHideButton.Margin = new System.Windows.Forms.Padding(1); + groupHideButton.Name = "groupHideButton"; + groupHideButton.Size = new System.Drawing.Size(56, 26); + groupHideButton.TabIndex = 9; + groupHideButton.Text = "Hide"; + groupHideButton.UseVisualStyleBackColor = true; + groupHideButton.Click += GroupHideButton_Click; + // + // _hint + // + _hint.Dock = System.Windows.Forms.DockStyle.Fill; + _hint.ForeColor = System.Drawing.SystemColors.GrayText; + _hint.Location = new System.Drawing.Point(0, 0); + _hint.Name = "_hint"; + _hint.Size = new System.Drawing.Size(144, 0); + _hint.TabIndex = 2; + _hint.Text = "Nothing selected"; + _hint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // InspectorPanel + // + Controls.Add(selectionBox); + Controls.Add(floorsBox); + Name = "InspectorPanel"; + floorsBox.ResumeLayout(false); + floorsPage.ResumeLayout(false); + floorsPage.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)_firstFloor).EndInit(); + ((System.ComponentModel.ISupportInitialize)_limitBar).EndInit(); + selectionBox.ResumeLayout(false); + selectionPage.ResumeLayout(false); + _single.ResumeLayout(false); + _single.PerformLayout(); + stackButtons.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)_x).EndInit(); + ((System.ComponentModel.ISupportInitialize)_y).EndInit(); + ((System.ComponentModel.ISupportInitialize)_z).EndInit(); + ((System.ComponentModel.ISupportInitialize)_thumb).EndInit(); + _group.ResumeLayout(false); + _group.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)_groupZ).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.GroupBox floorsBox; + private System.Windows.Forms.Panel floorsPage; + private System.Windows.Forms.NumericUpDown _firstFloor; + private System.Windows.Forms.Label firstFloorLabel; + private System.Windows.Forms.Button _showHidden; + private System.Windows.Forms.Button _editFloors; + private System.Windows.Forms.TrackBar _limitBar; + private System.Windows.Forms.Label _limitLabel; + private System.Windows.Forms.CheckBox _limit; + private System.Windows.Forms.CheckBox _hideWalls; + private System.Windows.Forms.CheckBox _hideAbove; + private System.Windows.Forms.ListBox _floorList; + private System.Windows.Forms.GroupBox selectionBox; + private System.Windows.Forms.Panel selectionPage; + private System.Windows.Forms.Panel _single; + private System.Windows.Forms.ListView _stack; + private System.Windows.Forms.ColumnHeader columnId; + private System.Windows.Forms.ColumnHeader columnZ; + private System.Windows.Forms.ColumnHeader columnName; + private System.Windows.Forms.ImageList _icons; + private System.Windows.Forms.FlowLayoutPanel stackButtons; + private System.Windows.Forms.Button stackZPlusButton; + private System.Windows.Forms.Button stackZMinusButton; + private System.Windows.Forms.Button stackDeleteButton; + private System.Windows.Forms.Button stackPickButton; + private System.Windows.Forms.Label tilesInCellLabel; + private System.Windows.Forms.CheckBox _dynamic; + private System.Windows.Forms.Label xLabel; + private System.Windows.Forms.Label yLabel; + private System.Windows.Forms.Label zLabel; + private System.Windows.Forms.NumericUpDown _x; + private System.Windows.Forms.NumericUpDown _y; + private System.Windows.Forms.NumericUpDown _z; + private System.Windows.Forms.Label _infoLabel; + private System.Windows.Forms.Label _idLabel; + private System.Windows.Forms.PictureBox _thumb; + private System.Windows.Forms.Panel _group; + private System.Windows.Forms.Label _groupLabel; + private System.Windows.Forms.Button groupZMinus5Button; + private System.Windows.Forms.Button groupZMinus1Button; + private System.Windows.Forms.Button groupZPlus1Button; + private System.Windows.Forms.Button groupZPlus5Button; + private System.Windows.Forms.Label groupZEqualsLabel; + private System.Windows.Forms.NumericUpDown _groupZ; + private System.Windows.Forms.Button groupSetZButton; + private System.Windows.Forms.Button groupDeleteButton; + private System.Windows.Forms.Button groupHideButton; + private System.Windows.Forms.Label _hint; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs new file mode 100644 index 00000000..14a2a4a5 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs @@ -0,0 +1,582 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Linq; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Editing; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Lower right panel: the selected tile(s) with their cell stack, and the floors/view options. + /// + internal sealed partial class InspectorPanel : UserControl + { + private const int _iconSize = 32; + private const TileFlag _shownFlags = TileFlag.Surface | TileFlag.Impassable | TileFlag.Wall | TileFlag.Bridge | + TileFlag.Roof | TileFlag.Door | TileFlag.Window | TileFlag.Foliage | + TileFlag.Wet | TileFlag.Background | TileFlag.Translucent | TileFlag.Damaging; + + private readonly Dictionary _iconIndex = new Dictionary(); + private readonly List<(string Name, int Floor, int Ceiling)> _levels = new List<(string Name, int Floor, int Ceiling)>(); + + private EditorSession _session; + private bool _updating; + + public InspectorPanel() + { + InitializeComponent(); + + _idLabel.Font = new Font(Font, FontStyle.Bold); + _firstFloor.Maximum = EditorSession.MaxFirstFloorZ; + Disposed += InspectorPanel_Disposed; + + Bind(null); + } + + private void InspectorPanel_Disposed(object sender, EventArgs e) + { + if (_session != null) + { + _session.SelectionChanged -= Session_SelectionChanged; + _session.DocumentChanged -= Session_DocumentChanged; + _session.ViewChanged -= Session_ViewChanged; + _session = null; + } + } + + private void X_ValueChanged(object sender, EventArgs e) + { + OnPositionChanged(); + } + + private void Y_ValueChanged(object sender, EventArgs e) + { + OnPositionChanged(); + } + + private void Z_ValueChanged(object sender, EventArgs e) + { + OnZChanged(); + } + + private void Dynamic_CheckedChanged(object sender, EventArgs e) + { + OnDynamicChanged(); + } + + private void StackZPlusButton_Click(object sender, EventArgs e) + { + StackZ(1); + } + + private void StackZMinusButton_Click(object sender, EventArgs e) + { + StackZ(-1); + } + + private void StackDeleteButton_Click(object sender, EventArgs e) + { + StackDelete(); + } + + private void StackPickButton_Click(object sender, EventArgs e) + { + StackPick(); + } + + private void GroupZMinus5Button_Click(object sender, EventArgs e) + { + GroupZ(-5); + } + + private void GroupZMinus1Button_Click(object sender, EventArgs e) + { + GroupZ(-1); + } + + private void GroupZPlus1Button_Click(object sender, EventArgs e) + { + GroupZ(1); + } + + private void GroupZPlus5Button_Click(object sender, EventArgs e) + { + GroupZ(5); + } + + private void GroupSetZButton_Click(object sender, EventArgs e) + { + GroupSetZ(); + } + + private void GroupDeleteButton_Click(object sender, EventArgs e) + { + GroupDelete(); + } + + private void GroupHideButton_Click(object sender, EventArgs e) + { + _session?.HideSelection(); + } + + private void FloorList_SelectedIndexChanged(object sender, EventArgs e) + { + OnFloorChosen(); + } + + private void HideAbove_CheckedChanged(object sender, EventArgs e) + { + Apply(() => _session.HideAboveLevel = _hideAbove.Checked); + } + + private void HideWalls_CheckedChanged(object sender, EventArgs e) + { + Apply(() => _session.HideWalls = _hideWalls.Checked); + } + + private void Limit_CheckedChanged(object sender, EventArgs e) + { + Apply(() => _session.HeightLimit = _limit.Checked ? _limitBar.Value : null); + } + + private void LimitBar_ValueChanged(object sender, EventArgs e) + { + Apply(() => + { + if (_limit.Checked) + { + _session.HeightLimit = _limitBar.Value; + } + }); + } + + private void ShowHidden_Click(object sender, EventArgs e) + { + _session?.ShowHiddenTiles(); + } + + // The split into levels is the user's call: names and starting Z per design. + private void EditFloors_Click(object sender, EventArgs e) + { + if (_session == null) + { + return; + } + + using var dialog = new FloorsDialog(_session); + if (dialog.ShowDialog(this) == DialogResult.OK) + { + _session.SetLevelDefinitions(dialog.Result); + } + } + + private void FirstFloor_ValueChanged(object sender, EventArgs e) + { + Apply(() => _session.FirstFloorZ = (int)_firstFloor.Value); + } + + /// Attaches to a session; null detaches and shows the empty state. + public void Bind(EditorSession session) + { + if (_session != null) + { + _session.SelectionChanged -= Session_SelectionChanged; + _session.DocumentChanged -= Session_DocumentChanged; + _session.ViewChanged -= Session_ViewChanged; + } + + _session = session; + + if (_session != null) + { + _session.SelectionChanged += Session_SelectionChanged; + _session.DocumentChanged += Session_DocumentChanged; + _session.ViewChanged += Session_ViewChanged; + } + + RebuildLevels(); + RefreshSelection(); + RefreshView(); + } + + private void Session_SelectionChanged() + { + RefreshSelection(); + } + + private void Session_DocumentChanged() + { + RebuildLevels(); + RefreshSelection(); + RefreshView(); + } + + private void Session_ViewChanged() + { + RefreshView(); + } + + /// Runs a session write unless the panel is itself refreshing its controls. + private void Apply(Action write) + { + if (_updating || _session == null) + { + return; + } + + write(); + } + + // ---------------------------------------------------------------- selection + + private void RefreshSelection() + { + bool previous = _updating; + _updating = true; + try + { + int count = _session?.Selection.Count ?? 0; + _hint.Visible = count == 0; + _single.Visible = count == 1; + _group.Visible = count > 1; + + if (count == 1) + { + ShowSingle(_session.SelectedTile); + } + else if (count > 1) + { + int min = _session.Selection.Min(t => t.Z); + int max = _session.Selection.Max(t => t.Z); + _groupLabel.Text = $"{count} tiles selected, Z {min}–{max}"; + _groupZ.Value = Math.Clamp(min, (int)_groupZ.Minimum, (int)_groupZ.Maximum); + } + } + finally + { + _updating = previous; + } + } + + private void ShowSingle(MultiTile tile) + { + ItemData data = TileData.ItemTable[tile.Id]; + _thumb.Image = Art.GetStatic(tile.Id); + _idLabel.Text = $"0x{tile.Id:X4} {data.Name}"; + TileFlag flags = data.Flags & _shownFlags; + _infoLabel.Text = $"Height {data.Height}\r\n{(flags == 0 ? "no flags" : flags.ToString())}"; + + _x.Maximum = Math.Max(0, _session.CompList.Width - 1); + _y.Maximum = Math.Max(0, _session.CompList.Height - 1); + _x.Value = Math.Clamp(tile.X, 0, (int)_x.Maximum); + _y.Value = Math.Clamp(tile.Y, 0, (int)_y.Maximum); + _z.Value = Math.Clamp(tile.Z, (int)_z.Minimum, (int)_z.Maximum); + _dynamic.Checked = tile.Invisible; + + // Rebuilt from the model each time; list order is top first. + _stack.BeginUpdate(); + try + { + _stack.Items.Clear(); + List cell = _session.CompList.GetTilesAt(tile.X, tile.Y); + for (int i = cell.Count - 1; i >= 0; --i) + { + MultiTile entry = cell[i]; + ItemData entryData = TileData.ItemTable[entry.Id]; + var item = new ListViewItem(entry.Invisible ? $"0x{entry.Id:X4} *" : $"0x{entry.Id:X4}", IconFor(entry.Id)) { Tag = entry }; + item.SubItems.Add(entry.Z.ToString()); + item.SubItems.Add(entryData.Name ?? string.Empty); + _stack.Items.Add(item); + if (entry == tile) + { + item.Selected = true; + item.EnsureVisible(); + } + } + } + finally + { + _stack.EndUpdate(); + } + } + + private void OnPositionChanged() + { + MultiTile tile = _session?.SelectedTile; + if (_updating || tile == null) + { + return; + } + + int x = (int)_x.Value; + int y = (int)_y.Value; + if (x == tile.X && y == tile.Y) + { + return; + } + + _session.CompList.TileMove(tile, x, y); + _session.AfterEdit(); + RefreshSelection(); + } + + private void OnZChanged() + { + MultiTile tile = _session?.SelectedTile; + int z = (int)_z.Value; + if (_updating || tile == null || z == tile.Z) + { + return; + } + + _session.CompList.TileZSet(tile, z); + _session.AfterEdit(z); + } + + private void OnDynamicChanged() + { + MultiTile tile = _session?.SelectedTile; + if (_updating || tile == null || tile.Invisible == _dynamic.Checked) + { + return; + } + + _session.CompList.TileSetInvisible(tile, _dynamic.Checked); + _session.AfterEdit(); + } + + private void Stack_SelectedIndexChanged(object sender, EventArgs e) + { + if (_updating || _stack.SelectedItems.Count == 0 || _stack.SelectedItems[0].Tag is not MultiTile tile) + { + return; + } + + // Selecting rebuilds this list, so let the ListView finish its own change first. + BeginInvoke(() => _session?.SetSelection(new[] { tile }, add: false)); + } + + private void StackZ(int delta) + { + MultiTile tile = _session?.SelectedTile; + if (tile == null) + { + return; + } + + _session.CompList.TileZMod(tile, delta); + _session.AfterEdit(delta > 0 ? tile.Z : null); + } + + private void StackDelete() + { + MultiTile removed = _session?.SelectedTile; + if (removed == null) + { + return; + } + + // Keep working in the same cell: select the tile now on top of it. + _session.CompList.TileRemove(removed); + List rest = _session.CompList.GetTilesAt(removed.X, removed.Y); + if (rest.Count > 0) + { + _session.SetSelection(new[] { rest[^1] }, add: false); + } + else + { + _session.ClearSelection(); + } + + _session.AfterEdit(); + } + + private void StackPick() + { + MultiTile tile = _session?.SelectedTile; + if (tile != null) + { + _session.SetDrawTile(tile.Id); + } + } + + private void GroupZ(int delta) + { + if (_session == null || _session.Selection.Count < 2) + { + return; + } + + var tiles = _session.Selection.ToList(); + _session.CompList.TileZMod(tiles, delta); + _session.AfterEdit(delta > 0 ? tiles.Max(t => t.Z) : null); + } + + private void GroupSetZ() + { + if (_session == null || _session.Selection.Count < 2) + { + return; + } + + int z = (int)_groupZ.Value; + _session.CompList.TileZSet(_session.Selection.ToList(), z); + _session.AfterEdit(z); + } + + private void GroupDelete() + { + if (_session == null || _session.Selection.Count < 2) + { + return; + } + + _session.CompList.TileRemoveBatch(_session.Selection.ToList()); + _session.ClearSelection(); + _session.AfterEdit(); + } + + private int IconFor(ushort id) + { + if (_iconIndex.TryGetValue(id, out int index)) + { + return index; + } + + var icon = new Bitmap(_iconSize, _iconSize); + Bitmap art = Art.GetStatic(id); + if (art != null) + { + using Graphics g = Graphics.FromImage(icon); + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + float scale = Math.Min(1f, Math.Min((float)_iconSize / art.Width, (float)_iconSize / art.Height)); + int w = Math.Max(1, (int)(art.Width * scale)); + int h = Math.Max(1, (int)(art.Height * scale)); + g.DrawImage(art, (_iconSize - w) / 2, _iconSize - h, w, h); + } + + _icons.Images.Add(icon); + icon.Dispose(); + index = _icons.Images.Count - 1; + _iconIndex[id] = index; + return index; + } + + // ---------------------------------------------------------------- floors + + /// + /// Works out the floors of the multi (same rule as the old editor's BuildLevels): a flat + /// surface tile at Z 7 means a foundation, with floors at 7, 27, 47 ...; otherwise floors + /// are at 0, 20, 40 ... + /// + private void RebuildLevels() + { + // The session owns the floors, so the list here, the toolbar and Ctrl+PgUp/PgDn agree. + _levels.Clear(); + if (_session != null) + { + foreach (EditorLevel level in _session.Levels) + { + _levels.Add((level.Description, level.Floor, level.Ceiling)); + } + } + + bool previous = _updating; + _updating = true; + try + { + _floorList.BeginUpdate(); + _floorList.Items.Clear(); + _floorList.Items.Add("All floors"); + foreach (var level in _levels) + { + _floorList.Items.Add(level.Name); + } + + _floorList.EndUpdate(); + SelectActiveRow(); + } + finally + { + _updating = previous; + } + } + + private void SelectActiveRow() + { + int row = Math.Min(_session?.LevelIndex ?? 0, _floorList.Items.Count - 1); + _floorList.SelectedIndex = row; + } + + private void OnFloorChosen() + { + if (_updating || _session == null || _floorList.SelectedIndex < 0) + { + return; + } + + _session.LevelIndex = _floorList.SelectedIndex; + } + + private void RefreshView() + { + bool previous = _updating; + _updating = true; + try + { + bool enabled = _session != null; + _floorList.Enabled = _hideAbove.Enabled = _hideWalls.Enabled = _limit.Enabled = enabled; + + if (_session == null) + { + _showHidden.Enabled = false; + _limitBar.Enabled = false; + return; + } + + SelectActiveRow(); + _hideAbove.Checked = _session.HideAboveLevel; + _firstFloor.Value = _session.FirstFloorZ; + _editFloors.Text = _session.CustomLevels ? "Edit floors... *" : "Edit floors..."; + _hideWalls.Checked = _session.HideWalls; + + MultiEditorComponentList list = _session.CompList; + int min = Math.Min(list.ZMin, list.ZMax); + int max = Math.Max(list.ZMin, list.ZMax); + _limitBar.Minimum = Math.Min(min, sbyte.MaxValue - 1); + _limitBar.Maximum = Math.Max(max, _limitBar.Minimum + 1); + + int? limit = _session.HeightLimit; + _limit.Checked = limit.HasValue; + _limitBar.Enabled = limit.HasValue; + if (limit.HasValue) + { + _limitBar.Value = Math.Clamp(limit.Value, _limitBar.Minimum, _limitBar.Maximum); + } + + _limitLabel.Text = limit.HasValue ? limit.Value.ToString() : "all"; + + int hidden = list.HiddenCount; + _showHidden.Text = $"Show hidden tiles ({hidden})"; + _showHidden.Enabled = hidden > 0; + } + finally + { + _updating = previous; + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.resx b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.resx new file mode 100644 index 00000000..88ab60fa --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.Designer.cs new file mode 100644 index 00000000..2e186483 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.Designer.cs @@ -0,0 +1,256 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class MapExtractForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + labelFacet = new System.Windows.Forms.Label(); + _facet = new System.Windows.Forms.ComboBox(); + labelX = new System.Windows.Forms.Label(); + _x = new System.Windows.Forms.NumericUpDown(); + labelY = new System.Windows.Forms.Label(); + _y = new System.Windows.Forms.NumericUpDown(); + labelWidth = new System.Windows.Forms.Label(); + _width = new System.Windows.Forms.NumericUpDown(); + labelHeight = new System.Windows.Forms.Label(); + _height = new System.Windows.Forms.NumericUpDown(); + labelMinZ = new System.Windows.Forms.Label(); + _minZ = new System.Windows.Forms.NumericUpDown(); + labelMaxZ = new System.Windows.Forms.Label(); + _maxZ = new System.Windows.Forms.NumericUpDown(); + _newDesign = new System.Windows.Forms.CheckBox(); + buttonOk = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)_x).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_y).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_width).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_height).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_minZ).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_maxZ).BeginInit(); + SuspendLayout(); + // + // labelFacet + // + labelFacet.AutoSize = true; + labelFacet.Location = new System.Drawing.Point(10, 13); + labelFacet.Name = "labelFacet"; + labelFacet.Size = new System.Drawing.Size(41, 15); + labelFacet.TabIndex = 0; + labelFacet.Text = "Facet:"; + // + // _facet + // + _facet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _facet.Location = new System.Drawing.Point(110, 10); + _facet.Name = "_facet"; + _facet.Size = new System.Drawing.Size(180, 23); + _facet.TabIndex = 1; + // + // labelX + // + labelX.AutoSize = true; + labelX.Location = new System.Drawing.Point(10, 43); + labelX.Name = "labelX"; + labelX.Size = new System.Drawing.Size(90, 15); + labelX.TabIndex = 2; + labelX.Text = "X (west edge):"; + // + // _x + // + _x.Location = new System.Drawing.Point(110, 40); + _x.Maximum = new decimal(new int[] { 32767, 0, 0, 0 }); + _x.Minimum = new decimal(new int[] { 0, 0, 0, 0 }); + _x.Name = "_x"; + _x.Size = new System.Drawing.Size(180, 23); + _x.TabIndex = 3; + // + // labelY + // + labelY.AutoSize = true; + labelY.Location = new System.Drawing.Point(10, 73); + labelY.Name = "labelY"; + labelY.Size = new System.Drawing.Size(97, 15); + labelY.TabIndex = 4; + labelY.Text = "Y (north edge):"; + // + // _y + // + _y.Location = new System.Drawing.Point(110, 70); + _y.Maximum = new decimal(new int[] { 32767, 0, 0, 0 }); + _y.Minimum = new decimal(new int[] { 0, 0, 0, 0 }); + _y.Name = "_y"; + _y.Size = new System.Drawing.Size(180, 23); + _y.TabIndex = 5; + // + // labelWidth + // + labelWidth.AutoSize = true; + labelWidth.Location = new System.Drawing.Point(10, 103); + labelWidth.Name = "labelWidth"; + labelWidth.Size = new System.Drawing.Size(41, 15); + labelWidth.TabIndex = 6; + labelWidth.Text = "Width:"; + // + // _width + // + _width.Location = new System.Drawing.Point(110, 100); + _width.Maximum = new decimal(new int[] { 256, 0, 0, 0 }); + _width.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); + _width.Name = "_width"; + _width.Size = new System.Drawing.Size(180, 23); + _width.TabIndex = 7; + // + // labelHeight + // + labelHeight.AutoSize = true; + labelHeight.Location = new System.Drawing.Point(10, 133); + labelHeight.Name = "labelHeight"; + labelHeight.Size = new System.Drawing.Size(47, 15); + labelHeight.TabIndex = 8; + labelHeight.Text = "Height:"; + // + // _height + // + _height.Location = new System.Drawing.Point(110, 130); + _height.Maximum = new decimal(new int[] { 256, 0, 0, 0 }); + _height.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); + _height.Name = "_height"; + _height.Size = new System.Drawing.Size(180, 23); + _height.TabIndex = 9; + // + // labelMinZ + // + labelMinZ.AutoSize = true; + labelMinZ.Location = new System.Drawing.Point(10, 163); + labelMinZ.Name = "labelMinZ"; + labelMinZ.Size = new System.Drawing.Size(59, 15); + labelMinZ.TabIndex = 10; + labelMinZ.Text = "Lowest Z:"; + // + // _minZ + // + _minZ.Location = new System.Drawing.Point(110, 160); + _minZ.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); + _minZ.Minimum = new decimal(new int[] { 128, 0, 0, -2147483648 }); + _minZ.Name = "_minZ"; + _minZ.Size = new System.Drawing.Size(180, 23); + _minZ.TabIndex = 11; + // + // labelMaxZ + // + labelMaxZ.AutoSize = true; + labelMaxZ.Location = new System.Drawing.Point(10, 193); + labelMaxZ.Name = "labelMaxZ"; + labelMaxZ.Size = new System.Drawing.Size(66, 15); + labelMaxZ.TabIndex = 12; + labelMaxZ.Text = "Highest Z:"; + // + // _maxZ + // + _maxZ.Location = new System.Drawing.Point(110, 190); + _maxZ.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); + _maxZ.Minimum = new decimal(new int[] { 128, 0, 0, -2147483648 }); + _maxZ.Name = "_maxZ"; + _maxZ.Size = new System.Drawing.Size(180, 23); + _maxZ.TabIndex = 13; + // + // _newDesign + // + _newDesign.AutoSize = true; + _newDesign.Location = new System.Drawing.Point(10, 222); + _newDesign.Name = "_newDesign"; + _newDesign.Size = new System.Drawing.Size(142, 19); + _newDesign.TabIndex = 14; + _newDesign.Text = "Open as a new design"; + _newDesign.UseVisualStyleBackColor = true; + // + // buttonOk + // + buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + buttonOk.Location = new System.Drawing.Point(215, 218); + buttonOk.Name = "buttonOk"; + buttonOk.Size = new System.Drawing.Size(75, 23); + buttonOk.TabIndex = 15; + buttonOk.Text = "Extract"; + buttonOk.UseVisualStyleBackColor = true; + // + // MapExtractForm + // + AcceptButton = buttonOk; + ClientSize = new System.Drawing.Size(300, 250); + Controls.Add(labelFacet); + Controls.Add(_facet); + Controls.Add(labelX); + Controls.Add(_x); + Controls.Add(labelY); + Controls.Add(_y); + Controls.Add(labelWidth); + Controls.Add(_width); + Controls.Add(labelHeight); + Controls.Add(_height); + Controls.Add(labelMinZ); + Controls.Add(_minZ); + Controls.Add(labelMaxZ); + Controls.Add(_maxZ); + Controls.Add(_newDesign); + Controls.Add(buttonOk); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "MapExtractForm"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Extract statics from the map"; + ((System.ComponentModel.ISupportInitialize)_x).EndInit(); + ((System.ComponentModel.ISupportInitialize)_y).EndInit(); + ((System.ComponentModel.ISupportInitialize)_width).EndInit(); + ((System.ComponentModel.ISupportInitialize)_height).EndInit(); + ((System.ComponentModel.ISupportInitialize)_minZ).EndInit(); + ((System.ComponentModel.ISupportInitialize)_maxZ).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label labelFacet; + private System.Windows.Forms.ComboBox _facet; + private System.Windows.Forms.Label labelX; + private System.Windows.Forms.NumericUpDown _x; + private System.Windows.Forms.Label labelY; + private System.Windows.Forms.NumericUpDown _y; + private System.Windows.Forms.Label labelWidth; + private System.Windows.Forms.NumericUpDown _width; + private System.Windows.Forms.Label labelHeight; + private System.Windows.Forms.NumericUpDown _height; + private System.Windows.Forms.Label labelMinZ; + private System.Windows.Forms.NumericUpDown _minZ; + private System.Windows.Forms.Label labelMaxZ; + private System.Windows.Forms.NumericUpDown _maxZ; + private System.Windows.Forms.CheckBox _newDesign; + private System.Windows.Forms.Button buttonOk; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.cs b/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.cs new file mode 100644 index 00000000..269e9039 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.cs @@ -0,0 +1,50 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// Asks for the facet, the rectangle and the Z range to extract statics from. + internal sealed partial class MapExtractForm : Form + { + public MapExtractForm(MapArea initial, bool canPlaceIntoDesign) + { + InitializeComponent(); + + foreach (var (name, _) in MapExtract.Facets) + { + _facet.Items.Add(name); + } + + int facetIndex = Array.FindIndex(MapExtract.Facets, f => f.Map() == initial.Map); + _facet.SelectedIndex = Math.Max(0, facetIndex); + + SetValue(_x, initial.X); + SetValue(_y, initial.Y); + SetValue(_width, initial.Width); + SetValue(_height, initial.Height); + SetValue(_minZ, initial.MinZ); + SetValue(_maxZ, initial.MaxZ); + _newDesign.Checked = initial.NewDesign || !canPlaceIntoDesign; + _newDesign.Enabled = canPlaceIntoDesign; + } + + /// The area as entered, valid after the form returned OK. + public MapArea Area => new MapArea(MapExtract.Facets[_facet.SelectedIndex].Map(), (int)_x.Value, (int)_y.Value, (int)_width.Value, (int)_height.Value, + (int)Math.Min(_minZ.Value, _maxZ.Value), (int)Math.Max(_minZ.Value, _maxZ.Value), _newDesign.Checked); + + private static void SetValue(NumericUpDown box, int value) + { + box.Value = Math.Clamp(value, (int)box.Minimum, (int)box.Maximum); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.resx b/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.resx new file mode 100644 index 00000000..1af7de15 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/MapExtractForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs new file mode 100644 index 00000000..2c244ae0 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs @@ -0,0 +1,552 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class MultiEditorControl + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + _hostMenuBlocker = new System.Windows.Forms.ContextMenuStrip(components); + _centre = new System.Windows.Forms.Panel(); + _emptyHint = new System.Windows.Forms.Label(); + _canvas = new UoFiddler.Plugin.MultiEditor.Rendering.GlCanvas(); + _docTabs = new UoFiddler.Controls.UserControls.ThemedTabControl(); + _toolPalette = new System.Windows.Forms.ToolStrip(); + _editToolsLabel = new System.Windows.Forms.ToolStripLabel(); + _drawToolsLabel = new System.Windows.Forms.ToolStripLabel(); + _houseToolsLabel = new System.Windows.Forms.ToolStripLabel(); + _sideSplitter = new UoFiddler.Plugin.MultiEditor.UI.GripSplitter(); + _sidePanel = new System.Windows.Forms.Panel(); + _sideSplit = new System.Windows.Forms.SplitContainer(); + _browser = new UoFiddler.Plugin.MultiEditor.UI.TileBrowserPanel(); + _inspector = new UoFiddler.Plugin.MultiEditor.UI.InspectorPanel(); + _optionsStrip = new System.Windows.Forms.ToolStrip(); + _toolLabel = new System.Windows.Forms.ToolStripLabel(); + _optionsSeparator1 = new System.Windows.Forms.ToolStripSeparator(); + _placeLabel = new System.Windows.Forms.ToolStripLabel(); + _brushLabel = new System.Windows.Forms.ToolStripLabel(); + _zStepLabel = new System.Windows.Forms.ToolStripLabel(); + _zStepCombo = new UoFiddler.Plugin.MultiEditor.UI.ToolStripChoice(50, "1", "2", "3", "4", "5", "10", "20"); + _optionsSeparator2 = new System.Windows.Forms.ToolStripSeparator(); + _floorLabel = new System.Windows.Forms.ToolStripLabel(); + _optionsSeparator3 = new System.Windows.Forms.ToolStripSeparator(); + _drawTileLabel = new System.Windows.Forms.ToolStripLabel(); + _ridgeSeparator = new System.Windows.Forms.ToolStripSeparator(); + _ridgeLabel = new System.Windows.Forms.ToolStripLabel(); + _gablesSeparator = new System.Windows.Forms.ToolStripSeparator(); + _gablesLabel = new System.Windows.Forms.ToolStripLabel(); + _gableFillSeparator = new System.Windows.Forms.ToolStripSeparator(); + _gableFillLabel = new System.Windows.Forms.ToolStripLabel(); + _mainStrip = new System.Windows.Forms.ToolStrip(); + _fileMenu = new System.Windows.Forms.ToolStripDropDownButton(); + _editMenu = new System.Windows.Forms.ToolStripDropDownButton(); + _selectMenu = new System.Windows.Forms.ToolStripDropDownButton(); + _viewMenu = new System.Windows.Forms.ToolStripDropDownButton(); + _mainSeparator1 = new System.Windows.Forms.ToolStripSeparator(); + _mainSeparator2 = new System.Windows.Forms.ToolStripSeparator(); + _mainSeparator3 = new System.Windows.Forms.ToolStripSeparator(); + _mainSeparator4 = new System.Windows.Forms.ToolStripSeparator(); + _zoomLabel = new System.Windows.Forms.ToolStripLabel(); + _statusStrip = new System.Windows.Forms.StatusStrip(); + _statusHint = new System.Windows.Forms.ToolStripStatusLabel(); + _statusCell = new System.Windows.Forms.ToolStripStatusLabel(); + _statusPlane = new System.Windows.Forms.ToolStripStatusLabel(); + _statusHover = new System.Windows.Forms.ToolStripStatusLabel(); + _statusSelection = new System.Windows.Forms.ToolStripStatusLabel(); + _statusSize = new System.Windows.Forms.ToolStripStatusLabel(); + _centre.SuspendLayout(); + _toolPalette.SuspendLayout(); + _sidePanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_sideSplit).BeginInit(); + _sideSplit.Panel1.SuspendLayout(); + _sideSplit.Panel2.SuspendLayout(); + _sideSplit.SuspendLayout(); + _optionsStrip.SuspendLayout(); + _mainStrip.SuspendLayout(); + _statusStrip.SuspendLayout(); + SuspendLayout(); + // + // _hostMenuBlocker + // + _hostMenuBlocker.Name = "_hostMenuBlocker"; + _hostMenuBlocker.Size = new System.Drawing.Size(61, 4); + _hostMenuBlocker.Opening += HostMenuBlocker_Opening; + // + // _centre + // + _centre.Controls.Add(_emptyHint); + _centre.Controls.Add(_canvas); + _centre.Controls.Add(_docTabs); + _centre.Dock = System.Windows.Forms.DockStyle.Fill; + _centre.Location = new System.Drawing.Point(96, 50); + _centre.Name = "_centre"; + _centre.Size = new System.Drawing.Size(532, 646); + _centre.TabIndex = 0; + // + // _emptyHint + // + _emptyHint.Dock = System.Windows.Forms.DockStyle.Fill; + _emptyHint.Location = new System.Drawing.Point(0, 24); + _emptyHint.Name = "_emptyHint"; + _emptyHint.Size = new System.Drawing.Size(532, 622); + _emptyHint.TabIndex = 1; + _emptyHint.Text = "Open a multi from the client (Ctrl+O), import files (Ctrl+I),\r\nimport from a folder (Ctrl+Shift+I) or start a new one (Ctrl+N)."; + _emptyHint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // _canvas + // + _canvas.Dock = System.Windows.Forms.DockStyle.Fill; + _canvas.Location = new System.Drawing.Point(0, 24); + _canvas.Name = "_canvas"; + _canvas.Size = new System.Drawing.Size(532, 622); + _canvas.TabIndex = 0; + _canvas.ContextFailed += ShowMessage; + _canvas.CameraChanged += UpdateZoomLabel; + _canvas.ContextRequested += ShowCanvasMenu; + // + // _docTabs + // + _docTabs.Dock = System.Windows.Forms.DockStyle.Top; + _docTabs.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed; + _docTabs.Location = new System.Drawing.Point(0, 0); + _docTabs.Name = "_docTabs"; + _docTabs.Padding = new System.Drawing.Point(14, 3); + _docTabs.ShowToolTips = true; + _docTabs.Size = new System.Drawing.Size(532, 24); + _docTabs.TabIndex = 2; + _docTabs.DrawItem += DocTabs_DrawItem; + _docTabs.SelectedIndexChanged += DocTabs_SelectedIndexChanged; + _docTabs.Selecting += DocTabs_Selecting; + _docTabs.MouseDown += DocTabs_MouseDown; + _docTabs.MouseLeave += DocTabs_MouseLeave; + _docTabs.MouseMove += DocTabs_MouseMove; + _docTabs.MouseUp += DocTabs_MouseUp; + // + // _toolPalette + // + _toolPalette.AutoSize = false; + _toolPalette.Dock = System.Windows.Forms.DockStyle.Left; + _toolPalette.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _toolPalette.ImageScalingSize = new System.Drawing.Size(20, 20); + _toolPalette.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _editToolsLabel, _drawToolsLabel, _houseToolsLabel }); + _toolPalette.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow; + _toolPalette.Location = new System.Drawing.Point(0, 50); + _toolPalette.Name = "_toolPalette"; + _toolPalette.Size = new System.Drawing.Size(96, 646); + _toolPalette.TabIndex = 1; + // + // _editToolsLabel + // + _editToolsLabel.ForeColor = System.Drawing.SystemColors.GrayText; + _editToolsLabel.Margin = new System.Windows.Forms.Padding(2, 6, 0, 2); + _editToolsLabel.Name = "_editToolsLabel"; + _editToolsLabel.Size = new System.Drawing.Size(93, 15); + _editToolsLabel.Text = "Edit"; + // + // _drawToolsLabel + // + _drawToolsLabel.ForeColor = System.Drawing.SystemColors.GrayText; + _drawToolsLabel.Margin = new System.Windows.Forms.Padding(2, 6, 0, 2); + _drawToolsLabel.Name = "_drawToolsLabel"; + _drawToolsLabel.Size = new System.Drawing.Size(93, 15); + _drawToolsLabel.Text = "Draw"; + // + // _houseToolsLabel + // + _houseToolsLabel.ForeColor = System.Drawing.SystemColors.GrayText; + _houseToolsLabel.Margin = new System.Windows.Forms.Padding(2, 6, 0, 2); + _houseToolsLabel.Name = "_houseToolsLabel"; + _houseToolsLabel.Size = new System.Drawing.Size(93, 15); + _houseToolsLabel.Text = "House"; + // + // _sideSplitter + // + _sideSplitter.Dock = System.Windows.Forms.DockStyle.Right; + _sideSplitter.Location = new System.Drawing.Point(628, 50); + _sideSplitter.MinExtra = 200; + _sideSplitter.MinSize = 240; + _sideSplitter.Name = "_sideSplitter"; + _sideSplitter.Size = new System.Drawing.Size(7, 646); + _sideSplitter.TabIndex = 2; + _sideSplitter.TabStop = false; + _sideSplitter.SplitterMoved += SideSplitter_SplitterMoved; + // + // _sidePanel + // + _sidePanel.Controls.Add(_sideSplit); + _sidePanel.Dock = System.Windows.Forms.DockStyle.Right; + _sidePanel.Location = new System.Drawing.Point(635, 50); + _sidePanel.Name = "_sidePanel"; + _sidePanel.Size = new System.Drawing.Size(645, 646); + _sidePanel.TabIndex = 3; + // + // _sideSplit + // + _sideSplit.Dock = System.Windows.Forms.DockStyle.Fill; + _sideSplit.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; + _sideSplit.Location = new System.Drawing.Point(0, 0); + _sideSplit.Name = "_sideSplit"; + // + // _sideSplit.Panel1 + // + _sideSplit.Panel1.Controls.Add(_browser); + // + // _sideSplit.Panel2 + // + _sideSplit.Panel2.Controls.Add(_inspector); + _sideSplit.Size = new System.Drawing.Size(645, 646); + _sideSplit.SplitterDistance = 545; + _sideSplit.SplitterWidth = 5; + _sideSplit.TabIndex = 0; + _sideSplit.SplitterMoved += SideSplit_SplitterMoved; + // + // _browser + // + _browser.Dock = System.Windows.Forms.DockStyle.Fill; + _browser.Location = new System.Drawing.Point(0, 0); + _browser.Name = "_browser"; + _browser.Size = new System.Drawing.Size(545, 646); + _browser.TabIndex = 0; + // + // _inspector + // + _inspector.Dock = System.Windows.Forms.DockStyle.Fill; + _inspector.Location = new System.Drawing.Point(0, 0); + _inspector.Name = "_inspector"; + _inspector.Size = new System.Drawing.Size(95, 646); + _inspector.TabIndex = 0; + // + // _optionsStrip + // + _optionsStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _optionsStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _toolLabel, _optionsSeparator1, _placeLabel, _brushLabel, _zStepLabel, _zStepCombo, _optionsSeparator2, _floorLabel, _optionsSeparator3, _drawTileLabel, _ridgeSeparator, _ridgeLabel, _gablesSeparator, _gablesLabel, _gableFillSeparator, _gableFillLabel }); + _optionsStrip.Location = new System.Drawing.Point(0, 25); + _optionsStrip.Name = "_optionsStrip"; + _optionsStrip.Size = new System.Drawing.Size(1280, 25); + _optionsStrip.TabIndex = 4; + // + // _toolLabel + // + _toolLabel.AutoSize = false; + _toolLabel.Name = "_toolLabel"; + _toolLabel.Size = new System.Drawing.Size(110, 23); + _toolLabel.Text = "Select"; + _toolLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _optionsSeparator1 + // + _optionsSeparator1.Name = "_optionsSeparator1"; + _optionsSeparator1.Size = new System.Drawing.Size(6, 25); + // + // _placeLabel + // + _placeLabel.Name = "_placeLabel"; + _placeLabel.Size = new System.Drawing.Size(35, 22); + _placeLabel.Text = "Place"; + _placeLabel.ToolTipText = "Where new tiles go (M steps through the modes)"; + // + // _brushLabel + // + _brushLabel.Name = "_brushLabel"; + _brushLabel.Size = new System.Drawing.Size(38, 22); + _brushLabel.Text = "Brush"; + _brushLabel.ToolTipText = "Brush size of the Draw tool (Ctrl+1, Ctrl+2, Ctrl+3)"; + // + // _zStepLabel + // + _zStepLabel.Name = "_zStepLabel"; + _zStepLabel.Size = new System.Drawing.Size(42, 22); + _zStepLabel.Text = "Z step"; + // + // _zStepCombo + // + _zStepCombo.Name = "_zStepCombo"; + _zStepCombo.ToolTipText = "Z added by the Altitude tool per click"; + _zStepCombo.SelectedIndexChanged += ZStepCombo_SelectedIndexChanged; + // + // _optionsSeparator2 + // + _optionsSeparator2.Name = "_optionsSeparator2"; + _optionsSeparator2.Size = new System.Drawing.Size(6, 25); + // + // _floorLabel + // + _floorLabel.Name = "_floorLabel"; + _floorLabel.Size = new System.Drawing.Size(34, 22); + _floorLabel.Text = "Floor"; + _floorLabel.ToolTipText = "Floor being built: PgUp / PgDn or Shift+wheel, Ctrl+Home for all"; + // + // _optionsSeparator3 + // + _optionsSeparator3.Name = "_optionsSeparator3"; + _optionsSeparator3.Size = new System.Drawing.Size(6, 25); + // + // _drawTileLabel + // + _drawTileLabel.AutoSize = false; + _drawTileLabel.Name = "_drawTileLabel"; + _drawTileLabel.Size = new System.Drawing.Size(230, 23); + _drawTileLabel.Text = "Tile: none"; + _drawTileLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _ridgeSeparator + // + _ridgeSeparator.Name = "_ridgeSeparator"; + _ridgeSeparator.Size = new System.Drawing.Size(6, 25); + // + // _ridgeLabel + // + _ridgeLabel.Name = "_ridgeLabel"; + _ridgeLabel.Size = new System.Drawing.Size(36, 22); + _ridgeLabel.Text = "Ridge"; + _ridgeLabel.ToolTipText = "Which way the ridge runs. Shift turns it for one stroke."; + // + // _gablesSeparator + // + _gablesSeparator.Name = "_gablesSeparator"; + _gablesSeparator.Size = new System.Drawing.Size(6, 25); + // + // _gablesLabel + // + _gablesLabel.Name = "_gablesLabel"; + _gablesLabel.Size = new System.Drawing.Size(41, 22); + _gablesLabel.Text = "Gables"; + _gablesLabel.ToolTipText = "Which gable ends are closed. Ctrl switches between front and both for one stroke."; + // + // _gableFillSeparator + // + _gableFillSeparator.Name = "_gableFillSeparator"; + _gableFillSeparator.Size = new System.Drawing.Size(6, 25); + // + // _gableFillLabel + // + _gableFillLabel.Name = "_gableFillLabel"; + _gableFillLabel.Size = new System.Drawing.Size(23, 22); + _gableFillLabel.Text = "Fill"; + _gableFillLabel.ToolTipText = "What closes a gable: small cap pieces, or whole wall pieces with caps on top (for big, high roofs)."; + // + // _mainStrip + // + _mainStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _mainStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _fileMenu, _editMenu, _selectMenu, _viewMenu, _mainSeparator1, _mainSeparator2, _mainSeparator3, _mainSeparator4, _zoomLabel }); + _mainStrip.Location = new System.Drawing.Point(0, 0); + _mainStrip.Name = "_mainStrip"; + _mainStrip.Size = new System.Drawing.Size(1280, 25); + _mainStrip.TabIndex = 5; + // + // _fileMenu + // + _fileMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _fileMenu.Name = "_fileMenu"; + _fileMenu.Size = new System.Drawing.Size(38, 22); + _fileMenu.Text = "File"; + _fileMenu.DropDownOpening += Menu_DropDownOpening; + // + // _editMenu + // + _editMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _editMenu.Name = "_editMenu"; + _editMenu.Size = new System.Drawing.Size(40, 22); + _editMenu.Text = "Edit"; + _editMenu.DropDownOpening += Menu_DropDownOpening; + // + // _selectMenu + // + _selectMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _selectMenu.Name = "_selectMenu"; + _selectMenu.Size = new System.Drawing.Size(51, 22); + _selectMenu.Text = "Select"; + _selectMenu.DropDownOpening += Menu_DropDownOpening; + // + // _viewMenu + // + _viewMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _viewMenu.Name = "_viewMenu"; + _viewMenu.Size = new System.Drawing.Size(45, 22); + _viewMenu.Text = "View"; + _viewMenu.DropDownOpening += Menu_DropDownOpening; + // + // _mainSeparator1 + // + _mainSeparator1.Name = "_mainSeparator1"; + _mainSeparator1.Size = new System.Drawing.Size(6, 25); + // + // _mainSeparator2 + // + _mainSeparator2.Name = "_mainSeparator2"; + _mainSeparator2.Size = new System.Drawing.Size(6, 25); + // + // _mainSeparator3 + // + _mainSeparator3.Name = "_mainSeparator3"; + _mainSeparator3.Size = new System.Drawing.Size(6, 25); + // + // _mainSeparator4 + // + _mainSeparator4.Name = "_mainSeparator4"; + _mainSeparator4.Size = new System.Drawing.Size(6, 25); + // + // _zoomLabel + // + _zoomLabel.AutoSize = false; + _zoomLabel.Name = "_zoomLabel"; + _zoomLabel.Size = new System.Drawing.Size(48, 23); + _zoomLabel.Text = "100%"; + // + // _statusStrip + // + _statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _statusHint, _statusCell, _statusPlane, _statusHover, _statusSelection, _statusSize }); + _statusStrip.Location = new System.Drawing.Point(0, 696); + _statusStrip.Name = "_statusStrip"; + _statusStrip.SizingGrip = false; + _statusStrip.Size = new System.Drawing.Size(1280, 24); + _statusStrip.TabIndex = 6; + // + // _statusHint + // + _statusHint.Name = "_statusHint"; + _statusHint.Size = new System.Drawing.Size(605, 19); + _statusHint.Spring = true; + _statusHint.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _statusCell + // + _statusCell.AutoSize = false; + _statusCell.Name = "_statusCell"; + _statusCell.Size = new System.Drawing.Size(110, 23); + _statusCell.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _statusPlane + // + _statusPlane.AutoSize = false; + _statusPlane.Name = "_statusPlane"; + _statusPlane.Size = new System.Drawing.Size(160, 23); + _statusPlane.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + _statusPlane.ToolTipText = "Height of the work plane: the chosen floor's base, or the first floor with all floors shown; Ctrl+PgUp / Ctrl+PgDn move it. At plane Z placement draws there."; + // + // _statusHover + // + _statusHover.AutoSize = false; + _statusHover.Name = "_statusHover"; + _statusHover.Size = new System.Drawing.Size(280, 23); + _statusHover.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _statusSelection + // + _statusSelection.AutoSize = false; + _statusSelection.Name = "_statusSelection"; + _statusSelection.Size = new System.Drawing.Size(120, 23); + _statusSelection.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _statusSize + // + _statusSize.AutoSize = false; + _statusSize.Name = "_statusSize"; + _statusSize.Size = new System.Drawing.Size(150, 23); + _statusSize.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // MultiEditorControl + // + ContextMenuStrip = _hostMenuBlocker; + Controls.Add(_centre); + Controls.Add(_toolPalette); + Controls.Add(_sideSplitter); + Controls.Add(_sidePanel); + Controls.Add(_optionsStrip); + Controls.Add(_mainStrip); + Controls.Add(_statusStrip); + Name = "MultiEditorControl"; + Size = new System.Drawing.Size(1280, 720); + _centre.ResumeLayout(false); + _toolPalette.ResumeLayout(false); + _toolPalette.PerformLayout(); + _sidePanel.ResumeLayout(false); + _sideSplit.Panel1.ResumeLayout(false); + _sideSplit.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)_sideSplit).EndInit(); + _sideSplit.ResumeLayout(false); + _optionsStrip.ResumeLayout(false); + _optionsStrip.PerformLayout(); + _mainStrip.ResumeLayout(false); + _mainStrip.PerformLayout(); + _statusStrip.ResumeLayout(false); + _statusStrip.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.ContextMenuStrip _hostMenuBlocker; + private System.Windows.Forms.Panel _centre; + private System.Windows.Forms.Label _emptyHint; + private UoFiddler.Plugin.MultiEditor.Rendering.GlCanvas _canvas; + private UoFiddler.Controls.UserControls.ThemedTabControl _docTabs; + private System.Windows.Forms.ToolStrip _toolPalette; + private System.Windows.Forms.ToolStripLabel _editToolsLabel; + private System.Windows.Forms.ToolStripLabel _drawToolsLabel; + private System.Windows.Forms.ToolStripLabel _houseToolsLabel; + private System.Windows.Forms.Splitter _sideSplitter; + private System.Windows.Forms.Panel _sidePanel; + private System.Windows.Forms.SplitContainer _sideSplit; + private UoFiddler.Plugin.MultiEditor.UI.TileBrowserPanel _browser; + private UoFiddler.Plugin.MultiEditor.UI.InspectorPanel _inspector; + private System.Windows.Forms.ToolStrip _optionsStrip; + private System.Windows.Forms.ToolStripLabel _toolLabel; + private System.Windows.Forms.ToolStripSeparator _optionsSeparator1; + private System.Windows.Forms.ToolStripLabel _placeLabel; + private System.Windows.Forms.ToolStripLabel _brushLabel; + private System.Windows.Forms.ToolStripLabel _zStepLabel; + private UoFiddler.Plugin.MultiEditor.UI.ToolStripChoice _zStepCombo; + private System.Windows.Forms.ToolStripSeparator _optionsSeparator2; + private System.Windows.Forms.ToolStripLabel _floorLabel; + private System.Windows.Forms.ToolStripSeparator _optionsSeparator3; + private System.Windows.Forms.ToolStripLabel _drawTileLabel; + private System.Windows.Forms.ToolStripSeparator _ridgeSeparator; + private System.Windows.Forms.ToolStripLabel _ridgeLabel; + private System.Windows.Forms.ToolStripSeparator _gablesSeparator; + private System.Windows.Forms.ToolStripLabel _gablesLabel; + private System.Windows.Forms.ToolStripSeparator _gableFillSeparator; + private System.Windows.Forms.ToolStripLabel _gableFillLabel; + private System.Windows.Forms.ToolStrip _mainStrip; + private System.Windows.Forms.ToolStripDropDownButton _fileMenu; + private System.Windows.Forms.ToolStripDropDownButton _editMenu; + private System.Windows.Forms.ToolStripDropDownButton _selectMenu; + private System.Windows.Forms.ToolStripDropDownButton _viewMenu; + private System.Windows.Forms.ToolStripSeparator _mainSeparator1; + private System.Windows.Forms.ToolStripSeparator _mainSeparator2; + private System.Windows.Forms.ToolStripSeparator _mainSeparator3; + private System.Windows.Forms.ToolStripSeparator _mainSeparator4; + private System.Windows.Forms.ToolStripLabel _zoomLabel; + private System.Windows.Forms.StatusStrip _statusStrip; + private System.Windows.Forms.ToolStripStatusLabel _statusHint; + private System.Windows.Forms.ToolStripStatusLabel _statusCell; + private System.Windows.Forms.ToolStripStatusLabel _statusPlane; + private System.Windows.Forms.ToolStripStatusLabel _statusHover; + private System.Windows.Forms.ToolStripStatusLabel _statusSelection; + private System.Windows.Forms.ToolStripStatusLabel _statusSize; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs new file mode 100644 index 00000000..deb6ac3d --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs @@ -0,0 +1,2070 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Controls.Classes; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.Editing; +using UoFiddler.Plugin.MultiEditor.Rendering; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The multi editor tab: command bar and tool options on top, tool palette on the left, + /// document tabs over the canvas in the middle, tile browser and inspector on the right, + /// status line at the bottom. The fixed layout is made in the designer; the commands, the + /// menus and buttons made from them and the settings wait for the first show. + /// + public partial class MultiEditorControl : UserControl + { + private sealed class EditorDocument + { + public EditorSession Session; + public Camera2D Camera = new Camera2D(); + public int? ClientId; + } + + private readonly ArtMasks _masks = new ArtMasks(); + private readonly List _documents = new List(); + private readonly CommandRegistry _commands = new CommandRegistry(); + private readonly Dictionary _toolCommands = new Dictionary(); + + private bool _built; + private bool _syncing; + private HouseStyles _houseStyles; + private EditorDocument _active; + + private Label _message; + private readonly List _brushCommands = new List(); + private readonly List<(EditorCommand Command, string Text, string Tip)> _placementCommands = new List<(EditorCommand, string, string)>(); + private readonly List _floorButtons = new List(); + + public MultiEditorControl() + { + InitializeComponent(); + SplitterGrip.Attach(_sideSplit); + + // Room after each tab's text for its close button, at any DPI. + _docTabs.Padding = new Point((CloseGlyphSize + LogicalToDeviceUnits(16)) / 2, _docTabs.Padding.Y); + } + + internal EditorSession Session => _active?.Session; + + internal GlCanvas Canvas => _canvas; + + // ---------------------------------------------------------------- entry points for the plugin + + /// Opens a multi from the loaded client files in a new document tab. + public void OpenMulti(int id) + { + EnsureBuilt(); + MultiComponentList list = Multis.GetComponents(id); + if (!_built || list == null || list == MultiComponentList.Empty) + { + return; + } + + AddDocument(new OpenedMulti(list, $"Multi 0x{id:X4}", id)); + } + + /// Makes a tile the draw tile (Items tab context menu). + public void SelectDrawTile(ushort id) + { + EnsureBuilt(); + if (Session != null) + { + Session.SetDrawTile(id); + Session.Tool = ToolKind.Draw; + } + } + + /// Asks for an area of a map and starts pasting its statics (Map tab context menu). + public void ExtractFromMap(Map map, Point location) + { + EnsureBuilt(); + if (!_built) + { + return; + } + + List tiles = DocumentIO.ExtractFromMap(this, map, location); + if (tiles == null || tiles.Count == 0) + { + return; + } + + if (Session == null) + { + int width = tiles.Max(t => t.Dx) + 1; + int height = tiles.Max(t => t.Dy) + 1; + NewDocument(width, height, "Map extract"); + } + + Session.BeginPaste(tiles); + _canvas.Focus(); + } + + // ---------------------------------------------------------------- construction + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + + if (Visible && !DesignMode) + { + EnsureBuilt(); + WatchHostForm(); + } + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + WatchHostForm(); + } + + // ---------------------------------------------------------------- window resizing + + private Form _hostForm; + private Timer _resizeTimer; + private bool _sidebarsHeld; + + /// + /// Starts OpenGL's windowing library ahead of the first show. It takes around 400 ms once + /// per process, which is better spent while the application sits idle after start-up than + /// when the tab is first clicked. + /// + internal static void WarmUpOpenGl() + { + try + { + OpenTK.Windowing.Desktop.GLFWProvider.EnsureInitialized(); + } + catch (Exception) + { + // The canvas reports the problem when it is created. + } + } + + /// The tab can be undocked into its own window, so the form is looked up again each time. + private void WatchHostForm() + { + Form form = FindForm(); + if (form == _hostForm) + { + return; + } + + if (_hostForm != null) + { + _hostForm.ResizeBegin -= HostForm_ResizeBegin; + _hostForm.ResizeEnd -= HostForm_ResizeEnd; + } + + _hostForm = form; + if (form != null) + { + form.ResizeBegin += HostForm_ResizeBegin; + form.ResizeEnd += HostForm_ResizeEnd; + } + } + + /// + /// While the window border is dragged, the two sidebars (hundreds of nested controls, most + /// of a resize's cost) are laid out a few times a second instead of on every mouse step. + /// The canvas and toolbars keep following the window live. + /// + private void HostForm_ResizeBegin(object sender, EventArgs e) + { + if (!_built || _sidebarsHeld) + { + return; + } + + // Undocked, the sidebars keep their size and just ride along with their panel, which + // costs nothing; docked, every step would lay out everything inside them. + _sidebarsHeld = true; + _sideSplit.Dock = DockStyle.None; + _resizeTimer ??= new Timer { Interval = 300 }; + _resizeTimer.Tick -= ResizeTimer_Tick; + _resizeTimer.Tick += ResizeTimer_Tick; + _resizeTimer.Start(); + } + + private void ResizeTimer_Tick(object sender, EventArgs e) + { + if (_sidebarsHeld && _sideSplit.Parent != null && _sideSplit.Bounds != _sideSplit.Parent.ClientRectangle) + { + _sideSplit.Bounds = _sideSplit.Parent.ClientRectangle; + } + } + + private void HostForm_ResizeEnd(object sender, EventArgs e) + { + if (!_sidebarsHeld) + { + return; + } + + _sidebarsHeld = false; + _resizeTimer?.Stop(); + _sideSplit.Dock = DockStyle.Fill; + LayoutSidebars(); + } + + private void EnsureBuilt() + { + if (_built || _message != null) + { + return; + } + + EditorSettings.Load(); + _browserShown = EditorSettings.Current.ShowTileBrowser; + _inspectorShown = EditorSettings.Current.ShowInspector; + EditorSettings.Changed += OnSettingsChanged; + Disposed += (_, _) => EditorSettings.Changed -= OnSettingsChanged; + + try + { + _houseStyles = HouseStyles.Load(splitFloorsByColour: true); + } + catch (Exception ex) + { + ShowMessage($"OpenGL could not be started:\r\n{ex.Message}"); + return; + } + + SuspendLayout(); + DefineCommands(); + BuildCanvasMenu(); + + _browser.SetHouseStyles(_houseStyles); + _browser.TileChosen += id => + { + Session?.SetDrawTile(id); + if (Session != null && !IsTileTool(Session.Tool)) + { + Session.Tool = ToolKind.Draw; + } + }; + _browser.DesignOpenRequested += designs => + { + if (!ConfirmOpenMany(designs.Count)) + { + return; + } + + foreach (UoaDesign design in designs) + { + OpenedMulti opened = LoadDesign(() => DocumentIO.FromDesign(design)); + if (opened != null) + { + AddDocument(opened); + } + } + }; + _browser.DesignPlaceRequested += design => + { + List tiles = LoadDesign(() => DesignLibraryPanel.ToTiles(UoaDesignFile.Load(design))); + if (tiles == null || tiles.Count == 0) + { + return; + } + + if (Session == null) + { + NewDocument(tiles.Max(t => t.Dx) + 1, tiles.Max(t => t.Dy) + 1, DocumentIO.DesignTitle(design)); + } + + Session.BeginPaste(tiles); + _canvas.Focus(); + }; + _browser.HouseStyleChosen += ChooseHouseStyle; + _browser.FloorPatternChosen += pattern => + { + if (Session != null) + { + Session.FloorPattern = pattern; + SetTool(ToolKind.FloorPattern); + } + }; + _browser.FoundationChosen += () => + { + // The foundation tool builds with the wall style its posts belong to. + if (Session != null && _browser.FoundationStyle != null) + { + Session.HouseStyle = _browser.FoundationStyle; + } + + SetTool(ToolKind.Foundation, fromHousePage: true); + }; + _browser.SwapToHouseStyleRequested += style => + { + if (Session != null && style != null) + { + Session.HouseStyle = style; + Session.SwapSelectionToHouseStyle(); + } + }; + _browser.PrefabChosen += tiles => + { + Session?.BeginPaste(tiles); + _canvas.Focus(); + }; + + // The hint takes its colours from the settings and its font from the host. + _emptyHint.ForeColor = EditorSettings.Current.BackgroundText; + _emptyHint.BackColor = EditorSettings.Current.EffectiveBackground; + _emptyHint.Font = new Font(Font.FontFamily, 11f); + + // The strips and the sidebars are laid out in the designer (docking runs from the last + // added control: strips first, then the sidebars on the right, the tool palette on the + // left, and the canvas area takes what is left). Here they get the command items. + BuildToolPalette(); + BuildOptionsStrip(); + BuildMainStrip(); + + // The performance box floats over the canvas's top right corner (F12). + _performancePanel = new PerformancePanel { Visible = false }; + _centre.Controls.Add(_performancePanel); + _performancePanel.BringToFront(); + _performancePanel.Bind(_canvas.Stats, () => Session?.CompList.TileCount ?? 0); + _performancePanel.SizeChanged += (_, _) => PlacePerformancePanel(); + _centre.Resize += (_, _) => PlacePerformancePanel(); + ResumeLayout(true); + + // Splitter distances only hold once the containers have their real size. + LayoutSidebars(); + + ControlEvents.FilePathChangeEvent += OnClientFilesChanged; + ControlEvents.ItemChangeEvent += OnItemChanged; + ControlEvents.TileDataChangeEvent += OnItemChanged; + Disposed += (_, _) => + { + ControlEvents.FilePathChangeEvent -= OnClientFilesChanged; + ControlEvents.ItemChangeEvent -= OnItemChanged; + ControlEvents.TileDataChangeEvent -= OnItemChanged; + }; + + _built = true; + Activate(-1); + } + + /// + /// The host's tab control has an "UnDock" menu that every child without a menu of its own + /// inherits. An empty menu that never opens keeps it off the canvas, toolbars and panels; + /// undocking stays on the tab header. + /// + private void HostMenuBlocker_Opening(object sender, System.ComponentModel.CancelEventArgs e) + { + e.Cancel = true; + } + + private void DocTabs_SelectedIndexChanged(object sender, EventArgs e) + { + Activate(_docTabs.SelectedIndex); + } + + /// + /// The sidebars sit in a panel docked right with a plain splitter, not in a SplitContainer: + /// they keep their width when the window is resized, and docked panels lay out far more cheaply. + /// Between the two sidebars (the tile browser at full height, and beside it floors and + /// selection) is a SplitContainer. + /// + private void SideSplitter_SplitterMoved(object sender, SplitterEventArgs e) + { + RememberSidebarWidths(); + } + + private void SideSplit_SplitterMoved(object sender, SplitterEventArgs e) + { + RememberSidebarWidths(); + } + + private void ShowMessage(string text) + { + if (_message == null) + { + _message = new Label { Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleCenter }; + Controls.Add(_message); + } + + foreach (Control control in Controls) + { + control.Visible = control == _message; + } + + _message.Text = text; + } + + private void OnClientFilesChanged() + { + NewMultiDialog.Reset(); + ResetArt(); + } + + private void OnItemChanged(object sender, int id) + { + ResetArt(); + } + + private void ResetArt() + { + _masks.Clear(); + _canvas.ResetArt(); + _browser.ReloadData(); + } + + // ---------------------------------------------------------------- commands + + private EditorCommand Command(string group, string text, Action execute, Keys shortcut = Keys.None, + Func can = null, Func isChecked = null, string glyph = null, Keys alt = Keys.None) + { + return _commands.Add(new EditorCommand(group, text, execute) + { + Shortcut = shortcut, + AltShortcut = alt, + CanExecute = can, + IsChecked = isChecked, + Glyph = glyph + }); + } + + private EditorCommand _new, _open, _import, _importFolder, _saveClient, _export, _savePrefab, _resize, _close, _closeAll; + private EditorCommand _undo, _redo, _cut, _copy, _paste, _delete; + private EditorCommand _selectAll, _invert, _selectConnected, _selectSameId, _replaceId; + private EditorCommand _rotateLeft, _rotateRight, _mirrorX, _mirrorY, _swapStyle, _hide, _showHidden; + private EditorCommand _grid, _hideWalls, _walkable, _doubleSurface, _hideAbove, _levelUp, _levelDown; + private EditorCommand _fit, _center, _zoomIn, _zoomOut, _zoomReset, _shortcuts; + private EditorCommand _zUp, _zDown, _planeUp, _planeDown, _cyclePlacement, _escape; + private EditorCommand _drawWithSelected, _workPlane; + private ContextMenuStrip _canvasMenu; + private ToolStripMenuItem _canvasMenuTitle; + private EditorCommand _preview, _moveReference, _planView, _allFloors, _showBrowser, _showInspector; + private bool _browserShown = true; + private bool _inspectorShown = true; + private bool _layingOutSidebars; + private bool _applyingOwnSettings; + private EditorCommand _settingsCommand; + private EditorCommand _performanceInfo; + private PerformancePanel _performancePanel; + private bool _performanceShown; + private EditorCommand _savePattern; + private bool _openingHousePage; + private readonly List _terrainCommands = new List(); + private ContextMenuStrip _previewMenu; + + private void DefineCommands() + { + Func hasDoc = () => Session != null; + Func hasSelection = () => Session != null && Session.Selection.Count > 0; + + _new = Command("File", "New multi...", NewDocumentPrompt, Keys.Control | Keys.N, glyph: Glyphs.New); + _open = Command("File", "Open from client...", OpenFromClient, Keys.Control | Keys.O, glyph: Glyphs.Open); + _import = Command("File", "Import files...", ImportFile, Keys.Control | Keys.I); + _importFolder = Command("File", "Import from folder...", ImportFolder, Keys.Control | Keys.Shift | Keys.I); + _saveClient = Command("File", "Save to client...", SaveToClient, Keys.Control | Keys.S, hasDoc, glyph: Glyphs.Save); + _export = Command("File", "Export file...", ExportFile, Keys.Control | Keys.E, hasDoc); + _savePrefab = Command("File", "Save selection as blueprint...", SavePrefab, can: hasSelection); + _savePattern = Command("File", "Save selection as floor pattern...", SaveFloorPattern, can: hasSelection); + _resize = Command("File", "Resize multi...", ResizePrompt, can: hasDoc); + _settingsCommand = Command("File", "Settings...", ShowSettings); + _close = Command("File", "Close design", () => CloseDocument(_active), Keys.Control | Keys.W, hasDoc); + _closeAll = Command("File", "Close all designs", CloseAllDocuments, Keys.Control | Keys.Shift | Keys.W, hasDoc); + + _undo = Command("Edit", "Undo", () => Session.Undo(), Keys.Control | Keys.Z, + () => Session != null && Session.CompList.UndoList.Count > 0, glyph: Glyphs.Undo); + _redo = Command("Edit", "Redo", () => Session.Redo(), Keys.Control | Keys.Y, + () => Session != null && Session.CompList.RedoList.Count > 0, glyph: Glyphs.Redo, alt: Keys.Control | Keys.Shift | Keys.Z); + _cut = Command("Edit", "Cut", () => Session.Cut(), Keys.Control | Keys.X, hasSelection, glyph: Glyphs.Cut); + _copy = Command("Edit", "Copy", () => Session.Copy(), Keys.Control | Keys.C, hasSelection, glyph: Glyphs.Copy); + _paste = Command("Edit", "Paste", () => Session.Paste(), Keys.Control | Keys.V, hasDoc, glyph: Glyphs.Paste); + _delete = Command("Edit", "Delete selection", () => Session.DeleteSelection(), Keys.Delete, hasSelection, glyph: Glyphs.Delete); + + _selectAll = Command("Select", "Select all", () => Session.SelectAll(), Keys.Control | Keys.A, hasDoc); + _invert = Command("Select", "Invert selection", () => Session.InvertSelection(), Keys.Control | Keys.Shift | Keys.A, hasDoc); + _selectConnected = Command("Select", "Grow to connected tiles of the same id", () => Session.SelectConnected(), Keys.Control | Keys.G, hasSelection); + _selectSameId = Command("Select", "Select all tiles with the same id", SelectSameId, Keys.Control | Keys.Shift | Keys.G, hasSelection); + _replaceId = Command("Select", "Replace tile id...", ReplaceIdPrompt, Keys.Control | Keys.H, hasDoc); + + _rotateLeft = Command("Arrange", "Rotate left", () => Transform(GroupTransformKind.RotateLeft), Keys.Oemcomma, hasDoc); + _rotateRight = Command("Arrange", "Rotate right", () => Transform(GroupTransformKind.RotateRight), Keys.OemPeriod, hasDoc); + _mirrorX = Command("Arrange", "Mirror X", () => Transform(GroupTransformKind.MirrorX), can: hasDoc); + _mirrorY = Command("Arrange", "Mirror Y", () => Transform(GroupTransformKind.MirrorY), can: hasDoc); + _swapStyle = Command("Arrange", "Swap selection to the chosen house style", () => Session.SwapSelectionToHouseStyle(), + Keys.Control | Keys.R, () => Session != null && Session.Selection.Count > 0 && Session.HouseStyle != null); + _zUp = Command("Arrange", "Raise selection (Z +1)", () => Session.ShiftSelectionZ(1), Keys.OemCloseBrackets, hasSelection, alt: Keys.Shift | Keys.Up); + _zDown = Command("Arrange", "Lower selection (Z -1)", () => Session.ShiftSelectionZ(-1), Keys.OemOpenBrackets, hasSelection, alt: Keys.Shift | Keys.Down); + _hide = Command("Arrange", "Hide selection", () => Session.HideSelection(), Keys.H, hasSelection); + _showHidden = Command("Arrange", "Show hidden tiles", () => Session.ShowHiddenTiles(), Keys.Shift | Keys.H, hasDoc); + + _workPlane = Command("View", "Work plane", () => Session.ShowWorkPlane = !Session.ShowWorkPlane, + Keys.F, hasDoc, () => Session?.ShowWorkPlane == true); + _grid = Command("View", "Grid", () => Session.ShowGrid = !Session.ShowGrid, Keys.G, hasDoc, () => Session?.ShowGrid == true, Glyphs.Grid); + _hideWalls = Command("View", "Hide walls", () => Session.HideWalls = !Session.HideWalls, Keys.W, hasDoc, () => Session?.HideWalls == true); + _walkable = Command("View", "Mark walkable tiles", () => Session.ShowWalkables = !Session.ShowWalkables, can: hasDoc, isChecked: () => Session?.ShowWalkables == true); + _doubleSurface = Command("View", "Mark double surfaces", () => Session.ShowDoubleSurface = !Session.ShowDoubleSurface, can: hasDoc, isChecked: () => Session?.ShowDoubleSurface == true); + _hideAbove = Command("View", "Hide floors above the active one", () => Session.HideAboveLevel = !Session.HideAboveLevel, can: hasDoc, isChecked: () => Session?.HideAboveLevel == true); + _levelUp = Command("View", "Floor up", () => Session.StepLevel(1), Keys.PageUp, hasDoc); + _levelDown = Command("View", "Floor down", () => Session.StepLevel(-1), Keys.PageDown, hasDoc); + _planeUp = Command("View", "Work plane up 1", () => Session.MoveWorkPlane(1), Keys.Control | Keys.PageUp, hasDoc); + _planeDown = Command("View", "Work plane down 1", () => Session.MoveWorkPlane(-1), Keys.Control | Keys.PageDown, hasDoc); + _allFloors = Command("View", "All floors", () => Session.LevelIndex = 0, Keys.Control | Keys.Home, hasDoc, () => Session?.LevelIndex == 0); + _showBrowser = Command("View", "Tile browser sidebar", () => ToggleSidebar(browser: true), Keys.F9, isChecked: () => _browserShown); + _showInspector = Command("View", "Floors and selection sidebar", () => ToggleSidebar(browser: false), Keys.F10, isChecked: () => _inspectorShown); + _preview = Command("View", "Preview as in the client", () => Session.PreviewMode = !Session.PreviewMode, + Keys.F5, hasDoc, () => Session?.PreviewMode == true); + _planView = Command("View", "Plan view (top-down)", TogglePlanView, Keys.V, hasDoc, () => Session?.PlanMode == true); + foreach (PreviewTerrain terrain in Enum.GetValues()) + { + string name = terrain == PreviewTerrain.None ? "No ground" : terrain.ToString(); + _terrainCommands.Add(Command("View", $"Preview on: {name}", () => SetPreviewTerrain(terrain), can: hasDoc, + isChecked: () => Session?.PreviewTerrain == terrain)); + } + + _moveReference = Command("View", "Move reference...", MoveReferencePrompt, can: () => Session?.Reference != null); + _fit = Command("View", "Fit to window", () => _canvas.FitToView(), Keys.Home, hasDoc, glyph: Glyphs.Fit); + _center = Command("View", "Center design", () => _canvas.CenterView(), Keys.Shift | Keys.Home, hasDoc, glyph: Glyphs.Center); + _zoomIn = Command("View", "Zoom in", () => _canvas.ZoomStep(1), Keys.Add, glyph: Glyphs.ZoomIn, alt: Keys.Shift | Keys.Oemplus); + _zoomOut = Command("View", "Zoom out", () => _canvas.ZoomStep(-1), Keys.Subtract, glyph: Glyphs.ZoomOut, alt: Keys.OemMinus); + _zoomReset = Command("View", "Zoom 100%", () => _canvas.SetZoom(1f), Keys.Control | Keys.D0, alt: Keys.Control | Keys.NumPad0); + _performanceInfo = Command("View", "Performance info", TogglePerformanceInfo, Keys.F12, isChecked: () => _performanceShown); + + AddTool(ToolKind.Select, "Select", Keys.S, Glyphs.Select); + AddTool(ToolKind.Lasso, "Lasso", Keys.Q, Glyphs.Lasso); + AddTool(ToolKind.Draw, "Draw", Keys.D, Glyphs.Draw); + AddTool(ToolKind.Remove, "Remove", Keys.R, Glyphs.Remove); + AddTool(ToolKind.Altitude, "Altitude", Keys.E, Glyphs.Altitude); + AddTool(ToolKind.Pipette, "Pick tile", Keys.P, Glyphs.Pipette); + AddTool(ToolKind.Transparent, "See through", Keys.T, Glyphs.Transparent); + AddTool(ToolKind.RectFill, "Rectangle", Keys.B, Glyphs.RectFill); + AddTool(ToolKind.Line, "Line", Keys.L, Glyphs.Line); + AddTool(ToolKind.Wall, "Walls", Keys.D1, Glyphs.Wall); + AddTool(ToolKind.Floor, "Floors", Keys.D2, Glyphs.Floor); + AddTool(ToolKind.Door, "Doors", Keys.D3, Glyphs.Door); + AddTool(ToolKind.Stair, "Stairs", Keys.D4, Glyphs.Stair); + AddTool(ToolKind.Roof, "Roofs", Keys.D5, Glyphs.Roof); + AddTool(ToolKind.Foundation, "Foundation", Keys.D6, Glyphs.Foundation); + AddTool(ToolKind.FloorPattern, "Floor pattern", Keys.None, Glyphs.Floor); + + _cyclePlacement = Command("Tools", "Next placement mode", CyclePlacement, Keys.M, hasDoc); + foreach ((PlacementMode mode, string text, string tip) in new[] + { + (PlacementMode.Stack, "On top", "On top of the tile under the cursor"), + (PlacementMode.Replace, "Replace", "Replacing the tile under the cursor, at its Z"), + (PlacementMode.FixedZ, "At plane Z", "At the work plane's Z, in the cell under the cursor") + }) + { + EditorCommand command = Command("Tools", $"Place: {text}", () => + { + Session.Placement = mode; + SyncOptions(); + }, can: hasDoc, isChecked: () => Session?.Placement == mode); + _placementCommands.Add((command, text, tip)); + } + + foreach ((int size, Keys key) in new[] { (1, Keys.D1), (3, Keys.D2), (5, Keys.D3) }) + { + _brushCommands.Add(Command("Tools", $"Brush {size}x{size}", () => Session.BrushSize = size, Keys.Control | key, + hasDoc, () => Session?.BrushSize == size)); + } + _escape = Command("Tools", "Cancel tool, then clear selection", Escape, Keys.Escape, hasDoc); + _shortcuts = Command("Help", "Keyboard shortcuts", ShowShortcuts, Keys.F1, glyph: Glyphs.Help); + _drawWithSelected = Command("Tools", "Draw with this tile", DrawWithSelected, can: () => Session?.SelectedTile != null); + } + + private void AddTool(ToolKind kind, string text, Keys key, string glyph) + { + _toolCommands[kind] = Command("Tools", text, () => SetTool(kind), key, () => Session != null, + () => Session != null && !Session.Pasting && Session.Tool == kind, glyph); + } + + private static bool IsTileTool(ToolKind kind) + { + return kind is ToolKind.Draw or ToolKind.RectFill or ToolKind.Line; + } + + private static bool IsHouseTool(ToolKind kind) + { + return kind is ToolKind.Wall or ToolKind.Floor or ToolKind.Door or ToolKind.Stair or ToolKind.Roof or ToolKind.Foundation; + } + + private void SetTool(ToolKind kind, bool fromHousePage = false) + { + if (Session == null) + { + return; + } + + Session.Tool = kind; + + // A house tool builds with a style from the House page: bring that page up on the + // matching kind. The page answers by choosing the style, which comes back here. + if (IsHouseTool(kind) && !fromHousePage && !_openingHousePage && _browserShown) + { + _openingHousePage = true; + try + { + HousePartKind part = kind switch + { + ToolKind.Floor => HousePartKind.Floor, + ToolKind.Door => HousePartKind.Door, + ToolKind.Stair => HousePartKind.Stair, + ToolKind.Roof => HousePartKind.Roof, + _ => HousePartKind.Wall + }; + _browser.ShowHousePage(part, foundation: kind == ToolKind.Foundation); + } + finally + { + _openingHousePage = false; + } + } + + _canvas.Focus(); + } + + private void ChooseHouseStyle(HouseStyle style) + { + if (Session == null || style == null) + { + return; + } + + Session.HouseStyle = style; + ToolKind kind = style.Kind switch + { + HousePartKind.Floor => ToolKind.Floor, + HousePartKind.Door => ToolKind.Door, + HousePartKind.Stair => ToolKind.Stair, + HousePartKind.Roof => ToolKind.Roof, + _ => ToolKind.Wall + }; + SetTool(kind, fromHousePage: true); + } + + private void CyclePlacement() + { + Session.Placement = (PlacementMode)(((int)Session.Placement + 1) % 3); + SyncOptions(); + } + + private void Escape() + { + // First Esc stops what the tool is doing, the next one clears the selection. + if (Session.Pasting || Session.ActiveTool.IsDragging || Session.Selection.Count == 0) + { + Session.CancelTool(); + } + else + { + Session.ClearSelection(); + } + } + + private void Transform(GroupTransformKind kind) + { + string problem = Session.TransformGroup(kind); + if (problem != null) + { + MessageBox.Show(this, problem, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + private void SelectSameId() + { + var ids = new HashSet(Session.Selection.Select(t => t.Id)); + Session.SelectWhere(t => ids.Contains(t.Id), add: false); + } + + private void ReplaceIdPrompt() + { + MultiTile selected = Session.SelectedTile ?? Session.Selection.FirstOrDefault(); + string from = Prompt.Text(this, "Replace tile id", "Tile id to replace (decimal or 0x hex):", + selected != null ? $"0x{selected.Id:X4}" : string.Empty); + if (from == null || !Prompt.TryParseId(from, out ushort fromId)) + { + return; + } + + string to = Prompt.Text(this, "Replace tile id", $"Replace 0x{fromId:X4} with (decimal or 0x hex):", $"0x{Session.DrawTileId:X4}"); + if (to == null || !Prompt.TryParseId(to, out ushort toId)) + { + return; + } + + bool selectionOnly = Session.Selection.Count > 1; + int count = Session.ReplaceTileId(fromId, toId, selectionOnly); + _statusHint.Text = $"Replaced {count} tile(s)" + (selectionOnly ? " in the selection" : string.Empty); + } + + private void SavePrefab() + { + List tiles = Session.SelectionAsClipboard(); + string name = tiles != null ? Prompt.Text(this, "Save blueprint", "Blueprint name:") : null; + if (name == null) + { + return; + } + + _browser.SaveBlueprint(name, tiles); + } + + private void DrawWithSelected() + { + Session.SetDrawTile(Session.SelectedTile.Id); + Session.Tool = ToolKind.Draw; + } + + private void BuildCanvasMenu() + { + _canvasMenu = new ContextMenuStrip(); + _canvasMenuTitle = new ToolStripMenuItem { Enabled = false }; + _canvasMenu.Items.Add(_canvasMenuTitle); + _canvasMenu.Items.Add(_commands.MenuItem(_drawWithSelected)); + var brushMenu = new ToolStripMenuItem("Brush size"); + foreach (EditorCommand brush in _brushCommands) + { + brushMenu.DropDownItems.Add(_commands.MenuItem(brush)); + } + + _canvasMenu.Items.Add(brushMenu); + _canvasMenu.Items.Add(new ToolStripSeparator()); + foreach (EditorCommand command in new[] { _cut, _copy, _paste, _delete }) + { + _canvasMenu.Items.Add(_commands.MenuItem(command)); + } + + _canvasMenu.Items.Add(new ToolStripSeparator()); + foreach (EditorCommand command in new[] { _zUp, _zDown, _rotateLeft, _rotateRight, _hide, _showHidden }) + { + _canvasMenu.Items.Add(_commands.MenuItem(command)); + } + + _canvasMenu.Items.Add(new ToolStripSeparator()); + foreach (EditorCommand command in new[] { _selectConnected, _selectSameId, _selectAll, _savePrefab, _savePattern }) + { + _canvasMenu.Items.Add(_commands.MenuItem(command)); + } + + _canvasMenu.Items.Add(new ToolStripSeparator()); + foreach (EditorCommand command in new[] { _workPlane, _grid, _fit, _center }) + { + _canvasMenu.Items.Add(_commands.MenuItem(command)); + } + } + + /// + /// Right click on the canvas: the menu acts on the selection, so a tile under the cursor + /// that is not part of it becomes the selection first. + /// + /// Picks the preview ground for this document and as the default for the next ones. + private void SetPreviewTerrain(PreviewTerrain terrain) + { + Session.PreviewTerrain = terrain; + EditorSettings settings = EditorSettings.Current.Clone(); + settings.PreviewTerrain = (int)terrain; + _applyingOwnSettings = true; + settings.Apply(); + _applyingOwnSettings = false; + } + + private void ShowCanvasMenu(Point location) + { + EditorSession session = Session; + if (session == null) + { + return; + } + + if (session.PreviewMode) + { + // Nothing can be edited in preview: the menu offers the ground and the way out. + if (_previewMenu == null) + { + _previewMenu = new ContextMenuStrip(); + foreach (EditorCommand terrain in _terrainCommands) + { + _previewMenu.Items.Add(_commands.MenuItem(terrain)); + } + + _previewMenu.Items.Add(new ToolStripSeparator()); + ToolStripMenuItem leave = _commands.MenuItem(_preview); + leave.Text = "Leave preview"; + _previewMenu.Items.Add(leave); + _previewMenu.Items.Add(_commands.MenuItem(_fit)); + } + + _commands.RefreshStates(); + _previewMenu.Show(_canvas, location); + return; + } + + MultiTile hover = session.HoverTile; + if (hover != null && !session.IsSelected(hover)) + { + session.SetSelection(new[] { hover }, add: false); + } + + MultiTile single = session.SelectedTile; + int count = session.Selection.Count; + _canvasMenuTitle.Text = single != null ? $"0x{single.Id:X4} {TileName(single.Id)} (Z {single.Z})" + : count > 1 ? $"{count} tiles selected" + : "Nothing selected"; + + _commands.RefreshStates(); + _canvasMenu.Show(_canvas, location); + } + + /// + /// Learns a bordered floor from the selection (a rectangle laid out by hand: corners, sides + /// and fill) and shows it on the House page, ready to lay at any size. + /// + private void SaveFloorPattern() + { + string name = Prompt.Text(this, "Save floor pattern", "Pattern name:"); + if (name == null) + { + return; + } + + FloorPattern pattern = FloorPattern.Learn(Session.Selection, name, out string problem); + if (pattern == null) + { + MessageBox.Show(this, problem, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + FloorPatterns.Save(pattern); + _browser.ShowPatterns(pattern); + } + + /// Reads a design from the library, with a message instead of an exception when its file is gone or damaged. + private T LoadDesign(Func load) where T : class + { + try + { + using (new WaitCursorScope(this)) + { + return load(); + } + } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException) + { + MessageBox.Show(this, "The design could not be read: " + ex.Message, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return null; + } + } + + private void ShowShortcuts() + { + using var form = new ShortcutsForm(); + form.ShowCommands(_commands.Commands); + form.ShowDialog(this); + } + + /// Lists the other open documents: one of them can be shown faintly under the active one. + private void FillReferenceMenu(ToolStripMenuItem menu) + { + menu.DropDownItems.Clear(); + menu.Enabled = Session != null; + if (Session == null) + { + return; + } + + var none = new ToolStripMenuItem("None") { Checked = Session.Reference == null }; + none.Click += (_, _) => Session.SetReference(null); + menu.DropDownItems.Add(none); + + foreach (EditorDocument document in _documents) + { + if (document == _active) + { + continue; + } + + MultiEditorComponentList list = document.Session.CompList; + var item = new ToolStripMenuItem(document.Session.Title) { Checked = Session.Reference == list }; + item.Click += (_, _) => Session.SetReference(list); + menu.DropDownItems.Add(item); + } + + if (menu.DropDownItems.Count == 1) + { + menu.DropDownItems.Add(new ToolStripMenuItem("(open another multi to use it as a reference)") { Enabled = false }); + } + } + + /// Narrowest a sidebar gets: below this its controls no longer fit. + private const int _minSidebar = 240; + + /// + /// Gives each sidebar its width from the settings, never below the minimum; a hidden one + /// hands its space to the canvas. When the window is too narrow for both at their saved + /// widths, the tile browser gives way first, then the other one, and the canvas keeps a + /// strip. Safe to call at any time: it is run again whenever the editor changes size, + /// because at start-up the first layout happens before the window has its real width. + /// + private void LayoutSidebars() + { + if (_sideSplit == null || _sidePanel == null) + { + return; + } + + const int paletteWidth = 96; + const int minCanvas = 200; + int browser = Math.Max(_minSidebar, EditorSettings.Current.TileBrowserWidth); + int inspector = Math.Max(_minSidebar, EditorSettings.Current.InspectorWidth); + bool both = _browserShown && _inspectorShown; + int bar = both ? _sideSplit.SplitterWidth : 0; + + _layingOutSidebars = true; + try + { + int available = Width - paletteWidth - minCanvas - _sideSplitter.Width - bar; + int over = (_browserShown ? browser : 0) + (_inspectorShown ? inspector : 0) - available; + if (over > 0 && Width > 0) + { + if (_browserShown) + { + int cut = Math.Min(over, browser - _minSidebar); + browser -= cut; + over -= cut; + } + + if (over > 0 && _inspectorShown) + { + inspector -= Math.Min(over, inspector - _minSidebar); + } + } + + int width = (_browserShown ? browser : 0) + (_inspectorShown ? inspector : 0) + bar; + _sidePanel.Visible = _sideSplitter.Visible = width > 0; + if (width == 0) + { + return; + } + + // Minimums off while the panels are resized: a split container refuses a width or a + // distance that breaks them, and the old values belong to the old size. + _sideSplit.Panel1MinSize = 25; + _sideSplit.Panel2MinSize = 25; + _sideSplit.Panel1Collapsed = !_browserShown; + _sideSplit.Panel2Collapsed = !_inspectorShown; + _sidePanel.Width = width; + _sidePanel.PerformLayout(); + + if (both) + { + int distance = _sideSplit.Width - inspector - _sideSplit.SplitterWidth; + if (distance >= 25 && distance <= _sideSplit.Width - 25 - _sideSplit.SplitterWidth) + { + _sideSplit.SplitterDistance = distance; + } + + if (_sideSplit.Width >= (2 * _minSidebar) + _sideSplit.SplitterWidth) + { + _sideSplit.Panel1MinSize = _minSidebar; + _sideSplit.Panel2MinSize = _minSidebar; + } + } + } + catch (InvalidOperationException) + { + // The split container was too small for the numbers; the next resize tries again. + } + finally + { + _layingOutSidebars = false; + } + } + + protected override void OnSizeChanged(EventArgs e) + { + base.OnSizeChanged(e); + if (_built && !_sidebarsHeld) + { + LayoutSidebars(); + } + } + + /// A splitter was dragged: the sidebar widths go into the profile. + private void RememberSidebarWidths() + { + if (_layingOutSidebars || !_built || _sidebarsHeld || !Visible) + { + return; + } + + // Only a real drag is remembered: widths below the minimum come from a layout in + // progress (the window still opening), not from the user. + EditorSettings settings = EditorSettings.Current.Clone(); + if (_browserShown && _inspectorShown) + { + if (_sideSplit.Panel1.Width < _minSidebar || _sideSplit.Panel2.Width < _minSidebar) + { + return; + } + + settings.TileBrowserWidth = _sideSplit.Panel1.Width; + settings.InspectorWidth = _sideSplit.Panel2.Width; + } + else if (_sidePanel.Width < _minSidebar) + { + return; + } + else if (_browserShown) + { + settings.TileBrowserWidth = _sidePanel.Width; + } + else if (_inspectorShown) + { + settings.InspectorWidth = _sidePanel.Width; + } + + _applyingOwnSettings = true; + settings.Apply(); + _applyingOwnSettings = false; + } + + private void OnSettingsChanged() + { + if (!_built || _applyingOwnSettings) + { + return; + } + + _emptyHint.BackColor = EditorSettings.Current.EffectiveBackground; + _emptyHint.ForeColor = EditorSettings.Current.BackgroundText; + _canvas.Invalidate(); + } + + private void ShowSettings() + { + using var dialog = new EditorSettingsDialog(EditorSettings.Current); + if (dialog.ShowDialog(this) == DialogResult.OK) + { + dialog.Result.Apply(); + } + } + + private void ToggleSidebar(bool browser) + { + if (browser) + { + _browserShown = !_browserShown; + } + else + { + _inspectorShown = !_inspectorShown; + } + + EditorSettings settings = EditorSettings.Current.Clone(); + settings.ShowTileBrowser = _browserShown; + settings.ShowInspector = _inspectorShown; + _applyingOwnSettings = true; + settings.Apply(); + _applyingOwnSettings = false; + LayoutSidebars(); + } + + private void TogglePlanView() + { + // The two views share nothing on screen, so each switch starts with the whole multi in view. + Session.PlanMode = !Session.PlanMode; + _canvas.FitToView(); + } + + /// Shows or hides the performance box; timings are only collected while it is shown. + private void TogglePerformanceInfo() + { + _performanceShown = !_performanceShown; + _canvas.CollectStats = _performanceShown; + _performancePanel.Visible = _performanceShown; + if (_performanceShown) + { + _performancePanel.UpdateNumbers(); + PlacePerformancePanel(); + } + + _commands.RefreshStates(); + } + + private void PlacePerformancePanel() + { + if (_performancePanel == null) + { + return; + } + + int margin = LogicalToDeviceUnits(8); + _performancePanel.Location = new Point(_centre.ClientSize.Width - _performancePanel.Width - margin, _canvas.Top + margin); + } + + private void MoveReferencePrompt() + { + (int x, int y, int z) = Session.ReferenceOffset; + int[] offset = Prompt.Numbers(this, "Move reference", ("Cells X", x, -200, 200), ("Cells Y", y, -200, 200), ("Z", z, -128, 127)); + if (offset != null) + { + Session.ReferenceOffset = (offset[0], offset[1], offset[2]); + } + } + + // ---------------------------------------------------------------- layout pieces + + /// Fills the designer's main strip: the menus, and the command buttons after each separator. + private void BuildMainStrip() + { + ToolStrip strip = _mainStrip; + + Menu(_fileMenu, _new, _open, _import, _importFolder, null, _saveClient, _export, _savePrefab, _savePattern, null, _resize, _settingsCommand, null, _close, _closeAll); + Menu(_editMenu, _undo, _redo, null, _cut, _copy, _paste, _delete, null, + _rotateLeft, _rotateRight, _mirrorX, _mirrorY, _swapStyle, null, _zUp, _zDown, _hide, _showHidden); + Menu(_selectMenu, _selectAll, _invert, _selectConnected, _selectSameId, null, _replaceId); + ToolStripDropDownButton view = Menu(_viewMenu, _preview, _planView, null, _workPlane, _grid, _hideWalls, _hideAbove, _walkable, _doubleSurface, null, + _allFloors, _levelUp, _levelDown, _planeUp, _planeDown, null, _showBrowser, _showInspector, null, _fit, _center, _zoomIn, _zoomOut, _zoomReset, null, _moveReference, null, _performanceInfo); + var terrainMenu = new ToolStripMenuItem("Preview ground"); + foreach (EditorCommand terrain in _terrainCommands) + { + ToolStripMenuItem item = _commands.MenuItem(terrain); + item.Text = terrain.Text.Replace("Preview on: ", string.Empty); + terrainMenu.DropDownItems.Add(item); + } + + view.DropDownItems.Insert(1, terrainMenu); + + var reference = new ToolStripMenuItem("Reference underlay"); + reference.DropDownItems.Add(new ToolStripMenuItem("None")); + view.DropDownItems.Insert(view.DropDownItems.Count - 1, reference); + view.DropDownOpening += (_, _) => FillReferenceMenu(reference); + + InsertButtons(strip, _mainSeparator1, _new, _open, _saveClient); + InsertButtons(strip, _mainSeparator2, _undo, _redo); + InsertButtons(strip, _mainSeparator3, _cut, _copy, _paste, _delete); + InsertButtons(strip, _mainSeparator4, _workPlane, _grid, _hideWalls); + + // Zoom, then help, after the other groups: zoom out, the zoom, zoom in, fit and centre. + int at = strip.Items.IndexOf(_zoomLabel); + strip.Items.Insert(at++, new ToolStripSeparator()); + strip.Items.Insert(at++, _commands.Button(_zoomOut)); + at++; // the zoom label + foreach (EditorCommand command in new[] { _zoomIn, _fit, _center }) + { + strip.Items.Insert(at++, _commands.Button(command)); + } + + strip.Items.Insert(at++, new ToolStripSeparator()); + strip.Items.Insert(at, _commands.Button(_shortcuts)); + + StyleSeparators(strip); + } + + /// Puts a button for each command into a strip, right after a designer item. + private void InsertButtons(ToolStrip strip, ToolStripItem after, params EditorCommand[] commands) + { + int at = strip.Items.IndexOf(after) + 1; + foreach (EditorCommand command in commands) + { + strip.Items.Insert(at++, _commands.Button(command)); + } + } + + /// Fills one of the designer's menus with command items; null is a separator. + private ToolStripDropDownButton Menu(ToolStripDropDownButton menu, params EditorCommand[] commands) + { + foreach (EditorCommand command in commands) + { + menu.DropDownItems.Add(command == null ? new ToolStripSeparator() : _commands.MenuItem(command)); + } + + return menu; + } + + private void Menu_DropDownOpening(object sender, EventArgs e) + { + _commands.RefreshStates(); + } + + /// Draws a strip's separators so they show on the dark theme too, with some room on both sides. + private static void StyleSeparators(ToolStrip strip) + { + foreach (ToolStripSeparator separator in strip.Items.OfType()) + { + separator.Margin = new Padding(4, 0, 4, 0); + separator.Paint += PaintSeparator; + } + } + + /// A separator as a plain line in a colour that shows on the light and the dark theme. + private static void PaintSeparator(object sender, PaintEventArgs e) + { + var separator = (ToolStripSeparator)sender; + int x = separator.Width / 2; + using var pen = new Pen(Options.DarkMode ? Color.FromArgb(105, 105, 112) : SystemColors.ControlDark); + e.Graphics.DrawLine(pen, x, 4, x, separator.Height - 5); + } + + /// Fills the designer's options strip: the brush buttons and the roof option buttons. + private void BuildOptionsStrip() + { + ToolStrip strip = _optionsStrip; + _toolLabel.Font = new Font(Font, FontStyle.Bold); + + // Where new tiles go: one button per mode, the pressed one in use (M steps through them). + int at = strip.Items.IndexOf(_placeLabel) + 1; + foreach ((EditorCommand command, string text, string tip) in _placementCommands) + { + ToolStripButton button = _commands.Button(command); + button.Text = text; + button.ToolTipText = $"{tip} (M)"; + button.Margin = new Padding(1, 1, 0, 2); + strip.Items.Insert(at++, button); + } + + // Separators between the groups: Place, Brush, Z step, Floor, ... + strip.Items.Insert(strip.Items.IndexOf(_brushLabel), new ToolStripSeparator()); + strip.Items.Insert(strip.Items.IndexOf(_zStepLabel), new ToolStripSeparator()); + StyleSeparators(strip); + + at = strip.Items.IndexOf(_brushLabel) + 1; + foreach (EditorCommand brush in _brushCommands) + { + // One press each instead of a dropdown; the pressed one is the size in use. + ToolStripButton button = _commands.Button(brush); + button.Text = brush.Text.Replace("Brush ", string.Empty); + button.AutoSize = false; + button.Width = 34; + button.Margin = new Padding(1, 1, 0, 2); + strip.Items.Insert(at++, button); + } + + // Roof options, shown only with the Roof tool. + RoofGroup(strip, _ridgeSeparator, _ridgeLabel, + ("Auto", () => Session.Roof.Ridge == RoofRidge.Auto, () => Session.Roof.Ridge = RoofRidge.Auto), + ("X", () => Session.Roof.Ridge == RoofRidge.AlongX, () => Session.Roof.Ridge = RoofRidge.AlongX), + ("Y", () => Session.Roof.Ridge == RoofRidge.AlongY, () => Session.Roof.Ridge = RoofRidge.AlongY)); + RoofGroup(strip, _gablesSeparator, _gablesLabel, + ("Front", () => Session.Roof.Gables == RoofGables.Front, () => Session.Roof.Gables = RoofGables.Front), + ("Both", () => Session.Roof.Gables == RoofGables.Both, () => Session.Roof.Gables = RoofGables.Both), + ("None", () => Session.Roof.Gables == RoofGables.None, () => Session.Roof.Gables = RoofGables.None)); + RoofGroup(strip, _gableFillSeparator, _gableFillLabel, + ("Caps", () => Session.Roof.GableFill == RoofGableFill.Caps, () => Session.Roof.GableFill = RoofGableFill.Caps), + ("Walls", () => Session.Roof.GableFill == RoofGableFill.Walls, () => Session.Roof.GableFill = RoofGableFill.Walls)); + } + + private void ZStepCombo_SelectedIndexChanged(object sender, EventArgs e) + { + Apply(() => Session.ZStep = int.Parse(_zStepCombo.Text)); + } + + private readonly List _roofItems = new List(); + private readonly List<(ToolStripButton Button, Func IsOn)> _roofButtons = new List<(ToolStripButton, Func)>(); + + /// + /// A labelled group of pick-one buttons for a roof option. The separator and the caption + /// come from the designer; the buttons go after the caption and share its tooltip. + /// + private void RoofGroup(ToolStrip strip, ToolStripSeparator separator, ToolStripLabel caption, params (string Text, Func IsOn, Action Set)[] choices) + { + string tip = caption.ToolTipText; + int at = strip.Items.IndexOf(caption) + 1; + _roofItems.Add(separator); + _roofItems.Add(caption); + foreach ((string text, Func isOn, Action set) in choices) + { + var button = new ToolStripButton(text) + { + DisplayStyle = ToolStripItemDisplayStyle.Text, + ToolTipText = tip, + AutoToolTip = false, + Margin = new Padding(1, 1, 0, 2) + }; + button.Click += (_, _) => + { + if (Session == null) + { + return; + } + + set(); + Session.ToolOptionsChanged(); + SyncRoofOptions(); + _canvas.Focus(); + }; + strip.Items.Insert(at++, button); + _roofItems.Add(button); + _roofButtons.Add((button, isOn)); + } + } + + private void SyncRoofOptions() + { + bool show = Session != null && !Session.Pasting && Session.Tool == ToolKind.Roof; + foreach (ToolStripItem item in _roofItems) + { + item.Visible = show; + } + + foreach ((ToolStripButton button, Func isOn) in _roofButtons) + { + button.Checked = show && isOn(); + } + } + + /// Runs a change coming from an options control, unless the control is being filled from the session. + private void Apply(Action change) + { + if (_syncing || Session == null) + { + return; + } + + change(); + _canvas.Focus(); + } + + /// Fills the designer's tool palette: the tool buttons under each section label. + private void BuildToolPalette() + { + ToolStrip strip = _toolPalette; + + void Section(ToolStripLabel title, params ToolKind[] kinds) + { + int at = strip.Items.IndexOf(title) + 1; + foreach (ToolKind kind in kinds) + { + ToolStripButton button = _commands.Button(_toolCommands[kind], showText: true); + button.ImageAlign = ContentAlignment.MiddleLeft; + button.TextAlign = ContentAlignment.MiddleLeft; + button.AutoSize = false; + button.Size = new Size(92, 26); + strip.Items.Insert(at++, button); + } + } + + Section(_editToolsLabel, ToolKind.Select, ToolKind.Lasso, ToolKind.Altitude, ToolKind.Pipette, ToolKind.Transparent, ToolKind.Remove); + Section(_drawToolsLabel, ToolKind.Draw, ToolKind.RectFill, ToolKind.Line); + Section(_houseToolsLabel, ToolKind.Wall, ToolKind.Floor, ToolKind.Door, ToolKind.Stair, ToolKind.Roof, ToolKind.Foundation); + } + + // ---------------------------------------------------------------- documents + + private void NewDocumentPrompt() + { + using var dialog = new NewMultiDialog(); + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + if (dialog.Foundation != null) + { + // A custom house starts as a copy of the client's foundation; it is not tied to that id. + AddDocument(new OpenedMulti(dialog.Foundation, "Custom house", null)); + Session.LevelIndex = 2; + return; + } + + NewDocument(dialog.MultiWidth, dialog.MultiHeight, "Untitled", dialog.FirstFloorZ); + } + + private void NewDocument(int width, int height, string title, int firstFloorZ = 0) + { + EditorDocument document = CreateDocument(title, null); + document.Session.NewBlank(width, height, firstFloorZ); + ShowDocument(document); + } + + private void OpenFromClient() + { + AddDocuments(DocumentIO.OpenFromClient(this)); + } + + private void ImportFile() + { + AddImported(DocumentIO.ImportFromFile(this)); + } + + private void ImportFolder() + { + AddImported(DocumentIO.ImportFromFolder(this)); + } + + /// Opens what an import read, then lists what it could not. + private void AddImported(ImportResult result) + { + if (result == null) + { + return; + } + + int opened = AddDocuments(result.Opened); + MultiFileImport.ShowSummary(this, opened, result.Failures); + } + + /// Opens each multi in its own tab, after asking when there are a lot of them. Returns how many opened. + private int AddDocuments(List opened) + { + if (opened == null || opened.Count == 0 || !ConfirmOpenMany(opened.Count)) + { + return 0; + } + + foreach (OpenedMulti multi in opened) + { + AddDocument(multi); + } + + return opened.Count; + } + + /// Asks before a selection opens more tabs than anyone picks by accident. + private bool ConfirmOpenMany(int count) + { + const int withoutAsking = 12; + return count <= withoutAsking || MessageBox.Show(this, $"Open {count} multis, each in its own tab?", "Multi Editor", + MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK; + } + + private void AddDocument(OpenedMulti opened) + { + EditorDocument document = CreateDocument(opened.Title, opened.ClientId); + document.Session.Load(opened.Components); + ShowDocument(document); + } + + private EditorDocument CreateDocument(string title, int? clientId) + { + var session = new EditorSession(_masks, _houseStyles) { Title = title }; + EditorSettings settings = EditorSettings.Current; + session.ShowWorkPlane = settings.StartWithWorkPlane; + session.ShowGrid = settings.StartWithGrid; + session.HideAboveLevel = settings.HideFloorsAbove; + session.PreviewTerrain = (PreviewTerrain)Math.Clamp(settings.PreviewTerrain, 0, 4); + if (_active != null) + { + session.FloorPattern = _active.Session.FloorPattern; + session.Roof.Ridge = _active.Session.Roof.Ridge; + session.Roof.Gables = _active.Session.Roof.Gables; + session.Roof.GableFill = _active.Session.Roof.GableFill; + + // A new tab starts with the tool setup you were working with. + session.SetDrawTile(_active.Session.DrawTileId); + session.Placement = _active.Session.Placement; + session.BrushSize = _active.Session.BrushSize; + session.ZStep = _active.Session.ZStep; + session.HouseStyle = _active.Session.HouseStyle; + } + + return new EditorDocument { Session = session, ClientId = clientId }; + } + + private void ShowDocument(EditorDocument document) + { + _documents.Add(document); + _docTabs.TabPages.Add(new TabPage(document.Session.Title)); + if (_docTabs.SelectedIndex == _documents.Count - 1) + { + Activate(_documents.Count - 1); + } + else + { + _docTabs.SelectedIndex = _documents.Count - 1; + } + + _canvas.Focus(); + } + + private void SaveToClient() + { + int? id = DocumentIO.SaveToClient(this, Session.CompList, _active.ClientId); + if (id == null) + { + return; + } + + _active.ClientId = id; + Session.Title = $"Multi 0x{id:X4}"; + Session.MarkSaved(); + } + + private void ExportFile() + { + if (DocumentIO.ExportToFile(this, Session.CompList, Session.Title, Session.FirstFloorZ)) + { + Session.MarkSaved(); + } + } + + private void ResizePrompt() + { + int[] size = Prompt.Numbers(this, "Resize multi", + ("Width (X)", Session.CompList.Width, 1, 200), ("Height (Y)", Session.CompList.Height, 1, 200)); + if (size != null) + { + Session.Resize(size[0], size[1]); + } + } + + /// Closes every tab, asking once when any of them has unsaved changes. + private void CloseAllDocuments() + { + int modified = _documents.Count(d => d.Session.Modified); + if (modified > 0 && MessageBox.Show(this, + (modified == 1 ? "1 design has" : $"{modified} designs have") + + " changes that were not saved to the client or exported.\r\nClose all designs anyway?", + "Multi Editor", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) + { + return; + } + + // The others first, the active one last, so no other tab is opened on the way. + foreach (EditorDocument document in _documents.Where(d => d != _active).Reverse().ToList()) + { + CloseDocument(document, ask: false); + } + + CloseDocument(_active, ask: false); + } + + private void CloseDocument(EditorDocument document, bool ask = true) + { + if (document == null) + { + return; + } + + if (ask && document.Session.Modified && MessageBox.Show(this, + $"\"{document.Session.Title}\" has changes that were not saved to the client or exported.\r\nClose it anyway?", + "Multi Editor", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) + { + return; + } + + int index = _documents.IndexOf(document); + if (_active == document) + { + Detach(); + } + + _documents.RemoveAt(index); + _removingTab = true; + try + { + _docTabs.TabPages.RemoveAt(index); + } + finally + { + _removingTab = false; + } + + Activate(_docTabs.SelectedIndex); + } + + private void DocTabs_MouseUp(object sender, MouseEventArgs e) + { + // Middle click closes a tab, like a browser. + if (e.Button != MouseButtons.Middle) + { + return; + } + + int index = TabAt(e.Location); + if (index >= 0) + { + CloseDocument(_documents[index]); + } + } + + // ---------------------------------------------------------------- tab close buttons + + /// Tab whose close button is under the mouse, or -1. + private int _hotCloseTab = -1; + + /// Set while a tab is removed, so the selection that follows is never cancelled. + private bool _removingTab; + + private int CloseGlyphSize => LogicalToDeviceUnits(14); + + private int TabAt(Point location) + { + for (int i = 0; i < _docTabs.TabCount; i++) + { + if (_docTabs.GetTabRect(i).Contains(location)) + { + return i; + } + } + + return -1; + } + + /// The close button of a tab: a square at the right end of its header. + private Rectangle CloseRect(Rectangle tab) + { + int size = CloseGlyphSize; + return new Rectangle(tab.Right - size - LogicalToDeviceUnits(4), tab.Top + ((tab.Height - size) / 2), size, size); + } + + private int CloseButtonAt(Point location) + { + int index = TabAt(location); + return index >= 0 && CloseRect(_docTabs.GetTabRect(index)).Contains(location) ? index : -1; + } + + private void DocTabs_DrawItem(object sender, DrawItemEventArgs e) + { + if (e.Index < 0 || e.Index >= _docTabs.TabCount) + { + return; + } + + bool selected = e.Index == _docTabs.SelectedIndex; + Rectangle bounds = e.Bounds; + using (var back = new SolidBrush(_docTabs.TabBackColor(selected))) + { + e.Graphics.FillRectangle(back, bounds); + } + + Rectangle close = CloseRect(bounds); + int inset = LogicalToDeviceUnits(6); + var textBounds = new Rectangle(bounds.Left + inset, bounds.Top, close.Left - bounds.Left - inset, bounds.Height); + TextRenderer.DrawText(e.Graphics, _docTabs.TabPages[e.Index].Text, _docTabs.Font, textBounds, + _docTabs.TabTextColor(selected), + // NoPadding: the tab's width was measured from the bare text. + TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | + TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding); + + bool hot = e.Index == _hotCloseTab; + if (hot) + { + using var hotBack = new SolidBrush(Color.FromArgb(232, 17, 35)); + e.Graphics.FillRectangle(hotBack, close); + } + + // The cross, a little inside the button. + int pad = LogicalToDeviceUnits(4); + Color crossColor = hot ? Color.White : _docTabs.GlyphColor(selected); + using var pen = new Pen(crossColor, Math.Max(1f, LogicalToDeviceUnits(1) * 1.4f)); + System.Drawing.Drawing2D.SmoothingMode previous = e.Graphics.SmoothingMode; + e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; + e.Graphics.DrawLine(pen, close.Left + pad, close.Top + pad, close.Right - pad - 1, close.Bottom - pad - 1); + e.Graphics.DrawLine(pen, close.Right - pad - 1, close.Top + pad, close.Left + pad, close.Bottom - pad - 1); + e.Graphics.SmoothingMode = previous; + } + + private void DocTabs_Selecting(object sender, TabControlCancelEventArgs e) + { + // A press on another tab's close button closes it without switching to it first. + if (!_removingTab && (MouseButtons & MouseButtons.Left) != 0 && CloseButtonAt(_docTabs.PointToClient(MousePosition)) >= 0) + { + e.Cancel = true; + } + } + + private void DocTabs_MouseDown(object sender, MouseEventArgs e) + { + if (e.Button != MouseButtons.Left) + { + return; + } + + int index = CloseButtonAt(e.Location); + if (index >= 0) + { + SetHotCloseTab(-1); + CloseDocument(_documents[index]); + } + } + + private void DocTabs_MouseMove(object sender, MouseEventArgs e) + { + SetHotCloseTab(CloseButtonAt(e.Location)); + } + + private void DocTabs_MouseLeave(object sender, EventArgs e) + { + SetHotCloseTab(-1); + } + + private void SetHotCloseTab(int index) + { + if (index == _hotCloseTab) + { + return; + } + + InvalidateTab(_hotCloseTab); + _hotCloseTab = index; + InvalidateTab(_hotCloseTab); + } + + private void InvalidateTab(int index) + { + if (index >= 0 && index < _docTabs.TabCount) + { + _docTabs.Invalidate(_docTabs.GetTabRect(index)); + } + } + + private void Detach() + { + if (_active == null) + { + return; + } + + EditorSession session = _active.Session; + session.CancelTool(); + session.DocumentChanged -= OnDocumentChanged; + session.SelectionChanged -= OnSelectionChanged; + session.HoverChanged -= UpdateStatus; + session.CursorCellChanged -= UpdateStatus; + session.ToolChanged -= OnToolChanged; + session.DrawTileChanged -= OnDrawTileChanged; + session.ViewChanged -= OnViewChanged; + session.TileUsed -= _browser.RecordRecent; + _active = null; + } + + private void Activate(int index) + { + EditorDocument document = index >= 0 && index < _documents.Count ? _documents[index] : null; + if (document == _active && document != null) + { + return; + } + + Detach(); + _active = document; + _emptyHint.Visible = document == null; + _docTabs.Visible = _documents.Count > 0; + + if (document == null) + { + _canvas.Show(null, null); + _inspector.Bind(null); + } + else + { + EditorSession session = document.Session; + session.DocumentChanged += OnDocumentChanged; + session.SelectionChanged += OnSelectionChanged; + session.HoverChanged += UpdateStatus; + session.CursorCellChanged += UpdateStatus; + session.ToolChanged += OnToolChanged; + session.DrawTileChanged += OnDrawTileChanged; + session.ViewChanged += OnViewChanged; + session.TileUsed += _browser.RecordRecent; + + _canvas.Show(session, document.Camera); + + _inspector.Bind(session); + if (session.DrawTileId != 0) + { + _browser.SetCurrentTile(session.DrawTileId); + } + } + + SyncOptions(); + UpdateTitle(); + UpdateStatus(); + UpdateZoomLabel(); + _commands.RefreshStates(); + } + + // ---------------------------------------------------------------- keeping the UI in line + + private void OnDocumentChanged() + { + SyncLevels(); + UpdateTitle(); + UpdateStatus(); + _commands.RefreshStates(); + } + + private void OnSelectionChanged() + { + UpdateStatus(); + _commands.RefreshStates(); + } + + private void OnToolChanged() + { + SyncOptions(); + UpdateStatus(); + _commands.RefreshStates(); + } + + private void OnDrawTileChanged() + { + _browser.SetCurrentTile(Session.DrawTileId); + SyncOptions(); + } + + private void OnViewChanged() + { + SyncLevels(); + _commands.RefreshStates(); + UpdateStatus(); + } + + /// + /// One button per floor in the options bar, the active one pressed. Every floor has a + /// button whether it holds tiles or not. + /// + private void SyncLevels() + { + var names = new List<(string Short, string Tip)> { ("All", "All floors (Ctrl+Home)") }; + if (Session != null) + { + names.AddRange(Session.Levels.Select(l => (l.ShortName, l.Description))); + } + + if (_floorButtons.Count != names.Count || !_floorButtons.Select(b => b.Text).SequenceEqual(names.Select(n => n.Short))) + { + foreach (ToolStripButton old in _floorButtons) + { + _optionsStrip.Items.Remove(old); + old.Dispose(); + } + + _floorButtons.Clear(); + int at = _optionsStrip.Items.IndexOf(_floorLabel) + 1; + for (int i = 0; i < names.Count; i++) + { + int index = i; + var button = new ToolStripButton(names[i].Short) + { + DisplayStyle = ToolStripItemDisplayStyle.Text, + ToolTipText = names[i].Tip, + AutoToolTip = false, + AutoSize = false, + Width = names[i].Short.Length > 2 ? 40 : 26, + Margin = new Padding(1, 1, 0, 2) + }; + button.Click += (_, _) => + { + if (Session != null) + { + Session.LevelIndex = index; + _canvas.Focus(); + } + }; + _floorButtons.Add(button); + _optionsStrip.Items.Insert(at + i, button); + } + } + + int active = Session?.LevelIndex ?? 0; + for (int i = 0; i < _floorButtons.Count; i++) + { + _floorButtons[i].Checked = i == active; + _floorButtons[i].Enabled = Session != null; + _floorButtons[i].ToolTipText = i < names.Count ? names[i].Tip : string.Empty; + } + } + + private void SyncOptions() + { + SyncLevels(); + SyncRoofOptions(); + _syncing = true; + try + { + EditorSession session = Session; + bool has = session != null; + _zStepCombo.Enabled = has; + if (!has) + { + _toolLabel.Text = string.Empty; + _drawTileLabel.Text = string.Empty; + return; + } + + _toolLabel.Text = session.Pasting ? "Paste" : _toolCommands[session.Tool].Text; + int zIndex = _zStepCombo.IndexOf(session.ZStep.ToString()); + _zStepCombo.SelectedIndex = Math.Max(0, zIndex); + + if (session.Tool == ToolKind.FloorPattern) + { + _drawTileLabel.Text = session.FloorPattern != null ? $"Pattern: {session.FloorPattern.Name}" : "Pattern: pick one in the House page"; + } + else if (IsHouseTool(session.Tool) && session.Tool != ToolKind.Foundation) + { + _drawTileLabel.Text = session.HouseStyle != null ? $"Style: {session.HouseStyle.Name}" : "Style: pick one in the House page"; + } + else if (session.Tool == ToolKind.Foundation) + { + _drawTileLabel.Text = "Foundation"; + } + else + { + ushort id = session.DrawTileId; + _drawTileLabel.Text = id == 0 ? "Tile: pick one in the tile browser" : $"Tile: 0x{id:X4} {TileName(id)}"; + } + } + finally + { + _syncing = false; + } + } + + private static string TileName(ushort id) + { + return id < TileData.ItemTable.Length ? TileData.ItemTable[id].Name : string.Empty; + } + + private void UpdateTitle() + { + for (int i = 0; i < _documents.Count; i++) + { + EditorSession session = _documents[i].Session; + string text = session.Title + (session.Modified ? " *" : string.Empty); + if (_docTabs.TabPages[i].Text != text) + { + _docTabs.TabPages[i].Text = text; + } + } + } + + private void UpdateZoomLabel() + { + if (_zoomLabel != null) + { + _zoomLabel.Text = $"{_canvas.Camera.Zoom * 100:0}%"; + } + } + + private void UpdateStatus() + { + EditorSession session = Session; + if (session == null) + { + _statusHint.Text = string.Empty; + _statusCell.Text = _statusPlane.Text = _statusHover.Text = _statusSelection.Text = _statusSize.Text = string.Empty; + return; + } + + _statusHint.Text = session.PreviewMode ? "Preview: editing is off. Right click picks the ground. F5 returns to the editor." + : session.Pasting ? "Click to place the tiles. Esc or right click cancels." + : ToolHint(session.Tool); + + (int x, int y, int z) = session.CursorCell; + _statusCell.Text = session.MouseInside && session.CompList.InBounds(x, y) ? $"Cell {x}, {y}, Z {z}" : string.Empty; + int offset = session.WorkPlaneOffset; + _statusPlane.Text = $"Work plane Z {session.WorkPlaneZ}" + (offset != 0 ? $" (floor {offset:+0;-0})" : string.Empty) + + (session.ShowWorkPlane ? string.Empty : " (hidden)"); + + MultiTile hover = session.HoverTile; + _statusHover.Text = hover != null ? $"0x{hover.Id:X4} {TileName(hover.Id)} Z {hover.Z} H {hover.Height}" : string.Empty; + + int count = session.Selection.Count; + _statusSelection.Text = count == 0 ? string.Empty : $"{count} selected"; + _statusSize.Text = $"{session.CompList.Width} x {session.CompList.Height}, {session.CompList.TileCount} tiles"; + } + + private static string ToolHint(ToolKind kind) + { + return kind switch + { + ToolKind.Select => "Click a tile to select, Ctrl+click adds, drag a box over tiles, drag the selection to move it.", + ToolKind.Lasso => "Draw an outline around tiles to select them. Ctrl adds to the selection.", + ToolKind.Draw => "Click or drag to place the chosen tile. Placement mode (M) decides the Z.", + ToolKind.Remove => "Click a tile to remove it, drag to remove an area.", + ToolKind.Altitude => "Click raises the tile by the Z step, Shift+click lowers it.", + ToolKind.Pipette => "Click a tile to draw with it.", + ToolKind.Transparent => "Click a tile to see through it, click again to restore.", + ToolKind.RectFill => "Drag a rectangle to fill with the chosen tile.", + ToolKind.Line => "Drag a line of the chosen tile.", + ToolKind.Wall => "Drag along the cells to build walls in the chosen style. Corners and posts are picked for you.", + ToolKind.Floor => "Drag an area to lay the chosen floor style.", + ToolKind.Door => "Click a wall cell to hang the chosen door.", + ToolKind.Stair => "Drag in the direction the stairs climb.", + ToolKind.Roof => "Click a walled room to roof it, or drag over the wall cells to size the roof by hand. Options: Ridge, Gables, Fill.", + ToolKind.Foundation => "Drag an area to lay a foundation under it.", + ToolKind.FloorPattern => "Drag an area to lay the bordered floor: corners, sides and fill repeat to fit.", + _ => string.Empty + }; + } + + // ---------------------------------------------------------------- keyboard + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (!_built || (keyData != Keys.Escape && IsTextInputFocused())) + { + return base.ProcessCmdKey(ref msg, keyData); + } + + if (_commands.TryRun(keyData)) + { + _commands.RefreshStates(); + return true; + } + + EditorSession session = Session; + if (session == null) + { + return base.ProcessCmdKey(ref msg, keyData); + } + + // Arrows move the selection one cell; without a selection, or with Ctrl, they pan. + (int dx, int dy) = (keyData & Keys.KeyCode) switch + { + Keys.Left => (-1, 0), + Keys.Right => (1, 0), + Keys.Up => (0, -1), + Keys.Down => (0, 1), + _ => (0, 0) + }; + + Keys modifiers = keyData & Keys.Modifiers; + if ((dx, dy) == (0, 0) || (modifiers != Keys.None && modifiers != Keys.Control)) + { + return base.ProcessCmdKey(ref msg, keyData); + } + + if (modifiers == Keys.None && session.Selection.Count > 0) + { + session.NudgeSelection(dx, dy, 0); + } + else + { + _canvas.Camera.Pan(-dx * 44, -dy * 44); + _canvas.Invalidate(); + } + + return true; + } + + /// True while typing in a text, number or combo box, where letters must not switch tools. + private bool IsTextInputFocused() + { + Control focused = this; + while (focused is ContainerControl container && container.ActiveControl != null) + { + focused = container.ActiveControl; + } + + return focused is TextBoxBase || focused is NumericUpDown || focused is ComboBox || + focused.Parent is NumericUpDown || focused is ToolStrip; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.resx b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.resx similarity index 99% rename from UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.resx rename to UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.resx index 4edf53f8..8b2ff64a 100644 --- a/UoFiddler.Plugin.MultiEditor/Forms/ShortcutsHelpForm.resx +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.resx @@ -1,4 +1,4 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.Designer.cs new file mode 100644 index 00000000..22dd677b --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.Designer.cs @@ -0,0 +1,75 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class NumbersPromptForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + _okButton = new System.Windows.Forms.Button(); + _cancelButton = new System.Windows.Forms.Button(); + SuspendLayout(); + // + // _okButton + // + _okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + _okButton.Location = new System.Drawing.Point(84, 16); + _okButton.Name = "_okButton"; + _okButton.Size = new System.Drawing.Size(76, 23); + _okButton.TabIndex = 0; + _okButton.Text = "OK"; + // + // _cancelButton + // + _cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + _cancelButton.Location = new System.Drawing.Point(168, 16); + _cancelButton.Name = "_cancelButton"; + _cancelButton.Size = new System.Drawing.Size(76, 23); + _cancelButton.TabIndex = 1; + _cancelButton.Text = "Cancel"; + // + // NumbersPromptForm + // + AcceptButton = _okButton; + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + CancelButton = _cancelButton; + ClientSize = new System.Drawing.Size(260, 68); + Controls.Add(_okButton); + Controls.Add(_cancelButton); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "NumbersPromptForm"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.Button _okButton; + private System.Windows.Forms.Button _cancelButton; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.cs b/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.cs new file mode 100644 index 00000000..8a9e12ec --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.cs @@ -0,0 +1,67 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Asks for whole numbers, one labelled box per field. Shown through . + /// The rows depend on the question, so they are added here; the form and its buttons are + /// laid out for no rows and move down by one row height per field. + /// + internal partial class NumbersPromptForm : Form + { + private const int _rowHeight = 32; + + private NumericUpDown[] _boxes = Array.Empty(); + + public NumbersPromptForm() + { + InitializeComponent(); + } + + public NumbersPromptForm(string title, (string Label, int Value, int Min, int Max)[] fields) + : this() + { + Text = title; + + SuspendLayout(); + int rows = fields.Length; + ClientSize = new Size(ClientSize.Width, ClientSize.Height + (rows * _rowHeight)); + _boxes = new NumericUpDown[rows]; + for (int i = 0; i < rows; i++) + { + Controls.Add(new Label { Text = fields[i].Label, Left = 12, Top = 16 + (i * _rowHeight), Width = 120, TabIndex = i * 2 }); + _boxes[i] = new NumericUpDown + { + Left = 140, + Top = 13 + (i * _rowHeight), + Width = 100, + Minimum = fields[i].Min, + Maximum = fields[i].Max, + Value = Math.Clamp(fields[i].Value, fields[i].Min, fields[i].Max), + TabIndex = (i * 2) + 1 + }; + Controls.Add(_boxes[i]); + } + + _okButton.Top += rows * _rowHeight; + _cancelButton.Top += rows * _rowHeight; + _okButton.TabIndex = rows * 2; + _cancelButton.TabIndex = (rows * 2) + 1; + ResumeLayout(false); + } + + /// The numbers as entered, in field order. + public int[] Values => Array.ConvertAll(_boxes, b => (int)b.Value); + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.resx b/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.resx new file mode 100644 index 00000000..8b2ff64a --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/NumbersPromptForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/PerformancePanel.cs b/UoFiddler.Plugin.MultiEditor/UI/PerformancePanel.cs new file mode 100644 index 00000000..603fc0a7 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/PerformancePanel.cs @@ -0,0 +1,187 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using UoFiddler.Controls.Classes; +using UoFiddler.Plugin.MultiEditor.Rendering; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The performance box over the canvas: the last second's timings as text, and a line chart of + /// frame, GPU, draw and lag times over the last seconds. + /// + internal sealed class PerformancePanel : Control + { + // Colours for the application's light or dark mode, chosen once (the mode is set at startup). + private readonly Color _back; + private readonly Color _text; + private readonly Color _axis; + private readonly (string Name, Color Color, Func Value)[] _series; + + private readonly Timer _timer = new Timer { Interval = 250 }; + private FrameStats _stats; + private Func _tiles; + private string _summary = string.Empty; + + public PerformancePanel() + { + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | + ControlStyles.ResizeRedraw, true); + SetStyle(ControlStyles.Selectable, false); + + bool dark = Options.DarkMode; + _back = dark ? Color.FromArgb(24, 24, 28) : Color.FromArgb(248, 248, 250); + _text = dark ? Color.FromArgb(220, 220, 220) : Color.FromArgb(30, 30, 30); + _axis = dark ? Color.FromArgb(70, 70, 78) : Color.FromArgb(165, 165, 172); + _series = new (string, Color, Func)[] + { + ("Frame", dark ? Color.WhiteSmoke : Color.FromArgb(40, 40, 40), p => p.Frame), + ("GPU", dark ? Color.Orange : Color.DarkOrange, p => p.Gpu), + ("Draw", dark ? Color.DeepSkyBlue : Color.RoyalBlue, p => p.Draw), + ("Lag", dark ? Color.HotPink : Color.MediumVioletRed, p => p.Lag) + }; + + Font = new Font(FontFamily.GenericMonospace, 8.25f); + BackColor = _back; + ForeColor = _text; + _timer.Tick += (_, _) => UpdateNumbers(); + } + + /// Where the numbers come from, and the tile count of the open design. + public void Bind(FrameStats stats, Func tiles) + { + _stats = stats; + _tiles = tiles; + UpdateNumbers(); + } + + /// Reads the numbers again and repaints; the box sizes itself to the text. + public void UpdateNumbers() + { + _summary = _stats?.Describe(_tiles?.Invoke() ?? 0) ?? string.Empty; + Size text = TextRenderer.MeasureText(_summary, Font); + int width = Math.Max(text.Width, LogicalToDeviceUnits(400)) + LogicalToDeviceUnits(16); + int height = text.Height + LogicalToDeviceUnits(16 + 130); + if (Width != width || Height != height) + { + Size = new Size(width, height); + } + + Invalidate(); + } + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + _timer.Enabled = Visible; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _timer.Dispose(); + } + + base.Dispose(disposing); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + g.Clear(_back); + int pad = LogicalToDeviceUnits(8); + TextRenderer.DrawText(g, _summary, Font, new Point(pad, pad), _text, TextFormatFlags.NoPrefix); + Size text = TextRenderer.MeasureText(_summary, Font); + + var chart = new Rectangle(pad + LogicalToDeviceUnits(34), pad + text.Height + LogicalToDeviceUnits(8), + Width - (pad * 2) - LogicalToDeviceUnits(34), Height - text.Height - (pad * 2) - LogicalToDeviceUnits(30)); + if (chart.Width <= 10 || chart.Height <= 10 || _stats == null) + { + return; + } + + IReadOnlyList history = _stats.History; + + // Scale to the largest value shown, at least one 60 Hz frame, in whole 5 ms steps. + double max = 16.7; + foreach (FrameStats.Point p in history) + { + foreach ((_, _, Func value) in _series) + { + max = Math.Max(max, value(p)); + } + } + + max = Math.Ceiling(max / 5) * 5; + float Y(double ms) => chart.Bottom - (float)(Math.Min(ms, max) / max * chart.Height); + float X(int index) => chart.Left + (index * chart.Width / (float)(FrameStats.HistorySeconds - 1)); + + using (var axis = new Pen(_axis)) + { + g.DrawRectangle(axis, chart); + + // The frame budgets of 120 Hz and 60 Hz displays, labelled on the axis. + axis.DashStyle = DashStyle.Dash; + foreach (double budget in new[] { 1000 / 120.0, 1000 / 60.0 }) + { + g.DrawLine(axis, chart.Left, Y(budget), chart.Right, Y(budget)); + TextRenderer.DrawText(g, $"{budget:F1}", Font, new Point(pad, (int)Y(budget) - LogicalToDeviceUnits(6)), _axis, TextFormatFlags.NoPrefix); + } + } + + TextRenderer.DrawText(g, $"{max:F0}", Font, new Point(pad, chart.Top - LogicalToDeviceUnits(4)), _axis, TextFormatFlags.NoPrefix); + TextRenderer.DrawText(g, "0 ms", Font, new Point(pad, chart.Bottom - LogicalToDeviceUnits(10)), _axis, TextFormatFlags.NoPrefix); + + // Newest on the right; a shorter history starts part way in. + int offset = FrameStats.HistorySeconds - history.Count; + g.SmoothingMode = SmoothingMode.AntiAlias; + foreach ((_, Color color, Func value) in _series) + { + if (history.Count < 2) + { + break; + } + + var points = new PointF[history.Count]; + for (int i = 0; i < history.Count; i++) + { + points[i] = new PointF(X(offset + i), Y(value(history[i]))); + } + + using var pen = new Pen(color, LogicalToDeviceUnits(1) * 1.3f); + g.DrawLines(pen, points); + } + + g.SmoothingMode = SmoothingMode.None; + + // Legend under the chart. + int x = chart.Left; + int y = chart.Bottom + LogicalToDeviceUnits(6); + foreach ((string name, Color color, _) in _series) + { + using (var brush = new SolidBrush(color)) + { + g.FillRectangle(brush, x, y + LogicalToDeviceUnits(5), LogicalToDeviceUnits(10), LogicalToDeviceUnits(3)); + } + + x += LogicalToDeviceUnits(14); + TextRenderer.DrawText(g, name, Font, new Point(x, y), _text, TextFormatFlags.NoPrefix); + x += TextRenderer.MeasureText(name, Font).Width + LogicalToDeviceUnits(8); + } + + TextRenderer.DrawText(g, $"last {FrameStats.HistorySeconds} s", Font, new Point(x, y), _axis, TextFormatFlags.NoPrefix); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.Designer.cs new file mode 100644 index 00000000..8a61c57e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.Designer.cs @@ -0,0 +1,76 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class ShortcutsForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + _list = new System.Windows.Forms.ListView(); + _commandColumn = new System.Windows.Forms.ColumnHeader(); + _keysColumn = new System.Windows.Forms.ColumnHeader(); + SuspendLayout(); + // + // _list + // + _list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { _commandColumn, _keysColumn }); + _list.Dock = System.Windows.Forms.DockStyle.Fill; + _list.FullRowSelect = true; + _list.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + _list.Location = new System.Drawing.Point(0, 0); + _list.Name = "_list"; + _list.Size = new System.Drawing.Size(520, 620); + _list.TabIndex = 0; + _list.View = System.Windows.Forms.View.Details; + // + // _commandColumn + // + _commandColumn.Text = "Command"; + _commandColumn.Width = 330; + // + // _keysColumn + // + _keysColumn.Text = "Keys"; + _keysColumn.Width = 160; + // + // ShortcutsForm + // + ClientSize = new System.Drawing.Size(520, 620); + Controls.Add(_list); + MinimizeBox = false; + Name = "ShortcutsForm"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Multi Editor shortcuts"; + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.ListView _list; + private System.Windows.Forms.ColumnHeader _commandColumn; + private System.Windows.Forms.ColumnHeader _keysColumn; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs new file mode 100644 index 00000000..3960d916 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs @@ -0,0 +1,87 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The list of keyboard shortcuts and mouse actions (F1). The rows come from the editor's + /// command registry, so the list always matches the keys that work. + /// + internal partial class ShortcutsForm : Form + { + private Font _headingFont; + + public ShortcutsForm() + { + InitializeComponent(); + Disposed += ShortcutsForm_Disposed; + } + + /// Fills the list: every command with a key, grouped, then the mouse actions. + public void ShowCommands(IEnumerable commands) + { + _headingFont ??= new Font(_list.Font, FontStyle.Bold); + + foreach (IGrouping group in commands.Where(c => c.Shortcut != Keys.None).GroupBy(c => c.Group)) + { + Heading(group.Key); + foreach (EditorCommand command in group) + { + Row(command.Text, command.ShortcutText); + } + } + + Heading("Mouse"); + foreach ((string what, string how) in new[] + { + ("Pan", "Right or middle drag, Space + drag"), + ("Zoom at the cursor", "Wheel"), + ("Step through the floors", "Shift + wheel"), + ("Context menu, or cancel a drag or paste", "Right click"), + ("Select the tile under the cursor (any tool)", "Middle click"), + ("Move the selection one cell", "Arrow keys"), + ("Pan one cell", "Ctrl + arrow keys") + }) + { + Row(what, how); + } + } + + /// + /// Section headings are ordinary bold rows in the list's own text colour. ListView groups + /// draw their titles in a fixed system blue, which cannot be read on a dark theme. + /// + private void Heading(string text) + { + if (_list.Items.Count > 0) + { + _list.Items.Add(new ListViewItem(string.Empty)); + } + + _list.Items.Add(new ListViewItem(text) { Font = _headingFont }); + } + + private void Row(string what, string how) + { + _list.Items.Add(new ListViewItem(new[] { " " + what, how })); + } + + private void ShortcutsForm_Disposed(object sender, EventArgs e) + { + _headingFont?.Dispose(); + _headingFont = null; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.resx b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.resx new file mode 100644 index 00000000..8b2ff64a --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.Designer.cs new file mode 100644 index 00000000..d012ed86 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.Designer.cs @@ -0,0 +1,96 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class TextPromptForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + _label = new System.Windows.Forms.Label(); + _valueBox = new System.Windows.Forms.TextBox(); + _okButton = new System.Windows.Forms.Button(); + _cancelButton = new System.Windows.Forms.Button(); + SuspendLayout(); + // + // _label + // + _label.Location = new System.Drawing.Point(12, 12); + _label.Name = "_label"; + _label.Size = new System.Drawing.Size(296, 23); + _label.TabIndex = 0; + // + // _valueBox + // + _valueBox.Location = new System.Drawing.Point(12, 36); + _valueBox.Name = "_valueBox"; + _valueBox.Size = new System.Drawing.Size(296, 23); + _valueBox.TabIndex = 1; + // + // _okButton + // + _okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + _okButton.Location = new System.Drawing.Point(144, 70); + _okButton.Name = "_okButton"; + _okButton.Size = new System.Drawing.Size(76, 23); + _okButton.TabIndex = 2; + _okButton.Text = "OK"; + // + // _cancelButton + // + _cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + _cancelButton.Location = new System.Drawing.Point(228, 70); + _cancelButton.Name = "_cancelButton"; + _cancelButton.Size = new System.Drawing.Size(76, 23); + _cancelButton.TabIndex = 3; + _cancelButton.Text = "Cancel"; + // + // TextPromptForm + // + AcceptButton = _okButton; + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + CancelButton = _cancelButton; + ClientSize = new System.Drawing.Size(320, 112); + Controls.Add(_label); + Controls.Add(_valueBox); + Controls.Add(_okButton); + Controls.Add(_cancelButton); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "TextPromptForm"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label _label; + private System.Windows.Forms.TextBox _valueBox; + private System.Windows.Forms.Button _okButton; + private System.Windows.Forms.Button _cancelButton; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.cs b/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.cs new file mode 100644 index 00000000..47e785fb --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.cs @@ -0,0 +1,33 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// Asks for one line of text. Shown through . + internal partial class TextPromptForm : Form + { + public TextPromptForm() + { + InitializeComponent(); + } + + public TextPromptForm(string title, string label, string value) + : this() + { + Text = title; + _label.Text = label; + _valueBox.Text = value; + } + + /// The text as typed. + public string Value => _valueBox.Text; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.resx b/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.resx new file mode 100644 index 00000000..8b2ff64a --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TextPromptForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserCatalog.cs b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserCatalog.cs new file mode 100644 index 00000000..9f4fa78e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserCatalog.cs @@ -0,0 +1,284 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Xml; +using Ultima; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// A node of the multieditor.xml tree: a group (union of its subgroups) or a subgroup. + internal sealed class TileBrowserCategory + { + public TileBrowserCategory(string name, TileBrowserCategory parent) + { + Name = name; + Parent = parent; + } + + public string Name { get; } + + public TileBrowserCategory Parent { get; } + + public List Children { get; } = new List(); + + public List Tiles { get; } = new List(); + + public string Path => Parent == null ? Name : Parent.Path + " / " + Name; + + public override string ToString() => Name; + } + + /// + /// The tile categories of multieditor.xml plus every valid static, read without throwing: + /// a missing or broken file leaves the tree empty. + /// + internal sealed class TileBrowserCatalog + { + private List _allTiles; + private Dictionary _firstCategory; + + private TileBrowserCatalog() + { + } + + public static string FilePath => System.IO.Path.Combine(Options.AppDataPath ?? string.Empty, "plugins", "multieditor.xml"); + + public List Groups { get; } = new List(); + + /// Why the file could not be read, or null. + public string Error { get; private set; } + + /// Every valid static, built on first use so it reflects the art loaded then. + public IReadOnlyList AllTiles + { + get + { + if (_allTiles == null) + { + int maxItemId = Art.GetMaxItemId(); + _allTiles = new List(maxItemId + 1); + for (int i = 0; i <= maxItemId; ++i) + { + if (Art.IsValidStatic(i)) + { + _allTiles.Add(i); + } + } + } + + return _allTiles; + } + } + + public static TileBrowserCatalog Load() + { + var catalog = new TileBrowserCatalog(); + string fileName = FilePath; + try + { + if (!File.Exists(fileName)) + { + return catalog; + } + + var dom = new XmlDocument(); + dom.Load(fileName); + XmlElement root = dom["TileGroups"]; + if (root == null) + { + return catalog; + } + + foreach (XmlElement xGroup in root.ChildNodes.OfType()) + { + var group = new TileBrowserCategory(xGroup.GetAttribute("name"), null); + var seen = new HashSet(); + foreach (XmlElement xSub in xGroup.ChildNodes.OfType()) + { + if (xSub.Name != "subgroup") + { + continue; + } + + var sub = new TileBrowserCategory(xSub.GetAttribute("name"), group); + foreach (XmlElement xEntry in xSub.ChildNodes.OfType()) + { + if (int.TryParse(xEntry.GetAttribute("index"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) && + Art.IsValidStatic(id)) + { + sub.Tiles.Add(id); + if (seen.Add(id)) + { + group.Tiles.Add(id); + } + } + } + + group.Children.Add(sub); + } + + catalog.Groups.Add(group); + } + } + catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException) + { + catalog.Groups.Clear(); + catalog.Error = ex.Message; + } + + return catalog; + } + + /// The first subgroup that lists the tile, or null. + public TileBrowserCategory FindCategoryOf(int id) + { + if (_firstCategory == null) + { + _firstCategory = new Dictionary(); + foreach (TileBrowserCategory sub in Groups.SelectMany(g => g.Children)) + { + foreach (int tile in sub.Tiles) + { + _firstCategory.TryAdd(tile, sub); + } + } + } + + return _firstCategory.TryGetValue(id, out TileBrowserCategory category) ? category : null; + } + } + + /// + /// What the search box asks for: either ids (decimal, 0x or $ hex, ranges like 0x100-0x1FF, + /// several separated by spaces or commas) or name words that must all occur. + /// + internal sealed class TileBrowserQuery + { + private static readonly char[] _separators = { ' ', ',', ';', '\t' }; + + private readonly List<(int Low, int High)> _ranges; + private readonly string[] _words; + + private TileBrowserQuery(List<(int, int)> ranges, string[] words) + { + _ranges = ranges; + _words = words; + } + + public bool IsIdQuery => _ranges != null; + + /// The query, or null when the text is blank. + public static TileBrowserQuery Parse(string text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + + string[] tokens = text.Split(_separators, StringSplitOptions.RemoveEmptyEntries); + var ranges = new List<(int, int)>(); + foreach (string token in tokens) + { + if (!TryParseRange(token, out int low, out int high)) + { + ranges = null; + break; + } + + ranges.Add((low, high)); + } + + return ranges != null ? new TileBrowserQuery(ranges, null) : new TileBrowserQuery(null, tokens); + } + + public bool MatchesId(int id) + { + if (_ranges == null) + { + return false; + } + + foreach ((int low, int high) in _ranges) + { + if (id >= low && id <= high) + { + return true; + } + } + + return false; + } + + /// True when every word occurs in the text (ignoring case). Id queries match no text. + public bool MatchesText(string text) + { + if (_words == null || string.IsNullOrEmpty(text)) + { + return false; + } + + foreach (string word in _words) + { + if (text.IndexOf(word, StringComparison.OrdinalIgnoreCase) < 0) + { + return false; + } + } + + return true; + } + + public bool MatchesTile(int id) => IsIdQuery ? MatchesId(id) : MatchesText(TileBrowserThumbnails.NameOf(id)); + + private static bool TryParseRange(string token, out int low, out int high) + { + int dash = token.IndexOf('-', 1); + if (dash > 0 && dash < token.Length - 1) + { + if (TryParseId(token[..dash], out low) && TryParseId(token[(dash + 1)..], out high)) + { + if (low > high) + { + (low, high) = (high, low); + } + + return true; + } + + high = 0; + return false; + } + + bool ok = TryParseId(token, out low); + high = low; + return ok; + } + + private static bool TryParseId(string text, out int id) + { + if (text.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { + return int.TryParse(text.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + } + + if (text.StartsWith('$')) + { + return int.TryParse(text.AsSpan(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + } + + return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out id); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserGrid.cs b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserGrid.cs new file mode 100644 index 00000000..91f9da04 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserGrid.cs @@ -0,0 +1,745 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +using Ultima; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// A virtualised, owner-drawn grid of tile thumbnails. Only visible cells are painted, and + /// mouse moves repaint just the two cells whose hover state changed. Drawing and hit-testing + /// share /, so they use the same pitch. + /// + internal sealed class TileBrowserGrid : Control + { + public const int MinCellSize = 32; + public const int MaxCellSize = 128; + private const int _padding = 3; + private const int _captionHeight = 12; + private const int _tipMaxArt = 220; + private const int _wmContextMenu = 0x007B; + + private readonly VScrollBar _scroll; + private readonly TileBrowserThumbnails _thumbnails; + private readonly ToolTip _toolTip; + private readonly Timer _tipTimer; + private readonly Font _captionFont; + private readonly SolidBrush _currentBrush; + private readonly SolidBrush _hoverBrush; + private readonly Pen _currentPen; + private readonly Pen _gridPen; + + private IReadOnlyList _items = Array.Empty(); + private int _cellSize = 56; + private int _hoverIndex = -1; + private int _focusIndex = -1; + private int _currentId = -1; + private int _currentIndex = -1; + private int _wheelRemainder; + private int _layoutColumns = 1; + private bool _showIds; + private int _tipId = -1; + private string _tipText; + + public TileBrowserGrid(TileBrowserThumbnails thumbnails) + { + _thumbnails = thumbnails; + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | + ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); + DoubleBuffered = true; + TabStop = true; + BackColor = SystemColors.Window; + + _scroll = new VScrollBar { Dock = DockStyle.Right, Visible = false, TabStop = false }; + _scroll.ValueChanged += (_, _) => OnScrolled(); + Controls.Add(_scroll); + + _toolTip = new ToolTip { OwnerDraw = true, UseAnimation = false, UseFading = false }; + _toolTip.Popup += ToolTip_Popup; + _toolTip.Draw += ToolTip_Draw; + _tipTimer = new Timer { Interval = 450 }; + _tipTimer.Tick += TipTimer_Tick; + + _captionFont = new Font(Font.FontFamily, 7f); + _currentBrush = new SolidBrush(Color.FromArgb(90, SystemColors.Highlight)); + _hoverBrush = new SolidBrush(Color.FromArgb(40, SystemColors.Highlight)); + _currentPen = new Pen(SystemColors.Highlight, 2f) { Alignment = System.Drawing.Drawing2D.PenAlignment.Inset }; + _gridPen = new Pen(SystemColors.ControlLight); + } + + /// A tile was clicked or Enter was pressed on it. + public event Action TileActivated; + + /// Right-click or the menu key on a tile; the location is in grid client coordinates. + public event Action TileContextMenuRequested; + + /// Ctrl+wheel changed the cell size, so the owner can resize its other grids. + public event Action CellSizeChanged; + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int CellSize + { + get => _cellSize; + set + { + int size = Math.Clamp(value, MinCellSize, MaxCellSize); + if (size == _cellSize) + { + return; + } + + int first = FirstVisibleIndex(); + _cellSize = size; + UpdateScrollRange(); + ScrollToIndexRow(first); + Invalidate(); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool ShowIds + { + get => _showIds; + set + { + if (_showIds != value) + { + _showIds = value; + Invalidate(); + } + } + } + + /// Tiles to flag with a corner mark (favorites). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Func IsMarked { get; set; } + + /// Shown when the list is empty. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string EmptyText { get; set; } = "No tiles"; + + public int Count => _items.Count; + + public IReadOnlyList Items => _items; + + /// The tile highlighted as the current draw tile, or -1. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int CurrentId + { + get => _currentId; + set + { + if (value == _currentId) + { + return; + } + + InvalidateCell(_currentIndex); + _currentId = value; + _currentIndex = IndexOf(value); + InvalidateCell(_currentIndex); + } + } + + /// The tile under the keyboard cursor, or -1. + public int FocusedId => _focusIndex >= 0 && _focusIndex < _items.Count ? _items[_focusIndex] : -1; + + public void SetItems(IReadOnlyList items, bool keepScroll = false) + { + int focusedId = FocusedId; + _items = items ?? Array.Empty(); + _currentIndex = IndexOf(_currentId); + _focusIndex = IndexOf(focusedId); + _hoverIndex = -1; + HideTip(); + int top = keepScroll ? ScrollTop : 0; + UpdateScrollRange(); + SetScrollTop(top); + Invalidate(); + } + + /// Scrolls to the tile and puts the keyboard cursor on it. False when it is not listed. + public bool ScrollToId(int id) + { + int index = IndexOf(id); + if (index < 0) + { + return false; + } + + MoveFocus(index); + return true; + } + + /// Puts the keyboard cursor on the first tile when none is set (for Down from the search box). + public void FocusFirst() + { + if (_focusIndex < 0 && _items.Count > 0) + { + MoveFocus(_currentIndex >= 0 ? _currentIndex : 0); + } + } + + public int IndexOf(int id) + { + if (id < 0) + { + return -1; + } + + for (int i = 0; i < _items.Count; i++) + { + if (_items[i] == id) + { + return i; + } + } + + return -1; + } + + // ---------------------------------------------------------------- layout + + private int ContentWidth => Math.Max(0, ClientSize.Width - (_scroll.Visible ? _scroll.Width : 0)); + + private int Columns => Math.Max(1, ContentWidth / _cellSize); + + private int RowCount => (_items.Count + Columns - 1) / Columns; + + private int ScrollTop => _scroll.Visible ? _scroll.Value : 0; + + private int MaxScrollTop => Math.Max(0, (RowCount * _cellSize) - ClientSize.Height); + + public Rectangle CellBounds(int index) + { + int columns = Columns; + return new Rectangle(index % columns * _cellSize, (index / columns * _cellSize) - ScrollTop, _cellSize, _cellSize); + } + + /// The list index under a client point, or -1. + public int HitTest(Point p) + { + int columns = Columns; + if (p.X < 0 || p.Y < 0 || p.X >= columns * _cellSize || p.X >= ContentWidth || p.Y >= ClientSize.Height) + { + return -1; + } + + int index = ((p.Y + ScrollTop) / _cellSize * columns) + (p.X / _cellSize); + return index < _items.Count ? index : -1; + } + + private void UpdateScrollRange() + { + if (ClientSize.Height <= 0) + { + return; + } + + // Columns depend on whether the bar is shown, so decide with the full width first. + int fullColumns = Math.Max(1, ClientSize.Width / _cellSize); + bool needed = (_items.Count + fullColumns - 1) / fullColumns * _cellSize > ClientSize.Height; + if (_scroll.Visible != needed) + { + _scroll.Visible = needed; + } + + _layoutColumns = Columns; + int total = RowCount * _cellSize; + int top = Math.Min(_scroll.Value, MaxScrollTop); + _scroll.Minimum = 0; + _scroll.Maximum = Math.Max(0, total - 1); + _scroll.LargeChange = Math.Max(1, ClientSize.Height); + _scroll.SmallChange = _cellSize; + _scroll.Value = Math.Max(0, top); + } + + private void SetScrollTop(int top) + { + if (!_scroll.Visible) + { + return; + } + + top = Math.Clamp(top, 0, MaxScrollTop); + if (_scroll.Value != top) + { + _scroll.Value = top; + } + } + + private int FirstVisibleIndex() => ScrollTop / _cellSize * Columns; + + private void ScrollToIndexRow(int index) + { + if (index >= 0) + { + SetScrollTop(index / Columns * _cellSize); + } + } + + private void EnsureVisible(int index) + { + if (index < 0) + { + return; + } + + int rowTop = index / Columns * _cellSize; + if (rowTop < ScrollTop) + { + SetScrollTop(rowTop); + } + else if (rowTop + _cellSize > ScrollTop + ClientSize.Height) + { + SetScrollTop(rowTop + _cellSize - ClientSize.Height); + } + } + + protected override void OnResize(EventArgs e) + { + // Keeps the first visible row's tiles in view when the column count changes. + int first = ScrollTop / _cellSize * _layoutColumns; + base.OnResize(e); + UpdateScrollRange(); + ScrollToIndexRow(first); + } + + private void OnScrolled() + { + HideTip(); + Invalidate(); + // The content moved under a resting mouse. + UpdateHover(PointToClient(MousePosition)); + } + + // ---------------------------------------------------------------- painting + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + Rectangle clip = e.ClipRectangle; + using (var background = new SolidBrush(BackColor)) + { + g.FillRectangle(background, clip); + } + + if (_items.Count == 0) + { + TextRenderer.DrawText(g, EmptyText, Font, new Rectangle(0, 0, ContentWidth, Math.Min(ClientSize.Height, 60)), + SystemColors.GrayText, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak); + return; + } + + int columns = Columns; + int top = ScrollTop; + int firstRow = Math.Max(0, (clip.Top + top) / _cellSize); + int lastRow = Math.Min(RowCount - 1, (clip.Bottom - 1 + top) / _cellSize); + int firstCol = Math.Max(0, clip.Left / _cellSize); + int lastCol = Math.Min(columns - 1, (clip.Right - 1) / _cellSize); + + for (int row = firstRow; row <= lastRow; row++) + { + for (int col = firstCol; col <= lastCol; col++) + { + int index = (row * columns) + col; + if (index >= _items.Count) + { + break; + } + + DrawCell(g, index, new Rectangle(col * _cellSize, (row * _cellSize) - top, _cellSize, _cellSize)); + } + } + } + + private void DrawCell(Graphics g, int index, Rectangle cell) + { + int id = _items[index]; + if (index == _currentIndex) + { + g.FillRectangle(_currentBrush, cell); + } + else if (index == _hoverIndex) + { + g.FillRectangle(_hoverBrush, cell); + } + + g.DrawLine(_gridPen, cell.Right - 1, cell.Top, cell.Right - 1, cell.Bottom - 1); + g.DrawLine(_gridPen, cell.Left, cell.Bottom - 1, cell.Right - 1, cell.Bottom - 1); + + int caption = _showIds ? _captionHeight : 0; + var box = new Rectangle(cell.X + _padding, cell.Y + _padding, cell.Width - (2 * _padding) - 1, cell.Height - (2 * _padding) - 1 - caption); + Bitmap thumb = box.Width > 0 && box.Height > 0 ? _thumbnails.Get(id, Math.Min(box.Width, box.Height)) : null; + if (thumb != null) + { + // Bottom-centred, the way the tile stands on the ground. + g.DrawImageUnscaled(thumb, box.X + ((box.Width - thumb.Width) / 2), box.Bottom - thumb.Height); + } + else + { + TextRenderer.DrawText(g, "?", Font, box, SystemColors.GrayText, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); + } + + if (caption > 0) + { + var captionBounds = new Rectangle(cell.X, box.Bottom, cell.Width - 1, caption + _padding); + TextRenderer.DrawText(g, $"{id:X4}", _captionFont, captionBounds, SystemColors.GrayText, + TextFormatFlags.HorizontalCenter | TextFormatFlags.Top | TextFormatFlags.NoPadding); + } + + if (IsMarked?.Invoke(id) == true) + { + Point[] corner = + { + new Point(cell.Right - 10, cell.Top), + new Point(cell.Right - 1, cell.Top), + new Point(cell.Right - 1, cell.Top + 9) + }; + g.FillPolygon(Brushes.Goldenrod, corner); + } + + if (index == _currentIndex) + { + g.DrawRectangle(_currentPen, cell.X, cell.Y, cell.Width - 1, cell.Height - 1); + } + + if (index == _focusIndex && Focused && ShowFocusCues) + { + ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(cell, -2, -2)); + } + } + + private void InvalidateCell(int index) + { + if (index >= 0 && index < _items.Count) + { + Invalidate(CellBounds(index)); + } + } + + // ---------------------------------------------------------------- mouse + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + UpdateHover(e.Location); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + SetHover(-1); + } + + private void UpdateHover(Point p) => SetHover(ClientRectangle.Contains(p) ? HitTest(p) : -1); + + private void SetHover(int index) + { + if (index == _hoverIndex) + { + return; + } + + InvalidateCell(_hoverIndex); + _hoverIndex = index; + InvalidateCell(_hoverIndex); + + HideTip(); + if (index >= 0) + { + _tipTimer.Start(); + } + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + HideTip(); + Focus(); + + int index = HitTest(e.Location); + if (index < 0) + { + return; + } + + if (e.Button == MouseButtons.Left) + { + MoveFocus(index); + TileActivated?.Invoke(this, _items[index]); + } + else if (e.Button == MouseButtons.Right) + { + MoveFocus(index); + } + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); + if (e is HandledMouseEventArgs handled) + { + handled.Handled = true; + } + + HideTip(); + _wheelRemainder += e.Delta; + int notches = _wheelRemainder / 120; + if (notches == 0) + { + return; + } + + _wheelRemainder -= notches * 120; + if ((ModifierKeys & Keys.Control) != 0) + { + int size = Math.Clamp(_cellSize + (notches * 8), MinCellSize, MaxCellSize); + if (size != _cellSize) + { + CellSize = size; + CellSizeChanged?.Invoke(size); + } + + return; + } + + int lines = SystemInformation.MouseWheelScrollLines; + int rowsPerNotch = lines <= 0 ? Math.Max(1, ClientSize.Height / _cellSize) : Math.Clamp(lines, 1, 3); + SetScrollTop(ScrollTop - (notches * rowsPerNotch * _cellSize)); + } + + protected override void WndProc(ref Message m) + { + if (m.Msg == _wmContextMenu) + { + long lParam = m.LParam.ToInt64(); + if (lParam == -1) + { + // Menu key or Shift+F10: the menu belongs to the keyboard cursor. + if (_focusIndex >= 0 && _focusIndex < _items.Count) + { + EnsureVisible(_focusIndex); + Rectangle bounds = CellBounds(_focusIndex); + TileContextMenuRequested?.Invoke(this, _items[_focusIndex], new Point(bounds.Left + (bounds.Width / 2), bounds.Bottom)); + } + } + else + { + Point p = PointToClient(new Point(unchecked((short)lParam), unchecked((short)(lParam >> 16)))); + int index = HitTest(p); + if (index >= 0) + { + TileContextMenuRequested?.Invoke(this, _items[index], p); + } + } + + return; + } + + base.WndProc(ref m); + } + + // ---------------------------------------------------------------- keyboard + + protected override bool IsInputKey(Keys keyData) + { + switch (keyData & Keys.KeyCode) + { + case Keys.Up: + case Keys.Down: + case Keys.Left: + case Keys.Right: + case Keys.Home: + case Keys.End: + case Keys.PageUp: + case Keys.PageDown: + case Keys.Enter: + return true; + default: + return base.IsInputKey(keyData); + } + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.Handled || _items.Count == 0) + { + return; + } + + int columns = Columns; + int pageRows = Math.Max(1, ClientSize.Height / _cellSize); + int from = _focusIndex >= 0 ? _focusIndex : Math.Max(0, _currentIndex); + int to; + switch (e.KeyCode) + { + case Keys.Left: + to = from - 1; + break; + case Keys.Right: + to = from + 1; + break; + case Keys.Up: + to = from - columns; + break; + case Keys.Down: + to = from + columns; + break; + case Keys.PageUp: + to = from - (pageRows * columns); + break; + case Keys.PageDown: + to = from + (pageRows * columns); + break; + case Keys.Home: + to = 0; + break; + case Keys.End: + to = _items.Count - 1; + break; + case Keys.Enter: + if (_focusIndex < 0) + { + MoveFocus(from); + } + + TileActivated?.Invoke(this, _items[_focusIndex]); + e.Handled = true; + e.SuppressKeyPress = true; + return; + default: + return; + } + + // A first key press only shows where the cursor is. + MoveFocus(_focusIndex < 0 ? from : Math.Clamp(to, 0, _items.Count - 1)); + e.Handled = true; + } + + private void MoveFocus(int index) + { + if (index < 0 || index >= _items.Count) + { + return; + } + + InvalidateCell(_focusIndex); + _focusIndex = index; + EnsureVisible(index); + InvalidateCell(_focusIndex); + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + InvalidateCell(_focusIndex); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + InvalidateCell(_focusIndex); + } + + // ---------------------------------------------------------------- tooltip with the full-size art + + private void TipTimer_Tick(object sender, EventArgs e) + { + _tipTimer.Stop(); + if (_hoverIndex < 0 || _hoverIndex >= _items.Count || !IsHandleCreated) + { + return; + } + + _tipId = _items[_hoverIndex]; + _tipText = TileBrowserThumbnails.Describe(_tipId); + Rectangle bounds = CellBounds(_hoverIndex); + _toolTip.Show(_tipText, this, bounds.Left, bounds.Bottom + 2, 10000); + } + + private void HideTip() + { + _tipTimer.Stop(); + if (_tipId >= 0) + { + _tipId = -1; + _toolTip.Hide(this); + } + } + + private static Size TipArtSize(Bitmap art) + { + if (art == null) + { + return Size.Empty; + } + + float scale = Math.Min(1f, Math.Min((float)_tipMaxArt / art.Width, (float)_tipMaxArt / art.Height)); + return new Size(Math.Max(1, (int)(art.Width * scale)), Math.Max(1, (int)(art.Height * scale))); + } + + private void ToolTip_Popup(object sender, PopupEventArgs e) + { + Size art = _tipId >= 0 ? TipArtSize(Art.GetStatic(_tipId)) : Size.Empty; + Size text = TextRenderer.MeasureText(_tipText ?? string.Empty, Font); + int width = Math.Max(art.Width, text.Width) + 12; + int height = (art.Height > 0 ? art.Height + 6 : 0) + text.Height + 10; + e.ToolTipSize = new Size(width, height); + } + + private void ToolTip_Draw(object sender, DrawToolTipEventArgs e) + { + Graphics g = e.Graphics; + g.FillRectangle(SystemBrushes.Info, e.Bounds); + g.DrawRectangle(SystemPens.InfoText, e.Bounds.X, e.Bounds.Y, e.Bounds.Width - 1, e.Bounds.Height - 1); + + int y = e.Bounds.Top + 5; + Bitmap art = _tipId >= 0 ? Art.GetStatic(_tipId) : null; + if (art != null) + { + Size size = TipArtSize(art); + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.DrawImage(art, new Rectangle(e.Bounds.Left + ((e.Bounds.Width - size.Width) / 2), y, size.Width, size.Height)); + y += size.Height + 6; + } + + TextRenderer.DrawText(g, _tipText ?? string.Empty, Font, + new Rectangle(e.Bounds.Left + 6, y, e.Bounds.Width - 12, e.Bounds.Bottom - y), SystemColors.InfoText, + TextFormatFlags.Left | TextFormatFlags.Top); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _tipTimer.Dispose(); + _toolTip.Dispose(); + _captionFont.Dispose(); + _currentBrush.Dispose(); + _hoverBrush.Dispose(); + _currentPen.Dispose(); + _gridPen.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserHouseGallery.cs b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserHouseGallery.cs new file mode 100644 index 00000000..ffd4bc62 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserHouseGallery.cs @@ -0,0 +1,408 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// One style in the gallery, with the piece that stands for it. + /// An item that is not a house style (a floor pattern) carries its object in Tag and has no Style. + internal sealed record HouseGalleryItem(HouseStyle Style, string Label, int IconId, object Tag = null); + + /// A titled run of styles, e.g. one wall material. + internal sealed record HouseGallerySection(string Title, IReadOnlyList Items); + + /// + /// House styles as pictures: sections with a heading, each style a cell showing one of its + /// pieces over its name. Only the visible cells are painted. + /// + internal sealed class TileBrowserHouseGallery : Control + { + private const int _cellWidth = 84; + private const int _imageHeight = 50; + private const int _textHeight = 28; + private const int _cellHeight = _imageHeight + _textHeight + 6; + private const int _headerHeight = 22; + + /// Where one thing is drawn: a section heading (Item null) or a style cell. + private readonly record struct Slot(Rectangle Bounds, string Header, HouseGalleryItem Item); + + private readonly VScrollBar _scroll; + private readonly ToolTip _toolTip = new ToolTip(); + private readonly List _slots = new List(); + private IReadOnlyList _sections = Array.Empty(); + private HouseStyle _selected; + private object _selectedTag; + private int _hover = -1; + private int _contentHeight; + + public TileBrowserHouseGallery() + { + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | + ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); + BackColor = SystemColors.Window; + _scroll = new VScrollBar { Dock = DockStyle.Right, SmallChange = 32 }; + _scroll.ValueChanged += (_, _) => Invalidate(); + Controls.Add(_scroll); + } + + /// A style was clicked or chosen with Enter (also when it already was the selected one). + public event Action StyleChosen; + + /// An item with a Tag was clicked or chosen with Enter. + public event Action TagChosen; + + /// The selected tagged item, when the gallery shows those. + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public object SelectedTag + { + get => _selectedTag; + set + { + _selectedTag = value; + Invalidate(); + } + } + + private bool IsSelected(HouseGalleryItem item) + { + return item.Tag != null ? item.Tag == _selectedTag : item.Style != null && item.Style == _selected; + } + + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string EmptyText { get; set; } = "No styles"; + + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public HouseStyle Selected + { + get => _selected; + set + { + _selected = value; + Invalidate(); + } + } + + public int Count { get; private set; } + + public void SetSections(IReadOnlyList sections) + { + _sections = sections ?? Array.Empty(); + _hover = -1; + _scroll.Value = 0; + Relayout(); + } + + /// The first style shown, or null. + public HouseStyle First() + { + foreach (Slot slot in _slots) + { + if (slot.Item != null) + { + return slot.Item.Style; + } + } + + return null; + } + + public void ScrollToSelected() + { + foreach (Slot slot in _slots) + { + if (slot.Item != null && IsSelected(slot.Item)) + { + int view = ClientSize.Height; + if (slot.Bounds.Top < _scroll.Value || slot.Bounds.Bottom > _scroll.Value + view) + { + SetScroll(slot.Bounds.Top - _headerHeight); + } + + return; + } + } + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + Relayout(); + } + + private void Relayout() + { + _slots.Clear(); + Count = 0; + int width = Math.Max(_cellWidth, ClientSize.Width - _scroll.Width); + int columns = Math.Max(1, width / _cellWidth); + + // Cells share the spare width, so the row always fills the panel. + int cell = width / columns; + int y = 2; + foreach (HouseGallerySection section in _sections) + { + if (section.Items.Count == 0) + { + continue; + } + + if (!string.IsNullOrEmpty(section.Title)) + { + _slots.Add(new Slot(new Rectangle(0, y, width, _headerHeight), section.Title, null)); + y += _headerHeight; + } + + for (int i = 0; i < section.Items.Count; i++) + { + int column = i % columns; + int row = i / columns; + _slots.Add(new Slot(new Rectangle(column * cell, y + (row * _cellHeight), cell, _cellHeight), null, section.Items[i])); + Count++; + } + + y += (((section.Items.Count - 1) / columns) + 1) * _cellHeight; + y += 4; + } + + _contentHeight = y; + int view = Math.Max(1, ClientSize.Height); + _scroll.Enabled = _contentHeight > view; + _scroll.Maximum = Math.Max(0, _contentHeight - 1); + _scroll.LargeChange = view; + SetScroll(_scroll.Value); + Invalidate(); + } + + private void SetScroll(int value) + { + int max = Math.Max(0, _contentHeight - Math.Max(1, ClientSize.Height)); + _scroll.Value = Math.Clamp(value, 0, max); + } + + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + g.Clear(BackColor); + if (Count == 0) + { + TextRenderer.DrawText(g, EmptyText, Font, ClientRectangle, SystemColors.GrayText, + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak); + return; + } + + int top = _scroll.Value; + int bottom = top + ClientSize.Height; + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + using var headerFont = new Font(Font, FontStyle.Bold); + + for (int i = 0; i < _slots.Count; i++) + { + Slot slot = _slots[i]; + if (slot.Bounds.Bottom < top || slot.Bounds.Top > bottom) + { + continue; + } + + Rectangle bounds = slot.Bounds; + bounds.Offset(0, -top); + if (slot.Item == null) + { + TextRenderer.DrawText(g, slot.Header, headerFont, new Rectangle(bounds.X + 4, bounds.Y, bounds.Width - 8, bounds.Height), + SystemColors.GrayText, TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); + using var line = new Pen(SystemColors.ControlLight); + g.DrawLine(line, bounds.X + 4, bounds.Bottom - 2, bounds.Right - 4, bounds.Bottom - 2); + continue; + } + + bool selected = IsSelected(slot.Item); + Rectangle inner = Rectangle.Inflate(bounds, -2, -2); + if (selected) + { + using var fill = new SolidBrush(Color.FromArgb(70, SystemColors.Highlight)); + g.FillRectangle(fill, inner); + using var border = new Pen(SystemColors.Highlight, 2); + g.DrawRectangle(border, inner); + } + else if (i == _hover) + { + using var fill = new SolidBrush(Color.FromArgb(35, SystemColors.Highlight)); + g.FillRectangle(fill, inner); + } + + DrawArt(g, slot.Item.IconId, new Rectangle(bounds.X + 4, bounds.Y + 4, bounds.Width - 8, _imageHeight)); + TextRenderer.DrawText(g, slot.Item.Label, Font, + new Rectangle(bounds.X + 2, bounds.Y + _imageHeight + 4, bounds.Width - 4, _textHeight), ForeColor, + TextFormatFlags.HorizontalCenter | TextFormatFlags.Top | TextFormatFlags.WordBreak | TextFormatFlags.EndEllipsis); + } + } + + /// The art bottom-centred in the box, scaled down when too large, never up. + private static void DrawArt(Graphics g, int id, Rectangle box) + { + Bitmap art = id > 0 ? Art.GetStatic(id) : null; + if (art == null) + { + return; + } + + float scale = Math.Min(1f, Math.Min((float)box.Width / art.Width, (float)box.Height / art.Height)); + int width = Math.Max(1, (int)(art.Width * scale)); + int height = Math.Max(1, (int)(art.Height * scale)); + g.DrawImage(art, box.X + ((box.Width - width) / 2), box.Bottom - height, width, height); + } + + private int HitTest(Point point) + { + int y = point.Y + _scroll.Value; + for (int i = 0; i < _slots.Count; i++) + { + Slot slot = _slots[i]; + if (slot.Item != null && slot.Bounds.Contains(point.X, y)) + { + return i; + } + } + + return -1; + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + int hover = HitTest(e.Location); + if (hover == _hover) + { + return; + } + + _hover = hover; + Invalidate(); + if (hover >= 0) + { + HouseGalleryItem item = _slots[hover].Item; + _toolTip.SetToolTip(this, item.Style != null + ? $"{item.Style.Name}\n{item.Style.Group}\n{item.Style.Slots.Count} pieces" + : item.Label); + } + else + { + _toolTip.SetToolTip(this, string.Empty); + } + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + if (_hover != -1) + { + _hover = -1; + Invalidate(); + } + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + Focus(); + int index = HitTest(e.Location); + if (e.Button == MouseButtons.Left && index >= 0) + { + Choose(_slots[index].Item); + } + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + base.OnMouseWheel(e); + SetScroll(_scroll.Value - (Math.Sign(e.Delta) * _cellHeight)); + } + + protected override bool IsInputKey(Keys keyData) + { + return (keyData & Keys.KeyCode) is Keys.Left or Keys.Right or Keys.Up or Keys.Down || base.IsInputKey(keyData); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + + // The styles in reading order; arrows walk them, a row at a time for up and down. + var cells = new List(); + for (int i = 0; i < _slots.Count; i++) + { + if (_slots[i].Item != null) + { + cells.Add(i); + } + } + + if (cells.Count == 0) + { + return; + } + + int current = cells.FindIndex(i => IsSelected(_slots[i].Item)); + int columns = Math.Max(1, Math.Max(_cellWidth, ClientSize.Width - _scroll.Width) / _cellWidth); + int next = e.KeyCode switch + { + Keys.Right => current + 1, + Keys.Left => current - 1, + Keys.Down => current + columns, + Keys.Up => current - columns, + Keys.Home => 0, + Keys.End => cells.Count - 1, + Keys.Enter => current, + _ => int.MinValue + }; + + if (next == int.MinValue) + { + return; + } + + e.Handled = true; + next = Math.Clamp(next, 0, cells.Count - 1); + Choose(_slots[cells[next]].Item); + ScrollToSelected(); + } + + private void Choose(HouseGalleryItem item) + { + if (item.Tag != null) + { + _selectedTag = item.Tag; + Invalidate(); + TagChosen?.Invoke(item.Tag); + return; + } + + _selected = item.Style; + Invalidate(); + StyleChosen?.Invoke(item.Style); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _toolTip.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.Designer.cs new file mode 100644 index 00000000..c067bf5f --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.Designer.cs @@ -0,0 +1,539 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class TileBrowserPanel + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 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)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + _filterBar = new System.Windows.Forms.TableLayoutPanel(); + _searchBox = new System.Windows.Forms.TextBox(); + _typeFilter = new System.Windows.Forms.ComboBox(); + _status = new System.Windows.Forms.Label(); + _tabs = new System.Windows.Forms.TabControl(); + _tilesPage = new System.Windows.Forms.TabPage(); + _tilesSplit = new System.Windows.Forms.SplitContainer(); + _categoryTree = new System.Windows.Forms.TreeView(); + _favoritesPage = new System.Windows.Forms.TabPage(); + _favoritesBar = new System.Windows.Forms.ToolStrip(); + _favoritePageBox = new System.Windows.Forms.ToolStripComboBox(); + _addFavoriteButton = new System.Windows.Forms.ToolStripButton(); + _removeFavoriteButton = new System.Windows.Forms.ToolStripButton(); + _favoritePageMenu = new System.Windows.Forms.ToolStripDropDownButton(); + _newFavoritePageItem = new System.Windows.Forms.ToolStripMenuItem(); + _renamePageItem = new System.Windows.Forms.ToolStripMenuItem(); + _deletePageItem = new System.Windows.Forms.ToolStripMenuItem(); + _favoritePageMenuSeparator = new System.Windows.Forms.ToolStripSeparator(); + _importUoheItem = new System.Windows.Forms.ToolStripMenuItem(); + _recentPage = new System.Windows.Forms.TabPage(); + _recentBar = new System.Windows.Forms.ToolStrip(); + _clearRecentButton = new System.Windows.Forms.ToolStripButton(); + _housePage = new System.Windows.Forms.TabPage(); + _houseGallery = new TileBrowserHouseGallery(); + _piecesSplitter = new GripSplitter(); + _swapButton = new System.Windows.Forms.Button(); + _houseHint = new System.Windows.Forms.Label(); + _houseKindBar = new System.Windows.Forms.ToolStrip(); + _foundationButton = new System.Windows.Forms.ToolStripButton(); + _patternsButton = new System.Windows.Forms.ToolStripButton(); + _prefabsPage = new System.Windows.Forms.TabPage(); + _prefabList = new System.Windows.Forms.ListView(); + _prefabIcons = new System.Windows.Forms.ImageList(components); + _prefabGroupBar = new System.Windows.Forms.ToolStrip(); + _designsPage = new System.Windows.Forms.TabPage(); + _designLibrary = new DesignLibraryPanel(); + _toolTip = new System.Windows.Forms.ToolTip(components); + _searchTimer = new System.Windows.Forms.Timer(components); + _tileMenu = new System.Windows.Forms.ContextMenuStrip(components); + _prefabMenu = new System.Windows.Forms.ContextMenuStrip(components); + _filterBar.SuspendLayout(); + _tabs.SuspendLayout(); + _tilesPage.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_tilesSplit).BeginInit(); + _tilesSplit.Panel1.SuspendLayout(); + _tilesSplit.SuspendLayout(); + _favoritesPage.SuspendLayout(); + _favoritesBar.SuspendLayout(); + _recentPage.SuspendLayout(); + _recentBar.SuspendLayout(); + _housePage.SuspendLayout(); + _houseKindBar.SuspendLayout(); + _prefabsPage.SuspendLayout(); + _designsPage.SuspendLayout(); + SuspendLayout(); + // + // _filterBar + // + _filterBar.AutoSize = true; + _filterBar.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; + _filterBar.ColumnCount = 1; + _filterBar.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + _filterBar.Controls.Add(_searchBox, 0, 0); + _filterBar.Controls.Add(_typeFilter, 0, 1); + _filterBar.Dock = System.Windows.Forms.DockStyle.Top; + _filterBar.Location = new System.Drawing.Point(0, 0); + _filterBar.Name = "_filterBar"; + _filterBar.Padding = new System.Windows.Forms.Padding(1); + _filterBar.RowCount = 2; + _filterBar.RowStyles.Add(new System.Windows.Forms.RowStyle()); + _filterBar.RowStyles.Add(new System.Windows.Forms.RowStyle()); + _filterBar.Size = new System.Drawing.Size(674, 52); + _filterBar.TabIndex = 2; + // + // _searchBox + // + _searchBox.Dock = System.Windows.Forms.DockStyle.Fill; + _searchBox.Location = new System.Drawing.Point(2, 2); + _searchBox.Margin = new System.Windows.Forms.Padding(1); + _searchBox.Name = "_searchBox"; + _searchBox.PlaceholderText = "Search name or id (0x1F4, 500, 0x100-0x1FF)"; + _searchBox.Size = new System.Drawing.Size(670, 23); + _searchBox.TabIndex = 0; + _toolTip.SetToolTip(_searchBox, "Type words of a tile name (all must match), or ids: decimal, 0x or $ hex, ranges like 0x100-0x1FF.\nEnter picks the first result, Down moves to the results, Esc clears."); + _searchBox.TextChanged += SearchBox_TextChanged; + _searchBox.KeyDown += SearchBox_KeyDown; + // + // _typeFilter + // + _typeFilter.Dock = System.Windows.Forms.DockStyle.Fill; + _typeFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _typeFilter.Location = new System.Drawing.Point(2, 27); + _typeFilter.Margin = new System.Windows.Forms.Padding(1); + _typeFilter.Name = "_typeFilter"; + _typeFilter.Size = new System.Drawing.Size(670, 23); + _typeFilter.TabIndex = 1; + _typeFilter.SelectedIndexChanged += TypeFilter_SelectedIndexChanged; + // + // _status + // + _status.AutoEllipsis = true; + _status.Dock = System.Windows.Forms.DockStyle.Bottom; + _status.Location = new System.Drawing.Point(0, 425); + _status.Name = "_status"; + _status.Padding = new System.Windows.Forms.Padding(2, 0, 2, 0); + _status.Size = new System.Drawing.Size(674, 20); + _status.TabIndex = 1; + _status.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // _tabs + // + _tabs.Controls.Add(_tilesPage); + _tabs.Controls.Add(_favoritesPage); + _tabs.Controls.Add(_recentPage); + _tabs.Controls.Add(_housePage); + _tabs.Controls.Add(_prefabsPage); + _tabs.Controls.Add(_designsPage); + _tabs.Dock = System.Windows.Forms.DockStyle.Fill; + _tabs.Location = new System.Drawing.Point(0, 52); + _tabs.Multiline = true; + _tabs.Name = "_tabs"; + _tabs.SelectedIndex = 0; + _tabs.Size = new System.Drawing.Size(674, 373); + _tabs.TabIndex = 0; + _tabs.SelectedIndexChanged += Tabs_SelectedIndexChanged; + // + // _tilesPage + // + _tilesPage.Controls.Add(_tilesSplit); + _tilesPage.Location = new System.Drawing.Point(4, 24); + _tilesPage.Name = "_tilesPage"; + _tilesPage.Size = new System.Drawing.Size(666, 345); + _tilesPage.TabIndex = 0; + _tilesPage.Text = "Tiles"; + // + // _tilesSplit + // + _tilesSplit.Dock = System.Windows.Forms.DockStyle.Fill; + _tilesSplit.Location = new System.Drawing.Point(0, 0); + _tilesSplit.Name = "_tilesSplit"; + _tilesSplit.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // _tilesSplit.Panel1 + // + _tilesSplit.Panel1.Controls.Add(_categoryTree); + _tilesSplit.Panel1MinSize = 50; + _tilesSplit.Panel2MinSize = 80; + _tilesSplit.Size = new System.Drawing.Size(666, 345); + _tilesSplit.SplitterDistance = 172; + _tilesSplit.TabIndex = 0; + _tilesSplit.SizeChanged += TilesSplit_SizeChanged; + // + // _categoryTree + // + _categoryTree.Dock = System.Windows.Forms.DockStyle.Fill; + _categoryTree.HideSelection = false; + _categoryTree.Location = new System.Drawing.Point(0, 0); + _categoryTree.Name = "_categoryTree"; + _categoryTree.ShowNodeToolTips = true; + _categoryTree.Size = new System.Drawing.Size(666, 172); + _categoryTree.TabIndex = 0; + _categoryTree.AfterCollapse += CategoryTree_AfterCollapse; + _categoryTree.AfterExpand += CategoryTree_AfterExpand; + _categoryTree.AfterSelect += CategoryTree_AfterSelect; + // + // _favoritesPage + // + _favoritesPage.Controls.Add(_favoritesBar); + _favoritesPage.Location = new System.Drawing.Point(4, 44); + _favoritesPage.Name = "_favoritesPage"; + _favoritesPage.Size = new System.Drawing.Size(192, 52); + _favoritesPage.TabIndex = 1; + _favoritesPage.Text = "Favorites"; + // + // _favoritesBar + // + _favoritesBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _favoritesBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _favoritePageBox, _addFavoriteButton, _removeFavoriteButton, _favoritePageMenu }); + _favoritesBar.Location = new System.Drawing.Point(0, 0); + _favoritesBar.Name = "_favoritesBar"; + _favoritesBar.Size = new System.Drawing.Size(192, 25); + _favoritesBar.TabIndex = 1; + // + // _favoritePageBox + // + _favoritePageBox.AutoSize = false; + _favoritePageBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _favoritePageBox.Name = "_favoritePageBox"; + _favoritePageBox.Size = new System.Drawing.Size(130, 23); + _favoritePageBox.ToolTipText = "Favorites page"; + _favoritePageBox.SelectedIndexChanged += FavoritePageBox_SelectedIndexChanged; + // + // _addFavoriteButton + // + _addFavoriteButton.Name = "_addFavoriteButton"; + _addFavoriteButton.Size = new System.Drawing.Size(33, 22); + _addFavoriteButton.Text = "Add"; + _addFavoriteButton.ToolTipText = "Add the current draw tile to this page"; + _addFavoriteButton.Click += AddFavoriteButton_Click; + // + // _removeFavoriteButton + // + _removeFavoriteButton.Name = "_removeFavoriteButton"; + _removeFavoriteButton.Size = new System.Drawing.Size(54, 19); + _removeFavoriteButton.Text = "Remove"; + _removeFavoriteButton.ToolTipText = "Remove the current draw tile from this page (Delete removes the tile under the cursor)"; + _removeFavoriteButton.Click += RemoveFavoriteButton_Click; + // + // _favoritePageMenu + // + _favoritePageMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { _newFavoritePageItem, _renamePageItem, _deletePageItem, _favoritePageMenuSeparator, _importUoheItem }); + _favoritePageMenu.Name = "_favoritePageMenu"; + _favoritePageMenu.Size = new System.Drawing.Size(46, 19); + _favoritePageMenu.Text = "Page"; + _favoritePageMenu.DropDownOpening += FavoritePageMenu_DropDownOpening; + // + // _newFavoritePageItem + // + _newFavoritePageItem.Name = "_newFavoritePageItem"; + _newFavoritePageItem.Size = new System.Drawing.Size(216, 22); + _newFavoritePageItem.Text = "New page..."; + _newFavoritePageItem.Click += NewFavoritePageItem_Click; + // + // _renamePageItem + // + _renamePageItem.Name = "_renamePageItem"; + _renamePageItem.Size = new System.Drawing.Size(216, 22); + _renamePageItem.Text = "Rename page..."; + _renamePageItem.Click += RenamePageItem_Click; + // + // _deletePageItem + // + _deletePageItem.Name = "_deletePageItem"; + _deletePageItem.Size = new System.Drawing.Size(216, 22); + _deletePageItem.Text = "Delete page"; + _deletePageItem.Click += DeletePageItem_Click; + // + // _favoritePageMenuSeparator + // + _favoritePageMenuSeparator.Name = "_favoritePageMenuSeparator"; + _favoritePageMenuSeparator.Size = new System.Drawing.Size(213, 6); + // + // _importUoheItem + // + _importUoheItem.Name = "_importUoheItem"; + _importUoheItem.Size = new System.Drawing.Size(216, 22); + _importUoheItem.Text = "Import UOHE bookmarks..."; + _importUoheItem.Click += ImportUoheItem_Click; + // + // _recentPage + // + _recentPage.Controls.Add(_recentBar); + _recentPage.Location = new System.Drawing.Point(4, 44); + _recentPage.Name = "_recentPage"; + _recentPage.Size = new System.Drawing.Size(192, 52); + _recentPage.TabIndex = 2; + _recentPage.Text = "Recent"; + // + // _recentBar + // + _recentBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _recentBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _clearRecentButton }); + _recentBar.Location = new System.Drawing.Point(0, 0); + _recentBar.Name = "_recentBar"; + _recentBar.Size = new System.Drawing.Size(192, 25); + _recentBar.TabIndex = 1; + // + // _clearRecentButton + // + _clearRecentButton.Name = "_clearRecentButton"; + _clearRecentButton.Size = new System.Drawing.Size(38, 22); + _clearRecentButton.Text = "Clear"; + _clearRecentButton.ToolTipText = "Forget the recently used tiles"; + _clearRecentButton.Click += ClearRecentButton_Click; + // + // _housePage + // + _housePage.Controls.Add(_houseGallery); + _housePage.Controls.Add(_piecesSplitter); + _housePage.Controls.Add(_swapButton); + _housePage.Controls.Add(_houseHint); + _housePage.Controls.Add(_houseKindBar); + _housePage.Location = new System.Drawing.Point(4, 44); + _housePage.Name = "_housePage"; + _housePage.Size = new System.Drawing.Size(192, 52); + _housePage.TabIndex = 3; + _housePage.Text = "House"; + // + // _houseGallery + // + _houseGallery.BackColor = System.Drawing.SystemColors.Window; + _houseGallery.Dock = System.Windows.Forms.DockStyle.Fill; + _houseGallery.Location = new System.Drawing.Point(0, 22); + _houseGallery.Name = "_houseGallery"; + _houseGallery.Size = new System.Drawing.Size(192, 0); + _houseGallery.TabIndex = 0; + _houseGallery.StyleChosen += PickHouseStyle; + _houseGallery.TagChosen += HouseGallery_TagChosen; + // + // _piecesSplitter + // + _piecesSplitter.Dock = System.Windows.Forms.DockStyle.Bottom; + _piecesSplitter.Location = new System.Drawing.Point(0, -15); + _piecesSplitter.MinExtra = 120; + _piecesSplitter.MinSize = 80; + _piecesSplitter.Name = "_piecesSplitter"; + _piecesSplitter.Size = new System.Drawing.Size(192, 7); + _piecesSplitter.TabIndex = 1; + _piecesSplitter.TabStop = false; + _piecesSplitter.SplitterMoved += PiecesSplitter_SplitterMoved; + // + // _swapButton + // + _swapButton.Dock = System.Windows.Forms.DockStyle.Bottom; + _swapButton.Location = new System.Drawing.Point(0, -8); + _swapButton.Name = "_swapButton"; + _swapButton.Size = new System.Drawing.Size(192, 26); + _swapButton.TabIndex = 3; + _swapButton.Text = "Swap selection to this style"; + _toolTip.SetToolTip(_swapButton, "Changes the selected pieces of this kind to the matching pieces of the chosen style (Ctrl+R)"); + _swapButton.Click += SwapButton_Click; + // + // _houseHint + // + _houseHint.Dock = System.Windows.Forms.DockStyle.Bottom; + _houseHint.ForeColor = System.Drawing.SystemColors.GrayText; + _houseHint.Location = new System.Drawing.Point(0, 18); + _houseHint.Name = "_houseHint"; + _houseHint.Padding = new System.Windows.Forms.Padding(2, 2, 2, 0); + _houseHint.Size = new System.Drawing.Size(192, 34); + _houseHint.TabIndex = 4; + // + // _houseKindBar + // + _houseKindBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _houseKindBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _foundationButton, _patternsButton }); + _houseKindBar.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; + _houseKindBar.Location = new System.Drawing.Point(0, 0); + _houseKindBar.Name = "_houseKindBar"; + _houseKindBar.Size = new System.Drawing.Size(192, 22); + _houseKindBar.TabIndex = 5; + // + // _foundationButton + // + _foundationButton.Name = "_foundationButton"; + _foundationButton.Size = new System.Drawing.Size(72, 19); + _foundationButton.Text = "Foundation"; + _foundationButton.ToolTipText = "Drag the house area: a low wall around a dirt floor 7 above it."; + _foundationButton.Click += FoundationButton_Click; + // + // _patternsButton + // + _patternsButton.Name = "_patternsButton"; + _patternsButton.Size = new System.Drawing.Size(54, 19); + _patternsButton.Text = "Patterns"; + _patternsButton.ToolTipText = "Bordered floors: corner, side and fill pieces laid as one. Save your own from a selection (File menu)."; + _patternsButton.Click += PatternsButton_Click; + // + // _prefabsPage + // + _prefabsPage.Controls.Add(_prefabList); + _prefabsPage.Controls.Add(_prefabGroupBar); + _prefabsPage.Location = new System.Drawing.Point(4, 44); + _prefabsPage.Name = "_prefabsPage"; + _prefabsPage.Size = new System.Drawing.Size(192, 52); + _prefabsPage.TabIndex = 4; + _prefabsPage.Text = "Blueprints"; + // + // _prefabList + // + _prefabList.Dock = System.Windows.Forms.DockStyle.Fill; + _prefabList.LargeImageList = _prefabIcons; + _prefabList.Location = new System.Drawing.Point(0, 0); + _prefabList.MultiSelect = false; + _prefabList.Name = "_prefabList"; + _prefabList.ShowItemToolTips = true; + _prefabList.Size = new System.Drawing.Size(192, 52); + _prefabList.TabIndex = 0; + _prefabList.UseCompatibleStateImageBehavior = false; + _prefabList.KeyDown += PrefabList_KeyDown; + _prefabList.MouseClick += PrefabList_MouseClick; + // + // _prefabIcons + // + _prefabIcons.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; + _prefabIcons.ImageSize = new System.Drawing.Size(80, 80); + _prefabIcons.TransparentColor = System.Drawing.Color.Transparent; + // + // _prefabGroupBar + // + _prefabGroupBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _prefabGroupBar.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; + _prefabGroupBar.Location = new System.Drawing.Point(0, 0); + _prefabGroupBar.Name = "_prefabGroupBar"; + _prefabGroupBar.Size = new System.Drawing.Size(192, 0); + _prefabGroupBar.TabIndex = 1; + // + // _designsPage + // + _designsPage.Controls.Add(_designLibrary); + _designsPage.Location = new System.Drawing.Point(4, 44); + _designsPage.Name = "_designsPage"; + _designsPage.Size = new System.Drawing.Size(192, 52); + _designsPage.TabIndex = 5; + _designsPage.Text = "Designs"; + // + // _designLibrary + // + _designLibrary.Dock = System.Windows.Forms.DockStyle.Fill; + _designLibrary.Location = new System.Drawing.Point(0, 0); + _designLibrary.Name = "_designLibrary"; + _designLibrary.Size = new System.Drawing.Size(192, 52); + _designLibrary.TabIndex = 0; + _designLibrary.OpenRequested += DesignLibrary_OpenRequested; + _designLibrary.PlaceRequested += DesignLibrary_PlaceRequested; + // + // _searchTimer + // + _searchTimer.Interval = 150; + _searchTimer.Tick += SearchTimer_Tick; + // + // _tileMenu + // + _tileMenu.Name = "_tileMenu"; + _tileMenu.Size = new System.Drawing.Size(61, 4); + // + // _prefabMenu + // + _prefabMenu.Name = "_prefabMenu"; + _prefabMenu.Size = new System.Drawing.Size(61, 4); + // + // TileBrowserPanel + // + Controls.Add(_tabs); + Controls.Add(_status); + Controls.Add(_filterBar); + Name = "TileBrowserPanel"; + Size = new System.Drawing.Size(674, 445); + _filterBar.ResumeLayout(false); + _filterBar.PerformLayout(); + _tabs.ResumeLayout(false); + _tilesPage.ResumeLayout(false); + _tilesSplit.Panel1.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)_tilesSplit).EndInit(); + _tilesSplit.ResumeLayout(false); + _favoritesPage.ResumeLayout(false); + _favoritesPage.PerformLayout(); + _favoritesBar.ResumeLayout(false); + _favoritesBar.PerformLayout(); + _recentPage.ResumeLayout(false); + _recentPage.PerformLayout(); + _recentBar.ResumeLayout(false); + _recentBar.PerformLayout(); + _housePage.ResumeLayout(false); + _housePage.PerformLayout(); + _houseKindBar.ResumeLayout(false); + _houseKindBar.PerformLayout(); + _prefabsPage.ResumeLayout(false); + _prefabsPage.PerformLayout(); + _designsPage.ResumeLayout(false); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.TableLayoutPanel _filterBar; + private System.Windows.Forms.TextBox _searchBox; + private System.Windows.Forms.ComboBox _typeFilter; + private System.Windows.Forms.Label _status; + private System.Windows.Forms.TabControl _tabs; + private System.Windows.Forms.TabPage _tilesPage; + private System.Windows.Forms.SplitContainer _tilesSplit; + private System.Windows.Forms.TreeView _categoryTree; + private System.Windows.Forms.TabPage _favoritesPage; + private System.Windows.Forms.ToolStrip _favoritesBar; + private System.Windows.Forms.ToolStripComboBox _favoritePageBox; + private System.Windows.Forms.ToolStripButton _addFavoriteButton; + private System.Windows.Forms.ToolStripButton _removeFavoriteButton; + private System.Windows.Forms.ToolStripDropDownButton _favoritePageMenu; + private System.Windows.Forms.ToolStripMenuItem _newFavoritePageItem; + private System.Windows.Forms.ToolStripMenuItem _renamePageItem; + private System.Windows.Forms.ToolStripMenuItem _deletePageItem; + private System.Windows.Forms.ToolStripSeparator _favoritePageMenuSeparator; + private System.Windows.Forms.ToolStripMenuItem _importUoheItem; + private System.Windows.Forms.TabPage _recentPage; + private System.Windows.Forms.ToolStrip _recentBar; + private System.Windows.Forms.ToolStripButton _clearRecentButton; + private System.Windows.Forms.TabPage _housePage; + private TileBrowserHouseGallery _houseGallery; + private GripSplitter _piecesSplitter; + private System.Windows.Forms.Button _swapButton; + private System.Windows.Forms.Label _houseHint; + private System.Windows.Forms.ToolStrip _houseKindBar; + private System.Windows.Forms.ToolStripButton _foundationButton; + private System.Windows.Forms.ToolStripButton _patternsButton; + private System.Windows.Forms.TabPage _prefabsPage; + private System.Windows.Forms.ListView _prefabList; + private System.Windows.Forms.ImageList _prefabIcons; + private System.Windows.Forms.ToolStrip _prefabGroupBar; + private System.Windows.Forms.TabPage _designsPage; + private DesignLibraryPanel _designLibrary; + private System.Windows.Forms.ToolTip _toolTip; + private System.Windows.Forms.Timer _searchTimer; + private System.Windows.Forms.ContextMenuStrip _tileMenu; + private System.Windows.Forms.ContextMenuStrip _prefabMenu; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.cs b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.cs new file mode 100644 index 00000000..55a92787 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.cs @@ -0,0 +1,2071 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.Editing; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The editor's tile picker: one search box over pages of tiles (the multieditor.xml tree), + /// favorites, recently placed tiles, house part styles and prefabs. Data files are read on + /// first show, and a missing file only leaves its page empty. + /// + internal sealed partial class TileBrowserPanel : UserControl + { + private const string _messageTitle = "Multi Editor"; + + /// Tile type filter choices, tested on tiledata. + private static readonly (string Name, Func Matches)[] _tileTypes = + { + ("Type: all (pick to filter by tiledata flags)", _ => true), + ("Walls", d => (d.Flags & TileFlag.Wall) != 0), + ("Floors (flat surfaces)", d => (d.Flags & TileFlag.Surface) != 0 && d.Height == 0), + ("Roofs", d => (d.Flags & TileFlag.Roof) != 0), + ("Doors", d => (d.Flags & TileFlag.Door) != 0), + ("Windows", d => (d.Flags & TileFlag.Window) != 0), + ("Stairs", d => (d.Flags & (TileFlag.StairBack | TileFlag.StairRight)) != 0), + ("Foliage", d => (d.Flags & TileFlag.Foliage) != 0), + ("Light sources", d => (d.Flags & TileFlag.LightSource) != 0), + ("Containers", d => (d.Flags & TileFlag.Container) != 0), + ("Flat (height 0)", d => d.Height == 0), + ("Tall (height 15 or more)", d => d.Height >= 15) + }; + + private readonly TileBrowserThumbnails _thumbnails = new TileBrowserThumbnails(); + private readonly List _grids = new List(); + + // Tiles page + private readonly TileBrowserGrid _tilesGrid; + private readonly HashSet _expandedGroups = new HashSet(StringComparer.Ordinal); + private TileBrowserCatalog _catalog; + private TileBrowserCategory _category; + private TileBrowserCategory _categoryBeforeSearch; + private bool _categoryPickedDuringSearch; + private bool _suppressTreeEvents; + private bool _splitPlaced; + + // Recent page + private readonly TileBrowserGrid _recentGrid; + private List _recentTiles; + + private TileBrowserQuery _query; + private string _queryText = string.Empty; + private bool _suppressFilterEvents; + private int _currentTile = -1; + private bool _loaded; + private bool _firstFillDone; + + // Each page remembers the filter it was built for, so switching tabs keeps its scroll. + private int _filterVersion; + private int _tilesVersion = -1; + private int _favoritesVersion = -1; + private int _recentVersion = -1; + private int _houseVersion = -1; + private int _prefabsVersion = -1; + + /// + /// House styles are not passed here: they arrive through , + /// before or after the panel is first shown. + /// + public TileBrowserPanel() + { + InitializeComponent(); + + // The type filter choices come from the table above; filled quietly, as the + // selection is not a filter change. + _suppressFilterEvents = true; + try + { + foreach (var (name, _) in _tileTypes) + { + _typeFilter.Items.Add(name); + } + + _typeFilter.SelectedIndex = 0; + } + finally + { + _suppressFilterEvents = false; + } + + // The grids share the thumbnail cache, which the designer cannot pass to a constructor, + // so they are made here. Docking runs from the last added control (fill first, edges + // after), so each fill grid goes to the front of its page. + SplitterGrip.Attach(_tilesSplit); + _tilesGrid = CreateGrid("No tiles match."); + _tilesGrid.TabIndex = 0; + _tilesSplit.Panel2.Controls.Add(_tilesGrid); + + BuildFavoritesPage(); + + _recentGrid = CreateGrid("Tiles you place show up here."); + _recentGrid.TabIndex = 0; + _recentPage.Controls.Add(_recentGrid); + _recentGrid.BringToFront(); + + BuildHousePage(); + + Disposed += TileBrowserPanel_Disposed; + } + + /// The user picked a tile to draw with. + public event Action TileChosen; + + /// The user wants a UO Architect design from the Designs page opened as a new multi. + public event Action> DesignOpenRequested; + + /// The user wants a UO Architect design placed into the multi being edited. + public event Action DesignPlaceRequested; + + /// The user picked a house part style; the shell switches to the tool for . + public event Action HouseStyleChosen; + + /// The user picked the foundation entry of the House page. + public event Action FoundationChosen; + + /// The user activated a prefab: the shell starts a paste with these tiles. + public event Action> PrefabChosen; + + /// + /// The House page's swap button: swap the selected pieces to the same columns of this style + /// (the GDI editor's "Swap selection to this style"). + /// + public event Action SwapToHouseStyleRequested; + + /// The current draw tile, or -1. + public int CurrentTile => _currentTile; + + /// The house style last picked on the House page, or null. + public HouseStyle CurrentHouseStyle => _houseStyle; + + /// The style the foundation entry uses (walls with the foundation post), or null. + public HouseStyle FoundationStyle => _houseStyles?.Styles.FirstOrDefault(IsFoundationStyle); + + /// + /// Highlights the id as the current draw tile and scrolls to it when the shown list has it. + /// Does not raise . + /// + public void SetCurrentTile(ushort id) + { + SetCurrent(id); + ActiveGrid?.ScrollToId(id); + } + + /// A tool placed the tile: it moves to the front of Recent, which is saved. + public void RecordRecent(ushort id) + { + EnsureRecent(); + _recentTiles.Remove(id); + _recentTiles.Insert(0, id); + if (_recentTiles.Count > TileRecentlyUsed.MaxRecentTiles) + { + _recentTiles.RemoveRange(TileRecentlyUsed.MaxRecentTiles, _recentTiles.Count - TileRecentlyUsed.MaxRecentTiles); + } + + TileRecentlyUsed.Save(_recentTiles); + _recentVersion = -1; + if (_loaded && _tabs.SelectedTab == _recentPage) + { + RefreshRecentGrid(keepScroll: false); + } + } + + /// Re-reads the prefab folder. + public void RefreshPrefabs() + { + if (_prefabsLoaded) + { + LoadPrefabs(); + } + } + + /// Art or tiledata changed: drops thumbnails, re-reads the category tree and repaints. + public void ReloadData() + { + _thumbnails.Clear(); + if (!_loaded) + { + return; + } + + string categoryPath = _category?.Path; + string beforeSearchPath = _categoryBeforeSearch?.Path; + _catalog = TileBrowserCatalog.Load(); + _category = FindCategory(categoryPath); + _categoryBeforeSearch = FindCategory(beforeSearchPath); + + ReloadHouseIcons(); + if (_prefabsLoaded) + { + LoadPrefabs(); + } + + _filterVersion++; + RefreshSelectedPage(keepScroll: true); + foreach (TileBrowserGrid grid in _grids) + { + grid.Invalidate(); + } + } + + /// The client changed: show its house design tables. + public void SetHouseStyles(HouseStyles houseStyles) + { + _houseStyles = houseStyles; + _houseStyle = null; + + // The panel is constructed before the shell loads the settings, so the saved height is applied here. + _housePieces.Height = Math.Clamp(EditorSettings.Current.HousePiecesHeight, 80, 800); + if (_houseLoaded) + { + RebuildHouseTree(); + } + } + + protected override void OnVisibleChanged(EventArgs e) + { + base.OnVisibleChanged(e); + if (Visible) + { + EnsureLoaded(); + } + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + + // Added to a parent that is already showing, the panel gets no VisibleChanged. + // Posted, so the load runs once the panel has its size. + BeginInvoke(new Action(() => + { + if (Visible) + { + EnsureLoaded(); + } + })); + } + + private void TileBrowserPanel_Disposed(object sender, EventArgs e) + { + // The timer, tooltip, menus and image list are in components; the thumbnail cache + // and the (never parented) pieces caption label are not. + _thumbnails.Dispose(); + _housePiecesLabel?.Dispose(); + } + + private void Tabs_SelectedIndexChanged(object sender, EventArgs e) + { + RefreshSelectedPage(); + } + + private void DesignLibrary_OpenRequested(IReadOnlyList picked) + { + DesignOpenRequested?.Invoke(picked); + } + + private void DesignLibrary_PlaceRequested(UoaDesign design) + { + DesignPlaceRequested?.Invoke(design); + } + + private void TilesSplit_SizeChanged(object sender, EventArgs e) + { + PlaceSplitter(); + } + + private void EnsureLoaded() + { + if (_loaded || DesignMode) + { + return; + } + + _loaded = true; + EnsureRecent(); + EnsureFavorites(); + _catalog = TileBrowserCatalog.Load(); + PlaceSplitter(); + RefreshSelectedPage(); + } + + private void EnsureRecent() + { + _recentTiles ??= TileRecentlyUsed.Load(); + } + + private void PlaceSplitter() + { + int height = _tilesSplit.Height; + if (_splitPlaced || height < _tilesSplit.Panel1MinSize + _tilesSplit.Panel2MinSize + 100) + { + return; + } + + _splitPlaced = true; + int max = height - _tilesSplit.Panel2MinSize - _tilesSplit.SplitterWidth; + _tilesSplit.SplitterDistance = Math.Clamp(height / 3, _tilesSplit.Panel1MinSize, max); + } + + // ---------------------------------------------------------------- grids and current tile + + private TileBrowserGrid ActiveGrid => + _tabs.SelectedTab == _tilesPage ? _tilesGrid : + _tabs.SelectedTab == _favoritesPage ? _favoritesGrid : + _tabs.SelectedTab == _recentPage ? _recentGrid : null; + + private TileBrowserGrid CreateGrid(string emptyText) + { + var grid = new TileBrowserGrid(_thumbnails) { Dock = DockStyle.Fill, EmptyText = emptyText, IsMarked = IsFavorite }; + grid.TileActivated += (_, id) => ChooseTile(id); + grid.TileContextMenuRequested += ShowTileMenu; + grid.CellSizeChanged += size => + { + foreach (TileBrowserGrid other in _grids) + { + other.CellSize = size; + } + }; + grid.KeyPress += Grid_KeyPress; + _grids.Add(grid); + return grid; + } + + private void ChooseTile(int id) + { + if (id < 0 || id > ushort.MaxValue) + { + return; + } + + SetCurrent(id); + TileChosen?.Invoke((ushort)id); + } + + private void SetCurrent(int id) + { + _currentTile = id; + foreach (TileBrowserGrid grid in _grids) + { + grid.CurrentId = id; + } + + UpdateStatus(); + } + + /// Typing on a grid goes to the search box, so search is always one keystroke away. + private void Grid_KeyPress(object sender, KeyPressEventArgs e) + { + if (char.IsControl(e.KeyChar)) + { + return; + } + + _searchBox.Focus(); + _searchBox.AppendText(e.KeyChar.ToString()); + e.Handled = true; + } + + private static List Filter(IEnumerable source, Func filter) + { + return filter == null ? source.ToList() : source.Where(filter).ToList(); + } + + /// The search and type filter as one test, or null when neither is set. + private Func TileFilter() + { + TileBrowserQuery query = _query; + Func type = _typeFilter.SelectedIndex > 0 ? _tileTypes[_typeFilter.SelectedIndex].Matches : null; + if (query == null && type == null) + { + return null; + } + + return id => (query == null || query.MatchesTile(id)) && + (type == null || (TileBrowserThumbnails.HasItemData(id) && type(TileData.ItemTable[id]))); + } + + // ---------------------------------------------------------------- search + + private void SearchTimer_Tick(object sender, EventArgs e) + { + ApplySearchNow(); + } + + private void TypeFilter_SelectedIndexChanged(object sender, EventArgs e) + { + if (!_suppressFilterEvents) + { + OnFilterChanged(); + } + } + + private void SearchBox_TextChanged(object sender, EventArgs e) + { + if (_suppressFilterEvents) + { + return; + } + + _searchTimer.Stop(); + _searchTimer.Start(); + } + + private void SearchBox_KeyDown(object sender, KeyEventArgs e) + { + switch (e.KeyCode) + { + case Keys.Escape: + if (_searchBox.TextLength > 0) + { + _searchBox.Clear(); + ApplySearchNow(); + } + + e.Handled = e.SuppressKeyPress = true; + break; + case Keys.Down: + ApplySearchNow(); + if (ActiveGrid is { } grid) + { + grid.Focus(); + grid.FocusFirst(); + } + else if (_tabs.SelectedTab == _housePage) + { + _houseGallery.Focus(); + } + else if (_tabs.SelectedTab == _prefabsPage) + { + _prefabList.Focus(); + } + + e.Handled = true; + break; + case Keys.Enter: + ApplySearchNow(); + PickFirstResult(); + e.Handled = e.SuppressKeyPress = true; + break; + } + } + + private void PickFirstResult() + { + if (ActiveGrid is { Count: > 0 } grid) + { + ChooseTile(grid.FocusedId >= 0 ? grid.FocusedId : grid.Items[0]); + grid.ScrollToId(_currentTile); + } + else if (_tabs.SelectedTab == _housePage) + { + ActivateFirstHouseNode(); + } + else if (_tabs.SelectedTab == _prefabsPage && _prefabList.Items.Count > 0) + { + _prefabList.Items[0].Selected = true; + PlaceSelectedPrefab(); + } + } + + private void ApplySearchNow() + { + _searchTimer.Stop(); + string text = _searchBox.Text.Trim(); + if (text == _queryText) + { + return; + } + + TileBrowserQuery query = TileBrowserQuery.Parse(text); + bool was = _query != null; + bool now = query != null; + if (!was && now) + { + // A search looks through every tile; picking a category in the filtered tree narrows it. + _categoryBeforeSearch = _category; + _category = null; + _categoryPickedDuringSearch = false; + } + else if (was && !now && !_categoryPickedDuringSearch) + { + _category = _categoryBeforeSearch; + } + + _queryText = text; + _query = query; + OnFilterChanged(); + } + + private void OnFilterChanged() + { + _filterVersion++; + RefreshSelectedPage(); + } + + private void RefreshSelectedPage(bool keepScroll = false) + { + EnsureLoaded(); + if (!_loaded) + { + return; + } + + TabPage page = _tabs.SelectedTab; + _typeFilter.Enabled = page == _tilesPage || page == _favoritesPage || page == _recentPage; + bool rebuilt = false; + if (page == _tilesPage && _tilesVersion != _filterVersion) + { + RebuildCategoryTree(); + RefreshTilesGrid(keepScroll); + rebuilt = true; + } + else if (page == _favoritesPage && _favoritesVersion != _filterVersion) + { + RefreshFavoritesGrid(keepScroll); + rebuilt = true; + } + else if (page == _recentPage && _recentVersion != _filterVersion) + { + RefreshRecentGrid(keepScroll); + rebuilt = true; + } + else if (page == _housePage) + { + EnsureHouse(); + if (_houseVersion != _filterVersion) + { + RebuildHouseTree(); + } + } + else if (page == _prefabsPage) + { + EnsurePrefabs(); + if (_prefabsVersion != _filterVersion) + { + RebuildPrefabList(); + } + } + + // Results start at the top; only a first fill looks for the current tile. + if (rebuilt && !keepScroll && _query == null && !_firstFillDone) + { + ActiveGrid?.ScrollToId(_currentTile); + } + + _firstFillDone |= rebuilt; + UpdateStatus(); + } + + private void UpdateStatus() + { + TabPage page = _tabs.SelectedTab; + string list; + if (page == _tilesPage) + { + list = $"{_tilesGrid.Count:N0} tiles" + (_category != null ? $" in {_category.Name}" : string.Empty); + if (_catalog?.Error != null) + { + list += " (multieditor.xml: " + _catalog.Error + ")"; + } + } + else if (page == _favoritesPage) + { + list = $"{_favoritesGrid.Count:N0} tiles"; + } + else if (page == _recentPage) + { + list = $"{_recentGrid.Count:N0} recent tiles"; + } + else if (page == _housePage) + { + list = _houseStyle != null ? $"{_houseStyle.Kind}: {_houseStyle.Name}" : $"{_houseStyleCount} styles"; + } + else + { + list = _prefabList.Items.Count == 0 && _query == null ? "No blueprints saved yet" : $"{_prefabList.Items.Count} blueprints"; + } + + string current = _currentTile >= 0 ? $"Current 0x{_currentTile:X4} {TileBrowserThumbnails.NameOf(_currentTile)}" : string.Empty; + _status.Text = current.Length > 0 ? list + " | " + current : list; + } + + // ---------------------------------------------------------------- tiles page + + private TileBrowserCategory FindCategory(string path) + { + if (path == null || _catalog == null) + { + return null; + } + + foreach (TileBrowserCategory group in _catalog.Groups) + { + if (group.Path == path) + { + return group; + } + + foreach (TileBrowserCategory sub in group.Children) + { + if (sub.Path == path) + { + return sub; + } + } + } + + return null; + } + + /// + /// Rebuilds the tree for the current filter: while filtering it lists only categories with + /// matches, each with its match count, so the tree shows where the results live. + /// + private void RebuildCategoryTree() + { + if (_catalog == null) + { + return; + } + + Func filter = TileFilter(); + _suppressTreeEvents = true; + _categoryTree.BeginUpdate(); + try + { + _categoryTree.Nodes.Clear(); + int allCount = filter == null ? _catalog.AllTiles.Count : _catalog.AllTiles.Count(filter); + var allNode = new TreeNode($"All Tiles ({allCount:N0})") { ToolTipText = "Every static in the art file" }; + _categoryTree.Nodes.Add(allNode); + TreeNode selected = allNode; + + foreach (TileBrowserCategory group in _catalog.Groups) + { + int groupCount = filter == null ? group.Tiles.Count : group.Tiles.Count(filter); + if (filter != null && groupCount == 0) + { + continue; + } + + var groupNode = new TreeNode($"{group.Name} ({groupCount})") { Tag = group }; + foreach (TileBrowserCategory sub in group.Children) + { + int count = filter == null ? sub.Tiles.Count : sub.Tiles.Count(filter); + if (filter != null && count == 0) + { + continue; + } + + var subNode = new TreeNode($"{sub.Name} ({count})") { Tag = sub }; + groupNode.Nodes.Add(subNode); + if (sub == _category) + { + selected = subNode; + } + } + + _categoryTree.Nodes.Add(groupNode); + if (group == _category) + { + selected = groupNode; + } + + if (filter != null || _expandedGroups.Contains(group.Path)) + { + groupNode.Expand(); + } + } + + if (_catalog.Groups.Count == 0) + { + _categoryTree.Nodes.Add(new TreeNode(_catalog.Error != null ? "multieditor.xml could not be read" : "No multieditor.xml in the plugins folder") + { + ForeColor = SystemColors.GrayText, + ToolTipText = TileBrowserCatalog.FilePath + }); + } + + // The category may be filtered out of the tree: show everything that matches instead. + _category = selected.Tag as TileBrowserCategory; + _categoryTree.SelectedNode = selected; + selected.EnsureVisible(); + } + finally + { + _categoryTree.EndUpdate(); + _suppressTreeEvents = false; + } + } + + private void CategoryTree_AfterExpand(object sender, TreeViewEventArgs e) + { + RememberExpansion(e.Node, true); + } + + private void CategoryTree_AfterCollapse(object sender, TreeViewEventArgs e) + { + RememberExpansion(e.Node, false); + } + + private void RememberExpansion(TreeNode node, bool expanded) + { + // Expansion forced by a filter is not the user's choice. + if (_suppressTreeEvents || TileFilter() != null || node.Tag is not TileBrowserCategory { Parent: null } group) + { + return; + } + + if (expanded) + { + _expandedGroups.Add(group.Path); + } + else + { + _expandedGroups.Remove(group.Path); + } + } + + private void CategoryTree_AfterSelect(object sender, TreeViewEventArgs e) + { + if (_suppressTreeEvents || e.Node == null) + { + return; + } + + if (e.Node.Tag is not TileBrowserCategory && e.Node.Parent == null && e.Node.Index > 0) + { + // The "no multieditor.xml" hint. + return; + } + + _category = e.Node.Tag as TileBrowserCategory; + if (_query != null) + { + _categoryPickedDuringSearch = true; + } + + RefreshTilesGrid(keepScroll: false); + _tilesGrid.ScrollToId(_currentTile); + UpdateStatus(); + } + + private void RefreshTilesGrid(bool keepScroll) + { + if (_catalog == null) + { + return; + } + + Func filter = TileFilter(); + IReadOnlyList source = _category != null ? _category.Tiles : _catalog.AllTiles; + _tilesGrid.SetItems(filter == null ? source : Filter(source, filter), keepScroll); + _tilesVersion = _filterVersion; + } + + /// Opens the first category listing the tile, with the search cleared, and scrolls to it. + private void ShowInCategory(int id) + { + TileBrowserCategory category = _catalog?.FindCategoryOf(id); + if (category == null) + { + return; + } + + _suppressFilterEvents = true; + try + { + _searchBox.Clear(); + _typeFilter.SelectedIndex = 0; + } + finally + { + _suppressFilterEvents = false; + } + + _searchTimer.Stop(); + _query = null; + _queryText = string.Empty; + _category = category; + _filterVersion++; + if (_tabs.SelectedTab != _tilesPage) + { + // Its SelectedIndexChanged refreshes the page. + _tabs.SelectedTab = _tilesPage; + } + else + { + RefreshSelectedPage(); + } + + _tilesGrid.ScrollToId(id); + _tilesGrid.Focus(); + } + + // ---------------------------------------------------------------- recent page + + private void RefreshRecentGrid(bool keepScroll) + { + EnsureRecent(); + _recentGrid.SetItems(Filter(_recentTiles, TileFilter()), keepScroll); + _recentVersion = _filterVersion; + UpdateStatus(); + } + + private void ClearRecentButton_Click(object sender, EventArgs e) + { + ClearRecent(); + } + + private void ClearRecent() + { + EnsureRecent(); + if (_recentTiles.Count == 0) + { + return; + } + + _recentTiles.Clear(); + TileRecentlyUsed.Save(_recentTiles); + RefreshRecentGrid(keepScroll: false); + } + + // ---------------------------------------------------------------- tile context menu + + private void ShowTileMenu(TileBrowserGrid grid, int id, Point location) + { + EnsureFavorites(); + ClearMenu(_tileMenu.Items); + + _tileMenu.Items.Add(new ToolStripMenuItem($"0x{id:X4} {TileBrowserThumbnails.NameOf(id)}") { Enabled = false }); + + var use = new ToolStripMenuItem("Draw with this tile"); + use.Click += (_, _) => ChooseTile(id); + _tileMenu.Items.Add(use); + _tileMenu.Items.Add(new ToolStripSeparator()); + + var add = new ToolStripMenuItem("Add to favorites"); + foreach (FavoritePage page in _favorites.Pages) + { + var item = new ToolStripMenuItem(page.Name) { Enabled = !page.Tiles.Contains(id) }; + item.Click += (_, _) => AddFavorite(page, id); + add.DropDownItems.Add(item); + } + + add.DropDownItems.Add(new ToolStripSeparator()); + var newPage = new ToolStripMenuItem("New page..."); + newPage.Click += (_, _) => + { + if (NewFavoritePage() is { } page) + { + AddFavorite(page, id); + } + }; + add.DropDownItems.Add(newPage); + _tileMenu.Items.Add(add); + + // On the Favorites page "remove" means the page shown; elsewhere any page holding the tile. + List holders = grid == _favoritesGrid && CurrentFavoritePage is { } shown + ? (shown.Tiles.Contains(id) ? new List { shown } : new List()) + : _favorites.Pages.Where(p => p.Tiles.Contains(id)).ToList(); + if (holders.Count == 1) + { + FavoritePage page = holders[0]; + var remove = new ToolStripMenuItem($"Remove from favorites (\"{page.Name}\")"); + remove.Click += (_, _) => RemoveFavorite(page, id); + _tileMenu.Items.Add(remove); + } + else if (holders.Count > 1) + { + var remove = new ToolStripMenuItem("Remove from favorites"); + foreach (FavoritePage page in holders) + { + var item = new ToolStripMenuItem(page.Name); + item.Click += (_, _) => RemoveFavorite(page, id); + remove.DropDownItems.Add(item); + } + + _tileMenu.Items.Add(remove); + } + + _tileMenu.Items.Add(new ToolStripSeparator()); + var copy = new ToolStripMenuItem("Copy id"); + copy.Click += (_, _) => CopyId(id); + _tileMenu.Items.Add(copy); + + TileBrowserCategory category = _catalog?.FindCategoryOf(id); + var show = new ToolStripMenuItem(category != null ? $"Show in category ({category.Path})" : "Show in category") + { + Enabled = category != null && !(grid == _tilesGrid && _category == category && TileFilter() == null) + }; + show.Click += (_, _) => ShowInCategory(id); + _tileMenu.Items.Add(show); + + _tileMenu.Items.Add(new ToolStripSeparator()); + var showIds = new ToolStripMenuItem("Show ids under tiles") { Checked = grid.ShowIds }; + showIds.Click += (_, _) => + { + bool value = !grid.ShowIds; + foreach (TileBrowserGrid other in _grids) + { + other.ShowIds = value; + } + }; + _tileMenu.Items.Add(showIds); + + _tileMenu.Show(grid, location); + } + + private static void ClearMenu(ToolStripItemCollection items) + { + while (items.Count > 0) + { + ToolStripItem item = items[0]; + items.RemoveAt(0); + item.Dispose(); + } + } + + private static void CopyId(int id) + { + try + { + Clipboard.SetText($"0x{id:X4}"); + } + catch (ExternalException) + { + // The clipboard is held by another program; nothing to do but skip it. + } + } + + // ---------------------------------------------------------------- favorites page + + private readonly HashSet _favoriteIds = new HashSet(); + private TileFavorites _favorites; + private TileBrowserGrid _favoritesGrid; + private int _favoritePageIndex; + private bool _suppressFavoriteEvents; + + private FavoritePage CurrentFavoritePage => + _favorites != null && _favoritePageIndex >= 0 && _favoritePageIndex < _favorites.Pages.Count ? _favorites.Pages[_favoritePageIndex] : null; + + /// The page's grid; its toolbar is in the designer. + private void BuildFavoritesPage() + { + _favoritesGrid = CreateGrid("This page is empty. Right-click a tile anywhere and choose \"Add to favorites\"."); + _favoritesGrid.KeyDown += FavoritesGrid_KeyDown; + _favoritesGrid.TabIndex = 0; + _favoritesPage.Controls.Add(_favoritesGrid); + _favoritesGrid.BringToFront(); + } + + private void FavoritesGrid_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Delete && CurrentFavoritePage is { } page && _favoritesGrid.FocusedId >= 0) + { + RemoveFavorite(page, _favoritesGrid.FocusedId); + e.Handled = true; + } + } + + private void FavoritePageBox_SelectedIndexChanged(object sender, EventArgs e) + { + if (_suppressFavoriteEvents || _favoritePageBox.SelectedIndex < 0) + { + return; + } + + _favoritePageIndex = _favoritePageBox.SelectedIndex; + RefreshFavoritesGrid(keepScroll: false); + } + + private void AddFavoriteButton_Click(object sender, EventArgs e) + { + if (_currentTile >= 0 && CurrentFavoritePage is { } page) + { + AddFavorite(page, _currentTile); + } + } + + private void RemoveFavoriteButton_Click(object sender, EventArgs e) + { + if (_currentTile >= 0 && CurrentFavoritePage is { } page) + { + RemoveFavorite(page, _currentTile); + } + } + + private void NewFavoritePageItem_Click(object sender, EventArgs e) + { + if (NewFavoritePage() is { } page) + { + _favoritePageIndex = _favorites.Pages.IndexOf(page); + SaveFavorites(); + RefreshFavoritesGrid(keepScroll: false); + } + } + + private void RenamePageItem_Click(object sender, EventArgs e) + { + if (CurrentFavoritePage is { } page && Prompt.Text(this, "Rename favorites page", "Page name:", page.Name) is { } name) + { + page.Name = name; + SaveFavorites(); + } + } + + private void DeletePageItem_Click(object sender, EventArgs e) + { + DeleteFavoritePage(); + } + + private void ImportUoheItem_Click(object sender, EventArgs e) + { + ImportUoheBookmarks(); + } + + private void FavoritePageMenu_DropDownOpening(object sender, EventArgs e) + { + EnsureFavorites(); + _renamePageItem.Enabled = CurrentFavoritePage != null; + _deletePageItem.Enabled = _favorites.Pages.Count > 1; + } + + private void EnsureFavorites() + { + if (_favorites != null) + { + return; + } + + _favorites = TileFavorites.Load(); + RebuildFavoriteIds(); + RefreshFavoritePageBox(); + } + + private bool IsFavorite(int id) => _favoriteIds.Contains(id); + + private void RebuildFavoriteIds() + { + _favoriteIds.Clear(); + foreach (FavoritePage page in _favorites.Pages) + { + _favoriteIds.UnionWith(page.Tiles); + } + } + + private void RefreshFavoritePageBox() + { + _suppressFavoriteEvents = true; + try + { + _favoritePageBox.Items.Clear(); + foreach (FavoritePage page in _favorites.Pages) + { + _favoritePageBox.Items.Add($"{page.Name} ({page.Tiles.Count})"); + } + + _favoritePageIndex = Math.Clamp(_favoritePageIndex, 0, Math.Max(0, _favorites.Pages.Count - 1)); + _favoritePageBox.SelectedIndex = _favorites.Pages.Count > 0 ? _favoritePageIndex : -1; + } + finally + { + _suppressFavoriteEvents = false; + } + } + + private void RefreshFavoritesGrid(bool keepScroll) + { + EnsureFavorites(); + IEnumerable tiles = CurrentFavoritePage?.Tiles ?? Enumerable.Empty(); + _favoritesGrid.SetItems(Filter(tiles, TileFilter()), keepScroll); + _favoritesVersion = _filterVersion; + UpdateStatus(); + } + + /// Saves, then brings the page list, the shown page and every grid's marks up to date. + private void SaveFavorites() + { + try + { + _favorites.Save(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + MessageBox.Show(this, $"Could not save the favorites: {ex.Message}", _messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + + RebuildFavoriteIds(); + RefreshFavoritePageBox(); + _favoritesVersion = -1; + if (_tabs.SelectedTab == _favoritesPage) + { + RefreshFavoritesGrid(keepScroll: true); + } + + foreach (TileBrowserGrid grid in _grids) + { + grid.Invalidate(); + } + } + + private void AddFavorite(FavoritePage page, int id) + { + if (!page.Tiles.Contains(id)) + { + page.Tiles.Add(id); + SaveFavorites(); + } + } + + private void RemoveFavorite(FavoritePage page, int id) + { + if (page.Tiles.Remove(id)) + { + SaveFavorites(); + } + } + + private FavoritePage NewFavoritePage() + { + EnsureFavorites(); + string name = Prompt.Text(this, "New favorites page", "Page name:"); + if (name == null) + { + return null; + } + + var page = new FavoritePage(name); + _favorites.Pages.Add(page); + return page; + } + + private void DeleteFavoritePage() + { + if (CurrentFavoritePage is not { } page || _favorites.Pages.Count <= 1) + { + return; + } + + if (MessageBox.Show(this, $"Delete the favorites page \"{page.Name}\" ({page.Tiles.Count} tiles)?", _messageTitle, + MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) + { + return; + } + + _favorites.Pages.Remove(page); + SaveFavorites(); + RefreshFavoritesGrid(keepScroll: false); + } + + private void ImportUoheBookmarks() + { + EnsureFavorites(); + using var dialog = new OpenFileDialog + { + Filter = "UOHE bookmarks (*.ini)|*.ini|All files (*.*)|*.*", + Title = "Import UOHE bookmarks" + }; + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + try + { + int before = _favorites.Pages.Count; + int pages = _favorites.ImportUoheBookmarks(dialog.FileName); + if (pages > 0) + { + _favoritePageIndex = before; + } + + SaveFavorites(); + RefreshFavoritesGrid(keepScroll: false); + MessageBox.Show(this, $"{pages} page(s) imported.", _messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + MessageBox.Show(this, $"Could not read {dialog.FileName}: {ex.Message}", _messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + // ---------------------------------------------------------------- house page + + /// The kinds of house parts, in the order you build with them. + private static readonly (HousePartKind Kind, string Title, string IconSlot, string Hint)[] _houseKinds = + { + (HousePartKind.Wall, "Walls", "Corner", "Drag a rectangle for a room, or along one row for a single wall. Shift: straight wall. Ctrl: erase."), + (HousePartKind.Floor, "Floors", "F1", "Drag an area to lay the floor. Flat tiles already there are replaced."), + (HousePartKind.Door, "Doors", "Piece3", "Click a wall to hang the door. Click the door again to turn it."), + (HousePartKind.Stair, "Stairs", "North", "Press on the bottom step and drag the way the stairs climb. They rise one floor."), + (HousePartKind.Roof, "Roofs", "EWCrosspiece", "Click a walled room to roof it, or drag over the walls to size it by hand. Ridge, gables and fill are in the options bar.") + }; + + private const string _foundationHint = "Drag the house area: a low wall around a dirt floor 7 above it."; + + private readonly Dictionary _lastStyleOfKind = new Dictionary(); + private readonly Dictionary _houseKindButtons = new Dictionary(); + private HouseStyles _houseStyles; + private HouseStyle _houseStyle; + private HousePartKind _houseKind = HousePartKind.Wall; + private bool _foundationPicked; + private const string _swapText = "Swap selection to this style"; + private bool _patternsShown; + private FloorPattern _pattern; + private TileBrowserGrid _housePieces; + private Label _housePiecesLabel; + private int _houseStyleCount; + private bool _houseLoaded; + + private static bool IsFoundationStyle(HouseStyle style) => + style.Kind == HousePartKind.Wall && style.Get("Post") == FoundationTool.FoundationPost; + + /// + /// The House page: a row of part kinds, the styles of the chosen kind as pictures, and + /// under them the single pieces of the chosen style. The designer holds the page's fixed + /// parts; the kind buttons (one per entry) and the pieces grid + /// are added here. + /// + private void BuildHousePage() + { + // Kind buttons go between Foundation and Patterns. + foreach (var (kind, title, _, hint) in _houseKinds) + { + var button = new ToolStripButton(title) { ToolTipText = hint }; + button.Click += (_, _) => ShowHouseKind(kind, activate: true); + _houseKindButtons[kind] = button; + _houseKindBar.Items.Insert(_houseKindBar.Items.IndexOf(_patternsButton), button); + } + + // The pieces of the chosen style: click one to draw with exactly that tile. + // Roughly half the page each by default; the splitter above the pieces moves the line. + _housePieces = new TileBrowserGrid(_thumbnails) + { + Dock = DockStyle.Bottom, + Height = Math.Clamp(EditorSettings.Current.HousePiecesHeight, 80, 800), + EmptyText = "Pick a style to see its pieces." + }; + _housePieces.CellSize = 64; + _housePieces.TileActivated += (_, id) => ChooseTile(id); + _housePieces.TileContextMenuRequested += ShowTileMenu; + _housePiecesLabel = new Label { Dock = DockStyle.Bottom, Height = 18, Text = "Pieces", ForeColor = SystemColors.GrayText }; + + // Docking runs from the last added control: the pieces sit right after the splitter, + // so they dock below it and above the swap button. + _housePieces.TabIndex = 2; + _housePage.Controls.Add(_housePieces); + _housePage.Controls.SetChildIndex(_housePieces, _housePage.Controls.GetChildIndex(_piecesSplitter) + 1); + } + + private void FoundationButton_Click(object sender, EventArgs e) + { + PickFoundation(); + } + + private void PatternsButton_Click(object sender, EventArgs e) + { + ShowPatterns(null); + } + + private void HouseGallery_TagChosen(object tag) + { + if (tag is FloorPattern pattern) + { + PickPattern(pattern); + } + } + + private void SwapButton_Click(object sender, EventArgs e) + { + if (_patternsShown) + { + DeletePattern(); + } + else if (_houseStyle != null) + { + SwapToHouseStyleRequested?.Invoke(_houseStyle); + } + } + + private void PiecesSplitter_SplitterMoved(object sender, SplitterEventArgs e) + { + EditorSettings settings = EditorSettings.Current.Clone(); + settings.HousePiecesHeight = _housePieces.Height; + settings.Apply(); + } + + /// + /// Opens the House page on a kind of part (or the foundation) and picks its style, as if the + /// kind button had been pressed. Called when a house tool is chosen from the tool palette. + /// + public void ShowHousePage(HousePartKind kind, bool foundation) + { + EnsureLoaded(); + if (_tabs.SelectedTab != _housePage) + { + _tabs.SelectedTab = _housePage; + } + + EnsureHouse(); + if (foundation) + { + if (_foundationButton.Enabled) + { + PickFoundation(); + } + } + else if (_houseKindButtons[kind].Enabled) + { + ShowHouseKind(kind, activate: true); + } + } + + private void EnsureHouse() + { + if (!_houseLoaded) + { + _houseLoaded = true; + RebuildHouseTree(); + } + } + + private void ReloadHouseIcons() + { + if (_houseLoaded) + { + RebuildHouseTree(); + } + } + + private bool HouseStyleMatches(HouseStyle style) + { + TileBrowserQuery query = _query; + return query == null || + (query.IsIdQuery ? style.Slots.Values.Any(id => query.MatchesId(id)) : query.MatchesText(style.Group + " " + style.Name)); + } + + /// + /// Shows the styles of the current kind that match the search (by style or material name, + /// or by a piece's id), and how many each kind has. + /// + private void RebuildHouseTree() + { + if (_patternsShown) + { + RebuildPatterns(); + return; + } + + _patternsButton.Checked = false; + _swapButton.Text = _swapText; + _swapButton.Enabled = true; + List styles = _houseStyles?.Styles ?? new List(); + _houseStyleCount = 0; + + foreach (var (kind, title, _, _) in _houseKinds) + { + int count = styles.Count(st => st.Kind == kind && HouseStyleMatches(st)); + _houseStyleCount += count; + ToolStripButton button = _houseKindButtons[kind]; + button.Text = $"{title} ({count})"; + button.Enabled = count > 0; + button.Checked = !_foundationPicked && kind == _houseKind; + } + + _foundationButton.Enabled = styles.Any(IsFoundationStyle); + _foundationButton.Checked = _foundationPicked; + + // A search that empties the current kind moves on to the first kind with matches. + if (!_houseKindButtons[_houseKind].Enabled) + { + foreach (var (kind, _, _, _) in _houseKinds) + { + if (_houseKindButtons[kind].Enabled) + { + _houseKind = kind; + _houseKindButtons[kind].Checked = !_foundationPicked; + break; + } + } + } + + string iconSlot = _houseKinds.First(k => k.Kind == _houseKind).IconSlot; + var sections = new List(); + foreach (IGrouping group in styles.Where(st => st.Kind == _houseKind && HouseStyleMatches(st)).GroupBy(st => st.Group)) + { + var items = new List(); + foreach (HouseStyle style in group) + { + int icon = style.Get(iconSlot) is var preferred and not 0 ? preferred : style.IconId; + items.Add(new HouseGalleryItem(style, ShortStyleName(style), icon)); + } + + sections.Add(new HouseGallerySection(group.Key, items)); + } + + // Headings help when a material has several styles (walls). Where most groups hold a + // single style (floors, doors), they only repeat its name and waste a row each. + if (sections.Count == 1 || sections.Count(section => section.Items.Count == 1) * 2 > sections.Count) + { + var all = new List(); + foreach (HouseGallerySection section in sections) + { + all.AddRange(section.Items); + } + + sections.Clear(); + sections.Add(new HouseGallerySection(null, all)); + } + + _houseGallery.EmptyText = _houseStyles == null || styles.Count == 0 + ? "No house design tables in this client." + : _query != null ? "No house styles match." : "No styles of this kind."; + _houseGallery.SetSections(sections); + _houseGallery.Selected = _foundationPicked ? null : _houseStyle; + _houseGallery.ScrollToSelected(); + + ShowHousePieces(); + _houseVersion = _filterVersion; + UpdateStatus(); + } + + /// The style name without the words its section heading or kind button already say. + private static string ShortStyleName(HouseStyle style) + { + string name = style.Name; + foreach (string word in new[] { " Walls", " Wall", " Floors", " Floor", " Doors", " Door", " Stairs", " Roofs", " Roof" }) + { + if (name.EndsWith(word, StringComparison.OrdinalIgnoreCase) && name.Length > word.Length) + { + name = name[..^word.Length]; + break; + } + } + + return name; + } + + private void ShowHousePieces() + { + HouseStyle style = _houseStyle; + var pieces = new List(); + if (style != null) + { + foreach (KeyValuePair slot in style.Slots) + { + // Stair styles also list stair multis; those are multi ids, not art. + if (!slot.Key.StartsWith("Multi", StringComparison.Ordinal) && !pieces.Contains(slot.Value)) + { + pieces.Add(slot.Value); + } + } + } + + _housePieces.SetItems(pieces); + _housePiecesLabel.Text = style != null ? $"Pieces of {style.Name} (click one to draw with it)" : "Pieces"; + _houseHint.Text = _foundationPicked ? _foundationHint : _houseKinds.First(k => k.Kind == _houseKind).Hint; + } + + /// + /// Switches the gallery to a kind. With the style last used for + /// that kind (or its first one) is picked straight away, so the tool is ready to drag. + /// + private void ShowHouseKind(HousePartKind kind, bool activate) + { + _houseKind = kind; + _foundationPicked = false; + _patternsShown = false; + if (activate) + { + _lastStyleOfKind.TryGetValue(kind, out HouseStyle last); + _houseStyle = last; + } + + RebuildHouseTree(); + if (!activate) + { + return; + } + + HouseStyle pick = _houseStyle != null && HouseStyleMatches(_houseStyle) ? _houseStyle : _houseGallery.First(); + if (pick != null) + { + PickHouseStyle(pick); + } + } + + private void PickHouseStyle(HouseStyle style) + { + _foundationPicked = false; + _patternsShown = false; + _houseStyle = style; + _houseKind = style.Kind; + _lastStyleOfKind[style.Kind] = style; + foreach (KeyValuePair button in _houseKindButtons) + { + button.Value.Checked = button.Key == style.Kind; + } + + _foundationButton.Checked = false; + _houseGallery.Selected = style; + ShowHousePieces(); + UpdateStatus(); + HouseStyleChosen?.Invoke(style); + } + + private void PickFoundation() + { + _foundationPicked = true; + _patternsShown = false; + _patternsButton.Checked = false; + _swapButton.Text = _swapText; + _houseStyle = FoundationStyle; + foreach (ToolStripButton button in _houseKindButtons.Values) + { + button.Checked = false; + } + + _foundationButton.Checked = true; + _houseGallery.Selected = null; + ShowHousePieces(); + UpdateStatus(); + FoundationChosen?.Invoke(); + } + + // ---------------------------------------------------------------- floor patterns + + /// The user picked a floor pattern; the shell switches to the floor pattern tool. + public event Action FloorPatternChosen; + + /// + /// Shows the floor patterns on the House page, re-read from disk, and picks one (the given + /// one, the last used, or the first). + /// + public void ShowPatterns(FloorPattern select) + { + EnsureLoaded(); + if (_tabs.SelectedTab != _housePage) + { + _tabs.SelectedTab = _housePage; + } + + EnsureHouse(); + _patternsShown = true; + _foundationPicked = false; + FloorPatterns.Reset(); + List all = FloorPatterns.All(); + FloorPattern pick = select != null ? all.Find(p => p.Name == select.Name) + : _pattern != null ? all.Find(p => p.Name == _pattern.Name) + : null; + pick ??= all.Count > 0 ? all[0] : null; + _pattern = pick; + RebuildPatterns(); + if (pick != null) + { + FloorPatternChosen?.Invoke(pick); + } + } + + private void RebuildPatterns() + { + foreach (ToolStripButton button in _houseKindButtons.Values) + { + button.Checked = false; + } + + _foundationButton.Checked = false; + _patternsButton.Checked = true; + + TileBrowserQuery query = _query; + var mine = new List(); + var shipped = new List(); + foreach (FloorPattern pattern in FloorPatterns.All()) + { + if (query != null && !(query.IsIdQuery ? pattern.Pieces().Any(id => query.MatchesId(id)) : query.MatchesText(pattern.Name))) + { + continue; + } + + (pattern.BuiltIn ? shipped : mine).Add(new HouseGalleryItem(null, pattern.Name, pattern.IconId, pattern)); + } + + _houseGallery.EmptyText = "No floor patterns yet. Lay out one bordered floor by hand, select it, " + + "and use File > Save selection as floor pattern."; + _houseGallery.SetSections(new List + { + new HouseGallerySection("Your patterns", mine), + new HouseGallerySection("Built in", shipped) + }); + _houseGallery.Selected = null; + _houseGallery.SelectedTag = _pattern; + _houseGallery.ScrollToSelected(); + + _housePieces.SetItems(_pattern != null ? _pattern.Pieces().Select(id => (int)id).ToList() : new List()); + _housePiecesLabel.Text = _pattern != null ? $"Pieces of {_pattern.Name}" : "Pieces"; + _houseHint.Text = "Drag an area: corners, sides and fill are laid as in the pattern, repeated to fit."; + _swapButton.Text = "Delete this pattern"; + _swapButton.Enabled = _pattern != null && !_pattern.BuiltIn; + _houseVersion = _filterVersion; + UpdateStatus(); + } + + private void PickPattern(FloorPattern pattern) + { + _pattern = pattern; + RebuildPatterns(); + FloorPatternChosen?.Invoke(pattern); + } + + private void DeletePattern() + { + if (_pattern == null || _pattern.BuiltIn || + MessageBox.Show(this, $"Delete the floor pattern \"{_pattern.Name}\"?", _messageTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) + { + return; + } + + FloorPatterns.Delete(_pattern); + _pattern = null; + ShowPatterns(null); + } + + private void ActivateFirstHouseNode() + { + if (_houseGallery.First() is { } style) + { + PickHouseStyle(style); + } + } + + // ---------------------------------------------------------------- blueprints page + + private const int _prefabIconSize = 80; + + private readonly List _prefabs = new List(); + private readonly List _prefabGroups = new List(); + private bool _prefabsLoaded; + + /// The group shown: null for all, empty for the blueprints in no group, else a group name. + private string _prefabGroup; + + /// A blueprint file. Group is the subfolder it is in, empty for the blueprint folder itself. + private sealed record PrefabEntry(string Name, string Group, string Path, int TileCount, int ImageIndex, HashSet Ids); + + /// + /// One click places a blueprint, like picking a tile; a right click opens its menu + /// without starting a paste. + /// + private void PrefabList_MouseClick(object sender, MouseEventArgs e) + { + if (_prefabList.GetItemAt(e.X, e.Y) is not { } item) + { + return; + } + + item.Selected = true; + if (e.Button == MouseButtons.Left) + { + PlaceSelectedPrefab(); + } + else if (e.Button == MouseButtons.Right) + { + ShowPrefabMenu(e.Location); + } + } + + private void PrefabList_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Delete) + { + DeleteSelectedPrefab(); + e.Handled = true; + } + else if (e.KeyCode == Keys.Enter) + { + PlaceSelectedPrefab(); + e.Handled = e.SuppressKeyPress = true; + } + else if (e.KeyCode == Keys.F2) + { + RenameSelectedPrefab(); + e.Handled = true; + } + } + + private void EnsurePrefabs() + { + if (!_prefabsLoaded) + { + LoadPrefabs(); + } + } + + /// + /// Saves tiles as a blueprint in the group being shown (no group when all are shown) and + /// brings up the Blueprints page. + /// + public void SaveBlueprint(string name, List tiles) + { + EnsureLoaded(); + try + { + string folder = GroupFolder(_prefabGroup ?? string.Empty); + Directory.CreateDirectory(folder); + File.WriteAllText(Path.Combine(folder, Prefabs.SafeName(name) + ".txt"), ClipboardTile.Format(tiles)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + MessageBox.Show(this, $"Could not save the blueprint: {ex.Message}", _messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + if (_tabs.SelectedTab != _prefabsPage) + { + _tabs.SelectedTab = _prefabsPage; + } + + LoadPrefabs(); + } + + private static string GroupFolder(string group) + { + return string.IsNullOrEmpty(group) ? Prefabs.Folder : Path.Combine(Prefabs.Folder, group); + } + + /// + /// Reads every blueprint file and draws its thumbnail; unreadable files are skipped. A + /// subfolder of the blueprint folder is a group, also when it is empty. + /// + private void LoadPrefabs() + { + _prefabsLoaded = true; + _prefabs.Clear(); + _prefabGroups.Clear(); + _prefabList.Items.Clear(); + _prefabIcons.Images.Clear(); + + try + { + if (Directory.Exists(Prefabs.Folder)) + { + AddPrefabsOf(string.Empty); + foreach (string folder in Directory.EnumerateDirectories(Prefabs.Folder).OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) + { + string group = Path.GetFileName(folder); + _prefabGroups.Add(group); + AddPrefabsOf(group); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // What could be read is shown. + } + + if (!string.IsNullOrEmpty(_prefabGroup) && !_prefabGroups.Contains(_prefabGroup)) + { + _prefabGroup = null; + } + + RebuildPrefabGroupBar(); + RebuildPrefabList(); + } + + private void AddPrefabsOf(string group) + { + foreach (string path in Directory.EnumerateFiles(GroupFolder(group), "*.txt").OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) + { + List tiles = LoadPrefab(path); + if (tiles == null || tiles.Count == 0) + { + continue; + } + + using (Bitmap thumb = Prefabs.Thumbnail(tiles, _prefabIconSize)) + { + _prefabIcons.Images.Add(thumb); + } + + _prefabs.Add(new PrefabEntry(Path.GetFileNameWithoutExtension(path), group, path, tiles.Count, + _prefabIcons.Images.Count - 1, tiles.Select(t => (int)t.Id).ToHashSet())); + } + } + + private static List LoadPrefab(string path) + { + try + { + return File.Exists(path) ? ClipboardTile.Parse(File.ReadAllText(path)) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + private void RebuildPrefabGroupBar() + { + _prefabGroupBar.Items.Clear(); + + void Add(string text, string group, string tip) + { + int count = group == null ? _prefabs.Count : _prefabs.Count(p => p.Group == group); + var button = new ToolStripButton($"{text} ({count})") + { + DisplayStyle = ToolStripItemDisplayStyle.Text, + Checked = _prefabGroup == group, + ToolTipText = tip, + AutoToolTip = false, + Margin = new Padding(1, 1, 0, 2) + }; + button.Click += (_, _) => + { + _prefabGroup = group; + RebuildPrefabGroupBar(); + RebuildPrefabList(); + }; + if (!string.IsNullOrEmpty(group)) + { + // A named group can be renamed or removed from its own button. + button.MouseUp += (_, e) => + { + if (e.Button == MouseButtons.Right) + { + ShowGroupMenu(group, _prefabGroupBar.PointToClient(Cursor.Position)); + } + }; + } + + _prefabGroupBar.Items.Add(button); + } + + Add("All", null, "Every blueprint"); + Add("Ungrouped", string.Empty, "Blueprints in no group"); + foreach (string group in _prefabGroups) + { + Add(group, group, "Right click to rename or remove this group"); + } + + var create = new ToolStripButton("+ Group") { DisplayStyle = ToolStripItemDisplayStyle.Text, ToolTipText = "Make a new group", AutoToolTip = false }; + create.Click += (_, _) => CreatePrefabGroup(null); + _prefabGroupBar.Items.Add(new ToolStripSeparator()); + _prefabGroupBar.Items.Add(create); + var refresh = new ToolStripButton("Refresh") { DisplayStyle = ToolStripItemDisplayStyle.Text, ToolTipText = "Read the blueprint folder again", AutoToolTip = false }; + refresh.Click += (_, _) => LoadPrefabs(); + _prefabGroupBar.Items.Add(refresh); + } + + /// Shows the blueprints of the chosen group whose name matches the search, or that hold a searched id. + private void RebuildPrefabList() + { + TileBrowserQuery query = _query; + string selected = (_prefabList.SelectedItems.Count > 0 ? _prefabList.SelectedItems[0].Tag as PrefabEntry : null)?.Path; + _prefabList.BeginUpdate(); + try + { + _prefabList.Items.Clear(); + foreach (PrefabEntry prefab in _prefabs) + { + if (_prefabGroup != null && prefab.Group != _prefabGroup) + { + continue; + } + + if (query != null && !(query.IsIdQuery ? prefab.Ids.Any(query.MatchesId) : query.MatchesText(prefab.Group + " " + prefab.Name))) + { + continue; + } + + string where = prefab.Group.Length > 0 ? $" (group {prefab.Group})" : string.Empty; + var item = new ListViewItem(prefab.Name, prefab.ImageIndex) + { + Tag = prefab, + ToolTipText = $"{prefab.Name}: {prefab.TileCount} tiles{where}" + }; + _prefabList.Items.Add(item); + item.Selected = prefab.Path == selected; + } + } + finally + { + _prefabList.EndUpdate(); + } + + _prefabsVersion = _filterVersion; + UpdateStatus(); + } + + private PrefabEntry SelectedPrefab => _prefabList.SelectedItems.Count > 0 ? _prefabList.SelectedItems[0].Tag as PrefabEntry : null; + + private void PlaceSelectedPrefab() + { + if (SelectedPrefab is not { } prefab) + { + return; + } + + // Read again so the shell gets its own list and sees the file as it is now. + List tiles = LoadPrefab(prefab.Path); + if (tiles != null && tiles.Count > 0) + { + PrefabChosen?.Invoke(tiles); + } + } + + private void ShowPrefabMenu(Point location) + { + if (SelectedPrefab is not { } prefab) + { + return; + } + + _prefabMenu.Items.Clear(); + _prefabMenu.Items.Add("Place", null, (_, _) => PlaceSelectedPrefab()); + + var move = new ToolStripMenuItem("Move to group"); + void Target(string text, string group) + { + var item = new ToolStripMenuItem(text) { Checked = prefab.Group == group, Enabled = prefab.Group != group }; + item.Click += (_, _) => MovePrefab(prefab, group); + move.DropDownItems.Add(item); + } + + Target("Ungrouped", string.Empty); + foreach (string group in _prefabGroups) + { + Target(group, group); + } + + move.DropDownItems.Add(new ToolStripSeparator()); + move.DropDownItems.Add("New group...", null, (_, _) => CreatePrefabGroup(prefab)); + _prefabMenu.Items.Add(move); + _prefabMenu.Items.Add("Rename...", null, (_, _) => RenameSelectedPrefab()); + _prefabMenu.Items.Add("Delete", null, (_, _) => DeleteSelectedPrefab()); + _prefabMenu.Show(_prefabList, location); + } + + /// Runs a file operation on the blueprint folder, shows why when it fails, and re-reads the folder. + private void PrefabFileAction(string what, Action action) + { + try + { + action(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + MessageBox.Show(this, $"Could not {what}: {ex.Message}", _messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + + LoadPrefabs(); + } + + private void MovePrefab(PrefabEntry prefab, string group) + { + PrefabFileAction("move the blueprint", () => + { + string folder = GroupFolder(group); + Directory.CreateDirectory(folder); + File.Move(prefab.Path, Path.Combine(folder, Path.GetFileName(prefab.Path))); + }); + } + + /// Asks for a group name and makes it; with a blueprint, moves that one into it. + private void CreatePrefabGroup(PrefabEntry moveIn) + { + if (Prompt.Text(this, "New blueprint group", "Group name:") is not { } typed || Prefabs.SafeName(typed).Length == 0) + { + return; + } + + string group = Prefabs.SafeName(typed); + PrefabFileAction("make the group", () => + { + Directory.CreateDirectory(GroupFolder(group)); + if (moveIn != null) + { + File.Move(moveIn.Path, Path.Combine(GroupFolder(group), Path.GetFileName(moveIn.Path))); + } + }); + + _prefabGroup = _prefabGroups.Contains(group) ? group : _prefabGroup; + RebuildPrefabGroupBar(); + RebuildPrefabList(); + } + + private void ShowGroupMenu(string group, Point location) + { + _prefabMenu.Items.Clear(); + _prefabMenu.Items.Add("Rename group...", null, (_, _) => + { + if (Prompt.Text(this, "Rename blueprint group", "Group name:", group) is { } typed && + Prefabs.SafeName(typed) is { Length: > 0 } name && name != group) + { + if (_prefabGroup == group) + { + _prefabGroup = name; + } + + PrefabFileAction("rename the group", () => Directory.Move(GroupFolder(group), GroupFolder(name))); + } + }); + _prefabMenu.Items.Add("Remove group (its blueprints become ungrouped)", null, (_, _) => + { + PrefabFileAction("remove the group", () => + { + foreach (string path in Directory.EnumerateFiles(GroupFolder(group), "*.txt").ToList()) + { + File.Move(path, Path.Combine(Prefabs.Folder, Path.GetFileName(path))); + } + + // Only an empty folder goes: anything else in it is not ours to delete. + if (!Directory.EnumerateFileSystemEntries(GroupFolder(group)).Any()) + { + Directory.Delete(GroupFolder(group)); + } + }); + }); + _prefabMenu.Show(_prefabGroupBar, location); + } + + private void RenameSelectedPrefab() + { + if (SelectedPrefab is not { } prefab || + Prompt.Text(this, "Rename blueprint", "Blueprint name:", prefab.Name) is not { } typed || + Prefabs.SafeName(typed) is not { Length: > 0 } name || name == prefab.Name) + { + return; + } + + PrefabFileAction("rename the blueprint", () => File.Move(prefab.Path, Path.Combine(Path.GetDirectoryName(prefab.Path), name + ".txt"))); + } + + private void DeleteSelectedPrefab() + { + if (SelectedPrefab is not { } prefab || + MessageBox.Show(this, $"Delete the blueprint \"{prefab.Name}\"?", _messageTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) + { + return; + } + + PrefabFileAction("delete the blueprint", () => File.Delete(prefab.Path)); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.resx b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.resx new file mode 100644 index 00000000..1f5fb7ed --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserPanel.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 643, 17 + + + 17, 17 + + + 138, 17 + + + 247, 17 + + + 379, 17 + + + 500, 17 + + + 739, 17 + + + 862, 17 + + + 968, 17 + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UI/TileBrowserThumbnails.cs b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserThumbnails.cs new file mode 100644 index 00000000..8284aa5a --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/TileBrowserThumbnails.cs @@ -0,0 +1,180 @@ +/*************************************************************************** + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Globalization; +using System.Text; +using Ultima; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Scaled-down copies of static art for the tile grids, in premultiplied ARGB because GDI+ + /// draws that format far faster than the 16 bit art. Art is never scaled up. + /// + internal sealed class TileBrowserThumbnails : IDisposable + { + // Enough for several screens of 64 px cells; a full clear past it is cheap and rare. + private const int _maxEntries = 3000; + + private static readonly (TileFlag Flag, string Name)[] _summaryFlags = + { + (TileFlag.Background, "Background"), + (TileFlag.Wall, "Wall"), + (TileFlag.Impassable, "Impassable"), + (TileFlag.Surface, "Surface"), + (TileFlag.Bridge, "Bridge"), + (TileFlag.Roof, "Roof"), + (TileFlag.Door, "Door"), + (TileFlag.Window, "Window"), + (TileFlag.StairBack, "StairBack"), + (TileFlag.StairRight, "StairRight"), + (TileFlag.Foliage, "Foliage"), + (TileFlag.Container, "Container"), + (TileFlag.LightSource, "Light"), + (TileFlag.Translucent, "Translucent"), + (TileFlag.Transparent, "Transparent"), + (TileFlag.Animation, "Animated"), + (TileFlag.Wet, "Wet"), + (TileFlag.NoShoot, "NoShoot"), + (TileFlag.HoverOver, "HoverOver"), + (TileFlag.Generic, "Generic") + }; + + private readonly Dictionary<(int Id, int Box), Bitmap> _cache = new Dictionary<(int, int), Bitmap>(); + + /// The art fitted into a box of the given size, or null when the tile has no art. + public Bitmap Get(int id, int box) + { + if (_cache.TryGetValue((id, box), out Bitmap thumb)) + { + return thumb; + } + + Bitmap art = Art.GetStatic(id); + if (art == null || art.Width <= 0 || art.Height <= 0) + { + _cache[(id, box)] = null; + return null; + } + + if (_cache.Count >= _maxEntries) + { + Clear(); + } + + float scale = Math.Min(1f, Math.Min((float)box / art.Width, (float)box / art.Height)); + int w = Math.Max(1, (int)Math.Round(art.Width * scale)); + int h = Math.Max(1, (int)Math.Round(art.Height * scale)); + thumb = new Bitmap(w, h, PixelFormat.Format32bppPArgb); + using (Graphics g = Graphics.FromImage(thumb)) + { + if (scale < 1f) + { + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + g.PixelOffsetMode = PixelOffsetMode.HighQuality; + using var attributes = new ImageAttributes(); + // Keeps the bicubic filter from pulling transparent black into the edge pixels. + attributes.SetWrapMode(WrapMode.TileFlipXY); + g.DrawImage(art, new Rectangle(0, 0, w, h), 0, 0, art.Width, art.Height, GraphicsUnit.Pixel, attributes); + } + else + { + g.DrawImageUnscaled(art, 0, 0); + } + } + + _cache[(id, box)] = thumb; + return thumb; + } + + public void Clear() + { + foreach (Bitmap bitmap in _cache.Values) + { + bitmap?.Dispose(); + } + + _cache.Clear(); + } + + public void Dispose() => Clear(); + + public static bool HasItemData(int id) => TileData.ItemTable != null && id >= 0 && id < TileData.ItemTable.Length; + + public static string NameOf(int id) => HasItemData(id) ? TileData.ItemTable[id].Name?.Trim() ?? string.Empty : string.Empty; + + /// Tooltip text: id, name, then height and the flags that matter when building. + public static string Describe(int id) + { + var text = new StringBuilder(); + text.Append(CultureInfo.InvariantCulture, $"0x{id:X4} ({id})"); + string name = NameOf(id); + if (name.Length > 0) + { + text.Append(" ").Append(name); + } + + if (!HasItemData(id)) + { + return text.ToString(); + } + + ItemData data = TileData.ItemTable[id]; + text.AppendLine().Append(CultureInfo.InvariantCulture, $"Height {data.Height}"); + if ((data.Flags & TileFlag.Bridge) != 0) + { + text.Append(CultureInfo.InvariantCulture, $" (calc {data.CalcHeight})"); + } + + text.Append(CultureInfo.InvariantCulture, $", weight {data.Weight}"); + + var flags = new List(); + foreach ((TileFlag flag, string flagName) in _summaryFlags) + { + if ((data.Flags & flag) != 0) + { + flags.Add(flagName); + } + } + + if (flags.Count > 0) + { + text.AppendLine(); + int lineLength = 0; + for (int i = 0; i < flags.Count; i++) + { + if (i > 0) + { + // Wraps long flag lists so the tooltip stays narrow. + if (lineLength + flags[i].Length > 40) + { + text.AppendLine(); + lineLength = 0; + } + else + { + text.Append(", "); + lineLength += 2; + } + } + + text.Append(flags[i]); + lineLength += flags[i].Length; + } + } + + return text.ToString(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj b/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj index 544c5c33..a4a02bae 100644 --- a/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj +++ b/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj @@ -3,14 +3,17 @@ MultiEditor net10.0-windows true + true false MultiEditor MultiEditor Copyright © 2026 - 1.7.0.0 - 1.7.0.0 + 3.0.0.0 + 3.0.0.0 true false + + false true @@ -25,23 +28,7 @@ Off - - Form - - - ShortcutsHelpForm.cs - - - UserControl - - - MultiEditorControl.cs - - - True - True - Resources.resx - + @@ -54,20 +41,149 @@ - - ShortcutsHelpForm.cs + + UserControl + + + DesignLibraryPanel.cs + + + Form + + + DocumentIOPickDialog.cs + + + Form + + + FolderImportDialog.cs + + + Form + + + DocumentIOSaveDialog.cs + + + Form + + + EditorSettingsDialog.cs + + + Form + + + FloorsDialog.cs + + + UserControl + + + InspectorPanel.cs + + + Form + + + MapExtractForm.cs + + + UserControl + + + MultiEditorControl.cs + + + Form + + + NewMultiDialog.cs + + + Form + + + NumbersPromptForm.cs + + + Form + + + ShortcutsForm.cs + + + Form + + + TextPromptForm.cs + + + UserControl + + + TileBrowserPanel.cs + + + + + DesignLibraryPanel.cs + + + DocumentIOPickDialog.cs + + + DocumentIOSaveDialog.cs + + + EditorSettingsDialog.cs + + + FloorsDialog.cs - + + InspectorPanel.cs + + + MapExtractForm.cs + + MultiEditorControl.cs - - ResXFileCodeGenerator - Resources.Designer.cs + + NewMultiDialog.cs + + + NumbersPromptForm.cs + + + ShortcutsForm.cs + + + TextPromptForm.cs + + + TileBrowserPanel.cs PreserveNewest + + PreserveNewest + + + + + <_PluginDependency Include="@(RuntimeCopyLocalItems)" /> + <_PluginDependency Include="@(RuntimeTargetsCopyLocalItems)" Condition="'%(RuntimeTargetsCopyLocalItems.RuntimeIdentifier)' == 'win-x64'" /> + + + \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.Designer.cs b/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.Designer.cs deleted file mode 100644 index 00a0a5bd..00000000 --- a/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.Designer.cs +++ /dev/null @@ -1,1237 +0,0 @@ -/*************************************************************************** - * - * $Author: MuadDib & Turley - * - * "THE BEER-WARE LICENSE" - * As long as you retain this notice you can do whatever you want with - * this stuff. If we meet some day, and you think this stuff is worth it, - * you can buy me a beer in return. - * - ***************************************************************************/ - -namespace UoFiddler.Plugin.MultiEditor.UserControls -{ - partial class MultiEditorControl - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// 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)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MultiEditorControl)); - TC_MultiEditorToolbox = new System.Windows.Forms.TabControl(); - tileTab = new System.Windows.Forms.TabPage(); - splitContainer4 = new System.Windows.Forms.SplitContainer(); - treeViewTilesXML = new System.Windows.Forms.TreeView(); - DummyContextMenu = new System.Windows.Forms.ContextMenuStrip(components); - pictureBoxDrawTiles = new System.Windows.Forms.PictureBox(); - vScrollBarDrawTiles = new System.Windows.Forms.VScrollBar(); - textBoxDrawTilesFilter = new System.Windows.Forms.TextBox(); - designTab = new System.Windows.Forms.TabPage(); - groupBox1 = new System.Windows.Forms.GroupBox(); - BTN_CreateBlank = new System.Windows.Forms.Button(); - numericUpDown_Size_Width = new System.Windows.Forms.NumericUpDown(); - BTN_Resize = new System.Windows.Forms.Button(); - numericUpDown_Size_Height = new System.Windows.Forms.NumericUpDown(); - importTab = new System.Windows.Forms.TabPage(); - treeViewMultiList = new System.Windows.Forms.TreeView(); - Save = new System.Windows.Forms.TabPage(); - groupBox4 = new System.Windows.Forms.GroupBox(); - BTN_Export_XML = new System.Windows.Forms.Button(); - BTN_Export_UOX3 = new System.Windows.Forms.Button(); - BTN_Export_CSV = new System.Windows.Forms.Button(); - BTN_Export_WSC = new System.Windows.Forms.Button(); - BTN_Export_UOA = new System.Windows.Forms.Button(); - textBox_Export = new System.Windows.Forms.TextBox(); - BTN_Export_Txt = new System.Windows.Forms.Button(); - groupBox2 = new System.Windows.Forms.GroupBox(); - textBox_SaveToID = new System.Windows.Forms.TextBox(); - BTN_Save = new System.Windows.Forms.Button(); - splitContainer1 = new System.Windows.Forms.SplitContainer(); - splitContainer3 = new System.Windows.Forms.SplitContainer(); - brushSizeLabel = new System.Windows.Forms.Label(); - BTN_RectFill = new System.Windows.Forms.CheckBox(); - imageListTools = new System.Windows.Forms.ImageList(components); - BTN_LineDraw = new System.Windows.Forms.CheckBox(); - RB_Brush_S = new System.Windows.Forms.RadioButton(); - RB_Brush_M = new System.Windows.Forms.RadioButton(); - RB_Brush_L = new System.Windows.Forms.RadioButton(); - BTN_Trans = new System.Windows.Forms.CheckBox(); - BTN_Pipette = new System.Windows.Forms.CheckBox(); - BTN_Floor = new System.Windows.Forms.CheckBox(); - BTN_Z = new System.Windows.Forms.CheckBox(); - BTN_Remove = new System.Windows.Forms.CheckBox(); - BTN_Draw = new System.Windows.Forms.CheckBox(); - BTN_Select = new System.Windows.Forms.CheckBox(); - numericUpDown_Floor = new System.Windows.Forms.NumericUpDown(); - numericUpDown_Z = new System.Windows.Forms.NumericUpDown(); - collapsibleSplitter1 = new UoFiddler.Controls.UserControls.CollapsibleSplitter(); - Selectedpanel = new System.Windows.Forms.Panel(); - groupBox3 = new System.Windows.Forms.GroupBox(); - DynamiccheckBox = new System.Windows.Forms.CheckBox(); - numericUpDown_Selected_Z = new System.Windows.Forms.NumericUpDown(); - numericUpDown_Selected_Y = new System.Windows.Forms.NumericUpDown(); - numericUpDown_Selected_X = new System.Windows.Forms.NumericUpDown(); - splitContainer2 = new System.Windows.Forms.SplitContainer(); - MaxHeightTrackBar = new System.Windows.Forms.TrackBar(); - splitter1 = new System.Windows.Forms.Splitter(); - pictureBoxMinimap = new System.Windows.Forms.PictureBox(); - pictureBoxMulti = new System.Windows.Forms.PictureBox(); - hScrollBar = new System.Windows.Forms.HScrollBar(); - vScrollBar = new System.Windows.Forms.VScrollBar(); - toolStrip1 = new System.Windows.Forms.ToolStrip(); - toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); - UndoItems = new System.Windows.Forms.ToolStripMenuItem(); - showWalkablesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - showDoubleSurfaceMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - removeAllTransToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); - DrawTileLabel = new System.Windows.Forms.ToolStripLabel(); - toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); - SelectedTileLabel = new System.Windows.Forms.ToolStripLabel(); - toolStripLabelCoord = new System.Windows.Forms.ToolStripLabel(); - toolStripBtnZoom = new System.Windows.Forms.ToolStripButton(); - toolStripSeparatorHelp = new System.Windows.Forms.ToolStripSeparator(); - toolStripBtnHelp = new System.Windows.Forms.ToolStripButton(); - toolTip1 = new System.Windows.Forms.ToolTip(components); - FloatingPreviewPanel = new System.Windows.Forms.Panel(); - TC_MultiEditorToolbox.SuspendLayout(); - tileTab.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)splitContainer4).BeginInit(); - splitContainer4.Panel1.SuspendLayout(); - splitContainer4.Panel2.SuspendLayout(); - splitContainer4.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)pictureBoxDrawTiles).BeginInit(); - designTab.SuspendLayout(); - groupBox1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Size_Width).BeginInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Size_Height).BeginInit(); - importTab.SuspendLayout(); - Save.SuspendLayout(); - groupBox4.SuspendLayout(); - groupBox2.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)splitContainer1).BeginInit(); - splitContainer1.Panel1.SuspendLayout(); - splitContainer1.Panel2.SuspendLayout(); - splitContainer1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)splitContainer3).BeginInit(); - splitContainer3.Panel1.SuspendLayout(); - splitContainer3.Panel2.SuspendLayout(); - splitContainer3.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Floor).BeginInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Z).BeginInit(); - Selectedpanel.SuspendLayout(); - groupBox3.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Selected_Z).BeginInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Selected_Y).BeginInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Selected_X).BeginInit(); - ((System.ComponentModel.ISupportInitialize)splitContainer2).BeginInit(); - splitContainer2.Panel1.SuspendLayout(); - splitContainer2.Panel2.SuspendLayout(); - splitContainer2.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)MaxHeightTrackBar).BeginInit(); - ((System.ComponentModel.ISupportInitialize)pictureBoxMinimap).BeginInit(); - ((System.ComponentModel.ISupportInitialize)pictureBoxMulti).BeginInit(); - toolStrip1.SuspendLayout(); - SuspendLayout(); - // - // TC_MultiEditorToolbox - // - TC_MultiEditorToolbox.Controls.Add(tileTab); - TC_MultiEditorToolbox.Controls.Add(designTab); - TC_MultiEditorToolbox.Controls.Add(importTab); - TC_MultiEditorToolbox.Controls.Add(Save); - TC_MultiEditorToolbox.Dock = System.Windows.Forms.DockStyle.Fill; - TC_MultiEditorToolbox.Location = new System.Drawing.Point(0, 104); - TC_MultiEditorToolbox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - TC_MultiEditorToolbox.Name = "TC_MultiEditorToolbox"; - TC_MultiEditorToolbox.SelectedIndex = 0; - TC_MultiEditorToolbox.Size = new System.Drawing.Size(280, 284); - TC_MultiEditorToolbox.TabIndex = 0; - // - // tileTab - // - tileTab.BackColor = System.Drawing.SystemColors.Window; - tileTab.Controls.Add(splitContainer4); - tileTab.Location = new System.Drawing.Point(4, 24); - tileTab.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - tileTab.Name = "tileTab"; - tileTab.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - tileTab.Size = new System.Drawing.Size(272, 256); - tileTab.TabIndex = 0; - tileTab.Text = "Tiles"; - tileTab.UseVisualStyleBackColor = true; - // - // splitContainer4 - // - splitContainer4.Dock = System.Windows.Forms.DockStyle.Fill; - splitContainer4.Location = new System.Drawing.Point(4, 3); - splitContainer4.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - splitContainer4.Name = "splitContainer4"; - splitContainer4.Orientation = System.Windows.Forms.Orientation.Horizontal; - // - // splitContainer4.Panel1 - // - splitContainer4.Panel1.Controls.Add(treeViewTilesXML); - // - // splitContainer4.Panel2 - // - splitContainer4.Panel2.Controls.Add(pictureBoxDrawTiles); - splitContainer4.Panel2.Controls.Add(vScrollBarDrawTiles); - splitContainer4.Panel2.Controls.Add(textBoxDrawTilesFilter); - splitContainer4.Size = new System.Drawing.Size(264, 250); - splitContainer4.SplitterDistance = 112; - splitContainer4.SplitterWidth = 5; - splitContainer4.TabIndex = 0; - // - // treeViewTilesXML - // - treeViewTilesXML.ContextMenuStrip = DummyContextMenu; - treeViewTilesXML.Dock = System.Windows.Forms.DockStyle.Fill; - treeViewTilesXML.HideSelection = false; - treeViewTilesXML.Location = new System.Drawing.Point(0, 0); - treeViewTilesXML.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - treeViewTilesXML.Name = "treeViewTilesXML"; - treeViewTilesXML.Size = new System.Drawing.Size(264, 112); - treeViewTilesXML.TabIndex = 0; - treeViewTilesXML.AfterSelect += TreeViewTilesXML_OnAfterSelect; - // - // DummyContextMenu - // - DummyContextMenu.Name = "DummyContextMenu"; - DummyContextMenu.Size = new System.Drawing.Size(61, 4); - DummyContextMenu.Opening += OnDummyContextMenuOpening; - // - // pictureBoxDrawTiles - // - pictureBoxDrawTiles.ContextMenuStrip = DummyContextMenu; - pictureBoxDrawTiles.Dock = System.Windows.Forms.DockStyle.Fill; - pictureBoxDrawTiles.Location = new System.Drawing.Point(0, 0); - pictureBoxDrawTiles.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - pictureBoxDrawTiles.Name = "pictureBoxDrawTiles"; - pictureBoxDrawTiles.Size = new System.Drawing.Size(247, 133); - pictureBoxDrawTiles.TabIndex = 3; - pictureBoxDrawTiles.TabStop = false; - pictureBoxDrawTiles.SizeChanged += PictureBoxDrawTiles_OnResize; - pictureBoxDrawTiles.Paint += PictureBoxDrawTiles_OnPaint; - pictureBoxDrawTiles.MouseClick += PictureBoxDrawTiles_OnMouseClick; - pictureBoxDrawTiles.MouseLeave += PictureBoxDrawTilesMouseLeave; - pictureBoxDrawTiles.MouseMove += PictureBoxDrawTilesMouseMove; - // - // vScrollBarDrawTiles - // - vScrollBarDrawTiles.Dock = System.Windows.Forms.DockStyle.Right; - vScrollBarDrawTiles.Location = new System.Drawing.Point(247, 0); - vScrollBarDrawTiles.Name = "vScrollBarDrawTiles"; - vScrollBarDrawTiles.Size = new System.Drawing.Size(17, 133); - vScrollBarDrawTiles.TabIndex = 0; - vScrollBarDrawTiles.Scroll += VScrollBarDrawTiles_Scroll; - // - // textBoxDrawTilesFilter - // - textBoxDrawTilesFilter.Dock = System.Windows.Forms.DockStyle.Top; - textBoxDrawTilesFilter.Location = new System.Drawing.Point(0, 0); - textBoxDrawTilesFilter.Name = "textBoxDrawTilesFilter"; - textBoxDrawTilesFilter.PlaceholderText = "Filter by name or 0x id"; - textBoxDrawTilesFilter.Size = new System.Drawing.Size(264, 23); - textBoxDrawTilesFilter.TabIndex = 1; - textBoxDrawTilesFilter.TextChanged += TextBoxDrawTilesFilter_TextChanged; - // - // designTab - // - designTab.BackColor = System.Drawing.SystemColors.Window; - designTab.Controls.Add(groupBox1); - designTab.Location = new System.Drawing.Point(4, 24); - designTab.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - designTab.Name = "designTab"; - designTab.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - designTab.Size = new System.Drawing.Size(272, 256); - designTab.TabIndex = 1; - designTab.Text = "Design"; - designTab.UseVisualStyleBackColor = true; - // - // groupBox1 - // - groupBox1.BackColor = System.Drawing.Color.Transparent; - groupBox1.Controls.Add(BTN_CreateBlank); - groupBox1.Controls.Add(numericUpDown_Size_Width); - groupBox1.Controls.Add(BTN_Resize); - groupBox1.Controls.Add(numericUpDown_Size_Height); - groupBox1.Location = new System.Drawing.Point(7, 7); - groupBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox1.Name = "groupBox1"; - groupBox1.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox1.Size = new System.Drawing.Size(210, 90); - groupBox1.TabIndex = 3; - groupBox1.TabStop = false; - groupBox1.Text = "Multi Size"; - // - // BTN_CreateBlank - // - BTN_CreateBlank.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - BTN_CreateBlank.Location = new System.Drawing.Point(110, 51); - BTN_CreateBlank.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_CreateBlank.Name = "BTN_CreateBlank"; - BTN_CreateBlank.Size = new System.Drawing.Size(92, 27); - BTN_CreateBlank.TabIndex = 3; - BTN_CreateBlank.Text = "Create Blank"; - BTN_CreateBlank.UseVisualStyleBackColor = true; - BTN_CreateBlank.Click += BTN_CreateBlank_Click; - // - // numericUpDown_Size_Width - // - numericUpDown_Size_Width.Location = new System.Drawing.Point(41, 22); - numericUpDown_Size_Width.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Size_Width.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); - numericUpDown_Size_Width.Name = "numericUpDown_Size_Width"; - numericUpDown_Size_Width.Size = new System.Drawing.Size(61, 23); - numericUpDown_Size_Width.TabIndex = 0; - // - // BTN_Resize - // - BTN_Resize.Location = new System.Drawing.Point(14, 51); - BTN_Resize.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Resize.Name = "BTN_Resize"; - BTN_Resize.Size = new System.Drawing.Size(88, 27); - BTN_Resize.TabIndex = 2; - BTN_Resize.Text = "Resize Multi"; - BTN_Resize.UseVisualStyleBackColor = true; - BTN_Resize.Click += BTN_ResizeMulti_Click; - // - // numericUpDown_Size_Height - // - numericUpDown_Size_Height.Location = new System.Drawing.Point(110, 22); - numericUpDown_Size_Height.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Size_Height.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); - numericUpDown_Size_Height.Name = "numericUpDown_Size_Height"; - numericUpDown_Size_Height.Size = new System.Drawing.Size(61, 23); - numericUpDown_Size_Height.TabIndex = 1; - // - // importTab - // - importTab.BackColor = System.Drawing.SystemColors.Window; - importTab.Controls.Add(treeViewMultiList); - importTab.Location = new System.Drawing.Point(4, 24); - importTab.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - importTab.Name = "importTab"; - importTab.Size = new System.Drawing.Size(272, 256); - importTab.TabIndex = 2; - importTab.Text = "Import"; - importTab.UseVisualStyleBackColor = true; - // - // treeViewMultiList - // - treeViewMultiList.ContextMenuStrip = DummyContextMenu; - treeViewMultiList.Dock = System.Windows.Forms.DockStyle.Fill; - treeViewMultiList.HideSelection = false; - treeViewMultiList.HotTracking = true; - treeViewMultiList.Location = new System.Drawing.Point(0, 0); - treeViewMultiList.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - treeViewMultiList.Name = "treeViewMultiList"; - treeViewMultiList.Size = new System.Drawing.Size(272, 256); - treeViewMultiList.TabIndex = 0; - treeViewMultiList.NodeMouseHover += TreeViewMultiList_NodeMouseHover; - treeViewMultiList.NodeMouseDoubleClick += TreeViewMultiList_NodeMouseDoubleClick; - // - // Save - // - Save.Controls.Add(groupBox4); - Save.Controls.Add(groupBox2); - Save.Location = new System.Drawing.Point(4, 24); - Save.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - Save.Name = "Save"; - Save.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - Save.Size = new System.Drawing.Size(272, 256); - Save.TabIndex = 3; - Save.Text = "Save"; - Save.UseVisualStyleBackColor = true; - // - // groupBox4 - // - groupBox4.BackColor = System.Drawing.Color.Transparent; - groupBox4.Controls.Add(BTN_Export_XML); - groupBox4.Controls.Add(BTN_Export_UOX3); - groupBox4.Controls.Add(BTN_Export_CSV); - groupBox4.Controls.Add(BTN_Export_WSC); - groupBox4.Controls.Add(BTN_Export_UOA); - groupBox4.Controls.Add(textBox_Export); - groupBox4.Controls.Add(BTN_Export_Txt); - groupBox4.Location = new System.Drawing.Point(8, 82); - groupBox4.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox4.Name = "groupBox4"; - groupBox4.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox4.Size = new System.Drawing.Size(209, 129); - groupBox4.TabIndex = 6; - groupBox4.TabStop = false; - groupBox4.Text = "Export"; - // - // BTN_Export_XML - // - BTN_Export_XML.Location = new System.Drawing.Point(149, 86); - BTN_Export_XML.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Export_XML.Name = "BTN_Export_XML"; - BTN_Export_XML.Size = new System.Drawing.Size(47, 27); - BTN_Export_XML.TabIndex = 6; - BTN_Export_XML.Text = ".xml"; - BTN_Export_XML.UseVisualStyleBackColor = true; - BTN_Export_XML.Click += BTN_Export_XML_Click; - // - // BTN_Export_UOX3 - // - BTN_Export_UOX3.Location = new System.Drawing.Point(66, 87); - BTN_Export_UOX3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Export_UOX3.Name = "BTN_Export_UOX3"; - BTN_Export_UOX3.Size = new System.Drawing.Size(75, 27); - BTN_Export_UOX3.TabIndex = 5; - BTN_Export_UOX3.Text = ".uox3"; - BTN_Export_UOX3.UseVisualStyleBackColor = true; - BTN_Export_UOX3.Click += BTN_Export_UOX3_Click; - // - // BTN_Export_CSV - // - BTN_Export_CSV.Location = new System.Drawing.Point(12, 87); - BTN_Export_CSV.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Export_CSV.Name = "BTN_Export_CSV"; - BTN_Export_CSV.Size = new System.Drawing.Size(47, 27); - BTN_Export_CSV.TabIndex = 4; - BTN_Export_CSV.Text = ".csv"; - BTN_Export_CSV.UseVisualStyleBackColor = true; - BTN_Export_CSV.Click += BTN_Export_CSV_OnClick; - // - // BTN_Export_WSC - // - BTN_Export_WSC.Location = new System.Drawing.Point(149, 53); - BTN_Export_WSC.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Export_WSC.Name = "BTN_Export_WSC"; - BTN_Export_WSC.Size = new System.Drawing.Size(47, 27); - BTN_Export_WSC.TabIndex = 3; - BTN_Export_WSC.Text = ".wsc"; - BTN_Export_WSC.UseVisualStyleBackColor = true; - BTN_Export_WSC.Click += BTN_Export_WSC_OnClick; - // - // BTN_Export_UOA - // - BTN_Export_UOA.Location = new System.Drawing.Point(65, 53); - BTN_Export_UOA.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Export_UOA.Name = "BTN_Export_UOA"; - BTN_Export_UOA.Size = new System.Drawing.Size(76, 27); - BTN_Export_UOA.TabIndex = 2; - BTN_Export_UOA.Text = ".uoa.txt"; - BTN_Export_UOA.UseVisualStyleBackColor = true; - BTN_Export_UOA.Click += BTN_Export_UOA_OnClick; - // - // textBox_Export - // - textBox_Export.Location = new System.Drawing.Point(7, 22); - textBox_Export.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - textBox_Export.Name = "textBox_Export"; - textBox_Export.Size = new System.Drawing.Size(194, 23); - textBox_Export.TabIndex = 1; - toolTip1.SetToolTip(textBox_Export, "FileName"); - // - // BTN_Export_Txt - // - BTN_Export_Txt.Location = new System.Drawing.Point(12, 53); - BTN_Export_Txt.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Export_Txt.Name = "BTN_Export_Txt"; - BTN_Export_Txt.Size = new System.Drawing.Size(47, 27); - BTN_Export_Txt.TabIndex = 0; - BTN_Export_Txt.Text = ".txt"; - BTN_Export_Txt.UseVisualStyleBackColor = true; - BTN_Export_Txt.Click += BTN_Export_TXT_OnClick; - // - // groupBox2 - // - groupBox2.BackColor = System.Drawing.Color.Transparent; - groupBox2.Controls.Add(textBox_SaveToID); - groupBox2.Controls.Add(BTN_Save); - groupBox2.Location = new System.Drawing.Point(8, 7); - groupBox2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox2.Name = "groupBox2"; - groupBox2.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox2.Size = new System.Drawing.Size(209, 68); - groupBox2.TabIndex = 5; - groupBox2.TabStop = false; - groupBox2.Text = "Save"; - // - // textBox_SaveToID - // - textBox_SaveToID.Location = new System.Drawing.Point(107, 25); - textBox_SaveToID.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - textBox_SaveToID.Name = "textBox_SaveToID"; - textBox_SaveToID.Size = new System.Drawing.Size(76, 23); - textBox_SaveToID.TabIndex = 1; - // - // BTN_Save - // - BTN_Save.Location = new System.Drawing.Point(8, 23); - BTN_Save.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Save.Name = "BTN_Save"; - BTN_Save.Size = new System.Drawing.Size(88, 27); - BTN_Save.TabIndex = 0; - BTN_Save.Text = "Save to ID"; - BTN_Save.UseVisualStyleBackColor = true; - BTN_Save.Click += BTN_Save_Click; - // - // splitContainer1 - // - splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; - splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; - splitContainer1.Location = new System.Drawing.Point(0, 0); - splitContainer1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - splitContainer1.Name = "splitContainer1"; - // - // splitContainer1.Panel1 - // - splitContainer1.Panel1.Controls.Add(splitContainer3); - // - // splitContainer1.Panel2 - // - splitContainer1.Panel2.Controls.Add(splitContainer2); - splitContainer1.Panel2.Controls.Add(toolStrip1); - splitContainer1.Size = new System.Drawing.Size(800, 480); - splitContainer1.SplitterDistance = 280; - splitContainer1.SplitterWidth = 5; - splitContainer1.TabIndex = 1; - // - // splitContainer3 - // - splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill; - splitContainer3.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; - splitContainer3.IsSplitterFixed = true; - splitContainer3.Location = new System.Drawing.Point(0, 0); - splitContainer3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - splitContainer3.Name = "splitContainer3"; - splitContainer3.Orientation = System.Windows.Forms.Orientation.Horizontal; - // - // splitContainer3.Panel1 - // - splitContainer3.Panel1.Controls.Add(brushSizeLabel); - splitContainer3.Panel1.Controls.Add(BTN_RectFill); - splitContainer3.Panel1.Controls.Add(BTN_LineDraw); - splitContainer3.Panel1.Controls.Add(RB_Brush_S); - splitContainer3.Panel1.Controls.Add(RB_Brush_M); - splitContainer3.Panel1.Controls.Add(RB_Brush_L); - splitContainer3.Panel1.Controls.Add(BTN_Trans); - splitContainer3.Panel1.Controls.Add(BTN_Pipette); - splitContainer3.Panel1.Controls.Add(BTN_Floor); - splitContainer3.Panel1.Controls.Add(BTN_Z); - splitContainer3.Panel1.Controls.Add(BTN_Remove); - splitContainer3.Panel1.Controls.Add(BTN_Draw); - splitContainer3.Panel1.Controls.Add(BTN_Select); - splitContainer3.Panel1.Controls.Add(numericUpDown_Floor); - splitContainer3.Panel1.Controls.Add(numericUpDown_Z); - // - // splitContainer3.Panel2 - // - splitContainer3.Panel2.Controls.Add(TC_MultiEditorToolbox); - splitContainer3.Panel2.Controls.Add(collapsibleSplitter1); - splitContainer3.Panel2.Controls.Add(Selectedpanel); - splitContainer3.Size = new System.Drawing.Size(280, 480); - splitContainer3.SplitterDistance = 90; - splitContainer3.SplitterWidth = 2; - splitContainer3.TabIndex = 1; - // - // brushSizeLabel - // - brushSizeLabel.AutoSize = true; - brushSizeLabel.Location = new System.Drawing.Point(68, 62); - brushSizeLabel.Name = "brushSizeLabel"; - brushSizeLabel.Size = new System.Drawing.Size(62, 15); - brushSizeLabel.TabIndex = 22; - brushSizeLabel.Text = "Brush size:"; - // - // BTN_RectFill - // - BTN_RectFill.Appearance = System.Windows.Forms.Appearance.Button; - BTN_RectFill.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_RectFill.ImageKey = "RectFillButton.bmp"; - BTN_RectFill.ImageList = imageListTools; - BTN_RectFill.Location = new System.Drawing.Point(5, 57); - BTN_RectFill.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_RectFill.Name = "BTN_RectFill"; - BTN_RectFill.Size = new System.Drawing.Size(24, 24); - BTN_RectFill.TabIndex = 17; - toolTip1.SetToolTip(BTN_RectFill, "Rectangle Fill [B]"); - BTN_RectFill.UseVisualStyleBackColor = true; - BTN_RectFill.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_RectFill.Click += BTN_RectFill_Click; - // - // imageListTools - // - imageListTools.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; - imageListTools.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("imageListTools.ImageStream"); - imageListTools.TransparentColor = System.Drawing.Color.Transparent; - imageListTools.Images.SetKeyName(0, "AltitudeButton.bmp"); - imageListTools.Images.SetKeyName(1, "DrawButton.bmp"); - imageListTools.Images.SetKeyName(2, "RemoveButton.bmp"); - imageListTools.Images.SetKeyName(3, "SelectButton.bmp"); - imageListTools.Images.SetKeyName(4, "AltitudeButton_Selected.bmp"); - imageListTools.Images.SetKeyName(5, "DrawButton_Selected.bmp"); - imageListTools.Images.SetKeyName(6, "RemoveButton_Selected.bmp"); - imageListTools.Images.SetKeyName(7, "SelectButton_Selected.bmp"); - imageListTools.Images.SetKeyName(8, "VirtualFloorButton.bmp"); - imageListTools.Images.SetKeyName(9, "VirtualFloorButton_Selected.bmp"); - imageListTools.Images.SetKeyName(10, "PipetteButton.bmp"); - imageListTools.Images.SetKeyName(11, "PipetteButton_Selected.bmp"); - imageListTools.Images.SetKeyName(12, "TransButton_Selected.bmp"); - imageListTools.Images.SetKeyName(13, "TransButton.bmp"); - imageListTools.Images.SetKeyName(14, "LineDrawButton.bmp"); - imageListTools.Images.SetKeyName(15, "LineDrawButton_Selected.bmp"); - imageListTools.Images.SetKeyName(16, "RectFillButton.bmp"); - imageListTools.Images.SetKeyName(17, "RectFillButton_Selected.bmp"); - // - // BTN_LineDraw - // - BTN_LineDraw.Appearance = System.Windows.Forms.Appearance.Button; - BTN_LineDraw.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_LineDraw.ImageKey = "LineDrawButton.bmp"; - BTN_LineDraw.ImageList = imageListTools; - BTN_LineDraw.Location = new System.Drawing.Point(36, 57); - BTN_LineDraw.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_LineDraw.Name = "BTN_LineDraw"; - BTN_LineDraw.Size = new System.Drawing.Size(24, 24); - BTN_LineDraw.TabIndex = 18; - toolTip1.SetToolTip(BTN_LineDraw, "Line Draw [L]"); - BTN_LineDraw.UseVisualStyleBackColor = true; - BTN_LineDraw.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_LineDraw.Click += BTN_LineDraw_Click; - // - // RB_Brush_S - // - RB_Brush_S.Appearance = System.Windows.Forms.Appearance.Button; - RB_Brush_S.Checked = true; - RB_Brush_S.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - RB_Brush_S.Location = new System.Drawing.Point(137, 57); - RB_Brush_S.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - RB_Brush_S.Name = "RB_Brush_S"; - RB_Brush_S.Size = new System.Drawing.Size(26, 24); - RB_Brush_S.TabIndex = 19; - RB_Brush_S.TabStop = true; - RB_Brush_S.Text = "S"; - RB_Brush_S.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; - toolTip1.SetToolTip(RB_Brush_S, "Small brush (1x1)"); - RB_Brush_S.UseVisualStyleBackColor = true; - // - // RB_Brush_M - // - RB_Brush_M.Appearance = System.Windows.Forms.Appearance.Button; - RB_Brush_M.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - RB_Brush_M.Location = new System.Drawing.Point(165, 57); - RB_Brush_M.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - RB_Brush_M.Name = "RB_Brush_M"; - RB_Brush_M.Size = new System.Drawing.Size(26, 24); - RB_Brush_M.TabIndex = 20; - RB_Brush_M.Text = "M"; - RB_Brush_M.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; - toolTip1.SetToolTip(RB_Brush_M, "Medium brush (3x3)"); - RB_Brush_M.UseVisualStyleBackColor = true; - // - // RB_Brush_L - // - RB_Brush_L.Appearance = System.Windows.Forms.Appearance.Button; - RB_Brush_L.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - RB_Brush_L.Location = new System.Drawing.Point(193, 57); - RB_Brush_L.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - RB_Brush_L.Name = "RB_Brush_L"; - RB_Brush_L.Size = new System.Drawing.Size(26, 24); - RB_Brush_L.TabIndex = 21; - RB_Brush_L.Text = "L"; - RB_Brush_L.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; - toolTip1.SetToolTip(RB_Brush_L, "Large brush (5x5)"); - RB_Brush_L.UseVisualStyleBackColor = true; - // - // BTN_Trans - // - BTN_Trans.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Trans.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Trans.ImageKey = "TransButton.bmp"; - BTN_Trans.ImageList = imageListTools; - BTN_Trans.Location = new System.Drawing.Point(102, 30); - BTN_Trans.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Trans.Name = "BTN_Trans"; - BTN_Trans.Size = new System.Drawing.Size(24, 24); - BTN_Trans.TabIndex = 15; - toolTip1.SetToolTip(BTN_Trans, "Switch Transparent [T]"); - BTN_Trans.UseVisualStyleBackColor = true; - BTN_Trans.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Trans.Click += BTN_Trans_Clicked; - // - // BTN_Pipette - // - BTN_Pipette.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Pipette.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Pipette.ImageKey = "PipetteButton.bmp"; - BTN_Pipette.ImageList = imageListTools; - BTN_Pipette.Location = new System.Drawing.Point(98, 3); - BTN_Pipette.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Pipette.Name = "BTN_Pipette"; - BTN_Pipette.Size = new System.Drawing.Size(24, 24); - BTN_Pipette.TabIndex = 14; - toolTip1.SetToolTip(BTN_Pipette, "Pick A Tile [P]"); - BTN_Pipette.UseVisualStyleBackColor = true; - BTN_Pipette.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Pipette.Click += BTN_Pipette_Click; - // - // BTN_Floor - // - BTN_Floor.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Floor.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Floor.ImageKey = "VirtualFloorButton.bmp"; - BTN_Floor.ImageList = imageListTools; - BTN_Floor.Location = new System.Drawing.Point(5, 30); - BTN_Floor.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Floor.Name = "BTN_Floor"; - BTN_Floor.Size = new System.Drawing.Size(24, 24); - BTN_Floor.TabIndex = 13; - toolTip1.SetToolTip(BTN_Floor, "Draw Virtual Floor [F]"); - BTN_Floor.UseVisualStyleBackColor = true; - BTN_Floor.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Floor.Click += BTN_Floor_Clicked; - // - // BTN_Z - // - BTN_Z.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Z.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Z.ImageKey = "AltitudeButton.bmp"; - BTN_Z.ImageList = imageListTools; - BTN_Z.Location = new System.Drawing.Point(130, 3); - BTN_Z.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Z.Name = "BTN_Z"; - BTN_Z.Size = new System.Drawing.Size(24, 24); - BTN_Z.TabIndex = 12; - toolTip1.SetToolTip(BTN_Z, "Apply Z Level [E]"); - BTN_Z.UseVisualStyleBackColor = true; - BTN_Z.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Z.Click += BTN_Z_Click; - // - // BTN_Remove - // - BTN_Remove.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Remove.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Remove.ImageKey = "RemoveButton.bmp"; - BTN_Remove.ImageList = imageListTools; - BTN_Remove.Location = new System.Drawing.Point(68, 3); - BTN_Remove.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Remove.Name = "BTN_Remove"; - BTN_Remove.Size = new System.Drawing.Size(24, 24); - BTN_Remove.TabIndex = 11; - toolTip1.SetToolTip(BTN_Remove, "Remove A Tile [R]"); - BTN_Remove.UseVisualStyleBackColor = true; - BTN_Remove.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Remove.Click += BTN_Remove_Click; - // - // BTN_Draw - // - BTN_Draw.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Draw.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Draw.ImageKey = "DrawButton.bmp"; - BTN_Draw.ImageList = imageListTools; - BTN_Draw.Location = new System.Drawing.Point(36, 3); - BTN_Draw.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Draw.Name = "BTN_Draw"; - BTN_Draw.Size = new System.Drawing.Size(24, 24); - BTN_Draw.TabIndex = 10; - toolTip1.SetToolTip(BTN_Draw, "Draw A Tile [D]"); - BTN_Draw.UseVisualStyleBackColor = true; - BTN_Draw.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Draw.Click += BTN_Draw_Click; - // - // BTN_Select - // - BTN_Select.Appearance = System.Windows.Forms.Appearance.Button; - BTN_Select.Checked = true; - BTN_Select.CheckState = System.Windows.Forms.CheckState.Checked; - BTN_Select.FlatStyle = System.Windows.Forms.FlatStyle.Popup; - BTN_Select.ImageKey = "SelectButton.bmp"; - BTN_Select.ImageList = imageListTools; - BTN_Select.Location = new System.Drawing.Point(5, 3); - BTN_Select.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - BTN_Select.Name = "BTN_Select"; - BTN_Select.Size = new System.Drawing.Size(24, 24); - BTN_Select.TabIndex = 9; - toolTip1.SetToolTip(BTN_Select, "Select A Tile [S]"); - BTN_Select.UseVisualStyleBackColor = true; - BTN_Select.CheckStateChanged += BTN_Toolbox_CheckedChanged; - BTN_Select.Click += BTN_Select_Click; - // - // numericUpDown_Floor - // - numericUpDown_Floor.Location = new System.Drawing.Point(36, 32); - numericUpDown_Floor.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Floor.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); - numericUpDown_Floor.Minimum = new decimal(new int[] { 128, 0, 0, int.MinValue }); - numericUpDown_Floor.Name = "numericUpDown_Floor"; - numericUpDown_Floor.Size = new System.Drawing.Size(58, 23); - numericUpDown_Floor.TabIndex = 8; - numericUpDown_Floor.ValueChanged += NumericUpDown_Floor_Changed; - // - // numericUpDown_Z - // - numericUpDown_Z.Location = new System.Drawing.Point(161, 6); - numericUpDown_Z.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Z.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); - numericUpDown_Z.Minimum = new decimal(new int[] { 128, 0, 0, int.MinValue }); - numericUpDown_Z.Name = "numericUpDown_Z"; - numericUpDown_Z.Size = new System.Drawing.Size(58, 23); - numericUpDown_Z.TabIndex = 5; - // - // collapsibleSplitter1 - // - collapsibleSplitter1.AnimationDelay = 20; - collapsibleSplitter1.AnimationStep = 20; - collapsibleSplitter1.BorderStyle3D = System.Windows.Forms.Border3DStyle.Flat; - collapsibleSplitter1.ControlToHide = Selectedpanel; - collapsibleSplitter1.Dock = System.Windows.Forms.DockStyle.Top; - collapsibleSplitter1.ExpandParentForm = false; - collapsibleSplitter1.Location = new System.Drawing.Point(0, 96); - collapsibleSplitter1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - collapsibleSplitter1.Name = "collapsibleSplitter1"; - collapsibleSplitter1.Size = new System.Drawing.Size(280, 8); - collapsibleSplitter1.TabIndex = 5; - collapsibleSplitter1.TabStop = false; - toolTip1.SetToolTip(collapsibleSplitter1, "Selected Tile Panel"); - collapsibleSplitter1.UseAnimations = true; - collapsibleSplitter1.VisualStyle = UoFiddler.Controls.UserControls.VisualStyles.DoubleDots; - // - // Selectedpanel - // - Selectedpanel.Controls.Add(groupBox3); - Selectedpanel.Dock = System.Windows.Forms.DockStyle.Top; - Selectedpanel.Location = new System.Drawing.Point(0, 0); - Selectedpanel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - Selectedpanel.Name = "Selectedpanel"; - Selectedpanel.Size = new System.Drawing.Size(280, 96); - Selectedpanel.TabIndex = 6; - // - // groupBox3 - // - groupBox3.Controls.Add(DynamiccheckBox); - groupBox3.Controls.Add(numericUpDown_Selected_Z); - groupBox3.Controls.Add(numericUpDown_Selected_Y); - groupBox3.Controls.Add(numericUpDown_Selected_X); - groupBox3.Location = new System.Drawing.Point(13, 3); - groupBox3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox3.Name = "groupBox3"; - groupBox3.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - groupBox3.Size = new System.Drawing.Size(209, 87); - groupBox3.TabIndex = 0; - groupBox3.TabStop = false; - groupBox3.Text = "Selected Tile X,Y,Z"; - // - // DynamiccheckBox - // - DynamiccheckBox.AutoSize = true; - DynamiccheckBox.Location = new System.Drawing.Point(117, 54); - DynamiccheckBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - DynamiccheckBox.Name = "DynamiccheckBox"; - DynamiccheckBox.Size = new System.Drawing.Size(69, 19); - DynamiccheckBox.TabIndex = 3; - DynamiccheckBox.Text = "Invisible"; - DynamiccheckBox.UseVisualStyleBackColor = true; - DynamiccheckBox.CheckedChanged += BTN_DynamicCheckBox_Changed; - // - // numericUpDown_Selected_Z - // - numericUpDown_Selected_Z.Location = new System.Drawing.Point(23, 53); - numericUpDown_Selected_Z.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Selected_Z.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); - numericUpDown_Selected_Z.Minimum = new decimal(new int[] { 128, 0, 0, int.MinValue }); - numericUpDown_Selected_Z.Name = "numericUpDown_Selected_Z"; - numericUpDown_Selected_Z.Size = new System.Drawing.Size(71, 23); - numericUpDown_Selected_Z.TabIndex = 2; - numericUpDown_Selected_Z.ValueChanged += NumericUpDown_Selected_Z_Changed; - // - // numericUpDown_Selected_Y - // - numericUpDown_Selected_Y.Location = new System.Drawing.Point(117, 23); - numericUpDown_Selected_Y.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Selected_Y.Name = "numericUpDown_Selected_Y"; - numericUpDown_Selected_Y.Size = new System.Drawing.Size(71, 23); - numericUpDown_Selected_Y.TabIndex = 1; - numericUpDown_Selected_Y.ValueChanged += NumericUpDown_Selected_Y_Changed; - // - // numericUpDown_Selected_X - // - numericUpDown_Selected_X.Location = new System.Drawing.Point(23, 23); - numericUpDown_Selected_X.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - numericUpDown_Selected_X.Name = "numericUpDown_Selected_X"; - numericUpDown_Selected_X.Size = new System.Drawing.Size(71, 23); - numericUpDown_Selected_X.TabIndex = 0; - numericUpDown_Selected_X.ValueChanged += NumericUpDown_Selected_X_Changed; - // - // splitContainer2 - // - splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; - splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; - splitContainer2.IsSplitterFixed = true; - splitContainer2.Location = new System.Drawing.Point(0, 0); - splitContainer2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - splitContainer2.Name = "splitContainer2"; - splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; - // - // splitContainer2.Panel1 - // - splitContainer2.Panel1.Controls.Add(MaxHeightTrackBar); - // - // splitContainer2.Panel2 - // - splitContainer2.Panel2.Controls.Add(splitter1); - splitContainer2.Panel2.Controls.Add(pictureBoxMinimap); - splitContainer2.Panel2.Controls.Add(pictureBoxMulti); - splitContainer2.Panel2.Controls.Add(hScrollBar); - splitContainer2.Panel2.Controls.Add(vScrollBar); - splitContainer2.Size = new System.Drawing.Size(515, 455); - splitContainer2.SplitterDistance = 30; - splitContainer2.SplitterWidth = 5; - splitContainer2.TabIndex = 2; - // - // MaxHeightTrackBar - // - MaxHeightTrackBar.Dock = System.Windows.Forms.DockStyle.Fill; - MaxHeightTrackBar.Location = new System.Drawing.Point(0, 0); - MaxHeightTrackBar.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - MaxHeightTrackBar.Name = "MaxHeightTrackBar"; - MaxHeightTrackBar.Size = new System.Drawing.Size(515, 30); - MaxHeightTrackBar.TabIndex = 0; - toolTip1.SetToolTip(MaxHeightTrackBar, "Max Height Displayed"); - MaxHeightTrackBar.ValueChanged += MaxHeightTrackBarOnValueChanged; - // - // splitter1 - // - splitter1.Location = new System.Drawing.Point(0, 0); - splitter1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - splitter1.Name = "splitter1"; - splitter1.Size = new System.Drawing.Size(4, 403); - splitter1.TabIndex = 3; - splitter1.TabStop = false; - // - // pictureBoxMinimap - // - pictureBoxMinimap.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - pictureBoxMinimap.BackColor = System.Drawing.Color.DimGray; - pictureBoxMinimap.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - pictureBoxMinimap.Location = new System.Drawing.Point(342, 276); - pictureBoxMinimap.Name = "pictureBoxMinimap"; - pictureBoxMinimap.Size = new System.Drawing.Size(155, 100); - pictureBoxMinimap.TabIndex = 10; - pictureBoxMinimap.TabStop = false; - toolTip1.SetToolTip(pictureBoxMinimap, "Minimap — click to pan"); - pictureBoxMinimap.MouseClick += PictureBoxMinimap_OnMouseClick; - // - // pictureBoxMulti - // - pictureBoxMulti.BackColor = System.Drawing.Color.White; - pictureBoxMulti.ContextMenuStrip = DummyContextMenu; - pictureBoxMulti.Dock = System.Windows.Forms.DockStyle.Fill; - pictureBoxMulti.Location = new System.Drawing.Point(0, 0); - pictureBoxMulti.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - pictureBoxMulti.Name = "pictureBoxMulti"; - pictureBoxMulti.Size = new System.Drawing.Size(498, 403); - pictureBoxMulti.TabIndex = 0; - pictureBoxMulti.TabStop = false; - pictureBoxMulti.SizeChanged += PictureBoxMultiOnResize; - pictureBoxMulti.Paint += PictureBoxMultiOnPaint; - pictureBoxMulti.MouseDown += PictureBoxMultiOnMouseDown; - pictureBoxMulti.MouseMove += PictureBoxMultiOnMouseMove; - pictureBoxMulti.MouseUp += PictureBoxMultiOnMouseUp; - // - // hScrollBar - // - hScrollBar.Dock = System.Windows.Forms.DockStyle.Bottom; - hScrollBar.Location = new System.Drawing.Point(0, 403); - hScrollBar.Name = "hScrollBar"; - hScrollBar.Size = new System.Drawing.Size(498, 17); - hScrollBar.TabIndex = 2; - hScrollBar.ValueChanged += ScrollBarsValueChanged; - // - // vScrollBar - // - vScrollBar.Dock = System.Windows.Forms.DockStyle.Right; - vScrollBar.Location = new System.Drawing.Point(498, 0); - vScrollBar.Name = "vScrollBar"; - vScrollBar.Size = new System.Drawing.Size(17, 420); - vScrollBar.TabIndex = 1; - vScrollBar.ValueChanged += ScrollBarsValueChanged; - // - // toolStrip1 - // - toolStrip1.Dock = System.Windows.Forms.DockStyle.Bottom; - toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; - toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripDropDownButton1, toolStripSeparator2, DrawTileLabel, toolStripSeparator1, SelectedTileLabel, toolStripLabelCoord, toolStripBtnZoom, toolStripSeparatorHelp, toolStripBtnHelp }); - toolStrip1.Location = new System.Drawing.Point(0, 455); - toolStrip1.Name = "toolStrip1"; - toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; - toolStrip1.Size = new System.Drawing.Size(515, 25); - toolStrip1.TabIndex = 3; - toolStrip1.Text = "toolStrip1"; - // - // toolStripDropDownButton1 - // - toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { UndoItems, showWalkablesToolStripMenuItem, showDoubleSurfaceMenuItem, removeAllTransToolStripMenuItem }); - toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new System.Drawing.Size(45, 22); - toolStripDropDownButton1.Text = "Misc"; - // - // UndoItems - // - UndoItems.Name = "UndoItems"; - UndoItems.Size = new System.Drawing.Size(189, 22); - UndoItems.Text = "Undo"; - UndoItems.DropDownOpening += UndoList_BeforeOpening; - // - // showWalkablesToolStripMenuItem - // - showWalkablesToolStripMenuItem.CheckOnClick = true; - showWalkablesToolStripMenuItem.Name = "showWalkablesToolStripMenuItem"; - showWalkablesToolStripMenuItem.Size = new System.Drawing.Size(189, 22); - showWalkablesToolStripMenuItem.Text = "Show Walkable tiles"; - showWalkablesToolStripMenuItem.Click += BTN_ShowWalkables_Click; - // - // showDoubleSurfaceMenuItem - // - showDoubleSurfaceMenuItem.CheckOnClick = true; - showDoubleSurfaceMenuItem.Name = "showDoubleSurfaceMenuItem"; - showDoubleSurfaceMenuItem.Size = new System.Drawing.Size(189, 22); - showDoubleSurfaceMenuItem.Text = "Show double surface"; - showDoubleSurfaceMenuItem.Click += BTN_ShowDoubleSurface; - // - // removeAllTransToolStripMenuItem - // - removeAllTransToolStripMenuItem.Name = "removeAllTransToolStripMenuItem"; - removeAllTransToolStripMenuItem.Size = new System.Drawing.Size(189, 22); - removeAllTransToolStripMenuItem.Text = "Reset transparent tiles"; - removeAllTransToolStripMenuItem.Click += BTN_ShowAllTrans; - // - // toolStripSeparator2 - // - toolStripSeparator2.Name = "toolStripSeparator2"; - toolStripSeparator2.Size = new System.Drawing.Size(6, 25); - // - // DrawTileLabel - // - DrawTileLabel.AutoSize = false; - DrawTileLabel.Name = "DrawTileLabel"; - DrawTileLabel.Size = new System.Drawing.Size(100, 22); - DrawTileLabel.Text = "Draw ID:"; - DrawTileLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // toolStripSeparator1 - // - toolStripSeparator1.Name = "toolStripSeparator1"; - toolStripSeparator1.Size = new System.Drawing.Size(6, 25); - // - // SelectedTileLabel - // - SelectedTileLabel.Name = "SelectedTileLabel"; - SelectedTileLabel.Size = new System.Drawing.Size(21, 22); - SelectedTileLabel.Text = "ID:"; - // - // toolStripLabelCoord - // - toolStripLabelCoord.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - toolStripLabelCoord.Name = "toolStripLabelCoord"; - toolStripLabelCoord.Size = new System.Drawing.Size(31, 22); - toolStripLabelCoord.Text = "0,0,0"; - toolStripLabelCoord.ToolTipText = "Coordinates"; - // - // toolStripBtnZoom - // - toolStripBtnZoom.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - toolStripBtnZoom.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; - toolStripBtnZoom.Name = "toolStripBtnZoom"; - toolStripBtnZoom.Size = new System.Drawing.Size(39, 22); - toolStripBtnZoom.Text = "100%"; - toolStripBtnZoom.ToolTipText = "Zoom — click or Ctrl+0 to reset to 100%"; - toolStripBtnZoom.Click += ToolStripBtnZoom_Click; - // - // toolStripSeparatorHelp - // - toolStripSeparatorHelp.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - toolStripSeparatorHelp.Name = "toolStripSeparatorHelp"; - toolStripSeparatorHelp.Size = new System.Drawing.Size(6, 25); - // - // toolStripBtnHelp - // - toolStripBtnHelp.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; - toolStripBtnHelp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; - toolStripBtnHelp.Name = "toolStripBtnHelp"; - toolStripBtnHelp.Size = new System.Drawing.Size(36, 22); - toolStripBtnHelp.Text = "Help"; - toolStripBtnHelp.ToolTipText = "Keyboard Shortcuts"; - toolStripBtnHelp.Click += ToolStripBtnHelp_Click; - // - // FloatingPreviewPanel - // - FloatingPreviewPanel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; - FloatingPreviewPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - FloatingPreviewPanel.Location = new System.Drawing.Point(292, 77); - FloatingPreviewPanel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - FloatingPreviewPanel.Name = "FloatingPreviewPanel"; - FloatingPreviewPanel.Size = new System.Drawing.Size(233, 115); - FloatingPreviewPanel.TabIndex = 4; - // - // MultiEditorControl - // - AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - Controls.Add(FloatingPreviewPanel); - Controls.Add(splitContainer1); - DoubleBuffered = true; - Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - Name = "MultiEditorControl"; - Size = new System.Drawing.Size(800, 480); - Load += OnLoad; - TC_MultiEditorToolbox.ResumeLayout(false); - tileTab.ResumeLayout(false); - splitContainer4.Panel1.ResumeLayout(false); - splitContainer4.Panel2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)splitContainer4).EndInit(); - splitContainer4.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)pictureBoxDrawTiles).EndInit(); - designTab.ResumeLayout(false); - groupBox1.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Size_Width).EndInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Size_Height).EndInit(); - importTab.ResumeLayout(false); - Save.ResumeLayout(false); - groupBox4.ResumeLayout(false); - groupBox4.PerformLayout(); - groupBox2.ResumeLayout(false); - groupBox2.PerformLayout(); - splitContainer1.Panel1.ResumeLayout(false); - splitContainer1.Panel2.ResumeLayout(false); - splitContainer1.Panel2.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)splitContainer1).EndInit(); - splitContainer1.ResumeLayout(false); - splitContainer3.Panel1.ResumeLayout(false); - splitContainer3.Panel1.PerformLayout(); - splitContainer3.Panel2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)splitContainer3).EndInit(); - splitContainer3.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Floor).EndInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Z).EndInit(); - Selectedpanel.ResumeLayout(false); - groupBox3.ResumeLayout(false); - groupBox3.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Selected_Z).EndInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Selected_Y).EndInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDown_Selected_X).EndInit(); - splitContainer2.Panel1.ResumeLayout(false); - splitContainer2.Panel1.PerformLayout(); - splitContainer2.Panel2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)splitContainer2).EndInit(); - splitContainer2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)MaxHeightTrackBar).EndInit(); - ((System.ComponentModel.ISupportInitialize)pictureBoxMinimap).EndInit(); - ((System.ComponentModel.ISupportInitialize)pictureBoxMulti).EndInit(); - toolStrip1.ResumeLayout(false); - toolStrip1.PerformLayout(); - ResumeLayout(false); - } - - private System.Windows.Forms.Button BTN_CreateBlank; - private System.Windows.Forms.CheckBox BTN_Draw; - private System.Windows.Forms.Button BTN_Export_Txt; - private System.Windows.Forms.Button BTN_Export_UOA; - private System.Windows.Forms.Button BTN_Export_WSC; - private System.Windows.Forms.CheckBox BTN_Floor; - private System.Windows.Forms.CheckBox BTN_Pipette; - private System.Windows.Forms.CheckBox BTN_Remove; - private System.Windows.Forms.Button BTN_Resize; - private System.Windows.Forms.Button BTN_Save; - private System.Windows.Forms.CheckBox BTN_Select; - private System.Windows.Forms.CheckBox BTN_Trans; - private System.Windows.Forms.CheckBox BTN_Z; - private UoFiddler.Controls.UserControls.CollapsibleSplitter collapsibleSplitter1; - private System.Windows.Forms.TabPage designTab; - private System.Windows.Forms.ToolStripLabel DrawTileLabel; - private System.Windows.Forms.ContextMenuStrip DummyContextMenu; - private System.Windows.Forms.CheckBox DynamiccheckBox; - private System.Windows.Forms.Panel FloatingPreviewPanel; - private System.Windows.Forms.GroupBox groupBox1; - private System.Windows.Forms.GroupBox groupBox2; - private System.Windows.Forms.GroupBox groupBox3; - private System.Windows.Forms.GroupBox groupBox4; - private System.Windows.Forms.HScrollBar hScrollBar; - private System.Windows.Forms.ImageList imageListTools; - private System.Windows.Forms.TabPage importTab; - private System.Windows.Forms.TrackBar MaxHeightTrackBar; - private System.Windows.Forms.NumericUpDown numericUpDown_Floor; - private System.Windows.Forms.NumericUpDown numericUpDown_Selected_X; - private System.Windows.Forms.NumericUpDown numericUpDown_Selected_Y; - private System.Windows.Forms.NumericUpDown numericUpDown_Selected_Z; - private System.Windows.Forms.NumericUpDown numericUpDown_Size_Height; - private System.Windows.Forms.NumericUpDown numericUpDown_Size_Width; - private System.Windows.Forms.NumericUpDown numericUpDown_Z; - private System.Windows.Forms.PictureBox pictureBoxDrawTiles; - private System.Windows.Forms.TextBox textBoxDrawTilesFilter; - private System.Windows.Forms.PictureBox pictureBoxMulti; - private System.Windows.Forms.ToolStripMenuItem removeAllTransToolStripMenuItem; - private System.Windows.Forms.TabPage Save; - private System.Windows.Forms.Panel Selectedpanel; - private System.Windows.Forms.ToolStripLabel SelectedTileLabel; - private System.Windows.Forms.ToolStripMenuItem showDoubleSurfaceMenuItem; - private System.Windows.Forms.ToolStripMenuItem showWalkablesToolStripMenuItem; - private System.Windows.Forms.SplitContainer splitContainer1; - private System.Windows.Forms.SplitContainer splitContainer2; - private System.Windows.Forms.SplitContainer splitContainer3; - private System.Windows.Forms.SplitContainer splitContainer4; - private System.Windows.Forms.Splitter splitter1; - private System.Windows.Forms.TabControl TC_MultiEditorToolbox; - private System.Windows.Forms.TextBox textBox_Export; - private System.Windows.Forms.TextBox textBox_SaveToID; - private System.Windows.Forms.TabPage tileTab; - private System.Windows.Forms.ToolStrip toolStrip1; - private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; - private System.Windows.Forms.ToolStripLabel toolStripLabelCoord; - private System.Windows.Forms.ToolStripButton toolStripBtnZoom; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; - private System.Windows.Forms.ToolTip toolTip1; - private System.Windows.Forms.TreeView treeViewMultiList; - private System.Windows.Forms.TreeView treeViewTilesXML; - private System.Windows.Forms.ToolStripMenuItem UndoItems; - private System.Windows.Forms.CheckBox BTN_RectFill; - private System.Windows.Forms.CheckBox BTN_LineDraw; - private System.Windows.Forms.RadioButton RB_Brush_S; - private System.Windows.Forms.RadioButton RB_Brush_M; - private System.Windows.Forms.RadioButton RB_Brush_L; - private System.Windows.Forms.PictureBox pictureBoxMinimap; - private System.Windows.Forms.VScrollBar vScrollBar; - private System.Windows.Forms.VScrollBar vScrollBarDrawTiles; - - #endregion - - private System.Windows.Forms.Button BTN_Export_CSV; - private System.Windows.Forms.Button BTN_Export_UOX3; - private System.Windows.Forms.Button BTN_Export_XML; - private System.Windows.Forms.Label brushSizeLabel; - private System.Windows.Forms.ToolStripSeparator toolStripSeparatorHelp; - private System.Windows.Forms.ToolStripButton toolStripBtnHelp; - } -} diff --git a/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.cs deleted file mode 100644 index 63383c3d..00000000 --- a/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.cs +++ /dev/null @@ -1,2682 +0,0 @@ -/*************************************************************************** - * - * $Author: MuadDib & Turley - * - * "THE BEER-WARE LICENSE" - * As long as you retain this notice you can do whatever you want with - * this stuff. If we meet some day, and you think this stuff is worth it, - * you can buy me a beer in return. - * - ***************************************************************************/ - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Windows.Forms; -using System.Xml; -using Ultima; -using UoFiddler.Controls.Classes; -using UoFiddler.Controls.Forms; -using UoFiddler.Plugin.MultiEditor.Classes; -using UoFiddler.Plugin.MultiEditor.Forms; - -namespace UoFiddler.Plugin.MultiEditor.UserControls -{ - public partial class MultiEditorControl : UserControl - { - private MultiEditorComponentList _compList; - - //Sin/Cos(45°) - private static readonly double _coordinateTransform = Math.Sqrt(2) / 2; - private const int _drawTileSizeHeight = 45; - private const int _drawTileSizeWidth = 45; - private List _drawTilesList = new List(); - private readonly List _overlayList = new List(); - private bool _loaded; - private bool _moving; - private readonly MultiTile _drawTile; - private MultiTile _hoverTile; - private MultiTile _selectedTile; - - // Multi-selection - private readonly HashSet _selectedTiles = new HashSet(); - private bool _isMarqueeDragging; - private Point _marqueeStart; - private Point _marqueeEnd; - - // Copy/Paste - // Dynamic flag and extra field travel with the tile, so a paste matches what was copied. - private List<(ushort id, int dx, int dy, int dz, bool invisible, int extra)> _clipboard; - private bool _isPasteMode; - - // Zoom - private float _zoomFactor = 1.0f; - - // Minimap - private bool _minimapDirty = true; - private Bitmap _minimapTilesBmp; // cached tile-dot layer, regenerated only when tiles change - - // Recently used tiles - private readonly List _recentTiles = new List(); - private FlowLayoutPanel _recentPanel; - private readonly List _recentSlots = new List(); - - // Rectangle fill tool - private bool _isRectFillDragging; - private int _rectFillStartX, _rectFillStartY; - private int _rectFillEndX, _rectFillEndY; - - // Line draw tool - private bool _isLineDragging; - private int _lineStartX, _lineStartY; - private int _lineEndX, _lineEndY; - - // Bulk remove tool (multi-space coords, mirrors rect fill) - private bool _isRemoveDragging; - private int _removeStartX, _removeStartY; - private int _removeEndX, _removeEndY; - - /// - /// Current MouseLoc + Scrollbar values (for hover effect) - /// - private Point _mouseLoc; - private Point _movingLoc; - - private int _pictureBoxDrawTilesCol; - private int _pictureBoxDrawTilesRow; - - public MultiEditorControl() - { - SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true); - InitializeComponent(); - - _mouseLoc = new Point(); - _movingLoc = new Point(); - - _drawTile = new MultiTile(); - - Selectedpanel.Visible = false; - - FloatingPreviewPanel.Visible = false; - FloatingPreviewPanel.Tag = -1; - - BTN_Select.Checked = true; - - pictureBoxDrawTiles.MouseWheel += PictureBoxDrawTiles_OnMouseWheel; - pictureBoxMulti.MouseWheel += PictureBoxMulti_OnMouseWheel; - - } - - /// - /// Floor Z level - /// - public int DrawFloorZ { get; private set; } - - /// - /// Current Hovered Tile (set inside MultiComponentList) - /// - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public MultiTile HoverTile - { - get => _hoverTile; - set - { - _hoverTile = value; - toolTip1.SetToolTip(pictureBoxMulti, value != null ? $"ID: 0x{_hoverTile.Id:X} Z: {_hoverTile.Z}" : string.Empty); - } - } - - /// - /// Current Selected Tile (set OnMouseUp). Setting this also syncs the single-tile selection panel. - /// - public MultiTile SelectedTile - { - get => _selectedTile; - private set - { - _selectedTile = value; - if (value != null) - { - Selectedpanel.Visible = true; - SelectedTileLabel.Text = $"ID: 0x{value.Id:X} Z: {value.Z}"; - numericUpDown_Selected_X.Value = value.X; - numericUpDown_Selected_Y.Value = value.Y; - numericUpDown_Selected_Z.Value = value.Z; - DynamiccheckBox.Checked = value.Invisible; - } - else if (_selectedTiles.Count == 0) - { - Selectedpanel.Visible = false; - SelectedTileLabel.Text = "ID:"; - } - else - { - // Multiple tiles selected — show count in label, keep panel visible for Z operations - Selectedpanel.Visible = true; - SelectedTileLabel.Text = $"{_selectedTiles.Count} tiles selected"; - } - } - } - - public bool ShowWalkables => showWalkablesToolStripMenuItem.Checked; - public bool ShowDoubleSurface => showDoubleSurfaceMenuItem.Checked; - public HashSet SelectedTiles => _selectedTiles; - - // Private Methods (35)  - - /// - /// Creates new blank Multi - /// - private void BTN_CreateBlank_Click(object sender, EventArgs e) - { - if (MessageBox.Show("Do you want to create a blank Multi?", "Create", MessageBoxButtons.OKCancel, - MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.OK) - { - return; - } - - int width = (int)numericUpDown_Size_Width.Value; - int height = (int)numericUpDown_Size_Height.Value; - - _compList = new MultiEditorComponentList(width, height, this); - ClearTileReferences(); - - UndoList_Clear(); - - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - MaxHeightTrackBar.Value = _compList.ZMax; - - numericUpDown_Selected_X.Maximum = _compList.Width - 1; - numericUpDown_Selected_Y.Maximum = _compList.Height - 1; - - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - } - - /// - /// Draw Button activate - /// - private void BTN_Draw_Click(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = true; - BTN_Remove.Checked = false; - BTN_Z.Checked = false; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = false; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = false; - - pictureBoxMulti.Invalidate(); - } - - private void DoExport(Multis.ImportType type) - { - var designName = textBox_Export.Text; - - if (string.IsNullOrEmpty(designName)) - { - MessageBox.Show( - "Export design name can't be empty.", - "Missing file name", - MessageBoxButtons.OK, - MessageBoxIcon.Warning, - MessageBoxDefaultButton.Button1); - - return; - } - - if (_compList == null) - { - return; - } - - string path = Options.OutputPath; - - MultiComponentList sdkList = _compList.ConvertToSdk(); - - var fileName = string.Empty; - - switch (type) - { - case Multis.ImportType.TXT: - fileName = Path.Combine(path, $"{designName}.txt"); - sdkList.ExportToTextFile(fileName); - break; - case Multis.ImportType.WSC: - fileName = Path.Combine(path, $"{designName}.wsc"); - sdkList.ExportToWscFile(fileName); - break; - case Multis.ImportType.UOA: - fileName = Path.Combine(path, $"{designName}.uoa.txt"); - sdkList.ExportToUOAFile(fileName); - break; - case Multis.ImportType.CSV: - fileName = Path.Combine(path, $"{designName}.csv"); - sdkList.ExportToCsvFile(fileName); - break; - case Multis.ImportType.UOX3: - fileName = Path.Combine(path, $"{designName}.uox3"); - sdkList.ExportToUox3File(fileName); - break; - case Multis.ImportType.XML: - fileName = Path.Combine(path, $"{designName}.xml"); - sdkList.ExportToXmlFile(fileName, designName); - break; - } - - FileSavedDialog.Show(FindForm(), fileName, "Multi design saved successfully."); - } - - private void BTN_Export_TXT_OnClick(object sender, EventArgs e) - { - DoExport(Multis.ImportType.TXT); - } - - private void BTN_Export_UOA_OnClick(object sender, EventArgs e) - { - DoExport(Multis.ImportType.UOA); - } - - private void BTN_Export_WSC_OnClick(object sender, EventArgs e) - { - DoExport(Multis.ImportType.WSC); - } - - private void BTN_Export_CSV_OnClick(object sender, EventArgs e) - { - DoExport(Multis.ImportType.CSV); - } - - private void BTN_Export_UOX3_Click(object sender, EventArgs e) - { - DoExport(Multis.ImportType.UOX3); - } - - private void BTN_Export_XML_Click(object sender, EventArgs e) - { - DoExport(Multis.ImportType.XML); - } - - /// - /// Virtual Floor clicked (check on click) - /// - private void BTN_Floor_Clicked(object sender, EventArgs e) - { - DrawFloorZ = (int)numericUpDown_Floor.Value; - - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - } - - /// - /// Change DrawTile to clicked Tile - /// - private void BTN_Pipette_Click(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = false; - BTN_Remove.Checked = false; - BTN_Z.Checked = false; - BTN_Pipette.Checked = true; - BTN_Trans.Checked = false; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = false; - - pictureBoxMulti.Invalidate(); - } - - /// - /// Remove Button activate - /// - private void BTN_Remove_Click(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = false; - BTN_Remove.Checked = true; - BTN_Z.Checked = false; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = false; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = false; - - pictureBoxMulti.Invalidate(); - } - - /// - /// Resize Multi Button clicked - /// - private void BTN_ResizeMulti_Click(object sender, EventArgs e) - { - if (_compList == null) - { - return; - } - - int width = (int)numericUpDown_Size_Width.Value; - int height = (int)numericUpDown_Size_Height.Value; - - _compList.Resize(width, height); - - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - MaxHeightTrackBar.Value = _compList.ZMax; - - numericUpDown_Selected_X.Maximum = _compList.Width - 1; - numericUpDown_Selected_Y.Maximum = _compList.Height - 1; - - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - } - - /// - /// Save Button clicked - /// - private void BTN_Save_Click(object sender, EventArgs e) - { - if (_compList != null && Utils.ConvertStringToInt(textBox_SaveToID.Text, out int id, 0, Multis.MaximumMultiIndex - 1)) - { - _compList.AddToSdkComponentList(id); // fires MultiChangeEvent - } - } - - /// - /// Select Button activate - /// - private void BTN_Select_Click(object sender, EventArgs e) - { - BTN_Select.Checked = true; - BTN_Draw.Checked = false; - BTN_Remove.Checked = false; - BTN_Z.Checked = false; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = false; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = false; - - pictureBoxMulti.Invalidate(); - } - - private void BTN_Toolbox_CheckedChanged(object sender, EventArgs e) - { - CheckBox thisBox = (CheckBox)sender; - - switch (thisBox.Name) - { - case "BTN_Select": - thisBox.ImageKey = thisBox.Checked ? "SelectButton_Selected.bmp" : "SelectButton.bmp"; - break; - case "BTN_Draw": - thisBox.ImageKey = thisBox.Checked ? "DrawButton_Selected.bmp" : "DrawButton.bmp"; - break; - case "BTN_Remove": - thisBox.ImageKey = thisBox.Checked ? "RemoveButton_Selected.bmp" : "RemoveButton.bmp"; - break; - case "BTN_Z": - thisBox.ImageKey = thisBox.Checked ? "AltitudeButton_Selected.bmp" : "AltitudeButton.bmp"; - break; - case "BTN_Floor": - thisBox.ImageKey = thisBox.Checked ? "VirtualFloorButton_Selected.bmp" : "VirtualFloorButton.bmp"; - break; - case "BTN_Pipette": - thisBox.ImageKey = thisBox.Checked ? "PipetteButton_Selected.bmp" : "PipetteButton.bmp"; - break; - case "BTN_Trans": - thisBox.ImageKey = thisBox.Checked ? "TransButton_Selected.bmp" : "TransButton.bmp"; - break; - case "BTN_RectFill": - thisBox.ImageKey = thisBox.Checked ? "RectFillButton_Selected.bmp" : "RectFillButton.bmp"; - break; - case "BTN_LineDraw": - thisBox.ImageKey = thisBox.Checked ? "LineDrawButton_Selected.bmp" : "LineDrawButton.bmp"; - break; - } - } - - /// - /// Z Button activate - /// - private void BTN_Z_Click(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = false; - BTN_Remove.Checked = false; - BTN_Z.Checked = true; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = false; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = false; - - pictureBoxMulti.Invalidate(); - } - - private void BTN_Trans_Clicked(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = false; - BTN_Remove.Checked = false; - BTN_Z.Checked = false; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = true; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = false; - - pictureBoxMulti.Invalidate(); - } - - private void BTN_RectFill_Click(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = false; - BTN_Remove.Checked = false; - BTN_Z.Checked = false; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = false; - BTN_LineDraw.Checked = false; - BTN_RectFill.Checked = true; - - pictureBoxMulti.Invalidate(); - } - - private void BTN_LineDraw_Click(object sender, EventArgs e) - { - BTN_Select.Checked = false; - BTN_Draw.Checked = false; - BTN_Remove.Checked = false; - BTN_Z.Checked = false; - BTN_Pipette.Checked = false; - BTN_Trans.Checked = false; - BTN_RectFill.Checked = false; - BTN_LineDraw.Checked = true; - - pictureBoxMulti.Invalidate(); - } - - - private int BrushSize => RB_Brush_M.Checked ? 3 : RB_Brush_L.Checked ? 4 : 1; - - /// - /// Converts pictureBox coords to Multi coords - /// - private void ConvertCoords(Point point, out int x, out int y, out int z) - { - // first check if current Tile matches - if (HoverTile != null) - { - // visible? - if (!BTN_Floor.Checked || HoverTile.Z >= DrawFloorZ) - { - x = HoverTile.X; - y = HoverTile.Y; - z = HoverTile.Z + HoverTile.Height; - // Cap placement Z to MaxHeightTrackBar when height filter is active - if (MaxHeightTrackBar.Value < MaxHeightTrackBar.Maximum) - { - z = Math.Min(z, MaxHeightTrackBar.Value); - } - return; - } - } - - // damn the hard way - z = 0; - - int cx = 0; // Get MouseCoords for (0/0) - int cy = 0; - - if (BTN_Floor.Checked) - { - cy -= DrawFloorZ * 4; - z = DrawFloorZ; - } - - cy -= 44; - cx -= _compList.XMin; - cy -= _compList.YMin; - cy += MultiEditorComponentList.GapYMod; //Mod for a bit of gap - cx += MultiEditorComponentList.GapXMod; - - double mx = point.X - cx; - double my = point.Y - cy; - double xx = mx; - double yy = my; - my = (xx * _coordinateTransform) - (yy * _coordinateTransform); // Rotate 45° Coordinate system - mx = (yy * _coordinateTransform) + (xx * _coordinateTransform); - mx /= _coordinateTransform * 44; // Math.Sqrt(2)*22==CoordinateTransform*44 - my /= _coordinateTransform * 44; // CoordinateTransform=Math.Sqrt(2)/2 - my *= -1; - x = (int)mx; - y = (int)my; - } - - /// - /// Value of TrackBar changed (for displayed MaxHeight) - /// - private void MaxHeightTrackBarOnValueChanged(object sender, EventArgs e) - { - ScrollbarsSetValue(); - - toolTip1.SetToolTip(MaxHeightTrackBar, MaxHeightTrackBar.Value.ToString()); - - pictureBoxMulti.Invalidate(); - } - - /// - /// Virtual Floor zValue changed - /// - private void NumericUpDown_Floor_Changed(object sender, EventArgs e) - { - if (_compList is null) - { - return; - } - - DrawFloorZ = (int)numericUpDown_Floor.Value; - - _compList.SetFloorZ(DrawFloorZ); - - if (!BTN_Floor.Checked) - { - return; - } - - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - } - - /// - /// SelectedTile panel X value changed - /// - private void NumericUpDown_Selected_X_Changed(object sender, EventArgs e) - { - if (_compList != null && SelectedTile != null && (int)numericUpDown_Selected_X.Value != SelectedTile.X) - { - _compList.TileMove(SelectedTile, (int)numericUpDown_Selected_X.Value, SelectedTile.Y); - - pictureBoxMulti.Invalidate(); - } - } - - /// - /// SelectedTile panel Y value changed - /// - private void NumericUpDown_Selected_Y_Changed(object sender, EventArgs e) - { - if (_compList != null && SelectedTile != null && (int)numericUpDown_Selected_Y.Value != SelectedTile.Y) - { - _compList.TileMove(SelectedTile, SelectedTile.X, (int)numericUpDown_Selected_Y.Value); - - pictureBoxMulti.Invalidate(); - } - } - - /// - /// SelectedTile panel Z value changed - /// - private void NumericUpDown_Selected_Z_Changed(object sender, EventArgs e) - { - if (_compList == null) - { - return; - } - - int newZ = (int)numericUpDown_Selected_Z.Value; - - if (_selectedTiles.Count > 1) - { - // Apply absolute Z to the whole group - _compList.TileZSet(_selectedTiles, newZ); - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - pictureBoxMulti.Invalidate(); - return; - } - - if (SelectedTile == null || newZ == SelectedTile.Z) - { - return; - } - - _compList.TileZSet(SelectedTile, newZ); - - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - - if (MaxHeightTrackBar.Value < SelectedTile.Z) - { - MaxHeightTrackBar.Value = SelectedTile.Z; - } - - pictureBoxMulti.Invalidate(); - } - - /// - /// Event Ultima FilePath changed - /// - private void OnFilePathChangeEvent() - { - if (_loaded) - { - OnLoad(null, null); - } - } - - /// - /// Load of UserControl - /// - private void ApplyDarkModeIfNeeded() - { - if (Options.DarkMode) - { - Color tabBg = Color.FromArgb(32, 32, 32); - TabPage[] tabPages = { tileTab, designTab, importTab, Save }; - foreach (var tp in tabPages) - { - tp.UseVisualStyleBackColor = false; - tp.BackColor = tabBg; - } - - pictureBoxDrawTiles.BackColor = Color.LightGray; - } - - ApplyPreviewBackgroundColor(); - } - - private void ApplyPreviewBackgroundColor() - { - pictureBoxMulti.BackColor = Options.PreviewBackgroundColor; - pictureBoxMulti.Invalidate(); - } - - private void OnLoad(object sender, EventArgs e) - { - ApplyDarkModeIfNeeded(); - - Options.LoadedUltimaClass["TileData"] = true; - Options.LoadedUltimaClass["Art"] = true; - Options.LoadedUltimaClass["Multis"] = true; - Options.LoadedUltimaClass["Hues"] = true; - - XML_InitializeToolBox(); - - if (!_loaded) - { - _recentTiles.Clear(); - _recentTiles.AddRange(TileRecentlyUsed.Load()); - InitializeRecentTab(); - } - - RefreshRecentPanel(); - - string path = Options.AppDataPath; - string fileName = Path.Combine(path, "Multilist.xml"); - - XmlDocument dom = null; - XmlElement xMultis = null; - if (File.Exists(fileName)) - { - dom = new XmlDocument(); - dom.Load(fileName); - xMultis = dom["Multis"]; - } - - treeViewMultiList.BeginUpdate(); - treeViewMultiList.Nodes.Clear(); - - // Let's create a root for import from Multi file and put these in there - TreeNode multiNode = new TreeNode("Multi.mul"); - for (int i = 0; i < Multis.MaximumMultiIndex; ++i) - { - if (Multis.GetComponents(i) == MultiComponentList.Empty) - { - continue; - } - - TreeNode node; - if (dom == null) - { - node = new TreeNode(string.Format("{0,5} (0x{0:X})", i)); - } - else - { - XmlNodeList xMultiNodeList = xMultis.SelectNodes("/Multis/Multi[@id='" + i + "']"); - string j = ""; - foreach (XmlNode xMultiNode in xMultiNodeList) - { - j = xMultiNode.Attributes["name"].Value; - } - - node = new TreeNode(string.Format("{0,5} (0x{0:X}) {1}", i, j)); - } - - node.Tag = i; - node.Name = i.ToString(); - multiNode.Nodes.Add(node); - } - - treeViewMultiList.Nodes.Add(multiNode); - TreeNode fileNode = new TreeNode("From File"); - - TreeNode txtNode = new TreeNode("Txt File") { Tag = "txt" }; - fileNode.Nodes.Add(txtNode); - - TreeNode uoaNode = new TreeNode("UOA Text File") { Tag = "uoa" }; - fileNode.Nodes.Add(uoaNode); - - TreeNode uoabNode = new TreeNode("UOA Binary File") { Tag = "uoab" }; - fileNode.Nodes.Add(uoabNode); - - TreeNode wscNode = new TreeNode("WSC File") { Tag = "wsc" }; - fileNode.Nodes.Add(wscNode); - - TreeNode cacheNode = new TreeNode("MultiCache File") { Tag = "cache" }; - fileNode.Nodes.Add(cacheNode); - - TreeNode uoadesignNode = new TreeNode("UOA Design File") { Tag = "uoadesign" }; - fileNode.Nodes.Add(uoadesignNode); - - TreeNode csvNode = new TreeNode("CSV File") { Tag = "csv" }; - fileNode.Nodes.Add(csvNode); - - treeViewMultiList.Nodes.Add(fileNode); - - TreeNode uopNode = new TreeNode("multicollection.uop") { Name = "uop" }; - if (!Multis.HasUopFile) - { - uopNode.Nodes.Add(new TreeNode("File not found")); - } - else - { - for (int i = 0; i < Multis.MaximumMultiIndex; ++i) - { - if (Multis.GetUopComponents(i) == MultiComponentList.Empty) - { - continue; - } - - TreeNode node; - if (dom == null) - { - node = new TreeNode(string.Format("{0,5} (0x{0:X})", i)); - } - else - { - XmlNodeList xMultiNodeList = xMultis.SelectNodes("/Multis/Multi[@id='" + i + "']"); - string j = ""; - foreach (XmlNode xMultiNode in xMultiNodeList) - { - j = xMultiNode.Attributes["name"].Value; - } - - node = new TreeNode(string.Format("{0,5} (0x{0:X}) {1}", i, j)); - } - - node.Tag = i; - node.Name = i.ToString(); - uopNode.Nodes.Add(node); - } - } - - treeViewMultiList.Nodes.Add(uopNode); - treeViewMultiList.EndUpdate(); - - if (!_loaded) - { - ControlEvents.FilePathChangeEvent += OnFilePathChangeEvent; - ControlEvents.MultiChangeEvent += OnMultiChangeEvent; - ControlEvents.PreviewBackgroundColorChangeEvent += ApplyPreviewBackgroundColor; - } - - _loaded = true; - } - - private void OnMultiChangeEvent(object sender, int id) - { - if (!_loaded) - { - return; - } - - if (sender.Equals(this)) - { - return; - } - - bool done = false; - bool remove = Multis.GetComponents(id) == MultiComponentList.Empty; - - for (int i = 0; i < treeViewMultiList.Nodes[0].Nodes.Count; ++i) - { - if (id == (int)treeViewMultiList.Nodes[0].Nodes[i].Tag) - { - done = true; - - if (remove) - { - treeViewMultiList.Nodes[0].Nodes.RemoveAt(i); - } - - break; - } - - if (id >= (int)treeViewMultiList.Nodes[0].Nodes[i].Tag) - { - continue; - } - - if (!remove) - { - TreeNode node = new TreeNode(string.Format("{0,5} (0x{0:X})", id)) - { - Tag = id, - Name = id.ToString() - }; - treeViewMultiList.Nodes[0].Nodes.Insert(i, node); - } - - done = true; - break; - } - - if (!remove && !done) - { - TreeNode node = new TreeNode(string.Format("{0,5} (0x{0:X})", id)) - { - Tag = id, - Name = id.ToString() - }; - - treeViewMultiList.Nodes[0].Nodes.Add(node); - } - } - - /// - /// Hover effect - /// - private void PictureBoxMultiOnMouseMove(object sender, MouseEventArgs e) - { - _mouseLoc = ToScrolledSpace(e.Location); - - if (_moving) - { - int deltaX = -1 * (e.X - _movingLoc.X); - int deltaY = -1 * (e.Y - _movingLoc.Y); - - _movingLoc = e.Location; - - hScrollBar.Value = Math.Max(0, Math.Min(hScrollBar.Maximum, hScrollBar.Value + deltaX)); - vScrollBar.Value = Math.Max(0, Math.Min(vScrollBar.Maximum, vScrollBar.Value + deltaY)); - } - else if (_isMarqueeDragging) - { - // Same zoom-aware space as the tiles, so the rectangle selects what it covers. - _marqueeEnd = ToScrolledSpace(e.Location); - } - else if (_isRectFillDragging && _compList != null) - { - ConvertCoords(_mouseLoc, out int x, out int y, out int _); - _rectFillEndX = x; - _rectFillEndY = y; - } - else if (_isLineDragging && _compList != null) - { - ConvertCoords(_mouseLoc, out int x, out int y, out int _); - _lineEndX = x; - _lineEndY = y; - } - else if (_isRemoveDragging && _compList != null) - { - ConvertCoords(_mouseLoc, out int rx, out int ry, out int _); - _removeEndX = rx; - _removeEndY = ry; - } - - pictureBoxMulti.Invalidate(); - } - - private void PictureBoxMultiOnMouseDown(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - _moving = true; - _movingLoc = e.Location; - Cursor = Cursors.Hand; - } - else if (e.Button == MouseButtons.Left && BTN_Select.Checked && _compList != null) - { - bool ctrlHeld = (ModifierKeys & Keys.Control) != 0; - if (_hoverTile == null && !ctrlHeld) - { - // Start marquee drag over empty space - _isMarqueeDragging = true; - _marqueeStart = ToScrolledSpace(e.Location); - _marqueeEnd = _marqueeStart; - } - } - else if (e.Button == MouseButtons.Left && BTN_RectFill.Checked && _compList != null) - { - ConvertCoords(_mouseLoc, out int x, out int y, out int _); - _isRectFillDragging = true; - _rectFillStartX = x; - _rectFillStartY = y; - _rectFillEndX = x; - _rectFillEndY = y; - } - else if (e.Button == MouseButtons.Left && BTN_LineDraw.Checked && _compList != null) - { - ConvertCoords(_mouseLoc, out int x, out int y, out int _); - _isLineDragging = true; - _lineStartX = x; - _lineStartY = y; - _lineEndX = x; - _lineEndY = y; - } - else if (e.Button == MouseButtons.Left && BTN_Remove.Checked && _compList != null) - { - ConvertCoords(_mouseLoc, out int rx, out int ry, out int _); - _isRemoveDragging = true; - _removeStartX = rx; - _removeStartY = ry; - _removeEndX = rx; - _removeEndY = ry; - } - else - { - _moving = false; - Cursor = Cursors.Default; - } - } - - /// - /// Select/Draw/Remove/Z a Tile - /// - private void PictureBoxMultiOnMouseUp(object sender, MouseEventArgs e) - { - _moving = false; - - Cursor = Cursors.Default; - - if (e.Button == MouseButtons.Right) - { - if (_isMarqueeDragging) - { - _isMarqueeDragging = false; - pictureBoxMulti.Invalidate(); - } - - if (_isRemoveDragging) - { - _isRemoveDragging = false; - pictureBoxMulti.Invalidate(); - return; - } - - if (_isPasteMode) - { - _isPasteMode = false; - pictureBoxMulti.Invalidate(); - } - - return; - } - - if (_compList == null) - { - return; - } - - // Paste commit - if (_isPasteMode && e.Button == MouseButtons.Left && _clipboard != null) - { - ConvertCoords(_mouseLoc, out int px, out int py, out int pz); - var batch = _clipboard.Select(c => (c.id, px + c.dx, py + c.dy, pz + c.dz, c.invisible, c.extra)).ToList(); - _compList.TileAddBatch(batch); - _isPasteMode = false; - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - pictureBoxMulti.Invalidate(); - return; - } - - if (e.Button == MouseButtons.Middle) - { - _overlayList.Clear(); - - if (_hoverTile != null) - { - foreach (MultiTile tile in _compList.GetMultiTileLitAtCoordinate(_hoverTile.X, _hoverTile.Y)) - { - if (tile.IsVirtualFloor) - { - continue; - } - - if (tile.Z == _hoverTile.Z) - { - _overlayList.Add(tile); - } - } - } - } - else if (BTN_Select.Checked) - { - bool ctrlHeld = (ModifierKeys & Keys.Control) != 0; - - if (_isMarqueeDragging) - { - _isMarqueeDragging = false; - int sx = Math.Min(_marqueeStart.X, _marqueeEnd.X) - hScrollBar.Value; - int sy = Math.Min(_marqueeStart.Y, _marqueeEnd.Y) - vScrollBar.Value; - int sw = Math.Abs(_marqueeEnd.X - _marqueeStart.X); - int sh = Math.Abs(_marqueeEnd.Y - _marqueeStart.Y); - - if (sw > 3 && sh > 3) - { - var rect = new Rectangle(sx, sy, sw, sh); - var tiles = _compList.GetTilesInScreenRect( - rect, hScrollBar.Value, vScrollBar.Value, - MaxHeightTrackBar.Value, BTN_Floor.Checked); - if (!ctrlHeld) - { - _selectedTiles.Clear(); - } - - foreach (var t in tiles) - { - _selectedTiles.Add(t); - } - - SelectedTile = _selectedTiles.Count == 1 ? _selectedTiles.First() : null; - } - else - { - // Tiny drag — treat as plain click - if (!ctrlHeld) - { - _selectedTiles.Clear(); - } - - if (_hoverTile != null) - { - _selectedTiles.Add(_hoverTile); - } - - SelectedTile = _hoverTile; - } - } - else if (ctrlHeld && _hoverTile != null) - { - if (_selectedTiles.Contains(_hoverTile)) - { - _selectedTiles.Remove(_hoverTile); - } - else - { - _selectedTiles.Add(_hoverTile); - } - - SelectedTile = _selectedTiles.Count == 1 ? _selectedTiles.First() : null; - } - else - { - _selectedTiles.Clear(); - if (_hoverTile != null) - { - _selectedTiles.Add(_hoverTile); - } - - SelectedTile = _hoverTile; - } - } - else if (BTN_Draw.Checked) - { - ConvertCoords(_mouseLoc, out int x, out int y, out int z); - - if (x >= 0 && x < _compList.Width && y >= 0 && y < _compList.Height) - { - int brushSize = BrushSize; - if (brushSize <= 1) - { - _compList.TileAdd(x, y, z, _drawTile.Id); - } - else - { - _compList.TileAddBrush(x, y, z, _drawTile.Id, brushSize); - } - - RecordRecentTile(_drawTile.Id); - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - if (MaxHeightTrackBar.Value < z) - { - MaxHeightTrackBar.Value = z; - } - } - } - else if (BTN_RectFill.Checked && _isRectFillDragging) - { - _isRectFillDragging = false; - ConvertCoords(_mouseLoc, out int ex, out int ey, out int z); - int x0 = Math.Min(_rectFillStartX, ex); - int x1 = Math.Max(_rectFillStartX, ex); - int y0 = Math.Min(_rectFillStartY, ey); - int y1 = Math.Max(_rectFillStartY, ey); - _compList.TileAddRect(x0, y0, x1, y1, z, _drawTile.Id); - RecordRecentTile(_drawTile.Id); - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - if (MaxHeightTrackBar.Value < z) - { - MaxHeightTrackBar.Value = z; - } - } - else if (BTN_LineDraw.Checked && _isLineDragging) - { - _isLineDragging = false; - ConvertCoords(_mouseLoc, out int ex, out int ey, out int z); - (ex, ey) = GetLineEnd(ex, ey); - _compList.TileAddLine(_lineStartX, _lineStartY, ex, ey, z, _drawTile.Id); - RecordRecentTile(_drawTile.Id); - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - if (MaxHeightTrackBar.Value < z) - { - MaxHeightTrackBar.Value = z; - } - } - else if (BTN_Remove.Checked) - { - bool wasDrag = _isRemoveDragging && - (_removeEndX != _removeStartX || _removeEndY != _removeStartY); - _isRemoveDragging = false; - - if (wasDrag) - { - int x0 = Math.Min(_removeStartX, _removeEndX); - int x1 = Math.Max(_removeStartX, _removeEndX); - int y0 = Math.Min(_removeStartY, _removeEndY); - int y1 = Math.Max(_removeStartY, _removeEndY); - _compList.TileRemoveRect(x0, y0, x1, y1, DrawFloorZ, MaxHeightTrackBar.Value); - } - else if (_hoverTile != null) - { - _compList.TileRemove(_hoverTile); - } - else - { - int overX = 0; - const int overY = 0; - - foreach (MultiTile tile in _overlayList) - { - Bitmap bmp = tile.GetBitmap(); - if (bmp == null) - { - continue; - } - - if (_mouseLoc.X > overX && _mouseLoc.X < overX + bmp.Width && _mouseLoc.Y > overY && - _mouseLoc.Y < overY + bmp.Height) - { - // Check for transparent part - Color p = bmp.GetPixel(_mouseLoc.X - overX, _mouseLoc.Y - overY); - if (!(p.R == 0 && p.G == 0 && p.B == 0)) - { - _compList.TileRemove(tile); - _overlayList.Remove(tile); - break; - } - } - - overX += bmp.Width + 10; - } - } - - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - } - else if (BTN_Z.Checked) - { - int z = (int)numericUpDown_Z.Value; - if (_selectedTiles.Count > 1) - { - _compList.TileZMod(_selectedTiles, z); - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - } - else if (_hoverTile != null) - { - _compList.TileZMod(_hoverTile, z); - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - if (MaxHeightTrackBar.Value < _hoverTile.Z) - { - MaxHeightTrackBar.Value = _hoverTile.Z; - } - } - } - else if (BTN_Pipette.Checked) - { - if (_hoverTile != null) - { - _drawTile.Set(_hoverTile.Id, 0); - PictureBoxDrawTiles_Select(); - DrawTileLabel.Text = $"Draw ID: 0x{_hoverTile.Id:X}"; - UpdateRecentSelection(); - } - } - else if (BTN_Trans.Checked) - { - if (_hoverTile != null) - { - _hoverTile.Transparent = !_hoverTile.Transparent; - } - } - - if (e.Button != MouseButtons.Middle && !BTN_Remove.Checked) - { - _overlayList.Clear(); - } - else if (_overlayList.Count == 1) - { - _overlayList.Clear(); - } - - _minimapDirty = true; - pictureBoxMulti.Invalidate(); - } - - private delegate void ADelegate(string t); - - private void SetToolStripText(string text) - { - toolStripLabelCoord.Text = text; - toolStrip1.Update(); - } - - /// - /// Draw Image - /// - private void PictureBoxMultiOnPaint(object sender, PaintEventArgs e) - { - e.Graphics.Clear(pictureBoxMulti.BackColor); - - if (_compList == null) - { - return; - } - - if (_zoomFactor != 1.0f) - { - float cx = pictureBoxMulti.Width / 2f; - float cy = pictureBoxMulti.Height / 2f; - e.Graphics.TranslateTransform(cx, cy); - e.Graphics.ScaleTransform(_zoomFactor, _zoomFactor); - e.Graphics.TranslateTransform(-cx, -cy); - } - - _compList.GetImage(e.Graphics, hScrollBar.Value, vScrollBar.Value, MaxHeightTrackBar.Value, _mouseLoc, BTN_Floor.Checked); - - - if (ShowWalkables) - { - showWalkablesToolStripMenuItem.Text = $"Show Walkable tiles ({_compList.WalkableCount})"; - } - - if (ShowDoubleSurface) - { - showDoubleSurfaceMenuItem.Text = $"Show double surface ({_compList.DoubleSurfaceCount})"; - } - - ConvertCoords(_mouseLoc, out int x, out int y, out int z); - - if (x >= 0 && x < _compList.Width && y >= 0 && y < _compList.Height) - { - Invoke(new ADelegate(SetToolStripText), $"{x},{y},{z}"); - } - - // Draw marquee selection rectangle - if (_isMarqueeDragging) - { - int sx = Math.Min(_marqueeStart.X, _marqueeEnd.X) - hScrollBar.Value; - int sy = Math.Min(_marqueeStart.Y, _marqueeEnd.Y) - vScrollBar.Value; - int sw = Math.Abs(_marqueeEnd.X - _marqueeStart.X); - int sh = Math.Abs(_marqueeEnd.Y - _marqueeStart.Y); - using (var pen = new System.Drawing.Pen(Color.DodgerBlue, 1)) - { - pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; - e.Graphics.DrawRectangle(pen, sx, sy, sw, sh); - } - - using (var brush = new SolidBrush(Color.FromArgb(30, Color.DodgerBlue))) - { - e.Graphics.FillRectangle(brush, sx, sy, sw, sh); - } - } - - // Bulk remove drag preview — highlight existing tiles in the multi-space rect - if (_isRemoveDragging) - { - int rx0 = Math.Min(_removeStartX, _removeEndX); - int rx1 = Math.Max(_removeStartX, _removeEndX); - int ry0 = Math.Min(_removeStartY, _removeEndY); - int ry1 = Math.Max(_removeStartY, _removeEndY); - foreach (MultiTile ht in _compList.Tiles) - { - if (ht.IsVirtualFloor || ht.Z < DrawFloorZ || ht.Z > MaxHeightTrackBar.Value || ht.X < rx0 || ht.X > rx1 || ht.Y < ry0 || ht.Y > ry1) - { - continue; - } - - Bitmap htBmp = ht.GetBitmap(); - if (htBmp == null) - { - continue; - } - - int hpx = ht.XMod - _compList.XMin - hScrollBar.Value; - int hpy = ht.YMod - _compList.YMin - vScrollBar.Value; - e.Graphics.DrawImage(htBmp, new Rectangle(hpx, hpy, htBmp.Width, htBmp.Height), - 0, 0, htBmp.Width, htBmp.Height, GraphicsUnit.Pixel, MultiTile.RemoveHighlightColor); - } - } - - // Paste ghost preview - if (_isPasteMode && _clipboard != null) - { - ConvertCoords(_mouseLoc, out int px, out int py, out int pz); - foreach (var (id, dx, dy, dz, _, _) in _clipboard) - { - var ghost = new MultiTile(id, px + dx, py + dy, pz + dz, 1); - Bitmap ghostBmp = ghost.GetBitmap(); - if (ghostBmp == null) - { - continue; - } - - int gpx = (ghost.X - ghost.Y) * 22 - ghostBmp.Width / 2 - _compList.XMin + MultiEditorComponentList.GapXMod - hScrollBar.Value; - int gpy = (ghost.X + ghost.Y) * 22 - ghost.Z * 4 - ghostBmp.Height - _compList.YMin + MultiEditorComponentList.GapYMod - vScrollBar.Value; - e.Graphics.DrawImage(ghostBmp, new Rectangle(gpx, gpy, ghostBmp.Width, ghostBmp.Height), - 0, 0, ghostBmp.Width, ghostBmp.Height, GraphicsUnit.Pixel, MultiTile.DrawColor); - } - } - - if (BTN_Draw.Checked) - { - if (x < 0 || x >= _compList.Width || y < 0 || y >= _compList.Height) - { - return; - } - - Invoke(new ADelegate(SetToolStripText), $"{x},{y},{z}"); - - int brushSize = BrushSize; - int half = brushSize / 2; - for (int dx = -half; dx <= half; dx++) - { - for (int dy = -half; dy <= half; dy++) - { - DrawTilePreviewAt(e.Graphics, x + dx, y + dy, z); - } - } - } - else if (BTN_RectFill.Checked && _isRectFillDragging) - { - int x0 = Math.Min(_rectFillStartX, _rectFillEndX); - int x1 = Math.Max(_rectFillStartX, _rectFillEndX); - int y0 = Math.Min(_rectFillStartY, _rectFillEndY); - int y1 = Math.Max(_rectFillStartY, _rectFillEndY); - for (int rx = x0; rx <= x1; rx++) - { - for (int ry = y0; ry <= y1; ry++) - { - DrawTilePreviewAt(e.Graphics, rx, ry, z); - } - } - } - else if (BTN_LineDraw.Checked && _isLineDragging) - { - var (cex, cey) = GetLineEnd(_lineEndX, _lineEndY); - foreach (var (lx, ly) in MultiEditorComponentList.BresenhamLinePublic(_lineStartX, _lineStartY, cex, cey)) - { - DrawTilePreviewAt(e.Graphics, lx, ly, z); - } - } - else if (_overlayList.Count > 0) - { - int overX = 0; - const int overY = 0; - - foreach (MultiTile tile in _overlayList) - { - Bitmap bmp = tile.GetBitmap(); - if (bmp == null) - { - continue; - } - - e.Graphics.DrawImage(bmp, new Rectangle(overX, overY, bmp.Width, bmp.Height)); - overX += bmp.Width + 10; - } - } - - UpdateMinimap(); - } - - private void PictureBoxMulti_OnMouseWheel(object sender, MouseEventArgs e) - { - if ((ModifierKeys & Keys.Control) != 0) - { - float delta = e.Delta > 0 ? 0.1f : -0.1f; - SetZoom(_zoomFactor + delta); - if (e is HandledMouseEventArgs hme) - { - hme.Handled = true; - } - - return; - } - - // Normal scroll: pan vertically - int scrollDelta = e.Delta > 0 ? -22 : 22; - vScrollBar.Value = Math.Clamp(vScrollBar.Value + scrollDelta, 0, vScrollBar.Maximum); - } - - private Point ToScrolledSpace(Point screenPt) - { - float cx = pictureBoxMulti.Width / 2f; - float cy = pictureBoxMulti.Height / 2f; - float sx = (screenPt.X - cx) / _zoomFactor + cx + hScrollBar.Value; - float sy = (screenPt.Y - cy) / _zoomFactor + cy + vScrollBar.Value; - return new Point((int)sx, (int)sy); - } - - private void DrawTilePreviewAt(Graphics gfx, int tx, int ty, int z) - { - if (tx < 0 || tx >= _compList.Width || ty < 0 || ty >= _compList.Height) - { - return; - } - - Bitmap bmp = _drawTile.GetBitmap(); - if (bmp == null) - { - return; - } - - int px = (tx - ty) * 22 - bmp.Width / 2 - _compList.XMin + MultiEditorComponentList.GapXMod - hScrollBar.Value; - int py = (tx + ty) * 22 - z * 4 - bmp.Height - _compList.YMin + MultiEditorComponentList.GapYMod - vScrollBar.Value; - gfx.DrawImage(bmp, new Rectangle(px, py, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, - GraphicsUnit.Pixel, MultiTile.DrawColor); - } - - /// - /// PictureBox size changed - /// - private void PictureBoxMultiOnResize(object sender, EventArgs e) - { - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - } - - /// - /// Does the Multi fit inside the PictureBox - /// - private void ScrollbarsSetValue() - { - if (_compList == null) - { - return; - } - - int yMin = _compList.YMinOrg; - int yMax = _compList.YMaxOrg; - - if (BTN_Floor.Checked) - { - int floorZMod = (-DrawFloorZ * 4) - 44; - if (yMin > floorZMod) - { - yMin = floorZMod; - } - - floorZMod = ((_compList.Width + _compList.Height) * 22) - (DrawFloorZ * 4); - - if (yMax < floorZMod) - { - yMax = floorZMod; - } - } - - int height = yMax - yMin + (MultiEditorComponentList.GapYMod * 3); - int width = _compList.XMax - _compList.XMin + (MultiEditorComponentList.GapXMod * 2); - - if (height <= pictureBoxMulti.Height + hScrollBar.Height) - { - vScrollBar.Enabled = false; - vScrollBar.Value = 0; - } - else - { - vScrollBar.Enabled = true; - vScrollBar.Maximum = height - pictureBoxMulti.Height + 10; - } - - if (width <= pictureBoxMulti.Width + vScrollBar.Width) - { - hScrollBar.Enabled = false; - vScrollBar.Value = 0; - } - else - { - hScrollBar.Enabled = true; - hScrollBar.Maximum = width - pictureBoxMulti.Width + 10; - } - } - - /// - /// Scrollbars changed - /// - private void ScrollBarsValueChanged(object sender, EventArgs e) - { - pictureBoxMulti.Invalidate(); - } - - private void TreeViewMultiList_LoadFromFile(Multis.ImportType importType) - { - OpenFileDialog dialog = new OpenFileDialog { Multiselect = false }; - - string type; - - switch (importType) - { - case Multis.ImportType.TXT: - type = "txt"; - break; - case Multis.ImportType.UOA: - type = "txt"; - break; - case Multis.ImportType.UOAB: - type = "uoab"; - break; - case Multis.ImportType.WSC: - type = "wsc"; - break; - case Multis.ImportType.MULTICACHE: - type = "Multicache.dat"; - break; - case Multis.ImportType.UOADESIGN: - type = "Designs"; - break; - case Multis.ImportType.CSV: - type = "csv"; - break; - default: - return; - } - - dialog.Title = $"Choose {type} file to import"; - dialog.CheckFileExists = true; - - switch (importType) - { - case Multis.ImportType.MULTICACHE: - dialog.Filter = string.Format("{0} file ({0})|{0}", type); - break; - case Multis.ImportType.UOADESIGN: - dialog.Filter = string.Format("{0} file ({0}.*)|{0}.*", type); - break; - case Multis.ImportType.UOAB: - dialog.Filter = string.Format("{0} file (*.{0})|*.{0}", "uoa"); - break; - default: - dialog.Filter = string.Format("{0} file (*.{0})|*.{0}", type); - break; - } - - if (dialog.ShowDialog() == DialogResult.OK) - { - switch (importType) - { - case Multis.ImportType.MULTICACHE: - { - List list = Multis.LoadFromCache(dialog.FileName); - TreeNode node = treeViewMultiList.Nodes[1].Nodes[4]; - node.Nodes.Clear(); - for (int i = 0; i < list.Count; ++i) - { - TreeNode child = new TreeNode("Entry " + i) { Tag = list[i] }; - node.Nodes.Add(child); - } - - break; - } - case Multis.ImportType.UOADESIGN: - { - List list = Multis.LoadFromDesigner(dialog.FileName); - TreeNode node = treeViewMultiList.Nodes[1].Nodes[5]; - node.Nodes.Clear(); - for (int i = 0; i < list.Count; ++i) - { - object[] data = list[i]; - TreeNode child = new TreeNode(data[0] + "(" + i + ")") - { - Tag = data[1] - }; - node.Nodes.Add(child); - } - - break; - } - default: - { - MultiComponentList multi = Multis.LoadFromFile(dialog.FileName, importType); - - _compList = new MultiEditorComponentList(multi, this); - ClearTileReferences(); - - UndoList_Clear(); - - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - - MaxHeightTrackBar.Value = _compList.ZMax; - - textBox_SaveToID.Text = "0"; - - numericUpDown_Size_Width.Value = _compList.Width; - numericUpDown_Size_Height.Value = _compList.Height; - - numericUpDown_Selected_X.Maximum = _compList.Width - 1; - numericUpDown_Selected_Y.Maximum = _compList.Height - 1; - - vScrollBar.Value = 0; - hScrollBar.Value = 0; - - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - break; - } - } - } - - dialog.Dispose(); - } - - /// - /// DoubleClick Node of Import tree view - /// - private void TreeViewMultiList_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) - { - if (e.Node.Tag == null) - { - return; - } - - switch (e.Node.Tag.ToString()) - { - case "txt": - TreeViewMultiList_LoadFromFile(Multis.ImportType.TXT); - return; - case "uoa": - TreeViewMultiList_LoadFromFile(Multis.ImportType.UOA); - return; - case "uoab": - TreeViewMultiList_LoadFromFile(Multis.ImportType.UOAB); - return; - case "wsc": - TreeViewMultiList_LoadFromFile(Multis.ImportType.WSC); - return; - case "cache": - TreeViewMultiList_LoadFromFile(Multis.ImportType.MULTICACHE); - return; - case "uoadesign": - TreeViewMultiList_LoadFromFile(Multis.ImportType.UOADESIGN); - return; - case "csv": - TreeViewMultiList_LoadFromFile(Multis.ImportType.CSV); - return; - } - - if (MessageBox.Show("Do you want to open selected Multi?", "Open", MessageBoxButtons.OKCancel, - MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.OK) - { - return; - } - - if (e.Node.Parent?.Tag != null && (e.Node.Parent.Tag.ToString() == "cache" || e.Node.Parent.Tag.ToString() == "uoadesign")) - { - MultiComponentList list = (MultiComponentList)e.Node.Tag; - if (list != null) - { - _compList = new MultiEditorComponentList(list, this); - - textBox_SaveToID.Text = "0"; - } - } - else - { - MultiComponentList multi = e.Node.Parent?.Name == "uop" - ? Multis.GetUopComponents((int)e.Node.Tag) - : Multis.GetComponents((int)e.Node.Tag); - - _compList = new MultiEditorComponentList(multi, this); - - textBox_SaveToID.Text = e.Node.Tag.ToString(); - } - - ClearTileReferences(); - UndoList_Clear(); - - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - MaxHeightTrackBar.Value = _compList.ZMax; - - numericUpDown_Size_Width.Value = _compList.Width; - numericUpDown_Size_Height.Value = _compList.Height; - - numericUpDown_Selected_X.Maximum = _compList.Width - 1; - numericUpDown_Selected_Y.Maximum = _compList.Height - 1; - - vScrollBar.Value = 0; - hScrollBar.Value = 0; - - ScrollbarsSetValue(); - - pictureBoxMulti.Invalidate(); - } - - private void TreeViewMultiList_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e) - { - switch (e.Node.Tag) - { - case int nodeTag: - { - MultiComponentList list = e.Node.Parent?.Name == "uop" - ? Multis.GetUopComponents(nodeTag) - : Multis.GetComponents(nodeTag); - toolTip1.SetToolTip(treeViewMultiList, $"{list.Width}x{list.Height} {list.SortedTiles.Length}"); - break; - } - case MultiComponentList multiComponentList: - { - MultiComponentList list = multiComponentList; - toolTip1.SetToolTip(treeViewMultiList, $"{list.Width}x{list.Height} {list.SortedTiles.Length}"); - break; - } - } - } - - private void TreeViewTilesXML_OnAfterSelect(object sender, TreeViewEventArgs e) - { - if (e.Node.Tag == null) - { - return; - } - - _drawTilesCategory = e.Node.Tag as List ?? GetAllValidStatics(); - ApplyDrawTilesFilter(); - } - - /// - /// Tiles of the selected tree node, before the filter textbox is applied. - /// - private List _drawTilesCategory = new List(); - - private const string _allTilesTag = "AllTiles"; - - private static List GetAllValidStatics() - { - int maxItemId = Art.GetMaxItemId(); - var list = new List(maxItemId + 1); - for (int i = 0; i <= maxItemId; ++i) - { - if (Art.IsValidStatic(i)) - { - list.Add(i); - } - } - - return list; - } - - /// - /// Shows the tiles of the selected node whose name contains the filter text (case insensitive), - /// or whose id matches when the text is a 0x prefixed hex number. - /// - private void ApplyDrawTilesFilter() - { - string filter = textBoxDrawTilesFilter.Text.Trim(); - - if (filter.Length == 0) - { - _drawTilesList = _drawTilesCategory; - } - else if (filter.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && Utils.ConvertStringToInt(filter, out int id)) - { - _drawTilesList = _drawTilesCategory.Where(tile => tile == id).ToList(); - } - else - { - _drawTilesList = _drawTilesCategory - // Art can hold more ids than tiledata - .Where(tile => tile < TileData.ItemTable.Length && - TileData.ItemTable[tile].Name?.Contains(filter, StringComparison.OrdinalIgnoreCase) == true) - .ToList(); - } - - vScrollBarDrawTiles.Maximum = (_drawTilesList.Count / Math.Max(1, _pictureBoxDrawTilesCol)) + 1; - vScrollBarDrawTiles.Minimum = 1; - vScrollBarDrawTiles.SmallChange = 1; - vScrollBarDrawTiles.LargeChange = 1; - vScrollBarDrawTiles.Value = 1; - pictureBoxDrawTiles.Invalidate(); - } - - private void TextBoxDrawTilesFilter_TextChanged(object sender, EventArgs e) - { - ApplyDrawTilesFilter(); - } - - private void Undo_onClick(object sender, EventArgs e) - { - if (_compList == null) - { - return; - } - - ToolStripMenuItem item = (ToolStripMenuItem)sender; - - int undo = (int)item.Tag; - _compList.Undo(undo); - - ClearTileReferences(); - SyncControlsToList(); - - pictureBoxMulti.Invalidate(); - } - - private void UndoList_BeforeOpening(object sender, EventArgs e) - { - if (_compList == null) - { - return; - } - - UndoItems.DropDownItems.Clear(); - for (int i = 0; i < _compList.UndoList.Count; i++) - { - var item = new ToolStripMenuItem(_compList.UndoList[i].Action ?? "---") - { - Tag = i - }; - item.Click += Undo_onClick; - UndoItems.DropDownItems.Add(item); - } - - if (UndoItems.DropDownItems.Count == 0) - { - UndoItems.DropDownItems.Add(new ToolStripMenuItem("---") { Enabled = false }); - } - } - - private void UndoList_Clear() - { - _compList?.UndoClear(); - UndoItems.DropDownItems.Clear(); - _minimapTilesBmp?.Dispose(); - _minimapTilesBmp = null; - _minimapDirty = true; - } - - private static void XML_AddChildren(TreeNode node, XmlElement mainNode) - { - foreach (XmlElement e in mainNode) - { - TreeNode tempNode = new TreeNode { Text = e.GetAttribute("name") }; - - if (e.Name == "subgroup") - { - tempNode.ImageIndex = 0; - - if (e.HasChildNodes) - { - List list = new List(); - foreach (XmlElement elem in e.ChildNodes) - { - int i = int.Parse(elem.GetAttribute("index")); - if (Art.IsValidStatic(i)) - { - list.Add(i); - } - } - - tempNode.Tag = list; - } - } - - node.Nodes.Add(tempNode); - } - } - - private void XML_InitializeToolBox() - { - // Rebuilt on every file path change, so start over instead of appending duplicates - treeViewTilesXML.Nodes.Clear(); - _drawTilesCategory = new List(); - _drawTilesList = _drawTilesCategory; - - // Every valid static, built when selected so it reflects the art loaded at that time - treeViewTilesXML.Nodes.Add(new TreeNode("All Tiles") { Tag = _allTilesTag, ImageIndex = 0 }); - - string path = Options.AppDataPath; - string fileName = Path.Combine(path, "plugins/multieditor.xml"); - if (!File.Exists(fileName)) - { - return; - } - - XmlDocument dom = new XmlDocument(); - dom.Load(fileName); - - XmlElement xTiles = dom["TileGroups"]; - if (xTiles == null) - { - return; - } - - foreach (XmlElement xRootGroup in xTiles) - { - TreeNode mainNode = new TreeNode - { - Text = xRootGroup.GetAttribute("name"), - Tag = null, - ImageIndex = 0 - }; - - XML_AddChildren(mainNode, xRootGroup); - treeViewTilesXML.Nodes.Add(mainNode); - } - } - - public void SelectDrawTile(ushort id) - { - _drawTile.Set(id, 0); - PictureBoxDrawTiles_Select(); - DrawTileLabel.Text = $"Draw ID: 0x{id:X}"; - UpdateRecentSelection(); - } - - private int GetIndex(int x, int y) - { - if (x >= _pictureBoxDrawTilesCol) - { - return -1; - } - - int value = Math.Max(0, (_pictureBoxDrawTilesCol * (vScrollBarDrawTiles.Value - 1)) + x + (y * _pictureBoxDrawTilesCol)); - - if (_drawTilesList.Count > value) - { - return _drawTilesList[value]; - } - - return -1; - } - - private void PictureBoxDrawTiles_OnMouseClick(object sender, MouseEventArgs e) - { - pictureBoxDrawTiles.Focus(); - - int x = e.X / (_drawTileSizeWidth - 1); - int y = e.Y / (_drawTileSizeHeight - 1); - - int index = GetIndex(x, y); - if (index < 0) - { - return; - } - - _drawTile.Set((ushort)index, 0); - - DrawTileLabel.Text = $"Draw ID: 0x{index:X}"; - - pictureBoxDrawTiles.Invalidate(); - UpdateRecentSelection(); - } - - private void PictureBoxDrawTilesMouseMove(object sender, MouseEventArgs e) - { - pictureBoxDrawTiles.Invalidate(); - } - - private void PictureBoxDrawTilesMouseLeave(object sender, EventArgs e) - { - FloatingPreviewPanel.Visible = false; - - pictureBoxDrawTiles.Invalidate(); - } - - private void PictureBoxDrawTiles_OnPaint(object sender, PaintEventArgs e) - { - e.Graphics.Clear(pictureBoxDrawTiles.BackColor); - - for (int y = 0; y < _pictureBoxDrawTilesRow; ++y) - { - for (int x = 0; x < _pictureBoxDrawTilesCol; ++x) - { - int index = GetIndex(x, y); - if (index < 0) - { - continue; - } - - Bitmap b = Art.GetStatic(index); - - if (b == null) - { - continue; - } - - Point loc = new Point((x * _drawTileSizeWidth) + 1, (y * _drawTileSizeHeight) + 1); - Size size = new Size(_drawTileSizeWidth - 1, _drawTileSizeHeight - 1); - Rectangle rect = new Rectangle(loc, size); - - e.Graphics.SetClip(rect); - - if (index == _drawTile.Id) - { - e.Graphics.FillRectangle(Brushes.LightBlue, rect); - } - - int width = b.Width; - int height = b.Height; - if (width > size.Width) - { - width = size.Width; - height = size.Height * b.Height / b.Width; - } - - if (height > size.Height) - { - height = size.Height; - width = size.Width * b.Width / b.Height; - } - - e.Graphics.DrawImage(b, new Rectangle(loc, new Size(width, height))); - } - } - - var pos = pictureBoxDrawTiles.PointToClient(MousePosition); - if (!pictureBoxDrawTiles.ClientRectangle.Contains(pos)) - { - return; - } - - int x1 = pos.X / (_drawTileSizeWidth - 1); - int y1 = pos.Y / (_drawTileSizeHeight - 1); - int staticIdx = GetIndex(x1, y1); - - if (staticIdx >= 0) - { - if (staticIdx != (int)FloatingPreviewPanel.Tag) - { - FloatingPreviewPanel.BackgroundImage = Art.GetStatic(staticIdx); - FloatingPreviewPanel.Size = - new Size(Art.GetStatic(staticIdx).Width + 10, Art.GetStatic(staticIdx).Height + 10); - } - - var currentPos = PointToClient(MousePosition); - FloatingPreviewPanel.Left = currentPos.X; - FloatingPreviewPanel.Top = currentPos.Y - FloatingPreviewPanel.Size.Height; - FloatingPreviewPanel.Visible = true; - FloatingPreviewPanel.Tag = staticIdx; - - toolTip1.SetToolTip(pictureBoxDrawTiles, string.Format("0x{0:X} ({0})", staticIdx)); - } - else - { - FloatingPreviewPanel.Visible = false; - toolTip1.SetToolTip(pictureBoxDrawTiles, string.Empty); - } - } - - private void PictureBoxDrawTiles_OnResize(object sender, EventArgs e) - { - if (pictureBoxDrawTiles.Height == 0 || pictureBoxDrawTiles.Width == 0) - { - return; - } - - _pictureBoxDrawTilesCol = pictureBoxDrawTiles.Width / _drawTileSizeWidth; - _pictureBoxDrawTilesRow = (pictureBoxDrawTiles.Height / _drawTileSizeHeight) + 1; - vScrollBarDrawTiles.Maximum = (_drawTilesList.Count / _pictureBoxDrawTilesCol) + 1; - vScrollBarDrawTiles.Minimum = 1; - vScrollBarDrawTiles.SmallChange = 1; - vScrollBarDrawTiles.LargeChange = _pictureBoxDrawTilesRow; - pictureBoxDrawTiles.Invalidate(); - } - - private void VScrollBarDrawTiles_Scroll(object sender, ScrollEventArgs e) - { - pictureBoxDrawTiles.Invalidate(); - } - - private void PictureBoxDrawTiles_OnMouseWheel(object sender, MouseEventArgs e) - { - if (e.Delta < 0) - { - if (vScrollBarDrawTiles.Value < vScrollBarDrawTiles.Maximum) - { - vScrollBarDrawTiles.Value++; - pictureBoxDrawTiles.Invalidate(); - } - } - else - { - if (vScrollBarDrawTiles.Value > 1) - { - vScrollBarDrawTiles.Value--; - pictureBoxDrawTiles.Invalidate(); - } - } - } - - private void PictureBoxDrawTiles_Select() - { - foreach (TreeNode node in treeViewTilesXML.Nodes) - { - foreach (TreeNode childNode in node.Nodes) - { - if (childNode.Tag == null) - { - continue; - } - - foreach (int index in (List)childNode.Tag) - { - if (index != _drawTile.Id) - { - continue; - } - - treeViewTilesXML.SelectedNode = childNode; - pictureBoxDrawTiles.Invalidate(); - return; - } - } - } - } - - /// - /// Drops every reference to tiles of the previous list. Undo, redo and opening a multi - /// rebuild the tiles as new objects, so old references would edit tiles no longer shown. - /// - private void ClearTileReferences() - { - _selectedTiles.Clear(); - _overlayList.Clear(); - HoverTile = null; - SelectedTile = null; - _isPasteMode = false; - } - - /// - /// Brings the size, height and selection limits in line with the current list. - /// - private void SyncControlsToList() - { - UpdateTrackBarAfterZChange(); - - numericUpDown_Size_Width.Value = _compList.Width; - numericUpDown_Size_Height.Value = _compList.Height; - - numericUpDown_Selected_X.Maximum = _compList.Width - 1; - numericUpDown_Selected_Y.Maximum = _compList.Height - 1; - - ScrollbarsSetValue(); - } - - /// - /// True when keyboard focus is in a text or number box, which needs its own keys - /// (minus, brackets, arrows, Ctrl+C/V/Z). - /// - private bool IsTextInputFocused() - { - Control focused = ActiveControl; - while (focused is ContainerControl { ActiveControl: not null } container) - { - focused = container.ActiveControl; - } - - return focused is TextBoxBase or UpDownBase or ComboBox; - } - - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) - { - if (_compList != null && (keyData == Keys.Escape || !IsTextInputFocused())) - { - // Undo / Redo - if (keyData == (Keys.Control | Keys.Z)) - { - if (_compList.UndoStep()) - { - ClearTileReferences(); - SyncControlsToList(); - pictureBoxMulti.Invalidate(); - } - - return true; - } - - if (keyData == (Keys.Control | Keys.Y) || keyData == (Keys.Control | Keys.Shift | Keys.Z)) - { - if (_compList.RedoStep()) - { - ClearTileReferences(); - SyncControlsToList(); - pictureBoxMulti.Invalidate(); - } - - return true; - } - - // Z up/down for selection: [ = -1, ] = +1 - IEnumerable zTargets = _selectedTiles.Count > 0 - ? (IEnumerable)_selectedTiles - : (SelectedTile != null ? new[] { SelectedTile } : null); - - if (keyData == Keys.OemOpenBrackets && zTargets != null) - { - _compList.TileZMod(zTargets, -1); - UpdateTrackBarAfterZChange(); - pictureBoxMulti.Invalidate(); - return true; - } - - if (keyData == Keys.OemCloseBrackets && zTargets != null) - { - _compList.TileZMod(zTargets, 1); - UpdateTrackBarAfterZChange(); - pictureBoxMulti.Invalidate(); - return true; - } - - // Copy / Paste - if (keyData == (Keys.Control | Keys.C) && _selectedTiles.Count > 0) - { - int ox = _selectedTiles.Min(t => t.X); - int oy = _selectedTiles.Min(t => t.Y); - int oz = _selectedTiles.Min(t => t.Z); - _clipboard = _selectedTiles.Select(t => (t.Id, t.X - ox, t.Y - oy, t.Z - oz, t.Invisible, t.Extra)).ToList(); - return true; - } - - if (keyData == (Keys.Control | Keys.V) && _clipboard != null) - { - _isPasteMode = true; - pictureBoxMulti.Invalidate(); - return true; - } - - if (keyData == Keys.Escape && _isPasteMode) - { - _isPasteMode = false; - pictureBoxMulti.Invalidate(); - return true; - } - - // Navigation: arrow keys pan, PgUp/PgDn step floor - const int PanStep = 22; - if (keyData == Keys.Left) { hScrollBar.Value = Math.Max(0, hScrollBar.Value - PanStep); return true; } - if (keyData == Keys.Right) { hScrollBar.Value = Math.Min(hScrollBar.Maximum, hScrollBar.Value + PanStep); return true; } - if (keyData == Keys.Up) { vScrollBar.Value = Math.Max(0, vScrollBar.Value - PanStep); return true; } - if (keyData == Keys.Down) { vScrollBar.Value = Math.Min(vScrollBar.Maximum, vScrollBar.Value + PanStep); return true; } - - if (keyData == Keys.PageUp) - { - numericUpDown_Floor.Value = Math.Min(numericUpDown_Floor.Maximum, numericUpDown_Floor.Value + 5); - return true; - } - - if (keyData == Keys.PageDown) - { - numericUpDown_Floor.Value = Math.Max(numericUpDown_Floor.Minimum, numericUpDown_Floor.Value - 5); - return true; - } - - // Zoom - if (keyData == Keys.Add || keyData == (Keys.Shift | Keys.Oemplus)) - { - SetZoom(_zoomFactor + 0.1f); - return true; - } - - if (keyData == Keys.Subtract || keyData == Keys.OemMinus) - { - SetZoom(_zoomFactor - 0.1f); - return true; - } - - if (keyData == (Keys.Control | Keys.D0) || keyData == (Keys.Control | Keys.NumPad0)) - { - SetZoom(1.0f); - return true; - } - - if (keyData == Keys.S) { BTN_Select_Click(null, EventArgs.Empty); return true; } - if (keyData == Keys.D) { BTN_Draw_Click(null, EventArgs.Empty); return true; } - if (keyData == Keys.R) { BTN_Remove_Click(null, EventArgs.Empty); return true; } - if (keyData == Keys.E) { BTN_Z_Click(null, EventArgs.Empty); return true; } - if (keyData == Keys.F) { BTN_Floor.Checked = !BTN_Floor.Checked; return true; } - if (keyData == Keys.P) { BTN_Pipette_Click(null, EventArgs.Empty); return true; } - if (keyData == Keys.T) { BTN_Trans_Clicked(null, EventArgs.Empty); return true; } - if (keyData == Keys.B) { BTN_RectFill_Click(null, EventArgs.Empty); return true; } - if (keyData == Keys.L) { BTN_LineDraw_Click(null, EventArgs.Empty); return true; } - } - - return base.ProcessCmdKey(ref msg, keyData); - } - - /// - /// Returns the line end constrained to the dominant axis when Shift is held. - /// - private (int ex, int ey) GetLineEnd(int rawEx, int rawEy) - { - if ((ModifierKeys & Keys.Shift) == 0) - { - return (rawEx, rawEy); - } - - int dx = Math.Abs(rawEx - _lineStartX); - int dy = Math.Abs(rawEy - _lineStartY); - return dx >= dy - ? (rawEx, _lineStartY) // horizontal axis - : (_lineStartX, rawEy); // vertical axis - } - - private void SetZoom(float factor) - { - _zoomFactor = Math.Clamp(factor, 0.25f, 4.0f); - toolStripBtnZoom.Text = $"{(int)Math.Round(_zoomFactor * 100)}%"; - pictureBoxMulti.Invalidate(); - } - - private void ToolStripBtnZoom_Click(object sender, EventArgs e) - { - SetZoom(1.0f); - } - - private void ToolStripBtnHelp_Click(object sender, EventArgs e) - { - using var form = new ShortcutsHelpForm(); - form.ShowDialog(this); - } - - private void UpdateTrackBarAfterZChange() - { - MaxHeightTrackBar.Minimum = _compList.ZMin; - MaxHeightTrackBar.Maximum = _compList.ZMax; - if (MaxHeightTrackBar.Value < _compList.ZMax) - { - MaxHeightTrackBar.Value = _compList.ZMax; - } - - _minimapDirty = true; - } - - private void BTN_DynamicCheckBox_Changed(object sender, EventArgs e) - { - if (_compList == null || SelectedTile == null) - { - return; - } - - _compList.TileSetInvisible(SelectedTile, DynamiccheckBox.Checked); - } - - private void BTN_ShowWalkables_Click(object sender, EventArgs e) - { - showWalkablesToolStripMenuItem.Text = "Show Walkable tiles"; - if (!ShowWalkables || _compList == null) - { - return; - } - - _compList.CalcWalkable(); - - pictureBoxMulti.Invalidate(); - } - - private void BTN_ShowAllTrans(object sender, EventArgs e) - { - if (_compList == null) - { - return; - } - - foreach (MultiTile tile in _compList.Tiles) - { - tile.Transparent = false; - } - - pictureBoxMulti.Invalidate(); - } - - private void BTN_ShowDoubleSurface(object sender, EventArgs e) - { - showDoubleSurfaceMenuItem.Text = "Show double surface"; - - if (!ShowDoubleSurface || _compList == null) - { - return; - } - - _compList.CalcDoubleSurface(); - - pictureBoxMulti.Invalidate(); - } - - private void OnDummyContextMenuOpening(object sender, System.ComponentModel.CancelEventArgs e) - { - e.Cancel = true; - } - - private void InitializeRecentTab() - { - var recentTab = new TabPage { Text = "Recent" }; - - _recentPanel = new FlowLayoutPanel - { - Dock = DockStyle.Fill, - AutoScroll = true, - Padding = new Padding(2) - }; - - for (int i = 0; i < TileRecentlyUsed.MaxRecentTiles; i++) - { - var slot = new PictureBox - { - Size = new Size(44, 44), - BorderStyle = BorderStyle.FixedSingle, - SizeMode = PictureBoxSizeMode.Zoom, - Tag = -1, - BackColor = Color.Transparent - }; - slot.Click += RecentSlot_Click; - - _recentSlots.Add(slot); - _recentPanel.Controls.Add(slot); - } - - recentTab.Controls.Add(_recentPanel); - TC_MultiEditorToolbox.TabPages.Add(recentTab); - } - - private void RefreshRecentPanel() - { - for (int i = 0; i < _recentSlots.Count; i++) - { - var slot = _recentSlots[i]; - if (i < _recentTiles.Count) - { - slot.Tag = _recentTiles[i]; - slot.Image = Ultima.Art.GetStatic(_recentTiles[i]); - toolTip1.SetToolTip(slot, $"0x{_recentTiles[i]:X}"); - } - else - { - slot.Tag = -1; - slot.Image = null; - toolTip1.SetToolTip(slot, string.Empty); - } - } - - UpdateRecentSelection(); - } - - private void UpdateRecentSelection() - { - foreach (var slot in _recentSlots) - { - slot.BackColor = slot.Tag is int id && id == _drawTile.Id - ? Color.LightBlue - : Color.Transparent; - } - } - - private void RecentSlot_Click(object sender, EventArgs e) - { - if (sender is PictureBox pb && pb.Tag is int id && id >= 0) - { - _drawTile.Set((ushort)id, 0); - DrawTileLabel.Text = $"Draw ID: 0x{id:X}"; - PictureBoxDrawTiles_Select(); - pictureBoxDrawTiles.Invalidate(); - UpdateRecentSelection(); - } - } - - private void RecordRecentTile(int tileId) - { - if (tileId < 0) - { - return; - } - - _recentTiles.Remove(tileId); - _recentTiles.Insert(0, tileId); - if (_recentTiles.Count > TileRecentlyUsed.MaxRecentTiles) - { - _recentTiles.RemoveAt(_recentTiles.Count - 1); - } - - TileRecentlyUsed.Save(_recentTiles); - RefreshRecentPanel(); - } - - private void UpdateMinimap() - { - if (_compList == null || pictureBoxMinimap.Width <= 0 || pictureBoxMinimap.Height <= 0) - { - return; - } - - int multiW = _compList.XMax - _compList.XMin + MultiEditorComponentList.GapXMod * 2; - int multiH = _compList.YMaxOrg - _compList.YMin + MultiEditorComponentList.GapYMod * 3; - if (multiW <= 0 || multiH <= 0) - { - return; - } - - float scaleX = (float)pictureBoxMinimap.Width / multiW; - float scaleY = (float)pictureBoxMinimap.Height / multiH; - float scale = Math.Min(scaleX, scaleY); - if (scale <= 0) - { - return; - } - - // Regenerate tile-dot layer only when tiles changed - if (_minimapDirty || _minimapTilesBmp == null) - { - _minimapDirty = false; - _minimapTilesBmp?.Dispose(); - _minimapTilesBmp = new Bitmap(pictureBoxMinimap.Width, pictureBoxMinimap.Height); - using (var gfx = Graphics.FromImage(_minimapTilesBmp)) - { - gfx.Clear(Color.DimGray); - int dotSize = Math.Max(1, (int)(2 * scale)); - using (var brush = new SolidBrush(Color.LightGray)) - { - foreach (MultiTile tile in _compList.Tiles) - { - if (tile.IsVirtualFloor) - { - continue; - } - - int px = (int)((tile.XMod - _compList.XMin) * scale); - int py = (int)((tile.YMod - _compList.YMin) * scale); - gfx.FillRectangle(brush, px, py, dotSize, dotSize); - } - } - } - } - - // Composite: tile dots + fresh viewport rect every frame - var bmp = new Bitmap(pictureBoxMinimap.Width, pictureBoxMinimap.Height); - using (var gfx = Graphics.FromImage(bmp)) - { - gfx.DrawImageUnscaled(_minimapTilesBmp, 0, 0); - - float vx = hScrollBar.Value * scale; - float vy = vScrollBar.Value * scale; - float vw = pictureBoxMulti.Width * scale; - float vh = pictureBoxMulti.Height * scale; - gfx.DrawRectangle(Pens.Red, vx, vy, Math.Max(1, vw), Math.Max(1, vh)); - } - - pictureBoxMinimap.Image?.Dispose(); - pictureBoxMinimap.Image = bmp; - } - - private void PictureBoxMinimap_OnMouseClick(object sender, MouseEventArgs e) - { - if (_compList == null) - { - return; - } - - int multiW = _compList.XMax - _compList.XMin + MultiEditorComponentList.GapXMod * 2; - int multiH = _compList.YMaxOrg - _compList.YMin + MultiEditorComponentList.GapYMod * 3; - if (multiW <= 0 || multiH <= 0) - { - return; - } - - float scaleX = (float)pictureBoxMinimap.Width / multiW; - float scaleY = (float)pictureBoxMinimap.Height / multiH; - float scale = Math.Min(scaleX, scaleY); - if (scale <= 0) - { - return; - } - - int newHScroll = Math.Clamp((int)(e.X / scale) - pictureBoxMulti.Width / 2, 0, hScrollBar.Maximum); - int newVScroll = Math.Clamp((int)(e.Y / scale) - pictureBoxMulti.Height / 2, 0, vScrollBar.Maximum); - hScrollBar.Value = newHScroll; - vScrollBar.Value = newVScroll; - } - } -} \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.resx b/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.resx deleted file mode 100644 index 28b60d2b..00000000 --- a/UoFiddler.Plugin.MultiEditor/UserControls/MultiEditorControl.resx +++ /dev/null @@ -1,869 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 478, 17 - - - 261, 17 - - - 353, 17 - - - - AAEAAAD/////AQAAAAAAAAAMAgAAAEZTeXN0ZW0uV2luZG93cy5Gb3JtcywgQ3VsdHVyZT1uZXV0cmFs - LCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAmU3lzdGVtLldpbmRvd3MuRm9ybXMu - SW1hZ2VMaXN0U3RyZWFtZXIBAAAABERhdGEHAgIAAAAJAwAAAA8DAAAARKoAAAJNU0Z0AUkBTAIBARIB - AAEsAQEBLAEBARIBAAESAQAE/wEhAQAI/wFCAU0BNgcAATYDAAEoAwABSAMAAVoDAAEBAQABIAUAAUAB - ZRIAAc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ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB - /wGHAWYBPAH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB - 0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB - /wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB - 0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB - /wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB - 0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB - /wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB - 0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB - /wHIAdAB1AH/AcgB0AHUAf8ByAHQAdQB/wFCAU0BPgcAAT4DAAEoAwABSAMAAVoDAAEBAQABAQUAATgB - BBYAA///AP8A/wD/AD0ACw== - - - - 162, 17 - - - 52 - - \ No newline at end of file diff --git a/UoFiddler.Plugin.MultiEditor/images/AltitudeButton.bmp b/UoFiddler.Plugin.MultiEditor/images/AltitudeButton.bmp deleted file mode 100644 index 96bbca48..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/AltitudeButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/AltitudeButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/AltitudeButton_Selected.bmp deleted file mode 100644 index d936c230..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/AltitudeButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/AltitudeButton_Selected.psd b/UoFiddler.Plugin.MultiEditor/images/AltitudeButton_Selected.psd deleted file mode 100644 index 74efd715..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/AltitudeButton_Selected.psd and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/DrawButton.bmp b/UoFiddler.Plugin.MultiEditor/images/DrawButton.bmp deleted file mode 100644 index f6172dd6..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/DrawButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/DrawButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/DrawButton_Selected.bmp deleted file mode 100644 index 0d574e6e..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/DrawButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/Help-Icon-16.png b/UoFiddler.Plugin.MultiEditor/images/Help-Icon-16.png deleted file mode 100644 index 6efed7eb..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/Help-Icon-16.png and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/LineDrawButton.bmp b/UoFiddler.Plugin.MultiEditor/images/LineDrawButton.bmp deleted file mode 100644 index eb9443bf..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/LineDrawButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/LineDrawButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/LineDrawButton_Selected.bmp deleted file mode 100644 index 0981e298..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/LineDrawButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/PipetteButton.bmp b/UoFiddler.Plugin.MultiEditor/images/PipetteButton.bmp deleted file mode 100644 index a03362bd..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/PipetteButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/PipetteButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/PipetteButton_Selected.bmp deleted file mode 100644 index 87a655ff..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/PipetteButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/RectFillButton.bmp b/UoFiddler.Plugin.MultiEditor/images/RectFillButton.bmp deleted file mode 100644 index 2972acb3..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/RectFillButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/RectFillButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/RectFillButton_Selected.bmp deleted file mode 100644 index a4dd8961..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/RectFillButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/RemoveButton.bmp b/UoFiddler.Plugin.MultiEditor/images/RemoveButton.bmp deleted file mode 100644 index 59c9787e..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/RemoveButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/RemoveButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/RemoveButton_Selected.bmp deleted file mode 100644 index 3a2830df..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/RemoveButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/SelectButton.bmp b/UoFiddler.Plugin.MultiEditor/images/SelectButton.bmp deleted file mode 100644 index bf12c116..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/SelectButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/SelectButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/SelectButton_Selected.bmp deleted file mode 100644 index 996a065d..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/SelectButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/TransButton.bmp b/UoFiddler.Plugin.MultiEditor/images/TransButton.bmp deleted file mode 100644 index 32a80a9b..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/TransButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/TransButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/TransButton_Selected.bmp deleted file mode 100644 index 2d84ac33..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/TransButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/TransButton_Selected.psd b/UoFiddler.Plugin.MultiEditor/images/TransButton_Selected.psd deleted file mode 100644 index c0e1cb08..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/TransButton_Selected.psd and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton.bmp b/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton.bmp deleted file mode 100644 index 1d022ef9..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton_Selected.bmp b/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton_Selected.bmp deleted file mode 100644 index 99d3dd64..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton_Selected.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton_Selected.psd b/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton_Selected.psd deleted file mode 100644 index 8d04d714..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/VirtualFloorButton_Selected.psd and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/images/treeViewImage.bmp b/UoFiddler.Plugin.MultiEditor/images/treeViewImage.bmp deleted file mode 100644 index aba12f3a..00000000 Binary files a/UoFiddler.Plugin.MultiEditor/images/treeViewImage.bmp and /dev/null differ diff --git a/UoFiddler.Plugin.MultiEditor/multieditor.xml b/UoFiddler.Plugin.MultiEditor/multieditor.xml index 4228b22c..dfd53d58 100644 --- a/UoFiddler.Plugin.MultiEditor/multieditor.xml +++ b/UoFiddler.Plugin.MultiEditor/multieditor.xml @@ -1426,6 +1426,9 @@ + + + @@ -1441,6 +1444,10 @@ + + + + @@ -1777,6 +1784,10 @@ + + + + @@ -1898,6 +1909,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -8743,6 +8848,11 @@ + + + + + @@ -9108,4 +9218,1679 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/UoFiddler/Classes/FiddlerOptions.cs b/UoFiddler/Classes/FiddlerOptions.cs index f562fee5..11a9312f 100644 --- a/UoFiddler/Classes/FiddlerOptions.cs +++ b/UoFiddler/Classes/FiddlerOptions.cs @@ -251,6 +251,19 @@ public static void SaveProfile() } } + if (Options.PluginSettings.Count > 0) + { + comment = dom.CreateComment("Plugin settings"); + sr.AppendChild(comment); + foreach (KeyValuePair setting in System.Linq.Enumerable.OrderBy(Options.PluginSettings, s => s.Key, StringComparer.Ordinal)) + { + XmlElement xmlSetting = dom.CreateElement("PluginSetting"); + xmlSetting.SetAttribute("name", setting.Key); + xmlSetting.SetAttribute("value", setting.Value ?? string.Empty); + sr.AppendChild(xmlSetting); + } + } + comment = dom.CreateComment("Path settings"); sr.AppendChild(comment); elem = dom.CreateElement("RootPath"); @@ -487,6 +500,12 @@ public static void LoadProfile(string filename) Options.PluginsToLoad.Add(name); } + Options.PluginSettings.Clear(); + foreach (XmlElement xSetting in xOptions.SelectNodes("PluginSetting")) + { + Options.PluginSettings[xSetting.GetAttribute("name")] = xSetting.GetAttribute("value"); + } + elem = (XmlElement)xOptions.SelectSingleNode("RootPath"); if (elem != null) { diff --git a/UoFiddler/Forms/AboutBoxForm.resx b/UoFiddler/Forms/AboutBoxForm.resx index c4bfd929..ca2aa07a 100644 --- a/UoFiddler/Forms/AboutBoxForm.resx +++ b/UoFiddler/Forms/AboutBoxForm.resx @@ -118,7 +118,22 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Version 4.27.0 + Version 4.28.0 +- Multi Editor: replaced by an OpenGL editor (3.0.0) with a tool palette, document tabs, a tile browser with house styles, blueprints and UO Architect designs, floors, a plan view and a preview +- Multi Editor: document tabs have close buttons and Close all designs, and the mouse wheel over the tab strip switches designs +- Multi Editor: one work plane follows the chosen floor and moves a Z at a time with Ctrl+PgUp/PgDn; its Z shows in the status bar +- Multi Editor: designs stay centred when the canvas resizes until panned or zoomed, and Center design centres them again +- Multi Editor: rotating turns each piece by its art and the client's house tables, so classic roofs and stair corners keep their facing +- Multi Editor: import several multi files or every multi in a folder at once; files that fail are skipped and listed +- Multi Editor: reads and writes UO Architect (.uoa and Designs.idx/bin), UOHE, WorldForge and POL multiforge designs, and exports every importable format +- Multi Editor: 1,697 more tiles in the tile groups and a tile rotation table +- Multi Editor: faster hover hit test and a performance box (F12) with frame, GPU, draw and lag timings +- Compare plugin: the compare views are sub-tabs of one Compare tab; the mouse wheel over the strip switches them +- Multis: the preview no longer flickers when switching entries +- Plugins: dependencies load from plugins\<plugin name>\, settings are kept in the profile, and plugins can add items to the Map tab's context menu +- Plugins: new ThemedTabControl with mouse wheel tab switching and dark mode painting + +Version 4.27.0 - Animations: pack an action's frames, or every action of a body, into a sprite sheet with a Json descriptor, and import sheets back into an action or a whole body. Directions 5-7 can be packed and are flipped back on import - Items: export and import item ranges as sprite sheets - Animations: export frames aligned on one canvas, centered like the Gif export, with a transparent background for Png and Tiff diff --git a/UoFiddler/UoFiddler.csproj b/UoFiddler/UoFiddler.csproj index 46430632..c000f846 100644 --- a/UoFiddler/UoFiddler.csproj +++ b/UoFiddler/UoFiddler.csproj @@ -9,9 +9,9 @@ UoFiddler UoFiddler Copyright © 2026 - 4.27.0 - 4.27.0 - 4.27.0 + 4.28.0 + 4.28.0 + 4.28.0 true