Basis 1920x1080 mit Kachel 96 (Phase 0.5): Assets, Daten-ids, Engine, Theme und Pruefungen umgestellt; alte 32-px-Master im Archiv. Boden, Dach und Haus gezeichnet statt generiert (boden.py, dach.py) — FLUX-Kacheln hatten nach --flatten nur zwei Farben. Schrift neu in Zielaufloesung (font16.py, 12x16 entworfen, x2 exportiert, proportionaler Vorschub). Zwei Register: gemaltes Ortsbild mit Hotspots und Kachelgebiet mit gemalten Figuren, verbunden ueber einen ScreenManager. Die Schleife ist ohne Fenster geprueft (tools/probe_schleife.tscn). Dokumentation: darstellung.md (Regeln), stand.md (Uebergabe), Beweise unter art/prep/ (terrain-96, kacheltest, stadt-gemalt, schleife, stil-vergleich).
204 lines
8.4 KiB
Python
204 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""font_export.py - 8x10-Pixelsatz als Engine-Font (BMFont + Textur-Atlas).
|
|
|
|
`font8.py` haelt den Satz als Python-Daten; Godot braucht eine Datei. Dieses
|
|
Werkzeug schreibt beides in `final/Font/`:
|
|
|
|
font8_10_atlas.png Textur, Glyphen weiss auf transparent (1x)
|
|
font8_10.fnt BMFont-Textformat, Zeigt auf die 1x-Textur
|
|
font8_10_2x.fnt dasselbe in 2x (eigene Textur, eigene Metriken)
|
|
font8_10_atlas_2x.png
|
|
font8_10_3x.fnt 3x-Fassung fuer die 1920x1080-Basis (Vorschub 24,
|
|
font8_10_atlas_3x.png Zeile 36)
|
|
|
|
python3 tools/font_export.py # schreiben + pruefen
|
|
python3 tools/font_export.py --check # nur pruefen
|
|
|
|
Metriken (1x): Zelle 8x10, Vorschub 8, Zeile 12, Basislinie 8. In der 2x-Fassung
|
|
sind alle Werte verdoppelt; das Bild ist nearest-skaliert, also pixelgleich.
|
|
|
|
**Pruefung ohne Godot:** `--check` liest die geschriebene .fnt mit einem eigenen
|
|
Parser, setzt daraus Text zusammen und vergleicht das Ergebnis Pixel fuer Pixel
|
|
mit `font8.draw_text`. Weicht etwas ab, ist die Datei falsch — nicht erst in
|
|
der Engine.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from PIL import Image, ImageDraw
|
|
|
|
ART = Path(__file__).resolve().parent.parent
|
|
BASIS = "font8_10"
|
|
sys.path.insert(0, str(ART / "tools"))
|
|
import importlib # noqa: E402
|
|
|
|
# Skalen, die exportiert und geprueft werden. Seit 15.11.2026 auch 3x, weil die
|
|
# Basisaufloesung auf 1920x1080 gewachsen ist (docs/roadmap.md, Raster-Entscheid).
|
|
SKALEN = (1, 2, 3)
|
|
|
|
font8 = importlib.import_module("font8") # Standard; --font waehlt anders
|
|
ZELLE_W = font8.ZELLE_W
|
|
ZELLE_H = font8.ZELLE_H
|
|
RAND = (font8.ZELLE_W - font8.COLS) // 2 # linker Vorlauf in der Zelle
|
|
SPALTEN = 16 # Glyphen pro Atlas-Zeile
|
|
|
|
|
|
def atlas(scale: int = 1) -> tuple[Image.Image, dict[str, tuple[int, int]]]:
|
|
"""Glyphenraster bauen; liefert Bild und Position je Zeichen."""
|
|
zeichen = sorted(font8.GLYPHS)
|
|
zeilen = (len(zeichen) + SPALTEN - 1) // SPALTEN
|
|
im = Image.new("RGBA", (SPALTEN * ZELLE_W, zeilen * ZELLE_H), (0, 0, 0, 0))
|
|
px = im.load()
|
|
pos: dict[str, tuple[int, int]] = {}
|
|
for i, ch in enumerate(zeichen):
|
|
gx, gy = (i % SPALTEN) * ZELLE_W, (i // SPALTEN) * ZELLE_H
|
|
pos[ch] = (gx, gy)
|
|
for row, zeile in enumerate(font8.GLYPHS[ch].split("/")):
|
|
for col, p in enumerate(zeile):
|
|
if p == "#":
|
|
px[gx + col + RAND, gy + row] = (255, 255, 255, 255)
|
|
if scale > 1:
|
|
im = im.resize((im.width * scale, im.height * scale), Image.NEAREST)
|
|
return im, pos
|
|
|
|
|
|
def fnt(scale: int, bild: str) -> str:
|
|
"""BMFont-Textformat (angelcode). Alle Masse in Pixeln dieser Fassung."""
|
|
zeichen = sorted(font8.GLYPHS)
|
|
s = scale
|
|
zeilen = [
|
|
f'info face="taloria8" size={font8.ROWS * s} bold=0 italic=0 charset="" '
|
|
f"unicode=1 stretchH=100 smooth=0 aa=1 padding=0,0,0,0 spacing=0,0 outline=0",
|
|
f"common lineHeight={font8.LINE * s} base={font8.BASE * s} scaleW={SPALTEN * ZELLE_W * s} "
|
|
f"scaleH={(len(zeichen) + SPALTEN - 1) // SPALTEN * ZELLE_H * s} pages=1 "
|
|
f"packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4",
|
|
f'page id=0 file="{bild}"',
|
|
f"chars count={len(zeichen)}",
|
|
]
|
|
for i, ch in enumerate(zeichen):
|
|
gx, gy = (i % SPALTEN) * ZELLE_W * s, (i // SPALTEN) * ZELLE_H * s
|
|
if hasattr(font8, "masse"):
|
|
versatz, vorschub = font8.masse(ch)
|
|
else:
|
|
versatz, vorschub = 0, font8.ADVANCE
|
|
zeilen.append(
|
|
f"char id={ord(ch)} x={gx} y={gy} width={ZELLE_W * s} height={ZELLE_H * s} "
|
|
f"xoffset={versatz * s} yoffset=0 xadvance={vorschub * s} page=0 chnl=15")
|
|
return "\n".join(zeilen) + "\n"
|
|
|
|
|
|
def lies_fnt(pfad: Path) -> dict:
|
|
"""Minimaler BMFont-Leser (nur was zum Pruefen gebraucht wird)."""
|
|
text = pfad.read_text()
|
|
m = re.search(r"lineHeight=(\d+) base=(\d+)", text)
|
|
kopf = {"lineHeight": int(m.group(1)), "base": int(m.group(2))}
|
|
chars = {}
|
|
for zeile in text.splitlines():
|
|
if not zeile.startswith("char id="):
|
|
continue
|
|
f = dict(re.findall(r"(\w+)=(-?\d+)", zeile))
|
|
chars[chr(int(f["id"]))] = {k: int(v) for k, v in f.items()}
|
|
seite = re.search(r'page id=0 file="([^"]+)"', text).group(1)
|
|
return {"kopf": kopf, "chars": chars, "seite": seite, "dir": pfad.parent}
|
|
|
|
|
|
def setze(text: str, f: dict, breite: int, hoehe: int) -> Image.Image:
|
|
"""Text nur mit den .fnt-Metriken setzen (kein font8, kein ui)."""
|
|
bild = Image.open(f["dir"] / f["seite"]).convert("RGBA")
|
|
im = Image.new("RGBA", (breite, hoehe), (0, 0, 0, 0))
|
|
x = y = 0
|
|
for ch in text:
|
|
if ch == "\n":
|
|
x, y = 0, y + f["kopf"]["lineHeight"]
|
|
continue
|
|
c = f["chars"].get(ch) or f["chars"]["?"]
|
|
teil = bild.crop((c["x"], c["y"], c["x"] + c["width"], c["y"] + c["height"]))
|
|
im.alpha_composite(teil, (x + c["xoffset"], y + c["yoffset"]))
|
|
x += c["xadvance"]
|
|
return im
|
|
|
|
|
|
def alle_zeichen(pro_zeile: int = 40) -> list[str]:
|
|
"""Alle Glyphen des Satzes, in Zeilen umbrochen — fuer die Vollpruefung."""
|
|
zs = sorted(font8.GLYPHS)
|
|
return ["".join(zs[i:i + pro_zeile]) for i in range(0, len(zs), pro_zeile)]
|
|
|
|
|
|
def pruefen(out: Path, skalierung: int = 1) -> list[str]:
|
|
probe = alle_zeichen()
|
|
name = f"{BASIS}{'' if skalierung == 1 else f'_{skalierung}x'}.fnt"
|
|
f = lies_fnt(out / name)
|
|
|
|
breite = max(font8.text_width(t) for t in probe) + 8
|
|
hoehe = len(probe) * font8.LINE
|
|
klein = Image.new("RGBA", (breite, hoehe), (0, 0, 0, 0))
|
|
d = ImageDraw.Draw(klein)
|
|
for i, zeile in enumerate(probe):
|
|
font8.draw_text(d, 0, i * font8.LINE, zeile, (255, 255, 255, 255))
|
|
soll = (klein if skalierung == 1 else
|
|
klein.resize((breite * skalierung, hoehe * skalierung), Image.NEAREST))
|
|
|
|
ist = setze("\n".join(probe), f, soll.width, soll.height)
|
|
return [] if ist.tobytes() == soll.tobytes() else [
|
|
f"{name}: gesetzter Text weicht von font8.draw_text ab"]
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
ap.add_argument("--check", action="store_true", help="nur pruefen")
|
|
ap.add_argument("--out", type=Path, default=ART / "final" / "Font")
|
|
ap.add_argument("--font", default="font8", choices=["font8", "font12", "font16"])
|
|
ap.add_argument("--scale", type=int, default=0, help="0 = alle (font8: 1/2/3)")
|
|
a = ap.parse_args(argv)
|
|
global font8, BASIS, ZELLE_W, ZELLE_H, RAND
|
|
font8 = importlib.import_module(a.font)
|
|
BASIS = {"font8": "font8_10", "font12": "font12_9", "font16": "font16_12"}[a.font]
|
|
ZELLE_W, ZELLE_H = font8.ZELLE_W, font8.ZELLE_H
|
|
RAND = (font8.ZELLE_W - font8.COLS) // 2
|
|
global SKALEN
|
|
SKALEN = (a.scale,) if a.scale else {"font8": (1, 2, 3), "font12": (6,), "font16": (2,)}[a.font]
|
|
out = a.out
|
|
|
|
if not a.check:
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
for s in SKALEN:
|
|
bild, _ = atlas(s)
|
|
endung = "" if s == 1 else f"_{s}x"
|
|
png = f"{BASIS}_atlas{endung}.png"
|
|
fntname = f"{BASIS}{endung}.fnt"
|
|
bild.save(out / png)
|
|
(out / fntname).write_text(fnt(s, png))
|
|
print(f" {png:26s} {bild.width}x{bild.height}")
|
|
print(f" {fntname:26s} {len(font8.GLYPHS)} Zeichen")
|
|
|
|
# Belegbild: derselbe Satz, aber ueber die .fnt gesetzt (nicht font8)
|
|
f = lies_fnt(out / "font8_10.fnt")
|
|
zeilen = ["Der Ghul greift an. ÄÖÜäöüß",
|
|
"Valyria zahlt 5 % in Ferrum —",
|
|
"Was wollt Ihr in Garana?"]
|
|
w = max(font8.text_width(z) for z in zeilen) + 10
|
|
h = len(zeilen) * font8.LINE + 8
|
|
blatt = Image.new("RGBA", (w, h), (58, 47, 39, 255))
|
|
blatt.alpha_composite(setze("\n".join(zeilen), f, w, h), (5, 4))
|
|
bild_out = ART / "prep" / "font8"
|
|
bild_out.mkdir(parents=True, exist_ok=True)
|
|
blatt.save(bild_out / "_bmfont_probe.png")
|
|
blatt.resize((w * 2, h * 2), Image.NEAREST).save(
|
|
bild_out / "_bmfont_probe_2x.png")
|
|
print(f" {bild_out}/_bmfont_probe.png (aus der .fnt gesetzt)")
|
|
|
|
fehler = []
|
|
for s in SKALEN:
|
|
fehler += pruefen(out, s)
|
|
for f in fehler:
|
|
print(" ", f, file=sys.stderr)
|
|
print("\nPruefung:", "bestanden" if not fehler else "FEHLGESCHLAGEN")
|
|
return 1 if fehler else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|