From 5dd5780f4289df3a8b168853692c67642e2932ef Mon Sep 17 00:00:00 2001 From: wtclaude Date: Wed, 25 Nov 2026 21:12:24 -0600 Subject: [PATCH] fix(bridge): decode legacy animation art without GDI+ (#39, 1 of 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a Linux/Mono shard the Asset Bridge's legacy-MUL catalogue art failed with [GDI+ status: NotImplemented]: the vendored Ultima.Frame ctor builds a 16bpp Bitmap (Settings.PixelFormat) and libgdiplus cannot create one. This finishes, for the legacy animation path, the GDI+-free migration §4.4 began for UOP — Windows and Linux now share one managed path rather than a Linux workaround. - BridgeMul: a hand-written anim*.mul first-frame decoder to ARGB1555, mirroring Ultima.Frame's run loop with BridgeUop's bounds (no System.Drawing, no Bitmap). - BridgeHue: Hue.ApplyTo reproduced over a ushort[], reusing the vendored Hues.List[i].Colors table so a body.def-hued creature tints identically. - BridgeAssetValidator: RecordReader.ReadRecordCopy hands the verdata-patched record bytes to the managed decoder; a ResolveAnimation overload surfaces the body.def hue it already computes and discarded. - BridgeCatalog: the legacy path now decodes through BridgeMul + BridgeHue -> BridgePng; the imaging gate is removed from assets.manifest/fetch, since the body catalogue (legacy + UOP) no longer touches System.Drawing. The record gate (ResolveAnimation/CheckEntry/AnimationSane) is unchanged. - BridgeAnimParity: a [BridgeAnimParity] GM command / BRIDGE_ANIM_PARITY=1 boot run that compares the managed decode against the vendored one pixel for pixel. Overlay-only; no wire change, no PROTOCOL_VERSION bump. The art/land path (BridgeArt) and its imaging gate are the second PR. The art family's imaging.ok status is unchanged meanwhile. Verified on this machine's ServUO + live client: the parity harness compared all 40,341 records the Bridge serves and every one is pixel-identical to the vendored GDI+ decode (0 mismatched, 0 missed); 102,923 out-of-band/invalid records the Bridge refuses were correctly skipped. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014HJEmcaKvWQ8LsnXHKha5y --- .../Scripts/Custom/Bridge/BridgeAnimParity.cs | 213 +++++++++ .../Custom/Bridge/BridgeAssetValidator.cs | 35 +- .../Scripts/Custom/Bridge/BridgeCatalog.cs | 422 ++++++++++++++---- overlay/Scripts/Custom/Bridge/BridgeHue.cs | 81 ++++ overlay/Scripts/Custom/Bridge/BridgeMul.cs | 178 ++++++++ 5 files changed, 841 insertions(+), 88 deletions(-) create mode 100644 overlay/Scripts/Custom/Bridge/BridgeAnimParity.cs create mode 100644 overlay/Scripts/Custom/Bridge/BridgeHue.cs create mode 100644 overlay/Scripts/Custom/Bridge/BridgeMul.cs diff --git a/overlay/Scripts/Custom/Bridge/BridgeAnimParity.cs b/overlay/Scripts/Custom/Bridge/BridgeAnimParity.cs new file mode 100644 index 0000000..2fb2fba --- /dev/null +++ b/overlay/Scripts/Custom/Bridge/BridgeAnimParity.cs @@ -0,0 +1,213 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Runtime.InteropServices; + +using Server; +using Server.Commands; + +using Ultima; + +namespace Server.Custom.Bridge +{ + /// + /// **The #39 merge gate**: the GM command [BridgeAnimParity], which proves the new + /// GDI+-free legacy decode ( + , driven by + /// ) is pixel-identical to the vendored + /// Ultima.Frame path it replaces. + /// + /// This is the one file left that still touches System.Drawing, and it does so only + /// to be the oracle: on Windows it runs the vendored GetAnimation, reads the + /// resulting 16bpp bitmap back to ARGB1555, and hands those pixels to the harness to compare + /// against the managed decode. On a real Linux/Mono shard the vendored bitmap ctor throws + /// NotImplemented (the very bug #39 fixes), the oracle reports itself unavailable, and + /// the harness falls back to confirming the managed path still renders — so the same command + /// is meaningful on both platforms. It ships in the overlay because it needs both decoders in + /// one process; it changes nothing the Bridge serves. + /// + public static class BridgeAnimParity + { + public static void Initialize() + { + CommandSystem.Register("BridgeAnimParity", AccessLevel.Administrator, OnCommand); + + // Headless gate run (servuo-plugins #39): with BRIDGE_ANIM_PARITY=1 in the environment, + // run the parity once the world is up and write parity-anim.txt, no client needed. For + // verification/CI only — it is never set on a production shard. + if (Environment.GetEnvironmentVariable("BRIDGE_ANIM_PARITY") == "1") + EventSink.ServerStarted += OnServerStartedParity; + } + + private static void OnServerStartedParity() + { + Console.WriteLine("[Bridge] anim parity: BRIDGE_ANIM_PARITY=1 — running at boot"); + Run(null); + } + + private static void OnCommand(CommandEventArgs e) + { + Run(e.Mobile); + } + + private static void Run(Mobile from) + { + if (from != null) + from.SendMessage( + "Running legacy anim GDI+ parity across the catalogue — the shard will pause for a bit."); + + Console.WriteLine("[Bridge] anim parity: starting"); + + string report; + + try + { + report = BridgeCatalog.RunAnimParity(Oracle); + } + catch (Exception ex) + { + report = "[Bridge] anim parity crashed: " + ex; + } + + Console.WriteLine(report); + + string path = null; + + try + { + path = Path.Combine(Core.BaseDirectory, "parity-anim.txt"); + File.WriteAllText(path, report); + } + catch (Exception ex) + { + Console.WriteLine("[Bridge] anim parity: cannot write file: " + ex.Message); + path = null; + } + + if (from != null) + { + from.SendMessage("Anim parity done." + + (path != null ? " Report: " + path : " (see the console)")); + + // The summary head, not the full detail list — the console and the file hold it all. + string[] lines = report.Split('\n'); + + for (int i = 0; i < lines.Length && i < 6; i++) + { + string line = lines[i].TrimEnd(); + + if (line.Length > 0) + from.SendMessage(line); + } + } + } + + /// + /// The vendored decode for one key, read back to ARGB1555. False with + /// still true means "no art here"; false with it set false + /// means the vendored path cannot run at all on this host (libgdiplus + /// NotImplemented), which is exactly the #39 fault and tells the harness to stop + /// asking the oracle. + /// + private static bool Oracle(int body, int action, int direction, + out ushort[] pixels, out int width, out int height, out bool available) + { + pixels = null; + width = 0; + height = 0; + available = true; + + Bitmap bmp = null; + + try + { + int hue = 0; + + // Exactly the call the old BridgeCatalog.Decode made: preserveHue false, first + // frame. The vendored path applies the body.def hue to the bitmap internally, so + // these pixels are already hued — matching what BridgeHue does on the managed side. + Frame[] frames = Animations.GetAnimation(body, action, direction, ref hue, false, true); + + if (frames == null || frames.Length == 0 || frames[0] == null) + return false; + + bmp = frames[0].Bitmap; + + if (bmp == null || bmp.Width <= 0 || bmp.Height <= 0) + { + bmp = null; // Frame.Empty / a null bitmap is not ours to dispose. + return false; + } + + width = bmp.Width; + height = bmp.Height; + pixels = ToArgb1555(bmp); + + return pixels != null; + } + catch (NotImplementedException) + { + // libgdiplus cannot create/lock the 16bpp bitmap — the #39 condition itself. + available = false; + return false; + } + catch + { + // Any other vendored failure: treat as no art for this key, keep the oracle alive. + return false; + } + finally + { + if (bmp != null) + { + try + { + bmp.Dispose(); + } + catch + { + // A fresh, uncached bitmap; nothing else holds it. + } + } + } + } + + /// + /// Reads a 16bpp ARGB1555 bitmap into a ushort[] with Marshal.Copy — no + /// unsafe block, exactly as BridgeAssets.BitmapToPng reads its source. + /// + private static ushort[] ToArgb1555(Bitmap bmp) + { + var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + + BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555); + + try + { + int w = bmp.Width; + int h = bmp.Height; + + var pixels = new ushort[w * h]; + var line = new short[w]; + + long scan = data.Scan0.ToInt64(); + + for (int y = 0; y < h; y++) + { + Marshal.Copy(new IntPtr(scan + ((long)y * data.Stride)), line, 0, w); + + int rowBase = y * w; + + for (int x = 0; x < w; x++) + pixels[rowBase + x] = (ushort)line[x]; + } + + return pixels; + } + finally + { + bmp.UnlockBits(data); + } + } + } +} diff --git a/overlay/Scripts/Custom/Bridge/BridgeAssetValidator.cs b/overlay/Scripts/Custom/Bridge/BridgeAssetValidator.cs index e1ecacc..7b6d0e2 100644 --- a/overlay/Scripts/Custom/Bridge/BridgeAssetValidator.cs +++ b/overlay/Scripts/Custom/Bridge/BridgeAssetValidator.cs @@ -361,10 +361,25 @@ namespace Server.Custom.Bridge /// public static bool ResolveAnimation( int body, int action, int direction, out int fileType, out int index, out string reason) + { + int hue; + return ResolveAnimation(body, action, direction, out fileType, out index, out hue, out reason); + } + + /// + /// As above, and also surfaces the hue GetAnimation(..., preserveHue: false, ...) + /// would apply. Animations.Translate(ref body, ref hue) pulls a body.def remap's + /// hue into (0 for a body that is not a hued remap); the legacy + /// catalogue decode needs it so a managed, GDI+-free path tints the same creatures the + /// vendored path tinted on Windows. + /// + public static bool ResolveAnimation( + int body, int action, int direction, out int fileType, out int index, out int hue, out string reason) { reason = null; fileType = 0; index = -1; + hue = 0; if (body <= 0 || action < 0) { @@ -383,7 +398,6 @@ namespace Server.Custom.Bridge } int translated = body; - int hue = 0; try { @@ -801,6 +815,25 @@ namespace Server.Custom.Bridge return AnimationRecordSane(_scratch, length, maxFrames, out reason); } + /// + /// One record as its own byte[] — the verdata-patched bytes + /// validates — for a managed decoder () to read without GDI+. + /// A fresh copy rather than the shared scratch buffer, because the caller holds it + /// across its whole decode and the next read would overwrite it. Null when there is + /// nothing to read or the read fails ( set on a failure). + /// + public byte[] ReadRecordCopy(FileIndex index, int at, out string reason) + { + int length = ReadRecord(index, at, out reason); + + if (length <= 0) + return null; + + var copy = new byte[length]; + Buffer.BlockCopy(_scratch, 0, copy, 0, length); + return copy; + } + /// /// Reads one record into . Returns its length, 0 for a /// failure (with set), or -1 when there is nothing to diff --git a/overlay/Scripts/Custom/Bridge/BridgeCatalog.cs b/overlay/Scripts/Custom/Bridge/BridgeCatalog.cs index 859bc89..149d9d9 100644 --- a/overlay/Scripts/Custom/Bridge/BridgeCatalog.cs +++ b/overlay/Scripts/Custom/Bridge/BridgeCatalog.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Drawing; using System.Globalization; using System.IO; using System.Text; @@ -193,19 +192,11 @@ namespace Server.Custom.Bridge /// private static void ReplyManifest(string reqId, string cursor) { - string imagingReason; - - if (!BridgeAssets.ImagingOk(out imagingReason)) - { - // Never a stack trace and never a 500: on a Linux host without libgdiplus this is - // the expected outcome, and it is actionable in one line (§4.4). - BridgeAssets.Fail(reqId, "UNAVAILABLE", - "this shard host cannot render images - Mono's System.Drawing needs " - + "libgdiplus. Install it (apt-get install libgdiplus) and re-run the import. " - + "Cliloc and atlas import are unaffected. (" + imagingReason + ")"); - return; - } - + // No imaging gate (servuo-plugins #39): the body catalogue is now wholly GDI+-free — + // the legacy half decodes through BridgeMul and the UOP half through BridgeUop, both + // into ARGB1555 with no System.Drawing — so a Linux/Mono host without libgdiplus + // imports it like any other. (The art family still gates in BridgeArt until its own + // migration.) string id = SourceId(); Catalog catalog; @@ -345,16 +336,8 @@ namespace Server.Custom.Bridge /// private static void ReplyFetch(string reqId, List keys, string expected, string cursor) { - string imagingReason; - - if (!BridgeAssets.ImagingOk(out imagingReason)) - { - BridgeAssets.Fail(reqId, "UNAVAILABLE", - "this shard host cannot render images - Mono's System.Drawing needs " - + "libgdiplus. (" + imagingReason + ")"); - return; - } - + // No imaging gate (servuo-plugins #39) — see ReplyManifest: the body catalogue decodes + // without System.Drawing now, so it serves on a host that has no libgdiplus. string id = SourceId(); if (BridgeAssets.CatalogMismatch(expected, id)) @@ -577,40 +560,36 @@ namespace Server.Custom.Bridge /// private static Sprite ResolveLegacy(string key, Readers readers, int body, int action, int direction) { - int fileType, at; - string reason; - - if (!BridgeAssetValidator.ResolveAnimation(body, action, direction, - out fileType, out at, out reason)) - return null; - - FileIndex index = readers.Index(fileType); - - if (index == null) - return null; - - if (BridgeAssetValidator.CheckEntry(index, at, readers.MulLength(fileType), - readers.VerdataLength, out reason) != BridgeAssetValidator.Verdict.Ok) - { - // The `length 0` case lands here, and it is the 357. The library would hand back - // the previously-decoded body's bitmap for every one of them. - return null; - } - - var reader = readers.Reader(fileType); - - if (reader == null) - return null; - - // `maxFrames: 1` because that is what `firstFrame: true` decodes. Checking frames - // nobody reads would invent refusals, and a checker that refuses real art is worse - // than no checker at all. - if (!reader.AnimationSane(index, at, 1, out reason)) - return null; - try { - return Decode(key, body, action, direction, fileType); + int fileType; + ushort[] pixels; + int width, height; + bool empty; + string reason; + + if (!LegacyPixels(readers, body, action, direction, + out fileType, out pixels, out width, out height, out empty, out reason)) + return null; + + byte[] png = BridgePng.FromArgb1555(pixels, width, height); + + if (png == null) + return null; + + return new Sprite + { + Key = key, + Body = body, + Action = action, + Direction = direction, + FileType = fileType, + Png = png, + Width = width, + Height = height, + Sha256 = BridgeAssets.Sha256Hex(png), + Source = "legacy" + }; } catch (Exception e) { @@ -620,6 +599,104 @@ namespace Server.Custom.Bridge } } + /// + /// The gate every legacy sprite passes before a pixel is read: ResolveAnimation + /// (Translate + BodyConverter + the §4.10 banding ceiling), CheckEntry (the §4.5 + /// entry check that refuses the 357 length 0 records), and AnimationSane. + /// A false return is a record the Bridge does not serve on either the old path or the + /// new one — out of a body's action band, or a record the vendored library would decode + /// into the previous body's bitmap. Factored out so the parity gate + /// () can tell "the Bridge refuses this" from "the managed + /// decode failed on a record it accepts": only the second is a defect. + /// + private static bool LegacyRecord(Readers readers, int body, int action, int direction, + out int fileType, out int at, out int hue, out string reason) + { + fileType = 0; + at = -1; + hue = 0; + + if (!BridgeAssetValidator.ResolveAnimation(body, action, direction, + out fileType, out at, out hue, out reason)) + return false; + + FileIndex index = readers.Index(fileType); + + if (index == null) + { + reason = "no index for file type " + fileType; + return false; + } + + if (BridgeAssetValidator.CheckEntry(index, at, readers.MulLength(fileType), + readers.VerdataLength, out reason) != BridgeAssetValidator.Verdict.Ok) + return false; + + var reader = readers.Reader(fileType); + + if (reader == null) + { + reason = "no reader for file type " + fileType; + return false; + } + + // `maxFrames: 1` because that is what `firstFrame: true` decodes. Checking frames + // nobody reads would invent refusals, and a checker that refuses real art is worse + // than no checker at all. + return reader.AnimationSane(index, at, 1, out reason); + } + + /// + /// The managed, GDI+-free legacy decode (servuo-plugins #39): the pixels the catalogue's + /// thumbnail is built from, validated and hued exactly as the vendored + /// Animations.GetAnimation(..., firstFrame: true) would, but into an ARGB1555 + /// ushort[] rather than a 16bpp Bitmap libgdiplus cannot create. The gate + /// () is unchanged and still vendored; only the two calls that + /// reached System.Drawing are replaced — the Frame ctor by + /// and Hue.ApplyTo by . A false + /// return is the ordinary "no legacy art here" (including a 0x0 frame, with + /// set), and the caller falls through to the UOP arm. This is + /// the exact path measures, so the harness proves the + /// shipping code rather than a copy of it. + /// + private static bool LegacyPixels(Readers readers, int body, int action, int direction, + out int fileType, out ushort[] pixels, out int width, out int height, + out bool empty, out string reason) + { + pixels = null; + width = 0; + height = 0; + empty = false; + + int at, hue; + + if (!LegacyRecord(readers, body, action, direction, out fileType, out at, out hue, out reason)) + return false; + + byte[] record = readers.Reader(fileType).ReadRecordCopy(readers.Index(fileType), at, out reason); + + if (record == null) + return false; + + if (!BridgeMul.TryDecodeFirstFrame(record, out pixels, out width, out height, + out empty, out reason)) + return false; + + // `preserveHue: false` — ResolveAnimation surfaced the body.def hue that + // GetAnimation would have applied. Apply it the same way (full, or gray-only per the + // 0x8000 flag), so a Linux shard tints the catalogue identically to a Windows one. + if (hue != 0) + { + short[] colors; + bool onlyGray; + + if (BridgeHue.Resolve(hue, out colors, out onlyGray)) + BridgeHue.Apply(pixels, colors, onlyGray); + } + + return true; + } + /// /// Phase 4's own reader over AnimationFrame*.uop (§4.3, §4.9), for the bodies /// the legacy path has nothing for. @@ -710,41 +787,212 @@ namespace Server.Custom.Bridge }; } - private static Sprite Decode(string key, int body, int action, int direction, int fileType) + // ── parity gate (servuo-plugins #39) ───────────────────────────────────────────────── + + /// + /// The vendored legacy decode for one key, as an oracle for . + /// The caller supplies it (from BridgeAnimParity, the only place that still + /// touches System.Drawing) so this file stays GDI+-free: it returns the ARGB1555 + /// pixels and dimensions the vendored path produced, or false for no art. + /// is set false when the oracle cannot run at all — a real + /// Linux/Mono host, where the vendored 16bpp Bitmap throws NotImplemented + /// — which tells the harness to drop into candidate-only (does-it-render) mode. + /// + public delegate bool ParityOracle(int body, int action, int direction, + out ushort[] pixels, out int width, out int height, out bool available); + + /// + /// Compares the shipping managed legacy decode () against the + /// vendored GDI+ decode, pixel for pixel, across every legacy-resolvable record (bodies + /// 1.., actions 0.., directions 0 and 1 — + /// both exercise the non-flip run loop, the only one this protocol reads). This is the + /// #39 merge gate: on Windows the vendored path is the oracle and every served sprite + /// must match it; on a Linux host the oracle is unavailable and the harness instead + /// confirms the managed path still produces art where the catalogue expects it. + /// + /// Returns a human-readable summary (also written to a file by the command that calls + /// this). It drives the real , not a reimplementation, so a + /// green run is evidence about the code that ships. + /// + public static string RunAnimParity(ParityOracle oracle) { - int hue = 0; + long resolved = 0, matched = 0, mismatched = 0, missed = 0, extra = 0; + long candidateOnly = 0, skipped = 0; + bool oracleAvailable = oracle != null; - // `preserveHue: false` — the catalogue is the creature's own art, and a body-level hue - // from Body.def belongs to a specific mob rather than to the species. §5's key scheme - // is where a hued variant is expressed (`static/3922/h33`), not here. - Frame[] frames = Animations.GetAnimation(body, action, direction, ref hue, false, true); + var detail = new StringBuilder(); + int shown = 0; + const int MaxShown = 30; - if (frames == null || frames.Length == 0 || frames[0] == null) - return null; - - Bitmap bitmap = frames[0].Bitmap; - - if (bitmap == null || bitmap.Width <= 0 || bitmap.Height <= 0) - return null; - - byte[] png = BridgeAssets.BitmapToPng(bitmap); - - if (png == null) - return null; - - return new Sprite + using (var readers = new Readers()) { - Key = key, - Body = body, - Action = action, - Direction = direction, - FileType = fileType, - Png = png, - Width = bitmap.Width, - Height = bitmap.Height, - Sha256 = BridgeAssets.Sha256Hex(png), - Source = "legacy" - }; + for (int body = 1; body <= MaxBody; body++) + { + if ((body & 0xFF) == 0) + Console.WriteLine("[Bridge] anim parity: body {0}/{1}", body, MaxBody); + + for (int action = 0; action < MaxAction; action++) + { + for (int direction = 0; direction <= 1; direction++) + { + int fileType, at, hue; + string reason; + + // The Bridge's own gate. A record it refuses (out of the action band, + // or a §4.5 bad entry) is one neither the old nor the new path serves, + // so it is not a parity case — comparing it against raw GetAnimation, + // which has no such gate, would only re-measure the §4.10/§4.5 bugs the + // validator exists to stop. + if (!LegacyRecord(readers, body, action, direction, + out fileType, out at, out hue, out reason)) + { + skipped++; + continue; + } + + ushort[] cand; + int cw, ch; + bool cEmpty; + + bool haveCand = LegacyPixels(readers, body, action, direction, + out fileType, out cand, out cw, out ch, out cEmpty, out reason); + + if (!oracleAvailable) + { + if (haveCand) + candidateOnly++; + + continue; + } + + ushort[] orc; + int ow, oh; + bool available; + + bool haveOrc = oracle(body, action, direction, + out orc, out ow, out oh, out available); + + if (!available) + { + // A Linux/Mono host: the vendored bitmap ctor cannot run. Switch + // to candidate-only for the rest of the walk. + oracleAvailable = false; + + if (haveCand) + candidateOnly++; + + continue; + } + + if (!haveCand && !haveOrc) + continue; + + if (haveCand && !haveOrc) + { + extra++; + + if (shown++ < MaxShown) + detail.AppendFormat(CultureInfo.InvariantCulture, + " EXTRA body {0} action {1} dir {2}: managed has {3}x{4}, vendored has none\n", + body, action, direction, cw, ch); + + continue; + } + + if (!haveCand && haveOrc) + { + missed++; + + if (shown++ < MaxShown) + detail.AppendFormat(CultureInfo.InvariantCulture, + " MISSED body {0} action {1} dir {2}: vendored has {3}x{4}, managed has none\n", + body, action, direction, ow, oh); + + continue; + } + + resolved++; + + int diffAt = -1; + + if (cw == ow && ch == oh && SamePixels(cand, orc, out diffAt)) + { + matched++; + } + else + { + mismatched++; + + if (shown++ < MaxShown) + { + if (cw != ow || ch != oh) + detail.AppendFormat(CultureInfo.InvariantCulture, + " DIM body {0} action {1} dir {2}: managed {3}x{4} vs vendored {5}x{6}\n", + body, action, direction, cw, ch, ow, oh); + else + detail.AppendFormat(CultureInfo.InvariantCulture, + " PIXEL body {0} action {1} dir {2}: {3}x{4}, first diff at {5}: managed {6:X4} vs vendored {7:X4}\n", + body, action, direction, cw, ch, diffAt, + cand[diffAt], orc[diffAt]); + } + } + } + } + } + } + + var sb = new StringBuilder(); + sb.AppendLine("[Bridge] legacy anim GDI+-free parity (servuo-plugins #39)"); + + if (oracle == null) + { + sb.AppendLine(" no oracle supplied"); + } + else if (candidateOnly > 0 && matched == 0 && mismatched == 0) + { + sb.AppendFormat(CultureInfo.InvariantCulture, + " oracle unavailable (GDI+ NotImplemented — a Linux/Mono host): the managed path produced {0} sprites\n", + candidateOnly); + } + else + { + sb.AppendFormat(CultureInfo.InvariantCulture, + " compared {0} matched {1} MISMATCHED {2} MISSED {3} EXTRA {4} (skipped {5} records the Bridge does not serve)\n", + resolved, matched, mismatched, missed, extra, skipped); + sb.AppendLine(mismatched == 0 && missed == 0 && extra == 0 + ? " RESULT: PASS — managed decode is pixel-identical to the vendored path" + : " RESULT: FAIL — see the records below"); + } + + if (detail.Length > 0) + { + sb.AppendLine(" first discrepancies:"); + sb.Append(detail); + } + + return sb.ToString(); + } + + private static bool SamePixels(ushort[] a, ushort[] b, out int diffAt) + { + diffAt = -1; + + if (a == null || b == null || a.Length != b.Length) + { + diffAt = 0; + return false; + } + + for (int i = 0; i < a.Length; i++) + { + if (a[i] != b[i]) + { + diffAt = i; + return false; + } + } + + return true; } // ── player bodies (§5.2) ───────────────────────────────────────────────────────────── diff --git a/overlay/Scripts/Custom/Bridge/BridgeHue.cs b/overlay/Scripts/Custom/Bridge/BridgeHue.cs new file mode 100644 index 0000000..abd9025 --- /dev/null +++ b/overlay/Scripts/Custom/Bridge/BridgeHue.cs @@ -0,0 +1,81 @@ +using Ultima; + +namespace Server.Custom.Bridge +{ + /// + /// **Hue application without GDI+** (servuo-plugins #39). The vendored + /// Ultima.Hue.ApplyTo(Bitmap, onlyHueGrayPixels) locks a 16bpp Bitmap and + /// repaints it in place, so the catalogue's body.def-hued creatures (162 Body.def + /// entries carry a non-zero hue) go back through libgdiplus after + /// has already escaped it. This reproduces ApplyTo over a + /// contiguous ARGB1555 ushort[] instead — same arithmetic, no Bitmap. + /// + /// The colour table is still the vendored one: Ultima.Hues.List[index].Colors is a + /// short[32] read from hues.mul with no System.Drawing, so reusing it + /// guarantees the managed path and the vendored path tint a pixel to the identical value. + /// + public static class BridgeHue + { + /// + /// Repaints each non-transparent pixel to colors[(pixel >> 10) & 0x1F] + /// — the pixel's own red channel chooses the entry on the 32-step ramp, exactly as + /// Hue.ApplyTo. In gray-only mode only pixels whose three channels are equal are + /// touched; everything else is left alone. The buffer is contiguous (no stride), so + /// there is no row padding to skip. + /// + public static void Apply(ushort[] pixels, short[] colors, bool onlyGray) + { + if (pixels == null || colors == null) + return; + + for (int i = 0; i < pixels.Length; i++) + { + int c = pixels[i]; + + if (c == 0) + continue; + + if (onlyGray) + { + int r = (c >> 10) & 0x1F; + int g = (c >> 5) & 0x1F; + int b = c & 0x1F; + + if (r == g && r == b) + pixels[i] = (ushort)colors[(c >> 10) & 0x1F]; + } + else + { + pixels[i] = (ushort)colors[(c >> 10) & 0x1F]; + } + } + } + + /// + /// The hue-object selection GetAnimation does (Animations.cs 474-487) before it + /// applies one: the 0x8000 bit of the raw hue is the "only gray pixels" flag, the low + /// 14 bits minus one are the Hues.List index, and an out-of-range index means no + /// hue at all. Returns the colour table to hand to . + /// + public static bool Resolve(int rawHue, out short[] colors, out bool onlyGray) + { + colors = null; + onlyGray = (rawHue & 0x8000) != 0; + + int index = (rawHue & 0x3FFF) - 1; + + if (index >= 0 && index < Hues.List.Length) + { + Hue hue = Hues.List[index]; + + if (hue != null) + { + colors = hue.Colors; + return colors != null; + } + } + + return false; + } + } +} diff --git a/overlay/Scripts/Custom/Bridge/BridgeMul.cs b/overlay/Scripts/Custom/Bridge/BridgeMul.cs new file mode 100644 index 0000000..084ce56 --- /dev/null +++ b/overlay/Scripts/Custom/Bridge/BridgeMul.cs @@ -0,0 +1,178 @@ +using System; + +namespace Server.Custom.Bridge +{ + /// + /// **The legacy-MUL animation reader** (servuo-plugins #39): the half of the GDI+-free + /// migration that left undone. §4.4 moved the UOP path off + /// System.Drawing because libgdiplus was archived in March 2025; this does the same + /// for anim*.mul, and for a sharper reason — on a Linux/Mono shard the vendored + /// Ultima.Frame ctor asks libgdiplus to create a 16bpp Bitmap + /// (Settings.PixelFormat) and libgdiplus answers NotImplemented, so the whole + /// catalogue's legacy art fails before a single pixel is read. + /// + /// This decodes the same bytes Ultima.Frame does, into an ARGB1555 ushort[] + /// with no Bitmap anywhere, for to encode. The + /// run loop is Frame's (Animations.cs), with the two bounds it does not have — + /// exactly as added them to the UOP run loop: a run + /// that would leave the canvas, or read past the record, refuses the frame rather than + /// writing through a raw pointer the way the library does. + /// + /// ── **Legacy layout vs UOP** ── + /// + /// The pixel format is identical (shared palette of ARGB1555, DoubleXor run headers, + /// the 0x7FFF7FFF terminator), but the container is not. A legacy record is a single + /// shared palette of 0x100 entries at the very start, then a frame count and a lookup + /// table, then the frames; a UOP record carries a per-frame palette after each + /// frame's header. So this reads the palette once and seeks the first frame through the + /// lookup table — it does not reuse 's offset math. + /// + public static class BridgeMul + { + /// The xor Ultima.Frame applies to every run header, and so must this. + private const int DoubleXor = (0x200 << 22) | (0x200 << 12); + + /// The shared palette: 0x100 ARGB1555 entries at the head of every record. + private const int PaletteBytes = 0x100 * 2; + + /// + /// Decodes the first frame of a legacy animation record (what a + /// FirstFrame: true GetAnimation call produces) into ARGB1555. + /// + /// is the raw record, verdata-patched, exactly as + /// hands it over — this + /// reads bytes only, never a stream, so every bound is a bound on a known array length. + /// A 0x0 frame returns false with set, which is how the + /// vendored ctor treats it too (an early return, not damage). + /// + public static bool TryDecodeFirstFrame(byte[] record, out ushort[] argb1555, + out int width, out int height, out bool empty, out string reason) + { + argb1555 = null; + width = 0; + height = 0; + empty = false; + reason = null; + + if (record == null || record.Length < PaletteBytes + 4) + { + reason = "record is too short to hold a palette and frame count"; + return false; + } + + var palette = new ushort[0x100]; + + for (int i = 0; i < 0x100; i++) + { + // The library's own xor: the stored entry has its alpha bit clear and every + // palette colour is opaque. A pixel no run covers stays zero, which is the + // sprite's transparent background. + palette[i] = (ushort)(BitConverter.ToUInt16(record, i * 2) ^ 0x8000); + } + + int start = PaletteBytes; // GetAnimation's `start`, after the palette + int frameCount = BitConverter.ToInt32(record, start); + + if (frameCount <= 0 || frameCount > BridgeAssetValidator.MaxAnimFrames) + { + reason = "record declares " + frameCount + " frames"; + return false; + } + + // Only the first frame is decoded, so only its lookup slot has to be inside the record. + int lookupAt = start + 4; + + if ((long)lookupAt + 4 > record.Length) + { + reason = "frame lookup table runs past the record"; + return false; + } + + long frameAt = (long)start + BitConverter.ToInt32(record, lookupAt); + + // The frame header is xCenter(i16), yCenter(i16), width(u16), height(u16) = 8 bytes. + if (frameAt < 0 || frameAt + 8 > record.Length) + { + reason = "frame points outside the record"; + return false; + } + + int at = (int)frameAt; + + int xCenter = BitConverter.ToInt16(record, at); + int yCenter = BitConverter.ToInt16(record, at + 2); + int w = BitConverter.ToUInt16(record, at + 4); + int h = BitConverter.ToUInt16(record, at + 6); + + if (w == 0 || h == 0) + { + // No art, exactly as Frame's ctor returns early on width==0 || height==0. + empty = true; + reason = "frame is " + w + "x" + h; + return false; + } + + if (w > BridgeAssetValidator.MaxArtDimension || h > BridgeAssetValidator.MaxArtDimension) + { + reason = "frame declares " + w + "x" + h; + return false; + } + + var canvas = new ushort[w * h]; + + int p = at + 8; + + int xBase = xCenter - 0x200; + int yBase = (yCenter + h) - 0x200; + + while (true) + { + if (p + 4 > record.Length) + { + reason = "frame has no terminator inside the record"; + return false; + } + + int header = BitConverter.ToInt32(record, p); + p += 4; + + if (header == 0x7FFF7FFF) + break; + + header ^= DoubleXor; + + int x = ((header >> 22) & 0x3FF) + xBase; + int y = ((header >> 12) & 0x3FF) + yBase; + int run = header & 0xFFF; + + if (run == 0) + continue; + + if (p + run > record.Length) + { + reason = "frame has a run past the end of the record"; + return false; + } + + if (y < 0 || y >= h || x < 0 || x + run > w) + { + reason = "frame has a run at " + x + "," + y + " of " + run + + " outside " + w + "x" + h; + return false; + } + + int cursor = (y * w) + x; + + for (int i = 0; i < run; i++) + canvas[cursor + i] = palette[record[p + i]]; + + p += run; + } + + argb1555 = canvas; + width = w; + height = h; + return true; + } + } +} -- 2.49.1