Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 154 additions & 19 deletions scripts/test_tools_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,37 +856,144 @@ def test_05_standalone_mugen_extractor(self) -> None:
except ImportError:
self.skipTest("Pillow not installed in test Python environment")

char_dir = os.path.join(self.work_dir, "chars", "ken_e2e")
import gzip

chars_root = os.path.join(self.work_dir, "chars")
char_dir = os.path.join(chars_root, "ken_e2e")
os.makedirs(char_dir, exist_ok=True)

# Build a fighter whose SFF embedded palette is a corrupted cyan ramp,
# while Classic1P.act stores authentic 1P colors in official Elecbyte reverse order (dest = 255 - i)
# AND stores a flashy neon yellow ramp at raw .act bytes 0..47 (slots 255..240).
spr = Image.new("P", (16, 24), 0)
pal = [0, 0, 0] * 256
pal[3:6] = [230, 40, 40]
pal[6:9] = [245, 220, 60]
spr.putpalette(pal)
corrupted_sff_pal = [0, 255, 255] * 256
corrupted_sff_pal[0:3] = [0, 0, 0]
spr.putpalette(corrupted_sff_pal)
for y in range(4, 22):
for x in range(4, 12):
spr.putpixel((x, y), 1)
for x in range(4, 12):
spr.putpixel((x, 4), 2)
spr.putpixel((x, y), 1) # Navy/Red gi
for x in range(5, 11):
spr.putpixel((x, 4), 2) # Blonde hair
spr.putpixel((x, 6), 3) # Natural skin
spr.putpixel((x, 7), 3)
spr.putpixel((x, 21), 4) # Dark outline
spr.putpixel((x, 12), 5) # Belt
pcx_buf = io.BytesIO()
spr.save(pcx_buf, format="PCX")
pcx_bytes = pcx_buf.getvalue()

sff_hdr = bytearray(512)
sff_hdr[0:12] = b"ElecbyteSpr\x00"
struct.pack_into("<I", sff_hdr, 20, 1)
struct.pack_into("<I", sff_hdr, 24, 512)
sub_hdr = struct.pack("<IIhhHHHxB", 0, len(pcx_bytes), 8, 24, 0, 0, 0, 0) + b"\x00" * 12
write_bytes(os.path.join(char_dir, "ken_e2e.sff"), bytes(sff_hdr) + sub_hdr + pcx_bytes)
fx_spr = Image.new("P", (16, 16), 0)
fx_spr.putpalette(corrupted_sff_pal)
for xy in range(2, 14):
fx_spr.putpixel((xy, xy), 250)
fx_buf = io.BytesIO()
fx_spr.save(fx_buf, format="PCX")
fx_pcx = fx_buf.getvalue()

cutin_spr = Image.new("P", (320, 240), 0)
cutin_spr.putpalette(corrupted_sff_pal)
for y in range(20, 220):
for x in range(20, 300):
cutin_spr.putpixel((x, y), 250)
cutin_buf = io.BytesIO()
cutin_spr.save(cutin_buf, format="PCX")
cutin_pcx = cutin_buf.getvalue()

def pack_sff(entries: list[tuple[int, int, int, int, int, int, bytes]]) -> bytes:
hdr = bytearray(512)
hdr[0:12] = b"ElecbyteSpr\x00"
struct.pack_into("<I", hdr, 20, len(entries))
struct.pack_into("<I", hdr, 24, 512)
out = bytearray(hdr)
for idx_e, (x_ax, y_ax, grp, img_n, prev_i, same_pal, raw_pcx) in enumerate(entries):
cur_off = len(out)
next_off = cur_off + 32 + len(raw_pcx) if idx_e + 1 < len(entries) else 0
sub = struct.pack("<IIhhHHHxB", next_off, len(raw_pcx), x_ax, y_ax, grp, img_n, prev_i, same_pal) + b"\x00" * 12
out.extend(sub)
out.extend(raw_pcx)
return bytes(out)

write_bytes(
os.path.join(char_dir, "ken_e2e.sff"),
pack_sff([
(8, 24, 0, 0, 0, 0, pcx_bytes),
(8, 16, 1000, 0, 0, 0, fx_pcx),
(160, 120, 3000, 0, 0, 0, cutin_pcx),
]),
)

act_1p = bytearray(768)
for fx_slot in range(240, 256):
raw_i = 255 - fx_slot
act_1p[raw_i * 3 : raw_i * 3 + 3] = bytes((255, 255, 0))
authentic_map = {
1: (32, 64, 200),
2: (220, 32, 32),
3: (232, 184, 144),
4: (28, 24, 32),
5: (240, 240, 240),
}
for pal_idx, rgb in authentic_map.items():
raw_i = 255 - pal_idx
act_1p[raw_i * 3 : raw_i * 3 + 3] = bytes(rgb)
write_bytes(os.path.join(char_dir, "Classic1P.act"), bytes(act_1p))

act_neon = bytearray(768)
for pal_idx in range(1, 16):
raw_i = 255 - pal_idx
act_neon[raw_i * 3 : raw_i * 3 + 3] = bytes((255, 10, 20))
write_bytes(os.path.join(char_dir, "Neon2P.act"), bytes(act_neon))

write_text(
os.path.join(char_dir, "ken_e2e.air"),
"[Begin Action 0]\n0,0, 0,0, 6\n\n[Begin Action 20]\n0,0, 0,0, 6\n\n[Begin Action 200]\n0,0, 0,0, 5\n",
"[Begin Action 0]\n0,0, 0,0, 6\n\n"
"[Begin Action 20]\n0,0, 0,0, 6\n\n"
"[Begin Action 200]\n0,0, 0,0, 5\n\n"
"[Begin Action 1000]\n1000,0, 0,0, 4, , A\n\n"
"[Begin Action 1010]\n0,0, 0,0, 5\n\n"
"[Begin Action 3000]\n3000,0, 0,0, 4\n0,0, 0,0, 6\n",
)
write_text(
os.path.join(char_dir, "ken_e2e.def"),
"[Info]\nname = \"Ken E2E\"\ndisplayname = \"Ken\"\n[Files]\nsprite = ken_e2e.sff\nanim = ken_e2e.air\n",
"[Info]\nname = \"Ken E2E\"\ndisplayname = \"Ken\"\npal.defaults = 4,1\n"
"[Files]\nsprite = ken_e2e.sff\nanim = ken_e2e.air\npal1 = Neon2P.act\npal4 = Classic1P.act\n",
)

chain_dir = os.path.join(chars_root, "sff_chain_e2e")
os.makedirs(chain_dir, exist_ok=True)
good_spr = Image.new("P", (16, 24), 0)
good_pal = [0, 0, 0] * 256
for pal_idx, rgb in authentic_map.items():
good_pal[pal_idx * 3 : pal_idx * 3 + 3] = list(rgb)
good_spr.putpalette(good_pal)
for y in range(4, 22):
for x in range(4, 12):
good_spr.putpixel((x, y), 1)
for x in range(5, 11):
good_spr.putpixel((x, 4), 2)
good_spr.putpixel((x, 6), 3)
good_spr.putpixel((x, 21), 4)
good_spr.putpixel((x, 12), 5)
good_buf = io.BytesIO()
good_spr.save(good_buf, format="PCX")
good_pcx = good_buf.getvalue()
stripped_pcx = good_pcx[:-769]

write_bytes(
os.path.join(chain_dir, "sff_chain.sff"),
pack_sff([
(8, 24, 9000, 0, 0, 0, good_pcx),
(8, 24, 0, 0, 0, 1, stripped_pcx),
(8, 24, 0, 1, 1, 1, b""),
]),
)
write_text(
os.path.join(chain_dir, "sff_chain.air"),
"[Begin Action 0]\n0,0, 0,0, 6\n0,1, 0,0, 6\n\n[Begin Action 20]\n0,1, 0,0, 6\n\n[Begin Action 200]\n0,0, 0,0, 5\n",
)
write_text(
os.path.join(chain_dir, "sff_chain.def"),
"[Info]\nname = \"Chain E2E\"\n[Files]\nsprite = sff_chain.sff\nanim = sff_chain.air\n",
)

out_fgt_dir = os.path.join(self.work_dir, "fighters_64")
Expand All @@ -896,11 +1003,13 @@ def test_05_standalone_mugen_extractor(self) -> None:
sys.executable,
mugen_py,
"--src",
os.path.dirname(char_dir),
chars_root,
"--dest",
out_fgt_dir,
"--mode",
"FULLSIZE",
"--scale",
"1.0",
"--compress",
"--workers",
"1",
Expand All @@ -910,8 +1019,34 @@ def test_05_standalone_mugen_extractor(self) -> None:
timeout=30,
)
self.assertEqual(r_mugen.returncode, 0, f"mugen_extractor.py failed:\n{r_mugen.stdout}\n{r_mugen.stderr}")
idx_txt = read_text(os.path.join(out_fgt_dir, "index.txt")).strip()
self.assertTrue(idx_txt.startswith("ken_e2e,"), f"Unexpected fighters index.txt: {idx_txt}")
idx_lines = sorted(read_text(os.path.join(out_fgt_dir, "index.txt")).strip().splitlines())
self.assertEqual(len(idx_lines), 2, f"Expected both characters extracted, got: {idx_lines}")

