- runtime/hd_sprites.c : choisit les sprites à dessiner en HD à partir de ce que le jeu a dessiné (dernier sprite encore visible par pixel), charge les images HD sur un fil à part, cache LRU. - Couleurs : correction par indice (palette du jeu - palette de l'export), interpolée dans le shader ; les planches d'objets partagées entre pièces et les fondus ont les bonnes couleurs. - Objets dessinés avec leur propre fond : la partie du fond de la couleur du décor revient au décor HD. - runtime/dxt.c : compression DXT5 et mipmaps sur le fil de chargement (4 fois moins de mémoire, sans à-coup) ; mémoire privée 243 Mo avec décors et sprites HD (objectif < 256 Mo). - Menu F12 : « Pack HD (mods) » avec deux sous-réglages, « Décors HD » (hd_decors) et « Personnages et objets HD » (hd_sprites). - tools/hd_export.py : --planches, --sprites, --sans-decors (planches RGBA, couleurs prolongées dans la transparence). - png.c sans état global (décodage sur le fil de chargement). - docs : MODS.md (sprites HD), SETTINGS.md (nouvelles clés), ROADMAP cochée. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
381 lines
16 KiB
Python
381 lines
16 KiB
Python
r"""Exporte les images du jeu en PNG, point de départ d'un pack HD.
|
||
|
||
Les images viennent des fichiers du joueur et restent sur sa machine : rien n'est redistribué.
|
||
On les agrandit ensuite avec l'outil de son choix (dessin à la main, Real-ESRGAN, waifu2x, xBRZ…)
|
||
puis on les dépose dans mods/<nom_du_mod>/hd/ sous le même nom et le même dossier. Voir docs/MODS.md.
|
||
|
||
python tools/hd_export.py DOSSIER_DU_JEU DOSSIER_SORTIE [--motif LOC*] [--echelle 1|2|4]
|
||
[--sprites [MOTIF]] [--planches [MOTIF]] [--sans-decors]
|
||
[--upscayl [MODELE]] [--upscayl-bin CHEMIN]
|
||
|
||
--motif décors PCX à exporter (défaut : LOC*, les décors des pièces) -> SORTIE/LOC01.png
|
||
--sprites fichiers SPRITES\*.SPR à exporter (défaut : tous) -> SORTIE/SPRITES/<NOM>.png, une planche
|
||
par fichier (puis <NOM>_P1.png… si elle déborde), images rangées comme le jeu les cherche
|
||
--planches planches de sprites PCX (Bud, objets, curseur…) -> SORTIE/SHEETS/<NOM>.png
|
||
(défaut : BUD_*,BUDL00_*,PEG_*,MAC_*,SCROBJ*,PANOBJS*,POINTER,CHARSET*,CHAR2,CLIO*,COGS*)
|
||
--sans-decors n'exporte pas les décors (seulement sprites et planches)
|
||
--echelle 1 = taille d'origine (à agrandir soi-même) ; 2 ou 4 = agrandissement Scale2x
|
||
intégré (contours en escalier adoucis, sans flou), pour tester un pack tout de suite
|
||
--upscayl agrandit ×4 avec Upscayl (Real-ESRGAN) s'il est installé ; modèle par défaut
|
||
digital-art-4x (autres : ultrasharp-4x, remacri-4x, high-fidelity-4x, upscayl-standard-4x…)
|
||
--upscayl-bin chemin de upscayl-bin.exe s'il n'est pas trouvé tout seul
|
||
|
||
Exemples :
|
||
python tools/hd_export.py ..\extracted\iso\TUCKER mods\hd_upscayl\hd --upscayl
|
||
python tools/hd_export.py ..\extracted\iso\TUCKER mods\hd_upscayl\hd --sans-decors --sprites A01_* --planches --upscayl
|
||
|
||
Décors : seules les images plein écran 320×200 servent, les autres sont ignorées. Sprites et planches sont
|
||
transparents (indice 0) ; la couleur des pixels transparents est prolongée depuis les bords pour éviter un
|
||
liseré sombre une fois agrandis. Toutes les images de sprites (55 millions de pixels) prennent du temps à
|
||
agrandir : commencer par une pièce (--sprites A01_*). Sprites et planches demandent numpy.
|
||
"""
|
||
import argparse
|
||
import fnmatch
|
||
import os
|
||
import re
|
||
import shutil
|
||
import struct
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import zlib
|
||
|
||
# mise en page des planches SPR : doit rester identique à make_layout() de runtime/sprites.c
|
||
SPR_PAGE_W = 1024
|
||
SPR_PAGE_H = 1024
|
||
SPR_PAD = 8
|
||
SHEETS = "BUD_*,BUDL00_*,PEG_*,MAC_*,SCROBJ*,PANOBJS*,POINTER,CHARSET*,CHAR2,CLIO*,COGS*"
|
||
|
||
|
||
def read_pcx(path):
|
||
"""PCX 8 bits 1 plan compressé RLE → (largeur, hauteur, indices, palette 768 octets)."""
|
||
d = open(path, "rb").read()
|
||
if len(d) < 128 + 769 or d[0] != 10 or d[3] != 8 or d[65] != 1:
|
||
raise ValueError("PCX 8 bits attendu : %s" % path)
|
||
x0, y0, x1, y1 = struct.unpack("<4H", d[4:12])
|
||
w, h = x1 - x0 + 1, y1 - y0 + 1
|
||
bpl = struct.unpack("<H", d[66:68])[0]
|
||
out, i, need = bytearray(), 128, bpl * h
|
||
while len(out) < need and i < len(d) - 769:
|
||
b = d[i]
|
||
i += 1
|
||
if b >= 0xC0:
|
||
out += bytes([d[i]]) * (b & 0x3F)
|
||
i += 1
|
||
else:
|
||
out.append(b)
|
||
out = out[:need].ljust(need, b"\0")
|
||
pix = b"".join(bytes(out[y * bpl:y * bpl + w]) for y in range(h))
|
||
if d[-769] != 12:
|
||
raise ValueError("palette absente : %s" % path)
|
||
return w, h, pix, d[-768:]
|
||
|
||
|
||
def read_spr(path):
|
||
"""Fichier SPR → [(largeur, hauteur, indices)] ; image : en-tête de 12 octets (u16 largeur, hauteur, …)
|
||
puis RLE : octet non nul = pixel, 00 n = n pixels transparents (lecture de la routine du jeu)."""
|
||
d = open(path, "rb").read()
|
||
n = struct.unpack_from("<I", d, 0)[0]
|
||
if n == 0 or 4 + 4 * n > len(d):
|
||
raise ValueError("SPR invalide : %s" % path)
|
||
out = []
|
||
for k in range(n):
|
||
o = struct.unpack_from("<I", d, 4 + 4 * k)[0]
|
||
w, h = struct.unpack_from("<2H", d, o)
|
||
total, i, px = w * h, o + 12, bytearray()
|
||
while len(px) < total and i < len(d):
|
||
b = d[i]
|
||
i += 1
|
||
if b:
|
||
px.append(b)
|
||
else:
|
||
run = d[i] if i < len(d) else 0
|
||
i += 1
|
||
px += bytes(min(run, total - len(px)))
|
||
out.append((w, h, bytes(px.ljust(total, b"\0"))))
|
||
return out
|
||
|
||
|
||
def layout(sizes):
|
||
"""Images (largeur, hauteur) → [(page, x, y)], [(largeur, hauteur) par page]. Comme make_layout()."""
|
||
total_w = SPR_PAD + sum(w + SPR_PAD for w, _ in sizes)
|
||
pw = min(total_w, SPR_PAGE_W)
|
||
page, x, y, rowh, lay, pages = 0, SPR_PAD, SPR_PAD, 0, [], []
|
||
for w, h in sizes:
|
||
if x + w + SPR_PAD > pw and x > SPR_PAD:
|
||
x, y, rowh = SPR_PAD, y + rowh + SPR_PAD, 0
|
||
if y + h + SPR_PAD > SPR_PAGE_H and y > SPR_PAD:
|
||
pages.append((pw, y + rowh + SPR_PAD))
|
||
page, x, y, rowh = page + 1, SPR_PAD, SPR_PAD, 0
|
||
lay.append((page, x, y))
|
||
x += w + SPR_PAD
|
||
rowh = max(rowh, h)
|
||
pages.append((pw, y + rowh + SPR_PAD))
|
||
return lay, pages
|
||
|
||
|
||
def find_file(folder, name):
|
||
"""Nom de fichier du jeu, casse indifférente ; None si absent."""
|
||
want = name.upper()
|
||
for f in os.listdir(folder):
|
||
if f.upper() == want:
|
||
return os.path.join(folder, f)
|
||
return None
|
||
|
||
|
||
_pals = {}
|
||
|
||
|
||
def pcx_palette(game, name):
|
||
if name not in _pals:
|
||
p = find_file(game, name + ".PCX")
|
||
_pals[name] = read_pcx(p)[3] if p else None
|
||
return _pals[name]
|
||
|
||
|
||
def palette_for(game, name):
|
||
"""Palette d'un fichier SPR : décor de la pièce indiquée par le nom (A01_02 -> LOC01, LOC03A si LOC03
|
||
n'existe pas), PARTONE/PARTTWO/PARTTHR -> PT1BAK/PT2BAK/PT3BAK, sinon LOC01. Comme spr_palette() de
|
||
runtime/sprites.c, qui compare les couleurs affichées à celles-ci (fondus)."""
|
||
special = {"PARTONE": "PT1BAK", "PARTTWO": "PT2BAK", "PARTTHR": "PT3BAK"}
|
||
if name in special:
|
||
return pcx_palette(game, special[name])
|
||
m = re.search(r"\d", name)
|
||
if not m or not name[m.start():m.start() + 2].isdigit():
|
||
return pcx_palette(game, "LOC01")
|
||
room = "LOC" + name[m.start():m.start() + 2]
|
||
return pcx_palette(game, room) or pcx_palette(game, room + "A")
|
||
|
||
|
||
def scale2x(w, h, px):
|
||
"""Scale2x (EPX) sur une liste de couleurs : chaque pixel devient 2×2 selon ses voisins."""
|
||
out = [0] * (4 * w * h)
|
||
W = 2 * w
|
||
for y in range(h):
|
||
row, up, dn = y * w, max(y - 1, 0) * w, min(y + 1, h - 1) * w
|
||
for x in range(w):
|
||
p = px[row + x]
|
||
a = px[up + x]
|
||
b = px[row + min(x + 1, w - 1)]
|
||
c = px[row + max(x - 1, 0)]
|
||
d = px[dn + x]
|
||
e0 = e1 = e2 = e3 = p
|
||
if c == a and c != d and a != b: e0 = a
|
||
if a == b and a != c and b != d: e1 = b
|
||
if d == c and d != b and c != a: e2 = c
|
||
if b == d and b != a and d != c: e3 = d
|
||
o = 2 * y * W + 2 * x
|
||
out[o], out[o + 1], out[o + W], out[o + W + 1] = e0, e1, e2, e3
|
||
return 2 * w, 2 * h, out
|
||
|
||
|
||
def write_png(path, w, h, data, alpha=False):
|
||
"""data : RVB (3 octets par pixel) ou RVBA si alpha."""
|
||
raw = bytearray()
|
||
stride = (4 if alpha else 3) * w
|
||
for y in range(h):
|
||
raw.append(0)
|
||
raw += data[y * stride:(y + 1) * stride]
|
||
|
||
def chunk(tag, payload):
|
||
c = tag + payload
|
||
return struct.pack(">I", len(payload)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
|
||
|
||
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6 if alpha else 2, 0, 0, 0))
|
||
png += chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b"")
|
||
with open(path, "wb") as f:
|
||
f.write(png)
|
||
|
||
|
||
def rgba_image(np, idx, pal):
|
||
"""Indices (h, w) → RVBA, indice 0 transparent, couleur des pixels transparents prolongée depuis les
|
||
pixels opaques voisins (12 passes) pour qu'un agrandissement ne fasse pas de liseré sombre."""
|
||
p = np.frombuffer(pal, dtype=np.uint8).reshape(256, 3).astype(np.float32)
|
||
col = p[idx]
|
||
filled = idx != 0
|
||
for _ in range(12):
|
||
if filled.all():
|
||
break
|
||
acc = np.zeros_like(col)
|
||
cnt = np.zeros(idx.shape, dtype=np.float32)
|
||
f = filled.astype(np.float32)
|
||
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)):
|
||
src = (slice(max(dy, 0), idx.shape[0] + min(dy, 0)), slice(max(dx, 0), idx.shape[1] + min(dx, 0)))
|
||
dst = (slice(max(-dy, 0), idx.shape[0] + min(-dy, 0)), slice(max(-dx, 0), idx.shape[1] + min(-dx, 0)))
|
||
acc[dst] += col[src] * f[src][..., None]
|
||
cnt[dst] += f[src]
|
||
new = (~filled) & (cnt > 0)
|
||
col[new] = acc[new] / cnt[new][..., None]
|
||
filled = filled | new
|
||
out = np.zeros(idx.shape + (4,), dtype=np.uint8)
|
||
out[..., :3] = np.clip(col + 0.5, 0, 255).astype(np.uint8)
|
||
out[..., 3] = np.where(idx != 0, 255, 0)
|
||
return out
|
||
|
||
|
||
def upscale_indices(np, idx, scale):
|
||
if scale == 1:
|
||
return idx
|
||
h, w = idx.shape
|
||
px = idx.reshape(-1).tolist()
|
||
s = 1
|
||
while s < scale:
|
||
w, h, px = scale2x(w, h, px)
|
||
s *= 2
|
||
return np.array(px, dtype=np.uint8).reshape(h, w)
|
||
|
||
|
||
def export_sprites(np, game, out, motif, scale):
|
||
folder = find_file(game, "SPRITES")
|
||
if not folder:
|
||
sys.exit("dossier SPRITES introuvable dans %s" % game)
|
||
pats = [m.strip().upper() for m in motif.split(",")]
|
||
names = sorted(f for f in os.listdir(folder) if f.upper().endswith(".SPR")
|
||
and any(fnmatch.fnmatch(f.upper()[:-4], p) or fnmatch.fnmatch(f.upper(), p) for p in pats))
|
||
os.makedirs(os.path.join(out, "SPRITES"), exist_ok=True)
|
||
n_img = 0
|
||
for f in names:
|
||
name = f.upper()[:-4]
|
||
frames = read_spr(os.path.join(folder, f))
|
||
pal = palette_for(game, name)
|
||
if pal is None:
|
||
print("%s : pas de palette, ignoré" % f)
|
||
continue
|
||
lay, pages = layout([(w, h) for w, h, _ in frames])
|
||
atlas = [np.zeros((ph, pw), dtype=np.uint8) for pw, ph in pages]
|
||
for (w, h, px), (pg, x, y) in zip(frames, lay):
|
||
if w and h:
|
||
atlas[pg][y:y + h, x:x + w] = np.frombuffer(px, dtype=np.uint8).reshape(h, w)
|
||
for pg, idx in enumerate(atlas):
|
||
img = rgba_image(np, upscale_indices(np, idx, scale), pal)
|
||
path = os.path.join(out, "SPRITES", name + ("_P%d" % pg if pg else "") + ".png")
|
||
write_png(path, img.shape[1], img.shape[0], img.tobytes(), alpha=True)
|
||
n_img += 1
|
||
print("%s : %d image(s), %d planche(s)" % (f, len(frames), len(pages)))
|
||
return n_img
|
||
|
||
|
||
def export_sheets(np, game, out, motif, scale):
|
||
pats = [m.strip().upper() for m in motif.split(",")]
|
||
names = sorted(f for f in os.listdir(game) if f.upper().endswith(".PCX")
|
||
and any(fnmatch.fnmatch(f.upper()[:-4], p) for p in pats))
|
||
os.makedirs(os.path.join(out, "SHEETS"), exist_ok=True)
|
||
for f in names:
|
||
w, h, pix, pal = read_pcx(os.path.join(game, f))
|
||
if (w, h) != (320, 200):
|
||
print("%s ignoré (%d×%d)" % (f, w, h))
|
||
continue
|
||
idx = upscale_indices(np, np.frombuffer(pix, dtype=np.uint8).reshape(h, w), scale)
|
||
img = rgba_image(np, idx, pal)
|
||
write_png(os.path.join(out, "SHEETS", f.upper()[:-4] + ".png"), img.shape[1], img.shape[0], img.tobytes(), alpha=True)
|
||
print("%s -> SHEETS" % f)
|
||
return len(names)
|
||
|
||
|
||
def export_backgrounds(game, out, motif, scale):
|
||
names = sorted(n for n in os.listdir(game)
|
||
if n.upper().endswith(".PCX") and fnmatch.fnmatch(n.upper(), motif.upper() + ("" if motif.upper().endswith(".PCX") else ".PCX")))
|
||
if not names:
|
||
sys.exit("aucun PCX ne correspond à %s dans %s" % (motif, game))
|
||
for n in names:
|
||
w, h, pix, pal = read_pcx(os.path.join(game, n))
|
||
if (w, h) != (320, 200):
|
||
print("%s ignoré (%d×%d, pas un décor plein écran)" % (n, w, h))
|
||
continue
|
||
px = list(pix)
|
||
s = 1
|
||
while s < scale:
|
||
w, h, px = scale2x(w, h, px)
|
||
s *= 2
|
||
rgb = bytearray(3 * w * h)
|
||
for i, c in enumerate(px):
|
||
rgb[3 * i:3 * i + 3] = pal[3 * c:3 * c + 3]
|
||
path = os.path.join(out, os.path.splitext(n)[0].upper() + ".png")
|
||
write_png(path, w, h, rgb)
|
||
print("%s -> %s (%d×%d)" % (n, path, w, h))
|
||
|
||
|
||
def find_upscayl(explicit):
|
||
"""upscayl-bin.exe : option, variable UPSCAYL_BIN, puis emplacements d'installation habituels."""
|
||
cands = [explicit, os.environ.get("UPSCAYL_BIN")]
|
||
for base in (os.environ.get("ProgramFiles"), os.environ.get("ProgramFiles(x86)"),
|
||
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs")):
|
||
if base:
|
||
cands.append(os.path.join(base, "Upscayl", "resources", "bin", "upscayl-bin.exe"))
|
||
cands += ["/opt/Upscayl/resources/bin/upscayl-bin", "/Applications/Upscayl.app/Contents/Resources/bin/upscayl-bin",
|
||
shutil.which("upscayl-bin") or ""]
|
||
for c in cands:
|
||
if c and os.path.isfile(c):
|
||
return c
|
||
return None
|
||
|
||
|
||
def run_upscayl(upscayl, models, model, src, dst):
|
||
"""Upscayl ne parcourt pas les sous-dossiers : un appel par dossier."""
|
||
pngs = [f for f in os.listdir(src) if f.lower().endswith(".png")]
|
||
if not pngs:
|
||
return 0
|
||
os.makedirs(dst, exist_ok=True)
|
||
print("Upscayl (%s) : %d image(s) %s -> %s" % (model, len(pngs), src, dst))
|
||
r = subprocess.run([upscayl, "-i", src, "-o", dst, "-m", models, "-n", model, "-s", "4", "-f", "png"],
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="replace")
|
||
if r.returncode != 0:
|
||
sys.exit("Upscayl a échoué :\n" + r.stderr[-2000:])
|
||
return len(pngs)
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||
ap.add_argument("jeu")
|
||
ap.add_argument("sortie")
|
||
ap.add_argument("--motif", default="LOC*")
|
||
ap.add_argument("--echelle", type=int, choices=(1, 2, 4), default=1)
|
||
ap.add_argument("--sprites", nargs="?", const="*", metavar="MOTIF")
|
||
ap.add_argument("--planches", nargs="?", const=SHEETS, metavar="MOTIF")
|
||
ap.add_argument("--sans-decors", action="store_true")
|
||
ap.add_argument("--upscayl", nargs="?", const="digital-art-4x", metavar="MODELE")
|
||
ap.add_argument("--upscayl-bin")
|
||
a = ap.parse_args()
|
||
try:
|
||
sys.stdout.reconfigure(errors="replace")
|
||
except AttributeError:
|
||
pass
|
||
np = None
|
||
if a.sprites or a.planches:
|
||
try:
|
||
import numpy as np
|
||
except ImportError:
|
||
sys.exit("--sprites et --planches demandent numpy (pip install numpy)")
|
||
upscayl = models = None
|
||
if a.upscayl:
|
||
upscayl = find_upscayl(a.upscayl_bin)
|
||
if not upscayl:
|
||
sys.exit("Upscayl introuvable : indiquez --upscayl-bin CHEMIN (upscayl-bin.exe)")
|
||
models = os.path.join(os.path.dirname(os.path.dirname(upscayl)), "models")
|
||
if not os.path.isfile(os.path.join(models, a.upscayl + ".param")):
|
||
dispo = sorted(f[:-6] for f in os.listdir(models) if f.endswith(".param")) if os.path.isdir(models) else []
|
||
sys.exit("modèle Upscayl inconnu : %s (disponibles : %s)" % (a.upscayl, ", ".join(dispo) or "aucun"))
|
||
a.echelle = 1
|
||
final = a.sortie
|
||
if upscayl:
|
||
a.sortie = tempfile.mkdtemp(prefix="hd_export_")
|
||
os.makedirs(a.sortie, exist_ok=True)
|
||
if not a.sans_decors:
|
||
export_backgrounds(a.jeu, a.sortie, a.motif, a.echelle)
|
||
if a.sprites:
|
||
export_sprites(np, a.jeu, a.sortie, a.sprites, a.echelle)
|
||
if a.planches:
|
||
export_sheets(np, a.jeu, a.sortie, a.planches, a.echelle)
|
||
if upscayl:
|
||
n = 0
|
||
for sub in ("", "SPRITES", "SHEETS"):
|
||
src = os.path.join(a.sortie, sub)
|
||
if os.path.isdir(src):
|
||
n += run_upscayl(upscayl, models, a.upscayl, src, os.path.join(final, sub))
|
||
shutil.rmtree(a.sortie, ignore_errors=True)
|
||
print("%d image(s) HD dans %s" % (n, final))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|