diff --git a/UoFiddler.Controls/UserControls/MapControl.Designer.cs b/UoFiddler.Controls/UserControls/MapControl.Designer.cs
index 6f23940e..ee1b26b8 100644
--- a/UoFiddler.Controls/UserControls/MapControl.Designer.cs
+++ b/UoFiddler.Controls/UserControls/MapControl.Designer.cs
@@ -63,6 +63,7 @@ private void InitializeComponent()
this.getMapInfoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.insertMarkerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
+ this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.gotoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.TextBoxGoto = new System.Windows.Forms.ToolStripTextBox();
this.sendClientToPosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@@ -199,6 +200,7 @@ private void InitializeComponent()
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.zoomToolStripMenuItem,
this.zoomToolStripMenuItem1,
+ this.toolStripSeparator9,
this.getMapInfoToolStripMenuItem,
this.insertMarkerToolStripMenuItem,
this.toolStripSeparator4,
@@ -246,6 +248,11 @@ private void InitializeComponent()
this.insertMarkerToolStripMenuItem.Text = "Insert Marker";
this.insertMarkerToolStripMenuItem.Click += new System.EventHandler(this.OnClickInsertMarker);
//
+ // toolStripSeparator9
+ //
+ this.toolStripSeparator9.Name = "toolStripSeparator9";
+ this.toolStripSeparator9.Size = new System.Drawing.Size(168, 6);
+ //
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
@@ -855,6 +862,7 @@ private void InitializeComponent()
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
+ private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.ToolStripMenuItem trammelToolStripMenuItem;
private System.Windows.Forms.VScrollBar vScrollBar;
diff --git a/UoFiddler.Plugin.MapPreview/Facets.cs b/UoFiddler.Plugin.MapPreview/Facets.cs
new file mode 100644
index 00000000..bf9f95ec
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/Facets.cs
@@ -0,0 +1,60 @@
+/***************************************************************************
+ *
+ * "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 Ultima;
+using UoFiddler.Controls.Classes;
+
+namespace UoFiddler.Plugin.MapPreview
+{
+ ///
+ /// The six facets by index. A preview keeps the index, not the , because a
+ /// client reload can put a new instance in the static field.
+ ///
+ internal static class Facets
+ {
+ public const int Count = 6;
+
+ /// The facet's index, or -1 for a map that is not one of the six.
+ public static int IndexOf(Map map)
+ {
+ for (int i = 0; i < Count; i++)
+ {
+ if (ReferenceEquals(Get(i), map))
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ public static Map Get(int index)
+ {
+ return index switch
+ {
+ 0 => Map.Felucca,
+ 1 => Map.Trammel,
+ 2 => Map.Ilshenar,
+ 3 => Map.Malas,
+ 4 => Map.Tokuno,
+ 5 => Map.TerMur,
+ _ => null
+ };
+ }
+
+ /// The name the map tab shows, which the user can change in the options.
+ public static string Name(int index, Map map)
+ {
+ string[] names = Options.MapNames;
+ return index >= 0 && names != null && index < names.Length && !string.IsNullOrEmpty(names[index])
+ ? names[index]
+ : $"Map{map?.FileIndex}";
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/MapPreviewPluginBase.cs b/UoFiddler.Plugin.MapPreview/MapPreviewPluginBase.cs
new file mode 100644
index 00000000..cd0985ac
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/MapPreviewPluginBase.cs
@@ -0,0 +1,91 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Drawing;
+using System.Windows.Forms;
+using Ultima;
+using UoFiddler.Controls.Plugin;
+using UoFiddler.Controls.Plugin.Interfaces;
+using UoFiddler.Plugin.MapPreview.UI;
+
+namespace UoFiddler.Plugin.MapPreview
+{
+ /// Adds "In-game preview here..." to the map tab's context menu.
+ public class MapPreviewPluginBase : PluginBase
+ {
+ public override string Author { get; } = "UOFiddler";
+
+ public override string Description { get; } = "Previews a map area as the client draws it\r\n(Adds a map context menu entry and a settings entry under Plugins)";
+
+ public override IPluginHost Host { get; set; }
+
+ public override string Name { get; } = "MapPreviewPlugin";
+
+ public override string Version { get; } = "1.0.0";
+
+ public override void Initialize()
+ {
+ // The Manage Plugins form also constructs disabled plugins, so events are
+ // subscribed here and not in the constructor.
+ PluginEvents.ModifyMapControlContextMenuEvent += OnMapContextMenu;
+ }
+
+ public override void Unload()
+ {
+ PluginEvents.ModifyMapControlContextMenuEvent -= OnMapContextMenu;
+ _window?.Close();
+ }
+
+ public override void ModifyPluginToolStrip(ToolStripDropDownButton toolStrip)
+ {
+ var settings = new ToolStripMenuItem { Text = "In-game preview settings..." };
+ settings.Click += (_, _) => MapPreviewForm.EditSettings(toolStrip.Owner?.FindForm());
+ toolStrip.DropDownItems.Add(settings);
+ }
+
+ public override void ModifyTabPages(TabControl tabControl)
+ {
+ }
+
+ /// The one preview window, reused for every spot until it is closed.
+ private MapPreviewForm _window;
+
+ private void OnMapContextMenu(ContextMenuStrip strip, Func<(Map Map, Point Location)> clickedAt)
+ {
+ var preview = new ToolStripMenuItem { Text = "In-game preview here" };
+ preview.Click += (_, _) =>
+ {
+ (Map map, Point location) = clickedAt();
+ if (map == null)
+ {
+ return;
+ }
+
+ if (_window == null || _window.IsDisposed)
+ {
+ _window = new MapPreviewForm();
+ _window.FormClosed += (_, _) => _window = null;
+ _window.Show(strip.SourceControl?.FindForm());
+ }
+ else if (_window.WindowState == FormWindowState.Minimized)
+ {
+ _window.WindowState = FormWindowState.Normal;
+ }
+
+ _window.ShowArea(map, location);
+ _window.Activate();
+ };
+
+ // Settings stay under Plugins only: next to this entry they were too easy to hit by mistake.
+ strip.Items.Add(new ToolStripSeparator());
+ strip.Items.Add(preview);
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/PreviewSettings.cs b/UoFiddler.Plugin.MapPreview/PreviewSettings.cs
new file mode 100644
index 00000000..a46888fd
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/PreviewSettings.cs
@@ -0,0 +1,155 @@
+/***************************************************************************
+ *
+ * "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.Globalization;
+using UoFiddler.Controls.Classes;
+using UoFiddler.Plugin.MapPreview.Rendering;
+
+namespace UoFiddler.Plugin.MapPreview
+{
+ ///
+ /// How a preview is made: the area around the clicked tile and what is drawn. Kept in the
+ /// profile (), so each profile has its own.
+ ///
+ public sealed class PreviewSettings
+ {
+ ///
+ /// The square areas offered, in tiles a side. The largest is about 11,000 pixels across at
+ /// 100% and around a hundred thousand sprites in a town: under a second to open.
+ ///
+ public static readonly int[] AreaSizes = { 32, 48, 64, 96, 128, 192, 256 };
+
+ /// How far one move of the area goes, in tiles: a nudge up to a jump.
+ public static readonly int[] MoveSteps = { 1, 8, 16, 32 };
+
+ private const string Prefix = "MapPreview.";
+
+ private static PreviewSettings _current;
+
+ /// Raised after settings were changed and stored.
+ public static event Action Changed;
+
+ /// The profile's settings, read on first use.
+ public static PreviewSettings Current => _current ??= Load();
+
+ public int AreaWidth { get; set; } = 64;
+
+ public int AreaHeight { get; set; } = 64;
+
+ public bool ShowLand { get; set; } = true;
+
+ public bool ShowStatics { get; set; } = true;
+
+ public bool Stretch { get; set; } = true;
+
+ public bool Lighting { get; set; } = true;
+
+ public bool Hues { get; set; } = true;
+
+ public bool HideRoofs { get; set; }
+
+ /// Cut everything above the ground at the clicked tile on every preview, as the client does indoors.
+ public bool AutoRoofCut { get; set; }
+
+ /// Max Z hides land too, to show statics under the terrain. Set on the preview's toolbar.
+ public bool CutLand { get; set; }
+
+ /// Tiles the area moves per arrow, one of .
+ public int MoveStep { get; set; } = 8;
+
+ public PreviewSettings Clone() => (PreviewSettings)MemberwiseClone();
+
+ public PreviewOptions ToOptions(int? maxZ) => new PreviewOptions
+ {
+ ShowLand = ShowLand,
+ ShowStatics = ShowStatics,
+ Stretch = Stretch,
+ Lighting = Lighting,
+ Hues = Hues,
+ HideRoofs = HideRoofs,
+ MaxZ = maxZ,
+ CutLand = CutLand
+ };
+
+ /// Makes these the current settings and puts them in the profile, which the application saves on exit.
+ public void Apply()
+ {
+ _current = this;
+
+ Write(nameof(AreaWidth), AreaWidth.ToString(CultureInfo.InvariantCulture));
+ Write(nameof(AreaHeight), AreaHeight.ToString(CultureInfo.InvariantCulture));
+ Write(nameof(ShowLand), ShowLand.ToString());
+ Write(nameof(ShowStatics), ShowStatics.ToString());
+ Write(nameof(Stretch), Stretch.ToString());
+ Write(nameof(Lighting), Lighting.ToString());
+ Write(nameof(Hues), Hues.ToString());
+ Write(nameof(HideRoofs), HideRoofs.ToString());
+ Write(nameof(AutoRoofCut), AutoRoofCut.ToString());
+ Write(nameof(CutLand), CutLand.ToString());
+ Write(nameof(MoveStep), MoveStep.ToString(CultureInfo.InvariantCulture));
+
+ Changed?.Invoke();
+ }
+
+ /// Reads the profile's settings; anything missing or unreadable keeps its default.
+ private static PreviewSettings Load()
+ {
+ var settings = new PreviewSettings();
+ settings.AreaWidth = NearestAreaSize(ReadInt(nameof(AreaWidth), settings.AreaWidth));
+ settings.AreaHeight = NearestAreaSize(ReadInt(nameof(AreaHeight), settings.AreaHeight));
+ settings.ShowLand = ReadBool(nameof(ShowLand), settings.ShowLand);
+ settings.ShowStatics = ReadBool(nameof(ShowStatics), settings.ShowStatics);
+ settings.Stretch = ReadBool(nameof(Stretch), settings.Stretch);
+ settings.Lighting = ReadBool(nameof(Lighting), settings.Lighting);
+ settings.Hues = ReadBool(nameof(Hues), settings.Hues);
+ settings.HideRoofs = ReadBool(nameof(HideRoofs), settings.HideRoofs);
+ settings.AutoRoofCut = ReadBool(nameof(AutoRoofCut), settings.AutoRoofCut);
+ settings.CutLand = ReadBool(nameof(CutLand), settings.CutLand);
+ int step = ReadInt(nameof(MoveStep), settings.MoveStep);
+ settings.MoveStep = Array.IndexOf(MoveSteps, step) >= 0 ? step : 8;
+ return settings;
+ }
+
+ /// The offered size closest to , for sizes saved before the list existed.
+ public static int NearestAreaSize(int size)
+ {
+ int best = AreaSizes[0];
+ foreach (int candidate in AreaSizes)
+ {
+ if (Math.Abs(candidate - size) < Math.Abs(best - size))
+ {
+ best = candidate;
+ }
+ }
+
+ return best;
+ }
+
+ private static void Write(string name, string value)
+ {
+ Options.PluginSettings[Prefix + name] = value;
+ }
+
+ private static int ReadInt(string name, int fallback)
+ {
+ return Options.PluginSettings.TryGetValue(Prefix + name, out string text) &&
+ int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)
+ ? value
+ : fallback;
+ }
+
+ private static bool ReadBool(string name, bool fallback)
+ {
+ return Options.PluginSettings.TryGetValue(Prefix + name, out string text) && bool.TryParse(text, out bool value)
+ ? value
+ : fallback;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/Rendering/HueTexture.cs b/UoFiddler.Plugin.MapPreview/Rendering/HueTexture.cs
new file mode 100644
index 00000000..c60cebec
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/Rendering/HueTexture.cs
@@ -0,0 +1,76 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using OpenTK.Graphics.OpenGL4;
+using Ultima;
+
+namespace UoFiddler.Plugin.MapPreview.Rendering
+{
+ ///
+ /// Every hue as one row of 32 colours, so a shader can recolour a pixel by looking its gray
+ /// level up in the hue's row.
+ ///
+ internal sealed class HueTexture : IDisposable
+ {
+ public const int ColorsPerHue = 32;
+
+ public HueTexture()
+ {
+ Hue[] hues = Hues.List ?? Array.Empty();
+ Count = Math.Max(1, hues.Length);
+
+ byte[] rgba = new byte[ColorsPerHue * Count * 4];
+ for (int h = 0; h < hues.Length; h++)
+ {
+ ushort[] colors = hues[h]?.Colors;
+ if (colors == null)
+ {
+ continue;
+ }
+
+ for (int c = 0; c < ColorsPerHue && c < colors.Length; c++)
+ {
+ int i = ((h * ColorsPerHue) + c) * 4;
+ ushort color = colors[c];
+ rgba[i] = Expand5((color >> 10) & 0x1F);
+ rgba[i + 1] = Expand5((color >> 5) & 0x1F);
+ rgba[i + 2] = Expand5(color & 0x1F);
+ rgba[i + 3] = 255;
+ }
+ }
+
+ Texture = GL.GenTexture();
+ GL.BindTexture(TextureTarget.Texture2D, Texture);
+ GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);
+ GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, ColorsPerHue, Count, 0,
+ PixelFormat.Rgba, PixelType.UnsignedByte, rgba);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
+ }
+
+ public int Texture { get; private set; }
+
+ /// How many hues the texture holds; a row index past this is not a hue.
+ public int Count { get; }
+
+ public void Dispose()
+ {
+ GL.DeleteTexture(Texture);
+ Texture = 0;
+ }
+
+ private static byte Expand5(int value)
+ {
+ return (byte)((value << 3) | (value >> 2));
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/Rendering/MapBatch.cs b/UoFiddler.Plugin.MapPreview/Rendering/MapBatch.cs
new file mode 100644
index 00000000..976281e1
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/Rendering/MapBatch.cs
@@ -0,0 +1,187 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using OpenTK.Graphics.OpenGL4;
+using UoFiddler.Rendering;
+
+namespace UoFiddler.Plugin.MapPreview.Rendering
+{
+ ///
+ /// The whole scene as one vertex buffer of quads, already in draw order. Each quad has four
+ /// explicit corners, so stretched land and upright sprites share one shader and one pass.
+ ///
+ internal sealed class MapBatch : IDisposable
+ {
+ /// x, y, u, v, layer, light, hue, partial, alpha.
+ public const int FloatsPerVertex = 9;
+
+ public const int FloatsPerQuad = FloatsPerVertex * 4;
+
+ private const string VertexSource = @"#version 330 core
+layout(location = 0) in vec2 aPos;
+layout(location = 1) in vec3 aUv;
+layout(location = 2) in vec4 aExtra;
+
+uniform vec2 uOrigin;
+uniform float uZoom;
+uniform vec2 uViewport;
+uniform float uAtlasSize;
+
+out vec3 vUv;
+out vec4 vExtra;
+
+void main()
+{
+ // Whole pixels, so art stays crisp. Shared corners snap alike, so land does not crack.
+ vec2 screen = floor((aPos - uOrigin) * uZoom + 0.5);
+ gl_Position = vec4(screen.x / uViewport.x * 2.0 - 1.0, 1.0 - screen.y / uViewport.y * 2.0, 0.0, 1.0);
+ vUv = vec3(aUv.xy / uAtlasSize, aUv.z);
+ vExtra = aExtra;
+}";
+
+ // Art is ARGB1555 widened to 8 bits, so red * 31 is the gray level a hue row is indexed by.
+ // A partial hue recolours only gray pixels.
+ private const string FragmentSource = @"#version 330 core
+in vec3 vUv;
+in vec4 vExtra;
+
+uniform sampler2DArray uAtlas;
+uniform sampler2D uHues;
+
+out vec4 fragColor;
+
+void main()
+{
+ // Art alpha is on or off. Filtering softens it at sprite edges when zoomed out, which would let
+ // the background show through as seams between land tiles, so it is made hard again.
+ vec4 color = texture(uAtlas, vUv);
+ if (color.a < 0.5)
+ {
+ discard;
+ }
+
+ color.rgb /= color.a;
+ color.a = 1.0;
+
+ float hue = vExtra.y;
+ if (hue >= 0.0)
+ {
+ bool gray = abs(color.r - color.g) < 0.02 && abs(color.g - color.b) < 0.02;
+ if (vExtra.z < 0.5 || gray)
+ {
+ int level = int(color.r * 31.0 + 0.5);
+ color.rgb = texelFetch(uHues, ivec2(level, int(hue)), 0).rgb;
+ }
+ }
+
+ fragColor = vec4(color.rgb * vExtra.x, color.a * vExtra.w);
+}";
+
+ private readonly ShaderProgram _shader;
+ private readonly int _vao;
+ private readonly int _vbo;
+ private readonly int _ebo;
+ private int _indexedQuads;
+ private int _quads;
+
+ public MapBatch()
+ {
+ _shader = new ShaderProgram(VertexSource, FragmentSource);
+ _vao = GL.GenVertexArray();
+ _vbo = GL.GenBuffer();
+ _ebo = GL.GenBuffer();
+
+ GL.BindVertexArray(_vao);
+ GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo);
+ GL.BindBuffer(BufferTarget.ElementArrayBuffer, _ebo);
+
+ const int stride = FloatsPerVertex * sizeof(float);
+ GL.EnableVertexAttribArray(0);
+ GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, stride, 0);
+ GL.EnableVertexAttribArray(1);
+ GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, stride, 2 * sizeof(float));
+ GL.EnableVertexAttribArray(2);
+ GL.VertexAttribPointer(2, 4, VertexAttribPointerType.Float, false, stride, 5 * sizeof(float));
+
+ GL.BindVertexArray(0);
+ }
+
+ /// Replaces the scene. holds quads.
+ public void Upload(float[] vertices, int quads)
+ {
+ _quads = quads;
+
+ GL.BindVertexArray(_vao);
+ GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo);
+ GL.BufferData(BufferTarget.ArrayBuffer, quads * FloatsPerQuad * sizeof(float), vertices,
+ BufferUsageHint.StaticDraw);
+
+ if (quads > _indexedQuads)
+ {
+ // Corners are top-left, top-right, bottom-left, bottom-right (for land: top, right,
+ // left, bottom), so both triangles fold along the right-left diagonal.
+ uint[] indices = new uint[quads * 6];
+ for (uint q = 0, i = 0; q < quads; q++)
+ {
+ uint v = q * 4;
+ indices[i++] = v;
+ indices[i++] = v + 1;
+ indices[i++] = v + 2;
+ indices[i++] = v + 2;
+ indices[i++] = v + 1;
+ indices[i++] = v + 3;
+ }
+
+ GL.BindBuffer(BufferTarget.ElementArrayBuffer, _ebo);
+ GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(uint), indices,
+ BufferUsageHint.StaticDraw);
+ _indexedQuads = quads;
+ }
+
+ GL.BindVertexArray(0);
+ }
+
+ /// Draws the scene with world point (originX, originY) at the top left of the viewport.
+ public void Draw(ArtAtlas atlas, HueTexture hues, float originX, float originY, float zoom, int viewportWidth,
+ int viewportHeight)
+ {
+ if (_quads == 0)
+ {
+ return;
+ }
+
+ _shader.Use();
+ GL.Uniform2(_shader.Uniform("uOrigin"), originX, originY);
+ GL.Uniform1(_shader.Uniform("uZoom"), zoom);
+ GL.Uniform2(_shader.Uniform("uViewport"), (float)viewportWidth, viewportHeight);
+ GL.Uniform1(_shader.Uniform("uAtlasSize"), (float)ArtAtlas.Size);
+ GL.Uniform1(_shader.Uniform("uAtlas"), 0);
+ GL.Uniform1(_shader.Uniform("uHues"), 1);
+
+ GL.ActiveTexture(TextureUnit.Texture0);
+ GL.BindTexture(TextureTarget.Texture2DArray, atlas.Texture);
+ GL.ActiveTexture(TextureUnit.Texture1);
+ GL.BindTexture(TextureTarget.Texture2D, hues.Texture);
+ GL.ActiveTexture(TextureUnit.Texture0);
+
+ GL.BindVertexArray(_vao);
+ GL.DrawElements(PrimitiveType.Triangles, _quads * 6, DrawElementsType.UnsignedInt, 0);
+ GL.BindVertexArray(0);
+ }
+
+ public void Dispose()
+ {
+ GL.DeleteBuffer(_vbo);
+ GL.DeleteBuffer(_ebo);
+ GL.DeleteVertexArray(_vao);
+ _shader.Dispose();
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/Rendering/MapMesh.cs b/UoFiddler.Plugin.MapPreview/Rendering/MapMesh.cs
new file mode 100644
index 00000000..06f38ec6
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/Rendering/MapMesh.cs
@@ -0,0 +1,221 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using Ultima;
+using UoFiddler.Plugin.MapPreview.Scene;
+using UoFiddler.Rendering;
+
+namespace UoFiddler.Plugin.MapPreview.Rendering
+{
+ /// What the preview shows. Changing any of it rebuilds the vertices.
+ public sealed record PreviewOptions
+ {
+ public bool ShowLand { get; init; } = true;
+
+ public bool ShowStatics { get; init; } = true;
+
+ public bool Stretch { get; init; } = true;
+
+ public bool Lighting { get; init; } = true;
+
+ public bool Hues { get; init; } = true;
+
+ public bool HideRoofs { get; init; }
+
+ /// Statics at or above this height are hidden; null shows all of them.
+ public int? MaxZ { get; init; }
+
+ ///
+ /// hides land too, so statics under the terrain show. The client's
+ /// roof cut never hides land, so this is off by default.
+ ///
+ public bool CutLand { get; init; }
+ }
+
+ /// A drawn quad, kept for hit testing. Corners run top, right, bottom, left.
+ internal readonly record struct MeshItem(DrawableKind Kind, int Index, PointF Top, PointF Right, PointF Bottom,
+ PointF Left);
+
+ /// Turns a sorted scene into quads for .
+ internal static class MapMesh
+ {
+ private const float TranslucentAlpha = 0.7f;
+
+ public static float[] Build(MapPreviewScene scene, Drawable[] order, PreviewOptions options, ArtAtlas atlas,
+ int hueCount, List items, out int quads, out RectangleF bounds)
+ {
+ items.Clear();
+ float[] vertices = new float[order.Length * MapBatch.FloatsPerQuad];
+ int v = 0;
+ float minX = float.MaxValue, minY = float.MaxValue, maxX = float.MinValue, maxY = float.MinValue;
+ int width = scene.Area.Width;
+
+ foreach (Drawable drawable in order)
+ {
+ MeshItem item;
+ if (drawable.Kind == DrawableKind.Land)
+ {
+ if (!options.ShowLand || LandCut(scene.Land[drawable.Index], options) ||
+ !TryLand(scene.Land[drawable.Index], drawable.Index, drawable.Index % width,
+ drawable.Index / width, options, atlas, vertices, ref v, out item))
+ {
+ continue;
+ }
+ }
+ else
+ {
+ SceneStatic s = scene.Statics[drawable.Index];
+ if (!options.ShowStatics || Hidden(s, options) ||
+ !TryStatic(s, drawable.Index, options, atlas, hueCount, vertices, ref v, out item))
+ {
+ continue;
+ }
+ }
+
+ items.Add(item);
+ foreach (PointF corner in new[] { item.Top, item.Right, item.Bottom, item.Left })
+ {
+ minX = Math.Min(minX, corner.X);
+ maxX = Math.Max(maxX, corner.X);
+ minY = Math.Min(minY, corner.Y);
+ maxY = Math.Max(maxY, corner.Y);
+ }
+ }
+
+ quads = v / MapBatch.FloatsPerQuad;
+ bounds = quads == 0 ? RectangleF.Empty : RectangleF.FromLTRB(minX, minY, maxX, maxY);
+ return vertices;
+ }
+
+ private static bool Hidden(in SceneStatic s, PreviewOptions options)
+ {
+ return (options.HideRoofs && (s.Flags & TileFlag.Roof) != 0) || (options.MaxZ is int maxZ && s.Z >= maxZ);
+ }
+
+ /// Land cut by the height, at the height it is sorted by: a stretched tile's middle.
+ private static bool LandCut(in SceneLand land, PreviewOptions options)
+ {
+ return options.CutLand && options.MaxZ is int maxZ &&
+ (options.Stretch && land.Stretched ? land.AverageZ : land.Z) >= maxZ;
+ }
+
+ private static bool TryLand(in SceneLand land, int index, int dx, int dy, PreviewOptions options, ArtAtlas atlas,
+ float[] vertices, ref int v, out MeshItem item)
+ {
+ float x = (dx - dy) * MapPreviewScene.TileHalf;
+ float row = (dx + dy) * MapPreviewScene.TileHalf;
+
+ if (options.Stretch && land.Stretched && atlas.TryGet(ArtAtlas.TexmapKey(land.TextureId), out AtlasSprite texmap))
+ {
+ var top = new PointF(x, row - (land.Top * MapPreviewScene.PixelsPerZ));
+ var right = new PointF(x + MapPreviewScene.TileHalf, row + MapPreviewScene.TileHalf - (land.Right * MapPreviewScene.PixelsPerZ));
+ var bottom = new PointF(x, row + MapPreviewScene.TileSize - (land.Bottom * MapPreviewScene.PixelsPerZ));
+ var left = new PointF(x - MapPreviewScene.TileHalf, row + MapPreviewScene.TileHalf - (land.Left * MapPreviewScene.PixelsPerZ));
+
+ // Half a texel in from the edge, so neighbouring sprites in the atlas never bleed in.
+ float u0 = texmap.X + 0.5f, v0 = texmap.Y + 0.5f;
+ float u1 = texmap.X + texmap.Width - 0.5f, v1 = texmap.Y + texmap.Height - 0.5f;
+
+ bool lit = options.Lighting;
+ Put(vertices, ref v, top, u0, v0, texmap.Layer, lit ? land.LightTop : 1f, -1, false, 1f);
+ Put(vertices, ref v, right, u1, v0, texmap.Layer, lit ? land.LightRight : 1f, -1, false, 1f);
+ Put(vertices, ref v, left, u0, v1, texmap.Layer, lit ? land.LightLeft : 1f, -1, false, 1f);
+ Put(vertices, ref v, bottom, u1, v1, texmap.Layer, lit ? land.LightBottom : 1f, -1, false, 1f);
+
+ item = new MeshItem(DrawableKind.Land, index, top, right, bottom, left);
+ return true;
+ }
+
+ if (!atlas.TryGet(ArtAtlas.LandKey(land.Id), out AtlasSprite art))
+ {
+ item = default;
+ return false;
+ }
+
+ float artTop = row - (land.Z * MapPreviewScene.PixelsPerZ);
+ AddSprite(vertices, ref v, art, x - MapPreviewScene.TileHalf, artTop, 1f, -1, false, 1f);
+
+ item = new MeshItem(DrawableKind.Land, index,
+ new PointF(x, artTop),
+ new PointF(x + MapPreviewScene.TileHalf, artTop + MapPreviewScene.TileHalf),
+ new PointF(x, artTop + MapPreviewScene.TileSize),
+ new PointF(x - MapPreviewScene.TileHalf, artTop + MapPreviewScene.TileHalf));
+ return true;
+ }
+
+ private static bool TryStatic(in SceneStatic s, int index, PreviewOptions options, ArtAtlas atlas, int hueCount,
+ float[] vertices, ref int v, out MeshItem item)
+ {
+ if (!atlas.TryGet(s.Id, out AtlasSprite art))
+ {
+ item = default;
+ return false;
+ }
+
+ float x = (s.X - s.Y) * MapPreviewScene.TileHalf;
+ float row = ((s.X + s.Y) * MapPreviewScene.TileHalf) - (s.Z * MapPreviewScene.PixelsPerZ);
+
+ // Bottom centre of the art on the bottom corner of the tile's diamond.
+ float left = x - (art.Width / 2);
+ float top = row + MapPreviewScene.TileSize - art.Height;
+
+ int hue = -1;
+ bool partial = false;
+ if (options.Hues)
+ {
+ int index0 = (s.Hue & 0x3FFF) - 1;
+ if (index0 >= 0 && index0 < hueCount)
+ {
+ hue = index0;
+ partial = (s.Hue & 0x8000) != 0 || (s.Flags & TileFlag.PartialHue) != 0;
+ }
+ }
+
+ float alpha = (s.Flags & TileFlag.Translucent) != 0 ? TranslucentAlpha : 1f;
+ AddSprite(vertices, ref v, art, left, top, 1f, hue, partial, alpha);
+
+ item = new MeshItem(DrawableKind.Static, index,
+ new PointF(left, top),
+ new PointF(left + art.Width, top),
+ new PointF(left + art.Width, top + art.Height),
+ new PointF(left, top + art.Height));
+ return true;
+ }
+
+ private static void AddSprite(float[] vertices, ref int v, in AtlasSprite art, float left, float top, float light,
+ int hue, bool partial, float alpha)
+ {
+ float right = left + art.Width;
+ float bottom = top + art.Height;
+ float u0 = art.X, v0 = art.Y, u1 = art.X + art.Width, v1 = art.Y + art.Height;
+
+ Put(vertices, ref v, new PointF(left, top), u0, v0, art.Layer, light, hue, partial, alpha);
+ Put(vertices, ref v, new PointF(right, top), u1, v0, art.Layer, light, hue, partial, alpha);
+ Put(vertices, ref v, new PointF(left, bottom), u0, v1, art.Layer, light, hue, partial, alpha);
+ Put(vertices, ref v, new PointF(right, bottom), u1, v1, art.Layer, light, hue, partial, alpha);
+ }
+
+ private static void Put(float[] vertices, ref int v, PointF position, float u, float texV, int layer, float light,
+ int hue, bool partial, float alpha)
+ {
+ vertices[v++] = position.X;
+ vertices[v++] = position.Y;
+ vertices[v++] = u;
+ vertices[v++] = texV;
+ vertices[v++] = layer;
+ vertices[v++] = light;
+ vertices[v++] = hue;
+ vertices[v++] = partial ? 1f : 0f;
+ vertices[v++] = alpha;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/Rendering/MapPreviewCanvas.cs b/UoFiddler.Plugin.MapPreview/Rendering/MapPreviewCanvas.cs
new file mode 100644
index 00000000..370b09c2
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/Rendering/MapPreviewCanvas.cs
@@ -0,0 +1,556 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Windows.Forms;
+using OpenTK.Graphics.OpenGL4;
+using Ultima;
+using UoFiddler.Plugin.MapPreview.Scene;
+using UoFiddler.Rendering;
+using GdiPixelFormat = System.Drawing.Imaging.PixelFormat;
+using PixelFormat = OpenTK.Graphics.OpenGL4.PixelFormat;
+
+namespace UoFiddler.Plugin.MapPreview.Rendering
+{
+ ///
+ /// Draws a as the client would. Dragging pans, the wheel zooms
+ /// towards the pointer and a double click fits the area.
+ ///
+ internal sealed class MapPreviewCanvas : GlHostControl
+ {
+ /// The largest side, in pixels, of an exported image.
+ public const int MaxExportSize = 16384;
+
+ private const int ExportTile = 2048;
+
+ private readonly List _items = new List();
+
+ private bool _ready;
+ private bool _failed;
+ private ArtAtlas _atlas;
+ private HueTexture _hues;
+ private MapBatch _batch;
+
+ private MapPreviewScene _scene;
+ private PreviewOptions _options = new PreviewOptions();
+ private Drawable[] _order;
+ private bool _orderStretched;
+ private bool _meshDirty = true;
+ private bool _fitPending = true;
+
+ /// The scene changed since the bounds were taken, so the next mesh sets them.
+ private bool _sceneChanged = true;
+
+ /// A scene has been framed once; later scenes keep the zoom instead of fitting.
+ private bool _hasView;
+ private RectangleF _bounds;
+
+ private bool _panning;
+ private Point _panLast;
+
+ /// Raised once when the context cannot be used; the text is for the user.
+ public event Action ContextFailed;
+
+ ///
+ /// Raised when the scene could not be turned into vertices, which means the client files
+ /// could not be read. The canvas stays usable; the text is for the user.
+ ///
+ public event Action SceneFailed;
+
+ /// Raised when the pointer moves onto another tile, with a line for the status bar.
+ public event Action HoverChanged;
+
+ /// Raised after the zoom changed.
+ public event Action ZoomChanged;
+
+ public Camera2D Camera { get; } = new Camera2D { MinZoom = 1f / 64f };
+
+ [Browsable(false)]
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+ public MapPreviewScene Scene
+ {
+ get => _scene;
+ set
+ {
+ _scene = value;
+ _order = null;
+ _meshDirty = true;
+ _sceneChanged = true;
+ _fitPending = true;
+ Invalidate();
+ }
+ }
+
+ ///
+ /// Shows a new scene. The first one is fitted to the view; after that the zoom the user
+ /// chose is kept and the view is centred on , a tile in map
+ /// coordinates, so clicking around the map moves the preview without resetting it.
+ ///
+ public void ShowScene(MapPreviewScene scene, Point focus)
+ {
+ if (!_hasView || scene == null)
+ {
+ Scene = scene;
+ return;
+ }
+
+ _scene = scene;
+ _order = null;
+ _meshDirty = true;
+ _sceneChanged = true;
+
+ int dx = Math.Clamp(focus.X - scene.Area.X, 0, scene.Area.Width - 1);
+ int dy = Math.Clamp(focus.Y - scene.Area.Y, 0, scene.Area.Height - 1);
+ float x = (dx - dy) * MapPreviewScene.TileHalf;
+ float y = ((dx + dy) * MapPreviewScene.TileHalf) + MapPreviewScene.TileHalf -
+ (scene.HeightAt(dx, dy) * MapPreviewScene.PixelsPerZ);
+
+ // The middle of the clicked tile's diamond, at its height.
+ Camera.CenterOn(new RectangleF(x, y, 0f, 0f), ClientSize);
+ Invalidate();
+ }
+
+ [Browsable(false)]
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+ public PreviewOptions Options
+ {
+ get => _options;
+ set
+ {
+ if (_options == value)
+ {
+ return;
+ }
+
+ _options = value;
+ _meshDirty = true;
+ Invalidate();
+ }
+ }
+
+ public void FitToView()
+ {
+ if (_bounds.IsEmpty)
+ {
+ _fitPending = true;
+ Invalidate();
+ return;
+ }
+
+ Camera.Fit(_bounds, ClientSize, 2f, 16);
+ ZoomChanged?.Invoke();
+ Invalidate();
+ }
+
+ /// Shows the art at 100%, keeping what is in the middle of the view there.
+ public void ZoomToActual()
+ {
+ Camera.ZoomAt(new Point(ClientSize.Width / 2, ClientSize.Height / 2), 1f);
+ ZoomChanged?.Invoke();
+ Invalidate();
+ }
+
+ /// Forgets cached art, after art, texmaps or hues changed.
+ public void ReloadArt()
+ {
+ // Not drawn yet: the atlas and hues are made from the current files on first paint.
+ if (!_ready || _failed || !IsHandleCreated)
+ {
+ return;
+ }
+
+ MakeCurrent();
+ _atlas.Clear();
+ _hues.Dispose();
+ _hues = new HueTexture();
+ _meshDirty = true;
+ Invalidate();
+ }
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ base.OnPaint(e);
+
+ Size size = ClientSize;
+ if (_failed || DesignMode || size.Width <= 0 || size.Height <= 0)
+ {
+ return;
+ }
+
+ try
+ {
+ MakeCurrent();
+ if (!_ready)
+ {
+ Initialize();
+ }
+
+ // Client files are data, not GL: a failure there empties the view and leaves the
+ // context working for the next scene.
+ try
+ {
+ RebuildIfNeeded();
+ }
+ catch (Exception ex)
+ {
+ _scene = null;
+ _order = null;
+ _meshDirty = true;
+ RebuildIfNeeded();
+ SceneFailed?.Invoke($"The preview could not be drawn from the client files: {ex.Message}");
+ }
+
+ if (_fitPending && !_bounds.IsEmpty)
+ {
+ _fitPending = false;
+ Camera.Fit(_bounds, size, 2f, 16);
+ ZoomChanged?.Invoke();
+ }
+
+ if (!_bounds.IsEmpty)
+ {
+ _hasView = true;
+ }
+
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
+ GL.Viewport(0, 0, size.Width, size.Height);
+ GL.ClearColor(0f, 0f, 0f, 1f);
+ GL.Clear(ClearBufferMask.ColorBufferBit);
+ _batch.Draw(_atlas, _hues, Camera.OriginX, Camera.OriginY, Camera.Zoom, size.Width, size.Height);
+ SwapBuffers();
+ }
+ catch (Exception ex)
+ {
+ _failed = true;
+ ContextFailed?.Invoke($"OpenGL rendering failed:\r\n{ex.Message}");
+ }
+ }
+
+ private void Initialize()
+ {
+ int major = GL.GetInteger(GetPName.MajorVersion);
+ int minor = GL.GetInteger(GetPName.MinorVersion);
+ if (major < 3 || (major == 3 && minor < 3))
+ {
+ throw new NotSupportedException(
+ $"OpenGL 3.3 is required, this system offers {major}.{minor} ({GL.GetString(StringName.Renderer)}).");
+ }
+
+ GL.Disable(EnableCap.DepthTest);
+ GL.Enable(EnableCap.Blend);
+ GL.BlendFuncSeparate(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha,
+ BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);
+
+ _atlas = new ArtAtlas();
+ _hues = new HueTexture();
+ _batch = new MapBatch();
+ _ready = true;
+ }
+
+ private void RebuildIfNeeded()
+ {
+ if (!_meshDirty)
+ {
+ return;
+ }
+
+ _meshDirty = false;
+ if (_scene == null)
+ {
+ _items.Clear();
+ _batch.Upload(Array.Empty(), 0);
+ _bounds = RectangleF.Empty;
+ return;
+ }
+
+ if (_order == null || _orderStretched != _options.Stretch)
+ {
+ _order = _scene.Arrange(_options.Stretch);
+ _orderStretched = _options.Stretch;
+ }
+
+ float[] vertices = MapMesh.Build(_scene, _order, _options, _atlas, _hues.Count, _items, out int quads,
+ out RectangleF bounds);
+ _batch.Upload(vertices, quads);
+
+ // The framing follows the area, not what a filter left of it, so toggles do not jump the view.
+ if (_bounds.IsEmpty || _sceneChanged)
+ {
+ _bounds = bounds;
+ _sceneChanged = false;
+ }
+ }
+
+ ///
+ /// Renders the whole area at into a bitmap with a transparent
+ /// background, a tile at a time so no single framebuffer gets large.
+ ///
+ public Bitmap RenderImage(float scale)
+ {
+ if (!_ready || _bounds.IsEmpty)
+ {
+ return null;
+ }
+
+ MakeCurrent();
+ RebuildIfNeeded();
+
+ int width = Math.Max(1, (int)Math.Ceiling(_bounds.Width * scale));
+ int height = Math.Max(1, (int)Math.Ceiling(_bounds.Height * scale));
+
+ var image = new Bitmap(width, height, GdiPixelFormat.Format32bppArgb);
+ int framebuffer = GL.GenFramebuffer();
+ int color = GL.GenTexture();
+ try
+ {
+ GL.BindTexture(TextureTarget.Texture2D, color);
+ GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, ExportTile, ExportTile, 0,
+ PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero);
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, framebuffer);
+ GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0,
+ TextureTarget.Texture2D, color, 0);
+
+ byte[] pixels = new byte[ExportTile * ExportTile * 4];
+ for (int ty = 0; ty < height; ty += ExportTile)
+ {
+ for (int tx = 0; tx < width; tx += ExportTile)
+ {
+ int w = Math.Min(ExportTile, width - tx);
+ int h = Math.Min(ExportTile, height - ty);
+
+ GL.Viewport(0, 0, w, h);
+ GL.ClearColor(0f, 0f, 0f, 0f);
+ GL.Clear(ClearBufferMask.ColorBufferBit);
+ _batch.Draw(_atlas, _hues, _bounds.X + (tx / scale), _bounds.Y + (ty / scale), scale, w, h);
+
+ GL.PixelStore(PixelStoreParameter.PackAlignment, 1);
+ GL.ReadPixels(0, 0, w, h, PixelFormat.Bgra, PixelType.UnsignedByte,
+ pixels);
+ CopyFlipped(pixels, w, h, image, tx, ty);
+ }
+ }
+ }
+ finally
+ {
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
+ GL.DeleteFramebuffer(framebuffer);
+ GL.DeleteTexture(color);
+ Invalidate();
+ }
+
+ return image;
+ }
+
+ /// The largest export scale up to 1:1 that keeps both sides within .
+ public float ExportScale()
+ {
+ if (_bounds.IsEmpty)
+ {
+ return 1f;
+ }
+
+ return Math.Min(1f, MaxExportSize / Math.Max(_bounds.Width, _bounds.Height));
+ }
+
+ private static unsafe void CopyFlipped(byte[] pixels, int width, int height, Bitmap image, int x, int y)
+ {
+ BitmapData data = image.LockBits(new Rectangle(x, y, width, height), ImageLockMode.WriteOnly,
+ GdiPixelFormat.Format32bppArgb);
+ try
+ {
+ for (int row = 0; row < height; row++)
+ {
+ // GL rows run bottom up.
+ var source = new ReadOnlySpan(pixels, (height - 1 - row) * width * 4, width * 4);
+ var target = new Span((byte*)data.Scan0 + (row * data.Stride), width * 4);
+ source.CopyTo(target);
+ }
+ }
+ finally
+ {
+ image.UnlockBits(data);
+ }
+ }
+
+ protected override void OnResize(EventArgs e)
+ {
+ base.OnResize(e);
+
+ if (Camera.ShowsFit && !_bounds.IsEmpty)
+ {
+ Camera.Fit(_bounds, ClientSize, 2f, 16);
+ ZoomChanged?.Invoke();
+ }
+
+ Invalidate();
+ }
+
+ protected override void OnMouseDown(MouseEventArgs e)
+ {
+ base.OnMouseDown(e);
+ Focus();
+
+ if (e.Button is MouseButtons.Left or MouseButtons.Right or MouseButtons.Middle)
+ {
+ _panning = true;
+ _panLast = e.Location;
+ Cursor = Cursors.SizeAll;
+ }
+ }
+
+ protected override void OnMouseMove(MouseEventArgs e)
+ {
+ base.OnMouseMove(e);
+
+ if (_panning)
+ {
+ Camera.Pan(e.X - _panLast.X, e.Y - _panLast.Y);
+ _panLast = e.Location;
+ Invalidate();
+ return;
+ }
+
+ string text;
+ try
+ {
+ text = Describe(Camera.ScreenToWorld(e.Location));
+ }
+ catch (Exception)
+ {
+ // Names and art come from client files that may be mid-change; a hover line is not
+ // worth an error.
+ text = string.Empty;
+ }
+
+ HoverChanged?.Invoke(text);
+ }
+
+ protected override void OnMouseUp(MouseEventArgs e)
+ {
+ base.OnMouseUp(e);
+
+ if (_panning)
+ {
+ _panning = false;
+ Cursor = Cursors.Default;
+ }
+ }
+
+ protected override void OnMouseWheel(MouseEventArgs e)
+ {
+ base.OnMouseWheel(e);
+
+ Camera.ZoomStep(e.Location, Math.Sign(e.Delta));
+ ZoomChanged?.Invoke();
+ Invalidate();
+ }
+
+ /// Arrow keys reach KeyDown instead of moving focus to the next control.
+ protected override bool IsInputKey(Keys keyData)
+ {
+ return (keyData & Keys.KeyCode) is Keys.Left or Keys.Right or Keys.Up or Keys.Down || base.IsInputKey(keyData);
+ }
+
+ protected override void OnDoubleClick(EventArgs e)
+ {
+ base.OnDoubleClick(e);
+
+ FitToView();
+ }
+
+ /// The topmost thing drawn under a world point, as a status line.
+ private string Describe(PointF world)
+ {
+ if (_scene == null)
+ {
+ return string.Empty;
+ }
+
+ for (int i = _items.Count - 1; i >= 0; i--)
+ {
+ MeshItem item = _items[i];
+ if (item.Kind == DrawableKind.Static)
+ {
+ if (world.X < item.Left.X || world.X >= item.Right.X || world.Y < item.Top.Y ||
+ world.Y >= item.Bottom.Y)
+ {
+ continue;
+ }
+
+ SceneStatic s = _scene.Statics[item.Index];
+ if (!IsOpaque(s.Id, (int)(world.X - item.Left.X), (int)(world.Y - item.Top.Y)))
+ {
+ continue;
+ }
+
+ string name = s.Id < TileData.ItemTable.Length ? TileData.ItemTable[s.Id].Name : string.Empty;
+ return $"{_scene.Area.X + s.X},{_scene.Area.Y + s.Y},{s.Z} static 0x{s.Id:X4} {name}" +
+ (s.Hue != 0 ? $" hue {s.Hue & 0x3FFF}" : string.Empty);
+ }
+
+ if (!InQuad(world, item))
+ {
+ continue;
+ }
+
+ int width = _scene.Area.Width;
+ SceneLand land = _scene.Land[item.Index];
+ string landName = land.Id < TileData.LandTable.Length ? TileData.LandTable[land.Id].Name : string.Empty;
+ return $"{_scene.Area.X + (item.Index % width)},{_scene.Area.Y + (item.Index / width)},{land.Z} " +
+ $"land 0x{land.Id:X4} {landName}" + (land.Stretched ? $" texmap 0x{land.TextureId:X4}" : string.Empty);
+ }
+
+ return string.Empty;
+ }
+
+ private static bool IsOpaque(ushort id, int x, int y)
+ {
+ Bitmap art = Art.GetStatic(id);
+ return art != null && x >= 0 && y >= 0 && x < art.Width && y < art.Height && art.GetPixel(x, y).A != 0;
+ }
+
+ /// Point in a convex quad given clockwise on screen: top, right, bottom, left.
+ private static bool InQuad(PointF p, in MeshItem item)
+ {
+ return Side(item.Top, item.Right, p) >= 0 && Side(item.Right, item.Bottom, p) >= 0 &&
+ Side(item.Bottom, item.Left, p) >= 0 && Side(item.Left, item.Top, p) >= 0;
+ }
+
+ private static float Side(PointF a, PointF b, PointF p)
+ {
+ return ((b.X - a.X) * (p.Y - a.Y)) - ((b.Y - a.Y) * (p.X - a.X));
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && _ready)
+ {
+ try
+ {
+ MakeCurrent();
+ _batch.Dispose();
+ _hues.Dispose();
+ _atlas.Dispose();
+ }
+ catch (Exception)
+ {
+ // The context is already gone when the window is torn down first.
+ }
+
+ _ready = false;
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/Scene/MapPreviewScene.cs b/UoFiddler.Plugin.MapPreview/Scene/MapPreviewScene.cs
new file mode 100644
index 00000000..14dbbb0f
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/Scene/MapPreviewScene.cs
@@ -0,0 +1,314 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using Ultima;
+
+namespace UoFiddler.Plugin.MapPreview.Scene
+{
+ /// What a drawable is.
+ public enum DrawableKind : byte
+ {
+ Land,
+ Static
+ }
+
+ /// One thing to draw, in the order the scene sorted it into.
+ public readonly record struct Drawable(DrawableKind Kind, int Index, double Depth);
+
+ /// A static in the area. X and Y are relative to the area.
+ public readonly record struct SceneStatic(int X, int Y, sbyte Z, ushort Id, int Hue, TileFlag Flags, byte Height);
+
+ ///
+ /// A map area as the client would draw it: land with its four corner heights and per-corner
+ /// light, the statics on it, and one painter's order for both. No GL here; the canvas turns this
+ /// into vertices.
+ ///
+ ///
+ /// Coordinates are isometric pixels with the top corner of the area's first tile at z 0 as the
+ /// origin: a tile's top corner is at ((x - y) * 22, (x + y) * 22 - z * 4).
+ ///
+ public sealed class MapPreviewScene
+ {
+ public const int TileHalf = 22;
+ public const int TileSize = 44;
+ public const int PixelsPerZ = 4;
+
+ /// Length of one tile edge in world units, so slopes come out at the right angle.
+ private const float TileEdge = 31.1127f;
+
+ /// Where light comes from, in tile axes: +y (south) and above, as the client lights land.
+ private static readonly (float X, float Y, float Z) _light = Normalize(0f, 1f, 1f);
+
+ /// How strongly a slope's angle to the light changes its brightness.
+ private const float LightStrength = 1.1f;
+
+ private readonly sbyte[] _heights;
+ private readonly int _heightsWidth;
+
+ private MapPreviewScene(Map map, Rectangle area, sbyte[] heights, int heightsWidth)
+ {
+ Map = map;
+ Area = area;
+ _heights = heights;
+ _heightsWidth = heightsWidth;
+ Land = new SceneLand[area.Width * area.Height];
+ }
+
+ public Map Map { get; }
+
+ /// The tiles shown, in map coordinates.
+ public Rectangle Area { get; }
+
+ /// Row-major, wide.
+ public SceneLand[] Land { get; }
+
+ public List Statics { get; } = new List();
+
+ ///
+ /// Reads an area. Every Ultima call is made here, on the calling thread, so the caller picks
+ /// the thread the map caches are used from.
+ ///
+ public static MapPreviewScene Build(Map map, Rectangle area)
+ {
+ area = Rectangle.Intersect(area, new Rectangle(0, 0, map.Width, map.Height));
+ if (area.Width <= 0 || area.Height <= 0)
+ {
+ throw new ArgumentException("The area is outside the map.", nameof(area));
+ }
+
+ // Corner heights reach one tile past the area and the corner normals one more.
+ const int margin = 2;
+ int heightsWidth = area.Width + (margin * 2);
+ int heightsHeight = area.Height + (margin * 2);
+ sbyte[] heights = new sbyte[heightsWidth * heightsHeight];
+ TileMatrix tiles = map.Tiles;
+
+ for (int hy = 0; hy < heightsHeight; hy++)
+ {
+ int y = Math.Clamp(area.Y - margin + hy, 0, map.Height - 1);
+ for (int hx = 0; hx < heightsWidth; hx++)
+ {
+ int x = Math.Clamp(area.X - margin + hx, 0, map.Width - 1);
+ heights[(hy * heightsWidth) + hx] = tiles.GetLandTile(x, y).Z;
+ }
+ }
+
+ var scene = new MapPreviewScene(map, area, heights, heightsWidth);
+
+ for (int dy = 0; dy < area.Height; dy++)
+ {
+ for (int dx = 0; dx < area.Width; dx++)
+ {
+ int x = area.X + dx;
+ int y = area.Y + dy;
+ scene.Land[(dy * area.Width) + dx] = scene.MakeLand(dx, dy, tiles.GetLandTile(x, y).Id);
+
+ foreach (HuedTile tile in tiles.GetStaticTiles(x, y))
+ {
+ if (IsNoDraw(tile.Id))
+ {
+ continue;
+ }
+
+ ItemData data = tile.Id < TileData.ItemTable.Length ? TileData.ItemTable[tile.Id] : default;
+ scene.Statics.Add(new SceneStatic(dx, dy, tile.Z, tile.Id, tile.Hue, data.Flags, data.Height));
+ }
+ }
+ }
+
+ return scene;
+ }
+
+ ///
+ /// The draw order, back to front. The key is the client's: the cell diagonal plus a small
+ /// share of the priority height, so a tall thing can sort in front of the next diagonal.
+ ///
+ /// Whether sloped land is stretched; it moves where land sorts.
+ public Drawable[] Arrange(bool stretch)
+ {
+ int width = Area.Width;
+ var order = new Drawable[Land.Length + Statics.Count];
+ int n = 0;
+
+ for (int i = 0; i < Land.Length; i++)
+ {
+ SceneLand land = Land[i];
+ if (land.NoDraw)
+ {
+ continue;
+ }
+
+ int priority = (stretch && land.Stretched ? land.AverageZ : land.Z) - 2;
+ order[n++] = new Drawable(DrawableKind.Land, i, Depth((i % width) + (i / width), priority));
+ }
+
+ for (int i = 0; i < Statics.Count; i++)
+ {
+ SceneStatic s = Statics[i];
+ order[n++] = new Drawable(DrawableKind.Static, i, Depth(s.X + s.Y, StaticPriority(s)));
+ }
+
+ Array.Resize(ref order, n);
+
+ // Stable, so equal keys keep land before statics and statics in file order.
+ var keys = new double[n];
+ var sequence = new int[n];
+ for (int i = 0; i < n; i++)
+ {
+ keys[i] = order[i].Depth;
+ sequence[i] = i;
+ }
+
+ Array.Sort(sequence, (a, b) =>
+ {
+ int byDepth = keys[a].CompareTo(keys[b]);
+ return byDepth != 0 ? byDepth : a.CompareTo(b);
+ });
+
+ var sorted = new Drawable[n];
+ for (int i = 0; i < n; i++)
+ {
+ sorted[i] = order[sequence[i]];
+ }
+
+ return sorted;
+ }
+
+ /// Background items sort under what stands on the same height, items with a height over it.
+ public static int StaticPriority(in SceneStatic s)
+ {
+ int priority = s.Z;
+ if ((s.Flags & TileFlag.Background) != 0)
+ {
+ priority--;
+ }
+
+ if (s.Height > 0)
+ {
+ priority++;
+ }
+
+ return priority;
+ }
+
+ public static double Depth(int diagonal, int priorityZ)
+ {
+ return diagonal + ((127 + priorityZ) * 0.01);
+ }
+
+ /// The land height under a tile of the area, clamped at the map edge.
+ public sbyte HeightAt(int dx, int dy)
+ {
+ return _heights[((dy + 2) * _heightsWidth) + dx + 2];
+ }
+
+ private SceneLand MakeLand(int dx, int dy, ushort id)
+ {
+ sbyte top = HeightAt(dx, dy);
+ sbyte right = HeightAt(dx + 1, dy);
+ sbyte bottom = HeightAt(dx + 1, dy + 1);
+ sbyte left = HeightAt(dx, dy + 1);
+
+ var land = new SceneLand
+ {
+ Id = id,
+ Z = top,
+ Top = top,
+ Right = right,
+ Bottom = bottom,
+ Left = left,
+ AverageZ = AverageZ(top, right, bottom, left),
+ NoDraw = id == 0x0002,
+ LightTop = CornerLight(dx, dy),
+ LightRight = CornerLight(dx + 1, dy),
+ LightBottom = CornerLight(dx + 1, dy + 1),
+ LightLeft = CornerLight(dx, dy + 1)
+ };
+
+ land.TextureId = id < TileData.LandTable.Length ? TileData.LandTable[id].TextureId : (ushort)0;
+
+ // Land without a texmap has nothing to stretch, and stays flat whatever its corners say.
+ bool canStretch = land.TextureId != 0 && Textures.TestTexture(land.TextureId);
+
+ // A level tile next to a slope still stretches, so its corners share the slope's light.
+ land.Stretched = canStretch &&
+ (top != right || top != bottom || top != left ||
+ !IsFlatAround(dx, dy) || !IsFlatAround(dx + 1, dy) ||
+ !IsFlatAround(dx + 1, dy + 1) || !IsFlatAround(dx, dy + 1));
+ return land;
+ }
+
+ ///
+ /// The client's average for sorting: the mean of the diagonal pair that is closer to level,
+ /// which is the fold the quad is drawn along.
+ ///
+ public static int AverageZ(int top, int right, int bottom, int left)
+ {
+ return Math.Abs(top - bottom) <= Math.Abs(left - right)
+ ? (top + bottom) >> 1
+ : (left + right) >> 1;
+ }
+
+ /// True when a grid point's four neighbours are at its height.
+ private bool IsFlatAround(int gx, int gy)
+ {
+ sbyte z = HeightAt(gx, gy);
+ return HeightAt(gx - 1, gy) == z && HeightAt(gx + 1, gy) == z &&
+ HeightAt(gx, gy - 1) == z && HeightAt(gx, gy + 1) == z;
+ }
+
+ ///
+ /// Brightness at a grid point from the slope through its neighbours, scaled so level ground
+ /// is 1 and matches the unlit flat art beside it.
+ ///
+ private float CornerLight(int gx, int gy)
+ {
+ float dzdx = (HeightAt(gx + 1, gy) - HeightAt(gx - 1, gy)) * PixelsPerZ / (2f * TileEdge);
+ float dzdy = (HeightAt(gx, gy + 1) - HeightAt(gx, gy - 1)) * PixelsPerZ / (2f * TileEdge);
+ (float nx, float ny, float nz) = Normalize(-dzdx, -dzdy, 1f);
+
+ float lit = (nx * _light.X) + (ny * _light.Y) + (nz * _light.Z);
+ return Math.Clamp(1f + (LightStrength * (lit - _light.Z)), 0.45f, 1.4f);
+ }
+
+ /// Tiles the client never draws: the "no draw" marker and invisible blockers.
+ private static bool IsNoDraw(ushort id)
+ {
+ return id == 0x0001 || id == 0x21BC;
+ }
+
+ private static (float X, float Y, float Z) Normalize(float x, float y, float z)
+ {
+ float length = MathF.Sqrt((x * x) + (y * y) + (z * z));
+ return (x / length, y / length, z / length);
+ }
+ }
+
+ /// A land tile with its corner heights, in the order top, right, bottom, left.
+ public struct SceneLand
+ {
+ public ushort Id;
+ public ushort TextureId;
+ public sbyte Z;
+ public sbyte Top;
+ public sbyte Right;
+ public sbyte Bottom;
+ public sbyte Left;
+ public int AverageZ;
+ public bool Stretched;
+ public bool NoDraw;
+ public float LightTop;
+ public float LightRight;
+ public float LightBottom;
+ public float LightLeft;
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.Designer.cs b/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.Designer.cs
new file mode 100644
index 00000000..d8c79b84
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.Designer.cs
@@ -0,0 +1,360 @@
+namespace UoFiddler.Plugin.MapPreview.UI
+{
+ partial class MapPreviewForm
+ {
+ ///
+ /// 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()
+ {
+ _navStrip = new System.Windows.Forms.ToolStrip();
+ _gotoLabel = new System.Windows.Forms.ToolStripLabel();
+ _separator5 = new System.Windows.Forms.ToolStripSeparator();
+ _viewStrip = new System.Windows.Forms.ToolStrip();
+ _landButton = new System.Windows.Forms.ToolStripButton();
+ _staticsButton = new System.Windows.Forms.ToolStripButton();
+ _stretchButton = new System.Windows.Forms.ToolStripButton();
+ _lightingButton = new System.Windows.Forms.ToolStripButton();
+ _huesButton = new System.Windows.Forms.ToolStripButton();
+ _roofsButton = new System.Windows.Forms.ToolStripButton();
+ _separator1 = new System.Windows.Forms.ToolStripSeparator();
+ _maxZLabel = new System.Windows.Forms.ToolStripLabel();
+ _autoZButton = new System.Windows.Forms.ToolStripButton();
+ _cutLandButton = new System.Windows.Forms.ToolStripButton();
+ _separator2 = new System.Windows.Forms.ToolStripSeparator();
+ _fitButton = new System.Windows.Forms.ToolStripButton();
+ _oneToOneButton = new System.Windows.Forms.ToolStripButton();
+ _zoomLabel = new System.Windows.Forms.ToolStripLabel();
+ _separator3 = new System.Windows.Forms.ToolStripSeparator();
+ _moveLabel = new System.Windows.Forms.ToolStripLabel();
+ _moveLeftButton = new System.Windows.Forms.ToolStripButton();
+ _moveUpButton = new System.Windows.Forms.ToolStripButton();
+ _moveDownButton = new System.Windows.Forms.ToolStripButton();
+ _moveRightButton = new System.Windows.Forms.ToolStripButton();
+ _stepBox = new System.Windows.Forms.ToolStripComboBox();
+ _separator4 = new System.Windows.Forms.ToolStripSeparator();
+ _exportButton = new System.Windows.Forms.ToolStripButton();
+ _refreshButton = new System.Windows.Forms.ToolStripButton();
+ _settingsButton = new System.Windows.Forms.ToolStripButton();
+ _gotoButton = new System.Windows.Forms.ToolStripButton();
+ _gotoBox = new System.Windows.Forms.ToolStripTextBox();
+ _statusStrip = new System.Windows.Forms.StatusStrip();
+ _statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
+ _navStrip.SuspendLayout();
+ _viewStrip.SuspendLayout();
+ _statusStrip.SuspendLayout();
+ SuspendLayout();
+ //
+ // _navStrip
+ //
+ _navStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
+ _navStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _gotoLabel, _gotoBox, _gotoButton, _separator1, _moveLabel, _moveLeftButton, _moveUpButton, _moveDownButton, _moveRightButton, _stepBox, _separator2, _fitButton, _oneToOneButton, _zoomLabel, _settingsButton, _separator5, _refreshButton, _exportButton, _separator3 });
+ _navStrip.Location = new System.Drawing.Point(0, 0);
+ _navStrip.Name = "_navStrip";
+ _navStrip.Size = new System.Drawing.Size(1100, 25);
+ _navStrip.TabIndex = 0;
+ //
+ // _viewStrip
+ //
+ _viewStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
+ _viewStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _landButton, _staticsButton, _stretchButton, _lightingButton, _huesButton, _roofsButton, _separator4, _maxZLabel, _autoZButton, _cutLandButton });
+ _viewStrip.Location = new System.Drawing.Point(0, 25);
+ _viewStrip.Name = "_viewStrip";
+ _viewStrip.Size = new System.Drawing.Size(1100, 25);
+ _viewStrip.TabIndex = 1;
+ //
+ // _gotoLabel
+ //
+ _gotoLabel.Name = "_gotoLabel";
+ _gotoLabel.Text = "Go to:";
+ //
+ // _separator1
+ //
+ _separator1.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0);
+ _separator1.Name = "_separator1";
+ //
+ // _separator2
+ //
+ _separator2.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0);
+ _separator2.Name = "_separator2";
+ //
+ // _separator3
+ //
+ _separator3.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
+ _separator3.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0);
+ _separator3.Name = "_separator3";
+ //
+ // _separator4
+ //
+ _separator4.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0);
+ _separator4.Name = "_separator4";
+ //
+ // _separator5
+ //
+ _separator5.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
+ _separator5.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0);
+ _separator5.Name = "_separator5";
+ //
+ // _landButton
+ //
+ _landButton.Checked = true;
+ _landButton.CheckOnClick = true;
+ _landButton.CheckState = System.Windows.Forms.CheckState.Checked;
+ _landButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _landButton.Name = "_landButton";
+ _landButton.Text = "Land";
+ //
+ // _staticsButton
+ //
+ _staticsButton.Checked = true;
+ _staticsButton.CheckOnClick = true;
+ _staticsButton.CheckState = System.Windows.Forms.CheckState.Checked;
+ _staticsButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _staticsButton.Name = "_staticsButton";
+ _staticsButton.Text = "Statics";
+ //
+ // _stretchButton
+ //
+ _stretchButton.Checked = true;
+ _stretchButton.CheckOnClick = true;
+ _stretchButton.CheckState = System.Windows.Forms.CheckState.Checked;
+ _stretchButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _stretchButton.Name = "_stretchButton";
+ _stretchButton.Text = "Stretched land";
+ _stretchButton.ToolTipText = "Draw sloped land with its texmap stretched over the corner heights";
+ //
+ // _lightingButton
+ //
+ _lightingButton.Checked = true;
+ _lightingButton.CheckOnClick = true;
+ _lightingButton.CheckState = System.Windows.Forms.CheckState.Checked;
+ _lightingButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _lightingButton.Name = "_lightingButton";
+ _lightingButton.Text = "Lighting";
+ _lightingButton.ToolTipText = "Shade stretched land by its slope";
+ //
+ // _huesButton
+ //
+ _huesButton.Checked = true;
+ _huesButton.CheckOnClick = true;
+ _huesButton.CheckState = System.Windows.Forms.CheckState.Checked;
+ _huesButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _huesButton.Name = "_huesButton";
+ _huesButton.Text = "Hues";
+ //
+ // _roofsButton
+ //
+ _roofsButton.CheckOnClick = true;
+ _roofsButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _roofsButton.Name = "_roofsButton";
+ _roofsButton.Text = "Hide roofs";
+ //
+ // _maxZLabel
+ //
+ _maxZLabel.Name = "_maxZLabel";
+ _maxZLabel.Text = "Max Z: all";
+ //
+ // _autoZButton
+ //
+ _autoZButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _autoZButton.Name = "_autoZButton";
+ _autoZButton.Text = "Auto";
+ _autoZButton.ToolTipText = "Cut everything 16 above the ground at the centre of the area, as the client does under a roof";
+ //
+ // _cutLandButton
+ //
+ _cutLandButton.CheckOnClick = true;
+ _cutLandButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _cutLandButton.Name = "_cutLandButton";
+ _cutLandButton.Text = "Cut land";
+ _cutLandButton.ToolTipText = "Max Z hides land too, to show statics under the terrain (the client never cuts land)";
+ //
+ // _fitButton
+ //
+ _fitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _fitButton.Name = "_fitButton";
+ _fitButton.Text = "Fit";
+ //
+ // _oneToOneButton
+ //
+ _oneToOneButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _oneToOneButton.Name = "_oneToOneButton";
+ _oneToOneButton.Text = "1:1";
+ _oneToOneButton.ToolTipText = "Zoom to 100%";
+ //
+ // _zoomLabel
+ //
+ _zoomLabel.Name = "_zoomLabel";
+ _zoomLabel.Text = "100%";
+ //
+ // _moveLabel
+ //
+ _moveLabel.Name = "_moveLabel";
+ _moveLabel.Text = "Move:";
+ //
+ // _moveLeftButton
+ //
+ _moveLeftButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _moveLeftButton.Name = "_moveLeftButton";
+ _moveLeftButton.Text = "◀";
+ _moveLeftButton.ToolTipText = "Move the area left (Left arrow)";
+ //
+ // _moveUpButton
+ //
+ _moveUpButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _moveUpButton.Name = "_moveUpButton";
+ _moveUpButton.Text = "▲";
+ _moveUpButton.ToolTipText = "Move the area up (Up arrow)";
+ //
+ // _moveDownButton
+ //
+ _moveDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _moveDownButton.Name = "_moveDownButton";
+ _moveDownButton.Text = "▼";
+ _moveDownButton.ToolTipText = "Move the area down (Down arrow)";
+ //
+ // _moveRightButton
+ //
+ _moveRightButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _moveRightButton.Name = "_moveRightButton";
+ _moveRightButton.Text = "▶";
+ _moveRightButton.ToolTipText = "Move the area right (Right arrow)";
+ //
+ // _stepBox
+ //
+ _stepBox.AutoSize = false;
+ _stepBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
+ _stepBox.Name = "_stepBox";
+ _stepBox.Size = new System.Drawing.Size(70, 25);
+ _stepBox.ToolTipText = "How far one move goes";
+ //
+ // _exportButton
+ //
+ _exportButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
+ _exportButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _exportButton.Name = "_exportButton";
+ _exportButton.Text = "Export PNG...";
+ //
+ // _refreshButton
+ //
+ _refreshButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
+ _refreshButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _refreshButton.Name = "_refreshButton";
+ _refreshButton.Text = "Refresh";
+ _refreshButton.ToolTipText = "Read the area and art again, after edits";
+ //
+ // _settingsButton
+ //
+ _settingsButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
+ _settingsButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _settingsButton.Name = "_settingsButton";
+ _settingsButton.Text = "Settings...";
+ //
+ // _gotoButton
+ //
+ _gotoButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
+ _gotoButton.Name = "_gotoButton";
+ _gotoButton.Text = "Go";
+ _gotoButton.ToolTipText = "Preview the area around these coordinates";
+ //
+ // _gotoBox
+ //
+ _gotoBox.AutoSize = false;
+ _gotoBox.Name = "_gotoBox";
+ _gotoBox.Size = new System.Drawing.Size(90, 25);
+ _gotoBox.ToolTipText = "Go to X, Y (Ctrl+G). Separate with a comma or a space; a Z after them is ignored.";
+ //
+ // _statusStrip
+ //
+ _statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _statusLabel });
+ _statusStrip.Location = new System.Drawing.Point(0, 738);
+ _statusStrip.Name = "_statusStrip";
+ _statusStrip.Size = new System.Drawing.Size(1100, 22);
+ _statusStrip.TabIndex = 1;
+ //
+ // _statusLabel
+ //
+ _statusLabel.Name = "_statusLabel";
+ _statusLabel.Spring = true;
+ _statusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
+ //
+ // MapPreviewForm
+ //
+ AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ ClientSize = new System.Drawing.Size(1100, 760);
+ Controls.Add(_statusStrip);
+ Controls.Add(_viewStrip);
+ Controls.Add(_navStrip);
+ KeyPreview = true;
+ MinimumSize = new System.Drawing.Size(800, 500);
+ Name = "MapPreviewForm";
+ StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+ Text = "In-game preview";
+ _navStrip.ResumeLayout(false);
+ _navStrip.PerformLayout();
+ _viewStrip.ResumeLayout(false);
+ _viewStrip.PerformLayout();
+ _statusStrip.ResumeLayout(false);
+ _statusStrip.PerformLayout();
+ ResumeLayout(false);
+ PerformLayout();
+ }
+
+ #endregion
+
+ private System.Windows.Forms.ToolStrip _navStrip;
+ private System.Windows.Forms.ToolStripLabel _gotoLabel;
+ private System.Windows.Forms.ToolStripSeparator _separator5;
+ private System.Windows.Forms.ToolStrip _viewStrip;
+ private System.Windows.Forms.ToolStripButton _landButton;
+ private System.Windows.Forms.ToolStripButton _staticsButton;
+ private System.Windows.Forms.ToolStripButton _stretchButton;
+ private System.Windows.Forms.ToolStripButton _lightingButton;
+ private System.Windows.Forms.ToolStripButton _huesButton;
+ private System.Windows.Forms.ToolStripButton _roofsButton;
+ private System.Windows.Forms.ToolStripSeparator _separator1;
+ private System.Windows.Forms.ToolStripLabel _maxZLabel;
+ private System.Windows.Forms.ToolStripButton _autoZButton;
+ private System.Windows.Forms.ToolStripButton _cutLandButton;
+ private System.Windows.Forms.ToolStripSeparator _separator2;
+ private System.Windows.Forms.ToolStripButton _fitButton;
+ private System.Windows.Forms.ToolStripButton _oneToOneButton;
+ private System.Windows.Forms.ToolStripLabel _zoomLabel;
+ private System.Windows.Forms.ToolStripSeparator _separator3;
+ private System.Windows.Forms.ToolStripLabel _moveLabel;
+ private System.Windows.Forms.ToolStripButton _moveLeftButton;
+ private System.Windows.Forms.ToolStripButton _moveUpButton;
+ private System.Windows.Forms.ToolStripButton _moveDownButton;
+ private System.Windows.Forms.ToolStripButton _moveRightButton;
+ private System.Windows.Forms.ToolStripComboBox _stepBox;
+ private System.Windows.Forms.ToolStripSeparator _separator4;
+ private System.Windows.Forms.ToolStripButton _exportButton;
+ private System.Windows.Forms.ToolStripButton _refreshButton;
+ private System.Windows.Forms.ToolStripButton _settingsButton;
+ private System.Windows.Forms.ToolStripButton _gotoButton;
+ private System.Windows.Forms.ToolStripTextBox _gotoBox;
+ private System.Windows.Forms.StatusStrip _statusStrip;
+ private System.Windows.Forms.ToolStripStatusLabel _statusLabel;
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.cs b/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.cs
new file mode 100644
index 00000000..7ec01762
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.cs
@@ -0,0 +1,570 @@
+/***************************************************************************
+ *
+ * "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.Drawing.Imaging;
+using System.Globalization;
+using System.Windows.Forms;
+using Ultima;
+using UoFiddler.Controls.Classes;
+using UoFiddler.Plugin.MapPreview.Rendering;
+using UoFiddler.Plugin.MapPreview.Scene;
+
+namespace UoFiddler.Plugin.MapPreview.UI
+{
+ ///
+ /// A map area drawn as the client would, with the toggles to look into it. One window is kept
+ /// and pointed at each new spot; its toggles are the saved .
+ ///
+ public partial class MapPreviewForm : Form
+ {
+ /// The highest Z: a cut here or above it hides nothing.
+ private const int NoCut = 127;
+
+ /// The client cuts this far above the ground the player stands on.
+ private const int RoofCut = 16;
+
+ ///
+ /// Heights one notch of the slider moves. A notch of 1 rebuilt the view at nearly every
+ /// pixel of a drag and flickered.
+ ///
+ private const int CutStep = 5;
+
+ /// The slider's notches: -125 to 125, and a last notch past them for no cut.
+ private const int MinCutNotch = -128 / CutStep;
+
+ private const int NoCutNotch = (NoCut / CutStep) + 1;
+
+ private readonly MapPreviewCanvas _canvas;
+ private readonly TrackBar _maxZ;
+
+ private Map _map;
+
+ /// Which of the six facets is, or -1; found again after a client reload.
+ private int _facet = -1;
+
+ private string _mapName;
+ private Point _center;
+ private Rectangle _area;
+
+ /// True while controls are set from the settings, so they do not write them back.
+ private bool _syncing;
+
+ ///
+ /// Statics at or above this are hidden; null shows all. Auto sets it exactly, between the
+ /// slider's notches.
+ ///
+ private int? _cutZ;
+
+ /// True while the slider is moved to show , so it does not round it.
+ private bool _showingCut;
+
+ public MapPreviewForm()
+ {
+ InitializeComponent();
+
+ _canvas = new MapPreviewCanvas { Dock = DockStyle.Fill };
+ _canvas.ContextFailed += message =>
+ {
+ _canvas.Visible = false;
+ _statusLabel.Text = message;
+ };
+ _canvas.HoverChanged += text => _statusLabel.Text = text;
+ _canvas.ZoomChanged += () =>
+ _zoomLabel.Text = (_canvas.Camera.Zoom * 100f).ToString("0.#", CultureInfo.InvariantCulture) + "%";
+ Controls.Add(_canvas);
+ _canvas.BringToFront();
+
+ _maxZ = new TrackBar
+ {
+ Minimum = MinCutNotch,
+ Maximum = NoCutNotch,
+ Value = NoCutNotch,
+ SmallChange = 1,
+ LargeChange = 4,
+ TickStyle = TickStyle.BottomRight,
+ TickFrequency = 1,
+ AutoSize = false,
+ Height = 28,
+ Width = 260
+ };
+ _maxZ.ValueChanged += (_, _) =>
+ {
+ if (!_showingCut)
+ {
+ SetCut(_maxZ.Value >= NoCutNotch ? null : _maxZ.Value * CutStep);
+ }
+ };
+ // Back to the preview after a drag: a focused slider takes the arrow keys meant for
+ // moving the area, and End jumps it to no cut.
+ _maxZ.MouseUp += (_, _) => _canvas.Focus();
+ _viewStrip.Items.Insert(_viewStrip.Items.IndexOf(_maxZLabel) + 1,
+ new ToolStripControlHost(_maxZ) { AutoSize = false, Width = 260, Height = 28, ToolTipText = $"Hide statics at or above this height (steps of {CutStep})" });
+
+ foreach (ToolStripButton toggle in new[] { _landButton, _staticsButton, _stretchButton, _lightingButton, _huesButton, _roofsButton, _cutLandButton })
+ {
+ toggle.CheckedChanged += (_, _) => SaveToggles();
+ }
+
+ _autoZButton.Click += (_, _) => CutAtCenter();
+ _fitButton.Click += (_, _) => _canvas.FitToView();
+ _oneToOneButton.Click += (_, _) => _canvas.ZoomToActual();
+ _moveLeftButton.Click += (_, _) => MoveArea(-1, 0);
+ _moveUpButton.Click += (_, _) => MoveArea(0, -1);
+ _moveDownButton.Click += (_, _) => MoveArea(0, 1);
+ _moveRightButton.Click += (_, _) => MoveArea(1, 0);
+ _canvas.KeyDown += OnCanvasKeyDown;
+
+ foreach (int step in PreviewSettings.MoveSteps)
+ {
+ _stepBox.Items.Add(step == 1 ? "1 tile" : $"{step} tiles");
+ }
+
+ _stepBox.SelectedIndexChanged += (_, _) => SaveStep();
+
+ _gotoButton.Click += (_, _) => GoTo();
+ _gotoBox.KeyDown += (_, e) =>
+ {
+ if (e.KeyCode == Keys.Enter)
+ {
+ GoTo();
+ e.Handled = e.SuppressKeyPress = true;
+ }
+ };
+ _exportButton.Click += (_, _) => Export();
+ _refreshButton.Click += (_, _) => OnClientReloaded();
+ _settingsButton.Click += (_, _) => EditSettings();
+
+ _canvas.SceneFailed += message =>
+ {
+ _canvas.Scene = null;
+ _statusLabel.Text = message;
+ };
+
+ PreviewSettings.Changed += OnSettingsChanged;
+ ControlEvents.FilePathChangeEvent += OnClientReloaded;
+ ControlEvents.MapSizeChangeEvent += OnClientReloaded;
+ ShowToggles(PreviewSettings.Current);
+ }
+
+ ///
+ /// Opens the settings. A change of area size applies to the next preview and, when a window
+ /// is open, to the spot it shows.
+ ///
+ public static void EditSettings(IWin32Window owner)
+ {
+ using var dialog = new MapPreviewSettingsDialog(PreviewSettings.Current);
+ if (dialog.ShowDialog(owner) == DialogResult.OK)
+ {
+ dialog.Result.Apply();
+ }
+ }
+
+ /// Shows the area the settings give around a tile, replacing what was shown.
+ public void ShowArea(Map map, Point center)
+ {
+ ShowArea(map, center, true);
+ }
+
+ ///
+ /// Redo the cut for the new spot: by Auto when the settings ask for it, else none. Off
+ /// keeps the cut the user set.
+ ///
+ private void ShowArea(Map map, Point center, bool recut)
+ {
+ _map = map;
+ _facet = Facets.IndexOf(map);
+ _center = center;
+ ShowCurrentArea(false, recut);
+ }
+
+ ///
+ /// The client files were reloaded or the map size changed: the facet may be a new instance,
+ /// a different size, or gone, and cached art and hues belong to the old files.
+ ///
+ private void OnClientReloaded()
+ {
+ if (IsDisposed || _map == null)
+ {
+ return;
+ }
+
+ if (_facet >= 0)
+ {
+ _map = Facets.Get(_facet);
+ }
+
+ ShowCurrentArea(true, false);
+ }
+
+ private void ShowCurrentArea(bool reloadArt, bool recut)
+ {
+ _mapName = Facets.Name(_facet, _map);
+ _area = AreaAround(_map, _center, PreviewSettings.Current);
+
+ Text = $"In-game preview - {_mapName} {_center.X},{_center.Y} ({_area.Width} x {_area.Height})";
+
+ // Shows where the preview is, ready to edit, unless the user is typing in it.
+ if (!_gotoBox.Focused)
+ {
+ _gotoBox.Text = $"{_center.X},{_center.Y}";
+ }
+ if (!LoadScene(reloadArt) || !recut)
+ {
+ return;
+ }
+
+ // A cut made for one spot means little at a far one, so it is redone or dropped.
+ if (PreviewSettings.Current.AutoRoofCut)
+ {
+ CutAtCenter();
+ }
+ else
+ {
+ SetCut(null);
+ }
+ }
+
+ ///
+ /// Moves the area by the chosen step in a screen direction. On the isometric view screen
+ /// right is map east plus north, and screen down is east plus south, so a step of n moves
+ /// n tiles along both map axes: n diamond widths across the screen.
+ ///
+ private void MoveArea(int screenX, int screenY)
+ {
+ if (_map == null)
+ {
+ return;
+ }
+
+ // After a button click, so the arrow keys carry on moving the area.
+ _canvas.Focus();
+
+ int step = PreviewSettings.Current.MoveStep;
+ int x = Math.Clamp(_center.X + ((screenX + screenY) * step), 0, _map.Width - 1);
+ int y = Math.Clamp(_center.Y + ((screenY - screenX) * step), 0, _map.Height - 1);
+ if (x == _center.X && y == _center.Y)
+ {
+ return;
+ }
+
+ // A step keeps the height being looked at; Auto, when set, follows the ground.
+ ShowArea(_map, new Point(x, y), PreviewSettings.Current.AutoRoofCut);
+ }
+
+ /// Previews the area around the coordinates typed in the go-to box.
+ private void GoTo()
+ {
+ if (_map == null)
+ {
+ return;
+ }
+
+ if (!TryParseLocation(_gotoBox.Text, out int x, out int y))
+ {
+ _statusLabel.Text = "Go to: type X and Y, for example 1430,1690 or 1430 1690.";
+ return;
+ }
+
+ if (x < 0 || y < 0 || x >= _map.Width || y >= _map.Height)
+ {
+ _statusLabel.Text = $"Go to: {x},{y} is outside {_mapName} (0-{_map.Width - 1}, 0-{_map.Height - 1}).";
+ return;
+ }
+
+ ShowArea(_map, new Point(x, y));
+ _canvas.Focus();
+ }
+
+ ///
+ /// "x,y", "x y", "x, y, z" and the like: the first two whole numbers. A z, as coordinates
+ /// are often written in game, is allowed and ignored.
+ ///
+ internal static bool TryParseLocation(string text, out int x, out int y)
+ {
+ x = y = 0;
+ string[] parts = (text ?? string.Empty).Split(new[] { ',', ' ', ';', '\t' }, StringSplitOptions.RemoveEmptyEntries);
+ return parts.Length is 2 or 3 &&
+ int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out x) &&
+ int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out y) &&
+ (parts.Length == 2 || int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out _));
+ }
+
+ private void OnCanvasKeyDown(object sender, KeyEventArgs e)
+ {
+ (int x, int y) = e.KeyCode switch
+ {
+ Keys.Left => (-1, 0),
+ Keys.Right => (1, 0),
+ Keys.Up => (0, -1),
+ Keys.Down => (0, 1),
+ _ => (0, 0)
+ };
+
+ if (x != 0 || y != 0)
+ {
+ MoveArea(x, y);
+ e.Handled = true;
+ }
+ }
+
+ /// The settings' area centred on a tile, moved inside the facet near its edges.
+ private static Rectangle AreaAround(Map map, Point center, PreviewSettings settings)
+ {
+ if (map == null || map.Width <= 0 || map.Height <= 0)
+ {
+ return Rectangle.Empty;
+ }
+
+ int width = Math.Min(settings.AreaWidth, map.Width);
+ int height = Math.Min(settings.AreaHeight, map.Height);
+ int x = Math.Clamp(center.X - (width / 2), 0, Math.Max(0, map.Width - width));
+ int y = Math.Clamp(center.Y - (height / 2), 0, Math.Max(0, map.Height - height));
+ return new Rectangle(x, y, width, height);
+ }
+
+ ///
+ /// Reads the area again. A client that cannot be read (a wrong path, missing files) leaves
+ /// an empty preview with the reason in the status bar rather than an error dialog.
+ ///
+ private bool LoadScene(bool reloadArt)
+ {
+ if (_map == null)
+ {
+ return false;
+ }
+
+ Cursor = Cursors.WaitCursor;
+ try
+ {
+ // Old art goes first, so nothing drawn from here on mixes the two clients.
+ if (reloadArt)
+ {
+ _canvas.ReloadArt();
+ }
+
+ // On the UI thread: the map caches are not safe to read from two threads, and the
+ // map tab reads them from this one.
+ _canvas.ShowScene(MapPreviewScene.Build(_map, _area), _center);
+ _statusLabel.Text = $"{_canvas.Scene.Statics.Count:N0} statics";
+ return true;
+ }
+ catch (Exception ex)
+ {
+ _canvas.Scene = null;
+ _statusLabel.Text = $"The area could not be read from the client files: {ex.Message}";
+ return false;
+ }
+ finally
+ {
+ Cursor = Cursors.Default;
+ }
+ }
+
+ private void EditSettings()
+ {
+ EditSettings(this);
+ }
+
+ private void OnSettingsChanged()
+ {
+ ShowToggles(PreviewSettings.Current);
+
+ // A new size takes effect on the spot shown now, not only on the next click.
+ if (_map != null && AreaAround(_map, _center, PreviewSettings.Current) != _area)
+ {
+ ShowCurrentArea(false, false);
+ }
+ }
+
+ private void ShowToggles(PreviewSettings settings)
+ {
+ _syncing = true;
+ try
+ {
+ _landButton.Checked = settings.ShowLand;
+ _staticsButton.Checked = settings.ShowStatics;
+ _stretchButton.Checked = settings.Stretch;
+ _lightingButton.Checked = settings.Lighting;
+ _huesButton.Checked = settings.Hues;
+ _roofsButton.Checked = settings.HideRoofs;
+ _cutLandButton.Checked = settings.CutLand;
+ _stepBox.SelectedIndex = Math.Max(0, Array.IndexOf(PreviewSettings.MoveSteps, settings.MoveStep));
+ }
+ finally
+ {
+ _syncing = false;
+ }
+
+ ApplyOptions();
+ }
+
+ /// A toggle flipped here is remembered, so the next preview starts the same way.
+ private void SaveToggles()
+ {
+ if (_syncing)
+ {
+ return;
+ }
+
+ PreviewSettings settings = PreviewSettings.Current.Clone();
+ settings.ShowLand = _landButton.Checked;
+ settings.ShowStatics = _staticsButton.Checked;
+ settings.Stretch = _stretchButton.Checked;
+ settings.Lighting = _lightingButton.Checked;
+ settings.Hues = _huesButton.Checked;
+ settings.HideRoofs = _roofsButton.Checked;
+ settings.CutLand = _cutLandButton.Checked;
+ settings.Apply();
+ }
+
+ private void SaveStep()
+ {
+ if (_syncing || _stepBox.SelectedIndex < 0)
+ {
+ return;
+ }
+
+ PreviewSettings settings = PreviewSettings.Current.Clone();
+ settings.MoveStep = PreviewSettings.MoveSteps[_stepBox.SelectedIndex];
+ settings.Apply();
+
+ // Back to the preview, so the arrow keys move the area again.
+ _canvas.Focus();
+ }
+
+ private void ApplyOptions()
+ {
+ _maxZLabel.Text = _cutZ is int z ? $"Max Z: {z}" : "Max Z: all";
+ _canvas.Options = PreviewSettings.Current.ToOptions(_cutZ);
+ }
+
+ /// Cuts at a height, or at none, and puts the slider on the nearest notch.
+ private void SetCut(int? z)
+ {
+ _cutZ = z;
+
+ _showingCut = true;
+ try
+ {
+ _maxZ.Value = z is int cut
+ ? Math.Clamp((int)Math.Round(cut / (double)CutStep), MinCutNotch, NoCutNotch - 1)
+ : NoCutNotch;
+ }
+ finally
+ {
+ _showingCut = false;
+ }
+
+ ApplyOptions();
+ }
+
+ private void CutAtCenter()
+ {
+ int z = GroundAt(_center) + RoofCut;
+ SetCut(z >= NoCut ? null : Math.Max(z, -128));
+ }
+
+ ///
+ /// Where someone standing on a tile would stand: the land, or a floor on it within a step
+ /// or two.
+ ///
+ private int GroundAt(Point tile)
+ {
+ MapPreviewScene scene = _canvas.Scene;
+ if (scene == null)
+ {
+ return 0;
+ }
+
+ int dx = Math.Clamp(tile.X - scene.Area.X, 0, scene.Area.Width - 1);
+ int dy = Math.Clamp(tile.Y - scene.Area.Y, 0, scene.Area.Height - 1);
+ int ground = scene.HeightAt(dx, dy);
+ int reach = ground + RoofCut;
+
+ foreach (SceneStatic s in scene.Statics)
+ {
+ if (s.X == dx && s.Y == dy && (s.Flags & TileFlag.Surface) != 0 && s.Z + s.Height <= reach)
+ {
+ ground = Math.Max(ground, s.Z + s.Height);
+ }
+ }
+
+ return ground;
+ }
+
+ private void Export()
+ {
+ if (_map == null)
+ {
+ return;
+ }
+
+ float scale = _canvas.ExportScale();
+ using var dialog = new SaveFileDialog
+ {
+ Filter = "PNG image (*.png)|*.png",
+ FileName = $"{_mapName}_{_area.X}_{_area.Y}_{_area.Width}x{_area.Height}.png"
+ };
+
+ if (dialog.ShowDialog(this) != DialogResult.OK)
+ {
+ return;
+ }
+
+ Cursor = Cursors.WaitCursor;
+ try
+ {
+ using Bitmap image = _canvas.RenderImage(scale);
+ if (image == null)
+ {
+ return;
+ }
+
+ image.Save(dialog.FileName, ImageFormat.Png);
+ _statusLabel.Text = scale < 1f
+ ? $"Saved {image.Width} x {image.Height} at {scale * 100f:0.#}% (an image side is capped at {MapPreviewCanvas.MaxExportSize} pixels)"
+ : $"Saved {image.Width} x {image.Height}";
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(this, ex.Message, "Export PNG", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ finally
+ {
+ Cursor = Cursors.Default;
+ }
+ }
+
+ protected override void OnKeyDown(KeyEventArgs e)
+ {
+ base.OnKeyDown(e);
+
+ if (e.KeyCode == Keys.Escape)
+ {
+ Close();
+ }
+ else if (e.KeyCode == Keys.G && e.Control)
+ {
+ _gotoBox.Focus();
+ _gotoBox.SelectAll();
+ e.Handled = e.SuppressKeyPress = true;
+ }
+ }
+
+ protected override void OnFormClosed(FormClosedEventArgs e)
+ {
+ PreviewSettings.Changed -= OnSettingsChanged;
+ ControlEvents.FilePathChangeEvent -= OnClientReloaded;
+ ControlEvents.MapSizeChangeEvent -= OnClientReloaded;
+ base.OnFormClosed(e);
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.resx b/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.resx
new file mode 100644
index 00000000..8b2ff64a
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UI/MapPreviewForm.resx
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.Designer.cs b/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.Designer.cs
new file mode 100644
index 00000000..136117d7
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.Designer.cs
@@ -0,0 +1,202 @@
+namespace UoFiddler.Plugin.MapPreview.UI
+{
+ partial class MapPreviewSettingsDialog
+ {
+ ///
+ /// 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()
+ {
+ _sizeLabel = new System.Windows.Forms.Label();
+ _sizeBox = new System.Windows.Forms.ComboBox();
+ _hintLabel = new System.Windows.Forms.Label();
+ _showGroup = new System.Windows.Forms.GroupBox();
+ _landBox = new System.Windows.Forms.CheckBox();
+ _staticsBox = new System.Windows.Forms.CheckBox();
+ _stretchBox = new System.Windows.Forms.CheckBox();
+ _lightingBox = new System.Windows.Forms.CheckBox();
+ _huesBox = new System.Windows.Forms.CheckBox();
+ _roofsBox = new System.Windows.Forms.CheckBox();
+ _autoCutBox = new System.Windows.Forms.CheckBox();
+ _okButton = new System.Windows.Forms.Button();
+ _cancelButton = new System.Windows.Forms.Button();
+ _showGroup.SuspendLayout();
+ SuspendLayout();
+ //
+ // _sizeLabel
+ //
+ _sizeLabel.Location = new System.Drawing.Point(12, 15);
+ _sizeLabel.Name = "_sizeLabel";
+ _sizeLabel.Size = new System.Drawing.Size(110, 20);
+ _sizeLabel.TabIndex = 0;
+ _sizeLabel.Text = "Area (tiles)";
+ //
+ // _sizeBox
+ //
+ _sizeBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
+ _sizeBox.Location = new System.Drawing.Point(128, 13);
+ _sizeBox.Name = "_sizeBox";
+ _sizeBox.Size = new System.Drawing.Size(164, 23);
+ _sizeBox.TabIndex = 1;
+ //
+ // _hintLabel
+ //
+ _hintLabel.ForeColor = System.Drawing.SystemColors.GrayText;
+ _hintLabel.Location = new System.Drawing.Point(12, 42);
+ _hintLabel.Name = "_hintLabel";
+ _hintLabel.Size = new System.Drawing.Size(300, 20);
+ _hintLabel.TabIndex = 4;
+ //
+ // _showGroup
+ //
+ _showGroup.Controls.Add(_landBox);
+ _showGroup.Controls.Add(_staticsBox);
+ _showGroup.Controls.Add(_stretchBox);
+ _showGroup.Controls.Add(_lightingBox);
+ _showGroup.Controls.Add(_huesBox);
+ _showGroup.Controls.Add(_roofsBox);
+ _showGroup.Controls.Add(_autoCutBox);
+ _showGroup.Location = new System.Drawing.Point(12, 68);
+ _showGroup.Name = "_showGroup";
+ _showGroup.Size = new System.Drawing.Size(300, 200);
+ _showGroup.TabIndex = 5;
+ _showGroup.TabStop = false;
+ _showGroup.Text = "Show";
+ //
+ // _landBox
+ //
+ _landBox.Location = new System.Drawing.Point(12, 22);
+ _landBox.Name = "_landBox";
+ _landBox.Size = new System.Drawing.Size(130, 22);
+ _landBox.TabIndex = 0;
+ _landBox.Text = "Land";
+ //
+ // _staticsBox
+ //
+ _staticsBox.Location = new System.Drawing.Point(150, 22);
+ _staticsBox.Name = "_staticsBox";
+ _staticsBox.Size = new System.Drawing.Size(130, 22);
+ _staticsBox.TabIndex = 1;
+ _staticsBox.Text = "Statics";
+ //
+ // _stretchBox
+ //
+ _stretchBox.Location = new System.Drawing.Point(12, 48);
+ _stretchBox.Name = "_stretchBox";
+ _stretchBox.Size = new System.Drawing.Size(130, 22);
+ _stretchBox.TabIndex = 2;
+ _stretchBox.Text = "Stretched land";
+ //
+ // _lightingBox
+ //
+ _lightingBox.Location = new System.Drawing.Point(150, 48);
+ _lightingBox.Name = "_lightingBox";
+ _lightingBox.Size = new System.Drawing.Size(130, 22);
+ _lightingBox.TabIndex = 3;
+ _lightingBox.Text = "Lighting";
+ //
+ // _huesBox
+ //
+ _huesBox.Location = new System.Drawing.Point(12, 74);
+ _huesBox.Name = "_huesBox";
+ _huesBox.Size = new System.Drawing.Size(130, 22);
+ _huesBox.TabIndex = 4;
+ _huesBox.Text = "Hues";
+ //
+ // _roofsBox
+ //
+ _roofsBox.Location = new System.Drawing.Point(150, 74);
+ _roofsBox.Name = "_roofsBox";
+ _roofsBox.Size = new System.Drawing.Size(130, 22);
+ _roofsBox.TabIndex = 5;
+ _roofsBox.Text = "Hide roofs";
+ //
+ // _autoCutBox
+ //
+ _autoCutBox.Location = new System.Drawing.Point(12, 106);
+ _autoCutBox.Name = "_autoCutBox";
+ _autoCutBox.Size = new System.Drawing.Size(280, 84);
+ _autoCutBox.TabIndex = 6;
+ _autoCutBox.Text = "Cut above the clicked spot on every preview (Max Z = the ground or floor there + 16), as the client does under a roof";
+ _autoCutBox.TextAlign = System.Drawing.ContentAlignment.TopLeft;
+ _autoCutBox.CheckAlign = System.Drawing.ContentAlignment.TopLeft;
+ //
+ // _okButton
+ //
+ _okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
+ _okButton.Location = new System.Drawing.Point(156, 280);
+ _okButton.Name = "_okButton";
+ _okButton.Size = new System.Drawing.Size(76, 23);
+ _okButton.TabIndex = 6;
+ _okButton.Text = "OK";
+ //
+ // _cancelButton
+ //
+ _cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
+ _cancelButton.Location = new System.Drawing.Point(236, 280);
+ _cancelButton.Name = "_cancelButton";
+ _cancelButton.Size = new System.Drawing.Size(76, 23);
+ _cancelButton.TabIndex = 7;
+ _cancelButton.Text = "Cancel";
+ //
+ // MapPreviewSettingsDialog
+ //
+ AcceptButton = _okButton;
+ AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ CancelButton = _cancelButton;
+ ClientSize = new System.Drawing.Size(324, 315);
+ Controls.Add(_sizeLabel);
+ Controls.Add(_sizeBox);
+ Controls.Add(_hintLabel);
+ Controls.Add(_showGroup);
+ Controls.Add(_okButton);
+ Controls.Add(_cancelButton);
+ FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
+ MaximizeBox = false;
+ MinimizeBox = false;
+ Name = "MapPreviewSettingsDialog";
+ ShowInTaskbar = false;
+ StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+ Text = "In-game preview settings";
+ _showGroup.ResumeLayout(false);
+ ResumeLayout(false);
+ }
+
+ #endregion
+
+ private System.Windows.Forms.Label _sizeLabel;
+ private System.Windows.Forms.ComboBox _sizeBox;
+ private System.Windows.Forms.Label _hintLabel;
+ private System.Windows.Forms.GroupBox _showGroup;
+ private System.Windows.Forms.CheckBox _landBox;
+ private System.Windows.Forms.CheckBox _staticsBox;
+ private System.Windows.Forms.CheckBox _stretchBox;
+ private System.Windows.Forms.CheckBox _lightingBox;
+ private System.Windows.Forms.CheckBox _huesBox;
+ private System.Windows.Forms.CheckBox _roofsBox;
+ private System.Windows.Forms.CheckBox _autoCutBox;
+ private System.Windows.Forms.Button _okButton;
+ private System.Windows.Forms.Button _cancelButton;
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.cs b/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.cs
new file mode 100644
index 00000000..74029e3f
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.cs
@@ -0,0 +1,68 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Windows.Forms;
+
+namespace UoFiddler.Plugin.MapPreview.UI
+{
+ /// Edits : the area a preview covers and what it draws.
+ public partial class MapPreviewSettingsDialog : Form
+ {
+ /// What the dialog opened with, for settings it does not show.
+ private readonly PreviewSettings _original;
+
+ public MapPreviewSettingsDialog(PreviewSettings settings)
+ {
+ InitializeComponent();
+
+ _original = settings;
+
+ _hintLabel.Text = "Centred on the clicked tile. Larger areas take longer to open.";
+ foreach (int size in PreviewSettings.AreaSizes)
+ {
+ _sizeBox.Items.Add(new AreaSize(size));
+ }
+
+ _sizeBox.SelectedIndex = Array.IndexOf(PreviewSettings.AreaSizes,
+ PreviewSettings.NearestAreaSize(Math.Max(settings.AreaWidth, settings.AreaHeight)));
+ _landBox.Checked = settings.ShowLand;
+ _staticsBox.Checked = settings.ShowStatics;
+ _stretchBox.Checked = settings.Stretch;
+ _lightingBox.Checked = settings.Lighting;
+ _huesBox.Checked = settings.Hues;
+ _roofsBox.Checked = settings.HideRoofs;
+ _autoCutBox.Checked = settings.AutoRoofCut;
+ }
+
+ /// The settings as edited. Not applied; the caller does that on OK.
+ public PreviewSettings Result => new PreviewSettings
+ {
+ AreaWidth = SelectedSize,
+ AreaHeight = SelectedSize,
+ ShowLand = _landBox.Checked,
+ ShowStatics = _staticsBox.Checked,
+ Stretch = _stretchBox.Checked,
+ Lighting = _lightingBox.Checked,
+ Hues = _huesBox.Checked,
+ HideRoofs = _roofsBox.Checked,
+ AutoRoofCut = _autoCutBox.Checked,
+ MoveStep = _original.MoveStep,
+ CutLand = _original.CutLand
+ };
+
+ private int SelectedSize => _sizeBox.SelectedItem is AreaSize size ? size.Tiles : PreviewSettings.AreaSizes[0];
+
+ /// A drop-down entry: "64 x 64".
+ private sealed record AreaSize(int Tiles)
+ {
+ public override string ToString() => $"{Tiles} x {Tiles}";
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.resx b/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.resx
new file mode 100644
index 00000000..8b2ff64a
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UI/MapPreviewSettingsDialog.resx
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/UoFiddler.Plugin.MapPreview/UoFiddler.Plugin.MapPreview.csproj b/UoFiddler.Plugin.MapPreview/UoFiddler.Plugin.MapPreview.csproj
new file mode 100644
index 00000000..c714eb72
--- /dev/null
+++ b/UoFiddler.Plugin.MapPreview/UoFiddler.Plugin.MapPreview.csproj
@@ -0,0 +1,65 @@
+
+
+ MapPreview
+ net10.0-windows
+ true
+ true
+ false
+ MapPreview
+ MapPreview
+ Copyright © 2026
+ 1.0.0.0
+ 1.0.0.0
+
+ false
+
+
+ true
+
+
+ portable
+ ..\UoFiddler\bin\$(Configuration)\plugins\
+
+
+ none
+ ..\UoFiddler\bin\$(Configuration)\plugins\
+ Off
+
+
+
+ false
+ runtime
+
+
+ false
+ runtime
+
+
+
+ false
+ runtime
+
+
+
+
+ Form
+
+
+ MapPreviewSettingsDialog.cs
+
+
+ Form
+
+
+ MapPreviewForm.cs
+
+
+
+
+ MapPreviewSettingsDialog.cs
+
+
+ MapPreviewForm.cs
+
+
+
diff --git a/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs b/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs
index 29ab8045..9ea7199d 100644
--- a/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs
+++ b/UoFiddler.Plugin.MultiEditor/MultiEditorPluginBase.cs
@@ -103,6 +103,7 @@ private void OnMapContextMenu(ContextMenuStrip strip, Func<(Map Map, System.Draw
(Map map, System.Drawing.Point location) = clickedAt();
_editor.ExtractFromMap(map, location);
};
+ strip.Items.Add(new ToolStripSeparator());
strip.Items.Add(item);
}
}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs
index 795badf9..b55c96b5 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs
@@ -12,6 +12,7 @@
using System;
using System.Collections.Generic;
using Ultima;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs
index 724f3f6a..f5d07f14 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs
@@ -8,6 +8,7 @@
***************************************************************************/
using System.Collections.Generic;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs b/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs
index f841db65..88ce6c62 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs
@@ -12,10 +12,9 @@
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
-using OpenTK.GLControl;
using OpenTK.Graphics.OpenGL4;
-using OpenTK.Windowing.Common;
using UoFiddler.Plugin.MultiEditor.Editing;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
@@ -24,7 +23,7 @@ namespace UoFiddler.Plugin.MultiEditor.Rendering
/// demand. It owns the camera gestures (pan, zoom) and passes the rest of the mouse to the
/// session in world coordinates.
///
- internal sealed class GlCanvas : GLControl
+ internal sealed class GlCanvas : GlHostControl
{
private bool _ready;
private bool _failed;
@@ -49,17 +48,6 @@ internal sealed class GlCanvas : GLControl
/// Raised after pan or zoom changed.
public event Action CameraChanged;
- public GlCanvas()
- : base(new GLControlSettings
- {
- API = ContextAPI.OpenGL,
- APIVersion = new Version(3, 3),
- Profile = ContextProfile.Core,
- Flags = ContextFlags.ForwardCompatible
- })
- {
- }
-
public Camera2D Camera { get; private set; } = new Camera2D();
/// The session shown. Each session keeps its own camera, passed in with it.
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs b/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs
index ba3d8949..19b15abf 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs
@@ -10,6 +10,7 @@
using System;
using System.Drawing;
using OpenTK.Graphics.OpenGL4;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs
index 6f2e5a7e..0ca5b6b2 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs
@@ -13,6 +13,7 @@
using UoFiddler.Plugin.MultiEditor.Tools;
using UoFiddler.Plugin.MultiEditor.Editing;
using UoFiddler.Plugin.MultiEditor.Model;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs
index f7c2bf42..01f72d52 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs
@@ -10,6 +10,7 @@
using System;
using System.Drawing;
using OpenTK.Graphics.OpenGL4;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs
index 162e6d33..a1e2c042 100644
--- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs
+++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs
@@ -18,6 +18,7 @@
using UoFiddler.Plugin.MultiEditor.Rendering;
using UoFiddler.Plugin.MultiEditor.Model;
using UoFiddler.Plugin.MultiEditor.Styles;
+using UoFiddler.Rendering;
namespace UoFiddler.Plugin.MultiEditor.UI
{
diff --git a/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj b/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj
index 2ee72d73..d4b8002f 100644
--- a/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj
+++ b/UoFiddler.Plugin.MultiEditor/UoFiddler.Plugin.MultiEditor.csproj
@@ -12,7 +12,7 @@
3.0.0.0
true
false
-
+
false
@@ -27,9 +27,6 @@
..\UoFiddler\bin\$(Configuration)\plugins\
Off
-
-
-
false
@@ -39,6 +36,11 @@
false
runtime
+
+
+ false
+ runtime
+
@@ -210,15 +212,4 @@
PreserveNewest
-
-
-
- <_PluginDependency Include="@(RuntimeCopyLocalItems)" />
- <_PluginDependency Include="@(RuntimeTargetsCopyLocalItems)" Condition="'%(RuntimeTargetsCopyLocalItems.RuntimeIdentifier)' == 'win-x64'" />
-
-
-
\ No newline at end of file
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtAtlas.cs b/UoFiddler.Rendering/ArtAtlas.cs
similarity index 83%
rename from UoFiddler.Plugin.MultiEditor/Rendering/ArtAtlas.cs
rename to UoFiddler.Rendering/ArtAtlas.cs
index 636b15c0..e43a01ce 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/ArtAtlas.cs
+++ b/UoFiddler.Rendering/ArtAtlas.cs
@@ -11,16 +11,16 @@
using System.Collections.Generic;
using OpenTK.Graphics.OpenGL4;
-namespace UoFiddler.Plugin.MultiEditor.Rendering
+namespace UoFiddler.Rendering
{
/// Where a sprite sits in the atlas, in pixels.
- internal readonly record struct AtlasSprite(int Layer, int X, int Y, int Width, int Height);
+ public readonly record struct AtlasSprite(int Layer, int X, int Y, int Width, int Height);
///
/// Static art packed into one texture array, filled as tiles are first drawn. One texture
/// means the whole multi draws in one call and keeps its draw order.
///
- internal sealed class ArtAtlas : IDisposable
+ public sealed class ArtAtlas : IDisposable
{
public const int Size = 2048;
@@ -35,9 +35,15 @@ internal sealed class ArtAtlas : IDisposable
/// Keys from here down are land tiles; see .
private const int _landBase = -1000;
+ /// Keys from here down are texmaps; see .
+ private const int _texmapBase = -100000;
+
/// The atlas key of a land tile's art (ground under a previewed multi).
public static int LandKey(int landId) => _landBase - landId;
+ /// The atlas key of a texmap, the texture stretched over sloped land.
+ public static int TexmapKey(int textureId) => _texmapBase - textureId;
+
private readonly Dictionary _sprites = new Dictionary();
private readonly HashSet _missing = new HashSet();
@@ -68,7 +74,7 @@ public bool TryGet(int key, out AtlasSprite sprite)
return false;
}
- byte[] pixels = Load(key, out int width, out int height);
+ byte[] pixels = TryLoad(key, out int width, out int height);
if (pixels == null || width > Size - Padding || height > Size - Padding)
{
_missing.Add(key);
@@ -102,6 +108,24 @@ public void Dispose()
_texture = 0;
}
+ ///
+ /// Art that cannot be read (files missing or swapped by a client reload) counts as having
+ /// none, so one bad entry blanks a sprite instead of failing the whole frame.
+ ///
+ private static byte[] TryLoad(int key, out int width, out int height)
+ {
+ try
+ {
+ return Load(key, out width, out height);
+ }
+ catch (Exception)
+ {
+ width = 0;
+ height = 0;
+ return null;
+ }
+ }
+
private static byte[] Load(int key, out int width, out int height)
{
switch (key)
@@ -115,6 +139,11 @@ private static byte[] Load(int key, out int width, out int height)
width = height = ArtPixels.FloorSize;
return ArtPixels.FloorDiamond();
default:
+ if (key <= _texmapBase)
+ {
+ return ArtPixels.LoadTexmap(_texmapBase - key, out width, out height);
+ }
+
return key <= _landBase
? ArtPixels.LoadLand(_landBase - key, out width, out height)
: ArtPixels.LoadStatic((ushort)key, out width, out height);
@@ -159,7 +188,7 @@ private void Grow()
Allocate(_layers * 2);
foreach (KeyValuePair entry in _sprites)
{
- byte[] pixels = Load(entry.Key, out int width, out int height);
+ byte[] pixels = TryLoad(entry.Key, out int width, out int height);
if (pixels != null && width == entry.Value.Width && height == entry.Value.Height)
{
Upload(entry.Value, pixels);
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs b/UoFiddler.Rendering/ArtPixels.cs
similarity index 87%
rename from UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs
rename to UoFiddler.Rendering/ArtPixels.cs
index bcf4c56e..0eae48cd 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs
+++ b/UoFiddler.Rendering/ArtPixels.cs
@@ -11,12 +11,13 @@
using System.Drawing.Imaging;
using Ultima;
-namespace UoFiddler.Plugin.MultiEditor.Rendering
+namespace UoFiddler.Rendering
{
///
- /// Static art as RGBA8 pixels, read from the art cache so replaced art shows.
+ /// Art and texmaps as RGBA8 pixels, read from the caches so replaced art shows. Each 5-bit
+ /// channel is widened, so a shader can get the hue index back from red.
///
- internal static class ArtPixels
+ public static class ArtPixels
{
public const int FloorSize = 44;
@@ -32,6 +33,12 @@ public static byte[] LoadLand(int id, out int width, out int height)
return ToRgba(Art.GetLand(id), out width, out height);
}
+ /// RGBA8 pixels of a texmap (64x64 or 128x128), or null when there is none.
+ public static byte[] LoadTexmap(int id, out int width, out int height)
+ {
+ return ToRgba(Textures.GetTexture(id), out width, out height);
+ }
+
private static unsafe byte[] ToRgba(Bitmap bitmap, out int width, out int height)
{
width = 0;
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/Camera2D.cs b/UoFiddler.Rendering/Camera2D.cs
similarity index 83%
rename from UoFiddler.Plugin.MultiEditor/Rendering/Camera2D.cs
rename to UoFiddler.Rendering/Camera2D.cs
index 2ade1cdc..4f04595f 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/Camera2D.cs
+++ b/UoFiddler.Rendering/Camera2D.cs
@@ -10,17 +10,22 @@
using System;
using System.Drawing;
-namespace UoFiddler.Plugin.MultiEditor.Rendering
+namespace UoFiddler.Rendering
{
///
- /// Pan and zoom of the canvas. World space is the tile pixel space of the multi
- /// (MultiTile.XMod/YMod); screen = (world - origin) * zoom.
+ /// Pan and zoom of a canvas. World space is the isometric tile pixel space of what is drawn;
+ /// screen = (world - origin) * zoom.
///
- internal sealed class Camera2D
+ public sealed class Camera2D
{
- public const float MinZoom = 0.25f;
public const float MaxZoom = 8f;
+ ///
+ /// The smallest zoom. Below a quarter the steps halve instead of dropping by a quarter, so a
+ /// large map area can be shown whole.
+ ///
+ public float MinZoom { get; init; } = 0.25f;
+
/// World position shown at the top left of the canvas.
public float OriginX { get; private set; }
@@ -75,11 +80,13 @@ public void ZoomStep(Point anchor, int direction)
float zoom = Zoom;
if (direction > 0)
{
- zoom = zoom < 1f ? Math.Min(1f, zoom + 0.25f) : (float)Math.Floor(zoom) + 1f;
+ zoom = zoom < 0.25f ? zoom * 2f
+ : zoom < 1f ? Math.Min(1f, zoom + 0.25f) : (float)Math.Floor(zoom) + 1f;
}
else
{
- zoom = zoom > 1f ? (float)Math.Ceiling(zoom) - 1f : zoom - 0.25f;
+ zoom = zoom > 1f ? (float)Math.Ceiling(zoom) - 1f
+ : zoom > 0.25f ? zoom - 0.25f : zoom / 2f;
}
ZoomAt(anchor, zoom);
@@ -112,7 +119,8 @@ public void Fit(RectangleF world, Size view, float maxZoom = 2f, int margin = 24
zoom = 1f;
while (zoom > MinZoom && zoom > fit)
{
- zoom -= 0.25f;
+ // Under a quarter the art is already a blur, so the view simply fits exactly.
+ zoom = zoom > 0.25f ? zoom - 0.25f : fit;
}
}
diff --git a/UoFiddler.Rendering/GlHostControl.cs b/UoFiddler.Rendering/GlHostControl.cs
new file mode 100644
index 00000000..4a144a20
--- /dev/null
+++ b/UoFiddler.Rendering/GlHostControl.cs
@@ -0,0 +1,33 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using OpenTK.GLControl;
+using OpenTK.Windowing.Common;
+
+namespace UoFiddler.Rendering
+{
+ ///
+ /// A WinForms surface with an OpenGL 3.3 core, forward-compatible context: the context every
+ /// shader in this library is written for.
+ ///
+ public abstract class GlHostControl : GLControl
+ {
+ protected GlHostControl()
+ : base(new GLControlSettings
+ {
+ API = ContextAPI.OpenGL,
+ APIVersion = new Version(3, 3),
+ Profile = ContextProfile.Core,
+ Flags = ContextFlags.ForwardCompatible
+ })
+ {
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ShaderProgram.cs b/UoFiddler.Rendering/ShaderProgram.cs
similarity index 95%
rename from UoFiddler.Plugin.MultiEditor/Rendering/ShaderProgram.cs
rename to UoFiddler.Rendering/ShaderProgram.cs
index 572118de..d2e02487 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/ShaderProgram.cs
+++ b/UoFiddler.Rendering/ShaderProgram.cs
@@ -10,9 +10,9 @@
using System;
using OpenTK.Graphics.OpenGL4;
-namespace UoFiddler.Plugin.MultiEditor.Rendering
+namespace UoFiddler.Rendering
{
- internal sealed class ShaderProgram : IDisposable
+ public sealed class ShaderProgram : IDisposable
{
public int Handle { get; }
diff --git a/UoFiddler.Rendering/UoFiddler.Rendering.csproj b/UoFiddler.Rendering/UoFiddler.Rendering.csproj
new file mode 100644
index 00000000..8f1e513a
--- /dev/null
+++ b/UoFiddler.Rendering/UoFiddler.Rendering.csproj
@@ -0,0 +1,43 @@
+
+
+ UoFiddler.Rendering
+ net10.0-windows
+ true
+ true
+ false
+ UoFiddler.Rendering
+ UoFiddler.Rendering
+ Copyright © 2026
+
+ false
+ true
+
+
+
+ portable
+ ..\UoFiddler\bin\$(Configuration)\plugins\UoFiddler.Rendering\
+
+
+ none
+ ..\UoFiddler\bin\$(Configuration)\plugins\UoFiddler.Rendering\
+
+
+
+
+
+
+ false
+ runtime
+
+
+
+
+ <_RenderingDependency Include="@(RuntimeCopyLocalItems)" />
+ <_RenderingDependency Include="@(RuntimeTargetsCopyLocalItems)" Condition="'%(RuntimeTargetsCopyLocalItems.RuntimeIdentifier)' == 'win-x64'" />
+
+
+
+
diff --git a/UoFiddler.sln b/UoFiddler.sln
index 96cc4f31..545fef03 100644
--- a/UoFiddler.sln
+++ b/UoFiddler.sln
@@ -29,6 +29,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UoFiddler.Plugin.UopPacker", "UoFiddler.Plugin.UopPacker\UoFiddler.Plugin.UopPacker.csproj", "{CB56DEB3-7304-4AD4-8442-BD1CAA58D472}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UoFiddler.Rendering", "UoFiddler.Rendering\UoFiddler.Rendering.csproj", "{F3367DE7-B9CC-4703-8E30-B57577AAF667}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UoFiddler.Plugin.MapPreview", "UoFiddler.Plugin.MapPreview\UoFiddler.Plugin.MapPreview.csproj", "{6780FAB6-9A07-48BB-9D18-872B44CDCDB6}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -147,6 +151,30 @@ Global
{CB56DEB3-7304-4AD4-8442-BD1CAA58D472}.Release|x64.Build.0 = Release|Any CPU
{CB56DEB3-7304-4AD4-8442-BD1CAA58D472}.Release|x86.ActiveCfg = Release|Any CPU
{CB56DEB3-7304-4AD4-8442-BD1CAA58D472}.Release|x86.Build.0 = Release|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Debug|x64.Build.0 = Debug|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Debug|x86.Build.0 = Debug|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Release|x64.ActiveCfg = Release|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Release|x64.Build.0 = Release|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Release|x86.ActiveCfg = Release|Any CPU
+ {F3367DE7-B9CC-4703-8E30-B57577AAF667}.Release|x86.Build.0 = Release|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Debug|x64.Build.0 = Debug|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Debug|x86.Build.0 = Debug|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Release|x64.ActiveCfg = Release|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Release|x64.Build.0 = Release|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Release|x86.ActiveCfg = Release|Any CPU
+ {6780FAB6-9A07-48BB-9D18-872B44CDCDB6}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/UoFiddler/Forms/AboutBoxForm.resx b/UoFiddler/Forms/AboutBoxForm.resx
index f93f4448..5535ac69 100644
--- a/UoFiddler/Forms/AboutBoxForm.resx
+++ b/UoFiddler/Forms/AboutBoxForm.resx
@@ -118,7 +118,15 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- Version 4.28.3
+ Version 4.29.0
+- Map Preview: new plugin; "In-game preview here" in the map context menu shows the area as the client draws it, with stretched and lit land, hues and hidden roofs
+- Map Preview: a Max Z slider cuts statics at a height, and Auto cuts them above the ground at the centre as the client does under a roof; Cut land hides the land above it too, to show statics under the terrain
+- Map Preview: fit, 1:1 and mouse zoom; the area exports to PNG
+- Map Preview: areas from 32 to 256 tiles; arrow buttons and keys move the area by 1 to 32 tiles, and Go to (Ctrl+G) jumps to X, Y
+- Map Preview: settings are under Plugins and kept in the profile; the preview follows client reloads
+- Map: the map context menu is split into groups
+
+Version 4.28.3
- Multi Editor: roofs sit on the wall tops whatever floor is chosen; a drag over the walls, the floor or the roof area fits the roof to the walls, and the overhang grows the multi
- Multi Editor: hip roofs; a roof dragged across another joins it with valleys and a T piece, and a click roofs each part of an L or T shaped house
- Multi Editor: a roof stays open for shaping (move and resize its wings, add wings, turn ridges) until Enter places it on a Roof layer; Esc drops it
diff --git a/UoFiddler/UoFiddler.csproj b/UoFiddler/UoFiddler.csproj
index 899414d5..ebad61b4 100644
--- a/UoFiddler/UoFiddler.csproj
+++ b/UoFiddler/UoFiddler.csproj
@@ -9,9 +9,9 @@
UoFiddler
UoFiddler
Copyright © 2026
- 4.28.3
- 4.28.3
- 4.28.3
+ 4.29.0
+ 4.29.0
+ 4.29.0
true