def unpack_fgt_gz_colors(fgt_gz_file: str) -> tuple[int, int, int, set[tuple[int, int, int]]]:
raw = gzip.decompress(read_bytes(fgt_gz_file))
self.assertEqual(raw[:4], b"FGT\x01")
w_f, h_f, nf_f, _ = struct.unpack("<HHHH", raw[4:12])
px_off = 12 + nf_f * 2
rgbs: set[tuple[int, int, int]] = set()
for pos in range(px_off, len(raw) - 1, 2):
c565 = struct.unpack_from("<H", raw, pos)[0]
if c565 != 0:
r8 = ((c565 >> 11) & 0x1F) * 255 // 31
g8 = ((c565 >> 5) & 0x3F) * 255 // 63
b8 = (c565 & 0x1F) * 255 // 31
rgbs.add((r8, g8, b8))
return w_f, h_f, nf_f, rgbs

w_k, h_k, _nf_k, ken_cols = unpack_fgt_gz_colors(os.path.join(out_fgt_dir, "ken_e2e", "stand.fgt.gz"))
self.assertLessEqual(w_k, 64)
self.assertLessEqual(h_k, 64)
self.assertTrue(any(b > 160 and r < 60 for r, g, b in ken_cols), f"Expected 1P colors from reversed .act, got {ken_cols}")
self.assertFalse(any(r > 230 and g > 230 and b < 30 for r, g, b in ken_cols), f"Un-reversed .act yellow FX ramp leaked: {ken_cols}")
self.assertFalse(any(r < 20 and g > 230 and b > 230 for r, g, b in ken_cols), f"Corrupted SFF cyan leaked: {ken_cols}")

_wc, _hc, nfc, chain_cols = unpack_fgt_gz_colors(os.path.join(out_fgt_dir, "sff_chain_e2e", "stand.fgt.gz"))
self.assertEqual(nfc, 2)
self.assertTrue(any(b > 160 and r < 60 for r, g, b in chain_cols))


if __name__ == "__main__":
Expand Down
56 changes: 25 additions & 31 deletions tools/mugen_extractor/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ The **`mugen_extractor.py`** script is designed to convert fighting game charact
|
v
[ resolve_master_palette() ]
- Heuristic scoring (score_palette)
- Modulo Bank Expansion (16/32/64c)
- Dynamic Offset Shifting
- Priority to pal.defaults
- Elecbyte .act reverse decode (255 - i)
- SFFv1 shared initial_palette chaining
- Canonical 1P & pal.defaults hierarchy
- Index-collapse & all-hue wash guard
|
+-------------------+-------------------+
| |
Expand Down Expand Up @@ -140,33 +140,27 @@ The `.fgt` format is a compact, streamable binary animation format engineered fo

## 5. Palette Resolution Algorithm (`resolve_master_palette`)

To ensure 100% authentic color rendering and eliminate fluorescent/neon artifacts across all MUGEN characters (arcade rips, digitized captures, and original creations):

1. **Body Reference Sprite Selection:**
* Prioritizes key body animation groups (`0`, `1`, `5`, `10`, `20`, `21`, `40`, `100`, `200`, `5000`).
* Prioritizes canonical stance frame `(0,0)`, then evaluates the frame with the maximum count of distinct pixel indices.
* Systematically excludes group `9000` (portraits / select icons) to avoid contamination.

2. **Canonical Candidate Hierarchy:**
* **1. Canonical SFF Palette (`sff.stand_palette`):** Embedded palette in sprite `(0,0)` of the `.sff` file validated by `0x0C` marker and anti-RLE check. Absolute priority (**+100 pts**).
* **2. Official DEF Palettes (`DEF(pal.defaults)`):** Palettes declared in `[Info]` `pal.defaults` (**+80 pts**).
* **3. Standard DEF Palettes (`DEF(pal1..12)`):** Palettes declared in `[Files]` (**+75 pts**).
* **4. SFF Big Portrait (`SFF(9000,1)`):** Palette of official full-size character portrait (**+70 pts**).
* **5. SFF First Palette (`sff.first_palette`):** First valid palette in the SFF container (**+60 pts**).
* **6. SFF Small Portrait (`SFF(9000,0)`):** Palette of 25x25 select icon (**+50 pts**).
* **7. Additional `.act` Files:** Extra palettes in character folder (**+30 pts**).

