diff --git a/ports/csharp/.gitignore b/ports/csharp/.gitignore new file mode 100644 index 0000000..e4c0ed0 --- /dev/null +++ b/ports/csharp/.gitignore @@ -0,0 +1,6 @@ +bin/ +obj/ +build/ +hello.png +examples/**/bin/ +examples/**/obj/ diff --git a/ports/csharp/Prism.cs b/ports/csharp/Prism.cs index ac3878f..bf37ade 100644 --- a/ports/csharp/Prism.cs +++ b/ports/csharp/Prism.cs @@ -7,9 +7,12 @@ namespace PrismCode { + /// Code mode: 8-color or black-and-white. public enum PrismMode { Color = 0, BW = 1 } + /// Payload type stored in the code header. public enum PrismType { Text = 0, Binary = 1 } + /// Thrown on any encode/decode failure; the message is a human-readable reason. public class PrismException : Exception { public PrismException(string message) : base(message) { } @@ -27,6 +30,8 @@ public sealed class PrismDecodeResult public int Type, Size, Ecc, Mode; } + /// Comb Code encoder and clean-image decoder, byte-exact with the live JavaScript. + /// A decode only returns a payload when its header CRC and payload CRC-32 pass. public static class Comb { /* -------------------------------------------------------- constants */ @@ -177,6 +182,7 @@ private static int RsDecode(byte[] r, int nsym) } /* ------------------------------------------------------------ CRC */ + /// CRC-32 (IEEE) of the first bytes. public static uint Crc32(byte[] bytes, int len) { uint c = 0xFFFFFFFFu; @@ -297,6 +303,7 @@ private static Capacity CapacityOf(int size, int ecc, int mode) } /// Maximum payload bytes for a size (0..5), ecc (0..3) and mode. + /// Maximum payload bytes for a size (0..5), repair level (0..3 = 10/20/30/40%) and mode. public static int CapacityPayload(int size, int ecc, PrismMode mode) => CapacityOf(size, ecc, (int)mode).Payload; @@ -393,6 +400,8 @@ private static Code EncodeCode(byte[] bytes, int size, int ecc, int mode, int ty /* ----------------------------------------------------------- render */ /// Encode payload bytes to an in-memory RGBA image. + /// Encode payload bytes to an in-memory image. -1 = automatic + /// or 0..5; 0..3; pixels per cell unit (live default 12). public static PrismImage Encode(byte[] payload, int size = -1, int ecc = 1, PrismMode mode = PrismMode.Color, PrismType type = PrismType.Text, int scale = 12) @@ -452,6 +461,7 @@ public static PrismImage Encode(byte[] payload, int size = -1, int ecc = 1, } /// Encode and write a PNG file. + /// Encode payload bytes and write a PNG file. public static void EncodePng(byte[] payload, string path, int size = -1, int ecc = 1, PrismMode mode = PrismMode.Color, PrismType type = PrismType.Text, int scale = 12) => @@ -572,6 +582,8 @@ private static PrismDecodeResult DecodeSized(PrismImage img, int size, double r) /// Decode a Comb code from a clean PNG (encoder output; not the robust /// camera pipeline). CRC32 verified. Throws PrismException on failure. /// + /// Decode a clean PNG produced by an encoder. For the phone-camera pipeline + /// (glare, blur, perspective) see the reader project in reader/. public static PrismDecodeResult DecodePng(string path) { var img = Png.Read(path); diff --git a/ports/csharp/PrismCards.cs b/ports/csharp/PrismCards.cs index 46127d2..5492255 100644 --- a/ports/csharp/PrismCards.cs +++ b/ports/csharp/PrismCards.cs @@ -8,6 +8,7 @@ namespace PrismCode { + /// Parsed Wi-Fi card fields (WIFI: payload). public sealed class WifiCard { public string Ssid = ""; @@ -16,12 +17,14 @@ public sealed class WifiCard public bool Hidden; } + /// Parsed contact-card fields (vCard 3.0 payload). public sealed class VCard { public string Name = "", Org = "", Title = "", Addr = "", Note = ""; public List Phones = new(), Emails = new(), Urls = new(); } + /// Parsed expiring-ticket fields (PRISM-TICKET/1 payload). public sealed class TicketCard { public long ExpiryMs; @@ -30,12 +33,15 @@ public sealed class TicketCard public enum CardKind { None, Ticket, Wifi, VCard } + /// Builds and parses the site's Wi-Fi, vCard 3.0 contact-card and expiring-ticket + /// payloads, byte-identical to the live comb-cards.js (escaping included). public static class PrismCards { /* ---------- Wi-Fi ---------- */ static string EscWifi(string s) => Regex.Replace(s, "([\\\\;,:\"'])", "\\$1"); + /// Build a Wi-Fi payload (WIFI:S:...;T:...;P:...;H:...;;). public static string WifiPayload(string ssid, string sec = "WPA", string pass = "", bool hidden = false) { string t = string.IsNullOrEmpty(sec) ? "WPA" : sec; @@ -47,6 +53,7 @@ public static string WifiPayload(string ssid, string sec = "WPA", string pass = return sb.ToString(); } + /// Parse a Wi-Fi payload. public static bool TryParseWifi(string text, out WifiCard card) { card = null!; @@ -91,6 +98,7 @@ void Push() static string EscV(string s) => s.Replace("\\", "\\\\").Replace("\n", "\\n").Replace(",", "\\,").Replace(";", "\\;"); + /// Build a vCard 3.0 contact-card payload. public static string VCardPayload(string name, string org = "", string title = "", string phone = "", string email = "", string url = "", string addr = "", string note = "") { @@ -116,6 +124,7 @@ public static string VCardPayload(string name, string org = "", string title = " static string UnescV(string s) => Regex.Replace(s.Replace("\\n", "\n").Replace("\\N", "\n"), "\\\\([,;\\\\])", "$1"); + /// Parse a vCard 3.0 contact-card payload. public static bool TryParseVCard(string text, out VCard card) { card = null!; @@ -148,9 +157,11 @@ string Get(string k) /* ---------- ticket ---------- */ + /// Build an expiring-ticket payload (expiry in milliseconds since the Unix epoch). public static string TicketPayload(long expiryMs, string text) => "PRISM-TICKET/1\nEXP:" + (expiryMs / 1000) + "\n" + (text ?? "").Trim(); + /// Parse an expiring-ticket payload. public static bool TryParseTicket(string text, out TicketCard card) { card = null!; @@ -161,6 +172,7 @@ public static bool TryParseTicket(string text, out TicketCard card) return true; } + /// Detect which card kind a decoded text payload holds. public static CardKind Detect(string text) { if (string.IsNullOrEmpty(text)) return CardKind.None; diff --git a/ports/csharp/PrismIssuers.cs b/ports/csharp/PrismIssuers.cs index 0f8d7c4..8b7ef6f 100644 --- a/ports/csharp/PrismIssuers.cs +++ b/ports/csharp/PrismIssuers.cs @@ -24,10 +24,13 @@ public sealed class Issuer public string? Url { get; set; } } + /// Ticket-issuer identities: recognize a signed ticket's issuer from its signing key + /// and match fingerprints against the site's issuers list (comb-issuers.js compatible). public static class PrismIssuers { /* Inspect decoded payload bytes. Returns null for plain or unsigned * payloads, else the identity. Read-only: never decrypts. */ + /// Identify the issuer of a decoded, signed ticket payload; null when not a signed ticket. public static IssuerIdentity? Identify(byte[] bytes) { if (bytes == null || bytes.Length < 5 + 65 + 64) return null; @@ -65,6 +68,7 @@ public static class PrismIssuers } /* Loads an issuers.json file (empty list when missing or damaged). */ + /// Load the site's issuers.json list. public static List Load(string path) { try @@ -93,6 +97,7 @@ static string Norm(string f) return sb.ToString(); } + /// Find an issuer by XXXX-XXXX fingerprint. public static Issuer? Find(IEnumerable issuers, string fingerprint) { string want = Norm(fingerprint); diff --git a/ports/csharp/PrismParts.cs b/ports/csharp/PrismParts.cs index 8367e39..f228468 100644 --- a/ports/csharp/PrismParts.cs +++ b/ports/csharp/PrismParts.cs @@ -6,6 +6,7 @@ namespace PrismCode { + /// Split plan for a file: per-part payload room, part count and cleaned name. public sealed class PartsPlan { public int Room; @@ -13,6 +14,7 @@ public sealed class PartsPlan public string Name = ""; } + /// Decoded PPT1 part: file id, position, whole-file length/CRC-32, name and chunk bytes. public sealed class PartInfo { public string Id = ""; @@ -22,6 +24,8 @@ public sealed class PartInfo public byte[] Chunk = Array.Empty(); } + /// Multi-part files (PPT1 payloads), byte-compatible with the live comb-parts.js. + /// Parts are encoded at 30% repair data, color mode. public static class PrismParts { public const int PartsEcc = 2; // parts are encoded at 30% repair data, color mode @@ -85,16 +89,18 @@ static byte[] NameBytes(string name) static int Overhead(int nameLen) => 4 + 4 + 2 + 2 + 4 + 4 + 1 + nameLen + 4; + /// Compute the split plan for bytes at code size 2..5. public static PartsPlan Plan(long len, string name, int codeSize) { byte[] nb = NameBytes(name); - int room = Prism.CapacityPayload(codeSize, PartsEcc, PrismMode.Color) - Overhead(nb.Length); + int room = Comb.CapacityPayload(codeSize, PartsEcc, PrismMode.Color) - Overhead(nb.Length); if (room < 64) throw new InvalidOperationException("Part size too small"); long total = Math.Max(1, (len + room - 1) / room); if (total > 65535) throw new InvalidOperationException("File is too big for this part size"); return new PartsPlan { Room = room, Total = (int)total, Name = Encoding.UTF8.GetString(nb) }; } + /// Split a file into PPT1 part payloads, ready to encode one code each. public static byte[][] Split(byte[] bytes, string name, int codeSize) { var plan = Plan(bytes.Length, name, codeSize); @@ -124,6 +130,8 @@ public static byte[][] Split(byte[] bytes, string name, int codeSize) } // ok: info set. notPart: not a part. bad: damaged part (site's message). + /// Parse one PPT1 payload. is true when the bytes are not a part at all; + /// carries the reason for a damaged part. public static bool TryParse(byte[] b, out PartInfo info, out bool notPart, out string bad) { info = null!; notPart = false; bad = null!; @@ -152,6 +160,7 @@ public static bool TryParse(byte[] b, out PartInfo info, out bool notPart, out s public enum PartAddStatus { NotPart, Bad, OtherFile, Duplicate, New, Complete } + /// Outcome of adding one part to a , with the site's user-facing message. public sealed class PartAddResult { public PartAddStatus Status; @@ -159,6 +168,8 @@ public sealed class PartAddResult public string Message = ""; } + /// Reassembles a file from its parts in any order: detects duplicates, parts of another + /// file and damaged parts, and verifies the whole-file CRC-32. public sealed class PartsAssembler { string _id = null!; @@ -172,6 +183,7 @@ public sealed class PartsAssembler public int Total => _total; public string Name => _name; + /// Add one decoded part payload. public PartAddResult Add(byte[] bytes) { if (!PrismParts.TryParse(bytes, out var p, out bool notPart, out string bad)) @@ -196,6 +208,7 @@ public PartAddResult Add(byte[] bytes) return new PartAddResult { Status = _have == _total ? PartAddStatus.Complete : PartAddStatus.New, N = p.N }; } + /// Return the reassembled file once all parts are present; throws otherwise. public byte[] Finish() { if (_have != _total) throw new InvalidOperationException("Parts are still missing."); diff --git a/ports/csharp/PrismSecure.cs b/ports/csharp/PrismSecure.cs index b40d2c3..06374b3 100644 --- a/ports/csharp/PrismSecure.cs +++ b/ports/csharp/PrismSecure.cs @@ -19,12 +19,14 @@ namespace PrismCode { + /// An ECDSA P-256 signing key: raw 0x04|X|Y public key plus JWK private key. public sealed class PrismSigningKey { public byte[] PublicKey = Array.Empty(); // 65 bytes, 0x04 | X | Y public string PrivateJwk = ""; // JWK JSON, as on the site } + /// Result of opening a secure envelope: payload, signature state and signer fingerprint. public sealed class PrismSecureResult { public bool Secure, Encrypted, Signed; @@ -37,6 +39,9 @@ public sealed class PrismSecureResult public int Version; } + /// Comb Code Secure (envelope v2, reads v1): AES-256-GCM payload locking with Argon2id + /// (128 MiB, 3 passes, RFC 9106) or PBKDF2-SHA256 (600,000 rounds), and ECDSA P-256 / SHA-256 + /// signing with the site's key formats and XXXX-XXXX fingerprints. public static class PrismSecure { private static readonly byte[] MAGIC = { 0x50, 0x53, 0x43 }; // "PSC" @@ -78,6 +83,7 @@ private static byte[] DeriveKeyBytes(string password, byte[] salt, int kdf, int finally { Array.Clear(pw); } } + /// Generate a new ECDSA P-256 signing key. public static PrismSigningKey GenerateSigningKey() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); @@ -118,6 +124,7 @@ byte[] Unb64(string s) return ec; } + /// XXXX-XXXX fingerprint of a raw 65-byte public key. public static string Fingerprint(byte[] publicKey65) { byte[] h = SHA256.HashData(publicKey65); @@ -131,6 +138,7 @@ public static string Fingerprint(byte[] publicKey65) } /// Seal payload bytes: lock with a password and/or sign. kdf: "argon2id" (default) or "pbkdf2". + /// Seal a payload into a secure envelope, optionally password-locked and/or signed. public static byte[] Seal(byte[] payload, string? password = null, PrismSigningKey? signWith = null, string kdf = "argon2id") { if (password == null && signWith == null) @@ -162,15 +170,18 @@ public static byte[] Seal(byte[] payload, string? password = null, PrismSigningK } } + /// True when the bytes are a Comb Code Secure envelope. public static bool IsSecure(byte[] b) => b.Length >= 6 && b[0] == MAGIC[0] && b[1] == MAGIC[1] && b[2] == MAGIC[2] && (b[3] == 1 || b[3] == 2) && (b[4] & ~3) == 0; + /// Report whether the bytes are a secure envelope, locked and/or signed, without opening it. public static (bool secure, bool encrypted, bool signed) Inspect(byte[] b) => !IsSecure(b) ? (false, false, false) : (true, (b[4] & F_ENC) != 0, (b[4] & F_SIG) != 0); /// Random passphrase: 7 groups of 4 from a 32-symbol alphabet = 140 bits /// of entropy (32 symbols = exactly 5 bits each, so no modulo bias). + /// Generate a memorable passphrase in the site's wordlist format. public static string GeneratePassphrase() { const string ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; @@ -191,6 +202,7 @@ public static string GeneratePassphrase() private static readonly string[] COMMON_WORDS = { "password", "passw0rd", "qwerty", "letmein", "welcome", "admin", "iloveyou", "monkey", "dragon", "football", "baseball", "shalom", "israel", "master", "login", "abc123", "prism", "secret", "hello", "test", "summer", "winter", "sunshine", "princess", "trustno1", "whatever", "google", "avi", "1234", "asdf", "zxcv", "love", "god", "cohen", "levi" }; /// Strength estimate in bits, same heuristic as the site (deliberately cautious). + /// The site's password strength meter: entropy bits, 0..4 level, label and warnings. public static (int bits, int level, string label, string[] warnings) Strength(string pw) { var warnings = new List(); @@ -226,6 +238,8 @@ public static (int bits, int level, string label, string[] warnings) Strength(st } /// Open a sealed payload. Plain (non-secure) payloads come back unchanged. + /// Open a secure envelope. A locked envelope needs ; + /// pass to verify the signer. public static PrismSecureResult Open(byte[] bytes, string? password = null, string[]? trustedFingerprints = null) { var outp = new PrismSecureResult(); diff --git a/ports/csharp/Program.cs b/ports/csharp/Program.cs index da6ca7e..5529c09 100644 --- a/ports/csharp/Program.cs +++ b/ports/csharp/Program.cs @@ -48,7 +48,7 @@ static int Main(string[] args) Console.WriteLine("size cells color-ecc0 bw-ecc0 (max payload bytes; ecc1/2/3 fit less)"); string[] cells = { "21x24", "29x33", "41x47", "57x66", "81x94", "113x130" }; for (int s = 0; s < 6; s++) - Console.WriteLine($"{s} {cells[s],-10} {Prism.CapacityPayload(s, 0, PrismMode.Color),-11} {Prism.CapacityPayload(s, 0, PrismMode.BW),-8}"); + Console.WriteLine($"{s} {cells[s],-10} {Comb.CapacityPayload(s, 0, PrismMode.Color),-11} {Comb.CapacityPayload(s, 0, PrismMode.BW),-8}"); return 0; } if (args[0] == "encode") @@ -97,7 +97,7 @@ string Next() data = PrismSecure.Seal(data, password, keyFile != null ? LoadKey(keyFile) : null, kdf); type = (int)PrismType.Binary; } - Prism.EncodePng(data, outp, size, ecc, mode, (PrismType)type, scale); + Comb.EncodePng(data, outp, size, ecc, mode, (PrismType)type, scale); Console.WriteLine($"wrote {outp} ({data.Length} payload bytes)"); return 0; } @@ -185,7 +185,7 @@ string Next() else { Usage(); return 2; } } if (inp == null) { Usage(); return 2; } - var res = Prism.DecodePng(inp); + var res = Comb.DecodePng(inp); if (PrismSecure.IsSecure(res.Bytes)) { var opened = PrismSecure.Open(res.Bytes, password); @@ -334,7 +334,7 @@ string Next() } if (inp == null) { Usage(); return 2; } byte[] bytes = inp.EndsWith(".png", StringComparison.OrdinalIgnoreCase) - ? Prism.DecodePng(inp).Bytes + ? Comb.DecodePng(inp).Bytes : File.ReadAllBytes(inp); var id = PrismIssuers.Identify(bytes); if (id == null) { Console.WriteLine("not a signed Comb Code Secure payload"); return 0; } diff --git a/ports/csharp/README.md b/ports/csharp/README.md index da98897..8a18229 100644 --- a/ports/csharp/README.md +++ b/ports/csharp/README.md @@ -104,10 +104,39 @@ CLI verbs: `issuer IN.png|IN.bin [--list issuers.json]`, bit-for-bit; splits and joins interoperate with the C and C++ ports and with the live JS module. -## Not in this port (yet) +## Library use -The phone-camera reading pipeline (glare, blur, perspective — that stays on -the website's reader pages) is being ported next. +The public API lives in namespace `PrismCode`: `Comb` (encoder/decoder), +`PrismSecure` (Comb Code Secure), `PrismParts` (multi-part files), +`PrismCards` (Wi-Fi / vCard / ticket payloads) and `PrismIssuers` (ticket +issuers). All public entry points have XML doc comments. Example +(`examples/EncodeDecode`, run with `dotnet run --project examples/EncodeDecode`): + +```csharp +using PrismCode; + +byte[] payload = System.Text.Encoding.UTF8.GetBytes("Hello from Comb Code"); +Comb.EncodePng(payload, "hello.png", -1, 1, PrismMode.Color, PrismType.Text, 12); +PrismDecodeResult r = Comb.DecodePng("hello.png"); +Console.WriteLine(System.Text.Encoding.UTF8.GetString(r.Bytes)); +``` + +### API reference (encoder/decoder, `Prism.cs`) + +- `Comb.Encode(payload, size, ecc, mode, type, scale)` -> `PrismImage` — + encode payload bytes to an in-memory image. `size` -1 = automatic or 0..5; + `ecc` 0..3 (10/20/30/40% repair data); mode color or black-and-white. +- `Comb.EncodePng(payload, path, size, ecc, mode, type, scale)` — encode and + write a PNG file. +- `Comb.DecodePng(path)` -> `PrismDecodeResult` — decode a clean PNG; the + payload is only returned when its CRC-32 passes. +- `Comb.CapacityPayload(size, ecc, mode)` — maximum payload bytes. + +## Camera reader + +`reader/` is a separate .NET 8 project porting the phone-camera reading +pipeline (glare, blur, perspective). It reads 722-723 of the 772 synthetic kit +scenes with 0 wrong payloads; see `reader/README.md` for the measured counts. ## License diff --git a/ports/csharp/examples/EncodeDecode/EncodeDecode.csproj b/ports/csharp/examples/EncodeDecode/EncodeDecode.csproj new file mode 100644 index 0000000..7bdf273 --- /dev/null +++ b/ports/csharp/examples/EncodeDecode/EncodeDecode.csproj @@ -0,0 +1,15 @@ + + + + Exe + net8.0 + disable + enable + encode-decode-example + + + + + + + diff --git a/ports/csharp/examples/EncodeDecode/Program.cs b/ports/csharp/examples/EncodeDecode/Program.cs new file mode 100644 index 0000000..0e211b3 --- /dev/null +++ b/ports/csharp/examples/EncodeDecode/Program.cs @@ -0,0 +1,19 @@ +// Comb Code C# example: encode a text payload to a PNG, decode it back. +using System; +using PrismCode; + +const string text = "Hello from Comb Code"; +byte[] payload = System.Text.Encoding.UTF8.GetBytes(text); + +// Encode: automatic size, 20% repair data, color mode, 12 px per cell unit. +Comb.EncodePng(payload, "hello.png", -1, 1, PrismMode.Color, PrismType.Text, 12); +Console.WriteLine($"encoded {payload.Length} bytes -> hello.png"); + +// Decode it back. The payload is only returned when its CRC-32 passes. +PrismDecodeResult r = Comb.DecodePng("hello.png"); +string outText = System.Text.Encoding.UTF8.GetString(r.Bytes); +Console.WriteLine($"decoded {r.Bytes.Length} bytes: {outText}"); + +bool ok = outText == text; +Console.WriteLine("round-trip " + (ok ? "OK" : "MISMATCH")); +return ok ? 0 : 1; diff --git a/ports/csharp/prism.csproj b/ports/csharp/prism.csproj index 71b5795..934c813 100644 --- a/ports/csharp/prism.csproj +++ b/ports/csharp/prism.csproj @@ -7,6 +7,15 @@ enable prism true + Comb Code + Avi Shor + Comb Code encoder, decoder, Comb Code Secure, multi-part files and card payloads (C# / .NET 8). + + + + + + diff --git a/ports/csharp/reader/.gitignore b/ports/csharp/reader/.gitignore new file mode 100644 index 0000000..6bc8908 --- /dev/null +++ b/ports/csharp/reader/.gitignore @@ -0,0 +1,3 @@ +bin/ +obj/ +build/ diff --git a/ports/csharp/reader/PrismChain.cs b/ports/csharp/reader/PrismChain.cs new file mode 100644 index 0000000..cd58c34 --- /dev/null +++ b/ports/csharp/reader/PrismChain.cs @@ -0,0 +1,101 @@ +// Comb Code page-side retry ordering, ROI and shared six-second deadline. +using System; +using System.Collections.Generic; +namespace Prism.Reader +{ + internal static partial class Chain + { + private static int Worker(ChainImage a,PrismRead r) + {Flags.CfgMinRadius=Flags.Mix!=0?.55:4;return DistFit.FastRead(a.Px,a.W,a.H,r);} + private static int RoiRead(ChainImage a,PrismRead r,int[] ibox=null,bool direct=false) + { + int[] b=ibox??SaliencyBox(a,.25,.4); + if(b!=null) + { + int sx=b[0],sy=b[1],bw=b[2],bh=b[3]; + if(Flags.Mix!=0){int dx=sx%2,dy=sy%2;sx-=dx;sy-=dy;bw+=dx;bh+=dy;} + var c=Crop(a,sx,sy,bw,bh);int m=Math.Max(c.W,c.H); + if(m<400&&Flags.Mix==0)c=UpNN(c,Math.Min(6,400.0/m)); + int rc=Worker(c,r);if(rc==0)return 0;if(Flags.CapStopped!=0)return 1; + if(direct&&Flags.Mix==0&&Flags.FbMs==450&&Math.Max(bw,bh)<260) + { + double sv=Flags.FbMs;Flags.Mix=1;Flags.Direct=1;Flags.FbMs=6000;rc=Worker(a,r); + Flags.Mix=0;Flags.Direct=0;Flags.FbMs=sv;if(rc==0)return 0;if(Flags.CapStopped!=0)return 1; + } + } + return Worker(a,r)==0?0:Flags.CapStopped!=0?1:-1; + } + private static string[] FrontStats(ChainImage a,out double aniso,out double grad) + { + int w=a.W,h=a.H;var d=a.Px;var hh=new int[256];var hn=new int[1100];var row=new int[w*3];double sm=0,gxs=0,gys=0,sts=0; + for(int y=0;y0)gxs+=Math.Abs(s-row[(y%3)*w+x-1]);if(y>0)gys+=Math.Abs(s-row[((y+2)%3)*w+x]); + if(y>1&&x>0&&x=.98*n){p98=i;break;}} + long tot=0;foreach(int v in hn)tot+=v;double nz=0;count=0;for(int i=0;i<1100;i++){count+=hn[i];if(count>=tot/2.0){nz=i/3.0;break;}} + if(mean<30&&p98<45)return nz<15.2?new[]{"llb","liftdn"}:new[]{"liftdn","llb"}; + if(nz>15)return new[]{"liftdn"}; + if(sts/n>=44&&p98>=228&&p98<=240&&nz>=3&&nz<=3.6)return new[]{"calmedon","gs3a2","lr2"}; + if(grad<1.6&&nz<3.5)return aniso>=1.4?new[]{"mlg19","mlg31","gs3a2"}:new[]{"calmedon","gs3a2","mlg31"}; + return Array.Empty(); + } + private static void ResetFlags() + {Flags.Calmed=0;Flags.Dd=0;Flags.Pq=0;Flags.Veil=0;Flags.Mix=0;Flags.Direct=0;} + private static int Attempt(ChainImage a,PrismRead r,double fb) + {Flags.FbMs=fb;int rc=RoiRead(a,r);Flags.FbMs=0;return rc;} + private static bool Finished(int rc)=>rc==0||Flags.CapStopped!=0; + private static string[] GlareFast(ChainImage a) + { + var b=SaliencyBox(a,.25,.4);if(b!=null&&Math.Max(b[2],b[3])<260)return Array.Empty(); + var d=a.Px;var hist=new int[256];long n=0,dark=0,clip=0,texture=0; + for(int k=0;k254)clip++;if(k>=4){double pv=(d[k-4]+d[k-3]+d[k-2])/3.0;if(Math.Abs(v-pv)>=1.5)texture++;}} + int p98=255;long count=0;for(int j=0;j<256;j++){count+=hist[j];if(count>=.98*n){p98=j;break;}} + return p98>=245&&(double)dark/n<.0001&&(double)clip/n>.03&&(double)texture/n>.5?new[]{"gl7","cenon","gln","veil","veilcalm"}:Array.Empty(); + } + public static int Read(byte[] rgba,int w,int h,PrismRead r) + { + ResetFlags();budgetT0=-1;Flags.CapStopped=0;Flags.PageCapS=Budget.Now()+6; + try{return ReadInner(new ChainImage(w,h,rgba),r);} + finally{ResetFlags();Flags.PageCapS=0;Flags.FbMs=0;} + } + private static int ReadInner(ChainImage a,PrismRead r) + { + var ibox=SaliencyBox(a,.25,.4);bool small=ibox!=null&&Math.Max(ibox[2],ibox[3])<260; + Flags.FbMs=450;int rc=RoiRead(a,r,ibox,true);Flags.FbMs=0;if(Finished(rc))return rc==0?0:-1;rc=-1; + foreach(string nm in GlareFast(a)) + { + ChainImage t;if(nm=="veilcalm"){Flags.Calmed=1;t=Apply("veil",a);}else t=Apply(nm,a); + if(t!=null)rc=Attempt(t,r,nm.StartsWith("veil",StringComparison.Ordinal)?1000:nm=="gln"?450:300); + Flags.Calmed=0;Flags.Dd=0;Flags.Pq=0;Flags.Veil=0;if(Finished(rc))return rc==0?0:-1; + } + if(small) + { + double sm=0,hi=0;int n=0;for(int k=0;k=1.2&&grad>=1.35?new[]{"mlw19"}:Array.Empty(); + int pc=Flags.Calmed;foreach(string nm in pre){Flags.Calmed=1;var t=Apply(nm,a);if(t!=null){rc=Attempt(t,r,450);if(Finished(rc)){Flags.Calmed=pc;return rc==0?0:-1;}}}Flags.Calmed=pc;Flags.FbMs=0; + string[] chain0={"cenon","llb","zoom","mlg19","mlg31","gl5","gl3","liftdn","crplain","zoomauto","zooman","gl6","gl7","gln","calmedon","gs3a2","deblkS","zoomw","mlw19","mlw31","lr2","veil","ml112","ml45","ml0","ml90","ml135"}; + var chain=new List();if(fs=="calmedon,gs3a2,mlg31")chain.Add("mlg31probe");chain.AddRange(front);foreach(string nm in chain0)if(Array.IndexOf(front,nm)<0)chain.Add(nm); + var oklist=new List();double t0=Budget.Now();Flags.FbMs=450; + foreach(string nm in chain) + { + if(Budget.Now()>Flags.PageCapS)return -1;if(Budget.Now()-t0>20)break; + var t=Apply(nm,a);if(t==null)continue;if(nm!="cenon"&&nm!="veil")oklist.Add(nm);rc=RoiRead(t,r);if(Finished(rc))return rc==0?0:-1; + if(nm=="cenon"){Flags.Dd=0;Flags.Pq=0;}if(nm=="veil"){Flags.Veil=0;Flags.Pq=0;} + } + Flags.Calmed=0;budgetT0=-1; + foreach(string nm in oklist) + {if(Budget.Now()>Flags.PageCapS)return -1;if(Budget.Now()-t0>20)break;var t=Apply(nm,a);if(t==null)continue;rc=RoiRead(t,r);if(Finished(rc))return rc==0?0:-1;} + if(!small){Flags.Mix=1;rc=Attempt(a,r,6000);Flags.Mix=0;} + return rc==0?0:-1; + } + } +} diff --git a/ports/csharp/reader/PrismChainFilters.cs b/ports/csharp/reader/PrismChainFilters.cs new file mode 100644 index 0000000..aabf5b7 --- /dev/null +++ b/ports/csharp/reader/PrismChainFilters.cs @@ -0,0 +1,95 @@ +// Comb Code retry-chain low-light and glare transforms. +using System; +namespace Prism.Reader +{ + internal static partial class Chain + { + private static ChainImage Llb(ChainImage a) + { + int w=a.W,h=a.H,n=w*h;var d=a.Px;double sum=0; + for(int i=0;i45||!BudgetOk())return null; + int r=5;var k=new float[11];double ks=0; + for(int i=-r;i<=r;i++){k[i+r]=(float)JsMath.Exp(-(double)i*i/(2*1.5*1.5));ks+=k[i+r];} + for(int i=0;i=pl){lo=v;break;}} + acc=0;for(int v=255;v>=0;v--){acc+=hist[v];if(acc>=pl){hi=v;break;}} + if(hi-lo<4)return null;var lut=new byte[256];for(int v=0;v<256;v++)lut[v]=U8(JsMath.Pow(Math.Clamp((double)(v-lo)/(hi-lo),0,1),.6)*255); + var o=new ChainImage(w,h);for(int i=0;ib?v:b):(vb?v:b):(v=w)continue;v+=(double)a[y*w+xx]*k[j+r];wt+=k[j+r];}t[y*w+x]=(float)(v/wt);} + for(int y=0;y=h)continue;v+=(double)t[yy*w+x]*k[j+r];wt+=k[j+r];}o[y*w+x]=(float)(v/wt);}return o; + } + private static ChainImage Gln(ChainImage a) + { + if(!BudgetOk())return null;int w=a.W,h=a.H,hw=w>>1,hh=h>>1,n=hw*hh;var d=a.Px;var lo=new float[3][];var hi=new float[3][]; + for(int c=0;c<3;c++) + {var ch=new float[n];for(int y=0;y=0&&yy=0&&xx (int)Math.Floor(x+0.5); + private static byte U8(double x) => !(x>0)?(byte)0:x>255?(byte)255:(byte)Math.Round(x,MidpointRounding.ToEven); + private static double budgetT0=-1; + private static bool BudgetOk() { if(budgetT0<0)budgetT0=Budget.Now(); return Budget.Now()-budgetT0<14; } + private static ChainImage Crop(ChainImage a,int sx,int sy,int w,int h) + { + var o=new ChainImage(w,h); + for(int y=0;y=th){hi=v;break;}} + double g=255.0/Math.Max(30,hi);var o=new ChainImage(a.W,a.H); + for(int p=0;p=0&&yy=0&&xxbest){best=norm;bx=x;by=y;bs=sg;}}} + return (bx,by,bs); + } + private static ChainImage ZoomAuto(ChainImage a,bool nn) + { + int w=a.W,h=a.H,gw=Math.Max(32,Round(w/8.0)),gh=Math.Max(32,Round(h/8.0));var (gx,gy,sg)=GridBest(a); + double px=(double)gx/gw*w,py=(double)gy/gh*h,ps=(double)sg/gw*w,m=ps*0.8; + int x0=Math.Max(0,Round(px-m)),y0=Math.Max(0,Round(py-m)),side=Math.Min(Math.Min(w-x0,h-y0),Round(ps+2*m)); + int n=Math.Min(nn?1400:1200,Round(side*(nn?6:5)));var r=Resize(Crop(a,x0,y0,side,side),n,n,!nn);return nn?r:Unsharp(r,1); + } + private static ChainImage CrPlain(ChainImage a) + { + int w=a.W,h=a.H,n=w*h;var d=a.Px;var lum=new float[n];var amp=new float[n];var tmp=new float[n];var bl=new float[n]; + for(int i=0,p=0;i=0)s-=amp[y*w+x-rad-1];bl[y*w+x]=(float)(s/(Math.Min(w-1,x+rad)-Math.Max(0,x-rad-1)));}} + for(int x=0;x=0)s-=bl[(y-rad-1)*w+x];tmp[y*w+x]=(float)(s/(Math.Min(h-1,y+rad)-Math.Max(0,y-rad-1)));}} + var o=new ChainImage(w,h); + for(int i=0,p=0;i255){double s=255/m;r*=s;g*=s;b*=s;} + o.Px[p]=U8(r);o.Px[p+1]=U8(g);o.Px[p+2]=U8(b);o.Px[p+3]=255;} + return o; + } + private static float[] Gk(double sig,out int r) + { + r=Math.Min(16,(int)Math.Ceiling(sig*3));var k=new float[2*r+1];double s=0; + for(int i=-r;i<=r;i++){double v=JsMath.Exp(-(double)i*i/(2*sig*sig));k[i+r]=(float)v;s+=v;} + for(int i=0;i(n>>1)){med[c]=v;break;}}} + var mask=new bool[n];var den=new bool[n];var lab=new int[n];Array.Fill(lab,-1);var sizes=new List();var stk=new int[n]; + for(int i=0;i90; + for(int y=0;y=0&&yy=0&&xx=3;} + for(int y=0;y=0)continue;int id=sizes.Count,sz=0,sp=0;stk[sp++]=p;lab[p]=id; + while(sp>0){int q=stk[--sp],cx=q%gw,cy=q/gw;sz++; + int[] nb={cx+10?q-1:-1,cy+10?q-gw:-1}; + foreach(int v in nb)if(v>=0&&den[v]&&lab[v]<0){lab[v]=id;stk[sp++]=v;}} + sizes.Add(sz); + } + if(sizes.Count==0)return null;int best=0;for(int i=1;isizes[best])best=i;if(sizes[best]<16)return null; + int x0=gw,x1=0,y0=gh,y1=0; + for(int y=0;ymaxArea*w*h)return null;return new[]{sx,sy,ex-sx,ey-sy}; + } + private static ChainImage SaliencyCrop(ChainImage a) + {var b=SaliencyBox(a,.15,.6);return b==null?a:Crop(a,b[0],b[1],b[2],b[3]);} + private static double lastRatio; + private static int MotionAngle(ChainImage a) + { + int w=a.W,h=a.H;var d=a.Px;var g=new float[w*h];var e=new double[60]; + for(int i=0;i>1;for(;(j&bit)!=0;bit>>=1)j^=bit;j^=bit;if(i offs) + { + var o=new float[src.Length];double kw=1.0/offs.Count; + for(int y=0;y(); + for(int t=-(length-1)/2;t<=(length-1)/2;t++){var v=(Round(dx*t),Round(dy*t));if(!offs.Contains(v))offs.Add(v);} + var y=ToF(a);var est=(float[])y.Clone(); + for(int it=0;it.Create((a, b) => + { + double d = axis != 0 ? ys[a] - ys[b] : xs[a] - xs[b]; + if (d != 0) return d < 0 ? -1 : 1; + return a - b; + })); + int a2 = n >> 1; + Node nd = new Node { Id = ids[start + a2], Axis = axis }; + nd.Left = Build(ids, start, a2, 1 - axis); + nd.Right = Build(ids, start + a2 + 1, n - a2 - 1, 1 - axis); + return nd; + } + private void QueryRec(Node l, double r, double o, int a, int excl, KdHit[] g, ref int gn) + { + if (l == null) return; + double hx = xs[l.Id], hy = ys[l.Id]; + double n2 = hx - r, s = hy - o, C = n2 * n2 + s * s; + if (l.Id != excl) + { + int A2 = 0; + for (; A2 < gn && (g[A2].D < C || (g[A2].D == C && g[A2].Id < l.Id)); A2++) { } + if (A2 < a) + { + int newn = gn + 1; if (newn > a) newn = a; + for (int k = newn - 1; k > A2; k--) g[k] = g[k - 1]; + g[A2].Id = l.Id; g[A2].D = C; + gn = newn; + } + } + double Q = l.Axis != 0 ? o - hy : r - hx; + Node E = Q < 0 ? l.Left : l.Right, B = Q < 0 ? l.Right : l.Left; + QueryRec(E, r, o, a, excl, g, ref gn); + if (gn < a || Q * Q <= g[gn - 1].D) QueryRec(B, r, o, a, excl, g, ref gn); + } + public int Query(double x, double y, int a, int excl, KdHit[] g) + { + int gn = 0; + QueryRec(root, x, y, a, excl, g, ref gn); + return gn; + } + } + + internal struct PrismMeshPt { public double X, Y, Dx, Dy; } + + internal sealed class PrismMesh + { + public int N; + public PrismMeshPt[] Pts; + public KdTree Tree; + } + + internal sealed class PrismRef + { + public PrismCell C; + public double[] O = new double[3]; + public double[] E = new double[3]; + public double[] Res = new double[3]; + } + + internal sealed class PrismCalib + { + public double[][] M = { new double[4], new double[4], new double[4] }; + public double Sigma; + public PrismRef[] Refs; public int NRefs; + public KdTree Tree; + } + + internal static class Classify + { + private const string ErrSing = "geometry:Singular geometry"; + + private static double MedianJs(double[] A, int n) + { + Array.Sort(A, 0, n); + return A[n >> 1]; + } + + public static void MeshEval(PrismMesh m, double x, double y, double[] outBuf) + { + if (m == null || m.N == 0) { outBuf[0] = 0; outBuf[1] = 0; return; } + KdHit[] g = new KdHit[4]; + int gn = m.Tree.Query(x, y, 4, -1, g); + double a = 0, i2 = 0, s = 0; + for (int k = 0; k < gn; k++) + { + double e = 1 / (g[k].D + 0.05); + a += m.Pts[g[k].Id].Dx * e; i2 += m.Pts[g[k].Id].Dy * e; s += e; + } + outBuf[0] = a / s; outBuf[1] = i2 / s; + } + + private static void EdgeVec(PrismMap A, double e, double t, double r, double o, double[] outBuf) + { + Image.MapPoint(A, e, t, out double ax, out double ay); + Image.MapPoint(A, e + r, t + o, out double bx, out double by); + outBuf[0] = bx - ax; outBuf[1] = by - ay; + } + + private static PrismMesh QaBuild(PrismFrame A, PrismMap e, PrismLayout t, int r, double[] o, PrismMesh a, bool dense) + { + double[,] lab = new double[9, 3], pal = new double[9, 3]; + Image.PalDump(pal, lab); + double[] ev = new double[2]; + EdgeVec(e, t.W / 2, t.H / 2, 1, 0, ev); + double g = JsMath.Hypot2(ev[0], ev[1]); + PrismMesh m = new PrismMesh(); + m.Pts = new PrismMeshPt[t.Known.Length]; + double[] i2 = new double[2], I2 = new double[2], C = new double[3], U2 = new double[3], labS = new double[3]; + for (int ci = 0; ci < t.Known.Length; ci++) + { + PrismCell tc = t.Known[ci]; + if (!dense && tc.Role != (int)Role.Pilot) continue; + I2[0] = 0; I2[1] = 0; + Image.MapPoint(e, tc.X, tc.Y, out i2[0], out i2[1]); + if (a != null) MeshEval(a, tc.X, tc.Y, I2); + double h = double.PositiveInfinity; + double ndx = 0, ndy = 0; + int s = Image.KnownSymbol(tc, r); + for (int e2 = -2; e2 <= 2; e2++) + for (int r2 = -2; r2 <= 2; r2++) + { + double a2 = I2[0] + 0.3 * r2 * g, l2 = I2[1] + 0.3 * e2 * g; + Image.FrameSample(A, i2[0] + a2, i2[1] + l2, C); + C[0] /= o[0]; C[1] /= o[1]; C[2] /= o[2]; + Image.LabOf(C, U2); + labS[0] = lab[s, 0]; labS[1] = lab[s, 1]; labS[2] = lab[s, 2]; + double Q = Image.LabDist2(U2, labS); + double E = (0.2 * (a2 * a2 + l2 * l2)) / (g * g); + if (Q + E < h) { h = Q + E; ndx = a2; ndy = l2; } + } + m.Pts[m.N].X = tc.X; m.Pts[m.N].Y = tc.Y; + m.Pts[m.N].Dx = ndx; m.Pts[m.N].Dy = ndy; + m.N++; + } + if (m.N != 0) + { + double[] xs = new double[m.N], ys = new double[m.N]; + for (int i = 0; i < m.N; i++) { xs[i] = m.Pts[i].X; ys[i] = m.Pts[i].Y; } + KdTree tr = new KdTree(xs, ys, m.N); + double gate = (dense ? 0.8 : 0.3) * g; + bool[] keepf = new bool[m.N]; + KdHit[] hits = new KdHit[8]; + for (int i = 0; i < m.N; i++) + { + int hn = tr.Query(m.Pts[i].X, m.Pts[i].Y, 8, i, hits); + bool keep = true; + if (hn != 0) + { + double[] dxs = new double[hn], dys = new double[hn]; + for (int k = 0; k < hn; k++) { dxs[k] = m.Pts[hits[k].Id].Dx; dys[k] = m.Pts[hits[k].Id].Dy; } + double mx = MedianJs(dxs, hn), my = MedianJs(dys, hn); + keep = JsMath.Hypot2(m.Pts[i].Dx - mx, m.Pts[i].Dy - my) <= gate; + } + keepf[i] = keep; + } + int w = 0; + for (int i = 0; i < m.N; i++) if (keepf[i]) m.Pts[w++] = m.Pts[i]; + m.N = w; + } + { + double[] xs = new double[m.N], ys = new double[m.N]; + for (int i = 0; i < m.N; i++) { xs[i] = m.Pts[i].X; ys[i] = m.Pts[i].Y; } + m.Tree = new KdTree(xs, ys, m.N); + } + return m; + } + public static PrismMesh QaBuildMesh(PrismFrame A, PrismMap e, PrismLayout t, int r, double[] o, PrismMesh a) => QaBuild(A, e, t, r, o, a, false); + public static PrismMesh QaBuildDenseMesh(PrismFrame A, PrismMap e, PrismLayout t, int r, double[] o, PrismMesh a) => QaBuild(A, e, t, r, o, a, true); + + public static int Calibrate(PrismFrame A, PrismMap e, PrismLayout t, int r, double[] o, PrismMesh a, out PrismCalib outCb, out string err) + { + double[,] pal = new double[9, 3], lab = new double[9, 3]; + Image.PalDump(pal, lab); + PrismCalib cb = new PrismCalib(); + outCb = cb; err = null; + cb.Refs = new PrismRef[t.Known.Length]; + double[] smp = new double[3], mv = new double[2]; + for (int ci = 0; ci < t.Known.Length; ci++) + { + PrismCell tc = t.Known[ci]; + int s = Image.KnownSymbol(tc, r); + double mdx = 0, mdy = 0; + if (a != null) { MeshEval(a, tc.X, tc.Y, mv); mdx = mv[0]; mdy = mv[1]; } + Image.SampleCellEx(A, e, tc, o, mdx, mdy, 0, smp); + if (!(8 == s || !(smp[0] > 0.9 && smp[1] > 0.9 && smp[2] > 0.9))) continue; + PrismRef rf = new PrismRef { C = tc }; + rf.O[0] = smp[0]; rf.O[1] = smp[1]; rf.O[2] = smp[2]; + rf.E[0] = pal[s, 0]; rf.E[1] = pal[s, 1]; rf.E[2] = pal[s, 2]; + cb.Refs[cb.NRefs++] = rf; + } + double[,] g = new double[4, 4]; double[,] h = new double[3, 4]; + for (int ri = 0; ri < cb.NRefs; ri++) + { + double[] e2 = { cb.Refs[ri].O[0], cb.Refs[ri].O[1], cb.Refs[ri].O[2], 1 }; + for (int t2 = 0; t2 < 4; t2++) + { + for (int A2 = 0; A2 < 4; A2++) g[t2, A2] += e2[t2] * e2[A2]; + for (int r2 = 0; r2 < 3; r2++) h[r2, t2] += e2[t2] * cb.Refs[ri].E[r2]; + } + } + for (int A2 = 0; A2 < 4; A2++) g[A2, A2] += 0.001; + for (int c = 0; c < 3; c++) + { + double[] gflat = new double[16]; + for (int i2 = 0; i2 < 4; i2++) for (int j = 0; j < 4; j++) gflat[i2 * 4 + j] = g[i2, j]; + double[] hc = { h[c, 0], h[c, 1], h[c, 2], h[c, 3] }; + if (Image.SolveN(4, gflat, hc, cb.M[c]) != 0) { err = ErrSing; return -1; } + } + for (int ri = 0; ri < cb.NRefs; ri++) + { + double[] o2 = cb.Refs[ri].O, E2 = cb.Refs[ri].E; + for (int c = 0; c < 3; c++) + { + double v = cb.M[c][0] * o2[0] + cb.M[c][1] * o2[1] + cb.M[c][2] * o2[2] + cb.M[c][3]; + cb.Refs[ri].Res[c] = E2[c] - v; + } + } + { + double[] xs = new double[cb.NRefs], ys = new double[cb.NRefs]; + for (int i = 0; i < cb.NRefs; i++) { xs[i] = cb.Refs[i].C.X; ys[i] = cb.Refs[i].C.Y; } + cb.Tree = new KdTree(xs, ys, cb.NRefs); + } + double[] B = new double[Math.Max(cb.NRefs, 1)]; + int nb = 0; + double[] cor = new double[3], u1 = new double[3], u2 = new double[3]; + for (int ri = 0; ri < cb.NRefs; ri++) + { + if (cb.Refs[ri].C.Role != (int)Role.Pilot) continue; + CalibCorrection(cb, cb.Refs[ri].O, cb.Refs[ri].C, cor); + Image.LabOf(cor, u1); Image.LabOf(cb.Refs[ri].E, u2); + B[nb++] = Math.Sqrt(Image.LabDist2(u1, u2)); + } + double med = nb != 0 ? MedianJs(B, nb) : 6; + cb.Sigma = Cm.Fmax(6, 1.4 * med); + return 0; + } + + public static void CalibCorrection(PrismCalib cb, double[] rgb, PrismCell c, double[] outBuf) + { + double[] t2 = new double[3]; + for (int i = 0; i < 3; i++) t2[i] = cb.M[i][0] * rgb[0] + cb.M[i][1] * rgb[1] + cb.M[i][2] * rgb[2] + cb.M[i][3]; + if (Flags.Calmed != 0) + { + KdHit[] hits = new KdHit[10]; + int hn = cb.Tree.Query(c.X, c.Y, 10, -1, hits); + for (int i = 0; i < 3; i++) + { + double[] rr = new double[Math.Max(hn, 1)]; + for (int k = 0; k < hn; k++) rr[k] = cb.Refs[hits[k].Id].Res[i]; + double m2 = hn != 0 ? MedianJs(rr, hn) : 0; + outBuf[i] = Cm.Clamp01(t2[i] + m2); + } + return; + } + KdHit[] hits6 = new KdHit[6]; + int hn6 = cb.Tree.Query(c.X, c.Y, 6, -1, hits6); + double o2 = 0; double[] a2 = new double[3]; + for (int k = 0; k < hn6; k++) + { + double w = 1 / (hits6[k].D + 0.05); + o2 += w; + for (int i = 0; i < 3; i++) a2[i] += w * cb.Refs[hits6[k].Id].Res[i]; + } + for (int i = 0; i < 3; i++) outBuf[i] = Cm.Clamp01(t2[i] + a2[i] / o2); + } + + public static void LlrBits(double[] rgb, int mode, double sigma, int glare, double[] outBuf) + { + if (glare != 0) { outBuf[0] = 0; outBuf[1] = 0; outBuf[2] = 0; return; } + double[,] lab = new double[9, 3], pal = new double[9, 3]; + double[] o2 = new double[3], h2 = new double[8], i2 = new double[8], lr = new double[3]; + Image.PalDump(pal, lab); + Image.LabOf(rgb, o2); + int na = mode != 0 ? 2 : 8; + for (int k = 0; k < na; k++) + { + int A2 = mode != 0 ? (k != 0 ? 8 : 0) : k; + lr[0] = lab[A2, 0]; lr[1] = lab[A2, 1]; lr[2] = lab[A2, 2]; + i2[k] = -Image.LabDist2(o2, lr) / (2 * sigma * sigma); + } + double g2 = i2[0]; + for (int k = 1; k < na; k++) if (i2[k] > g2) g2 = i2[k]; + for (int k = 0; k < na; k++) h2[k] = JsMath.Exp(i2[k] - g2); + int nvals = mode != 0 ? 1 : 3; + for (int A2 = 0; A2 < nvals; A2++) + { + double t2 = 1e-6, r2 = 1e-6; + for (int k = 0; k < na; k++) + { + int v = mode != 0 ? (k != 0 ? 8 : 0) : k; + int bit = mode != 0 ? (0 == v ? 1 : 0) : ((v ^ (v >> 1)) >> (2 - A2)) & 1; + if (bit != 0) t2 += h2[k]; else r2 += h2[k]; + } + outBuf[A2] = Cm.Fmax(-12, Cm.Fmin(12, JsMath.Log(r2 / t2))); + } + } + + public static int HeaderDecode24(float[] A, out PrismHeader outH, out string err) + { + outH = default; err = null; + byte[] e = new byte[24]; + for (int i = 0; i < 24; i++) e[i] = (byte)(A[i] < 0 ? 1 : 0); + int t2 = 0, o = 0, a = 0, i2, g, l = 0, I = 0; + for (int k = 0; k < 3; k++) o = (o << 1) | e[t2++]; + for (int k = 0; k < 2; k++) a = (a << 1) | e[t2++]; + i2 = e[t2++]; g = e[t2++]; + for (int k = 0; k < 13; k++) l = (l << 1) | e[t2++]; + for (int k = 0; k < 4; k++) I = (I << 1) | e[t2++]; + if (Foundations.Crc4Bits(e, 20) != I || o > 5) { err = "header:Header checksum did not pass"; return -1; } + PrismCapacity cap = new PrismCapacity(); + Foundations.CapacityGet(o, a, i2, cap); + if (l > cap.Payload) { err = "header:Invalid length"; return -1; } + outH = new PrismHeader { Size = o, Ecc = a, Mode = i2, Type = g, Length = l }; + return 0; + } + + private static int[] cA; + private static void CaInit() + { + if (cA != null) return; + int[] t = new int[24]; + for (int e = 0; e < 24; e++) + { + if (e >= 20) { t[e] = 1 << (23 - e); continue; } + byte[] t2 = new byte[20]; t2[e] = 1; + t[e] = Foundations.Crc4Bits(t2, 20); + } + cA = t; + } + + private struct HCand { public PrismHeader H; public double Cost; } + + private static List HeaderCandidates(float[] h, int size, int mode) + { + CaInit(); + List hc = new List(); + float[] r2 = (float[])h.Clone(); + for (int A2 = 0; A2 < 3; A2++) r2[A2] = ((size >> (2 - A2)) & 1) != 0 ? -36f : 36f; + r2[5] = mode != 0 ? -36f : 36f; + void Try(int[] subset, int ns) + { + int i2; + { + byte[] ib = new byte[24]; + for (int k = 0; k < 24; k++) ib[k] = (byte)(r2[k] < 0 ? 1 : 0); + i2 = Foundations.Crc4Bits(ib, 20); + int tail = 0; + for (int k = 20; k < 24; k++) tail = (tail << 1) | ib[k]; + i2 ^= tail; + } + for (int k = 0; k < ns; k++) + { + int A3 = subset[k]; + if ((r2[A3] < 0) != (-r2[A3] < 0)) i2 ^= cA[A3]; + } + if (i2 != 0) return; + float[] l2 = (float[])r2.Clone(); + double I2 = 0; + for (int k = 0; k < ns; k++) { l2[subset[k]] = -l2[subset[k]]; I2 += Math.Abs((double)h[subset[k]]); } + if (HeaderDecode24(l2, out PrismHeader hd, out _) == 0 && hd.Size == size && hd.Mode == mode && hc.Count < 600) + hc.Add(new HCand { H = hd, Cost = I2 }); + } + int[] o2 = new int[20]; int no = 0; + for (int k = 0; k < 24; k++) if (k != 0 && k != 1 && k != 2 && k != 5) o2[no++] = k; + for (int i = 1; i < no; i++) + { + int c = o2[i], j = i - 1; + while (j >= 0 && Math.Abs((double)h[o2[j]]) > Math.Abs((double)h[c])) { o2[j + 1] = o2[j]; j--; } + o2[j + 1] = c; + } + if (no > 12) no = 12; + Try(new int[0], 0); + for (int A2 = 0; A2 < no; A2++) + { + Try(new[] { o2[A2] }, 1); + for (int e2 = A2 + 1; e2 < no; e2++) + { + Try(new[] { o2[A2], o2[e2] }, 2); + for (int t2 = e2 + 1; t2 < no; t2++) Try(new[] { o2[A2], o2[e2], o2[t2] }, 3); + } + } + for (int i = 1; i < hc.Count; i++) + { + HCand c = hc[i]; int j = i - 1; + while (j >= 0 && hc[j].Cost > c.Cost) { hc[j + 1] = hc[j]; j--; } + hc[j + 1] = c; + } + List res = new List(); + for (int i = 0; i < hc.Count && res.Count < 12; i++) + { + bool dup = false; + foreach (var x in res) if (x.Equals(hc[i].H)) { dup = true; break; } + if (!dup) res.Add(hc[i].H); + } + return res; + } + + private static void MeshOff(PrismMesh mesh, PrismCell tc, out double mdx, out double mdy) + { + mdx = 0; mdy = 0; + if (mesh != null) { double[] mv = new double[2]; MeshEval(mesh, tc.X, tc.Y, mv); mdx = mv[0]; mdy = mv[1]; } + } + + private static double G(double v) => JsMath.Pow(Cm.Fmax(0, Cm.Fmin(1, v)), 0.4545); + + private sealed class VPt + { + public double[] B = new double[28]; public double[] O = new double[3]; public int S; public double W; + public VPt Clone() { VPt p = new VPt { S = S, W = W }; Array.Copy(B, p.B, 28); Array.Copy(O, p.O, 3); return p; } + } + + private sealed class Gauss8 { public double[] M = new double[3], V = new double[9]; public double Dt; } + + public static int UA(PrismFrame A, PrismMap e, PrismLayout r, int o, double[] a, PrismMesh mesh, out PrismClassify outC, out string err) + { + PrismClassify oc = new PrismClassify(); + outC = oc; err = null; + if (Flags.Mix != 0 && o == 0) + { + Budget.FastDeadlineSet(Budget.OverallDeadlineGet()); + double[] fit = Mix.MixFit(A, e.H, r); + PrismPayload z = Mix.MixRecover(A, fit, r, null); + if (z != null) + { + oc.MixDecoded = z; + oc.Header = z.Header; + oc.Headers[0] = z.Header; oc.NHeaders = 1; + oc.Stream = null; oc.NStream = 0; + oc.KnownMatch = 1; oc.Sigma = 6; + return 0; + } + } + if (Calibrate(A, e, r, o, a, mesh, out PrismCalib cb, out string cerr) != 0) { err = cerr; return -1; } + float[] h = new float[24]; + double[] smp = new double[3], cor = new double[3], llr = new double[3]; + for (int hi = 0; hi < r.Headers.Length; hi++) + { + PrismCell tc = r.Headers[hi]; + MeshOff(mesh, tc, out double mdx, out double mdy); + Image.SampleCellEx(A, e, tc, a, mdx, mdy, 0, smp); + CalibCorrection(cb, smp, tc, cor); + LlrBits(cor, 1, cb.Sigma, 0, llr); + h[tc.Header % 24] = (float)((double)h[tc.Header % 24] + llr[0]); + } + Array.Copy(h, oc.Hb, 24); + List n = HeaderCandidates(h, r.Size, o); + List nf = new List(); + foreach (var hv in n) + { + if (hv.Length != 0) { nf.Add(hv); continue; } + if (HeaderDecode24(h, out PrismHeader hd, out _) == 0 && hd.Equals(hv)) nf.Add(hv); + } + n = nf; + if (n.Count == 0) { err = "header:Header checksum did not pass"; return -1; } + PrismHeader s = n[0]; + if (s.Size != r.Size || s.Mode != o) { err = "header:Header conflicts with geometry"; return -1; } + oc.Header = s; + oc.NHeaders = n.Count; + for (int i = 0; i < n.Count; i++) oc.Headers[i] = n[i]; + int nData = r.Data.Length; + int stride = o != 0 ? 1 : 3; + oc.NStream = nData * stride; + oc.Stream = new float[oc.NStream]; + oc.Points = new PrismPointConf[nData]; + oc.NPoints = nData; + oc.ExtGlare = new int[nData]; oc.NExtGlare = 0; + oc.GlareSamples = new PrismGlareSample[nData]; oc.NGlare = 0; + int f = 0; + double[] I2 = new double[3], h2 = new double[3], s2 = new double[3]; + for (int di = 0; di < nData; di++) + { + PrismCell tc = r.Data[di]; + MeshOff(mesh, tc, out double mdx, out double mdy); + Image.SampleCellEx(A, e, tc, a, mdx, mdy, 0, I2); + CalibCorrection(cb, I2, tc, h2); + bool n2 = o == 0 && I2[0] > 0.9 && I2[1] > 0.9 && I2[2] > 0.9; + LlrBits(h2, o, cb.Sigma, n2 ? 1 : 0, s2); + int ns = o != 0 ? 1 : 3; + if (o == 0 && r.Size <= 1 && !n2 && I2[0] > 0.7 && I2[1] > 0.7 && I2[2] > 0.7) + oc.ExtGlare[oc.NExtGlare++] = f; + if (n2 && r.Size <= 1) + { + oc.GlareSamples[oc.NGlare].At = f; + oc.GlareSamples[oc.NGlare].Cv = new[] { h2[0], h2[1], h2[2] }; + oc.NGlare++; + } + for (int A2 = 0; A2 < ns; A2++) oc.Stream[f++] = (float)s2[A2]; + double mn = Math.Abs(s2[0]); + for (int A2 = 1; A2 < ns; A2++) if (Math.Abs(s2[A2]) < mn) mn = Math.Abs(s2[A2]); + oc.Points[di].X = tc.X; oc.Points[di].Y = tc.Y; + oc.Points[di].Confidence = mn / 12; + } + double[,] pal = new double[9, 3], lab = new double[9, 3]; + if (Flags.Veil != 0 && o == 0) Veil(A, e, r, o, a, mesh, oc, pal, lab); + if (Flags.Dd != 0 && o == 0) Dd(A, e, r, o, a, mesh, oc, cb, pal, lab); + { + int c = 0; + for (int ri = 0; ri < cb.NRefs; ri++) + { + CalibCorrection(cb, cb.Refs[ri].O, cb.Refs[ri].C, cor); + if (Image.NearestSym(cor, o, out double d2) == Image.KnownSymbol(cb.Refs[ri].C, o)) c++; + } + oc.KnownMatch = cb.NRefs != 0 ? (double)c / cb.NRefs : double.NaN; + } + oc.Sigma = cb.Sigma; + return 0; + } + + private static void Veil(PrismFrame A, PrismMap e, PrismLayout r, int o, double[] a, PrismMesh mesh, PrismClassify oc, double[,] pal, double[,] lab) + { + Image.PalDump(pal, lab); + double[][] vP = new double[8][]; + for (int s2 = 0; s2 < 8; s2++) + { + vP[s2] = new double[3]; + for (int c = 0; c < 3; c++) vP[s2][c] = JsMath.Pow(Cm.Fmax(0, Cm.Fmin(1, pal[s2, c])), 0.4545); + } + void VB(double x, double y, double[] q) + { + double u = (2.0 * x) / r.W - 1, w2 = (2.0 * y) / r.H - 1; + int n_ = 0; + for (int d = 0; d <= 6; d++) for (int k = 0; k <= d; k++) + q[n_++] = JsMath.Pow(u, d - k) * JsMath.Pow(w2, k); + } + List vA = new List(); + double[] smp = new double[3]; + for (int ci = 0; ci < r.Known.Length; ci++) + { + PrismCell tc = r.Known[ci]; + int s2 = Image.KnownSymbol(tc, o); + if (s2 < 0 || s2 >= 8) continue; + MeshOff(mesh, tc, out double mdx, out double mdy); + Image.SampleCellEx(A, e, tc, a, mdx, mdy, 0, smp); + VPt p = new VPt(); + VB(tc.X, tc.Y, p.B); + for (int c = 0; c < 3; c++) p.O[c] = JsMath.Pow(Cm.Fmax(0, Cm.Fmin(1, smp[c])), 0.4545); + p.S = s2; p.W = 1; + vA.Add(p); + } + int nvA = vA.Count; + int vNn = r.Data.Length; + VPt[] vX = new VPt[vNn]; + for (int di = 0; di < vNn; di++) + { + PrismCell tc = r.Data[di]; + MeshOff(mesh, tc, out double mdx, out double mdy); + Image.SampleCellEx(A, e, tc, a, mdx, mdy, 0, smp); + VPt p = new VPt(); + VB(tc.X, tc.Y, p.B); + for (int c = 0; c < 3; c++) p.O[c] = JsMath.Pow(Cm.Fmax(0, Cm.Fmin(1, smp[c])), 0.4545); + p.S = 0; p.W = 1; + vX[di] = p; + } + if (nvA < 40) return; + const int vN = 28, vM = 56; + void VS(double[][] Mx, double[] y, double[] z) + { + for (int c = 0; c < vM; c++) + { + int p2 = c; + for (int k = c + 1; k < vM; k++) if (Math.Abs(Mx[k][c]) > Math.Abs(Mx[p2][c])) p2 = k; + double[] tm = Mx[c]; Mx[c] = Mx[p2]; Mx[p2] = tm; + double ty = y[c]; y[c] = y[p2]; y[p2] = ty; + double dv = Mx[c][c]; if (!(dv != 0.0)) dv = 1e-12; + for (int k = c + 1; k < vM; k++) + { + double f2 = Mx[k][c] / dv; + if (f2 != 0) + { + for (int j = c; j < vM; j++) Mx[k][j] -= f2 * Mx[c][j]; + y[k] -= f2 * y[c]; + } + } + } + for (int c = 0; c < vM; c++) z[c] = 0; + for (int c = vM - 1; c >= 0; c--) + { + double sm = y[c]; + for (int j = c + 1; j < vM; j++) sm -= Mx[c][j] * z[j]; + double dv = Mx[c][c]; if (!(dv != 0.0)) dv = 1e-12; + z[c] = sm / dv; + } + } + double[][] cf = { new double[56], new double[56], new double[56] }; + void VF(List pts2, int npts) + { + for (int c = 0; c < 3; c++) + { + double[][] Mx = new double[vM][]; + for (int k = 0; k < vM; k++) Mx[k] = new double[vM]; + double[] y = new double[vM]; + double[] f2 = new double[56]; + for (int p2 = 0; p2 < npts; p2++) + { + VPt pp = pts2[p2]; + if (!(pp.W > 0)) continue; + double pc = vP[pp.S][c]; + for (int k = 0; k < vN; k++) { f2[k] = pp.B[k] * pc; f2[vN + k] = pp.B[k]; } + for (int k = 0; k < vM; k++) + { + double fk = pp.W * f2[k]; + if (fk == 0) continue; + double[] row = Mx[k]; + for (int j = 0; j <= k; j++) row[j] += fk * f2[j]; + y[k] += fk * pp.O[c]; + } + } + for (int k = 0; k < vM; k++) + { + for (int j = k + 1; j < vM; j++) Mx[k][j] = Mx[j][k]; + Mx[k][k] += 1e-6; + } + double[] z = new double[56]; + VS(Mx, y, z); + Array.Copy(z, cf[c], 56); + } + } + double[] vDs = new double[vNn * 8]; + int[] vPr = new int[vNn]; + double[] vMg = new double[vNn]; + void VC(VPt p2, int off) + { + for (int s2 = 0; s2 < 8; s2++) + { + double d = 0; + for (int c = 0; c < 3; c++) + { + double av = 0, bv = 0; + for (int k = 0; k < vN; k++) { av += cf[c][k] * p2.B[k]; bv += cf[c][vN + k] * p2.B[k]; } + double df = vP[s2][c] * av + bv - p2.O[c]; + d += df * df; + } + vDs[off + s2] = Math.Sqrt(d); + } + } + void VCl() + { + for (int k = 0; k < vNn; k++) + { + int off = k * 8; + VC(vX[k], off); + int b0 = 0, b1 = -1; + for (int s2 = 1; s2 < 8; s2++) + { + if (vDs[off + s2] < vDs[off + b0]) { b1 = b0; b0 = s2; } + else if (b1 < 0 || vDs[off + s2] < vDs[off + b1]) b1 = s2; + } + vPr[k] = b0; vMg[k] = vDs[off + b1] - vDs[off + b0]; + } + } + List pts = new List(); + for (int i = 0; i < nvA; i++) pts.Add(vA[i]); + VF(pts, nvA); + VCl(); + for (int it = 0; it < 3; it++) + { + pts = new List(); + for (int i = 0; i < nvA; i++) { VPt q = vA[i].Clone(); q.W = 1; pts.Add(q); } + for (int k = 0; k < vNn; k++) + { + VPt q = vX[k].Clone(); + q.S = vPr[k]; + q.W = Cm.Fmin(1, vMg[k] / 0.078); + pts.Add(q); + } + VF(pts, pts.Count); + VCl(); + } + double[] vBest = new double[Math.Max(vNn, 1)]; + for (int k = 0; k < vNn; k++) vBest[k] = vDs[k * 8 + vPr[k]]; + double vSg = 0.015; + if (vNn != 0) + { + double med = MedianJs(vBest, vNn); + vSg = Cm.Fmax(0.015, (1.3 * med) / 1.54); + } + double[] pp8 = new double[8]; + for (int k = 0; k < vNn; k++) + { + int off = k * 8; + double mn = vDs[off]; + for (int s2 = 1; s2 < 8; s2++) if (vDs[off + s2] < mn) mn = vDs[off + s2]; + for (int s2 = 0; s2 < 8; s2++) pp8[s2] = JsMath.Exp(-(vDs[off + s2] * vDs[off + s2] - mn * mn) / (2 * vSg * vSg)); + for (int b = 0; b < 3; b++) + { + double n0 = 1e-9, n1 = 1e-9; + for (int s2 = 0; s2 < 8; s2++) + { + if ((((s2 ^ (s2 >> 1)) >> (2 - b)) & 1) != 0) n1 += pp8[s2]; else n0 += pp8[s2]; + } + oc.Stream[k * 3 + b] = (float)Cm.Fmax(-12, Cm.Fmin(12, JsMath.Log(n0 / n1))); + } + double mnc = Math.Abs((double)oc.Stream[k * 3]); + if (Math.Abs((double)oc.Stream[k * 3 + 1]) < mnc) mnc = Math.Abs((double)oc.Stream[k * 3 + 1]); + if (Math.Abs((double)oc.Stream[k * 3 + 2]) < mnc) mnc = Math.Abs((double)oc.Stream[k * 3 + 2]); + oc.Points[k].Confidence = mnc / 12; + } + } + + private static void Est(List P2, double[] W2, int n2, Gauss8 g2) + { + double sw = 0; double[] m2 = new double[3]; + for (int j = 0; j < n2; j++) { sw += W2[j]; for (int k = 0; k < 3; k++) m2[k] += W2[j] * P2[j][k]; } + for (int k = 0; k < 3; k++) m2[k] /= sw; + double[] cm = new double[9]; + for (int j = 0; j < n2; j++) + for (int x = 0; x < 3; x++) + for (int y = 0; y < 3; y++) + cm[x * 3 + y] += W2[j] * (P2[j][x] - m2[x]) * (P2[j][y] - m2[y]); + for (int k = 0; k < 9; k++) cm[k] = cm[k] / sw + (k % 4 == 0 ? 3e-4 : 0); + double p0 = cm[0], p1 = cm[1], p2 = cm[2], p3 = cm[3], p4 = cm[4], p5 = cm[5], p6 = cm[6], p7 = cm[7], p8 = cm[8]; + double A1 = p4 * p8 - p5 * p7, B1 = -(p3 * p8 - p5 * p6), C1 = p3 * p7 - p4 * p6; + double dt = p0 * A1 + p1 * B1 + p2 * C1; + g2.Dt = dt; + g2.M[0] = m2[0]; g2.M[1] = m2[1]; g2.M[2] = m2[2]; + g2.V[0] = A1 / dt; + g2.V[1] = -(p1 * p8 - p2 * p7) / dt; + g2.V[2] = (p1 * p5 - p2 * p4) / dt; + g2.V[3] = B1 / dt; + g2.V[4] = (p0 * p8 - p2 * p6) / dt; + g2.V[5] = -(p0 * p5 - p2 * p3) / dt; + g2.V[6] = C1 / dt; + g2.V[7] = -(p0 * p7 - p1 * p6) / dt; + g2.V[8] = (p0 * p4 - p1 * p3) / dt; + } + + private static void Dd(PrismFrame A, PrismMap e, PrismLayout r, int o, double[] a, PrismMesh mesh, PrismClassify oc, PrismCalib cb, double[,] pal, double[,] lab) + { + Image.PalDump(pal, lab); + List[] K2 = new List[8]; + for (int s2 = 0; s2 < 8; s2++) K2[s2] = new List(); + for (int ri = 0; ri < cb.NRefs; ri++) + { + int s2 = Image.KnownSymbol(cb.Refs[ri].C, o); + if (s2 < 0 || s2 > 7) continue; + double[] v = new double[3]; + for (int c = 0; c < 3; c++) v[c] = G(cb.Refs[ri].O[c]); + K2[s2].Add(v); + } + bool okk = true; + for (int s2 = 0; s2 < 8; s2++) if (K2[s2].Count < 6) okk = false; + if (!(okk && K2[0].Count != 0 && !double.IsNaN(K2[0][0][0]) && !double.IsInfinity(K2[0][0][0]))) return; + Gauss8[] M = new Gauss8[8]; + for (int s2 = 0; s2 < 8; s2++) + { + double[] ones = new double[K2[s2].Count]; + for (int i = 0; i < ones.Length; i++) ones[i] = 1; + M[s2] = new Gauss8(); + Est(K2[s2], ones, K2[s2].Count, M[s2]); + } + int nData = r.Data.Length; + List DU = new List(); + List DK = new List(); + int ddf = 0, ddk = 0; + double[] smp = new double[3]; + for (int di = 0; di < nData; di++) + { + if (!((double)oc.Stream[ddf] == 0 && (double)oc.Stream[ddf + 1] == 0 && (double)oc.Stream[ddf + 2] == 0)) + { + PrismCell tc = r.Data[di]; + MeshOff(mesh, tc, out double mdx, out double mdy); + Image.SampleCellEx(A, e, tc, a, mdx, mdy, 0, smp); + double[] v = new double[3]; + for (int c = 0; c < 3; c++) v[c] = G(smp[c]); + DU.Add(v); DK.Add(ddk); + } + ddf += 3; ddk++; + } + int nDU = DU.Count; + void PO(double[] u, double[] pp) + { + double[] ll = new double[8]; + for (int s2 = 0; s2 < 8; s2++) + { + double d0 = u[0] - M[s2].M[0], d1 = u[1] - M[s2].M[1], d2 = u[2] - M[s2].M[2]; + double[] v = M[s2].V; + ll[s2] = -0.5 * (d0 * (v[0] * d0 + v[1] * d1 + v[2] * d2) + + d1 * (v[3] * d0 + v[4] * d1 + v[5] * d2) + + d2 * (v[6] * d0 + v[7] * d1 + v[8] * d2)) - + 0.5 * JsMath.Log(Cm.Fmax(1e-12, M[s2].Dt)); + } + double mx = ll[0]; + for (int s2 = 1; s2 < 8; s2++) if (ll[s2] > mx) mx = ll[s2]; + double sm = 0; + for (int s2 = 0; s2 < 8; s2++) { pp[s2] = JsMath.Exp(ll[s2] - mx); sm += pp[s2]; } + for (int s2 = 0; s2 < 8; s2++) pp[s2] /= sm; + } + for (int it = 0; it < 3; it++) + { + double[][] PS = new double[nDU][]; + for (int j = 0; j < nDU; j++) { PS[j] = new double[8]; PO(DU[j], PS[j]); } + for (int s2 = 0; s2 < 8; s2++) + { + int n2 = nDU + K2[s2].Count; + List P2 = new List(n2); + double[] W2 = new double[n2]; + for (int j = 0; j < nDU; j++) { P2.Add(DU[j]); W2[j] = PS[j][s2] + 1e-9; } + for (int j = 0; j < K2[s2].Count; j++) { P2.Add(K2[s2][j]); W2[nDU + j] = 1; } + Est(P2, W2, n2, M[s2]); + } + } + double[] ppv = new double[8]; + for (int j = 0; j < nDU; j++) + { + PO(DU[j], ppv); + int f2 = DK[j] * 3; + for (int b = 0; b < 3; b++) + { + double n0 = 1e-6, n1 = 1e-6; + for (int s2 = 0; s2 < 8; s2++) + { + if ((((s2 ^ (s2 >> 1)) >> (2 - b)) & 1) != 0) n1 += ppv[s2]; else n0 += ppv[s2]; + } + oc.Stream[f2 + b] = (float)Cm.Fmax(-12, Cm.Fmin(12, JsMath.Log(n0 / n1))); + } + double mnc = Math.Abs((double)oc.Stream[DK[j] * 3]); + if (Math.Abs((double)oc.Stream[DK[j] * 3 + 1]) < mnc) mnc = Math.Abs((double)oc.Stream[DK[j] * 3 + 1]); + if (Math.Abs((double)oc.Stream[DK[j] * 3 + 2]) < mnc) mnc = Math.Abs((double)oc.Stream[DK[j] * 3 + 2]); + oc.Points[DK[j]].Confidence = mnc / 12; + } + } + } +} diff --git a/ports/csharp/reader/PrismDecode.cs b/ports/csharp/reader/PrismDecode.cs new file mode 100644 index 0000000..de584eb --- /dev/null +++ b/ports/csharp/reader/PrismDecode.cs @@ -0,0 +1,427 @@ +// PrismDecode.cs - stream decode layer: PADK, padVote, PLcd, PLfb, dA2, dA0, dA, wA, mA. +// Transliterated from ports/c/reader/prism_decode.c. Float32 stores round like the JS Float32Array. +using System; +using System.Collections.Generic; +using System.Text; + +namespace Prism.Reader +{ + internal static class Decode + { + private static PrismErr Mk(string stage, string msg) => new PrismErr { Stage = stage, Msg = msg }; + private static void Set(PrismErr e, string stage, string msg) { e.Stage = stage; e.Msg = msg; } + private static void Copy(PrismErr from, PrismErr to) { to.Stage = from.Stage; to.Msg = from.Msg; } + + private static bool BudgetCheck(PrismErr err) + { + if (Budget.BudgetExceeded()) + { + if (err != null) Set(err, "budget", "Image needs a clearer view. Processing limit reached."); + return true; + } + return false; + } + + private static int PADK(int o) + { + uint x = unchecked((uint)(o + unchecked((int)0x9e3779b9)) * 0x85ebca6bu); + x ^= x >> 13; + x = unchecked(x * 0xc2b2ae35u); + x ^= x >> 16; + return (int)(x & 255); + } + + private static bool PadVote(PrismHeader h, float[] st) + { + if (!(h.Length > 0)) return true; + PrismCapacity c = new PrismCapacity(); Foundations.CapacityGet(h.Size, h.Ecc, h.Mode, c); + byte[] by = new byte[8192]; + for (int i = 0; i < c.N; i++) + { + int v = 0; + for (int k = 0; k < 8; k++) v = (v << 1) | (st[8 * i + k] < 0 ? 1 : 0); + by[i] = (byte)v; + } + int[] offs = new int[32]; int a = 0, maxn = 0; + for (int j = 0; j < c.NBlocks; j++) { offs[j] = a; a += c.Blocks[j].K; if (c.Blocks[j].N > maxn) maxn = c.Blocks[j].N; } + int at = 0, z = 0, q = 0; + for (int p = 0; p < maxn; p++) + for (int j = 0; j < c.NBlocks; j++) + { + PrismBlock b = c.Blocks[j]; + if (p < b.N) + { + if (p < b.K && offs[j] + p >= h.Length + 4) + { + int v = by[at]; + if (v == 0) z++; + if (v == PADK(offs[j] + p)) q++; + } + at++; + } + } + return q >= z; + } + + private sealed class RsCand { public byte[] Data = new byte[256]; public int Corrected, Erasures; public double Score; public int Seq; } + private sealed class RsBlock + { + public int N, Nsym, K, Offset; + public byte[] Bytes = new byte[256]; public float[] Conf = new float[256]; public byte[] Masks = new byte[256]; + public int[] Order = new int[256]; + public RsCand[] Cands = new RsCand[8]; public int NCands, CandSeq; + public bool[] Tried = new bool[128]; + public RsBlock() { for (int i = 0; i < 8; i++) Cands[i] = new RsCand(); } + } + + private static bool SameK(byte[] a, byte[] b, int k) { for (int i = 0; i < k; i++) if (a[i] != b[i]) return false; return true; } + + private static void CandPush(RsBlock e, byte[] data, int corrected, int erasures, double score) + { + for (int i = 0; i < e.NCands; i++) if (SameK(e.Cands[i].Data, data, e.K)) return; + if (e.NCands == 8) { if (!(score < e.Cands[7].Score)) return; } + RsCand c = e.Cands[e.NCands < 8 ? e.NCands++ : 7]; + Array.Copy(data, c.Data, e.K); + c.Corrected = corrected; c.Erasures = erasures; c.Score = score; c.Seq = e.CandSeq++; + for (int i = e.NCands - 1; i > 0; i--) + { + if (e.Cands[i].Score < e.Cands[i - 1].Score) { var tmp = e.Cands[i]; e.Cands[i] = e.Cands[i - 1]; e.Cands[i - 1] = tmp; } + else break; + } + } + + private static bool Utf8Valid(byte[] p, int n) + { + int i = 0; + while (i < n) + { + byte b = p[i]; + if (b < 0x80) { i++; continue; } + int need; uint minc, c; + if ((b & 0xe0) == 0xc0) { need = 1; c = (uint)(b & 0x1f); minc = 0x80; } + else if ((b & 0xf0) == 0xe0) { need = 2; c = (uint)(b & 0x0f); minc = 0x800; } + else if ((b & 0xf8) == 0xf0) { need = 3; c = (uint)(b & 0x07); minc = 0x10000; } + else return false; + if (i + need >= n) return false; + for (int k = 1; k <= need; k++) + { + byte cb = p[i + k]; + if ((cb & 0xc0) != 0x80) return false; + c = (c << 6) | (uint)(cb & 0x3f); + } + if (c < minc || c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff)) return false; + i += need + 1; + } + return true; + } + + private sealed class D2Ctx + { + public PrismHeader A; public RsBlock[] L; public int NBlocks; + public long Attempts, Valid; public byte[] Found; public int FCorrected, FErasures; public long CrcTried; + } + + private static void D2Dfs(D2Ctx cx, int o, byte[] a, int na, int ic, int ig) + { + if (cx.Found != null || cx.CrcTried >= 1024) return; + if (o == cx.NBlocks) + { + cx.CrcTried++; + int len = cx.A.Length; + uint want = 0; + for (int e = len; e < len + 4; e++) want = (want << 8) | a[e]; + if (Foundations.Crc32Bytes(a, len) == want) + { + if (cx.A.Type == 0 && !Utf8Valid(a, len)) return; + cx.Found = new byte[len]; + Array.Copy(a, cx.Found, len); + cx.FCorrected = ic; cx.FErasures = ig; + } + return; + } + RsBlock b = cx.L[o]; + for (int i = 0; i < b.NCands; i++) + { + Array.Copy(b.Cands[i].Data, 0, a, na, b.K); + D2Dfs(cx, o + 1, a, na + b.K, ic + b.Cands[i].Corrected, ig + b.Cands[i].Erasures); + if (cx.Found != null || cx.CrcTried >= 1024) return; + } + } + private static bool D2Combine(D2Ctx cx, byte[] work) + { + for (int i = 0; i < cx.NBlocks; i++) if (cx.L[i].NCands == 0) return false; + D2Dfs(cx, 0, work, 0, 0, 0); + return cx.Found != null; + } + + private static int DA2(PrismHeader A, float[] r, bool PK, PrismPayload outP, PrismErr err) + { + PrismCapacity o = new PrismCapacity(); Foundations.CapacityGet(A.Size, A.Ecc, A.Mode, o); + RsBlock[] l = new RsBlock[o.NBlocks]; + for (int i = 0; i < o.NBlocks; i++) l[i] = new RsBlock(); + D2Ctx cx = new D2Ctx { A = A, L = l, NBlocks = o.NBlocks }; + int I = 0; + for (int bi = 0; bi < o.NBlocks; bi++) { l[bi].N = o.Blocks[bi].N; l[bi].Nsym = o.Blocks[bi].Nsym; l[bi].K = o.Blocks[bi].K; } + int maxn = 0; for (int bi = 0; bi < o.NBlocks; bi++) if (l[bi].N > maxn) maxn = l[bi].N; + byte[] ab = new byte[o.N]; float[] cf = new float[o.N]; byte[] mk = new byte[o.N]; + for (int i = 0; i < o.N; i++) + { + int e = 0; float t = 12; + for (int k = 0; k < 8; k++) + { + float a = r[8 * i + k]; + e = (e << 1) | (a < 0 ? 1 : 0); + if (a == 0) mk[i] |= (byte)(1 << (7 - k)); + if (Math.Abs(a) < t) t = Math.Abs(a); + } + ab[i] = (byte)e; cf[i] = t; + } + for (int p = 0; p < maxn; p++) + for (int bi = 0; bi < o.NBlocks; bi++) + if (p < l[bi].N) { l[bi].Bytes[p] = ab[I]; l[bi].Conf[p] = cf[I]; l[bi].Masks[p] = mk[I]; I++; } + int s = 0; + for (int bi = 0; bi < o.NBlocks; bi++) + { + RsBlock e = l[bi]; + e.Offset = s; + for (int t = 0; t < e.K; t++) + if (A.Length > 0 && s + t >= A.Length + 4) + { + e.Bytes[t] = (byte)(PK ? PADK(s + t) : 0); + e.Conf[t] = 12; e.Masks[t] = 0; + } + s += e.K; + for (int i = 0; i < e.N; i++) e.Order[i] = i; + for (int i = 1; i < e.N; i++) + { + int v = e.Order[i], j = i - 1; + while (j >= 0 && e.Conf[e.Order[j]] > e.Conf[v]) { e.Order[j + 1] = e.Order[j]; j--; } + e.Order[j + 1] = v; + } + } + byte[] work = new byte[o.K + 8]; + void Try(RsBlock eb, int rc_) + { + if (eb.Tried[rc_]) return; + eb.Tried[rc_] = true; cx.Attempts++; + byte[] buf = new byte[256]; Array.Copy(eb.Bytes, buf, eb.N); + int[] eras = new int[128]; for (int i = 0; i < rc_; i++) eras[i] = eb.Order[i]; + int corr = Foundations.RsDecode(buf, eb.N, eb.Nsym, eras, rc_, out _); + if (corr >= 0) + { + bool padok = true; + for (int t = 0; t < eb.K; t++) + if (eb.Offset + t >= A.Length + 4 && (PK ? PADK(eb.Offset + t) : 0) != buf[t]) { padok = false; break; } + if (padok) + { + cx.Valid++; + double sc = 0; + for (int i = 0; i < eb.N; i++) if (buf[i] != eb.Bytes[i]) sc += 0.02 + eb.Conf[i]; + CandPush(eb, buf, corr, rc_, sc); + } + } + } + bool done = false; + for (int bi = 0; bi < o.NBlocks; bi++) + { + RsBlock e = l[bi]; + int prev = -1; + for (int fi = 0; fi < 5; fi++) + { + int v = (int)Math.Floor((double)e.Nsym * ((double)fi / 4.0) + 0.5); + if (v == prev) continue; + prev = v; + Try(e, v); + if (e.NCands != 0) break; + } + } + if (D2Combine(cx, work)) done = true; + if (!done) + { + for (int bi = 0; bi < o.NBlocks; bi++) + { + RsBlock e = l[bi]; + for (int r2 = 0; r2 <= e.Nsym; r2 += 2) Try(e, r2); + } + if (D2Combine(cx, work)) done = true; + } + if (!done && A.Size <= 1) + { + for (int bi = 0; bi < o.NBlocks; bi++) + { + RsBlock t = l[bi]; + if (BudgetCheck(err)) return -1; + byte[] rb = new byte[256]; + int corr = Foundations.RsRecoverBits(t.Bytes, t.Masks, t.N, t.Nsym, rb, out _); + if (corr < 0) continue; + bool bad = false; + for (int e = 0; e < t.K; e++) + if (t.Offset + e >= A.Length + 4 && (PK ? PADK(t.Offset + e) : 0) != rb[e]) { bad = true; break; } + if (bad) continue; + bool dup = false; + for (int i = 0; i < t.NCands; i++) if (SameK(t.Cands[i].Data, rb, t.K)) { dup = true; break; } + if (!dup && t.NCands < 8) + { + RsCand c = t.Cands[t.NCands++]; + Array.Copy(rb, c.Data, t.K); + c.Corrected = corr; c.Erasures = 0; c.Score = 0; c.Seq = t.CandSeq++; + } + } + if (D2Combine(cx, work)) done = true; + } + if (!done) + { + bool someEmpty = false; + for (int bi = 0; bi < o.NBlocks; bi++) if (l[bi].NCands == 0) someEmpty = true; + if (someEmpty) Set(err, "RS", "Error correction could not recover this image"); + else Set(err, "CRC", "Payload checksum did not pass"); + return -1; + } + int len = A.Length; + outP.Bytes = cx.Found; outP.NBytes = len; + outP.Header = A; + outP.Corrected = cx.FCorrected; outP.Erasures = cx.FErasures; + outP.Text = A.Type == 0 ? Encoding.UTF8.GetString(cx.Found, 0, len) : null; + return 0; + } + + private static int DA0(PrismHeader A, float[] r, PrismPayload outP, PrismErr err) + { + bool t = PadVote(A, r); + if (DA2(A, r, t, outP, err) == 0) return 0; + PrismErr e1 = Mk(err.Stage, err.Msg); + if (DA2(A, r, !t, outP, err) == 0) return 0; + Copy(e1, err); + return -1; + } + + private struct CdEnt { public PrismCell C; public int K; public int B; } + + private static int Plfb(PrismHeader h, float[] st, PrismPayload outP, PrismErr err) + { + PrismLayout l = Foundations.LayoutGet(h.Size); + int N = l.Data.Length, m = h.Mode != 0 ? 1 : 3; + CdEnt[] cd = new CdEnt[N]; + double cx = l.W / 2, cy = l.H / 2; + for (int k = 0; k < N; k++) + { + double dx = l.Data[k].X - cx, dy = l.Data[k].Y - cy; + cd[k].C = l.Data[k]; cd[k].K = k; + cd[k].B = (int)Math.Floor(Math.Sqrt(dx * dx + dy * dy) / 3); + } + Array.Sort(cd, (p, q) => p.B != q.B ? q.B - p.B : p.K - q.K); + float[] s2 = new float[N * m]; + for (int k = 0; k < N; k++) + { + int p = -1; + for (int i = 0; i < N; i++) if (l.Data[i].Index == cd[k].C.Index) { p = i; break; } + for (int j = 0; j < m; j++) s2[k * m + j] = st[p * m + j]; + } + int n1 = (int)Math.Floor((double)N * 0.12); + double ga = 0, gc = 0; long gb = 0, gd = 0; + for (int k = 0; k < N; k++) + { + double v = 0; + for (int j = 0; j < m; j++) v += Math.Abs((double)s2[k * m + j]); + if (k >= N - n1) { ga += v; gb++; } + else if (k < N / 2) { gc += v; gd++; } + } + if (ga / (double)gb > (0.9 * gc) / (double)gd) { Set(err, "logo", "center-distance gate"); return -1; } + double[] fr = { 0.1, 0.18, 0.26, 0.34 }; + PrismErr last = Mk(err.Stage, err.Msg); + for (int fi = 0; fi < 4; fi++) + { + float[] s3 = (float[])s2.Clone(); + for (int k = (int)Math.Floor((double)N * (1 - fr[fi])); k < N; k++) + for (int j = 0; j < m; j++) s3[k * m + j] = 0; + if (DA0(h, s3, outP, err) == 0) return 0; + last = Mk(err.Stage, err.Msg); + } + Copy(last, err); + return -1; + } + + public static int DecodeStream(PrismHeader h, float[] st, PrismPayload outP, PrismErr err) + { + if (DA0(h, st, outP, err) == 0) return 0; + PrismErr e1 = Mk(err.Stage, err.Msg); + if (Flags.NoLogo == 0) { if (Plfb(h, st, outP, err) == 0) return 0; } + Copy(e1, err); + return -1; + } + + private static int WA(PrismClassify A, float[] stream, PrismPayload outP, PrismErr err) + { + PrismErr last = null; + int nh = A.NHeaders != 0 ? A.NHeaders : 1; + for (int ri = 0; ri < nh; ri++) + { + PrismHeader r = A.NHeaders != 0 ? A.Headers[ri] : A.Header; + if (BudgetCheck(err)) return -1; + for (int o = 0; o < 2; o++) + { + float[] a = stream; + if (o != 0) + { + PrismRng g = default; Foundations.RngSeed(ref g, 49374); + float[] white = new float[A.NStream]; + for (int i = 0; i < A.NStream; i++) white[i] = Foundations.RngNext(ref g) < 0.5 ? -stream[i] : stream[i]; + a = white; + } + if (DecodeStream(r, a, outP, err) == 0) { outP.Variant = o != 0 ? "generator-whitened" : "original"; return 0; } + last = Mk(err.Stage, err.Msg); + } + } + if (last != null) Copy(last, err); + else Set(err, "header", "Header checksum did not pass"); + return -1; + } + + public static int DecodeClass(PrismClassify A, PrismPayload outP, PrismErr err) + { + if (A.MixDecoded != null) + { + PrismPayload m = A.MixDecoded; + outP.Bytes = (byte[])m.Bytes.Clone(); outP.NBytes = m.NBytes; outP.Text = m.Text; outP.Header = m.Header; + outP.Corrected = m.Corrected; outP.Erasures = m.Erasures; outP.Variant = m.Variant; + return 0; + } + PrismErr t = Mk("", ""); + if (WA(A, A.Stream, outP, t) == 0) return 0; + bool skipGlare = A.NGlare == 0 || A.KnownMatch < 0.85; + if (skipGlare) Copy(t, err); + else + { + if (BudgetCheck(err)) return -1; + float[] r = new float[A.NStream]; + Array.Copy(A.Stream, r, A.NStream); + double[] llr = new double[3]; + for (int i = 0; i < A.NGlare; i++) + { + Classify.LlrBits(A.GlareSamples[i].Cv, 0, A.Sigma, 0, llr); + for (int j = 0; j < 3; j++) + { + int at = A.GlareSamples[i].At + j; + if (at >= 0 && at < A.NStream) r[at] = (float)(0.001 * llr[j]); + } + } + if (WA(A, r, outP, t) == 0) return 0; + } + if (A.NExtGlare == 0 || A.KnownMatch < 0.85) { Copy(t, err); return -1; } + if (BudgetCheck(err)) return -1; + { + float[] r = new float[A.NStream]; + Array.Copy(A.Stream, r, A.NStream); + for (int i = 0; i < A.NExtGlare; i++) + for (int j = 0; j < 3; j++) + { + int at = A.ExtGlare[i] + j; + if (at >= 0 && at < A.NStream) r[at] = 0; + } + if (WA(A, r, outP, t) == 0) return 0; + } + Copy(t, err); + return -1; + } + } +} diff --git a/ports/csharp/reader/PrismDetect.cs b/ports/csharp/reader/PrismDetect.cs new file mode 100644 index 0000000..7bb9c3a --- /dev/null +++ b/ports/csharp/reader/PrismDetect.cs @@ -0,0 +1,733 @@ +// PrismDetect.cs - exact port of detect: lApq (quad detect), lA (legacy +// boundary). Transliterated from the verified C port +// (ports/c/reader/prism_detect.c). All float32/double semantics replicated. +using System; +using System.Collections.Generic; + +namespace Prism.Reader +{ + internal sealed class PrismCand + { + public double[,] P = new double[4, 2]; + public int Sz; // -1: unknown (legacy lA) + public int R0; + } + + internal static class Detect + { + private static double Clampd(double v, double lo, double hi) { return v < lo ? lo : (v > hi ? hi : v); } + + /* ---- dynamic int-point list ---- */ + private sealed class IPts + { + public List X = new List(); + public List Y = new List(); + public int N => X.Count; + public void Push(int x, int y) { X.Add(x); Y.Add(y); } + public void Pop() { X.RemoveAt(X.Count - 1); Y.RemoveAt(Y.Count - 1); } + public void RemoveAt(int i) { X.RemoveAt(i); Y.RemoveAt(i); } + } + private sealed class DPts + { + public List X = new List(); + public List Y = new List(); + public int N => X.Count; + public void Push(double x, double y) { X.Add(x); Y.Add(y); } + public void RemoveAt(int i) { X.RemoveAt(i); Y.RemoveAt(i); } + } + + /* cross product eA on int points */ + private static long ICr(long ax, long ay, long bx, long by, long cx, long cy) + { + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); + } + private static double DCr(double ax, double ay, double bx, double by, double cx, double cy) + { + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); + } + + /* tA: convex hull of int points (monotone chain), JS semantics */ + private static void HullOf(List xs, List ys, IPts outPts) + { + int n = xs.Count; + int[] ix = new int[n]; + for (int i = 0; i < n; i++) ix[i] = i; + /* stable sort by (x,y) */ + for (int i = 1; i < n; i++) + { + int k = ix[i], j = i - 1; + while (j >= 0 && (xs[ix[j]] > xs[k] || (xs[ix[j]] == xs[k] && ys[ix[j]] > ys[k]))) { ix[j + 1] = ix[j]; j--; } + ix[j + 1] = k; + } + IPts lo = new IPts(), up = new IPts(); + for (int i = 0; i < n; i++) + { + int p = ix[i]; + while (lo.N >= 2 && ICr(lo.X[lo.N - 2], lo.Y[lo.N - 2], lo.X[lo.N - 1], lo.Y[lo.N - 1], xs[p], ys[p]) <= 0) lo.Pop(); + lo.Push(xs[p], ys[p]); + } + for (int i = n - 1; i >= 0; i--) + { + int p = ix[i]; + while (up.N >= 2 && ICr(up.X[up.N - 2], up.Y[up.N - 2], up.X[up.N - 1], up.Y[up.N - 1], xs[p], ys[p]) <= 0) up.Pop(); + up.Push(xs[p], ys[p]); + } + lo.Pop(); up.Pop(); + for (int i = 0; i < lo.N; i++) outPts.Push(lo.X[i], lo.Y[i]); + for (int i = 0; i < up.N; i++) outPts.Push(up.X[i], up.Y[i]); + } + + /* rA: polygon area (int points) */ + private static double PolyAreaI(List xs, List ys) + { + int n = xs.Count; + double a = 0; + for (int i = 0; i < n; i++) + { + int j = (i + 1) % n; + a += (double)xs[i] * ys[j] - (double)ys[i] * xs[j]; + } + return Math.Abs(a) / 2; + } + + /* iA: line fit -> out[3] = {g=-sin(t), l=cos(t), c=g*mx+l*my} */ + private static void LineFit(List xs, List ys, double[] outBuf) + { + int n = xs.Count; + double e = 0, t = 0; + for (int i = 0; i < n; i++) { e += xs[i]; t += ys[i]; } + e /= n; t /= n; + double r = 0, o = 0, a = 0; + for (int i = 0; i < n; i++) + { + double A = xs[i] - e, g = ys[i] - t; + r += A * A; o += A * g; a += g * g; + } + double i2 = 0.5 * JsMath.Atan2(2 * o, r - a); + double g2 = -JsMath.Sin(i2), l = JsMath.Cos(i2); + outBuf[0] = g2; outBuf[1] = l; outBuf[2] = g2 * e + l * t; + } + + /* gA: line intersection; returns 0 ok, -1 parallel */ + private static int LineIsect(double[] A, double[] B, out double x, out double y) + { + double t = A[0] * B[1] - A[1] * B[0]; + if (Math.Abs(t) < 1e-6) { x = 0; y = 0; return -1; } + x = (A[2] * B[1] - A[1] * B[2]) / t; + y = (A[0] * B[2] - A[2] * B[0]) / t; + return 0; + } + + /* oA: separable morphology with clamped window. o=1 dilate(or), 0 erode(and). */ + private static void MorphU8(byte[] A, int e, int t, int r, int o, byte[] outBuf) + { + byte[] a = new byte[e * t]; + for (int i = 0; i < t; i++) + for (int x = 0; x < e; x++) + { + int g = o != 0 ? 0 : 1; + for (int d = -r; d <= r; d++) + { + int rr = (int)Clampd(x + d, 0, e - 1); + if (o != 0) g |= A[i * e + rr]; else g &= A[i * e + rr]; + } + a[i * e + x] = (byte)g; + } + for (int i = 0; i < t; i++) + for (int x = 0; x < e; x++) + { + int g = o != 0 ? 0 : 1; + for (int d = -r; d <= r; d++) + { + int rr = (int)Clampd(i + d, 0, t - 1); + if (o != 0) g |= a[rr * e + x]; else g &= a[rr * e + x]; + } + outBuf[i * e + x] = (byte)g; + } + } + + /* aA: separable smooth (box mean, o=0) or sliding max (o=1), radius r, + clamped window. Float32 in/out; sums in double; deque max exactly as JS. */ + private static void SmoothF32(float[] A, int e, int t, int r, int o, float[] outBuf) + { + float[] a = new float[e * t]; + for (int i = 0; i < t; i++) + { + /* horizontal */ + double l = 0; + int g = 0, tn = 0; + int[] qx = new int[e + 2 * r + 2]; float[] qv = new float[e + 2 * r + 2]; + for (int h = -r; h < e + r; h++) + { + float n = A[i * e + (int)Clampd(h, 0, e - 1)]; + if (o != 0) + { + while (tn > g && qv[tn - 1] <= n) tn--; + qx[tn] = h; qv[tn] = n; tn++; + while (qx[g] < h - 2 * r) g++; + } + else + { + l += n; + if (h > r) l -= A[i * e + (int)Clampd(h - 2 * r - 1, 0, e - 1)]; + } + if (h >= r) a[i * e + h - r] = o != 0 ? qv[g] : (float)(l / (2 * r + 1)); + } + } + for (int x = 0; x < e; x++) + { + /* vertical */ + double l = 0; + int g = 0, tn = 0; + int[] qy = new int[t + 2 * r + 2]; float[] qv = new float[t + 2 * r + 2]; + for (int n2 = -r; n2 < t + r; n2++) + { + float s = a[(int)Clampd(n2, 0, t - 1) * e + x]; + if (o != 0) + { + while (tn > g && qv[tn - 1] <= s) tn--; + qy[tn] = n2; qv[tn] = s; tn++; + while (qy[g] < n2 - 2 * r) g++; + } + else + { + l += s; + if (n2 > r) l -= a[(int)Clampd(n2 - 2 * r - 1, 0, t - 1) * e + x]; + } + if (n2 >= r) outBuf[(n2 - r) * e + x] = o != 0 ? qv[g] : (float)(l / (2 * r + 1)); + } + } + } + + /* lApq-local box: edge-aware mean, radius r; Float32 in/out, double sums */ + private static float[] BoxLocal(float[] a, int w, int h, int r) + { + int n = w * h; + float[] t = new float[n], o = new float[n]; + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + { + double s = 0; int c = 0; + for (int d = -r; d <= r; d++) + { + int xx = x + d; + if (xx >= 0 && xx < w) { s += a[y * w + xx]; c++; } + } + t[y * w + x] = (float)(s / c); + } + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + { + double s = 0; int c = 0; + for (int d = -r; d <= r; d++) + { + int yy = y + d; + if (yy >= 0 && yy < h) { s += t[yy * w + x]; c++; } + } + o[y * w + x] = (float)(s / c); + } + return o; + } + + /* ---- lApq: quad detection ---- */ + public static int DetectLapq(PrismFrame f, List outList) + { + int sc = (int)Math.Max(1, Math.Floor(Math.Max(f.W, f.H) / 360.0 + 0.5)); /* Math.round */ + int w = f.W / sc, h = f.H / sc; + int n = w * h; + float[] S = new float[n]; + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + { + int i = ((y * sc + (sc >> 1)) * f.W + x * sc + (sc >> 1)) * 3; + float m = f.P[i]; + if (f.P[i + 1] < m) m = f.P[i + 1]; + if (f.P[i + 2] < m) m = f.P[i + 2]; + S[y * w + x] = (float)JsMath.Pow(m, 0.4545); + } + S = BoxLocal(S, w, h, 2); + /* Otsu */ + double[] hist = new double[256]; + for (int i = 0; i < n; i++) + { + int b = (int)Math.Floor((double)S[i] * 255 + 0.5); + if (b < 0) b = 0; if (b > 255) b = 255; + hist[b]++; + } + double sum = 0; + for (int i = 0; i < 256; i++) sum += i * hist[i]; + double wb = 0, sb = 0, bt = 0; + int th0 = 128; + for (int i = 0; i < 256; i++) + { + wb += hist[i]; + if (wb == 0) continue; + double wf = n - wb; + if (wf == 0) break; + sb += i * hist[i]; + double mb = sb / wb, mf = (sum - sb) / wf, v = wb * wf * (mb - mf) * (mb - mf); + if (v > bt) { bt = v; th0 = i; } + } + const double mg = 5.196; + int[] dths = { 0, 14, 28, -14 }; + for (int di = 0; di < 4; di++) + { + int th = th0 + dths[di]; + float[] m = new float[n]; + for (int i = 0; i < n; i++) m[i] = (double)S[i] * 255 > th ? 1 : 0; + m = BoxLocal(m, w, h, 2); + float[] m2 = new float[n]; + for (int i = 0; i < n; i++) m2[i] = (double)m[i] > 0.01 ? 1 : 0; + m2 = BoxLocal(m2, w, h, 2); + byte[] mk = new byte[n]; + for (int i = 0; i < n; i++) mk[i] = (double)m2[i] > 0.99 ? (byte)1 : (byte)0; + byte[] seen = new byte[n]; + int[] qu = new int[n]; + double bestA = 0; + IPts bestHull = new IPts(); + for (int k = 0; k < n; k++) + { + if (mk[k] == 0 || seen[k] != 0) continue; + int hd = 0, tl = 1; + IPts bd = new IPts(); + qu[0] = k; seen[k] = 1; + while (hd < tl) + { + int p = qu[hd++], x = p % w, y = (p - x) / w; + bool ed = false; + int[] qs = new int[4]; + qs[0] = x > 0 ? p - 1 : -1; + qs[1] = x < w - 1 ? p + 1 : -1; + qs[2] = y > 0 ? p - w : -1; + qs[3] = y < h - 1 ? p + w : -1; + for (int qi = 0; qi < 4; qi++) + { + int q = qs[qi]; + if (q < 0 || mk[q] == 0) { ed = true; continue; } + if (seen[q] == 0) { seen[q] = 1; qu[tl++] = q; } + } + if (ed) bd.Push(x, y); + } + if (tl < 0.03 * (double)n || tl > 0.9 * (double)n) continue; + /* sort bd by (x,y) - stable insertion sort */ + for (int i = 1; i < bd.N; i++) + { + int kx = bd.X[i], ky = bd.Y[i], j = i - 1; + while (j >= 0 && (bd.X[j] > kx || (bd.X[j] == kx && bd.Y[j] > ky))) { bd.X[j + 1] = bd.X[j]; bd.Y[j + 1] = bd.Y[j]; j--; } + bd.X[j + 1] = kx; bd.Y[j + 1] = ky; + } + /* hull */ + IPts hl = new IPts(); + { + IPts lo = new IPts(), up = new IPts(); + for (int i = 0; i < bd.N; i++) + { + while (lo.N >= 2 && ICr(lo.X[lo.N - 2], lo.Y[lo.N - 2], lo.X[lo.N - 1], lo.Y[lo.N - 1], bd.X[i], bd.Y[i]) <= 0) lo.Pop(); + lo.Push(bd.X[i], bd.Y[i]); + } + for (int i = bd.N - 1; i >= 0; i--) + { + while (up.N >= 2 && ICr(up.X[up.N - 2], up.Y[up.N - 2], up.X[up.N - 1], up.Y[up.N - 1], bd.X[i], bd.Y[i]) <= 0) up.Pop(); + up.Push(bd.X[i], bd.Y[i]); + } + lo.Pop(); up.Pop(); + for (int i = 0; i < lo.N; i++) hl.Push(lo.X[i], lo.Y[i]); + for (int i = 0; i < up.N; i++) hl.Push(up.X[i], up.Y[i]); + } + if (hl.N < 4) continue; + double ar = PolyAreaI(hl.X, hl.Y); + if (ar > bestA) + { + bestA = ar; + bestHull = hl; + } + } + if (bestHull.N == 0) continue; + /* polygon simplify to 4 (int arithmetic) */ + IPts po = new IPts(); + for (int i = 0; i < bestHull.N; i++) po.Push(bestHull.X[i], bestHull.Y[i]); + while (po.N > 4) + { + long mn = (long)1e18; int at = 0; + for (int i = 0; i < po.N; i++) + { + int ai = (i + po.N - 1) % po.N, bi = (i + 1) % po.N; + long v = Math.Abs(ICr(po.X[ai], po.Y[ai], po.X[bi], po.Y[bi], po.X[i], po.Y[i])); + if (v < mn) { mn = v; at = i; } + } + po.RemoveAt(at); + } + long sa = 0; + for (int i = 0; i < 4; i++) + { + int j = (i + 1) % 4; + sa += (long)po.X[i] * po.Y[j] - (long)po.X[j] * po.Y[i]; + } + if (sa < 0) + { + for (int i = 0; i < 2; i++) + { + int tx = po.X[i], ty = po.Y[i]; + po.X[i] = po.X[3 - i]; po.Y[i] = po.Y[3 - i]; + po.X[3 - i] = tx; po.Y[3 - i] = ty; + } + } + /* scale to full res */ + DPts P = new DPts(); + for (int i = 0; i < 4; i++) P.Push((po.X[i] + 0.5) * sc, (po.Y[i] + 0.5) * sc); + /* edge refinement */ + { + double[,] ln = new double[4, 4]; + bool[] lok = new bool[4]; + for (int i = 0; i < 4; i++) + { + double ax = P.X[i], ay = P.Y[i], bx = P.X[(i + 1) % 4], by = P.Y[(i + 1) % 4]; + double dx = bx - ax, dy = by - ay; + double L = JsMath.Hypot2(dx, dy); + double nx = dy / L, ny = -dx / L; + DPts pts = new DPts(); + for (double t = 0.15; t <= 0.851; t += 0.035) + { + double px = ax + t * dx, py = ay + t * dy; + double vi = 0, vo = 0; int ci = 0, co = 0; bool bad = false; + for (double d = -3 * sc - 2; d <= -2 * sc; d += 1) + { + double v = DetectGx(f, px + nx * d, py + ny * d); + if (v < 0) { bad = true; break; } + vi += v; ci++; + } + if (!bad) for (double d = 2 * sc; d <= 3 * sc + 2; d += 1) + { + double v = DetectGx(f, px + nx * d, py + ny * d); + if (v < 0) { bad = true; break; } + vo += v; co++; + } + if (bad) continue; + vi /= ci; vo /= co; + if (vi - vo < 0.06) continue; + double mid = (vi + vo) / 2; + double prev = DetectGx(f, px - nx * 5 * sc, py - ny * 5 * sc), pd = -5 * sc; + if (prev < 0) continue; + double hit = 0; bool have = false; + for (double d = -5 * sc + 0.5; d <= 5 * sc; d += 0.5) + { + double v = DetectGx(f, px + nx * d, py + ny * d); + if (v < 0) break; + if (prev >= mid && v < mid) { hit = pd + ((prev - mid) / (prev - v)) * (d - pd); have = true; break; } + prev = v; pd = d; + } + if (have) pts.Push(px + nx * hit, py + ny * hit); + } + if (pts.N < 6) continue; + double[] fl = { 0, 0, 0, 0 }; + for (int it = 0; it < 3; it++) + { + double mx = 0, my = 0; + for (int p2 = 0; p2 < pts.N; p2++) { mx += pts.X[p2]; my += pts.Y[p2]; } + mx /= pts.N; my /= pts.N; + double sxx = 0, sxy = 0, syy = 0; + for (int p2 = 0; p2 < pts.N; p2++) + { + double u = pts.X[p2] - mx, v = pts.Y[p2] - my; + sxx += u * u; sxy += u * v; syy += v * v; + } + double tt = 0.5 * JsMath.Atan2(2 * sxy, sxx - syy); + double cx = JsMath.Cos(tt), cy = JsMath.Sin(tt); + fl[0] = mx; fl[1] = my; fl[2] = cx; fl[3] = cy; + /* filter */ + DPts kept = new DPts(); + for (int p2 = 0; p2 < pts.N; p2++) + if (Math.Abs((pts.X[p2] - mx) * cy - (pts.Y[p2] - my) * cx) < 2) kept.Push(pts.X[p2], pts.Y[p2]); + if (kept.N < 6 || kept.N == pts.N) break; + pts = kept; + } + for (int q4 = 0; q4 < 4; q4++) ln[i, q4] = fl[q4]; + lok[i] = true; + } + /* new corners */ + double[,] np = new double[4, 2]; + for (int i = 0; i < 4; i++) + { + int i1 = (i + 3) % 4, i2 = i; + if (!lok[i1] || !lok[i2]) { np[i, 0] = P.X[i]; np[i, 1] = P.Y[i]; continue; } + double l10 = ln[i1, 0], l11 = ln[i1, 1], l12 = ln[i1, 2], l13 = ln[i1, 3]; + double l20 = ln[i2, 0], l21 = ln[i2, 1], l22 = ln[i2, 2], l23 = ln[i2, 3]; + double det = l12 * l23 - l13 * l22; + if (Math.Abs(det) < 0.1) { np[i, 0] = P.X[i]; np[i, 1] = P.Y[i]; continue; } + double t = ((l20 - l10) * l23 - (l21 - l11) * l22) / det; + double x = l10 + t * l12, y = l11 + t * l13; + if (JsMath.Hypot2(x - P.X[i], y - P.Y[i]) < 14 * sc) { np[i, 0] = x; np[i, 1] = y; } + else { np[i, 0] = P.X[i]; np[i, 1] = P.Y[i]; } + } + for (int i = 0; i < 4; i++) { P.X[i] = np[i, 0]; P.Y[i] = np[i, 1]; } + } + /* candidates for each size and rotation */ + for (int sz = 0; sz < 6; sz++) + { + PrismLayout l = Foundations.LayoutGet(sz); + double PW = l.W + 2 * mg, PH = l.H + 2 * mg; + for (int r = 0; r < 4; r++) + { + double[,] q = new double[4, 2]; + for (int i = 0; i < 4; i++) { q[i, 0] = P.X[(i + r) % 4]; q[i, 1] = P.Y[(i + r) % 4]; } + double[,] src = { { 0, 0 }, { PW, 0 }, { PW, PH }, { 0, PH } }; + PrismMap hh = new PrismMap(); + if (Image.Homography(src, q, hh) != 0) continue; + PrismCand cand = new PrismCand { Sz = sz, R0 = 1 }; + double[,] cc = { { mg, mg }, { l.W + mg, mg }, { l.W + mg, l.H + mg }, { mg, l.H + mg } }; + for (int i = 0; i < 4; i++) + { + Image.MapPoint(hh, cc[i, 0], cc[i, 1], out double cx2, out double cy2); + cand.P[i, 0] = cx2; cand.P[i, 1] = cy2; + } + outList.Add(cand); + } + } + } + return 0; + } + + /* gx used by lApq edge refinement: min-channel bilinear, pow 0.4545; -1 if out of bounds */ + public static double DetectGx(PrismFrame f, double x, double y) + { + if (x < 0 || y < 0 || x > f.W - 1.001 || y > f.H - 1.001) return -1; + int x0 = (int)x, y0 = (int)y; + double tx = x - x0, ty = y - y0; + int i = (y0 * f.W + x0) * 3, j = i + f.W * 3; + double mni = f.P[i]; if (f.P[i + 1] < mni) mni = f.P[i + 1]; if (f.P[i + 2] < mni) mni = f.P[i + 2]; + double mni3 = f.P[i + 3]; if (f.P[i + 4] < mni3) mni3 = f.P[i + 4]; if (f.P[i + 5] < mni3) mni3 = f.P[i + 5]; + double mnj = f.P[j]; if (f.P[j + 1] < mnj) mnj = f.P[j + 1]; if (f.P[j + 2] < mnj) mnj = f.P[j + 2]; + double mnj3 = f.P[j + 3]; if (f.P[j + 4] < mnj3) mnj3 = f.P[j + 4]; if (f.P[j + 5] < mnj3) mnj3 = f.P[j + 5]; + double v = (mni * (1 - tx) + mni3 * tx) * (1 - ty) + (mnj * (1 - tx) + mnj3 * tx) * ty; + if (v < 0) v = 0; + return JsMath.Pow(v, 0.4545); + } + + /* ---- lA: legacy boundary detect. Returns 0 ok, -1 "no code", -2 "no edges". ---- */ + public static int DetectLa(PrismFrame A, List outList) + { + const double detectionWidth = 320, saturation = 0.25, darkness = 0.55; + double e = Math.Min(1, detectionWidth / Math.Max(A.W, A.H)); + int r = (int)Math.Floor(A.W * e + 0.5), o = (int)Math.Floor(A.H * e + 0.5); + int n = r * o; + float[] a = new float[n], i8 = new float[n]; + double[] QT = QtInit(); + { + float[] Pf = A.P; + int W3 = 3 * A.W; + double XM = A.W - 1, YM = A.H - 1; + for (int t = 0; t < o; t++) + { + double Y = t / e; + for (int o2 = 0; o2 < r; o2++) + { + double X = o2 / e; + double l, Iv; + if (X < 0 || Y < 0 || X >= XM || Y >= YM) { l = 1; Iv = 1; } + else + { + int x0 = (int)Math.Floor(X), y0 = (int)Math.Floor(Y); + double fx = X - x0, fy = Y - y0; + int b = 3 * (y0 * A.W + x0); + double c0 = (Pf[b] * (1 - fx) + Pf[b + 3] * fx) * (1 - fy) + (Pf[b + W3] * (1 - fx) + Pf[b + W3 + 3] * fx) * fy; + double c1 = (Pf[b + 1] * (1 - fx) + Pf[b + 4] * fx) * (1 - fy) + (Pf[b + W3 + 1] * (1 - fx) + Pf[b + W3 + 4] * fx) * fy; + double c2 = (Pf[b + 2] * (1 - fx) + Pf[b + 5] * fx) * (1 - fy) + (Pf[b + W3 + 2] * (1 - fx) + Pf[b + W3 + 5] * fx) * fy; + l = c0 > c1 ? (c0 > c2 ? c0 : c2) : c1 > c2 ? c1 : c2; + Iv = c0 < c1 ? (c0 < c2 ? c0 : c2) : c1 < c2 ? c1 : c2; + double ql; + if (!(l < 1)) ql = Image.SrgbQ(l); + else { double u = l * 8192; int k = (int)u; ql = QT[k] + (QT[k + 1] - QT[k]) * (u - k); } + if (Iv == l) Iv = ql; + else if (!(Iv < 1)) Iv = Image.SrgbQ(Iv); + else { double u = Iv * 8192; int k = (int)u; Iv = QT[k] + (QT[k + 1] - QT[k]) * (u - k); } + l = ql; + } + a[t * r + o2] = (float)l; + i8[t * r + o2] = (float)(l != 0 ? (l - Iv) / l : 0); + } + } + } + float[] g1 = new float[n]; + SmoothF32(a, r, o, 7, 1, g1); + float[] g = new float[n]; + SmoothF32(g1, r, o, 15, 0, g); + byte[] I = new byte[n]; + for (int i = 0; i < n; i++) + I[i] = ((double)i8[i] > saturation && (double)a[i] > 0.15) || (double)a[i] < darkness * Math.Max((double)g[i], 0.4) ? (byte)1 : (byte)0; + byte[] I2 = new byte[n]; + MorphU8(I, r, o, 2, 1, I2); + byte[] I3 = new byte[n]; + MorphU8(I2, r, o, 2, 0, I3); + I = I3; + /* components */ + byte[] h8 = new byte[n]; + int[] nq = new int[n]; + var comps = new List<(IPts hu, int tail, double ar, IPts boundary)>(); + for (int Ai = 0; Ai < n; Ai++) + { + if (I[Ai] == 0 || h8[Ai] != 0) continue; + int e2 = 0, t2 = 1; + IPts bd = new IPts(); + nq[0] = Ai; h8[Ai] = 1; + while (e2 < t2) + { + int A2 = nq[e2++], ix = A2 % r, gy = A2 / r; + bool l2 = false; + int[] es = new int[4]; + es[0] = ix > 0 ? A2 - 1 : -1; + es[1] = ix < r - 1 ? A2 + 1 : -1; + es[2] = gy > 0 ? A2 - r : -1; + es[3] = gy < o - 1 ? A2 + r : -1; + for (int q2 = 0; q2 < 4; q2++) + { + int e3 = es[q2]; + if (e3 < 0 || I[e3] == 0) l2 = true; + else if (h8[e3] == 0) { h8[e3] = 1; nq[t2++] = e3; } + } + if (l2) bd.Push(ix, gy); + } + if (t2 < 100) continue; + /* tA(a) sorts a in place; boundary stays sorted. Boundary pixels are + unique, so any correct sort gives the identical order. */ + for (int i = 1; i < bd.N; i++) + { + int kx = bd.X[i], ky = bd.Y[i], j = i - 1; + while (j >= 0 && (bd.X[j] > kx || (bd.X[j] == kx && bd.Y[j] > ky))) { bd.X[j + 1] = bd.X[j]; bd.Y[j + 1] = bd.Y[j]; j--; } + bd.X[j + 1] = kx; bd.Y[j + 1] = ky; + } + IPts hu = new IPts(); + HullOf(bd.X, bd.Y, hu); + if (hu.N == 0) continue; + double ar = PolyAreaI(hu.X, hu.Y); + int mnx = hu.X[0], mxx = hu.X[0], mny = hu.Y[0], mxy = hu.Y[0]; + for (int i2 = 1; i2 < hu.N; i2++) + { + if (hu.X[i2] < mnx) mnx = hu.X[i2]; if (hu.X[i2] > mxx) mxx = hu.X[i2]; + if (hu.Y[i2] < mny) mny = hu.Y[i2]; if (hu.Y[i2] > mxy) mxy = hu.Y[i2]; + } + double Q = (double)(mxx - mnx) / (double)(mxy - mny); + if ((double)t2 / ar < 0.04 || Q < 0.4 || Q > 2.5) continue; + comps.Add((hu, t2, ar, bd)); + } + if (comps.Count == 0) return -1; + /* stable sort desc by ar */ + var compArr = comps.ToArray(); + for (int i = 1; i < compArr.Length; i++) + { + var c = compArr[i]; int j = i - 1; + while (j >= 0 && compArr[j].ar < c.ar) { compArr[j + 1] = compArr[j]; j--; } + compArr[j + 1] = c; + } + int found = 0; + for (int ci = 0; ci < compArr.Length && ci < 3; ci++) + { + var cp = compArr[ci]; + /* simplify: t = hull as double points */ + DPts t = new DPts(); + for (int i = 0; i < cp.hu.N; i++) t.Push(cp.hu.X[i], cp.hu.Y[i]); + while (t.N > 4) + { + double best = double.PositiveInfinity; int at = 0; + for (int i = 0; i < t.N; i++) + { + int pi = (i + t.N - 1) % t.N, ni = (i + 1) % t.N; + double v = Math.Abs(DCr(t.X[pi], t.Y[pi], t.X[i], t.Y[i], t.X[ni], t.Y[ni])) / JsMath.Hypot2(t.X[ni] - t.X[pi], t.Y[ni] - t.Y[pi]); + if (v < best) { best = v; at = i; } + } + if (best > 0.7) break; + t.RemoveAt(at); + } + /* edges: 4 longest */ + var edges = new List<(int i, double ax, double ay, double bx, double by, double len)>(); + for (int i = 0; i < t.N; i++) + { + int ni = (i + 1) % t.N; + edges.Add((i, t.X[i], t.Y[i], t.X[ni], t.Y[ni], JsMath.Hypot2(t.X[i] - t.X[ni], t.Y[i] - t.Y[ni]))); + } + /* sort desc len (stable), take 4, sort asc i (stable) */ + var edgeArr = edges.ToArray(); + for (int i = 1; i < edgeArr.Length; i++) + { + var c = edgeArr[i]; int j = i - 1; + while (j >= 0 && edgeArr[j].len < c.len) { edgeArr[j + 1] = edgeArr[j]; j--; } + edgeArr[j + 1] = c; + } + var four = new (int i, double ax, double ay, double bx, double by, double len)[4]; + for (int i = 0; i < 4; i++) four[i] = edgeArr[i]; + for (int i = 1; i < 4; i++) + { + var c = four[i]; int j = i - 1; + while (j >= 0 && four[j].i > c.i) { four[j + 1] = four[j]; j--; } + four[j + 1] = c; + } + double[,] ls = new double[4, 3]; + bool ok = true; + for (int i = 0; i < 4; i++) + { + double dx = four[i].bx - four[i].ax, dy = four[i].by - four[i].ay; + double l = JsMath.Hypot2(dx, dy); + /* boundary filter |eA|/l < 2 */ + var fx = new List(); var fy = new List(); + for (int b = 0; b < cp.boundary.N; b++) + if (Math.Abs(DCr(four[i].ax, four[i].ay, four[i].bx, four[i].by, cp.boundary.X[b], cp.boundary.Y[b])) / l < 2) + { + fx.Add(cp.boundary.X[b]); fy.Add(cp.boundary.Y[b]); + } + double[] lsRow = new double[3]; + if (fx.Count >= 2) LineFit(fx, fy, lsRow); + else + { + var ex = new List { four[i].ax, four[i].bx }; + var ey = new List { four[i].ay, four[i].by }; + LineFit(ex, ey, lsRow); + } + ls[i, 0] = lsRow[0]; ls[i, 1] = lsRow[1]; ls[i, 2] = lsRow[2]; + } + /* corners */ + double[,] quad = new double[4, 2]; + for (int i = 0; i < 4; i++) + { + double[] l1 = { ls[(i + 3) % 4, 0], ls[(i + 3) % 4, 1], ls[(i + 3) % 4, 2] }; + double[] l2 = { ls[i, 0], ls[i, 1], ls[i, 2] }; + if (LineIsect(l1, l2, out double qx, out double qy) != 0) { ok = false; break; } + quad[i, 0] = (qx + 0.5) / e; + quad[i, 1] = (qy + 0.5) / e; + } + if (ok) + { + PrismCand cand = new PrismCand { Sz = -1, R0 = 0 }; + for (int i = 0; i < 4; i++) { cand.P[i, 0] = quad[i, 0]; cand.P[i, 1] = quad[i, 1]; } + outList.Add(cand); + found++; + } + } + if (found == 0) return -2; + return 0; + } + + /* lAp: lApq candidates + lA candidates (errors swallowed as in JS) */ + public static int DetectLap(PrismFrame f, List outList, out string err) + { + err = null; + int na = outList.Count; + DetectLapq(f, outList); /* lApq never throws in JS except OOM */ + int ra = outList.Count - na; + int rb = DetectLa(f, outList); + if (rb != 0 && ra == 0) + { + err = rb == -1 ? "No code found. Use a plain background with a wide white margin." : "Could not fit four edges"; + return rb; + } + return 0; + } + + private static double[] qtTable; + private static double[] QtInit() + { + if (qtTable != null) return qtTable; + qtTable = new double[8194]; + for (int k = 0; k < 8194; k++) qtTable[k] = Image.SrgbQ(k / 8192.0); + return qtTable; + } + } +} diff --git a/ports/csharp/reader/PrismDistFit.cs b/ports/csharp/reader/PrismDistFit.cs new file mode 100644 index 0000000..e8ef33f --- /dev/null +++ b/ports/csharp/reader/PrismDistFit.cs @@ -0,0 +1,1015 @@ +// PrismDistFit.cs - PrismLocal.normalize, PrismDistance.fields, detectTexture, PrismDistFit.read, +// PrismFastReader.read. Transliterated from ports/c/reader/prism_distfit.c. +using System; +using System.Collections.Generic; + +namespace Prism.Reader +{ + internal static class DistFit + { + private static double Clamp01(double A) => A < 0 ? 0 : A > 1 ? 1 : A; + private static double EA(double[] A, double[] e, double[] t) => (e[0] - A[0]) * (t[1] - A[1]) - (e[1] - A[1]) * (t[0] - A[0]); + private static int JsRound(double x) => (int)Math.Floor(x + 0.5); + + private static void MorphU8(byte[] A, int e, int t, int r, bool o, byte[] outBuf) + { + byte[] a = new byte[e * t]; + for (int i = 0; i < t; i++) + for (int tt = 0; tt < e; tt++) + { + int g = o ? 0 : 1; + for (int da = -r; da <= r; da++) + { + int rr = tt + da; if (rr < 0) rr = 0; if (rr > e - 1) rr = e - 1; + if (o) g |= A[i * e + rr]; else g &= A[i * e + rr]; + } + a[i * e + tt] = (byte)g; + } + for (int A2 = 0; A2 < t; A2++) + for (int g2 = 0; g2 < e; g2++) + { + int l = o ? 0 : 1; + for (int di = -r; di <= r; di++) + { + int rr = A2 + di; if (rr < 0) rr = 0; if (rr > t - 1) rr = t - 1; + if (o) l |= a[rr * e + g2]; else l &= a[rr * e + g2]; + } + outBuf[A2 * e + g2] = (byte)l; + } + } + + public static void LocalNormalize(byte[] rgba, int w, int h, byte[] outBuf) + { + int n = w * h; + uint[][] hist = { new uint[256], new uint[256], new uint[256] }; + float[][] ch = { new float[n], new float[n], new float[n] }; + for (int A = 0; A < n * 4; A += 4) + for (int e = 0; e < 3; e++) { hist[e][rgba[A + e]]++; ch[e][A / 4] = (float)rgba[A + e]; } + int[] blk = new int[3]; + for (int e = 0; e < 3; e++) + { + uint r = 0; blk[e] = 0; + for (int o = 0; o < 256; o++) + { + r += hist[e][o]; + if (r > (double)w * h * 0.02) { blk[e] = o; break; } + } + } + int rp = JsRound(0.035 * (w < h ? w : h)); + float[][] mn = new float[3][]; + for (int e = 0; e < 3; e++) + { + float[] o = new float[n], a2 = new float[n]; + int i2 = (w > h ? w : h) + 2 * rp + 1; + int[] gq = new int[i2]; float[] lq = new float[i2]; + for (int yy = 0; yy < h; yy++) + { + int t = 0, i3 = 0; + int I = yy * w; + for (int a = -rp; a < w + rp; a++) + { + int ci = a < 0 ? 0 : a > w - 1 ? w - 1 : a; + float hv = ch[e][I + ci]; + for (; i3 > t && lq[i3 - 1] <= hv;) i3--; + gq[i3] = a; lq[i3++] = hv; + for (; gq[t] < a - 2 * rp;) t++; + if (a >= rp) o[I + a - rp] = lq[t]; + } + } + for (int xx = 0; xx < w; xx++) + { + int i3 = 0, I3 = 0; + for (int hh = -rp; hh < h + rp; hh++) + { + int ci = hh < 0 ? 0 : hh > h - 1 ? h - 1 : hh; + float nv = o[ci * w + xx]; + for (; I3 > i3 && lq[I3 - 1] <= nv;) I3--; + gq[I3] = hh; lq[I3++] = nv; + for (; gq[i3] < hh - 2 * rp;) i3++; + if (hh >= rp) a2[(hh - rp) * w + xx] = lq[i3]; + } + } + mn[e] = a2; + } + for (int A = 0; A < n; A++) + { + for (int e = 0; e < 3; e++) + { + double d = (255.0 * (ch[e][A] - blk[e])) / Cm.Fmax(30, mn[e][A] - blk[e]); + if (d < 0) d = 0; if (d > 255) d = 255; + outBuf[4 * A + e] = (byte)Math.Round(d, MidpointRounding.ToEven); + } + outBuf[4 * A + 3] = 255; + } + } + + private sealed class DFields { public float[][] Maps = new float[9][]; public int W, H; public double Scale; } + + private static void Chamfer(float[] A, int t, int r) + { + for (int e = 0; e < r; e++) + for (int rr = 0; rr < t; rr++) + { + int o = e * t + rr; + double a = A[o]; + if (rr != 0) { double v = A[o - 1] + 1; if (v < a) a = v; } + if (e != 0) { double v = A[o - t] + 1; if (v < a) a = v; } + if (rr != 0 && e != 0) { double v = A[o - t - 1] + 1.414; if (v < a) a = v; } + if (rr < t - 1 && e != 0) { double v = A[o - t + 1] + 1.414; if (v < a) a = v; } + A[o] = (float)a; + } + for (int e = r - 1; e >= 0; e--) + for (int o2 = t - 1; o2 >= 0; o2--) + { + int a2 = e * t + o2; + double i = A[a2]; + if (o2 < t - 1) { double v = A[a2 + 1] + 1; if (v < i) i = v; } + if (e < r - 1) { double v = A[a2 + t] + 1; if (v < i) i = v; } + if (o2 < t - 1 && e < r - 1) { double v = A[a2 + t + 1] + 1.414; if (v < i) i = v; } + if (o2 != 0 && e < r - 1) { double v = A[a2 + t - 1] + 1.414; if (v < i) i = v; } + A[a2] = (float)i; + } + } + + private static DFields FieldsCompute(byte[] rgba, int W, int H) + { + DFields F = new DFields(); + double e = Math.Min(1, 240.0 / (W > H ? W : H)); + int t = JsRound(W * e), r = JsRound(H * e); + uint[][] o = { new uint[256], new uint[256], new uint[256] }; + for (long e2 = 0; e2 < (long)W * H * 4; e2 += 16) + for (int tt = 0; tt < 3; tt++) o[tt][rgba[e2 + tt]]++; + double a = Math.Ceiling((double)W * H * 4 / 16); + double[] lo = new double[3], hi = new double[3]; + for (int c = 0; c < 3; c++) + { + uint rr = 0; double elo = 0, ehi = 255; + for (int tt = 0; tt < 256; tt++) { rr += o[c][tt]; if (rr >= 0.02 * a) { elo = tt; break; } } + rr = 0; + for (int e2 = 0; e2 < 256; e2++) { rr += o[c][e2]; if (rr >= 0.98 * a) { ehi = e2; break; } } + lo[c] = elo; hi[c] = ehi; + } + int n = t * r; + for (int k = 0; k < 9; k++) + { + F.Maps[k] = new float[n]; + for (int i = 0; i < n; i++) F.Maps[k][i] = 1e3f; + } + Dictionary memo = new Dictionary(); + double[] I = new double[3], lin = new double[3]; + for (int yy = 0; yy < r; yy++) + for (int xx = 0; xx < t; xx++) + { + int a2 = 4 * ((int)(yy / e) * W + (int)(xx / e)); + for (int c = 0; c < 3; c++) I[c] = Clamp01((rgba[a2 + c] - lo[c]) / Cm.Fmax(20, hi[c] - lo[c])); + uint key = 32 * (32 * (uint)JsRound(31 * I[0]) + (uint)JsRound(31 * I[1])) + (uint)JsRound(31 * I[2]); + if (!memo.TryGetValue(key, out int sym)) + { + lin[0] = Image.LinSPub(I[0]); lin[1] = Image.LinSPub(I[1]); lin[2] = Image.LinSPub(I[2]); + sym = Image.NearestSym(lin, 0, out double d); + memo[key] = sym; + } + F.Maps[sym][yy * t + xx] = 0; + } + for (int k = 0; k < 9; k++) Chamfer(F.Maps[k], t, r); + for (int k = 0; k < 9; k++) + { + float[] ef = new float[n]; + for (int i = 0; i < n; i++) ef[i] = F.Maps[k][i] == 0 ? 1e3f : 0; + Chamfer(ef, t, r); + for (int i = 0; i < n; i++) + F.Maps[k][i] = (float)(F.Maps[k][i] / 0.6 + 0.7 * Cm.Fmax(0, 1.7 - ef[i] / 0.6)); + } + F.W = t; F.H = r; F.Scale = e; + return F; + } + + private static double FieldsAt(DFields F, int sym, double o, double a) + { + a *= F.Scale; o *= F.Scale; + if (o < 0 || a < 0 || o >= F.W - 1 || a >= F.H - 1) return 12; + int i = (int)Math.Floor(o), l = (int)Math.Floor(a); + double I = o - i, h = a - l; + float[] n = F.Maps[sym]; + int s = l * F.W + i; + return (n[s] * (1 - I) + n[s + 1] * I) * (1 - h) + (n[s + F.W] * (1 - I) + n[s + F.W + 1] * I) * h; + } + + private static int HullTA(double[][] A, int n, double[][] outH) + { + for (int i = 0; i < n - 1; i++) + for (int j = i + 1; j < n; j++) + if (A[j][0] < A[i][0] || (A[j][0] == A[i][0] && A[j][1] < A[i][1])) { var t = A[i]; A[i] = A[j]; A[j] = t; } + double[][] e = new double[2 * (n + 1)][], t2 = new double[2 * (n + 1)][]; + int ne = 0, nt = 0; + for (int i = 0; i < n; i++) + { + for (; ne > 1 && EA(e[ne - 2], e[ne - 1], A[i]) <= 0;) ne--; + e[ne++] = new[] { A[i][0], A[i][1] }; + } + for (int i = n - 1; i >= 0; i--) + { + for (; nt > 1 && EA(t2[nt - 2], t2[nt - 1], A[i]) <= 0;) nt--; + t2[nt++] = new[] { A[i][0], A[i][1] }; + } + ne--; nt--; + int k = 0; + for (int i = 0; i < ne; i++) outH[k++] = new[] { e[i][0], e[i][1] }; + for (int i = 0; i < nt; i++) outH[k++] = new[] { t2[i][0], t2[i][1] }; + return k; + } + + private static double AreaRA(double[][] A, int n) + { + double s = 0; + for (int i = 0; i < n; i++) { int j = (i + 1) % n; s += A[i][0] * A[j][1] - A[i][1] * A[j][0]; } + return Math.Abs(s) / 2; + } + + private static double[] LineIA(List A) + { + int n = A.Count; + double e = 0, t = 0; + for (int i = 0; i < n; i++) { e += A[i][0]; t += A[i][1]; } + e /= n; t /= n; + double r = 0, o = 0, a = 0; + for (int i = 0; i < n; i++) + { + double dx = A[i][0] - e, dy = A[i][1] - t; + r += dx * dx; o += dx * dy; a += dy * dy; + } + double i2 = 0.5 * JsMath.Atan2(2 * o, r - a); + double g = -JsMath.Sin(i2), l = JsMath.Cos(i2); + return new[] { g, l, g * e + l * t }; + } + + private static double[] IsectGA(double[] A, double[] e) + { + double t = A[0] * e[1] - A[1] * e[0]; + if (Math.Abs(t) < 1e-6) return null; + return new[] { (A[2] * e[1] - A[1] * e[2]) / t, (A[0] * e[2] - A[2] * e[0]) / t }; + } + + private sealed class Region { public double[][] Hu; public int Nhu; public int Tail; public double[][] Bnd; public int Nbnd; public double Ar; } + + private static double[,] Q4(double[][] p) + { + double[,] q = new double[4, 2]; + for (int k = 0; k < 4; k++) { q[k, 0] = p[k][0]; q[k, 1] = p[k][1]; } + return q; + } + + private static int DetectTexture(PrismFrame A, double edge, bool useEdge, double thresh, bool useThresh, int radius, bool useRadius, List outL, out string err) + { + err = null; + double rEdge = useEdge ? edge : 0.13; + double t = Math.Min(1, 320.0 / (A.W > A.H ? A.W : A.H)); + int i = JsRound(A.W * t), g = JsRound(A.H * t); + float[] l = new float[i * g * 3]; + for (int rr = 0; rr < g; rr++) + for (int oo = 0; oo < i; oo++) + { + double a = oo / t, gg = rr / t; + int I = 3 * (rr * i + oo); + if (a < 0 || gg < 0 || a >= A.W - 1 || gg >= A.H - 1) + { + l[I] = l[I + 1] = l[I + 2] = (float)Image.SrgbQ(1); + continue; + } + int hh = (int)Math.Floor(a), nn = (int)Math.Floor(gg); + double s = a - hh, C = gg - nn; + int Q = 3 * (nn * A.W + hh); + for (int e = 0; e < 3; e++) + l[I + e] = (float)Image.SrgbQ( + (A.P[Q + e] * (1 - s) + A.P[Q + 3 + e] * s) * (1 - C) + + (A.P[3 * A.W + Q + e] * (1 - s) + A.P[3 * A.W + 3 + Q + e] * s) * C); + } + float[] Ie = new float[i * g]; + for (int A2 = 1; A2 < g - 1; A2++) + for (int e2 = 1; e2 < i - 1; e2++) + { + int tt = 3 * (A2 * i + e2); + double r = 0; + for (int A3 = 0; A3 < 2; A3++) + { + int e3 = tt + (A3 != 0 ? 3 * i : 3); + double o = 0; + for (int A4 = 0; A4 < 3; A4++) o += (l[tt + A4] - l[e3 + A4]) * (l[tt + A4] - l[e3 + A4]); + double sq = Math.Sqrt(o); + if (sq > r) r = sq; + } + Ie[A2 * i + e2] = r > rEdge ? 1 : 0; + } + float[] hI = new float[(i + 1) * (g + 1)]; + for (int A2 = 0; A2 < g; A2++) + { + double e2 = 0; + for (int t2 = 0; t2 < i; t2++) + { + e2 += Ie[A2 * i + t2]; + hI[(A2 + 1) * (i + 1) + t2 + 1] = (float)(hI[A2 * (i + 1) + t2 + 1] + e2); + } + } + byte[] hb = new byte[g * i]; + int n2 = useRadius ? radius : 4; + double thr = useThresh ? thresh : 0.33; + for (int A2 = 0; A2 < g; A2++) + for (int e2 = 0; e2 < i; e2++) + { + int tt = e2 - n2 > 0 ? e2 - n2 : 0; + int rr = e2 + n2 + 1 < i ? e2 + n2 + 1 : i; + int oo = A2 - n2 > 0 ? A2 - n2 : 0; + int aa = A2 + n2 + 1 < g ? A2 + n2 + 1 : g; + double iv = hI[aa * (i + 1) + rr] - hI[oo * (i + 1) + rr] - hI[aa * (i + 1) + tt] + hI[oo * (i + 1) + tt]; + hb[A2 * i + e2] = iv / ((rr - tt) * (aa - oo)) > thr ? (byte)1 : (byte)0; + } + byte[] h2 = new byte[g * i]; + MorphU8(hb, i, g, 1, true, h2); + MorphU8(h2, i, g, 1, false, hb); + byte[] seen = new byte[g * i]; + int[] queue = new int[g * i]; + double[][] boundary = new double[g * i][]; + var regs = new List(); + for (int A2 = 0; A2 < g * i; A2++) + { + if (hb[A2] == 0 || seen[A2] != 0) continue; + int e2 = 0, t2 = 1, nb = 0; + queue[0] = A2; seen[A2] = 1; + while (e2 < t2) + { + int cur = queue[e2++]; + int oo = cur % i, aa = cur / i; + bool isb = false; + for (int e3 = 0; e3 < 4; e3++) + { + int rr = e3 == 0 ? (oo > 0 ? cur - 1 : -1) + : e3 == 1 ? (oo < i - 1 ? cur + 1 : -1) + : e3 == 2 ? (aa > 0 ? cur - i : -1) + : (aa < g - 1 ? cur + i : -1); + if (rr < 0 || hb[rr] == 0) isb = true; + else if (seen[rr] == 0) { seen[rr] = 1; queue[t2++] = rr; } + } + if (isb) { boundary[nb++] = new double[] { oo, aa }; } + } + if (t2 < 100) continue; + double[][] hull = new double[nb][]; + for (int k = 0; k < nb; k++) hull[k] = new[] { boundary[k][0], boundary[k][1] }; + double[][] hullOut = new double[nb + 2][]; + int nhu = HullTA(hull, nb, hullOut); + /* JS tA sorts the boundary array itself in place */ + for (int a4 = 0; a4 < nb - 1; a4++) + for (int b4 = a4 + 1; b4 < nb; b4++) + if (boundary[b4][0] < boundary[a4][0] || (boundary[b4][0] == boundary[a4][0] && boundary[b4][1] < boundary[a4][1])) + { var tmp = boundary[a4]; boundary[a4] = boundary[b4]; boundary[b4] = tmp; } + double[][] hl = new double[nhu][]; + for (int k = 0; k < nhu; k++) hl[k] = hullOut[k]; + double ar = AreaRA(hl, nhu); + double minx = 1e300, maxx = -1e300, miny = 1e300, maxy = -1e300; + for (int k = 0; k < nhu; k++) + { + if (hl[k][0] < minx) minx = hl[k][0]; if (hl[k][0] > maxx) maxx = hl[k][0]; + if (hl[k][1] < miny) miny = hl[k][1]; if (hl[k][1] > maxy) maxy = hl[k][1]; + } + double asp = (maxx - minx) / (maxy - miny); + if (t2 / ar < 0.04 || asp < 0.4 || asp > 2.5) continue; + if (regs.Count < 64) + { + Region R = new Region { Hu = hl, Nhu = nhu, Tail = t2, Ar = ar, Nbnd = nb }; + R.Bnd = new double[nb][]; + for (int k = 0; k < nb; k++) R.Bnd[k] = new[] { boundary[k][0], boundary[k][1] }; + regs.Add(R); + } + } + int nreg = regs.Count; + for (int a2 = 0; a2 < nreg - 1; a2++) + for (int b2 = a2 + 1; b2 < nreg; b2++) + if (regs[b2].Ar > regs[a2].Ar) { var tmp = regs[a2]; regs[a2] = regs[b2]; regs[b2] = tmp; } + if (nreg == 0) { err = "No code found. Use a plain background with a wide white margin."; return -1; } + for (int ri = 0; ri < nreg && ri < 3; ri++) + { + Region R = regs[ri]; + int nhu = R.Nhu; + double best = double.PositiveInfinity; double[,] bq = new double[4, 2]; bool have = false; + for (int rr = 0; rr < nhu; rr++) + { + double[] o = R.Hu[rr], a2 = R.Hu[(rr + 1) % nhu]; + double g2 = a2[0] - o[0], l2 = a2[1] - o[1]; + double I2 = JsMath.Hypot2(g2, l2); + g2 /= I2; l2 /= I2; + double smin = 1e300, smax = -1e300, nmin = 1e300, nmax = -1e300; + for (int k = 0; k < nhu; k++) + { + double hp = R.Hu[k][0] * g2 + R.Hu[k][1] * l2; + double np = -R.Hu[k][0] * l2 + R.Hu[k][1] * g2; + if (hp < smin) smin = hp; if (hp > smax) smax = hp; + if (np < nmin) nmin = np; if (np > nmax) nmax = np; + } + double B = (smax - smin) * (nmax - nmin); + if (B < best) + { + best = B; have = true; + double[,] corners = { { smin, nmin }, { smax, nmin }, { smax, nmax }, { smin, nmax } }; + for (int k = 0; k < 4; k++) + { + bq[k, 0] = (corners[k, 0] * g2 - corners[k, 1] * l2 + 0.5) / t; + bq[k, 1] = (corners[k, 0] * l2 + corners[k, 1] * g2 + 0.5) / t; + } + } + } + if (have) outL.Add((double[,])bq.Clone()); + List r2 = new List(R.Hu); + int nr = nhu; + while (nr > 4) + { + double bestc = double.PositiveInfinity; int be = 0; + for (int tt = 0; tt < nr; tt++) + { + double[] po = r2[(tt + nr - 1) % nr], pa = r2[(tt + 1) % nr]; + double ic = Math.Abs(EA(po, r2[tt], pa)) / Cm.Fmax(0.1, JsMath.Hypot2(pa[0] - po[0], pa[1] - po[1])); + if (ic < bestc) { bestc = ic; be = tt; } + } + r2.RemoveAt(be); nr--; + } + if (nr == 4) + { + double[,] q4 = new double[4, 2]; + for (int k = 0; k < 4; k++) { q4[k, 0] = (r2[k][0] + 0.5) / t; q4[k, 1] = (r2[k][1] + 0.5) / t; } + outL.Add(q4); + double[][] lines = new double[4][]; bool ok = true; + for (int tt = 0; tt < 4 && ok; tt++) + { + double[] o = r2[tt], a2 = r2[(tt + 1) % 4]; + int ii = -1, gg = -1; + for (int k = 0; k < nhu; k++) + { + if (R.Hu[k][0] == o[0] && R.Hu[k][1] == o[1]) ii = k; + if (R.Hu[k][0] == a2[0] && R.Hu[k][1] == a2[1]) gg = k; + } + double bestg = 0; int bi = -1; + for (int e2 = ii; e2 != gg; e2 = (e2 + 1) % nhu) + { + double[] t3 = R.Hu[e2], r3 = R.Hu[(e2 + 1) % nhu]; + double o2 = JsMath.Hypot2(t3[0] - r3[0], t3[1] - r3[1]); + if (o2 > bestg) { bestg = o2; bi = e2; } + } + double[] hh, nn; + if (bi >= 0) { hh = R.Hu[bi]; nn = R.Hu[(bi + 1) % nhu]; } else { hh = o; nn = a2; } + var spts = new List(); + for (int k = 0; k < R.Nbnd; k++) + if (Math.Abs(EA(hh, nn, R.Bnd[k])) / Cm.Fmax(1, bestg) < 2) spts.Add(R.Bnd[k]); + if (spts.Count > 2) lines[tt] = LineIA(spts); + else lines[tt] = LineIA(new List { hh, nn }); + } + double[][] tq = new double[4][]; + for (int tt = 0; tt < 4 && ok; tt++) + { + tq[tt] = IsectGA(lines[(tt + 3) % 4], lines[tt]); + if (tq[tt] == null) ok = false; + } + if (ok) + { + double aq = AreaRA(tq, 4); + if (aq > 0.6 * R.Ar && aq < 1.5 * R.Ar) + { + double[,] q5 = new double[4, 2]; + for (int k = 0; k < 4; k++) { q5[k, 0] = (tq[k][0] + 0.5) / t; q5[k, 1] = (tq[k][1] + 0.5) / t; } + outL.Add(q5); + } + } + } + List o2l = new List(R.Hu); + int no = nhu; + while (no > 4) + { + double bestc = double.PositiveInfinity; int be = 0; + for (int tt = 0; tt < no; tt++) + { + double[] pr = o2l[(tt + no - 1) % no], pa = o2l[(tt + 1) % no]; + double ic = Math.Abs(EA(pr, o2l[tt], pa)) / JsMath.Hypot2(pa[0] - pr[0], pa[1] - pr[1]); + if (ic < bestc) { bestc = ic; be = tt; } + } + if (bestc > 0.7) break; + o2l.RemoveAt(be); no--; + } + var segs = new (int idx, double len)[no]; + for (int e2 = 0; e2 < no; e2++) + segs[e2] = (e2, JsMath.Hypot2(o2l[e2][0] - o2l[(e2 + 1) % no][0], o2l[e2][1] - o2l[(e2 + 1) % no][1])); + for (int a3 = 0; a3 < no - 1; a3++) + for (int b3 = a3 + 1; b3 < no; b3++) + if (segs[b3].len > segs[a3].len) { var tmp = segs[a3]; segs[a3] = segs[b3]; segs[b3] = tmp; } + int ntake = no < 4 ? no : 4; + var top = new (int idx, double len)[4]; + for (int k = 0; k < ntake; k++) top[k] = segs[k]; + for (int a3 = 0; a3 < ntake - 1; a3++) + for (int b3 = a3 + 1; b3 < ntake; b3++) + if (top[b3].idx < top[a3].idx) { var tmp = top[a3]; top[a3] = top[b3]; top[b3] = tmp; } + if (ntake == 4) + { + double[][] lines = new double[4][]; bool ok = true; + for (int e2 = 0; e2 < 4 && ok; e2++) + { + double[] t3 = o2l[top[e2].idx], r3 = o2l[(top[e2].idx + 1) % no]; + double l3 = JsMath.Hypot2(t3[0] - r3[0], t3[1] - r3[1]); + var spts = new List(); + for (int k = 0; k < R.Nbnd; k++) + if (Math.Abs(EA(t3, r3, R.Bnd[k])) / l3 < 2) spts.Add(R.Bnd[k]); + if (spts.Count >= 2) lines[e2] = LineIA(spts); + else lines[e2] = LineIA(new List { t3, r3 }); + } + double[][] tq = new double[4][]; + for (int e2 = 0; e2 < 4 && ok; e2++) + { + tq[e2] = IsectGA(lines[(e2 + 3) % 4], lines[e2]); + if (tq[e2] == null) ok = false; + } + if (ok) + { + double[,] q6 = new double[4, 2]; + for (int k = 0; k < 4; k++) { q6[k, 0] = (tq[k][0] + 0.5) / t; q6[k, 1] = (tq[k][1] + 0.5) / t; } + outL.Add(q6); + } + } + } + if (outL.Count == 0) { err = "Could not fit four edges"; return -1; } + return 0; + } + + /* Debug probe mirroring the C port's df_probe_fields (test_distfit.c). */ + public static string ProbeFields(byte[] rgba, int W, int H) + { + DFields F = FieldsCompute(rgba, W, H); + var sb = new System.Text.StringBuilder(); + sb.Append("FIELDS w=" + F.W + " h=" + F.H + " scale=" + BitConverter.DoubleToInt64Bits(F.Scale).ToString("x16")); + for (int k = 0; k < 9; k++) + { + ulong h2 = 0xcbf29ce484222325UL; + foreach (float fv in F.Maps[k]) + foreach (byte b in BitConverter.GetBytes(fv)) { h2 ^= b; h2 *= 0x100000001b3UL; } + sb.Append(" m" + k + "=" + h2.ToString("x16")); + } + return sb.ToString(); + } + + /* Debug probe mirroring the C port's df_probe_texture (test_distfit.c). */ + public static List ProbeTexture(byte[] rgba, int W, int H) + { + PrismFrame fr = Image.FrameCreate(W, H, rgba); + var lines = new List(); + for (int cfg = 0; cfg < 3; cfg++) + { + var ql = new List(); + string derr; + int rc; + if (cfg == 0) rc = DetectTexture(fr, 0, false, 0, false, 0, false, ql, out derr); + else if (cfg == 1) rc = DetectTexture(fr, 0.13, true, 0.5, true, 0, false, ql, out derr); + else rc = DetectTexture(fr, 0.2, true, 0.4, true, 0, false, ql, out derr); + if (rc != 0) { lines.Add("DT err=\"" + (derr ?? "") + "\""); } + else + { + var sb = new System.Text.StringBuilder("DT n=" + ql.Count); + foreach (var q in ql) + { + sb.Append(" q="); + for (int k = 0; k < 4; k++) + { + if (k > 0) sb.Append(';'); + sb.Append(BitConverter.DoubleToInt64Bits(q[k, 0]).ToString("x16")); + sb.Append(','); + sb.Append(BitConverter.DoubleToInt64Bits(q[k, 1]).ToString("x16")); + } + } + lines.Add(sb.ToString()); + } + } + return lines; + } + + private static void DfSplitErr(string s, PrismErr e) + { + int c = s.IndexOf(':'); + if (c >= 0) { e.Stage = s.Substring(0, Math.Min(c, 23)); e.Msg = s.Substring(c + 1); } + else { e.Stage = "undefined"; e.Msg = s; } + } + + private sealed class DFHyp { public PrismMap H; public PrismLayout L; public double[,] Quad = new double[4, 2]; public double Score, Cost; public int Seq; } + + private static void DfRank(DFields F, PrismMap c, PrismLayout t, out double cost, out double score) + { + int nk = t.Known.Length; + int step = nk / 48; if (step < 1) step = 1; + double r = 0; int o = 0; + for (int a = 0; a < nk; a += step) + { + PrismCell cell = t.Known[a]; + Image.MapPoint(c, cell.X, cell.Y, out double gx, out double gy); + double l2 = FieldsAt(F, Image.KnownSymbol(cell, 0), gx, gy); + double v = l2 * l2; if (v > 25) v = 25; + r += v; o++; + } + cost = r / o; + score = 1 / (1 + r / o); + } + + private static double DfScore(DFields F, PrismMap R, PrismLayout S, PrismCell[] J, int nj) + { + double[] A = new double[nj]; + for (int k = 0; k < nj; k++) + { + Image.MapPoint(R, J[k].X, J[k].Y, out double gx, out double gy); + double o = FieldsAt(F, Image.KnownSymbol(J[k], 0), gx, gy); + double v = o * o; if (v > 64) v = 64; + A[k] = v; + } + for (int a = 0; a < nj - 1; a++) + for (int b = a + 1; b < nj; b++) + if (A[b] < A[a]) { double t2 = A[a]; A[a] = A[b]; A[b] = t2; } + int t = (int)Math.Floor(0.85 * nj); + double r = 0; + for (int k = 0; k < t; k++) r += A[k]; + r /= t; + double o2 = 0; + for (int A2 = 0; A2 < 24; A2++) + { + double t2 = 0, r2 = 0; + for (int k = 0; k < S.Headers.Length; k++) + { + PrismCell hc = S.Headers[k]; + if (hc.Header % 24 != A2) continue; + Image.MapPoint(R, hc.X, hc.Y, out double gx, out double gy); + double a3 = FieldsAt(F, 8, gx, gy), i3 = FieldsAt(F, 0, gx, gy); + double v1 = a3 * a3; if (v1 > 36) v1 = 36; + double v2 = i3 * i3; if (v2 > 36) v2 = 36; + t2 += v1; r2 += v2; + } + o2 += t2 < r2 ? t2 : r2; + } + return r + (o2 / 72) * 0.35; + } + + private static PrismMap CloneMap(PrismMap m) { PrismMap c = new PrismMap(); c.CopyFrom(m); return c; } + private static void SetWarp(PrismMap c, PrismLayout E, double[] p) { c.HasWarp = 1; c.WarpW = E.W; c.WarpH = E.H; Array.Copy(p, c.WarpP, 10); } + + public static int Read(byte[] rgba, int w, int h, PrismRead outR) + { + Budget.BudgetSet(15.0); + double dfT0 = Budget.Now(); + DFields F = FieldsCompute(rgba, w, h); + PrismFrame fr = Image.FrameCreate(w, h, rgba); + var cands = new List(); + DetectTexture(fr, 0, false, 0, false, 0, false, cands, out _); + DetectTexture(fr, 0.13, true, 0.5, true, 0, false, cands, out _); + DetectTexture(fr, 0.2, true, 0.4, true, 0, false, cands, out _); + var ded = new List(); + for (int i = 0; i < cands.Count; i++) + { + bool dup = false; + for (int j = 0; j < i && !dup; j++) + for (int rr = 0; rr < 4 && !dup; rr++) + { + double s = 0; + for (int k = 0; k < 4; k++) + s += (cands[i][k, 0] - cands[j][(k + rr) % 4, 0]) * (cands[i][k, 0] - cands[j][(k + rr) % 4, 0]) + + (cands[i][k, 1] - cands[j][(k + rr) % 4, 1]) * (cands[i][k, 1] - cands[j][(k + rr) % 4, 1]); + if (s < 100) dup = true; + } + if (!dup) ded.Add(cands[i]); + } + var vars = new List(); + double[] sc3 = { 1, 1.04, 1.08 }; + for (int i = 0; i < ded.Count; i++) + { + double cx = 0, cy = 0; + for (int k = 0; k < 4; k++) { cx += ded[i][k, 0]; cy += ded[i][k, 1]; } + cx /= 4; cy /= 4; + for (int s2 = 0; s2 < 3; s2++) + { + double[,] q = new double[4, 2]; + for (int k = 0; k < 4; k++) + { + q[k, 0] = cx + (ded[i][k, 0] - cx) * sc3[s2]; + q[k, 1] = cy + (ded[i][k, 1] - cy) * sc3[s2]; + } + vars.Add(q); + } + } + var hyps = new List(); + double[] S1 = { -6, 0, 6 }, S2 = { 0, 6 }, S3 = { 0, 3 }, T2 = { 0, -3 }; + for (int ci = 0; ci < vars.Count; ci++) + for (int Q = 0; Q < 6; Q++) + { + PrismLayout E = Foundations.LayoutGet(Q); + double[,] src = new double[4, 2]; + Image.CornersOf(E, src); + for (int B = 0; B < 4; B++) + { + double[,] f = new double[4, 2]; + for (int k = 0; k < 4; k++) { f[k, 0] = vars[ci][(k + B) % 4, 0]; f[k, 1] = vars[ci][(k + B) % 4, 1]; } + PrismMap c = new PrismMap(); + if (Image.Homography(src, f, c) != 0) + { + outR.Err = new PrismErr { Stage = "undefined", Msg = "Singular geometry" }; + return -1; + } + DfRank(F, c, E, out double wcost, out double wscore); + double[] u = new double[10]; + for (int d = 0; d < 3; d++) + for (int y = 0; y < 3; y++) + for (int M = 0; M < 2; M++) + for (int D = 0; D < 2; D++) + { + double[] p = { S1[d], 0, 0, 0, 0, S1[y], S2[M], S3[D], 0, 0 }; + SetWarp(c, E, p); + DfRank(F, c, E, out double pc, out double ps); + if (ps > wscore || (ps == wscore && pc < wcost)) { wscore = ps; wcost = pc; Array.Copy(p, u, 10); } + } + for (int F2 = 0; F2 < 3; F2++) + for (int k2 = 0; k2 < 3; k2++) + for (int G = 0; G < 2; G++) + { + double[] p = { 0, 0, S1[F2], S1[k2], 0, 0, 0, 0, T2[G], T2[G] }; + SetWarp(c, E, p); + DfRank(F, c, E, out double pc, out double ps); + if (ps > wscore) { wscore = ps; wcost = pc; Array.Copy(p, u, 10); } + } + SetWarp(c, E, u); + DFHyp H = new DFHyp { H = c, L = E, Score = wscore, Cost = wcost, Seq = hyps.Count }; + Array.Copy(f, H.Quad, 8); + hyps.Add(H); + } + } + hyps.Sort((A, e) => + { + if (A.Score != e.Score) return A.Score < e.Score ? 1 : -1; + if (A.Cost != e.Cost) return A.Cost > e.Cost ? 1 : -1; + return A.Seq - e.Seq; + }); + var kept = new List(); + for (int i = 0; i < hyps.Count; i++) + { + bool dup = false; + for (int j = 0; j < kept.Count && !dup; j++) + { + if (kept[j].L.Size != hyps[i].L.Size) continue; + double s = 0; + for (int k = 0; k < 4; k++) + s += (hyps[i].Quad[k, 0] - kept[j].Quad[k, 0]) * (hyps[i].Quad[k, 0] - kept[j].Quad[k, 0]) + + (hyps[i].Quad[k, 1] - kept[j].Quad[k, 1]) * (hyps[i].Quad[k, 1] - kept[j].Quad[k, 1]); + if (s >= 2) continue; + bool all = true; + for (int k = 0; k < 10; k++) if (Math.Abs(hyps[i].H.WarpP[k] - kept[j].H.WarpP[k]) >= 0.1) { all = false; break; } + if (all) dup = true; + } + if (!dup) kept.Add(hyps[i]); + } + outR.Err = new PrismErr { Stage = "undefined", Msg = "Nonlinear geometry did not decode" }; + double[] XS = { -8, -4, 0, 4, 8 }, OS = { -2, 0, 3, 6, 9 }; + double[] SCALES = { 2, 1, 0.5, 0.25, 0.125 }; + for (int Li = 0; Li < kept.Count && Li < 20; Li++) + { + if (Budget.FastDeadlineHit()) break; + if (Budget.Now() - dfT0 > 15.0) break; + PrismMap R = CloneMap(kept[Li].H); + PrismLayout S = kept[Li].L; + double[,] N = (double[,])kept[Li].Quad.Clone(); + double[] q = new double[3]; + Image.WhiteBalance(fr, R, S, q); + int step = S.Known.Length / 160; if (step < 1) step = 1; + PrismCell[] J = new PrismCell[S.Known.Length / step + 2]; int nj = 0; + for (int k = 0; k < S.Known.Length; k++) if (k % step == 0) J[nj++] = S.Known[k]; + double W = DfScore(F, R, S, J, nj); + double[] K = R.WarpP, P = new double[10]; + Array.Copy(K, P, 10); + for (int xi = 0; xi < 5; xi++) + for (int oi = 0; oi < 5; oi++) + { + bool V = Math.Abs(K[2]) + Math.Abs(K[3]) > Math.Abs(K[0]) + Math.Abs(K[5]); + int j2 = V ? 8 : 6; + K[V ? 2 : 0] = XS[xi]; + K[j2] = V ? -OS[oi] : OS[oi]; + double sc = DfScore(F, R, S, J, nj); + if (sc < W) { W = sc; Array.Copy(K, P, 10); } + } + Array.Copy(P, K, 10); + bool nextCand = false; + for (int si = 0; si < 5 && !nextCand; si++) + { + double sc = SCALES[si]; + for (int pass = 0; pass < 3 && !nextCand; pass++) + { + bool improved = false; + K = R.WarpP; /* C: double *K = R.warpp aliases R's inline array across struct copies; + corner loop reassigns R to new objects, so re-sync each pass */ + for (int oi = 0; oi < 10; oi++) + { + double aA2 = K[oi], iA2 = aA2; + for (int gi = 0; gi < 2; gi++) + { + double gA2 = gi != 0 ? 1 : -1; + K[oi] = aA2 + gA2 * sc; + if (Math.Abs(K[oi]) > 12) continue; + double lA2 = DfScore(F, R, S, J, nj); + if (lA2 < W) { W = lA2; iA2 = K[oi]; improved = true; } + } + K[oi] = iA2; + } + double rA2 = JsMath.Hypot2(N[1, 0] - N[0, 0], N[1, 1] - N[0, 1]) / S.W; + double[,] src = new double[4, 2]; + Image.CornersOf(S, src); + for (int IA = 0; IA < 4 && !nextCand; IA++) + for (int hA = 0; hA < 2 && !nextCand; hA++) + { + double nA = N[IA, hA], sA2 = nA; + for (int ci = 0; ci < 2; ci++) + { + double CA = ci != 0 ? 1 : -1; + N[IA, hA] = nA + CA * sc * rA2 * 0.35; + PrismMap QA = new PrismMap(); + if (Image.Homography(src, N, QA) != 0) + { + outR.Err = new PrismErr { Stage = "undefined", Msg = "Singular geometry" }; + nextCand = true; break; + } + QA.HasWarp = R.HasWarp; QA.WarpW = R.WarpW; QA.WarpH = R.WarpH; + Array.Copy(R.WarpP, QA.WarpP, 10); + PrismMap EA2 = R; + R = QA; + double BA2 = DfScore(F, R, S, J, nj); + if (BA2 < W) { W = BA2; sA2 = N[IA, hA]; improved = true; } + else R = EA2; + } + if (nextCand) break; + N[IA, hA] = sA2; + { + PrismMap tmp = new PrismMap(); + if (Image.Homography(src, N, tmp) != 0) + { + outR.Err = new PrismErr { Stage = "undefined", Msg = "Singular geometry" }; + nextCand = true; break; + } + tmp.HasWarp = R.HasWarp; tmp.WarpW = R.WarpW; tmp.WarpH = R.WarpH; + Array.Copy(R.WarpP, tmp.WarpP, 10); + R = tmp; + } + } + if (!improved) break; + } + } + if (nextCand) continue; + Image.WhiteBalance(fr, R, S, q); + PrismErr g2 = new PrismErr { Stage = "undefined", Msg = "" }; + bool success = false; + if (Classify.UA(fr, R, S, 0, q, null, out PrismClassify cA, out string uerr) != 0) + { + DfSplitErr(uerr, g2); + outR.Err = g2; + continue; + } + PrismPayload fA = new PrismPayload(); bool haveFA = false; + bool denseRetry = false, closeNow = false; + if (cA.KnownMatch < 0.65) + { + if (cA.KnownMatch < 0.5 || W > 3.5) g2.Msg = "Weak known-cell support"; + else denseRetry = true; + } + else + { + PrismClassify c3 = ShallowHeaders(cA); + PrismErr pe = new PrismErr(); + if (Decode.DecodeClass(c3, fA, pe) == 0) haveFA = true; + else if (cA.KnownMatch < 0.5 || W > 3.5) g2 = pe; + else denseRetry = true; + } + if (denseRetry) + { + PrismMesh m1 = Classify.QaBuildDenseMesh(fr, R, S, 0, q, null); + PrismMesh m2 = Classify.QaBuildDenseMesh(fr, R, S, 0, q, m1); + if (Classify.UA(fr, R, S, 0, q, m2, out cA, out uerr) != 0) + { + DfSplitErr(uerr, g2); + closeNow = true; + } + else if (cA.KnownMatch < 0.7) + { + g2.Msg = "Weak mesh known-cell support"; + closeNow = true; + } + else + { + PrismClassify c4 = ShallowHeaders(cA); + PrismErr pe2 = new PrismErr(); + if (Decode.DecodeClass(c4, fA, pe2) == 0) haveFA = true; else g2 = pe2; + } + } + if (!closeNow && haveFA) + { + if (fA.NBytes == 0) + { + g2.Stage = "undefined"; + g2.Msg = "Nonlinear recovery does not accept empty payload hypotheses"; + } + else + { + outR.Ok = true; outR.Payload = fA; outR.Quality = cA.KnownMatch; + Array.Copy(N, outR.Quad, 8); Array.Copy(R.H, outR.H, 8); + outR.LayoutSize = S.Size; outR.Sigma = cA.Sigma; + outR.Radius = JsMath.Hypot2(N[1, 0] - N[0, 0], N[1, 1] - N[0, 1]) / S.W; + Array.Copy(R.WarpP, outR.Warp, 10); + outR.Reader = "original cells + fitted nonlinear surface"; + success = true; + } + } + if (success) return 0; + outR.Err = g2; + } + return -1; + } + + private static PrismClassify ShallowHeaders(PrismClassify a) + { + PrismClassify c = (PrismClassify)typeof(PrismClassify).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(a, null); + if (c.NHeaders > 3) c.NHeaders = 3; + return c; + } + + public static double FbMs { get => Flags.FbMs; set => Flags.FbMs = value; } + + private static void SetErr(PrismRead o, string stage, string msg) { o.Err = new PrismErr { Stage = stage, Msg = msg }; } + + public static int FastRead(byte[] rgba, int w, int h, PrismRead outR) + { + double fb = Flags.FbMs; + double t = Budget.Now(); + if (Flags.PageCapS > 0 && t > Flags.PageCapS) + { + Flags.CapStopped = 1; + SetErr(outR, "fast", "Read stopped: six-second limit reached"); + return -1; + } + double r = t + (fb > 0 ? fb : 950) / 1000.0; + bool capBinding = false; + if (Flags.PageCapS > 0 && Flags.PageCapS < r) { r = Flags.PageCapS; capBinding = true; } + Budget.OverallDeadlineSet(r); + Budget.FastDeadlineSet(t + (fb > 0 ? Math.Floor(fb * 0.66 + 0.5) : 700) / 1000.0); + int rc = -1; + void Fill(PrismMixResult z) + { + outR.Ok = true; outR.Payload = z.Payload; outR.Quality = z.Quality; + Array.Copy(z.H, outR.H, 8); outR.Radius = z.Radius; outR.Sigma = z.Sigma; + for (int k = 0; k < 4; k++) outR.Quad[k, 0] = outR.Quad[k, 1] = double.NaN; + } + if (Flags.Direct != 0) + { + PrismMixResult z = Mix.MixDirect(rgba, w, h); + if (z != null && Budget.Now() <= r) { Fill(z); rc = 0; } + else if (capBinding && Budget.Now() > r) { Flags.CapStopped = 1; SetErr(outR, "fast", "Read stopped: six-second limit reached"); } + else SetErr(outR, "fast", "No direct mixing read"); + Budget.FastDeadlineSet(0); Budget.OverallDeadlineSet(0); + return rc; + } + if (Flags.Mix != 0) + { + PrismMixResult z = Mix.MixDirect(rgba, w, h); + if (z != null) { Fill(z); rc = 0; } + } + if (rc != 0) + { + PrismRead tmp = new PrismRead(); + if (ReadLayer.ReadImage(rgba, w, h, false, tmp) == 0) { ReadLayer.CopyRead(tmp, outR); rc = 0; } + else ReadLayer.CopyRead(tmp, outR); + } + if (rc == 0 && Budget.Now() > r) + { + outR.Ok = false; outR.Payload = new PrismPayload(); + if (capBinding) { Flags.CapStopped = 1; SetErr(outR, "fast", "Read stopped: six-second limit reached"); } + else SetErr(outR, "fast", "No verified read within one second"); + rc = -1; + } + if (rc != 0) + { + Budget.FastDeadlineSet(r); + byte[] norm = new byte[w * h * 4]; + LocalNormalize(rgba, w, h, norm); + if (Budget.Now() > r) + { + if (capBinding) { Flags.CapStopped = 1; SetErr(outR, "fast", "Read stopped: six-second limit reached"); } + else SetErr(outR, "fast", "Fast read budget reached"); + } + else + { + PrismRead d = new PrismRead(); + rc = Read(norm, w, h, d); + ReadLayer.CopyRead(d, outR); + if (rc == 0 && Budget.Now() > r) + { + outR.Ok = false; outR.Payload = new PrismPayload(); + if (capBinding) { Flags.CapStopped = 1; SetErr(outR, "fast", "Read stopped: six-second limit reached"); } + else SetErr(outR, "fast", "No verified read within one second"); + rc = -1; + } + } + } + Budget.FastDeadlineSet(0); Budget.OverallDeadlineSet(0); + return rc; + } + } +} diff --git a/ports/csharp/reader/PrismFoundations.cs b/ports/csharp/reader/PrismFoundations.cs new file mode 100644 index 0000000..4885b7b --- /dev/null +++ b/ports/csharp/reader/PrismFoundations.cs @@ -0,0 +1,418 @@ +// PrismFoundations.cs - GF(256), Reed-Solomon, bit-erasure RS, rng, crc, +// bit writer, layout / capacity / header. Transliterated from the verified C +// port (ports/c/reader/prism_foundations.c), which is bit-exact vs the live +// JS reader. +using System; + +namespace Prism.Reader +{ + internal enum Role { Data = 0, Gap = 1, Ring = 2, Pilot = 3, Header = 4 } + + internal sealed class PrismCell + { + public int I, J; // col, row + public double X, Y; // lattice position + public int Role; + public int Symbol; // gap=8, ring=(5j+3i)%8, pilot=(2pi+3pj)%9, data=-1 + public double Pi, Pj; // pilot lattice coords (fractional on non-pilot cells) + public int Index; // position in Cells[] + public int Header; // header bit index 0..71, else -1 + } + + internal sealed class PrismLayout + { + public int Size, C, R; + public double W, H; + public PrismCell[] Cells; + public PrismCell[] Headers; // 72 + public PrismCell[] Data; // post-header, shuffled + public PrismCell[] Known; // ring+pilot, scan order + } + + internal struct PrismBlock { public int N, Nsym, K; } + + internal sealed class PrismCapacity + { + public int N; // total stream bytes + public int NBlocks; + public PrismBlock[] Blocks = new PrismBlock[32]; + public int K; // sum k + public int Payload; // k - 4 + } + + internal struct PrismRng { public uint S; } + + internal static class Foundations + { + public const double SQRT3 = 1.7320508075688772; + public const double Q = 3.0 * SQRT3; + + public static readonly int[,] Sizes = { { 21, 24 }, { 29, 33 }, { 41, 47 }, { 57, 66 }, { 81, 94 }, { 113, 130 } }; + + /* ================= GF(256) ================= */ + private static readonly byte[] EXP = new byte[512]; + private static readonly byte[] LOG = new byte[256]; + private static bool gfReady; + private static void GfInit() + { + if (gfReady) return; + int qq = 1; + for (int A = 0; A < 255; A++) + { + EXP[A] = (byte)qq; LOG[qq] = (byte)A; qq <<= 1; if ((qq & 256) != 0) qq ^= 285; + } + for (int A = 255; A < 512; A++) EXP[A] = EXP[A - 255]; + gfReady = true; + } + public static byte GfMul(byte A, byte e) { GfInit(); return (A != 0 && e != 0) ? EXP[LOG[A] + LOG[e]] : (byte)0; } + public static byte GfDiv(byte A, byte e) { GfInit(); return A != 0 ? EXP[(LOG[A] + 255 - LOG[e]) % 255] : (byte)0; } + public static byte GfPeval(byte[] p, int n, byte x) + { + byte t = 0; + for (int r = n - 1; r >= 0; r--) t = (byte)(GfMul(t, x) ^ p[r]); + return t; + } + public static void GfPolyMul(byte[] a, int na, byte[] b, int nb, byte[] outBuf) + { + for (int r = 0; r < na; r++) + for (int o = 0; o < nb; o++) outBuf[r + o] ^= GfMul(a[r], b[o]); + } + + /* generator polynomial cache: gen[e] has e+1 coeffs */ + private static readonly byte[][] genCache = new byte[65][]; + private static byte[] RsGen(int e) + { + GfInit(); + if (genCache[e] != null) return genCache[e]; + byte[] cur = new byte[66]; cur[0] = 1; + int nc = 1; + for (int A = 0; A < e; A++) + { + byte[] nxt = new byte[nc + 1]; + byte[] f2 = { 1, EXP[A] }; + GfPolyMul(cur, nc, f2, 2, nxt); + cur = new byte[66]; + Array.Copy(nxt, cur, nc + 1); nc++; + } + byte[] g = new byte[nc]; + Array.Copy(cur, g, nc); + genCache[e] = g; + return g; + } + public static void RsEncode(byte[] msg, int len, int e, byte[] outBuf) + { + byte[] g = RsGen(e); + Array.Clear(outBuf, 0, len + e); + Array.Copy(msg, outBuf, len); + for (int i = 0; i < len; i++) + { + byte A = outBuf[i]; + if (A != 0) for (int o = 1; o <= e; o++) outBuf[i + o] ^= GfMul(g[o], A); + } + Array.Copy(msg, outBuf, len); + } + public static void RsSyndromes(byte[] cw, int len, int e, byte[] outBuf) + { + GfInit(); + for (int r = 0; r < e; r++) + { + byte acc = 0; + for (int t = 0; t < len; t++) acc = (byte)(GfMul(acc, EXP[r]) ^ cw[t]); + outBuf[r] = acc; + } + } + + /* Berlekamp-Massey on Forney syndromes i[0..ni); writes locator (len r+1) into outBuf, returns r */ + private static int RsBm(byte[] i, int ni, byte[] outBuf) + { + byte[] e2 = new byte[130], t2 = new byte[130]; + e2[0] = t2[0] = 1; + int r = 0, o = 1; + byte a = 1; + for (int i2 = 0; i2 < ni; i2++) + { + byte g = i[i2]; + for (int t = 1; t <= r; t++) g ^= GfMul(e2[t], i[i2 - t]); + if (g == 0) { o++; continue; } + byte[] l = (byte[])e2.Clone(); + byte I = GfDiv(g, a); + for (int A = 0; A + o < ni + 1; A++) e2[A + o] ^= GfMul(I, t2[A]); + if (2 * r <= i2) { r = i2 + 1 - r; t2 = l; a = g; o = 1; } + else o++; + } + Array.Copy(e2, outBuf, r + 1); + return r; + } + + /* returns corrected count, or -1 with err set */ + public static int RsDecode(byte[] r, int n, int e, int[] eras, int nEras, out string err) + { + err = null; + GfInit(); + byte[] o = new byte[130]; + RsSyndromes(r, n, e, o); + bool allzero = true; + for (int i = 0; i < e; i++) if (o[i] != 0) { allzero = false; break; } + if (allzero) return 0; + if (nEras > e) { err = "Too many erasures"; return -1; } + byte[] a = new byte[130]; int na = 1; a[0] = 1; + byte[] i_ = new byte[130]; int ni = e; + Array.Copy(o, i_, e); + for (int q = 0; q < nEras; q++) + { + int A = eras[q]; + if (A < 0 || A >= n) { err = "Erasure index"; return -1; } + byte er = EXP[n - 1 - A]; + byte[] f2 = { 1, er }, nxt = new byte[130]; + GfPolyMul(a, na, f2, 2, nxt); + Array.Copy(nxt, a, na + 1); na++; + for (int A2 = 0; A2 < ni - 1; A2++) i_[A2] = (byte)(GfMul(i_[A2], er) ^ i_[A2 + 1]); + ni--; + } + byte[] g = new byte[130]; + int deg = RsBm(i_, ni, g); + if (2 * deg + nEras > e) { err = "RS correction limit"; return -1; } + byte[] l = new byte[300]; /* l = c(a, g) */ + GfPolyMul(a, na, g, deg + 1, l); + int nl = na + deg; + int[] I = new int[300]; int nI = 0; + for (int A = 0; A < n; A++) + { + int ev = n - 1 - A; + if (0 == GfPeval(l, nl, EXP[(255 - ev) % 255])) I[nI++] = A; + } + if (nI != nl - 1) { err = "RS roots"; return -1; } + byte[] h2 = new byte[300]; /* c(o, l).slice(0, e) */ + { + byte[] tmp = new byte[400]; + GfPolyMul(o, e, l, nl, tmp); + Array.Copy(tmp, h2, e < tmp.Length ? e : tmp.Length); + } + byte[] dv = new byte[300]; int ndv = nl - 1 > 1 ? nl - 1 : 1; + for (int A = 1; A < nl; A += 2) dv[A - 1] = l[A]; + for (int q = 0; q < nI; q++) + { + int A = I[q]; + int ev = n - 1 - A; + byte t_ = EXP[ev], o_ = EXP[(255 - ev) % 255]; + byte num = GfMul(t_, GfPeval(h2, e, o_)); + byte den = GfPeval(dv, ndv, o_); + if (den == 0) { err = "GF division by zero"; return -1; } + r[A] ^= GfDiv(num, den); + } + RsSyndromes(r, n, e, o); + for (int i = 0; i < e; i++) if (o[i] != 0) { err = "RS syndrome check"; return -1; } + return nI; + } + + public static int RsRecoverBits(byte[] A, byte[] mask, int n, int t, byte[] outBuf, out string err) + { + err = null; + GfInit(); + byte[] o = new byte[600]; + Array.Copy(A, o, n); + int[] aPos = new int[2100], aBit = new int[2100]; + int ni = 0; + for (int i = 0; i < n; i++) + { + o[i] &= (byte)~mask[i]; + for (int e = 0; e < 8; e++) if ((mask[i] & (1 << e)) != 0) { aPos[ni] = i; aBit[ni] = e; ni++; } + } + int limit = 8 * t < 512 ? 8 * t : 512; + if (ni == 0 || ni > limit) { err = "Bit erasure count"; return -1; } + int rows = 8 * t; + int W = (ni + 1 + 31) / 32; + uint[] g = new uint[rows * W]; + byte[] l = new byte[130]; + RsSyndromes(o, n, t, l); + for (int A2 = 0; A2 < t; A2++) + { + for (int e = 0; e < 8; e++) + if ((l[A2] & (1 << e)) != 0) g[(8 * A2 + e) * W + (ni >> 5)] |= 1u << (31 & ni); + for (int e = 0; e < ni; e++) + { + byte coef = GfMul((byte)(1 << aBit[e]), EXP[(A2 * (n - 1 - aPos[e])) % 255]); + for (int r2 = 0; r2 < 8; r2++) + if ((coef & (1 << r2)) != 0) g[(8 * A2 + r2) * W + (e >> 5)] |= 1u << (31 & e); + } + } + int I = 0; int[] h = new int[520]; + for (int A2 = 0; A2 < ni; A2++) + { + int t2 = I; + for (; t2 < rows && ((g[t2 * W + (A2 >> 5)] >> (31 & A2)) & 1) == 0;) t2++; + if (t2 == rows) { err = "Ambiguous bit erasures"; return -1; } + for (int w = 0; w < W; w++) { uint tmp = g[t2 * W + w]; g[t2 * W + w] = g[I * W + w]; g[I * W + w] = tmp; } + for (int e2 = I + 1; e2 < rows; e2++) + if (((g[e2 * W + (A2 >> 5)] >> (31 & A2)) & 1) != 0) + for (int w = A2 >> 5; w < W; w++) g[e2 * W + w] ^= g[I * W + w]; + h[I] = A2; I++; + } + for (int A2 = I; A2 < rows; A2++) + if (((g[A2 * W + (ni >> 5)] >> (31 & ni)) & 1) != 0) { err = "Inconsistent bit erasures"; return -1; } + byte[] n_ = new byte[520]; + for (int A2 = I - 1; A2 >= 0; A2--) + { + int e = h[A2]; + int t2 = (int)((g[A2 * W + (ni >> 5)] >> (31 & ni)) & 1); + for (int r2 = e + 1; r2 < ni; r2++) + if (((g[A2 * W + (r2 >> 5)] >> (31 & r2)) & 1) != 0) t2 ^= n_[r2]; + n_[e] = (byte)t2; + } + for (int A2 = 0; A2 < ni; A2++) if (n_[A2] != 0) o[aPos[A2]] |= (byte)(1 << aBit[A2]); + RsSyndromes(o, n, t, l); + for (int i = 0; i < t; i++) if (l[i] != 0) { err = "Bit erasure syndrome check"; return -1; } + Array.Copy(o, outBuf, n); + int corr = 0; + for (int i = 0; i < n; i++) if (o[i] != A[i]) corr++; + return corr; + } + + /* ================= rng ================= */ + public static void RngSeed(ref PrismRng r, uint seed) { r.S = seed; } + private static int Imul32(int a, int b) { unchecked { return (int)((uint)a * (uint)b); } } + public static double RngNext(ref PrismRng r) + { + unchecked + { + int A = (int)r.S; + A = (int)((uint)A + 1831565813u); + r.S = (uint)A; + int e = Imul32(A ^ (int)((uint)A >> 15), 1 | A); + e = (int)((uint)(e + Imul32(e ^ (int)((uint)e >> 7), 61 | e)) ^ (uint)e); + return (double)(uint)(e ^ (int)((uint)e >> 14)) / 4294967296.0; + } + } + + /* ================= crc ================= */ + private static readonly uint[] CRC32T = new uint[256]; + private static bool crcReady; + private static void CrcInit() + { + if (crcReady) return; + for (int e = 0; e < 256; e++) + { + uint v = (uint)e; + for (int A = 0; A < 8; A++) v = (v & 1) != 0 ? (3988292384u ^ (v >> 1)) : (v >> 1); + CRC32T[e] = v; + } + crcReady = true; + } + public static uint Crc32Bytes(byte[] p, int n) + { + CrcInit(); + uint e = 4294967295u; + for (int t = 0; t < n; t++) e = CRC32T[(int)(255 & (e ^ p[t]))] ^ (e >> 8); + return 4294967295u ^ e; + } + public static int Crc4Bits(byte[] bits, int n) + { + int e = 0; + for (int t = 0; t < n; t++) + { + int A = ((e >> 3) & 1) ^ bits[t]; + e = (e << 1) & 15; + if (A != 0) e ^= 3; + } + return e; + } + public static void BitsPush(byte[] bits, ref int n, uint v, int nbits) + { + for (int r = nbits - 1; r >= 0; r--) bits[n++] = (byte)((v >> r) & 1); + } + + /* ================= layout / capacity / header ================= */ + private static readonly PrismLayout[] LAY = new PrismLayout[6]; + public static PrismLayout LayoutGet(int size) + { + if (LAY[size] != null) return LAY[size]; + PrismLayout L = new PrismLayout(); + int C = Sizes[size, 0], R = Sizes[size, 1]; + double r = SQRT3; + int n = C * R; + L.Cells = new PrismCell[n]; + for (int q = 0; q < n; q++) L.Cells[q] = new PrismCell(); + PrismCell[] scanData = new PrismCell[n]; + int nScan = 0, nKnown = 0; + for (int A = 0; A < R; A++) + for (int a = 0; a < C; a++) + { + PrismCell s = L.Cells[A * C + a]; + int role = (int)Reader.Role.Data, sym = -1; + double h2 = (a - 2) / 5.0, n2 = (A - 2) / 5.0; + if (A <= 2 && a <= 2) { role = (int)Reader.Role.Gap; sym = 8; } + else if (0 == A || A == R - 1 || 0 == a || a == C - 1) { role = (int)Reader.Role.Ring; sym = (5 * A + 3 * a) % 8; } + else if (a % 5 == 2 && A % 5 == 2) { role = (int)Reader.Role.Pilot; sym = (2 * (int)h2 + 3 * (int)n2) % 9; } + s.I = a; s.J = A; + s.X = r * (a + 0.5 + 0.5 * (1 & A)); + s.Y = 1 + 1.5 * A; + s.Role = role; s.Symbol = sym; s.Pi = h2; s.Pj = n2; + s.Index = A * C + a; s.Header = -1; + if (role == (int)Reader.Role.Data) scanData[nScan++] = s; + else if (role != (int)Reader.Role.Gap) nKnown++; + } + L.Headers = new PrismCell[72]; + for (int A = 0; A < 72; A++) + { + PrismCell e = scanData[(int)Math.Floor(((A + 0.5) * nScan) / 72.0)]; + e.Role = (int)Reader.Role.Header; e.Header = A; + L.Headers[A] = e; + } + int nData = 0; + for (int q = 0; q < nScan; q++) if (scanData[q].Role == (int)Reader.Role.Data) nData++; + L.Data = new PrismCell[nData]; + nData = 0; + for (int q = 0; q < nScan; q++) if (scanData[q].Role == (int)Reader.Role.Data) L.Data[nData++] = scanData[q]; + /* Fisher-Yates with rng(24301 ^ size) */ + PrismRng rng = default; RngSeed(ref rng, (uint)(24301 ^ size)); + for (int A = L.Data.Length - 1; A > 0; A--) + { + int e = (int)Math.Floor(RngNext(ref rng) * (A + 1)); + PrismCell tmp = L.Data[A]; L.Data[A] = L.Data[e]; L.Data[e] = tmp; + } + L.Known = new PrismCell[nKnown]; + nKnown = 0; + for (int A = 0; A < R; A++) + for (int a = 0; a < C; a++) + { + PrismCell s = L.Cells[A * C + a]; + if (s.Role == (int)Reader.Role.Ring || s.Role == (int)Reader.Role.Pilot) L.Known[nKnown++] = s; + } + L.Size = size; L.C = C; L.R = R; + L.W = r * (C + 0.5); + L.H = 2 + 1.5 * (R - 1); + LAY[size] = L; + return L; + } + + public static void CapacityGet(int size, int ecc, int mode, PrismCapacity outCap) + { + PrismLayout L = LayoutGet(size); + double[] FRAC = { 0.1, 0.2, 0.3, 0.4 }; + int o = (int)Math.Floor((L.Data.Length * (mode != 0 ? 1 : 3)) / 8.0); + int a = (o + 254) / 255; + outCap.N = o; outCap.NBlocks = a; outCap.K = 0; + for (int A = 0; A < a; A++) + { + int t = o / a + (A < o % a ? 1 : 0); + int ns = 2 * (int)Math.Floor(t * FRAC[ecc] / 2.0 + 0.5); + if (ns < 4) ns = 4; + outCap.Blocks[A].N = t; outCap.Blocks[A].Nsym = ns; outCap.Blocks[A].K = t - ns; + outCap.K += t - ns; + } + outCap.Payload = outCap.K - 4 > 0 ? outCap.K - 4 : 0; + } + + public static void HeaderBits(int size, int ecc, int mode, int type, int len, byte[] outBuf) + { + int n = 0; + BitsPush(outBuf, ref n, (uint)size, 3); + BitsPush(outBuf, ref n, (uint)ecc, 2); + BitsPush(outBuf, ref n, (uint)mode, 1); + BitsPush(outBuf, ref n, (uint)type, 1); + BitsPush(outBuf, ref n, (uint)len, 13); + int c = Crc4Bits(outBuf, n); + BitsPush(outBuf, ref n, (uint)c, 4); + } + } +} diff --git a/ports/csharp/reader/PrismImage.cs b/ports/csharp/reader/PrismImage.cs new file mode 100644 index 0000000..fab2f26 --- /dev/null +++ b/ports/csharp/reader/PrismImage.cs @@ -0,0 +1,357 @@ +// PrismImage.cs - frame, sampling, Lab palette, homography, hypothesis +// scoring, quad refinement. Transliterated from the verified C port +// (ports/c/reader/prism_image.c), bit-exact vs the live JS reader. +using System; + +namespace Prism.Reader +{ + internal sealed class PrismFrame + { + public int W, H; + public float[] P; // interleaved RGB, linear + public byte[] Image; // original RGBA + } + + internal sealed class PrismMap + { + public double[] H = new double[8]; + public int HasWarp; + public double WarpW, WarpH; + public double[] WarpP = new double[10]; + public void CopyFrom(PrismMap o) + { + Array.Copy(o.H, H, 8); + HasWarp = o.HasWarp; WarpW = o.WarpW; WarpH = o.WarpH; + Array.Copy(o.WarpP, WarpP, 10); + } + } + + internal static class Image + { + /* sRGB linearize table (N), float32 storage like the JS Float32Array */ + private static readonly float[] LIN = new float[256]; + private static bool linReady; + public static double LinSPub(double A) { return LinS(A); } + private static double LinS(double A) { return A <= 0.04045 ? A / 12.92 : JsMath.Pow((A + 0.055) / 1.055, 2.4); } + public static double SrgbQ(double A) { return A <= 0.0031308 ? 12.92 * A : 1.055 * JsMath.Pow(A, 1 / 2.4) - 0.055; } + + private static void LinInit() + { + if (linReady) return; + for (int i = 0; i < 256; i++) LIN[i] = (float)LinS(i / 255.0); + linReady = true; + } + + /* 7-point stencil: center + 6 hex at 0.45, exact V8/fdlibm doubles */ + private static readonly double[,] STEN = new double[7, 2]; + private static bool stenReady; + private static void StenInit() + { + if (stenReady) return; + long[] bits = { + 0x3fdccccccccccccdL, 0x0000000000000000L, + 0x3fcccccccccccccfL, 0x3fd8f1083782ab66L, + unchecked((long)0xbfccccccccccccc9UL), 0x3fd8f1083782ab67L, + unchecked((long)0xbfdccccccccccccdUL), 0x3c8fc4ab28be3f40L, + unchecked((long)0xbfccccccccccccd4UL), unchecked((long)0xbfd8f1083782ab65UL), + 0x3fcccccccccccccfL, unchecked((long)0xbfd8f1083782ab66UL), + }; + for (int i = 0; i < 6; i++) { STEN[i + 1, 0] = BitConverter.Int64BitsToDouble(bits[2 * i]); STEN[i + 1, 1] = BitConverter.Int64BitsToDouble(bits[2 * i + 1]); } + stenReady = true; + } + + public static PrismFrame FrameCreate(int w, int h, byte[] rgba) + { + LinInit(); StenInit(); + PrismFrame f = new PrismFrame { W = w, H = h, Image = rgba }; + f.P = new float[w * h * 3]; + int e = 0; + for (int A = 0; A < w * h * 4; A += 4) + { + f.P[e++] = LIN[rgba[A]]; + f.P[e++] = LIN[rgba[A + 1]]; + f.P[e++] = LIN[rgba[A + 2]]; + } + return f; + } + public static void LinDump(float[] outBuf) { LinInit(); Array.Copy(LIN, outBuf, 256); } + public static void StencilGet(double[,] outBuf) { StenInit(); Array.Copy(STEN, outBuf, 14); } + + public static void FrameSample(PrismFrame A, double t, double r, double[] outBuf) + { + if (t < 0 || r < 0 || t >= A.W - 1 || r >= A.H - 1) { outBuf[0] = outBuf[1] = outBuf[2] = 1; return; } + int o = (int)Math.Floor(t), a = (int)Math.Floor(r); + double i = t - o, g = r - a; + int l = 3 * (a * A.W + o); + float[] p = A.P; + outBuf[0] = (p[l + 0] * (1 - i) + p[l + 3] * i) * (1 - g) + (p[l + 3 * A.W + 0] * (1 - i) + p[l + 3 * A.W + 3] * i) * g; + outBuf[1] = (p[l + 1] * (1 - i) + p[l + 4] * i) * (1 - g) + (p[l + 3 * A.W + 1] * (1 - i) + p[l + 3 * A.W + 4] * i) * g; + outBuf[2] = (p[l + 2] * (1 - i) + p[l + 5] * i) * (1 - g) + (p[l + 3 * A.W + 2] * (1 - i) + p[l + 3 * A.W + 5] * i) * g; + } + + private static double MedianN(double[] A, int n) { Array.Sort(A, 0, n); return A[n >> 1]; } + /* O(): NaN check on first 7 then insertion sort median */ + private static double MedianO(double[] A, int n) + { + bool nan = false; + for (int i = 0; i < 7 && i < n; i++) if (A[i] != A[i]) { nan = true; break; } + if (nan) return MedianN(A, n); + for (int e = 1; e < n; e++) + { + double t = A[e]; + int r = e - 1; + for (; r >= 0 && A[r] > t;) { A[r + 1] = A[r]; r--; } + A[r + 1] = t; + } + return A[n >> 1]; + } + + public static void MapPoint(PrismMap A, double t, double r, out double ox, out double oy) + { + if (A.HasWarp != 0) + { + double i = (2 * t) / A.WarpW - 1, g = (2 * r) / A.WarpH - 1; + double[] a = A.WarpP; + t += (1 - i * i) * (a[0] + a[1] * g) + a[2] * (1 - g * g) + a[6] * i * (1 - i * i) + a[8] * i * (1 - g * g); + r += (1 - g * g) * (a[3] + a[4] * i) + a[5] * (1 - i * i) + a[7] * g * (1 - i * i) + a[9] * g * (1 - g * g); + } + double o = A.H[6] * t + A.H[7] * r + 1; + ox = (A.H[0] * t + A.H[1] * r + A.H[2]) / o; + oy = (A.H[3] * t + A.H[4] * r + A.H[5]) / o; + } + + /* W(): Gauss-Jordan with partial pivot; returns 0 ok */ + public static int SolveN(int n, double[] A /* n rows of n */, double[] e, double[] outBuf) + { + double[] r = new double[n * (n + 1)]; + for (int i = 0; i < n; i++) { Array.Copy(A, i * n, r, i * (n + 1), n); r[i * (n + 1) + n] = e[i]; } + for (int A2 = 0; A2 < n; A2++) + { + int e2 = A2; + for (int o = A2 + 1; o < n; o++) if (Math.Abs(r[o * (n + 1) + A2]) > Math.Abs(r[e2 * (n + 1) + A2])) e2 = o; + if (Math.Abs(r[e2 * (n + 1) + A2]) < 1e-10) return -1; + if (e2 != A2) for (int k = 0; k <= n; k++) { double tmp = r[A2 * (n + 1) + k]; r[A2 * (n + 1) + k] = r[e2 * (n + 1) + k]; r[e2 * (n + 1) + k] = tmp; } + double piv = r[A2 * (n + 1) + A2]; + for (int e3 = A2; e3 <= n; e3++) r[A2 * (n + 1) + e3] /= piv; + for (int e3 = 0; e3 < n; e3++) + if (e3 != A2) + { + piv = r[e3 * (n + 1) + A2]; + for (int a = A2; a <= n; a++) r[e3 * (n + 1) + a] -= piv * r[A2 * (n + 1) + a]; + } + } + for (int i = 0; i < n; i++) outBuf[i] = r[i * (n + 1) + n]; + return 0; + } + + public static int Homography(double[,] A, double[,] e, PrismMap outMap) + { + double[] t = new double[8 * 8], r = new double[8]; + for (int o = 0; o < 4; o++) + { + double a = A[o, 0], i = A[o, 1], g = e[o, 0], l = e[o, 1]; + double[] row0 = { a, i, 1, 0, 0, 0, -g * a, -g * i }; + double[] row1 = { 0, 0, 0, a, i, 1, -l * a, -l * i }; + Array.Copy(row0, 0, t, o * 16, 8); + Array.Copy(row1, 0, t, o * 16 + 8, 8); + r[o * 2] = g; r[o * 2 + 1] = l; + } + return SolveN(8, t, r, outMap.H); + } + + public static void CornersOf(PrismLayout l, double[,] outBuf) + { + outBuf[0, 0] = 0; outBuf[0, 1] = 0; + outBuf[1, 0] = l.W; outBuf[1, 1] = 0; + outBuf[2, 0] = l.W; outBuf[2, 1] = l.H; + outBuf[3, 0] = 0; outBuf[3, 1] = l.H; + } + + public static int KnownSymbol(PrismCell A, int e) + { + if (e != 0) return (A.Role == (int)Role.Ring || (A.Pi + A.Pj) % 2.0 == 0.0) ? 0 : 8; + return A.Symbol; + } + + /* palette: 9 hex colors, linear + Lab */ + private static readonly double[,] PAL = new double[9, 3]; + private static readonly double[,] LAB = new double[9, 3]; + private static readonly string[] HEX = { "#1B1B1B", "#2E5BFF", "#00B8D9", "#2DB35A", "#F5C518", "#F77F00", "#D7263D", "#B5179E", "#FFFFFF" }; + + public static void LabOf(double[] A, double[] outBuf) + { + double e = (0.4124564 * A[0] + 0.3575761 * A[1] + 0.1804375 * A[2]) / 0.95047; + double t = 0.2126729 * A[0] + 0.7151522 * A[1] + 0.0721750 * A[2]; + double r = (0.0193339 * A[0] + 0.1191920 * A[1] + 0.9503041 * A[2]) / 1.08883; + double fo; + e = e > 0.008856 ? JsMath.Cbrt(e) : 7.787 * e + 16.0 / 116; + fo = t > 0.008856 ? JsMath.Cbrt(t) : 7.787 * t + 16.0 / 116; + r = r > 0.008856 ? JsMath.Cbrt(r) : 7.787 * r + 16.0 / 116; + outBuf[0] = 116 * fo - 16; + outBuf[1] = 500 * (e - fo); + outBuf[2] = 200 * (fo - r); + } + public static double LabDist2(double[] A, double[] e) + { + return (A[0] - e[0]) * (A[0] - e[0]) + (A[1] - e[1]) * (A[1] - e[1]) + (A[2] - e[2]) * (A[2] - e[2]); + } + private static bool palReady; + public static void PalInit() + { + if (palReady) return; + LinInit(); + for (int i = 0; i < 9; i++) + { + for (int c = 0; c < 3; c++) + { + int v = Convert.ToInt32(HEX[i].Substring(1 + 2 * c, 2), 16); + PAL[i, c] = LinS(v / 255.0); + } + double[] rgb = { PAL[i, 0], PAL[i, 1], PAL[i, 2] }; + double[] lab = new double[3]; + LabOf(rgb, lab); + LAB[i, 0] = lab[0]; LAB[i, 1] = lab[1]; LAB[i, 2] = lab[2]; + } + palReady = true; + } + + public static void PalDump(double[,] pal, double[,] lab) { PalInit(); Array.Copy(PAL, pal, 27); Array.Copy(LAB, lab, 27); } + + public static int NearestSym(double[] A, int e, out double d) + { + PalInit(); + double[] t = new double[3]; + LabOf(A, t); + int r = -1; + double o = double.PositiveInfinity; + for (int A2 = 0; A2 < 9; A2++) + { + if (e != 0 && 0 != A2 && 8 != A2) continue; + double[] labRow = { LAB[A2, 0], LAB[A2, 1], LAB[A2, 2] }; + double a = LabDist2(t, labRow); + if (a < o) { o = a; r = A2; } + } + d = Math.Sqrt(o); + return r; + } + + public static void SampleCellEx(PrismFrame A, PrismMap e, PrismCell t, double[] r, double mdx, double mdy, int a, double[] outBuf) + { + StenInit(); + if (a != 0) + { + MapPoint(e, t.X + STEN[0, 0], t.Y + STEN[0, 1], out double x, out double y); + double[] s = new double[3]; + FrameSample(A, x + mdx, y + mdy, s); + outBuf[0] = s[0] / r[0]; outBuf[1] = s[1] / r[1]; outBuf[2] = s[2] / r[2]; + return; + } + double[,] g = new double[3, 7]; + for (int o = 0; o < 7; o++) + { + MapPoint(e, t.X + STEN[o, 0], t.Y + STEN[o, 1], out double x, out double y); + double[] l = new double[3]; + FrameSample(A, x + mdx, y + mdy, l); + for (int c = 0; c < 3; c++) g[c, o] = l[c] / r[c]; + } + for (int c = 0; c < 3; c++) + { + double[] col = new double[7]; + for (int o = 0; o < 7; o++) col[o] = g[c, o]; + outBuf[c] = MedianO(col, 7); + } + } + + public static void SampleCell(PrismFrame A, PrismMap e, PrismCell t, double[] r, int a, double[] outBuf) + { + SampleCellEx(A, e, t, r, 0, 0, a, outBuf); + } + + public static void WhiteBalance(PrismFrame A, PrismMap e, PrismLayout t, double[] outBuf) + { + double[][] r = { new double[96], new double[96], new double[96] }; + int[] n = { 0, 0, 0 }; + for (int o = 0; o < 24; o++) + { + double a = (o + 0.5) / 24.0; + double[,] pts = { { a * t.W, -2.5 }, { a * t.W, t.H + 2.5 }, { -2.5, a * t.H }, { t.W + 2.5, a * t.H } }; + for (int q = 0; q < 4; q++) + { + MapPoint(e, pts[q, 0], pts[q, 1], out double x, out double y); + if (x < 0 || y < 0 || x >= A.W - 1 || y >= A.H - 1) continue; + double[] s = new double[3]; + FrameSample(A, x, y, s); + for (int c = 0; c < 3; c++) r[c][n[c]++] = s[c]; + } + } + for (int c = 0; c < 3; c++) + { + double m = n[c] != 0 ? MedianN(r[c], n[c]) : 1.0; + outBuf[c] = m > 0.08 ? m : 0.08; + } + } + + public static void HypothesisScore(PrismFrame A, PrismMap t, PrismLayout r, int o, double[] a, int i, out double cost, out double score) + { + PalInit(); + double g = 0; + int I = 0, l = 0; + int h = r.Known.Length / ((i != 0 && o == 0) ? 60 : 120); + if (h < 1) h = 1; + for (int e = 0; e < r.Known.Length; e += h) + { + PrismCell hc = r.Known[e]; + if (o != 0 && hc.Role == (int)Role.Ring) continue; + double[] n2 = new double[3]; + SampleCell(A, t, hc, a, i, n2); + int s = KnownSymbol(hc, o); + double[] un = new double[3]; + LabOf(n2, un); + double[] labRow = { LAB[s, 0], LAB[s, 1], LAB[s, 2] }; + double Q = Math.Sqrt(LabDist2(un, labRow)); + int C = NearestSym(n2, o, out double d); + g += Q / 30 < 1 ? Q / 30 : 1; + I += C == s ? 1 : 0; + l++; + } + cost = g / l; + score = (double)I / l; + } + + public static double RefineQuad(PrismFrame A, PrismMap e, PrismLayout t, int r, double[,] o, double[] a, ref int err) + { + double[,] i = (double[,])o.Clone(); + double g = JsMath.Hypot2(i[1, 0] - i[0, 0], i[1, 1] - i[0, 1]) / t.W; + double I = 0.5 * g; + HypothesisScore(A, e, t, r, a, 0, out double h, out double sc); + double[,] src = new double[4, 2]; + CornersOf(t, src); + for (; I > g * 0.03; I *= 0.5) + { + for (int round = 0; round < 2; round++) + { + bool changed = false; + for (int g2 = 0; g2 < 4; g2++) + for (int l = 0; l < 2; l++) + { + double n = i[g2, l], s = n; + for (int Cs = 0; Cs < 2; Cs++) + { + double C = Cs != 0 ? 1.0 : -1.0; + i[g2, l] = n + C * I; + PrismMap Q2 = new PrismMap(); + if (Homography(src, i, Q2) != 0) { err = 1; return h; } + HypothesisScore(A, Q2, t, r, a, 0, out double E, out double sc2); + if (E < h) { h = E; s = i[g2, l]; e.CopyFrom(Q2); changed = true; } + } + i[g2, l] = s; + } + if (!changed) break; + } + } + Array.Copy(i, o, 8); + err = 0; + return h; + } + } +} diff --git a/ports/csharp/reader/PrismJsMath.cs b/ports/csharp/reader/PrismJsMath.cs new file mode 100644 index 0000000..b65ce47 --- /dev/null +++ b/ports/csharp/reader/PrismJsMath.cs @@ -0,0 +1,783 @@ +// PrismJsMath.cs - C# port of prism_jsmath.c: exact ports of V8 12.4 math +// functions (fdlibm-based ieee754.cc). .NET's System.Math does not match V8 +// bit-for-bit; these do. Transliterated 1:1 from the verified C source. +using System; + +namespace Prism.Reader +{ + internal static class JsMath + { + private static long Bits(double x) => BitConverter.DoubleToInt64Bits(x); + private static double FromBits(long u) => BitConverter.Int64BitsToDouble(u); + private static int Hi(double x) => (int)(BitConverter.DoubleToInt64Bits(x) >> 32); + private static uint Lo(double x) => (uint)BitConverter.DoubleToInt64Bits(x); + private static double WithHi(double x, int h) + { + long u = BitConverter.DoubleToInt64Bits(x); + u = (u & 0xffffffffL) | ((long)(uint)h << 32); + return BitConverter.Int64BitsToDouble(u); + } + private static double WithLo(double x, uint l) + { + long u = BitConverter.DoubleToInt64Bits(x); + u = (u & unchecked((long)0xffffffff00000000UL)) | l; + return BitConverter.Int64BitsToDouble(u); + } + private static double Insert(int h, uint l) + => BitConverter.Int64BitsToDouble(((long)(uint)h << 32) | l); + + /* fdlibm s_scalbn (needed by Pow's subnormal path) */ + private static double Scalbn(double x, int n) + { + const double two54 = 1.80143985094819840000e+16, + twom54 = 5.55111512312578270212e-17, + huge = 1.0e+300, tiny = 1.0e-300; + int hx = Hi(x); uint lx = Lo(x); + int k = (hx & 0x7ff00000) >> 20; + if (k == 0) + { + if (((hx & 0x7fffffff) | (int)lx) == 0) return x; + x *= two54; + hx = Hi(x); + k = ((hx & 0x7ff00000) >> 20) - 54; + if (n < -50000) return tiny * x; + } + if (k == 0x7ff) return x + x; + k += n; + if (k > 0x7fe) return huge * Math.CopySign(huge, x); + if (k > 0) return WithHi(x, (hx & unchecked((int)0x800fffff)) | (k << 20)); + if (k <= -54) + { + if (n > 50000) return huge * Math.CopySign(huge, x); + return tiny * Math.CopySign(tiny, x); + } + k += 54; + x = WithHi(x, (hx & unchecked((int)0x800fffff)) | (k << 20)); + return x * twom54; + } + + /* ---- V8 12.4 base::ieee754::pow (fdlibm e_pow) ---- */ + public static double Pow(double x, double y) + { + unchecked + { + double[] bp = { 1.0, 1.5 }; + double[] dp_h = { 0.0, 5.84962487220764160156e-01 }; + double[] dp_l = { 0.0, 1.35003920212974897128e-08 }; + const double zero = 0.0, one = 1.0, two = 2.0, + two53 = 9007199254740992.0, + huge = 1.0e300, tiny = 1.0e-300, + L1 = 5.99999999999994648725e-01, L2 = 4.28571428578550184252e-01, + L3 = 3.33333329818377432918e-01, L4 = 2.72728123808534006489e-01, + L5 = 2.30660745775561754067e-01, L6 = 2.06975017800338417784e-01, + P1 = 1.66666666666666019037e-01, P2 = -2.77777777770155933842e-03, + P3 = 6.61375632143793436117e-05, P4 = -1.65339022054652515390e-06, + P5 = 4.13813679705723846039e-08, + lg2 = 6.93147180559945286227e-01, + lg2_h = 6.93147182464599609375e-01, + lg2_l = -1.90465429995776804525e-09, + ovt = 8.0085662595372944372e-0017, + cp = 9.61796693925975554329e-01, + cp_h = 9.61796700954437255859e-01, + cp_l = -7.02846165095275826516e-09, + ivln2 = 1.44269504088896338700e+00, + ivln2_h = 1.44269502162933349609e+00, + ivln2_l = 1.92596299112661746887e-08; + double z, ax, z_h, z_l, p_h, p_l; + double y1, t1, t2, r, s, t, u, v, w; + int i, j, k, yisint, n; + int hx, hy, ix, iy; + uint lx, ly; + hx = Hi(x); lx = Lo(x); + hy = Hi(y); ly = Lo(y); + ix = hx & 0x7fffffff; + iy = hy & 0x7fffffff; + if (((uint)iy | ly) == 0) return one; + if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) || iy > 0x7ff00000 || + ((iy == 0x7ff00000) && (ly != 0))) return x + y; + yisint = 0; + if (hx < 0) + { + if (iy >= 0x43400000) yisint = 2; + else if (iy >= 0x3ff00000) + { + k = (iy >> 20) - 0x3ff; + if (k > 20) + { + j = (int)(ly >> (52 - k)); + if ((j << (52 - k)) == (int)ly) yisint = 2 - (j & 1); + } + else if (ly == 0) + { + j = iy >> (20 - k); + if ((j << (20 - k)) == iy) yisint = 2 - (j & 1); + } + } + } + if (ly == 0) + { + if (iy == 0x7ff00000) + { + if (((ix - 0x3ff00000) | (int)lx) == 0) return y - y; + else if (ix >= 0x3ff00000) return (hy >= 0) ? y : zero; + else return (hy < 0) ? -y : zero; + } + if (iy == 0x3ff00000) { if (hy < 0) return one / x; else return x; } + if (hy == 0x40000000) return x * x; + if (hy == 0x3fe00000) { if (hx >= 0) return Math.Sqrt(x); } + } + ax = Math.Abs(x); + if (lx == 0) + { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) + { + z = ax; + if (hy < 0) z = one / z; + if (hx < 0) + { + if (((ix - 0x3ff00000) | yisint) == 0) z = 0.0 / 0.0; + else if (yisint == 1) z = -z; + } + return z; + } + } + n = (hx >> 31) + 1; + if ((n | yisint) == 0) return 0.0 / 0.0; + s = one; + if ((n | (yisint - 1)) == 0) s = -one; + if (iy > 0x41e00000) + { + if (iy > 0x43f00000) + { + if (ix <= 0x3fefffff) return (hy < 0) ? huge * huge : tiny * tiny; + if (ix >= 0x3ff00000) return (hy > 0) ? huge * huge : tiny * tiny; + } + if (ix < 0x3fefffff) return (hy < 0) ? s * huge * huge : s * tiny * tiny; + if (ix > 0x3ff00000) return (hy > 0) ? s * huge * huge : s * tiny * tiny; + t = ax - one; + w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25)); + u = ivln2_h * t; + v = t * ivln2_l - w * ivln2; + t1 = u + v; + t1 = WithLo(t1, 0); + t2 = v - (t1 - u); + } + else + { + double ss, s2, s_h, s_l, t_h, t_l; + n = 0; + if (ix < 0x00100000) + { + ax *= two53; + n -= 53; + ix = Hi(ax); + } + n += (ix >> 20) - 0x3ff; + j = ix & 0x000fffff; + ix = j | 0x3ff00000; + if (j <= 0x3988E) k = 0; + else if (j < 0xBB67A) k = 1; + else { k = 0; n += 1; ix -= 0x00100000; } + ax = WithHi(ax, ix); + u = ax - bp[k]; + v = one / (ax + bp[k]); + ss = u * v; + s_h = ss; + s_h = WithLo(s_h, 0); + t_h = zero; + t_h = WithHi(t_h, ((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18)); + t_l = ax - (t_h - bp[k]); + s_l = v * ((u - s_h * t_h) - s_h * t_l); + s2 = ss * ss; + r = s2 * s2 * (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6))))); + r += s_l * (s_h + ss); + s2 = s_h * s_h; + t_h = 3.0 + s2 + r; + t_h = WithLo(t_h, 0); + t_l = r - ((t_h - 3.0) - s2); + u = s_h * t_h; + v = s_l * t_h + t_l * ss; + p_h = u + v; + p_h = WithLo(p_h, 0); + p_l = v - (p_h - u); + z_h = cp_h * p_h; + z_l = cp_l * p_h + p_l * cp + dp_l[k]; + t = n; + t1 = (((z_h + z_l) + dp_h[k]) + t); + t1 = WithLo(t1, 0); + t2 = z_l - (((t1 - t) - dp_h[k]) - z_h); + } + y1 = y; + y1 = WithLo(y1, 0); + p_l = (y - y1) * t1 + y * t2; + p_h = y1 * t1; + z = p_l + p_h; + j = Hi(z); i = (int)Lo(z); + if (j >= 0x40900000) + { + if (((j - 0x40900000) | i) != 0) return s * huge * huge; + else { if (p_l + ovt > z - p_h) return s * huge * huge; } + } + else if ((j & 0x7fffffff) >= 0x4090cc00) + { + if (((j - (int)0xc090cc00) | i) != 0) return s * tiny * tiny; + else { if (p_l <= z - p_h) return s * tiny * tiny; } + } + i = j & 0x7fffffff; + k = (i >> 20) - 0x3ff; + n = 0; + if (i > 0x3fe00000) + { + n = j + (0x00100000 >> (k + 1)); + k = ((n & 0x7fffffff) >> 20) - 0x3ff; + t = zero; + t = WithHi(t, n & ~(0x000fffff >> k)); + n = ((n & 0x000fffff) | 0x00100000) >> (20 - k); + if (j < 0) n = -n; + p_h -= t; + } + t = p_l + p_h; + t = WithLo(t, 0); + u = t * lg2_h; + v = (p_l - (t - p_h)) * lg2 + t * lg2_l; + z = u + v; + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + r = (z * t1) / ((t1 - two) - (w + z * w)); + z = one - (r - z); + j = Hi(z); + j += (int)((uint)n << 20); + if ((j >> 20) <= 0) z = Scalbn(z, n); + else z = WithHi(z, j); + return s * z; + } + } + + /* ---- V8 12.4 cbrt (msun-style); proven 0/300030 diffs ---- */ + public static double Cbrt(double x) + { + unchecked + { + const double P0 = 1.87595182427177009643, + P1 = -1.88497979543377169875, + P2 = 1.621429720105354466140, + P3 = -0.758397934778766047437, + P4 = 0.145996192886612446982; + ulong ux = (ulong)BitConverter.DoubleToInt64Bits(x); + int hx = (int)(ux >> 32); + uint low = (uint)ux; + uint sign = (uint)hx & 0x80000000u; + hx ^= (int)sign; + if (hx >= 0x7ff00000) return x + x; + double t; + if (hx < 0x00100000) + { + if ((hx | (int)low) == 0) return x; + t = BitConverter.Int64BitsToDouble(0x43500000L << 32); + t *= x; + ulong u2 = (ulong)BitConverter.DoubleToInt64Bits(t); + uint high = (uint)(u2 >> 32); + u2 = (ulong)(sign | ((high & 0x7fffffffu) / 3 + 696219795u)) << 32; + t = BitConverter.Int64BitsToDouble((long)u2); + } + else + { + ulong u2 = (ulong)(sign | ((uint)hx / 3 + 715094163u)) << 32; + t = BitConverter.Int64BitsToDouble((long)u2); + } + double r, s, w; + r = (t * t) * (t / x); + t = t * ((P0 + r * (P1 + r * P2)) + ((r * r) * r) * (P3 + r * P4)); + ulong bits = (ulong)BitConverter.DoubleToInt64Bits(t); + bits = (bits + 0x80000000UL) & 0xFFFFFFFFC0000000UL; + t = BitConverter.Int64BitsToDouble((long)bits); + s = t * t; + r = x / s; + w = t + t; + r = (r - t) / (w + r); + t = t + t * r; + return t; + } + } + + /* ---- fdlibm s_atan ---- */ + public static double Atan(double x) + { + unchecked + { + double[] atanhi = { + 4.63647609000806093515e-01, 7.85398163397448278999e-01, + 9.82793723247329054082e-01, 1.57079632679489655800e+00 }; + double[] atanlo = { + 2.26987774529616870924e-17, 3.06161699786838301793e-17, + 1.39033110312309984516e-17, 6.12323399573676603587e-17 }; + double[] aT = { + 3.33333333333329318027e-01, -1.99999999998764832476e-01, + 1.42857142725034663711e-01, -1.11111104054623557880e-01, + 9.09088713343650656196e-02, -7.69187620504482999495e-02, + 6.66107313738753120669e-02, -5.83357013379057348645e-02, + 4.97687799461593236017e-02, -3.65315727442169155270e-02, + 1.62858201153657823623e-02 }; + const double one = 1.0, huge = 1.0e300; + double w, s1, s2, z; + int ix, hx, id; + hx = Hi(x); + ix = hx & 0x7FFFFFFF; + if (ix >= 0x44100000) + { + uint low = Lo(x); + if (ix > 0x7FF00000 || (ix == 0x7FF00000 && (low != 0))) return x + x; + if (hx > 0) return atanhi[3] + atanlo[3]; + else return -atanhi[3] - atanlo[3]; + } + if (ix < 0x3FDC0000) + { + if (ix < 0x3E400000) { if (huge + x > one) return x; } + id = -1; + } + else + { + x = Math.Abs(x); + if (ix < 0x3FF30000) + { + if (ix < 0x3FE60000) { id = 0; x = (2.0 * x - one) / (2.0 + x); } + else { id = 1; x = (x - one) / (x + one); } + } + else + { + if (ix < 0x40038000) { id = 2; x = (x - 1.5) / (one + 1.5 * x); } + else { id = 3; x = -1.0 / x; } + } + } + z = x * x; + w = z * z; + s1 = z * (aT[0] + w * (aT[2] + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10]))))); + s2 = w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9])))); + if (id < 0) return x - x * (s1 + s2); + z = atanhi[id] - ((x * (s1 + s2) - atanlo[id]) - x); + return (hx < 0) ? -z : z; + } + } + + /* ---- fdlibm e_atan2 ---- */ + public static double Atan2(double y, double x) + { + unchecked + { + const double zero = 0.0, + pi_o_4 = 7.8539816339744827900E-01, + pi_o_2 = 1.5707963267948965580E+00, + pi = 3.1415926535897931160E+00; + const double tiny = 1.0e-300; + const double pi_lo = 1.2246467991473531772E-16; + double z; + int k, m, hx, hy, ix, iy; + uint lx, ly; + hx = Hi(x); lx = Lo(x); + ix = hx & 0x7FFFFFFF; + hy = Hi(y); ly = Lo(y); + iy = hy & 0x7FFFFFFF; + if (((ix | (int)((lx | (uint)(-(int)lx)) >> 31)) > 0x7FF00000) || + ((iy | (int)((ly | (uint)(-(int)ly)) >> 31)) > 0x7FF00000)) + return x + y; + if ((uint)(hx - 0x3FF00000) == 0 && lx == 0) return Atan(y); + m = ((hy >> 31) & 1) | ((hx >> 30) & 2); + if (((uint)iy | ly) == 0) + { + switch (m) + { + case 0: + case 1: return y; + case 2: return pi + tiny; + default: return -pi - tiny; + } + } + if (((uint)ix | lx) == 0) return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; + if (ix == 0x7FF00000) + { + if (iy == 0x7FF00000) + { + switch (m) + { + case 0: return pi_o_4 + tiny; + case 1: return -pi_o_4 - tiny; + case 2: return 3.0 * pi_o_4 + tiny; + default: return -3.0 * pi_o_4 - tiny; + } + } + else + { + switch (m) + { + case 0: return zero; + case 1: return -zero; + case 2: return pi + tiny; + default: return -pi - tiny; + } + } + } + if (iy == 0x7FF00000) return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; + k = (iy - ix) >> 20; + if (k > 60) { z = pi_o_2 + 0.5 * pi_lo; m &= 1; } + else if (hx < 0 && k < -60) z = 0.0; + else z = Atan(Math.Abs(y / x)); + switch (m) + { + case 0: return z; + case 1: return -z; + case 2: return pi - (z - pi_lo); + default: return (z - pi_lo) - pi; + } + } + } + + /* ---- __ieee754_rem_pio2 (small/medium paths; huge args unsupported) ---- */ + private static int RemPio2(double x, double[] y) + { + unchecked + { + int[] npio2_hw = { + 0x3FF921FB, 0x400921FB, 0x4012D97C, 0x401921FB, 0x401F6A7A, 0x4022D97C, + 0x4025FDBB, 0x402921FB, 0x402C463A, 0x402F6A7A, 0x4031475C, 0x4032D97C, + 0x40346B9C, 0x4035FDBB, 0x40378FDB, 0x403921FB, 0x403AB41B, 0x403C463A, + 0x403DD85A, 0x403F6A7A, 0x40407E4C, 0x4041475C, 0x4042106C, 0x4042D97C, + 0x4043A28C, 0x40446B9C, 0x404534AC, 0x4045FDBB, 0x4046C6CB, 0x40478FDB, + 0x404858EB, 0x404921FB }; + const double + half = 5.00000000000000000000e-01, + invpio2 = 6.36619772367581382433e-01, + pio2_1 = 1.57079632673412561417e+00, + pio2_1t = 6.07710050650619224932e-11, + pio2_2 = 6.07710050630396597660e-11, + pio2_2t = 2.02226624879595063154e-21, + pio2_3 = 2.02226624871116645580e-21, + pio2_3t = 8.47842766036889956997e-32; + double z = 0, w, t, r, fn; + int i, j, n, ix, hx; + hx = Hi(x); + ix = hx & 0x7FFFFFFF; + if (ix <= 0x3FE921FB) { y[0] = x; y[1] = 0; return 0; } + if (ix < 0x4002D97C) + { + if (hx > 0) + { + z = x - pio2_1; + if (ix != 0x3FF921FB) { y[0] = z - pio2_1t; y[1] = (z - y[0]) - pio2_1t; } + else { z -= pio2_2; y[0] = z - pio2_2t; y[1] = (z - y[0]) - pio2_2t; } + return 1; + } + else + { + z = x + pio2_1; + if (ix != 0x3FF921FB) { y[0] = z + pio2_1t; y[1] = (z - y[0]) + pio2_1t; } + else { z += pio2_2; y[0] = z + pio2_2t; y[1] = (z - y[0]) + pio2_2t; } + return -1; + } + } + if (ix <= 0x413921FB) + { + t = Math.Abs(x); + n = (int)(t * invpio2 + half); + fn = n; + r = t - fn * pio2_1; + w = fn * pio2_1t; + if (n < 32 && ix != npio2_hw[n - 1]) { y[0] = r - w; } + else + { + uint high; + j = ix >> 20; + y[0] = r - w; + high = (uint)(Bits(y[0]) >> 32); + i = j - ((int)(high >> 20) & 0x7FF); + if (i > 16) + { + t = r; w = fn * pio2_2; r = t - w; + w = fn * pio2_2t - ((t - r) - w); + y[0] = r - w; + high = (uint)(Bits(y[0]) >> 32); + i = j - ((int)(high >> 20) & 0x7FF); + if (i > 49) + { + t = r; w = fn * pio2_3; r = t - w; + w = fn * pio2_3t - ((t - r) - w); + y[0] = r - w; + } + } + } + y[1] = (r - y[0]) - w; + if (hx < 0) { y[0] = -y[0]; y[1] = -y[1]; return -n; } + return n; + } + if (ix >= 0x7FF00000) { y[0] = y[1] = x - x; return 0; } + throw new NotSupportedException("huge-arg rem_pio2 path not needed by reader"); + } + } + + private static double KernelSin(double x, double y, int iy) + { + unchecked + { + const double + half = 5.00000000000000000000e-01, + S1 = -1.66666666666666324348e-01, + S2 = 8.33333333332248946124e-03, + S3 = -1.98412698298579493134e-04, + S4 = 2.75573137070700676789e-06, + S5 = -2.50507602534068634195e-08, + S6 = 1.58969099521155010221e-10; + double z, r, v; + int ix; + ix = Hi(x); + ix &= 0x7FFFFFFF; + if (ix < 0x3E400000) { if ((int)x == 0) return x; } + z = x * x; + v = z * x; + r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))); + if (iy == 0) return x + v * (S1 + z * r); + return x - ((z * (half * y - v * r) - y) - v * S1); + } + } + + private static double KernelCos(double x, double y) + { + unchecked + { + const double + one = 1.00000000000000000000e+00, + C1 = 4.16666666666666019037e-02, + C2 = -1.38888888888741095749e-03, + C3 = 2.48015872894767294178e-05, + C4 = -2.75573143513906633035e-07, + C5 = 2.08757232129817482790e-09, + C6 = -1.13596475577881948265e-11; + double a, iz, z, r, qx; + int ix; + ix = Hi(x); + ix &= 0x7FFFFFFF; + if (ix < 0x3E400000) { if ((int)x == 0) return one; } + z = x * x; + r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))))); + if (ix < 0x3FD33333) return one - (0.5 * z - (z * r - x * y)); + if (ix > 0x3FE90000) qx = 0.28125; + else qx = Insert(ix - 0x00200000, 0); + iz = 0.5 * z - qx; + a = one - qx; + return a - (iz - (z * r - x * y)); + } + } + + public static double Cos(double x) + { + unchecked + { + double[] y = new double[2]; + const double z = 0.0; + int n, ix; + ix = Hi(x); + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) return KernelCos(x, z); + else if (ix >= 0x7FF00000) return x - x; + if (ix > 0x413921FB) return Math.Cos(x); /* huge-arg: never in reader */ + n = RemPio2(x, y); + switch (n & 3) + { + case 0: return KernelCos(y[0], y[1]); + case 1: return -KernelSin(y[0], y[1], 1); + case 2: return -KernelCos(y[0], y[1]); + default: return KernelSin(y[0], y[1], 1); + } + } + } + + public static double Sin(double x) + { + unchecked + { + double[] y = new double[2]; + const double z = 0.0; + int n, ix; + ix = Hi(x); + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) return KernelSin(x, z, 0); + else if (ix >= 0x7FF00000) return x - x; + if (ix > 0x413921FB) return Math.Sin(x); /* huge-arg: never in reader */ + n = RemPio2(x, y); + switch (n & 3) + { + case 0: return KernelSin(y[0], y[1], 1); + case 1: return KernelCos(y[0], y[1]); + case 2: return -KernelSin(y[0], y[1], 1); + default: return -KernelCos(y[0], y[1]); + } + } + } + + /* ---- fdlibm e_exp ---- */ + public static double Exp(double x) + { + unchecked + { + double[] halF = { 0.5, -0.5 }; + double[] ln2HI = { 6.93147180369123816490e-01, -6.93147180369123816490e-01 }; + double[] ln2LO = { 1.90821492927058770002e-10, -1.90821492927058770002e-10 }; + const double + one = 1.0, + o_threshold = 7.09782712893383973096e+02, + u_threshold = -7.45133219101941108420e+02, + invln2 = 1.44269504088896338700e+00, + P1 = 1.66666666666666019037e-01, + P2 = -2.77777777770155933842e-03, + P3 = 6.61375632143793436117e-05, + P4 = -1.65339022054652515390e-06, + P5 = 4.13813679705723846039e-08, + E = 2.718281828459045; + const double huge = 1.0e+300, + twom1000 = 9.33263618503218878990e-302, + two1023 = 8.988465674311579539e307; + double y, hi = 0.0, lo = 0.0, c, t, twopk; + int k = 0, xsb; + uint hx; + hx = (uint)(Bits(x) >> 32); + xsb = (int)((hx >> 31) & 1); + hx &= 0x7FFFFFFF; + if (hx >= 0x40862E42) + { + if (hx >= 0x7FF00000) + { + uint lx = Lo(x); + if (((hx & 0xFFFFF) | lx) != 0) return x + x; + else return (xsb == 0) ? x : 0.0; + } + if (x > o_threshold) return huge * huge; + if (x < u_threshold) return twom1000 * twom1000; + } + if (hx > 0x3FD62E42) + { + if (hx < 0x3FF0A2B2) + { + if (x == 1.0) return E; + hi = x - ln2HI[xsb]; + lo = ln2LO[xsb]; + k = 1 - xsb - xsb; + } + else + { + k = (int)(invln2 * x + halF[xsb]); + t = k; + hi = x - t * ln2HI[0]; + lo = t * ln2LO[0]; + } + x = hi - lo; + } + else if (hx < 0x3E300000) + { + if (huge + x > one) return one + x; + } + else + { + k = 0; + } + t = x * x; + if (k >= -1021) twopk = Insert(0x3FF00000 + (int)((uint)k << 20), 0); + else twopk = Insert(0x3FF00000 + (int)((uint)(k + 1000) << 20), 0); + c = x - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + if (k == 0) return one - ((x * c) / (c - 2.0) - x); + y = one - ((lo - (x * c) / (2.0 - c)) - hi); + if (k >= -1021) + { + if (k == 1024) return y * 2.0 * two1023; + return y * twopk; + } + return y * twopk * twom1000; + } + } + + /* ---- fdlibm e_log ---- */ + public static double Log(double x) + { + unchecked + { + const double + ln2_hi = 6.93147180369123816490e-01, + ln2_lo = 1.90821492927058770002e-10, + two54 = 1.80143985094819840000e+16, + Lg1 = 6.666666666666735130e-01, + Lg2 = 3.999999999940941908e-01, + Lg3 = 2.857142874366239149e-01, + Lg4 = 2.222219843214978396e-01, + Lg5 = 1.818357216161805012e-01, + Lg6 = 1.531383769920937332e-01, + Lg7 = 1.479819860511658591e-01; + const double zero = 0.0; + double hfsq, f, s, z, R, w, t1, t2, dk; + int k, hx, i, j; + uint lx; + hx = Hi(x); lx = Lo(x); + k = 0; + if (hx < 0x00100000) + { + if (((hx & 0x7FFFFFFF) | (int)lx) == 0) return -1.0 / 0.0; + if (hx < 0) return 0.0 / 0.0; + k -= 54; + x *= two54; + hx = Hi(x); + } + if (hx >= 0x7FF00000) return x + x; + k += (hx >> 20) - 1023; + hx &= 0x000FFFFF; + i = (hx + 0x95F64) & 0x100000; + x = WithHi(x, hx | (i ^ 0x3FF00000)); + k += (i >> 20); + f = x - 1.0; + if ((0x000FFFFF & (2 + hx)) < 3) + { + if (f == zero) + { + if (k == 0) return zero; + dk = k; + return dk * ln2_hi + dk * ln2_lo; + } + R = f * f * (0.5 - 0.33333333333333333 * f); + if (k == 0) return f - R; + dk = k; + return dk * ln2_hi - ((R - dk * ln2_lo) - f); + } + s = f / (2.0 + f); + dk = k; + z = s * s; + i = hx - 0x6147A; + w = z * z; + j = 0x6B851 - hx; + t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + i |= j; + R = t2 + t1; + if (i > 0) + { + hfsq = 0.5 * f * f; + if (k == 0) return f - (hfsq - s * (hfsq + R)); + return dk * ln2_hi - ((hfsq - (s * (hfsq + R) + dk * ln2_lo)) - f); + } + else + { + if (k == 0) return f - s * (f - R); + return dk * ln2_hi - ((s * (f - R) - dk * ln2_lo) - f); + } + } + } + + /* ---- Math.hypot(x,y): V8 torque algorithm (max-scaled) ---- */ + public static double Hypot2(double x, double y) + { + x = Math.Abs(x); y = Math.Abs(y); + double max = x > y ? x : y; + if (max == 0) return 0; + if (double.IsInfinity(max)) return max; + double sum = 0; + if (x != 0) { double v = x / max; sum += v * v; } + if (y != 0) { double v = y / max; sum += v * v; } + return max * Math.Sqrt(sum); + } + } +} diff --git a/ports/csharp/reader/PrismMix.cs b/ports/csharp/reader/PrismMix.cs new file mode 100644 index 0000000..4930cfb --- /dev/null +++ b/ports/csharp/reader/PrismMix.cs @@ -0,0 +1,759 @@ +// PrismMix.cs - palette-mixing layer: mixFit, mixRecover, mixAlternate (returns H, the worker's +// OffscreenCanvas-less fallback), mixDirect. Transliterated from ports/c/reader/prism_mix.c. +using System; +using System.Collections.Generic; + +namespace Prism.Reader +{ + internal struct PrismMixCand { public int Size; public double[] H; public double Score; } + + internal sealed class PrismMixResult + { + public PrismPayload Payload; + public int Quality; + public double[] H = new double[8]; + public double Radius, Sigma; + } + + internal static class Mix + { + private static readonly string[] MixHex = { "#1B1B1B", "#2E5BFF", "#00B8D9", "#2DB35A", "#F5C518", "#F77F00", "#D7263D", "#B5179E", "#FFFFFF" }; + private static int HexByte(string h, int off) + { + int v = 0; + for (int i = 0; i < 2; i++) + { + char c = h[off + i]; int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; + else d = c - 'A' + 10; + v = v * 16 + d; + } + return v; + } + private static double MjRound(double x) => Math.Floor(x + 0.5); + + private static double[,] MixOffsets() + { + double[,] v = new double[7, 2]; + for (int k = 0; k < 6; k++) + { + v[k + 1, 0] = 0.45 * JsMath.Cos((double)k * Math.PI / 3); + v[k + 1, 1] = 0.45 * JsMath.Sin((double)k * Math.PI / 3); + } + return v; + } + + public static double[] MixFit(PrismFrame A, double[] H, PrismLayout L) + { + byte[] d = A.Image; + int W = A.W, Ht = A.H; + double[] bas = (double[])H.Clone(); + double[] pal = new double[9]; + for (int s = 0; s < 9; s++) + { + int r = HexByte(MixHex[s], 1), g = HexByte(MixHex[s], 3), b = HexByte(MixHex[s], 5); + pal[s] = 0.299 * r + 0.587 * g + 0.114 * b; + } + double[,] v = MixOffsets(); + int nKnown = L.Known.Length; + double[] Cand(double[] p) + { + double[] h = (double[])bas.Clone(); + h[2] += p[0]; h[5] += p[1]; + h[0] *= 1 + p[2]; h[4] *= 1 + p[3]; + h[1] += p[4]; h[3] += p[5]; + return h; + } + double Lum(double x_, double y_) + { + int xi = (int)Math.Floor(x_), yi = (int)Math.Floor(y_); + double fx = x_ - xi, fy = y_ - yi; + if (xi < 0 || yi < 0 || xi >= W - 1 || yi >= Ht - 1) return 255; + double val = 0; + for (int dy = 0; dy < 2; dy++) for (int dx = 0; dx < 2; dx++) + { + int q = ((yi + dy) * W + xi + dx) * 4; + val += (0.299 * d[q] + 0.587 * d[q + 1] + 0.114 * d[q + 2]) * (dx != 0 ? fx : 1 - fx) * (dy != 0 ? fy : 1 - fy); + } + return val; + } + PrismMap mm = new PrismMap(); + double Loss(double[] p) + { + double[] h = Cand(p); + Array.Copy(h, mm.H, 8); + double sum = 0; + for (int ki = 0; ki < nKnown; ki++) + { + PrismCell c = L.Known[ki]; + for (int oi = 0; oi < 7; oi++) + { + Image.MapPoint(mm, c.X + v[oi, 0], c.Y + v[oi, 1], out double qx, out double qy); + double lv = Lum(qx, qy); + double err = lv - pal[c.Symbol]; + sum += err * err < 2500 ? err * err : 2500; + } + } + return sum; + } + double[] pp = new double[6]; + double[] sc = { 1, 1, 1 / L.W, 1 / L.H, 1 / L.H, 1 / L.W }; + double best = Loss(pp); + double[] steps = { 0.8, 0.4, 0.2, 0.1, 0.05 }; + for (int si = 0; si < 5; si++) + for (int it = 0; it < 4; it++) + { + bool changed = false; + for (int k = 0; k < 6; k++) + { + double bk = pp[k]; + for (int sg = 0; sg < 2; sg++) + { + double[] q = (double[])pp.Clone(); + q[k] += (sg != 0 ? 1.0 : -1.0) * steps[si] * sc[k]; + double ls = Loss(q); + if (ls < best) { best = ls; bk = q[k]; changed = true; } + } + pp[k] = bk; + } + if (!changed) break; + } + return Cand(pp); + } + + private sealed class MixRow + { + public List N = new List(); public List Wt = new List(); + public int Count => N.Count; + public void Add(int n, double wt) + { + for (int i = 0; i < N.Count; i++) if (N[i] == n) { Wt[i] += wt; return; } + N.Add(n); Wt.Add(wt); + } + } + private sealed class Col { public List R = new List(); public List Wt = new List(); } + + private static bool mixSymbolsValid; + + public static PrismPayload MixRecover(PrismFrame A, double[] h, PrismLayout L, int[] symbolsOut) + { + byte[] d = A.Image; + int W = A.W, H = A.H; + double pitch = JsMath.Hypot2(h[0], h[3]) * Math.Sqrt(3); + if (pitch < 1 || pitch > 4.5) return null; + int N = L.Cells.Length; + double[][] pal = new double[9][]; + for (int s = 0; s < 9; s++) + { + double pr = HexByte(MixHex[s], 1), pg = HexByte(MixHex[s], 3), pb = HexByte(MixHex[s], 5); + pal[s] = new[] { 0.299 * pr + 0.587 * pg + 0.114 * pb, 128 - 0.168736 * pr - 0.331264 * pg + 0.5 * pb, 128 + 0.5 * pr - 0.418688 * pg - 0.081312 * pb }; + } + PrismMap mm = new PrismMap(); Array.Copy(h, mm.H, 8); + double minx = 1e30, miny = 1e30, maxx = -1e30, maxy = -1e30; + for (int i = 0; i < N; i++) + { + Image.MapPoint(mm, L.Cells[i].X, L.Cells[i].Y, out double px, out double py); + if (px < minx) minx = px; if (px > maxx) maxx = px; + if (py < miny) miny = py; if (py > maxy) maxy = py; + } + int x0 = (int)Cm.Fmax(0, Math.Floor(minx - 6)), y0 = (int)Cm.Fmax(0, Math.Floor(miny - 6)); + int x1 = (int)Cm.Fmin(W, Math.Ceiling(maxx + 8)), y1 = (int)Cm.Fmin(H, Math.Ceiling(maxy + 8)); + x0 -= x0 % 2; y0 -= y0 % 2; x1 -= x1 % 2; y1 -= y1 % 2; + int w = x1 - x0, ht = y1 - y0; + long Mq = (long)w * ht; + if (Mq <= 0 || Mq > 50000) return null; + int M = (int)Mq; + double a = h[0], b = h[1], c = h[2], dd = h[3], ee = h[4], f = h[5], g = h[6], hh = h[7]; + double[] inv = { + ee - f * hh, c * hh - b, b * f - c * ee, + f * g - dd, a - c * g, c * dd - a * f, + dd * hh - ee * g, b * dd - a * hh, a * ee - b * dd, + }; + double[][] obs = { new double[M], new double[M], new double[M] }; + MixRow[] rows = new MixRow[M]; + for (int i = 0; i < M; i++) rows[i] = new MixRow(); + double S3 = Math.Sqrt(3); + int[,] tap = { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }; + for (int y = 0; y < ht; y++) + for (int x = 0; x < w; x++) + { + int ix = x + x0, iy = y + y0; + int k = y * w + x; + int q = (iy * W + ix) * 4; + double r = d[q], gg = d[q + 1], bb = d[q + 2]; + obs[0][k] = 0.299 * r + 0.587 * gg + 0.114 * bb; + obs[1][k] = 128 - 0.168736 * r - 0.331264 * gg + 0.5 * bb; + obs[2][k] = 128 + 0.5 * r - 0.418688 * gg - 0.081312 * bb; + double z = inv[6] * ix + inv[7] * iy + inv[8]; + double u = (inv[0] * ix + inv[1] * iy + inv[2]) / z; + double vv = (inv[3] * ix + inv[4] * iy + inv[5]) / z; + double tx = (u + 3 * S3) * 10, ty = (vv + 3 * S3) * 10; + int ux = (int)Math.Floor(tx), vy = (int)Math.Floor(ty); + double fx = tx - ux, fy = ty - vy; + MixRow row = rows[k]; + for (int t = 0; t < 4; t++) + { + int dx = tap[t, 0], dy = tap[t, 1]; + double wt = (dx != 0 ? fx : 1 - fx) * (dy != 0 ? fy : 1 - fy); + for (int sy = 0; sy < 4; sy++) + for (int sx = 0; sx < 4; sx++) + { + double uu = (ux + dx + (sx + 0.5) / 4) / 10 - 3 * S3; + double v2 = (vy + dy + (sy + 0.5) / 4) / 10 - 3 * S3; + int jr = (int)MjRound((v2 - 1) / 1.5); + int n = N; + for (int j = jr - 1; j <= jr + 1; j++) + { + int ii = (int)MjRound(uu / S3 - 0.5 - 0.5 * (j & 1)); + if (ii < 0 || ii >= L.C || j < 0 || j >= L.R) continue; + double hx = Math.Abs(uu - S3 * (ii + 0.5 + 0.5 * (j & 1))); + double hy = Math.Abs(v2 - 1 - 1.5 * j); + if (hx <= (1.03 * S3) / 2 && hy <= 1.03 - hx / S3) + n = (int)Cm.Fmax(n == N ? -1 : n, (double)(j * L.C + ii)); + } + row.Add(n, wt / 16); + } + } + } + MixRow[] chrom = new MixRow[M]; + for (int i = 0; i < M; i++) chrom[i] = new MixRow(); + for (int y = 0; y < ht; y++) + for (int x = 0; x < w; x++) + { + MixRow row = chrom[y * w + x]; + for (int ky_ = 0; ky_ < 2; ky_++) + { + int ky = ky_ == 0 ? y >> 1 : (y >> 1) + (y % 2 != 0 ? 1 : -1); + int kymax = (ht >> 1) - 1; + if (ky < 0) ky = 0; if (ky > kymax) ky = kymax; + double wy = ky_ == 0 ? 0.75 : 0.25; + for (int kx_ = 0; kx_ < 2; kx_++) + { + int kx = kx_ == 0 ? x >> 1 : (x >> 1) + (x % 2 != 0 ? 1 : -1); + int kxmax = (w >> 1) - 1; + if (kx < 0) kx = 0; if (kx > kxmax) kx = kxmax; + double wx = kx_ == 0 ? 0.75 : 0.25; + for (int oy = 0; oy < 2; oy++) + for (int ox = 0; ox < 2; ox++) + { + MixRow src = rows[(ky * 2 + oy) * w + kx * 2 + ox]; + for (int i = 0; i < src.Count; i++) + row.Add(src.N[i], src.Wt[i] * wy * wx * 0.25); + } + } + } + } + bool[] known = new bool[N + 1]; + int[] symbols = new int[N + 1]; + for (int i = 0; i < N; i++) + { + int rl = L.Cells[i].Role; + known[i] = (rl == (int)Role.Ring || rl == (int)Role.Pilot || rl == (int)Role.Gap); + symbols[i] = known[i] ? L.Cells[i].Symbol : 0; + } + known[N] = true; symbols[N] = 8; + List unknownL = new List(); + for (int k = 0; k < N; k++) if (!known[k]) unknownL.Add(k); + int[] unknown = unknownL.ToArray(); int nUnknown = unknown.Length; + double[][] X = new double[N + 1][]; + for (int k = 0; k <= N; k++) X[k] = (double[])pal[symbols[k]].Clone(); + MixRow[][] mats = { rows, chrom, chrom }; + Col[][] links = new Col[3][]; + for (int ch = 0; ch < 3; ch++) + { + MixRow[] mat = mats[ch]; + Col[] col = new Col[N + 1]; + for (int n = 0; n <= N; n++) col[n] = new Col(); + double[] rhs = (double[])obs[ch].Clone(); + for (int r = 0; r < M; r++) + for (int i = 0; i < mat[r].Count; i++) + { + int n = mat[r].N[i]; double wt = mat[r].Wt[i]; + col[n].R.Add(r); col[n].Wt.Add(wt); + if (known[n]) rhs[r] -= wt * X[n][ch]; + } + double[] vecOut = new double[N + 1]; + double[] rr = new double[N + 1]; + for (int ui = 0; ui < nUnknown; ui++) + { + int n = unknown[ui]; + for (int i = 0; i < col[n].R.Count; i++) rr[n] += col[n].Wt[i] * rhs[col[n].R[i]]; + } + double[] p = (double[])rr.Clone(); + double[] sol = new double[N + 1]; + double rs = 0; + for (int ui = 0; ui < nUnknown; ui++) rs += rr[unknown[ui]] * rr[unknown[ui]]; + for (int it = 0; it < 150 && rs > 1e-8; it++) + { + Array.Clear(vecOut, 0, N + 1); + for (int r = 0; r < M; r++) + { + MixRow mr = mat[r]; + double v = 0; + for (int i = 0; i < mr.Count; i++) if (!known[mr.N[i]]) v += mr.Wt[i] * p[mr.N[i]]; + for (int i = 0; i < mr.Count; i++) if (!known[mr.N[i]]) vecOut[mr.N[i]] += mr.Wt[i] * v; + } + for (int ui = 0; ui < nUnknown; ui++) vecOut[unknown[ui]] += 0.0625 * p[unknown[ui]]; + double den = 0; + for (int ui = 0; ui < nUnknown; ui++) den += p[unknown[ui]] * vecOut[unknown[ui]]; + if (den <= 0) break; + double alpha = rs / den; + for (int ui = 0; ui < nUnknown; ui++) + { + int n = unknown[ui]; + sol[n] += alpha * p[n]; + rr[n] -= alpha * vecOut[n]; + } + double ns = 0; + for (int ui = 0; ui < nUnknown; ui++) ns += rr[unknown[ui]] * rr[unknown[ui]]; + double beta = ns / rs; + for (int ui = 0; ui < nUnknown; ui++) { int n = unknown[ui]; p[n] = rr[n] + beta * p[n]; } + rs = ns; + } + for (int ui = 0; ui < nUnknown; ui++) X[unknown[ui]][ch] = sol[unknown[ui]]; + links[ch] = col; + } + for (int ui = 0; ui < nUnknown; ui++) + { + int n = unknown[ui]; + int bs = 0; double bc = double.PositiveInfinity; + for (int s = 0; s < 9; s++) + { + int role = L.Cells[n].Role; + if ((role == (int)Role.Data && s == 8) || (role == (int)Role.Header && s > 0 && s < 8)) continue; + double cost = 0; + for (int ch = 0; ch < 3; ch++) + { + double dlt = X[n][ch] - pal[s][ch]; + cost += (ch == 0 ? 8 : 1) * dlt * dlt; + } + if (cost < bc) { bc = cost; bs = s; } + } + symbols[n] = bs; + X[n] = (double[])pal[bs].Clone(); + } + double[][] resid = new double[3][]; + for (int ch = 0; ch < 3; ch++) + { + resid[ch] = new double[M]; + MixRow[] mat = mats[ch]; + for (int r = 0; r < M; r++) + { + double s = 0; + for (int i = 0; i < mat[r].Count; i++) s += mat[r].Wt[i] * X[mat[r].N[i]][ch]; + resid[ch][r] = obs[ch][r] - s; + } + } + void Costs(int n_, double[] outc) + { + for (int s_ = 0; s_ < 9; s_++) outc[s_] = 0; + for (int ch_ = 0; ch_ < 3; ch_++) + { + double sq_ = 0, rv_ = 0; + Col cl = links[ch_][n_]; + for (int i_ = 0; i_ < cl.R.Count; i_++) + { + double wt_ = cl.Wt[i_]; + sq_ += wt_ * wt_; + rv_ += wt_ * resid[ch_][cl.R[i_]]; + } + for (int s_ = 0; s_ < 9; s_++) + { + double dlt_ = pal[s_][ch_] - X[n_][ch_]; + outc[s_] += (ch_ == 0 ? 8 : 1) * (sq_ * dlt_ * dlt_ - 2 * rv_ * dlt_); + } + } + if (L.Cells[n_].Role == (int)Role.Data) outc[8] = 1e20; + else if (L.Cells[n_].Role == (int)Role.Header) for (int s_ = 1; s_ < 8; s_++) outc[s_] = 1e20; + } + double[] cs = new double[9]; + for (int it = 0; it < 12; it++) + { + int changed = 0; + for (int ui = 0; ui < nUnknown; ui++) + { + int n = unknown[ui]; + Costs(n, cs); + int bs = 0; double mn = cs[0]; + for (int s = 1; s < 9; s++) if (cs[s] < mn) { mn = cs[s]; bs = s; } + if (bs == symbols[n]) continue; + changed++; + for (int ch = 0; ch < 3; ch++) + { + double dlt = pal[bs][ch] - X[n][ch]; + Col cl = links[ch][n]; + for (int i = 0; i < cl.R.Count; i++) resid[ch][cl.R[i]] -= cl.Wt[i] * dlt; + } + symbols[n] = bs; + X[n] = (double[])pal[bs].Clone(); + } + if (changed == 0) break; + } + if (symbolsOut != null) Array.Copy(symbols, symbolsOut, N + 1); + mixSymbolsValid = true; + float[] hb = new float[24]; + double[][] csAll = new double[N][]; + for (int n = 0; n < N; n++) + { + if (known[n]) continue; + csAll[n] = new double[9]; + Costs(n, csAll[n]); + } + for (int i = 0; i < L.Headers.Length; i++) + { + PrismCell cc = L.Headers[i]; + if (known[cc.Index]) continue; + hb[cc.Header % 24] = (float)(hb[cc.Header % 24] + (csAll[cc.Index][0] - csAll[cc.Index][8])); + } + if (Classify.HeaderDecode24(hb, out PrismHeader header, out _) != 0) return null; + if (header.Size != L.Size || header.Mode != 0) return null; + double[] temps = { 80, 300, 1200 }; + for (int ti = 0; ti < 3; ti++) + { + int nstream = L.Data.Length * 3; + float[] stream = new float[nstream]; + int sp = 0; + double[] pp = new double[9]; + for (int i = 0; i < L.Data.Length; i++) + { + PrismCell cc = L.Data[i]; + double[] dd2 = csAll[cc.Index]; + double mn = dd2[0]; + for (int s = 1; s < 9; s++) if (dd2[s] < mn) mn = dd2[s]; + for (int s = 0; s < 9; s++) pp[s] = JsMath.Exp(-(dd2[s] - mn) / temps[ti]); + for (int bb2 = 0; bb2 < 3; bb2++) + { + double n0 = 1e-12, n1 = 1e-12; + for (int s = 0; s < 8; s++) + if ((((s ^ (s >> 1)) >> (2 - bb2)) & 1) != 0) n1 += pp[s]; else n0 += pp[s]; + double lv = JsMath.Log(n0 / n1); + if (lv < -12) lv = -12; else if (lv > 12) lv = 12; + stream[sp++] = (float)lv; + } + } + PrismPayload outP = new PrismPayload(); + PrismErr perr = new PrismErr(); + if (Decode.DecodeStream(header, stream, outP, perr) == 0) + { + outP.Variant = "palette mixing"; + return outP; + } + } + return null; + } + + /* Software reproduction of the browser canvas rasterization used by + * mixAlternate (validated vs captured browser output: 0 diff in fill + * regions, ~4 luma on AA edge pixels). See the C port's prism_mix.c. */ + /* Fast coverage for the convex hexagon: corner tests against the 6 edge + * half-planes (CCW vertices). All-inside -> 1 and all-outside of one + * edge -> 0, both numerically identical to running the clip; only edge + * pixels pay for Sutherland-Hodgman. */ + private static double HexClipArea(double[] vx, double[] vy, int n, int px, int py) + { + int nin = 0; + for (int e = 0; e < n; e++) + { + double ex = vx[(e + 1) % n] - vx[e], ey = vy[(e + 1) % n] - vy[e]; + bool anyIn = false; + for (int cnr = 0; cnr < 4; cnr++) + { + double cxp = px + (cnr & 1), cyp = py + (cnr >> 1); + if (ex * (cyp - vy[e]) - ey * (cxp - vx[e]) >= 0) { anyIn = true; if (e == 0) nin++; } + } + if (!anyIn) return 0.0; + } + if (nin == 4) + { + /* all corners inside edge 0; check remaining edges for full containment */ + bool all = true; + for (int e = 1; e < n && all; e++) + { + double ex = vx[(e + 1) % n] - vx[e], ey = vy[(e + 1) % n] - vy[e]; + for (int cnr = 0; cnr < 4; cnr++) + { + double cxp = px + (cnr & 1), cyp = py + (cnr >> 1); + if (ex * (cyp - vy[e]) - ey * (cxp - vx[e]) < 0) { all = false; break; } + } + } + if (all) return 1.0; + } + double[] cx = new double[16], cy = new double[16]; + int cn = n; + for (int i = 0; i < n; i++) { cx[i] = vx[i]; cy[i] = vy[i]; } + double[] nx_ = { 1, -1, 0, 0 }, ny_ = { 0, 0, 1, -1 }; + double[] d_ = { px, -(double)(px + 1), py, -(double)(py + 1) }; + for (int h = 0; h < 4 && cn > 0; h++) + { + double nx = nx_[h], ny = ny_[h], dd = d_[h]; + double[] ox = new double[16], oy = new double[16]; + int on = 0; + for (int i = 0; i < cn; i++) + { + double ax = cx[i], ay = cy[i], bx = cx[(i + 1) % cn], by = cy[(i + 1) % cn]; + double fa = nx * ax + ny * ay - dd, fb = nx * bx + ny * by - dd; + if (fa >= 0) { ox[on] = ax; oy[on] = ay; on++; } + if ((fa >= 0) != (fb >= 0)) + { + double t = fa / (fa - fb); + ox[on] = ax + t * (bx - ax); oy[on] = ay + t * (by - ay); on++; + } + } + for (int i = 0; i < on; i++) { cx[i] = ox[i]; cy[i] = oy[i]; } + cn = on; + } + if (cn == 0) return 0.0; + double a = 0.0; + for (int i = 0; i < cn; i++) + { + double ax = cx[i], ay = cy[i], bx = cx[(i + 1) % cn], by = cy[(i + 1) % cn]; + a += ax * by - bx * ay; + } + return Math.Abs(a) / 2; + } + + private static void MaltCand(double[] baseH, double[] p, double[] h) + { + Array.Copy(baseH, h, 8); + h[2] += p[0]; h[5] += p[1]; h[0] *= 1 + p[2]; h[4] *= 1 + p[3]; + } + + private static double MaltLoss(float[] yy, int yw, int yh, int x0, int x1, int y0, int y1, + PrismFrame A, double[] baseH, double[] p, double Q) + { + double[] h = new double[8]; MaltCand(baseH, p, h); + double a = h[0], b = h[1], c = h[2], d0 = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + double i0 = e - f * hh, i1 = c * hh - b, i2 = b * f - c * e, + i3 = f * g - d0, i4 = a - c * g, i5 = c * d0 - a * f, + i6 = d0 * hh - e * g, i7 = b * d0 - a * hh, i8 = a * e - b * d0; + byte[] d = A.Image; int AW = A.W; + double sum = 0; long n = 0; + for (int y = y0; y <= y1; y++) for (int x = x0; x <= x1; x++) + { + double z = i6 * x + i7 * y + i8; + double u = ((i0 * x + i1 * y + i2) / z + Q) * 10; + double v = ((i3 * x + i4 * y + i5) / z + Q) * 10; + int ux = (int)Math.Floor(u), vy = (int)Math.Floor(v); + double fx = u - ux, fy = v - vy; + if (ux < 0 || vy < 0 || ux >= yw - 1 || vy >= yh - 1) continue; + long j = (long)vy * yw + ux; + double pred = (yy[j] * (1 - fx) + yy[j + 1] * fx) * (1 - fy) + + (yy[j + yw] * (1 - fx) + yy[j + yw + 1] * fx) * fy; + long k = ((long)y * AW + x) * 4; + double ob = .299 * d[k] + .587 * d[k + 1] + .114 * d[k + 2]; + double df = ob - pred; sum += df * df > 2000 ? 2000 : df * df; n++; + } + return sum / (n > 1 ? n : 1); + } + + public static double[] MixAlternate(PrismFrame A, double[] H, PrismLayout L, int[] symbols) + { + double Q = Foundations.Q; + int W = (int)Math.Ceiling((L.W + 2 * Q) * 10); + int Ht = (int)Math.Ceiling((L.H + 2 * Q) * 10); + const int scale = 4; + int BW = W * scale, BH = Ht * scale; + byte[] big = new byte[(long)BW * BH * 3]; + for (long i = 0; i < big.Length; i++) big[i] = 255; + /* rasterize hexagons in cell order, src-over with per-fill byte rounding */ + foreach (var c in L.Cells) + { + int s = symbols[c.Index]; + if (s == 8) continue; + int pr = HexByte(MixHex[s], 1), pg = HexByte(MixHex[s], 3), pb = HexByte(MixHex[s], 5); + double[] vx = new double[6], vy = new double[6]; + double x0 = 1e300, x1 = -1e300, y0 = 1e300, y1 = -1e300; + for (int k = 0; k < 6; k++) + { + double ang = (30 + 60 * k) * Math.PI / 180; + vx[k] = (c.X + Q + 1.03 * JsMath.Cos(ang)) * 10 * scale; + vy[k] = (c.Y + Q + 1.03 * JsMath.Sin(ang)) * 10 * scale; + if (vx[k] < x0) x0 = vx[k]; if (vx[k] > x1) x1 = vx[k]; + if (vy[k] < y0) y0 = vy[k]; if (vy[k] > y1) y1 = vy[k]; + } + int px0 = Math.Max(0, (int)Math.Floor(x0)), px1 = Math.Min(BW - 1, (int)Math.Ceiling(x1)); + int py0 = Math.Max(0, (int)Math.Floor(y0)), py1 = Math.Min(BH - 1, (int)Math.Ceiling(y1)); + for (int py = py0; py <= py1; py++) for (int px = px0; px <= px1; px++) + { + double cov = HexClipArea(vx, vy, 6, px, py); + if (cov <= 0) continue; + if (cov > 1) cov = 1; + long o = ((long)py * BW + px) * 3; + big[o] = (byte)Math.Floor(pr * cov + big[o] * (1 - cov) + 0.5); + big[o + 1] = (byte)Math.Floor(pg * cov + big[o + 1] * (1 - cov) + 0.5); + big[o + 2] = (byte)Math.Floor(pb * cov + big[o + 2] * (1 - cov) + 0.5); + } + } + /* 4x drawImage downscale: bilinear bytes at (4*dst+1.5), byte-rounded, luma */ + float[] yy = new float[(long)W * Ht]; + for (int dy = 0; dy < Ht; dy++) for (int dx = 0; dx < W; dx++) + { + double u = 4 * dx + 1.5, v = 4 * dy + 1.5; + int x0 = (int)Math.Floor(u), y0 = (int)Math.Floor(v); + double fx = u - x0, fy = v - y0; + long b00 = ((long)y0 * BW + x0) * 3, b01 = ((long)(y0 + 1) * BW + x0) * 3; + int[] o = new int[3]; + for (int ch = 0; ch < 3; ch++) + { + double val = (big[b00 + ch] * (1 - fx) + big[b00 + 3 + ch] * fx) * (1 - fy) + + (big[b01 + ch] * (1 - fx) + big[b01 + 3 + ch] * fx) * fy; + o[ch] = (int)Math.Floor(val + 0.5); + } + yy[(long)dy * W + dx] = (float)(.299 * o[0] + .587 * o[1] + .114 * o[2]); + } + big = null; + /* loss window: P(H, cell) bbox clamped to the image */ + int wx0, wx1, wy0, wy1; + { + double mnx = 1e300, mxx = -1e300, mny = 1e300, mxy = -1e300; + foreach (var c in L.Cells) + { + double o = H[6] * c.X + H[7] * c.Y + 1; + double px = (H[0] * c.X + H[1] * c.Y + H[2]) / o; + double py = (H[3] * c.X + H[4] * c.Y + H[5]) / o; + if (px < mnx) mnx = px; if (px > mxx) mxx = px; + if (py < mny) mny = py; if (py > mxy) mxy = py; + } + wx0 = Math.Max(0, (int)Math.Floor(mnx)); wx1 = Math.Min(A.W - 1, (int)Math.Ceiling(mxx)); + wy0 = Math.Max(0, (int)Math.Floor(mny)); wy1 = Math.Min(A.H - 1, (int)Math.Ceiling(mxy)); + } + /* coordinate descent, exact JS ordering */ + double[] p = { 0, 0, 0, 0 }; + double[] sc = { 1, 1, 1 / L.W, 1 / L.H }; + double best = MaltLoss(yy, W, Ht, wx0, wx1, wy0, wy1, A, H, p, Q); + double[] steps = { .15, .075, .035, .015 }; + for (int si = 0; si < 4; si++) for (int it = 0; it < 3; it++) for (int k = 0; k < 4; k++) + { + double bk = p[k]; + for (int sg = 0; sg < 2; sg++) + { + double sign = sg == 0 ? -1 : 1; + double[] q = (double[])p.Clone(); + q[k] += sign * steps[si] * sc[k]; + double ls = MaltLoss(yy, W, Ht, wx0, wx1, wy0, wy1, A, H, q, Q); + if (ls < best) { best = ls; bk = q[k]; } + } + p[k] = bk; + } + double[] outH = new double[8]; + MaltCand(H, p, outH); + return outH; + } + + public static int LastN; + public static PrismMixCand[] Last = new PrismMixCand[8]; + + public static PrismMixResult MixDirect(byte[] rgba, int W, int H) + { + if ((long)W * H > 800000) return null; + byte[] d = rgba; + byte[] seen = new byte[W * H]; + var blobs = new List<(int x0, int y0, int w, int h, long n)>(); + int[] qq = new int[W * H]; + for (int k = 0; k < W * H; k++) + { + if (seen[k] != 0) continue; + int m3 = Math.Min((int)d[k * 4], (int)d[k * 4 + 1]); + if (d[k * 4 + 2] < m3) m3 = d[k * 4 + 2]; + if (m3 < 232) continue; + int qn = 0; + qq[qn++] = k; + seen[k] = 1; + int x0 = W, y0 = H, x1 = 0, y1 = 0; + int[] ns = new int[4]; + for (int j = 0; j < qn; j++) + { + int p = qq[j], x = p % W, y = p / W; + if (x < x0) x0 = x; if (x > x1) x1 = x; + if (y < y0) y0 = y; if (y > y1) y1 = y; + ns[0] = p - 1; ns[1] = p + 1; ns[2] = p - W; ns[3] = p + W; + for (int t = 0; t < 4; t++) + { + int n = ns[t]; + if (n < 0 || n >= W * H || seen[n] != 0 || Math.Abs((n % W) - x) > 1) continue; + seen[n] = 1; + int m2 = Math.Min((int)d[n * 4], (int)d[n * 4 + 1]); + if (d[n * 4 + 2] < m2) m2 = d[n * 4 + 2]; + if (m2 >= 232) qq[qn++] = n; + } + } + int w = x1 - x0 + 1, h = y1 - y0 + 1; + if (w >= 30 && h >= 30 && w < 200 && h < 200 && (double)w / h > 0.85 && (double)w / h < 1.15 && qn > (long)w * h * 0.12) + blobs.Add((x0, y0, w, h, qn)); + } + for (int i = 1; i < blobs.Count; i++) + { + var v = blobs[i]; int j = i - 1; + while (j >= 0 && blobs[j].n < v.n) { blobs[j + 1] = blobs[j]; j--; } + blobs[j + 1] = v; + } + PrismFrame A = Image.FrameCreate(W, H, rgba); + var cands = new List<(double[] fit, int size, double score)>(); + double q3 = 3 * Math.Sqrt(3); + double[] one3 = { 1, 1, 1 }; + for (int bi = 0; bi < blobs.Count && bi < 2; bi++) + { + var b = blobs[bi]; + for (int size = 0; size < 4; size++) + { + PrismLayout L = Foundations.LayoutGet(size); + double sx = (double)b.w / (L.W + 2 * q3), sy = (double)b.h / (L.H + 2 * q3); + double[] h = { sx, 0, b.x0 + sx * q3, 0, sy, b.y0 + sy * q3, 0, 0 }; + double[] fit = MixFit(A, h, L); + double score = 0; int count = 0; + PrismMap fm = new PrismMap(); Array.Copy(fit, fm.H, 8); + double[] v = new double[3]; + for (int ki = 0; ki < L.Known.Length; ki++) + { + PrismCell c = L.Known[ki]; + Image.SampleCellEx(A, fm, c, one3, 0, 0, 1, v); + for (int z = 0; z < 3; z++) + { + double gq = v[z] <= 0.0031308 ? 12.92 * v[z] : 1.055 * JsMath.Pow(v[z], 1 / 2.4) - 0.055; + v[z] = 255 * gq; + } + double yy = 0.299 * v[0] + 0.587 * v[1] + 0.114 * v[2]; + int r = HexByte(MixHex[c.Symbol], 1), g2 = HexByte(MixHex[c.Symbol], 3), bb = HexByte(MixHex[c.Symbol], 5); + double ey = 0.299 * r + 0.587 * g2 + 0.114 * bb; + double df = yy - ey; + score += df * df < 2500 ? df * df : 2500; + count++; + } + cands.Add((fit, size, score / count)); + } + } + for (int i = 1; i < cands.Count; i++) + { + var t = cands[i]; int j = i - 1; + while (j >= 0 && cands[j].score > t.score) { cands[j + 1] = cands[j]; j--; } + cands[j + 1] = t; + } + LastN = cands.Count; + for (int i = 0; i < cands.Count && i < 8; i++) + Last[i] = new PrismMixCand { Size = cands[i].size, H = (double[])cands[i].fit.Clone(), Score = cands[i].score }; + for (int ci = 0; ci < cands.Count && ci < 3; ci++) + { + if (cands[ci].score > 700) continue; + PrismLayout L = Foundations.LayoutGet(cands[ci].size); + int[] symbols = new int[L.Cells.Length + 1]; + PrismPayload r = MixRecover(A, cands[ci].fit, L, symbols); + double[] hh = (double[])cands[ci].fit.Clone(); + for (int it = 0; r == null && mixSymbolsValid && it < 3; it++) + { + hh = MixAlternate(A, hh, L, symbols); + r = MixRecover(A, hh, L, symbols); + } + if (r != null) + { + PrismMixResult result = new PrismMixResult { Payload = r, Quality = 1 }; + Array.Copy(cands[ci].fit, result.H, 8); + result.Radius = JsMath.Hypot2(cands[ci].fit[0], cands[ci].fit[3]); + result.Sigma = 6; + return result; + } + } + return null; + } + } +} diff --git a/ports/csharp/reader/PrismRead.cs b/ports/csharp/reader/PrismRead.cs new file mode 100644 index 0000000..f6621f5 --- /dev/null +++ b/ports/csharp/reader/PrismRead.cs @@ -0,0 +1,373 @@ +// PrismRead.cs - readImage legacy hypothesis flow + yA full-canvas generator export. +// Transliterated from ports/c/reader/prism_read.c. +using System; +using System.Collections.Generic; + +namespace Prism.Reader +{ + internal sealed class PrismRead + { + public bool Ok; + public PrismPayload Payload = new PrismPayload(); + public double Quality, Radius, Sigma; + public double[,] Quad = new double[4, 2]; + public double[] H = new double[8]; + public int LayoutSize; + public string Fallback; + public double FitSkew, FitCurve, FitLoss; + public double[] Warp = new double[10]; + public string Reader; + public PrismErr Err = new PrismErr(); + } + + internal static class ReadLayer + { + public static int StageRank(string s) + { + if (s == "hypothesis" || s == "too small") return 1; + if (s == "header") return 2; + if (s == "RS") return 3; + if (s == "CRC") return 4; + return 0; + } + private static PrismErr Mk(string st, string m) => new PrismErr { Stage = st, Msg = m }; + private static PrismErr Cp(PrismErr e) => new PrismErr { Stage = e.Stage, Msg = e.Msg }; + public static void SplitErr(string s, PrismErr e) + { + int c = s.IndexOf(':'); + if (c >= 0) { e.Stage = s.Substring(0, Math.Min(c, 23)); e.Msg = s.Substring(c + 1); } + else { e.Stage = ""; e.Msg = s; } + } + + private sealed class ReadHyp + { + public PrismMap H; public PrismLayout L; public int Mode; + public double[,] Quad = new double[4, 2]; + public double[] White = new double[3]; + public int Rot, Pp; public double Score, Cost; public int Seq; + } + + private static void FillResult(PrismRead o, PrismPayload w, double quality, double radius, double[,] quad, PrismMap h, PrismLayout l, double sigma) + { + o.Ok = true; o.Payload = w; o.Quality = quality; o.Radius = radius; o.Sigma = sigma; + Array.Copy(quad, o.Quad, 8); + Array.Copy(h.H, o.H, 8); + o.LayoutSize = l.Size; o.Fallback = null; + } + + private static int ReadInner(PrismFrame I, PrismRead outR) + { + var cands = new List(); + int dr; + string dummy; + dr = Flags.Pq != 0 ? Detect.DetectLap(I, cands, out dummy) : Detect.DetectLa(I, cands); + if (dr != 0) { outR.Err = Mk("detect", "Could not fit four edges"); return -1; } + var hyps = new List(); + for (int ci = 0; ci < cands.Count; ci++) + { + if (Budget.FastDeadlineHit()) { outR.Err = Mk("fast", "Fast read budget reached"); return -1; } + PrismCand e = cands[ci]; + int sz0 = e.Sz >= 0 ? e.Sz : 0, sz1 = e.Sz >= 0 ? e.Sz + 1 : 6; + for (int A = sz0; A < sz1; A++) + { + PrismLayout r = Foundations.LayoutGet(A); + double[,] src = new double[4, 2]; + Image.CornersOf(r, src); + for (int o = 0; o < (e.R0 != 0 ? 1 : 4); o++) + { + double[,] iq = new double[4, 2]; + for (int t = 0; t < 4; t++) { iq[t, 0] = e.P[(t + o) % 4, 0]; iq[t, 1] = e.P[(t + o) % 4, 1]; } + PrismMap a = new PrismMap(); + if (Image.Homography(src, iq, a) != 0) continue; + double[] g = new double[3]; + Image.WhiteBalance(I, a, r, g); + for (int m = 0; m < 2; m++) + { + Image.HypothesisScore(I, a, r, m, g, 1, out double cost, out double score); + ReadHyp H = new ReadHyp { L = r, Mode = m, Rot = o, Pp = e.R0 != 0 ? 1 : 0, Score = score, Cost = cost, Seq = hyps.Count }; + H.H = new PrismMap(); H.H.CopyFrom(a); + Array.Copy(iq, H.Quad, 8); + Array.Copy(g, H.White, 3); + hyps.Add(H); + } + } + } + } + hyps.Sort((A, e) => + { + if (A.Score != e.Score) return A.Score < e.Score ? 1 : -1; + if (A.Cost != e.Cost) return A.Cost > e.Cost ? 1 : -1; + return A.Seq - e.Seq; + }); + if (Flags.Pq != 0) + { + var re = new List(); + int nr = 0; + for (int i = 0; i < hyps.Count && nr < 4; i++) if (hyps[i].Pp == 0) { re.Add(hyps[i]); nr++; } + for (int i = 0, k = 0; i < hyps.Count && k < 4; i++) if (hyps[i].Pp != 0) { re.Add(hyps[i]); k++; } + hyps = re; + } + else if (hyps.Count > 4) hyps = hyps.GetRange(0, 4); + + PrismErr best = Mk("", ""); bool haveBest = false; + PrismErr Q = Mk("hypothesis", "Code pattern not recognized. Try better light or a closer photo."); + for (int hi = 0; hi < hyps.Count; hi++) + { + ReadHyp A = hyps[hi]; + PrismMap h = new PrismMap(); h.CopyFrom(A.H); + PrismLayout n = A.L; + int s = A.Mode; + double[,] C = (double[,])A.Quad.Clone(); + double[] E = (double[])A.White.Clone(); + PrismErr e = Mk("", ""); + PrismPayload w = new PrismPayload(); bool haveW = false; + if (A.Score > 0.92) + { + double e0 = Budget.FastDeadlineGet(); + if (e0 != 0) + { + double od = Budget.OverallDeadlineGet(); + if (od == 0) od = e0; + double lim = Budget.Now() + (n.Size >= 4 ? 0.850 : 0.450); + if (lim > od) lim = od; + if (lim > e0) Budget.FastDeadlineSet(lim); + } + } + if (A.Score > 0.92 && s == 0 && n.Size < 4) + { + if (Classify.UA(I, h, n, s, E, null, out PrismClassify c0, out _) == 0) + { + PrismErr pe = new PrismErr(); + if (Decode.DecodeClass(c0, w, pe) == 0) + { + FillResult(outR, w, A.Score, JsMath.Hypot2(C[1, 0] - C[0, 0], C[1, 1] - C[0, 1]) / n.W, C, h, n, c0.Sigma); + return 0; + } + } + } + { + int rerr = 0; + Image.RefineQuad(I, h, n, s, C, E, ref rerr); + Image.WhiteBalance(I, h, n, E); + } + Image.HypothesisScore(I, h, n, s, E, 0, out double cost2, out double B); + bool rejected = false; + if (B < (s != 0 ? 0.75 : 0.5)) { e = Mk("hypothesis", "Known cells do not match"); rejected = true; } + double f = 0; + if (!rejected) + { + Image.MapPoint(h, n.W / 2, n.H / 2, out double ax, out double ay); + Image.MapPoint(h, n.W / 2 + 1, n.H / 2, out double bx, out double by); + Image.MapPoint(h, n.W / 2, n.H / 2 + 1, out double cx, out double cy); + double f1 = JsMath.Hypot2(bx - ax, by - ay), f2 = JsMath.Hypot2(cx - ax, cy - ay); + f = f1 < f2 ? f1 : f2; + if (f < (n.Size >= 4 ? 2 : Flags.CfgMinRadius)) { e = Mk("too small", "Too small. Move closer or use a larger image."); rejected = true; } + } + if (!rejected) + { + bool haveC = false; + PrismClassify c = null; + if (Classify.UA(I, h, n, s, E, null, out c, out string uerr) == 0) haveC = true; + else SplitErr(uerr, Q); + if (haveC) + { + PrismErr pe = new PrismErr(); + if (Decode.DecodeClass(c, w, pe) == 0) haveW = true; else Q = pe; + } + if (!haveW) + { + PrismMesh m1 = Classify.QaBuildMesh(I, h, n, s, E, null); + PrismMesh m2 = Classify.QaBuildMesh(I, h, n, s, E, m1); + if (Classify.UA(I, h, n, s, E, m2, out c, out uerr) == 0) haveC = true; + else { SplitErr(uerr, Q); haveC = false; } + if (haveC) + { + PrismErr pe = new PrismErr(); + if (Decode.DecodeClass(c, w, pe) == 0) haveW = true; else Q = pe; + } + } + if (haveW) + { + FillResult(outR, w, B, f, C, h, n, c.Sigma); + return 0; + } + e = Cp(Q); + } + if (!haveBest || StageRank(e.Stage) > StageRank(best.Stage)) { best = Cp(e); haveBest = true; } + if (!((e.Stage != "RS" && e.Stage != "CRC") && (Q.Stage == "RS" || Q.Stage == "CRC"))) + Q = Cp(e); + } + outR.Err = haveBest ? best : Q; + return -1; + } + + public static int ReadImage(byte[] rgba, int w, int h, bool exportFallback, PrismRead outR) + { + Budget.BudgetSet(2.5); + PrismFrame I = Image.FrameCreate(w, h, rgba); + int r = ReadInner(I, outR); + if (r == 0) + { + if (outR.Payload.NBytes == 0 && outR.Quality < 0.8) + { + outR.Payload = new PrismPayload(); + outR.Ok = false; + outR.Err = Mk("hypothesis", "Empty result lacks a strong code-pattern match"); + r = -1; + } + else return 0; + } + if (exportFallback) + { + PrismRead g = new PrismRead(); + if (ReadGenerator(rgba, w, h, g) == 0) { CopyRead(g, outR); return 0; } + } + return -1; + } + + public static void CopyRead(PrismRead s, PrismRead d) + { + d.Ok = s.Ok; d.Payload = s.Payload; d.Quality = s.Quality; d.Radius = s.Radius; d.Sigma = s.Sigma; + Array.Copy(s.Quad, d.Quad, 8); Array.Copy(s.H, d.H, 8); d.LayoutSize = s.LayoutSize; d.Fallback = s.Fallback; + d.FitSkew = s.FitSkew; d.FitCurve = s.FitCurve; d.FitLoss = s.FitLoss; Array.Copy(s.Warp, d.Warp, 10); d.Reader = s.Reader; d.Err = s.Err; + } + + private static double Clamp01(double A) => A < 0 ? 0 : A > 1 ? 1 : A; + + private sealed class GenCand + { + public int Size; public PrismLayout L; public double R; public double[] H = new double[8]; + public double Loss, Skew, Curve; public int Seq; + } + + private static double GenLoss(PrismFrame r, PrismLayout s, double C, PrismCell[] Q, int nq, double skew, double curve) + { + double[][][] t = new double[9][][]; + for (int i = 0; i < 9; i++) { t[i] = new double[1024][]; } + int[] nt = new int[9]; + double a = Math.Tan(skew * Math.PI / 180); + double[] v = new double[3]; + for (int qi = 0; qi < nq; qi++) + { + PrismCell A = Q[qi]; + double i = (A.Y + Foundations.Q) * C; + double g = a * (i / r.H - 0.5) * i + Math.Sin(i / r.H * Math.PI) * curve * r.W * 0.08; + Image.FrameSample(r, (A.X + Foundations.Q) * C + g, i, v); + int b = A.Symbol; + t[b][nt[b]] = new[] { Image.SrgbQ(v[0]), Image.SrgbQ(v[1]), Image.SrgbQ(v[2]) }; + nt[b]++; + } + double[][] mean = new double[9][]; double[] I = new double[3]; + int h = 0; + for (int A = 0; A < 9; A++) + { + mean[A] = new double[3]; + if (nt[A] != 0) + { + for (int k = 0; k < nt[A]; k++) for (int e = 0; e < 3; e++) mean[A][e] += t[A][k][e]; + for (int e = 0; e < 3; e++) { mean[A][e] /= nt[A]; I[e] += mean[A][e]; } + h++; + } + } + for (int e = 0; e < 3; e++) I[e] /= h; + double l = 0, g2 = 0; + for (int A = 0; A < 9; A++) + if (nt[A] != 0) + { + for (int e = 0; e < 3; e++) l += (mean[A][e] - I[e]) * (mean[A][e] - I[e]); + for (int k = 0; k < nt[A]; k++) for (int e = 0; e < 3; e++) g2 += (t[A][k][e] - mean[A][e]) * (t[A][k][e] - mean[A][e]); + } + if (l < 0.02) return 1e6; + return g2 / nq / (l / h); + } + + public static int ReadGenerator(byte[] rgba, int w, int h, PrismRead outR) + { + outR.Ok = false; + PrismFrame r = Image.FrameCreate(w, h, rgba); + var cands = new List(); + for (int n = 0; n < 6; n++) + { + PrismLayout s = Foundations.LayoutGet(n); + double C = (r.W / (s.W + 2 * Foundations.Q) + r.H / (s.H + 2 * Foundations.Q)) / 2; + if (C < Flags.CfgMinRadius) continue; + if (Math.Abs((s.W + 2 * Foundations.Q) * C - r.W) > 2) continue; + if (Math.Abs((s.H + 2 * Foundations.Q) * C - r.H) > 2) continue; + int nq0 = s.Known.Length; + int E = nq0 / 180; if (E < 1) E = 1; + PrismCell[] Q = new PrismCell[1024]; int nq = 0; + for (int i = 0; i < nq0; i++) if (i % E == 0) Q[nq++] = s.Known[i]; + GenCand F = new GenCand { Size = n, L = s, R = C, Seq = cands.Count }; + F.H[0] = C; F.H[1] = 0; F.H[2] = Foundations.Q * C; F.H[3] = 0; + F.H[4] = C; F.H[5] = Foundations.Q * C; F.H[6] = 0; F.H[7] = 0; + F.Loss = double.PositiveInfinity; F.Skew = 0; F.Curve = 0; + for (double m = -18; m <= 18; m += 3) + for (double w2 = 0; w2 <= 1.001; w2 += 0.1) + { + double u = GenLoss(r, s, C, Q, nq, m, w2); + if (u < F.Loss) { F.Loss = u; F.Skew = m; F.Curve = w2; } + } + double csk = F.Skew, ccv = F.Curve; + for (double d = -3; d <= 3.001; d += 0.3) + for (double y = -0.1; y <= 0.1001; y += 0.01) + { + double M = csk + d, D = ccv + y; + double p = GenLoss(r, s, C, Q, nq, M, D); + if (p < F.Loss) { F.Loss = p; F.Skew = M; F.Curve = D; } + } + cands.Add(F); + } + cands.Sort((A, e) => A.Loss != e.Loss ? (A.Loss > e.Loss ? 1 : -1) : A.Seq - e.Seq); + outR.Err = Mk("hypothesis", "Full-canvas export geometry did not match"); + for (int ci = 0; ci < cands.Count && ci < 2; ci++) + { + GenCand F = cands[ci]; + if (F.Loss > 0.45) continue; + byte[] N = new byte[w * h * 4]; + double U = Math.Tan(F.Skew * Math.PI / 180); + double[] v = new double[3]; + for (int H = 0; H < h; H++) + for (int W = 0; W < w; W++) + { + double K = U * ((double)H / h - 0.5) * H + Math.Sin((double)H / h * Math.PI) * F.Curve * w * 0.08; + Image.FrameSample(r, W + K, H, v); + int z = 4 * (H * w + W); + for (int X = 0; X < 3; X++) + { + double d = 255 * Clamp01(Image.SrgbQ(v[X])); + N[z + X] = (byte)Math.Round(d, MidpointRounding.ToEven); + } + N[z + 3] = 255; + } + PrismFrame J = Image.FrameCreate(w, h, N); + PrismMap L = new PrismMap(); Array.Copy(F.H, L.H, 8); + double[] x = new double[3]; + Image.WhiteBalance(J, L, F.L, x); + if (Classify.UA(J, L, F.L, 0, x, null, out PrismClassify O, out string uerr) == 0) + { + PrismPayload V = new PrismPayload(); PrismErr pe = new PrismErr(); + if (Decode.DecodeClass(O, V, pe) == 0) + { + if (V.NBytes == 0) + { + outR.Err = Mk("header", "Empty payload needs a direct high-confidence header"); + continue; + } + outR.Ok = true; outR.Payload = V; outR.Quality = O.KnownMatch; outR.Radius = F.R; outR.Sigma = O.Sigma; + double[,] src = new double[4, 2]; + Image.CornersOf(F.L, src); + for (int k = 0; k < 4; k++) { Image.MapPoint(L, src[k, 0], src[k, 1], out double qx, out double qy); outR.Quad[k, 0] = qx; outR.Quad[k, 1] = qy; } + Array.Copy(F.H, outR.H, 8); + outR.LayoutSize = F.Size; + outR.Fallback = "full-canvas generator curve model"; + outR.FitSkew = F.Skew; outR.FitCurve = F.Curve; outR.FitLoss = F.Loss; + return 0; + } + outR.Err = pe; + } + else SplitErr(uerr, outR.Err); + } + return -1; + } + } +} diff --git a/ports/csharp/reader/PrismTypes.cs b/ports/csharp/reader/PrismTypes.cs new file mode 100644 index 0000000..fa8f8a6 --- /dev/null +++ b/ports/csharp/reader/PrismTypes.cs @@ -0,0 +1,77 @@ +// PrismTypes.cs - shared reader types, worker-global flags, deadlines. +// Transliterated from ports/c/reader/prism_reader.h and prism_decode.c. +using System; +using System.Diagnostics; + +namespace Prism.Reader +{ + internal struct PrismHeader : IEquatable + { + public int Size, Ecc, Mode, Type, Length; + public bool Equals(PrismHeader o) => Size == o.Size && Ecc == o.Ecc && Mode == o.Mode && Type == o.Type && Length == o.Length; + public override bool Equals(object o) => o is PrismHeader h && Equals(h); + public override int GetHashCode() => HashCode.Combine(Size, Ecc, Mode, Type, Length); + } + + internal sealed class PrismErr { public string Stage = ""; public string Msg = ""; } + + internal sealed class PrismPayload + { + public byte[] Bytes; + public int NBytes; + public string Text; // utf-8 text when header.type == 0, else null + public PrismHeader Header; + public int Corrected, Erasures; + public string Variant; // "original" | "generator-whitened" | "palette mixing" + } + + internal struct PrismPointConf { public double X, Y, Confidence; } + internal struct PrismGlareSample { public int At; public double[] Cv; } + + internal sealed class PrismClassify + { + public PrismHeader Header; + public PrismHeader[] Headers = new PrismHeader[12]; public int NHeaders; + public float[] Stream; public int NStream; + public int[] ExtGlare; public int NExtGlare; + public PrismGlareSample[] GlareSamples; public int NGlare; + public float[] Hb = new float[24]; + public double Sigma; + public PrismPointConf[] Points; public int NPoints; + public double KnownMatch; + public PrismPayload MixDecoded; + } + + internal static class Flags + { + public static int Calmed, Dd, Veil, Mix, Pq, Direct; + public static double PageCapS; + public static int CapStopped; + public static double CfgMinRadius = 4; + public static int NoLogo; + public static double FbMs; + } + + internal static class Budget + { + private static readonly Stopwatch SW = Stopwatch.StartNew(); + public static double Now() => SW.Elapsed.TotalSeconds + 1000.0; + private static double budgetDeadline, fastDeadline, overallDeadline; + public static void BudgetSet(double secondsFromNow) { budgetDeadline = secondsFromNow > 0 ? Now() + secondsFromNow : 0; } + public static double BudgetDeadline => budgetDeadline; + public static void FastDeadlineSet(double v) { fastDeadline = v; } + public static double FastDeadlineGet() => fastDeadline; + public static void OverallDeadlineSet(double v) { overallDeadline = v; } + public static double OverallDeadlineGet() => overallDeadline; + public static bool FastDeadlineHit() => fastDeadline != 0 && Now() > fastDeadline; + public static bool BudgetExceeded() => budgetDeadline != 0 && Now() > budgetDeadline; + } + + /* C fmax/fmin semantics: a NaN operand yields the other operand. */ + internal static class Cm + { + public static double Fmax(double a, double b) { if (double.IsNaN(a)) return b; if (double.IsNaN(b)) return a; return a > b ? a : b; } + public static double Fmin(double a, double b) { if (double.IsNaN(a)) return b; if (double.IsNaN(b)) return a; return a < b ? a : b; } + public static double Clamp01(double a) => Fmax(0, Fmin(1, a)); + } +} diff --git a/ports/csharp/reader/Program.cs b/ports/csharp/reader/Program.cs new file mode 100644 index 0000000..3e75922 --- /dev/null +++ b/ports/csharp/reader/Program.cs @@ -0,0 +1,35 @@ +// Comb Code camera-reader CLI: read a Comb Code from a raw RGBA file. +// usage: prism-reader [--chain] +// raw = 8 bytes little-endian width and height followed by RGBA bytes. +// Runs the full retry chain; --chain is accepted for explicitness. +// Prints OK / OKBIN / FAIL . A result is only printed +// when the header CRC and payload CRC-32 pass. +using System; + +namespace Prism.Reader +{ + internal static class Program + { + private static int Main(string[] args) + { + if (args.Length < 1) { Console.Error.WriteLine("usage: prism-reader [--chain]"); return 2; } + byte[] raw; + if (args[0] == "/dev/stdin") { using var ms = new System.IO.MemoryStream(); Console.OpenStandardInput().CopyTo(ms); raw = ms.ToArray(); } + else if (System.IO.File.Exists(args[0])) raw = System.IO.File.ReadAllBytes(args[0]); + else { Console.Error.WriteLine("usage: prism-reader [--chain]"); return 2; } + if (raw.Length < 8) return 2; + int w = BitConverter.ToInt32(raw, 0), h = BitConverter.ToInt32(raw, 4); + if (w <= 0 || h <= 0 || raw.Length != 8L + (long)w * h * 4) return 2; + byte[] px = new byte[checked(w * h * 4)]; Array.Copy(raw, 8, px, 0, px.Length); + var result = new PrismRead(); + int rc = Chain.Read(px, w, h, result); + if (rc == 0 && result.Ok) + { + if (result.Payload.Text != null) Console.WriteLine("OK " + result.Payload.Text); + else Console.WriteLine("OKBIN " + Convert.ToHexString(result.Payload.Bytes, 0, result.Payload.NBytes).ToLowerInvariant()); + } + else Console.WriteLine("FAIL " + result.Err.Stage); + return 0; + } + } +} diff --git a/ports/csharp/reader/README.md b/ports/csharp/reader/README.md new file mode 100644 index 0000000..5cc7cb2 --- /dev/null +++ b/ports/csharp/reader/README.md @@ -0,0 +1,38 @@ +# Comb Code camera reader — C# (.NET 8) + +A .NET 8 port of the live Comb Code photo/camera reader: detection, hypothesis +search, palette-mix recovery, distance-fit recovery and the full retry chain. +It reads real photos, not only clean PNGs. Standard library only, no NuGet +packages. The clean-PNG encoder/decoder is in the parent folder. + +Build: `dotnet build -c Release -o build` (produces `build/prism-reader`). + +Run: `./build/prism-reader scene.raw`, where the file is 8 bytes little-endian +width and height followed by RGBA bytes. Prints `OK `, `OKBIN ` or +`FAIL `. A result is only returned when the header CRC and payload +CRC-32 pass. + +## Verified status + +Method: 772 synthetic scenes from the bench kit, run sequentially, each result +compared to the live JavaScript reader's result for the same image +(`../../reader-verify/verify_vs_live.py`). + +| Result | Scenes | +|---|---| +| Read, payload identical to live reader | 722-723 | +| Both fail | 44 | +| Live reader reads, port does not | 5-6 | +| Wrong payload | 0 | +| Port reads, live reader does not | 0 | + +The live reader reads 728 of the 772 scenes. The 5 to 6 scenes the port misses are +wall-clock budget cutoffs, not wrong reads: the retry chain gives each attempt +a 450 ms budget and each page 6 seconds (as the live reader does), and the +managed distance-fit read runs about 2x slower than the C port, so those +attempts are cut off. Timing: run verification one process at a time; under +heavy parallel load more borderline scenes time out. This is a +synthetic-scene result, not a physical-camera result. + +Comb Code, Copyright (c) 2026 Avi Shor. Free to use, with or without credit. +No warranty. diff --git a/ports/csharp/reader/prism-reader.csproj b/ports/csharp/reader/prism-reader.csproj new file mode 100644 index 0000000..e9739b2 --- /dev/null +++ b/ports/csharp/reader/prism-reader.csproj @@ -0,0 +1,18 @@ + + + + Exe + net8.0 + disable + disable + prism-reader + Prism.Reader + Comb Code + Avi Shor + Comb Code camera reader: detection, hypothesis search and the full retry chain for photos (C# / .NET 8). + + true + + +