Repository navigation
Expand file tree
/
Copy pathtxsource.py
More file actions
1768 lines (1588 loc) · 75 KB
/
Copy pathtxsource.py
File metadata and controls
1768 lines (1588 loc) · 75 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
"""txsource.py — show the Japanese original next to each USA string.
The translation editor's rows are keyed to the USA disc (SLUS_204.69). A
translator who reads Japanese is better served by the line the writers
wrote, so this module finds, for every USA catalog row, the matching string
on the one Japanese Episode I disc that is around: **Xenosaga Episode I
Reloaded** (SLPS_290.05, 2003), a stripped rebuild of the USA code whose
text was put back into Japanese (EUC-JP). Nothing is ever written to either
disc; the result is a ``{row id: Japanese text}`` map the editor shows as the
"original".
Public API (all read-only; callable from txserver / txcatalog)::
sources(iso_path_usa) -> [{"id": "en-usa", "label": "English (USA disc)"},
{"id": "ja-reloaded",
"label": "Japanese (Xenosaga I Reloaded disc)",
"needs": "path to the Reloaded ISO"}]
identify_disc(path) -> "usa" | "reloaded" | "jp-original" | None
align(usa_iso, source_iso, rows=None, log=print, use_cache=True) -> {
"source": "ja-reloaded", # or "en-usa" when source_iso is
# the USA disc (texts = row src)
"texts": {row_id: display text}, # only rows that align; never
# blank or whitespace-only
"partial": [row_id, ...], # text is the whole Japanese message
# the row is one piece of
"stats": {family: {"rows": n, "aligned": m, "unaligned": k,
"visible": v, "visible_aligned": w}},
"by_cat": {category: same five counts},
"detail": {family: {aligner counter: n}},
"notes": [str, ...]}
display_ja(raw, ctl="c0", font="field") -> str # EUC-JP bytes -> display text
disc_id(path) -> sha1 hex # identity used in the cache key
class SourceError(ValueError)
``family`` is the catalog's ``fam`` (evt / umn / fix / ovl); "visible" counts
rows without a ``hide`` reason. ``align`` raises ``SourceError`` with a
readable message when a disc is not supported: the USA argument is not
SLUS_204.69, the source is another game or unreadable, or the source is the
2002 original Japanese disc ("recognised but not supported yet"). ``rows`` is
the USA catalog row list (``txcatalog.build_catalog(usa)["rows"]``); when
omitted it is built (cached). The display text follows the catalog's display
form (txcodec): Japanese characters as Unicode, control codes as ⟦XX⟧, evt
``/[...]`` tags literal, speaker rows hold just the name. The result is cached
in ``~/.cache/xs1-txeditor/source-<hash>.json``; the hash covers both discs'
identity (``disc_id``), the code of this module and of every reader it uses,
and the row list. A fresh run takes about 12-40 s (both discs read once),
a cached one well under a second plus ~0.2 s per disc for ``disc_id``.
How each family is aligned (and why that is safe):
* **evt** (field maps, cutscenes, speaker names, script menus). Reloaded has
the same 569 containers with the same classes (paired by FL00 row name;
one container gained a stub row) and the same methods in the same order
(checked per class, not assumed). The constant pool order differs (it is
alphabetical by content), so strings are matched by *code position*: each
method is turned into a token stream (opcodes with their member / class
operands, every ``ldc`` String as a placeholder), and the n-th String load
of a USA method is paired with the n-th of the Reloaded method when the
streams are identical (26,116 of 26,190 methods). Field messages are
``String[]`` arrays (``[label, text, waitkey]``) and Reloaded often splits
one USA text element into one element per line, so arrays are compared as
units (``_array_pairs``): elements are classed as speaker label,
control-only (tags) or text, consecutive text elements form a group, and
groups pair in order when both arrays have the same shape. A USA text that
is one element gets the concatenation of its Japanese group. Where the
sizes differ, where the two scripts break the message into pages
differently, or where the shapes agree but the pages' English/Japanese
length ratios differ more than 6x (the text sits on different pages:
ST1060 "It says," | quote against quote | "...that's what it says"),
every USA text element of the message gets the whole Japanese
message and is listed in ``partial``. Methods whose streams differ are
aligned with a longest-common-subsequence match of the token streams; only
String loads inside identical runs are paired.
* **umn**. Mail pages (same numbers on both discs): Reloaded writes
``件名:`` / ``差出人:`` instead of ``Subject:`` / ``Sender:``; parsed the
same way. Chats: the ``<msg>`` blocks of the same ``eventNN.txt`` pair by
index when the sequence of ``<char>`` speakers agrees (all 19 files do).
Database pages are numbered in each language's alphabetical order, so file
numbers do NOT line up; ``_db_pairs`` pairs them inside the header's group
key by evidence only (numbers in the text, capital-letter acronyms, last
page of a group) and leaves the rest without Japanese.
* **fix**: same files, but four of the seven tables have another layout on
Reloaded (checked file by file in ``fix_map``): key items and plug-ins pad
the name to a fixed column, the junk-part blocks are stored in another
order with space padding, card texts are not packed. Enemy battle quotes
pair by index inside the same think file when the PRINT / MSG sequence
agrees (all 100 files). ``endou\savemap.bin`` is not on Reloaded.
* **ovl** (SLUS / OV*.OVL). Reloaded's executables have no symbols. Each
USA function (USA symbol table) is found in the Reloaded file by its
masked instruction words (immediates and jump targets masked) at a likely
function start; every ``lui``/``addiu`` pair that forms a USA string
address is then read at the same offset in the Reloaded function. Data
tables (``itmNameTbl`` ...): the Reloaded address of each USA object that
holds string pointers is its USA address plus a displacement. Candidate
displacements come from the code addressing the object and from the
displacements already found in the file (or, when nothing places any
table, a scan of +-32 KiB for the largest objects); a candidate must keep
the object's layout (every non-pointer word equal, every string pointer
facing a pointer to a string start) and be clearly the best at pairing
strings with the same line breaks, the same numbers and correlated
lengths, against the other candidates and their shifts by up to four
words (``_pick_delta``). Small objects are placed only between two
anchors with the same displacement. A row is aligned only when every
reference that resolves agrees.
Japanese text is decoded by ``display_ja``: JIS X 0208 pairs pass through
as Unicode (``txcodec.to_display`` would read rows 0xD0+ as the USA accent
block, but on Reloaded they are level-2 kanji), everything else (control
codes, ``/[...]`` tags, ASCII) goes through ``txcodec.to_display``.
Quality checks the selftest runs on the result: the control tags that drive
the message window (``waitkey``, ``close``, ``clear``, ``label``, ``$n``,
``#n``) must agree between USA and Japanese, and a Japanese line must not be
paired with a USA debug print and vice versa; counts are reported, and the
selftest fails above a small threshold.
The 2002 original Japanese disc (SLPS_250.xx) is recognised by
``identify_disc`` but ``align`` refuses it with "not supported yet". Design
for adding it: its code predates the USA build (Reloaded is the USA code
rebuilt), so the same steps apply with lower coverage expected: evt by code
position (class / method lists must be checked per container), ovl by masked
function match against the USA symbols (the original ELF is also stripped),
umn / fix by file + record. It becomes a third entry of ``sources()`` with id
``ja-original`` once a disc has been checked.
python3 txsource.py selftest --usa USA.iso --source RELOADED.iso
python3 txsource.py align --usa USA.iso --source RELOADED.iso --out ja.json
python3 txsource.py identify DISC.iso
"""
from __future__ import annotations
import difflib
import hashlib
import json
import os
import re
import struct
import sys
import tempfile
import time
from collections import Counter, defaultdict
from pathlib import Path
from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple
ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import txcodec as tc # noqa: E402
from iso9660 import IsoImage # noqa: E402
VERSION = 2
CACHE_DIR = Path.home() / ".cache" / "xs1-txeditor"
SRC_EN = "en-usa"
SRC_JA = "ja-reloaded"
SRC_JA_ORIGINAL = "ja-original" # recognised, not supported yet
BOOT_USA = "SLUS_204.69"
BOOT_RELOADED = "SLPS_290.05"
_BOOT_JP_ORIGINAL = re.compile(r"^SLPS_250\.\d\d$", re.I)
FAMILIES = ("evt", "umn", "fix", "ovl")
class SourceError(ValueError):
"""The source disc cannot be used (wrong disc, unsupported, unreadable)."""
def _log_null(msg: str) -> None:
pass
# ---------------------------------------------------------------------------
# discs
# ---------------------------------------------------------------------------
def identify_disc(path: str) -> Optional[str]:
""""usa" | "reloaded" | "jp-original" | None, from the boot executable
named in SYSTEM.CNF (plus XENOSAGA.00 and OV01.OVL, so another game with
a similar serial is not taken for Episode I). Never raises for a bad
path; returns None."""
try:
iso = IsoImage(path)
except Exception:
return None
try:
boot = (iso.boot_elf_name() or "").upper()
files = {n.upper() for n in iso.files}
except Exception:
return None
finally:
try:
iso.close()
except Exception:
pass
if "XENOSAGA.00" not in files or "OV01.OVL" not in files:
return None
if boot == BOOT_USA:
return "usa"
if boot == BOOT_RELOADED:
return "reloaded"
if _BOOT_JP_ORIGINAL.match(boot):
return "jp-original"
return None
def sources(iso_path_usa: Optional[str] = None) -> List[dict]:
"""Source-language options for the editor. ``iso_path_usa`` is accepted
for symmetry (the English source is the USA disc itself) and not read."""
return [{"id": SRC_EN, "label": "English (USA disc)"},
{"id": SRC_JA, "label": "Japanese (Xenosaga I Reloaded disc)",
"needs": "path to the Reloaded ISO"}]
def disc_id(path: str) -> str:
"""sha1 of the boot ELF, every OV*.OVL and the three TOC files (the
same object set as ``txproject.retail_id``, for any Episode I disc)."""
iso = IsoImage(path)
try:
boot = iso.boot_elf_name()
if not boot or boot not in iso.files:
raise SourceError(f"{path}: no boot executable on the disc")
names = [boot] + sorted(n for n in iso.files if n.upper().endswith(".OVL")) + \
[n for n in ("XENOSAGA.00", "XENOSAGA.10", "XENOSAGA.20") if n in iso.files]
h = hashlib.sha1()
for n in names:
h.update(n.encode() + b"\0")
h.update(bytes(iso.read_file(n)))
return h.hexdigest()
finally:
iso.close()
# ---------------------------------------------------------------------------
# Japanese display form
# ---------------------------------------------------------------------------
def display_ja(raw: bytes, ctl: str = "c0", font: str = "field") -> str:
"""EUC-JP engine bytes -> display text. Two-byte JIS X 0208 characters
(and 0x8E half-width kana) are decoded as Unicode; runs of everything
else go through ``txcodec.to_display`` with the row's ``ctl`` and
``font`` (face font1), so control codes come out as the usual ⟦XX⟧
tokens and ``/[...]`` tags stay."""
out: List[str] = []
run = bytearray()
i, n = 0, len(raw)
def flush():
if run:
out.append(tc.to_display(bytes(run), ctl, font, tc.FONT1))
run.clear()
while i < n:
b = raw[i]
if 0xA1 <= b <= 0xFE and i + 1 < n and 0xA1 <= raw[i + 1] <= 0xFE:
try:
ch = raw[i:i + 2].decode("euc_jp")
except UnicodeDecodeError:
ch = None
if ch is not None:
flush()
out.append(ch)
i += 2
continue
if b == 0x8E and i + 1 < n and 0xA1 <= raw[i + 1] <= 0xDF:
flush()
out.append(raw[i:i + 2].decode("euc_jp", "replace"))
i += 2
continue
if b < 0x80:
run.append(b)
i += 1
continue
# a lone high byte: let the codec show it as ⟦XX⟧
run.append(b)
i += 1
flush()
return "".join(out)
# ---------------------------------------------------------------------------
# evt: bytecode position
# ---------------------------------------------------------------------------
def _u16(b: bytes, o: int) -> int:
return struct.unpack_from(">H", b, o)[0]
def _u32(b: bytes, o: int) -> int:
return struct.unpack_from(">I", b, o)[0]
def _utf(ent, i: int) -> bytes:
e = ent[i] if 0 < i < len(ent) else None
return e[1].rstrip(b"\0") if e and e[0] == 1 else b""
def _cref(ent, i: int) -> tuple:
"""Constant-pool operand in a disc-independent form."""
e = ent[i] if 0 < i < len(ent) else None
if not e:
return ("?",)
tag = e[0]
if tag == 8:
return ("S",)
if tag in (3, 4, 5, 6):
return ("K", tag, e[1])
if tag == 7:
return ("C", _utf(ent, _u16(e[1], 0)))
if tag in (9, 10, 11):
ci, nt = struct.unpack(">HH", e[1])
cn = _utf(ent, _u16(ent[ci][1], 0))
ni, di = struct.unpack(">HH", ent[nt][1])
return ("M", cn, _utf(ent, ni), _utf(ent, di))
return ("?", tag)
_CPOOL_OPS = {0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBB, 0xBD, 0xC0, 0xC1, 0xC5}
_ONE_BYTE_OPERAND = {0x10, 0x15, 0x16, 0x17, 0x18, 0x19, 0x36, 0x37, 0x38, 0x39, 0x3A, 0xBC}
_INT_PUSH = set(range(0x02, 0x09)) | {0x10, 0x11} # iconst_m1..5, bipush, sipush
_DUP, _AASTORE, _ANEWARRAY = 0x59, 0x53, 0xBD
_STR_CLASS = ("C", b"java/lang/String")
def _class_methods(cls: bytes):
"""[(name, desc, tokens)] per method. A token is a tuple; a String load
is ("str", utf8 pool index)."""
import evttext as et
from txfam_evt import _OPLEN
ent, p = et.parse_pool(cls)
p += 6
p += 2 + 2 * _u16(cls, p)
def attrs(q, on=None):
n = _u16(cls, q)
q += 2
for _ in range(n):
an = _utf(ent, _u16(cls, q))
al = _u32(cls, q + 2)
if an == b"Code" and on is not None:
body = q + 6
on(cls[body + 8:body + 8 + _u32(cls, body + 4)])
q += 6 + al
return q
nf = _u16(cls, p)
p += 2
for _ in range(nf):
p = attrs(p + 6)
nm = _u16(cls, p)
p += 2
out = []
for _ in range(nm):
name, desc = _utf(ent, _u16(cls, p + 2)), _utf(ent, _u16(cls, p + 4))
got: List[bytes] = []
p = attrs(p + 6, got.append)
toks: List[tuple] = []
if got:
code = got[0]
pc, n = 0, len(code)
while pc < n:
op = code[pc]
if op in (0x12, 0x13, 0x14):
idx = code[pc + 1] if op == 0x12 else _u16(code, pc + 1)
r = _cref(ent, idx)
if r[0] == "S":
toks.append(("str", _u16(ent[idx][1], 0)))
else:
toks.append(("ldc",) + r)
elif op in _CPOOL_OPS:
toks.append((op,) + _cref(ent, _u16(code, pc + 1)))
elif op in _ONE_BYTE_OPERAND:
toks.append((op, code[pc + 1]))
elif op == 0x11:
toks.append((op, _u16(code, pc + 1)))
elif op == 0x84:
toks.append((op, code[pc + 1], code[pc + 2]))
else:
toks.append((op,))
if op == 0xAA:
q = (pc + 4) & ~3
lo, hi = struct.unpack_from(">ii", code, q + 4)
pc = q + 12 + 4 * (hi - lo + 1)
continue
if op == 0xAB:
q = (pc + 4) & ~3
pc = q + 8 + 8 * struct.unpack_from(">i", code, q + 4)[0]
continue
if op == 0xC4:
pc += 6 if code[pc + 1] == 0x84 else 4
continue
pc += _OPLEN[op]
out.append((name, desc, toks))
return ent, out
def _fold_arrays(toks: List[tuple]) -> List[tuple]:
"""Replace each ``new String[n] {ldc, ldc, ...}`` construction by one
("arr", (elem, ...)) item; elem = utf8 pool index, or None for an element
that is not a String literal. The size push is dropped (Reloaded's arrays
often have more elements). Anything unusual leaves the tokens as they are."""
out: List[tuple] = []
i, n = 0, len(toks)
while i < n:
t = toks[i]
if t[0] == _ANEWARRAY and t[1:] == _STR_CLASS and out and out[-1][0] in _INT_PUSH:
j = i + 1
elems: List[Optional[int]] = []
ok = True
while j + 1 < n and toks[j][0] == _DUP and toks[j + 1][0] in _INT_PUSH:
k = j + 2
val = []
while k < n and toks[k][0] != _AASTORE:
if toks[k][0] in (_ANEWARRAY, _DUP) or len(val) > 6:
ok = False
break
val.append(toks[k])
k += 1
if not ok or k >= n:
ok = False
break
elems.append(val[0][1] if len(val) == 1 and val[0][0] == "str" else None)
j = k + 1
if ok and elems:
out.pop() # the size push
out.append(("arr", tuple(elems)))
i = j
continue
out.append(t)
i += 1
return out
def _key(t: tuple) -> tuple:
if t[0] == "str":
return ("str",)
if t[0] == "arr":
return ("arr",)
return t
_TAG_RE = re.compile(rb"/\[[^\]]*\]")
def _elem_kind(raw: bytes) -> str:
body = raw.rstrip(b"\0")
if body.startswith(b"/[label("):
return "label"
if not body.strip():
return "text" # whitespace: part of the text around it
if not _TAG_RE.sub(b"", body).strip():
return "ctl"
return "text"
def _array_pairs(ue: Sequence[Optional[int]], re_: Sequence[Optional[int]],
uent, rent) -> Optional[List[Tuple[int, List[int], bool]]]:
"""Pair the elements of a USA and a Reloaded String[]: [(usa pool,
[reloaded pools], partial)], or None when they cannot be paired.
Elements are speaker labels, control-only elements (tags) and text;
whitespace-only elements count as text. Consecutive text elements form a
group. Same shape, when _pagewise_ok finds the page split plausible:
groups pair in order (one-to-one when the sizes agree, a single USA
element takes the whole Japanese group). Otherwise, or with a different
shape but the same
speaker labels (the two scripts break the message into pages differently,
``/[waitkey(1)]/[clear()]``): labels pair in order and every USA text
element gets the whole Japanese message (its text groups joined by a line
break), ``partial``."""
def shape(elems, ent):
segs: List[Tuple[str, List[int]]] = []
for e in elems:
if e is None:
segs.append(("expr", []))
continue
k = _elem_kind(_utf_raw(ent, e))
if k == "text":
if segs and segs[-1][0] == "text":
segs[-1][1].append(e)
else:
segs.append(("text", [e]))
else:
segs.append((k, [e]))
return segs
su, sr = shape(ue, uent), shape(re_, rent)
out: List[Tuple[int, List[int], bool]] = []
if [k for k, _ in su] == [k for k, _ in sr] and _pagewise_ok(su, sr, uent, rent):
for (k, a), (_, b) in zip(su, sr):
if k == "expr":
continue
if k != "text" or len(a) == len(b):
out += [(x, [y], False) for x, y in zip(a, b)]
else: # len(a) == 1 (_pagewise_ok)
out.append((a[0], b, False))
return out
lu = [a[0] for k, a in su if k == "label"]
lr = [b[0] for k, b in sr if k == "label"]
if len(lu) != len(lr) or len(lu) > 1 or any(k == "expr" for k, _ in su + sr):
return None
tu = [x for k, a in su if k == "text" for x in a]
groups = [b for k, b in sr if k == "text"]
if not tu or not groups:
return None
whole: List[int] = []
for g in groups:
if whole:
whole.append(-1) # line break between pages
whole += g
out += [(x, [y], False) for x, y in zip(lu, lr)]
out += [(x, whole, True) for x in tu]
return out
# two pages whose English/Japanese length ratios differ by more than this
# are taken as the scripts putting the text on different pages
_PAGE_RATIO_MAX = 6.0
def _text_len(ent, i: int) -> int:
return len(_TAG_RE.sub(b"", _utf_raw(ent, i).rstrip(b"\0")).strip())
def _pagewise_ok(su, sr, uent, rent) -> bool:
"""Same shape: is pairing the text groups page by page plausible? Not
when a USA group cannot map onto its Japanese group (several USA
elements against a different number of Japanese ones), nor when the
groups' English/Japanese length ratios disagree strongly (ST1060: USA
"It says," | quote, Japanese quote | "...that's what it says"): the two
scripts split the message at different points. The caller then gives
every USA element the whole message, ``partial``."""
ratios = []
for (k, a), (_, b) in zip(su, sr):
if k != "text":
continue
if len(a) > 1 and len(b) != len(a):
return False
la = sum(_text_len(uent, x) for x in a)
lb = sum(_text_len(rent, y) for y in b)
if la and lb:
ratios.append(lb / la)
return len(ratios) < 2 or max(ratios) / min(ratios) <= _PAGE_RATIO_MAX
def _utf_raw(ent, i: int) -> bytes:
e = ent[i] if 0 < i < len(ent) else None
return e[1] if e and e[0] == 1 else b""
def _method_pairs(ut: List[tuple], rt: List[tuple], uent, rent, st: Counter):
"""Yield (usa pool, [reloaded pools], partial) for one method pair."""
uf, rf = _fold_arrays(ut), _fold_arrays(rt)
uk, rk = [_key(t) for t in uf], [_key(t) for t in rf]
if uk == rk:
blocks = [(0, 0, len(uk))]
st["methods_same"] += 1
else:
sm = difflib.SequenceMatcher(None, uk, rk, autojunk=False)
blocks = [b for b in sm.get_matching_blocks() if b[2]]
st["methods_lcs"] += 1
for a, b, size in blocks:
for k in range(size):
x, y = uf[a + k], rf[b + k]
if x[0] == "str":
yield x[1], [y[1]], False
elif x[0] == "arr":
pr = _array_pairs(x[1], y[1], uent, rent)
if pr is None:
st["arrays_shape_differs"] += 1
continue
st["arrays_paired"] += 1
yield from pr
def evt_map(usa_iso: str, src_iso: str, log=_log_null) -> Tuple[Dict[str, Tuple[bytes, bool]], dict]:
"""{evt row id: (Japanese raw bytes, partial)} for every USA literal
that has a code-position partner, plus counters. Ids use txfam_evt's
scheme (``evt:chain|path|class row|utf8 pool index``); speaker labels
map to the whole ``/[label(...)]`` literal (the caller unwraps)."""
import evttext as et
st: Counter = Counter()
def load(p):
iso = IsoImage(p)
try:
return {(ch, path): data for ch, path, data, _ in et.iter_containers(iso)}
finally:
iso.close()
u, r = load(usa_iso), load(src_iso)
out: Dict[str, Tuple[bytes, bool]] = {}
conflicts = 0
for key in sorted(u):
if key not in r:
st["containers_missing"] += 1
continue
ud, rd = u[key], r[key]
try:
ue, re_ = et.fl00_entries(ud), et.fl00_entries(rd)
except et.EvtTextError:
continue
# classes pair by FL00 row name (one container gained a stub row on Reloaded)
rname = {rd[no:no + nl]: k for k, (no, nl, _, _) in enumerate(re_)}
if len(rname) != len(re_):
st["containers_duplicate_names"] += 1
continue
if len(ue) != len(re_):
st["containers_row_count_differs"] += 1
st["containers"] += 1
for ri, (no, nl, do, ds) in enumerate(ue):
rj = rname.get(ud[no:no + nl])
if rj is None:
st["classes_missing"] += 1
continue
_, _, do2, ds2 = re_[rj]
ucls, rcls = ud[do:do + ds], rd[do2:do2 + ds2]
if ds <= 24 or ucls[:4] != et.CAFEBABE or rcls[:4] != et.CAFEBABE:
continue
try:
uent, um = _class_methods(ucls)
rent, rm = _class_methods(rcls)
except Exception:
st["classes_unparsed"] += 1
continue
if [(a, b) for a, b, _ in um] != [(a, b) for a, b, _ in rm]:
st["classes_methods_differ"] += 1
continue
st["classes"] += 1
chain, path = key
got: Dict[int, List[Tuple[bytes, bool]]] = defaultdict(list)
for (_, _, ut), (_, _, rt) in zip(um, rm):
for upool, rpools, partial in _method_pairs(ut, rt, uent, rent, st):
raw = b"".join(b"\n" if p < 0 else _utf_raw(rent, p).rstrip(b"\0")
for p in rpools)
got[upool].append((raw, partial))
for upool, cands in got.items():
first = cands[0]
if any(c[0] != first[0] for c in cands[1:]):
conflicts += 1
# several code positions share this USA literal and the Japanese
# differs between them; show the most common (first on a tie)
cnt = Counter(c[0] for c in cands)
best = max(cnt.values())
first = next(c for c in cands if cnt[c[0]] == best)
out[f"evt:{chain}|{path}|{ri}|{upool}"] = first
st["literals_conflicting"] = conflicts
log(f"evt: {st['containers']} containers, {st['classes']} classes, "
f"{st['methods_same']} methods identical + {st['methods_lcs']} matched by LCS, "
f"{st['arrays_paired']} arrays paired, {st['arrays_shape_differs']} shape differs; "
f"{len(out)} literals mapped ({conflicts} with differing Japanese per use)")
return out, dict(st)
_LABEL_RAW = re.compile(rb"^/\[label\((.*?)\)?\]$", re.S)
def _evt_texts(rows: List[dict], m: Dict[str, Tuple[bytes, bool]]):
texts, partial = {}, []
for r in rows:
hit = m.get(r["id"])
if hit is None:
continue
raw, part = hit
if r["cat"] == "Speaker names" and r.get("ctx", "").startswith("field speaker label"):
# the USA's empty label literal is one pool entry shared by many
# positions; a name taken from one of them is not this row's
if not r["src"].strip():
continue
mm = _LABEL_RAW.match(raw)
if not mm:
continue
raw = mm.group(1)
texts[r["id"]] = display_ja(raw, "evt", r.get("font") or tc.FIELD)
if part:
partial.append(r["id"])
return texts, partial
# ---------------------------------------------------------------------------
# umn: same files; mail / chat / database
# ---------------------------------------------------------------------------
_JA_SUBJECT = "件名:".encode("euc_jp")
_JA_SENDER = "差出人:".encode("euc_jp")
def _ja_mail_slots(t: bytes) -> Optional[Dict[str, bytes]]:
"""Reloaded mail page -> {"subject", "sender", "body"} raw bytes, cut
the way txfam_umn cuts a USA page (``_strip`` past control codes)."""
import txfam_umn as fu
ls = fu._lines(t)
if len(ls) < 3:
return None
out: Dict[str, bytes] = {}
for k, (label, part) in enumerate(((_JA_SUBJECT, "subject"), (_JA_SENDER, "sender"))):
la, lb = ls[k]
p = t.find(label, la, lb)
if p != la:
return None
a, b = fu._strip(t, p + len(label), lb, lead_nl=False)
out[part] = t[a:b]
a, b = fu._strip(t, ls[1][1] + 1, len(t))
out["body"] = t[a:b]
return out
def umn_map(usa_iso: str, src_iso: str, log=_log_null) -> Tuple[Dict[str, bytes], dict]:
"""{umn row id: Japanese raw bytes}. Mails by file (subject / sender /
body), chats by ``<msg>`` index when the speaker sequences agree,
database pages through ``_db_pairs`` (the files are numbered in each
language's own alphabetical order, so file numbers do not line up)."""
import txfam_umn as fu
su, sr = fu._load(usa_iso), fu._load(src_iso)
out: Dict[str, bytes] = {}
st: Counter = Counter()
# mails
for path, data in su.objs.items():
m = fu._MAIL_RE.search(path)
if not m or path not in sr.objs:
continue
ja = _ja_mail_slots(fu._text_of(path, sr.objs[path]))
if ja is None:
st["mail_pages_unparsed"] += 1
continue
st["mail_pages"] += 1
for part, raw in ja.items():
rid = f"umn:mail:{m.group(1)}:{part}"
if rid in su.slots:
out[rid] = raw
# chats
chats: Dict[str, List[str]] = defaultdict(list)
for rid in su.slots:
if rid.startswith("umn:chat:"):
chats[rid.rsplit(":", 1)[0]].append(rid)
for base, ids in chats.items():
rids = [rid for rid in sr.slots if rid.rsplit(":", 1)[0] == base]
if len(rids) != len(ids) or [su.slots[i].row["ctx"] for i in ids] != \
[sr.slots[i].row["ctx"] for i in rids]:
st["chat_files_differ"] += 1
continue
st["chat_files"] += 1
for a, b in zip(ids, rids):
out[a] = sr.slots[b].raw
# database
pairs, dst = _db_pairs(su, sr)
st.update(dst)
for unum, rnum in pairs.items():
for part in ("title", "body"):
a, b = f"umn:db:{unum}:{part}", f"umn:db:{rnum}:{part}"
if a in su.slots and b in sr.slots:
out[a] = sr.slots[b].raw
log(f"umn: {st['mail_pages']} mail pages, {st['chat_files']} chat files "
f"({st['chat_files_differ']} differ), {len(pairs)} database pages paired")
return out, dict(st)
def _db_pairs(su, sr) -> Tuple[Dict[str, str], Counter]:
"""USA database file number -> Reloaded file number.
The two discs number their pages in their own alphabetical order
(``db_fileno.txt``: A, B, C ... against ア行, カ行 ...), so 9000.uml is
"AAA class encryption" on one and "アーキタイプ" on the other. The one
language-independent key in a page is the u32 at 0x0C of its header,
which groups pages (the pages of a group share it; the 41 groups have
the same sizes on both discs, 245 pages). Inside a group, pages are
paired only by evidence that cannot pair two different articles:
1. the set of numbers in title + body (full-width digits folded; at
least two numbers or one of 3+ digits: years like T.C. 4743, "Plan
401"), when exactly one page on each side has that set;
2. then the run of capital Latin letters of the title ("ECM",
"DME addiction" / "DME中毒"), at least two, mutually unique;
3. then, when one page is left on each side of a group, those two.
Everything else stays unpaired (no guessing between look-alikes)."""
import unicodedata
import txfam_umn as fu
st: Counter = Counter()
def groups(state):
g: Dict[int, Dict[str, Tuple[frozenset, str]]] = defaultdict(dict)
for path, data in state.objs.items():
m = fu._DB_RE.search(path)
if not m or len(data) < 0x10:
continue
n = m.group(1)
title = state.slots.get(f"umn:db:{n}:title")
body = state.slots.get(f"umn:db:{n}:body")
tt = unicodedata.normalize("NFKC", (title.raw if title else b"").decode("euc_jp", "replace"))
bt = unicodedata.normalize("NFKC", (body.raw if body else b"").decode("euc_jp", "replace"))
nums = frozenset(re.findall(r"\d+", tt + "\n" + bt))
caps = "".join(re.findall(r"[A-Z]", tt))
g[struct.unpack_from("<I", data, 0x0C)[0]][n] = (nums, caps)
return g
def strong_nums(ns) -> bool:
return len(ns) >= 2 or any(len(x) >= 3 for x in ns)
gu, gr = groups(su), groups(sr)
out: Dict[str, str] = {}
for key, a in gu.items():
b = dict(gr.get(key, {}))
a = dict(a)
if len(a) != len(b):
st["db_groups_size_differs"] += 1
continue
for field, strong, why in ((0, strong_nums, "db_pairs_numbers"),
(1, lambda c: len(c) >= 2, "db_pairs_capitals")):
changed = True
while changed:
changed = False
for un, fu_ in list(a.items()):
if not strong(fu_[field]):
continue
hits = [rn for rn, fr in b.items() if fr[field] == fu_[field]]
twins = [x for x, fx in a.items() if fx[field] == fu_[field]]
if len(hits) == 1 and len(twins) == 1:
out[un] = hits[0]
del a[un], b[hits[0]]
st[why] += 1
changed = True
if len(a) == 1 and len(b) == 1:
out[next(iter(a))] = next(iter(b))
st["db_pairs_last_in_group"] += 1
st["db_pages_unpaired"] += len(a) - (1 if len(a) == 1 and len(b) == 1 else 0)
return out, st
# ---------------------------------------------------------------------------
# fix: same files, per-file record layouts
# ---------------------------------------------------------------------------
def _cstr(buf: bytes, off: int, end: Optional[int] = None) -> bytes:
end = len(buf) if end is None else end
j = buf.find(b"\0", off, end)
return bytes(buf[off:end if j < 0 else j])
def _cstr_ctl(buf: bytes, off: int, end: Optional[int] = None) -> bytes:
"""A NUL-terminated engine string that may contain control codes whose
operand is 0 (Reloaded writes ``\x19\x00`` / ``\x19\x01`` around
half-width punctuation, e.g. ``U\x19\x01.\x19\x00M``): operands are
stepped over with ``font.control_length``, as the printer does."""
from font import control_length
end = len(buf) if end is None else end
i = off
while i < end and buf[i] != 0:
if buf[i] < 0x20 and buf[i] != 0x0A:
try:
i += max(1, control_length(buf, i))
except (IndexError, TypeError):
i += 1
else:
i += 1
return bytes(buf[off:min(i, end)])
def _name_desc(rec: bytes, desc_end: int) -> Tuple[bytes, bytes]:
"""Reloaded's name + description records: the name at 0, the
description at the first non-NUL byte after it (Reloaded pads the name
with NULs to a fixed column instead of packing the two)."""
name = _cstr_ctl(rec, 0, desc_end)
k = len(name) + 1
while k < desc_end and rec[k] == 0:
k += 1
return name, (_cstr_ctl(rec, k, desc_end) if k < desc_end else b"")
def fix_map(usa_iso: str, src_iso: str, log=_log_null) -> Tuple[Dict[str, bytes], dict]:
"""{fix row id: Japanese raw bytes}. Layouts checked against the
Reloaded files (they differ from USA's in four of the seven tables)."""
import txfam_fix as ff
fu_, ou = ff.scan(usa_iso)
fr, orr = ff.scan(src_iso)
ids = {f.id: f for f in fu_}
out: Dict[str, bytes] = {}
st: Counter = Counter()
lower = {p.lower(): p for p in orr}
def obj(p):
k = lower.get(p.lower())
return orr.get(k) if k else None
# key items: 255 x 0x80 records, same item numbers; the last 4 bytes of a
# Reloaded record hold a separate two-byte code, not text
d = obj(ff.P_EVTITEM)
if d is not None and len(d) == len(ou.get(ff.P_EVTITEM, b"")):
for i in range(len(d) // 0x80):
rec = d[i * 0x80:(i + 1) * 0x80]
if not any(rec[:0x7C]):
continue
name, desc = _name_desc(rec, 0x7C)
for part, raw in (("name", name), ("desc", desc)):
rid = f"fix:evtitem:{i + 1}:{part}"
if rid in ids and raw:
out[rid] = raw
st["evtitem"] = 1
# U.M.N. plug-ins: 6 records of 127 bytes on Reloaded (128 on USA)
d = obj(ff.P_UMNTXT)
nu = len(ou.get(ff.P_UMNTXT, b"")) // 0x80
if d is not None and nu and len(d) % nu == 0:
size = len(d) // nu
for i in range(nu):
name, desc = _name_desc(d[i * size:(i + 1) * size], size)
for part, raw in (("name", name), ("desc", desc)):
rid = f"fix:umntxt:{i}:{part}"
if rid in ids and raw:
out[rid] = raw
st["umntxt"] = 1
# junk parts: the same 64 strings, but Reloaded stores the blocks in the
# order info (23), map names (18), item names (23) with space padding
d = obj(ff.P_MAPEX)
if d is not None:
ss = [s.rstrip(b" ") for s in d.split(b"\0") if s.strip(b" ")]
blocks_u = ff._mapex_split(ou[ff.P_MAPEX])
n0, n1, n2 = (len(b) for b in blocks_u)
if len(ss) == n0 + n1 + n2:
jb = {0: ss[:n0], 2: ss[n0:n0 + n2], 1: ss[n0 + n2:]}
# check: every map name has one line break on both discs, no item name has one
if all(s.count(b"\n") == 1 for s in jb[2]) and all(b"\n" not in s for s in jb[1]) \
and all(s.count(b"\n") == 1 for s in blocks_u[2]):
for bi, strings in jb.items():
for si, raw in enumerate(strings):
rid = f"fix:mapex:{bi}:{si}"
if rid in ids:
out[rid] = raw
st["mapex"] = 1
# card game: same 148 records; Reloaded's texts are not packed (a third
# offset is used), so read name / caption through their offsets
d = obj(ff.P_CARD)
if d is not None and len(d) > 0x10:
cnt = struct.unpack_from("<H", d, 0)[0]
if cnt == struct.unpack_from("<H", ou[ff.P_CARD], 0)[0]:
for i in range(cnt):
no, co, _ = struct.unpack_from("<III", d, ff.CARD_HEADER + i * ff.CARD_REC + 0x18)
for part, off in (("name", no), ("caption", co)):
rid = f"fix:card:{i}:{part}"
if rid in ids and 0 < off < len(d):
out[rid] = ff.card_to_print(_cstr_ctl(d, off))
st["card"] = 1
# casino: identical layout
d = obj(ff.P_CASINO)
if d is not None and len(d) == len(ou.get(ff.P_CASINO, b"")):
for f in ff._fields_casino(d):
if f.id in ids and f.raw:
out[f.id] = f.raw
st["casino"] = 1
# save-screen locations: endou\savemap.bin is not on the Reloaded disc
# enemy battle quotes: the n-th string of the same think file, when the
# PRINT / MSG sequence agrees
for p in sorted(x for x in ou if x.lower().startswith(ff.THINK_DIR)):
d = obj(p)
if d is None:
continue
try:
a, b = ff.think_strings(ou[p]), ff.think_strings(d)
except ff.ThinkError:
st["think_unparsed"] += 1
continue
if [s.op for s in a] != [s.op for s in b]:
st["think_differs"] += 1
continue
st["think_files"] += 1
stem = p.rsplit("\\", 1)[-1].rsplit(".", 1)[0]
for x, y in zip(a, b):
rid = f"fix:{stem}:{x.off:x}"
if rid in ids:
out[rid] = y.raw
log(f"fix: tables {sorted(k for k in st if st[k] == 1 and not k.startswith('think'))}, "
f"{st['think_files']} think files ({st['think_differs']} differ)")
return out, dict(st)
# ---------------------------------------------------------------------------
# ovl: masked function match against the USA symbols
# ---------------------------------------------------------------------------
_JR_RA = 0x03E00008
_MASK_IMM = {0x09, 0x0D} | set(range(0x20, 0x40)) # addiu, ori, loads / stores
def _mask(w: int) -> int:
op = w >> 26
if op in (0x02, 0x03):
return op << 26 # j / jal target
if op == 0x0F:
return w & 0xFFFF0000 # lui immediate
if op in _MASK_IMM:
return w & 0xFFFF0000 # address / offset low half
return w
class _Elf:
"""Load segments of an executable and its words, for the Reloaded side
(no symbols needed)."""
def __init__(self, data: bytes):
from txfam_ovl import _phdrs