Repository navigation
Expand file tree
/
Copy pathglyphs.py
More file actions
1378 lines (1223 loc) · 62.7 KB
/
Copy pathglyphs.py
File metadata and controls
1378 lines (1223 loc) · 62.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""glyphs.py — put a new script's glyphs into Episode III's fonts.
Borrowed from Xenosaga1PythonExtractor/glyphs.py (2026-11-20). Kept as is:
``Glyph``, the bitmap helpers, ``GlyphSet`` (keys, json, ``from_png``), the
``TTFRenderer`` (HarfBuzz shaping through uharfbuzz, outlines through
fonttools, the kit's own even-odd scanline rasteriser at 4x supersampling,
averaged to the font's four levels) and the glyph-key scheme ``langpack``
uses (``u:<text>``, ``g:<font>:<gid>``, ``c:<font>:<gid>@dx,dy;...``). What
changed for Episode III:
* fonttools and uharfbuzz are REQUIRED (requirements.txt), not optional;
* the SLOT MODEL is new (``SlotModel``): Episode I had a fixed 256-slot
proportional block and the kanji rows; Episode III's room depends on the
build's addressing (``font.Addressing``: gate, prop_cells, A9 row), on the
cells retail text draws (scanned from the disc, parse-only), and on the
optional executable unlocks below;
* a proportional glyph is drawn twice: its ink-aligned image at cell + 0x240
(what ``$prop1;`` draws, FUN_00185770 measures it with the metric pair of
the base cell) and a centred copy at the base cell (what ``$prop0;`` draws);
* codes are byte strings of 1 or 2 bytes (USA single bytes 0x80-0xFF are
characters of their own).
Slot model, per build (all addressing read from the executable by font.py):
USA / May 2006 prototype (whitelist gate, prop cells < 384, A9 row):
proportional tier cells 0..383 reachable through gate-accepted codes:
A4A1-A4FE -> 192-285; single bytes 0x80-0xFF -> byte + 0x80
= 256-383 (except the bytes that can start a pair: A1 A2 A3
A4 A6 AD); A1/A2/A3 codes below 192 (A1BD/DA/DB/DF/EE,
A2F6, A3B0-B9). Codes flagged 0x1000 (always fixed width:
A1B9, A1BC, A1F9-FC, the A2A0 group) are not slots.
wide tier A6 pairs -> 384..438 (one EUC trail per cell), AD B5-B7 -> 564-566
reserved cell 0 (space), 0x7F (the fallback), the 96 cells of the
``$han`` table, every cell retail text draws (and its
half-size twin, FUN_00181db8), cells 576..959 (the images of
cells 0..383), and the extra-kanji cells 3989+.
Japan (euc gate, prop cells < 192, no A9 row; M22 of the JP brief):
any pair with lead A1..CF and trail A1..FE whose cell the Japanese font
leaves BLANK and retail text does not draw; tier by cell (< 192 prop).
Latin-1, SS2/SS3 (8E/8F) and 0x80-0x9F are not code space on Japan.
Optional unlocks of the USA executable (``UNLOCKS``; data the langpack can
request, NOT tested in game). Each is a list of patch descriptors
(VA, old bytes, new bytes); ``apply_patches`` checks every old word before it
writes anything, and refuses a mismatch:
jp-gate the pair gate FUN_00181e48's first four words become the Japanese
gate (lead >= 0xA0, trail untested). Kanji rows B0-CF reach cells
1024..3988 (2,965 wide cells, ~3,000) and A5 reaches 288-383. Cost:
USA Latin-1 singles 0xA0-0xFF become leads, so all English text
must be re-encoded (``SlotModel.code_for`` gives the new code of
every cell: e.g. e-acute (cell 361) = A5EA instead of E9; cells 382/383
only through a non-EUC trail, e.g. A76F / A640).
jp-prop the two prop-gate immediates 0x180 -> 0xC0 (printer 0x1856e4,
measurer 0x182dd4), as on Japan: cells 192-383 become fixed width
and their metric pairs serve the half-size path only.
jp both.
Usage (``add_commands``)::
glyphs-slots --iso DISC.iso [--unlock jp] [--json slots.json]
glyphs-coverage --iso JP.iso # T7: every EUC pair inked
glyphs-render --iso DISC.iso --ttf F.ttf --text "абв" --out gs.json [--png prev.png]
glyphs-apply --glyphset gs.json --font font0.bin --out new.bin
glyphs-unlock --iso US.iso [--iso US2.iso] --mode jp (--out-exe FILE | --out OUT)
python glyphs.py --self-test
XS1KOR (https://github.com/poketony/XS1KOR), poketony's Korean localisation
of the Japanese Episode I, is the proof the approach works: 2,048 Hangul cells
rendered from a TTF into the kanji area.
"""
from __future__ import annotations
import argparse
import dataclasses
import hashlib
import json
import math
import os
import re
import sys
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import font as fontmod # noqa: E402
import patch # noqa: E402
from font import (CELL_H, CELL_W, CELL_COUNT, EXTRA_KANJI_BASE, FALLBACK_CELL, FIXED_ADVANCE, # noqa: E402
FIXED_FLAG, PROP_CELL_SHIFT, PROP_LIMIT, Addressing, Font, FontError, half_cell)
class GlyphError(ValueError):
pass
# --- bitmaps (unchanged from XS1) ----------------------------------------------
Bitmap = List[List[int]] # CELL_H rows of CELL_W values 0..3
def blank() -> Bitmap:
return [[0] * CELL_W for _ in range(CELL_H)]
def ink_bounds(bm: Bitmap) -> Optional[Tuple[int, int]]:
cols = [x for x in range(CELL_W) if any(row[x] for row in bm)]
return (cols[0], cols[-1]) if cols else None
def shift_x(bm: Bitmap, dx: int) -> Bitmap:
out = blank()
for y in range(CELL_H):
for x in range(CELL_W):
if 0 <= x - dx < CELL_W:
out[y][x] = bm[y][x - dx]
return out
class Glyph:
def __init__(self, key: str, bitmap: Bitmap, advance_hint: Optional[int] = None):
self.key = key
self.bitmap = bitmap
self.bounds = ink_bounds(bitmap)
self.advance_hint = advance_hint # for blank glyphs (spaces)
@property
def ink_width(self) -> int:
return self.bounds[1] - self.bounds[0] + 1 if self.bounds else 0
# --- executable unlocks ------------------------------------------------------------
@dataclass(frozen=True)
class Patch:
va: int
old: bytes
new: bytes
what: str
_SITES = {va: (old, new) for va, old, new in fontmod.UNLOCK_SITES} # font.py holds the words
UNLOCKS: Dict[str, Tuple[Patch, ...]] = {
"jp-gate": (Patch(0x181E48, *_SITES[0x181E48],
"pair gate FUN_00181e48 -> the Japanese four words (lead >= 0xA0)"),),
"jp-prop": (Patch(0x1856E4, *_SITES[0x1856E4], "printer prop gate sltiu v0,s1,0x180 -> 0xC0"),
Patch(0x182DD4, *_SITES[0x182DD4], "measurer prop gate slti v0,a0,0x180 -> 0xC0")),
}
UNLOCK_MODES: Dict[str, Tuple[str, ...]] = {"none": (), "jp-gate": ("jp-gate",), "jp-prop": ("jp-prop",),
"jp": ("jp-gate", "jp-prop")}
# the builds whose code these VAs were read from (the prototype's code sits at the
# retail addresses; checked word for word by apply_patches either way)
UNLOCK_BUILDS = ("us", "proto-2006-05")
def unlock_patches(mode: str) -> List[Patch]:
if mode not in UNLOCK_MODES:
raise GlyphError(f"unknown unlock mode {mode!r}; one of {', '.join(UNLOCK_MODES)}")
return [p for name in UNLOCK_MODES[mode] for p in UNLOCKS[name]]
def apply_patches(exe: bytes, patches: Sequence[Patch]) -> Tuple[bytes, List[str]]:
"""``exe`` with every patch applied. Each site must hold its old bytes (or
already its new bytes: reported, not rewritten); any other content refuses
the whole set before anything is written."""
out = bytearray(exe)
report, todo = [], []
for p in patches:
cur = fontmod.read_va(exe, p.va, len(p.old))
if cur == p.new:
report.append(f"{p.va:#x} already patched ({p.what})")
elif cur == p.old:
todo.append(p)
else:
raise GlyphError(f"{p.va:#x}: expected {p.old.hex()} ({p.what}), found {cur.hex()}: "
f"not a build these patches were made for")
for p in todo:
o = fontmod.va_to_offset(exe, p.va, len(p.new))
out[o:o + len(p.new)] = p.new
report.append(f"{p.va:#x} {p.old.hex()} -> {p.new.hex()} ({p.what})")
return bytes(out), report
def unlocked_addressing(a: Addressing, mode: str) -> Addressing:
"""The addressing the USA executable has after ``mode`` (no executable needed)."""
names = UNLOCK_MODES.get(mode)
if names is None:
raise GlyphError(f"unknown unlock mode {mode!r}")
if names and a.gate != "whitelist":
raise GlyphError(f"unlock {mode!r} is for the USA/prototype executable; this one has the {a.gate} gate")
rep = {}
if "jp-gate" in names:
rep["gate"] = "euc"
if "jp-prop" in names:
rep["prop_cells"] = fontmod.JP_PROP_CELLS
return dataclasses.replace(a, **rep)
def patch_iso(iso_path, mode: str) -> List[str]:
"""Patch the boot executable of an ISO in place (a COPY: this writes; the CLI
does not use it any more, ``glyphs-unlock --out`` goes through
``patch.patch_copy``, which never writes a source image). The
executable's file extent is found through ISO9660; every patch site is
checked first. Returns the report lines."""
from iso9660 import IsoImage
with IsoImage(iso_path) as im:
name = im.boot_elf_name()
f = im.find(name) if name else None
if f is None or f.layer:
raise GlyphError(f"{iso_path}: no first-layer boot executable")
exe = bytes(im.read_file(f.path))
start = f.lba * 2048
try:
prof = fontmod.profile_for(exe)
except FontError:
prof = None
if prof is not None and prof.name not in UNLOCK_BUILDS:
raise GlyphError(f"{iso_path}: the {prof.name} executable needs no unlock (or has other VAs)")
new, report = apply_patches(exe, unlock_patches(mode))
if new != exe:
with open(iso_path, "r+b") as fh:
for i in range(0, len(exe), 4):
if new[i:i + 4] != exe[i:i + 4]:
fh.seek(start + i)
fh.write(new[i:i + 4])
with IsoImage(iso_path) as im:
if bytes(im.read_file(f.path)) != new:
raise GlyphError(f"{iso_path}: re-read of the patched executable differs")
return report
# --- retail text scan (parse-only) ---------------------------------------------------
def _walk_game(a: Addressing, s: bytes, cells: Counter, font_nos=(0, 1)) -> None:
"""The printer's walk: '$' commands and control sequences (with their operand
lengths) are stepped over; characters from 0x80 up give cells."""
i, n = 0, len(s)
while i < n:
b = s[i]
if b == 0x24:
try:
i = a.command_at(s, i)[2]
continue
except FontError:
i += 1
continue
if b < 0x20:
try:
i += max(1, a.control_length(s, i))
except (FontError, IndexError):
i += 1
continue
if b < 0x80:
i += 1
continue
g = None
for k in font_nos:
g = a.glyph(s, i, True, k)
cells[fontmod.cell_index(g.cell)] += 1
i += g.length
def _walk_plain(a: Addressing, s: bytes, cells: Counter, font_nos=(0, 1)) -> None:
"""Every byte below 0x80 is one byte (no operand skipping): for whole text
files, and as a second, desync-proof pass over parsed strings."""
i, n = 0, len(s)
while i < n:
if s[i] < 0x80:
i += 1
continue
g = None
for k in font_nos:
g = a.glyph(s, i, True, k)
cells[fontmod.cell_index(g.cell)] += 1
i += g.length
def _text_runs(data: bytes, min_len: int = 2) -> Iterable[bytes]:
for run in data.split(b"\0"):
if len(run) >= min_len and all(c >= 0x20 or c in (9, 10, 13) for c in run):
yield run
_LETTERS = re.compile(rb"[A-Za-z]{2}")
def plausible(run: bytes, gate: str) -> bool:
"""Is a NUL-delimited run from a binary file (batdat.bin, Message.Dat, the
executable, the overlays) text? USA: 4+ bytes, 75% printable ASCII, two
letters in a row (keeps 'Ω Universitas', 'Press <○>' and drops code bytes).
Japan: a strict EUC-JP (+NEC row 13) reading with 2+ kana/kanji."""
if gate == "euc":
if len(run) < 4 or not any(c >= 0xA1 for c in run):
return False
try:
t = run.decode("euc_jis_2004")
except UnicodeDecodeError:
return False
return sum(0x3040 <= ord(ch) <= 0x9FFF or 0xFF00 <= ord(ch) <= 0xFFEF for ch in t) >= 2
pr = sum(0x20 <= c < 0x7F for c in run)
return len(run) >= 4 and pr >= 0.75 * len(run) and bool(_LETTERS.search(run))
def _disc_paths(d) -> List[str]:
return [e.path for _c, e in d.entries()]
def text_sources(paths: Iterable[str], lang: str) -> List[Tuple[str, str]]:
"""(path, kind) of every text file the scan reads: kinds sb, txd, nj, file
(whole-file subtitles / pse messages), raw (batdat.bin, Message.Dat: text
runs). The executable and overlays (kind exe) are added by ``scan_retail``."""
import njbin
nj = {n.lower() for n in njbin.NAMES}
out = []
for p in paths:
low = p.replace("/", "\\").lstrip("\\").lower()
parts = low.split("\\")
if low.endswith(".sb") and len(parts) == 3 and parts[0] in ("cf", "bat") and parts[1] == lang:
out.append((p, "sb"))
elif parts[:2] == ["mnu", lang] and len(parts) == 3 and low.endswith(".txd"):
out.append((p, "txd"))
elif parts[:2] == ["mnu", lang] and len(parts) == 3 and parts[2] in nj:
out.append((p, "nj"))
elif parts[0] in ("mov", "evt") and len(parts) >= 3 and parts[1] == lang and low.endswith(".txt"):
out.append((p, "file"))
elif parts[:3] == ["mnu", "pse", lang] and low.endswith(".mes"):
out.append((p, "file"))
elif low in (f"bat\\{lang}\\batdat.bin", f"mg1\\{lang}\\message.dat"):
out.append((p, "raw"))
return sorted(out, key=lambda x: x[0].lower())
def scan_strings(read, sources: Sequence[Tuple[str, str]], gate: str,
region=None) -> Iterable[Tuple[str, str, bytes, str]]:
"""(path, kind, string, category) for every string of ``sources`` that the
game may draw. category "text", or on the USA gate "untranslated": Japanese
left in the USA build (.sb placeholder lines, the euc_jp .mes files AC / PP /
opening / test, the prototype's EUC DBC2) that the USA printer would draw as
Latin-1/hiragana soup. USA .sb developer notes (never drawn) and identifiers
are skipped; on Japan every non-identifier string is text."""
import njbin
import sb
import subtitle
import textcodec
us = gate == "whitelist"
for p, kind in sources:
data = read(p)
if kind == "sb":
for s in sb.parse(data).strings:
role = sb.classify(s)
if role == "identifier" or (us and role == "note"):
continue
yield p, kind, s, "untranslated" if us and role == "untranslated" else "text"
elif kind == "txd":
import txd
for s in txd.parse(data).strings:
yield p, kind, s, "text"
elif kind == "nj":
for b in njbin.parse(data).blobs:
for s in b.strings:
yield p, kind, s, "untranslated" if us and textcodec.NoteCodec.pick_euc(s) else "text"
elif kind == "file":
jp_mes = us and subtitle.codec_name("\\" + p.lstrip("\\"), data) not in ("us",)
yield p, kind, data, "untranslated" if jp_mes else "text"
else:
for s in _text_runs(data):
if plausible(s, gate):
yield p, kind, s, "text"
# plus every item the text pipeline (msgdat / batdat parse, textpack,
# langpack) treats as display text. The plausible-run filter alone
# misses USA Message.Dat #0587 / #0589 (prototype #0586 / #0588): the
# hiragana table of the HaKox password input ("The password function
# was abolished", #0588). Those are EUC Japanese that the USA printer
# draws as A4-row soup, so on the USA gate they count as
# "untranslated" like the mnu .bin EUC strings (reserved only with
# include_untranslated), not silently as free cells.
if region is not None:
import batdat
import msgdat
mod = msgdat if p.lower().endswith("message.dat") else batdat
for it in mod.parse(data, region).items:
if it.codec in ("us", "jp") and it.role not in ("note", "identifier", "untranslated"):
jp_left = us and textcodec.NoteCodec.pick_euc(it.raw)
yield p, kind, it.raw, "untranslated" if jp_left else "text"
@dataclass
class RetailScan:
cells: Counter # cell -> hits, category "text"
untranslated: Counter # cell -> hits, category "untranslated" (USA only)
files: Counter # kind -> files read
strings: Counter # kind -> strings walked
lang: str = "us"
def reserved(self, include_untranslated: bool = False) -> Set[int]:
return set(self.cells) | (set(self.untranslated) if include_untranslated else set())
def to_json(self) -> dict:
return {"lang": self.lang, "files": dict(self.files), "strings": dict(self.strings),
"cells": {str(k): v for k, v in sorted(self.cells.items())},
"untranslated_cells": {str(k): v for k, v in sorted(self.untranslated.items())}}
def scan_retail(d, a: Addressing, lang: Optional[str] = None, exe: bool = True) -> RetailScan:
"""Every cell the retail text of disc ``d`` (a ``disc.Disc``) draws under the
build's own addressing ``a``: .sb / .txd / mnu .bin strings (parsed), the
subtitle and .mes files, plausible text runs of batdat.bin and Message.Dat,
and (``exe``) of the boot executable and the root overlays OV*.OVL. Parsed
strings are walked twice (the printer's walk and a plain byte walk) and the
union kept, so a misread operand can only over-reserve."""
lang = lang or a.font_dir
sources = text_sources(_disc_paths(d), lang)
cells, untr, files, strings = Counter(), Counter(), Counter(), Counter()
for p, kind in sources:
files[kind] += 1
import region as _region
items = list(scan_strings(d.read, sources, a.gate, _region.detect(d)))
if exe:
iso = d.iso
names = [n for n, f in iso.files.items() if "\\" not in n and not f.is_dir
and (n == iso.boot_elf_name() or re.match(r"(?i)^OV\d\d\.OVL$", n))]
for n in sorted(names):
files["exe"] += 1
data = bytes(iso.read_file(n))
items += [(n, "exe", s, "text") for s in _text_runs(data) if plausible(s, a.gate)]
for p, kind, s, cat in items:
strings[kind] += 1
tgt = cells if cat == "text" else untr
if kind in ("file", "raw", "exe"):
_walk_plain(a, s, tgt)
else:
_walk_game(a, s, tgt)
_walk_plain(a, s, tgt)
return RetailScan(cells, untr, files, strings, lang)
# --- slot model ---------------------------------------------------------------------
PROP_IMAGES = range(PROP_CELL_SHIFT, PROP_CELL_SHIFT + PROP_LIMIT) # 576..959
def reachable(a: Addressing, font_no: int = 0, flagged: bool = False) -> Dict[int, bytes]:
"""cell -> the shortest (then lowest) code that draws it under ``a``. Pairs use
EUC trails A1..FE only; leads from 0xD0 (the extra-kanji lists) and fallback
results are left out. 0x1000-flagged codes (always fixed width) are left out
unless ``flagged``, and then only fill cells no other code reaches, as do
pairs with a printable non-EUC trail (the euc gate does not test the trail);
``flagged`` is the re-encoding table, never the slot list."""
out: Dict[int, bytes] = {}
late: Dict[int, bytes] = {}
if a.a9_row:
for b in range(0x80, 0x100):
if any(a.pair(b, t) for t in range(1, 0x100)):
continue # may start a pair: not a safe single
c = a.glyph(bytes((b,)), 0, True, font_no).cell
if c != FALLBACK_CELL:
(late if c & FIXED_FLAG else out).setdefault(fontmod.cell_index(c), bytes((b,)))
for lead in range(0xA1, 0xD0):
for trail in range(0xA1, 0xFF):
if not a.pair(lead, trail):
continue
c = a.cell(lead, trail, font_no)
if c == FALLBACK_CELL:
continue
(late if c & FIXED_FLAG else out).setdefault(fontmod.cell_index(c), bytes((lead, trail)))
if flagged:
for c, code in late.items():
out.setdefault(c, code)
# last resort for re-encoding only: printable non-EUC trails (not '$', '\\')
for lead in range(0xA1, 0xD0):
for trail in range(0x21, 0xA1):
if trail in (0x24, 0x5C) or not a.pair(lead, trail):
continue
c = a.cell(lead, trail, font_no)
if c != FALLBACK_CELL:
out.setdefault(fontmod.cell_index(c), bytes((lead, trail)))
return out
@dataclass
class SlotModel:
build: str # addressing profile (us / proto-2006-05 / jp)
unlock: str # none / jp-gate / jp-prop / jp
gate: str
prop_cells: int
a9_row: bool
codes: Dict[int, bytes] # every reachable cell -> code
reserved: Set[int]
prop: List[int] = field(default_factory=list) # free proportional cells, ascending
wide: List[int] = field(default_factory=list) # free fixed-width cells, ascending
exe_sha1: str = ""
def code_for(self, cell: int) -> bytes:
try:
return self.codes[cell]
except KeyError:
raise GlyphError(f"cell {cell} is not reachable by any code under this model")
def summary(self) -> str:
return (f"{self.build} (unlock {self.unlock}): gate {self.gate}, prop cells < {self.prop_cells}; "
f"{len(self.codes)} cells have a code, {len(self.reserved & set(self.codes))} of them reserved; "
f"free: {len(self.prop)} proportional, {len(self.wide)} wide")
def to_json(self) -> dict:
return {"build": self.build, "unlock": self.unlock, "gate": self.gate, "prop_cells": self.prop_cells,
"a9_row": self.a9_row, "exe_sha1": self.exe_sha1,
"prop": [[c, self.codes[c].hex().upper()] for c in self.prop],
"wide": [[c, self.codes[c].hex().upper()] for c in self.wide],
"reserved": sorted(self.reserved)}
def build_model(a: Addressing, retail: Iterable[int], font: Optional[Font] = None, unlock: str = "none",
require_blank: Optional[bool] = None, exe_sha1: str = "") -> SlotModel:
"""Free slots of a build. ``retail`` = cells retail text draws (``scan_retail``,
taken under the ORIGINAL addressing: they stay reserved under an unlock, and
``code_for`` gives their new codes). ``require_blank`` also refuses cells the
font has ink in (on the Japanese disc no reachable cell is blank, so the
default is off everywhere: a free cell is one no retail text draws).
With ``font`` given, a fixed-width cell below 384 whose half-size image
(cell + 0x240, drawn under control 0x18) has ink is reserved too: on Japan
that is the whole kana block 192-383, including A4F4-A4FC whose half-size
images 851-859 are the unexplained '3 K O S - M ...' glyphs."""
if unlock != "none":
a = unlocked_addressing(a, unlock)
require_blank = bool(require_blank)
if require_blank and font is None:
raise GlyphError("require_blank needs the font")
slots_ok = set(reachable(a, 0))
codes = reachable(a, 0, flagged=True)
reserved: Set[int] = {0, FALLBACK_CELL}
for b in range(0x20, 0x80): # the $han table
code = a.han_code(b)
reserved.add(fontmod.cell_index(a.cell(code >> 8, code & 0xFF, 0)))
for c in retail:
c = fontmod.cell_index(c)
reserved.add(c)
reserved.add(fontmod.cell_index(half_cell(c)))
reserved.update(PROP_IMAGES)
reserved.update(range(EXTRA_KANJI_BASE, CELL_COUNT))
if font is not None:
reserved.update(c for c in range(a.prop_cells, PROP_LIMIT)
if any(any(r) for r in font.cell(c + PROP_CELL_SHIFT)))
prop, wide = [], []
for c in sorted(slots_ok):
if c in reserved:
continue
if require_blank and (any(any(r) for r in font.cell(c))
or (c < a.prop_cells and any(any(r) for r in font.cell(c + PROP_CELL_SHIFT)))):
continue
(prop if c < a.prop_cells else wide).append(c)
return SlotModel(a.profile, unlock, a.gate, a.prop_cells, a.a9_row, codes, reserved, prop, wide, exe_sha1)
def model_from_disc(iso_path, unlock: str = "none", require_blank: Optional[bool] = None,
font_no: int = 0, include_untranslated: bool = False) -> Tuple[SlotModel, Addressing, RetailScan]:
"""The slot model of a disc: its executable's addressing, its retail text
scanned, and its font (for the half-size rule and ``require_blank``).
``include_untranslated`` also reserves what the Japanese left in the USA
build would draw (off by default: those lines show as soup either way)."""
from disc import Disc
exe = fontmod.read_boot_exe(iso_path)
applied = applied_unlock(exe)
if applied != "none":
if unlock not in ("none", applied):
raise GlyphError(f"this disc's executable already carries unlock {applied!r}, not {unlock!r}")
unlock = applied
exe = fontmod.unpatched(exe) # retail text is read under the retail rules
a = Addressing.from_executable(exe)
with Disc(iso_path) as d:
scan = scan_retail(d, a)
f = Font.from_bytes(d.read(fontmod.font_paths(a.font_dir)[font_no]))
m = build_model(a, scan.reserved(include_untranslated), f, unlock, require_blank,
hashlib.sha1(exe).hexdigest())
return m, a, scan
def applied_unlock(exe: bytes) -> str:
"""Which unlock mode a USA / prototype executable carries ("none" for a retail
one, and for any other build: the Japanese gate is native there)."""
if fontmod.profile_for(exe).name not in UNLOCK_BUILDS:
return "none"
on = set()
for name, patches in UNLOCKS.items():
state = [fontmod.read_va(exe, p.va, len(p.new)) == p.new for p in patches]
if all(state):
on.add(name)
elif any(state):
raise GlyphError(f"unlock {name!r} is only partly applied to this executable")
for mode, names in UNLOCK_MODES.items():
if set(names) == on:
return mode
raise GlyphError(f"unlock state {sorted(on)} matches no mode")
# --- allocation -----------------------------------------------------------------------
class GlyphSet:
def __init__(self, source: str = ""):
self.source = source
self.glyphs: Dict[str, Glyph] = {}
self.slots: Dict[str, dict] = {} # key -> {tier, cell, code (bytes), left, right}
self.model: dict = {} # build / unlock / exe_sha1 the slots were made for
def add(self, g: Glyph) -> None:
self.glyphs[g.key] = g
def allocate(self, order: Sequence[str], model: SlotModel, prop_only: bool = False,
wide_only: bool = False) -> None:
"""Give every key in ``order`` (most frequent first) a slot: free
proportional cells first (ink up to 18 px wide), then wide cells. Keys
already placed keep their place; the result depends only on ``order``,
the model and the bitmaps."""
if self.model and (self.model.get("build"), self.model.get("unlock")) != (model.build, model.unlock):
raise GlyphError(f"this glyph set was made for {self.model.get('build')}/{self.model.get('unlock')}, "
f"not {model.build}/{model.unlock}")
self.model = {"build": model.build, "unlock": model.unlock, "exe_sha1": model.exe_sha1,
"prop_cells": model.prop_cells}
used = {v["cell"] for v in self.slots.values()}
clash = used & model.reserved
if clash:
raise GlyphError(f"placed glyphs sit on cells the model reserves: {sorted(clash)[:10]}")
free_prop = [c for c in model.prop if c not in used]
free_wide = [c for c in model.wide if c not in used]
for key in order:
if key in self.slots:
continue
g = self.glyphs.get(key)
if g is None:
raise GlyphError(f"no bitmap for key {key!r}")
if not wide_only and free_prop and (g.ink_width <= 18 or prop_only):
c = free_prop.pop(0)
left, right = self._prop_metrics(g)
self.slots[key] = {"tier": "prop", "cell": c, "code": model.code_for(c), "left": left, "right": right}
elif not prop_only and free_wide:
c = free_wide.pop(0)
self.slots[key] = {"tier": "wide", "cell": c, "code": model.code_for(c), "left": 0, "right": 19}
else:
raise GlyphError(f"out of font cells at key {key!r} ({len(self.slots)} placed)")
@staticmethod
def _prop_metrics(g: Glyph) -> Tuple[int, int]:
"""(left, right) for a proportional slot. Ink starts at column 1 at the
earliest (``apply`` shifts the bitmap to match), so the advance is always
FUN_00185770's ``right - left + 3``."""
if g.bounds is None:
w = max(2, min(18, (g.advance_hint or 6) - 2))
return 1, w # blank slot with a usable advance
left, right = g.bounds
shift = 1 - left if left < 1 else 0
return 1 if shift else left, min(19, right + shift)
def width(self, key: str) -> int:
s = self.slots[key]
return s["right"] - s["left"] + 3 if s["tier"] == "prop" else FIXED_ADVANCE
# applying
def apply(self, font: Font) -> None:
"""Draw every placed glyph into ``font``: proportional = ink-aligned image
at cell + 0x240 plus metrics at the cell, and a centred copy at the cell;
wide = centred at the cell."""
for key, s in self.slots.items():
g = self.glyphs[key]
bm = g.bitmap
centred = shift_x(bm, (CELL_W - g.ink_width) // 2 - g.bounds[0]) if g.bounds else bm
if s["tier"] == "prop":
aligned = shift_x(bm, s["left"] - g.bounds[0]) if g.bounds and g.bounds[0] != s["left"] else bm
font.set_cell(s["cell"] + PROP_CELL_SHIFT, aligned)
font.set_metrics(s["cell"], s["left"], s["right"])
font.set_cell(s["cell"], centred)
# persistence
def to_json(self) -> str:
return json.dumps({
"source": self.source,
"model": self.model,
"slots": {k: dict(v, code=v["code"].hex().upper()) for k, v in self.slots.items()},
"bitmaps": {k: ["".join(str(v) for v in row) for row in g.bitmap]
for k, g in self.glyphs.items()},
}, ensure_ascii=False, indent=0)
@classmethod
def from_json(cls, text: str) -> "GlyphSet":
d = json.loads(text)
gs = cls(d.get("source", ""))
gs.model = d.get("model", {})
for k, rows in d.get("bitmaps", {}).items():
gs.add(Glyph(k, [[int(ch) for ch in row] for row in rows]))
for k, v in d.get("slots", {}).items():
gs.slots[k] = dict(v, code=bytes.fromhex(v["code"]))
return gs
def save(self, path) -> None:
Path(path).write_text(self.to_json(), encoding="utf-8")
@classmethod
def load(cls, path) -> "GlyphSet":
return cls.from_json(Path(path).read_text(encoding="utf-8"))
def code_bytes(self, key: str) -> bytes:
return self.slots[key]["code"]
def check(self, a: Addressing, model: SlotModel) -> List[str]:
"""Problems: a slot on a reserved cell, two keys on one cell, or a code
that the addressing does not draw as the slot's cell."""
out, seen = [], {}
for k, s in self.slots.items():
c = s["cell"]
if c in model.reserved:
out.append(f"{k}: cell {c} is reserved")
if c in seen:
out.append(f"{k}: cell {c} also holds {seen[c]}")
seen[c] = k
g = a.glyph(s["code"] + b"\0", 0, True, 0)
if g.length != len(s["code"]) or fontmod.cell_index(g.cell) != c:
out.append(f"{k}: code {s['code'].hex()} draws cell {g.cell}, not {c}")
if s["tier"] == "prop" and not a.is_prop(c):
out.append(f"{k}: cell {c} is not proportional under this addressing")
return out
# --- PNG cells -------------------------------------------------------------------------
def from_png(png_path, keys: Iterable[str], source: str = "") -> GlyphSet:
"""Cells read left-to-right, top-to-bottom from a 20x24-grid PNG."""
w, h, gray = fontmod.png_to_gray(Path(png_path).read_bytes())
if w % CELL_W or h % CELL_H:
raise GlyphError(f"sheet {w}x{h} is not a multiple of {CELL_W}x{CELL_H}")
q = fontmod.quantize(gray)
per_row = w // CELL_W
gs = GlyphSet(source or str(png_path))
for i, key in enumerate(keys):
cx, cy = (i % per_row) * CELL_W, (i // per_row) * CELL_H
if cy + CELL_H > h:
raise GlyphError("more keys than cells in the sheet")
bm = [list(q[(cy + r) * w + cx:(cy + r) * w + cx + CELL_W]) for r in range(CELL_H)]
gs.add(Glyph(key, bm))
return gs
def to_png(glyphs: Sequence[Glyph], per_row: int = 16) -> bytes:
"""A preview / editing sheet of 20x24 cells (the layout ``from_png`` reads)."""
rows = max(1, -(-len(glyphs) // per_row))
w, h = per_row * CELL_W, rows * CELL_H
px = bytearray(w * h)
for i, g in enumerate(glyphs):
cx, cy = (i % per_row) * CELL_W, (i // per_row) * CELL_H
for y in range(CELL_H):
for x in range(CELL_W):
px[(cy + y) * w + cx + x] = fontmod.GREY[g.bitmap[y][x] & 3]
return fontmod.gray_png(px, w, h)
# --- TrueType rendering (fonttools + uharfbuzz, required) -------------------------------
class TTFRenderer:
"""Shape text with HarfBuzz and rasterise glyph outlines into cells.
``px`` is the em size in pixels (20 fits most scripts in a 24 px cell;
Devanagari with stacked marks may want 16-18), ``baseline`` the cell
row the baseline sits on (default 17: six rows for descenders).
"""
def __init__(self, path, px: float = 20.0, baseline: int = 17,
face_index: int = 0, features: Optional[dict] = None,
supersample: int = 4):
from fontTools.ttLib import TTFont, TTCollection
import uharfbuzz as hb
self.hb = hb
p = Path(path)
data = p.read_bytes()
if p.suffix.lower() == ".ttc":
self.tt = TTCollection(str(p)).fonts[face_index]
else:
self.tt = TTFont(str(p))
self.upem = self.tt["head"].unitsPerEm
self.glyph_set = self.tt.getGlyphSet()
self.glyph_order = self.tt.getGlyphOrder()
face = hb.Face(data, face_index)
self.hbfont = hb.Font(face)
self.hbfont.scale = (self.upem, self.upem)
self.px = px
self.baseline = baseline
# one cell per glyph: keep required ligatures (lam-alef, conjuncts)
# but not the optional wide ones a 20 px cell cannot hold
self.features = {"liga": False, "dlig": False, "calt": False} if features is None else features
self.ss = supersample
self.name = p.stem
self.scale = px / self.upem
# shaping
def shape(self, text: str, direction: str = "ltr", script: Optional[str] = None,
language: Optional[str] = None):
"""-> list of (gid, cluster, x_advance, x_offset, y_offset) in font units."""
hb = self.hb
buf = hb.Buffer()
buf.add_str(text)
buf.guess_segment_properties()
buf.direction = direction
if script:
buf.script = script
if language:
buf.language = language
hb.shape(self.hbfont, buf, self.features)
return [(i.codepoint, i.cluster, p.x_advance, p.x_offset, p.y_offset)
for i, p in zip(buf.glyph_infos, buf.glyph_positions)]
def gid_name(self, gid: int) -> str:
return self.glyph_order[gid]
def advance_px(self, gid: int) -> float:
return self.hbfont.get_glyph_h_advance(gid) * self.scale
# outlines
def contours(self, gid: int) -> List[List[Tuple[float, float]]]:
"""Flattened closed contours in font units."""
from fontTools.pens.recordingPen import DecomposingRecordingPen
pen = DecomposingRecordingPen(self.glyph_set) # flattens TrueType components
self.glyph_set[self.gid_name(gid)].draw(pen)
out: List[List[Tuple[float, float]]] = []
cur: List[Tuple[float, float]] = []
last = (0.0, 0.0)
for op, args in pen.value:
if op == "moveTo":
if cur:
out.append(cur)
cur = [args[0]]
last = args[0]
elif op == "lineTo":
cur.append(args[0])
last = args[0]
elif op == "qCurveTo":
pts = list(args)
if pts[-1] is None: # TrueType implied on-curve start
pts = pts[:-1]
ctrls = pts[:-1]
end = pts[-1]
p0 = last
for i, c in enumerate(ctrls):
nxt = ctrls[i + 1] if i + 1 < len(ctrls) else end
p2 = nxt if i + 1 == len(ctrls) else ((c[0] + nxt[0]) / 2, (c[1] + nxt[1]) / 2)
for t in range(1, 9):
u = t / 8
x = (1 - u) ** 2 * p0[0] + 2 * (1 - u) * u * c[0] + u * u * p2[0]
y = (1 - u) ** 2 * p0[1] + 2 * (1 - u) * u * c[1] + u * u * p2[1]
cur.append((x, y))
p0 = p2
last = end
elif op == "curveTo":
c1, c2, end = args[-3], args[-2], args[-1]
p0 = last
for t in range(1, 9):
u = t / 8
x = ((1 - u) ** 3 * p0[0] + 3 * (1 - u) ** 2 * u * c1[0]
+ 3 * (1 - u) * u * u * c2[0] + u ** 3 * end[0])
y = ((1 - u) ** 3 * p0[1] + 3 * (1 - u) ** 2 * u * c1[1]
+ 3 * (1 - u) * u * u * c2[1] + u ** 3 * end[1])
cur.append((x, y))
last = end
elif op in ("closePath", "endPath"):
if cur:
out.append(cur)
cur = []
if cur:
out.append(cur)
return out
# rasterising
def raster(self, placements: Sequence[Tuple[int, float, float]],
x_origin: float = 1.0) -> Bitmap:
"""Draw glyphs (gid, x_px, y_px offsets from the pen) into one cell.
Even-odd scanline fill at ``supersample`` x resolution, then averaged
to the four levels the font supports."""
ss = self.ss
W, H = CELL_W * ss, CELL_H * ss
cov = [[0] * W for _ in range(H)]
edges = []
for gid, dx, dy in placements:
for contour in self.contours(gid):
pts = [((x_origin + dx + x * self.scale) * ss,
(self.baseline - dy - y * self.scale) * ss) for x, y in contour]
for i in range(len(pts)):
x0, y0 = pts[i]
x1, y1 = pts[(i + 1) % len(pts)]
if y0 != y1:
edges.append((x0, y0, x1, y1))
for sy in range(H):
yc = sy + 0.5
xs = []
for x0, y0, x1, y1 in edges:
if (y0 <= yc < y1) or (y1 <= yc < y0):
xs.append(x0 + (yc - y0) * (x1 - x0) / (y1 - y0))
xs.sort()
for i in range(0, len(xs) - 1, 2):
a, b = int(math.floor(xs[i] + 0.5)), int(math.floor(xs[i + 1] + 0.5))
for sx in range(max(a, 0), min(b, W)):
cov[sy][sx] = 1
bm = blank()
n = ss * ss
for y in range(CELL_H):
for x in range(CELL_W):
s = sum(cov[y * ss + j][x * ss + i] for j in range(ss) for i in range(ss))
bm[y][x] = min(3, (s * 4 + n // 2) // n) if s else 0
return bm
def render_gid(self, gid: int) -> Glyph:
bm = self.raster([(gid, 0.0, 0.0)])
return Glyph(f"g:{self.name}:{gid}", bm, round(self.advance_px(gid)))
def render_cluster(self, parts: Sequence[Tuple[int, float, float]], key: str) -> Glyph:
return Glyph(key, self.raster(parts))
def render_text(self, text: str, key: str, direction: str = "ltr",
script: Optional[str] = None) -> Glyph:
"""Shape ``text`` as one unit and draw it into one cell (left-aligned)."""
pen = 0.0
parts = []
for gid, _, adv, xo, yo in self.shape(text, direction, script):
parts.append((gid, (pen + xo) * self.scale, yo * self.scale))
pen += adv
return Glyph(key, self.raster(parts), round(pen * self.scale))
# --- T7: font coverage of retail text -------------------------------------------------
# Codes the Japanese retail text uses that no font cell answers: E5D0 '縊' (once,
# bat\jp\RAV_B02.sb, in '少々見縊っていたようね'). Lead E5 >= 0xD0 goes through the
# extra-kanji lists, and E5D0 is in neither, so the game would draw cell 0x7F
# there (not checked in game).
T7_KNOWN_GAPS = ("E5D0",)
def coverage(d, a: Addressing, fonts: Sequence[Font]) -> dict:
"""Every two-byte code (lead >= 0xA0) in the parsed retail strings, resolved
through ``a`` in each font. A code passes when it is A1A1 (the full-width
space, blank by design) or resolves in at least one font to an inked cell
other than the fallback; codes whose lead is 0xD0 or above resolve only
through that font's extra-kanji list, so they are judged per font."""
sources = text_sources(_disc_paths(d), a.font_dir)
pairs: Counter = Counter()
kinds: Counter = Counter()
for _p, kind, s, _cat in scan_strings(d.read, sources, "euc" if a.gate == "euc" else a.gate):
if kind == "raw":
continue
kinds[kind] += 1
i = 0
while i < len(s):
if a.pair(s[i], s[i + 1] if i + 1 < len(s) else 0) and i + 1 < len(s) and s[i] >= 0xA0:
pairs[(s[i], s[i + 1])] += 1
i += 2
else:
i += 1
ink = [[any(any(r) for r in f.cell(c)) for c in range(CELL_COUNT)] for f in fonts]
bad, per_font_only = Counter(), Counter()
for (l, t), n in pairs.items():
if (l, t) == (0xA1, 0xA1):
continue
ok = []
for k in range(len(fonts)):
c = fontmod.cell_index(a.cell(l, t, k))
ok.append(c != FALLBACK_CELL and ink[k][c])
if not any(ok):
bad[(l, t)] += n
elif not all(ok):
per_font_only[(l, t)] += n
return {"strings": dict(kinds), "codes": len(pairs), "uses": sum(pairs.values()),
"unresolved": {f"{l:02X}{t:02X}": n for (l, t), n in sorted(bad.items())},
"one_font_only": len(per_font_only),
"one_font_only_all_extra": all(l >= 0xD0 for l, _ in per_font_only)}
# --- CLI ------------------------------------------------------------------------------
def _wrap(fn):
def run(a):
try:
return fn(a)
except (GlyphError, FontError) as e:
print(f"refused: {e}", file=sys.stderr)
return 1
return run
def cmd_slots(a) -> int:
m, ad, scan = model_from_disc(a.iso, a.unlock, a.require_blank, a.font, a.include_untranslated)
print(m.summary())
print(f"retail scan: {dict(scan.files)} files, {sum(scan.strings.values())} strings, "
f"{len(scan.cells)} distinct cells drawn by text, {len(scan.untranslated)} by untranslated Japanese"
f"{' (reserved)' if a.include_untranslated else ' (not reserved)'}")
if a.json:
Path(a.json).write_text(json.dumps(dict(m.to_json(), retail=scan.to_json()), indent=0))
print(f"wrote {a.json}")
return 0
def cmd_coverage(a) -> int:
from disc import Disc
ad = Addressing.from_iso(a.iso)
with Disc(a.iso) as d: