diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs deleted file mode 100644 index 0d2d73d5..00000000 --- a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs +++ /dev/null @@ -1,442 +0,0 @@ -/*************************************************************************** - * - * $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/Editing/EditorLevel.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorLevel.cs new file mode 100644 index 00000000..f132a50e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorLevel.cs @@ -0,0 +1,21 @@ +/*************************************************************************** + * + * "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.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})"; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Clipboard.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Clipboard.cs new file mode 100644 index 00000000..9b33ec05 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Clipboard.cs @@ -0,0 +1,125 @@ +/*************************************************************************** + * + * "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.Linq; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Model; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + internal sealed partial class EditorSession + { + // Shared by every open document, so a copy in one tab pastes into another. + private static List _clipboard; + + // ---------------------------------------------------------------- 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(); + + /// Puts a copy of the selection on the cursor to place with the mouse. The clipboard is left alone. + public void Duplicate() + { + BeginPaste(SelectionAsClipboard(), "Duplicate"); + } + + /// The selection as tiles relative to its lowest X, Y and Z (also used to save a blueprint). + public List SelectionAsClipboard() + { + return _selection.Count == 0 ? null : ToClipboard(_selection); + } + + /// Every tile of the design, relative to its lowest X, Y and Z; null when it is empty. + public List DesignAsClipboard() + { + List tiles = CompList.RealTiles.ToList(); + return tiles.Count == 0 ? null : ToClipboard(tiles); + } + + 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; + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs index 0712822d..c479ba57 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs @@ -11,105 +11,21 @@ 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; +using UoFiddler.Plugin.MultiEditor.House; +using UoFiddler.Plugin.MultiEditor.Model; +using UoFiddler.Plugin.MultiEditor.Rendering; +using UoFiddler.Plugin.MultiEditor.Storage; +using UoFiddler.Plugin.MultiEditor.Styles; 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(); - - /// Puts a copy of the selection on the cursor to place with the mouse. The clipboard is left alone. - public void Duplicate() - { - BeginPaste(SelectionAsClipboard(), "Duplicate"); - } - // ---------------------------------------------------------------- layers public IReadOnlyList Layers => CompList.Layers; @@ -239,7 +155,7 @@ public DesignData ToDesign() { return new DesignData(Title, CompList.Width, CompList.Height, FirstFloorZ, CustomLevels ? _levelDefinitions.ToList() : null, CompList.DesignLayers(), - CompList.Layers.ToList().IndexOf(CompList.ActiveLayer)); + CompList.Layers.ToList().IndexOf(CompList.ActiveLayer), PlacedHouses.ToList()); } /// Opens what a design file holds as this session's document. @@ -247,13 +163,14 @@ public void LoadDesign(DesignData design) { NewBlank(design.Width, design.Height, design.FirstFloorZ); CompList.RestoreLayers(design.Layers, design.ActiveLayer, (0, 0)); + SetPlacedHouses(design.Houses); if (design.Levels != null) { SetLevelDefinitions(design.Levels); } RebuildLevels(); - Modified = false; + MarkClean(); DocumentChanged?.Invoke(); LayersChanged?.Invoke(); OnViewChanged(); @@ -358,60 +275,6 @@ public void RepeatSelection(int copies, int dx, int dy, int dz) AfterEdit(dz > 0 ? tiles.Max(t => t.z) : null); } - /// The selection as tiles relative to its lowest X, Y and Z (also used to save a blueprint). - public List SelectionAsClipboard() - { - return _selection.Count == 0 ? null : ToClipboard(_selection); - } - - /// Every tile of the design, relative to its lowest X, Y and Z; null when it is empty. - public List DesignAsClipboard() - { - List tiles = CompList.RealTiles.ToList(); - return tiles.Count == 0 ? null : ToClipboard(tiles); - } - - 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() @@ -833,271 +696,5 @@ public PointF TileAnchor(MultiTile tile) 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.Drafts.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Drafts.cs new file mode 100644 index 00000000..07827442 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Drafts.cs @@ -0,0 +1,157 @@ +/*************************************************************************** + * + * "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 UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.House; +using UoFiddler.Plugin.MultiEditor.Model; +using UoFiddler.Plugin.MultiEditor.Storage; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + internal sealed partial class EditorSession + { + // ---------------------------------------------------------------- placed houses + + private readonly List _placedHouses = new List(); + + /// + /// The houses placed with the House tool, each as the draft it was placed from. They are + /// kept with the design (design file, layers file), so a placed house can be opened as a + /// draft again. + /// + public IReadOnlyList PlacedHouses => _placedHouses; + + private string FreeHouseName() + { + for (int n = _placedHouses.Count + 1; ; ++n) + { + string name = $"House {n}"; + if (_placedHouses.All(h => (string)h.Attribute("name") != name) && CompList.Layers.All(l => l.Name != name)) + { + return name; + } + } + } + + /// Sets the placed houses of a design just opened, moved by an offset (the layers file counts cells from the save origin). + public void SetPlacedHouses(IEnumerable houses, int dx = 0, int dy = 0) + { + _placedHouses.Clear(); + foreach (System.Xml.Linq.XElement house in houses ?? Enumerable.Empty()) + { + try + { + _placedHouses.Add(dx == 0 && dy == 0 ? new System.Xml.Linq.XElement(house) : HouseDraftFile.Shifted(house, dx, dy, HouseStyles)); + } + catch (System.IO.InvalidDataException) + { + // A house that cannot be read is only lost as a draft: its tiles are in the multi. + } + } + + DraftChanged?.Invoke(); + } + + /// The placed houses moved by an offset, for a file that counts cells from another origin. + public List PlacedHousesShifted(int dx, int dy) + { + return _placedHouses.Select(h => HouseDraftFile.Shifted(h, dx, dy, HouseStyles)).ToList(); + } + + /// + /// Opens a placed house as a draft again: the tiles it was placed with that are still in + /// the multi are taken out (one undo step) and the House tool gets its draft back. Tiles + /// changed by hand since stay where they are. Returns what is wrong, or null. + /// + public string ReopenHouse(System.Xml.Linq.XElement house) + { + if (House.HasPending) + { + return "Place or drop the house being designed first."; + } + + List<(ushort Id, int X, int Y, int Z, string Layer)> built; + try + { + built = House.TilesOf(house); + } + catch (System.IO.InvalidDataException ex) + { + return ex.Message; + } + + // The house is on the layer named after it, or on a layer per part. + string name = (string)house.Attribute("name"); + var remove = new List(); + foreach ((ushort id, int x, int y, int z, string layer) in built) + { + MultiTile tile = CompList.GetTilesAt(x, y).FirstOrDefault(t => + t.Id == id && t.Z == z && (t.Layer.Name == name || t.Layer.Name == layer) && !remove.Contains(t)); + if (tile != null) + { + remove.Add(tile); + } + } + + _placedHouses.Remove(house); + if (remove.Count * 2 < built.Count) + { + DraftChanged?.Invoke(); + return "This house is no longer in the multi: most of its tiles were changed or removed."; + } + + CompList.ReplaceTilesOnLayers(remove, new List<(ushort, int, int, int, string)>(), "Edit house", HouseDraft.WallsLayer); + House.OpenXml(house, keepName: true); + AfterEdit(); + LayersChanged?.Invoke(); + return null; + } + + /// The house tool, for its draft and options. + public HouseTool House => (HouseTool)_tools[ToolKind.House]; + + /// Raised when a roof or house draft starts, changes or ends. + public event Action DraftChanged; + + /// The roof or house tool when it is the tool in use, else null. + public WingDraftTool WingTool => _temporaryTool == null ? _tools[_toolKind] as WingDraftTool : null; + + /// + /// The draft that Enter places, Esc drops and undo steps through: the one of the wing + /// tool in use, else an open house draft (which stays open under the other tools). + /// + public WingDraftTool OpenDraft => WingTool is { HasPending: true } tool ? tool : House.HasPending ? House : null; + + /// + /// The open draft when the tool in use works on it (a wing tool, or a tool that edits the + /// house draft): the one Enter places and Esc drops. + /// + public WingDraftTool DraftInFocus => _temporaryTool != null ? null + : WingTool is { HasPending: true } tool ? tool + : House.HasPending && ActiveTool is DraftEditTool ? House : null; + + /// True while a wing tool is in use and holds a draft that is not placed yet. + public bool ShapingRoof => WingTool is { HasPending: true }; + + /// The storey of an open house draft that the chosen floor means. + public int DraftStorey => House.StoreyFor(WorkZ); + + /// Draws an open house draft while a tool that does not work on it is in use. + public void PaintIdleDraft(IToolOverlay overlay) + { + if (House.HasPending && _temporaryTool == null && ActiveTool is not (HouseTool or DraftEditTool)) + { + House.PaintDraft(overlay, active: false); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Levels.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Levels.cs new file mode 100644 index 00000000..34d8a8a3 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Levels.cs @@ -0,0 +1,316 @@ +/*************************************************************************** + * + * "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.Model; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + internal sealed partial class EditorSession + { + 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; + + // ---------------------------------------------------------------- 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. + /// A design without a floor has it where most of its walls stand. + /// + 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) + { + 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; + } + } + } + + // No floor laid (a building lifted off the map stands on terrain): where its walls stand. + var walls = new Dictionary(); + foreach (MultiTile tile in CompList.RealTiles) + { + if (tile.Z >= 0 && tile.Z <= MaxFirstFloorZ && tile.Height >= 10 && + (TileData.ItemTable[tile.Id].Flags & TileFlag.Wall) != 0) + { + walls[tile.Z] = walls.GetValueOrDefault(tile.Z) + 1; + } + } + + int best = 0, most = 3; + foreach ((int z, int count) in walls) + { + if (count > most) + { + (best, most) = (z, count); + } + } + + return best; + } + + /// 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.Selection.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Selection.cs new file mode 100644 index 00000000..ea049ef8 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Selection.cs @@ -0,0 +1,276 @@ +/*************************************************************************** + * + * "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.Linq; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Tools; +using UoFiddler.Plugin.MultiEditor.Rendering; +using UoFiddler.Plugin.MultiEditor.Model; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + internal sealed partial class EditorSession + { + // ---------------------------------------------------------------- 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(); + } + + /// Takes tiles out of the selection, with one change notice. + public void Deselect(IEnumerable tiles) + { + bool changed = false; + foreach (MultiTile tile in tiles) + { + changed |= _selection.Remove(tile); + } + + if (changed) + { + SelectionChanged?.Invoke(); + Invalidated?.Invoke(); + } + } + + private HashSet _listHighlight = new HashSet(); + + /// + /// Tiles pointed at outside the canvas (a row of the selection list), drawn like the hovered + /// tile. Empty for none. + /// + public IReadOnlyCollection ListHighlight + { + get => _listHighlight; + set + { + var next = value == null ? new HashSet() : new HashSet(value); + if (next.SetEquals(_listHighlight)) + { + return; + } + + _listHighlight = next; + Invalidated?.Invoke(); + } + } + + public bool IsListHighlighted(MultiTile tile) => _listHighlight.Count > 0 && _listHighlight.Contains(tile); + + /// 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(); + + // Alt+click with a draw tool picks a tile: the tool does not see the click. + _pickClick = PickingWithAlt; + if (!_pickClick) + { + 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) + { + if (_pickClick) + { + _pickClick = false; + if (HoverTile != null) + { + PickDrawTile(HoverTile.Id); + } + } + else + { + ActiveTool.OnMouseUp(e); + } + } + + Invalidated?.Invoke(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs index 2fa581f9..95e8293d 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs @@ -10,40 +10,15 @@ 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; +using UoFiddler.Plugin.MultiEditor.Model; +using UoFiddler.Plugin.MultiEditor.Styles; 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 @@ -53,6 +28,7 @@ internal sealed partial class EditorSession : IEditorContext, IMultiViewSettings { private readonly HashSet _selection = new HashSet(); private readonly Dictionary _tools = new Dictionary(); + private readonly Dictionary _draftTools = new Dictionary(); private readonly ArtMasks _masks; private readonly PasteTool _pasteTool; private readonly RepeatPreviewTool _repeatTool; @@ -92,7 +68,28 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles) _tools[ToolKind.Floor] = new FloorStyleTool(this); _tools[ToolKind.Door] = new DoorTool(this); _tools[ToolKind.Stair] = new StairTool(this); - _tools[ToolKind.Roof] = new RoofTool(this); + var roof = new RoofTool(this); + var house = new HouseTool(this, roof); + foreach (WingDraftTool draft in new WingDraftTool[] { roof, house }) + { + draft.Changed += () => + { + DraftChanged?.Invoke(); + ToolChanged?.Invoke(); + Invalidated?.Invoke(); + }; + draft.Committed += () => LayersChanged?.Invoke(); + } + + house.FreeName = FreeHouseName; + house.Placed += placed => _placedHouses.Add(placed); + + _tools[ToolKind.Roof] = roof; + _tools[ToolKind.House] = house; + _draftTools[ToolKind.Wall] = new DraftWallTool(this, house); + _draftTools[ToolKind.Door] = new DraftDoorTool(this, house); + _draftTools[ToolKind.Floor] = new DraftFloorTool(this, house); + _draftTools[ToolKind.Stair] = new DraftStairTool(this, house); _tools[ToolKind.Foundation] = new FoundationTool(this); _tools[ToolKind.FloorPattern] = new FloorPatternTool(this); _pasteTool = new PasteTool(this); @@ -136,9 +133,43 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles) /// Name shown on the document tab. public string Title { get; set; } = "Untitled"; - /// True when there are edits since the last save or load. + /// + /// True when there are edits since the last save or load. Undoing back to the step that + /// was saved makes the design unchanged again; an edit that left no step in the history + /// keeps it changed. + /// public bool Modified { get; private set; } + // The history step on top when the design was saved, and when it was last looked at. + private EditCommand _savedStep; + private EditCommand _lastStep; + private bool _unloggedEdit; + private bool _steppingHistory; + + private EditCommand TopStep => CompList.UndoList.Count > 0 ? CompList.UndoList[0] : null; + + private void MarkClean() + { + _savedStep = _lastStep = TopStep; + _unloggedEdit = false; + Modified = false; + } + + /// The names of the steps Undo would take back, the latest first. + public IReadOnlyList UndoSteps(int most) + { + var names = new List(); + if (UndoDraftTool == null) + { + for (int i = 0; i < CompList.UndoList.Count && i < most; ++i) + { + names.Add(CompList.UndoList[i].Action); + } + } + + return names; + } + public void NewBlank(int width, int height, int firstFloorZ = 0) { SetDocument(new MultiEditorComponentList(width, height, this)); @@ -152,35 +183,104 @@ public void Load(MultiComponentList list) public void MarkSaved() { - Modified = false; + MarkClean(); DocumentChanged?.Invoke(); } + /// True when Undo has something to take back: a step of an open draft, or of the multi. + public bool CanUndo => HasDocument && (UndoDraftTool != null || CompList.UndoList.Count > 0); + + public bool CanRedo => HasDocument && (RedoDraftTool != null || (OpenDraft == null && CompList.RedoList.Count > 0) || + (OpenDraft is { ReopenedFrom: not null } reopened && CompList.RedoList.Count > 0 && + ReferenceEquals(CompList.RedoList[0], reopened.ReopenedFrom))); + + // The draft whose history undo and redo walk first: the wing tool in use, else the house. + private WingDraftTool UndoDraftTool => WingTool is { CanUndoDraft: true } tool ? tool : House.CanUndoDraft ? House : null; + + private WingDraftTool RedoDraftTool => WingTool is { CanRedoDraft: true } tool ? tool : House.CanRedoDraft ? House : null; + + /// + /// Takes back the last step: of the draft being shaped while there is one, else of the + /// multi. Undoing the step that placed a roof or house brings its draft back as it was. + /// public bool Undo() { + if (UndoDraftTool is { } draft) + { + return draft.UndoDraft(); + } + + EditCommand step = CompList.UndoList.Count > 0 ? CompList.UndoList[0] : null; if (!CompList.UndoStep()) { return false; } + foreach (WingDraftTool tool in new WingDraftTool[] { House, Roof }) + { + // A roof draft shows only with the roof tool, so it comes back only there; a + // house draft shows under every tool. + if (tool.PlacedBy != null && ReferenceEquals(tool.PlacedBy, step) && !tool.HasPending && + (tool is HouseTool || _toolKind == ToolKind.Roof)) + { + tool.Reopen(); + if (tool is HouseTool reopened && reopened.LastPlaced != null) + { + _placedHouses.Remove(reopened.LastPlaced); + } + } + } + + _steppingHistory = true; AfterEdit(); + _steppingHistory = false; + LayersChanged?.Invoke(); return true; } + /// + /// Redoes a step of the draft being shaped, else of the multi. While a draft is open the + /// multi's steps wait, except the one that placed that very draft. + /// public bool Redo() { + if (RedoDraftTool is { } draft) + { + return draft.RedoDraft(); + } + + if (OpenDraft is { } open) + { + if (open.ReopenedFrom == null || CompList.RedoList.Count == 0 || !ReferenceEquals(CompList.RedoList[0], open.ReopenedFrom)) + { + return false; + } + + open.CloseReopened(); + if (open is HouseTool closed && closed.LastPlaced != null && !_placedHouses.Contains(closed.LastPlaced)) + { + _placedHouses.Add(closed.LastPlaced); + } + } + if (!CompList.RedoStep()) { return false; } + _steppingHistory = true; AfterEdit(); + _steppingHistory = false; + LayersChanged?.Invoke(); return true; } private void SetDocument(MultiEditorComponentList list) { CancelTool(); + Roof.Reset(); + House.Reset(); + _placedHouses.Clear(); CompList = list; _selection.Clear(); HoverTile = null; @@ -188,7 +288,7 @@ private void SetDocument(MultiEditorComponentList list) _activeLevel = null; _levelIndex = 0; _workPlaneOffset = 0; - Modified = false; + MarkClean(); _firstFloorZ = DetectFirstFloorZ(); _levelDefinitions.Clear(); CustomLevels = false; @@ -343,6 +443,13 @@ public ToolKind Tool get => _toolKind; set { + // A roof still being shaped is placed when another tool is taken up. + // A house draft stays open instead: the wall, door, floor and stair tools work on it. + if (_toolKind == ToolKind.Roof && value != ToolKind.Roof) + { + Roof.Commit(); + } + CancelTool(); _toolKind = value; if (IsTileTool(value)) @@ -355,7 +462,12 @@ public ToolKind Tool } } - public EditorTool ActiveTool => _temporaryTool ?? _tools[_toolKind]; + /// + /// The tool in use. While a house draft is open the wall, door, floor and stair tools are + /// the ones that change the draft. + /// + public EditorTool ActiveTool => _temporaryTool ?? + (House.HasPending && _draftTools.TryGetValue(_toolKind, out EditorTool draftTool) ? draftTool : _tools[_toolKind]); /// True for the tools that place the draw tile (draw, rectangle, line). public static bool IsTileTool(ToolKind kind) @@ -374,7 +486,7 @@ public static bool IsTileTool(ToolKind kind) /// 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). + /// The roof tool, for its shape options (ridge, gables, gable fill) and the roof being shaped. public RoofTool Roof => (RoofTool)_tools[ToolKind.Roof]; /// Call after a tool option changed, so the preview under the cursor follows. @@ -455,260 +567,6 @@ public void PickDrawTile(ushort id) } } - // ---------------------------------------------------------------- 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(); - } - - /// Takes tiles out of the selection, with one change notice. - public void Deselect(IEnumerable tiles) - { - bool changed = false; - foreach (MultiTile tile in tiles) - { - changed |= _selection.Remove(tile); - } - - if (changed) - { - SelectionChanged?.Invoke(); - Invalidated?.Invoke(); - } - } - - private HashSet _listHighlight = new HashSet(); - - /// - /// Tiles pointed at outside the canvas (a row of the selection list), drawn like the hovered - /// tile. Empty for none. - /// - public IReadOnlyCollection ListHighlight - { - get => _listHighlight; - set - { - var next = value == null ? new HashSet() : new HashSet(value); - if (next.SetEquals(_listHighlight)) - { - return; - } - - _listHighlight = next; - Invalidated?.Invoke(); - } - } - - public bool IsListHighlighted(MultiTile tile) => _listHighlight.Count > 0 && _listHighlight.Contains(tile); - - /// 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(); - - // Alt+click with a draw tool picks a tile: the tool does not see the click. - _pickClick = PickingWithAlt; - if (!_pickClick) - { - 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) - { - if (_pickClick) - { - _pickClick = false; - if (HoverTile != null) - { - PickDrawTile(HoverTile.Id); - } - } - else - { - ActiveTool.OnMouseUp(e); - } - } - - Invalidated?.Invoke(); - } - // ---------------------------------------------------------------- IEditorContext Point IEditorContext.MouseLoc => _mouseLoc; @@ -762,7 +620,15 @@ public void AfterEdit(int? raiseTo = null) SelectionChanged?.Invoke(); } - Modified = true; + // A change that left no step in the history cannot be undone back to the saved state. + EditCommand top = TopStep; + if (ReferenceEquals(top, _lastStep) && !_steppingHistory) + { + _unloggedEdit = true; + } + + _lastStep = top; + Modified = _unloggedEdit || !ReferenceEquals(top, _savedStep); RebuildLevels(); if (_showWalkables) { diff --git a/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs b/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs index f052304e..dcf46056 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs @@ -9,15 +9,8 @@ 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; +using UoFiddler.Plugin.MultiEditor.Model; namespace UoFiddler.Plugin.MultiEditor.Editing { @@ -251,326 +244,4 @@ private static List Period(List run) 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/FloorPatterns.cs b/UoFiddler.Plugin.MultiEditor/Editing/FloorPatterns.cs new file mode 100644 index 00000000..777dd39c --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/FloorPatterns.cs @@ -0,0 +1,194 @@ +/*************************************************************************** + * + * "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; + +namespace UoFiddler.Plugin.MultiEditor.Editing +{ + /// + /// 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; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/LevelDefinition.cs b/UoFiddler.Plugin.MultiEditor/Editing/LevelDefinition.cs new file mode 100644 index 00000000..1c9886b4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/LevelDefinition.cs @@ -0,0 +1,14 @@ +/*************************************************************************** + * + * "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.Editing +{ + /// 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); +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/PreviewTerrain.cs b/UoFiddler.Plugin.MultiEditor/Editing/PreviewTerrain.cs new file mode 100644 index 00000000..12c9b371 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/PreviewTerrain.cs @@ -0,0 +1,21 @@ +/*************************************************************************** + * + * "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.Editing +{ + /// The ground a previewed multi stands on. + internal enum PreviewTerrain + { + None, + Grass, + Dirt, + Sand, + Snow + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Editing/ToolKind.cs b/UoFiddler.Plugin.MultiEditor/Editing/ToolKind.cs new file mode 100644 index 00000000..70a33721 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Editing/ToolKind.cs @@ -0,0 +1,39 @@ +/*************************************************************************** + * + * "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.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, + + /// Designs a whole house as a draft and places it. + House + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/FrontDoorSide.cs b/UoFiddler.Plugin.MultiEditor/House/FrontDoorSide.cs new file mode 100644 index 00000000..0c3a48b3 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/FrontDoorSide.cs @@ -0,0 +1,28 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// + /// A house being designed, beside its wings: the materials of each storey and what was changed + /// by hand (partitions, openings, doors, windows, floor areas, stairs). + /// turns wings and draft into tiles. A wing's box is its wall cells, as the wall tool drags + /// them: walls stand on the +Y / +X edges of their cells, so the rooms inside are the box + /// without its first row and column. + /// + /// The outer wall of the first wing that gets the front door. + internal enum FrontDoorSide + { + None, + South, + East + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Build.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Build.cs new file mode 100644 index 00000000..bb8e60c4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Build.cs @@ -0,0 +1,344 @@ +/*************************************************************************** + * + * $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 UoFiddler.Plugin.MultiEditor.Styles; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.House +{ + internal sealed partial class HouseDraft + { + /// The tiles of a built draft, each with its layer, and the walls among them. + public sealed class Built + { + public List<(ushort Id, int X, int Y, int Z, string Layer)> Tiles { get; } = new List<(ushort, int, int, int, string)>(); + + public List<(ushort Id, int X, int Y, int Z)> Walls { get; } = new List<(ushort, int, int, int)>(); + } + + /// + /// Foundation, walls with their doors and windows, floors and stairs of the house, storey + /// by storey. The roof is not part of it: the roof tool plans it over these walls. + /// + public Built Build(IReadOnlyList wings, HouseStyles styles) + { + var built = new Built(); + int top = Top(wings); + var cut = new HashSet<(int X, int Y)>[MaxStoreys + 1]; + + // Stairs first: a run opens the floor of the storey it climbs to. + foreach ((int storey, int x, int y, string column, HouseStyle style) in Stairs) + { + if (storey >= top || !Region(wings, storey).Contains((x, y))) + { + continue; + } + + foreach ((ushort id, int tx, int ty, int tz) in StairTool.Tiles(style, column, x, y, BaseZ + (storey * StoreyHeight))) + { + built.Tiles.Add((id, tx, ty, tz, StairsLayer)); + (cut[storey + 1] ??= new HashSet<(int X, int Y)>()).Add((tx, ty)); + } + } + + for (int storey = 0; storey < top; ++storey) + { + int z = BaseZ + (storey * StoreyHeight); + HashSet<(int X, int Y)> region = Region(wings, storey); + StoreyLayout layout = LayOut(wings, storey); + HashSet<(int X, int Y)> south = layout.South, east = layout.East; + + HouseStyle foundation = FoundationStyle; + if (foundation == null) + { + styles.TryGetRole(FoundationTool.FoundationPost, out foundation, out _); + } + + if (storey == 0 && Foundation && foundation != null) + { + var ringSouth = new HashSet<(int X, int Y)>(); + var ringEast = new HashSet<(int X, int Y)>(); + Outline(region, ringSouth, ringEast); + foreach ((int x, int y) in WallCells(ringSouth, ringEast)) + { + string column = WallPlanner.PieceFor(ringSouth, ringEast, x, y); + ushort id = column != null ? foundation.Get(column) : (ushort)0; + // One row, or rows one on the other, each as high as the piece. + int rise = id != 0 ? Math.Max(1, (int)Ultima.TileData.ItemTable[id].Height) : 0; + for (int tier = 0; id != 0 && tier < Math.Clamp(FoundationTiers, 1, 3); ++tier) + { + built.Tiles.Add((id, x, y, z - FoundationHeight + (tier * rise), FoundationLayer)); + } + } + } + + HouseStyle wallStyle = WallStyles[storey]; + foreach ((int x, int y) in WallCells(south, east)) + { + if (Doors.TryGetValue((storey, x, y), out (HouseStyle Style, string Piece) door) && + (WallPlanner.DoorAlongX(door.Piece) ? south : east).Contains((x, y)) && door.Style.Get(door.Piece) is var doorId and not 0) + { + built.Tiles.Add((doorId, x, y, z, WallsLayer)); + built.Walls.Add((doorId, x, y, z)); + continue; + } + + // A door the draft hangs by itself: between rooms, or the front door. + if (DoorStyle != null && layout.Doors.TryGetValue((x, y), out string ownPiece) && + (WallPlanner.DoorAlongX(ownPiece) ? south : east).Contains((x, y)) && DoorStyle.Get(ownPiece) is var ownId and not 0) + { + built.Tiles.Add((ownId, x, y, z, WallsLayer)); + built.Walls.Add((ownId, x, y, z)); + continue; + } + + string column = WallPlanner.PieceFor(wallStyle, south, east, x, y); + if (column == null || wallStyle == null) + { + continue; + } + + ushort id = wallStyle.Get(column); + if ((Windows.Contains((storey, x, y)) || layout.Windows.Contains((x, y))) && column != "Corner" && column != "Post" && + styles.WindowFor(wallStyle, south.Contains((x, y))) is var windowId and not 0) + { + id = windowId; + } + + if (id != 0) + { + built.Tiles.Add((id, x, y, z, WallsLayer)); + built.Walls.Add((id, x, y, z)); + } + } + + foreach ((int x, int y) in region) + { + if (cut[storey] != null && cut[storey].Contains((x, y))) + { + continue; + } + + HouseStyle floorStyle = FloorStyles[storey]; + foreach ((int areaStorey, int x0, int y0, int x1, int y1, HouseStyle areaStyle) in FloorAreas) + { + if (areaStorey == storey && x >= x0 && x <= x1 && y >= y0 && y <= y1) + { + floorStyle = areaStyle; + } + } + + if (floorStyle == null) + { + continue; + } + + ushort[] pieces = Pieces(floorStyle); + if (pieces.Length > 0) + { + // The same cell always gets the same piece, so the preview does not flicker. + built.Tiles.Add((pieces[(int)((uint)HashCode.Combine(x, y, storey) % (uint)pieces.Length)], x, y, z, FloorsLayer)); + } + } + } + + // Flat roofs: the floor of the wing's top storey once more, on top of its walls. Where a + // taller wing stands, its own floor is there already. + foreach (RoofWing wing in wings) + { + int storeys = Math.Clamp(wing.Storeys, 1, MaxStoreys); + HouseStyle style = FlatRoofStyle ?? FloorStyles[storeys - 1]; + if (wing.NoRoof || wing.Shape != RoofShape.Flat || style == null) + { + continue; + } + + HashSet<(int X, int Y)> above = Region(wings, storeys); + ushort[] pieces = Pieces(style); + for (int x = wing.X0 + 1; pieces.Length > 0 && x <= wing.X1; ++x) + { + for (int y = wing.Y0 + 1; y <= wing.Y1; ++y) + { + if (!above.Contains((x, y))) + { + built.Tiles.Add((pieces[(int)((uint)HashCode.Combine(x, y, storeys) % (uint)pieces.Length)], x, y, + BaseZ + (storeys * StoreyHeight), RoofTool.LayerName)); + } + } + } + } + + if (Parapet) + { + AddParapets(wings, styles, built); + } + + if (Foundation && StairStyle != null && top > 0 && LayOut(wings, 0).FrontDoor is { } front) + { + AddSteps(front, styles, built); + } + + return built; + } + + /// + /// Steps up to the front door of a house on a foundation, as the client's houses have + /// them: one row outside the door, a step under it and a corner piece on each side, 5 + /// below the floor (the pieces are 5 high). + /// + private void AddSteps((int X, int Y) door, HouseStyles styles, Built built) + { + bool south = FrontDoor == FrontDoorSide.South; + ushort step = StairStyle.Get(south ? "North" : "West"); + if (step == 0) + { + return; + } + + // The step's top meets the floor; on a foundation lower than the step it starts where the foundation does. + int z = BaseZ - Math.Min(FoundationHeight, Math.Max(1, (int)Ultima.TileData.ItemTable[step].Height)); + (int X, int Y) at = south ? (door.X, door.Y + 1) : (door.X + 1, door.Y); + built.Tiles.Add((step, at.X, at.Y, z, StairsLayer)); + + // The corners: south-east, north-east, north-west, south-west of a stair set. + ushort before = StairStyle.Get("Squared1"), after = StairStyle.Get("Squared2"); + if (after != 0 && styles.TryGetStairCorner(after, out ushort[] corners, out _) && corners.Length == 4) + { + (before, after) = south ? (corners[3], corners[0]) : (corners[1], corners[0]); + } + else if (!south) + { + (before, after) = (0, 0); + } + + if (before != 0 && (south ? at.X : at.Y) > 0) + { + built.Tiles.Add((before, south ? at.X - 1 : at.X, south ? at.Y : at.Y - 1, z, StairsLayer)); + } + + if (after != 0) + { + built.Tiles.Add((after, south ? at.X + 1 : at.X, south ? at.Y : at.Y + 1, z, StairsLayer)); + } + } + + /// + /// Battlements around the flat roofs. The flat wings of one height are walled as one + /// roof: along its edge, but not where a taller wing stands (its wall is there). Measured + /// on the client's tower, keep and castle: the edging stands in the roof's wall cells at + /// the roof's Z and once more on top of that, and a third row has every second straight + /// piece, leaving the corners out. + /// + private void AddParapets(IReadOnlyList wings, HouseStyles styles, Built built) + { + // A wing without a roof is a walled yard: its walls carry battlements too. + foreach (IGrouping level in wings.Where(w => w.NoRoof || w.Shape == RoofShape.Flat).GroupBy(w => Math.Clamp(w.Storeys, 1, MaxStoreys))) + { + int storeys = level.Key; + HouseStyle style = styles.ParapetFor(WallStyles[storeys - 1]); + if (style == null) + { + continue; + } + + HashSet<(int X, int Y)> above = Region(wings, storeys); + var roof = new HashSet<(int X, int Y)>(); + foreach (RoofWing wing in level) + { + for (int x = wing.X0 + 1; x <= wing.X1; ++x) + { + for (int y = wing.Y0 + 1; y <= wing.Y1; ++y) + { + if (!above.Contains((x, y))) + { + roof.Add((x, y)); + } + } + } + } + + if (roof.Count == 0) + { + continue; + } + + var south = new HashSet<(int X, int Y)>(); + var east = new HashSet<(int X, int Y)>(); + Outline(roof, south, east); + south.RemoveWhere(c => above.Contains(c) || above.Contains((c.X, c.Y + 1))); + east.RemoveWhere(c => above.Contains(c) || above.Contains((c.X + 1, c.Y))); + + // The wall cells start one before the roof cells; the tower counts its merlons from there. + int minX = roof.Min(c => c.X) - 1, minY = roof.Min(c => c.Y) - 1; + int z = BaseZ + (storeys * StoreyHeight); + int tier = Math.Max(1, (int)Ultima.TileData.ItemTable[style.Get("South2")].Height); + foreach ((int x, int y) in WallCells(south, east)) + { + string column = WallPlanner.PieceFor(south, east, x, y); + ushort id = column != null ? style.Get(column) : (ushort)0; + if (id == 0) + { + continue; + } + + built.Tiles.Add((id, x, y, z, RoofTool.LayerName)); + built.Tiles.Add((id, x, y, z + tier, RoofTool.LayerName)); + + // The merlons: every second straight piece. + bool alongX = column.StartsWith("South", StringComparison.Ordinal), alongY = column.StartsWith("East", StringComparison.Ordinal); + if ((alongX && (x - minX) % 2 == 0) || (alongY && (y - minY) % 2 == 0)) + { + built.Tiles.Add((id, x, y, z + (2 * tier), RoofTool.LayerName)); + } + else if (column == "Corner" && (x - minX) % 2 == 0 && style.Get("South2") is var merlon and not 0) + { + // A corner cell in step with the wall along X carries that wall's merlon (the tower's inner corner does). + built.Tiles.Add((merlon, x, y, z + (2 * tier), RoofTool.LayerName)); + } + } + } + } + + private readonly Dictionary _pieces = new Dictionary(); + + private ushort[] Pieces(HouseStyle style) + { + if (!_pieces.TryGetValue(style, out ushort[] pieces)) + { + _pieces[style] = pieces = style.Slots.Values.Where(id => HouseStyle.InTileData(id)).Distinct().ToArray(); + } + + return pieces; + } + + /// Every cell that may hold a wall piece: the cells with an edge, and the ones a post goes in. + private static HashSet<(int X, int Y)> WallCells(HashSet<(int X, int Y)> south, HashSet<(int X, int Y)> east) + { + var cells = new HashSet<(int X, int Y)>(south); + cells.UnionWith(east); + foreach ((int x, int y) in south) + { + cells.Add((x - 1, y)); + } + + foreach ((int x, int y) in east) + { + cells.Add((x, y - 1)); + } + + cells.RemoveWhere(c => c.X < 0 || c.Y < 0); + return cells; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.HandEdits.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.HandEdits.cs new file mode 100644 index 00000000..afd2318d --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.HandEdits.cs @@ -0,0 +1,179 @@ +/*************************************************************************** + * + * $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.Linq; +using UoFiddler.Plugin.MultiEditor.Styles; + +namespace UoFiddler.Plugin.MultiEditor.House +{ + internal sealed partial class HouseDraft + { + /// + /// Moves what was changed by hand inside a wing along with that wing: walls added and + /// taken away, doors, windows, floor areas and stairs whose cell lies in the box. + /// + public void ShiftWithin((int X0, int Y0, int X1, int Y1) box, int dx, int dy) + { + if (dx == 0 && dy == 0) + { + return; + } + + bool In(int x, int y) => x >= box.X0 && x <= box.X1 && y >= box.Y0 && y <= box.Y1; + void Move(HashSet<(int X, int Y)> set) + { + var moved = new List<(int X, int Y)>(); + foreach ((int x, int y) in set) + { + moved.Add(In(x, y) ? (x + dx, y + dy) : (x, y)); + } + + set.Clear(); + set.UnionWith(moved); + } + + void MoveOnStoreys(HashSet<(int Storey, int X, int Y)> set) + { + var moved = new List<(int Storey, int X, int Y)>(); + foreach ((int storey, int x, int y) in set) + { + moved.Add(In(x, y) ? (storey, x + dx, y + dy) : (storey, x, y)); + } + + set.Clear(); + set.UnionWith(moved); + } + + for (int k = 0; k < MaxStoreys; ++k) + { + Move(AddedSouth[k]); + Move(AddedEast[k]); + Move(ErasedSouth[k]); + Move(ErasedEast[k]); + } + + MoveOnStoreys(Windows); + MoveOnStoreys(Suppressed); + var doors = new List>(Doors); + Doors.Clear(); + foreach (var door in doors) + { + (int storey, int x, int y) = door.Key; + Doors[In(x, y) ? (storey, x + dx, y + dy) : door.Key] = door.Value; + } + + for (int i = 0; i < FloorAreas.Count; ++i) + { + var a = FloorAreas[i]; + if (In(a.X0, a.Y0) && In(a.X1, a.Y1)) + { + FloorAreas[i] = (a.Storey, a.X0 + dx, a.Y0 + dy, a.X1 + dx, a.Y1 + dy, a.Style); + } + } + + for (int i = 0; i < Stairs.Count; ++i) + { + var s = Stairs[i]; + if (In(s.X, s.Y)) + { + Stairs[i] = (s.Storey, s.X + dx, s.Y + dy, s.Column, s.Style); + } + } + } + + /// + /// What was changed by hand inside a wing, for a copy of the wing: walls added and taken + /// away, doors, windows, floor areas and stairs whose cell lies in the box. + /// + public HouseDraft CopyWithin((int X0, int Y0, int X1, int Y1) box) + { + var part = new HouseDraft(); + CopyHandEditsInto(part, box); + return part; + } + + // A box that holds every cell. + private static readonly (int X0, int Y0, int X1, int Y1) _everywhere = (int.MinValue, int.MinValue, int.MaxValue, int.MaxValue); + + /// Adds the hand edits whose cell lies in the box to . + private void CopyHandEditsInto(HouseDraft part, (int X0, int Y0, int X1, int Y1) box) + { + bool In(int x, int y) => x >= box.X0 && x <= box.X1 && y >= box.Y0 && y <= box.Y1; + for (int k = 0; k < MaxStoreys; ++k) + { + part.AddedSouth[k].UnionWith(AddedSouth[k].Where(c => In(c.X, c.Y))); + part.AddedEast[k].UnionWith(AddedEast[k].Where(c => In(c.X, c.Y))); + part.ErasedSouth[k].UnionWith(ErasedSouth[k].Where(c => In(c.X, c.Y))); + part.ErasedEast[k].UnionWith(ErasedEast[k].Where(c => In(c.X, c.Y))); + } + + foreach (var door in Doors) + { + if (In(door.Key.X, door.Key.Y)) + { + part.Doors[door.Key] = door.Value; + } + } + + part.Windows.UnionWith(Windows.Where(c => In(c.X, c.Y))); + part.Suppressed.UnionWith(Suppressed.Where(c => In(c.X, c.Y))); + part.FloorAreas.AddRange(FloorAreas.Where(a => In(a.X0, a.Y0) && In(a.X1, a.Y1))); + part.Stairs.AddRange(Stairs.Where(s => In(s.X, s.Y))); + } + + /// Adds what took, moved by this many cells: the hand edits of a pasted wing. + public void AddShifted(HouseDraft part, int dx, int dy) + { + HouseDraft moved = part.Clone(); + moved.Shift(dx, dy); + + // Where the pasted wing says otherwise, it wins: a wall added there is no longer + // taken away, a door replaces a window, and the reverse. + for (int k = 0; k < MaxStoreys; ++k) + { + ErasedSouth[k].ExceptWith(moved.AddedSouth[k]); + ErasedEast[k].ExceptWith(moved.AddedEast[k]); + AddedSouth[k].ExceptWith(moved.ErasedSouth[k]); + AddedEast[k].ExceptWith(moved.ErasedEast[k]); + AddedSouth[k].UnionWith(moved.AddedSouth[k]); + AddedEast[k].UnionWith(moved.AddedEast[k]); + ErasedSouth[k].UnionWith(moved.ErasedSouth[k]); + ErasedEast[k].UnionWith(moved.ErasedEast[k]); + } + + foreach (var door in moved.Doors) + { + Doors[door.Key] = door.Value; + Windows.Remove(door.Key); + } + + foreach (var window in moved.Windows) + { + Windows.Add(window); + Doors.Remove(window); + } + + Suppressed.UnionWith(moved.Suppressed); + FloorAreas.AddRange(moved.FloorAreas); + + // A stair already starting in a cell gives way to the pasted one. + foreach (var stair in moved.Stairs) + { + Stairs.RemoveAll(s => s.Storey == stair.Storey && s.X == stair.X && s.Y == stair.Y); + Stairs.Add(stair); + } + } + + /// Moves everything changed by hand along with the house. + public void Shift(int dx, int dy) => ShiftWithin(_everywhere, dx, dy); + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Layout.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Layout.cs new file mode 100644 index 00000000..e0221dce --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Layout.cs @@ -0,0 +1,533 @@ +/*************************************************************************** + * + * $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 UoFiddler.Plugin.MultiEditor.Styles; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.House +{ + internal sealed partial class HouseDraft + { + /// Storeys of the tallest wing. + public static int Top(IReadOnlyList wings) + { + int top = 0; + foreach (RoofWing wing in wings) + { + top = Math.Max(top, Math.Clamp(wing.Storeys, 1, MaxStoreys)); + } + + return top; + } + + /// The cells inside the house on a storey (0 is the ground floor): the rooms of every wing that high. + public static HashSet<(int X, int Y)> Region(IReadOnlyList wings, int storey) + { + var region = new HashSet<(int X, int Y)>(); + foreach (RoofWing wing in wings) + { + if (wing.Storeys <= storey) + { + continue; + } + + for (int x = wing.X0 + 1; x <= wing.X1; ++x) + { + for (int y = wing.Y0 + 1; y <= wing.Y1; ++y) + { + region.Add((x, y)); + } + } + } + + return region; + } + + /// The wall edges around a region: its outline. + public static void Outline(HashSet<(int X, int Y)> region, HashSet<(int X, int Y)> south, HashSet<(int X, int Y)> east) + { + foreach ((int x, int y) in region) + { + if (!region.Contains((x, y + 1))) + { + south.Add((x, y)); + } + + if (!region.Contains((x, y - 1))) + { + south.Add((x, y - 1)); + } + + if (!region.Contains((x + 1, y))) + { + east.Add((x, y)); + } + + if (!region.Contains((x - 1, y))) + { + east.Add((x - 1, y)); + } + } + } + + /// The wall edges of a storey with its generated doors and windows. + public sealed class StoreyLayout + { + /// Cells with a wall on their +Y edge. + public HashSet<(int X, int Y)> South { get; } = new HashSet<(int X, int Y)>(); + + /// Cells with a wall on their +X edge. + public HashSet<(int X, int Y)> East { get; } = new HashSet<(int X, int Y)>(); + + /// Doors the draft makes itself (room doors, the front door): wall cell and door piece. + public Dictionary<(int X, int Y), string> Doors { get; } = new Dictionary<(int X, int Y), string>(); + + /// Wall cells the draft makes windows itself. + public HashSet<(int X, int Y)> Windows { get; } = new HashSet<(int X, int Y)>(); + + /// The wall cell of the front door, when the storey has one. + public (int X, int Y)? FrontDoor { get; set; } + } + + /// + /// The wall edges of a storey: the outline of its rooms, with the edges added by hand that + /// still touch a room and without the ones taken away. + /// + public void Edges(IReadOnlyList wings, int storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east) + { + StoreyLayout layout = LayOut(wings, storey); + south = layout.South; + east = layout.East; + } + + /// + /// The walls of a storey and what the draft puts in them by itself: the outline of the + /// wings, the walls between the rooms of each wing with their doorways (doors, with + /// ), the edges added and taken away by hand, the front door and + /// the windows along the outer walls. + /// + public StoreyLayout LayOut(IReadOnlyList wings, int storey) + { + var layout = new StoreyLayout(); + HashSet<(int X, int Y)> region = Region(wings, storey); + var outerSouth = new HashSet<(int X, int Y)>(); + var outerEast = new HashSet<(int X, int Y)>(); + Outline(region, outerSouth, outerEast); + layout.South.UnionWith(outerSouth); + layout.East.UnionWith(outerEast); + + HashSet<(int X, int Y)> stairs = StairCells(storey); + RoomPlan firstPlan = null; + for (int index = 0; index < wings.Count; ++index) + { + RoofWing wing = wings[index]; + if (wing.Storeys <= storey) + { + continue; + } + + (int rooms, RoomLayout kind) = wing.RoomsOn(storey); + RoomPlan plan = RoomPlanner.Plan(wing.X0 + 1, wing.Y0 + 1, wing.X1, wing.Y1, kind, Math.Clamp(rooms, 1, MaxRooms)); + RoomPlanner.Avoid(plan, stairs); + if (index == 0) + { + firstPlan = plan; + } + + Partition(wings, index, storey, plan, stairs, layout); + } + + WallOff(wings, storey, region, stairs, layout); + + foreach ((int x, int y) in AddedSouth[storey]) + { + if (region.Contains((x, y)) || region.Contains((x, y + 1))) + { + layout.South.Add((x, y)); + } + } + + foreach ((int x, int y) in AddedEast[storey]) + { + if (region.Contains((x, y)) || region.Contains((x + 1, y))) + { + layout.East.Add((x, y)); + } + } + + layout.South.ExceptWith(ErasedSouth[storey]); + layout.East.ExceptWith(ErasedEast[storey]); + + if (storey == 0) + { + AddFrontDoor(wings, firstPlan, outerSouth, outerEast, stairs, layout); + } + + if (WindowSpacing > 0) + { + AddWindows(storey, outerSouth, true, layout); + AddWindows(storey, outerEast, false, layout); + } + + return layout; + } + + /// The cells stairs stand in on a storey: the stairs that start there and the opening of those that arrive. + private HashSet<(int X, int Y)> StairCells(int storey) + { + var cells = new HashSet<(int X, int Y)>(); + foreach ((int stairStorey, int x, int y, string column, HouseStyle style) in Stairs) + { + if (stairStorey != storey && stairStorey != storey - 1) + { + continue; + } + + foreach ((ushort _, int tx, int ty, int _) in StairTool.Tiles(style, column, x, y, 0)) + { + cells.Add((tx, ty)); + } + } + + return cells; + } + + /// + /// The walls between the rooms of a wing. Each pair of rooms the plan joins gets one + /// doorway, in the middle of the wall they share, or as near to it as stairs allow. A + /// wall is left out where another wing's rooms lie and where it would cut through stairs. + /// + private void Partition(IReadOnlyList wings, int index, int storey, RoomPlan plan, HashSet<(int X, int Y)> stairs, StoreyLayout layout) + { + if (plan.Rooms.Count < 2) + { + return; + } + + RoofWing wing = wings[index]; + int RoomAt(int x, int y) + { + for (int i = 0; i < plan.Rooms.Count; ++i) + { + (int x0, int y0, int x1, int y1) = plan.Rooms[i]; + if (x >= x0 && x <= x1 && y >= y0 && y <= y1) + { + return i; + } + } + + return -1; + } + + bool Other(int x, int y) + { + for (int j = 0; j < wings.Count; ++j) + { + RoofWing other = wings[j]; + if (j != index && other.Storeys > storey && x > other.X0 && x <= other.X1 && y > other.Y0 && y <= other.Y1) + { + return true; + } + } + + return false; + } + + var between = new Dictionary<(int A, int B), List<(int X, int Y, bool South)>>(); + for (int x = wing.X0 + 1; x <= wing.X1; ++x) + { + for (int y = wing.Y0 + 1; y <= wing.Y1; ++y) + { + int room = RoomAt(x, y); + foreach ((int nx, int ny, bool south) in new[] { (x + 1, y, false), (x, y + 1, true) }) + { + if (nx > wing.X1 || ny > wing.Y1) + { + continue; + } + + int next = RoomAt(nx, ny); + if (next == room || Other(x, y) || Other(nx, ny) || (stairs.Contains((x, y)) && stairs.Contains((nx, ny)))) + { + continue; + } + + (int, int) key = (Math.Min(room, next), Math.Max(room, next)); + if (!between.TryGetValue(key, out List<(int X, int Y, bool South)> shared)) + { + between[key] = shared = new List<(int X, int Y, bool South)>(); + } + + shared.Add((x, y, south)); + } + } + } + + var doorways = new HashSet<(int X, int Y, bool South)>(); + foreach ((int a, int b) in plan.Links) + { + if (!between.TryGetValue((Math.Min(a, b), Math.Max(a, b)), out List<(int X, int Y, bool South)> shared) || shared.Count == 0) + { + continue; + } + + int middle = (shared.Count - 1) / 2, pick = middle, nearest = int.MaxValue; + for (int i = 0; i < shared.Count; ++i) + { + (int x, int y, bool south) = shared[i]; + bool free = !stairs.Contains((x, y)) && !stairs.Contains(south ? (x, y + 1) : (x + 1, y)); + if (free && Math.Abs(i - middle) < nearest) + { + (pick, nearest) = (i, Math.Abs(i - middle)); + } + } + + doorways.Add(shared[pick]); + } + + foreach (List<(int X, int Y, bool South)> shared in between.Values) + { + foreach ((int x, int y, bool south) in shared) + { + if (doorways.Contains((x, y, south))) + { + // A doorway: open, or a door in the wall. + if (!AutoDoors || Suppressed.Contains((storey, x, y))) + { + continue; + } + + layout.Doors[(x, y)] = south ? DoorAlongX : DoorAlongY; + } + + (south ? layout.South : layout.East).Add((x, y)); + } + } + } + + /// + /// The walls of the wings that keep them () against the wings + /// they meet. Each cell belongs to one wing: a walled one where there is one, else the + /// first. A wall stands between cells of different wings when either is walled, and each + /// stretch of wall between the same two wings gets one doorway in its middle (a door, with + /// ), as near to it as stairs allow. + /// + private void WallOff(IReadOnlyList wings, int storey, HashSet<(int X, int Y)> region, HashSet<(int X, int Y)> stairs, StoreyLayout layout) + { + bool any = false; + foreach (RoofWing wing in wings) + { + any |= wing.Walled && wing.Storeys > storey; + } + + if (!any) + { + return; + } + + var owners = new Dictionary<(int X, int Y), int>(); + int Owner((int X, int Y) cell) + { + if (owners.TryGetValue(cell, out int known)) + { + return known; + } + + int first = -1, walled = -1; + for (int i = 0; i < wings.Count && walled < 0; ++i) + { + RoofWing wing = wings[i]; + if (wing.Storeys > storey && cell.X > wing.X0 && cell.X <= wing.X1 && cell.Y > wing.Y0 && cell.Y <= wing.Y1) + { + first = first < 0 ? i : first; + walled = wing.Walled ? i : walled; + } + } + + return owners[cell] = walled >= 0 ? walled : first; + } + + // Stretches of wall: along one line, between the same two wings, cell after cell. + var stretches = new Dictionary<(bool South, int Line, int A, int B), List<(int X, int Y)>>(); + foreach ((int x, int y) in region) + { + foreach ((int nx, int ny, bool south) in new[] { (x + 1, y, false), (x, y + 1, true) }) + { + if (!region.Contains((nx, ny)) || (south ? layout.South : layout.East).Contains((x, y))) + { + continue; + } + + int a = Owner((x, y)), b = Owner((nx, ny)); + if (a == b || a < 0 || b < 0 || !(wings[a].Walled || wings[b].Walled)) + { + continue; + } + + var key = (south, south ? y : x, a, b); + if (!stretches.TryGetValue(key, out List<(int X, int Y)> cells)) + { + stretches[key] = cells = new List<(int X, int Y)>(); + } + + cells.Add((x, y)); + } + } + + foreach (KeyValuePair<(bool South, int Line, int A, int B), List<(int X, int Y)>> stretch in stretches) + { + bool south = stretch.Key.South; + List<(int X, int Y)> cells = stretch.Value.OrderBy(c => south ? c.X : c.Y).ToList(); + for (int start = 0; start < cells.Count;) + { + int end = start; + while (end + 1 < cells.Count && (south ? cells[end + 1].X - cells[end].X : cells[end + 1].Y - cells[end].Y) == 1) + { + ++end; + } + + int middle = (start + end) / 2, pick = middle, nearest = int.MaxValue; + for (int i = start; i <= end; ++i) + { + (int x, int y) = cells[i]; + bool free = !stairs.Contains((x, y)) && !stairs.Contains(south ? (x, y + 1) : (x + 1, y)); + if (free && Math.Abs(i - middle) < nearest) + { + (pick, nearest) = (i, Math.Abs(i - middle)); + } + } + + for (int i = start; i <= end; ++i) + { + (int x, int y) = cells[i]; + if (i == pick) + { + if (!AutoDoors || Suppressed.Contains((storey, x, y))) + { + continue; + } + + layout.Doors[(x, y)] = south ? DoorAlongX : DoorAlongY; + } + + (south ? layout.South : layout.East).Add((x, y)); + } + + start = end + 1; + } + } + } + + /// + /// The front door: in the chosen outer wall of the first wing, in the middle of it, or of + /// the corridor or hall where that reaches the wall. Corners, wall ends and stairs are passed over. + /// + private void AddFrontDoor(IReadOnlyList wings, RoomPlan plan, HashSet<(int X, int Y)> outerSouth, HashSet<(int X, int Y)> outerEast, + HashSet<(int X, int Y)> stairs, StoreyLayout layout) + { + if (FrontDoor == FrontDoorSide.None || wings.Count == 0) + { + return; + } + + RoofWing wing = wings[0]; + bool south = FrontDoor == FrontDoorSide.South; + int from = south ? wing.X0 + 1 : wing.Y0 + 1, to = south ? wing.X1 : wing.Y1; + double centre = (from + to) / 2.0; + if (plan is { Main: >= 0 }) + { + (int x0, int y0, int x1, int y1) = plan.Rooms[plan.Main]; + if (south ? y1 == wing.Y1 : x1 == wing.X1) + { + centre = south ? (x0 + x1) / 2.0 : (y0 + y1) / 2.0; + } + } + + (int X, int Y)? best = null; + double nearest = double.MaxValue; + for (int i = from; i <= to; ++i) + { + (int X, int Y) cell = south ? (i, wing.Y1) : (wing.X1, i); + bool wall = (south ? outerSouth : outerEast).Contains(cell) && (south ? layout.South : layout.East).Contains(cell); + bool straight = wall && !(south ? layout.East : layout.South).Contains(cell); + if (straight && !stairs.Contains(cell) && Math.Abs(i - centre) < nearest) + { + (best, nearest) = (cell, Math.Abs(i - centre)); + } + } + + if (best is { } door && !Suppressed.Contains((0, door.X, door.Y))) + { + layout.Doors[door] = south ? DoorAlongX : DoorAlongY; + layout.FrontDoor = door; + } + } + + /// + /// Windows along the outer walls, cells apart and centred on + /// each stretch of wall between corners and the walls that meet it (so on each room). + /// A stretch has wall left at both ends; doors and cells set back by hand are passed over. + /// + private void AddWindows(int storey, HashSet<(int X, int Y)> outer, bool alongX, StoreyLayout layout) + { + var run = new List<(int X, int Y)>(); + void Close() + { + if (run.Count >= 3) + { + int count = 1 + ((run.Count - 3) / WindowSpacing); + int start = (run.Count - 1 - ((count - 1) * WindowSpacing)) / 2; + for (int i = 0; i < count; ++i) + { + (int X, int Y) cell = run[start + (i * WindowSpacing)]; + if (!Doors.ContainsKey((storey, cell.X, cell.Y)) && !layout.Doors.ContainsKey(cell) && !Suppressed.Contains((storey, cell.X, cell.Y))) + { + layout.Windows.Add(cell); + } + } + } + + run.Clear(); + } + + foreach (IGrouping line in outer.GroupBy(c => alongX ? c.Y : c.X)) + { + int last = int.MinValue; + foreach ((int X, int Y) cell in line.OrderBy(c => alongX ? c.X : c.Y)) + { + int at = alongX ? cell.X : cell.Y; + if (at != last + 1) + { + Close(); + } + + last = at; + bool straight = (alongX ? layout.South : layout.East).Contains(cell) && !(alongX ? layout.East : layout.South).Contains(cell); + + // A wall that meets this one from the far side ends the stretch as a corner does. + bool joined = alongX ? layout.East.Contains((cell.X, cell.Y + 1)) : layout.South.Contains((cell.X + 1, cell.Y)); + if (!straight || joined) + { + Close(); + continue; + } + + run.Add(cell); + } + + Close(); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.cs new file mode 100644 index 00000000..fc4d85a4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.cs @@ -0,0 +1,180 @@ +/*************************************************************************** + * + * $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.Plugin.MultiEditor.Styles; + +namespace UoFiddler.Plugin.MultiEditor.House +{ + internal sealed partial class HouseDraft + { + /// The door pieces the draft hangs by itself in a wall along X and in one along Y. + public const string DoorAlongX = "Piece3"; + public const string DoorAlongY = "Piece5"; + + public const int StoreyHeight = 20; + public const int MaxStoreys = 4; + public const string WallsLayer = "Walls"; + public const string FloorsLayer = "Floors"; + public const string StairsLayer = "Stairs"; + public const string FoundationLayer = "Foundation"; + + /// How far below the ground floor the foundation of most client houses starts. + public const int UsualFoundationHeight = 7; + + /// Z of the ground floor. + public int BaseZ { get; set; } + + public HouseStyle[] WallStyles { get; } = new HouseStyle[MaxStoreys]; + + public HouseStyle[] FloorStyles { get; } = new HouseStyle[MaxStoreys]; + + public HouseStyle RoofStyle { get; set; } + + /// The floor style a flat roof is laid in; without one, the floor style of the wing's top storey. + public HouseStyle FlatRoofStyle { get; set; } + + public bool Foundation { get; set; } + + /// The wall style the foundation ring is built in; without one, the client houses' own (light brick). + public HouseStyle FoundationStyle { get; set; } + + /// Rows of foundation pieces, one on the other: the stone tower, keep and castle have two. + public int FoundationTiers { get; set; } = 1; + + /// How far below the ground floor the foundation starts. + public int FoundationHeight { get; set; } = UsualFoundationHeight; + + /// The door style of the house: what a theme sets, and what doors made for the rooms are. + public HouseStyle DoorStyle { get; set; } + + /// The stair style of the house. + public HouseStyle StairStyle { get; set; } + + /// Which gable ends of the house's roofs are closed, and with what. + public RoofGables Gables { get; set; } = RoofGables.Front; + + public RoofGableFill GableFill { get; set; } = RoofGableFill.Caps; + + /// + /// True when flat roofs get battlements, as the client's tower, keep and castle have them: + /// two rows of the walls' roof edging around the roof and a third of every second piece. + /// + public bool Parapet { get; set; } + + /// True when the doorways between rooms get a door of . + public bool AutoDoors { get; set; } + + public FrontDoorSide FrontDoor { get; set; } + + /// Cells between the windows the draft puts along the outer walls; 0 for none. + public int WindowSpacing { get; set; } + + /// Wall cells where a door or window the draft made by itself was taken out by hand. + public HashSet<(int Storey, int X, int Y)> Suppressed { get; } = new HashSet<(int, int, int)>(); + + /// Most rooms a wing can be divided into. + public const int MaxRooms = 6; + + // Wall edges added and taken away by hand, per storey: cells with a wall on their +Y edge + // (south) and on their +X edge (east). + public HashSet<(int X, int Y)>[] AddedSouth { get; } = Sets(); + + public HashSet<(int X, int Y)>[] AddedEast { get; } = Sets(); + + public HashSet<(int X, int Y)>[] ErasedSouth { get; } = Sets(); + + public HashSet<(int X, int Y)>[] ErasedEast { get; } = Sets(); + + /// Doors by storey and wall cell: the door style and its piece (hinge variant). + public Dictionary<(int Storey, int X, int Y), (HouseStyle Style, string Piece)> Doors { get; } = new Dictionary<(int, int, int), (HouseStyle, string)>(); + + /// Wall cells whose piece is the style's window. + public HashSet<(int Storey, int X, int Y)> Windows { get; } = new HashSet<(int, int, int)>(); + + /// Floor areas laid in another style than the storey's; later ones lie on top. + public List<(int Storey, int X0, int Y0, int X1, int Y1, HouseStyle Style)> FloorAreas { get; } = new List<(int, int, int, int, int, HouseStyle)>(); + + /// Stairs by storey: the cell of the bottom step, the stair column (MultiNorth ...) and the style. + public List<(int Storey, int X, int Y, string Column, HouseStyle Style)> Stairs { get; } = new List<(int, int, int, string, HouseStyle)>(); + + private static HashSet<(int X, int Y)>[] Sets() + { + var sets = new HashSet<(int X, int Y)>[MaxStoreys]; + for (int i = 0; i < MaxStoreys; ++i) + { + sets[i] = new HashSet<(int X, int Y)>(); + } + + return sets; + } + + /// A copy that shares nothing but the styles. + public HouseDraft Clone() + { + HouseDraft copy = Fresh(); + copy.BaseZ = BaseZ; + CopyHandEditsInto(copy, _everywhere); + return copy; + } + + /// Puts another style in the place of every style the draft holds: after the styles were read again. + public void Remap(Func successor) + { + for (int k = 0; k < MaxStoreys; ++k) + { + WallStyles[k] = successor(WallStyles[k]); + FloorStyles[k] = successor(FloorStyles[k]); + } + + RoofStyle = successor(RoofStyle); + FlatRoofStyle = successor(FlatRoofStyle); + FoundationStyle = successor(FoundationStyle); + DoorStyle = successor(DoorStyle); + StairStyle = successor(StairStyle); + foreach (var key in new List<(int Storey, int X, int Y)>(Doors.Keys)) + { + Doors[key] = (successor(Doors[key].Style), Doors[key].Piece); + } + + for (int i = 0; i < FloorAreas.Count; ++i) + { + var a = FloorAreas[i]; + FloorAreas[i] = (a.Storey, a.X0, a.Y0, a.X1, a.Y1, successor(a.Style)); + } + + for (int i = 0; i < Stairs.Count; ++i) + { + var s = Stairs[i]; + Stairs[i] = (s.Storey, s.X, s.Y, s.Column, successor(s.Style)); + } + + _pieces.Clear(); + } + + /// A draft with the same materials and nothing changed by hand: the next house. + public HouseDraft Fresh() + { + var copy = new HouseDraft + { + RoofStyle = RoofStyle, FlatRoofStyle = FlatRoofStyle, Foundation = Foundation, + FoundationStyle = FoundationStyle, FoundationTiers = FoundationTiers, FoundationHeight = FoundationHeight, + DoorStyle = DoorStyle, StairStyle = StairStyle, + AutoDoors = AutoDoors, FrontDoor = FrontDoor, WindowSpacing = WindowSpacing, + Gables = Gables, GableFill = GableFill, Parapet = Parapet + }; + Array.Copy(WallStyles, copy.WallStyles, MaxStoreys); + Array.Copy(FloorStyles, copy.FloorStyles, MaxStoreys); + return copy; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseFoundation.cs b/UoFiddler.Plugin.MultiEditor/House/HouseFoundation.cs new file mode 100644 index 00000000..9ec22b5a --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/HouseFoundation.cs @@ -0,0 +1,32 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// + /// A foundation as the client's houses have them: a low wall style around the house, in one + /// or two rows, with the ground floor a given height above where it starts. From the style + /// file; offered when the client has the wall style. + /// + internal sealed class HouseFoundation + { + public string Name { get; set; } + + /// Anchor piece of the wall style; 0 for the usual one (light brick quarter walls). + public ushort Style { get; set; } + + public int Tiers { get; set; } = 1; + + public int Height { get; set; } = HouseDraft.UsualFoundationHeight; + + public override string ToString() => Name; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseTheme.cs b/UoFiddler.Plugin.MultiEditor/House/HouseTheme.cs new file mode 100644 index 00000000..4858e232 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/HouseTheme.cs @@ -0,0 +1,50 @@ +/*************************************************************************** + * + * $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 UoFiddler.Plugin.MultiEditor.Styles; + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// + /// A house theme: the styles of every part of a house, picked together. Each style is named + /// by its anchor piece (); 0 leaves that part as it is, except + /// for the foundation (0 is the usual one, light brick). + /// Themes come from the style file; the ones the user saved are in the user's copy of it. + /// + internal sealed class HouseTheme + { + public string Name { get; set; } + + public ushort Walls { get; set; } + + public ushort Floor { get; set; } + + public ushort Roof { get; set; } + + public ushort FlatRoof { get; set; } + + public ushort Door { get; set; } + + public ushort Stairs { get; set; } + + public ushort Foundation { get; set; } + + /// Rows of the foundation's pieces, one on the other, and how far below the ground floor the foundation starts. + public int FoundationTiers { get; set; } = 1; + + public int FoundationHeight { get; set; } = HouseDraft.UsualFoundationHeight; + + /// True for a theme from the user's copy of the style file. + public bool IsUser { get; set; } + + public override string ToString() => Name; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofGableFill.cs b/UoFiddler.Plugin.MultiEditor/House/RoofGableFill.cs new file mode 100644 index 00000000..c0f324ac --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoofGableFill.cs @@ -0,0 +1,23 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// 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 + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofGables.cs b/UoFiddler.Plugin.MultiEditor/House/RoofGables.cs new file mode 100644 index 00000000..7c569721 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoofGables.cs @@ -0,0 +1,22 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// Which gable ends of a roof are closed. + internal enum RoofGables + { + /// The south or east end, as the official houses do. + Front, + Both, + None + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofPlanner.cs b/UoFiddler.Plugin.MultiEditor/House/RoofPlanner.cs new file mode 100644 index 00000000..0f74d446 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoofPlanner.cs @@ -0,0 +1,383 @@ +/*************************************************************************** + * + * $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.House +{ + /// + /// Roofs as a height per cell. A wing (a rectangle with a ridge direction) gives each of its + /// cells a height, wings are joined by taking the higher one, and the roof.txt piece of a cell + /// follows from how its neighbours' heights compare with its own. The rules were measured on + /// the official multis and the UO Architect designs (109,000 roof cells): + /// + /// a slope is named for the side it comes down to: lower to the west is a West piece; + /// a ridge cell (lower on both sides) is the crosspiece running the other way; + /// a valley cell, level with two neighbours and below the other two, is a Dent piece: + /// higher to the west and south EDent, west and north SDent, east and north WDent, east and + /// south NDent; + /// where a wing's ridge runs into another ridge of the same height the cell is the T + /// piece named for the side the wing comes from, and the X piece where two ridges cross. + /// roof.txt has no pieces made for hips. The Dent pieces serve: each is a tile of two + /// faces, and on a hip line the one with the same two faces closes the corner when it sits 3 + /// lower than the slopes beside it (the south-east one at their height). Found by drawing + /// every piece at every corner; it closes cleanly in thatch, stone, slate and shingles and + /// leaves small seams in Tile Roof. + /// + /// + internal static class RoofPlanner + { + /// Z a slope gains per cell: the roof pieces are 3 high. + public const int Rise = 3; + + /// Marks a fixed piece that sits lower than its cell's height: "EDent@-3". + public const char LiftMark = '@'; + + // The corner pieces of a hip, by the corner of the wing they lie towards. + private const string _hipNorthWest = "NDent@-3"; + private const string _hipNorthEast = "EDent@-3"; + private const string _hipSouthEast = "SDent"; + private const string _hipSouthWest = "WDent@-3"; + + /// Narrowest part of a house that gets a wing of its own. + private const int _minWing = 3; + + /// + /// The ridge direction the official houses would give a box: across the odd side, so the + /// ridge gets its crosspiece; otherwise along the longer side, along Y when square. + /// + public static bool RidgeAlongY((int X0, int Y0, int X1, int Y1) box) + { + int spanX = box.X1 - box.X0 + 1, spanY = box.Y1 - box.Y0 + 1; + return spanX % 2 != spanY % 2 ? spanX % 2 == 1 : spanY >= spanX; + } + + /// + /// Adds a wing to a roof: every cell of the box gets the wing's height there unless the + /// roof is already higher. A gable climbs from its two long sides to the ridge. A hip + /// climbs from all four sides; the cells on its hip lines get their corner piece in + /// . Cells with a negative coordinate are left out. + /// + public static void AddWing(Dictionary<(int X, int Y), int> heights, Dictionary<(int X, int Y), string> fixedPieces, + (int X0, int Y0, int X1, int Y1) box, bool ridgeAlongY, RoofShape shape, int eaveZ) + { + int across0 = ridgeAlongY ? box.X0 : box.Y0; + int across1 = ridgeAlongY ? box.X1 : box.Y1; + for (int x = Math.Max(0, box.X0); x <= box.X1; ++x) + { + for (int y = Math.Max(0, box.Y0); y <= box.Y1; ++y) + { + int a = ridgeAlongY ? x : y; + int steps = Math.Min(a - across0, across1 - a); + string corner = null; + if (shape == RoofShape.Hip) + { + int west = x - box.X0, east = box.X1 - x, north = y - box.Y0, south = box.Y1 - y; + steps = Math.Min(Math.Min(west, east), Math.Min(north, south)); + + // On a hip line two sides are equally near; on the ridge the opposite ones are. + if (west != east && north != south) + { + corner = west == steps && north == steps ? _hipNorthWest + : east == steps && north == steps ? _hipNorthEast + : east == steps && south == steps ? _hipSouthEast + : west == steps && south == steps ? _hipSouthWest + : null; + } + } + + int z = eaveZ + (Rise * steps); + if (heights.TryGetValue((x, y), out int known) && known >= z) + { + continue; + } + + heights[(x, y)] = z; + if (corner != null) + { + fixedPieces[(x, y)] = corner; + } + else + { + fixedPieces.Remove((x, y)); + } + } + } + } + + // -1 lower (or no roof there), 0 level, 1 higher: a neighbour's height against a cell's. + private static int Side(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y, int height) + { + return heights.TryGetValue((x, y), out int n) ? Math.Sign(n - height) : -1; + } + + /// + /// The roof.txt column of the piece for a cell, from the heights around it; null for a + /// cell level with all its neighbours, which no piece fits. A style without the piece + /// named leaves the cell open: no other piece is put there in its place. + /// + public static string Piece(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y) + { + if (!heights.TryGetValue((x, y), out int h)) + { + return null; + } + + int Side(int cx, int cy, int ch) => RoofPlanner.Side(heights, cx, cy, ch); + bool RidgeAlongYAt(int cx, int cy) => heights.TryGetValue((cx, cy), out int ch) && Side(cx - 1, cy, ch) < 0 && Side(cx + 1, cy, ch) < 0; + bool RidgeAlongXAt(int cx, int cy) => heights.TryGetValue((cx, cy), out int ch) && Side(cx, cy - 1, ch) < 0 && Side(cx, cy + 1, ch) < 0; + + int w = Side(x - 1, y, h), e = Side(x + 1, y, h), n = Side(x, y - 1, h), s = Side(x, y + 1, h); + + // Valley: level with one neighbour and below the other on both axes. + if (w + e == 1 && w * e == 0 && n + s == 1 && n * s == 0) + { + if (w > 0) + { + return s > 0 ? "EDent" : "SDent"; + } + + return n > 0 ? "WDent" : "NDent"; + } + + // Ridges of this height leaving the cell. + bool armW = w == 0 && RidgeAlongXAt(x - 1, y), armE = e == 0 && RidgeAlongXAt(x + 1, y); + bool armN = n == 0 && RidgeAlongYAt(x, y - 1), armS = s == 0 && RidgeAlongYAt(x, y + 1); + int arms = (armW ? 1 : 0) + (armE ? 1 : 0) + (armN ? 1 : 0) + (armS ? 1 : 0); + if (arms == 4) + { + return "XPiece"; + } + + if (arms == 3) + { + return !armW ? "ETPiece" : !armE ? "WTPiece" : !armN ? "STPiece" : "NTPiece"; + } + + bool ridgeY = w < 0 && e < 0, ridgeX = n < 0 && s < 0; + if (ridgeY && ridgeX) + { + return armE || armW ? "EWCrosspiece" : "NSCrosspiece"; + } + + if (ridgeY) + { + return "NSCrosspiece"; + } + + if (ridgeX) + { + return "EWCrosspiece"; + } + + int climbX = e - w, climbY = s - n; + if (climbX == 0 && climbY == 0) + { + return null; + } + + // The roof's edge counts as lower, so at a gable end a cell of the top rows of an even + // span drops as much to the edge as down its slope. The slope is the side where roof + // lies lower, not the edge. + if (Math.Abs(climbX) == Math.Abs(climbY)) + { + bool roofLowerX = heights.ContainsKey((climbX > 0 ? x - 1 : x + 1, y)); + bool roofLowerY = heights.ContainsKey((x, climbY > 0 ? y - 1 : y + 1)); + if (roofLowerY && !roofLowerX) + { + return climbY > 0 ? "North" : "South"; + } + } + + return Math.Abs(climbX) >= Math.Abs(climbY) ? (climbX > 0 ? "West" : "East") : (climbY > 0 ? "North" : "South"); + } + + /// + /// The end piece of a ridge, for the sets that have them (the ceramic tiles): a ridge cell + /// lower on three sides and level on the fourth. North end MoreNS, south end NSEnd, west + /// end MoreEW, east end EWEnd, as the UO Architect ceramic roofs place them. Null for any + /// other cell; a set without end pieces ends its ridge with the crosspiece. + /// + public static string RidgeEnd(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y) + { + if (!heights.TryGetValue((x, y), out int h)) + { + return null; + } + + int w = Side(heights, x - 1, y, h), e = Side(heights, x + 1, y, h), n = Side(heights, x, y - 1, h), s = Side(heights, x, y + 1, h); + if (w < 0 && e < 0 && n + s == -1 && n * s == 0) + { + return n < 0 ? "MoreNS" : "NSEnd"; + } + + if (n < 0 && s < 0 && w + e == -1 && w * e == 0) + { + return w < 0 ? "MoreEW" : "EWEnd"; + } + + return null; + } + + /// + /// Drops the hip corners that joined wings have covered. A corner stays only where the + /// roof still turns there: lower (or no roof) on its two outer sides, level on the two + /// inner ones. Any other cell is a joint, whose piece follows from the heights. + /// + public static void SettleCorners(IReadOnlyDictionary<(int X, int Y), int> heights, Dictionary<(int X, int Y), string> fixedPieces) + { + foreach (((int x, int y), string piece) in new List>(fixedPieces)) + { + (int outerX, int outerY) = piece switch + { + _hipNorthWest => (-1, -1), + _hipNorthEast => (1, -1), + _hipSouthEast => (1, 1), + _hipSouthWest => (-1, 1), + _ => (0, 0) + }; + if (outerX == 0 || !heights.TryGetValue((x, y), out int h)) + { + continue; + } + + bool corner = Side(heights, x + outerX, y, h) < 0 && Side(heights, x, y + outerY, h) < 0 && + Side(heights, x - outerX, y, h) == 0 && Side(heights, x, y - outerY, h) == 0; + if (!corner) + { + fixedPieces.Remove((x, y)); + } + } + } + + /// + /// The wings that roof a house whose cells are : its largest + /// rectangles, biggest first, each with its ridge along its longer side. A wing that runs + /// through an earlier one across its ridge stops at that ridge, so the two meet in a T + /// instead of the wing showing a gable on the far side. Parts narrower than three cells + /// get no wing. A plain rectangle, or a shape too ragged to split, is one wing: the + /// region's box. + /// + public static List<((int X0, int Y0, int X1, int Y1) Box, bool RidgeAlongY)> Wings(ICollection<(int X, int Y)> region) + { + var wings = new List<((int X0, int Y0, int X1, int Y1) Box, bool RidgeAlongY)>(); + if (region.Count == 0) + { + return wings; + } + + int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + foreach ((int x, int y) in region) + { + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + + var whole = (minX, minY, maxX, maxY); + int width = maxX - minX + 1, height = maxY - minY + 1; + if (region.Count == width * height) + { + wings.Add((whole, RidgeAlongY(whole))); + return wings; + } + + // Filled cells before (x, y), so a rectangle is checked in one step. + var sum = new int[width + 1, height + 1]; + var set = region as ISet<(int X, int Y)> ?? new HashSet<(int X, int Y)>(region); + for (int x = 0; x < width; ++x) + { + for (int y = 0; y < height; ++y) + { + sum[x + 1, y + 1] = sum[x, y + 1] + sum[x + 1, y] - sum[x, y] + (set.Contains((minX + x, minY + y)) ? 1 : 0); + } + } + + bool Full(int x0, int y0, int x1, int y1) + { + return x0 >= 0 && y0 >= 0 && x1 < width && y1 < height && + sum[x1 + 1, y1 + 1] - sum[x0, y1 + 1] - sum[x1 + 1, y0] + sum[x0, y0] == (x1 - x0 + 1) * (y1 - y0 + 1); + } + + var found = new List<(int X0, int Y0, int X1, int Y1)>(); + for (int x0 = 0; x0 < width; ++x0) + { + for (int y0 = 0; y0 < height; ++y0) + { + for (int x1 = x0 + _minWing - 1; x1 < width && Full(x0, y0, x1, y0); ++x1) + { + for (int y1 = y0 + _minWing - 1; y1 < height && Full(x0, y0, x1, y1); ++y1) + { + if (!Full(x0 - 1, y0, x0 - 1, y1) && !Full(x1 + 1, y0, x1 + 1, y1) && + !Full(x0, y0 - 1, x1, y0 - 1) && !Full(x0, y1 + 1, x1, y1 + 1)) + { + found.Add((minX + x0, minY + y0, minX + x1, minY + y1)); + } + } + } + } + } + + found.Sort((a, b) => ((b.X1 - b.X0 + 1) * (b.Y1 - b.Y0 + 1)).CompareTo((a.X1 - a.X0 + 1) * (a.Y1 - a.Y0 + 1))); + if (found.Count == 0 || found.Count > 6) + { + wings.Add((whole, RidgeAlongY(whole))); + return wings; + } + + foreach ((int X0, int Y0, int X1, int Y1) rect in found) + { + var box = rect; + bool alongY = box.Y1 - box.Y0 != box.X1 - box.X0 ? box.Y1 - box.Y0 > box.X1 - box.X0 : RidgeAlongY(box); + foreach (((int X0, int Y0, int X1, int Y1) other, bool otherAlongY) in wings) + { + bool overlap = box.X0 <= other.X1 && box.X1 >= other.X0 && box.Y0 <= other.Y1 && box.Y1 >= other.Y0; + if (!overlap || otherAlongY == alongY) + { + continue; + } + + if (alongY) + { + // The other ridge runs along X: stop at its row when sticking out one way only. + bool south = box.Y1 > other.Y1, north = box.Y0 < other.Y0; + if (south && !north) + { + box.Y0 = Math.Max(box.Y0, (other.Y0 + other.Y1 + 1) / 2); + } + else if (north && !south) + { + box.Y1 = Math.Min(box.Y1, (other.Y0 + other.Y1) / 2); + } + } + else + { + bool east = box.X1 > other.X1, west = box.X0 < other.X0; + if (east && !west) + { + box.X0 = Math.Max(box.X0, (other.X0 + other.X1 + 1) / 2); + } + else if (west && !east) + { + box.X1 = Math.Min(box.X1, (other.X0 + other.X1) / 2); + } + } + } + + wings.Add((box, alongY)); + } + + return wings; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofRidge.cs b/UoFiddler.Plugin.MultiEditor/House/RoofRidge.cs new file mode 100644 index 00000000..5c8217f0 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoofRidge.cs @@ -0,0 +1,22 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// 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 + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofShape.cs b/UoFiddler.Plugin.MultiEditor/House/RoofShape.cs new file mode 100644 index 00000000..6d63ff2e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoofShape.cs @@ -0,0 +1,29 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// The shape of one roof wing. + internal enum RoofShape + { + /// Two slopes meeting in a ridge. + Gable, + + /// Four slopes: the ends slope too, instead of standing as gables. + Hip, + + /// + /// No slopes: a floor on top of the walls, as the towers have. Only a house wing can have + /// it; the house draft lays it, not this planner. + /// + Flat + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofWing.cs b/UoFiddler.Plugin.MultiEditor/House/RoofWing.cs new file mode 100644 index 00000000..583ecd99 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoofWing.cs @@ -0,0 +1,101 @@ +/*************************************************************************** + * + * $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; + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// + /// One rectangle of a roof or a house being shaped. For a roof the box is the cells the roof + /// covers and the height of its eaves; for a house the box is the wall + /// cells and the Z its ground floor stands on. + /// + internal sealed class RoofWing + { + public int X0 { get; set; } + + public int Y0 { get; set; } + + public int X1 { get; set; } + + public int Y1 { get; set; } + + public int EaveZ { get; set; } + + /// Storeys of a house wing. + public int Storeys { get; set; } = 1; + + /// A house wing left without a roof. + public bool NoRoof { get; set; } + + /// + /// Rooms a house wing is divided into on each of its storeys: partitions across its longer + /// side, each with a doorway left in the middle. 1 leaves the wing undivided. + /// + public int Rooms { get; set; } = 1; + + /// How the rooms of a house wing are laid out. + public RoomLayout Layout { get; set; } + + /// + /// True for a house wing that keeps its walls where it meets other wings, with a doorway + /// in each stretch of wall they share: a tower at a keep's corner, a hall in a castle's + /// yard. Wings without it run into each other as one open space. + /// + public bool Walled { get; set; } + + /// + /// Rooms and layout of the storeys above the ground floor that have their own; a storey + /// without takes those of the storey below it. Index 0 is not used. + /// + public (int Rooms, RoomLayout Layout)?[] RoomsAbove { get; private set; } = new (int, RoomLayout)?[HouseDraft.MaxStoreys]; + + /// Rooms and layout of a storey. + public (int Rooms, RoomLayout Layout) RoomsOn(int storey) + { + for (int k = Math.Min(storey, HouseDraft.MaxStoreys - 1); k >= 1; --k) + { + if (RoomsAbove[k] is { } own) + { + return own; + } + } + + return (Rooms, Layout); + } + + public RoofShape Shape { get; set; } + + public bool RidgeAlongY { get; set; } + + /// True while the ridge follows the box's proportions as it is resized. + public bool RidgeAuto { get; set; } + + public (int X0, int Y0, int X1, int Y1) Box => (X0, Y0, X1, Y1); + + public RoofWing Clone() + { + var copy = (RoofWing)MemberwiseClone(); + copy.RoomsAbove = ((int, RoomLayout)?[])RoomsAbove.Clone(); + return copy; + } + + public void CopyFrom(RoofWing other) + { + (X0, Y0, X1, Y1, EaveZ) = (other.X0, other.Y0, other.X1, other.Y1, other.EaveZ); + (Shape, RidgeAlongY, RidgeAuto, Storeys, NoRoof) = (other.Shape, other.RidgeAlongY, other.RidgeAuto, other.Storeys, other.NoRoof); + Rooms = other.Rooms; + Layout = other.Layout; + Walled = other.Walled; + RoomsAbove = ((int, RoomLayout)?[])other.RoomsAbove.Clone(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoomLayout.cs b/UoFiddler.Plugin.MultiEditor/House/RoomLayout.cs new file mode 100644 index 00000000..72220479 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoomLayout.cs @@ -0,0 +1,29 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.House +{ + /// How the rooms of a house wing are laid out. + internal enum RoomLayout + { + /// Side by side along the wing's longer side. + Row, + + /// Two rows of rooms. + Grid, + + /// A corridor along the wing's longer side with rooms on both sides of it. + Corridor, + + /// One large room, and the others in a row across the wing's end. + Hall + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoomPlan.cs b/UoFiddler.Plugin.MultiEditor/House/RoomPlan.cs new file mode 100644 index 00000000..87d69fb0 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoomPlan.cs @@ -0,0 +1,28 @@ +/*************************************************************************** + * + * $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.House +{ + /// The rooms of a wing on one storey: their cells, and which of them a doorway joins. + internal sealed class RoomPlan + { + /// The rooms as cell rectangles, both ends included. + public List<(int X0, int Y0, int X1, int Y1)> Rooms { get; } = new List<(int, int, int, int)>(); + + /// Pairs of rooms with a doorway between them. Every room is reached through them. + public List<(int A, int B)> Links { get; } = new List<(int, int)>(); + + /// The room the others open to (the corridor, the hall), or -1 when there is none. + public int Main { get; set; } = -1; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/House/RoomPlanner.cs b/UoFiddler.Plugin.MultiEditor/House/RoomPlanner.cs new file mode 100644 index 00000000..d87e14ed --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/House/RoomPlanner.cs @@ -0,0 +1,239 @@ +/*************************************************************************** + * + * $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.House +{ + /// + /// Divides the inside of a house wing into rooms. It only says where the rooms are and which + /// are joined: the draft makes the walls, doorways, doors and windows from that. + /// + internal static class RoomPlanner + { + /// Narrowest a room may be, in cells. + public const int MinRoom = 2; + + /// + /// The rooms of the cells .. by + /// ... A layout the wing is too small for falls + /// back to a row of rooms, and that to fewer rooms, down to the wing undivided. + /// + public static RoomPlan Plan(int x0, int y0, int x1, int y1, RoomLayout layout, int rooms) + { + int width = x1 - x0 + 1, depth = y1 - y0 + 1; + bool alongX = width >= depth; + int length = alongX ? width : depth, cross = alongX ? depth : width; + rooms = Math.Max(1, rooms); + + // A rectangle given along the wing's longer side (a) and across it (b), as cells. + (int, int, int, int) Rect((int From, int To) a, (int From, int To) b) => alongX + ? (x0 + a.From, y0 + b.From, x0 + a.To, y0 + b.To) + : (x0 + b.From, y0 + a.From, x0 + b.To, y0 + a.To); + + var plan = new RoomPlan(); + switch (layout) + { + case RoomLayout.Grid when rooms >= 3 && cross >= 2 * MinRoom: + { + List<(int From, int To)> halves = Split(0, cross, 2); + List<(int From, int To)> first = Split(0, length, (rooms + 1) / 2), second = Split(0, length, rooms / 2); + foreach ((int From, int To) part in first) + { + plan.Rooms.Add(Rect(part, halves[0])); + } + + foreach ((int From, int To) part in second) + { + plan.Rooms.Add(Rect(part, halves[1])); + } + + for (int i = 1; i < first.Count; ++i) + { + plan.Links.Add((i - 1, i)); + } + + // Each room of the second row opens to the room of the first it shares most wall with. + for (int j = 0; j < second.Count; ++j) + { + int best = 0, most = -1; + for (int i = 0; i < first.Count; ++i) + { + int shared = Math.Min(first[i].To, second[j].To) - Math.Max(first[i].From, second[j].From) + 1; + if (shared > most) + { + (best, most) = (i, shared); + } + } + + plan.Links.Add((best, first.Count + j)); + } + + return plan; + } + + case RoomLayout.Corridor when rooms >= 2 && cross >= (2 * MinRoom) + 1: + { + int corridor = cross >= 8 ? 2 : 1; + int side = (cross - corridor) / 2; + plan.Main = 0; + plan.Rooms.Add(Rect((0, length - 1), (side, side + corridor - 1))); + foreach ((int From, int To) part in Split(0, length, (rooms + 1) / 2)) + { + plan.Links.Add((0, plan.Rooms.Count)); + plan.Rooms.Add(Rect(part, (0, side - 1))); + } + + foreach ((int From, int To) part in Split(0, length, rooms / 2)) + { + plan.Links.Add((0, plan.Rooms.Count)); + plan.Rooms.Add(Rect(part, (side + corridor, cross - 1))); + } + + return plan; + } + + case RoomLayout.Hall when rooms >= 2 && length >= 3 + MinRoom: + { + int hall = Math.Clamp((int)Math.Round(length * 0.6), 3, length - MinRoom); + plan.Main = 0; + plan.Rooms.Add(Rect((0, hall - 1), (0, cross - 1))); + foreach ((int From, int To) part in Split(0, cross, rooms - 1)) + { + plan.Links.Add((0, plan.Rooms.Count)); + plan.Rooms.Add(Rect((hall, length - 1), part)); + } + + return plan; + } + } + + foreach ((int From, int To) part in Split(0, length, Math.Min(rooms, HouseDraft.MaxRooms))) + { + if (plan.Rooms.Count > 0) + { + plan.Links.Add((plan.Rooms.Count - 1, plan.Rooms.Count)); + } + + plan.Rooms.Add(Rect(part, (0, cross - 1))); + } + + return plan; + } + + /// + /// Moves the walls between rooms off stairs: a wall that would run between two stair + /// cells steps one or two cells aside, where the rooms on both sides stay wide enough. + /// A wall that cannot is left where it is (the draft then leaves it open at the stairs). + /// + public static void Avoid(RoomPlan plan, ICollection<(int X, int Y)> stairs) + { + if (stairs.Count == 0 || plan.Rooms.Count < 2) + { + return; + } + + foreach (bool alongY in new[] { true, false }) + { + // A wall along Y stands after column c: between the rooms that end at c and those that start at c + 1. + int End((int X0, int Y0, int X1, int Y1) r) => alongY ? r.X1 : r.Y1; + int Start((int X0, int Y0, int X1, int Y1) r) => alongY ? r.X0 : r.Y0; + (int From, int To) Side((int X0, int Y0, int X1, int Y1) r) => alongY ? (r.Y0, r.Y1) : (r.X0, r.X1); + bool Cut(int c, List before) + { + foreach (int i in before) + { + (int from, int to) = Side(plan.Rooms[i]); + for (int at = from; at <= to; ++at) + { + if (alongY ? stairs.Contains((c, at)) && stairs.Contains((c + 1, at)) : stairs.Contains((at, c)) && stairs.Contains((at, c + 1))) + { + return true; + } + } + } + + return false; + } + + foreach (int c in plan.Rooms.Select(End).Distinct().ToList()) + { + var before = new List(); + var after = new List(); + for (int i = 0; i < plan.Rooms.Count; ++i) + { + if (End(plan.Rooms[i]) == c) + { + before.Add(i); + } + else if (Start(plan.Rooms[i]) == c + 1) + { + after.Add(i); + } + } + + // Only a wall with the same rooms' length on both sides can move as one. + if (after.Count == 0 || before.Sum(i => Side(plan.Rooms[i]).To - Side(plan.Rooms[i]).From + 1) != after.Sum(i => Side(plan.Rooms[i]).To - Side(plan.Rooms[i]).From + 1) || + !Cut(c, before)) + { + continue; + } + + foreach (int by in new[] { 1, -1, 2, -2 }) + { + // A room keeps the least width; one already narrower (a corridor) keeps its own. + int least(int i) => Math.Min(MinRoom, End(plan.Rooms[i]) - Start(plan.Rooms[i]) + 1); + bool fits = before.All(i => c + by - Start(plan.Rooms[i]) + 1 >= least(i)) && after.All(i => End(plan.Rooms[i]) - (c + by + 1) + 1 >= least(i)); + if (!fits || Cut(c + by, before)) + { + continue; + } + + foreach (int i in before) + { + (int x0, int y0, int x1, int y1) = plan.Rooms[i]; + plan.Rooms[i] = alongY ? (x0, y0, c + by, y1) : (x0, y0, x1, c + by); + } + + foreach (int i in after) + { + (int x0, int y0, int x1, int y1) = plan.Rooms[i]; + plan.Rooms[i] = alongY ? (c + by + 1, y0, x1, y1) : (x0, c + by + 1, x1, y1); + } + + break; + } + } + } + } + + /// + /// Cuts a span of cells into parts of about the same size, each at least + /// long: fewer parts when the span is too short for that many. + /// + private static List<(int From, int To)> Split(int from, int length, int parts) + { + parts = Math.Max(1, Math.Min(parts, length / MinRoom)); + var result = new List<(int, int)>(); + int start = 0; + for (int i = 1; i <= parts; ++i) + { + int end = i == parts ? length : (int)Math.Round(i * length / (double)parts); + result.Add((from + start, from + end - 1)); + start = end; + } + + return result; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs b/UoFiddler.Plugin.MultiEditor/House/WallPlanner.cs similarity index 79% rename from UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs rename to UoFiddler.Plugin.MultiEditor/House/WallPlanner.cs index 6dacbc84..9aa3214b 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs +++ b/UoFiddler.Plugin.MultiEditor/House/WallPlanner.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: Turley * @@ -11,8 +11,10 @@ using System; using System.Collections.Generic; +using UoFiddler.Plugin.MultiEditor.Model; +using UoFiddler.Plugin.MultiEditor.Styles; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.House { /// /// Builds walls from cell edges. A wall piece sits on the +Y edge of its cell (a "South" piece, @@ -173,7 +175,7 @@ void Edit(HashSet<(int, int)> set, (int X, int Y) cell) continue; } - string column = PieceFor(cell.X, cell.Y); + string column = PieceFor(_style, _south, _east, cell.X, cell.Y); ushort want = column != null ? _style.Get(column) : (ushort)0; _pieces.TryGetValue(cell, out MultiTile have); @@ -207,6 +209,53 @@ void Edit(HashSet<(int, int)> set, (int X, int Y) cell) /// public string PieceFor(int x, int y) => PieceFor(_south, _east, x, y); + /// + /// The column of a style's piece for a cell. As , + /// except in a paired style (): there the straight pieces of + /// a run alternate between the two halves of the ornament, counted from the run's start, + /// and the last piece of a run of odd length is the plain one. + /// + public static string PieceFor(HouseStyle style, HashSet<(int X, int Y)> southEdges, HashSet<(int X, int Y)> eastEdges, int x, int y) + { + string column = PieceFor(southEdges, eastEdges, x, y); + bool cycles = style != null && style.CycleSouth > 0 && style.CycleEast > 0; + if (style == null || (!style.Paired && !cycles) || column == null || column is "Corner" or "Post") + { + return column; + } + + bool alongX = column.StartsWith("South", StringComparison.Ordinal); + bool Straight(int cx, int cy) => alongX + ? southEdges.Contains((cx, cy)) && !eastEdges.Contains((cx, cy)) + : eastEdges.Contains((cx, cy)) && !southEdges.Contains((cx, cy)); + + int before = 0, after = 0; + while (Straight(alongX ? x - before - 1 : x, alongX ? y : y - before - 1)) + { + ++before; + } + + while (Straight(alongX ? x + after + 1 : x, alongX ? y : y + after + 1)) + { + ++after; + } + + // A set of panels: one after the other along the run. + if (cycles) + { + return alongX ? $"CycleSouth{(before % style.CycleSouth) + 1}" : $"CycleEast{(before % style.CycleEast) + 1}"; + } + + int length = before + after + 1; + if (length % 2 == 1 && after == 0) + { + return alongX ? "South2" : "East2"; + } + + bool firstHalf = before % 2 == 0; + return alongX ? (firstHalf ? "South1" : "South3") : (firstHalf ? "East3" : "East1"); + } + /// /// The walls.txt column for a cell given the +Y edges () and /// +X edges () of a wall layer. diff --git a/UoFiddler.Plugin.MultiEditor/Model/ClipboardTile.cs b/UoFiddler.Plugin.MultiEditor/Model/ClipboardTile.cs new file mode 100644 index 00000000..f025db11 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Model/ClipboardTile.cs @@ -0,0 +1,97 @@ +/*************************************************************************** + * + * $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.Linq; +using System.Text; + +namespace UoFiddler.Plugin.MultiEditor.Model +{ + /// + /// 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(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs b/UoFiddler.Plugin.MultiEditor/Model/EditCommand.cs similarity index 79% rename from UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs rename to UoFiddler.Plugin.MultiEditor/Model/EditCommand.cs index 3c787b4c..543a8db6 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/EditCommand.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: Turley * @@ -11,26 +11,8 @@ using System.Collections.Generic; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { - /// - /// 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, TileLayer Layer) - { - public static TileState Of(MultiTile tile) => new(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible, tile.Layer); - - public void ApplyTo(MultiTile tile) - { - tile.Id = Id; - tile.Invisible = Invisible; - tile.Layer = Layer; - 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. diff --git a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs b/UoFiddler.Plugin.MultiEditor/Model/GroupTransform.cs similarity index 93% rename from UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs rename to UoFiddler.Plugin.MultiEditor/Model/GroupTransform.cs index e7f60b81..14a85882 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/GroupTransform.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: Turley * @@ -12,17 +12,12 @@ using System; using System.Collections.Generic; using System.Linq; +using UoFiddler.Plugin.MultiEditor.House; +using UoFiddler.Plugin.MultiEditor.Rendering; +using UoFiddler.Plugin.MultiEditor.Styles; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { - 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. @@ -469,8 +464,31 @@ private static string TurnSlot(string slot, Func mapDirection, b } } + // Eave + side, Hip + corner and HipEave + corner (ceramic, crystal and shadow sets). + if (slot.StartsWith("Eave", StringComparison.Ordinal) && _directions.ContainsKey(slot.Substring(4))) + { + return "Eave" + mapDirection(slot.Substring(4)); + } + + foreach (string prefix in new[] { "HipEave", "Hip" }) + { + if (slot.Length == prefix.Length + 2 && slot.StartsWith(prefix, StringComparison.Ordinal)) + { + // A corner is two sides: both turn, and north or south is named first. + string first = mapDirection(_directions.Keys.First(d => d[0] == slot[^2])); + string second = mapDirection(_directions.Keys.First(d => d[0] == slot[^1])); + (string ns, string ew) = first[0] is 'N' or 'S' ? (first, second) : (second, first); + return prefix + ns[0] + ew[0]; + } + } + if (swapsAxes) { + if (slot is "NSEnd" or "EWEnd") + { + return slot == "NSEnd" ? "EWEnd" : "NSEnd"; + } + if (slot == "NSCrosspiece") { return "EWCrosspiece"; diff --git a/UoFiddler.Plugin.MultiEditor/Model/GroupTransformKind.cs b/UoFiddler.Plugin.MultiEditor/Model/GroupTransformKind.cs new file mode 100644 index 00000000..66a93b5b --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Model/GroupTransformKind.cs @@ -0,0 +1,21 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.Model +{ + internal enum GroupTransformKind + { + RotateLeft, + RotateRight, + MirrorX, + MirrorY + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs b/UoFiddler.Plugin.MultiEditor/Model/IMultiViewSettings.cs similarity index 84% rename from UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs rename to UoFiddler.Plugin.MultiEditor/Model/IMultiViewSettings.cs index 599b017a..17a0c796 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/IMultiViewSettings.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: MuadDib & Turley * @@ -10,7 +10,7 @@ ***************************************************************************/ -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { /// /// The view options the edited multi depends on. diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.Layers.cs similarity index 88% rename from UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs rename to UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.Layers.cs index 07cece0e..f5b37194 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.Layers.cs @@ -11,7 +11,7 @@ using System.Collections.Generic; using System.Linq; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { // The layers of the design: the list, the active one, and the edits on them. Changes to the // list and to which layer a tile is on are undo steps; a layer's visibility is not. @@ -111,6 +111,62 @@ public TileLayer LayerAdd(string name) return layer; } + /// + /// Removes some tiles and adds others in one undo step, each new one on the layer it + /// names, or on when it names none. Layers the multi does + /// not have yet are made on top of the others, in the order they are first named; the + /// active layer stays as it is. The multi grows to hold tiles added past its +X/+Y end. + /// + public void ReplaceTilesOnLayers(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z, string Layer)> add, + string action, string defaultLayer) + { + var added = new List<(ushort Id, int X, int Y, int Z, string Layer)>(add); + BeginEdit(action); + foreach (MultiTile tile in new List(remove)) + { + RecordRemove(tile); + } + + int width = Width, height = Height; + foreach (var (_, x, y, _, _) in added) + { + if (x >= 0 && y >= 0) + { + width = Math.Max(width, x + 1); + height = Math.Max(height, y + 1); + } + } + + if (width != Width || height != Height) + { + RebuildGrid(width, height, new List(RealTiles)); + } + + var byName = new Dictionary(); + foreach (var (id, x, y, z, name) in added) + { + string wanted = name ?? defaultLayer; + if (!byName.TryGetValue(wanted, out TileLayer layer)) + { + layer = _layers.FirstOrDefault(l => l.Name == wanted); + if (layer == null) + { + RecordLayers(); + TileLayer active = ActiveLayer; + layer = new TileLayer(wanted); + _layers.Add(layer); + ActiveLayer = active; + } + + byName[wanted] = layer; + } + + RecordNew(id, x, y, z, false, 0, layer: layer); + } + + EndEdit(); + } + /// Removes a layer with its tiles. The last layer stays. public bool LayerRemove(TileLayer layer) { diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.cs similarity index 96% rename from UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs rename to UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.cs index b11941e1..65e2b8aa 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: MuadDib & Turley * @@ -13,8 +13,9 @@ using System.Collections.Generic; using Ultima; using UoFiddler.Controls.Classes; +using UoFiddler.Plugin.MultiEditor.Rendering; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { /// /// The edited multi. Tiles are kept per cell, each cell sorted in draw order with its virtual @@ -528,16 +529,37 @@ public void TileSetIds(IEnumerable<(MultiTile Tile, ushort Id)> changes, string } /// - /// Removes some tiles and adds others in one undo step (wall and house part tools). + /// Removes some tiles and adds others in one undo step (wall and house part tools). With + /// the multi is made bigger, in the same step, to hold tiles added + /// past its +X/+Y end; otherwise those are dropped. /// - public void ReplaceTiles(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z)> add, string action) + public void ReplaceTiles(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z)> add, string action, bool grow = false) { + add = new List<(ushort Id, int X, int Y, int Z)>(add); BeginEdit(action); foreach (MultiTile tile in new List(remove)) { RecordRemove(tile); } + if (grow) + { + int width = Width, height = Height; + foreach (var (_, x, y, _) in add) + { + if (x >= 0 && y >= 0) + { + width = Math.Max(width, x + 1); + height = Math.Max(height, y + 1); + } + } + + if (width != Width || height != Height) + { + RebuildGrid(width, height, new List(RealTiles)); + } + } + foreach (var (id, x, y, z) in add) { RecordNew(id, x, y, z, false, 0); diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs b/UoFiddler.Plugin.MultiEditor/Model/MultiTile.cs similarity index 97% rename from UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs rename to UoFiddler.Plugin.MultiEditor/Model/MultiTile.cs index b424e4fd..b4bfe357 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/MultiTile.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: MuadDib & Turley * @@ -12,10 +12,11 @@ using System; using System.Collections.Generic; using Ultima; +using UoFiddler.Plugin.MultiEditor.Rendering; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { - public partial class MultiTile : IComparable + public class MultiTile : IComparable { private int _x; private int _y; diff --git a/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs b/UoFiddler.Plugin.MultiEditor/Model/RotationTable.cs similarity index 96% rename from UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs rename to UoFiddler.Plugin.MultiEditor/Model/RotationTable.cs index c32c8280..c70e6613 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/RotationTable.cs @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** * * $Author: Turley * @@ -16,7 +16,7 @@ using System.Xml; using UoFiddler.Controls.Classes; -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { /// /// Facing table for tiles the client's house tables do not list (classic stairs, signs, diff --git a/UoFiddler.Plugin.MultiEditor/Model/SavedLayer.cs b/UoFiddler.Plugin.MultiEditor/Model/SavedLayer.cs new file mode 100644 index 00000000..875a45f4 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Model/SavedLayer.cs @@ -0,0 +1,20 @@ +/*************************************************************************** + * + * "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.Model +{ + /// + /// A layer as the layers file keeps it. is false for a layer that was + /// left out of the saved multi, so its tiles exist only here. + /// + internal sealed record SavedLayer(string Name, bool Visible, bool InFile, + List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> Tiles); +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs b/UoFiddler.Plugin.MultiEditor/Model/TileLayer.cs similarity index 69% rename from UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs rename to UoFiddler.Plugin.MultiEditor/Model/TileLayer.cs index 98c0dc11..75fb28d7 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs +++ b/UoFiddler.Plugin.MultiEditor/Model/TileLayer.cs @@ -7,9 +7,7 @@ * ***************************************************************************/ -using System.Collections.Generic; - -namespace UoFiddler.Plugin.MultiEditor.Classes +namespace UoFiddler.Plugin.MultiEditor.Model { /// /// A named group of tiles in a design. Every tile is on exactly one layer and new tiles go on @@ -29,11 +27,4 @@ public TileLayer(string name) public override string ToString() => Name; } - - /// - /// A layer as the layers file keeps it. is false for a layer that was - /// left out of the saved multi, so its tiles exist only here. - /// - internal sealed record SavedLayer(string Name, bool Visible, bool InFile, - List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> Tiles); } diff --git a/UoFiddler.Plugin.MultiEditor/Model/TileState.cs b/UoFiddler.Plugin.MultiEditor/Model/TileState.cs new file mode 100644 index 00000000..1ad882a3 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Model/TileState.cs @@ -0,0 +1,31 @@ +/*************************************************************************** + * + * $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. + * + ***************************************************************************/ + +namespace UoFiddler.Plugin.MultiEditor.Model +{ + /// + /// 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, TileLayer Layer) + { + public static TileState Of(MultiTile tile) => new(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible, tile.Layer); + + public void ApplyTo(MultiTile tile) + { + tile.Id = Id; + tile.Invisible = Invisible; + tile.Layer = Layer; + tile.X = X; + tile.Y = Y; + tile.Z = Z; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml b/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml new file mode 100644 index 00000000..50c9b8f1 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml @@ -0,0 +1,870 @@ + + + + + + + + + + + + + + + + + + + + + + + +