Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 01561683d1 | |||
| cac66a6b83 | |||
| db87b20fae | |||
| 5dd5780f42 |
225
overlay/Scripts/Custom/Bridge/BridgeAnimParity.cs
Normal file
225
overlay/Scripts/Custom/Bridge/BridgeAnimParity.cs
Normal file
@@ -0,0 +1,225 @@
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// **The #39 merge gate**: the GM command <c>[BridgeAnimParity]</c>, which proves the new
|
||||
/// GDI+-free legacy decode (<see cref="BridgeMul"/> + <see cref="BridgeHue"/>, driven by
|
||||
/// <see cref="BridgeCatalog.RunAnimParity"/>) is pixel-identical to the vendored
|
||||
/// <c>Ultima.Frame</c> path it replaces.
|
||||
///
|
||||
/// This is the one file left that still touches <c>System.Drawing</c>, and it does so only
|
||||
/// to be the <b>oracle</b>: on Windows it runs the vendored <c>GetAnimation</c>, 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
|
||||
/// <c>NotImplemented</c> (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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The vendored decode for one key, read back to ARGB1555. False with
|
||||
/// <paramref name="available"/> still true means "no art here"; false with it set false
|
||||
/// means the vendored path cannot run at all on this host (libgdiplus
|
||||
/// <c>NotImplemented</c>), which is exactly the #39 fault and tells the harness to stop
|
||||
/// asking the oracle.
|
||||
/// </summary>
|
||||
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 6.1 cannot create/lock the 16bpp bitmap — the #39 condition itself.
|
||||
available = false;
|
||||
return false;
|
||||
}
|
||||
catch (DllNotFoundException)
|
||||
{
|
||||
// No libgdiplus at all on this host: System.Drawing cannot run. Oracle unavailable.
|
||||
available = false;
|
||||
return false;
|
||||
}
|
||||
catch (TypeInitializationException)
|
||||
{
|
||||
// The System.Drawing static ctor failed (usually wrapping the DllNotFoundException).
|
||||
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.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a 16bpp ARGB1555 bitmap into a <c>ushort[]</c> with <c>Marshal.Copy</c> — no
|
||||
/// <c>unsafe</c> block, the same read <see cref="BridgeArtParity"/> makes of its oracle.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
@@ -51,19 +50,26 @@ namespace Server.Custom.Bridge
|
||||
/// the same trade §2.1 already refused. So hue is part of the key, and the key is resolved
|
||||
/// where the files are.
|
||||
///
|
||||
/// ── **The trap this phase existed to find** ──
|
||||
/// ── **The trap this phase existed to find, and why it is gone** ──
|
||||
///
|
||||
/// <c>Art.GetStatic</c> memoises into a static <c>Bitmap[0xFFFF]</c> and returns **the same
|
||||
/// instance** every time; <c>Hue.ApplyTo</c> repaints a bitmap **in place**. Hue a static
|
||||
/// once and the library's own copy is hued from then on — the plain key comes back hued,
|
||||
/// and the next hue stacks on the last. It is §4.5's failure mode (a confident, plausible,
|
||||
/// wrong picture that every success count agrees with) reached through a door §4.5 never
|
||||
/// looked at, because phase 0 was auditing *records* and this is the library's *cache*.
|
||||
/// The hue is applied in place, and the picture it is applied to must be this call's alone.
|
||||
/// The vendored path made that hard: <c>Art.GetStatic</c> memoised into a static
|
||||
/// <c>Bitmap[0xFFFF]</c> and returned **the same instance** every time, while
|
||||
/// <c>Hue.ApplyTo</c> repainted a bitmap **in place** — so hueing a static once left the
|
||||
/// library's own copy hued from then on, the plain key came back hued, and the next hue
|
||||
/// stacked on the last. It was §4.5's failure mode (a confident, plausible, wrong picture
|
||||
/// that every success count agrees with) reached through the library's *cache* rather than
|
||||
/// a *record*. Phase 5 defused it by turning <c>Files.CacheData</c> off for the process and
|
||||
/// re-checking that invariant before every hue.
|
||||
///
|
||||
/// <see cref="BridgeAssets.Initialize"/> turns <c>Files.CacheData</c> off for the life of
|
||||
/// the process, which makes every bitmap this file receives its own. That invariant is
|
||||
/// load-bearing enough that <see cref="Render"/> **re-checks it** before applying a hue and
|
||||
/// refuses rather than risk it: an invariant nothing verifies is a comment.
|
||||
/// As of #39 PR 2 the trap cannot be set at all: <see cref="BridgeArtMul"/> decodes each key
|
||||
/// into **its own fresh <c>ushort[]</c>** off the raw record (no <c>Bitmap</c>, no library
|
||||
/// cache), and <see cref="BridgeHue.Apply"/> repaints that private buffer, so the plain key
|
||||
/// and the hued key never share pixels no matter what <c>Files.CacheData</c> says. The whole
|
||||
/// path is GDI+-free, which is the point — a Linux/Mono shard serves item and land art it
|
||||
/// could not decode before. (<see cref="BridgeAssets.Initialize"/> still turns
|
||||
/// <c>Files.CacheData</c> off, now only so the <c>[BridgeArtParity]</c> oracle's vendored
|
||||
/// decode hands back fresh bitmaps.)
|
||||
///
|
||||
/// ── **What is validated, and against what** ──
|
||||
///
|
||||
@@ -161,18 +167,11 @@ namespace Server.Custom.Bridge
|
||||
/// </summary>
|
||||
private static void ReplyFetch(string reqId, List<string> keys, string expected, string cursor)
|
||||
{
|
||||
string imagingReason;
|
||||
|
||||
if (!BridgeAssets.ImagingOk(out imagingReason))
|
||||
{
|
||||
// §17.9: a flat refusal, not a partial answer. Every picture in this family needs
|
||||
// a decoder that goes through GDI+, so there is no half of it to serve.
|
||||
BridgeAssets.Fail(reqId, "UNAVAILABLE",
|
||||
"this shard host cannot render images - Mono's System.Drawing needs "
|
||||
+ "libgdiplus. (" + imagingReason + ")");
|
||||
return;
|
||||
}
|
||||
|
||||
// No imaging gate (servuo-plugins #39, PR 2): item and land art now decode through the
|
||||
// managed BridgeArtMul -> BridgeHue -> BridgePng path, with no System.Drawing anywhere,
|
||||
// so a Linux/Mono host with no libgdiplus serves this family exactly as Windows does.
|
||||
// The flat NO_IMAGING refusal this family carried until #39 is gone with the GDI+ it
|
||||
// guarded.
|
||||
string id = SourceId();
|
||||
|
||||
if (BridgeAssets.CatalogMismatch(expected, id))
|
||||
@@ -363,90 +362,23 @@ namespace Server.Custom.Bridge
|
||||
if (!TryParseKey(key, out land, out id, out hue))
|
||||
return Unsupported(key, "not a key this shard serves");
|
||||
|
||||
FileIndex index = readers.Index;
|
||||
|
||||
if (index == null || index.Index == null)
|
||||
return Absent(key, "this shard has no art file");
|
||||
|
||||
int at = land ? id : StaticBase + id;
|
||||
|
||||
if (at < 0 || at >= index.Index.Length)
|
||||
return Unsupported(key, "id " + id + " is past the end of this client's art index");
|
||||
|
||||
ushort[] pixels;
|
||||
int width, height;
|
||||
bool partial, decodeRefused;
|
||||
string reason;
|
||||
|
||||
BridgeAssetValidator.Verdict verdict =
|
||||
BridgeAssetValidator.CheckEntry(index, at, readers.DataLength, readers.VerdataLength, out reason);
|
||||
ArtOutcome outcome = TryArtPixels(readers, land, id, at, hue,
|
||||
out pixels, out width, out height, out partial, out decodeRefused, out reason);
|
||||
|
||||
if (verdict == BridgeAssetValidator.Verdict.Absent)
|
||||
{
|
||||
// The 9,962 statics and 12,140 land tiles of §4.5: an index entry that reads
|
||||
// `lookup 0, length 0`, which the library treats as a hit and answers with the
|
||||
// previous asset's pixels. Absent is the true answer and the only safe one.
|
||||
return Absent(key, reason);
|
||||
}
|
||||
|
||||
if (verdict != BridgeAssetValidator.Verdict.Ok)
|
||||
{
|
||||
// A damaged record rather than a missing one. Still absent to the website — there
|
||||
// is no picture either way — but the reason is worth carrying, because this one an
|
||||
// operator can act on.
|
||||
Console.WriteLine("[Bridge] art: {0} refused: {1}", key, reason);
|
||||
return Absent(key, reason);
|
||||
}
|
||||
|
||||
if (land)
|
||||
{
|
||||
if (!BridgeAssetValidator.LandLengthSane(index, at, out reason))
|
||||
{
|
||||
Console.WriteLine("[Bridge] art: {0} refused: {1}", key, reason);
|
||||
return Absent(key, reason);
|
||||
}
|
||||
}
|
||||
else if (readers.Reader == null || !readers.Reader.StaticSane(index, at, out reason))
|
||||
{
|
||||
Console.WriteLine("[Bridge] art: {0} refused: {1}",
|
||||
key, reason ?? "the art record could not be read");
|
||||
|
||||
return Absent(key, reason ?? "the art record could not be read");
|
||||
}
|
||||
|
||||
// A hue is resolved BEFORE anything is decoded, so a bad one costs no pixels and, more
|
||||
// to the point, cannot half-apply to a picture that then gets cached and served.
|
||||
Ultima.Hue applied = null;
|
||||
bool partial = false;
|
||||
|
||||
if (hue > 0)
|
||||
{
|
||||
if (!TryHue(id, hue, out applied, out partial, out reason))
|
||||
if (outcome == ArtOutcome.Unsupported)
|
||||
return Unsupported(key, reason);
|
||||
}
|
||||
|
||||
Bitmap bitmap = land
|
||||
? Art.GetLand(id)
|
||||
// `checkmaxid: false` on purpose (§4.5): the default maps an out-of-range id to 0
|
||||
// and returns ITEM ZERO'S PICTURE. The id is already bounded against the index
|
||||
// that was actually opened, so this can only be loud.
|
||||
: Art.GetStatic(id, false);
|
||||
if (outcome != ArtOutcome.Ok)
|
||||
return Absent(key, reason ?? "the decoder returned no picture");
|
||||
|
||||
// **Whether this bitmap is ours to dispose is the same question as whether it is ours
|
||||
// to hue**, and it has the same answer. With the library's cache off — which
|
||||
// `BridgeAssets.Initialize` guarantees and `TryHue` re-checks — every call decodes a
|
||||
// fresh instance that nothing else holds, so not disposing it would leak one bitmap per
|
||||
// fetched key. With the cache on, that instance is the library's own copy and disposing
|
||||
// it would leave a disposed `Bitmap` in a static array for the next caller to fault on.
|
||||
// Both mistakes are silent; the flag decides, once, here.
|
||||
bool owned = !Files.CacheData;
|
||||
|
||||
try
|
||||
{
|
||||
if (bitmap == null || bitmap.Width <= 0 || bitmap.Height <= 0)
|
||||
return Absent(key, "the decoder returned no picture");
|
||||
|
||||
if (applied != null)
|
||||
applied.ApplyTo(bitmap, partial);
|
||||
|
||||
byte[] png = BridgeAssets.BitmapToPng(bitmap);
|
||||
byte[] png = BridgePng.FromArgb1555(pixels, width, height);
|
||||
|
||||
if (png == null)
|
||||
return Absent(key, "the picture could not be encoded");
|
||||
@@ -457,32 +389,151 @@ namespace Server.Custom.Bridge
|
||||
Status = "ok",
|
||||
Sha256 = BridgeAssets.Sha256Hex(png),
|
||||
Png = png,
|
||||
Width = bitmap.Width,
|
||||
Height = bitmap.Height,
|
||||
Width = width,
|
||||
Height = height,
|
||||
Hue = hue,
|
||||
PartialHue = partial,
|
||||
Source = readers.Source
|
||||
};
|
||||
}
|
||||
finally
|
||||
|
||||
private enum ArtOutcome { Ok, Absent, Unsupported }
|
||||
|
||||
/// <summary>
|
||||
/// The gate, the managed decode and the hue for one art key, to a hued ARGB1555 buffer:
|
||||
/// the exact path <see cref="Render"/> encodes and <see cref="RunArtParity"/> proves, so
|
||||
/// a green parity run is evidence about the code that ships rather than a copy of it.
|
||||
///
|
||||
/// <paramref name="at"/> is the index entry — a land id, or <c>0x4000 + id</c> for a
|
||||
/// static. <see cref="ArtOutcome.Unsupported"/> is a key this shard does not serve (a
|
||||
/// hue it cannot resolve, an id past the index); <see cref="ArtOutcome.Absent"/> is a
|
||||
/// key it serves but has no picture for (the §4.5 phantoms, a damaged record, a 0×0
|
||||
/// static); <see cref="ArtOutcome.Ok"/> fills <paramref name="pixels"/>.
|
||||
/// </summary>
|
||||
private static ArtOutcome TryArtPixels(Readers readers, bool land, int id, int at, int hue,
|
||||
out ushort[] pixels, out int width, out int height, out bool partial,
|
||||
out bool decodeRefused, out string reason)
|
||||
{
|
||||
if (owned && bitmap != null)
|
||||
bitmap.Dispose();
|
||||
pixels = null;
|
||||
width = 0;
|
||||
height = 0;
|
||||
partial = false;
|
||||
decodeRefused = false;
|
||||
reason = null;
|
||||
|
||||
FileIndex index = readers.Index;
|
||||
|
||||
if (index == null || index.Index == null)
|
||||
{
|
||||
reason = "this shard has no art file";
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
if (at < 0 || at >= index.Index.Length)
|
||||
{
|
||||
reason = "id " + id + " is past the end of this client's art index";
|
||||
return ArtOutcome.Unsupported;
|
||||
}
|
||||
|
||||
BridgeAssetValidator.Verdict verdict =
|
||||
BridgeAssetValidator.CheckEntry(index, at, readers.DataLength, readers.VerdataLength, out reason);
|
||||
|
||||
if (verdict == BridgeAssetValidator.Verdict.Absent)
|
||||
{
|
||||
// The 9,962 statics and 12,140 land tiles of §4.5: an index entry that reads
|
||||
// `lookup 0, length 0`, which the library treats as a hit and answers with the
|
||||
// previous asset's pixels. Absent is the true answer and the only safe one.
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
if (verdict != BridgeAssetValidator.Verdict.Ok)
|
||||
{
|
||||
// A damaged record rather than a missing one. Still absent to the website — there is
|
||||
// no picture either way — but the reason is worth carrying.
|
||||
Console.WriteLine("[Bridge] art: entry {0} refused: {1}", at, reason);
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
if (land)
|
||||
{
|
||||
if (!BridgeAssetValidator.LandLengthSane(index, at, out reason))
|
||||
{
|
||||
Console.WriteLine("[Bridge] art: land {0} refused: {1}", id, reason);
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
}
|
||||
else if (readers.Reader == null || !readers.Reader.StaticSane(index, at, out reason))
|
||||
{
|
||||
Console.WriteLine("[Bridge] art: static {0} refused: {1}",
|
||||
id, reason ?? "the art record could not be read");
|
||||
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
// A hue is resolved BEFORE anything is decoded, so a bad one costs no pixels and cannot
|
||||
// half-apply to a picture that then gets served.
|
||||
short[] hueColors = null;
|
||||
|
||||
if (hue > 0)
|
||||
{
|
||||
if (!TryHue(id, hue, out hueColors, out partial, out reason))
|
||||
return ArtOutcome.Unsupported;
|
||||
}
|
||||
|
||||
if (readers.Reader == null)
|
||||
{
|
||||
reason = "this shard cannot read the art file";
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
byte[] record = readers.Reader.ReadRecordCopy(index, at, out reason);
|
||||
|
||||
if (record == null)
|
||||
{
|
||||
reason = reason ?? "the art record could not be read";
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
// Raw record bytes -> ARGB1555 ushort[], no System.Drawing (servuo-plugins #39, PR 2).
|
||||
// Each key decodes its own fresh buffer that nothing else holds, so the hue below
|
||||
// repaints a private array — the vendored path's shared-Bitmap aliasing hazard (see the
|
||||
// class summary) cannot occur, and there is nothing to dispose.
|
||||
bool empty = false;
|
||||
|
||||
bool decoded = land
|
||||
? BridgeArtMul.TryDecodeLand(record, out pixels, out width, out height, out reason)
|
||||
: BridgeArtMul.TryDecodeStatic(record, out pixels, out width, out height, out empty, out reason);
|
||||
|
||||
if (!decoded)
|
||||
{
|
||||
// A 0×0 static is no art rather than damage — the vendored decoder returns early on
|
||||
// the same condition — so it is silently absent. Anything else is the managed
|
||||
// decoder refusing a record the gate admitted (a cumulative-column overflow, a run
|
||||
// past the record): worth a line, and — because the vendored path might still render
|
||||
// it — surfaced to the parity harness through `decodeRefused` so it cannot hide in
|
||||
// the skip bucket.
|
||||
if (!empty)
|
||||
{
|
||||
decodeRefused = true;
|
||||
Console.WriteLine("[Bridge] art: {0} {1} refused: {2}", land ? "land" : "static", id, reason);
|
||||
}
|
||||
|
||||
return ArtOutcome.Absent;
|
||||
}
|
||||
|
||||
if (hueColors != null)
|
||||
BridgeHue.Apply(pixels, hueColors, partial);
|
||||
|
||||
return ArtOutcome.Ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves one wire hue onto a ramp, and decides whether it repaints the whole sprite
|
||||
/// or only its grey pixels.
|
||||
///
|
||||
/// Four things have to hold, and every one of them has a way of not holding that
|
||||
/// Three things have to hold, and every one of them has a way of not holding that
|
||||
/// produces a picture rather than an error:
|
||||
///
|
||||
/// **The library's cache is off.** Re-checked here because <c>ApplyTo</c> repaints in
|
||||
/// place: with the cache on, this would edit the copy <c>Art</c> hands to everyone
|
||||
/// else. <see cref="BridgeAssets.Initialize"/> turns it off at boot and this refuses
|
||||
/// if it somehow did not, because the failure is invisible and permanent.
|
||||
///
|
||||
/// **`hues.mul` is present.** When it is missing <c>Hues.Initialize</c> does not throw
|
||||
/// — it fills all 3,000 slots with a <c>new Hue(index)</c> whose ramp is **all zeroes**,
|
||||
/// and applying one of those paints the sprite black. An all-zero ramp is therefore
|
||||
@@ -499,19 +550,12 @@ namespace Server.Custom.Bridge
|
||||
/// **Land has no such flag**, which is why <see cref="TryParseKey"/> does not accept a
|
||||
/// hue on a land key at all rather than guessing a mode for it.
|
||||
/// </summary>
|
||||
private static bool TryHue(int id, int hue, out Ultima.Hue applied, out bool partial, out string reason)
|
||||
private static bool TryHue(int id, int hue, out short[] colors, out bool partial, out string reason)
|
||||
{
|
||||
applied = null;
|
||||
colors = null;
|
||||
partial = false;
|
||||
reason = null;
|
||||
|
||||
if (Files.CacheData)
|
||||
{
|
||||
reason = "this shard's art cache is on, so a hue cannot be applied safely";
|
||||
Console.WriteLine("[Bridge] art: refusing hue {0}: {1}", hue, reason);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hue < 1 || hue > MaxHue)
|
||||
{
|
||||
reason = "hue " + hue + " is outside 1-" + MaxHue;
|
||||
@@ -537,7 +581,7 @@ namespace Server.Custom.Bridge
|
||||
if (!TryPartialHue(id, out partial, out reason))
|
||||
return false;
|
||||
|
||||
applied = candidate;
|
||||
colors = candidate.Colors;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -838,5 +882,269 @@ namespace Server.Custom.Bridge
|
||||
_cache.Id, _cache.ByKey.Count, _cache.Bytes, BridgeConfig.AssetArtCacheBytes);
|
||||
}
|
||||
}
|
||||
|
||||
// ── the #39 PR 2 merge gate: managed decode/hue vs the vendored GDI+ path ──────────────
|
||||
|
||||
/// <summary>
|
||||
/// The vendored decode for one art key, read back to ARGB1555, as the oracle for
|
||||
/// <see cref="RunArtParity"/>. Supplied by <c>BridgeArtParity</c> — the only art file
|
||||
/// that still touches <c>System.Drawing</c> — so this file stays GDI+-free.
|
||||
/// <paramref name="hue"/> is 0 for the decode pass or a wire hue for the hue pass, and
|
||||
/// <paramref name="partial"/> is the mode the shipping path chose (from
|
||||
/// <c>tiledata.mul</c>), so the vendored <c>Hue.ApplyTo</c> tints identically.
|
||||
/// <paramref name="available"/> false means the vendored bitmap cannot run on this host
|
||||
/// (libgdiplus <c>NotImplemented</c> — the very #39 fault), which drops the harness into
|
||||
/// candidate-only (does-it-render) mode for the rest of the walk.
|
||||
/// </summary>
|
||||
public delegate bool ArtParityOracle(bool land, int id, int hue, bool partial,
|
||||
out ushort[] pixels, out int width, out int height, out bool available);
|
||||
|
||||
/// <summary>A real, non-empty hue on every client — the hue pass tints each served static with it.</summary>
|
||||
private const int ParityHue = 33;
|
||||
|
||||
private const int ParityMaxShown = 20;
|
||||
|
||||
private sealed class ParityCounts
|
||||
{
|
||||
public long Resolved, Matched, Mismatched, Missed, Extra, CandidateOnly, Skipped;
|
||||
public readonly StringBuilder Detail = new StringBuilder();
|
||||
public int Shown;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares the shipping managed decode+hue (<see cref="TryArtPixels"/>) against the
|
||||
/// vendored GDI+ path, pixel for pixel, across every served item and land id. The #39
|
||||
/// PR 2 merge gate: on Windows the vendored path is the oracle and every served picture
|
||||
/// must match it; on a Linux/Mono host the oracle is unavailable (the 16bpp
|
||||
/// <c>Bitmap</c> throws <c>NotImplemented</c>) and the harness instead confirms the
|
||||
/// managed path still renders where the art index says it should.
|
||||
///
|
||||
/// Two passes. The first decodes every served static and land id with no hue — the bulk
|
||||
/// parity. The second tints every served static with <see cref="ParityHue"/> in the mode
|
||||
/// its <c>tiledata.mul</c> <c>PartialHue</c> flag dictates, which is the only pass that
|
||||
/// exercises the grey-only branch on the ~13,259 ids that need it. Land takes no hue.
|
||||
/// </summary>
|
||||
public static string RunArtParity(ArtParityOracle oracle)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("[Bridge] item/land art GDI+-free parity (servuo-plugins #39, PR 2)");
|
||||
|
||||
if (oracle == null)
|
||||
{
|
||||
sb.AppendLine(" no oracle supplied");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
using (var readers = new Readers())
|
||||
{
|
||||
FileIndex index = readers.Index;
|
||||
|
||||
if (index == null || index.Index == null)
|
||||
{
|
||||
sb.AppendLine(" this shard has no art index");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// Statics address 0x4000 + id; the addressable ceiling is the smaller of the item
|
||||
// range (0xBFFF) and what this client's index actually holds.
|
||||
int staticMax = Math.Min(0xBFFF, index.Index.Length - StaticBase - 1);
|
||||
|
||||
bool oracleUp = true;
|
||||
|
||||
oracleUp = Walk(sb, "decode (no hue)", readers, oracle, oracleUp, staticMax, false, 0);
|
||||
Walk(sb, "hue " + ParityHue, readers, oracle, oracleUp, staticMax, true, ParityHue);
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One pass: every served static (and, when <paramref name="staticsOnly"/> is false,
|
||||
/// every served land id) at <paramref name="hue"/>, compared against the oracle. Returns
|
||||
/// the oracle's availability so the caller does not keep probing a Linux host that has
|
||||
/// already answered <c>NotImplemented</c> once.
|
||||
/// </summary>
|
||||
private static bool Walk(StringBuilder sb, string label, Readers readers, ArtParityOracle oracle,
|
||||
bool oracleUp, int staticMax, bool staticsOnly, int hue)
|
||||
{
|
||||
var c = new ParityCounts();
|
||||
|
||||
for (int id = 0; id <= staticMax; id++)
|
||||
{
|
||||
if ((id & 0x1FFF) == 0)
|
||||
Console.WriteLine("[Bridge] art parity ({0}): static {1}/{2}", label, id, staticMax);
|
||||
|
||||
oracleUp = Compare(readers, oracle, oracleUp, false, id, StaticBase + id, hue, c);
|
||||
}
|
||||
|
||||
if (!staticsOnly)
|
||||
{
|
||||
for (int id = 0; id < LandCount; id++)
|
||||
oracleUp = Compare(readers, oracle, oracleUp, true, id, id, hue, c);
|
||||
}
|
||||
|
||||
if (c.CandidateOnly > 0 && c.Matched == 0 && c.Mismatched == 0)
|
||||
{
|
||||
sb.AppendFormat(CultureInfo.InvariantCulture,
|
||||
" {0}: oracle unavailable (GDI+ NotImplemented — a Linux/Mono host): the managed path produced {1} pictures\n",
|
||||
label, c.CandidateOnly);
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendFormat(CultureInfo.InvariantCulture,
|
||||
" {0}: compared {1} matched {2} MISMATCHED {3} MISSED {4} EXTRA {5} (skipped {6} ids the Bridge does not serve)\n",
|
||||
label, c.Resolved, c.Matched, c.Mismatched, c.Missed, c.Extra, c.Skipped);
|
||||
sb.AppendLine(c.Mismatched == 0 && c.Missed == 0 && c.Extra == 0
|
||||
? " RESULT: PASS — managed decode is pixel-identical to the vendored path"
|
||||
: " RESULT: FAIL — see the records below");
|
||||
}
|
||||
|
||||
if (c.Detail.Length > 0)
|
||||
{
|
||||
sb.AppendLine(" first discrepancies:");
|
||||
sb.Append(c.Detail);
|
||||
}
|
||||
|
||||
return oracleUp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One key. A key the Bridge gate does not admit a picture for — a §4.5 phantom, a
|
||||
/// damaged record, a 0×0 static, an unresolvable hue — is skipped, not a parity case:
|
||||
/// comparing it against raw <c>Get*</c> (which has no §4.5 gate) would re-measure the
|
||||
/// phantoms the validator exists to stop.
|
||||
///
|
||||
/// But a record the gate ADMITS and the managed decoder then refuses (a cumulative-column
|
||||
/// overflow, a run past the record — conditions <c>StaticSane</c> does not all catch) is
|
||||
/// the one regression this gate exists to find, because the vendored path might still
|
||||
/// render it. <see cref="TryArtPixels"/> flags that case through <c>decodeRefused</c>, and
|
||||
/// it is checked against the oracle and counted <c>MISSED</c> rather than left to hide in
|
||||
/// the skip bucket.
|
||||
/// </summary>
|
||||
private static bool Compare(Readers readers, ArtParityOracle oracle, bool oracleUp,
|
||||
bool land, int id, int at, int hue, ParityCounts c)
|
||||
{
|
||||
ushort[] cand;
|
||||
int cw, ch;
|
||||
bool partial, decodeRefused;
|
||||
string reason;
|
||||
|
||||
if (TryArtPixels(readers, land, id, at, hue,
|
||||
out cand, out cw, out ch, out partial, out decodeRefused, out reason)
|
||||
!= ArtOutcome.Ok)
|
||||
{
|
||||
// The gate admitted the record but the managed decoder refused it: the vendored path
|
||||
// may still render it, so this is a MISSED candidate, not a skip.
|
||||
if (decodeRefused && oracleUp)
|
||||
{
|
||||
ushort[] orcM;
|
||||
int owM, ohM;
|
||||
bool availM;
|
||||
|
||||
if (oracle(land, id, hue, partial, out orcM, out owM, out ohM, out availM))
|
||||
{
|
||||
if (!availM)
|
||||
{
|
||||
c.CandidateOnly++;
|
||||
return false;
|
||||
}
|
||||
|
||||
c.Missed++;
|
||||
|
||||
if (c.Shown++ < ParityMaxShown)
|
||||
c.Detail.AppendFormat(CultureInfo.InvariantCulture,
|
||||
" MISSED {0} {1} hue {2}: vendored has {3}x{4}, managed refused ({5})\n",
|
||||
land ? "land" : "static", id, hue, owM, ohM, reason);
|
||||
|
||||
return oracleUp;
|
||||
}
|
||||
|
||||
// Both agree there is no servable art here — not a miss.
|
||||
}
|
||||
|
||||
c.Skipped++;
|
||||
return oracleUp;
|
||||
}
|
||||
|
||||
if (!oracleUp)
|
||||
{
|
||||
c.CandidateOnly++;
|
||||
return oracleUp;
|
||||
}
|
||||
|
||||
ushort[] orc;
|
||||
int ow, oh;
|
||||
bool available;
|
||||
|
||||
bool haveOrc = oracle(land, id, hue, partial, out orc, out ow, out oh, out available);
|
||||
|
||||
if (!available)
|
||||
{
|
||||
// A Linux/Mono host: the vendored bitmap ctor cannot run. Switch to candidate-only.
|
||||
c.CandidateOnly++;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!haveOrc)
|
||||
{
|
||||
c.Extra++;
|
||||
|
||||
if (c.Shown++ < ParityMaxShown)
|
||||
c.Detail.AppendFormat(CultureInfo.InvariantCulture,
|
||||
" EXTRA {0} {1} hue {2}: managed has {3}x{4}, vendored has none\n",
|
||||
land ? "land" : "static", id, hue, cw, ch);
|
||||
|
||||
return oracleUp;
|
||||
}
|
||||
|
||||
c.Resolved++;
|
||||
|
||||
int diffAt = -1;
|
||||
|
||||
if (cw == ow && ch == oh && SamePixels(cand, orc, out diffAt))
|
||||
{
|
||||
c.Matched++;
|
||||
}
|
||||
else
|
||||
{
|
||||
c.Mismatched++;
|
||||
|
||||
if (c.Shown++ < ParityMaxShown)
|
||||
{
|
||||
if (cw != ow || ch != oh)
|
||||
c.Detail.AppendFormat(CultureInfo.InvariantCulture,
|
||||
" DIM {0} {1} hue {2}: managed {3}x{4} vs vendored {5}x{6}\n",
|
||||
land ? "land" : "static", id, hue, cw, ch, ow, oh);
|
||||
else
|
||||
c.Detail.AppendFormat(CultureInfo.InvariantCulture,
|
||||
" PIXEL {0} {1} hue {2}: {3}x{4}, first diff at {5}: managed {6:X4} vs vendored {7:X4}\n",
|
||||
land ? "land" : "static", id, hue, cw, ch, diffAt, cand[diffAt], orc[diffAt]);
|
||||
}
|
||||
}
|
||||
|
||||
return oracleUp;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
223
overlay/Scripts/Custom/Bridge/BridgeArtMul.cs
Normal file
223
overlay/Scripts/Custom/Bridge/BridgeArtMul.cs
Normal file
@@ -0,0 +1,223 @@
|
||||
using System;
|
||||
|
||||
namespace Server.Custom.Bridge
|
||||
{
|
||||
/// <summary>
|
||||
/// **The item-and-land art reader** (servuo-plugins #39, PR 2): the half of the GDI+-free
|
||||
/// migration <see cref="BridgeMul"/> (animations) and <see cref="BridgeUop"/> (UOP bodies)
|
||||
/// left for the art plane. On a Linux/Mono shard the vendored <c>Ultima.Art.LoadStatic</c>
|
||||
/// and <c>LoadLand</c> build a 16bpp <c>Bitmap</c> (<c>Settings.PixelFormat</c>) and
|
||||
/// libgdiplus 6.1 answers <c>NotImplemented</c>, so every item and land picture the Asset
|
||||
/// Bridge serves fails before a pixel is read. This decodes the same bytes into an ARGB1555
|
||||
/// <c>ushort[]</c> with no <c>Bitmap</c> anywhere, for <see cref="BridgePng.FromArgb1555"/>
|
||||
/// to encode and <see cref="BridgeHue"/> to tint.
|
||||
///
|
||||
/// ── **Faithful to the vendored run loops, with the bounds they lack** ──
|
||||
///
|
||||
/// <c>LoadStatic</c>'s inner loop advances a raw pointer by a run header's
|
||||
/// <c>(xOffset, xRun)</c> pair and writes <c>xRun</c> palette-less ARGB1555 pixels
|
||||
/// (<c>stored ^ 0x8000</c>), stopping a row on the <c>(0,0)</c> terminator or when a pair
|
||||
/// would leave the scanline. It guards neither the read cursor nor the write against the
|
||||
/// record — <see cref="BridgeAssetValidator.StaticRecordSane"/> is the shipped gate that
|
||||
/// walks the same table bounded, and this reader re-checks every read and every write
|
||||
/// against the known array length anyway rather than writing through a pointer the way the
|
||||
/// library does. Two behaviours differ from a raw pointer, and they differ from each other:
|
||||
///
|
||||
/// - **Row-stop (truncate).** `xOffset > width` or `xOffset + xRun > width` *stops the row*
|
||||
/// and moves on — exactly what <c>LoadStatic</c> does against the padded 16bpp stride
|
||||
/// (`delta`), and what <c>StaticRecordSane</c> does against `width`. Because this reader
|
||||
/// bounds against the real `width` rather than `delta`, the two can differ by one case: a
|
||||
/// run whose last pixel lands in a scanline's invisible pad column (only possible for an
|
||||
/// odd width) — the library writes it into the pad, this truncates the row. No record this
|
||||
/// client's own packer produces reaches it, and the pixel is invisible either way.
|
||||
/// - **Canvas-overflow (refuse).** If the cumulative column plus a run would cross into the
|
||||
/// next scanline (`col + xRun > width`), the library bleeds a visible run into the next
|
||||
/// row through its pointer; this *refuses the whole record* (returns false). A refusal is
|
||||
/// surfaced to the merge-gate harness as a possible miss rather than silently dropped.
|
||||
///
|
||||
/// <c>LoadLand</c> is fixed geometry: a 44×44 diamond of 1,012 stored ARGB1555 values
|
||||
/// (<c>stored | 0x8000</c>), two triangular halves, read straight off the record with no run
|
||||
/// headers. <see cref="BridgeAssetValidator.LandLengthSane"/> guarantees the 2,024 bytes the
|
||||
/// vendored reader consumes regardless of the declared length are present.
|
||||
/// </summary>
|
||||
public static class BridgeArtMul
|
||||
{
|
||||
/// <summary>
|
||||
/// Decodes one static item record (<c>art.mul</c> / <c>artLegacyMUL.uop</c>) into
|
||||
/// ARGB1555. <paramref name="record"/> is the raw, verdata-patched record exactly as
|
||||
/// <see cref="BridgeAssetValidator.RecordReader.ReadRecordCopy"/> hands it over.
|
||||
///
|
||||
/// Returns false with <paramref name="empty"/> set for a 0×0 (or non-positive) record —
|
||||
/// the same early return <c>LoadStatic</c> makes before it builds a bitmap, which the
|
||||
/// Bridge treats as "no picture here" rather than damage. Any other false is a record
|
||||
/// this reader refused, with <paramref name="reason"/> set.
|
||||
/// </summary>
|
||||
public static bool TryDecodeStatic(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;
|
||||
|
||||
// The 8-byte header: a 4-byte flag, then width and height as ushorts.
|
||||
if (record == null || record.Length < 8)
|
||||
{
|
||||
reason = "static record is too short to hold an 8-byte header";
|
||||
return false;
|
||||
}
|
||||
|
||||
int w = BitConverter.ToUInt16(record, 4);
|
||||
int h = BitConverter.ToUInt16(record, 6);
|
||||
|
||||
// LoadStatic returns null here rather than misbehaving: no art, not damage.
|
||||
if (w <= 0 || h <= 0)
|
||||
{
|
||||
empty = true;
|
||||
reason = "static is " + w + "x" + h;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (w > BridgeAssetValidator.MaxArtDimension || h > BridgeAssetValidator.MaxArtDimension)
|
||||
{
|
||||
reason = "static declares " + w + "x" + h;
|
||||
return false;
|
||||
}
|
||||
|
||||
int words = record.Length / 2;
|
||||
|
||||
// The row-lookup table: h ushorts starting at word 4.
|
||||
if (4 + h > words)
|
||||
{
|
||||
reason = "row table (" + h + " entries) does not fit in a " + record.Length + "-byte record";
|
||||
return false;
|
||||
}
|
||||
|
||||
int start = h + 4;
|
||||
var canvas = new ushort[w * h];
|
||||
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
// GetStatic's `lookups[y] = start + bindata[4 + y]`, in ushort units.
|
||||
int count = start + BitConverter.ToUInt16(record, (4 + y) * 2);
|
||||
int rowBase = y * w;
|
||||
int col = 0; // cur - line, in pixels — cumulative across this row's pairs
|
||||
|
||||
while (true)
|
||||
{
|
||||
// Two ushorts for the run header, both inside the record.
|
||||
if (count < 0 || count + 1 >= words)
|
||||
{
|
||||
reason = "row " + y + " reads at word " + count + ", past the record's " + words;
|
||||
return false;
|
||||
}
|
||||
|
||||
int xOffset = BitConverter.ToUInt16(record, count * 2);
|
||||
int xRun = BitConverter.ToUInt16(record, (count + 1) * 2);
|
||||
count += 2;
|
||||
|
||||
// The (0,0) terminator LoadStatic stops the row on.
|
||||
if (xOffset + xRun == 0)
|
||||
break;
|
||||
|
||||
// LoadStatic stops the row here (against the scanline); the read cursor stops
|
||||
// with it. StaticRecordSane makes the identical test against width.
|
||||
if (xOffset > w || xOffset + xRun > w)
|
||||
break;
|
||||
|
||||
col += xOffset;
|
||||
|
||||
// The run's pixels must be inside the record...
|
||||
if (count + xRun > words)
|
||||
{
|
||||
reason = "row " + y + " declares a " + xRun + "-pixel run running past the record";
|
||||
return false;
|
||||
}
|
||||
|
||||
// ...and inside the row. The vendored writer bounds each pair but not the
|
||||
// cumulative column; no record this client packs crosses the scanline, and one
|
||||
// that did would have the library bleed into the next row rather than refuse.
|
||||
if (col < 0 || col + xRun > w)
|
||||
{
|
||||
reason = "row " + y + " writes a run to column " + col + "+" + xRun + ", past " + w;
|
||||
return false;
|
||||
}
|
||||
|
||||
int at = rowBase + col;
|
||||
|
||||
for (int i = 0; i < xRun; i++)
|
||||
canvas[at + i] = (ushort)(BitConverter.ToUInt16(record, (count + i) * 2) ^ 0x8000);
|
||||
|
||||
count += xRun;
|
||||
col += xRun;
|
||||
}
|
||||
}
|
||||
|
||||
argb1555 = canvas;
|
||||
width = w;
|
||||
height = h;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The land diamond is always 44×44 — <c>LoadLand</c> hard-codes it.</summary>
|
||||
private const int LandSize = 44;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes one land tile record into a 44×44 ARGB1555 diamond, mirroring
|
||||
/// <c>LoadLand</c>: two triangular halves of stored values, <c>stored | 0x8000</c>, read
|
||||
/// straight off the record. The four corners outside the diamond are never written and
|
||||
/// stay transparent, exactly as the vendored fresh bitmap leaves them.
|
||||
/// </summary>
|
||||
public static bool TryDecodeLand(byte[] record, out ushort[] argb1555,
|
||||
out int width, out int height, out string reason)
|
||||
{
|
||||
argb1555 = null;
|
||||
width = 0;
|
||||
height = 0;
|
||||
reason = null;
|
||||
|
||||
// LoadLand reads 2,024 bytes whatever the declared length; LandLengthSane is the gate
|
||||
// that refuses a shorter record, and this re-states the bound on the known array.
|
||||
if (record == null || record.Length < BridgeAssetValidator.LandRecordBytes)
|
||||
{
|
||||
reason = "land record is "
|
||||
+ (record == null ? 0 : record.Length)
|
||||
+ " bytes; LoadLand always reads " + BridgeAssetValidator.LandRecordBytes;
|
||||
return false;
|
||||
}
|
||||
|
||||
var canvas = new ushort[LandSize * LandSize];
|
||||
int src = 0; // byte offset of the next stored ushort
|
||||
|
||||
// Top half: rows 0..21 widen from 2 to 44, centred.
|
||||
int xOffset = 21;
|
||||
int xRun = 2;
|
||||
|
||||
for (int y = 0; y < 22; y++, xOffset--, xRun += 2)
|
||||
{
|
||||
int at = (y * LandSize) + xOffset;
|
||||
|
||||
for (int i = 0; i < xRun; i++, src += 2)
|
||||
canvas[at + i] = (ushort)(BitConverter.ToUInt16(record, src) | 0x8000);
|
||||
}
|
||||
|
||||
// Bottom half: rows 22..43 narrow from 44 back to 2.
|
||||
xOffset = 0;
|
||||
xRun = 44;
|
||||
|
||||
for (int y = 22; y < 44; y++, xOffset++, xRun -= 2)
|
||||
{
|
||||
int at = (y * LandSize) + xOffset;
|
||||
|
||||
for (int i = 0; i < xRun; i++, src += 2)
|
||||
canvas[at + i] = (ushort)(BitConverter.ToUInt16(record, src) | 0x8000);
|
||||
}
|
||||
|
||||
argb1555 = canvas;
|
||||
width = LandSize;
|
||||
height = LandSize;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
235
overlay/Scripts/Custom/Bridge/BridgeArtParity.cs
Normal file
235
overlay/Scripts/Custom/Bridge/BridgeArtParity.cs
Normal file
@@ -0,0 +1,235 @@
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// **The #39 PR 2 merge gate**: the GM command <c>[BridgeArtParity]</c>, which proves the
|
||||
/// new GDI+-free item/land decode (<see cref="BridgeArtMul"/> + <see cref="BridgeHue"/>,
|
||||
/// driven by <see cref="BridgeArt.RunArtParity"/>) is pixel-identical to the vendored
|
||||
/// <c>Ultima.Art</c> + <c>Hue.ApplyTo</c> path it replaces.
|
||||
///
|
||||
/// Like <see cref="BridgeAnimParity"/> for the catalogue, this is the one art file that
|
||||
/// still touches <c>System.Drawing</c>, and it does so only to be the <b>oracle</b>: on
|
||||
/// Windows it runs the vendored <c>Art.GetStatic</c>/<c>GetLand</c> (and, for the hue pass,
|
||||
/// <c>Hue.ApplyTo</c>), 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 <c>NotImplemented</c> (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.
|
||||
/// </summary>
|
||||
public static class BridgeArtParity
|
||||
{
|
||||
public static void Initialize()
|
||||
{
|
||||
CommandSystem.Register("BridgeArtParity", AccessLevel.Administrator, OnCommand);
|
||||
|
||||
// Headless gate run (servuo-plugins #39): with BRIDGE_ART_PARITY=1 in the environment,
|
||||
// run the parity once the world is up and write parity-art.txt, no client needed. For
|
||||
// verification/CI only — it is never set on a production shard.
|
||||
if (Environment.GetEnvironmentVariable("BRIDGE_ART_PARITY") == "1")
|
||||
EventSink.ServerStarted += OnServerStartedParity;
|
||||
}
|
||||
|
||||
private static void OnServerStartedParity()
|
||||
{
|
||||
Console.WriteLine("[Bridge] art parity: BRIDGE_ART_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 item/land art GDI+ parity across the art index — the shard will pause for a bit.");
|
||||
|
||||
Console.WriteLine("[Bridge] art parity: starting");
|
||||
|
||||
string report;
|
||||
|
||||
try
|
||||
{
|
||||
report = BridgeArt.RunArtParity(Oracle);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
report = "[Bridge] art parity crashed: " + ex;
|
||||
}
|
||||
|
||||
Console.WriteLine(report);
|
||||
|
||||
string path = null;
|
||||
|
||||
try
|
||||
{
|
||||
path = Path.Combine(Core.BaseDirectory, "parity-art.txt");
|
||||
File.WriteAllText(path, report);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("[Bridge] art parity: cannot write file: " + ex.Message);
|
||||
path = null;
|
||||
}
|
||||
|
||||
if (from != null)
|
||||
{
|
||||
from.SendMessage("Art 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 < 8; i++)
|
||||
{
|
||||
string line = lines[i].TrimEnd();
|
||||
|
||||
if (line.Length > 0)
|
||||
from.SendMessage(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The vendored decode for one art key, hued the way the shipping path chose and read
|
||||
/// back to ARGB1555. False with <paramref name="available"/> still true means "no art
|
||||
/// here"; false with it set false means the vendored path cannot run at all on this host
|
||||
/// (libgdiplus <c>NotImplemented</c>), which is exactly the #39 fault and tells the
|
||||
/// harness to stop asking the oracle.
|
||||
/// </summary>
|
||||
private static bool Oracle(bool land, int id, int hue, bool partial,
|
||||
out ushort[] pixels, out int width, out int height, out bool available)
|
||||
{
|
||||
pixels = null;
|
||||
width = 0;
|
||||
height = 0;
|
||||
available = true;
|
||||
|
||||
Bitmap bmp = null;
|
||||
|
||||
// With Files.CacheData off (BridgeAssets.Initialize guarantees it) GetStatic/GetLand
|
||||
// decode a fresh instance that nothing else holds, so it is ours to hue in place and to
|
||||
// dispose. The managed side's §4.5-equivalent re-check is why this flag is trusted.
|
||||
bool owned = !Files.CacheData;
|
||||
|
||||
try
|
||||
{
|
||||
// `checkmaxid: false` matches the Bridge's own GetStatic call: the id is already
|
||||
// bounded against the opened index, and the default would map an out-of-range id to
|
||||
// item zero's picture.
|
||||
bmp = land ? Art.GetLand(id) : Art.GetStatic(id, false);
|
||||
|
||||
if (bmp == null || bmp.Width <= 0 || bmp.Height <= 0)
|
||||
{
|
||||
bmp = null; // a null bitmap is not ours to dispose
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hue > 0)
|
||||
{
|
||||
Hue[] list = Hues.List;
|
||||
|
||||
if (list != null && hue - 1 < list.Length && list[hue - 1] != null)
|
||||
list[hue - 1].ApplyTo(bmp, partial);
|
||||
}
|
||||
|
||||
width = bmp.Width;
|
||||
height = bmp.Height;
|
||||
pixels = ToArgb1555(bmp);
|
||||
|
||||
return pixels != null;
|
||||
}
|
||||
catch (NotImplementedException)
|
||||
{
|
||||
// libgdiplus 6.1 cannot create/lock the 16bpp bitmap — the #39 condition itself.
|
||||
available = false;
|
||||
return false;
|
||||
}
|
||||
catch (DllNotFoundException)
|
||||
{
|
||||
// No libgdiplus at all on this host: System.Drawing cannot run. Same verdict — the
|
||||
// oracle is unavailable, not "this id has no art".
|
||||
available = false;
|
||||
return false;
|
||||
}
|
||||
catch (TypeInitializationException)
|
||||
{
|
||||
// The System.Drawing static ctor failed (typically wrapping the DllNotFoundException
|
||||
// above). Still "oracle unavailable", not an EXTRA per id.
|
||||
available = false;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Any other vendored failure: treat as no art for this key, keep the oracle alive.
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (owned && bmp != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
bmp.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A fresh, uncached bitmap; nothing else holds it.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a 16bpp ARGB1555 bitmap into a <c>ushort[]</c> with <c>Marshal.Copy</c> — no
|
||||
/// <c>unsafe</c> block, exactly as <see cref="BridgeAnimParity"/> reads its source.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -361,10 +361,25 @@ namespace Server.Custom.Bridge
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// As above, and also surfaces the hue <c>GetAnimation(..., preserveHue: false, ...)</c>
|
||||
/// would apply. <c>Animations.Translate(ref body, ref hue)</c> pulls a body.def remap's
|
||||
/// hue into <paramref name="hue"/> (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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One record as its own byte[] — the verdata-patched bytes <see cref="ReadRecord"/>
|
||||
/// validates — for a managed decoder (<see cref="BridgeMul"/>) 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 (<paramref name="reason"/> set on a failure).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads one record into <see cref="_scratch"/>. Returns its length, 0 for a
|
||||
/// failure (with <paramref name="reason"/> set), or -1 when there is nothing to
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
@@ -120,12 +117,6 @@ namespace Server.Custom.Bridge
|
||||
public string Sha256;
|
||||
}
|
||||
|
||||
// ── imaging (§4.4) ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static bool _imagingChecked;
|
||||
private static bool _imagingOk;
|
||||
private static string _imagingReason;
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (!BridgeConfig.Enabled)
|
||||
@@ -583,93 +574,6 @@ namespace Server.Custom.Bridge
|
||||
Accept(reqId, "assets.manifest", () => manifest(reqId, cursor));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ARGB1555 to a PNG with a transparent background.
|
||||
///
|
||||
/// <c>Frame</c> writes 16-bit ARGB1555: a pixel the sprite does not cover is left as
|
||||
/// zero and a pixel it does cover carries the top bit set. Saving that format straight
|
||||
/// to PNG asks GDI+ to make the conversion, and what it does with a one-bit alpha
|
||||
/// channel varies by platform — on Mono it is a different implementation entirely. A
|
||||
/// sprite that came back with a black rectangle behind it would look fine in a test
|
||||
/// that only checked the bytes decoded, and wrong on every page that showed it.
|
||||
///
|
||||
/// So the expansion is done here, explicitly: alpha bit clear becomes fully
|
||||
/// transparent, and each 5-bit channel is widened to 8 bits by repeating its high bits
|
||||
/// (<c>(c << 3) | (c >> 2)</c>) rather than by shifting alone, which would
|
||||
/// cap white at 248 and tint the whole catalogue.
|
||||
/// </summary>
|
||||
internal static byte[] BitmapToPng(Bitmap source)
|
||||
{
|
||||
var rect = new Rectangle(0, 0, source.Width, source.Height);
|
||||
|
||||
if (source.PixelFormat != PixelFormat.Format16bppArgb1555)
|
||||
{
|
||||
// Not what this library has ever produced. Save it rather than reinterpret it:
|
||||
// guessing at an unknown layout is how a catalogue fills with confident nonsense.
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
source.Save(ms, ImageFormat.Png);
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
using (var target = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb))
|
||||
{
|
||||
BitmapData src = source.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555);
|
||||
BitmapData dst = null;
|
||||
|
||||
try
|
||||
{
|
||||
dst = target.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
|
||||
|
||||
var line = new short[source.Width];
|
||||
var outLine = new int[source.Width];
|
||||
|
||||
for (int y = 0; y < source.Height; y++)
|
||||
{
|
||||
Marshal.Copy(new IntPtr(src.Scan0.ToInt64() + ((long)y * src.Stride)),
|
||||
line, 0, source.Width);
|
||||
|
||||
for (int x = 0; x < source.Width; x++)
|
||||
{
|
||||
int p = line[x] & 0xFFFF;
|
||||
|
||||
if ((p & 0x8000) == 0)
|
||||
{
|
||||
outLine[x] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
int r = (p >> 10) & 0x1F;
|
||||
int g = (p >> 5) & 0x1F;
|
||||
int b = p & 0x1F;
|
||||
|
||||
outLine[x] = unchecked((int)0xFF000000)
|
||||
| (((r << 3) | (r >> 2)) << 16)
|
||||
| (((g << 3) | (g >> 2)) << 8)
|
||||
| ((b << 3) | (b >> 2));
|
||||
}
|
||||
|
||||
Marshal.Copy(outLine, 0, new IntPtr(dst.Scan0.ToInt64() + ((long)y * dst.Stride)),
|
||||
source.Width);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (dst != null)
|
||||
target.UnlockBits(dst);
|
||||
|
||||
source.UnlockBits(src);
|
||||
}
|
||||
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
target.Save(ms, ImageFormat.Png);
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Does a caller's asserted catalog id disagree with what this shard holds?
|
||||
///
|
||||
@@ -835,7 +739,11 @@ namespace Server.Custom.Bridge
|
||||
.Bool("assetsEnabled", BridgeConfig.AssetsEnabled)
|
||||
.Bool("treeEnabled", BridgeConfig.TreeEnabled);
|
||||
|
||||
WriteImaging(sb);
|
||||
// No imaging/NO_IMAGING field (servuo-plugins #39, PR 2): every picture family — the
|
||||
// body catalogue (PR 1) and item/land art (PR 2) — now decodes into ARGB1555 with no
|
||||
// System.Drawing, so this shard serves pictures whether or not the host has libgdiplus.
|
||||
// The source gate no longer reports an imaging state because there is no longer one that
|
||||
// gates anything.
|
||||
|
||||
// §4.6: whichever of art.mul / artLegacyMUL.uop `FileIndex` would actually open. An
|
||||
// operator who added custom graphics to art.mul while the UOP is present is getting
|
||||
@@ -968,88 +876,6 @@ namespace Server.Custom.Bridge
|
||||
return (long)(utc - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
||||
}
|
||||
|
||||
// ── imaging (§4.4) ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Whether this host can turn a record into a picture at all.
|
||||
///
|
||||
/// ServUO targets net48, so a Linux shard runs it under Mono, where
|
||||
/// <c>System.Drawing</c> is a thin layer over **libgdiplus** — and §4.2 put
|
||||
/// <c>System.Drawing</c> in the *decode* path, not merely the encode: <c>Frame</c>
|
||||
/// writes ARGB1555 through a <c>LockBits</c> pointer. Without that library a Linux
|
||||
/// shard cannot read a sprite at all, while clilocs and the atlas are unaffected
|
||||
/// because neither touches pixels.
|
||||
///
|
||||
/// It must never present as a stack trace or a 500. It is a named, actionable outcome
|
||||
/// in the same family as the cliloc reader's `COMPRESSED`, and it is reported here —
|
||||
/// on the *source gate*, the first call any import makes — so an operator learns it
|
||||
/// while setting the shard up rather than from an empty bestiary weeks later.
|
||||
/// </summary>
|
||||
private static void WriteImaging(StringBuilder sb)
|
||||
{
|
||||
CheckImaging();
|
||||
|
||||
sb.Append(",\"imaging\":{\"ok\":").Append(_imagingOk ? "true" : "false");
|
||||
|
||||
if (!_imagingOk)
|
||||
{
|
||||
sb.Append(",\"code\":\"NO_IMAGING\",\"reason\":");
|
||||
BridgeJson.Text(sb,
|
||||
"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 + ")");
|
||||
}
|
||||
|
||||
sb.Append('}');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether this host can produce a picture, for the families that produce pictures.
|
||||
///
|
||||
/// <see cref="WriteImaging"/> reports this on the source gate so an operator learns it
|
||||
/// while setting the shard up. The catalogue needs the same answer as a *decision* —
|
||||
/// it must refuse rather than throw a <c>DllNotFoundException</c> out of the middle of
|
||||
/// a decode loop — so the check itself is shared and this is its one accessor.
|
||||
/// </summary>
|
||||
internal static bool ImagingOk(out string reason)
|
||||
{
|
||||
CheckImaging();
|
||||
reason = _imagingReason;
|
||||
return _imagingOk;
|
||||
}
|
||||
|
||||
private static void CheckImaging()
|
||||
{
|
||||
if (_imagingChecked)
|
||||
return;
|
||||
|
||||
_imagingChecked = true;
|
||||
|
||||
try
|
||||
{
|
||||
TouchImaging();
|
||||
_imagingOk = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// On a host with no libgdiplus this is a TypeInitializationException wrapping a
|
||||
// DllNotFoundException, and it can surface as the method failing to JIT rather
|
||||
// than as a throw from inside it — which is why the construction lives in its own
|
||||
// method, so the failure is contained here instead of taking this class's
|
||||
// static initialisation with it.
|
||||
_imagingOk = false;
|
||||
_imagingReason = e.GetType().Name + ": " + e.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private static void TouchImaging()
|
||||
{
|
||||
using (var bmp = new System.Drawing.Bitmap(1, 1))
|
||||
{
|
||||
bmp.SetPixel(0, 0, System.Drawing.Color.Black);
|
||||
}
|
||||
}
|
||||
|
||||
// ── the hash cache (§6) ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static string CachedHashFor(string path, long size, long mtime)
|
||||
|
||||
@@ -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
|
||||
/// </summary>
|
||||
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
|
||||
/// </summary>
|
||||
private static void ReplyFetch(string reqId, List<string> 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
|
||||
/// </summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gate every legacy sprite passes before a pixel is read: <c>ResolveAnimation</c>
|
||||
/// (Translate + BodyConverter + the §4.10 banding ceiling), <c>CheckEntry</c> (the §4.5
|
||||
/// entry check that refuses the 357 <c>length 0</c> records), and <c>AnimationSane</c>.
|
||||
/// 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
|
||||
/// (<see cref="RunAnimParity"/>) can tell "the Bridge refuses this" from "the managed
|
||||
/// decode failed on a record it accepts": only the second is a defect.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>Animations.GetAnimation(..., firstFrame: true)</c> would, but into an ARGB1555
|
||||
/// <c>ushort[]</c> rather than a 16bpp <c>Bitmap</c> libgdiplus cannot create. The gate
|
||||
/// (<see cref="LegacyRecord"/>) is unchanged and still vendored; only the two calls that
|
||||
/// reached <c>System.Drawing</c> are replaced — the <c>Frame</c> ctor by
|
||||
/// <see cref="BridgeMul"/> and <c>Hue.ApplyTo</c> by <see cref="BridgeHue"/>. A false
|
||||
/// return is the ordinary "no legacy art here" (including a 0x0 frame, with
|
||||
/// <paramref name="empty"/> set), and the caller falls through to the UOP arm. This is
|
||||
/// the exact path <see cref="RunAnimParity"/> measures, so the harness proves the
|
||||
/// shipping code rather than a copy of it.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Phase 4's own reader over <c>AnimationFrame*.uop</c> (§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) ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The vendored legacy decode for one key, as an oracle for <see cref="RunAnimParity"/>.
|
||||
/// The caller supplies it (from <c>BridgeAnimParity</c>, the only place that still
|
||||
/// touches <c>System.Drawing</c>) so this file stays GDI+-free: it returns the ARGB1555
|
||||
/// pixels and dimensions the vendored path produced, or false for no art.
|
||||
/// <paramref name="available"/> is set false when the oracle cannot run at all — a real
|
||||
/// Linux/Mono host, where the vendored 16bpp <c>Bitmap</c> throws <c>NotImplemented</c>
|
||||
/// — which tells the harness to drop into candidate-only (does-it-render) mode.
|
||||
/// </summary>
|
||||
public delegate bool ParityOracle(int body, int action, int direction,
|
||||
out ushort[] pixels, out int width, out int height, out bool available);
|
||||
|
||||
/// <summary>
|
||||
/// Compares the shipping managed legacy decode (<see cref="LegacyPixels"/>) against the
|
||||
/// vendored GDI+ decode, pixel for pixel, across every legacy-resolvable record (bodies
|
||||
/// 1..<see cref="MaxBody"/>, actions 0..<see cref="MaxAction"/>, 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 <see cref="LegacyPixels"/>, not a reimplementation, so a
|
||||
/// green run is evidence about the code that ships.
|
||||
/// </summary>
|
||||
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) ─────────────────────────────────────────────────────────────
|
||||
|
||||
81
overlay/Scripts/Custom/Bridge/BridgeHue.cs
Normal file
81
overlay/Scripts/Custom/Bridge/BridgeHue.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using Ultima;
|
||||
|
||||
namespace Server.Custom.Bridge
|
||||
{
|
||||
/// <summary>
|
||||
/// **Hue application without GDI+** (servuo-plugins #39). The vendored
|
||||
/// <c>Ultima.Hue.ApplyTo(Bitmap, onlyHueGrayPixels)</c> locks a 16bpp <c>Bitmap</c> and
|
||||
/// repaints it in place, so the catalogue's body.def-hued creatures (162 <c>Body.def</c>
|
||||
/// entries carry a non-zero hue) go back through libgdiplus after
|
||||
/// <see cref="BridgeMul"/> has already escaped it. This reproduces <c>ApplyTo</c> over a
|
||||
/// contiguous ARGB1555 <c>ushort[]</c> instead — same arithmetic, no <c>Bitmap</c>.
|
||||
///
|
||||
/// The colour table is still the vendored one: <c>Ultima.Hues.List[index].Colors</c> is a
|
||||
/// <c>short[32]</c> read from <c>hues.mul</c> with no <c>System.Drawing</c>, so reusing it
|
||||
/// guarantees the managed path and the vendored path tint a pixel to the identical value.
|
||||
/// </summary>
|
||||
public static class BridgeHue
|
||||
{
|
||||
/// <summary>
|
||||
/// Repaints each non-transparent pixel to <c>colors[(pixel >> 10) & 0x1F]</c>
|
||||
/// — the pixel's own red channel chooses the entry on the 32-step ramp, exactly as
|
||||
/// <c>Hue.ApplyTo</c>. 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.
|
||||
/// </summary>
|
||||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The hue-object selection <c>GetAnimation</c> 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 <c>Hues.List</c> index, and an out-of-range index means no
|
||||
/// hue at all. Returns the colour table to hand to <see cref="Apply"/>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
178
overlay/Scripts/Custom/Bridge/BridgeMul.cs
Normal file
178
overlay/Scripts/Custom/Bridge/BridgeMul.cs
Normal file
@@ -0,0 +1,178 @@
|
||||
using System;
|
||||
|
||||
namespace Server.Custom.Bridge
|
||||
{
|
||||
/// <summary>
|
||||
/// **The legacy-MUL animation reader** (servuo-plugins #39): the half of the GDI+-free
|
||||
/// migration that <see cref="BridgeUop"/> left undone. §4.4 moved the UOP path off
|
||||
/// <c>System.Drawing</c> because libgdiplus was archived in March 2025; this does the same
|
||||
/// for <c>anim*.mul</c>, and for a sharper reason — on a Linux/Mono shard the vendored
|
||||
/// <c>Ultima.Frame</c> ctor asks libgdiplus to create a 16bpp <c>Bitmap</c>
|
||||
/// (<c>Settings.PixelFormat</c>) and libgdiplus answers <c>NotImplemented</c>, so the whole
|
||||
/// catalogue's legacy art fails before a single pixel is read.
|
||||
///
|
||||
/// This decodes the same bytes <c>Ultima.Frame</c> does, into an ARGB1555 <c>ushort[]</c>
|
||||
/// with no <c>Bitmap</c> anywhere, for <see cref="BridgePng.FromArgb1555"/> to encode. The
|
||||
/// run loop is <c>Frame</c>'s (<c>Animations.cs</c>), with the two bounds it does not have —
|
||||
/// exactly as <see cref="BridgeUop.Group.TryDecode"/> 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, <c>DoubleXor</c> run headers,
|
||||
/// the <c>0x7FFF7FFF</c> terminator), but the container is not. A legacy record is a single
|
||||
/// <b>shared</b> palette of 0x100 entries at the very start, then a frame count and a lookup
|
||||
/// table, then the frames; a UOP record carries a <b>per-frame</b> 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 <see cref="BridgeUop"/>'s offset math.
|
||||
/// </summary>
|
||||
public static class BridgeMul
|
||||
{
|
||||
/// <summary>The xor <c>Ultima.Frame</c> applies to every run header, and so must this.</summary>
|
||||
private const int DoubleXor = (0x200 << 22) | (0x200 << 12);
|
||||
|
||||
/// <summary>The shared palette: 0x100 ARGB1555 entries at the head of every record.</summary>
|
||||
private const int PaletteBytes = 0x100 * 2;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the first frame of a legacy animation record (what a
|
||||
/// <c>FirstFrame: true</c> <c>GetAnimation</c> call produces) into ARGB1555.
|
||||
///
|
||||
/// <paramref name="record"/> is the raw record, verdata-patched, exactly as
|
||||
/// <see cref="BridgeAssetValidator.RecordReader.ReadRecordCopy"/> 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 <paramref name="empty"/> set, which is how the
|
||||
/// vendored ctor treats it too (an early return, not damage).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user