diff --git a/Ultima/AnimationEdit.cs b/Ultima/AnimationEdit.cs
index 227cbede..df87a6ac 100644
--- a/Ultima/AnimationEdit.cs
+++ b/Ultima/AnimationEdit.cs
@@ -255,27 +255,96 @@ public static bool IsActionDefined(int fileType, int body, int action)
return valid && length >= 1;
}
- public static void LoadFromVD(int fileType, int body, BinaryReader bin)
+ ///
+ /// Number of actions in a body .vd of . That is the body's action count when a
+ /// .vd type exists for it (22, 13 or 35). Otherwise it is the body's whole idx block, so a 9-action sea
+ /// monster in a 22-action block goes out as a 22-action monster .vd and nothing is lost.
+ ///
+ public static int GetVdActionCount(int body, int fileType)
{
- AnimIdx[] cache = GetCache(fileType);
- GetFileIndex(body, fileType, 0, 0, out FileIndex _, out int index);
- int animLength = Animations.GetAnimLength(body, fileType) * 5;
- var entries = new Entry3D[animLength];
+ int animLength = Animations.GetAnimLength(body, fileType);
+ return GetVdType(animLength) >= 0 ? animLength : Animations.GetActionCapacity(body, fileType);
+ }
- for (int i = 0; i < animLength; ++i)
+ ///
+ /// .vd header type for a body with actions: 0 = 22 (monster),
+ /// 1 = 13 (animal), 2 = 35 (human), or -1 when no type has that many.
+ ///
+ public static short GetVdType(int actionCount)
+ {
+ switch (actionCount)
+ {
+ case 22: return 0;
+ case 13: return 1;
+ case 35: return 2;
+ default: return -1;
+ }
+ }
+
+ ///
+ /// Reads the index entries that follow the .vd header and checks that the
+ /// file really holds that many: every entry with data must point past the index.
+ ///
+ /// The file holds fewer entries than expected.
+ private static Entry3D[] ReadVdEntries(BinaryReader bin, int count)
+ {
+ long dataStart = bin.BaseStream.Position + (12L * count);
+ long fileLength = bin.BaseStream.Length;
+ if (dataStart > fileLength)
+ {
+ throw new InvalidDataException(
+ $"The file is too short for {count / 5} actions. It was made for a body with fewer actions. Nothing was imported.");
+ }
+
+ var entries = new Entry3D[count];
+ for (int i = 0; i < count; ++i)
{
entries[i].Lookup = bin.ReadInt32();
entries[i].Length = bin.ReadInt32();
entries[i].Extra = bin.ReadInt32();
}
- for (int i = 0; i < entries.Length; ++i, ++index)
+ for (int i = 0; i < count; ++i)
+ {
+ Entry3D entry = entries[i];
+ if (entry.Lookup > 0 && entry.Length > 0 && (entry.Lookup < dataStart || entry.Lookup >= fileLength))
+ {
+ throw new InvalidDataException(
+ $"The file does not hold {count / 5} actions: action {i / 5}, direction {i % 5} points into the index. " +
+ "It was made for a body with fewer actions. Nothing was imported.");
+ }
+ }
+
+ return entries;
+ }
+
+ ///
+ /// Reads a body .vd, positioned after its 4-byte header, into . The file must
+ /// hold actions. Nothing changes if it can't be read.
+ ///
+ /// The file holds fewer entries than the body needs.
+ public static void LoadFromVD(int fileType, int body, BinaryReader bin)
+ {
+ AnimIdx[] cache = GetCache(fileType);
+ GetFileIndex(body, fileType, 0, 0, out FileIndex _, out int index);
+ Entry3D[] entries = ReadVdEntries(bin, GetVdActionCount(body, fileType) * 5);
+
+ var loaded = new AnimIdx[entries.Length];
+ for (int i = 0; i < entries.Length; ++i)
{
Entry3D entry = entries[i];
- if ((entry.Lookup > 0) && (entry.Lookup < bin.BaseStream.Length) && (entry.Length > 0))
+ if ((entry.Lookup > 0) && (entry.Length > 0))
{
bin.BaseStream.Seek(entry.Lookup, SeekOrigin.Begin);
- cache[index] = new AnimIdx(bin, entry.Extra);
+ loaded[i] = new AnimIdx(bin, entry.Extra);
+ }
+ }
+
+ for (int i = 0; i < entries.Length; ++i, ++index)
+ {
+ if (loaded[i] != null)
+ {
+ cache[index] = loaded[i];
}
else
{
@@ -300,38 +369,76 @@ private static void EnsureFramesFit(AnimIdx anim, string where)
}
}
- public static void ExportToVD(int fileType, int body, string file)
+ ///
+ /// Writes the body as a .vd file. A other than 1 resizes every frame
+ /// and its center in the file only; the loaded animation is left as it is.
+ ///
+ /// A frame does not fit its run headers. Nothing is written.
+ public static void ExportToVD(int fileType, int body, string file, double scale = 1.0)
{
AnimIdx[] cache = GetCache(fileType);
GetFileIndex(body, fileType, 0, 0, out FileIndex fileIndex, out int index);
- int bodyLength = Animations.GetAnimLength(body, fileType) * 5;
- for (int i = 0; i < bodyLength && cache != null && index + i < cache.Length; ++i)
+ int animLength = GetVdActionCount(body, fileType);
+ var anims = new AnimIdx[animLength * 5];
+ for (int i = 0; i < anims.Length; ++i)
{
- EnsureFramesFit(cache[index + i], $"Body {body}, action {i / 5}, direction {i % 5}");
+ int slot = index + i;
+ AnimIdx anim = cache[slot] ?? (cache[slot] = new AnimIdx(slot, fileIndex));
+ anims[i] = ScaleForExport(anim, scale);
+ EnsureFramesFit(anims[i], $"Body {body}, action {i / 5}, direction {i % 5}");
}
+ WriteBodyVD(file, GetVdType(animLength), anims);
+ }
+
+ ///
+ /// Writes as a .vd in another body type's action layout. Action
+ /// t of the file holds action sourceActions[t] of the body, or nothing where that is -1.
+ /// A sea monster layout (9 actions) is written as a 22-action monster .vd with the rest left empty,
+ /// the way sea monster bodies are stored.
+ ///
+ /// A frame does not fit its run headers. Nothing is written.
+ public static void ExportRemappedToVD(int fileType, int body, MobType layout, IReadOnlyList sourceActions, string file, double scale = 1.0)
+ {
+ int layoutActions = MobTypes.GetActionCount(layout == MobType.Equipment ? MobType.Human : layout);
+ int vdActions = GetVdType(layoutActions) >= 0 ? layoutActions : 22;
+
+ var anims = new AnimIdx[vdActions * 5];
+ for (int target = 0; target < layoutActions && target < sourceActions.Count; ++target)
+ {
+ int source = sourceActions[target];
+ if (source < 0 || !IsActionInRange(fileType, body, source))
+ {
+ continue;
+ }
+
+ for (int dir = 0; dir < 5; ++dir)
+ {
+ AnimIdx anim = ScaleForExport(GetAnimation(fileType, body, source, dir), scale);
+ EnsureFramesFit(anim, $"Body {body}, action {source}, direction {dir}");
+ anims[(target * 5) + dir] = anim;
+ }
+ }
+
+ WriteBodyVD(file, GetVdType(vdActions), anims);
+ }
+
+ ///
+ /// Writes a body .vd: the header, one index entry per action and direction, then each animation.
+ /// A null animation gets an empty entry.
+ ///
+ private static void WriteBodyVD(string file, short vdType, AnimIdx[] anims)
+ {
using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Write))
using (var bin = new BinaryWriter(fs))
{
bin.Write((short)6);
- int animLength = Animations.GetAnimLength(body, fileType);
- int currType = animLength == 22 ? 0 : animLength == 13 ? 1 : 2;
- bin.Write((short)currType);
+ bin.Write(vdType);
long indexPos = bin.BaseStream.Position;
- long animPos = bin.BaseStream.Position + (12 * animLength * 5);
- for (int i = index; i < index + (animLength * 5); i++)
+ long animPos = bin.BaseStream.Position + (12 * anims.Length);
+ foreach (AnimIdx anim in anims)
{
- AnimIdx anim;
- if (cache != null)
- {
- anim = cache[i] != null ? cache[i] : cache[i] = new AnimIdx(i, fileIndex);
- }
- else
- {
- anim = cache[i] = new AnimIdx(i, fileIndex);
- }
-
if (anim == null)
{
bin.BaseStream.Seek(indexPos, SeekOrigin.Begin);
@@ -377,11 +484,14 @@ public static bool IsActionInRange(int fileType, int body, int action)
///
/// Writes one action as a .vd file: the body .vd layout with 5 index entries, one per direction.
///
- public static void ExportActionToVD(int fileType, int body, int action, string file)
+ /// A frame does not fit its run headers. Nothing is written.
+ public static void ExportActionToVD(int fileType, int body, int action, string file, double scale = 1.0)
{
+ var anims = new AnimIdx[5];
for (int dir = 0; dir < 5; ++dir)
{
- EnsureFramesFit(GetAnimation(fileType, body, action, dir), $"Body {body}, action {action}, direction {dir}");
+ anims[dir] = ScaleForExport(GetAnimation(fileType, body, action, dir), scale);
+ EnsureFramesFit(anims[dir], $"Body {body}, action {action}, direction {dir}");
}
using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Write))
@@ -393,30 +503,34 @@ public static void ExportActionToVD(int fileType, int body, int action, string f
long animPos = bin.BaseStream.Position + (12 * 5);
for (int dir = 0; dir < 5; ++dir)
{
- GetAnimation(fileType, body, action, dir).ExportToVD(bin, ref indexPos, ref animPos);
+ anims[dir].ExportToVD(bin, ref indexPos, ref animPos);
}
}
}
+ private static AnimIdx ScaleForExport(AnimIdx anim, double scale)
+ {
+ if (anim == null || scale == 1.0)
+ {
+ return anim;
+ }
+
+ return anim.ScaledCopy(scale);
+ }
+
///
/// Reads a single-action .vd, positioned after its 4-byte header, into the given action.
/// Directions the file leaves empty are cleared. Nothing changes if the file can't be read.
///
public static void LoadActionFromVD(int fileType, int body, int action, BinaryReader bin)
{
- var entries = new Entry3D[5];
- for (int dir = 0; dir < 5; ++dir)
- {
- entries[dir].Lookup = bin.ReadInt32();
- entries[dir].Length = bin.ReadInt32();
- entries[dir].Extra = bin.ReadInt32();
- }
+ Entry3D[] entries = ReadVdEntries(bin, 5);
var loaded = new AnimIdx[5];
for (int dir = 0; dir < 5; ++dir)
{
Entry3D entry = entries[dir];
- if ((entry.Lookup > 0) && (entry.Lookup < bin.BaseStream.Length) && (entry.Length > 0))
+ if ((entry.Lookup > 0) && (entry.Length > 0))
{
bin.BaseStream.Seek(entry.Lookup, SeekOrigin.Begin);
loaded[dir] = new AnimIdx(bin, entry.Extra);
@@ -544,6 +658,11 @@ public sealed class AnimIdx
public ushort[] Palette { get; private set; }
public List Frames { get; private set; }
+ private AnimIdx()
+ {
+ Palette = new ushort[PaletteCapacity];
+ }
+
public AnimIdx(int index, FileIndex fileIndex)
{
Palette = new ushort[PaletteCapacity];
@@ -1037,6 +1156,111 @@ public void CopyFrom(AnimIdx source)
_idxExtra = source._idxExtra;
}
+ ///
+ /// Width or height of a frame resized by , at least 1.
+ ///
+ public static int ScaledLength(int length, double scale)
+ {
+ return Math.Max(1, (int)Math.Round(length * scale));
+ }
+
+ ///
+ /// Center of a frame pixels high once it is resized by
+ /// to . The point the center marks, left edge plus X and bottom edge plus Y,
+ /// moves with the scale, so the feet stay where they were.
+ ///
+ public static Point ScaleCenter(Point center, int height, int scaledHeight, double scale)
+ {
+ return new Point(
+ (int)Math.Round(center.X * scale),
+ (int)Math.Round((center.Y + height) * scale) - scaledHeight);
+ }
+
+ ///
+ /// A copy with every frame resized by . Pixels are picked by nearest
+ /// neighbour, so no colours outside the palette appear. Centers scale with the frame, measured
+ /// from the frame's bottom so the feet stay on the same point.
+ ///
+ public unsafe AnimIdx ScaledCopy(double scale)
+ {
+ if (!(scale > 0))
+ {
+ throw new ArgumentOutOfRangeException(nameof(scale), scale, "Scale must be greater than zero.");
+ }
+
+ var copy = new AnimIdx();
+ Array.Copy(Palette, copy.Palette, PaletteCapacity);
+ copy._idxExtra = _idxExtra;
+ if (Frames == null)
+ {
+ return copy;
+ }
+
+ copy.Frames = new List(Frames.Count);
+ Bitmap[] bits = GetFrames();
+ try
+ {
+ for (int i = 0; i < Frames.Count; ++i)
+ {
+ FrameEdit frame = Frames[i];
+ Bitmap source = bits?[i];
+ if (source == null)
+ {
+ copy.Frames.Add(new FrameEdit(frame));
+ continue;
+ }
+
+ int width = ScaledLength(source.Width, scale);
+ int height = ScaledLength(source.Height, scale);
+ Point center = ScaleCenter(frame.Center, source.Height, height, scale);
+ int centerX = center.X;
+ int centerY = center.Y;
+
+ using (var target = new Bitmap(width, height, PixelFormat.Format16bppArgb1555))
+ {
+ BitmapData sd = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555);
+ BitmapData td = target.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555);
+ try
+ {
+ var sp = (ushort*)sd.Scan0;
+ var tp = (ushort*)td.Scan0;
+ int sStride = sd.Stride >> 1;
+ int tStride = td.Stride >> 1;
+ for (int y = 0; y < height; ++y)
+ {
+ int sy = Math.Min(source.Height - 1, (int)(y / scale));
+ ushort* sRow = sp + (sy * sStride);
+ ushort* tRow = tp + (y * tStride);
+ for (int x = 0; x < width; ++x)
+ {
+ tRow[x] = sRow[Math.Min(source.Width - 1, (int)(x / scale))];
+ }
+ }
+ }
+ finally
+ {
+ target.UnlockBits(td);
+ source.UnlockBits(sd);
+ }
+
+ copy.Frames.Add(new FrameEdit(target, copy.Palette, centerX, centerY));
+ }
+ }
+ }
+ finally
+ {
+ if (bits != null)
+ {
+ foreach (Bitmap bit in bits)
+ {
+ bit?.Dispose();
+ }
+ }
+ }
+
+ return copy;
+ }
+
public void ExportPalette(string filename, int type)
{
switch (type)
diff --git a/Ultima/MobActionMap.cs b/Ultima/MobActionMap.cs
new file mode 100644
index 00000000..dc2598c7
--- /dev/null
+++ b/Ultima/MobActionMap.cs
@@ -0,0 +1,213 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+
+namespace Ultima
+{
+ ///
+ /// What an action shows, independent of the body type's action layout.
+ ///
+ public enum ActionRole
+ {
+ None,
+ Walk,
+ Run,
+ Idle,
+ Fidget,
+ Alert,
+ Eat,
+ LieDown,
+ CombatIdle,
+ CombatAdvance,
+ Attack1,
+ Attack2,
+ Attack3,
+ AttackBow,
+ AttackCrossbow,
+ AttackThrow,
+ Punch,
+ Pillage,
+ Stomp,
+ Cast1,
+ Cast2,
+ Block,
+ GetHit,
+ GetHitInAir,
+ Die1,
+ Die2,
+ Fly,
+ TakeOff,
+ MountWalk,
+ MountRun,
+ MountIdle,
+ MountAttack,
+ Emote
+ }
+
+ ///
+ /// Maps actions between the monster (22), sea monster (9), animal (13) and human (35) action layouts by
+ /// what each action shows, falling back to the closest action the other layout has (run to walk, a third
+ /// attack to the first, ...). Equipment uses the human layout.
+ ///
+ public static class MobActionMap
+ {
+ private static readonly ActionRole[] _monster =
+ {
+ ActionRole.Walk, ActionRole.Idle, ActionRole.Die1, ActionRole.Die2, ActionRole.Attack1, ActionRole.Attack2,
+ ActionRole.Attack3, ActionRole.AttackBow, ActionRole.AttackCrossbow, ActionRole.AttackThrow, ActionRole.GetHit,
+ ActionRole.Pillage, ActionRole.Stomp, ActionRole.Cast1, ActionRole.Cast2, ActionRole.Block, ActionRole.Block,
+ ActionRole.Idle, ActionRole.Fidget, ActionRole.Fly, ActionRole.TakeOff, ActionRole.GetHitInAir
+ };
+
+ private static readonly ActionRole[] _sea =
+ {
+ ActionRole.Walk, ActionRole.Run, ActionRole.Idle, ActionRole.Idle, ActionRole.Fidget, ActionRole.Attack1,
+ ActionRole.Attack2, ActionRole.GetHit, ActionRole.Die1
+ };
+
+ private static readonly ActionRole[] _animal =
+ {
+ ActionRole.Walk, ActionRole.Run, ActionRole.Idle, ActionRole.Eat, ActionRole.Alert, ActionRole.Attack1,
+ ActionRole.Attack2, ActionRole.GetHit, ActionRole.Die1, ActionRole.Idle, ActionRole.Fidget, ActionRole.LieDown,
+ ActionRole.Die2
+ };
+
+ private static readonly ActionRole[] _human =
+ {
+ ActionRole.Walk, ActionRole.Walk, ActionRole.Run, ActionRole.Run, ActionRole.Idle, ActionRole.Idle,
+ ActionRole.Fidget, ActionRole.CombatIdle, ActionRole.CombatIdle, ActionRole.Attack1, ActionRole.Attack2,
+ ActionRole.Attack3, ActionRole.Attack3, ActionRole.Attack1, ActionRole.Attack2, ActionRole.CombatAdvance,
+ ActionRole.Cast1, ActionRole.Cast2, ActionRole.AttackBow, ActionRole.AttackCrossbow, ActionRole.GetHit,
+ ActionRole.Die1, ActionRole.Die2, ActionRole.MountWalk, ActionRole.MountRun, ActionRole.MountIdle,
+ ActionRole.MountAttack, ActionRole.MountAttack, ActionRole.MountAttack, ActionRole.MountAttack, ActionRole.Block,
+ ActionRole.Punch, ActionRole.Emote, ActionRole.Emote, ActionRole.Eat
+ };
+
+ // Roles tried, in order, when a layout has no action with the role itself. A mount action falls back
+ // to what the mount does under the rider, so a rider's actions map onto the mount's.
+ private static readonly Dictionary _fallbacks = new()
+ {
+ [ActionRole.Run] = new[] { ActionRole.Walk },
+ [ActionRole.Fidget] = new[] { ActionRole.Idle },
+ [ActionRole.Alert] = new[] { ActionRole.Fidget, ActionRole.Idle },
+ [ActionRole.Eat] = new[] { ActionRole.Fidget, ActionRole.Idle },
+ [ActionRole.LieDown] = new[] { ActionRole.Idle },
+ [ActionRole.CombatIdle] = new[] { ActionRole.Idle },
+ [ActionRole.CombatAdvance] = new[] { ActionRole.Walk },
+ [ActionRole.Attack2] = new[] { ActionRole.Attack1 },
+ [ActionRole.Attack3] = new[] { ActionRole.Attack2, ActionRole.Attack1 },
+ [ActionRole.AttackBow] = new[] { ActionRole.AttackThrow, ActionRole.Attack1 },
+ [ActionRole.AttackCrossbow] = new[] { ActionRole.AttackBow, ActionRole.AttackThrow, ActionRole.Attack1 },
+ [ActionRole.AttackThrow] = new[] { ActionRole.AttackBow, ActionRole.Attack1 },
+ [ActionRole.Punch] = new[] { ActionRole.Attack1 },
+ [ActionRole.Pillage] = new[] { ActionRole.Attack1 },
+ [ActionRole.Stomp] = new[] { ActionRole.Attack2, ActionRole.Attack1 },
+ [ActionRole.Cast1] = new[] { ActionRole.Cast2, ActionRole.Attack1 },
+ [ActionRole.Cast2] = new[] { ActionRole.Cast1, ActionRole.Attack1 },
+ [ActionRole.Block] = new[] { ActionRole.GetHit },
+ [ActionRole.GetHitInAir] = new[] { ActionRole.GetHit },
+ [ActionRole.Die2] = new[] { ActionRole.Die1 },
+ [ActionRole.Fly] = new[] { ActionRole.Walk },
+ [ActionRole.TakeOff] = new[] { ActionRole.Fly, ActionRole.Walk },
+ [ActionRole.MountWalk] = new[] { ActionRole.Walk },
+ [ActionRole.MountRun] = new[] { ActionRole.Run, ActionRole.Walk },
+ [ActionRole.MountIdle] = new[] { ActionRole.Idle },
+ [ActionRole.MountAttack] = new[] { ActionRole.MountIdle, ActionRole.Idle },
+ [ActionRole.Emote] = new[] { ActionRole.Fidget, ActionRole.Idle },
+ };
+
+ ///
+ /// The action roles of a layout, indexed by action.
+ ///
+ public static IReadOnlyList GetRoles(MobType type)
+ {
+ return type switch
+ {
+ MobType.Monster => _monster,
+ MobType.Sea => _sea,
+ MobType.Animal => _animal,
+ _ => _human
+ };
+ }
+
+ public static ActionRole GetRole(MobType type, int action)
+ {
+ IReadOnlyList roles = GetRoles(type);
+ return action >= 0 && action < roles.Count ? roles[action] : ActionRole.None;
+ }
+
+ ///
+ /// The action of layout that best matches of layout
+ /// , or -1 when the target layout has nothing close. Within one layout an action
+ /// maps to itself.
+ ///
+ public static int MapAction(MobType from, int action, MobType to)
+ {
+ from = Normalize(from);
+ to = Normalize(to);
+ if (from == to)
+ {
+ return action >= 0 && action < GetRoles(to).Count ? action : -1;
+ }
+
+ return FindAction(to, GetRole(from, action));
+ }
+
+ ///
+ /// The first action of layout with or, failing that, with
+ /// the nearest fallback role; -1 when there is none.
+ ///
+ public static int FindAction(MobType type, ActionRole role)
+ {
+ if (role == ActionRole.None)
+ {
+ return -1;
+ }
+
+ IReadOnlyList roles = GetRoles(Normalize(type));
+ int found = IndexOf(roles, role);
+ if (found >= 0 || !_fallbacks.TryGetValue(role, out ActionRole[] fallbacks))
+ {
+ return found;
+ }
+
+ foreach (ActionRole fallback in fallbacks)
+ {
+ found = IndexOf(roles, fallback);
+ if (found >= 0)
+ {
+ return found;
+ }
+ }
+
+ return -1;
+ }
+
+ private static MobType Normalize(MobType type)
+ {
+ return type == MobType.Equipment ? MobType.Human : type;
+ }
+
+ private static int IndexOf(IReadOnlyList roles, ActionRole role)
+ {
+ for (int i = 0; i < roles.Count; ++i)
+ {
+ if (roles[i] == role)
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+ }
+}
diff --git a/UoFiddler.Controls/Classes/FramesXml.cs b/UoFiddler.Controls/Classes/FramesXml.cs
new file mode 100644
index 00000000..493d36c5
--- /dev/null
+++ b/UoFiddler.Controls/Classes/FramesXml.cs
@@ -0,0 +1,149 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Globalization;
+using System.IO;
+using System.Xml;
+using System.Xml.Linq;
+
+namespace UoFiddler.Controls.Classes
+{
+ ///
+ /// One frame listed in a frames XML file.
+ ///
+ public sealed class FramesXmlFrame
+ {
+ public int Direction { get; set; }
+ public int Index { get; set; }
+ public Point Center { get; set; }
+
+ /// Image file name, in the XML file's folder or its _frames folder.
+ public string File { get; set; }
+ }
+
+ ///
+ /// Animation frames saved as one PNG per frame plus an XML file listing each frame's direction, index and
+ /// center. The images go in a {name}_frames folder next to {name}.xml.
+ ///
+ public static class FramesXml
+ {
+ public static string GetFramesFolder(string xmlFile)
+ {
+ return Path.Combine(Path.GetDirectoryName(xmlFile) ?? string.Empty, Path.GetFileNameWithoutExtension(xmlFile) + "_frames");
+ }
+
+ ///
+ /// Saves each frame as {direction}_{index}.png in the frames folder and lists them in .
+ ///
+ public static void Write(string xmlFile, IReadOnlyList<(int Direction, int Index, Point Center, Bitmap Image)> frames)
+ {
+ string framesFolder = GetFramesFolder(xmlFile);
+ Directory.CreateDirectory(framesFolder);
+
+ var root = new XElement("Animation");
+ foreach (var (direction, index, center, image) in frames)
+ {
+ string fileName = $"{direction}_{index:D2}.png";
+ image.Save(Path.Combine(framesFolder, fileName), ImageFormat.Png);
+ root.Add(new XElement("Frame",
+ new XAttribute("dir", direction),
+ new XAttribute("index", index),
+ new XAttribute("centerX", center.X),
+ new XAttribute("centerY", center.Y),
+ new XAttribute("file", fileName)));
+ }
+
+ new XDocument(root).Save(xmlFile);
+ }
+
+ /// The file is not a frames XML file.
+ public static List Read(string xmlFile)
+ {
+ string name = Path.GetFileName(xmlFile);
+ XDocument document;
+ try
+ {
+ document = XDocument.Load(xmlFile);
+ }
+ catch (XmlException ex)
+ {
+ throw new InvalidDataException($"{name} is not a valid frames XML file: {ex.Message}", ex);
+ }
+
+ if (document.Root?.Name.LocalName != "Animation")
+ {
+ throw new InvalidDataException($"{name} is not a frames XML file: the root element is not .");
+ }
+
+ var frames = new List();
+ foreach (XElement element in document.Root.Elements("Frame"))
+ {
+ frames.Add(new FramesXmlFrame
+ {
+ Direction = ReadInt(element, "dir", name),
+ Index = ReadInt(element, "index", name),
+ Center = new Point(ReadInt(element, "centerX", name), ReadInt(element, "centerY", name)),
+ File = (string)element.Attribute("file") ?? throw new InvalidDataException($"{name}: a has no file attribute.")
+ });
+ }
+
+ return frames;
+ }
+
+ ///
+ /// Path of a frame's image, or null if it is in neither the XML file's folder nor the frames folder.
+ /// Only the file name is used, so an XML file can't point outside those folders.
+ ///
+ public static string FindImage(string xmlFile, FramesXmlFrame frame)
+ {
+ string fileName = Path.GetFileName(frame.File);
+ if (string.IsNullOrEmpty(fileName))
+ {
+ return null;
+ }
+
+ string beside = Path.Combine(Path.GetDirectoryName(xmlFile) ?? string.Empty, fileName);
+ if (System.IO.File.Exists(beside))
+ {
+ return beside;
+ }
+
+ string inFolder = Path.Combine(GetFramesFolder(xmlFile), fileName);
+ return System.IO.File.Exists(inFolder) ? inFolder : null;
+ }
+
+ ///
+ /// Loads an image as 32bpp ARGB without keeping the file locked.
+ ///
+ public static Bitmap LoadImage(string file)
+ {
+ using (var loaded = new Bitmap(file))
+ {
+ return loaded.Clone(new Rectangle(0, 0, loaded.Width, loaded.Height), PixelFormat.Format32bppArgb);
+ }
+ }
+
+ private static int ReadInt(XElement element, string attribute, string name)
+ {
+ string value = (string)element.Attribute(attribute);
+ if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result))
+ {
+ throw new InvalidDataException($"{name}: a has no valid {attribute} attribute.");
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/UoFiddler.Controls/Classes/SpriteSheetPacker.cs b/UoFiddler.Controls/Classes/SpriteSheetPacker.cs
index 4e8a2975..4dbf3e63 100644
--- a/UoFiddler.Controls/Classes/SpriteSheetPacker.cs
+++ b/UoFiddler.Controls/Classes/SpriteSheetPacker.cs
@@ -122,6 +122,40 @@ public static Bitmap Compose(int width, int height, IReadOnlyList images
return sheet;
}
+ ///
+ /// A 32bpp ARGB copy of resized by . Pixels are
+ /// picked by nearest neighbour, so no new colours appear.
+ ///
+ public static unsafe Bitmap ScaleNearest(Bitmap source, double scale)
+ {
+ int width = Ultima.AnimIdx.ScaledLength(source.Width, scale);
+ int height = Ultima.AnimIdx.ScaledLength(source.Height, scale);
+ var target = new Bitmap(width, height, PixelFormat.Format32bppArgb);
+
+ BitmapData src = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
+ BitmapData dst = target.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
+ try
+ {
+ for (int y = 0; y < height; ++y)
+ {
+ int sy = Math.Min(source.Height - 1, (int)(y / scale));
+ uint* srcLine = (uint*)((byte*)src.Scan0 + (sy * src.Stride));
+ uint* dstLine = (uint*)((byte*)dst.Scan0 + (y * dst.Stride));
+ for (int x = 0; x < width; ++x)
+ {
+ dstLine[x] = srcLine[Math.Min(source.Width - 1, (int)(x / scale))];
+ }
+ }
+ }
+ finally
+ {
+ source.UnlockBits(src);
+ target.UnlockBits(dst);
+ }
+
+ return target;
+ }
+
public static PackedMeta CreateMeta(string imageFile, Bitmap sheet)
{
return new PackedMeta
diff --git a/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs b/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs
index 153d748c..67059d36 100644
--- a/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs
+++ b/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs
@@ -31,7 +31,7 @@ private void InitializeComponent()
components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AnimationEditForm));
MainSplitContainer = new System.Windows.Forms.SplitContainer();
- AnimationListTreeView = new System.Windows.Forms.TreeView();
+ AnimationListTreeView = new UoFiddler.Controls.UserControls.VirtualTreeView();
ContextMenuStripTreeView = new System.Windows.Forms.ContextMenuStrip(components);
removeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
extractImagesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
@@ -43,6 +43,9 @@ private void InitializeComponent()
fromvdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
actionFromVdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
actionToVdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ tovdScaledToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ tovdRemappedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ actionToVdScaledToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
copyActionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
exportToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
tovdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@@ -103,6 +106,7 @@ private void InitializeComponent()
ZoomLabel = new System.Windows.Forms.ToolStripLabel();
ZoomComboBox = new System.Windows.Forms.ToolStripComboBox();
zoomToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
+ FrameSizeToolStripLabel = new System.Windows.Forms.ToolStripLabel();
toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
DrawFullRectangleToolStripButton = new System.Windows.Forms.ToolStripButton();
toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
@@ -135,6 +139,9 @@ private void InitializeComponent()
SameCenterButton = new System.Windows.Forms.Button();
CenterXNumericUpDown = new System.Windows.Forms.NumericUpDown();
CenterYNumericUpDown = new System.Windows.Forms.NumericUpDown();
+ RelativeCenterCheckBox = new System.Windows.Forms.CheckBox();
+ CenterAllDirectionsCheckBox = new System.Windows.Forms.CheckBox();
+ CenterAllActionsCheckBox = new System.Windows.Forms.CheckBox();
ReferencialPointGroupBox = new System.Windows.Forms.GroupBox();
ToolStripLockButton = new System.Windows.Forms.CheckBox();
RefYLabel = new System.Windows.Forms.Label();
@@ -240,6 +247,7 @@ private void InitializeComponent()
AnimationListTreeView.Name = "AnimationListTreeView";
AnimationListTreeView.Size = new System.Drawing.Size(232, 796);
AnimationListTreeView.TabIndex = 0;
+ AnimationListTreeView.BeforeExpand += OnBeforeExpandBody;
AnimationListTreeView.AfterSelect += AfterSelectTreeView;
//
// ContextMenuStripTreeView
@@ -328,7 +336,7 @@ private void InitializeComponent()
//
// exportToolStripMenuItem1
//
- exportToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { tovdToolStripMenuItem, actionToVdToolStripMenuItem });
+ exportToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { tovdToolStripMenuItem, actionToVdToolStripMenuItem, tovdScaledToolStripMenuItem, actionToVdScaledToolStripMenuItem, tovdRemappedToolStripMenuItem });
exportToolStripMenuItem1.Name = "exportToolStripMenuItem1";
exportToolStripMenuItem1.Size = new System.Drawing.Size(157, 22);
exportToolStripMenuItem1.Text = "Export..";
@@ -347,6 +355,30 @@ private void InitializeComponent()
actionToVdToolStripMenuItem.Text = "Action to .vd";
actionToVdToolStripMenuItem.ToolTipText = "Export the selected action, all directions, as a single-action .vd";
actionToVdToolStripMenuItem.Click += OnClickExportActionToVD;
+ //
+ // tovdScaledToolStripMenuItem
+ //
+ tovdScaledToolStripMenuItem.Name = "tovdScaledToolStripMenuItem";
+ tovdScaledToolStripMenuItem.Size = new System.Drawing.Size(200, 22);
+ tovdScaledToolStripMenuItem.Text = "Body to .vd, scaled...";
+ tovdScaledToolStripMenuItem.ToolTipText = "Export the body as a .vd with every frame and center resized";
+ tovdScaledToolStripMenuItem.Click += OnClickExportScaledToVD;
+ //
+ // tovdRemappedToolStripMenuItem
+ //
+ tovdRemappedToolStripMenuItem.Name = "tovdRemappedToolStripMenuItem";
+ tovdRemappedToolStripMenuItem.Size = new System.Drawing.Size(200, 22);
+ tovdRemappedToolStripMenuItem.Text = "Body to .vd, remapped...";
+ tovdRemappedToolStripMenuItem.ToolTipText = "Export the body as a .vd of another body type, choosing which action goes in each slot";
+ tovdRemappedToolStripMenuItem.Click += OnClickExportRemappedToVD;
+ //
+ // actionToVdScaledToolStripMenuItem
+ //
+ actionToVdScaledToolStripMenuItem.Name = "actionToVdScaledToolStripMenuItem";
+ actionToVdScaledToolStripMenuItem.Size = new System.Drawing.Size(200, 22);
+ actionToVdScaledToolStripMenuItem.Text = "Action to .vd, scaled...";
+ actionToVdScaledToolStripMenuItem.ToolTipText = "Export the selected action as a single-action .vd with every frame and center resized";
+ actionToVdScaledToolStripMenuItem.Click += OnClickExportActionScaledToVD;
//
// AnimationFileToolStrip
//
@@ -926,7 +958,7 @@ private void InitializeComponent()
AnimationEditToolStrip.Dock = System.Windows.Forms.DockStyle.Bottom;
AnimationEditToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
AnimationEditToolStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
- AnimationEditToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { ZoomLabel, ZoomComboBox, zoomToolStripSeparator, toolStripSeparator7, DrawFullRectangleToolStripButton, toolStripSeparator5, DrawEmptyRectangleToolStripButton, toolStripSeparator6, DrawReferencialPointToolStripButton, toolStripSeparator10 });
+ AnimationEditToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { ZoomLabel, ZoomComboBox, zoomToolStripSeparator, FrameSizeToolStripLabel, toolStripSeparator7, DrawFullRectangleToolStripButton, toolStripSeparator5, DrawEmptyRectangleToolStripButton, toolStripSeparator6, DrawReferencialPointToolStripButton, toolStripSeparator10 });
AnimationEditToolStrip.Location = new System.Drawing.Point(0, 702);
AnimationEditToolStrip.Name = "AnimationEditToolStrip";
AnimationEditToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
@@ -952,6 +984,12 @@ private void InitializeComponent()
//
zoomToolStripSeparator.Name = "zoomToolStripSeparator";
zoomToolStripSeparator.Size = new System.Drawing.Size(6, 27);
+ //
+ // FrameSizeToolStripLabel
+ //
+ FrameSizeToolStripLabel.Name = "FrameSizeToolStripLabel";
+ FrameSizeToolStripLabel.Size = new System.Drawing.Size(0, 24);
+ FrameSizeToolStripLabel.ToolTipText = "Frame size in pixels, shown while a frame rectangle is drawn";
//
// toolStripSeparator7
//
@@ -1247,12 +1285,15 @@ private void InitializeComponent()
LocationCenterGroupBox.Controls.Add(SameCenterButton);
LocationCenterGroupBox.Controls.Add(CenterXNumericUpDown);
LocationCenterGroupBox.Controls.Add(CenterYNumericUpDown);
+ LocationCenterGroupBox.Controls.Add(RelativeCenterCheckBox);
+ LocationCenterGroupBox.Controls.Add(CenterAllDirectionsCheckBox);
+ LocationCenterGroupBox.Controls.Add(CenterAllActionsCheckBox);
LocationCenterGroupBox.Dock = System.Windows.Forms.DockStyle.Top;
LocationCenterGroupBox.Location = new System.Drawing.Point(0, 221);
LocationCenterGroupBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
LocationCenterGroupBox.Name = "LocationCenterGroupBox";
LocationCenterGroupBox.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3);
- LocationCenterGroupBox.Size = new System.Drawing.Size(190, 89);
+ LocationCenterGroupBox.Size = new System.Drawing.Size(190, 158);
LocationCenterGroupBox.TabIndex = 21;
LocationCenterGroupBox.TabStop = false;
LocationCenterGroupBox.Text = "Location Center";
@@ -1315,7 +1356,38 @@ private void InitializeComponent()
CenterYNumericUpDown.TabIndex = 4;
CenterYNumericUpDown.ValueChanged += OnCenterYValueChanged;
CenterYNumericUpDown.KeyDown += TxtSendData_KeyDown;
- //
+ //
+ // RelativeCenterCheckBox
+ //
+ RelativeCenterCheckBox.AutoSize = true;
+ RelativeCenterCheckBox.Location = new System.Drawing.Point(9, 84);
+ RelativeCenterCheckBox.Name = "RelativeCenterCheckBox";
+ RelativeCenterCheckBox.Size = new System.Drawing.Size(68, 19);
+ RelativeCenterCheckBox.TabIndex = 19;
+ RelativeCenterCheckBox.Text = "Relative";
+ RelativeCenterCheckBox.UseVisualStyleBackColor = true;
+ RelativeCenterCheckBox.CheckedChanged += RelativeCenterCheckBox_CheckedChanged;
+ //
+ // CenterAllDirectionsCheckBox
+ //
+ CenterAllDirectionsCheckBox.AutoSize = true;
+ CenterAllDirectionsCheckBox.Location = new System.Drawing.Point(9, 107);
+ CenterAllDirectionsCheckBox.Name = "CenterAllDirectionsCheckBox";
+ CenterAllDirectionsCheckBox.Size = new System.Drawing.Size(97, 19);
+ CenterAllDirectionsCheckBox.TabIndex = 20;
+ CenterAllDirectionsCheckBox.Text = "All directions";
+ CenterAllDirectionsCheckBox.UseVisualStyleBackColor = true;
+ //
+ // CenterAllActionsCheckBox
+ //
+ CenterAllActionsCheckBox.AutoSize = true;
+ CenterAllActionsCheckBox.Location = new System.Drawing.Point(9, 130);
+ CenterAllActionsCheckBox.Name = "CenterAllActionsCheckBox";
+ CenterAllActionsCheckBox.Size = new System.Drawing.Size(83, 19);
+ CenterAllActionsCheckBox.TabIndex = 21;
+ CenterAllActionsCheckBox.Text = "All actions";
+ CenterAllActionsCheckBox.UseVisualStyleBackColor = true;
+ //
// ReferencialPointGroupBox
//
ReferencialPointGroupBox.Controls.Add(ToolStripLockButton);
@@ -1702,6 +1774,9 @@ private void InitializeComponent()
private System.Windows.Forms.ToolStripMenuItem fromvdToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem actionFromVdToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem actionToVdToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem tovdScaledToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem tovdRemappedToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem actionToVdScaledToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyActionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem1;
@@ -1741,7 +1816,7 @@ private void InitializeComponent()
private System.Windows.Forms.ToolStripComboBox SelectFileToolStripComboBox;
private System.Windows.Forms.ToolStripMenuItem tovdToolStripMenuItem;
private System.Windows.Forms.TrackBar DirectionTrackBar;
- private System.Windows.Forms.TreeView AnimationListTreeView;
+ private UoFiddler.Controls.UserControls.VirtualTreeView AnimationListTreeView;
private System.Windows.Forms.StatusStrip StatusStrip;
private System.Windows.Forms.ToolStripDropDownButton MiscToolStripButton;
private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem;
@@ -1773,6 +1848,9 @@ private void InitializeComponent()
private System.Windows.Forms.Button SameCenterButton;
private System.Windows.Forms.NumericUpDown CenterXNumericUpDown;
private System.Windows.Forms.NumericUpDown CenterYNumericUpDown;
+ private System.Windows.Forms.CheckBox RelativeCenterCheckBox;
+ private System.Windows.Forms.CheckBox CenterAllDirectionsCheckBox;
+ private System.Windows.Forms.CheckBox CenterAllActionsCheckBox;
private System.Windows.Forms.ToolStrip AnimationEditToolStrip;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton DrawFullRectangleToolStripButton;
@@ -1796,6 +1874,7 @@ private void InitializeComponent()
private System.Windows.Forms.ToolStripLabel ZoomLabel;
private System.Windows.Forms.ToolStripComboBox ZoomComboBox;
private System.Windows.Forms.ToolStripSeparator zoomToolStripSeparator;
+ private System.Windows.Forms.ToolStripLabel FrameSizeToolStripLabel;
private System.Windows.Forms.GroupBox SecondAnimGroupBox;
private System.Windows.Forms.CheckBox SecondAnimCheckBox;
private System.Windows.Forms.ComboBox SecondAnimFileComboBox;
diff --git a/UoFiddler.Controls/Forms/AnimationEditForm.cs b/UoFiddler.Controls/Forms/AnimationEditForm.cs
index 8b90b5b8..74104407 100644
--- a/UoFiddler.Controls/Forms/AnimationEditForm.cs
+++ b/UoFiddler.Controls/Forms/AnimationEditForm.cs
@@ -19,6 +19,7 @@
using System.Windows.Forms;
using Ultima;
using UoFiddler.Controls.Classes;
+using UoFiddler.Controls.UserControls;
namespace UoFiddler.Controls.Forms
{
@@ -36,9 +37,16 @@ public partial class AnimationEditForm : Form
private static bool _drawEmpty;
private static bool _drawFull;
private static int _lastAddFilterIndex = 1;
+ private static int _lastExportScale = 100;
private float _zoomFactor = 1.0f;
+ // Center editing: set while the center boxes are filled from code, and the
+ // box values last applied in relative mode.
+ private bool _updatingCenterUi;
+ private int _lastRelativeX;
+ private int _lastRelativeY;
+
// Second-animation overlay state
private bool _secondAnimActivated;
private int _secondAnimId;
@@ -334,52 +342,29 @@ private void OnLoad(object sender, EventArgs e)
if (_fileType != 0)
{
int count = Animations.GetAnimCount(_fileType);
- TreeNode[] nodes = new TreeNode[count];
+ VirtualTreeNode[] nodes = new VirtualTreeNode[count];
for (int i = 0; i < count; ++i)
{
MobType mobType = Animations.GetBodyMobType(i, _fileType);
int animLength = Animations.GetAnimLength(i, _fileType);
- string[] names = ResolveActionNames(mobType);
- // mobtypes.txt is keyed by server body id; reverse-map for anim2..6.
- int serverBody = _fileType == 1 ? i : BodyConverter.GetTrueBody(_fileType, i);
- uint mobFlags = MobTypes.IsLoaded && serverBody >= 0 ? MobTypes.GetFlags(serverBody) : 0u;
char typeTag = _typeTag[(int)mobType];
- TreeNode node = new TreeNode
+ VirtualTreeNode node = new VirtualTreeNode
{
Tag = i,
Text = $"{typeTag}: {i} ({BodyConverter.GetTrueBody(_fileType, i)})"
};
bool valid = false;
- for (int j = 0; j < animLength; ++j)
+ for (int j = 0; j < animLength && !valid; ++j)
{
- string name = j < names.Length ? names[j] : $"Action{j}";
- TreeNode treeNode = new TreeNode
- {
- Tag = j,
- Text = string.Format("{0:D2} {1}", j, name)
- };
-
- if (AnimationEdit.IsActionDefined(_fileType, i, j))
- {
- valid = true;
- }
- else
- {
- treeNode.ForeColor = _invalidColor;
- }
-
- if (MobTypes.IsLoaded && treeNode.ForeColor != _invalidColor)
- {
- string missing = GetMissingActionFlag(mobType, mobFlags, j);
- if (missing != null)
- {
- treeNode.ForeColor = Color.Gray;
- treeNode.ToolTipText = BuildDimmedTooltip(missing, mobFlags);
- }
- }
+ valid = AnimationEdit.IsActionDefined(_fileType, i, j);
+ }
- node.Nodes.Add(treeNode);
+ // Action nodes are made when the body is first expanded: a native tree item costs
+ // a fraction of a millisecond to create and to destroy, and every body has 13-35 actions.
+ if (animLength > 0)
+ {
+ node.Nodes.Add(new VirtualTreeNode { Tag = _actionsPlaceholder });
}
if (!valid)
@@ -442,10 +427,105 @@ private void OnFilePathChangeEvent()
OnLoad(null);
}
- private TreeNode GetNode(int tag)
+ // Tag of the single child a body node holds until its action nodes are made.
+ private static readonly object _actionsPlaceholder = new object();
+
+ private static bool HasActionNodes(VirtualTreeNode body)
+ {
+ return body.Nodes.Count > 0 && body.Nodes[0].Tag != _actionsPlaceholder;
+ }
+
+ private void OnBeforeExpandBody(object sender, VirtualTreeNodeEventArgs e)
+ {
+ if (e.Node.Parent == null)
+ {
+ EnsureActionNodes(e.Node);
+ }
+ }
+
+ ///
+ /// Replaces a body node's placeholder with its action nodes.
+ ///
+ private void EnsureActionNodes(VirtualTreeNode body)
+ {
+ if (body.Nodes.Count == 0 || HasActionNodes(body))
+ {
+ return;
+ }
+
+ int bodyId = (int)body.Tag;
+ int animLength = Animations.GetAnimLength(bodyId, _fileType);
+ string[] names = ResolveActionNames(Animations.GetBodyMobType(bodyId, _fileType));
+ var actions = new VirtualTreeNode[animLength];
+ for (int j = 0; j < animLength; ++j)
+ {
+ string name = j < names.Length ? names[j] : $"Action{j}";
+ actions[j] = new VirtualTreeNode
+ {
+ Tag = j,
+ Text = string.Format("{0:D2} {1}", j, name)
+ };
+ StyleActionNode(actions[j], bodyId, j);
+ }
+
+ AnimationListTreeView.BeginUpdate();
+ try
+ {
+ body.Nodes.Clear();
+ body.Nodes.AddRange(actions);
+ }
+ finally
+ {
+ AnimationListTreeView.EndUpdate();
+ }
+ }
+
+ ///
+ /// Colours an action node: invalid when it has no frames, grey with a tooltip when mobtypes.txt
+ /// says the body lacks the action.
+ ///
+ private void StyleActionNode(VirtualTreeNode actionNode, int body, int action)
+ {
+ actionNode.ToolTipText = string.Empty;
+ if (!AnimationEdit.IsActionDefined(_fileType, body, action))
+ {
+ actionNode.ForeColor = _invalidColor;
+ return;
+ }
+
+ actionNode.ForeColor = Color.Empty;
+ if (!MobTypes.IsLoaded)
+ {
+ return;
+ }
+
+ // mobtypes.txt is keyed by server body id; reverse-map for anim2..6.
+ int serverBody = _fileType == 1 ? body : BodyConverter.GetTrueBody(_fileType, body);
+ uint mobFlags = serverBody >= 0 ? MobTypes.GetFlags(serverBody) : 0u;
+ string missing = GetMissingActionFlag(Animations.GetBodyMobType(body, _fileType), mobFlags, action);
+ if (missing != null)
+ {
+ actionNode.ForeColor = Color.Gray;
+ actionNode.ToolTipText = BuildDimmedTooltip(missing, mobFlags);
+ }
+ }
+
+ ///
+ /// Recolours one action node of from the animation data. A body whose actions
+ /// were never expanded has nothing to recolour; its nodes get the current state when they are made.
+ ///
+ private void RefreshActionNode(VirtualTreeNode body, int action)
+ {
+ if (HasActionNodes(body) && action >= 0 && action < body.Nodes.Count)
+ {
+ StyleActionNode(body.Nodes[action], (int)body.Tag, action);
+ }
+ }
+
+ private VirtualTreeNode GetNode(int tag)
{
return _showOnlyValid
- ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(node => (int)node.Tag == tag)
+ ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(node => (int)node.Tag == tag)
: AnimationListTreeView.Nodes[tag];
}
@@ -569,7 +649,7 @@ private void GalleryTileViewMouseDoubleClick(object sender, MouseEventArgs e)
}
int body = _galleryBodies[idx];
- TreeNode target = GetNode(body);
+ VirtualTreeNode target = GetNode(body);
if (target == null)
{
return;
@@ -580,7 +660,7 @@ private void GalleryTileViewMouseDoubleClick(object sender, MouseEventArgs e)
AnimationListTreeView.Focus();
}
- private void AfterSelectTreeView(object sender, TreeViewEventArgs e)
+ private void AfterSelectTreeView(object sender, VirtualTreeNodeEventArgs e)
{
if (AnimationListTreeView.SelectedNode == null)
{
@@ -647,8 +727,7 @@ private void AfterSelectTreeView(object sender, TreeViewEventArgs e)
FramesTrackBar.Value = 0;
FramesTrackBar.Invalidate();
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
}
//Soulblighter Modification
else
@@ -742,7 +821,16 @@ private void AnimationPictureBox_OnPaintFrame(object sender, PaintEventArgs e)
AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir);
Bitmap[] currentBits = edit?.GetFrames();
- if (edit != null && currentBits?.Length > 0 && FramesTrackBar.Value < currentBits.Length && currentBits[FramesTrackBar.Value] != null)
+ bool hasFrame = edit != null && currentBits?.Length > 0 && FramesTrackBar.Value < currentBits.Length && currentBits[FramesTrackBar.Value] != null;
+ string frameSize = hasFrame && (_drawEmpty || _drawFull)
+ ? $"{currentBits[FramesTrackBar.Value].Width}x{currentBits[FramesTrackBar.Value].Height}"
+ : string.Empty;
+ if (FrameSizeToolStripLabel.Text != frameSize)
+ {
+ FrameSizeToolStripLabel.Text = frameSize;
+ }
+
+ if (hasFrame)
{
int varW;
int varH;
@@ -840,6 +928,17 @@ private Color GetSecondAnimTintColor()
}
}
+ ///
+ /// The overlay body's action matching the primary body's current action, or -1 if it has none.
+ ///
+ private int GetSecondAnimAction()
+ {
+ MobType primary = Animations.GetBodyMobType(_currentBody, _fileType);
+ MobType overlay = Animations.GetBodyMobType(_secondAnimId, _secondAnimFileIndex);
+ int action = MobActionMap.MapAction(primary, _currentAction, overlay);
+ return action >= 0 && AnimationEdit.IsActionInRange(_secondAnimFileIndex, _secondAnimId, action) ? action : -1;
+ }
+
private void DrawSecondAnimation(Graphics graphics)
{
if (!_secondAnimActivated || _secondAnimFileIndex < 1 || _secondAnimFileIndex > 5)
@@ -847,9 +946,16 @@ private void DrawSecondAnimation(Graphics graphics)
return;
}
- // Action and direction follow the primary selection — equipment shares the human
- // action set, so no action remapping is needed for the matching use case.
- AnimIdx edit = AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, _currentAction, _currentDir);
+ // The direction follows the primary selection. The action does too when both bodies share an
+ // action layout (equipment uses the human one); otherwise the overlay plays its closest action,
+ // so a mount under a rider walks, runs and stands with the rider's horse actions.
+ int action = GetSecondAnimAction();
+ if (action < 0)
+ {
+ return;
+ }
+
+ AnimIdx edit = AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, action, _currentDir);
Bitmap[] frames = edit?.GetFrames();
if (frames == null || frames.Length == 0)
{
@@ -938,7 +1044,8 @@ private void UpdateSecondAnimWarning()
int primaryCount = FramesTrackBar.Maximum + 1;
int overlayCount = 0;
- AnimIdx overlay = AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, _currentAction, _currentDir);
+ int action = GetSecondAnimAction();
+ AnimIdx overlay = action < 0 ? null : AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, action, _currentDir);
Bitmap[] frames = overlay?.GetFrames();
if (frames != null)
{
@@ -1043,92 +1150,206 @@ private void OnFrameCountBarChanged(object sender, EventArgs e)
return;
}
+ ShowFrameCenter(GetCurrentFrame());
+
+ AnimationPictureBox.Invalidate();
+ }
+ //End of Soulblighter Modification
+
+ private FrameEdit GetCurrentFrame()
+ {
+ if (_fileType == 0)
+ {
+ return null;
+ }
+
AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir);
- if (edit != null && edit.Frames.Count > FramesTrackBar.Value)
+ if (edit?.Frames == null || FramesTrackBar.Value >= edit.Frames.Count)
{
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ return null;
}
- AnimationPictureBox.Invalidate();
+ return edit.Frames[FramesTrackBar.Value];
}
- //End of Soulblighter Modification
- private void OnCenterXValueChanged(object sender, EventArgs e)
+ ///
+ /// Shows the frame's center in the center boxes. In relative mode the boxes hold the
+ /// offset applied so far, so they are left alone.
+ ///
+ private void ShowFrameCenter(FrameEdit frame)
+ {
+ if (frame == null || RelativeCenterCheckBox.Checked)
+ {
+ return;
+ }
+
+ SetCenterBoxes(frame.Center.X, frame.Center.Y);
+ }
+
+ private void SetCenterBoxes(int x, int y)
{
+ _updatingCenterUi = true;
try
{
- if (_fileType == 0)
+ CenterXNumericUpDown.Value = x;
+ CenterYNumericUpDown.Value = y;
+ }
+ finally
+ {
+ _updatingCenterUi = false;
+ }
+ }
+
+ private void OnCenterXValueChanged(object sender, EventArgs e)
+ {
+ OnCenterValueChanged(true);
+ }
+
+ private void OnCenterYValueChanged(object sender, EventArgs e)
+ {
+ OnCenterValueChanged(false);
+ }
+
+ private void OnCenterValueChanged(bool xAxis)
+ {
+ if (_updatingCenterUi || _fileType == 0)
+ {
+ return;
+ }
+
+ int value = (int)(xAxis ? CenterXNumericUpDown.Value : CenterYNumericUpDown.Value);
+
+ if (RelativeCenterCheckBox.Checked)
+ {
+ int delta = value - (xAxis ? _lastRelativeX : _lastRelativeY);
+ if (delta == 0)
{
return;
}
- AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir);
- if (edit == null || edit.Frames.Count < FramesTrackBar.Value)
+ bool moved = ApplyCenterChange(center => xAxis
+ ? new Point(center.X + delta, center.Y)
+ : new Point(center.X, center.Y + delta));
+
+ if (!moved)
{
- return;
+ SetCenterBoxes(_lastRelativeX, _lastRelativeY);
}
-
- FrameEdit frame = edit.Frames[FramesTrackBar.Value];
- if (CenterXNumericUpDown.Value == frame.Center.X)
+ else if (xAxis)
{
- return;
+ _lastRelativeX = value;
}
-
- if (!frame.CanCenterAt((int)CenterXNumericUpDown.Value, frame.Center.Y))
+ else
{
- ShowCenterOutOfRange((int)CenterXNumericUpDown.Value, frame.Center.Y);
- CenterXNumericUpDown.Value = frame.Center.X;
- return;
+ _lastRelativeY = value;
}
- frame.ChangeCenter((int)CenterXNumericUpDown.Value, frame.Center.Y);
- Options.ChangedUltimaClass["Animations"] = true;
- AnimationPictureBox.Invalidate();
+ return;
}
- catch (NullReferenceException)
+
+ bool changed = ApplyCenterChange(center => xAxis
+ ? new Point(value, center.Y)
+ : new Point(center.X, value));
+
+ if (!changed)
{
- // TODO: add logging or fix?
- // ignored
+ ShowFrameCenter(GetCurrentFrame());
}
}
- private void OnCenterYValueChanged(object sender, EventArgs e)
+ ///
+ /// Moves the center of every frame in the chosen scope: the current frame, all frames of
+ /// the action in all directions, or all frames of every action. Nothing changes if any
+ /// frame can't take its new center.
+ ///
+ private bool ApplyCenterChange(Func move)
{
- try
+ var changes = new List<(FrameEdit Frame, Point Center)>();
+ foreach (FrameEdit frame in GetCenterTargets())
{
- if (_fileType == 0)
+ Point center = move(frame.Center);
+ if (center == frame.Center)
{
- return;
+ continue;
}
- AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir);
- if (edit == null || edit.Frames.Count < FramesTrackBar.Value)
+ if (!frame.CanCenterAt(center.X, center.Y))
{
- return;
+ ShowCenterOutOfRange(center.X, center.Y);
+ return false;
}
- FrameEdit frame = edit.Frames[FramesTrackBar.Value];
- if (CenterYNumericUpDown.Value == frame.Center.Y)
+ changes.Add((frame, center));
+ }
+
+ foreach ((FrameEdit frame, Point center) in changes)
+ {
+ frame.ChangeCenter(center.X, center.Y);
+ }
+
+ if (changes.Count > 0)
+ {
+ Options.ChangedUltimaClass["Animations"] = true;
+ }
+
+ AnimationPictureBox.Invalidate();
+ return true;
+ }
+
+ private IEnumerable GetCenterTargets()
+ {
+ bool allActions = CenterAllActionsCheckBox.Checked;
+ if (!allActions && !CenterAllDirectionsCheckBox.Checked)
+ {
+ FrameEdit current = GetCurrentFrame();
+ if (current != null)
{
- return;
+ yield return current;
}
- if (!frame.CanCenterAt(frame.Center.X, (int)CenterYNumericUpDown.Value))
+ yield break;
+ }
+
+ int firstAction = allActions ? 0 : _currentAction;
+ int lastAction = allActions ? Animations.GetAnimLength(_currentBody, _fileType) - 1 : _currentAction;
+ for (int action = firstAction; action <= lastAction; ++action)
+ {
+ if (!AnimationEdit.IsActionInRange(_fileType, _currentBody, action))
{
- ShowCenterOutOfRange(frame.Center.X, (int)CenterYNumericUpDown.Value);
- CenterYNumericUpDown.Value = frame.Center.Y;
- return;
+ continue;
}
- frame.ChangeCenter(frame.Center.X, (int)CenterYNumericUpDown.Value);
- Options.ChangedUltimaClass["Animations"] = true;
- AnimationPictureBox.Invalidate();
+ for (int dir = 0; dir < 5; ++dir)
+ {
+ AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, action, dir);
+ if (edit?.Frames == null)
+ {
+ continue;
+ }
+
+ foreach (FrameEdit frame in edit.Frames)
+ {
+ yield return frame;
+ }
+ }
}
- catch (NullReferenceException)
+ }
+
+ private void RelativeCenterCheckBox_CheckedChanged(object sender, EventArgs e)
+ {
+ _lastRelativeX = 0;
+ _lastRelativeY = 0;
+
+ // Same Center reads absolute values from the boxes, which hold an offset in relative mode.
+ SameCenterButton.Enabled = !RelativeCenterCheckBox.Checked && !AnimationTimer.Enabled;
+
+ if (RelativeCenterCheckBox.Checked)
{
- // TODO: add logging or fix?
- // ignored
+ SetCenterBoxes(0, 0);
+ }
+ else
+ {
+ ShowFrameCenter(GetCurrentFrame());
}
}
@@ -1272,15 +1493,18 @@ private void OnClickRemoveAction(object sender, EventArgs e)
return;
}
- AnimationListTreeView.SelectedNode.ForeColor = _invalidColor;
- for (int i = 0; i < AnimationListTreeView.SelectedNode.Nodes.Count; ++i)
+ VirtualTreeNode bodyNode = AnimationListTreeView.SelectedNode;
+ bodyNode.ForeColor = _invalidColor;
+ int actionCount = Animations.GetAnimLength(_currentBody, _fileType);
+ for (int i = 0; i < actionCount; ++i)
{
- AnimationListTreeView.SelectedNode.Nodes[i].ForeColor = _invalidColor;
for (int d = 0; d < 5; ++d)
{
AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, i, d);
edit?.ClearFrames();
}
+
+ RefreshActionNode(bodyNode, i);
}
if (_showOnlyValid)
@@ -1306,9 +1530,9 @@ private void OnClickRemoveAction(object sender, EventArgs e)
edit?.ClearFrames();
}
- AnimationListTreeView.SelectedNode.Parent.Nodes[_currentAction].ForeColor = _invalidColor;
+ RefreshActionNode(AnimationListTreeView.SelectedNode.Parent, _currentAction);
bool valid = false;
- foreach (TreeNode node in AnimationListTreeView.SelectedNode.Parent.Nodes)
+ foreach (VirtualTreeNode node in AnimationListTreeView.SelectedNode.Parent.Nodes)
{
if (node.ForeColor == _invalidColor)
{
@@ -1490,8 +1714,7 @@ private void OnClickAdd(object sender, EventArgs e)
SetPaletteBox();
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
Options.ChangedUltimaClass["Animations"] = true;
}
@@ -1500,11 +1723,11 @@ private void OnClickAdd(object sender, EventArgs e)
{
edit.AddFrame(bitmap);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -1530,8 +1753,7 @@ private void OnClickAdd(object sender, EventArgs e)
FramesListView.TileSize = new Size(width + 5, height + 5);
FramesTrackBar.Maximum = i;
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
Options.ChangedUltimaClass["Animations"] = true;
}
@@ -1568,11 +1790,11 @@ private void AddImageAtCertainIndex(int frameCount, Bitmap[] bitBmp, Bitmap bmp,
for (int index = 0; index < frameCount; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width / 2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -1724,17 +1946,15 @@ private void OnClickImportFromVD(object sender, EventArgs e)
int animLength = Animations.GetAnimLength(_currentBody, _fileType);
// .vd file format: animType 0 = 22-action (monster), 1 = 13-action (animal),
- // 2 = 35-action (human). Other lengths can't be represented; reject.
- int currentType;
- switch (animLength)
- {
- case 22: currentType = 0; break;
- case 13: currentType = 1; break;
- case 35: currentType = 2; break;
- default:
- MessageBox.Show($"Body action length {animLength} cannot be imported as .vd palette.",
- "Import", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
- return;
+ // 2 = 35-action (human). Bodies with another count (9-action sea monsters)
+ // use their whole idx block, as the export writes them.
+ int vdActionCount = AnimationEdit.GetVdActionCount(_currentBody, _fileType);
+ int currentType = AnimationEdit.GetVdType(vdActionCount);
+ if (currentType < 0)
+ {
+ MessageBox.Show($"A body with {vdActionCount} actions can't be imported from a .vd.",
+ "Import", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
+ return;
}
using (FileStream fs = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
@@ -1763,25 +1983,28 @@ private void OnClickImportFromVD(object sender, EventArgs e)
MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
return;
}
- AnimationEdit.LoadFromVD(_fileType, _currentBody, bin);
+
+ try
+ {
+ AnimationEdit.LoadFromVD(_fileType, _currentBody, bin);
+ }
+ catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is ArgumentException || ex is OverflowException)
+ {
+ MessageBox.Show($"Could not read {Path.GetFileName(dialog.FileName)}: {ex.Message}", "Import",
+ MessageBoxButtons.OK, MessageBoxIcon.Warning);
+ return;
+ }
}
}
bool valid = false;
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
for (int j = 0; j < animLength; ++j)
{
- if (AnimationEdit.IsActionDefined(_fileType, _currentBody, j))
- {
- node.Nodes[j].ForeColor = Color.Empty;
- valid = true;
- }
- else
- {
- node.Nodes[j].ForeColor = _invalidColor;
- }
+ valid |= AnimationEdit.IsActionDefined(_fileType, _currentBody, j);
+ RefreshActionNode(node, j);
}
node.ForeColor = valid ? Color.Empty : _invalidColor;
}
@@ -1795,15 +2018,61 @@ private void OnClickImportFromVD(object sender, EventArgs e)
}
private void OnClickExportToVD(object sender, EventArgs e)
+ {
+ ExportBodyToVD(100);
+ }
+
+ private void OnClickExportScaledToVD(object sender, EventArgs e)
+ {
+ if (_fileType != 0 && TryAskExportScale(out int percent))
+ {
+ ExportBodyToVD(percent);
+ }
+ }
+
+ private void ExportBodyToVD(int percent)
{
if (_fileType == 0)
{
return;
}
- string path = Options.OutputPath;
- string fileName = Path.Combine(path, $"anim{_fileType}_{Utils.FormatExportId(_currentBody)}.vd");
- if (!TryRunAnimationWrite(() => AnimationEdit.ExportToVD(_fileType, _currentBody, fileName), "Export"))
+ string fileName = Path.Combine(Options.OutputPath, $"anim{_fileType}_{Utils.FormatExportId(_currentBody)}{ScaleSuffix(percent)}.vd");
+ if (!TryRunAnimationWrite(() => AnimationEdit.ExportToVD(_fileType, _currentBody, fileName, percent / 100.0), "Export"))
+ {
+ return;
+ }
+
+ FileSavedDialog.Show(FindForm(), Options.OutputPath, "Animation saved successfully.");
+ }
+
+ private void OnClickExportRemappedToVD(object sender, EventArgs e)
+ {
+ if (_fileType == 0)
+ {
+ return;
+ }
+
+ int body = _currentBody;
+ MobType sourceType = Animations.GetBodyMobType(body, _fileType);
+ var hasFrames = new bool[Animations.GetAnimLength(body, _fileType)];
+ for (int action = 0; action < hasFrames.Length; ++action)
+ {
+ hasFrames[action] = AnimationEdit.IsActionDefined(_fileType, body, action);
+ }
+
+ using var form = new VdRemapForm(body, sourceType, hasFrames, ResolveActionNames);
+ if (form.ShowDialog(this) != DialogResult.OK)
+ {
+ return;
+ }
+
+ MobType layout = form.TargetLayout;
+ int[] sourceActions = form.SourceActions;
+ int percent = form.ScalePercent;
+ string fileName = Path.Combine(Options.OutputPath,
+ $"anim{_fileType}_{Utils.FormatExportId(body)}_as_{layout.ToString().ToLowerInvariant()}{ScaleSuffix(percent)}.vd");
+ if (!TryRunAnimationWrite(() => AnimationEdit.ExportRemappedToVD(_fileType, body, layout, sourceActions, fileName, percent / 100.0), "Export"))
{
return;
}
@@ -1811,17 +2080,65 @@ private void OnClickExportToVD(object sender, EventArgs e)
FileSavedDialog.Show(FindForm(), Options.OutputPath, "Animation saved successfully.");
}
+ private static string ScaleSuffix(int percent)
+ {
+ return percent == 100 ? string.Empty : $"_scale{percent}";
+ }
+
+ ///
+ /// Asks for the size of exported frames, in percent of the original.
+ ///
+ private bool TryAskExportScale(out int percent)
+ {
+ using var dialog = new Form
+ {
+ Text = "Export scaled",
+ ClientSize = new Size(260, 84),
+ FormBorderStyle = FormBorderStyle.FixedDialog,
+ StartPosition = FormStartPosition.CenterParent,
+ MaximizeBox = false,
+ MinimizeBox = false,
+ ShowInTaskbar = false,
+ };
+ var label = new Label { Text = "Frame size (%):", AutoSize = true, Location = new Point(12, 16) };
+ var scale = new NumericUpDown
+ {
+ Minimum = 10,
+ Maximum = 400,
+ Increment = 10,
+ Value = _lastExportScale,
+ Location = new Point(130, 12),
+ Width = 70,
+ };
+ var ok = new Button { Text = "Export", DialogResult = DialogResult.OK, Location = new Point(92, 48) };
+ var cancel = new Button { Text = "Cancel", DialogResult = DialogResult.Cancel, Location = new Point(173, 48) };
+ dialog.Controls.AddRange(new Control[] { label, scale, ok, cancel });
+ dialog.AcceptButton = ok;
+ dialog.CancelButton = cancel;
+
+ percent = 100;
+ if (dialog.ShowDialog(this) != DialogResult.OK)
+ {
+ return false;
+ }
+
+ percent = (int)scale.Value;
+ _lastExportScale = percent;
+ return true;
+ }
+
private void OnTreeViewContextMenuOpening(object sender, System.ComponentModel.CancelEventArgs e)
{
bool actionSelected = _fileType != 0 && TryGetSelectedAction(out _, out _);
copyActionToolStripMenuItem.Enabled = actionSelected;
actionFromVdToolStripMenuItem.Enabled = actionSelected;
actionToVdToolStripMenuItem.Enabled = actionSelected;
+ actionToVdScaledToolStripMenuItem.Enabled = actionSelected;
}
private bool TryGetSelectedAction(out int body, out int action)
{
- TreeNode node = AnimationListTreeView.SelectedNode;
+ VirtualTreeNode node = AnimationListTreeView.SelectedNode;
if (node?.Parent == null)
{
body = -1;
@@ -1835,14 +2152,27 @@ private bool TryGetSelectedAction(out int body, out int action)
}
private void OnClickExportActionToVD(object sender, EventArgs e)
+ {
+ ExportActionToVD(100);
+ }
+
+ private void OnClickExportActionScaledToVD(object sender, EventArgs e)
+ {
+ if (_fileType != 0 && TryGetSelectedAction(out _, out _) && TryAskExportScale(out int percent))
+ {
+ ExportActionToVD(percent);
+ }
+ }
+
+ private void ExportActionToVD(int percent)
{
if (_fileType == 0 || !TryGetSelectedAction(out int body, out int action))
{
return;
}
- string fileName = Path.Combine(Options.OutputPath, $"anim{_fileType}_{Utils.FormatExportId(body)}_action{action}.vd");
- if (!TryRunAnimationWrite(() => AnimationEdit.ExportActionToVD(_fileType, body, action, fileName), "Export"))
+ string fileName = Path.Combine(Options.OutputPath, $"anim{_fileType}_{Utils.FormatExportId(body)}_action{action}{ScaleSuffix(percent)}.vd");
+ if (!TryRunAnimationWrite(() => AnimationEdit.ExportActionToVD(_fileType, body, action, fileName, percent / 100.0), "Export"))
{
return;
}
@@ -1897,7 +2227,7 @@ private void OnClickImportActionFromVD(object sender, EventArgs e)
{
AnimationEdit.LoadActionFromVD(_fileType, body, action, bin);
}
- catch (Exception ex) when (ex is IOException || ex is ArgumentException || ex is OverflowException)
+ catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is ArgumentException || ex is OverflowException)
{
MessageBox.Show($"Could not read {Path.GetFileName(dialog.FileName)}: {ex.Message}", "Import",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -1938,8 +2268,8 @@ private void OnClickCopyAction(object sender, EventArgs e)
///
private void UpdateBodyNode(int body)
{
- TreeNode node = _showOnlyValid
- ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(n => (int)n.Tag == body)
+ VirtualTreeNode node = _showOnlyValid
+ ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(n => (int)n.Tag == body)
: body < AnimationListTreeView.Nodes.Count ? AnimationListTreeView.Nodes[body] : null;
if (node == null)
{
@@ -1947,20 +2277,11 @@ private void UpdateBodyNode(int body)
}
bool valid = false;
- foreach (TreeNode child in node.Nodes)
+ int animLength = Animations.GetAnimLength(body, _fileType);
+ for (int action = 0; action < animLength; ++action)
{
- if (AnimationEdit.IsActionDefined(_fileType, body, (int)child.Tag))
- {
- valid = true;
- if (child.ForeColor == _invalidColor)
- {
- child.ForeColor = Color.Empty;
- }
- }
- else
- {
- child.ForeColor = _invalidColor;
- }
+ valid |= AnimationEdit.IsActionDefined(_fileType, body, action);
+ RefreshActionNode(node, action);
}
node.ForeColor = valid ? Color.Empty : _invalidColor;
@@ -2320,11 +2641,11 @@ private bool ReplaceActionFromImages(string[] files)
}
}
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
Options.ChangedUltimaClass["Animations"] = true;
@@ -2370,8 +2691,7 @@ private void AddFilesAllDirections(OpenFileDialog dialog)
FramesListView.Invalidate();
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
Options.ChangedUltimaClass["Animations"] = true;
}
@@ -2428,7 +2748,7 @@ private void ToolStripButtonPlayAnimation_Click(object sender, EventArgs e)
{
AnimationTimer.Enabled = false;
FramesTrackBar.Enabled = true;
- SameCenterButton.Enabled = true;
+ SameCenterButton.Enabled = !RelativeCenterCheckBox.Checked;
CenterXNumericUpDown.Enabled = true;
CenterYNumericUpDown.Enabled = true;
@@ -2921,11 +3241,11 @@ private void AddAnimationX1(Color customConvert, Bitmap bmp)
for (int index = 0; index < frameCount; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -2960,8 +3280,7 @@ private void AddAnimationX1(Color customConvert, Bitmap bmp)
ProgressBar.Invalidate();
SetPaletteBox();
FramesListView.Invalidate();
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
Options.ChangedUltimaClass["Animations"] = true;
}
@@ -3352,8 +3671,7 @@ private void AddDirectionsAddWithCanvasUniqueImageToolStripMenuItem_Click(object
SetPaletteBox();
FramesListView.Invalidate();
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
Options.ChangedUltimaClass["Animations"] = true;
}
@@ -3384,11 +3702,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens
for (int index = frameCount / 8 * 4; index < frameCount / 8 * 5; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -3431,11 +3749,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens
for (int index = 0; index < frameCount / 8; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -3478,11 +3796,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens
for (int index = frameCount / 8 * 5; index < frameCount / 8 * 6; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -3525,11 +3843,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens
for (int index = frameCount / 8 * 1; index < frameCount / 8 * 2; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -3572,11 +3890,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens
for (int index = frameCount / 8 * 6; index < frameCount / 8 * 7; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -4038,8 +4356,7 @@ private void AllDirectionsAddWithCanvasKRFrameEditorColorCorrectorToolStripMenuI
SetPaletteBox();
FramesListView.Invalidate();
- CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X;
- CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y;
+ ShowFrameCenter(edit.Frames[FramesTrackBar.Value]);
Options.ChangedUltimaClass["Animations"] = true;
}
@@ -4070,11 +4387,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi
for (int index = frameCount / 5 * 0; index < frameCount / 5 * 1; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -4117,11 +4434,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi
for (int index = frameCount / 5 * 1; index < frameCount / 5 * 2; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -4164,11 +4481,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi
for (int index = frameCount / 5 * 2; index < frameCount / 5 * 3; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -4211,11 +4528,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi
for (int index = frameCount / 5 * 3; index < frameCount / 5 * 4; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
@@ -4258,11 +4575,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi
for (int index = frameCount / 5 * 4; index < frameCount / 5 * 5; index++)
{
edit.AddFrame(bitBmp[index], bitBmp[index].Width/2);
- TreeNode node = GetNode(_currentBody);
+ VirtualTreeNode node = GetNode(_currentBody);
if (node != null)
{
node.ForeColor = Color.Empty;
- node.Nodes[_currentAction].ForeColor = Color.Empty;
+ RefreshActionNode(node, _currentAction);
}
int i = edit.Frames.Count - 1;
diff --git a/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs b/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs
index 235d490f..696c6a3e 100644
--- a/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs
+++ b/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs
@@ -39,10 +39,16 @@ private void InitializeComponent()
SpacingUpDown = new System.Windows.Forms.NumericUpDown();
OneRowPerDirectionCheckBox = new System.Windows.Forms.CheckBox();
ExportAllActionsCheckBox = new System.Windows.Forms.CheckBox();
+ ScaleLabel = new System.Windows.Forms.Label();
+ ScaleUpDown = new System.Windows.Forms.NumericUpDown();
+ FormatLabel = new System.Windows.Forms.Label();
+ SheetFormatRadioButton = new System.Windows.Forms.RadioButton();
+ FramesXmlFormatRadioButton = new System.Windows.Forms.RadioButton();
OkButton = new System.Windows.Forms.Button();
CancelDialogButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)MaxWidthUpDown).BeginInit();
((System.ComponentModel.ISupportInitialize)SpacingUpDown).BeginInit();
+ ((System.ComponentModel.ISupportInitialize)ScaleUpDown).BeginInit();
SuspendLayout();
//
// DirectionsLabel
@@ -148,13 +154,63 @@ private void InitializeComponent()
ExportAllActionsCheckBox.TabIndex = 7;
ExportAllActionsCheckBox.Text = "Export all actions of the body";
ExportAllActionsCheckBox.UseVisualStyleBackColor = true;
+ //
+ // ScaleLabel
+ //
+ ScaleLabel.AutoSize = true;
+ ScaleLabel.Location = new System.Drawing.Point(212, 142);
+ ScaleLabel.Name = "ScaleLabel";
+ ScaleLabel.Size = new System.Drawing.Size(88, 15);
+ ScaleLabel.Text = "Frame size (%):";
+ //
+ // ScaleUpDown
+ //
+ ScaleUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0 });
+ ScaleUpDown.Location = new System.Drawing.Point(212, 160);
+ ScaleUpDown.Maximum = new decimal(new int[] { 400, 0, 0, 0 });
+ ScaleUpDown.Minimum = new decimal(new int[] { 10, 0, 0, 0 });
+ ScaleUpDown.Name = "ScaleUpDown";
+ ScaleUpDown.Size = new System.Drawing.Size(80, 23);
+ ScaleUpDown.TabIndex = 8;
+ ScaleUpDown.Value = new decimal(new int[] { 100, 0, 0, 0 });
+ //
+ // FormatLabel
+ //
+ FormatLabel.AutoSize = true;
+ FormatLabel.Location = new System.Drawing.Point(12, 236);
+ FormatLabel.Name = "FormatLabel";
+ FormatLabel.Size = new System.Drawing.Size(48, 15);
+ FormatLabel.Text = "Format:";
+ //
+ // SheetFormatRadioButton
+ //
+ SheetFormatRadioButton.AutoSize = true;
+ SheetFormatRadioButton.Checked = true;
+ SheetFormatRadioButton.Location = new System.Drawing.Point(12, 254);
+ SheetFormatRadioButton.Name = "SheetFormatRadioButton";
+ SheetFormatRadioButton.Size = new System.Drawing.Size(170, 19);
+ SheetFormatRadioButton.TabIndex = 9;
+ SheetFormatRadioButton.TabStop = true;
+ SheetFormatRadioButton.Text = "Sprite sheet (.png + .json)";
+ SheetFormatRadioButton.UseVisualStyleBackColor = true;
+ SheetFormatRadioButton.CheckedChanged += OnCheckedChangedFormat;
+ //
+ // FramesXmlFormatRadioButton
+ //
+ FramesXmlFormatRadioButton.AutoSize = true;
+ FramesXmlFormatRadioButton.Location = new System.Drawing.Point(12, 279);
+ FramesXmlFormatRadioButton.Name = "FramesXmlFormatRadioButton";
+ FramesXmlFormatRadioButton.Size = new System.Drawing.Size(232, 19);
+ FramesXmlFormatRadioButton.TabIndex = 10;
+ FramesXmlFormatRadioButton.Text = "One image per frame (.png + .xml)";
+ FramesXmlFormatRadioButton.UseVisualStyleBackColor = true;
//
// OkButton
//
- OkButton.Location = new System.Drawing.Point(218, 240);
+ OkButton.Location = new System.Drawing.Point(218, 312);
OkButton.Name = "OkButton";
OkButton.Size = new System.Drawing.Size(75, 25);
- OkButton.TabIndex = 8;
+ OkButton.TabIndex = 11;
OkButton.Text = "OK";
OkButton.UseVisualStyleBackColor = true;
OkButton.Click += OnClickOk;
@@ -162,10 +218,10 @@ private void InitializeComponent()
// CancelDialogButton
//
CancelDialogButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
- CancelDialogButton.Location = new System.Drawing.Point(299, 240);
+ CancelDialogButton.Location = new System.Drawing.Point(299, 312);
CancelDialogButton.Name = "CancelDialogButton";
CancelDialogButton.Size = new System.Drawing.Size(75, 25);
- CancelDialogButton.TabIndex = 9;
+ CancelDialogButton.TabIndex = 12;
CancelDialogButton.Text = "Cancel";
CancelDialogButton.UseVisualStyleBackColor = true;
//
@@ -173,7 +229,7 @@ private void InitializeComponent()
//
AcceptButton = OkButton;
CancelButton = CancelDialogButton;
- ClientSize = new System.Drawing.Size(386, 277);
+ ClientSize = new System.Drawing.Size(386, 349);
Controls.Add(DirectionsLabel);
Controls.Add(DirectionsListBox);
Controls.Add(MaxWidthLabel);
@@ -185,6 +241,11 @@ private void InitializeComponent()
Controls.Add(SpacingUpDown);
Controls.Add(OneRowPerDirectionCheckBox);
Controls.Add(ExportAllActionsCheckBox);
+ Controls.Add(ScaleLabel);
+ Controls.Add(ScaleUpDown);
+ Controls.Add(FormatLabel);
+ Controls.Add(SheetFormatRadioButton);
+ Controls.Add(FramesXmlFormatRadioButton);
Controls.Add(OkButton);
Controls.Add(CancelDialogButton);
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
@@ -196,6 +257,7 @@ private void InitializeComponent()
Text = "Pack Frames";
((System.ComponentModel.ISupportInitialize)MaxWidthUpDown).EndInit();
((System.ComponentModel.ISupportInitialize)SpacingUpDown).EndInit();
+ ((System.ComponentModel.ISupportInitialize)ScaleUpDown).EndInit();
ResumeLayout(false);
PerformLayout();
}
@@ -213,6 +275,11 @@ private void InitializeComponent()
private System.Windows.Forms.NumericUpDown SpacingUpDown;
private System.Windows.Forms.CheckBox OneRowPerDirectionCheckBox;
private System.Windows.Forms.CheckBox ExportAllActionsCheckBox;
+ private System.Windows.Forms.Label ScaleLabel;
+ private System.Windows.Forms.NumericUpDown ScaleUpDown;
+ private System.Windows.Forms.Label FormatLabel;
+ private System.Windows.Forms.RadioButton SheetFormatRadioButton;
+ private System.Windows.Forms.RadioButton FramesXmlFormatRadioButton;
private System.Windows.Forms.Button OkButton;
private System.Windows.Forms.Button CancelDialogButton;
}
diff --git a/UoFiddler.Controls/Forms/PackOptionsForm.cs b/UoFiddler.Controls/Forms/PackOptionsForm.cs
index 7409bf4a..73510d81 100644
--- a/UoFiddler.Controls/Forms/PackOptionsForm.cs
+++ b/UoFiddler.Controls/Forms/PackOptionsForm.cs
@@ -63,6 +63,12 @@ public PackOptionsForm()
public bool ExportAllActions => ExportAllActionsCheckBox.Checked;
+ /// Size of the exported frames relative to the stored ones; 1 keeps them as they are.
+ public double FrameScale => (double)ScaleUpDown.Value / 100.0;
+
+ /// Save one image per frame and a frames XML file instead of a sprite sheet.
+ public bool FramesXmlFormat => FramesXmlFormatRadioButton.Checked;
+
private void OnClickPreset(object sender, EventArgs e)
{
MaxWidthUpDown.Value = decimal.Parse(((Button)sender).Text);
@@ -70,8 +76,23 @@ private void OnClickPreset(object sender, EventArgs e)
private void OnCheckedChangedOneRowPerDirection(object sender, EventArgs e)
{
+ UpdateSheetOptions();
+ }
+
+ private void OnCheckedChangedFormat(object sender, EventArgs e)
+ {
+ UpdateSheetOptions();
+ }
+
+ private void UpdateSheetOptions()
+ {
+ // The layout options only shape a sprite sheet
+ bool sheet = SheetFormatRadioButton.Checked;
+ SpacingUpDown.Enabled = sheet;
+ OneRowPerDirectionCheckBox.Enabled = sheet;
+
// Rows follow the directions, so the width limit does not apply
- bool limitWidth = !OneRowPerDirectionCheckBox.Checked;
+ bool limitWidth = sheet && !OneRowPerDirectionCheckBox.Checked;
MaxWidthUpDown.Enabled = limitWidth;
Preset1024Button.Enabled = limitWidth;
Preset2048Button.Enabled = limitWidth;
diff --git a/UoFiddler.Controls/Forms/VdRemapForm.Designer.cs b/UoFiddler.Controls/Forms/VdRemapForm.Designer.cs
new file mode 100644
index 00000000..b5c22bd3
--- /dev/null
+++ b/UoFiddler.Controls/Forms/VdRemapForm.Designer.cs
@@ -0,0 +1,199 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Controls.Forms
+{
+ partial class VdRemapForm
+ {
+ ///
+ /// 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
+
+ private void InitializeComponent()
+ {
+ SourceLabel = new System.Windows.Forms.Label();
+ LayoutLabel = new System.Windows.Forms.Label();
+ LayoutComboBox = new System.Windows.Forms.ComboBox();
+ ScaleLabel = new System.Windows.Forms.Label();
+ ScaleUpDown = new System.Windows.Forms.NumericUpDown();
+ DefaultsButton = new System.Windows.Forms.Button();
+ MappingPanel = new System.Windows.Forms.Panel();
+ MappingTable = new System.Windows.Forms.TableLayoutPanel();
+ OkButton = new System.Windows.Forms.Button();
+ CancelDialogButton = new System.Windows.Forms.Button();
+ ((System.ComponentModel.ISupportInitialize)ScaleUpDown).BeginInit();
+ MappingPanel.SuspendLayout();
+ SuspendLayout();
+ //
+ // SourceLabel
+ //
+ SourceLabel.AutoSize = true;
+ SourceLabel.Location = new System.Drawing.Point(12, 12);
+ SourceLabel.Name = "SourceLabel";
+ SourceLabel.Size = new System.Drawing.Size(46, 15);
+ SourceLabel.TabIndex = 0;
+ SourceLabel.Text = "Source:";
+ //
+ // LayoutLabel
+ //
+ LayoutLabel.AutoSize = true;
+ LayoutLabel.Location = new System.Drawing.Point(12, 40);
+ LayoutLabel.Name = "LayoutLabel";
+ LayoutLabel.Size = new System.Drawing.Size(72, 15);
+ LayoutLabel.TabIndex = 1;
+ LayoutLabel.Text = "Save as type:";
+ //
+ // LayoutComboBox
+ //
+ LayoutComboBox.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
+ LayoutComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
+ LayoutComboBox.Location = new System.Drawing.Point(100, 37);
+ LayoutComboBox.Name = "LayoutComboBox";
+ LayoutComboBox.Size = new System.Drawing.Size(388, 23);
+ LayoutComboBox.TabIndex = 2;
+ LayoutComboBox.SelectedIndexChanged += OnLayoutChanged;
+ //
+ // ScaleLabel
+ //
+ ScaleLabel.AutoSize = true;
+ ScaleLabel.Location = new System.Drawing.Point(12, 72);
+ ScaleLabel.Name = "ScaleLabel";
+ ScaleLabel.Size = new System.Drawing.Size(88, 15);
+ ScaleLabel.TabIndex = 3;
+ ScaleLabel.Text = "Frame size (%):";
+ //
+ // ScaleUpDown
+ //
+ ScaleUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0 });
+ ScaleUpDown.Location = new System.Drawing.Point(110, 69);
+ ScaleUpDown.Maximum = new decimal(new int[] { 400, 0, 0, 0 });
+ ScaleUpDown.Minimum = new decimal(new int[] { 10, 0, 0, 0 });
+ ScaleUpDown.Name = "ScaleUpDown";
+ ScaleUpDown.Size = new System.Drawing.Size(70, 23);
+ ScaleUpDown.TabIndex = 4;
+ ScaleUpDown.Value = new decimal(new int[] { 100, 0, 0, 0 });
+ //
+ // DefaultsButton
+ //
+ DefaultsButton.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right;
+ DefaultsButton.AutoSize = true;
+ DefaultsButton.Location = new System.Drawing.Point(368, 67);
+ DefaultsButton.Name = "DefaultsButton";
+ DefaultsButton.Size = new System.Drawing.Size(120, 27);
+ DefaultsButton.TabIndex = 5;
+ DefaultsButton.Text = "Default mapping";
+ DefaultsButton.UseVisualStyleBackColor = true;
+ DefaultsButton.Click += OnClickDefaults;
+ //
+ // MappingPanel
+ //
+ MappingPanel.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
+ MappingPanel.AutoScroll = true;
+ MappingPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
+ MappingPanel.Controls.Add(MappingTable);
+ MappingPanel.Location = new System.Drawing.Point(12, 102);
+ MappingPanel.Name = "MappingPanel";
+ MappingPanel.Size = new System.Drawing.Size(476, 410);
+ MappingPanel.TabIndex = 6;
+ //
+ // MappingTable
+ //
+ MappingTable.AutoSize = true;
+ MappingTable.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
+ MappingTable.ColumnCount = 2;
+ MappingTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 210F));
+ MappingTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 240F));
+ MappingTable.Dock = System.Windows.Forms.DockStyle.Top;
+ MappingTable.Location = new System.Drawing.Point(0, 0);
+ MappingTable.Name = "MappingTable";
+ MappingTable.Padding = new System.Windows.Forms.Padding(4);
+ MappingTable.Size = new System.Drawing.Size(457, 8);
+ MappingTable.TabIndex = 0;
+ //
+ // OkButton
+ //
+ OkButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
+ OkButton.DialogResult = System.Windows.Forms.DialogResult.OK;
+ OkButton.Location = new System.Drawing.Point(332, 522);
+ OkButton.Name = "OkButton";
+ OkButton.Size = new System.Drawing.Size(75, 25);
+ OkButton.TabIndex = 7;
+ OkButton.Text = "Export";
+ OkButton.UseVisualStyleBackColor = true;
+ //
+ // CancelDialogButton
+ //
+ CancelDialogButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
+ CancelDialogButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
+ CancelDialogButton.Location = new System.Drawing.Point(413, 522);
+ CancelDialogButton.Name = "CancelDialogButton";
+ CancelDialogButton.Size = new System.Drawing.Size(75, 25);
+ CancelDialogButton.TabIndex = 8;
+ CancelDialogButton.Text = "Cancel";
+ CancelDialogButton.UseVisualStyleBackColor = true;
+ //
+ // VdRemapForm
+ //
+ AcceptButton = OkButton;
+ CancelButton = CancelDialogButton;
+ ClientSize = new System.Drawing.Size(500, 559);
+ Controls.Add(SourceLabel);
+ Controls.Add(LayoutLabel);
+ Controls.Add(LayoutComboBox);
+ Controls.Add(ScaleLabel);
+ Controls.Add(ScaleUpDown);
+ Controls.Add(DefaultsButton);
+ Controls.Add(MappingPanel);
+ Controls.Add(OkButton);
+ Controls.Add(CancelDialogButton);
+ MinimizeBox = false;
+ MinimumSize = new System.Drawing.Size(460, 400);
+ Name = "VdRemapForm";
+ ShowInTaskbar = false;
+ StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+ Text = "Body to .vd, remapped";
+ ((System.ComponentModel.ISupportInitialize)ScaleUpDown).EndInit();
+ MappingPanel.ResumeLayout(false);
+ MappingPanel.PerformLayout();
+ ResumeLayout(false);
+ PerformLayout();
+ }
+
+ #endregion
+
+ private System.Windows.Forms.Label SourceLabel;
+ private System.Windows.Forms.Label LayoutLabel;
+ private System.Windows.Forms.ComboBox LayoutComboBox;
+ private System.Windows.Forms.Label ScaleLabel;
+ private System.Windows.Forms.NumericUpDown ScaleUpDown;
+ private System.Windows.Forms.Button DefaultsButton;
+ private System.Windows.Forms.Panel MappingPanel;
+ private System.Windows.Forms.TableLayoutPanel MappingTable;
+ private System.Windows.Forms.Button OkButton;
+ private System.Windows.Forms.Button CancelDialogButton;
+ }
+}
diff --git a/UoFiddler.Controls/Forms/VdRemapForm.cs b/UoFiddler.Controls/Forms/VdRemapForm.cs
new file mode 100644
index 00000000..d1463d97
--- /dev/null
+++ b/UoFiddler.Controls/Forms/VdRemapForm.cs
@@ -0,0 +1,156 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Windows.Forms;
+using Ultima;
+using UoFiddler.Controls.Classes;
+
+namespace UoFiddler.Controls.Forms
+{
+ ///
+ /// Picks, for each action of a target body type's layout, which action of the source body goes there,
+ /// for a .vd export in that layout.
+ ///
+ public partial class VdRemapForm : Form
+ {
+ private static readonly MobType[] _layouts = { MobType.Monster, MobType.Sea, MobType.Animal, MobType.Human };
+
+ private readonly MobType _sourceType;
+ private readonly string[] _sourceNames;
+ private readonly bool[] _sourceHasFrames;
+ private readonly Func _actionNames;
+ private readonly List _rows = new();
+
+ /// Body being exported, for the title.
+ /// The body's own action layout.
+ /// For each action of the body, whether it has frames.
+ /// Action names of a layout.
+ public VdRemapForm(int body, MobType sourceType, bool[] sourceHasFrames, Func actionNames)
+ {
+ InitializeComponent();
+ Icon = Options.GetFiddlerIcon();
+
+ _sourceType = sourceType;
+ _sourceHasFrames = sourceHasFrames;
+ _actionNames = actionNames;
+ string[] names = actionNames(sourceType);
+ _sourceNames = Enumerable.Range(0, sourceHasFrames.Length)
+ .Select(i => i < names.Length ? names[i] : $"Action {i}")
+ .ToArray();
+
+ Text = $"Body {body} to .vd, remapped";
+ SourceLabel.Text = $"Source: body {body}, {DescribeLayout(sourceType)}";
+
+ foreach (MobType layout in _layouts)
+ {
+ LayoutComboBox.Items.Add(DescribeLayout(layout));
+ }
+
+ // Start on another layout than the body's own; that is what a remap is for
+ MobType start = sourceType == MobType.Animal ? MobType.Monster : MobType.Animal;
+ LayoutComboBox.SelectedIndex = Array.IndexOf(_layouts, start);
+ }
+
+ public MobType TargetLayout => _layouts[LayoutComboBox.SelectedIndex];
+
+ /// For each action of the target layout, the source action written there, or -1 for none.
+ public int[] SourceActions => _rows.Select(row => row.SelectedIndex - 1).ToArray();
+
+ public int ScalePercent => (int)ScaleUpDown.Value;
+
+ private static string DescribeLayout(MobType layout)
+ {
+ return layout switch
+ {
+ MobType.Monster => "monster (22 actions)",
+ MobType.Sea => "sea monster (9 actions, saved as a 22-action monster .vd)",
+ MobType.Animal => "animal (13 actions)",
+ MobType.Equipment => "equipment (35 actions)",
+ _ => "human (35 actions)"
+ };
+ }
+
+ private void OnLayoutChanged(object sender, EventArgs e)
+ {
+ BuildRows();
+ }
+
+ private void OnClickDefaults(object sender, EventArgs e)
+ {
+ ApplyDefaults();
+ }
+
+ private void BuildRows()
+ {
+ MobType layout = TargetLayout;
+ IReadOnlyList roles = MobActionMap.GetRoles(layout);
+ string[] targetNames = _actionNames(layout);
+
+ var sourceItems = new List { "(empty)" };
+ for (int i = 0; i < _sourceNames.Length; ++i)
+ {
+ sourceItems.Add(_sourceHasFrames[i] ? $"{i:D2} {_sourceNames[i]}" : $"{i:D2} {_sourceNames[i]} (no frames)");
+ }
+
+ MappingTable.SuspendLayout();
+ MappingTable.Controls.Clear();
+ MappingTable.RowStyles.Clear();
+ _rows.Clear();
+ MappingTable.RowCount = roles.Count;
+
+ for (int target = 0; target < roles.Count; ++target)
+ {
+ string name = target < targetNames.Length ? targetNames[target] : $"Action {target}";
+ var label = new Label
+ {
+ Text = $"{target:D2} {name}",
+ AutoSize = true,
+ Anchor = AnchorStyles.Left
+ };
+ var combo = new ComboBox
+ {
+ DropDownStyle = ComboBoxStyle.DropDownList,
+ Dock = DockStyle.Fill
+ };
+ combo.Items.AddRange(sourceItems.ToArray