Files
DoubleTroubleRecomp/tools/hd_export.py
T
linkatplugandClaude Opus 5.5 37acf64362 Mods (remplacement de fichiers) et pack HD des décors
- mods/<nom>/files/ : remplace tout fichier lu par le jeu, sans toucher aux originaux ;
  ordre alphabétique des mods, le dernier l'emporte ; dossiers _x et .x ignorés.
- mods/<nom>/hd/<PCX>.png : décors HD. Le moteur décode le PCX d'origine, le retrouve
  dans l'écran 320×200 (décalage de défilement compris, pièces LOCxxA/B/C/D) et ne
  laisse voir l'image HD que là où le décor d'origine est visible ; personnages,
  objets et panneau restent ceux du jeu. Les fondus de palette suivent.
- Décodeur PNG intégré (inflate inclus), vérifié contre zlib sur tous les formats.
- Rendu : couche HD avec mipmaps sous l'image du jeu (alpha = masque) pour les
  filtres net, lissé et xBR ; le CRT garde l'image d'origine.
- Réglages : [display] hd_pack, [mods] enabled/dir/disabled (valeurs texte, clés
  reconnues par section) ; menu F12 « Décors HD (mods) ».
- Options : --mods DOSSIER, --sans-mods, --sans-hd (session seulement).
- tools/hd_export.py --upscayl : pack HD complet avec Upscayl (Real-ESRGAN).
- docs/MODS.md, docs/SETTINGS.md ; mods/ exclu du dépôt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 03:30:28 +01:00

171 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
r"""Exporte les images PCX 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 (LOC01.png). Voir docs/MODS.md.
python tools/hd_export.py DOSSIER_DU_JEU DOSSIER_SORTIE [--motif LOC*] [--echelle 1|2|4]
[--upscayl [MODELE]] [--upscayl-bin CHEMIN]
--motif noms de fichiers PCX à exporter (défaut : LOC*, les décors des pièces)
--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
Exemple (pack prêt à jouer) :
python tools/hd_export.py ..\extracted\iso\TUCKER mods\hd_upscayl\hd --upscayl
Seules les images plein écran 320×200 servent au pack HD : les autres sont ignorées.
"""
import argparse
import fnmatch
import os
import shutil
import struct
import subprocess
import sys
import tempfile
import zlib
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 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, rgb):
raw = bytearray()
stride = 3 * w
for y in range(h):
raw.append(0)
raw += rgb[y * stride:(y + 1) * stride]
def chunk(tag, data):
c = tag + data
return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 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 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 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("--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
upscayl = 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)
names = sorted(n for n in os.listdir(a.jeu)
if n.upper().endswith(".PCX") and fnmatch.fnmatch(n.upper(), a.motif.upper() + ("" if a.motif.upper().endswith(".PCX") else ".PCX")))
if not names:
sys.exit("aucun PCX ne correspond à %s dans %s" % (a.motif, a.jeu))
for n in names:
w, h, pix, pal = read_pcx(os.path.join(a.jeu, 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 < a.echelle:
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]
out = os.path.join(a.sortie, os.path.splitext(n)[0].upper() + ".png")
write_png(out, w, h, rgb)
print("%s -> %s (%d×%d)" % (n, out, w, h))
if upscayl:
os.makedirs(final, exist_ok=True)
print("Upscayl (%s) : %s -> %s" % (a.upscayl, a.sortie, final))
r = subprocess.run([upscayl, "-i", a.sortie, "-o", final, "-m", models, "-n", a.upscayl, "-s", "4", "-f", "png"],
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="replace")
shutil.rmtree(a.sortie, ignore_errors=True)
if r.returncode != 0:
sys.exit("Upscayl a échoué :\n" + r.stderr[-2000:])
print("%d image(s) HD dans %s" % (len([f for f in os.listdir(final) if f.lower().endswith(".png")]), final))
if __name__ == "__main__":
main()