3. **Anti-Fluorescent Evaluation & Scoring Function (`score_palette`):**
* **Anti-RLE Filter (`is_rle_garbage`):** Immediate rejection of fake PCX palettes consisting of compressed image data (> 35% bytes $\ge 192$ and > 25% bytes $\le 15$).
* **Monochrome / Empty Palette Rejection:** If the palette produces only a single color shade (`u_colors <= 1`) while the sprite has multiple indices, score = **-9999**.
* **Residual Neon / Chroma Mask Rejection:** If more than 5% of body pixels resolve to pure primary neon colors (pure magenta `255,0,255`, pure cyan `0,255,255`, pure green `0,255,0`), the palette is rejected.
* **Shifted / Mostly-Black Palette Rejection:** If more than 60% of pixels in a non-trivial sprite map to pure black `(0,0,0)`, the palette is rejected.
* **Coverage Score Formula:**
$$\text{Coverage Ratio} = \min\left(1.0, \frac{\text{Unique Colors}}{\text{Unique Indices}}\right)$$
$$\text{Base Score} = \text{Coverage Ratio} \times 100 + \min(\text{Unique Colors}, \text{Unique Indices}) \times 2$$
$$\text{Luminance Bonus} = +30 \quad \text{if } 15 \le \text{Mean Luminance} \le 215$$
$$\text{Over/Under-exposure Penalty} = -50 \quad \text{if } L < 10 \text{ or } L > 240$$
* `ACT(folder)`: **+10 pts**
To guarantee authentic 1P color rendering and eliminate fluorescent/monochrome silhouettes across all MUGEN characters (arcade rips, digitized captures, and custom edits):

1. **Elecbyte `.act` Reverse Index Decoding (`decode_mugen_act`) & SFFv1 Shared Chaining:**
* In official MUGEN `SFFv1` external `.act` files (768 bytes = 256 RGB triplets), entries are stored in **reverse palette order**: entry `i` in the `.act` file maps to sprite palette index `255 - i` (with index `0` reserved for transparency).
* In `SFFv1Parser`, when stance sprite `(0,0)` has `same_pal != 0` (shared palette without a local `0x0C` trailer), it inherits Sprite `#0`'s `initial_palette`, and linked frames (`data_length == 0`) reuse `sprite_list[prev]`.

2. **Multi-Pose Body Reference & Canonical 1P Hierarchy:**
* Samples pixel indices across stance `(0,0)` plus `walk`/`attack` body sprites while excluding group `9000` portraits.
* Ranks candidates by 1P authority (with non-standard forward `.act` files kept strictly as last-resort fallbacks):
* **1. Explicit Canonical 1P DEF Filenames (`Normal.act`, `Default.act`, `Classic.act`, `Original.act`):** **+220 pts**
* **2. `DEF(pal1) == SFF(stand)` Consensus** (when `pal.defaults` was customized to a high slot): **+215 pts**
* **3. Capcom 6-Button LP (`pal4 = *01.act` when `pal1 = *04.act`):** **+210 pts**
* **4. Primary `DEF(pal.defaults[0])`:** **+200 pts** (secondary `pal.defaults`: **+150 pts**)
* **5. Canonical SFF Stance Palette (`sff.stand_palette`):** **+196 pts**
* **6. Non-default DEF Slots / Extra Folder `.act` / SFF Fallbacks:** **+65..+130 pts**

3. **Structural & Perceptual Validation (`score_palette`, `[0..32]` pts or `-9999`):**
* **Anti-RLE Filter (`is_rle_garbage`):** Rejects compressed PCX pixel streams misidentified as palettes.
* **Index-Collapse Guard:** Rejects palettes where $\ge 4$ distinct non-zero sprite indices collapse onto `(0,0,0)` (`> 32%` black) or onto a single identical fill color (`> 40%` of pixels), while preserving intentional dark outfits that use 1–2 black indices.
* **Chroma-Key & All-Hue Monochrome Ramp Guard:** Rejects chroma-key background leaks (`> 3%` pure magenta/green/cyan) and single-hue neon FX ramps across all hues without penalizing warm Red/Orange + natural Skin 1P costumes.
* **Disembodied Helper & Fullscreen Cut-In Filtering:** `special1..3` and `super1..3` selection skips pure additive (`blend = A/S`) projectile helpers, `1x1` AI dummy actions, and `320x240` / `640x480` fullscreen super cut-ins.

---

Expand Down
Loading
Loading