From 5fb5152ec7dd10f12127221433bff3b8a517f75d Mon Sep 17 00:00:00 2001 From: AsY!um- <377468+AsYlum-@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:11:12 +0100 Subject: [PATCH 01/16] Shape and place roofs in the multi editor Eaves fit the wall tops; gable and joined roofs are shaped as wings and placed on a Roof layer. --- .../MultiEditorComponentList.Layers.cs | 49 + .../Classes/MultiEditorComponentList.cs | 25 +- .../Classes/RoofPlanner.cs | 281 +++++ .../Editing/EditorSession.Commands.cs | 33 +- .../Editing/EditorSession.cs | 21 +- .../Tools/HousePartTools.cs | 359 ------ .../Tools/PlaneDragTool.cs | 9 +- .../Tools/RoofTool.cs | 1113 +++++++++++++++++ .../UI/MultiEditorControl.Designer.cs | 20 +- .../UI/MultiEditorControl.cs | 63 +- .../UI/ShortcutsForm.cs | 12 +- 11 files changed, 1606 insertions(+), 379 deletions(-) create mode 100644 UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs create mode 100644 UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs index 07cece0e..5014f086 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs @@ -111,6 +111,55 @@ public TileLayer LayerAdd(string name) return layer; } + /// + /// Removes some tiles and adds others in one undo step, the new ones on the layer each + /// names or, when it names none, on the layer called . That + /// layer is made on top of the others when the multi has none of that name; the active + /// layer stays as it is. The multi grows to hold tiles added past its +X/+Y end. + /// + public void ReplaceTilesOnLayer(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z, TileLayer Layer)> add, + string action, string layerName) + { + var added = new List<(ushort Id, int X, int Y, int Z, TileLayer 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)); + } + + TileLayer named = _layers.FirstOrDefault(l => l.Name == layerName); + if (named == null && added.Any(a => a.Layer == null)) + { + RecordLayers(); + TileLayer active = ActiveLayer; + named = new TileLayer(layerName); + _layers.Add(named); + ActiveLayer = active; + } + + foreach (var (id, x, y, z, layer) in added) + { + RecordNew(id, x, y, z, false, 0, layer: layer != null && _layers.Contains(layer) ? layer : named); + } + + 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/Classes/MultiEditorComponentList.cs index b11941e1..e4d5fa2b 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs @@ -528,16 +528,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/RoofPlanner.cs b/UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs new file mode 100644 index 00000000..09c44867 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs @@ -0,0 +1,281 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// The shape of one roof wing. + internal enum RoofShape + { + /// Two slopes meeting in a ridge. + Gable + } + + /// + /// 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. + /// + /// + internal static class RoofPlanner + { + /// Z a slope gains per cell: the roof pieces are 3 high. + public const int Rise = 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 cell it + /// raises loses any fixed piece another wing gave it 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); + int z = eaveZ + (Rise * steps); + if (heights.TryGetValue((x, y), out int known) && known >= z) + { + continue; + } + + heights[(x, y)] = z; + fixedPieces.Remove((x, y)); + } + } + } + + /// + /// The roof.txt column of the piece for a cell, from the heights around it; null for a + /// cell level with all its neighbours. is the plain piece to + /// use when the style has no such joint piece. + /// + public static string Piece(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y, out string fallback) + { + fallback = null; + if (!heights.TryGetValue((x, y), out int h)) + { + return null; + } + + // -1 lower (or no roof there), 0 level, 1 higher. + int Side(int cx, int cy, int ch) => heights.TryGetValue((cx, cy), out int n) ? Math.Sign(n - ch) : -1; + 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) + { + fallback = s > 0 ? "East" : "South"; + return s > 0 ? "EDent" : "SDent"; + } + + fallback = n > 0 ? "West" : "North"; + 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) + { + fallback = "NSCrosspiece"; + return "XPiece"; + } + + if (arms == 3) + { + fallback = armN && armS ? "NSCrosspiece" : "EWCrosspiece"; + 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; + } + + return Math.Abs(climbX) >= Math.Abs(climbY) ? (climbX > 0 ? "West" : "East") : (climbY > 0 ? "North" : "South"); + } + + /// + /// 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/Editing/EditorSession.Commands.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs index 0712822d..52a88e3b 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs @@ -998,6 +998,7 @@ private void ApplyLevelDefinitions(IEnumerable levels, bool cus /// /// 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() { @@ -1010,21 +1011,39 @@ private int DetectFirstFloorZ() } } - if (flat.Count == 0) + 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; + } + } + } + + // 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 needed = Math.Max(4, flat.Values.Max() / 4); - foreach ((int z, int count) in flat) + int best = 0, most = 3; + foreach ((int z, int count) in walls) { - if (z >= 0 && z <= MaxFirstFloorZ && count >= needed) + if (count > most) { - return z; + (best, most) = (z, count); } } - return 0; + return best; } /// A short label for a level's button: the number of "Floor 2", else the start of the name. diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs index 2fa581f9..932ee8ad 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs @@ -92,7 +92,14 @@ 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); + roof.Changed += () => + { + ToolChanged?.Invoke(); + Invalidated?.Invoke(); + }; + roof.Committed += () => LayersChanged?.Invoke(); + _tools[ToolKind.Roof] = roof; _tools[ToolKind.Foundation] = new FoundationTool(this); _tools[ToolKind.FloorPattern] = new FloorPatternTool(this); _pasteTool = new PasteTool(this); @@ -181,6 +188,7 @@ public bool Redo() private void SetDocument(MultiEditorComponentList list) { CancelTool(); + Roof.Discard(); CompList = list; _selection.Clear(); HoverTile = null; @@ -343,6 +351,12 @@ public ToolKind Tool get => _toolKind; set { + // A roof still being shaped is placed when another tool is taken up. + if (_toolKind == ToolKind.Roof && value != ToolKind.Roof) + { + Roof.Commit(); + } + CancelTool(); _toolKind = value; if (IsTileTool(value)) @@ -374,9 +388,12 @@ 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]; + /// True while the roof tool is in use and holds a roof that is not placed yet. + public bool ShapingRoof => _temporaryTool == null && _toolKind == ToolKind.Roof && Roof.HasPending; + /// Call after a tool option changed, so the preview under the cursor follows. public void ToolOptionsChanged() { diff --git a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs index 80547dc7..7edca4cd 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs @@ -66,365 +66,6 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z } } - /// Which way a gable roof's ridge runs. - internal enum RoofRidge - { - /// As the official houses: along the longer side, or so the ridge gets its crosspiece. - Auto, - AlongX, - AlongY - } - - /// Which gable ends of a roof are closed. - internal enum RoofGables - { - /// The south or east end, as the official houses do. - Front, - Both, - None - } - - /// What closes a gable. - internal enum RoofGableFill - { - /// 3 high cap pieces matching the walls. - Caps, - - /// Whole wall pieces as far as they fit under the slope, caps for the rest: for big, high roofs. - Walls - } - - /// - /// A gable roof over a house. A click on (or inside) a walled room fits the roof to its walls; - /// a drag over the wall cells sizes it by hand, as with the wall tool. The slopes rise 3 per - /// cell from the eaves, like the official house roofs: West pieces climb to an NS crosspiece - /// and East pieces come down (North / EW crosspiece / South the other way). Roof pieces - /// already in those cells are replaced. , and - /// choose the shape; Shift turns the ridge and Ctrl switches between - /// one and both gables for a single stroke. - /// - internal sealed class RoofTool : PlaneDragTool - { - private const int _rise = 3; - private const string _capStyles = "Miscellaneous Roof Pieces"; - - public RoofRidge Ridge { get; set; } = RoofRidge.Auto; - - public RoofGables Gables { get; set; } = RoofGables.Front; - - public RoofGableFill GableFill { get; set; } = RoofGableFill.Caps; - - public RoofTool(IEditorContext context) : base(context) - { - } - - protected override HousePartKind Kind => HousePartKind.Roof; - - protected override string ActionName => "Roof"; - - /// - /// The eaves go on the work plane, or on top of what the mouse points at (a wall top). - /// - protected override void BaseCell(out int x, out int y, out int z) - { - Context.CellAt(Context.MouseLoc, out x, out y, out z); - if (Context.WorkZ is { } baseZ) - { - z = baseZ; - Context.PlaneCell(Context.MouseLoc, z, out x, out y); - } - } - - protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( - int startX, int startY, int endX, int endY, int z, bool final) - { - var remove = new List(); - var add = new List<(ushort, int, int, int)>(); - MultiEditorComponentList list = Context.CompList; - - // Dragged like the wall tool, over the wall cells. Walls sit on the +X/+Y edges of their - // cells, so the roof over them is the same box one cell further along X and Y (as in the - // official houses, which overhang their east and south walls by a cell). - int wallX0 = Math.Min(startX, endX), wallX1 = Math.Max(startX, endX); - int wallY0 = Math.Min(startY, endY), wallY1 = Math.Max(startY, endY); - - // A click, not a drag: take the walls of the room it points at. - if (startX == endX && startY == endY && FitToWalls(startX, startY, z, out var fitted)) - { - (wallX0, wallY0, wallX1, wallY1) = fitted; - } - - int x0 = wallX0 + 1, x1 = wallX1 + 1; - int y0 = wallY0 + 1, y1 = wallY1 + 1; - - // Like the official houses: the slopes go across the odd side, so the ridge gets its - // crosspiece; otherwise the ridge runs along the longer side, along Y when square. - int spanX = x1 - x0 + 1, spanY = y1 - y0 + 1; - bool ridgeAlongY = Ridge switch - { - RoofRidge.AlongX => false, - RoofRidge.AlongY => true, - _ => spanX % 2 != spanY % 2 ? spanX % 2 == 1 : spanY >= spanX - }; - ridgeAlongY ^= ShiftHeld; - int across0 = ridgeAlongY ? x0 : y0; - int across1 = ridgeAlongY ? x1 : y1; - int span = across1 - across0 + 1; - string low = ridgeAlongY ? "West" : "North"; - string high = ridgeAlongY ? "East" : "South"; - string ridge = ridgeAlongY ? "NSCrosspiece" : "EWCrosspiece"; - - for (int x = x0; x <= x1; ++x) - { - for (int y = y0; y <= y1; ++y) - { - if (!list.InBounds(x, y)) - { - continue; - } - - int a = ridgeAlongY ? x : y; - int fromLow = a - across0; - int fromHigh = across1 - a; - string column = span % 2 == 1 && fromLow == fromHigh ? ridge : fromLow < fromHigh ? low : high; - ushort id = Style.Get(column); - if (id == 0) - { - continue; - } - - foreach (MultiTile tile in list.GetTilesAt(x, y)) - { - if (list.IsShown(tile) && Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Roof) - { - remove.Add(tile); - } - } - - add.Add((id, x, y, z + (_rise * Math.Min(fromLow, fromHigh)))); - } - } - - // Caps from an earlier roof over these walls go too, so a turned ridge leaves none behind. - for (int x = wallX0; x <= x1; ++x) - { - for (int y = wallY0; y <= y1; ++y) - { - foreach (MultiTile tile in list.GetTilesAt(x, y)) - { - if (IsCap(tile.Id) && list.IsShown(tile)) - { - remove.Add(tile); - } - } - } - } - - // Gables: in the wall row at the gable end, filled up to where the slope has risen there. - RoofGables gables = Gables; - if (CtrlHeld) - { - gables = gables == RoofGables.Both ? RoofGables.Front : RoofGables.Both; - } - - var gableRows = new List(); - if (gables != RoofGables.None) - { - gableRows.Add(ridgeAlongY ? wallY1 : wallX1); - } - - if (gables == RoofGables.Both) - { - gableRows.Add(ridgeAlongY ? wallY0 : wallX0); - } - - foreach (int row in gableRows) - { - ushort wall = GableWall(row, ridgeAlongY, wallX0, wallX1, wallY0, wallY1, z); - ushort cap = wall != 0 ? CapFor(wall, ridgeAlongY) : (ushort)0; - - // Whole walls: the plain piece of the wall's own style that runs along the gable. - ushort block = 0; - int blockHeight = 0; - if (GableFill == RoofGableFill.Walls && wall != 0) - { - block = wall; - if (Context.HouseStyles.TryGetRole(wall, out HouseStyle wallStyle, out _) && - wallStyle.Get(ridgeAlongY ? "South2" : "East2") is var plain and not 0) - { - block = plain; - } - - blockHeight = TileData.ItemTable[block].Height; - } - - if (cap == 0 && blockHeight <= 0) - { - continue; - } - - for (int a = across0; a <= across1; ++a) - { - int top = _rise * Math.Min(a - across0, across1 - a); - int x = ridgeAlongY ? a : row; - int y = ridgeAlongY ? row : a; - if (!list.InBounds(x, y)) - { - continue; - } - - int filled = 0; - while (blockHeight > 0 && top - filled >= blockHeight) - { - add.Add((block, x, y, z + filled)); - filled += blockHeight; - } - - while (cap != 0 && top - filled >= _rise) - { - add.Add((cap, x, y, z + filled)); - filled += _rise; - } - } - } - - return (remove, add); - } - - /// - /// The walls a click means: the box of the connected run of wall cells, on the level just - /// below , that holds the clicked cell. A click inside a room takes the - /// smallest such box around it. False when there are no walls there. - /// - private bool FitToWalls(int cx, int cy, int z, out (int X0, int Y0, int X1, int Y1) box) - { - MultiEditorComponentList list = Context.CompList; - bool IsWall(int x, int y) - { - foreach (MultiTile tile in list.GetTilesAt(x, y)) - { - if (tile.Z < z && tile.Z >= z - 20 && - Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) - { - return true; - } - } - - return false; - } - - box = default; - long bestArea = long.MaxValue; - var seen = new HashSet<(int, int)>(); - var queue = new Queue<(int X, int Y)>(); - for (int sx = 0; sx < list.Width; ++sx) - { - for (int sy = 0; sy < list.Height; ++sy) - { - if (seen.Contains((sx, sy)) || !IsWall(sx, sy)) - { - continue; - } - - int x0 = sx, y0 = sy, x1 = sx, y1 = sy, cells = 0; - seen.Add((sx, sy)); - queue.Enqueue((sx, sy)); - while (queue.Count > 0) - { - (int x, int y) = queue.Dequeue(); - ++cells; - x0 = Math.Min(x0, x); - y0 = Math.Min(y0, y); - x1 = Math.Max(x1, x); - y1 = Math.Max(y1, y); - foreach ((int dx, int dy) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) }) - { - (int nx, int ny) = (x + dx, y + dy); - if (list.InBounds(nx, ny) && !seen.Contains((nx, ny)) && IsWall(nx, ny)) - { - seen.Add((nx, ny)); - queue.Enqueue((nx, ny)); - } - } - } - - long area = (long)(x1 - x0 + 1) * (y1 - y0 + 1); - if (cells > 1 && cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1 && area < bestArea) - { - bestArea = area; - box = (x0, y0, x1, y1); - } - } - } - - return bestArea != long.MaxValue; - } - - private bool IsCap(ushort id) - { - return Context.HouseStyles.TryGetRole(id, out HouseStyle owner, out _) && - owner.Kind == HousePartKind.Misc && owner.Group.StartsWith(_capStyles, StringComparison.Ordinal); - } - - /// A wall tile below the eaves in a gable wall row, or 0 when the row has none. - private ushort GableWall(int row, bool alongX, int wallX0, int wallX1, int wallY0, int wallY1, int z) - { - MultiEditorComponentList list = Context.CompList; - ushort wall = 0; - int from = alongX ? wallX0 : wallY0, to = alongX ? wallX1 : wallY1; - for (int a = from; a <= to && wall == 0; ++a) - { - foreach (MultiTile tile in list.GetTilesAt(alongX ? a : row, alongX ? row : a)) - { - if (tile.Z < z && Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) - { - wall = tile.Id; - break; - } - } - } - - return wall; - } - - /// - /// The cap for a gable over a wall: the misc.txt roof piece with the wall's tiledata name and - /// the id nearest its own. Odd pieces close walls along X, even pieces walls along Y (as - /// placed in the official multis). 0 when no cap matches. - /// - private ushort CapFor(ushort wall, bool alongX) - { - string name = TileData.ItemTable[wall].Name; - ushort best = 0; - foreach (HouseStyle style in Context.HouseStyles.Styles) - { - if (style.Kind != HousePartKind.Misc || !style.Group.StartsWith(_capStyles, StringComparison.Ordinal)) - { - continue; - } - - for (int pair = 1; pair <= 7; pair += 2) - { - ushort first = style.Get($"Piece{pair}"); - ushort second = style.Get($"Piece{pair + 1}"); - ushort cap = alongX ? first : second; - if (first == 0 || second == 0 || TileData.ItemTable[cap].Height > 4 || - !string.Equals(TileData.ItemTable[cap].Name, name, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - if (best == 0 || Math.Abs(cap - wall) < Math.Abs(best - wall)) - { - best = cap; - } - } - } - - return best; - } - } - /// /// A house foundation like the client's customizable house multis: the dragged rectangle gets /// a ring of 5 high foundation walls at the base Z and a dirt floor 7 above it inside. diff --git a/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs index 323adc08..153f80d3 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/PlaneDragTool.cs @@ -9,8 +9,10 @@ * ***************************************************************************/ +using System; using System.Collections.Generic; using System.Drawing; +using System.Linq; using System.Windows.Forms; using UoFiddler.Plugin.MultiEditor.Classes; @@ -45,6 +47,9 @@ protected PlaneDragTool(IEditorContext context) : base(context) /// The edit's name in the undo list. protected abstract string ActionName { get; } + /// True when tiles planned past the +X/+Y end of the multi make it bigger instead of being dropped. + protected virtual bool GrowsMulti => false; + public override void OnMouseDown(MouseEventArgs e) { if (Style == null) @@ -78,8 +83,8 @@ public override void OnMouseUp(MouseEventArgs e) var (remove, add) = Plan(_startX, _startY, _endX, _endY, _z, final: true); if (remove.Count > 0 || add.Count > 0) { - Context.CompList.ReplaceTiles(remove, add, ActionName); - Context.AfterEdit(_z); + Context.CompList.ReplaceTiles(remove, add, ActionName, GrowsMulti); + Context.AfterEdit(add.Count > 0 ? Math.Max(_z, add.Max(a => a.Z)) : _z); } } diff --git a/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs new file mode 100644 index 00000000..e4dea8bd --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs @@ -0,0 +1,1113 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using Ultima; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// Which way a gable roof's ridge runs. + internal enum RoofRidge + { + /// As the official houses: along the longer side, or so the ridge gets its crosspiece. + Auto, + AlongX, + AlongY + } + + /// Which gable ends of a roof are closed. + internal enum RoofGables + { + /// The south or east end, as the official houses do. + Front, + Both, + None + } + + /// What closes a gable. + internal enum RoofGableFill + { + /// 3 high cap pieces matching the walls. + Caps, + + /// Whole wall pieces as far as they fit under the slope, caps for the rest: for big, high roofs. + Walls + } + + /// One rectangle of a roof being shaped: where it lies, how high its eaves are and how it slopes. + 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; } + + 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() => (RoofWing)MemberwiseClone(); + + public void CopyFrom(RoofWing other) + { + (X0, Y0, X1, Y1, EaveZ) = (other.X0, other.Y0, other.X1, other.Y1, other.EaveZ); + (Shape, RidgeAlongY, RidgeAuto) = (other.Shape, other.RidgeAlongY, other.RidgeAuto); + } + } + + /// + /// Roofs, shaped before they are placed. The first click on (or inside) a walled room fits a + /// roof to its walls, part by part on an L or T shaped house; a drag over the walls, the floor + /// inside them or the area the roof will cover fits it too, and any other drag is a roof of + /// that size on the work plane. The roof then stays pending, shown as it will be built: + /// + /// click a wing to select it, drag it to move it, drag an edge of the selected wing to + /// resize it; + /// drag anywhere else to add a wing, which joins the others with valleys and T pieces; + /// Shift+click turns a wing's ridge, the Shape and Ridge options + /// change the selected wing, Delete removes it; + /// Enter, or switching to another tool, places the roof on the layer named + /// in one undo step; Esc drops it. + /// + /// A fitted roof sits on the wall tops whatever floor is chosen, overhangs the south and east + /// walls by a cell and grows the multi when that cell lies outside it. Slopes rise 3 per cell + /// like the official house roofs. A roof already there is replaced when it lies wholly under + /// the new one and joined otherwise. + /// + internal sealed class RoofTool : EditorTool + { + /// The layer a placed roof goes on; made on first use. + public const string LayerName = "Roof"; + + private const int _rise = RoofPlanner.Rise; + private const int _storey = 20; + private const string _capStyles = "Miscellaneous Roof Pieces"; + + private enum DragKind + { + None, + New, + Move, + Resize + } + + private readonly List _wings = new List(); + private int _selected = -1; + private HouseStyle _lastStyle; + private RoofShape _shape = RoofShape.Gable; + private RoofRidge _ridge = RoofRidge.Auto; + + private DragKind _drag; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + private int _z; + private RoofWing _before; + private int _grabX; + private int _grabY; + private bool _west; + private bool _east; + private bool _north; + private bool _south; + + public RoofTool(IEditorContext context) : base(context) + { + } + + /// Raised when the pending roof starts, changes or ends. + public event Action Changed; + + /// Raised after a roof was placed. + public event Action Committed; + + /// The shape of new wings; also sets the selected wing's. + public RoofShape Shape + { + get => _shape; + set + { + _shape = value; + if (SelectedWing is { } wing) + { + wing.Shape = value; + } + } + } + + /// The ridge direction of new wings; also sets the selected wing's. + public RoofRidge Ridge + { + get => _ridge; + set + { + _ridge = value; + if (SelectedWing is { } wing) + { + wing.RidgeAuto = value == RoofRidge.Auto; + wing.RidgeAlongY = value == RoofRidge.Auto ? RoofPlanner.RidgeAlongY(wing.Box) : value == RoofRidge.AlongY; + } + } + } + + public RoofGables Gables { get; set; } = RoofGables.Front; + + public RoofGableFill GableFill { get; set; } = RoofGableFill.Caps; + + /// True while a roof is being shaped and not yet placed. + public bool HasPending => _wings.Count > 0; + + public bool HasSelectedWing => SelectedWing != null; + + public IReadOnlyList Wings => _wings; + + public override bool IsDragging => _drag != DragKind.None; + + public override bool TracksCursorCell => true; + + private RoofWing SelectedWing => _selected >= 0 && _selected < _wings.Count ? _wings[_selected] : null; + + /// The roof style chosen in the House tab; a pending roof keeps the last one. + private HouseStyle Style + { + get + { + if (Context.HouseStyle is { Kind: HousePartKind.Roof } style) + { + _lastStyle = style; + return style; + } + + return HasPending ? _lastStyle : null; + } + } + + // ---------------------------------------------------------------- shaping + + public override void OnMouseDown(MouseEventArgs e) + { + if (Style == null) + { + return; + } + + if (HasPending) + { + int hit = HitWing(out int cx, out int cy); + if (hit >= 0) + { + RoofWing wing = _wings[hit]; + bool wasSelected = hit == _selected; + _selected = hit; + if (ShiftHeld) + { + Turn(wing); + Changed?.Invoke(); + return; + } + + _before = wing.Clone(); + (_grabX, _grabY) = (cx, cy); + + // The selected wing is resized by its outermost cells; a side too short to + // have a middle moves the wing instead. + bool wide = wing.X1 - wing.X0 >= 2, deep = wing.Y1 - wing.Y0 >= 2; + _west = wasSelected && wide && cx == wing.X0; + _east = wasSelected && wide && cx == wing.X1; + _north = wasSelected && deep && cy == wing.Y0; + _south = wasSelected && deep && cy == wing.Y1; + _drag = _west || _east || _north || _south ? DragKind.Resize : DragKind.Move; + Changed?.Invoke(); + return; + } + + // A new wing, level with the wing worked on last. + _z = (SelectedWing ?? _wings[^1]).EaveZ; + Context.PlaneCell(Context.MouseLoc, _z, out _startX, out _startY); + } + else + { + BaseCell(out _startX, out _startY, out _z); + } + + (_endX, _endY) = (_startX, _startY); + _drag = DragKind.New; + } + + public override void OnMouseMove(MouseEventArgs e) + { + switch (_drag) + { + case DragKind.New: + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + break; + case DragKind.Move: + case DragKind.Resize: + DragWing(); + break; + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + DragKind drag = _drag; + if (drag is DragKind.Move or DragKind.Resize) + { + DragWing(); + } + + _drag = DragKind.None; + if (drag == DragKind.New) + { + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + List wings = WingsFor(_startX, _startY, _endX, _endY, _z, out bool fitted); + if (HasPending && !fitted && _startX == _endX && _startY == _endY) + { + // A click beside the roof lets go of the selected wing. + _selected = -1; + } + else + { + _wings.AddRange(wings); + _selected = _wings.Count - wings.Count; + } + + Changed?.Invoke(); + } + else if (drag != DragKind.None) + { + _before = null; + Changed?.Invoke(); + } + } + + /// Stops a drag: a wing being moved or resized goes back to where it was. + public override void Cancel() + { + if (_drag is DragKind.Move or DragKind.Resize && _before != null && SelectedWing is { } wing) + { + wing.CopyFrom(_before); + } + + _before = null; + _drag = DragKind.None; + } + + /// Drops the pending roof. + public void Discard() + { + bool had = HasPending; + _wings.Clear(); + _selected = -1; + _before = null; + _drag = DragKind.None; + if (had) + { + Changed?.Invoke(); + } + } + + /// Removes the selected wing from the pending roof. + public void DeleteWing() + { + if (SelectedWing == null || IsDragging) + { + return; + } + + _wings.RemoveAt(_selected); + _selected = _wings.Count - 1; + Changed?.Invoke(); + } + + /// + /// Places the pending roof: its tiles go on the layer, pieces of + /// an older roof that had to change stay on their own layer, all in one undo step. + /// + public void Commit() + { + Cancel(); + if (!HasPending) + { + return; + } + + if (Style != null) + { + var (remove, add) = Plan(_wings); + if (remove.Count > 0 || add.Count > 0) + { + Context.CompList.ReplaceTilesOnLayer(remove, add, "Roof", LayerName); + Context.AfterEdit(add.Count > 0 ? add.Max(a => a.Z) : null); + Committed?.Invoke(); + } + } + + Discard(); + } + + /// Lays a roof in one go, as a press at one cell and a release at another would shape it. For scripts and tests. + public void Place(int startX, int startY, int endX, int endY, int z) + { + if (Style == null) + { + return; + } + + _wings.AddRange(WingsFor(startX, startY, endX, endY, z, out _)); + Commit(); + } + + /// + /// The eaves go on the work plane, or on top of what the mouse points at (a wall top). + /// + 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); + } + } + + /// The pending wing under the mouse, the selected one first, and the cell pointed at on its eaves. + private int HitWing(out int cx, out int cy) + { + (cx, cy) = (0, 0); + for (int pass = 0; pass < 2; ++pass) + { + for (int i = _wings.Count - 1; i >= 0; --i) + { + if ((pass == 0) != (i == _selected)) + { + continue; + } + + RoofWing wing = _wings[i]; + Context.PlaneCell(Context.MouseLoc, wing.EaveZ, out cx, out cy); + if (cx >= wing.X0 && cx <= wing.X1 && cy >= wing.Y0 && cy <= wing.Y1) + { + return i; + } + } + } + + return -1; + } + + private void DragWing() + { + if (_before == null || SelectedWing is not { } wing) + { + return; + } + + Context.PlaneCell(Context.MouseLoc, _before.EaveZ, out int cx, out int cy); + int dx = cx - _grabX, dy = cy - _grabY; + if (_drag == DragKind.Move) + { + dx = Math.Max(dx, -_before.X0); + dy = Math.Max(dy, -_before.Y0); + (wing.X0, wing.X1, wing.Y0, wing.Y1) = (_before.X0 + dx, _before.X1 + dx, _before.Y0 + dy, _before.Y1 + dy); + return; + } + + wing.X0 = _west ? Math.Clamp(_before.X0 + dx, 0, _before.X1) : _before.X0; + wing.X1 = _east ? Math.Max(_before.X1 + dx, _before.X0) : _before.X1; + wing.Y0 = _north ? Math.Clamp(_before.Y0 + dy, 0, _before.Y1) : _before.Y0; + wing.Y1 = _south ? Math.Max(_before.Y1 + dy, _before.Y0) : _before.Y1; + if (wing.RidgeAuto) + { + wing.RidgeAlongY = RoofPlanner.RidgeAlongY(wing.Box); + } + } + + /// Turns a wing's ridge the other way. + private static void Turn(RoofWing wing) + { + wing.RidgeAlongY = !wing.RidgeAlongY; + wing.RidgeAuto = false; + } + + /// + /// The wings a stroke makes. Walls sit on the +X/+Y edges of their cells, so the roof over + /// them is their box one cell further along X and Y (as in the official houses, which + /// overhang their east and south walls by a cell). A click takes the walls of the room it + /// points at, each part of an L or T shaped house as a wing of its own; a drag that comes + /// within a cell of such a roof on every side means that roof. Any other stroke is the + /// roof itself, at . Shift turns a gable's ridge. + /// + private List WingsFor(int startX, int startY, int endX, int endY, int z, out bool fitted) + { + int x0 = Math.Min(startX, endX), x1 = Math.Max(startX, endX); + int y0 = Math.Min(startY, endY), y1 = Math.Max(startY, endY); + bool click = x0 == x1 && y0 == y1; + var wings = new List(); + fitted = FitToWalls(x0, y0, x1, y1, z, out WallBox walls); + if (fitted) + { + (x0, y0, x1, y1) = (walls.X0 + 1, walls.Y0 + 1, walls.X1 + 1, walls.Y1 + 1); + z = walls.Top; + if (click && Shape == RoofShape.Gable) + { + var parts = RoofPlanner.Wings(RoofRegion(walls)); + if (parts.Count > 1) + { + foreach (((int X0, int Y0, int X1, int Y1) box, bool alongY) in parts) + { + wings.Add(new RoofWing { X0 = box.X0, Y0 = box.Y0, X1 = box.X1, Y1 = box.Y1, EaveZ = z, RidgeAlongY = alongY }); + } + + return wings; + } + } + } + + bool auto = Ridge == RoofRidge.Auto; + bool ridgeAlongY = auto ? RoofPlanner.RidgeAlongY((x0, y0, x1, y1)) : Ridge == RoofRidge.AlongY; + if (ShiftHeld && Shape == RoofShape.Gable) + { + (ridgeAlongY, auto) = (!ridgeAlongY, false); + } + + wings.Add(new RoofWing + { + X0 = x0, Y0 = y0, X1 = x1, Y1 = y1, EaveZ = z, Shape = Shape, + RidgeAlongY = ridgeAlongY, RidgeAuto = auto + }); + return wings; + } + + // ---------------------------------------------------------------- overlay + + public override void PaintOverlay(IToolOverlay overlay) + { + if (Style == null) + { + return; + } + + // What is shown is what Enter would build: the pending wings, with the one being + // dragged out; before there is a roof, the one a click here would start. + var wings = new List(_wings); + if (_drag == DragKind.New) + { + wings.AddRange(WingsFor(_startX, _startY, _endX, _endY, _z, out _)); + } + else if (!HasPending) + { + BaseCell(out int x, out int y, out int z); + wings.AddRange(WingsFor(x, y, x, y, z, out _)); + } + + var (remove, add) = Plan(wings); + foreach (MultiTile tile in remove) + { + overlay.Highlight(tile, TileHighlight.Remove); + } + + foreach (var (id, x, y, z, _) in add) + { + overlay.Ghost(id, x, y, z); + } + + for (int i = 0; i < _wings.Count; ++i) + { + RoofWing wing = _wings[i]; + Point top = Corner(wing.X0, wing.Y0, wing.EaveZ), right = Corner(wing.X1 + 1, wing.Y0, wing.EaveZ); + Point bottom = Corner(wing.X1 + 1, wing.Y1 + 1, wing.EaveZ), left = Corner(wing.X0, wing.Y1 + 1, wing.EaveZ); + overlay.Polyline(new[] { top, right, bottom, left }, closed: true); + if (i != _selected) + { + continue; + } + + // Grips in the middle of the selected wing's sides. + foreach ((Point a, Point b) in new[] { (top, right), (right, bottom), (bottom, left), (left, top) }) + { + var mid = new Point((a.X + b.X) / 2, (a.Y + b.Y) / 2); + overlay.Polyline(new[] + { + new Point(mid.X - 5, mid.Y - 5), new Point(mid.X + 5, mid.Y - 5), + new Point(mid.X + 5, mid.Y + 5), new Point(mid.X - 5, mid.Y + 5) + }, closed: true); + } + } + } + + /// Canvas position of the top corner of a cell's diamond at height z. + private static Point Corner(int x, int y, int z) + { + return new Point(((x - y) * 22) + MultiEditorComponentList.GapXMod, ((x + y) * 22) - (z * 4) - 22); + } + + // ---------------------------------------------------------------- planning + + /// + /// The tiles a roof of these wings takes away and adds. An added tile with no layer goes + /// on the roof layer; a re-pieced tile of an older roof names the layer it stays on. + /// + private (List Remove, List<(ushort Id, int X, int Y, int Z, TileLayer Layer)> Add) Plan(IReadOnlyList wings) + { + var remove = new List(); + var add = new List<(ushort Id, int X, int Y, int Z, TileLayer Layer)>(); + HouseStyle style = Style; + if (wings.Count == 0 || style == null) + { + return (remove, add); + } + + MultiEditorComponentList list = Context.CompList; + var heights = new Dictionary<(int X, int Y), int>(); + var fixedPieces = new Dictionary<(int X, int Y), string>(); + foreach (RoofWing wing in wings) + { + RoofPlanner.AddWing(heights, fixedPieces, wing.Box, wing.RidgeAlongY, wing.Shape, wing.EaveZ); + } + + var footprint = new HashSet<(int X, int Y)>(heights.Keys); + JoinExisting(footprint, heights, fixedPieces, remove, add); + + foreach ((int x, int y) in footprint) + { + if (!fixedPieces.TryGetValue((x, y), out string column)) + { + column = RoofPlanner.Piece(heights, x, y, out string fallback) ?? (wings[0].RidgeAlongY ? "West" : "North"); + if (style.Get(column) == 0 && fallback != null) + { + column = fallback; + } + } + + ushort id = style.Get(column); + if (id != 0) + { + add.Add((id, x, y, heights[(x, y)], null)); + } + } + + // Caps from an earlier roof over these walls go too, so a turned ridge leaves none behind. + foreach (RoofWing wing in wings) + { + for (int x = wing.X0 - 1; x <= wing.X1; ++x) + { + for (int y = wing.Y0 - 1; y <= wing.Y1; ++y) + { + foreach (MultiTile tile in list.GetTilesAt(x, y)) + { + if (IsCap(tile.Id) && list.IsShown(tile) && !remove.Contains(tile)) + { + remove.Add(tile); + } + } + } + } + } + + // Every gable wing closes the ends it shows. + var caps = new HashSet<(ushort, int, int, int)>(); + foreach (RoofWing wing in wings) + { + if (wing.Shape == RoofShape.Gable) + { + AddGables(wing, heights, caps, add); + } + } + + return (remove, add); + } + + /// + /// Closes a gable's ends: in the wall row at the gable end, each wall cell is filled up + /// to where the wing's slope has risen over it. An end that runs into another wing shows + /// no gable and gets none: only cells with no roof beyond them are filled. + /// + private void AddGables(RoofWing wing, Dictionary<(int X, int Y), int> heights, HashSet<(ushort, int, int, int)> placed, + List<(ushort Id, int X, int Y, int Z, TileLayer Layer)> add) + { + MultiEditorComponentList list = Context.CompList; + bool ridgeAlongY = wing.RidgeAlongY; + int z = wing.EaveZ; + int wallX0 = wing.X0 - 1, wallX1 = wing.X1 - 1; + int wallY0 = wing.Y0 - 1, wallY1 = wing.Y1 - 1; + int across0 = ridgeAlongY ? wing.X0 : wing.Y0; + int across1 = ridgeAlongY ? wing.X1 : wing.Y1; + + var gableRows = new List<(int Row, bool Front)>(); + if (Gables != RoofGables.None) + { + gableRows.Add((ridgeAlongY ? wallY1 : wallX1, true)); + } + + if (Gables == RoofGables.Both) + { + gableRows.Add((ridgeAlongY ? wallY0 : wallX0, false)); + } + + foreach ((int row, bool front) in gableRows) + { + ushort wall = GableWall(row, ridgeAlongY, wallX0, wallX1, wallY0, wallY1, z); + ushort cap = wall != 0 ? CapFor(wall, ridgeAlongY) : (ushort)0; + + // Whole walls: the plain piece of the wall's own style that runs along the gable. + ushort block = 0; + int blockHeight = 0; + if (GableFill == RoofGableFill.Walls && wall != 0) + { + block = wall; + if (Context.HouseStyles.TryGetRole(wall, out HouseStyle wallStyle, out _) && + wallStyle.Get(ridgeAlongY ? "South2" : "East2") is var plain and not 0) + { + block = plain; + } + + blockHeight = TileData.ItemTable[block].Height; + } + + if (cap == 0 && blockHeight <= 0) + { + continue; + } + + for (int a = across0; a <= across1; ++a) + { + int x = ridgeAlongY ? a : row; + int y = ridgeAlongY ? row : a; + + // The front wall stands a cell inside the roof's last row, the back wall a + // cell before its first; the end shows where no roof lies past it. + (int X, int Y) beyond = front ? (ridgeAlongY ? (x, y + 2) : (x + 2, y)) : (x, y); + if (!list.InBounds(x, y) || heights.ContainsKey(beyond) || !HasStoreyWall(x, y, z)) + { + continue; + } + + int top = _rise * Math.Min(a - across0, across1 - a); + int filled = 0; + while (blockHeight > 0 && top - filled >= blockHeight) + { + if (placed.Add((block, x, y, z + filled))) + { + add.Add((block, x, y, z + filled, null)); + } + + filled += blockHeight; + } + + while (cap != 0 && top - filled >= _rise) + { + if (placed.Add((cap, x, y, z + filled))) + { + add.Add((cap, x, y, z + filled, null)); + } + + filled += _rise; + } + } + } + } + + /// A connected run of wall cells and the Z its walls end at. + private readonly record struct WallBox(int X0, int Y0, int X1, int Y1, int Top, HashSet<(int X, int Y)> Cells); + + /// + /// The cells a roof over these walls covers: the wall cells and everything they enclose, + /// one cell further along X and Y. For walls that do not close it is the walls alone. + /// + private static HashSet<(int X, int Y)> RoofRegion(WallBox walls) + { + // Flood the outside, from a ring one cell around the box. + var outside = new HashSet<(int X, int Y)>(); + var queue = new Queue<(int X, int Y)>(); + outside.Add((walls.X0 - 1, walls.Y0 - 1)); + queue.Enqueue((walls.X0 - 1, walls.Y0 - 1)); + while (queue.Count > 0) + { + (int x, int y) = queue.Dequeue(); + foreach ((int dx, int dy) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) }) + { + (int X, int Y) next = (x + dx, y + dy); + if (next.X >= walls.X0 - 1 && next.X <= walls.X1 + 1 && next.Y >= walls.Y0 - 1 && next.Y <= walls.Y1 + 1 && + !walls.Cells.Contains(next) && outside.Add(next)) + { + queue.Enqueue(next); + } + } + } + + var region = new HashSet<(int X, int Y)>(); + for (int x = walls.X0; x <= walls.X1; ++x) + { + for (int y = walls.Y0; y <= walls.Y1; ++y) + { + if (!outside.Contains((x, y))) + { + region.Add((x + 1, y + 1)); + } + } + } + + return region; + } + + /// + /// Fits a new roof to the roof already there. A roof lying wholly under the new one is + /// replaced. One that reaches beyond it is joined: each cell keeps the higher of the two, + /// and the old cells next to the new roof get the piece their place now calls for (a + /// valley, a T where the ridges meet), in their own style. Cells the old roof keeps are + /// taken out of . + /// + private void JoinExisting(HashSet<(int X, int Y)> footprint, Dictionary<(int X, int Y), int> heights, + Dictionary<(int X, int Y), string> fixedPieces, List remove, List<(ushort Id, int X, int Y, int Z, TileLayer Layer)> add) + { + MultiEditorComponentList list = Context.CompList; + var existing = new Dictionary<(int X, int Y), List>(); + foreach (MultiTile tile in list.RealTiles) + { + if (!list.IsShown(tile) || !IsRoofPiece(tile.Id)) + { + continue; + } + + if (!existing.TryGetValue((tile.X, tile.Y), out List tiles)) + { + existing[(tile.X, tile.Y)] = tiles = new List(); + } + + tiles.Add(tile); + } + + var seen = new HashSet<(int X, int Y)>(); + var queue = new Queue<(int X, int Y)>(); + var kept = new Dictionary<(int X, int Y), MultiTile>(); + foreach ((int X, int Y) start in new List<(int X, int Y)>(footprint)) + { + if (!existing.ContainsKey(start) || !seen.Add(start)) + { + continue; + } + + var roof = new List<(int X, int Y)>(); + bool inside = true; + queue.Enqueue(start); + while (queue.Count > 0) + { + (int x, int y) = queue.Dequeue(); + roof.Add((x, y)); + inside &= footprint.Contains((x, y)) || kept.ContainsKey((x, y)); + foreach ((int dx, int dy) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) }) + { + if (existing.ContainsKey((x + dx, y + dy)) && seen.Add((x + dx, y + dy))) + { + queue.Enqueue((x + dx, y + dy)); + } + } + } + + foreach ((int X, int Y) cell in roof) + { + List tiles = existing[cell]; + MultiTile top = tiles[0]; + foreach (MultiTile tile in tiles) + { + if (tile.Z > top.Z) + { + top = tile; + } + } + + if (inside || (footprint.Contains(cell) && heights[cell] > top.Z)) + { + remove.AddRange(tiles); + continue; + } + + heights[cell] = top.Z; + fixedPieces.Remove(cell); + footprint.Remove(cell); + kept[cell] = top; + } + } + + foreach (((int x, int y), MultiTile tile) in kept) + { + bool beside = false; + for (int dx = -2; dx <= 2 && !beside; ++dx) + { + for (int dy = -2; dy <= 2 && !beside; ++dy) + { + beside = footprint.Contains((x + dx, y + dy)); + } + } + + string fallback = null; + string column = beside ? RoofPlanner.Piece(heights, x, y, out fallback) : null; + if (column == null) + { + continue; + } + + HouseStyle style = Style; + string now = null; + if (Context.HouseStyles.TryGetRoleByArt(tile.Id, out HouseStyle owner, out string slot, out _) && owner.Kind == HousePartKind.Roof) + { + (style, now) = (owner, slot); + } + + if (now == column || (style.Get(column) == 0 && now == fallback)) + { + continue; + } + + ushort id = style.Get(column) != 0 ? style.Get(column) : style.Get(fallback ?? column); + if (id != 0 && id != tile.Id) + { + remove.Add(tile); + add.Add((id, x, y, tile.Z, tile.Layer)); + } + } + } + + private bool IsRoofPiece(ushort id) + { + return Context.HouseStyles.TryGetRole(id, out HouseStyle owner, out _) + ? owner.Kind == HousePartKind.Roof + : (TileData.ItemTable[id].Flags & TileFlag.Roof) != 0; + } + + /// + /// The walls a stroke means, among the walls standing on or just below + /// . A click (one cell) takes the smallest box of connected wall cells + /// around it. A drag takes the box whose roof it matches to within a cell on every side. + /// False when no walls fit. + /// + private bool FitToWalls(int x0, int y0, int x1, int y1, int z, out WallBox box) + { + box = default; + bool click = x0 == x1 && y0 == y1; + long best = long.MaxValue; + foreach (WallBox walls in WallBoxes(z)) + { + long score; + if (click) + { + if (x0 < walls.X0 || x0 > walls.X1 || y0 < walls.Y0 || y0 > walls.Y1) + { + continue; + } + + score = (long)(walls.X1 - walls.X0 + 1) * (walls.Y1 - walls.Y0 + 1); + } + else + { + int dx0 = Math.Abs(x0 - (walls.X0 + 1)), dx1 = Math.Abs(x1 - (walls.X1 + 1)); + int dy0 = Math.Abs(y0 - (walls.Y0 + 1)), dy1 = Math.Abs(y1 - (walls.Y1 + 1)); + if (Math.Max(Math.Max(dx0, dx1), Math.Max(dy0, dy1)) > 1) + { + continue; + } + + score = dx0 + dx1 + dy0 + dy1; + } + + if (score < best) + { + best = score; + box = walls; + } + } + + return best != long.MaxValue; + } + + /// + /// The boxes of connected wall cells of the storey that stands on or just below + /// (the work plane, or the top of what the mouse points at), each with + /// the Z its walls end at. Walls a little short of a storey count as a full one, as the + /// official houses roof their 19 high plaster walls at 20. + /// + private List WallBoxes(int z) + { + MultiEditorComponentList list = Context.CompList; + var tops = new Dictionary<(int, int), int>(); + foreach (MultiTile tile in list.RealTiles) + { + if (tile.Z > z || tile.Z <= z - _storey - 5 || !list.IsShown(tile) || !IsStoreyWall(tile)) + { + continue; + } + + int height = tile.Height >= _storey - 3 ? Math.Max(tile.Height, _storey) : tile.Height; + int top = tile.Z + height; + if (!tops.TryGetValue((tile.X, tile.Y), out int known) || top > known) + { + tops[(tile.X, tile.Y)] = top; + } + } + + var boxes = new List(); + var seen = new HashSet<(int, int)>(); + var queue = new Queue<(int X, int Y)>(); + var counts = new Dictionary(); + foreach ((int, int) start in tops.Keys) + { + if (!seen.Add(start)) + { + continue; + } + + int x0 = start.Item1, y0 = start.Item2, x1 = x0, y1 = y0; + var cells = new HashSet<(int X, int Y)>(); + counts.Clear(); + queue.Enqueue(start); + while (queue.Count > 0) + { + (int x, int y) = queue.Dequeue(); + cells.Add((x, y)); + x0 = Math.Min(x0, x); + y0 = Math.Min(y0, y); + x1 = Math.Max(x1, x); + y1 = Math.Max(y1, y); + int top = tops[(x, y)]; + counts[top] = counts.GetValueOrDefault(top) + 1; + foreach ((int dx, int dy) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) }) + { + (int, int) next = (x + dx, y + dy); + if (tops.ContainsKey(next) && seen.Add(next)) + { + queue.Enqueue(next); + } + } + } + + if (cells.Count > 1) + { + int common = counts.OrderByDescending(c => c.Value).ThenByDescending(c => c.Key).First().Key; + boxes.Add(new WallBox(x0, y0, x1, y1, common, cells)); + } + } + + return boxes; + } + + /// True when a wall of the storey below stands in the cell. + private bool HasStoreyWall(int x, int y, int z) + { + foreach (MultiTile tile in Context.CompList.GetTilesAt(x, y)) + { + if (tile.Z < z && tile.Z > z - _storey - 5 && IsStoreyWall(tile)) + { + return true; + } + } + + return false; + } + + /// A wall, window or door at least half a storey high; not a gable cap or a roof piece. + private bool IsStoreyWall(MultiTile tile) + { + if (tile.Height < _storey / 2) + { + return false; + } + + if (Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _)) + { + return owner.Kind is HousePartKind.Wall or HousePartKind.Door; + } + + TileFlag flags = TileData.ItemTable[tile.Id].Flags; + return (flags & (TileFlag.Wall | TileFlag.Window | TileFlag.Door)) != 0 && (flags & TileFlag.Roof) == 0; + } + + private bool IsCap(ushort id) + { + return Context.HouseStyles.TryGetRole(id, out HouseStyle owner, out _) && + owner.Kind == HousePartKind.Misc && owner.Group.StartsWith(_capStyles, StringComparison.Ordinal); + } + + /// A wall tile below the eaves in a gable wall row, or 0 when the row has none. + private ushort GableWall(int row, bool alongX, int wallX0, int wallX1, int wallY0, int wallY1, int z) + { + MultiEditorComponentList list = Context.CompList; + ushort wall = 0; + int from = alongX ? wallX0 : wallY0, to = alongX ? wallX1 : wallY1; + for (int a = from; a <= to && wall == 0; ++a) + { + foreach (MultiTile tile in list.GetTilesAt(alongX ? a : row, alongX ? row : a)) + { + if (tile.Z < z && Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) + { + wall = tile.Id; + break; + } + } + } + + return wall; + } + + /// + /// The cap for a gable over a wall: the misc.txt roof piece with the wall's tiledata name and + /// the id nearest its own. Odd pieces close walls along X, even pieces walls along Y (as + /// placed in the official multis). 0 when no cap matches. + /// + private ushort CapFor(ushort wall, bool alongX) + { + string name = TileData.ItemTable[wall].Name; + ushort best = 0; + foreach (HouseStyle style in Context.HouseStyles.Styles) + { + if (style.Kind != HousePartKind.Misc || !style.Group.StartsWith(_capStyles, StringComparison.Ordinal)) + { + continue; + } + + for (int pair = 1; pair <= 7; pair += 2) + { + ushort first = style.Get($"Piece{pair}"); + ushort second = style.Get($"Piece{pair + 1}"); + ushort cap = alongX ? first : second; + if (first == 0 || second == 0 || TileData.ItemTable[cap].Height > 4 || + !string.Equals(TileData.ItemTable[cap].Name, name, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (best == 0 || Math.Abs(cap - wall) < Math.Abs(best - wall)) + { + best = cap; + } + } + } + + return best; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs index 2c244ae0..9cb96933 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs @@ -54,6 +54,8 @@ private void InitializeComponent() _floorLabel = new System.Windows.Forms.ToolStripLabel(); _optionsSeparator3 = new System.Windows.Forms.ToolStripSeparator(); _drawTileLabel = new System.Windows.Forms.ToolStripLabel(); + _shapeSeparator = new System.Windows.Forms.ToolStripSeparator(); + _shapeLabel = new System.Windows.Forms.ToolStripLabel(); _ridgeSeparator = new System.Windows.Forms.ToolStripSeparator(); _ridgeLabel = new System.Windows.Forms.ToolStripLabel(); _gablesSeparator = new System.Windows.Forms.ToolStripSeparator(); @@ -242,7 +244,7 @@ private void InitializeComponent() // _optionsStrip // _optionsStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; - _optionsStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _toolLabel, _optionsSeparator1, _placeLabel, _brushLabel, _zStepLabel, _zStepCombo, _optionsSeparator2, _floorLabel, _optionsSeparator3, _drawTileLabel, _ridgeSeparator, _ridgeLabel, _gablesSeparator, _gablesLabel, _gableFillSeparator, _gableFillLabel }); + _optionsStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _toolLabel, _optionsSeparator1, _placeLabel, _brushLabel, _zStepLabel, _zStepCombo, _optionsSeparator2, _floorLabel, _optionsSeparator3, _drawTileLabel, _shapeSeparator, _shapeLabel, _ridgeSeparator, _ridgeLabel, _gablesSeparator, _gablesLabel, _gableFillSeparator, _gableFillLabel }); _optionsStrip.Location = new System.Drawing.Point(0, 25); _optionsStrip.Name = "_optionsStrip"; _optionsStrip.Size = new System.Drawing.Size(1280, 25); @@ -312,6 +314,18 @@ private void InitializeComponent() _drawTileLabel.Text = "Tile: none"; _drawTileLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // + // _shapeSeparator + // + _shapeSeparator.Name = "_shapeSeparator"; + _shapeSeparator.Size = new System.Drawing.Size(6, 25); + // + // _shapeLabel + // + _shapeLabel.Name = "_shapeLabel"; + _shapeLabel.Size = new System.Drawing.Size(39, 22); + _shapeLabel.Text = "Shape"; + _shapeLabel.ToolTipText = "Gable: two slopes and a ridge."; + // // _ridgeSeparator // _ridgeSeparator.Name = "_ridgeSeparator"; @@ -322,7 +336,7 @@ private void InitializeComponent() _ridgeLabel.Name = "_ridgeLabel"; _ridgeLabel.Size = new System.Drawing.Size(36, 22); _ridgeLabel.Text = "Ridge"; - _ridgeLabel.ToolTipText = "Which way the ridge runs. Shift turns it for one stroke."; + _ridgeLabel.ToolTipText = "Which way the ridge runs. Shift turns a gable's ridge for one stroke."; // // _gablesSeparator // @@ -525,6 +539,8 @@ private void InitializeComponent() private System.Windows.Forms.ToolStripLabel _floorLabel; private System.Windows.Forms.ToolStripSeparator _optionsSeparator3; private System.Windows.Forms.ToolStripLabel _drawTileLabel; + private System.Windows.Forms.ToolStripSeparator _shapeSeparator; + private System.Windows.Forms.ToolStripLabel _shapeLabel; private System.Windows.Forms.ToolStripSeparator _ridgeSeparator; private System.Windows.Forms.ToolStripLabel _ridgeLabel; private System.Windows.Forms.ToolStripSeparator _gablesSeparator; diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs index 007ed9df..1ace2356 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs @@ -503,7 +503,8 @@ private void DefineCommands() _paste = Command("Edit", "Paste", () => Session.Paste(), Keys.Control | Keys.V, hasDoc, glyph: Glyphs.Paste); _duplicate = Command("Edit", "Duplicate selection", () => Session.Duplicate(), Keys.Control | Keys.D, hasSelection); _repeat = Command("Edit", "Repeat selection...", RepeatSelectionPrompt, Keys.Control | Keys.Shift | Keys.D, hasSelection); - _delete = Command("Edit", "Delete selection", () => Session.DeleteSelection(), Keys.Delete, hasSelection, glyph: Glyphs.Delete); + _delete = Command("Edit", "Delete selection", DeleteSelectionOrWing, Keys.Delete, + () => Session != null && (Session.ShapingRoof ? Session.Roof.HasSelectedWing : Session.Selection.Count > 0), glyph: Glyphs.Delete); _selectAll = Command("Select", "Select all", () => Session.SelectAll(), Keys.Control | Keys.A, hasDoc); _invert = Command("Select", "Invert selection", () => Session.InvertSelection(), Keys.Control | Keys.Shift | Keys.A, hasDoc); @@ -598,6 +599,8 @@ private void DefineCommands() hasDoc, () => Session?.BrushSize == size)); } _escape = Command("Tools", "Cancel tool, then clear selection", Escape, Keys.Escape, hasDoc); + _placeRoof = Command("Tools", "Place the roof being shaped", () => Session.Roof.Commit(), Keys.Enter, + () => Session != null && Session.ShapingRoof); _shortcuts = Command("Help", "Keyboard shortcuts", ShowShortcuts, Keys.F1, glyph: Glyphs.Help); _drawWithSelected = Command("Tools", "Draw with this tile", DrawWithSelected, can: () => (_menuTile ?? Session?.SelectedTile) != null); } @@ -673,8 +676,27 @@ private void CyclePlacement() SyncOptions(); } + private void DeleteSelectionOrWing() + { + if (Session.ShapingRoof) + { + Session.Roof.DeleteWing(); + } + else + { + Session.DeleteSelection(); + } + } + private void Escape() { + // With a roof being shaped: the first Esc stops a drag, the next one drops the roof. + if (Session.ShapingRoof && !Session.ActiveTool.IsDragging) + { + Session.Roof.Discard(); + return; + } + // First Esc stops what the tool is doing, the next one clears the selection. if (Session.Pasting || Session.ActiveTool.IsDragging || Session.Selection.Count == 0) { @@ -1318,6 +1340,8 @@ private void BuildOptionsStrip() } // Roof options, shown only with the Roof tool. + RoofGroup(strip, _shapeSeparator, _shapeLabel, + ("Gable", () => Session.Roof.Shape == RoofShape.Gable, () => Session.Roof.Shape = RoofShape.Gable)); RoofGroup(strip, _ridgeSeparator, _ridgeLabel, ("Auto", () => Session.Roof.Ridge == RoofRidge.Auto, () => Session.Roof.Ridge = RoofRidge.Auto), ("X", () => Session.Roof.Ridge == RoofRidge.AlongX, () => Session.Roof.Ridge = RoofRidge.AlongX), @@ -1329,6 +1353,10 @@ private void BuildOptionsStrip() RoofGroup(strip, _gableFillSeparator, _gableFillLabel, ("Caps", () => Session.Roof.GableFill == RoofGableFill.Caps, () => Session.Roof.GableFill = RoofGableFill.Caps), ("Walls", () => Session.Roof.GableFill == RoofGableFill.Walls, () => Session.Roof.GableFill = RoofGableFill.Walls)); + + // Shown while a roof is being shaped. + _placeRoofButton = RoofAction(strip, "Place roof", "Places the roof on the Roof layer (Enter).", () => Session.Roof.Commit()); + _dropRoofButton = RoofAction(strip, "Drop", "Drops the roof being shaped (Esc).", () => Session.Roof.Discard()); } private void ZStepCombo_SelectedIndexChanged(object sender, EventArgs e) @@ -1336,6 +1364,9 @@ private void ZStepCombo_SelectedIndexChanged(object sender, EventArgs e) Apply(() => Session.ZStep = int.Parse(_zStepCombo.Text)); } + private EditorCommand _placeRoof; + private ToolStripButton _placeRoofButton; + private ToolStripButton _dropRoofButton; private readonly List _roofItems = new List(); private readonly List<(ToolStripButton Button, Func IsOn)> _roofButtons = new List<(ToolStripButton, Func)>(); @@ -1376,6 +1407,29 @@ private void RoofGroup(ToolStrip strip, ToolStripSeparator separator, ToolStripL } } + private ToolStripButton RoofAction(ToolStrip strip, string text, string tip, Action run) + { + var button = new ToolStripButton(text) + { + DisplayStyle = ToolStripItemDisplayStyle.Text, + ToolTipText = tip, + AutoToolTip = false, + Margin = new Padding(6, 1, 0, 2), + Visible = false + }; + button.Click += (_, _) => + { + if (Session != null && Session.ShapingRoof) + { + run(); + _commands.RefreshStates(); + _canvas.Focus(); + } + }; + strip.Items.Add(button); + return button; + } + private void SyncRoofOptions() { bool show = Session != null && !Session.Pasting && Session.Tool == ToolKind.Roof; @@ -1384,6 +1438,8 @@ private void SyncRoofOptions() item.Visible = show; } + _placeRoofButton.Visible = _dropRoofButton.Visible = show && Session.ShapingRoof; + foreach ((ToolStripButton button, Func isOn) in _roofButtons) { button.Checked = show && isOn(); @@ -1537,6 +1593,7 @@ private EditorDocument CreateDocument(string title, int? clientId) if (_active != null) { session.FloorPattern = _active.Session.FloorPattern; + session.Roof.Shape = _active.Session.Roof.Shape; session.Roof.Ridge = _active.Session.Roof.Ridge; session.Roof.Gables = _active.Session.Roof.Gables; session.Roof.GableFill = _active.Session.Roof.GableFill; @@ -2180,6 +2237,8 @@ private void UpdateStatus() _statusHint.Text = session.PreviewMode ? "Preview: editing is off. Right click picks the ground. F5 returns to the editor." : session.PreviewingRepeat ? "The copies are shown as they would be placed." : session.Pasting ? "Click to place the tiles, as often as you like. Esc or right click stops." + : session.ShapingRoof ? "Shaping the roof: drag a wing to move it, an edge of the selected wing to resize it, anywhere else to add a wing. " + + "Shift+click turns a ridge, Delete removes a wing. Enter places the roof on the Roof layer, Esc drops it." : ToolHint(session.Tool); (int x, int y, int z) = session.CursorCell; @@ -2213,7 +2272,7 @@ private static string ToolHint(ToolKind kind) ToolKind.Floor => "Drag an area to lay the chosen floor style.", ToolKind.Door => "Click a wall cell to hang the chosen door.", ToolKind.Stair => "Drag in the direction the stairs climb.", - ToolKind.Roof => "Click a walled room to roof it, or drag over the wall cells to size the roof by hand. Options: Ridge, Gables, Fill.", + ToolKind.Roof => "Click a walled room to start its roof, or drag out a roof of any size. It stays open for shaping until Enter places it.", ToolKind.Foundation => "Drag an area to lay a foundation under it.", ToolKind.FloorPattern => "Drag an area to lay the bordered floor: corners, sides and fill repeat to fit.", _ => string.Empty diff --git a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs index 9d1c172b..25f2943c 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs @@ -64,9 +64,15 @@ public void ShowCommands(IEnumerable commands) ("Keep the line straight (Line)", "Shift + drag"), ("One straight wall instead of a room (Walls)", "Shift + drag"), ("Erase walls (Walls)", "Ctrl + drag"), - ("Fit the roof to the walls (Roof)", "Click without dragging"), - ("Turn the ridge the other way (Roof)", "Shift"), - ("Gables at one end or both (Roof)", "Ctrl")); + ("Start a roof fitted to the walls, part by part on an L or T shaped house (Roof)", "Click without dragging"), + ("Start a roof fitted to the walls (Roof)", "Drag over the walls, the floor or the roof area"), + ("Select a wing of the roof being shaped, or move it (Roof)", "Click / drag the wing"), + ("Resize the selected wing (Roof)", "Drag one of its edges"), + ("Add a wing: valleys, and a T where the ridges meet (Roof)", "Drag beside the roof"), + ("Turn a wing's ridge (Roof)", "Shift + click the wing"), + ("Remove the selected wing (Roof)", "Delete"), + ("Place the roof on the Roof layer (Roof)", "Enter, or pick another tool"), + ("Drop the roof being shaped (Roof)", "Esc")); Section("Tile browser", ("Go from the search box to the results", "Down"), From 0e9ee64e05ac25f43250cdafac5046068a36f657 Mon Sep 17 00:00:00 2001 From: AsY!um- <377468+AsYlum-@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:40:19 +0100 Subject: [PATCH 02/16] Add a House tool that designs a house as a draft --- .../Classes/HouseDraft.cs | 360 +++++++++ .../MultiEditorComponentList.Layers.cs | 43 +- .../Editing/EditorSession.cs | 131 +++- .../Rendering/SceneRenderer.cs | 49 +- .../Tools/DraftEditTools.cs | 312 ++++++++ .../Tools/EditorTool.cs | 24 + .../Tools/HousePartTools.cs | 22 +- .../Tools/HouseTool.cs | 515 ++++++++++++ .../Tools/RoofTool.cs | 489 +++--------- .../Tools/WingDraftTool.cs | 733 ++++++++++++++++++ .../UI/HousePanel.Designer.cs | 459 +++++++++++ UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs | 233 ++++++ .../UI/MultiEditorControl.cs | 158 +++- .../UI/ShortcutsForm.cs | 10 +- .../UoFiddler.Plugin.MultiEditor.csproj | 6 + 15 files changed, 3108 insertions(+), 436 deletions(-) create mode 100644 UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs create mode 100644 UoFiddler.Plugin.MultiEditor/Tools/DraftEditTools.cs create mode 100644 UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs create mode 100644 UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs create mode 100644 UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs create mode 100644 UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs new file mode 100644 index 00000000..59bec0c6 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs @@ -0,0 +1,360 @@ +/*************************************************************************** + * + * $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.Tools; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// 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. + /// + internal sealed class HouseDraft + { + 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"; + + // The foundation ring stands this far below the ground floor, as in the client's house foundations. + private const int _foundationBelow = 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; } + + public bool Foundation { get; set; } + + // 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; + for (int k = 0; k < MaxStoreys; ++k) + { + copy.AddedSouth[k].UnionWith(AddedSouth[k]); + copy.AddedEast[k].UnionWith(AddedEast[k]); + copy.ErasedSouth[k].UnionWith(ErasedSouth[k]); + copy.ErasedEast[k].UnionWith(ErasedEast[k]); + } + + foreach (var door in Doors) + { + copy.Doors[door.Key] = door.Value; + } + + copy.Windows.UnionWith(Windows); + copy.FloorAreas.AddRange(FloorAreas); + copy.Stairs.AddRange(Stairs); + return copy; + } + + /// A draft with the same materials and nothing changed by hand: the next house. + public HouseDraft Fresh() + { + var copy = new HouseDraft { RoofStyle = RoofStyle, Foundation = Foundation }; + Array.Copy(WallStyles, copy.WallStyles, MaxStoreys); + Array.Copy(FloorStyles, copy.FloorStyles, MaxStoreys); + return copy; + } + + /// 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: 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) + { + HashSet<(int X, int Y)> region = Region(wings, storey); + south = new HashSet<(int X, int Y)>(); + east = new HashSet<(int X, int Y)>(); + Outline(region, south, east); + foreach ((int x, int y) in AddedSouth[storey]) + { + if (region.Contains((x, y)) || region.Contains((x, y + 1))) + { + south.Add((x, y)); + } + } + + foreach ((int x, int y) in AddedEast[storey]) + { + if (region.Contains((x, y)) || region.Contains((x + 1, y))) + { + east.Add((x, y)); + } + } + + south.ExceptWith(ErasedSouth[storey]); + east.ExceptWith(ErasedEast[storey]); + } + + /// 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); + Edges(wings, storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east); + + if (storey == 0 && Foundation && styles.TryGetRole(FoundationTool.FoundationPost, out HouseStyle foundation, out _)) + { + 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; + if (id != 0) + { + built.Tiles.Add((id, x, y, z - _foundationBelow, 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; + } + + string column = WallPlanner.PieceFor(south, east, x, y); + if (column == null || wallStyle == null) + { + continue; + } + + if (Windows.Contains((storey, x, y)) && column != "Corner" && column != "Post") + { + string window = column.StartsWith("South", StringComparison.Ordinal) ? "WindowS" : "WindowE"; + if (wallStyle.Get(window) != 0) + { + column = window; + } + } + + ushort id = wallStyle.Get(column); + 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)); + } + } + } + + return built; + } + + private readonly Dictionary _pieces = new Dictionary(); + + private ushort[] Pieces(HouseStyle style) + { + if (!_pieces.TryGetValue(style, out ushort[] pieces)) + { + _pieces[style] = pieces = style.Slots.Values.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/Classes/MultiEditorComponentList.Layers.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs index 5014f086..d56c3890 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs @@ -112,15 +112,15 @@ public TileLayer LayerAdd(string name) } /// - /// Removes some tiles and adds others in one undo step, the new ones on the layer each - /// names or, when it names none, on the layer called . That - /// layer is made on top of the others when the multi has none of that name; the active - /// layer stays as it is. The multi grows to hold tiles added past its +X/+Y end. + /// 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 ReplaceTilesOnLayer(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z, TileLayer Layer)> add, - string action, string layerName) + 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, TileLayer Layer)>(add); + var added = new List<(ushort Id, int X, int Y, int Z, string Layer)>(add); BeginEdit(action); foreach (MultiTile tile in new List(remove)) { @@ -142,19 +142,26 @@ public void ReplaceTilesOnLayer(IEnumerable remove, IEnumerable<(usho RebuildGrid(width, height, new List(RealTiles)); } - TileLayer named = _layers.FirstOrDefault(l => l.Name == layerName); - if (named == null && added.Any(a => a.Layer == null)) + var byName = new Dictionary(); + foreach (var (id, x, y, z, name) in added) { - RecordLayers(); - TileLayer active = ActiveLayer; - named = new TileLayer(layerName); - _layers.Add(named); - ActiveLayer = active; - } + 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; + } - foreach (var (id, x, y, z, layer) in added) - { - RecordNew(id, x, y, z, false, 0, layer: layer != null && _layers.Contains(layer) ? layer : named); + byName[wanted] = layer; + } + + RecordNew(id, x, y, z, false, 0, layer: layer); } EndEdit(); diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs index 932ee8ad..5ff747ce 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs @@ -41,7 +41,10 @@ internal enum ToolKind Foundation, /// Lays a bordered floor pattern; chosen from the House page, not the palette. - FloorPattern + FloorPattern, + + /// Designs a whole house as a draft and places it. + House } /// @@ -53,6 +56,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; @@ -93,13 +97,24 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles) _tools[ToolKind.Door] = new DoorTool(this); _tools[ToolKind.Stair] = new StairTool(this); var roof = new RoofTool(this); - roof.Changed += () => + var house = new HouseTool(this, roof); + foreach (WingDraftTool draft in new WingDraftTool[] { roof, house }) { - ToolChanged?.Invoke(); - Invalidated?.Invoke(); - }; - roof.Committed += () => LayersChanged?.Invoke(); + draft.Changed += () => + { + DraftChanged?.Invoke(); + ToolChanged?.Invoke(); + Invalidated?.Invoke(); + }; + draft.Committed += () => LayersChanged?.Invoke(); + } + _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); @@ -163,32 +178,87 @@ public void MarkSaved() 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(); + } + } + AfterEdit(); + 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 (!CompList.RedoStep()) { return false; } AfterEdit(); + LayersChanged?.Invoke(); return true; } private void SetDocument(MultiEditorComponentList list) { CancelTool(); - Roof.Discard(); + Roof.Reset(); + House.Reset(); CompList = list; _selection.Clear(); HoverTile = null; @@ -352,6 +422,7 @@ public ToolKind Tool 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(); @@ -369,7 +440,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) @@ -391,8 +467,43 @@ public static bool IsTileTool(ToolKind kind) /// The roof tool, for its shape options (ridge, gables, gable fill) and the roof being shaped. public RoofTool Roof => (RoofTool)_tools[ToolKind.Roof]; - /// True while the roof tool is in use and holds a roof that is not placed yet. - public bool ShapingRoof => _temporaryTool == null && _toolKind == ToolKind.Roof && Roof.HasPending; + /// 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); + } + } /// Call after a tool option changed, so the preview under the cursor follows. public void ToolOptionsChanged() diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs index 0b725215..aa0b3313 100644 --- a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs +++ b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs @@ -126,6 +126,7 @@ public void Draw(EditorSession session, Camera2D camera, Size viewport) if (!session.PickingWithAlt) { session.ActiveTool.PaintOverlay(this); + session.PaintIdleDraft(this); } LastSpriteCount += _sprites.Count; _sprites.Flush(_atlas, camera, viewport); @@ -566,7 +567,8 @@ void IToolOverlay.Ghost(ushort id, int x, int y, int z) return; } - if (!_session.CompList.InBounds(x, y) || !_atlas.TryGet(id, out AtlasSprite sprite)) + // A ghost may lie past the multi's end: tools that grow the multi show what they add. + if (x < 0 || y < 0 || !_atlas.TryGet(id, out AtlasSprite sprite)) { return; } @@ -604,6 +606,51 @@ void IToolOverlay.Polyline(System.Collections.Generic.IReadOnlyList point } } + private static Color ToneColor(OverlayTone tone) => tone switch + { + OverlayTone.Selected => Color.FromArgb(255, 255, 214, 64), + OverlayTone.Hover => Color.FromArgb(255, 255, 255, 255), + OverlayTone.Remove => Color.FromArgb(255, 255, 80, 80), + _ => Color.FromArgb(200, 120, 190, 255) + }; + + void IToolOverlay.Outline(System.Collections.Generic.IReadOnlyList points, OverlayTone tone) + { + // Lines are a pixel wide: a strong outline is the same line drawn side by side. + Color color = ToneColor(tone); + int width = tone == OverlayTone.Selected ? 3 : tone == OverlayTone.Plain ? 1 : 2; + for (int pass = 0; pass < width; ++pass) + { + int shift = pass == 0 ? 0 : pass == 1 ? 1 : -1; + for (int i = 0; i < points.Count; i++) + { + Point a = points[i], b = points[(i + 1) % points.Count]; + _lines.Add(a.X, a.Y + shift, b.X, b.Y + shift, color); + if (shift != 0) + { + _lines.Add(a.X + shift, a.Y, b.X + shift, b.Y, color); + } + } + } + } + + void IToolOverlay.CellMark(int x, int y, int z, OverlayTone tone) + { + Color color = Color.FromArgb(tone == OverlayTone.Plain ? 40 : tone == OverlayTone.Selected ? 70 : 110, ToneColor(tone)); + if (_session.PlanMode) + { + Point o = PlanView.CellOrigin(x, y); + Fill(o.X, o.Y, PlanView.Cell, PlanView.Cell, color); + return; + } + + if (_atlas.TryGet(ArtAtlas.FloorKey, out AtlasSprite diamond)) + { + PointF corner = EditorSession.CellCorner(x, y, z); + _sprites.Add(diamond, corner.X - 22, corner.Y, SpriteTint.Solid(color)); + } + } + void IToolOverlay.Marquee(Rectangle rect) { if (_atlas.TryGet(ArtAtlas.WhiteKey, out AtlasSprite white)) diff --git a/UoFiddler.Plugin.MultiEditor/Tools/DraftEditTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/DraftEditTools.cs new file mode 100644 index 00000000..6d52efb9 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/DraftEditTools.cs @@ -0,0 +1,312 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// Base for the tools that stand in for the wall, door, floor and stair tools while a house + /// draft is open: they change the draft, on the storey of the chosen floor, instead of the + /// multi. The draft is drawn under what the tool itself shows. + /// + internal abstract class DraftEditTool : EditorTool + { + protected DraftEditTool(IEditorContext context, HouseTool house) : base(context) + { + House = house; + } + + protected HouseTool House { get; } + + public override bool TracksCursorCell => true; + + /// The storey worked on: the chosen floor's. + protected int Storey => House.StoreyFor(Context.WorkZ); + + protected int StoreyZ => House.BaseZ + (Storey * HouseDraft.StoreyHeight); + + /// The cell under the mouse on the storey's floor. + protected void MouseCell(out int x, out int y) + { + Context.PlaneCell(Context.MouseLoc, StoreyZ, out x, out y); + } + + public override void PaintOverlay(IToolOverlay overlay) + { + House.PaintDraft(overlay, active: false); + PaintEdit(overlay); + } + + protected abstract void PaintEdit(IToolOverlay overlay); + } + + /// + /// Walls of a house draft. A drag adds walls along the cells (a rectangle of them, or one + /// straight wall with Shift or along a single row or column); Ctrl takes walls away, also + /// outer ones, which leaves an opening. A click on a straight wall turns it into a window + /// and back. + /// + internal sealed class DraftWallTool : DraftEditTool + { + private bool _dragging; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + + public DraftWallTool(IEditorContext context, HouseTool house) : base(context, house) + { + } + + public override bool IsDragging => _dragging; + + public override void OnMouseDown(MouseEventArgs e) + { + MouseCell(out _startX, out _startY); + (_endX, _endY) = (_startX, _startY); + _dragging = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (_dragging) + { + MouseCell(out _endX, out _endY); + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + MouseCell(out _endX, out _endY); + if (_startX == _endX && _startY == _endY && !CtrlHeld && House.ToggleWindow(Storey, _startX, _startY)) + { + return; + } + + var (south, east) = WallPlanner.DragEdges(_startX, _startY, _endX, _endY, ShiftHeld); + House.EditEdges(Storey, south, east, CtrlHeld); + } + + public override void Cancel() + { + _dragging = false; + } + + protected override void PaintEdit(IToolOverlay overlay) + { + if (!_dragging) + { + MouseCell(out int x, out int y); + overlay.CellMark(x, y, StoreyZ, OverlayTone.Hover); + return; + } + + OverlayTone tone = CtrlHeld ? OverlayTone.Remove : OverlayTone.Hover; + var (south, east) = WallPlanner.DragEdges(_startX, _startY, _endX, _endY, ShiftHeld); + var cells = new HashSet<(int X, int Y)>(south); + cells.UnionWith(east); + foreach ((int x, int y) in cells) + { + overlay.CellMark(x, y, StoreyZ, tone); + } + } + } + + /// + /// Doors of a house draft: a click on a straight wall hangs the chosen door there, a click on + /// that door turns it to its next hinge variant, Ctrl+click takes the door out. + /// + internal sealed class DraftDoorTool : DraftEditTool + { + public DraftDoorTool(IEditorContext context, HouseTool house) : base(context, house) + { + } + + public override void OnMouseUp(MouseEventArgs e) + { + MouseCell(out int x, out int y); + House.CycleDoor(Storey, x, y, Context.HouseStyle, CtrlHeld); + } + + protected override void PaintEdit(IToolOverlay overlay) + { + MouseCell(out int x, out int y); + House.EdgesOf(Storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east); + bool fits = south.Contains((x, y)) != east.Contains((x, y)); + overlay.CellMark(x, y, StoreyZ, CtrlHeld || !fits ? OverlayTone.Remove : OverlayTone.Hover); + } + } + + /// + /// Floors of a house draft: a drag lays that area of the storey in the chosen floor style; + /// the rest keeps the storey's own. + /// + internal sealed class DraftFloorTool : DraftEditTool + { + private bool _dragging; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + + public DraftFloorTool(IEditorContext context, HouseTool house) : base(context, house) + { + } + + public override bool IsDragging => _dragging; + + public override void OnMouseDown(MouseEventArgs e) + { + MouseCell(out _startX, out _startY); + (_endX, _endY) = (_startX, _startY); + _dragging = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (_dragging) + { + MouseCell(out _endX, out _endY); + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + MouseCell(out _endX, out _endY); + House.AddFloorArea(Storey, _startX, _startY, _endX, _endY, Context.HouseStyle); + } + + public override void Cancel() + { + _dragging = false; + } + + protected override void PaintEdit(IToolOverlay overlay) + { + int x0, y0, x1, y1; + if (_dragging) + { + (x0, y0, x1, y1) = (Math.Min(_startX, _endX), Math.Min(_startY, _endY), Math.Max(_startX, _endX), Math.Max(_startY, _endY)); + } + else + { + MouseCell(out x0, out y0); + (x1, y1) = (x0, y0); + } + + for (int x = x0; x <= x1; ++x) + { + for (int y = y0; y <= y1; ++y) + { + overlay.CellMark(x, y, StoreyZ, OverlayTone.Hover); + } + } + } + } + + /// + /// Stairs of a house draft: press on the cell of the bottom step and drag the way the stairs + /// should climb (a click climbs north). They open the floor of the storey above. + /// Ctrl+click on a bottom step takes the stairs out. + /// + internal sealed class DraftStairTool : DraftEditTool + { + private bool _dragging; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + + public DraftStairTool(IEditorContext context, HouseTool house) : base(context, house) + { + } + + public override bool IsDragging => _dragging; + + public override void OnMouseDown(MouseEventArgs e) + { + MouseCell(out _startX, out _startY); + (_endX, _endY) = (_startX, _startY); + _dragging = true; + } + + public override void OnMouseMove(MouseEventArgs e) + { + if (_dragging) + { + MouseCell(out _endX, out _endY); + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + MouseCell(out _endX, out _endY); + if (CtrlHeld) + { + House.RemoveStairs(Storey, _startX, _startY); + } + else + { + House.AddStairs(Storey, _startX, _startY, StairTool.Column(_endX - _startX, _endY - _startY), Context.HouseStyle); + } + } + + public override void Cancel() + { + _dragging = false; + } + + protected override void PaintEdit(IToolOverlay overlay) + { + int x, y; + if (_dragging) + { + (x, y) = (_startX, _startY); + } + else + { + MouseCell(out x, out y); + } + + overlay.CellMark(x, y, StoreyZ, CtrlHeld ? OverlayTone.Remove : OverlayTone.Hover); + if (!CtrlHeld && Context.HouseStyle is { Kind: HousePartKind.Stair } style) + { + string column = _dragging ? StairTool.Column(_endX - _startX, _endY - _startY) : "MultiNorth"; + foreach ((ushort id, int tx, int ty, int tz) in StairTool.Tiles(style, column, x, y, StoreyZ)) + { + overlay.Ghost(id, tx, ty, tz); + } + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs index 356e1f13..df2e9913 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs @@ -104,6 +104,24 @@ internal enum TileHighlight Remove } + /// + /// How strongly a tool marks something it draws. + /// + internal enum OverlayTone + { + /// There, but not what is being worked on. + Plain, + + /// Under the mouse: what a press would take hold of. + Hover, + + /// The thing being worked on. + Selected, + + /// Something a release would take away. + Remove + } + /// /// What a tool draws over the multi. The canvas decides how it looks. /// @@ -120,6 +138,12 @@ internal interface IToolOverlay /// A line through canvas points, joined back to the start when closed. void Polyline(IReadOnlyList points, bool closed); + + /// A closed outline through canvas points, drawn as strongly as its tone asks. + void Outline(IReadOnlyList points, OverlayTone tone); + + /// A cell tinted on the plane at height z. + void CellMark(int x, int y, int z, OverlayTone tone); } /// diff --git a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs index 7edca4cd..52a1cf35 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs @@ -216,18 +216,26 @@ public StairTool(IEditorContext context) : base(context) protected override (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan( int startX, int startY, int endX, int endY, int z, bool final) { - var add = new List<(ushort, int, int, int)>(); - int dx = endX - startX; - int dy = endY - startY; - string column = Math.Abs(dx) > Math.Abs(dy) + return (new List(), Tiles(Style, Column(endX - startX, endY - startY), startX, startY, z)); + } + + /// The stair column for the way a drag points: the stairs climb that way, north for a click. + public static string Column(int dx, int dy) + { + return Math.Abs(dx) > Math.Abs(dy) ? (dx > 0 ? "MultiEast" : "MultiWest") : (dy > 0 ? "MultiSouth" : "MultiNorth"); + } - ushort multiId = Style.Get(column); + /// The tiles of a style's stairs with their lowest step in a cell, climbing one level from . + public static List<(ushort Id, int X, int Y, int Z)> Tiles(HouseStyle style, string column, int startX, int startY, int z) + { + var add = new List<(ushort, int, int, int)>(); + ushort multiId = style.Get(column); MultiComponentList stairs = multiId != 0 ? Multis.GetComponents(multiId) : MultiComponentList.Empty; if (stairs == MultiComponentList.Empty || stairs.Width == 0) { - return (new List(), add); + return add; } // The lowest step goes under the cursor. @@ -260,7 +268,7 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z } } - return (new List(), add); + return add; } } } diff --git a/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs new file mode 100644 index 00000000..bab2fdd7 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs @@ -0,0 +1,515 @@ +/*************************************************************************** + * + * $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.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// A whole house, designed before it is placed. Drag a rectangle of wall cells to add a wing; + /// wings are selected, moved, resized and removed as describes. + /// Each wing has a number of storeys and a roof; each storey of the house has a wall style + /// and a floor style. The house is shown as it will be built and nothing is written to the + /// multi until it is placed, on the layers Foundation, Walls, Floors, Stairs and Roof. + /// While the draft is open the wall, door, floor and stair tools change the draft + /// (), and every change is a step of the draft's undo history. + /// + internal sealed class HouseTool : WingDraftTool + { + private readonly RoofTool _roof; + private HouseDraft _draft = new HouseDraft(); + private int _storeys = 1; + private RoofShape _shape = RoofShape.Gable; + private bool _noRoof; + private RoofRidge _ridge = RoofRidge.Auto; + + // The last build, kept while nothing it depends on changes: a house is thousands of tiles. + private string _builtFor; + private (List Remove, List<(ushort Id, int X, int Y, int Z, string Layer)> Add) _built; + private int _version; + + public HouseTool(IEditorContext context, RoofTool roof) : base(context) + { + _roof = roof; + } + + /// The materials and hand-made changes of the house. Change it through this tool, so the history follows. + public HouseDraft Draft => _draft; + + /// Z of the ground floor: the first wing's, which the others share. + public int BaseZ => Wings.Count > 0 ? Wings[0].EaveZ : _draft.BaseZ; + + /// Storeys of the tallest wing; 1 before there is one. + public int TopStorey => Math.Max(1, HouseDraft.Top(Wings)); + + /// Storeys of new wings. + public int Storeys => SelectedWing?.Storeys ?? _storeys; + + public RoofShape Shape => SelectedWing?.Shape ?? _shape; + + public bool NoRoof => SelectedWing?.NoRoof ?? _noRoof; + + public RoofRidge Ridge => SelectedWing is { } wing + ? wing.RidgeAuto ? RoofRidge.Auto : wing.RidgeAlongY ? RoofRidge.AlongY : RoofRidge.AlongX + : _ridge; + + protected override bool Ready + { + get + { + EnsureMaterials(); + return _draft.WallStyles[0] != null; + } + } + + protected override string ActionName => "House"; + + protected override string DefaultLayer => HouseDraft.WallsLayer; + + protected override bool PreviewsFirstClick => false; + + protected override bool GhostsFollowView => true; + + /// + /// Storeys without a material take the one below; the ground floor and the roof take the + /// first style the client has, until one is chosen. + /// + private void EnsureMaterials() + { + if (Context.HouseStyles == null) + { + return; + } + + HouseStyle First(HousePartKind kind) => Context.HouseStyles.Styles.FirstOrDefault(s => s.Kind == kind && s.IconId != 0); + _draft.WallStyles[0] ??= Context.HouseStyles.Styles.FirstOrDefault(s => + s.Kind == HousePartKind.Wall && s.Get("South2") is var id and not 0 && Ultima.TileData.ItemTable[id].Height >= 15) ?? First(HousePartKind.Wall); + _draft.FloorStyles[0] ??= First(HousePartKind.Floor); + _draft.RoofStyle ??= First(HousePartKind.Roof); + for (int k = 1; k < HouseDraft.MaxStoreys; ++k) + { + _draft.WallStyles[k] ??= _draft.WallStyles[k - 1]; + _draft.FloorStyles[k] ??= _draft.FloorStyles[k - 1]; + } + } + + // ---------------------------------------------------------------- wings + + protected override void StartCell(out int x, out int y, out int z) + { + Context.CellAt(Context.MouseLoc, out x, out y, out z); + if (Context.WorkZ is { } baseZ) + { + z = baseZ; + } + + Context.PlaneCell(Context.MouseLoc, z, out x, out y); + } + + protected override int NextWingZ => BaseZ; + + /// A wing is the dragged rectangle of wall cells; it needs room for a room. + protected override List WingsFor(int startX, int startY, int endX, int endY, int z, out bool fitted) + { + fitted = false; + var wings = new List(); + int x0 = Math.Max(0, Math.Min(startX, endX)), x1 = Math.Max(startX, endX); + int y0 = Math.Max(0, Math.Min(startY, endY)), y1 = Math.Max(startY, endY); + if (x1 - x0 < 2 || y1 - y0 < 2) + { + return wings; + } + + var wing = new RoofWing + { + X0 = x0, Y0 = y0, X1 = x1, Y1 = y1, EaveZ = z, Storeys = _storeys, + Shape = _shape, NoRoof = _noRoof, RidgeAuto = _ridge == RoofRidge.Auto + }; + wing.RidgeAlongY = wing.RidgeAuto ? RoofPlanner.RidgeAlongY(RoofBox(wing)) : _ridge == RoofRidge.AlongY; + wings.Add(wing); + return wings; + } + + private static (int X0, int Y0, int X1, int Y1) RoofBox(RoofWing wing) => (wing.X0 + 1, wing.Y0 + 1, wing.X1 + 1, wing.Y1 + 1); + + protected override void WingResized(RoofWing wing) + { + if (wing.RidgeAuto) + { + wing.RidgeAlongY = RoofPlanner.RidgeAlongY(RoofBox(wing)); + } + } + + protected override void Turn(RoofWing wing) + { + wing.RidgeAlongY = !wing.RidgeAlongY; + wing.RidgeAuto = false; + } + + protected override object CaptureExtra() => _draft.Clone(); + + protected override void RestoreExtra(object extra) + { + _draft = extra is HouseDraft saved ? saved.Clone() : _draft.Fresh(); + ++_version; + } + + // ---------------------------------------------------------------- changes to the draft + + /// Runs a change to the draft as one step of its history. + private void Edit(Action change) + { + Remember(); + change(); + ++_version; + RaiseChanged(); + } + + /// Sets the storeys of the selected wing, and of the wings drawn next. + public void SetStoreys(int storeys) + { + storeys = Math.Clamp(storeys, 1, HouseDraft.MaxStoreys); + _storeys = storeys; + if (SelectedWing is { } wing && wing.Storeys != storeys) + { + Edit(() => wing.Storeys = storeys); + } + else + { + RaiseChanged(); + } + } + + /// Sets the roof of the selected wing, and of the wings drawn next: a shape, or none. + public void SetRoof(RoofShape shape, bool none) + { + (_shape, _noRoof) = (shape, none); + if (SelectedWing is { } wing && (wing.Shape != shape || wing.NoRoof != none)) + { + Edit(() => (wing.Shape, wing.NoRoof) = (shape, none)); + } + else + { + RaiseChanged(); + } + } + + public void SetRidge(RoofRidge ridge) + { + _ridge = ridge; + if (SelectedWing is { } wing) + { + Edit(() => + { + wing.RidgeAuto = ridge == RoofRidge.Auto; + wing.RidgeAlongY = wing.RidgeAuto ? RoofPlanner.RidgeAlongY(RoofBox(wing)) : ridge == RoofRidge.AlongY; + }); + } + else + { + RaiseChanged(); + } + } + + /// Moves the whole house up or down. + public void SetBaseZ(int z) + { + z = Math.Clamp(z, -100, 100); + if (Wings.Count == 0 || z == BaseZ) + { + return; + } + + Edit(() => + { + foreach (RoofWing wing in Wings) + { + wing.EaveZ = z; + } + }); + } + + public void SetFoundation(bool on) + { + if (_draft.Foundation != on) + { + Edit(() => _draft.Foundation = on); + } + } + + /// + /// Sets a wall, floor or roof style. A wall or floor style goes to one storey, or to + /// every storey when is null. + /// + public void SetMaterial(HouseStyle style, int? storey) + { + if (style == null) + { + return; + } + + Edit(() => + { + if (style.Kind == HousePartKind.Roof) + { + _draft.RoofStyle = style; + return; + } + + HouseStyle[] target = style.Kind == HousePartKind.Floor ? _draft.FloorStyles : style.Kind == HousePartKind.Wall ? _draft.WallStyles : null; + for (int k = 0; target != null && k < HouseDraft.MaxStoreys; ++k) + { + if (storey == null || storey == k) + { + target[k] = style; + } + } + }); + } + + /// The storey the work plane is on (the chosen floor); the ground floor with all floors shown. + public int StoreyFor(int? workZ) + { + if (workZ is not { } z) + { + return 0; + } + + return Math.Clamp((int)Math.Round((z - BaseZ) / (double)HouseDraft.StoreyHeight), 0, TopStorey - 1); + } + + /// The wall edges of a storey as the draft has them now. + public void EdgesOf(int storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east) + { + _draft.Edges(Wings, storey, out south, out east); + } + + /// Adds wall edges to a storey (partitions), or takes edges away (openings). + public void EditEdges(int storey, IReadOnlyCollection<(int X, int Y)> south, IReadOnlyCollection<(int X, int Y)> east, bool erase) + { + if (south.Count + east.Count == 0) + { + return; + } + + Edit(() => + { + if (erase) + { + _draft.AddedSouth[storey].ExceptWith(south); + _draft.AddedEast[storey].ExceptWith(east); + _draft.ErasedSouth[storey].UnionWith(south); + _draft.ErasedEast[storey].UnionWith(east); + } + else + { + _draft.ErasedSouth[storey].ExceptWith(south); + _draft.ErasedEast[storey].ExceptWith(east); + _draft.AddedSouth[storey].UnionWith(south); + _draft.AddedEast[storey].UnionWith(east); + } + }); + } + + /// Turns the wall in a cell into a window, or back. False when the cell has no straight wall. + public bool ToggleWindow(int storey, int x, int y) + { + EdgesOf(storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east); + if (south.Contains((x, y)) == east.Contains((x, y))) + { + return false; + } + + Edit(() => + { + if (!_draft.Windows.Remove((storey, x, y))) + { + _draft.Windows.Add((storey, x, y)); + _draft.Doors.Remove((storey, x, y)); + } + }); + return true; + } + + // Hinge variants per wall direction, in the order a click cycles through them. + private static readonly string[] _doorsAlongX = { "Piece3", "Piece1", "Piece4", "Piece2" }; + private static readonly string[] _doorsAlongY = { "Piece5", "Piece7", "Piece6", "Piece8" }; + + /// + /// Hangs a door in the wall of a cell, or turns the door there to its next hinge variant; + /// with takes it out. False when the cell has no straight wall. + /// + public bool CycleDoor(int storey, int x, int y, HouseStyle style, bool remove) + { + EdgesOf(storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east); + bool alongX = south.Contains((x, y)); + if (alongX == east.Contains((x, y))) + { + return false; + } + + bool has = _draft.Doors.TryGetValue((storey, x, y), out (HouseStyle Style, string Piece) door); + if (remove) + { + if (has) + { + Edit(() => _draft.Doors.Remove((storey, x, y))); + } + + return has; + } + + if (style == null || style.Kind != HousePartKind.Door) + { + return false; + } + + string[] variants = alongX ? _doorsAlongX : _doorsAlongY; + int next = has && door.Style == style ? (Array.IndexOf(variants, door.Piece) + 1) % variants.Length : 0; + for (int i = 0; i < variants.Length; ++i) + { + string piece = variants[(next + i) % variants.Length]; + if (style.Get(piece) != 0) + { + Edit(() => + { + _draft.Doors[(storey, x, y)] = (style, piece); + _draft.Windows.Remove((storey, x, y)); + }); + return true; + } + } + + return false; + } + + /// Lays an area of a storey's floor in another style. + public void AddFloorArea(int storey, int x0, int y0, int x1, int y1, HouseStyle style) + { + if (style is { Kind: HousePartKind.Floor }) + { + Edit(() => _draft.FloorAreas.Add((storey, Math.Min(x0, x1), Math.Min(y0, y1), Math.Max(x0, x1), Math.Max(y0, y1), style))); + } + } + + /// Puts stairs on a storey, their bottom step in a cell; they open the floor above. + public void AddStairs(int storey, int x, int y, string column, HouseStyle style) + { + if (style is { Kind: HousePartKind.Stair } && style.Get(column) != 0) + { + Edit(() => _draft.Stairs.Add((storey, x, y, column, style))); + } + } + + /// Takes out the stairs whose bottom step is in a cell. + public bool RemoveStairs(int storey, int x, int y) + { + int index = _draft.Stairs.FindLastIndex(s => s.Storey == storey && s.X == x && s.Y == y); + if (index < 0) + { + return false; + } + + Edit(() => _draft.Stairs.RemoveAt(index)); + return true; + } + + // ---------------------------------------------------------------- building + + protected override (List Remove, List<(ushort Id, int X, int Y, int Z, string Layer)> Add) Plan(IReadOnlyList wings) + { + if (wings.Count == 0) + { + return (new List(), new List<(ushort, int, int, int, string)>()); + } + + EnsureMaterials(); + string key = string.Join(";", wings.Select(w => + $"{w.X0},{w.Y0},{w.X1},{w.Y1},{w.EaveZ},{w.Storeys},{w.Shape},{w.NoRoof},{w.RidgeAlongY}")) + + $"|{_version}|{_roof.Gables}|{_roof.GableFill}|{Context.CompList.UndoList.Count}|{Context.CompList.RedoList.Count}"; + if (key == _builtFor) + { + return _built; + } + + int baseZ = wings[0].EaveZ; + _draft.BaseZ = baseZ; + HouseDraft.Built built = _draft.Build(wings, Context.HouseStyles); + var remove = new List(); + var add = built.Tiles; + + // A new floor replaces the flat tiles lying where it goes, as the floor tool does. + MultiEditorComponentList list = Context.CompList; + foreach ((ushort _, int x, int y, int z, string layer) in built.Tiles) + { + if (layer != HouseDraft.FloorsLayer) + { + continue; + } + + foreach (MultiTile tile in list.GetTilesAt(x, y)) + { + if (tile.Z == z && tile.Height == 0 && list.IsShown(tile)) + { + remove.Add(tile); + } + } + } + + // The roof: each wing's walls one cell further along X and Y, eaves on its top storey. + var roofWings = new List(); + foreach (RoofWing wing in wings) + { + if (wing.NoRoof) + { + continue; + } + + RoofWing roof = wing.Clone(); + (roof.X0, roof.Y0, roof.X1, roof.Y1) = RoofBox(wing); + roof.EaveZ = baseZ + (Math.Clamp(wing.Storeys, 1, HouseDraft.MaxStoreys) * HouseDraft.StoreyHeight); + roofWings.Add(roof); + } + + if (roofWings.Count > 0 && _draft.RoofStyle != null) + { + // A lower wing's roof stops at the walls of a taller one. + bool Hidden(int x, int y, int z) + { + foreach (RoofWing wing in wings) + { + if (x >= wing.X0 && x <= wing.X1 && y >= wing.Y0 && y <= wing.Y1 && + z < baseZ + (wing.Storeys * HouseDraft.StoreyHeight)) + { + return true; + } + } + + return false; + } + + var (roofRemove, roofAdd) = _roof.PlanRoof(roofWings, _draft.RoofStyle, built.Walls, Hidden); + remove.AddRange(roofRemove); + foreach (var (id, x, y, z, layer) in roofAdd) + { + add.Add((id, x, y, z, layer ?? RoofTool.LayerName)); + } + } + + _builtFor = key; + _built = (remove, add); + return _built; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs index e4dea8bd..d76afbdc 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs @@ -48,57 +48,20 @@ internal enum RoofGableFill Walls } - /// One rectangle of a roof being shaped: where it lies, how high its eaves are and how it slopes. - 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; } - - 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() => (RoofWing)MemberwiseClone(); - - public void CopyFrom(RoofWing other) - { - (X0, Y0, X1, Y1, EaveZ) = (other.X0, other.Y0, other.X1, other.Y1, other.EaveZ); - (Shape, RidgeAlongY, RidgeAuto) = (other.Shape, other.RidgeAlongY, other.RidgeAuto); - } - } - /// - /// Roofs, shaped before they are placed. The first click on (or inside) a walled room fits a - /// roof to its walls, part by part on an L or T shaped house; a drag over the walls, the floor - /// inside them or the area the roof will cover fits it too, and any other drag is a roof of - /// that size on the work plane. The roof then stays pending, shown as it will be built: - /// - /// click a wing to select it, drag it to move it, drag an edge of the selected wing to - /// resize it; - /// drag anywhere else to add a wing, which joins the others with valleys and T pieces; - /// Shift+click turns a wing's ridge, the Shape and Ridge options - /// change the selected wing, Delete removes it; - /// Enter, or switching to another tool, places the roof on the layer named - /// in one undo step; Esc drops it. - /// + /// Roofs, shaped before they are placed (see for the shaping). + /// The first click on (or inside) a walled room fits a roof to its walls, part by part on an + /// L or T shaped house; a drag over the walls, the floor inside them or the area the roof + /// will cover fits it too, and any other drag is a roof of that size on the work plane. + /// Further wings join the others with valleys and T pieces. The Shape and Ridge options + /// change the selected wing; Shift+click turns a wing's ridge. Enter, or + /// switching to another tool, places the roof on the layer named . /// A fitted roof sits on the wall tops whatever floor is chosen, overhangs the south and east /// walls by a cell and grows the multi when that cell lies outside it. Slopes rise 3 per cell /// like the official house roofs. A roof already there is replaced when it lies wholly under /// the new one and joined otherwise. /// - internal sealed class RoofTool : EditorTool + internal sealed class RoofTool : WingDraftTool { /// The layer a placed roof goes on; made on first use. public const string LayerName = "Roof"; @@ -107,55 +70,33 @@ internal sealed class RoofTool : EditorTool private const int _storey = 20; private const string _capStyles = "Miscellaneous Roof Pieces"; - private enum DragKind - { - None, - New, - Move, - Resize - } - - private readonly List _wings = new List(); - private int _selected = -1; private HouseStyle _lastStyle; + private HouseStyle _planStyle; private RoofShape _shape = RoofShape.Gable; private RoofRidge _ridge = RoofRidge.Auto; + private RoofGables _gables = RoofGables.Front; + private RoofGableFill _gableFill = RoofGableFill.Caps; - private DragKind _drag; - private int _startX; - private int _startY; - private int _endX; - private int _endY; - private int _z; - private RoofWing _before; - private int _grabX; - private int _grabY; - private bool _west; - private bool _east; - private bool _north; - private bool _south; + // Walls a house draft is about to build, which the multi does not hold yet. + private Dictionary<(int X, int Y), List<(ushort Id, int Z)>> _draftWalls; public RoofTool(IEditorContext context) : base(context) { } - /// Raised when the pending roof starts, changes or ends. - public event Action Changed; - - /// Raised after a roof was placed. - public event Action Committed; - /// The shape of new wings; also sets the selected wing's. public RoofShape Shape { get => _shape; set { - _shape = value; - if (SelectedWing is { } wing) + if (SelectedWing is { } wing && wing.Shape != value) { + Remember(); wing.Shape = value; } + + _shape = value; } } @@ -165,31 +106,34 @@ public RoofRidge Ridge get => _ridge; set { - _ridge = value; if (SelectedWing is { } wing) { + Remember(); wing.RidgeAuto = value == RoofRidge.Auto; wing.RidgeAlongY = value == RoofRidge.Auto ? RoofPlanner.RidgeAlongY(wing.Box) : value == RoofRidge.AlongY; } + + _ridge = value; } } - public RoofGables Gables { get; set; } = RoofGables.Front; - - public RoofGableFill GableFill { get; set; } = RoofGableFill.Caps; - - /// True while a roof is being shaped and not yet placed. - public bool HasPending => _wings.Count > 0; - - public bool HasSelectedWing => SelectedWing != null; + public RoofGables Gables + { + get => _gables; + set => _gables = value; + } - public IReadOnlyList Wings => _wings; + public RoofGableFill GableFill + { + get => _gableFill; + set => _gableFill = value; + } - public override bool IsDragging => _drag != DragKind.None; + protected override bool Ready => Style != null; - public override bool TracksCursorCell => true; + protected override string ActionName => "Roof"; - private RoofWing SelectedWing => _selected >= 0 && _selected < _wings.Count ? _wings[_selected] : null; + protected override string DefaultLayer => LayerName; /// The roof style chosen in the House tab; a pending roof keeps the last one. private HouseStyle Style @@ -206,186 +150,10 @@ private HouseStyle Style } } - // ---------------------------------------------------------------- shaping - - public override void OnMouseDown(MouseEventArgs e) - { - if (Style == null) - { - return; - } - - if (HasPending) - { - int hit = HitWing(out int cx, out int cy); - if (hit >= 0) - { - RoofWing wing = _wings[hit]; - bool wasSelected = hit == _selected; - _selected = hit; - if (ShiftHeld) - { - Turn(wing); - Changed?.Invoke(); - return; - } - - _before = wing.Clone(); - (_grabX, _grabY) = (cx, cy); - - // The selected wing is resized by its outermost cells; a side too short to - // have a middle moves the wing instead. - bool wide = wing.X1 - wing.X0 >= 2, deep = wing.Y1 - wing.Y0 >= 2; - _west = wasSelected && wide && cx == wing.X0; - _east = wasSelected && wide && cx == wing.X1; - _north = wasSelected && deep && cy == wing.Y0; - _south = wasSelected && deep && cy == wing.Y1; - _drag = _west || _east || _north || _south ? DragKind.Resize : DragKind.Move; - Changed?.Invoke(); - return; - } - - // A new wing, level with the wing worked on last. - _z = (SelectedWing ?? _wings[^1]).EaveZ; - Context.PlaneCell(Context.MouseLoc, _z, out _startX, out _startY); - } - else - { - BaseCell(out _startX, out _startY, out _z); - } - - (_endX, _endY) = (_startX, _startY); - _drag = DragKind.New; - } - - public override void OnMouseMove(MouseEventArgs e) - { - switch (_drag) - { - case DragKind.New: - Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); - break; - case DragKind.Move: - case DragKind.Resize: - DragWing(); - break; - } - } - - public override void OnMouseUp(MouseEventArgs e) - { - DragKind drag = _drag; - if (drag is DragKind.Move or DragKind.Resize) - { - DragWing(); - } - - _drag = DragKind.None; - if (drag == DragKind.New) - { - Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); - List wings = WingsFor(_startX, _startY, _endX, _endY, _z, out bool fitted); - if (HasPending && !fitted && _startX == _endX && _startY == _endY) - { - // A click beside the roof lets go of the selected wing. - _selected = -1; - } - else - { - _wings.AddRange(wings); - _selected = _wings.Count - wings.Count; - } - - Changed?.Invoke(); - } - else if (drag != DragKind.None) - { - _before = null; - Changed?.Invoke(); - } - } - - /// Stops a drag: a wing being moved or resized goes back to where it was. - public override void Cancel() - { - if (_drag is DragKind.Move or DragKind.Resize && _before != null && SelectedWing is { } wing) - { - wing.CopyFrom(_before); - } - - _before = null; - _drag = DragKind.None; - } - - /// Drops the pending roof. - public void Discard() - { - bool had = HasPending; - _wings.Clear(); - _selected = -1; - _before = null; - _drag = DragKind.None; - if (had) - { - Changed?.Invoke(); - } - } - - /// Removes the selected wing from the pending roof. - public void DeleteWing() - { - if (SelectedWing == null || IsDragging) - { - return; - } - - _wings.RemoveAt(_selected); - _selected = _wings.Count - 1; - Changed?.Invoke(); - } - - /// - /// Places the pending roof: its tiles go on the layer, pieces of - /// an older roof that had to change stay on their own layer, all in one undo step. - /// - public void Commit() - { - Cancel(); - if (!HasPending) - { - return; - } - - if (Style != null) - { - var (remove, add) = Plan(_wings); - if (remove.Count > 0 || add.Count > 0) - { - Context.CompList.ReplaceTilesOnLayer(remove, add, "Roof", LayerName); - Context.AfterEdit(add.Count > 0 ? add.Max(a => a.Z) : null); - Committed?.Invoke(); - } - } - - Discard(); - } - - /// Lays a roof in one go, as a press at one cell and a release at another would shape it. For scripts and tests. - public void Place(int startX, int startY, int endX, int endY, int z) - { - if (Style == null) - { - return; - } - - _wings.AddRange(WingsFor(startX, startY, endX, endY, z, out _)); - Commit(); - } - /// /// The eaves go on the work plane, or on top of what the mouse points at (a wall top). /// - private void BaseCell(out int x, out int y, out int z) + protected override void StartCell(out int x, out int y, out int z) { Context.CellAt(Context.MouseLoc, out x, out y, out z); if (Context.WorkZ is { } baseZ) @@ -395,52 +163,8 @@ private void BaseCell(out int x, out int y, out int z) } } - /// The pending wing under the mouse, the selected one first, and the cell pointed at on its eaves. - private int HitWing(out int cx, out int cy) + protected override void WingResized(RoofWing wing) { - (cx, cy) = (0, 0); - for (int pass = 0; pass < 2; ++pass) - { - for (int i = _wings.Count - 1; i >= 0; --i) - { - if ((pass == 0) != (i == _selected)) - { - continue; - } - - RoofWing wing = _wings[i]; - Context.PlaneCell(Context.MouseLoc, wing.EaveZ, out cx, out cy); - if (cx >= wing.X0 && cx <= wing.X1 && cy >= wing.Y0 && cy <= wing.Y1) - { - return i; - } - } - } - - return -1; - } - - private void DragWing() - { - if (_before == null || SelectedWing is not { } wing) - { - return; - } - - Context.PlaneCell(Context.MouseLoc, _before.EaveZ, out int cx, out int cy); - int dx = cx - _grabX, dy = cy - _grabY; - if (_drag == DragKind.Move) - { - dx = Math.Max(dx, -_before.X0); - dy = Math.Max(dy, -_before.Y0); - (wing.X0, wing.X1, wing.Y0, wing.Y1) = (_before.X0 + dx, _before.X1 + dx, _before.Y0 + dy, _before.Y1 + dy); - return; - } - - wing.X0 = _west ? Math.Clamp(_before.X0 + dx, 0, _before.X1) : _before.X0; - wing.X1 = _east ? Math.Max(_before.X1 + dx, _before.X0) : _before.X1; - wing.Y0 = _north ? Math.Clamp(_before.Y0 + dy, 0, _before.Y1) : _before.Y0; - wing.Y1 = _south ? Math.Max(_before.Y1 + dy, _before.Y0) : _before.Y1; if (wing.RidgeAuto) { wing.RidgeAlongY = RoofPlanner.RidgeAlongY(wing.Box); @@ -448,7 +172,7 @@ private void DragWing() } /// Turns a wing's ridge the other way. - private static void Turn(RoofWing wing) + protected override void Turn(RoofWing wing) { wing.RidgeAlongY = !wing.RidgeAlongY; wing.RidgeAuto = false; @@ -462,7 +186,7 @@ private static void Turn(RoofWing wing) /// within a cell of such a roof on every side means that roof. Any other stroke is the /// roof itself, at . Shift turns a gable's ridge. /// - private List WingsFor(int startX, int startY, int endX, int endY, int z, out bool fitted) + protected override List WingsFor(int startX, int startY, int endX, int endY, int z, out bool fitted) { int x0 = Math.Min(startX, endX), x1 = Math.Max(startX, endX); int y0 = Math.Min(startY, endY), y1 = Math.Max(startY, endY); @@ -503,85 +227,45 @@ private List WingsFor(int startX, int startY, int endX, int endY, int return wings; } - // ---------------------------------------------------------------- overlay - - public override void PaintOverlay(IToolOverlay overlay) + protected override (List Remove, List<(ushort Id, int X, int Y, int Z, string Layer)> Add) Plan(IReadOnlyList wings) { - if (Style == null) - { - return; - } - - // What is shown is what Enter would build: the pending wings, with the one being - // dragged out; before there is a roof, the one a click here would start. - var wings = new List(_wings); - if (_drag == DragKind.New) - { - wings.AddRange(WingsFor(_startX, _startY, _endX, _endY, _z, out _)); - } - else if (!HasPending) - { - BaseCell(out int x, out int y, out int z); - wings.AddRange(WingsFor(x, y, x, y, z, out _)); - } - - var (remove, add) = Plan(wings); - foreach (MultiTile tile in remove) - { - overlay.Highlight(tile, TileHighlight.Remove); - } - - foreach (var (id, x, y, z, _) in add) - { - overlay.Ghost(id, x, y, z); - } - - for (int i = 0; i < _wings.Count; ++i) - { - RoofWing wing = _wings[i]; - Point top = Corner(wing.X0, wing.Y0, wing.EaveZ), right = Corner(wing.X1 + 1, wing.Y0, wing.EaveZ); - Point bottom = Corner(wing.X1 + 1, wing.Y1 + 1, wing.EaveZ), left = Corner(wing.X0, wing.Y1 + 1, wing.EaveZ); - overlay.Polyline(new[] { top, right, bottom, left }, closed: true); - if (i != _selected) - { - continue; - } - - // Grips in the middle of the selected wing's sides. - foreach ((Point a, Point b) in new[] { (top, right), (right, bottom), (bottom, left), (left, top) }) - { - var mid = new Point((a.X + b.X) / 2, (a.Y + b.Y) / 2); - overlay.Polyline(new[] - { - new Point(mid.X - 5, mid.Y - 5), new Point(mid.X + 5, mid.Y - 5), - new Point(mid.X + 5, mid.Y + 5), new Point(mid.X - 5, mid.Y + 5) - }, closed: true); - } - } - } - - /// Canvas position of the top corner of a cell's diamond at height z. - private static Point Corner(int x, int y, int z) - { - return new Point(((x - y) * 22) + MultiEditorComponentList.GapXMod, ((x + y) * 22) - (z * 4) - 22); + return PlanRoof(wings, Style, null, null); } - // ---------------------------------------------------------------- planning /// - /// The tiles a roof of these wings takes away and adds. An added tile with no layer goes - /// on the roof layer; a re-pieced tile of an older roof names the layer it stays on. + /// The tiles a roof of these wings takes away and adds, in a roof style. An added tile + /// with no layer goes on the roof layer; a re-pieced tile of an older roof names the layer + /// it stays on. are walls about to be built with the roof (a + /// house draft), which count as standing for the gable ends. + /// tells roof cells that must not be built (inside a taller part of the house). /// - private (List Remove, List<(ushort Id, int X, int Y, int Z, TileLayer Layer)> Add) Plan(IReadOnlyList wings) + public (List Remove, List<(ushort Id, int X, int Y, int Z, string Layer)> Add) PlanRoof(IReadOnlyList wings, + HouseStyle style, IReadOnlyList<(ushort Id, int X, int Y, int Z)> draftWalls, Func hidden) { var remove = new List(); - var add = new List<(ushort Id, int X, int Y, int Z, TileLayer Layer)>(); - HouseStyle style = Style; + var add = new List<(ushort Id, int X, int Y, int Z, string Layer)>(); if (wings.Count == 0 || style == null) { return (remove, add); } + _planStyle = style; + _draftWalls = null; + if (draftWalls != null) + { + _draftWalls = new Dictionary<(int X, int Y), List<(ushort Id, int Z)>>(); + foreach ((ushort id, int x, int y, int z) in draftWalls) + { + if (!_draftWalls.TryGetValue((x, y), out List<(ushort Id, int Z)> there)) + { + _draftWalls[(x, y)] = there = new List<(ushort Id, int Z)>(); + } + + there.Add((id, z)); + } + } + MultiEditorComponentList list = Context.CompList; var heights = new Dictionary<(int X, int Y), int>(); var fixedPieces = new Dictionary<(int X, int Y), string>(); @@ -590,6 +274,18 @@ private static Point Corner(int x, int y, int z) RoofPlanner.AddWing(heights, fixedPieces, wing.Box, wing.RidgeAlongY, wing.Shape, wing.EaveZ); } + if (hidden != null) + { + foreach (((int X, int Y) cell, int height) in new List>(heights).Select(h => (h.Key, h.Value))) + { + if (hidden(cell.X, cell.Y, height)) + { + heights.Remove(cell); + fixedPieces.Remove(cell); + } + } + } + var footprint = new HashSet<(int X, int Y)>(heights.Keys); JoinExisting(footprint, heights, fixedPieces, remove, add); @@ -648,7 +344,7 @@ private static Point Corner(int x, int y, int z) /// no gable and gets none: only cells with no roof beyond them are filled. /// private void AddGables(RoofWing wing, Dictionary<(int X, int Y), int> heights, HashSet<(ushort, int, int, int)> placed, - List<(ushort Id, int X, int Y, int Z, TileLayer Layer)> add) + List<(ushort Id, int X, int Y, int Z, string Layer)> add) { MultiEditorComponentList list = Context.CompList; bool ridgeAlongY = wing.RidgeAlongY; @@ -783,7 +479,7 @@ private void AddGables(RoofWing wing, Dictionary<(int X, int Y), int> heights, H /// taken out of . /// private void JoinExisting(HashSet<(int X, int Y)> footprint, Dictionary<(int X, int Y), int> heights, - Dictionary<(int X, int Y), string> fixedPieces, List remove, List<(ushort Id, int X, int Y, int Z, TileLayer Layer)> add) + Dictionary<(int X, int Y), string> fixedPieces, List remove, List<(ushort Id, int X, int Y, int Z, string Layer)> add) { MultiEditorComponentList list = Context.CompList; var existing = new Dictionary<(int X, int Y), List>(); @@ -872,7 +568,7 @@ private void JoinExisting(HashSet<(int X, int Y)> footprint, Dictionary<(int X, continue; } - HouseStyle style = Style; + HouseStyle style = _planStyle; string now = null; if (Context.HouseStyles.TryGetRoleByArt(tile.Id, out HouseStyle owner, out string slot, out _) && owner.Kind == HousePartKind.Roof) { @@ -888,7 +584,7 @@ private void JoinExisting(HashSet<(int X, int Y)> footprint, Dictionary<(int X, if (id != 0 && id != tile.Id) { remove.Add(tile); - add.Add((id, x, y, tile.Z, tile.Layer)); + add.Add((id, x, y, tile.Z, tile.Layer.Name)); } } } @@ -1026,6 +722,17 @@ private bool HasStoreyWall(int x, int y, int z) } } + if (_draftWalls != null && _draftWalls.TryGetValue((x, y), out List<(ushort Id, int Z)> planned)) + { + foreach ((ushort id, int wallZ) in planned) + { + if (wallZ < z && wallZ > z - _storey - 5 && TileData.ItemTable[id].Height >= _storey / 2) + { + return true; + } + } + } + return false; } @@ -1060,7 +767,8 @@ private ushort GableWall(int row, bool alongX, int wallX0, int wallX1, int wallY int from = alongX ? wallX0 : wallY0, to = alongX ? wallX1 : wallY1; for (int a = from; a <= to && wall == 0; ++a) { - foreach (MultiTile tile in list.GetTilesAt(alongX ? a : row, alongX ? row : a)) + (int X, int Y) cell = (alongX ? a : row, alongX ? row : a); + foreach (MultiTile tile in list.GetTilesAt(cell.X, cell.Y)) { if (tile.Z < z && Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) { @@ -1068,6 +776,19 @@ private ushort GableWall(int row, bool alongX, int wallX0, int wallX1, int wallY break; } } + + // The top storey of a house being drafted: the walls the gable stands on. + if (wall == 0 && _draftWalls != null && _draftWalls.TryGetValue(cell, out List<(ushort Id, int Z)> planned)) + { + foreach ((ushort id, int wallZ) in planned.OrderByDescending(p => p.Z)) + { + if (wallZ < z && Context.HouseStyles.TryGetRole(id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Wall) + { + wall = id; + break; + } + } + } } return wall; diff --git a/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs new file mode 100644 index 00000000..5d4ed7d5 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs @@ -0,0 +1,733 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Tools +{ + /// + /// 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; } + + 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() => (RoofWing)MemberwiseClone(); + + 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); + } + } + + /// + /// Base for the tools that shape something out of wings before it is placed (roofs, houses). + /// The first stroke starts a draft, shown as it will be built. Then: click a wing to select + /// it, drag it to move it, drag an outermost row or column of the selected wing to resize + /// it, drag anywhere else to add a wing, Shift+click to turn one, Delete to remove one. + /// Nothing is written to the multi until ; drops + /// the draft. Every change to the draft is a step of its own undo history, which + /// and walk; dropping the draft is such a + /// step too, and undoing a placement in the multi brings the draft back with its history. + /// + internal abstract class WingDraftTool : EditorTool + { + private const int _historySize = 200; + + private enum DragKind + { + None, + New, + Move, + Resize + } + + private sealed class State + { + public List Wings; + public int Selected; + public object Extra; + } + + private List _wings = new List(); + private int _selected = -1; + private List _undo = new List(); + private List _redo = new List(); + + private DragKind _drag; + private int _startX; + private int _startY; + private int _endX; + private int _endY; + private int _z; + private RoofWing _before; + private State _dragStart; + private int _grabX; + private int _grabY; + private bool _west; + private bool _east; + private bool _north; + private bool _south; + + // The last placement, so undoing it in the multi can bring the draft back. + private State _placed; + private List _placedHistory; + + protected WingDraftTool(IEditorContext context) : base(context) + { + } + + /// Raised when the draft starts, changes or ends, and when the selected wing changes. + public event Action Changed; + + /// Raised after the draft was placed. + public event Action Committed; + + /// True while there is a draft that is not placed yet. + public bool HasPending => _wings.Count > 0; + + public IReadOnlyList Wings => _wings; + + public RoofWing SelectedWing => _selected >= 0 && _selected < _wings.Count ? _wings[_selected] : null; + + public bool HasSelectedWing => SelectedWing != null; + + public int SelectedIndex + { + get => SelectedWing != null ? _selected : -1; + set + { + int index = value >= 0 && value < _wings.Count ? value : -1; + if (index != _selected) + { + _selected = index; + RaiseChanged(); + } + } + } + + public bool CanUndoDraft => _undo.Count > 0; + + public bool CanRedoDraft => _redo.Count > 0; + + /// The multi's undo step that placed the last draft, or null. + public object PlacedBy { get; private set; } + + /// The multi's undo step whose undoing brought the current draft back, or null. + public object ReopenedFrom { get; private set; } + + public override bool IsDragging => _drag != DragKind.None; + + public override bool TracksCursorCell => true; + + /// True when the tool has what it needs to build (its styles). + protected abstract bool Ready { get; } + + /// The edit's name in the multi's undo list. + protected abstract string ActionName { get; } + + /// The layer tiles go on when they name none. + protected abstract string DefaultLayer { get; } + + /// The cell and Z a first stroke starts at. + protected abstract void StartCell(out int x, out int y, out int z); + + /// The wings a stroke makes; none when the stroke means nothing. tells a stroke that was fitted to something there. + protected abstract List WingsFor(int startX, int startY, int endX, int endY, int z, out bool fitted); + + /// The tiles a draft of these wings takes away and adds; an added tile names its layer or none. + protected abstract (List Remove, List<(ushort Id, int X, int Y, int Z, string Layer)> Add) Plan(IReadOnlyList wings); + + /// The height a wing's outline and grips are drawn and taken hold of at. + protected virtual int GripZ(RoofWing wing) => wing.EaveZ; + + /// The Z a further wing starts at. + protected virtual int NextWingZ => GripZ(SelectedWing ?? _wings[^1]); + + /// True when the tool shows what a click would start before there is a draft. + protected virtual bool PreviewsFirstClick => true; + + /// True when the draft is drawn only up to the highest Z the view shows (the chosen floor, the height slider). + protected virtual bool GhostsFollowView => false; + + /// What the draft holds beside its wings, for the undo history. + protected virtual object CaptureExtra() => null; + + protected virtual void RestoreExtra(object extra) + { + } + + /// Called when a wing's box changed. + protected virtual void WingResized(RoofWing wing) + { + } + + /// Shift+click on a wing. + protected virtual void Turn(RoofWing wing) + { + } + + /// Drawn after the ghost tiles and before the wing outlines. + protected virtual void PaintDetails(IToolOverlay overlay, bool active) + { + } + + // ---------------------------------------------------------------- history + + private State Capture() + { + return new State { Wings = _wings.Select(w => w.Clone()).ToList(), Selected = _selected, Extra = CaptureExtra() }; + } + + private void Restore(State state) + { + _wings = state.Wings.Select(w => w.Clone()).ToList(); + _selected = state.Selected; + RestoreExtra(state.Extra); + } + + /// Call before changing the draft: the state as it is becomes an undo step. + public void Remember() + { + Push(Capture()); + } + + private void Push(State state) + { + _undo.Add(state); + if (_undo.Count > _historySize) + { + _undo.RemoveAt(0); + } + + _redo.Clear(); + ReopenedFrom = null; + } + + protected void RaiseChanged() => Changed?.Invoke(); + + public bool UndoDraft() + { + if (_undo.Count == 0) + { + return false; + } + + CancelDrag(); + _redo.Add(Capture()); + Restore(_undo[^1]); + _undo.RemoveAt(_undo.Count - 1); + RaiseChanged(); + return true; + } + + public bool RedoDraft() + { + if (_redo.Count == 0) + { + return false; + } + + CancelDrag(); + _undo.Add(Capture()); + Restore(_redo[^1]); + _redo.RemoveAt(_redo.Count - 1); + RaiseChanged(); + return true; + } + + // ---------------------------------------------------------------- shaping + + public override void OnMouseDown(MouseEventArgs e) + { + if (!Ready) + { + return; + } + + if (HasPending) + { + int hit = HitWing(out int cx, out int cy); + if (hit >= 0) + { + RoofWing wing = _wings[hit]; + bool wasSelected = hit == _selected; + if (ShiftHeld) + { + Remember(); + _selected = hit; + Turn(wing); + RaiseChanged(); + return; + } + + _selected = hit; + _before = wing.Clone(); + _dragStart = Capture(); + (_grabX, _grabY) = (cx, cy); + Edges(wing, cx, cy, wasSelected, out _west, out _east, out _north, out _south); + _drag = _west || _east || _north || _south ? DragKind.Resize : DragKind.Move; + RaiseChanged(); + return; + } + + _z = NextWingZ; + Context.PlaneCell(Context.MouseLoc, _z, out _startX, out _startY); + } + else + { + StartCell(out _startX, out _startY, out _z); + } + + (_endX, _endY) = (_startX, _startY); + _drag = DragKind.New; + } + + /// + /// The sides a press on a cell of the selected wing takes hold of: its outermost rows and + /// columns. A side too short to have a middle moves the wing instead. + /// + private static void Edges(RoofWing wing, int cx, int cy, bool selected, out bool west, out bool east, out bool north, out bool south) + { + bool wide = wing.X1 - wing.X0 >= 2, deep = wing.Y1 - wing.Y0 >= 2; + west = selected && wide && cx == wing.X0; + east = selected && wide && cx == wing.X1; + north = selected && deep && cy == wing.Y0; + south = selected && deep && cy == wing.Y1; + } + + public override void OnMouseMove(MouseEventArgs e) + { + switch (_drag) + { + case DragKind.New: + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + break; + case DragKind.Move: + case DragKind.Resize: + DragWing(); + break; + } + } + + public override void OnMouseUp(MouseEventArgs e) + { + DragKind drag = _drag; + if (drag is DragKind.Move or DragKind.Resize) + { + DragWing(); + } + + _drag = DragKind.None; + if (drag == DragKind.New) + { + Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY); + List wings = WingsFor(_startX, _startY, _endX, _endY, _z, out bool fitted); + if (wings.Count == 0 || (HasPending && !fitted && _startX == _endX && _startY == _endY)) + { + // A click beside the draft lets go of the selected wing. + _selected = -1; + } + else + { + Remember(); + _wings.AddRange(wings); + _selected = _wings.Count - wings.Count; + } + + RaiseChanged(); + } + else if (drag != DragKind.None) + { + if (SelectedWing is { } wing && _before != null && wing.Box != _before.Box && _dragStart != null) + { + Push(_dragStart); + } + + _before = null; + _dragStart = null; + RaiseChanged(); + } + } + + /// Stops a drag: a wing being moved or resized goes back to where it was. + public override void Cancel() + { + CancelDrag(); + } + + private void CancelDrag() + { + if (_drag is DragKind.Move or DragKind.Resize && _before != null && SelectedWing is { } wing) + { + wing.CopyFrom(_before); + } + + _before = null; + _dragStart = null; + _drag = DragKind.None; + } + + /// Drops the draft. A step of the draft's history: undo brings it back. + public void Discard() + { + CancelDrag(); + if (!HasPending) + { + return; + } + + Remember(); + _wings.Clear(); + _selected = -1; + RestoreExtra(null); + RaiseChanged(); + } + + /// Forgets the draft and its history (another document). + public void Reset() + { + CancelDrag(); + bool had = HasPending; + _wings.Clear(); + _selected = -1; + _undo.Clear(); + _redo.Clear(); + _placed = null; + _placedHistory = null; + PlacedBy = null; + ReopenedFrom = null; + RestoreExtra(null); + if (had) + { + RaiseChanged(); + } + } + + /// Removes the selected wing from the draft. + public void DeleteWing() + { + if (SelectedWing == null || IsDragging) + { + return; + } + + Remember(); + _wings.RemoveAt(_selected); + _selected = _wings.Count - 1; + RaiseChanged(); + } + + /// + /// Places the draft in one undo step of the multi. Undoing that step brings the draft + /// back (). + /// + public void Commit() + { + CancelDrag(); + if (!HasPending) + { + return; + } + + if (Ready) + { + var (remove, add) = Plan(_wings); + if (remove.Count > 0 || add.Count > 0) + { + int steps = Context.CompList.UndoList.Count; + object top = steps > 0 ? Context.CompList.UndoList[0] : null; + Context.CompList.ReplaceTilesOnLayers(remove, add, ActionName, DefaultLayer); + Context.AfterEdit(add.Count > 0 ? add.Max(a => a.Z) : null); + object placedBy = Context.CompList.UndoList.Count > 0 ? Context.CompList.UndoList[0] : null; + if (placedBy != null && !ReferenceEquals(placedBy, top)) + { + _placed = Capture(); + _placedHistory = new List(_undo); + PlacedBy = placedBy; + } + + Committed?.Invoke(); + } + } + + _wings.Clear(); + _selected = -1; + _undo.Clear(); + _redo.Clear(); + ReopenedFrom = null; + RestoreExtra(null); + RaiseChanged(); + } + + /// Brings back the draft that placed, after that step was undone. + public void Reopen() + { + if (_placed == null) + { + return; + } + + Restore(_placed); + _undo = new List(_placedHistory); + _redo.Clear(); + ReopenedFrom = PlacedBy; + PlacedBy = null; + RaiseChanged(); + } + + /// Lets go of a reopened draft because its placement is being redone in the multi. + public void CloseReopened() + { + if (ReopenedFrom == null) + { + return; + } + + _placed = Capture(); + _placedHistory = new List(_undo); + PlacedBy = ReopenedFrom; + ReopenedFrom = null; + _wings.Clear(); + _selected = -1; + _undo.Clear(); + _redo.Clear(); + RestoreExtra(null); + RaiseChanged(); + } + + /// Lays a draft in one go, as a press at one cell and a release at another would start it. For scripts and tests. + public void Place(int startX, int startY, int endX, int endY, int z) + { + if (!Ready) + { + return; + } + + _wings.AddRange(WingsFor(startX, startY, endX, endY, z, out _)); + Commit(); + } + + /// The wing under the mouse, the selected one first, and the cell pointed at on its plane. + private int HitWing(out int cx, out int cy) + { + (cx, cy) = (0, 0); + for (int pass = 0; pass < 2; ++pass) + { + for (int i = _wings.Count - 1; i >= 0; --i) + { + if ((pass == 0) != (i == _selected)) + { + continue; + } + + RoofWing wing = _wings[i]; + Context.PlaneCell(Context.MouseLoc, GripZ(wing), out cx, out cy); + if (cx >= wing.X0 && cx <= wing.X1 && cy >= wing.Y0 && cy <= wing.Y1) + { + return i; + } + } + } + + return -1; + } + + private void DragWing() + { + if (_before == null || SelectedWing is not { } wing) + { + return; + } + + Context.PlaneCell(Context.MouseLoc, GripZ(_before), out int cx, out int cy); + int dx = cx - _grabX, dy = cy - _grabY; + if (_drag == DragKind.Move) + { + dx = Math.Max(dx, -_before.X0); + dy = Math.Max(dy, -_before.Y0); + (wing.X0, wing.X1, wing.Y0, wing.Y1) = (_before.X0 + dx, _before.X1 + dx, _before.Y0 + dy, _before.Y1 + dy); + return; + } + + wing.X0 = _west ? Math.Clamp(_before.X0 + dx, 0, _before.X1) : _before.X0; + wing.X1 = _east ? Math.Max(_before.X1 + dx, _before.X0) : _before.X1; + wing.Y0 = _north ? Math.Clamp(_before.Y0 + dy, 0, _before.Y1) : _before.Y0; + wing.Y1 = _south ? Math.Max(_before.Y1 + dy, _before.Y0) : _before.Y1; + WingResized(wing); + } + + // ---------------------------------------------------------------- overlay + + public override void PaintOverlay(IToolOverlay overlay) + { + PaintDraft(overlay, active: true); + } + + /// + /// Draws the draft as it would be built. With (this tool is in + /// use) it also shows what the mouse would take hold of: the wing under it, the side of + /// the selected wing a press would resize, and the wing being dragged out. + /// + public void PaintDraft(IToolOverlay overlay, bool active) + { + if (!Ready) + { + return; + } + + var wings = new List(_wings); + List stroke = null; + if (active && _drag == DragKind.New) + { + stroke = WingsFor(_startX, _startY, _endX, _endY, _z, out _); + } + else if (active && !HasPending && PreviewsFirstClick) + { + StartCell(out int x, out int y, out int z); + stroke = WingsFor(x, y, x, y, z, out _); + } + + if (stroke != null) + { + wings.AddRange(stroke); + } + + var (remove, add) = Plan(wings); + foreach (MultiTile tile in remove) + { + overlay.Highlight(tile, TileHighlight.Remove); + } + + // A house is looked into like the multi: storeys above the chosen floor are left out. + int highest = GhostsFollowView ? Context.MaxHeight : int.MaxValue; + foreach (var (id, x, y, z, _) in add) + { + if (z <= highest) + { + overlay.Ghost(id, x, y, z); + } + } + + PaintDetails(overlay, active); + + int hover = -1, hx = 0, hy = 0; + if (active && _drag == DragKind.None && HasPending) + { + hover = HitWing(out hx, out hy); + } + + for (int i = 0; i < _wings.Count; ++i) + { + RoofWing wing = _wings[i]; + int z = GripZ(wing); + bool selected = i == _selected; + if (selected && active) + { + // The rows and columns a press would resize by; the one under the mouse stands out. + Edges(wing, hx, hy, hover == i, out bool west, out bool east, out bool north, out bool south); + if (_drag == DragKind.Resize) + { + (west, east, north, south) = (_west, _east, _north, _south); + } + + for (int x = wing.X0; x <= wing.X1; ++x) + { + for (int y = wing.Y0; y <= wing.Y1; ++y) + { + bool band = x == wing.X0 || x == wing.X1 || y == wing.Y0 || y == wing.Y1; + bool held = (west && x == wing.X0) || (east && x == wing.X1) || (north && y == wing.Y0) || (south && y == wing.Y1); + if (held) + { + overlay.CellMark(x, y, z, OverlayTone.Hover); + } + else if (band) + { + overlay.CellMark(x, y, z, OverlayTone.Selected); + } + } + } + } + + OverlayTone tone = selected ? OverlayTone.Selected : i == hover ? OverlayTone.Hover : OverlayTone.Plain; + Point[] corners = BoxOutline(wing.X0, wing.Y0, wing.X1, wing.Y1, z); + overlay.Outline(corners, tone); + if (!selected || !active) + { + continue; + } + + // Grips in the middle of the selected wing's sides. + for (int side = 0; side < 4; ++side) + { + Point a = corners[side], b = corners[(side + 1) % 4]; + var mid = new Point((a.X + b.X) / 2, (a.Y + b.Y) / 2); + overlay.Outline(new[] + { + new Point(mid.X - 5, mid.Y - 5), new Point(mid.X + 5, mid.Y - 5), + new Point(mid.X + 5, mid.Y + 5), new Point(mid.X - 5, mid.Y + 5) + }, OverlayTone.Selected); + } + } + + if (stroke != null && _drag == DragKind.New) + { + foreach (RoofWing wing in stroke) + { + overlay.Outline(BoxOutline(wing.X0, wing.Y0, wing.X1, wing.Y1, GripZ(wing)), OverlayTone.Hover); + } + } + } + + /// The corners of a box of cells on the plane at height z: top, right, bottom, left. + protected static Point[] BoxOutline(int x0, int y0, int x1, int y1, int z) + { + return new[] { Corner(x0, y0, z), Corner(x1 + 1, y0, z), Corner(x1 + 1, y1 + 1, z), Corner(x0, y1 + 1, z) }; + } + + /// Canvas position of the top corner of a cell's diamond at height z. + protected static Point Corner(int x, int y, int z) + { + return new Point(((x - y) * 22) + MultiEditorComponentList.GapXMod, ((x + y) * 22) - (z * 4) - 22); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs new file mode 100644 index 00000000..2e2646fe --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs @@ -0,0 +1,459 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class HousePanel + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + houseBox = new System.Windows.Forms.GroupBox(); + _wingList = new System.Windows.Forms.ListBox(); + _wingHint = new System.Windows.Forms.Label(); + _storeysLabel = new System.Windows.Forms.Label(); + _storeys = new System.Windows.Forms.NumericUpDown(); + _removeWing = new System.Windows.Forms.Button(); + _roofLabel = new System.Windows.Forms.Label(); + _roofShape = new System.Windows.Forms.ComboBox(); + _ridge = new System.Windows.Forms.ComboBox(); + _materialsLabel = new System.Windows.Forms.Label(); + _storey1 = new System.Windows.Forms.Label(); + _wall1 = new System.Windows.Forms.Button(); + _floor1 = new System.Windows.Forms.Button(); + _storey2 = new System.Windows.Forms.Label(); + _wall2 = new System.Windows.Forms.Button(); + _floor2 = new System.Windows.Forms.Button(); + _storey3 = new System.Windows.Forms.Label(); + _wall3 = new System.Windows.Forms.Button(); + _floor3 = new System.Windows.Forms.Button(); + _storey4 = new System.Windows.Forms.Label(); + _wall4 = new System.Windows.Forms.Button(); + _floor4 = new System.Windows.Forms.Button(); + _roofStyleLabel = new System.Windows.Forms.Label(); + _roofStyle = new System.Windows.Forms.Button(); + _foundation = new System.Windows.Forms.CheckBox(); + _baseZLabel = new System.Windows.Forms.Label(); + _baseZ = new System.Windows.Forms.NumericUpDown(); + _undo = new System.Windows.Forms.Button(); + _redo = new System.Windows.Forms.Button(); + _place = new System.Windows.Forms.Button(); + _drop = new System.Windows.Forms.Button(); + _status = new System.Windows.Forms.Label(); + houseBox.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_storeys).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_baseZ).BeginInit(); + SuspendLayout(); + // + // houseBox + // + houseBox.Controls.Add(_wingList); + houseBox.Controls.Add(_wingHint); + houseBox.Controls.Add(_storeysLabel); + houseBox.Controls.Add(_storeys); + houseBox.Controls.Add(_removeWing); + houseBox.Controls.Add(_roofLabel); + houseBox.Controls.Add(_roofShape); + houseBox.Controls.Add(_ridge); + houseBox.Controls.Add(_materialsLabel); + houseBox.Controls.Add(_storey1); + houseBox.Controls.Add(_wall1); + houseBox.Controls.Add(_floor1); + houseBox.Controls.Add(_storey2); + houseBox.Controls.Add(_wall2); + houseBox.Controls.Add(_floor2); + houseBox.Controls.Add(_storey3); + houseBox.Controls.Add(_wall3); + houseBox.Controls.Add(_floor3); + houseBox.Controls.Add(_storey4); + houseBox.Controls.Add(_wall4); + houseBox.Controls.Add(_floor4); + houseBox.Controls.Add(_roofStyleLabel); + houseBox.Controls.Add(_roofStyle); + houseBox.Controls.Add(_foundation); + houseBox.Controls.Add(_baseZLabel); + houseBox.Controls.Add(_baseZ); + houseBox.Controls.Add(_undo); + houseBox.Controls.Add(_redo); + houseBox.Controls.Add(_place); + houseBox.Controls.Add(_drop); + houseBox.Controls.Add(_status); + houseBox.Dock = System.Windows.Forms.DockStyle.Fill; + houseBox.Location = new System.Drawing.Point(0, 0); + houseBox.Name = "houseBox"; + houseBox.Size = new System.Drawing.Size(250, 430); + houseBox.TabIndex = 0; + houseBox.TabStop = false; + houseBox.Text = "House draft"; + // + // _wingList + // + _wingList.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _wingList.FormattingEnabled = true; + _wingList.IntegralHeight = false; + _wingList.Location = new System.Drawing.Point(6, 20); + _wingList.Name = "_wingList"; + _wingList.Size = new System.Drawing.Size(238, 64); + _wingList.TabIndex = 0; + _wingList.SelectedIndexChanged += WingList_SelectedIndexChanged; + // + // _wingHint + // + _wingHint.AutoSize = true; + _wingHint.Location = new System.Drawing.Point(6, 90); + _wingHint.Name = "_wingHint"; + _wingHint.Size = new System.Drawing.Size(120, 15); + _wingHint.TabIndex = 1; + _wingHint.Text = "New wings:"; + // + // _storeysLabel + // + _storeysLabel.AutoSize = true; + _storeysLabel.Location = new System.Drawing.Point(6, 113); + _storeysLabel.Name = "_storeysLabel"; + _storeysLabel.Size = new System.Drawing.Size(50, 15); + _storeysLabel.TabIndex = 2; + _storeysLabel.Text = "Storeys"; + // + // _storeys + // + _storeys.Maximum = new decimal(new int[] { 4, 0, 0, 0 }); + _storeys.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); + _storeys.Value = new decimal(new int[] { 1, 0, 0, 0 }); + _storeys.Location = new System.Drawing.Point(60, 110); + _storeys.Name = "_storeys"; + _storeys.Size = new System.Drawing.Size(44, 23); + _storeys.TabIndex = 3; + _storeys.ValueChanged += Storeys_ValueChanged; + // + // _removeWing + // + _removeWing.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + _removeWing.UseVisualStyleBackColor = true; + _removeWing.Location = new System.Drawing.Point(150, 109); + _removeWing.Name = "_removeWing"; + _removeWing.Size = new System.Drawing.Size(94, 25); + _removeWing.TabIndex = 4; + _removeWing.Text = "Remove wing"; + _removeWing.Click += RemoveWing_Click; + // + // _roofLabel + // + _roofLabel.AutoSize = true; + _roofLabel.Location = new System.Drawing.Point(6, 143); + _roofLabel.Name = "_roofLabel"; + _roofLabel.Size = new System.Drawing.Size(50, 15); + _roofLabel.TabIndex = 5; + _roofLabel.Text = "Roof"; + // + // _roofShape + // + _roofShape.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _roofShape.FormattingEnabled = true; + _roofShape.Items.AddRange(new object[] { "Gable", "None" }); + _roofShape.Location = new System.Drawing.Point(60, 140); + _roofShape.Name = "_roofShape"; + _roofShape.Size = new System.Drawing.Size(80, 23); + _roofShape.TabIndex = 6; + _roofShape.SelectedIndexChanged += RoofShape_SelectedIndexChanged; + // + // _ridge + // + _ridge.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _ridge.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _ridge.FormattingEnabled = true; + _ridge.Items.AddRange(new object[] { "Ridge: auto", "Ridge along X", "Ridge along Y" }); + _ridge.Location = new System.Drawing.Point(146, 140); + _ridge.Name = "_ridge"; + _ridge.Size = new System.Drawing.Size(98, 23); + _ridge.TabIndex = 7; + _ridge.SelectedIndexChanged += Ridge_SelectedIndexChanged; + // + // _materialsLabel + // + _materialsLabel.Location = new System.Drawing.Point(6, 172); + _materialsLabel.Name = "_materialsLabel"; + _materialsLabel.Size = new System.Drawing.Size(238, 15); + _materialsLabel.TabIndex = 8; + _materialsLabel.Text = "Storey: walls and floor style"; + // + // _storey1 + // + _storey1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + _storey1.Location = new System.Drawing.Point(6, 196); + _storey1.Name = "_storey1"; + _storey1.Size = new System.Drawing.Size(18, 17); + _storey1.TabIndex = 9; + _storey1.Text = "1"; + // + // _wall1 + // + _wall1.UseVisualStyleBackColor = true; + _wall1.Location = new System.Drawing.Point(28, 192); + _wall1.Name = "_wall1"; + _wall1.Size = new System.Drawing.Size(106, 25); + _wall1.TabIndex = 10; + _wall1.Text = "(walls)"; + // + // _floor1 + // + _floor1.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _floor1.UseVisualStyleBackColor = true; + _floor1.Location = new System.Drawing.Point(138, 192); + _floor1.Name = "_floor1"; + _floor1.Size = new System.Drawing.Size(106, 25); + _floor1.TabIndex = 11; + _floor1.Text = "(floor)"; + // + // _storey2 + // + _storey2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + _storey2.Location = new System.Drawing.Point(6, 223); + _storey2.Name = "_storey2"; + _storey2.Size = new System.Drawing.Size(18, 17); + _storey2.TabIndex = 12; + _storey2.Text = "2"; + // + // _wall2 + // + _wall2.UseVisualStyleBackColor = true; + _wall2.Location = new System.Drawing.Point(28, 219); + _wall2.Name = "_wall2"; + _wall2.Size = new System.Drawing.Size(106, 25); + _wall2.TabIndex = 13; + _wall2.Text = "(walls)"; + // + // _floor2 + // + _floor2.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _floor2.UseVisualStyleBackColor = true; + _floor2.Location = new System.Drawing.Point(138, 219); + _floor2.Name = "_floor2"; + _floor2.Size = new System.Drawing.Size(106, 25); + _floor2.TabIndex = 14; + _floor2.Text = "(floor)"; + // + // _storey3 + // + _storey3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + _storey3.Location = new System.Drawing.Point(6, 250); + _storey3.Name = "_storey3"; + _storey3.Size = new System.Drawing.Size(18, 17); + _storey3.TabIndex = 15; + _storey3.Text = "3"; + // + // _wall3 + // + _wall3.UseVisualStyleBackColor = true; + _wall3.Location = new System.Drawing.Point(28, 246); + _wall3.Name = "_wall3"; + _wall3.Size = new System.Drawing.Size(106, 25); + _wall3.TabIndex = 16; + _wall3.Text = "(walls)"; + // + // _floor3 + // + _floor3.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _floor3.UseVisualStyleBackColor = true; + _floor3.Location = new System.Drawing.Point(138, 246); + _floor3.Name = "_floor3"; + _floor3.Size = new System.Drawing.Size(106, 25); + _floor3.TabIndex = 17; + _floor3.Text = "(floor)"; + // + // _storey4 + // + _storey4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + _storey4.Location = new System.Drawing.Point(6, 277); + _storey4.Name = "_storey4"; + _storey4.Size = new System.Drawing.Size(18, 17); + _storey4.TabIndex = 18; + _storey4.Text = "4"; + // + // _wall4 + // + _wall4.UseVisualStyleBackColor = true; + _wall4.Location = new System.Drawing.Point(28, 273); + _wall4.Name = "_wall4"; + _wall4.Size = new System.Drawing.Size(106, 25); + _wall4.TabIndex = 19; + _wall4.Text = "(walls)"; + // + // _floor4 + // + _floor4.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _floor4.UseVisualStyleBackColor = true; + _floor4.Location = new System.Drawing.Point(138, 273); + _floor4.Name = "_floor4"; + _floor4.Size = new System.Drawing.Size(106, 25); + _floor4.TabIndex = 20; + _floor4.Text = "(floor)"; + // + // _roofStyleLabel + // + _roofStyleLabel.AutoSize = true; + _roofStyleLabel.Location = new System.Drawing.Point(6, 305); + _roofStyleLabel.Name = "_roofStyleLabel"; + _roofStyleLabel.Size = new System.Drawing.Size(50, 15); + _roofStyleLabel.TabIndex = 21; + _roofStyleLabel.Text = "Roof"; + // + // _roofStyle + // + _roofStyle.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _roofStyle.UseVisualStyleBackColor = true; + _roofStyle.Location = new System.Drawing.Point(60, 300); + _roofStyle.Name = "_roofStyle"; + _roofStyle.Size = new System.Drawing.Size(184, 25); + _roofStyle.TabIndex = 22; + _roofStyle.Text = "(roof)"; + // + // _foundation + // + _foundation.AutoSize = true; + _foundation.UseVisualStyleBackColor = true; + _foundation.Location = new System.Drawing.Point(6, 332); + _foundation.Name = "_foundation"; + _foundation.Size = new System.Drawing.Size(100, 19); + _foundation.TabIndex = 23; + _foundation.Text = "Foundation"; + _foundation.CheckedChanged += Foundation_CheckedChanged; + // + // _baseZLabel + // + _baseZLabel.AutoSize = true; + _baseZLabel.Location = new System.Drawing.Point(126, 334); + _baseZLabel.Name = "_baseZLabel"; + _baseZLabel.Size = new System.Drawing.Size(44, 15); + _baseZLabel.TabIndex = 24; + _baseZLabel.Text = "Base Z"; + // + // _baseZ + // + _baseZ.Maximum = new decimal(new int[] { 100, 0, 0, 0 }); + _baseZ.Minimum = new decimal(new int[] { 100, 0, 0, int.MinValue }); + _baseZ.Location = new System.Drawing.Point(174, 331); + _baseZ.Name = "_baseZ"; + _baseZ.Size = new System.Drawing.Size(56, 23); + _baseZ.TabIndex = 25; + _baseZ.ValueChanged += BaseZ_ValueChanged; + // + // _undo + // + _undo.UseVisualStyleBackColor = true; + _undo.Location = new System.Drawing.Point(6, 362); + _undo.Name = "_undo"; + _undo.Size = new System.Drawing.Size(54, 25); + _undo.TabIndex = 26; + _undo.Text = "Undo"; + _undo.Click += Undo_Click; + // + // _redo + // + _redo.UseVisualStyleBackColor = true; + _redo.Location = new System.Drawing.Point(62, 362); + _redo.Name = "_redo"; + _redo.Size = new System.Drawing.Size(54, 25); + _redo.TabIndex = 27; + _redo.Text = "Redo"; + _redo.Click += Redo_Click; + // + // _place + // + _place.UseVisualStyleBackColor = true; + _place.Location = new System.Drawing.Point(122, 362); + _place.Name = "_place"; + _place.Size = new System.Drawing.Size(72, 25); + _place.TabIndex = 28; + _place.Text = "Place"; + _place.Click += Place_Click; + // + // _drop + // + _drop.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _drop.UseVisualStyleBackColor = true; + _drop.Location = new System.Drawing.Point(196, 362); + _drop.Name = "_drop"; + _drop.Size = new System.Drawing.Size(48, 25); + _drop.TabIndex = 29; + _drop.Text = "Drop"; + _drop.Click += Drop_Click; + // + // _status + // + _status.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _status.Location = new System.Drawing.Point(6, 392); + _status.Name = "_status"; + _status.Size = new System.Drawing.Size(238, 32); + _status.TabIndex = 30; + // + // HousePanel + // + AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + Controls.Add(houseBox); + Name = "HousePanel"; + Size = new System.Drawing.Size(250, 430); + houseBox.ResumeLayout(false); + houseBox.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)_storeys).EndInit(); + ((System.ComponentModel.ISupportInitialize)_baseZ).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.GroupBox houseBox; + private System.Windows.Forms.ListBox _wingList; + private System.Windows.Forms.Label _wingHint; + private System.Windows.Forms.Label _storeysLabel; + private System.Windows.Forms.NumericUpDown _storeys; + private System.Windows.Forms.Button _removeWing; + private System.Windows.Forms.Label _roofLabel; + private System.Windows.Forms.ComboBox _roofShape; + private System.Windows.Forms.ComboBox _ridge; + private System.Windows.Forms.Label _materialsLabel; + private System.Windows.Forms.Label _storey1; + private System.Windows.Forms.Button _wall1; + private System.Windows.Forms.Button _floor1; + private System.Windows.Forms.Label _storey2; + private System.Windows.Forms.Button _wall2; + private System.Windows.Forms.Button _floor2; + private System.Windows.Forms.Label _storey3; + private System.Windows.Forms.Button _wall3; + private System.Windows.Forms.Button _floor3; + private System.Windows.Forms.Label _storey4; + private System.Windows.Forms.Button _wall4; + private System.Windows.Forms.Button _floor4; + private System.Windows.Forms.Label _roofStyleLabel; + private System.Windows.Forms.Button _roofStyle; + private System.Windows.Forms.CheckBox _foundation; + private System.Windows.Forms.Label _baseZLabel; + private System.Windows.Forms.NumericUpDown _baseZ; + private System.Windows.Forms.Button _undo; + private System.Windows.Forms.Button _redo; + private System.Windows.Forms.Button _place; + private System.Windows.Forms.Button _drop; + private System.Windows.Forms.Label _status; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs new file mode 100644 index 00000000..d744288b --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs @@ -0,0 +1,233 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Editing; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The house draft of the session: its wings, the storeys and roof of the selected wing, the + /// wall and floor style of each storey, the roof style, foundation and base Z, and the + /// draft's undo, redo, place and drop. The row of the storey that the chosen floor means is + /// marked, as that is the storey the wall, door, floor and stair tools work on. + /// + internal sealed partial class HousePanel : UserControl + { + private readonly Button[] _wallButtons; + private readonly Button[] _floorButtons; + private readonly Label[] _storeyLabels; + private readonly Font _boldFont; + private EditorSession _session; + private bool _updating; + + public HousePanel() + { + InitializeComponent(); + _wallButtons = new[] { _wall1, _wall2, _wall3, _wall4 }; + _floorButtons = new[] { _floor1, _floor2, _floor3, _floor4 }; + _storeyLabels = new[] { _storey1, _storey2, _storey3, _storey4 }; + _boldFont = new Font(Font, FontStyle.Bold); + Disposed += (_, _) => _boldFont.Dispose(); + + for (int k = 0; k < HouseDraft.MaxStoreys; ++k) + { + int storey = k; + _wallButtons[k].Click += (_, _) => PickStyle?.Invoke(HousePartKind.Wall, storey); + _floorButtons[k].Click += (_, _) => PickStyle?.Invoke(HousePartKind.Floor, storey); + } + + _roofStyle.Click += (_, _) => PickStyle?.Invoke(HousePartKind.Roof, 0); + } + + /// Asks for a style to be picked on the House page for a storey's walls or floor, or for the roof. + public event Action PickStyle; + + /// Raised after a button of the panel was used, so the canvas can take the keyboard back. + public event Action Used; + + public void Bind(EditorSession session) + { + if (_session != null) + { + _session.DraftChanged -= RefreshDraft; + _session.ViewChanged -= RefreshDraft; + } + + _session = session; + if (_session != null) + { + _session.DraftChanged += RefreshDraft; + _session.ViewChanged += RefreshDraft; + } + + RefreshDraft(); + } + + /// Fills the panel from the session's house draft. + public void RefreshDraft() + { + HouseTool house = _session?.House; + Enabled = house != null; + if (house == null) + { + return; + } + + _updating = true; + try + { + _wingList.BeginUpdate(); + _wingList.Items.Clear(); + for (int i = 0; i < house.Wings.Count; ++i) + { + RoofWing wing = house.Wings[i]; + string roof = wing.NoRoof ? "no roof" : wing.Shape.ToString().ToLowerInvariant(); + _wingList.Items.Add($"Wing {i + 1}: {wing.X1 - wing.X0 + 1} x {wing.Y1 - wing.Y0 + 1}, {wing.Storeys} storey{(wing.Storeys == 1 ? string.Empty : "s")}, {roof}"); + } + + _wingList.SelectedIndex = house.SelectedIndex; + _wingList.EndUpdate(); + + _storeys.Value = Math.Clamp(house.Storeys, 1, HouseDraft.MaxStoreys); + // The drop-down lists the roof shapes in their order, then None. + _roofShape.SelectedIndex = house.NoRoof ? _roofShape.Items.Count - 1 : (int)house.Shape; + _ridge.SelectedIndex = (int)house.Ridge; + _ridge.Enabled = !house.NoRoof; + _removeWing.Enabled = house.HasSelectedWing; + _wingHint.Text = house.HasSelectedWing ? "Selected wing:" : "New wings:"; + + int top = house.TopStorey; + int active = house.HasPending ? _session.DraftStorey : -1; + for (int k = 0; k < HouseDraft.MaxStoreys; ++k) + { + bool used = k < top || k < house.Storeys; + _storeyLabels[k].Visible = _wallButtons[k].Visible = _floorButtons[k].Visible = used; + _wallButtons[k].Text = house.Draft.WallStyles[k]?.Name ?? "(walls)"; + _floorButtons[k].Text = house.Draft.FloorStyles[k]?.Name ?? "(floor)"; + + // The storey the chosen floor means: where the other tools work. + bool current = k == active; + _storeyLabels[k].Font = current ? _boldFont : Font; + _storeyLabels[k].BackColor = current ? Color.FromArgb(255, 214, 64) : Color.Transparent; + _storeyLabels[k].ForeColor = current ? Color.Black : ForeColor; + } + + _roofStyle.Text = house.Draft.RoofStyle?.Name ?? "(roof)"; + _foundation.Checked = house.Draft.Foundation; + _baseZ.Enabled = house.HasPending; + _baseZ.Value = Math.Clamp(house.BaseZ, (int)_baseZ.Minimum, (int)_baseZ.Maximum); + + _undo.Enabled = house.CanUndoDraft; + _redo.Enabled = house.CanRedoDraft; + _place.Enabled = _drop.Enabled = house.HasPending; + + if (!house.HasPending) + { + _status.Text = "Drag on the canvas to draw the first wing."; + } + else + { + int x0 = house.Wings.Min(w => w.X0), x1 = house.Wings.Max(w => w.X1); + int y0 = house.Wings.Min(w => w.Y0), y1 = house.Wings.Max(w => w.Y1); + _status.Text = $"{house.Wings.Count} wing{(house.Wings.Count == 1 ? string.Empty : "s")}, {x1 - x0 + 1} x {y1 - y0 + 1} cells, " + + $"{top} storey{(top == 1 ? string.Empty : "s")}. Not in the multi until placed."; + } + } + finally + { + _updating = false; + } + } + + private void Run(Action action) + { + if (_updating || _session == null) + { + return; + } + + action(_session.House); + Used?.Invoke(); + } + + private void WingList_SelectedIndexChanged(object sender, EventArgs e) + { + if (!_updating && _session != null) + { + _session.House.SelectedIndex = _wingList.SelectedIndex; + } + } + + private void Storeys_ValueChanged(object sender, EventArgs e) + { + if (!_updating && _session != null) + { + _session.House.SetStoreys((int)_storeys.Value); + } + } + + private void RoofShape_SelectedIndexChanged(object sender, EventArgs e) + { + int index = _roofShape.SelectedIndex; + bool none = index == _roofShape.Items.Count - 1; + Run(house => house.SetRoof(!none && Enum.IsDefined((RoofShape)index) ? (RoofShape)index : RoofShape.Gable, none)); + } + + private void Ridge_SelectedIndexChanged(object sender, EventArgs e) + { + Run(house => house.SetRidge((RoofRidge)Math.Max(0, _ridge.SelectedIndex))); + } + + private void RemoveWing_Click(object sender, EventArgs e) + { + Run(house => house.DeleteWing()); + } + + private void Foundation_CheckedChanged(object sender, EventArgs e) + { + Run(house => house.SetFoundation(_foundation.Checked)); + } + + private void BaseZ_ValueChanged(object sender, EventArgs e) + { + if (!_updating && _session != null) + { + _session.House.SetBaseZ((int)_baseZ.Value); + } + } + + private void Undo_Click(object sender, EventArgs e) + { + Run(house => house.UndoDraft()); + } + + private void Redo_Click(object sender, EventArgs e) + { + Run(house => house.RedoDraft()); + } + + private void Place_Click(object sender, EventArgs e) + { + Run(house => house.Commit()); + } + + private void Drop_Click(object sender, EventArgs e) + { + Run(house => house.Discard()); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs index 1ace2356..7d0e3074 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs @@ -59,6 +59,16 @@ public MultiEditorControl() InitializeComponent(); SplitterGrip.Attach(_sideSplit); + // The house draft's panel sits above the floors and selection; shown with the House tool or an open draft. + _housePanel = new HousePanel { Dock = DockStyle.Top, Visible = false }; + _housePanel.PickStyle += PickHouseMaterial; + _housePanel.Used += () => + { + _commands.RefreshStates(); + _canvas.Focus(); + }; + _sideSplit.Panel2.Controls.Add(_housePanel); + // Room after each tab's text for its close button, at any DPI. _docTabs.Padding = new Point((CloseGlyphSize + LogicalToDeviceUnits(16)) / 2, _docTabs.Padding.Y); } @@ -495,16 +505,16 @@ private void DefineCommands() _closeAll = Command("File", "Close all designs", CloseAllDocuments, Keys.Control | Keys.Shift | Keys.W, hasDoc); _undo = Command("Edit", "Undo", () => Session.Undo(), Keys.Control | Keys.Z, - () => Session != null && Session.CompList.UndoList.Count > 0, glyph: Glyphs.Undo); + () => Session != null && Session.CanUndo, glyph: Glyphs.Undo); _redo = Command("Edit", "Redo", () => Session.Redo(), Keys.Control | Keys.Y, - () => Session != null && Session.CompList.RedoList.Count > 0, glyph: Glyphs.Redo, alt: Keys.Control | Keys.Shift | Keys.Z); + () => Session != null && Session.CanRedo, glyph: Glyphs.Redo, alt: Keys.Control | Keys.Shift | Keys.Z); _cut = Command("Edit", "Cut", () => Session.Cut(), Keys.Control | Keys.X, hasSelection, glyph: Glyphs.Cut); _copy = Command("Edit", "Copy", () => Session.Copy(), Keys.Control | Keys.C, hasSelection, glyph: Glyphs.Copy); _paste = Command("Edit", "Paste", () => Session.Paste(), Keys.Control | Keys.V, hasDoc, glyph: Glyphs.Paste); _duplicate = Command("Edit", "Duplicate selection", () => Session.Duplicate(), Keys.Control | Keys.D, hasSelection); _repeat = Command("Edit", "Repeat selection...", RepeatSelectionPrompt, Keys.Control | Keys.Shift | Keys.D, hasSelection); _delete = Command("Edit", "Delete selection", DeleteSelectionOrWing, Keys.Delete, - () => Session != null && (Session.ShapingRoof ? Session.Roof.HasSelectedWing : Session.Selection.Count > 0), glyph: Glyphs.Delete); + () => Session != null && (Session.ShapingRoof ? Session.WingTool.HasSelectedWing : Session.Selection.Count > 0), glyph: Glyphs.Delete); _selectAll = Command("Select", "Select all", () => Session.SelectAll(), Keys.Control | Keys.A, hasDoc); _invert = Command("Select", "Invert selection", () => Session.InvertSelection(), Keys.Control | Keys.Shift | Keys.A, hasDoc); @@ -575,6 +585,7 @@ private void DefineCommands() AddTool(ToolKind.Stair, "Stairs", Keys.D4, Glyphs.Stair); AddTool(ToolKind.Roof, "Roofs", Keys.D5, Glyphs.Roof); AddTool(ToolKind.Foundation, "Foundation", Keys.D6, Glyphs.Foundation); + AddTool(ToolKind.House, "House", Keys.D7, Glyphs.Foundation); AddTool(ToolKind.FloorPattern, "Floor pattern", Keys.None, Glyphs.Floor); _cyclePlacement = Command("Tools", "Next placement mode", CyclePlacement, Keys.M, hasDoc); @@ -599,8 +610,8 @@ private void DefineCommands() hasDoc, () => Session?.BrushSize == size)); } _escape = Command("Tools", "Cancel tool, then clear selection", Escape, Keys.Escape, hasDoc); - _placeRoof = Command("Tools", "Place the roof being shaped", () => Session.Roof.Commit(), Keys.Enter, - () => Session != null && Session.ShapingRoof); + _placeRoof = Command("Tools", "Place the roof or house being shaped", () => Session.DraftInFocus?.Commit(), Keys.Enter, + () => Session?.DraftInFocus != null); _shortcuts = Command("Help", "Keyboard shortcuts", ShowShortcuts, Keys.F1, glyph: Glyphs.Help); _drawWithSelected = Command("Tools", "Draw with this tile", DrawWithSelected, can: () => (_menuTile ?? Session?.SelectedTile) != null); } @@ -625,6 +636,12 @@ private void SetTool(ToolKind kind, bool fromHousePage = false) Session.Tool = kind; + // The house draft is worked on in its panel, which sits in the floors and selection sidebar. + if (kind == ToolKind.House && !_inspectorShown) + { + ToggleSidebar(browser: false); + } + // A house tool builds with a style from the House page: bring that page up on the // matching kind. The page answers by choosing the style, which comes back here. if (IsHouseTool(kind) && !fromHousePage && !_openingHousePage && _browserShown) @@ -658,6 +675,16 @@ private void ChooseHouseStyle(HouseStyle style) return; } + // A pick asked for by the house panel is a material of the draft, not a tool's style. + if (_housePick is { } pick && pick.Kind == style.Kind) + { + _housePick = null; + Session.House.SetMaterial(style, style.Kind == HousePartKind.Roof ? null : pick.Storey); + SetTool(ToolKind.House, fromHousePage: true); + return; + } + + _housePick = null; Session.HouseStyle = style; ToolKind kind = style.Kind switch { @@ -670,6 +697,35 @@ private void ChooseHouseStyle(HouseStyle style) SetTool(kind, fromHousePage: true); } + /// The house panel asks for a style: the House page comes up on that kind and the next pick there goes to the draft. + private void PickHouseMaterial(HousePartKind kind, int storey) + { + if (Session == null) + { + return; + } + + if (!_browserShown) + { + ToggleSidebar(browser: true); + } + + _housePick = (kind, storey); + _openingHousePage = true; + try + { + _browser.ShowHousePage(kind, foundation: false); + } + finally + { + _openingHousePage = false; + } + + _statusHint.Text = kind == HousePartKind.Roof + ? "Pick the roof style of the house on the House page." + : $"Pick the {(kind == HousePartKind.Wall ? "wall" : "floor")} style of storey {storey + 1} on the House page."; + } + private void CyclePlacement() { Session.Placement = (PlacementMode)(((int)Session.Placement + 1) % 3); @@ -680,7 +736,7 @@ private void DeleteSelectionOrWing() { if (Session.ShapingRoof) { - Session.Roof.DeleteWing(); + Session.WingTool.DeleteWing(); } else { @@ -691,9 +747,9 @@ private void DeleteSelectionOrWing() private void Escape() { // With a roof being shaped: the first Esc stops a drag, the next one drops the roof. - if (Session.ShapingRoof && !Session.ActiveTool.IsDragging) + if (Session.DraftInFocus is { } draft && !Session.ActiveTool.IsDragging) { - Session.Roof.Discard(); + draft.Discard(); return; } @@ -1355,8 +1411,22 @@ private void BuildOptionsStrip() ("Walls", () => Session.Roof.GableFill == RoofGableFill.Walls, () => Session.Roof.GableFill = RoofGableFill.Walls)); // Shown while a roof is being shaped. - _placeRoofButton = RoofAction(strip, "Place roof", "Places the roof on the Roof layer (Enter).", () => Session.Roof.Commit()); - _dropRoofButton = RoofAction(strip, "Drop", "Drops the roof being shaped (Esc).", () => Session.Roof.Discard()); + _placeRoofButton = RoofAction(strip, "Place", "Places what is being shaped: the roof on the Roof layer, the house on its layers (Enter).", () => Session.DraftInFocus?.Commit()); + _dropRoofButton = RoofAction(strip, "Drop", "Drops what is being shaped (Esc). Undo brings it back.", () => Session.DraftInFocus?.Discard()); + } + + /// What the tool in use does to the open house draft. + private static string DraftHint(EditorSession session) + { + string storey = $"House draft, storey {session.DraftStorey + 1} (the floor buttons choose it): "; + return session.Tool switch + { + ToolKind.Wall => storey + "drag to add walls, Ctrl+drag to take walls away, click a wall for a window.", + ToolKind.Door => storey + "click a wall to hang the chosen door, again to turn it, Ctrl+click to take it out.", + ToolKind.Floor => storey + "drag an area to lay it in the chosen floor style.", + ToolKind.Stair => storey + "press on the bottom step and drag the way the stairs climb; Ctrl+click a bottom step removes them.", + _ => "A house draft is open. This tool works on the multi; House, Walls, Doors, Floors and Stairs work on the draft." + }; } private void ZStepCombo_SelectedIndexChanged(object sender, EventArgs e) @@ -1364,6 +1434,8 @@ private void ZStepCombo_SelectedIndexChanged(object sender, EventArgs e) Apply(() => Session.ZStep = int.Parse(_zStepCombo.Text)); } + private readonly HousePanel _housePanel; + private (HousePartKind Kind, int Storey)? _housePick; private EditorCommand _placeRoof; private ToolStripButton _placeRoofButton; private ToolStripButton _dropRoofButton; @@ -1419,7 +1491,7 @@ private ToolStripButton RoofAction(ToolStrip strip, string text, string tip, Act }; button.Click += (_, _) => { - if (Session != null && Session.ShapingRoof) + if (Session?.DraftInFocus != null) { run(); _commands.RefreshStates(); @@ -1438,7 +1510,13 @@ private void SyncRoofOptions() item.Visible = show; } - _placeRoofButton.Visible = _dropRoofButton.Visible = show && Session.ShapingRoof; + _placeRoofButton.Visible = _dropRoofButton.Visible = Session != null && !Session.Pasting && Session.DraftInFocus != null; + + bool house = Session != null && (Session.Tool == ToolKind.House || Session.House.HasPending); + if (_housePanel.Visible != house) + { + _housePanel.Visible = house; + } foreach ((ToolStripButton button, Func isOn) in _roofButtons) { @@ -1479,7 +1557,7 @@ void Section(ToolStripLabel title, params ToolKind[] kinds) Section(_editToolsLabel, ToolKind.Select, ToolKind.Lasso, ToolKind.Altitude, ToolKind.Pipette, ToolKind.Transparent, ToolKind.Remove); Section(_drawToolsLabel, ToolKind.Draw, ToolKind.RectFill, ToolKind.Line); - Section(_houseToolsLabel, ToolKind.Wall, ToolKind.Floor, ToolKind.Door, ToolKind.Stair, ToolKind.Roof, ToolKind.Foundation); + Section(_houseToolsLabel, ToolKind.Wall, ToolKind.Floor, ToolKind.Door, ToolKind.Stair, ToolKind.Roof, ToolKind.Foundation, ToolKind.House); } // ---------------------------------------------------------------- documents @@ -1627,6 +1705,11 @@ private void ShowDocument(EditorDocument document) private void SaveToClient() { + if (!SettleOpenDraft()) + { + return; + } + if (AskIncludeHiddenLayers("Leaves them out of the client's multi. They stay in the editor's layers and come back when you open it here.") is not { } includeHidden) { return; @@ -1656,6 +1739,11 @@ private void SaveToClient() private void ExportFile() { + if (!SettleOpenDraft()) + { + return; + } + if (AskIncludeHiddenLayers("Leaves them out of the file. Exported files do not keep layers.") is not { } includeHidden) { return; @@ -1671,6 +1759,37 @@ private void ExportFile() /// Before a save: asks whether tiles on hidden layers go into it. True without asking when /// no hidden layer has tiles; null when the save is cancelled. /// + /// + /// Before a save: a roof or house still being shaped is not in the multi. Asks whether to + /// place it first. False when the save was cancelled. + /// + private bool SettleOpenDraft() + { + WingDraftTool draft = Session.House.HasPending ? Session.House : Session.Roof.HasPending ? Session.Roof : null; + if (draft == null) + { + return true; + } + + string what = draft is HouseTool ? "house" : "roof"; + DialogResult answer = MessageBox.Show(this, + $"The {what} being shaped is not placed yet, so it is not part of the multi.\r\n\r\nPlace it before saving?\r\n\r\n" + + "Yes places it. No saves without it and keeps it open.", + "Multi Editor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); + if (answer == DialogResult.Cancel) + { + return false; + } + + if (answer == DialogResult.Yes) + { + draft.Commit(); + _commands.RefreshStates(); + } + + return true; + } + private bool? AskIncludeHiddenLayers(string whenLeftOut) { MultiEditorComponentList list = Session.CompList; @@ -1742,6 +1861,11 @@ private void OpenDesignFile() /// private void SaveDesignFile(bool saveAs) { + if (!SettleOpenDraft()) + { + return; + } + string path = _active.FilePath; if (saveAs || path == null) { @@ -2032,6 +2156,7 @@ private void Activate(int index) { _canvas.Show(null, null); _inspector.Bind(null); + _housePanel.Bind(null); } else { @@ -2048,6 +2173,7 @@ private void Activate(int index) _canvas.Show(session, document.Camera); _inspector.Bind(session); + _housePanel.Bind(session); if (session.DrawTileId != 0) { _browser.SetCurrentTile(session.DrawTileId); @@ -2237,8 +2363,9 @@ private void UpdateStatus() _statusHint.Text = session.PreviewMode ? "Preview: editing is off. Right click picks the ground. F5 returns to the editor." : session.PreviewingRepeat ? "The copies are shown as they would be placed." : session.Pasting ? "Click to place the tiles, as often as you like. Esc or right click stops." - : session.ShapingRoof ? "Shaping the roof: drag a wing to move it, an edge of the selected wing to resize it, anywhere else to add a wing. " + - "Shift+click turns a ridge, Delete removes a wing. Enter places the roof on the Roof layer, Esc drops it." + : session.ShapingRoof ? "Shaping: drag a wing to move it, a marked edge of the selected wing to resize it, anywhere else to add a wing. " + + "Shift+click turns a ridge, Delete removes a wing, Ctrl+Z steps back. Enter places it, Esc drops it." + : session.House.HasPending ? DraftHint(session) : ToolHint(session.Tool); (int x, int y, int z) = session.CursorCell; @@ -2274,6 +2401,7 @@ private static string ToolHint(ToolKind kind) ToolKind.Stair => "Drag in the direction the stairs climb.", ToolKind.Roof => "Click a walled room to start its roof, or drag out a roof of any size. It stays open for shaping until Enter places it.", ToolKind.Foundation => "Drag an area to lay a foundation under it.", + ToolKind.House => "Drag out the wall cells of a wing to start a house. Storeys, roof and materials are in the House panel; nothing is placed until Enter.", ToolKind.FloorPattern => "Drag an area to lay the bordered floor: corners, sides and fill repeat to fit.", _ => string.Empty }; diff --git a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs index 25f2943c..bb82b089 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs @@ -72,7 +72,15 @@ public void ShowCommands(IEnumerable commands) ("Turn a wing's ridge (Roof)", "Shift + click the wing"), ("Remove the selected wing (Roof)", "Delete"), ("Place the roof on the Roof layer (Roof)", "Enter, or pick another tool"), - ("Drop the roof being shaped (Roof)", "Esc")); + ("Drop the roof being shaped (Roof)", "Esc"), + ("Add a wing to the house draft (House)", "Drag out its wall cells"), + ("Select, move, resize, turn or remove a wing (House)", "As with the roof's wings"), + ("Step back and forth through the draft (Roof, House)", "Ctrl+Z / Ctrl+Y"), + ("Partitions and openings in the house draft (Walls)", "Drag / Ctrl + drag"), + ("Window in a wall of the house draft (Walls)", "Click the wall"), + ("Door in the house draft (Doors)", "Click a wall; Ctrl + click removes"), + ("Place the house on its layers (House and its draft tools)", "Enter"), + ("Drop the house draft; undo brings it back (House)", "Esc")); Section("Tile browser", ("Go from the search box to the results", "Down"), diff --git a/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj b/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj index 0484dc45..f2f388ee 100644 --- a/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj +++ b/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj @@ -83,6 +83,12 @@ FloorsDialog.cs + + UserControl + + + HousePanel.cs + UserControl From 754a0d335adacf0171d1b147c67f3af3d36409e9 Mon Sep 17 00:00:00 2001 From: AsY!um- <377468+AsYlum-@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:52:33 +0100 Subject: [PATCH 03/16] Let shortcut keys be typed while a layer is renamed --- .../UI/MultiEditorControl.cs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs index 7d0e3074..2d571e83 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs @@ -2467,7 +2467,30 @@ private bool IsTextInputFocused() } return focused is TextBoxBase || focused is NumericUpDown || focused is ComboBox || - focused.Parent is NumericUpDown || focused is ToolStrip; + focused.Parent is NumericUpDown || focused is ToolStrip || NativeEditHasFocus(); } + + /// + /// True while a plain Windows edit box has the keyboard: the box a list or tree shows to + /// rename an item (a layer's name) is one, and it is no WinForms control, so the + /// focused control is still the list. + /// + private static bool NativeEditHasFocus() + { + IntPtr focus = GetFocus(); + if (focus == IntPtr.Zero) + { + return false; + } + + var name = new System.Text.StringBuilder(32); + return GetClassName(focus, name, name.Capacity) > 0 && name.ToString().Equals("Edit", StringComparison.OrdinalIgnoreCase); + } + + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern IntPtr GetFocus(); + + [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] + private static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder className, int maxCount); } } From 99975247fb907b20a8143b0835b330a037f82174 Mon Sep 17 00:00:00 2001 From: AsY!um- <377468+AsYlum-@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:39:25 +0100 Subject: [PATCH 04/16] Add hip roofs, rooms, house files and a house tab Placed houses reopen as drafts; the preview can hide walls, floors or roof; preview opacity setting. --- .../Classes/DesignFile.cs | 14 +- .../Classes/HouseDraft.cs | 127 +++++++++ .../Classes/HouseDraftFile.cs | 244 ++++++++++++++++++ .../Classes/LayerStore.cs | 12 +- .../Classes/RoofPlanner.cs | 57 +++- .../Editing/EditorSession.Commands.cs | 3 +- .../Editing/EditorSession.cs | 109 ++++++++ .../Rendering/SceneRenderer.cs | 4 +- .../Tools/HouseTool.cs | 227 +++++++++++++++- .../Tools/RoofTool.cs | 20 +- .../Tools/WingDraftTool.cs | 44 +++- .../UI/EditorSettings.cs | 10 + .../UI/EditorSettingsDialog.Designer.cs | 71 ++++- .../UI/EditorSettingsDialog.cs | 14 + .../UI/HousePanel.Designer.cs | 199 ++++++++++++-- UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs | 90 ++++++- .../UI/MultiEditorControl.Designer.cs | 2 +- .../UI/MultiEditorControl.cs | 203 +++++++++++++-- 18 files changed, 1381 insertions(+), 69 deletions(-) create mode 100644 UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs diff --git a/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs b/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs index 12bcb59b..aad0effa 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs @@ -29,8 +29,9 @@ namespace UoFiddler.Plugin.MultiEditor.Classes /// The floors when they were set by hand, else null. /// The layers, bottom first, each with all its tiles by cell. /// Index of the active layer. + /// The houses placed with the House tool, each as a house draft, so they can be opened as drafts again; or null. internal sealed record DesignData(string Name, int Width, int Height, int FirstFloorZ, - List Levels, List Layers, int ActiveLayer); + List Levels, List Layers, int ActiveLayer, List Houses = null); /// /// The editor's own design file (*.uomd): XML with the size, the floors and one element per @@ -79,6 +80,14 @@ public static void Save(string path, DesignData design) } root.Add(layers); + + // Read by this editor from the first format version on: an editor that does not know + // the element skips it, so it needs no new version. + if (design.Houses is { Count: > 0 }) + { + root.Add(new XElement("Houses", design.Houses.Select(h => new XElement(h)))); + } + new XDocument(root).Save(path); } @@ -131,7 +140,8 @@ public static DesignData Load(string path) return new DesignData((string)root.Attribute("name") ?? string.Empty, width, height, (int?)root.Attribute("firstFloorZ") ?? 0, levels is { Count: > 0 } ? levels : null, - layers, (int?)layersElement?.Attribute("active") ?? 0); + layers, (int?)layersElement?.Attribute("active") ?? 0, + root.Element("Houses")?.Elements("House").Select(h => new XElement(h)).ToList()); } catch (Exception ex) when (ex is XmlException or FormatException or OverflowException or IndexOutOfRangeException or ArgumentNullException) { diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs index 59bec0c6..1ddff348 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs @@ -46,6 +46,9 @@ internal sealed class HouseDraft public bool Foundation { get; set; } + /// 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(); @@ -184,6 +187,7 @@ public void Edges(IReadOnlyList wings, int storey, out HashSet<(int X, south = new HashSet<(int X, int Y)>(); east = new HashSet<(int X, int Y)>(); Outline(region, south, east); + Partitions(wings, storey, south, east); foreach ((int x, int y) in AddedSouth[storey]) { if (region.Contains((x, y)) || region.Contains((x, y + 1))) @@ -204,6 +208,103 @@ public void Edges(IReadOnlyList wings, int storey, out HashSet<(int X, east.ExceptWith(ErasedEast[storey]); } + /// + /// The walls that divide each wing of a storey into its rooms (): + /// across the wing's longer side, evenly spaced, with the middle cell of each left open as + /// a doorway. A wing too short for that many rooms gets as many as fit two cells each. + /// + private static void Partitions(IReadOnlyList wings, int storey, HashSet<(int X, int Y)> south, HashSet<(int X, int Y)> east) + { + foreach (RoofWing wing in wings) + { + int width = wing.X1 - wing.X0, depth = wing.Y1 - wing.Y0; + bool alongX = width >= depth; + int length = alongX ? width : depth; + int rooms = Math.Min(Math.Clamp(wing.Rooms, 1, MaxRooms), length / 2); + if (wing.Storeys <= storey || rooms < 2) + { + continue; + } + + for (int i = 1; i < rooms; ++i) + { + int at = (int)Math.Round(i * length / (double)rooms); + if (alongX) + { + int doorway = wing.Y0 + 1 + ((depth - 1) / 2); + for (int y = wing.Y0 + 1; y <= wing.Y1; ++y) + { + if (y != doorway) + { + east.Add((wing.X0 + at, y)); + } + } + } + else + { + int doorway = wing.X0 + 1 + ((width - 1) / 2); + for (int x = wing.X0 + 1; x <= wing.X1; ++x) + { + if (x != doorway) + { + south.Add((x, wing.Y0 + at)); + } + } + } + } + } + } + + /// Moves everything changed by hand along with the house. + public void Shift(int dx, int dy) + { + static void Move(HashSet<(int X, int Y)> set, int dx, int dy) + { + var moved = new List<(int X, int Y)>(set.Count); + foreach ((int x, int y) in set) + { + moved.Add((x + dx, y + dy)); + } + + set.Clear(); + set.UnionWith(moved); + } + + for (int k = 0; k < MaxStoreys; ++k) + { + Move(AddedSouth[k], dx, dy); + Move(AddedEast[k], dx, dy); + Move(ErasedSouth[k], dx, dy); + Move(ErasedEast[k], dx, dy); + } + + var doors = new List>(Doors); + Doors.Clear(); + foreach (var door in doors) + { + Doors[(door.Key.Storey, door.Key.X + dx, door.Key.Y + dy)] = door.Value; + } + + var windows = new List<(int Storey, int X, int Y)>(Windows); + Windows.Clear(); + foreach ((int storey, int x, int y) in windows) + { + Windows.Add((storey, x + dx, y + dy)); + } + + for (int i = 0; i < FloorAreas.Count; ++i) + { + var a = FloorAreas[i]; + 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]; + Stairs[i] = (s.Storey, s.X + dx, s.Y + dy, s.Column, s.Style); + } + } + /// The tiles of a built draft, each with its layer, and the walls among them. public sealed class Built { @@ -323,6 +424,32 @@ public Built Build(IReadOnlyList wings, HouseStyles styles) } } + // 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 = 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)); + } + } + } + } + return built; } diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs new file mode 100644 index 00000000..2d3f0896 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs @@ -0,0 +1,244 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; +using UoFiddler.Plugin.MultiEditor.Tools; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// A house draft as XML: one House element with its wings, the materials of each storey + /// and everything changed by hand. It is what a house draft file (*.uohouse) holds, and what + /// a design file and the layers file keep of each house placed in a multi, so the house can + /// be opened as a draft again. Styles are kept by kind and name, as the client's tables name + /// them; one the client no longer has is left to the draft's defaults. + /// + internal static class HouseDraftFile + { + public const string Extension = "uohouse"; + + public const string Filter = "House draft (*.uohouse)|*.uohouse|All files (*.*)|*.*"; + + private const string _root = "House"; + + /// Format version of the element: raise it when an older editor would misread the content. + private const int _version = 1; + + public static XElement ToXml(IReadOnlyList wings, HouseDraft draft, string name) + { + var root = new XElement(_root, + new XAttribute("version", _version), + new XAttribute("name", LayerStore.XmlSafe(name ?? string.Empty, "House")), + new XAttribute("baseZ", wings.Count > 0 ? wings[0].EaveZ : draft.BaseZ), + new XAttribute("foundation", draft.Foundation)); + if (draft.RoofStyle != null) + { + root.Add(new XAttribute("roof", draft.RoofStyle.Name)); + } + + foreach (RoofWing wing in wings) + { + root.Add(new XElement("Wing", + new XAttribute("x0", wing.X0), new XAttribute("y0", wing.Y0), new XAttribute("x1", wing.X1), new XAttribute("y1", wing.Y1), + new XAttribute("storeys", wing.Storeys), + new XAttribute("rooms", wing.Rooms), + new XAttribute("roof", wing.NoRoof ? "None" : wing.Shape.ToString()), + new XAttribute("ridge", wing.RidgeAuto ? "Auto" : wing.RidgeAlongY ? "Y" : "X"))); + } + + for (int k = 0; k < HouseDraft.MaxStoreys; ++k) + { + var storey = new XElement("Storey", new XAttribute("index", k)); + if (draft.WallStyles[k] != null) + { + storey.Add(new XAttribute("walls", draft.WallStyles[k].Name)); + } + + if (draft.FloorStyles[k] != null) + { + storey.Add(new XAttribute("floor", draft.FloorStyles[k].Name)); + } + + AddCells(storey, "addedSouth", draft.AddedSouth[k]); + AddCells(storey, "addedEast", draft.AddedEast[k]); + AddCells(storey, "erasedSouth", draft.ErasedSouth[k]); + AddCells(storey, "erasedEast", draft.ErasedEast[k]); + AddCells(storey, "windows", draft.Windows.Where(w => w.Storey == k).Select(w => (w.X, w.Y))); + root.Add(storey); + } + + foreach (var door in draft.Doors) + { + root.Add(new XElement("Door", new XAttribute("storey", door.Key.Storey), new XAttribute("x", door.Key.X), new XAttribute("y", door.Key.Y), + new XAttribute("style", door.Value.Style.Name), new XAttribute("piece", door.Value.Piece))); + } + + foreach ((int storey, int x0, int y0, int x1, int y1, HouseStyle style) in draft.FloorAreas) + { + root.Add(new XElement("FloorArea", new XAttribute("storey", storey), new XAttribute("x0", x0), new XAttribute("y0", y0), + new XAttribute("x1", x1), new XAttribute("y1", y1), new XAttribute("style", style.Name))); + } + + foreach ((int storey, int x, int y, string column, HouseStyle style) in draft.Stairs) + { + root.Add(new XElement("Stairs", new XAttribute("storey", storey), new XAttribute("x", x), new XAttribute("y", y), + new XAttribute("column", column), new XAttribute("style", style.Name))); + } + + return root; + } + + private static void AddCells(XElement element, string name, IEnumerable<(int X, int Y)> cells) + { + string text = string.Join(" ", cells.Select(c => $"{c.X.ToString(CultureInfo.InvariantCulture)},{c.Y.ToString(CultureInfo.InvariantCulture)}")); + if (text.Length > 0) + { + element.Add(new XAttribute(name, text)); + } + } + + private static IEnumerable<(int X, int Y)> Cells(XElement element, string name) + { + foreach (string cell in ((string)element.Attribute(name) ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + string[] parts = cell.Split(','); + yield return (int.Parse(parts[0], CultureInfo.InvariantCulture), int.Parse(parts[1], CultureInfo.InvariantCulture)); + } + } + + /// + /// Reads a house back. gives the styles for anything the + /// element does not name or the client no longer has. Throws + /// when the element is not a house or is damaged. + /// + public static (List Wings, HouseDraft Draft, string Name) FromXml(XElement root, HouseStyles styles, HouseDraft materials) + { + try + { + if (root == null || root.Name.LocalName != _root) + { + throw new InvalidDataException("This is not a house draft."); + } + + if (((int?)root.Attribute("version") ?? 0) > _version) + { + throw new InvalidDataException("This house draft was saved by a newer multi editor."); + } + + HouseStyle Style(HousePartKind kind, string name) => + name == null ? null : styles.Styles.FirstOrDefault(s => s.Kind == kind && string.Equals(s.Name, name, StringComparison.Ordinal)); + + HouseDraft draft = materials.Fresh(); + int baseZ = (int?)root.Attribute("baseZ") ?? 0; + draft.BaseZ = baseZ; + draft.Foundation = (bool?)root.Attribute("foundation") ?? false; + // A draft saved before rooms were set per wing names one count for the house. + int houseRooms = (int?)root.Attribute("rooms") ?? 1; + draft.RoofStyle = Style(HousePartKind.Roof, (string)root.Attribute("roof")) ?? draft.RoofStyle; + + var wings = new List(); + foreach (XElement element in root.Elements("Wing")) + { + string roof = (string)element.Attribute("roof") ?? "Gable"; + string ridge = (string)element.Attribute("ridge") ?? "Auto"; + var wing = new RoofWing + { + X0 = (int)element.Attribute("x0"), Y0 = (int)element.Attribute("y0"), + X1 = (int)element.Attribute("x1"), Y1 = (int)element.Attribute("y1"), + EaveZ = baseZ, + Storeys = Math.Clamp((int?)element.Attribute("storeys") ?? 1, 1, HouseDraft.MaxStoreys), + Rooms = Math.Clamp((int?)element.Attribute("rooms") ?? houseRooms, 1, HouseDraft.MaxRooms), + NoRoof = roof == "None", + Shape = Enum.TryParse(roof, out RoofShape shape) ? shape : RoofShape.Gable, + RidgeAuto = ridge == "Auto" + }; + wing.RidgeAlongY = wing.RidgeAuto + ? RoofPlanner.RidgeAlongY((wing.X0 + 1, wing.Y0 + 1, wing.X1 + 1, wing.Y1 + 1)) + : ridge == "Y"; + if (wing.X1 - wing.X0 >= 2 && wing.Y1 - wing.Y0 >= 2) + { + wings.Add(wing); + } + } + + foreach (XElement element in root.Elements("Storey")) + { + int k = (int?)element.Attribute("index") ?? -1; + if (k < 0 || k >= HouseDraft.MaxStoreys) + { + continue; + } + + draft.WallStyles[k] = Style(HousePartKind.Wall, (string)element.Attribute("walls")) ?? draft.WallStyles[k]; + draft.FloorStyles[k] = Style(HousePartKind.Floor, (string)element.Attribute("floor")) ?? draft.FloorStyles[k]; + draft.AddedSouth[k].UnionWith(Cells(element, "addedSouth")); + draft.AddedEast[k].UnionWith(Cells(element, "addedEast")); + draft.ErasedSouth[k].UnionWith(Cells(element, "erasedSouth")); + draft.ErasedEast[k].UnionWith(Cells(element, "erasedEast")); + foreach ((int x, int y) in Cells(element, "windows")) + { + draft.Windows.Add((k, x, y)); + } + } + + foreach (XElement element in root.Elements("Door")) + { + if (Style(HousePartKind.Door, (string)element.Attribute("style")) is { } style && (string)element.Attribute("piece") is { } piece) + { + draft.Doors[((int)element.Attribute("storey"), (int)element.Attribute("x"), (int)element.Attribute("y"))] = (style, piece); + } + } + + foreach (XElement element in root.Elements("FloorArea")) + { + if (Style(HousePartKind.Floor, (string)element.Attribute("style")) is { } style) + { + draft.FloorAreas.Add(((int)element.Attribute("storey"), (int)element.Attribute("x0"), (int)element.Attribute("y0"), + (int)element.Attribute("x1"), (int)element.Attribute("y1"), style)); + } + } + + foreach (XElement element in root.Elements("Stairs")) + { + if (Style(HousePartKind.Stair, (string)element.Attribute("style")) is { } style && (string)element.Attribute("column") is { } column) + { + draft.Stairs.Add(((int)element.Attribute("storey"), (int)element.Attribute("x"), (int)element.Attribute("y"), column, style)); + } + } + + return (wings, draft, (string)root.Attribute("name") ?? "House"); + } + catch (Exception ex) when (ex is XmlException or FormatException or OverflowException or IndexOutOfRangeException or ArgumentNullException) + { + throw new InvalidDataException("The house draft is damaged: " + ex.Message, ex); + } + } + + /// The same house moved by a number of cells. + public static XElement Shifted(XElement house, int dx, int dy, HouseStyles styles) + { + var (wings, draft, name) = FromXml(house, styles, new HouseDraft()); + foreach (RoofWing wing in wings) + { + (wing.X0, wing.X1, wing.Y0, wing.Y1) = (wing.X0 + dx, wing.X1 + dx, wing.Y0 + dy, wing.Y1 + dy); + } + + draft.Shift(dx, dy); + return ToXml(wings, draft, name); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs b/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs index 126f0d43..0fc322de 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs @@ -46,7 +46,8 @@ public static string FilePath(int clientId) /// Keeps the layers of a multi saved to the client. A design with only the one plain layer /// every design starts with has nothing to keep, and an older set for the same tiles goes. /// - public static void Save(int clientId, List layers, int activeIndex, long fingerprint) + /// The houses placed with the House tool, as house drafts with cells counted from the save origin. + public static void Save(int clientId, List layers, int activeIndex, long fingerprint, IReadOnlyList houses = null) { string path = FilePath(clientId); string multi = fingerprint.ToString(CultureInfo.InvariantCulture); @@ -66,6 +67,11 @@ public static void Save(int clientId, List layers, int activeIndex, TilesText(layer.Tiles))); } + foreach (XElement house in houses ?? Array.Empty()) + { + set.Add(new XElement(house)); + } + sets.Insert(0, set); } @@ -87,7 +93,7 @@ public static void Save(int clientId, List layers, int activeIndex, /// Reads the layers kept for a client multi with these tiles. Null when there are none or /// the file cannot be read. /// - public static (List Layers, int Active)? Load(int clientId, long fingerprint) + public static (List Layers, int Active, List Houses)? Load(int clientId, long fingerprint) { try { @@ -105,7 +111,7 @@ public static (List Layers, int Active)? Load(int clientId, long fin (bool?)element.Attribute("visible") ?? true, (bool?)element.Attribute("inFile") ?? true, ParseTiles(element.Value))); } - return layers.Count == 0 ? null : (layers, (int?)set.Attribute("active") ?? 0); + return layers.Count == 0 ? null : (layers, (int?)set.Attribute("active") ?? 0, set.Elements("House").Select(h => new XElement(h)).ToList()); } catch (Exception ex) when (ex is FormatException or IndexOutOfRangeException or OverflowException) { diff --git a/UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs b/UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs index 09c44867..92e74e12 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/RoofPlanner.cs @@ -18,7 +18,16 @@ namespace UoFiddler.Plugin.MultiEditor.Classes internal enum RoofShape { /// Two slopes meeting in a ridge. - Gable + 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 } /// @@ -34,6 +43,11 @@ internal enum RoofShape /// 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 @@ -41,6 +55,15 @@ 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; @@ -56,9 +79,9 @@ public static bool RidgeAlongY((int X0, int Y0, int X1, int Y1) box) /// /// 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 cell it - /// raises loses any fixed piece another wing gave it in . - /// Cells with a negative coordinate are left out. + /// 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) @@ -71,6 +94,23 @@ public static void AddWing(Dictionary<(int X, int Y), int> heights, Dictionary<( { 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) { @@ -78,7 +118,14 @@ public static void AddWing(Dictionary<(int X, int Y), int> heights, Dictionary<( } heights[(x, y)] = z; - fixedPieces.Remove((x, y)); + if (corner != null) + { + fixedPieces[(x, y)] = corner; + } + else + { + fixedPieces.Remove((x, y)); + } } } } diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs index 52a88e3b..42a0bb52 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs @@ -239,7 +239,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,6 +247,7 @@ 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); diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs index 5ff747ce..35839679 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs @@ -109,6 +109,9 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles) 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); @@ -215,6 +218,10 @@ public bool Undo() (tool is HouseTool || _toolKind == ToolKind.Roof)) { tool.Reopen(); + if (tool is HouseTool reopened && reopened.LastPlaced != null) + { + _placedHouses.Remove(reopened.LastPlaced); + } } } @@ -242,6 +249,10 @@ public bool Redo() } open.CloseReopened(); + if (open is HouseTool closed && closed.LastPlaced != null && !_placedHouses.Contains(closed.LastPlaced)) + { + _placedHouses.Add(closed.LastPlaced); + } } if (!CompList.RedoStep()) @@ -259,6 +270,7 @@ private void SetDocument(MultiEditorComponentList list) CancelTool(); Roof.Reset(); House.Reset(); + _placedHouses.Clear(); CompList = list; _selection.Clear(); HoverTile = null; @@ -467,6 +479,103 @@ public static bool IsTileTool(ToolKind kind) /// The roof tool, for its shape options (ridge, gables, gable fill) and the roof being shaped. public RoofTool Roof => (RoofTool)_tools[ToolKind.Roof]; + // ---------------------------------------------------------------- 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]; diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs index aa0b3313..d750d47c 100644 --- a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs +++ b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs @@ -29,7 +29,8 @@ internal sealed class SceneRenderer : IDisposable, IToolOverlay private static readonly SpriteTint _belowLevel = new SpriteTint(0.55f, 0.55f, 0.55f, 1f, 0f, 0f, 0f); private static readonly SpriteTint _transparent = SpriteTint.Alpha(0.3f); private static readonly SpriteTint _standable = new SpriteTint(0.6f, 1f, 0.6f, 1f, 0f, 0.3f, 0f); - private static readonly SpriteTint _toolGhost = new SpriteTint(1f, 1f, 1f, 0.6f, 0f, 0.08f, 0.16f); + // Tiles a tool is about to place: see-through by the setting, with a little blue so they differ from placed ones. + private SpriteTint _toolGhost = new SpriteTint(1f, 1f, 1f, 0.8f, 0f, 0.08f, 0.16f); private static readonly SpriteTint _removeMark = new SpriteTint(1f, 0.3f, 0.3f, 0.85f, 0.45f, 0f, 0f); private static readonly SpriteTint _reference = new SpriteTint(0.7f, 0.8f, 1f, 0.4f, 0f, 0.05f, 0.15f); @@ -81,6 +82,7 @@ public void Draw(EditorSession session, Camera2D camera, Size viewport) _marqueeLine = settings.SelectionBox; _marqueeFill = Color.FromArgb(40, settings.SelectionBox); _workPlane = SpriteTint.Solid(settings.WorkPlane); + _toolGhost = new SpriteTint(1f, 1f, 1f, settings.PreviewOpacity / 100f, 0f, 0.08f, 0.16f); if (!session.HasDocument) { diff --git a/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs index bab2fdd7..9baae6f3 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/HouseTool.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Xml.Linq; using UoFiddler.Plugin.MultiEditor.Classes; namespace UoFiddler.Plugin.MultiEditor.Tools @@ -30,6 +31,7 @@ internal sealed class HouseTool : WingDraftTool private readonly RoofTool _roof; private HouseDraft _draft = new HouseDraft(); private int _storeys = 1; + private int _rooms = 1; private RoofShape _shape = RoofShape.Gable; private bool _noRoof; private RoofRidge _ridge = RoofRidge.Auto; @@ -53,9 +55,12 @@ public HouseTool(IEditorContext context, RoofTool roof) : base(context) /// Storeys of the tallest wing; 1 before there is one. public int TopStorey => Math.Max(1, HouseDraft.Top(Wings)); - /// Storeys of new wings. + /// Storeys of the selected wing, else of the wings drawn next. public int Storeys => SelectedWing?.Storeys ?? _storeys; + /// Rooms of the selected wing, else of the wings drawn next. + public int Rooms => SelectedWing?.Rooms ?? _rooms; + public RoofShape Shape => SelectedWing?.Shape ?? _shape; public bool NoRoof => SelectedWing?.NoRoof ?? _noRoof; @@ -81,6 +86,47 @@ protected override bool Ready protected override bool GhostsFollowView => true; + // What the preview shows. A view choice: it is no step of the history and what is placed + // is always the whole house. + private bool _showWalls = true; + private bool _showFloors = true; + private bool _showRoof = true; + + /// Walls, doors, windows, stairs and the foundation in the preview. + public bool ShowWalls + { + get => _showWalls; + set => SetShown(ref _showWalls, value); + } + + /// Floors in the preview: off to look at the walls of a storey without the floor above. + public bool ShowFloors + { + get => _showFloors; + set => SetShown(ref _showFloors, value); + } + + /// The roof and its gable ends in the preview. + public bool ShowRoof + { + get => _showRoof; + set => SetShown(ref _showRoof, value); + } + + private void SetShown(ref bool field, bool value) + { + if (field != value) + { + field = value; + RaiseChanged(); + } + } + + protected override bool ShowsInPreview(string layer) + { + return layer == HouseDraft.FloorsLayer ? _showFloors : layer == RoofTool.LayerName ? _showRoof : _showWalls; + } + /// /// Storeys without a material take the one below; the ground floor and the roof take the /// first style the client has, until one is chosen. @@ -133,9 +179,10 @@ protected override List WingsFor(int startX, int startY, int endX, int var wing = new RoofWing { - X0 = x0, Y0 = y0, X1 = x1, Y1 = y1, EaveZ = z, Storeys = _storeys, + X0 = x0, Y0 = y0, X1 = x1, Y1 = y1, EaveZ = z, Storeys = _storeys, Rooms = _rooms, Shape = _shape, NoRoof = _noRoof, RidgeAuto = _ridge == RoofRidge.Auto }; + Snap(wing, moved: false); wing.RidgeAlongY = wing.RidgeAuto ? RoofPlanner.RidgeAlongY(RoofBox(wing)) : _ridge == RoofRidge.AlongY; wings.Add(wing); return wings; @@ -143,6 +190,47 @@ protected override List WingsFor(int startX, int startY, int endX, int private static (int X0, int Y0, int X1, int Y1) RoofBox(RoofWing wing) => (wing.X0 + 1, wing.Y0 + 1, wing.X1 + 1, wing.Y1 + 1); + /// + /// A wing drawn or moved to stand right beside another would leave two walls back to back + /// and its roof a cell short of the other's wall. It is pulled in by that cell, so the two + /// share the wall between them: one house inside, and the lower roof runs up to the + /// higher wall. + /// + protected override void Snap(RoofWing wing, bool moved) + { + foreach (RoofWing other in Wings) + { + if (ReferenceEquals(other, wing)) + { + continue; + } + + bool besideX = wing.Y0 <= other.Y1 && wing.Y1 >= other.Y0; + bool besideY = wing.X0 <= other.X1 && wing.X1 >= other.X0; + if (besideX && wing.X0 == other.X1 + 1) + { + wing.X0 -= 1; + wing.X1 -= moved ? 1 : 0; + } + else if (besideX && wing.X1 == other.X0 - 1) + { + wing.X1 += 1; + wing.X0 += moved ? 1 : 0; + } + + if (besideY && wing.Y0 == other.Y1 + 1) + { + wing.Y0 -= 1; + wing.Y1 -= moved ? 1 : 0; + } + else if (besideY && wing.Y1 == other.Y0 - 1) + { + wing.Y1 += 1; + wing.Y0 += moved ? 1 : 0; + } + } + } + protected override void WingResized(RoofWing wing) { if (wing.RidgeAuto) @@ -240,6 +328,118 @@ public void SetBaseZ(int z) }); } + /// Divides the selected wing, and the wings drawn next, into this many rooms on every storey (1: undivided). + public void SetRooms(int rooms) + { + rooms = Math.Clamp(rooms, 1, HouseDraft.MaxRooms); + _rooms = rooms; + if (SelectedWing is { } wing && wing.Rooms != rooms) + { + Edit(() => wing.Rooms = rooms); + } + else + { + RaiseChanged(); + } + } + + // ---------------------------------------------------------------- layers + + private static readonly string[] _parts = + { + HouseDraft.FoundationLayer, HouseDraft.WallsLayer, HouseDraft.FloorsLayer, HouseDraft.StairsLayer, RoofTool.LayerName + }; + + // The name the house being placed gets: of the house it was reopened from, else a free one. + private string _placeName; + private string _reopenedName; + + /// Gives a name no placed house and no layer of the multi has yet. + public Func FreeName { get; set; } + + /// True when a placed house's parts each go on a layer of their own instead of one layer named after the house. + public static bool LayerPerPart => !UI.EditorSettings.Current.HouseOnOneLayer; + + private string PlaceName => _placeName ??= _reopenedName ?? FreeName?.Invoke() ?? "House"; + + /// The house's parts go on the layer named after the house; a tile that names another layer (a re-pieced older roof) keeps it. + protected override string LayerFor(string layer) + { + return !LayerPerPart && (layer == null || Array.IndexOf(_parts, layer) >= 0) ? PlaceName : layer; + } + + // ---------------------------------------------------------------- drafts kept outside the tool + + /// The house last placed, as it is kept with the multi. + public XElement LastPlaced { get; private set; } + + /// Raised when a house was placed, with what is kept of it. + public event Action Placed; + + /// The draft as XML: what a house draft file holds. + public XElement ToXml(string name) + { + return HouseDraftFile.ToXml(Wings, _draft, name); + } + + /// + /// Makes a saved house the draft, in place of the one being worked on (a step of the + /// history). A house reaching past the multi's first row or column is moved inside. + /// + public void OpenXml(XElement house, bool keepName = false) + { + EnsureMaterials(); + _reopenedName = keepName ? (string)house.Attribute("name") : null; + var (wings, draft, _) = HouseDraftFile.FromXml(house, Context.HouseStyles, _draft); + if (wings.Count == 0) + { + throw new System.IO.InvalidDataException("The house draft has no wings."); + } + + int dx = Math.Max(0, -wings.Min(w => w.X0)), dy = Math.Max(0, -wings.Min(w => w.Y0)); + if (dx != 0 || dy != 0) + { + foreach (RoofWing wing in wings) + { + (wing.X0, wing.X1, wing.Y0, wing.Y1) = (wing.X0 + dx, wing.X1 + dx, wing.Y0 + dy, wing.Y1 + dy); + } + + draft.Shift(dx, dy); + } + + LoadWings(wings); + _draft = draft; + ++_version; + RaiseChanged(); + } + + /// The tiles a saved house builds, each with its layer: what placing it put into the multi. + public List<(ushort Id, int X, int Y, int Z, string Layer)> TilesOf(XElement house) + { + EnsureMaterials(); + var (wings, draft, _) = HouseDraftFile.FromXml(house, Context.HouseStyles, _draft); + HouseDraft own = _draft; + _draft = draft; + ++_version; + try + { + return new List<(ushort Id, int X, int Y, int Z, string Layer)>(Plan(wings).Add); + } + finally + { + _draft = own; + ++_version; + } + } + + protected override void OnPlaced() + { + LastPlaced = ToXml(PlaceName); + _placeName = null; + _reopenedName = null; + Placed?.Invoke(LastPlaced); + } + public void SetFoundation(bool on) { if (_draft.Foundation != on) @@ -436,7 +636,7 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z EnsureMaterials(); string key = string.Join(";", wings.Select(w => - $"{w.X0},{w.Y0},{w.X1},{w.Y1},{w.EaveZ},{w.Storeys},{w.Shape},{w.NoRoof},{w.RidgeAlongY}")) + + $"{w.X0},{w.Y0},{w.X1},{w.Y1},{w.EaveZ},{w.Storeys},{w.Rooms},{w.Shape},{w.NoRoof},{w.RidgeAlongY}")) + $"|{_version}|{_roof.Gables}|{_roof.GableFill}|{Context.CompList.UndoList.Count}|{Context.CompList.RedoList.Count}"; if (key == _builtFor) { @@ -471,7 +671,7 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z var roofWings = new List(); foreach (RoofWing wing in wings) { - if (wing.NoRoof) + if (wing.NoRoof || wing.Shape == RoofShape.Flat) { continue; } @@ -484,12 +684,14 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z if (roofWings.Count > 0 && _draft.RoofStyle != null) { - // A lower wing's roof stops at the walls of a taller one. + // A lower wing's roof stops at the walls of a taller one. A roof piece is seen half a + // cell before its own cell, and the walls stand on the far edges of theirs: the + // first row and column inside a north or west wall still reach it from outside. bool Hidden(int x, int y, int z) { foreach (RoofWing wing in wings) { - if (x >= wing.X0 && x <= wing.X1 && y >= wing.Y0 && y <= wing.Y1 && + if (x >= wing.X0 + 2 && x <= wing.X1 && y >= wing.Y0 + 2 && y <= wing.Y1 && z < baseZ + (wing.Storeys * HouseDraft.StoreyHeight)) { return true; @@ -499,11 +701,16 @@ bool Hidden(int x, int y, int z) return false; } - var (roofRemove, roofAdd) = _roof.PlanRoof(roofWings, _draft.RoofStyle, built.Walls, Hidden); - remove.AddRange(roofRemove); - foreach (var (id, x, y, z, layer) in roofAdd) + // Wings of the same height share one roof; a lower wing has a roof of its own, which + // lies under the eaves of a taller one where the two meet. + foreach (IGrouping level in roofWings.GroupBy(r => r.EaveZ)) { - add.Add((id, x, y, z, layer ?? RoofTool.LayerName)); + var (roofRemove, roofAdd) = _roof.PlanRoof(level.ToList(), _draft.RoofStyle, built.Walls, Hidden); + remove.AddRange(roofRemove.Where(t => !remove.Contains(t))); + foreach (var (id, x, y, z, layer) in roofAdd) + { + add.Add((id, x, y, z, layer ?? RoofTool.LayerName)); + } } } diff --git a/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs index d76afbdc..ee1f8871 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/RoofTool.cs @@ -291,7 +291,23 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z foreach ((int x, int y) in footprint) { - if (!fixedPieces.TryGetValue((x, y), out string column)) + int lift = 0; + if (fixedPieces.TryGetValue((x, y), out string column)) + { + // A hip's corner piece names how far below the slopes it sits. + int mark = column.IndexOf(RoofPlanner.LiftMark); + if (mark > 0) + { + lift = int.Parse(column.AsSpan(mark + 1)); + column = column.Substring(0, mark); + if (style.Get(column) == 0) + { + // A style without corner pieces: the slope facing the same way. + (column, lift) = (column[0] switch { 'N' => "North", 'E' => "East", 'S' => "South", _ => "West" }, 0); + } + } + } + else { column = RoofPlanner.Piece(heights, x, y, out string fallback) ?? (wings[0].RidgeAlongY ? "West" : "North"); if (style.Get(column) == 0 && fallback != null) @@ -303,7 +319,7 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z ushort id = style.Get(column); if (id != 0) { - add.Add((id, x, y, heights[(x, y)], null)); + add.Add((id, x, y, heights[(x, y)] + lift, null)); } } diff --git a/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs index 5d4ed7d5..293de389 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/WingDraftTool.cs @@ -41,6 +41,12 @@ internal sealed class RoofWing /// 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; + public RoofShape Shape { get; set; } public bool RidgeAlongY { get; set; } @@ -56,6 +62,7 @@ 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; } } @@ -189,6 +196,12 @@ public int SelectedIndex /// True when the draft is drawn only up to the highest Z the view shows (the chosen floor, the height slider). protected virtual bool GhostsFollowView => false; + /// The layer of the multi that tiles planned for a layer are placed on: the same one, unless the tool gathers them. + protected virtual string LayerFor(string layer) => layer; + + /// True when the tiles a draft puts on a layer are drawn in its preview. What is placed does not depend on it. + protected virtual bool ShowsInPreview(string layer) => true; + /// What the draft holds beside its wings, for the undo history. protected virtual object CaptureExtra() => null; @@ -196,6 +209,28 @@ protected virtual void RestoreExtra(object extra) { } + /// Called when the draft was written to the multi, before it is cleared. + protected virtual void OnPlaced() + { + } + + /// Makes these wings the draft, as one step of its history. + protected void LoadWings(List wings) + { + CancelDrag(); + Remember(); + _wings = wings; + _selected = wings.Count > 0 ? 0 : -1; + } + + /// + /// Called while a wing is moved or resized, to pull it into line with the other wings. + /// A moved wing is shifted whole; a resized one has the side in question moved. + /// + protected virtual void Snap(RoofWing wing, bool moved) + { + } + /// Called when a wing's box changed. protected virtual void WingResized(RoofWing wing) { @@ -476,7 +511,7 @@ public void Commit() { int steps = Context.CompList.UndoList.Count; object top = steps > 0 ? Context.CompList.UndoList[0] : null; - Context.CompList.ReplaceTilesOnLayers(remove, add, ActionName, DefaultLayer); + Context.CompList.ReplaceTilesOnLayers(remove, add.Select(a => (a.Id, a.X, a.Y, a.Z, LayerFor(a.Layer))), ActionName, DefaultLayer); Context.AfterEdit(add.Count > 0 ? add.Max(a => a.Z) : null); object placedBy = Context.CompList.UndoList.Count > 0 ? Context.CompList.UndoList[0] : null; if (placedBy != null && !ReferenceEquals(placedBy, top)) @@ -484,6 +519,7 @@ public void Commit() _placed = Capture(); _placedHistory = new List(_undo); PlacedBy = placedBy; + OnPlaced(); } Committed?.Invoke(); @@ -586,6 +622,7 @@ private void DragWing() dx = Math.Max(dx, -_before.X0); dy = Math.Max(dy, -_before.Y0); (wing.X0, wing.X1, wing.Y0, wing.Y1) = (_before.X0 + dx, _before.X1 + dx, _before.Y0 + dy, _before.Y1 + dy); + Snap(wing, moved: true); return; } @@ -593,6 +630,7 @@ private void DragWing() wing.X1 = _east ? Math.Max(_before.X1 + dx, _before.X0) : _before.X1; wing.Y0 = _north ? Math.Clamp(_before.Y0 + dy, 0, _before.Y1) : _before.Y0; wing.Y1 = _south ? Math.Max(_before.Y1 + dy, _before.Y0) : _before.Y1; + Snap(wing, moved: false); WingResized(wing); } @@ -640,9 +678,9 @@ public void PaintDraft(IToolOverlay overlay, bool active) // A house is looked into like the multi: storeys above the chosen floor are left out. int highest = GhostsFollowView ? Context.MaxHeight : int.MaxValue; - foreach (var (id, x, y, z, _) in add) + foreach (var (id, x, y, z, layer) in add) { - if (z <= highest) + if (z <= highest && ShowsInPreview(layer)) { overlay.Ghost(id, x, y, z); } diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs index 5b1006ca..e336e33d 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettings.cs @@ -56,6 +56,15 @@ internal sealed class EditorSettings public Color SelectionBox { get; set; } = Color.DodgerBlue; + /// + /// True puts a placed house on one layer named after it ("House 1"); false gives its + /// foundation, walls, floors, stairs and roof a layer each. + /// + public bool HouseOnOneLayer { get; set; } = true; + + /// How solid the tiles a tool is about to place are drawn (roof and house drafts, walls, stamps), in percent. + public int PreviewOpacity { get; set; } = 80; + // How a new document starts. public bool StartWithWorkPlane { get; set; } = true; @@ -138,6 +147,7 @@ public static void Load() settings.Background = Color.Empty; } + settings.PreviewOpacity = Math.Clamp(settings.PreviewOpacity, 20, 100); settings.TileBrowserWidth = Math.Clamp(settings.TileBrowserWidth, 200, 900); settings.InspectorWidth = Math.Clamp(settings.InspectorWidth, 200, 600); Current = settings; diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs index 0050485f..a84a3270 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.Designer.cs @@ -34,6 +34,9 @@ private void InitializeComponent() labelWorkPlane = new System.Windows.Forms.Label(); labelWorkPlaneOpacity = new System.Windows.Forms.Label(); alphaWorkPlane = new System.Windows.Forms.NumericUpDown(); + labelPreview = new System.Windows.Forms.Label(); + labelPreviewOpacity = new System.Windows.Forms.Label(); + alphaPreview = new System.Windows.Forms.NumericUpDown(); swatchWorkPlane = new System.Windows.Forms.Button(); labelGrid = new System.Windows.Forms.Label(); labelGridOpacity = new System.Windows.Forms.Label(); @@ -49,10 +52,12 @@ private void InitializeComponent() checkWorkPlane = new System.Windows.Forms.CheckBox(); checkGrid = new System.Windows.Forms.CheckBox(); checkHideFloorsAbove = new System.Windows.Forms.CheckBox(); + checkHouseOneLayer = new System.Windows.Forms.CheckBox(); buttonDefaults = new System.Windows.Forms.Button(); buttonOk = new System.Windows.Forms.Button(); buttonCancel = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)alphaWorkPlane).BeginInit(); + ((System.ComponentModel.ISupportInitialize)alphaPreview).BeginInit(); ((System.ComponentModel.ISupportInitialize)alphaGrid).BeginInit(); ((System.ComponentModel.ISupportInitialize)alphaOutline).BeginInit(); SuspendLayout(); @@ -223,11 +228,41 @@ private void InitializeComponent() swatchSelection.TabIndex = 20; swatchSelection.UseVisualStyleBackColor = true; swatchSelection.Click += SwatchSelection_Click; + // + // labelPreview + // + labelPreview.AutoSize = true; + labelPreview.Location = new System.Drawing.Point(24, 190); + labelPreview.Name = "labelPreview"; + labelPreview.Size = new System.Drawing.Size(190, 15); + labelPreview.TabIndex = 30; + labelPreview.Text = "Preview of what a tool will place"; + // + // labelPreviewOpacity + // + labelPreviewOpacity.AutoSize = true; + labelPreviewOpacity.Location = new System.Drawing.Point(272, 190); + labelPreviewOpacity.Name = "labelPreviewOpacity"; + labelPreviewOpacity.Size = new System.Drawing.Size(62, 15); + labelPreviewOpacity.TabIndex = 31; + labelPreviewOpacity.Text = "Opacity %"; + // + // alphaPreview + // + alphaPreview.Increment = new decimal(new int[] { 5, 0, 0, 0 }); + alphaPreview.Location = new System.Drawing.Point(340, 187); + alphaPreview.Maximum = new decimal(new int[] { 100, 0, 0, 0 }); + alphaPreview.Minimum = new decimal(new int[] { 20, 0, 0, 0 }); + alphaPreview.Name = "alphaPreview"; + alphaPreview.Size = new System.Drawing.Size(56, 23); + alphaPreview.TabIndex = 32; + alphaPreview.Value = new decimal(new int[] { 80, 0, 0, 0 }); + alphaPreview.ValueChanged += AlphaPreview_ValueChanged; // // headingStart // headingStart.AutoSize = true; - headingStart.Location = new System.Drawing.Point(12, 194); + headingStart.Location = new System.Drawing.Point(12, 224); headingStart.Name = "headingStart"; headingStart.Size = new System.Drawing.Size(202, 15); headingStart.TabIndex = 21; @@ -236,7 +271,7 @@ private void InitializeComponent() // checkWorkPlane // checkWorkPlane.AutoSize = true; - checkWorkPlane.Location = new System.Drawing.Point(24, 218); + checkWorkPlane.Location = new System.Drawing.Point(24, 248); checkWorkPlane.Name = "checkWorkPlane"; checkWorkPlane.Size = new System.Drawing.Size(129, 19); checkWorkPlane.TabIndex = 23; @@ -247,7 +282,7 @@ private void InitializeComponent() // checkGrid // checkGrid.AutoSize = true; - checkGrid.Location = new System.Drawing.Point(24, 242); + checkGrid.Location = new System.Drawing.Point(24, 272); checkGrid.Name = "checkGrid"; checkGrid.Size = new System.Drawing.Size(86, 19); checkGrid.TabIndex = 24; @@ -258,17 +293,28 @@ private void InitializeComponent() // checkHideFloorsAbove // checkHideFloorsAbove.AutoSize = true; - checkHideFloorsAbove.Location = new System.Drawing.Point(24, 266); + checkHideFloorsAbove.Location = new System.Drawing.Point(24, 296); checkHideFloorsAbove.Name = "checkHideFloorsAbove"; checkHideFloorsAbove.Size = new System.Drawing.Size(365, 19); checkHideFloorsAbove.TabIndex = 25; checkHideFloorsAbove.Text = "Floors above the active one hidden (off: drawn faintly)"; checkHideFloorsAbove.UseVisualStyleBackColor = true; checkHideFloorsAbove.CheckedChanged += CheckHideFloorsAbove_CheckedChanged; + // + // checkHouseOneLayer + // + checkHouseOneLayer.AutoSize = true; + checkHouseOneLayer.Location = new System.Drawing.Point(24, 326); + checkHouseOneLayer.Name = "checkHouseOneLayer"; + checkHouseOneLayer.Size = new System.Drawing.Size(365, 19); + checkHouseOneLayer.TabIndex = 33; + checkHouseOneLayer.Text = "A placed house goes on one layer (off: one per part)"; + checkHouseOneLayer.UseVisualStyleBackColor = true; + checkHouseOneLayer.CheckedChanged += CheckHouseOneLayer_CheckedChanged; // // buttonDefaults // - buttonDefaults.Location = new System.Drawing.Point(12, 302); + buttonDefaults.Location = new System.Drawing.Point(12, 362); buttonDefaults.Name = "buttonDefaults"; buttonDefaults.Size = new System.Drawing.Size(80, 23); buttonDefaults.TabIndex = 26; @@ -279,7 +325,7 @@ private void InitializeComponent() // buttonOk // buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - buttonOk.Location = new System.Drawing.Point(236, 302); + buttonOk.Location = new System.Drawing.Point(236, 362); buttonOk.Name = "buttonOk"; buttonOk.Size = new System.Drawing.Size(76, 23); buttonOk.TabIndex = 27; @@ -289,7 +335,7 @@ private void InitializeComponent() // buttonCancel // buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - buttonCancel.Location = new System.Drawing.Point(320, 302); + buttonCancel.Location = new System.Drawing.Point(320, 362); buttonCancel.Name = "buttonCancel"; buttonCancel.Size = new System.Drawing.Size(76, 23); buttonCancel.TabIndex = 28; @@ -302,7 +348,7 @@ private void InitializeComponent() AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; CancelButton = buttonCancel; - ClientSize = new System.Drawing.Size(410, 340); + ClientSize = new System.Drawing.Size(410, 400); Controls.Add(headingColours); Controls.Add(labelBackground); Controls.Add(swatchBackground); @@ -320,10 +366,14 @@ private void InitializeComponent() Controls.Add(swatchOutline); Controls.Add(labelSelection); Controls.Add(swatchSelection); + Controls.Add(labelPreview); + Controls.Add(labelPreviewOpacity); + Controls.Add(alphaPreview); Controls.Add(headingStart); Controls.Add(checkWorkPlane); Controls.Add(checkGrid); Controls.Add(checkHideFloorsAbove); + Controls.Add(checkHouseOneLayer); Controls.Add(buttonDefaults); Controls.Add(buttonOk); Controls.Add(buttonCancel); @@ -335,6 +385,7 @@ private void InitializeComponent() StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; Text = "Multi Editor settings"; ((System.ComponentModel.ISupportInitialize)alphaWorkPlane).EndInit(); + ((System.ComponentModel.ISupportInitialize)alphaPreview).EndInit(); ((System.ComponentModel.ISupportInitialize)alphaGrid).EndInit(); ((System.ComponentModel.ISupportInitialize)alphaOutline).EndInit(); ResumeLayout(false); @@ -349,6 +400,9 @@ private void InitializeComponent() private System.Windows.Forms.Label labelWorkPlane; private System.Windows.Forms.Label labelWorkPlaneOpacity; private System.Windows.Forms.NumericUpDown alphaWorkPlane; + private System.Windows.Forms.Label labelPreview; + private System.Windows.Forms.Label labelPreviewOpacity; + private System.Windows.Forms.NumericUpDown alphaPreview; private System.Windows.Forms.Button swatchWorkPlane; private System.Windows.Forms.Label labelGrid; private System.Windows.Forms.Label labelGridOpacity; @@ -364,6 +418,7 @@ private void InitializeComponent() private System.Windows.Forms.CheckBox checkWorkPlane; private System.Windows.Forms.CheckBox checkGrid; private System.Windows.Forms.CheckBox checkHideFloorsAbove; + private System.Windows.Forms.CheckBox checkHouseOneLayer; private System.Windows.Forms.Button buttonDefaults; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Button buttonCancel; diff --git a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs index b8adf601..d79ade19 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/EditorSettingsDialog.cs @@ -37,9 +37,13 @@ public EditorSettingsDialog(EditorSettings current) ColorRow(swatchOutline, alphaOutline, () => _settings.Outline); ColorRow(swatchSelection, null, () => _settings.SelectionBox); + alphaPreview.Value = Math.Clamp(_settings.PreviewOpacity, 20, 100); + _refresh.Add(() => alphaPreview.Value = Math.Clamp(_settings.PreviewOpacity, 20, 100)); + CheckRow(checkWorkPlane, () => _settings.StartWithWorkPlane); CheckRow(checkGrid, () => _settings.StartWithGrid); CheckRow(checkHideFloorsAbove, () => _settings.HideFloorsAbove); + CheckRow(checkHouseOneLayer, () => _settings.HouseOnOneLayer); } /// The edited copy; apply it when the dialog returns OK. @@ -115,6 +119,11 @@ private void AlphaWorkPlane_ValueChanged(object sender, EventArgs e) ChangeOpacity(alphaWorkPlane, () => _settings.WorkPlane, c => _settings.WorkPlane = c); } + private void AlphaPreview_ValueChanged(object sender, EventArgs e) + { + _settings.PreviewOpacity = (int)alphaPreview.Value; + } + private void AlphaGrid_ValueChanged(object sender, EventArgs e) { ChangeOpacity(alphaGrid, () => _settings.Grid, c => _settings.Grid = c); @@ -135,6 +144,11 @@ private void CheckGrid_CheckedChanged(object sender, EventArgs e) _settings.StartWithGrid = checkGrid.Checked; } + private void CheckHouseOneLayer_CheckedChanged(object sender, EventArgs e) + { + _settings.HouseOnOneLayer = checkHouseOneLayer.Checked; + } + private void CheckHideFloorsAbove_CheckedChanged(object sender, EventArgs e) { _settings.HideFloorsAbove = checkHideFloorsAbove.Checked; diff --git a/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs index 2e2646fe..c5476469 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.Designer.cs @@ -55,14 +55,27 @@ private void InitializeComponent() _foundation = new System.Windows.Forms.CheckBox(); _baseZLabel = new System.Windows.Forms.Label(); _baseZ = new System.Windows.Forms.NumericUpDown(); + _roomsLabel = new System.Windows.Forms.Label(); + _rooms = new System.Windows.Forms.NumericUpDown(); + _showLabel = new System.Windows.Forms.Label(); + _showWalls = new System.Windows.Forms.CheckBox(); + _showFloors = new System.Windows.Forms.CheckBox(); + _showRoof = new System.Windows.Forms.CheckBox(); _undo = new System.Windows.Forms.Button(); _redo = new System.Windows.Forms.Button(); _place = new System.Windows.Forms.Button(); _drop = new System.Windows.Forms.Button(); + _saveDraft = new System.Windows.Forms.Button(); + _openDraft = new System.Windows.Forms.Button(); + _blueprint = new System.Windows.Forms.Button(); + _placedLabel = new System.Windows.Forms.Label(); + _placed = new System.Windows.Forms.ComboBox(); + _edit = new System.Windows.Forms.Button(); _status = new System.Windows.Forms.Label(); houseBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)_storeys).BeginInit(); ((System.ComponentModel.ISupportInitialize)_baseZ).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_rooms).BeginInit(); SuspendLayout(); // // houseBox @@ -93,15 +106,27 @@ private void InitializeComponent() houseBox.Controls.Add(_foundation); houseBox.Controls.Add(_baseZLabel); houseBox.Controls.Add(_baseZ); + houseBox.Controls.Add(_roomsLabel); + houseBox.Controls.Add(_rooms); + houseBox.Controls.Add(_showLabel); + houseBox.Controls.Add(_showWalls); + houseBox.Controls.Add(_showFloors); + houseBox.Controls.Add(_showRoof); houseBox.Controls.Add(_undo); houseBox.Controls.Add(_redo); houseBox.Controls.Add(_place); houseBox.Controls.Add(_drop); + houseBox.Controls.Add(_saveDraft); + houseBox.Controls.Add(_openDraft); + houseBox.Controls.Add(_blueprint); + houseBox.Controls.Add(_placedLabel); + houseBox.Controls.Add(_placed); + houseBox.Controls.Add(_edit); houseBox.Controls.Add(_status); houseBox.Dock = System.Windows.Forms.DockStyle.Fill; houseBox.Location = new System.Drawing.Point(0, 0); houseBox.Name = "houseBox"; - houseBox.Size = new System.Drawing.Size(250, 430); + houseBox.Size = new System.Drawing.Size(250, 518); houseBox.TabIndex = 0; houseBox.TabStop = false; houseBox.Text = "House draft"; @@ -150,11 +175,11 @@ private void InitializeComponent() // _removeWing.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; _removeWing.UseVisualStyleBackColor = true; - _removeWing.Location = new System.Drawing.Point(150, 109); + _removeWing.Location = new System.Drawing.Point(206, 109); _removeWing.Name = "_removeWing"; - _removeWing.Size = new System.Drawing.Size(94, 25); + _removeWing.Size = new System.Drawing.Size(38, 25); _removeWing.TabIndex = 4; - _removeWing.Text = "Remove wing"; + _removeWing.Text = "Del"; _removeWing.Click += RemoveWing_Click; // // _roofLabel @@ -170,7 +195,7 @@ private void InitializeComponent() // _roofShape.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; _roofShape.FormattingEnabled = true; - _roofShape.Items.AddRange(new object[] { "Gable", "None" }); + _roofShape.Items.AddRange(new object[] { "Gable", "Hip", "Flat", "None" }); _roofShape.Location = new System.Drawing.Point(60, 140); _roofShape.Name = "_roofShape"; _roofShape.Size = new System.Drawing.Size(80, 23); @@ -358,33 +383,101 @@ private void InitializeComponent() _baseZ.TabIndex = 25; _baseZ.ValueChanged += BaseZ_ValueChanged; // + // _roomsLabel + // + _roomsLabel.AutoSize = true; + _roomsLabel.Location = new System.Drawing.Point(110, 113); + _roomsLabel.Name = "_roomsLabel"; + _roomsLabel.Size = new System.Drawing.Size(44, 15); + _roomsLabel.TabIndex = 26; + _roomsLabel.Text = "Rooms"; + // + // _rooms + // + _rooms.Maximum = new decimal(new int[] { 6, 0, 0, 0 }); + _rooms.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); + _rooms.Value = new decimal(new int[] { 1, 0, 0, 0 }); + _rooms.Location = new System.Drawing.Point(156, 110); + _rooms.Name = "_rooms"; + _rooms.Size = new System.Drawing.Size(44, 23); + _rooms.TabIndex = 27; + _rooms.ValueChanged += Rooms_ValueChanged; + // + // _showLabel + // + _showLabel.AutoSize = true; + _showLabel.Location = new System.Drawing.Point(6, 364); + _showLabel.Name = "_showLabel"; + _showLabel.Size = new System.Drawing.Size(50, 15); + _showLabel.TabIndex = 28; + _showLabel.Text = "Preview"; + // + // _showWalls + // + _showWalls.AutoSize = true; + _showWalls.Checked = true; + _showWalls.CheckState = System.Windows.Forms.CheckState.Checked; + _showWalls.UseVisualStyleBackColor = true; + _showWalls.Location = new System.Drawing.Point(60, 362); + _showWalls.Name = "_showWalls"; + _showWalls.Size = new System.Drawing.Size(56, 19); + _showWalls.TabIndex = 29; + _showWalls.Text = "Walls"; + _showWalls.CheckedChanged += Show_CheckedChanged; + // + // _showFloors + // + _showFloors.AutoSize = true; + _showFloors.Checked = true; + _showFloors.CheckState = System.Windows.Forms.CheckState.Checked; + _showFloors.UseVisualStyleBackColor = true; + _showFloors.Location = new System.Drawing.Point(122, 362); + _showFloors.Name = "_showFloors"; + _showFloors.Size = new System.Drawing.Size(60, 19); + _showFloors.TabIndex = 30; + _showFloors.Text = "Floors"; + _showFloors.CheckedChanged += Show_CheckedChanged; + // + // _showRoof + // + _showRoof.AutoSize = true; + _showRoof.Checked = true; + _showRoof.CheckState = System.Windows.Forms.CheckState.Checked; + _showRoof.UseVisualStyleBackColor = true; + _showRoof.Location = new System.Drawing.Point(188, 362); + _showRoof.Name = "_showRoof"; + _showRoof.Size = new System.Drawing.Size(52, 19); + _showRoof.TabIndex = 31; + _showRoof.Text = "Roof"; + _showRoof.CheckedChanged += Show_CheckedChanged; + // // _undo // _undo.UseVisualStyleBackColor = true; - _undo.Location = new System.Drawing.Point(6, 362); + _undo.Location = new System.Drawing.Point(6, 392); _undo.Name = "_undo"; _undo.Size = new System.Drawing.Size(54, 25); - _undo.TabIndex = 26; + _undo.TabIndex = 32; _undo.Text = "Undo"; _undo.Click += Undo_Click; // // _redo // _redo.UseVisualStyleBackColor = true; - _redo.Location = new System.Drawing.Point(62, 362); + _redo.Location = new System.Drawing.Point(62, 392); _redo.Name = "_redo"; _redo.Size = new System.Drawing.Size(54, 25); - _redo.TabIndex = 27; + _redo.TabIndex = 33; _redo.Text = "Redo"; _redo.Click += Redo_Click; // // _place // _place.UseVisualStyleBackColor = true; - _place.Location = new System.Drawing.Point(122, 362); + _place.Location = new System.Drawing.Point(122, 392); _place.Name = "_place"; _place.Size = new System.Drawing.Size(72, 25); - _place.TabIndex = 28; + _place.TabIndex = 34; _place.Text = "Place"; _place.Click += Place_Click; // @@ -392,20 +485,81 @@ private void InitializeComponent() // _drop.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; _drop.UseVisualStyleBackColor = true; - _drop.Location = new System.Drawing.Point(196, 362); + _drop.Location = new System.Drawing.Point(196, 392); _drop.Name = "_drop"; _drop.Size = new System.Drawing.Size(48, 25); - _drop.TabIndex = 29; + _drop.TabIndex = 35; _drop.Text = "Drop"; _drop.Click += Drop_Click; // + // _saveDraft + // + _saveDraft.UseVisualStyleBackColor = true; + _saveDraft.Location = new System.Drawing.Point(6, 421); + _saveDraft.Name = "_saveDraft"; + _saveDraft.Size = new System.Drawing.Size(76, 25); + _saveDraft.TabIndex = 36; + _saveDraft.Text = "Save draft"; + _saveDraft.Click += SaveDraft_Click; + // + // _openDraft + // + _openDraft.UseVisualStyleBackColor = true; + _openDraft.Location = new System.Drawing.Point(84, 421); + _openDraft.Name = "_openDraft"; + _openDraft.Size = new System.Drawing.Size(76, 25); + _openDraft.TabIndex = 37; + _openDraft.Text = "Open draft"; + _openDraft.Click += OpenDraft_Click; + // + // _blueprint + // + _blueprint.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _blueprint.UseVisualStyleBackColor = true; + _blueprint.Location = new System.Drawing.Point(162, 421); + _blueprint.Name = "_blueprint"; + _blueprint.Size = new System.Drawing.Size(82, 25); + _blueprint.TabIndex = 38; + _blueprint.Text = "As blueprint"; + _blueprint.Click += Blueprint_Click; + // + // _placedLabel + // + _placedLabel.AutoSize = true; + _placedLabel.Location = new System.Drawing.Point(6, 454); + _placedLabel.Name = "_placedLabel"; + _placedLabel.Size = new System.Drawing.Size(60, 15); + _placedLabel.TabIndex = 39; + _placedLabel.Text = "Placed"; + // + // _placed + // + _placed.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + _placed.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + _placed.FormattingEnabled = true; + _placed.Location = new System.Drawing.Point(60, 451); + _placed.Name = "_placed"; + _placed.Size = new System.Drawing.Size(130, 23); + _placed.TabIndex = 40; + // + // _edit + // + _edit.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + _edit.UseVisualStyleBackColor = true; + _edit.Location = new System.Drawing.Point(196, 450); + _edit.Name = "_edit"; + _edit.Size = new System.Drawing.Size(48, 25); + _edit.TabIndex = 41; + _edit.Text = "Edit"; + _edit.Click += Edit_Click; + // // _status // _status.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - _status.Location = new System.Drawing.Point(6, 392); + _status.Location = new System.Drawing.Point(6, 480); _status.Name = "_status"; _status.Size = new System.Drawing.Size(238, 32); - _status.TabIndex = 30; + _status.TabIndex = 42; // // HousePanel // @@ -413,11 +567,12 @@ private void InitializeComponent() AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; Controls.Add(houseBox); Name = "HousePanel"; - Size = new System.Drawing.Size(250, 430); + Size = new System.Drawing.Size(250, 518); houseBox.ResumeLayout(false); houseBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)_storeys).EndInit(); ((System.ComponentModel.ISupportInitialize)_baseZ).EndInit(); + ((System.ComponentModel.ISupportInitialize)_rooms).EndInit(); ResumeLayout(false); } @@ -450,10 +605,22 @@ private void InitializeComponent() private System.Windows.Forms.CheckBox _foundation; private System.Windows.Forms.Label _baseZLabel; private System.Windows.Forms.NumericUpDown _baseZ; + private System.Windows.Forms.Label _roomsLabel; + private System.Windows.Forms.NumericUpDown _rooms; + private System.Windows.Forms.Label _showLabel; + private System.Windows.Forms.CheckBox _showWalls; + private System.Windows.Forms.CheckBox _showFloors; + private System.Windows.Forms.CheckBox _showRoof; private System.Windows.Forms.Button _undo; private System.Windows.Forms.Button _redo; private System.Windows.Forms.Button _place; private System.Windows.Forms.Button _drop; + private System.Windows.Forms.Button _saveDraft; + private System.Windows.Forms.Button _openDraft; + private System.Windows.Forms.Button _blueprint; + private System.Windows.Forms.Label _placedLabel; + private System.Windows.Forms.ComboBox _placed; + private System.Windows.Forms.Button _edit; private System.Windows.Forms.Label _status; } } diff --git a/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs index d744288b..13c0243e 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs @@ -56,6 +56,17 @@ public HousePanel() /// Asks for a style to be picked on the House page for a storey's walls or floor, or for the roof. public event Action PickStyle; + /// Asks for the draft to be saved to, or opened from, a house draft file. + public event Action SaveDraft; + + public event Action OpenDraft; + + /// Asks for the house as built to be saved to the blueprints. + public event Action SaveBlueprint; + + /// Asks for a placed house to be opened as a draft again. + public event Action EditHouse; + /// Raised after a button of the panel was used, so the canvas can take the keyboard back. public event Action Used; @@ -96,7 +107,7 @@ public void RefreshDraft() { RoofWing wing = house.Wings[i]; string roof = wing.NoRoof ? "no roof" : wing.Shape.ToString().ToLowerInvariant(); - _wingList.Items.Add($"Wing {i + 1}: {wing.X1 - wing.X0 + 1} x {wing.Y1 - wing.Y0 + 1}, {wing.Storeys} storey{(wing.Storeys == 1 ? string.Empty : "s")}, {roof}"); + _wingList.Items.Add($"Wing {i + 1}: {wing.X1 - wing.X0 + 1} x {wing.Y1 - wing.Y0 + 1}, {wing.Storeys} storey{(wing.Storeys == 1 ? string.Empty : "s")}, {(wing.Rooms > 1 ? $"{wing.Rooms} rooms, " : string.Empty)}{roof}"); } _wingList.SelectedIndex = house.SelectedIndex; @@ -106,7 +117,7 @@ public void RefreshDraft() // The drop-down lists the roof shapes in their order, then None. _roofShape.SelectedIndex = house.NoRoof ? _roofShape.Items.Count - 1 : (int)house.Shape; _ridge.SelectedIndex = (int)house.Ridge; - _ridge.Enabled = !house.NoRoof; + _ridge.Enabled = !house.NoRoof && house.Shape == RoofShape.Gable; _removeWing.Enabled = house.HasSelectedWing; _wingHint.Text = house.HasSelectedWing ? "Selected wing:" : "New wings:"; @@ -128,6 +139,24 @@ public void RefreshDraft() _roofStyle.Text = house.Draft.RoofStyle?.Name ?? "(roof)"; _foundation.Checked = house.Draft.Foundation; + _rooms.Value = Math.Clamp(house.Rooms, 1, HouseDraft.MaxRooms); + _showWalls.Checked = house.ShowWalls; + _showFloors.Checked = house.ShowFloors; + _showRoof.Checked = house.ShowRoof; + _saveDraft.Enabled = _blueprint.Enabled = house.HasPending; + + // The houses already placed in this design, which can be opened as drafts again. + object chosen = _placed.SelectedItem; + _placed.Items.Clear(); + foreach (System.Xml.Linq.XElement placed in _session.PlacedHouses) + { + _placed.Items.Add(new PlacedHouse(placed)); + } + + _placed.SelectedIndex = _placed.Items.Count == 0 ? -1 + : Math.Max(0, _placed.Items.Cast().ToList().FindIndex(p => chosen is PlacedHouse c && c.House == p.House)); + _placed.Enabled = _placed.Items.Count > 0; + _edit.Enabled = _placed.Items.Count > 0 && !house.HasPending; _baseZ.Enabled = house.HasPending; _baseZ.Value = Math.Clamp(house.BaseZ, (int)_baseZ.Minimum, (int)_baseZ.Maximum); @@ -153,6 +182,63 @@ public void RefreshDraft() } } + /// A placed house in the list, shown by its name and size. + private sealed class PlacedHouse + { + public PlacedHouse(System.Xml.Linq.XElement house) + { + House = house; + } + + public System.Xml.Linq.XElement House { get; } + + public override string ToString() + { + int wings = House.Elements("Wing").Count(); + return $"{(string)House.Attribute("name") ?? "House"} ({wings} wing{(wings == 1 ? string.Empty : "s")})"; + } + } + + private void Rooms_ValueChanged(object sender, EventArgs e) + { + if (!_updating && _session != null) + { + _session.House.SetRooms((int)_rooms.Value); + } + } + + private void Show_CheckedChanged(object sender, EventArgs e) + { + Run(house => (house.ShowWalls, house.ShowFloors, house.ShowRoof) = (_showWalls.Checked, _showFloors.Checked, _showRoof.Checked)); + } + + private void SaveDraft_Click(object sender, EventArgs e) + { + SaveDraft?.Invoke(); + Used?.Invoke(); + } + + private void OpenDraft_Click(object sender, EventArgs e) + { + OpenDraft?.Invoke(); + Used?.Invoke(); + } + + private void Blueprint_Click(object sender, EventArgs e) + { + SaveBlueprint?.Invoke(); + Used?.Invoke(); + } + + private void Edit_Click(object sender, EventArgs e) + { + if (_placed.SelectedItem is PlacedHouse placed) + { + EditHouse?.Invoke(placed.House); + Used?.Invoke(); + } + } + private void Run(Action action) { if (_updating || _session == null) diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs index 9cb96933..91afa961 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.Designer.cs @@ -324,7 +324,7 @@ private void InitializeComponent() _shapeLabel.Name = "_shapeLabel"; _shapeLabel.Size = new System.Drawing.Size(39, 22); _shapeLabel.Text = "Shape"; - _shapeLabel.ToolTipText = "Gable: two slopes and a ridge."; + _shapeLabel.ToolTipText = "Gable: two slopes and a ridge. Hip: four slopes, no gable ends."; // // _ridgeSeparator // diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs index 2d571e83..cd0b086d 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs @@ -59,15 +59,29 @@ public MultiEditorControl() InitializeComponent(); SplitterGrip.Attach(_sideSplit); - // The house draft's panel sits above the floors and selection; shown with the House tool or an open draft. - _housePanel = new HousePanel { Dock = DockStyle.Top, Visible = false }; + // The right sidebar has two pages: the design (floors, layers, selection) and the + // house draft, which is too tall to share a page. The House page scrolls when the + // window is short, and comes to the front with the House tool or an open draft. + _housePanel = new HousePanel { Dock = DockStyle.Top }; _housePanel.PickStyle += PickHouseMaterial; + _housePanel.SaveDraft += SaveHouseDraft; + _housePanel.OpenDraft += OpenHouseDraft; + _housePanel.SaveBlueprint += SaveHouseBlueprint; + _housePanel.EditHouse += EditPlacedHouse; _housePanel.Used += () => { _commands.RefreshStates(); _canvas.Focus(); }; - _sideSplit.Panel2.Controls.Add(_housePanel); + _designPage = new TabPage("Design"); + _housePage = new TabPage("House draft") { AutoScroll = true }; + _sideSplit.Panel2.Controls.Remove(_inspector); + _designPage.Controls.Add(_inspector); + _housePage.Controls.Add(_housePanel); + _sideTabs = new UoFiddler.Controls.UserControls.ThemedTabControl { Dock = DockStyle.Fill }; + _sideTabs.TabPages.Add(_designPage); + _sideTabs.TabPages.Add(_housePage); + _sideSplit.Panel2.Controls.Add(_sideTabs); // Room after each tab's text for its close button, at any DPI. _docTabs.Padding = new Point((CloseGlyphSize + LogicalToDeviceUnits(16)) / 2, _docTabs.Padding.Y); @@ -675,6 +689,13 @@ private void ChooseHouseStyle(HouseStyle style) return; } + // The House page names its current style when it is brought up for a pick of the + // house panel: that is not the pick, which is the next style clicked there. + if (_housePick != null && _openingHousePage) + { + return; + } + // A pick asked for by the house panel is a material of the draft, not a tool's style. if (_housePick is { } pick && pick.Kind == style.Kind) { @@ -685,6 +706,18 @@ private void ChooseHouseStyle(HouseStyle style) } _housePick = null; + + // With the House tool in use, a wall, floor or roof style clicked on the House page is + // a material of the house too: of the storey the chosen floor means, or of every + // storey with all floors shown. Doors and stairs have tools of their own. + if (Session.Tool == ToolKind.House && style.Kind is HousePartKind.Wall or HousePartKind.Floor or HousePartKind.Roof) + { + int? storey = style.Kind == HousePartKind.Roof || Session.WorkZ == null ? null : Session.DraftStorey; + Session.House.SetMaterial(style, storey); + _canvas.Focus(); + return; + } + Session.HouseStyle = style; ToolKind kind = style.Kind switch { @@ -726,6 +759,113 @@ private void PickHouseMaterial(HousePartKind kind, int storey) : $"Pick the {(kind == HousePartKind.Wall ? "wall" : "floor")} style of storey {storey + 1} on the House page."; } + private static string HouseDraftFolder + { + get + { + string folder = System.IO.Path.Combine(Options.AppDataPath, "MultiEditorHouses"); + System.IO.Directory.CreateDirectory(folder); + return folder; + } + } + + /// Writes the house being designed to a house draft file, to open again in any design. + private void SaveHouseDraft() + { + if (Session == null || !Session.House.HasPending) + { + return; + } + + using var dialog = new SaveFileDialog + { + Title = "Save house draft", Filter = HouseDraftFile.Filter, DefaultExt = HouseDraftFile.Extension, + InitialDirectory = HouseDraftFolder, FileName = "House" + }; + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + try + { + new System.Xml.Linq.XDocument(Session.House.ToXml(System.IO.Path.GetFileNameWithoutExtension(dialog.FileName))).Save(dialog.FileName); + } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException) + { + MessageBox.Show(this, "The house draft could not be saved:\r\n" + ex.Message, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + /// Opens a house draft file as the draft of the House tool; the draft being designed can be had back with undo. + private void OpenHouseDraft() + { + if (Session == null) + { + return; + } + + using var dialog = new OpenFileDialog { Title = "Open house draft", Filter = HouseDraftFile.Filter, InitialDirectory = HouseDraftFolder }; + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + try + { + Session.House.OpenXml(System.Xml.Linq.XDocument.Load(dialog.FileName).Root); + SetTool(ToolKind.House); + } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or System.Xml.XmlException or System.IO.InvalidDataException) + { + MessageBox.Show(this, "The house draft could not be opened:\r\n" + ex.Message, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + /// Saves the house being designed, as built, to the blueprints: tiles to stamp, not a draft. + private void SaveHouseBlueprint() + { + if (Session == null || !Session.House.HasPending) + { + return; + } + + var built = Session.House.TilesOf(Session.House.ToXml("House")); + if (built.Count == 0) + { + return; + } + + int ox = built.Min(t => t.X), oy = built.Min(t => t.Y), oz = built.Min(t => t.Z); + List tiles = built.Select(t => new ClipboardTile(t.Id, t.X - ox, t.Y - oy, t.Z - oz, false, 0)).ToList(); + var source = new BlueprintSource("House", tiles.Count, () => tiles); + if (BlueprintSaveDialog.Run(this, new[] { source }, out string showGroup) != null) + { + BlueprintsSaved(showGroup); + } + } + + /// Opens a placed house as a draft again. + private void EditPlacedHouse(System.Xml.Linq.XElement house) + { + if (Session == null || house == null) + { + return; + } + + string problem = Session.ReopenHouse(house); + if (problem != null) + { + MessageBox.Show(this, problem, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + SetTool(ToolKind.House); + } + + _commands.RefreshStates(); + } + private void CyclePlacement() { Session.Placement = (PlacementMode)(((int)Session.Placement + 1) % 3); @@ -1395,24 +1535,38 @@ private void BuildOptionsStrip() strip.Items.Insert(at++, button); } - // Roof options, shown only with the Roof tool. - RoofGroup(strip, _shapeSeparator, _shapeLabel, - ("Gable", () => Session.Roof.Shape == RoofShape.Gable, () => Session.Roof.Shape = RoofShape.Gable)); - RoofGroup(strip, _ridgeSeparator, _ridgeLabel, + // Roof and draft options get a row of their own under the tool options, shown only + // while they apply: beside the other options they ended up far to the right. + _roofStrip = new ToolStrip { GripStyle = ToolStripGripStyle.Hidden, Dock = DockStyle.Top, Visible = false, Renderer = strip.Renderer, RenderMode = strip.RenderMode }; + foreach (ToolStripItem item in new ToolStripItem[] + { + _shapeSeparator, _shapeLabel, _ridgeSeparator, _ridgeLabel, _gablesSeparator, _gablesLabel, _gableFillSeparator, _gableFillLabel + }) + { + _roofStrip.Items.Add(item); + } + + Controls.Add(_roofStrip); + Controls.SetChildIndex(_roofStrip, Controls.GetChildIndex(_optionsStrip)); + RoofGroup(_roofStrip, _shapeSeparator, _shapeLabel, + ("Gable", () => Session.Roof.Shape == RoofShape.Gable, () => Session.Roof.Shape = RoofShape.Gable), + ("Hip", () => Session.Roof.Shape == RoofShape.Hip, () => Session.Roof.Shape = RoofShape.Hip)); + RoofGroup(_roofStrip, _ridgeSeparator, _ridgeLabel, ("Auto", () => Session.Roof.Ridge == RoofRidge.Auto, () => Session.Roof.Ridge = RoofRidge.Auto), ("X", () => Session.Roof.Ridge == RoofRidge.AlongX, () => Session.Roof.Ridge = RoofRidge.AlongX), ("Y", () => Session.Roof.Ridge == RoofRidge.AlongY, () => Session.Roof.Ridge = RoofRidge.AlongY)); - RoofGroup(strip, _gablesSeparator, _gablesLabel, + RoofGroup(_roofStrip, _gablesSeparator, _gablesLabel, ("Front", () => Session.Roof.Gables == RoofGables.Front, () => Session.Roof.Gables = RoofGables.Front), ("Both", () => Session.Roof.Gables == RoofGables.Both, () => Session.Roof.Gables = RoofGables.Both), ("None", () => Session.Roof.Gables == RoofGables.None, () => Session.Roof.Gables = RoofGables.None)); - RoofGroup(strip, _gableFillSeparator, _gableFillLabel, + RoofGroup(_roofStrip, _gableFillSeparator, _gableFillLabel, ("Caps", () => Session.Roof.GableFill == RoofGableFill.Caps, () => Session.Roof.GableFill = RoofGableFill.Caps), ("Walls", () => Session.Roof.GableFill == RoofGableFill.Walls, () => Session.Roof.GableFill = RoofGableFill.Walls)); // Shown while a roof is being shaped. - _placeRoofButton = RoofAction(strip, "Place", "Places what is being shaped: the roof on the Roof layer, the house on its layers (Enter).", () => Session.DraftInFocus?.Commit()); - _dropRoofButton = RoofAction(strip, "Drop", "Drops what is being shaped (Esc). Undo brings it back.", () => Session.DraftInFocus?.Discard()); + _placeRoofButton = RoofAction(_roofStrip, "Place", "Places what is being shaped: the roof on the Roof layer, the house on its layers (Enter).", () => Session.DraftInFocus?.Commit()); + _dropRoofButton = RoofAction(_roofStrip, "Drop", "Drops what is being shaped (Esc). Undo brings it back.", () => Session.DraftInFocus?.Discard()); + StyleSeparators(_roofStrip); } /// What the tool in use does to the open house draft. @@ -1435,7 +1589,12 @@ private void ZStepCombo_SelectedIndexChanged(object sender, EventArgs e) } private readonly HousePanel _housePanel; + private readonly TabControl _sideTabs; + private readonly TabPage _designPage; + private readonly TabPage _housePage; + private bool _houseWasShown; private (HousePartKind Kind, int Storey)? _housePick; + private ToolStrip _roofStrip; private EditorCommand _placeRoof; private ToolStripButton _placeRoofButton; private ToolStripButton _dropRoofButton; @@ -1510,12 +1669,24 @@ private void SyncRoofOptions() item.Visible = show; } - _placeRoofButton.Visible = _dropRoofButton.Visible = Session != null && !Session.Pasting && Session.DraftInFocus != null; + bool draft = Session != null && !Session.Pasting && Session.DraftInFocus != null; + _placeRoofButton.Visible = _dropRoofButton.Visible = draft; + + // The first group needs no line before it on a row of its own. + _shapeSeparator.Visible = false; + if (_roofStrip.Visible != (show || draft)) + { + _roofStrip.Visible = show || draft; + } + // The House page comes to the front when the House tool is taken up or a draft is + // opened, and gives way again when both are over; in between the pages are yours. bool house = Session != null && (Session.Tool == ToolKind.House || Session.House.HasPending); - if (_housePanel.Visible != house) + _housePanel.RefreshDraft(); + if (house != _houseWasShown) { - _housePanel.Visible = house; + _houseWasShown = house; + _sideTabs.SelectedTab = house ? _housePage : _designPage; } foreach ((ToolStripButton button, Func isOn) in _roofButtons) @@ -1656,6 +1827,7 @@ private void AddDocument(OpenedMulti opened) LayerStore.Load(clientId, document.Session.CompList.Fingerprint(origin)) is { } saved) { document.Session.RestoreLayers(saved.Layers, saved.Active, origin); + document.Session.SetPlacedHouses(saved.Houses, origin.X, origin.Y); } ShowDocument(document); } @@ -1724,7 +1896,8 @@ private void SaveToClient() try { - LayerStore.Save(id.Value, list.SaveLayers(includeHidden), list.Layers.ToList().IndexOf(list.ActiveLayer), list.Fingerprint(list.SaveOrigin, includeHidden)); + LayerStore.Save(id.Value, list.SaveLayers(includeHidden), list.Layers.ToList().IndexOf(list.ActiveLayer), list.Fingerprint(list.SaveOrigin, includeHidden), + Session.PlacedHousesShifted(-list.SaveOrigin.X, -list.SaveOrigin.Y)); } catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or ArgumentException or System.Xml.XmlException) { From b100810cd43f6eb925a6d416dd16bb875b43f48d Mon Sep 17 00:00:00 2001 From: AsY!um- <377468+AsYlum-@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:33:10 +0100 Subject: [PATCH 05/16] Read house styles from a style file and complete the wall sets Wall styles named by material and kind; shadow, celtic, gargish and gothic sets built from their plain pieces. --- .../Classes/GroupTransform.cs | 23 + .../Classes/HouseDraft.cs | 9 +- .../Classes/HouseDraftFile.cs | 6 + .../Classes/HouseStyleConfig.cs | 298 +++++++ .../Classes/HouseStyles.cs | 727 ++++++++++++++- .../Classes/WallPlanner.cs | 49 +- .../MultiEditorHouseStyles.xml | 831 ++++++++++++++++++ .../Tools/HouseTool.cs | 15 +- .../Tools/RoofTool.cs | 31 +- UoFiddler.Plugin.MultiEditor/UI/HousePanel.cs | 13 +- .../UI/MultiEditorControl.cs | 14 +- .../UI/TileBrowserPanel.cs | 4 +- .../UoFiddler.Plugin.MultiEditor.csproj | 3 + 13 files changed, 1986 insertions(+), 37 deletions(-) create mode 100644 UoFiddler.Plugin.MultiEditor/Classes/HouseStyleConfig.cs create mode 100644 UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml diff --git a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs b/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs index e7f60b81..35eb222c 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs @@ -469,8 +469,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/Classes/HouseDraft.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs index 1ddff348..22c5e9c7 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraft.cs @@ -44,6 +44,9 @@ internal sealed class HouseDraft 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; } /// Most rooms a wing can be divided into. @@ -109,7 +112,7 @@ public HouseDraft Clone() /// A draft with the same materials and nothing changed by hand: the next house. public HouseDraft Fresh() { - var copy = new HouseDraft { RoofStyle = RoofStyle, Foundation = Foundation }; + var copy = new HouseDraft { RoofStyle = RoofStyle, FlatRoofStyle = FlatRoofStyle, Foundation = Foundation }; Array.Copy(WallStyles, copy.WallStyles, MaxStoreys); Array.Copy(FloorStyles, copy.FloorStyles, MaxStoreys); return copy; @@ -371,7 +374,7 @@ public Built Build(IReadOnlyList wings, HouseStyles styles) continue; } - string column = WallPlanner.PieceFor(south, east, x, y); + string column = WallPlanner.PieceFor(wallStyle, south, east, x, y); if (column == null || wallStyle == null) { continue; @@ -429,7 +432,7 @@ public Built Build(IReadOnlyList wings, HouseStyles styles) foreach (RoofWing wing in wings) { int storeys = Math.Clamp(wing.Storeys, 1, MaxStoreys); - HouseStyle style = FloorStyles[storeys - 1]; + HouseStyle style = FlatRoofStyle ?? FloorStyles[storeys - 1]; if (wing.NoRoof || wing.Shape != RoofShape.Flat || style == null) { continue; diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs index 2d3f0896..85fd18c2 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseDraftFile.cs @@ -50,6 +50,11 @@ public static XElement ToXml(IReadOnlyList wings, HouseDraft draft, st root.Add(new XAttribute("roof", draft.RoofStyle.Name)); } + if (draft.FlatRoofStyle != null) + { + root.Add(new XAttribute("flatRoof", draft.FlatRoofStyle.Name)); + } + foreach (RoofWing wing in wings) { root.Add(new XElement("Wing", @@ -149,6 +154,7 @@ HouseStyle Style(HousePartKind kind, string name) => // A draft saved before rooms were set per wing names one count for the house. int houseRooms = (int?)root.Attribute("rooms") ?? 1; draft.RoofStyle = Style(HousePartKind.Roof, (string)root.Attribute("roof")) ?? draft.RoofStyle; + draft.FlatRoofStyle = Style(HousePartKind.Floor, (string)root.Attribute("flatRoof")) ?? draft.FlatRoofStyle; var wings = new List(); foreach (XElement element in root.Elements("Wing")) diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyleConfig.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyleConfig.cs new file mode 100644 index 00000000..a4786c3f --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyleConfig.cs @@ -0,0 +1,298 @@ +/*************************************************************************** + * + * $Author: Turley + * + * "THE BEER-WARE LICENSE" + * As long as you retain this notice you can do whatever you want with + * this stuff. If we meet some day, and you think this stuff is worth it, + * you can buy me a beer in return. + * + ***************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// One Style element of the style file: what it says about one house style. + internal sealed class HouseStyleEntry + { + public const string LayoutRun = "Run"; + public const string LayoutPaired = "Paired"; + public const string LayoutCycle = "Cycle"; + + public HousePartKind Kind { get; set; } + + /// A piece of the style: the entry is about the first style of its kind that lists it. + public ushort Anchor { get; set; } + + /// True for a style the tables do not have: it is made from the entry's pieces. + public bool IsNew { get; set; } + + /// Pieces of further styles this one takes the place of. + public List Replaces { get; } = new List(); + + public string Name { get; set; } + + public string Group { get; set; } + + public string Family { get; set; } + + public bool? Hidden { get; set; } + + /// How a wall run is laid: , or . Null leaves it. + public string Layout { get; set; } + + public bool? Borrows { get; set; } + + /// The style's pieces by column label, in place of the table's. Null keeps the table's. + public List<(string Role, ushort Id)> Pieces { get; set; } + + public (HousePartKind Kind, ushort Anchor, bool IsNew) Key => (Kind, Anchor, IsNew); + } + + /// + /// The style file (MultiEditorHouseStyles.xml): names, groups, order and corrected pieces for + /// the house styles read from the client's tables. One ships beside the plugin; a file of the + /// same name in the profile's plugins folder holds the user's changes, entry by entry, on + /// top of it. + /// + internal sealed class HouseStyleConfig + { + public const string FileName = "MultiEditorHouseStyles.xml"; + + private const string _root = "HouseStyles"; + private const int _version = 1; + + public List Styles { get; } = new List(); + + public List Errors { get; } = new List(); + + public static string ShippedPath + { + get + { + string folder = Path.GetDirectoryName(typeof(HouseStyleConfig).Assembly.Location); + return string.IsNullOrEmpty(folder) ? null : Path.Combine(folder, FileName); + } + } + + public static string UserPath => string.IsNullOrEmpty(Options.AppDataPath) ? null : Path.Combine(Options.AppDataPath, "plugins", FileName); + + /// The shipped file with the user's file on top. A file that is missing or cannot be read counts as empty. + public static HouseStyleConfig Load() + { + HouseStyleConfig config = LoadFile(ShippedPath); + config.Merge(LoadFile(UserPath)); + return config; + } + + public static HouseStyleConfig LoadFile(string path) + { + var config = new HouseStyleConfig(); + if (string.IsNullOrEmpty(path) || !File.Exists(path)) + { + return config; + } + + try + { + XElement root = XDocument.Load(path).Root; + if (root == null || root.Name.LocalName != _root) + { + config.Errors.Add($"{Path.GetFileName(path)}: not a house style file"); + return config; + } + + if (ParseInt((string)root.Attribute("version")) > _version) + { + config.Errors.Add($"{Path.GetFileName(path)}: written by a newer version of the editor"); + return config; + } + + foreach (XElement element in root.Elements("Style")) + { + HouseStyleEntry entry = ReadStyle(element); + if (entry != null) + { + config.Styles.Add(entry); + } + else + { + config.Errors.Add($"{Path.GetFileName(path)}: a Style without a kind or an anchor (line {((IXmlLineInfo)element).LineNumber})"); + } + } + } + catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException) + { + config.Errors.Add($"{Path.GetFileName(path)}: {ex.Message}"); + } + + return config; + } + + /// + /// Lays another file's entries over these. An entry for a style both name takes the other + /// file's values where it gives any; its other entries are added at the end. + /// + public void Merge(HouseStyleConfig other) + { + Dictionary<(HousePartKind, ushort, bool), HouseStyleEntry> mine = Styles + .GroupBy(entry => entry.Key) + .ToDictionary(group => group.Key, group => group.First()); + foreach (HouseStyleEntry theirs in other.Styles) + { + if (!mine.TryGetValue(theirs.Key, out HouseStyleEntry entry)) + { + Styles.Add(theirs); + mine[theirs.Key] = theirs; + continue; + } + + entry.Name = theirs.Name ?? entry.Name; + entry.Group = theirs.Group ?? entry.Group; + entry.Family = theirs.Family ?? entry.Family; + entry.Hidden = theirs.Hidden ?? entry.Hidden; + entry.Layout = theirs.Layout ?? entry.Layout; + entry.Borrows = theirs.Borrows ?? entry.Borrows; + entry.Pieces = theirs.Pieces ?? entry.Pieces; + if (theirs.Replaces.Count > 0) + { + entry.Replaces.Clear(); + entry.Replaces.AddRange(theirs.Replaces); + } + } + + Errors.AddRange(other.Errors); + } + + public void Save(string path) + { + var root = new XElement(_root, new XAttribute("version", _version)); + foreach (HouseStyleEntry entry in Styles) + { + root.Add(WriteStyle(entry)); + } + + Directory.CreateDirectory(Path.GetDirectoryName(path) ?? string.Empty); + new XDocument(root).Save(path); + } + + private static HouseStyleEntry ReadStyle(XElement element) + { + if (!Enum.TryParse((string)element.Attribute("kind"), out HousePartKind kind) || + !TryParseId((string)element.Attribute("anchor"), out ushort anchor) || anchor == 0) + { + return null; + } + + var entry = new HouseStyleEntry + { + Kind = kind, + Anchor = anchor, + IsNew = (bool?)element.Attribute("new") ?? false, + Name = (string)element.Attribute("name"), + Group = (string)element.Attribute("group"), + Family = (string)element.Attribute("family"), + Hidden = (bool?)element.Attribute("hidden"), + Layout = (string)element.Attribute("layout"), + Borrows = (bool?)element.Attribute("borrows") + }; + foreach (string text in ((string)element.Attribute("replaces") ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (TryParseId(text, out ushort id)) + { + entry.Replaces.Add(id); + } + } + + List pieces = element.Elements("Piece").ToList(); + if (pieces.Count > 0) + { + entry.Pieces = new List<(string, ushort)>(); + foreach (XElement piece in pieces) + { + string role = (string)piece.Attribute("role"); + if (!string.IsNullOrEmpty(role) && TryParseId((string)piece.Attribute("id"), out ushort id)) + { + entry.Pieces.Add((role, id)); + } + } + } + + return entry; + } + + private static XElement WriteStyle(HouseStyleEntry entry) + { + var element = new XElement("Style", + new XAttribute("kind", entry.Kind), + new XAttribute("anchor", FormatId(entry.Anchor))); + if (entry.IsNew) + { + element.Add(new XAttribute("new", true)); + } + + if (entry.Replaces.Count > 0) + { + element.Add(new XAttribute("replaces", string.Join(" ", entry.Replaces.Select(FormatId)))); + } + + AddText(element, "name", entry.Name); + AddText(element, "group", entry.Group); + AddText(element, "family", entry.Family); + AddText(element, "layout", entry.Layout); + if (entry.Hidden.HasValue) + { + element.Add(new XAttribute("hidden", entry.Hidden.Value)); + } + + if (entry.Borrows.HasValue) + { + element.Add(new XAttribute("borrows", entry.Borrows.Value)); + } + + if (entry.Pieces != null) + { + foreach ((string role, ushort id) in entry.Pieces) + { + element.Add(new XElement("Piece", new XAttribute("role", role), new XAttribute("id", FormatId(id)))); + } + } + + return element; + } + + private static void AddText(XElement element, string name, string value) + { + if (value != null) + { + element.Add(new XAttribute(name, value)); + } + } + + public static string FormatId(ushort id) => "0x" + id.ToString("X4", CultureInfo.InvariantCulture); + + public static bool TryParseId(string text, out ushort id) + { + id = 0; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + text = text.Trim(); + return text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + ? ushort.TryParse(text.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id) + : ushort.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out id); + } + + private static int ParseInt(string text) => int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) ? value : 0; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs index 0d2d73d5..edf66c74 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs @@ -11,6 +11,7 @@ using System; using System.Collections.Generic; +using System.Linq; using UoFiddler.Controls.Classes.TilesInfo; namespace UoFiddler.Plugin.MultiEditor.Classes @@ -44,12 +45,46 @@ public HouseStyle(HousePartKind kind, string group, string name) public HousePartKind Kind { get; } /// The category name (the first style's comment), grouping a material's styles. - public string Group { get; } + public string Group { get; internal set; } - public string Name { get; } + public string Name { get; internal set; } + + /// The material, shared by the styles of every kind made of it. From the style file; may be empty. + public string Family { get; internal set; } = string.Empty; + + /// True for a style the style file keeps out of the lists. + public bool Hidden { get; internal set; } + + /// A piece that tells the style from every other of its kind: how files refer to it. 0 when it has none. + public ushort Anchor { get; internal set; } + + /// False for a wall style that takes no post or corner from the other rows of its category. + internal bool Borrows { get; set; } = true; + + /// The table category the style was read from, counted over all tables. + internal int Category { get; set; } = -1; + + /// True for a wall style of a category sorted by its art. + internal bool ByArt { get; set; } public IReadOnlyDictionary Slots => _slots; + /// + /// True for a wall style whose run pieces are the two halves of an ornament (the shadow + /// banner): South1 and South3 along X, East3 and East1 along Y, with South2 and East2 the + /// plain wall. A run is then laid as pairs, not as start, middle and end. + /// + public bool Paired { get; internal set; } + + /// + /// For a wall style that is a set of different panels (the carved red marble): how many + /// it has along X (CycleSouth1 ...) and along Y (CycleEast1 ...). A run is laid as one + /// panel after another, starting again after the last. 0 for an ordinary style. + /// + public int CycleSouth { get; internal set; } + + public int CycleEast { get; internal set; } + /// A piece to show for the style in lists. public ushort IconId { get; private set; } @@ -65,6 +100,12 @@ internal void Add(string label, ushort id) } } + internal void Clear() + { + _slots.Clear(); + IconId = 0; + } + public override string ToString() => Name; } @@ -104,15 +145,23 @@ private HouseStyles() /// /// 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. + /// floor laid with a style does not mix them. The style file () + /// then names, groups, orders and corrects what the tables give. /// public static HouseStyles Load(bool splitFloorsByColour = false) + { + return Load(splitFloorsByColour, HouseStyleConfig.Load()); + } + + internal static HouseStyles Load(bool splitFloorsByColour, HouseStyleConfig config) { // New tables mean the client files may have changed: measure the art again. ArtFacing.Clear(); var result = new HouseStyles(); + var wallNamesUsed = new HashSet(System.StringComparer.OrdinalIgnoreCase); List files = TileGroupRegistry.LoadAll(out List errors); + int categoryNumber = 0; foreach (TileGroupFile file in files) { if (!_kinds.TryGetValue(file.DisplayName, out HousePartKind kind)) @@ -122,19 +171,48 @@ public static HouseStyles Load(bool splitFloorsByColour = false) foreach (TileCategory category in file.Categories) { - foreach (TileStyle tileStyle in category.Styles) + int number = categoryNumber++; + + // A roof set with more pieces than a row of roof.txt holds runs on into a second + // row of its category: the rows are one style. + if (kind == HousePartKind.Roof) { - var style = new HouseStyle(kind, category.Name, tileStyle.Name); - foreach (TileSlot slot in tileStyle.Slots) + HouseStyle roof = RoofStyle(category); + if (roof.Slots.Count > 0) { - // 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)) + roof.Category = number; + result.Styles.Add(roof); + } + + continue; + } + + // A category whose pieces are mostly not what their headings say is sorted by its art. + bool byArt = kind == HousePartKind.Wall && HeadingsAreOff(category); + + // Wall rows are named so that each row of a category can be told from the others. + (string wallGroup, List wallNames) = kind == HousePartKind.Wall ? WallNames(category, wallNamesUsed, byArt) : (null, null); + for (int row = 0; row < category.Styles.Count; ++row) + { + TileStyle tileStyle = category.Styles[row]; + var style = new HouseStyle(kind, wallGroup ?? category.Name, wallNames != null ? wallNames[row] : tileStyle.Name); + if (byArt) + { + SortByArt(style, PiecesOf(tileStyle), WindowPieces(tileStyle)); + } + else + { + foreach (TileSlot slot in tileStyle.Slots) { - continue; - } + // Stairs list stair multis; they are multi ids, not art. + bool multiColumn = IsMultiColumn(slot.Label); + if (slot.IsEmpty || slot.TileId > ushort.MaxValue || (!multiColumn && !slot.IsValid)) + { + continue; + } - style.Add(slot.Label, (ushort)slot.TileId); + style.Add(slot.Label, (ushort)slot.TileId); + } } if (style.Slots.Count == 0) @@ -147,24 +225,633 @@ public static HouseStyles Load(bool splitFloorsByColour = false) : new[] { style }; foreach (HouseStyle part in parts) { + part.Category = number; + part.ByArt = byArt; 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.Apply(config); + result.BuildRoles(); + result.FinishWalls(); + result.Order(); + result.Errors.AddRange(errors); + if (config != null) + { + result.Errors.AddRange(config.Errors); + } + return result; } + /// Stairs list stair multis under "Multi" columns: multi ids, not art. + private static bool IsMultiColumn(string label) => label.StartsWith("Multi", System.StringComparison.Ordinal); + + // Where each style named by the style file comes in the lists. + private readonly Dictionary _rank = new Dictionary(); + + /// + /// Applies the style file to the styles read from the tables. An entry finds its style by + /// a piece (its anchor): the first style of the kind that lists it. It can rename and + /// regroup the style, give it other pieces, and take the place of further styles (a set + /// the table spreads over several rows). An entry whose pieces this client has no art for + /// is left out, so one file serves every client. + /// + private void Apply(HouseStyleConfig config) + { + var owners = new Dictionary<(HousePartKind Kind, ushort Id), HouseStyle>(); + foreach (HouseStyle style in Styles) + { + foreach (KeyValuePair piece in style.Slots) + { + if (!IsMultiColumn(piece.Key)) + { + owners.TryAdd((style.Kind, piece.Value), style); + } + } + } + + foreach (HouseStyle style in Styles) + { + foreach (KeyValuePair piece in style.Slots) + { + if (!IsMultiColumn(piece.Key) && owners[(style.Kind, piece.Value)] == style) + { + style.Anchor = piece.Value; + break; + } + } + } + + if (config == null) + { + return; + } + + var removed = new HashSet(); + foreach (HouseStyleEntry entry in config.Styles) + { + List<(string Role, ushort Id)> pieces = entry.Pieces? + .Where(piece => IsMultiColumn(piece.Role) || (piece.Id < Ultima.TileData.ItemTable.Length && Ultima.Art.IsValidStatic(piece.Id))) + .ToList(); + if (pieces != null && !pieces.Any(piece => !IsMultiColumn(piece.Role))) + { + continue; + } + + HouseStyle target = null; + if (!entry.IsNew) + { + owners.TryGetValue((entry.Kind, entry.Anchor), out target); + } + + if (target == null) + { + // A style of the file's own. It stands where the first style it replaces stood. + if (pieces == null) + { + continue; + } + + HouseStyle first = null; + foreach (ushort id in entry.Replaces) + { + if (owners.TryGetValue((entry.Kind, id), out first)) + { + break; + } + } + + target = new HouseStyle(entry.Kind, entry.Group ?? entry.Name ?? string.Empty, entry.Name ?? string.Empty) + { + Category = first?.Category ?? -1, + ByArt = first?.ByArt ?? false + }; + int at = first != null ? Styles.IndexOf(first) : -1; + Styles.Insert(at >= 0 ? at : Styles.Count, target); + } + + if (pieces != null) + { + target.Clear(); + foreach ((string role, ushort id) in pieces) + { + target.Add(role, id); + } + } + + foreach (ushort id in entry.Replaces) + { + if (owners.TryGetValue((entry.Kind, id), out HouseStyle other) && other != target) + { + removed.Add(other); + } + } + + target.Anchor = entry.Anchor != 0 ? entry.Anchor : target.IconId; + target.Name = entry.Name ?? target.Name; + target.Group = entry.Group ?? target.Group; + target.Family = entry.Family ?? target.Family; + target.Hidden = entry.Hidden ?? target.Hidden; + target.Borrows = entry.Borrows ?? target.Borrows; + if (entry.Layout != null) + { + target.Paired = entry.Layout == HouseStyleEntry.LayoutPaired; + bool cycle = entry.Layout == HouseStyleEntry.LayoutCycle; + target.CycleSouth = cycle ? target.Slots.Keys.Count(label => label.StartsWith("CycleSouth", System.StringComparison.Ordinal)) : 0; + target.CycleEast = cycle ? target.Slots.Keys.Count(label => label.StartsWith("CycleEast", System.StringComparison.Ordinal)) : 0; + } + + _rank[target] = _rank.Count; + } + + Styles.RemoveAll(removed.Contains); + } + + /// + /// The lookup from a tile to its style and column: the first style that lists it. A panel + /// of a style that goes through its panels in turn counts as a plain run piece for + /// everything that asks what a tile is (redrawing, turning). + /// + private void BuildRoles() + { + foreach (HouseStyle style in Styles) + { + foreach (KeyValuePair piece in style.Slots) + { + if (IsMultiColumn(piece.Key)) + { + continue; + } + + string label = piece.Key.StartsWith("CycleSouth", System.StringComparison.Ordinal) ? "South2" + : piece.Key.StartsWith("CycleEast", System.StringComparison.Ordinal) ? "East2" + : piece.Key; + _roles.TryAdd(piece.Value, (style, label)); + } + } + } + + /// + /// Makes every wall style build whole walls: empty run columns are filled, a row without a + /// post borrows one from its category, and in a category sorted by its art corners and + /// posts are lent between the rows. A style the file marks as not borrowing is two or + /// three pieces on their own and stays as it is. + /// + private void FinishWalls() + { + var posts = new Dictionary>(); + var sorted = new Dictionary>(); + foreach (HouseStyle style in Styles) + { + if (style.Kind != HousePartKind.Wall) + { + continue; + } + + if (style.ByArt && style.Borrows) + { + if (!sorted.TryGetValue(style.Category, out List rows)) + { + sorted[style.Category] = rows = new List(); + } + + rows.Add(style); + } + + FillWallRuns(style, style.Get("CycleSouth1"), style.Get("CycleEast1")); + + // A row without a post (Celtic Walls 2) borrows the one of an earlier row + // of its category that is as high: the same wall, differently decorated. + if (!posts.TryGetValue(style.Category, out List categoryPosts)) + { + posts[style.Category] = categoryPosts = new List(); + } + + ushort post = style.Get("Post"), straight = style.Get("South1"); + if (post != 0) + { + categoryPosts.Add(post); + } + else if (straight != 0 && style.Borrows) + { + foreach (ushort other in categoryPosts) + { + if (Ultima.TileData.ItemTable[other].Height == Ultima.TileData.ItemTable[straight].Height) + { + style.Add("Post", other); + break; + } + } + } + } + + foreach (List rows in sorted.Values) + { + LendCornersAndPosts(rows); + } + } + + /// + /// Puts the styles in the style file's order. A style the file does not name (one only + /// another client version has) stays behind the style it follows in the tables. + /// + private void Order() + { + if (_rank.Count == 0) + { + return; + } + + var last = new Dictionary(); + var keys = new Dictionary(); + for (int i = 0; i < Styles.Count; ++i) + { + HouseStyle style = Styles[i]; + if (_rank.TryGetValue(style, out int rank)) + { + last[style.Kind] = rank; + } + else if (!last.TryGetValue(style.Kind, out rank)) + { + rank = -1; + } + + keys[style] = (rank, _rank.ContainsKey(style) ? -1 : i); + } + + List ordered = Styles.OrderBy(style => keys[style].Rank).ThenBy(style => keys[style].Index).ToList(); + Styles.Clear(); + Styles.AddRange(ordered); + } + + /// + /// In a category sorted by its art, a row often has walls but no corner or post of its + /// own: the set's corners and posts sit in another row. Such a style takes the first + /// piece of the category that is a corner (or post) of its walls' height. + /// + private static void LendCornersAndPosts(List styles) + { + static int Class(ushort id) => Ultima.TileData.ItemTable[id].Height >= 15 ? 2 : Ultima.TileData.ItemTable[id].Height >= 8 ? 1 : 0; + var pieces = new List(); + foreach (HouseStyle style in styles) + { + foreach (ushort id in style.Slots.Values) + { + if (!pieces.Contains(id)) + { + pieces.Add(id); + } + } + } + + foreach (HouseStyle style in styles) + { + ushort wall = style.Get("South1") != 0 ? style.Get("South1") : style.Get("East1"); + if (wall == 0) + { + continue; + } + + foreach ((string column, TilePlacement placement) in new[] { ("Corner", TilePlacement.Cell), ("Post", TilePlacement.Vertex) }) + { + if (style.Get(column) != 0) + { + continue; + } + + foreach (ushort id in pieces) + { + if (Class(id) == Class(wall) && ArtFacing.Placement(id) == placement && + (Ultima.TileData.ItemTable[id].Flags & Ultima.TileFlag.Window) == 0) + { + style.Add(column, id); + break; + } + } + } + } + } + + /// The pieces a row lists under its window headings. + private static HashSet WindowPieces(TileStyle row) + { + var ids = new HashSet(); + foreach (TileSlot slot in row.Slots) + { + if (!slot.IsEmpty && slot.IsValid && slot.TileId <= ushort.MaxValue && slot.Label.Contains("Window", System.StringComparison.Ordinal)) + { + ids.Add((ushort)slot.TileId); + } + } + + return ids; + } + + /// The pieces a row lists, each once, in the row's order. + private static List PiecesOf(TileStyle row) + { + var ids = new List(); + foreach (TileSlot slot in row.Slots) + { + if (!slot.IsEmpty && slot.IsValid && slot.TileId <= ushort.MaxValue && !ids.Contains((ushort)slot.TileId)) + { + ids.Add((ushort)slot.TileId); + } + } + + return ids; + } + + private static readonly string[] _southWindows = { "WindowS", "AltWindowS", "SecondAltWindowS" }; + private static readonly string[] _eastWindows = { "WindowE", "AltWindowE", "SecondAltWindowE" }; + + /// What a wall column's heading says its piece is. + private static TilePlacement HeadingPlacement(string label) + { + return label == "Corner" ? TilePlacement.Cell + : label == "Post" ? TilePlacement.Vertex + : label.StartsWith("South", System.StringComparison.Ordinal) || label.EndsWith("S", System.StringComparison.Ordinal) ? TilePlacement.SouthEdge + : TilePlacement.EastEdge; + } + + /// + /// True for a walls.txt category where at least three pieces in ten are not what their + /// column heading says, going by the art: a piece under "South" that runs along Y, a + /// "Corner" that is a straight wall. All the gargish sets and the gothic one are like + /// that; in the other categories it is at most a spare window under "Corner". + /// + private static bool HeadingsAreOff(TileCategory category) + { + int pieces = 0, off = 0; + foreach (TileStyle row in category.Styles) + { + foreach (TileSlot slot in row.Slots) + { + if (slot.IsEmpty || !slot.IsValid || slot.TileId > ushort.MaxValue) + { + continue; + } + + ++pieces; + if (ArtFacing.Placement((ushort)slot.TileId) != HeadingPlacement(slot.Label)) + { + ++off; + } + } + } + + return pieces > 0 && off * 10 >= pieces * 3; + } + + /// + /// Fills a wall style from a row whose headings cannot be trusted. Each piece goes where + /// its art says: a wall along X to the South columns, one along Y to the East columns, a + /// piece that fills its cell's corner to Corner, a column to Post, windows to the window + /// columns. The pieces keep the row's order. What does not fit (a fourth wall along X, a + /// second corner, a piece of another height than most of the row) stays with the style as + /// a "More" piece, to place by hand. + /// + private static void SortByArt(HouseStyle style, List ids, HashSet listedAsWindows) + { + if (ids.Count == 0) + { + return; + } + + // The row's usual height: full, half or low walls. + static int Class(ushort id) => Ultima.TileData.ItemTable[id].Height >= 15 ? 2 : Ultima.TileData.ItemTable[id].Height >= 8 ? 1 : 0; + int usual = ids.GroupBy(Class).OrderByDescending(g => g.Count()).ThenByDescending(g => g.Key).First().Key; + + int more = 0; + void Put(string[] columns, ushort id) + { + foreach (string column in columns) + { + if (style.Get(column) == 0) + { + style.Add(column, id); + return; + } + } + + style.Add($"More{++more}", id); + } + + foreach (ushort id in ids) + { + // An arch or opening the table lists under a window heading is one, flagged or not. + bool window = (Ultima.TileData.ItemTable[id].Flags & Ultima.TileFlag.Window) != 0 || listedAsWindows.Contains(id); + if (Class(id) != usual) + { + style.Add($"More{++more}", id); + continue; + } + + switch (ArtFacing.Placement(id)) + { + case TilePlacement.SouthEdge: + Put(window ? _southWindows : _southRun, id); + break; + case TilePlacement.EastEdge: + Put(window ? _eastWindows : _eastRun, id); + break; + case TilePlacement.Vertex: + Put(new[] { "Post" }, id); + break; + default: + Put(new[] { "Corner" }, id); + break; + } + } + } + + private static readonly string[] _southRun = { "South1", "South2", "South3" }; + private static readonly string[] _eastRun = { "East1", "East2", "East3" }; + + /// + /// Many wall rows list one piece per direction where the table has three columns (the + /// start, middle and end of a run): the later sets, and most half and quarter walls. A + /// run built from such a row had holes. The columns a row leaves empty take the piece of + /// the nearest one it has, so every row builds whole walls. (The piece keeps the one role + /// it is listed under.) + /// + private static void FillWallRuns(HouseStyle style, ushort south = 0, ushort east = 0) + { + foreach (string[] run in new[] { _southRun, _eastRun }) + { + // The middle piece first: it stands in best for a missing end, and an end for a missing middle. + ushort have = style.Get(run[1]) != 0 ? style.Get(run[1]) : style.Get(run[0]) != 0 ? style.Get(run[0]) : style.Get(run[2]); + if (have == 0) + { + have = run == _southRun ? south : east; + } + if (have == 0) + { + continue; + } + + foreach (string column in run) + { + if (style.Get(column) == 0) + { + style.Add(column, have); + } + } + } + } + + private static readonly string[] _wallFillerWords = { "Standard", "Walls", "Wall", "Set", "Style", "-" }; + + /// + /// The group and the row names of a walls.txt category. The table's comments name many + /// rows alike ("Carved Wood 1" four times: full, windowed, half and quarter walls) or only + /// by number ("Crystal Walls 2"). The group is the material: what the rows' names share, + /// without filler words and numbers. A row whose name is used twice, or is only numbered, + /// is named by what it holds instead: material + Walls, Window Walls, Half Walls or + /// Quarter Walls, by the height of its pieces. Other rows keep their comment. + /// + private static (string Group, List Names) WallNames(TileCategory category, HashSet used, bool byArt) + { + var raw = new List(); + foreach (TileStyle row in category.Styles) + { + string name = (row.Name ?? string.Empty).Trim().TrimEnd('\\').Trim(); + raw.Add(name); + } + + // The material: the words every row starts with. + string[] first = raw.Count > 0 ? raw[0].Split(' ', System.StringSplitOptions.RemoveEmptyEntries) : System.Array.Empty(); + int shared = first.Length; + foreach (string name in raw) + { + string[] words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries); + int same = 0; + while (same < shared && same < words.Length && string.Equals(words[same], first[same], System.StringComparison.OrdinalIgnoreCase)) + { + ++same; + } + + shared = same; + } + + // A category of two materials (Weathered Stone and Granite) shares no words: it goes by its first row. + bool oneMaterial = shared > 0; + var material = new List(first.Take(oneMaterial ? shared : first.Length)); + + // "Gargish Wall Set 2": the set's number is part of what it is, as there are three such categories. + string set = material.Count >= 3 && material[^2] == "Set" && int.TryParse(material[^1], out _) ? " Set " + material[^1] : string.Empty; + while (material.Count > 0 && (System.Array.IndexOf(_wallFillerWords, material[^1]) >= 0 || int.TryParse(material[^1], out _))) + { + material.RemoveAt(material.Count - 1); + } + + string group = material.Count > 0 ? string.Join(" ", material) + set : (category.Name ?? string.Empty).Trim(); + if (group.Length > 0) + { + group = char.ToUpperInvariant(group[0]) + group.Substring(1); + } + + var names = new List(); + for (int row = 0; row < raw.Count; ++row) + { + string name = raw[row]; + string[] words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries); + // In a category sorted by its art the comments say little: any numbered row of the material is renamed. + bool numbered = words.Length >= 2 && int.TryParse(words[^1], out _) && + (words[^2] is "Walls" or "Wall" or "Set" || raw.Count(n => n == name) > 1 || + (byArt && material.Count > 0 && name.StartsWith(string.Join(" ", material), System.StringComparison.OrdinalIgnoreCase))); + bool vague = raw.Count(n => string.Equals(n, name, System.StringComparison.OrdinalIgnoreCase)) > 1 || numbered || + name.Contains(" - Style", System.StringComparison.Ordinal); + if (vague && oneMaterial && material.Count > 0) + { + string kindName = WallKind(category.Styles[row]); + name = kindName == "Window Walls" && group.Contains("Window", System.StringComparison.OrdinalIgnoreCase) ? group : group + " " + kindName; + } + + // Two rows of one kind: the second and later ones are numbered. + string unique = name; + for (int n = 2; !used.Add(unique); ++n) + { + unique = $"{name} {n}"; + } + + names.Add(unique); + } + + return (group, names); + } + + /// What a wall row holds, by its pieces: their usual height, and whether most are windows. + private static string WallKind(TileStyle row) + { + var heights = new List(); + int windows = 0; + foreach (TileSlot slot in row.Slots) + { + if (slot.IsEmpty || slot.TileId > ushort.MaxValue || !slot.IsValid) + { + continue; + } + + heights.Add(Ultima.TileData.ItemTable[slot.TileId].Height); + if ((Ultima.TileData.ItemTable[slot.TileId].Flags & Ultima.TileFlag.Window) != 0) + { + ++windows; + } + } + + if (heights.Count == 0) + { + return "Walls"; + } + + heights.Sort(); + int height = heights[heights.Count / 2]; + return height >= 15 ? (windows * 2 > heights.Count ? "Window Walls" : "Walls") : height >= 8 ? "Half Walls" : "Quarter Walls"; + } + + /// + /// One style from the rows of a roof.txt category, named after the category without its + /// row number ("Straw Roof 1" and "Straw Roof 2" are "Straw Roof"). The first row's pieces + /// keep their column headings; the pieces of a further row are extras of the set, kept + /// under "More" + heading so they still count as its roof pieces. Sets whose rows do not + /// follow the headings (ceramic, crystal, shadow) get their pieces from the style file, + /// which has labels for what the headings have no word for: Eave + side (a slope with + /// the roof's edge), Hip + corner (a hip line), HipEave + corner, NSEnd and EWEnd. + /// + private static HouseStyle RoofStyle(TileCategory category) + { + string name = category.Name ?? string.Empty; + if (name.EndsWith(" 1", System.StringComparison.Ordinal)) + { + name = name.Substring(0, name.Length - 2); + } + + var style = new HouseStyle(HousePartKind.Roof, name, name); + for (int row = 0; row < category.Styles.Count; ++row) + { + foreach (TileSlot slot in category.Styles[row].Slots) + { + if (slot.IsEmpty || slot.TileId > ushort.MaxValue || !slot.IsValid) + { + continue; + } + + string label = row == 0 ? slot.Label : "More" + slot.Label; + if (style.Get(label) == 0) + { + style.Add(label, (ushort)slot.TileId); + } + } + } + + return style; + } + /// How far apart two radar colours may be (RGB distance) and still count as one floor colour. private const int _sameColour = 20; diff --git a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs b/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs index 6dacbc84..f930d0e5 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs @@ -173,7 +173,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 +207,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/MultiEditorHouseStyles.xml b/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml new file mode 100644 index 00000000..d20ccd03 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml @@ -0,0 +1,831 @@ + + + + + + + + + + + + + + + + + + + + + + + +