Files
lilygo-t-deck/examples/MiataDrive/sprite_tool.py
T
Dejvino 1a1ab8637e MiataDrive: sprite sheet cleanup pass
sprite_tool.py gains a 'clean' subcommand that tidies the sheet in place:
drops specks (<=4px) and 1px sliver lines left over from the original
checker-keyed extractions, and re-centers every sprite in its cell
(bottom-anchored, 2px margin) so nothing touches the cell edges.
Tree trunks / palm fronds are protected from thin-line removal.

Run on the sheet: 489 junk pixels removed; re-import crops tightened
(e.g. car_white_turn 108x60 -> 92x54, car_yellow_turn 86x60 -> 80x56).
2026-11-12 22:34:22 +01:00

278 lines
10 KiB
Python

#!/usr/bin/env python3
"""
Lotus3 sprite tool — hand-editing workflow for the game's sprite assets.
1. python3 sprite_tool.py export -> sprites_sheet.png (editable image)
2. edit sprites_sheet.png by hand (paint over magenta = transparent)
3. python3 sprite_tool.py import -> sprites.h regenerated from the image
Sheet layout (fixed, so the cutter never needs to guess):
* 7 columns x 4 rows of 160x140 cells (image is 1120x560)
* the top 14px of each cell is a label strip (name text); the cutter skips it
* content area per cell: 160x126 -- big enough for the largest sprite
(arch 140x109). If you draw bigger, it will be clipped.
* background is pure magenta (255,0,255) = transparent
* pink/magenta anti-aliasing fringes are cut (magenta excess > 35) or
despilled (pulled back toward the sprite color)
Cell order (row-major) is fixed and matches the game's SpriteId enum:
0..15 player cars: red/blue/white/yellow x (rear, slight, turn, side)
16..21 scenery: palm, pine, bush, billboard, arch, tires
22..27 traffic: blue rear/turn, white rear/turn, yellow rear/turn
Requires Pillow: python3 -m pip install --user pillow
"""
import re
import sys
import os
from collections import deque
try:
from PIL import Image, ImageDraw
except ImportError:
sys.exit("Pillow required: python3 -m pip install --user pillow")
HERE = os.path.dirname(os.path.abspath(__file__))
HDR = os.path.join(HERE, "sprites.h")
SHEET = os.path.join(HERE, "sprites_sheet.png")
CELL_W, CELL_H = 160, 140
LABEL_H = 14
COLS, ROWS = 7, 4
MAGENTA = (255, 0, 255)
NAMES = [
"p_red_rear", "p_red_slight", "p_red_turn", "p_red_side",
"p_blue_rear", "p_blue_slight", "p_blue_turn", "p_blue_side",
"p_white_rear", "p_white_slight", "p_white_turn", "p_white_side",
"p_yellow_rear", "p_yellow_slight", "p_yellow_turn", "p_yellow_side",
"palm", "pine", "bush", "billboard", "arch", "tires",
"car_blue", "car_blue_turn", "car_white", "car_white_turn",
"car_yellow", "car_yellow_turn",
]
assert len(NAMES) == COLS * ROWS
ENUM = """enum SpriteId {
SPR_P_RED, SPR_P_RED_S, SPR_P_RED_T, SPR_P_RED_SIDE,
SPR_P_BLUE, SPR_P_BLUE_S, SPR_P_BLUE_T, SPR_P_BLUE_SIDE,
SPR_P_WHITE, SPR_P_WHITE_S, SPR_P_WHITE_T, SPR_P_WHITE_SIDE,
SPR_P_YELLOW, SPR_P_YELLOW_S, SPR_P_YELLOW_T, SPR_P_YELLOW_SIDE,
SPR_PALM, SPR_PINE, SPR_BUSH, SPR_BILLBOARD, SPR_ARCH, SPR_TIRES,
SPR_CAR_BLUE, SPR_CAR_BLUE_T, SPR_CAR_WHITE, SPR_CAR_WHITE_T,
SPR_CAR_YELLOW, SPR_CAR_YELLOW_T,
SPR_COUNT };"""
def is_bg(p):
return p[0] > 160 and p[2] > 160 and p[1] < 150
def key_pixel(p):
"""magenta key + halo despill -> (keep, r, g, b)"""
r, g, b = p[:3]
if is_bg(p):
return False, 0, 0, 0
e = min(r, b) - g # magenta excess
if e > 35:
return False, 0, 0, 0 # pink halo pixel -> cut
if e > 8: # mild fringe -> despill
f = min(1.0, (e - 8) / 30.0) * 0.85
r = int(r - (r - g) * f)
b = int(b - (b - g) * f)
return True, r, g, b
def expand565(v):
"""RGB565 -> 8-bit with bit replication (exact inverse of the C encoder)."""
r = (v >> 11) & 0x1F
g = (v >> 5) & 0x3F
b = v & 0x1F
return (r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2)
def parse_sprites_h(path):
"""returns ordered list of (name, w, h, [rgb565 values])"""
src = open(path).read()
table = re.findall(r'\{\s*\w+,\s*(\d+),\s*(\d+)\s*\}\s*,\s*//\s*(\w+)', src)
dims = {name: (int(w), int(h)) for w, h, name in table}
order = [name for _, _, name in table]
arrays = {}
for m in re.finditer(r'static const uint16_t (SPR_\w+)\[(\d+)\] = \{([^}]*)\}', src, re.S):
vals = [int(x, 16) for x in re.findall(r'0x([0-9A-Fa-f]{4})', m.group(3))]
arrays[m.group(1)] = vals
out = []
for name in order:
w, h = dims[name]
arr = arrays.get("SPR_" + name + "_DATA")
if arr is None or len(arr) != w * h:
sys.exit(f"sprites.h: cannot resolve {name}")
out.append((name, w, h, arr))
return out
def cmd_export():
sprites = parse_sprites_h(HDR)
if len(sprites) != len(NAMES):
sys.exit(f"sprites.h has {len(sprites)} sprites, tool expects {len(NAMES)}")
sheet = Image.new("RGB", (COLS * CELL_W, ROWS * CELL_H), MAGENTA)
draw = ImageDraw.Draw(sheet)
for i, (cur, w, h, vals) in enumerate(sprites):
cx, cy = (i % COLS) * CELL_W, (i // COLS) * CELL_H
draw.text((cx + 3, cy + 1), f"{i}:{NAMES[i]}", fill=(0, 0, 0))
for y in range(h):
for x in range(w):
v = vals[y * w + x]
if v == 0x0001:
continue # magenta shows through
sheet.putpixel((cx + x, cy + LABEL_H + y), expand565(v))
sheet.save(SHEET)
print(f"wrote {SHEET} ({sheet.size[0]}x{sheet.size[1]}, {len(sprites)} sprites)")
def cmd_import():
sheet = Image.open(SHEET).convert("RGB")
if sheet.size != (COLS * CELL_W, ROWS * CELL_H):
sys.exit(f"{SHEET} is {sheet.size}, expected {(COLS*CELL_W, ROWS*CELL_H)}")
parts = []
parts.append("""// Auto-generated by sprite_tool.py from sprites_sheet.png — do not edit by hand;
// edit the sheet image and re-run: python3 sprite_tool.py import
#pragma once
#include <stdint.h>
#define SPR_TRANSP 0x0001
struct GameSprite {
const uint16_t* data;
int w, h;
};
""")
dims = []
for i, name in enumerate(NAMES):
cx, cy = (i % COLS) * CELL_W, (i // COLS) * CELL_H
cell = sheet.crop((cx, cy + LABEL_H, cx + CELL_W, cy + CELL_H))
w, h = cell.size
minx, miny, maxx, maxy = w, h, -1, -1
for y in range(h):
for x in range(w):
if not is_bg(cell.getpixel((x, y))):
if x < minx: minx = x
if x > maxx: maxx = x
if y < miny: miny = y
if y > maxy: maxy = y
if maxx < 0:
minx, miny, maxx, maxy = 0, 0, 0, 0
sw, sh = maxx - minx + 1, maxy - miny + 1
vals = []
for y in range(miny, maxy + 1):
for x in range(minx, maxx + 1):
keep, r, g, b = key_pixel(cell.getpixel((x, y)))
vals.append(0x0001 if not keep else ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3))
parts.append(f"static const uint16_t SPR_{name}_DATA[{sw*sh}] = {{\n")
for k in range(0, len(vals), 16):
parts.append(" " + ", ".join(f"0x{v:04X}" for v in vals[k:k+16]) + ",\n")
parts.append("};\n\n")
dims.append((name, sw, sh))
print(f" {i:2d} {name:16s} {sw}x{sh}")
parts.append("static const GameSprite SPRITES[] = {\n")
for name, sw, sh in dims:
parts.append(f" {{ SPR_{name}_DATA, {sw}, {sh} }}, // {name}\n")
parts.append("};\n\n")
parts.append(ENUM + "\n")
open(HDR, "w").write("".join(parts))
print(f"wrote {HDR}")
def _cell_components(cell):
"""8-connected components of non-background pixels -> list of (area, minx, miny, maxx, maxy, pixelset)"""
w, h = cell.size
px = cell.load()
seen = [[False] * w for _ in range(h)]
comps = []
for y in range(h):
for x in range(w):
if is_bg(px[x, y]) or seen[y][x]:
continue
q = deque([(x, y)])
seen[y][x] = True
area = 0
minx = maxx = x
miny = maxy = y
pix = set()
while q:
a, b = q.popleft()
area += 1
pix.add((a, b))
if a < minx: minx = a
if a > maxx: maxx = a
if b < miny: miny = b
if b > maxy: maxy = b
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
nx, ny = a + dx, b + dy
if 0 <= nx < w and 0 <= ny < h and not seen[ny][nx] and not is_bg(px[nx, ny]):
seen[ny][nx] = True
q.append((nx, ny))
comps.append((area, minx, miny, maxx, maxy, pix))
comps.sort(reverse=True)
return comps
# cells whose 1px-wide vertical runs may be real content (tree trunks etc.)
NO_THIN_REMOVAL = {"palm", "pine"}
def cmd_clean():
"""tidy sprites_sheet.png in place: drop specks/1px slivers, re-center sprites"""
sheet = Image.open(SHEET).convert("RGB")
removed_total = 0
for i, name in enumerate(NAMES):
cx, cy = (i % COLS) * CELL_W, (i // COLS) * CELL_H
cell = sheet.crop((cx, cy + LABEL_H, cx + CELL_W, cy + CELL_H))
w, h = cell.size
comps = _cell_components(cell)
if not comps:
continue
allow_thin = name not in NO_THIN_REMOVAL
removed = set()
for area, minx, miny, maxx, maxy, pix in comps[1:]:
bw, bh = maxx - minx + 1, maxy - miny + 1
tiny = area <= 4
sliver = allow_thin and ((bh == 1 and bw <= 30) or (bw == 1 and bh <= 30))
if tiny or sliver:
removed |= pix
if removed:
px = cell.load()
for x, y in removed:
px[x, y] = MAGENTA
removed_total += len(removed)
# re-center: horizontal middle, bottom anchored 2px above content bottom
comps = _cell_components(cell)
minx = min(c[1] for c in comps)
maxx = max(c[3] for c in comps)
miny = min(c[2] for c in comps)
maxy = max(c[4] for c in comps)
bw, bh = maxx - minx + 1, maxy - miny + 1
dx = (CELL_W - bw) // 2 - minx
dy = (h - 2 - maxy)
if dx or dy:
shifted = Image.new("RGB", (w, h), MAGENTA)
shifted.paste(cell, (dx, dy))
sheet.paste(shifted, (cx, cy + LABEL_H))
sheet.save(SHEET)
print(f"cleaned {SHEET}: {removed_total} junk pixels removed, sprites re-centered")
if __name__ == "__main__":
mode = sys.argv[1] if len(sys.argv) > 1 else ""
if mode == "export":
cmd_export()
elif mode == "import":
cmd_import()
elif mode == "clean":
cmd_clean()
else:
print(__doc__)
sys.exit(1)