Repository navigation
Expand file tree
/
Copy pathschedule.py
More file actions
1453 lines (1305 loc) · 65.1 KB
/
Copy pathschedule.py
File metadata and controls
1453 lines (1305 loc) · 65.1 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
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 Nexxus Drako Multimedia
"""Season schedule reader for Let's Make a Soccer Team! (PS2).
The season calendar lives in three BINPAC packs in DAT/PARAM, all full of
TBB1 tables (see DOC/SCHEDULE_FORMAT.md):
SCHEDULE_SYSTEM.PAC 5 named TBBs. year_schedule_data: one 20-byte
row per schedule UID (0-163): competition, load
condition, and a 96-bit mask of the turns with
games. open_nation: 72 rows of host nations.
make_list: team-list definitions. savectrl: one
save-buffer type per UID.
SCHEDULE_COMPETITION.PAC 164 entries, one per UID: a 16-byte header, the
games (4 bytes each) and the pairings.
SCHEDULE_TEAM_ENTRY.PAC 164 entries: where each entrant slot's team
comes from (last season's rank, a current table
position, a random pick from a list, a fixed team).
Confirmed from SLES_541.51: ScheEuro_SubCtrl::initYearScheduleData
(0x20a008), getYearSchedule (0x20a170), get_open_turn (0x209968),
getOpenNation (0x209f40), CScheEuro_*::acceptLoadRequest (0x2072a8,
0x207458, 0x2075c8), CScheEuro::OneLoadCompCB (0x2068f8),
Sche_Block_decode_main2 (0x2dc258), getOneGameFromBlockAndGameIndex
(0x2dab38), ScheEuro_TeamEntry::makeTeamEntryIDList (0x20a298) and its
four *_TeamEntryProc handlers, ScheEuro_TeamEntryList::requestMakeList
(0x20b188), scheCtrl_GetMatchupBufferSize (0x2dfb28) and
ScheduleControllerBaseSystem::entryWinTeamTournament (0x2dcc80).
`info` checks every entry against that layout and cross-checks the packs:
each competition's game days against its UID's turn mask, and its entrant
count against the team-entry slots.
Usage:
python schedule.py info <DAT/PARAM> # check all three packs
python schedule.py year <DAT/PARAM> # one line per year_schedule_data row
python schedule.py compe <DAT/PARAM> <uid> # header, games and pairings of one UID
python schedule.py entry <DAT/PARAM> <uid> # team-entry slots of one UID
python schedule.py roundtrip <DAT/PARAM> # re-encode all three packs and their .HED, !! if not identical
python schedule.py league <DAT/PARAM> [<n> [single]] # generated leagues: check every size, or print one
python schedule.py knockout <DAT/PARAM> [<n> [two] [seeded]] # generated cups: rebuild the disc's and check every size, or print one
python schedule.py turns <DAT/PARAM> [<uid> [<days>]] [--national] # leagues' game days and room; one UID's calendar
python schedule.py shift <SCHEDULE_SYSTEM.PAC> <out.PAC> <delta> <uid>[-<uid>] ... # move UIDs' game days
python schedule.py balance <SCHEDULE_COMPETITION.PAC> <out.PAC> [<uid>[-<uid>] ...] # rebuild badly balanced leagues
`shift` moves each UID's turn mask and start turn by delta turns (-1 is
one turn earlier) and writes the pack with its .HED. The end turn stays,
and a UID that runs across the year end is refused. patch_disc.py
--mod national-cups uses it for the World and Euro National Cups.
`balance` rebuilds league UIDs (by default UNBALANCED: 1, 11, 30, 40,
48, 154 and 155, the templates with more than two games running at one
venue) with set_league at their own size, and writes the pack with its
.HED. The games, pairings and entrants keep their counts, so every entry
keeps its size. A UID already balanced is left as it is. patch_disc.py
--mod league-balance uses it.
`league` builds round robins for 2-32 clubs (league_days, set_league):
each club alternates home and away, the second leg starts one round
later than the first so rematches are far apart, and an odd size gets a
rest day. With no size it checks every size, once and twice round, and
compares each with the disc's own template of that size (`!!` on a
generated league that breaks a rule). leaguesize.py build puts a league
of a new size into the packs, with its turn mask and team-entry slots.
`knockout` builds cup brackets for 2-128 clubs (knockout_tables,
set_knockout): each half of a bracket splits in two again, a half of odd
size (it holds a bye) goes to the outer side, and a tie is played as soon
as both sides are known, one or two legs. The seeded layout
(knockout_bracket_seeded, `seeded`) is the usual draw instead: byes in
the first round only, for the top slots, and each round played together;
patch_disc.py --mod third-tier builds the lower cups with it. A winner's link (table 3) names
the pairing and side it goes to, which is what the game follows
(entryWinTeamTournament 0x2dcc80); the pairing names it as slot entrants
+ pairing. With no size it rebuilds every knockout on the disc from its
shape (71 of 87 come out byte for byte; the rest are listed with how they
differ) and checks every size in both layouts (`!!` on a generated
bracket that breaks a rule).
`turns` lists each league UID's game days and how many it could have:
the free turns inside its season, where no game of its own, of its
nation's cups or of a European, national-team or runtime competition
falls (the disc's leagues keep clear of those). With a UID it draws that
season as a calendar, and with a number of days the turns
league_turns() would use: added ones fill the widest gaps, weekends
first, and dropped ones are midweeks first. --national also counts the
national teams' dates (competitions 44-47) as free: no club plays then,
and the qualifying dates call the squads up and release them on the
match turn itself (SCHEDULE_LIST.TBB). The disc's leagues never use
them; whether a league game there misses its called-up players isn't
known.
Writing: every entry re-encodes from its fields (year rows, competition
headers, games, pairings, team-entry records), and a pack is rebuilt with
pac.py's BINPAC writer together with its .HED, which the game reads the
offsets from (its copies are in PRELOAD/STATIONFILE.PAC).
"""
import os
import struct
import sys
from collections import Counter
import pac
import tbb
SYSTEM_PAC = "SCHEDULE_SYSTEM.PAC"
COMPE_PAC = "SCHEDULE_COMPETITION.PAC"
ENTRY_PAC = "SCHEDULE_TEAM_ENTRY.PAC"
UID_COUNT = 164
# patch_disc.py --mod third-tier (LMASTER) adds the third tiers as UIDs
# 165-176; 164, the default rules' REGULATION row, has no schedule, and
# the packs' entry 164 is a placeholder (DOC/UID_LIMITS.md).
TIER_UID_COUNT = 177
LAYOUTS = {UID_COUNT: list(range(UID_COUNT)),
TIER_UID_COUNT: list(range(UID_COUNT)) + list(range(UID_COUNT + 1, TIER_UID_COUNT))}
COMPE_COUNT = 72 # PLSCHE_COMPE 0-71: open_nation's 72 rows
TURNS_PER_YEAR = 96 # get_open_turn: open turn = years * 0x60 + bit
YEAR_ROW = 0x14 # year_schedule_data row size
OPEN_NATION_ROW = 0x2c # s16 compe, s16 start, s16 nation[20]
MAKE_LIST_ROW = 4
ENTRY_ROW = 6 # every team-entry record
COMPE_HEADER = 0x10
GAME_ROW = 4
PAIR_ROW = 2
MAX_TEAM = 0x22d # PlTeamId_TeamEntryProc fills 1 <= id <= 0x22d, skips others
# year_schedule_data +6: which mode loads the UID (acceptLoadRequest).
LOAD_KIND = {0: "always", 1: "own-nation", 2: "other-nations", 3: "runtime",
4: "first-promote", 5: "vs"}
# Competition header +4 (Sche_Block_decode_main2 allocates the next-pairing
# table only for 1).
COMPE_TYPE = {0: "league", 1: "knockout"}
# make_list +2, through the jump table at 0x52fb10.
SRC_KIND = {0: "uefa", 1: "uefa", 2: "clubrank", 3: "clubrank", 4: "fifa",
5: "fifa", 6: "list", 7: "domestic"}
# LIST records with a negative kind (List_TeamEntryProc 0x20a91c). Any
# other negative kind leaves the slot empty.
LIST_SPECIAL = {-4: "host-nation-team", -3: "team-1"}
def s16(b, o):
return struct.unpack_from("<h", b, o)[0]
def u16(b, o):
return struct.unpack_from("<H", b, o)[0]
def bits(mask):
return [i * 8 + k for i, b in enumerate(mask) for k in range(8) if b >> k & 1]
# --- SCHEDULE_SYSTEM ---------------------------------------------------------
class YearRow:
def __init__(self, raw):
self.raw = raw
self.uid = s16(raw, 0) # -1: second-year part of the row before
self.start, self.end = raw[2], raw[3]
self.compe = struct.unpack_from("<b", raw, 4)[0]
self.cycle = raw[5] # year of the 4-year cycle, 0xff = every year
self.kind, self.flag = raw[6], raw[7]
self.turns = bits(raw[8:20])
def encode(self):
"""The 20-byte row from its fields; the mask from the turn list."""
mask = bytearray(12)
for t in self.turns:
if not 0 <= t < TURNS_PER_YEAR:
raise ValueError("turn %d out of range 0-%d" % (t, TURNS_PER_YEAR - 1))
mask[t >> 3] |= 1 << (t & 7)
return (struct.pack("<hBBbBBB", self.uid, self.start, self.end, self.compe,
self.cycle, self.kind, self.flag) + bytes(mask))
def year_uids(rows):
"""{uid: (row, continuation row or None)} as getYearSchedule pairs them."""
out = {}
for i, r in enumerate(rows):
if r.uid < 0:
continue
nxt = rows[i + 1] if i + 1 < len(rows) and rows[i + 1].uid == -1 else None
out[r.uid] = (r, nxt)
return out
class System:
NAMES = ("year_schedule_data.tbb", "open_nation.tbb", "make_list.tbb",
"PeriodName.tbb", "savectrl.tbb")
def __init__(self, entries):
names = [n for n, _ in entries]
if names != list(self.NAMES):
raise ValueError("unexpected entries %s" % ", ".join(names))
self.entries = entries
t = [tbb.parse(buf)[1] for _, buf in entries]
year = t[0][0].data
if len(year) % YEAR_ROW:
raise ValueError("year_schedule_data is not a whole number of rows")
self.year = [YearRow(year[i:i + YEAR_ROW]) for i in range(0, len(year), YEAR_ROW)]
on = t[1][0].data
if len(on) % OPEN_NATION_ROW:
raise ValueError("open_nation is not a whole number of rows")
self.open_nation = [struct.unpack_from("<22h", on, i)
for i in range(0, len(on), OPEN_NATION_ROW)]
ml = t[2][0].data
self.make_list = [ml[i:i + MAKE_LIST_ROW] for i in range(0, len(ml), MAKE_LIST_ROW)]
self.make_list_tables = len(t[2])
self.savectrl = t[4][0].data
def encode(self):
"""[(name, bytes)] of the 5 entries; year_schedule_data rebuilt from
its rows, the others as they are (no writer touches them yet)."""
out = []
for i, (name, buf) in enumerate(self.entries):
if i == 0:
end, t = tbb.parse(buf)
trailer = tbb.trailer(buf, t)
t[0].data = b"".join(r.encode() for r in self.year)
buf = tbb.build(t, end, trailer)
out.append((name, buf))
return out
# --- SCHEDULE_COMPETITION ----------------------------------------------------
class Game:
def __init__(self, w0, w1):
self.day = w0 & 0xff
self.flag = (w0 >> 8) & 3 # unknown
self.round = (w0 >> 10) & 0xf # 1 final, 2 semi, 3 quarter, 4 last 16, 0 other
self.pair = w1 & 0x1ff
self.swap = (w1 >> 9) & 3 # home = pair[swap], away = pair[1 - swap]
self.spare = (w0 >> 14, w1 >> 11)
def encode(self):
if not (0 <= self.day < 0x100 and 0 <= self.round < 0x10 and 0 <= self.pair < 0x200
and 0 <= self.flag < 4 and 0 <= self.swap < 4):
raise ValueError("game field out of range (day %d, round %d, pairing %d)"
% (self.day, self.round, self.pair))
w0 = self.day | self.flag << 8 | self.round << 10 | self.spare[0] << 14
w1 = self.pair | self.swap << 9 | self.spare[1] << 11
return struct.pack("<HH", w0, w1)
class Competition:
def __init__(self, buf):
self.buf = buf
self.end, t = tbb.parse(buf)
self.tbb_tables = t
if len(t) not in (3, 4):
raise ValueError("%d tables, expected 3 or 4" % len(t))
h = t[0].data
if len(h) != COMPE_HEADER:
raise ValueError("header is %d bytes" % len(h))
self.tables = len(t)
self.header = h
self.uid, self.compe = u16(h, 0), u16(h, 2) # not read by the game
self.type, self.entrants = h[4], h[5]
self.pair_count, self.game_count = u16(h, 6), u16(h, 8)
g = t[1].data
self.games = [Game(*struct.unpack_from("<HH", g, i)) for i in range(0, len(g) - 3, GAME_ROW)]
self.game_bytes = len(g)
p = t[2].data
self.pairs = [(p[i], p[i + 1]) for i in range(0, len(p) - 1, PAIR_ROW)]
self.next = None
if len(t) == 4:
n = t[3].data
self.next = [(n[i], n[i + 1]) for i in range(0, len(n) - 1, PAIR_ROW)]
# Bytes past the last whole record, kept as they are.
self.tails = [g[len(self.games) * GAME_ROW:], p[len(self.pairs) * PAIR_ROW:],
t[3].data[len(self.next) * PAIR_ROW:] if self.next is not None else b""]
def encode(self):
"""The entry's bytes from the header fields, games, pairings and
next links, with tbb.build. The header's counts are written from
the fields: entrants, pairings and games."""
t = self.tbb_tables
trailer = tbb.trailer(self.buf, t)
head = bytearray(self.header)
head[4], head[5] = self.type, self.entrants
struct.pack_into("<HH", head, 6, self.pair_count, self.game_count)
t[0].data = bytes(head)
t[1].data = b"".join(g.encode() for g in self.games) + self.tails[0]
t[2].data = b"".join(bytes(pr) for pr in self.pairs) + self.tails[1]
if self.next is not None:
t[3].data = b"".join(bytes(nx) for nx in self.next) + self.tails[2]
return tbb.build(t, self.end, trailer)
@property
def days(self):
return max(g.day for g in self.games) + 1 if self.games else 0
def problems(self):
out = []
if self.type not in COMPE_TYPE:
out.append("type %d" % self.type)
if self.tables != (4 if self.type == 1 else 3):
out.append("%d tables for type %d" % (self.tables, self.type))
if self.game_bytes != self.game_count * GAME_ROW:
out.append("%d game bytes for %d games" % (self.game_bytes, self.game_count))
if len(self.pairs) != self.pair_count:
out.append("%d pairings, header says %d" % (len(self.pairs), self.pair_count))
if self.next is not None and len(self.next) != self.pair_count:
out.append("%d next links for %d pairings" % (len(self.next), self.pair_count))
if any(g.spare != (0, 0) for g in self.games):
out.append("games use bits 14-15 / 11-15")
if any(g.pair >= self.pair_count for g in self.games):
out.append("game pairing index out of range")
if any(g.swap > 1 for g in self.games):
out.append("home/away swap > 1")
if sorted(set(g.day for g in self.games)) != list(range(self.days)):
out.append("game days not contiguous from 0")
if self.type == 0:
if any(a >= self.entrants or b >= self.entrants for a, b in self.pairs):
out.append("league pairing slot >= %d entrants" % self.entrants)
elif self.type == 1:
# A knockout's first-round pairings name entrant slots; later
# pairings name winner slots after them.
if any(max(a, b) >= 2 * self.pair_count for a, b in self.pairs):
out.append("knockout pairing slot out of range")
# A link at or past the pairing count sends the winner out of
# this competition (single-round ties, the final).
if any(n >= 2 * self.pair_count or s > 1 for n, s in self.next):
out.append("next-pairing link out of range")
return out
# --- building a league -------------------------------------------------------
LEAGUE_MAX = 32 # pairing index is 9 bits: n(n-1)/2 <= 511
def league_days(n, legs=2):
"""A round robin for entrant slots 0..n-1, as a list of game days, each
a list of (home, away). Berger tables: each club alternates home and
away, so no club plays more than two games in a row at one venue. The
second leg plays the first leg's rounds again with home and away
swapped, starting from round 1 (round 0's return games come last), so
a rematch is n-2 or more game days after the first meeting. An odd n
gets a rest day: slot n is a dummy, and its games are left out."""
if not 2 <= n <= LEAGUE_MAX or legs not in (1, 2):
raise ValueError("a league has 2-%d clubs playing 1 or 2 legs" % LEAGUE_MAX)
size = n + n % 2
m = size - 1
first = []
for r in range(m):
day = [(r, m) if r % 2 == 0 else (m, r)]
for i in range(1, size // 2):
a, b = (r + i) % m, (r - i) % m
day.append((a, b) if i % 2 else (b, a))
first.append([g for g in day if n not in g])
if legs == 1:
return first
return first + [[(a, h) for h, a in day] for day in first[1:] + first[:1]]
def league_tables(n, legs=2):
"""(pairings, games) for league_days(n, legs) in the layout of
SCHEDULE_COMPETITION tables 1 and 2: pairings in the order they are
first played, each as (home, away) of its first game, and games in day
order, swap 1 for a return game."""
pairs, index, games = [], {}, []
for day, fixtures in enumerate(league_days(n, legs)):
for h, a in fixtures:
key = frozenset((h, a))
if key not in index:
index[key] = len(pairs)
pairs.append((h, a))
k = index[key]
games.append(Game(day, k | (0 if pairs[k][0] == h else 1) << 9))
return pairs, games
def set_league(c, n, legs=2):
"""Make Competition `c` a league of n entrants with league_tables'
pairings and games. The other header bytes are kept. Returns the
number of game days, which the UID's turn mask must match."""
if c.next is not None:
raise ValueError("UID is a knockout (4 tables); only a league can be rebuilt")
c.pairs, c.games = league_tables(n, legs)
c.type, c.entrants = 0, n
c.pair_count, c.game_count = len(c.pairs), len(c.games)
return c.days
def league_stats(c):
"""(problems, breaks, longest run at one venue, shortest gap in game
days between two meetings of the same clubs) of a league Competition."""
probs = []
venue = {t: {} for t in range(c.entrants)}
meetings = {}
for g in c.games:
if g.pair >= len(c.pairs):
probs.append("game on day %d names pairing %d of %d" % (g.day, g.pair, len(c.pairs)))
continue
pair = c.pairs[g.pair]
h, a = pair[g.swap], pair[1 - g.swap]
for t, v in ((h, "H"), (a, "A")):
if t not in venue:
probs.append("slot %d out of range" % t)
elif g.day in venue[t]:
probs.append("slot %d plays twice on day %d" % (t, g.day))
else:
venue[t][g.day] = v
meetings.setdefault(g.pair, []).append((g.day, h))
legs = {len(m) for m in meetings.values()}
if len(meetings) != len(c.pairs) or len(legs) != 1:
probs.append("pairings are played %s times" % sorted(legs))
elif legs == {2} and any(m[0][1] == m[1][1] for m in meetings.values()):
probs.append("a pairing has both games at the same club")
if {frozenset(p) for p in c.pairs} != {frozenset((i, j)) for i in range(c.entrants)
for j in range(i + 1, c.entrants)}:
probs.append("pairings are not every two slots once")
breaks = longest = 0
for days in venue.values():
seq = [days[d] for d in sorted(days)]
run = 1
for i in range(1, len(seq)):
run = run + 1 if seq[i] == seq[i - 1] else 1
breaks += seq[i] == seq[i - 1]
longest = max(longest, run)
gap = min((m[1][0] - m[0][0] for m in meetings.values() if len(m) > 1), default=0)
return probs, breaks, longest, gap
# The disc's league templates with runs of more than two games at one
# venue: the 22-club leagues (up to 7), the 26-club English second
# division with your club (9) and the 8-club VS leagues (5).
UNBALANCED = (1, 11, 30, 40, 48, 154, 155)
BALANCED_RUN = 2 # what league_days gives at every size
def balance_pack(data, uids=UNBALANCED):
"""(SCHEDULE_COMPETITION.PAC bytes, [rebuilt UIDs]) with each league
UID that has a run of more than BALANCED_RUN games at one venue rebuilt
by set_league at its own size and legs. The entrants, the game days
and the counts stay, so each entry keeps its size and the pack its
header (and .HED); team slots are untouched. A UID already balanced,
as leaguesize.py build leaves the leagues it rebuilds, is skipped."""
h, blobs = pac.binpac_blobs(data)
if len(blobs) not in LAYOUTS:
raise ValueError("%d entries, expected %s" % (len(blobs), " or ".join(map(str, LAYOUTS))))
done = []
for u in uids:
c = Competition(blobs[u])
if c.type != 0 or not c.pairs:
raise ValueError("UID %d is not a league" % u)
if league_stats(c)[2] <= BALANCED_RUN:
continue
legs, days = len(c.games) // len(c.pairs), c.days
# Game bit w0 8 is the same for every game of a day (empirical, all
# 164 UIDs of both releases), so it stays with its day.
flags = {g.day: g.flag for g in c.games}
if set_league(c, c.entrants, legs) != days:
raise ValueError("UID %d: the rebuilt league has %d game days, not %d"
% (u, c.days, days))
for g in c.games:
g.flag = flags[g.day]
new = c.encode()
if len(new) != len(blobs[u]):
raise ValueError("UID %d: the rebuilt entry is %d bytes, not %d"
% (u, len(new), len(blobs[u])))
probs, _, longest, _ = league_stats(Competition(new))
if probs or longest > BALANCED_RUN:
raise ValueError("UID %d: the rebuilt league fails its check" % u)
blobs[u] = new
done.append(u)
out = pac.build_binpac(data[:h.header_size], blobs)
if len(out) != len(data) or out[:h.header_size] != data[:h.header_size]:
raise ValueError("the rebuilt pack changed its layout")
return out, done
# --- building a knockout -----------------------------------------------------
KNOCKOUT_MAX = 128 # slots are u8: the last winner slot, 2n - 3, must fit
LABELS = ("none", "final", "all") # which games get a round number (Game.round)
def knockout_bracket(n):
"""The bracket for entrant slots 0..n-1 as a tree of nested pairs (a
leaf is a slot), in slot order left to right. Each node splits its
clubs in two halves, and a half of odd size, which holds a bye, goes
to the node's own outer side: the left one in a left half, the right
one in a right half (at the top, the left). That is the layout of
every disc cup with byes (UIDs 8, 9, 17, 26 and their twins)."""
if not 2 <= n <= KNOCKOUT_MAX:
raise ValueError("a knockout has 2-%d clubs" % KNOCKOUT_MAX)
slots = iter(range(n))
def node(size, left):
if size == 1:
return next(slots)
small, big = size // 2, size - size // 2
odd, even = (small, big) if small % 2 else (big, small)
parts = (odd, even) if left else (even, odd)
if small == big:
parts = (small, big)
return (node(parts[0], True), node(parts[1], False))
return node(n, True)
KNOCKOUT_LAYOUTS = ("disc", "seeded") # knockout_bracket's, or knockout_bracket_seeded's
def knockout_bracket_seeded(n):
"""The bracket for entrant slots 0..n-1 with byes in the first round
only, as a tree like knockout_bracket's. The slots are seeds (slot 0
the first) in the usual draw of a bracket of the next power of two
(1 v 16, 8 v 9, 4 v 13, ...); a seed past n is a bye, so the top
seeds go straight to the second round and the lowest play the first."""
if not 2 <= n <= KNOCKOUT_MAX:
raise ValueError("a knockout has 2-%d clubs" % KNOCKOUT_MAX)
order = [0]
while len(order) < n:
size = 2 * len(order)
order = [x for s in order for x in (s, size - 1 - s)]
def node(seeds):
if len(seeds) == 1:
return seeds[0]
half = len(seeds) // 2
left, right = node(seeds[:half]), node(seeds[half:])
if isinstance(right, int) and right >= n: # a bye
return left
return (left, right)
return node(order)
def knockout_tables(n, legs=1, final_legs=None, labels="final", single=False, layout="disc"):
"""(pairings, next links, games) of a knockout of n entrant slots in the
layout of SCHEDULE_COMPETITION tables 1-3 (see the doc's knockout
tables). Pairings name entrant slots, or the winner of pairing p as
slot n + p. With layout "disc" (knockout_bracket) a tie is played as
soon as both sides are known; with "seeded" (knockout_bracket_seeded)
each round is played together, the first round's ties first and the
clubs with a bye from the second. A tie's legs are on consecutive game
days, the second with home and away swapped
(swap 1). Pairings are numbered by their first game day, then left to
right. A winner's link names the pairing and side it goes to; the
final's, and with `single` every first-round tie's (a round whose
winners go on to another UID), leave the competition: the pairing
count plus the order they leave in. `labels` sets Game.round: "all"
numbers the rounds from the final (1 final, 2 semi-finals, ...),
"final" marks the final only and "none" leaves every game 0."""
if labels not in LABELS:
raise ValueError("labels is one of %s" % ", ".join(LABELS))
if layout not in KNOCKOUT_LAYOUTS:
raise ValueError("layout is one of %s" % ", ".join(KNOCKOUT_LAYOUTS))
final_legs = legs if final_legs is None else final_legs
if legs not in (1, 2) or final_legs not in (1, 2):
raise ValueError("a tie is played over 1 or 2 legs")
# Each tie: its two sides (an entrant slot or another tie), its first
# game day, its level (1 for a first-round tie) and its leftmost slot.
ties = []
# A seeded bracket plays by round: a tie `depth` steps below the final
# is in round `rounds - depth`, on that round's game days.
rounds = (n - 1).bit_length() if layout == "seeded" and not single else None
def walk(t, depth=0):
"""(tie index, or None for an entrant slot; last game day; level;
leftmost slot) of a subtree, its ties added to `ties` children first."""
if isinstance(t, int):
return None, -1, 0, t
sides = [walk(s, depth + 1) for s in t]
if rounds is None:
day = max(s[1] for s in sides) + 1
level = max(s[2] for s in sides) + 1
else:
level = rounds - depth
day = (level - 1) * legs
ties.append((sides, day, level, sides[0][3]))
return len(ties) - 1, day + legs - 1, level, sides[0][3]
if single:
if n % 2 or not 2 <= n <= KNOCKOUT_MAX:
raise ValueError("a single round has an even number of clubs, 2-%d" % KNOCKOUT_MAX)
for i in range(0, n, 2):
walk((i, i + 1))
else:
walk(knockout_bracket_seeded(n) if layout == "seeded" else knockout_bracket(n))
final = None if single else len(ties) - 1 # walk adds the final last
top = ties[-1][2]
order = sorted(range(len(ties)), key=lambda k: (ties[k][1], ties[k][3]))
index = {k: i for i, k in enumerate(order)}
pairs, nexts, games, out = [], [None] * len(ties), [], 0
for i, k in enumerate(order):
sides, day, level, _ = ties[k]
pair = []
for side, (sub, _, _, slot) in enumerate(sides):
if sub is None:
pair.append(slot)
else:
pair.append(n + index[sub])
nexts[index[sub]] = (i, side)
pairs.append(tuple(pair))
if single or k == final:
nexts[i] = (len(ties) + out, 0)
out += 1
if labels == "all":
label = top - level + 1
else:
label = 1 if labels == "final" and k == final else 0
if label > 0xf:
raise ValueError("%d rounds: the round number is 4 bits" % top)
for leg in range(final_legs if k == final else legs):
games.append(Game(day + leg | label << 10, i | leg << 9))
games.sort(key=lambda g: (g.day, g.pair))
return pairs, nexts, games
def knockout_shape(c):
"""(legs, final legs, labels, single) of a knockout Competition, the
arguments knockout_tables needs to build one like it."""
if c.type != 1 or c.next is None:
raise ValueError("not a knockout")
played = Counter(g.pair for g in c.games)
# A lone tie is a final: its link leaves either way.
single = c.pair_count > 1 and all(n >= c.pair_count for n, _ in c.next)
final = None if single else c.pair_count - 1
legs = max((v for k, v in played.items() if k != final), default=played[final])
rounds = {g.round for g in c.games}
labels = "all" if max(rounds) > 1 else "final" if 1 in rounds else "none"
return legs, played[final] if final is not None else legs, labels, single
def set_knockout(c, n, legs=1, final_legs=None, labels="final", single=False, layout="disc"):
"""Make Competition `c` a knockout of n entrants with knockout_tables'
pairings, next links and games (`layout` as there). The other header bytes are kept, and
so is game bit w0 8 for each game day the old entry had (it is the
same for every game of a day; new days get the last day's). Returns
the number of game days, which the UID's turn mask must match."""
if c.next is None:
raise ValueError("UID is a league (3 tables); only a knockout can be rebuilt")
flags = {g.day: g.flag for g in c.games}
last = flags[max(flags)] if flags else 1
c.pairs, c.next, c.games = knockout_tables(n, legs, final_legs, labels, single, layout)
for g in c.games:
g.flag = flags.get(g.day, last)
c.type, c.entrants = 1, n
c.pair_count, c.game_count = len(c.pairs), len(c.games)
return c.days
def knockout_stats(c):
"""Problems of a knockout Competition, played through: every entrant
slot and every winner slot is named once, each winner link points
back at its winner's slot, a winner plays on only after its tie's
last game, no slot plays twice on one day, and one club is left (or,
with every tie leaving, one per tie)."""
probs = []
n, count = c.entrants, c.pair_count
named = Counter(s for p in c.pairs for s in p)
days = {}
for g in c.games:
if g.pair < count:
days.setdefault(g.pair, []).append(g.day)
if set(days) != set(range(count)):
probs.append("pairings without a game")
for s in range(n):
if named[s] != 1:
probs.append("entrant slot %d named %d times" % (s, named[s]))
leaving = 0
for p, (to, side) in enumerate(c.next):
if to >= count:
leaving += 1
if named[n + p]:
probs.append("pairing %d leaves, but its winner slot %d is named" % (p, n + p))
continue
if c.pairs[to][side] != n + p:
probs.append("pairing %d's link names pairing %d side %d, which holds slot %d"
% (p, to, side, c.pairs[to][side]))
if named[n + p] != 1:
probs.append("winner slot %d named %d times" % (n + p, named[n + p]))
if p in days and to in days and min(days[to]) <= max(days[p]):
probs.append("pairing %d plays on day %d, before pairing %d is decided"
% (to, min(days[to]), p))
if any(s >= n + count for p in c.pairs for s in p):
probs.append("a pairing names a slot past the winner slots")
single = all(to >= count for to, _ in c.next)
if leaving != (count if single else 1):
probs.append("%d ties leave the competition" % leaving)
busy = Counter()
for g in c.games:
if g.pair < count:
for s in c.pairs[g.pair]:
busy[(s, g.day)] += 1
if any(v > 1 for v in busy.values()):
probs.append("a slot plays twice on one day")
return probs
MONTHS = ("Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
TURNS_PER_MONTH = 8 # 4 weeks of a midweek and a weekend turn (empirical)
def turn_name(t):
"""A turn as the game's calendar shows it: "Aug w2 weekend" (empirical:
the year starts in July, 8 turns a month, even turns midweek)."""
m, k = divmod(t % TURNS_PER_YEAR, TURNS_PER_MONTH)
return "%s w%d %s" % (MONTHS[m], k // 2 + 1, "midweek" if k % 2 == 0 else "weekend")
def compe_nation(system, compe):
"""The one nation a competition always belongs to (open_nation rows
that repeat a nation, with no 4-year start), or None for one whose
host changes (the European and national-team competitions)."""
row = next((r for r in system.open_nation if r[0] == compe), None)
if row is None or row[1] != -1 or len(set(row[2:])) != 1:
return None
return row[2]
def shift_turns(system, uids, delta):
"""Move each UID's game days `delta` turns (its mask and its start
turn). The end turn stays: what the game does with it isn't traced,
and the national cups' 95 is the end of the year either way. The games
and pairings are by game day, so SCHEDULE_COMPETITION is unchanged."""
rows = year_uids(system.year)
for u in uids:
if u not in rows:
raise ValueError("UID %d has no year_schedule_data row" % u)
r, nxt = rows[u]
if nxt is not None:
raise ValueError("UID %d runs across the year end; shifting it isn't supported" % u)
turns = [t + delta for t in r.turns]
if turns and not 0 <= turns[0] <= turns[-1] < TURNS_PER_YEAR:
raise ValueError("UID %d: turns %d-%d move out of the year" % (
u, turns[0], turns[-1]))
start = r.start
if start != 0xff:
start += delta
if not 0 <= start < TURNS_PER_YEAR or (turns and start > turns[0]):
raise ValueError("UID %d: start turn %d would be past its first game day"
% (u, start))
r.turns, r.start = turns, start
def shift_pack(data, uids, delta):
"""SCHEDULE_SYSTEM.PAC bytes with shift_turns applied. The year rows
keep their size, so the pack and its .HED keep their layout."""
h, blobs = pac.binpac_blobs(data)
system = System([(e[2], b) for e, b in zip(h.entries, blobs)])
shift_turns(system, uids, delta)
out = pac.build_binpac(data[:h.header_size], [b for _, b in system.encode()])
if len(out) != len(data) or out[:h.header_size] != data[:h.header_size]:
raise ValueError("the rebuilt pack changed its layout")
return out
def parse_uids(args):
"""UIDs from '98' and '98-102' arguments."""
out = []
for a in args:
lo, _, hi = a.partition("-")
out += range(int(lo, 0), int(hi or lo, 0) + 1)
return out
def year_turns(system):
"""{uid: (row, [turns])}, a second-year row's turns counted from 96."""
out, last = {}, None
for r in system.year:
if r.uid >= 0:
out[r.uid] = (r, list(r.turns))
last = r.uid
elif last is not None:
out[last][1].extend(t + TURNS_PER_YEAR for t in r.turns)
return out
def national_compe(system, compe):
"""True for the national teams' competitions (44-47): the only
open_nation rows with a start year, whose host changes every 4 years."""
row = next((r for r in system.open_nation if r[0] == compe), None)
return row is not None and row[1] != -1
def blocked_turns(system, compes, uid, national=False):
"""Turns a league UID's clubs may be busy on, as the disc's leagues
keep clear of them (empirical): games of any competition whose host
changes (European, national teams, the runtime cups) and of the
league's own nation's knockouts. VS and first-promotion UIDs, the
runtime friendlies and other leagues don't count. With `national`,
the national teams' dates are left open: no club plays on them, and
on a qualifying date the call-up and release fall on the match turn
itself (SCHEDULE_LIST.TBB)."""
rows = year_turns(system)
nation = compe_nation(system, rows[uid][0].compe)
out = set()
for u, (r, turns) in rows.items():
if u == uid or r.kind in (4, 5) or u >= len(compes):
continue
n = compe_nation(system, r.compe)
if n == 0:
continue # the runtime friendlies (competition 49)
if national and national_compe(system, r.compe):
continue
if n is None or (n == nation and compes[u].type == 1):
out.update(turns)
return out
def free_turns(system, compes, uid, national=False):
"""The turns inside a league UID's season (its first to last game day)
with no game of its own and none it keeps clear of."""
turns = year_turns(system)[uid][1]
busy = blocked_turns(system, compes, uid, national) | set(turns)
return [t for t in range(turns[0], turns[-1] + 1) if t not in busy]
def league_turns(system, compes, uid, days, national=False):
"""A turn list of `days` game days for a league UID, made from its own
by adding free turns inside its season or dropping turns. Each added
turn goes into the widest gap between game days (a weekend before a
midweek), each dropped one closes the narrowest (a midweek first), so
the games stay spread over the season. `national` also offers the
national teams' dates (blocked_turns)."""
row, turns = year_turns(system)[uid]
if len(turns) != len(set(turns)) or any(t >= TURNS_PER_YEAR for t in turns):
raise ValueError("UID %d runs across the year end; not supported" % uid)
turns = sorted(turns)
free = free_turns(system, compes, uid, national)
if days - len(turns) > len(free):
raise ValueError("UID %d has room for %d game days (%d now, %d free turns)"
% (uid, len(turns) + len(free), len(turns), len(free)))
if days < 1:
raise ValueError("a league needs at least 1 game day")
while len(turns) < days:
def room(t):
before = max((x for x in turns if x < t), default=turns[0])
after = min((x for x in turns if x > t), default=turns[-1])
return (min(t - before, after - t), t % 2, -t)
t = max(free, key=room)
free.remove(t)
turns = sorted(turns + [t])
while len(turns) > days:
def loss(i):
t = turns[i]
# The first and last game days stay, so the season keeps its dates.
before = turns[i - 1] if i else t - TURNS_PER_YEAR
after = turns[i + 1] if i + 1 < len(turns) else t + TURNS_PER_YEAR
return (t % 2, after - before, t)
turns.pop(min(range(len(turns)), key=loss))
return turns
# --- SCHEDULE_TEAM_ENTRY -----------------------------------------------------
class TeamEntry:
KINDS = ("last_rank", "list", "now_rank", "plteamid")
def __init__(self, buf):
self.buf = buf
self.end, t = tbb.parse(buf)
self.tbb_tables = t
if len(t) not in (4, 5):
raise ValueError("%d tables, expected 4 or 5" % len(t))
h = t[0].data
if len(h) != ENTRY_ROW:
raise ValueError("header is %d bytes" % len(h))
self.header = h
self.counts = {"last_rank": h[2], "list": h[3], "now_rank": h[4], "plteamid": h[5]}
# makeTeamEntryIDList: t1 LAST_RANK, t2 LIST, t3 NOW_RANK, t4 PLTEAMID.
self.records = {}
for kind, tab in zip(self.KINDS, t[1:]):
d = tab.data
if len(d) % ENTRY_ROW:
raise ValueError("%s table is not a whole number of records" % kind)
self.records[kind] = [d[i:i + ENTRY_ROW] for i in range(0, len(d), ENTRY_ROW)]
self.records.setdefault("plteamid", [])
def encode(self):
"""The entry's bytes: the header with the four counts, then each
kind's records."""
t = self.tbb_tables
trailer = tbb.trailer(self.buf, t)
head = bytearray(self.header)
head[2:6] = bytes(self.counts[k] for k in self.KINDS)
t[0].data = bytes(head)
for kind, tab in zip(self.KINDS, t[1:]):
tab.data = b"".join(self.records[kind])
return tbb.build(t, self.end, trailer)
@property
def slots(self):
return sum(self.counts.values())
def used(self, kind):
"""Records the game walks: the header count for all but NOW_RANK,
which runs over its whole table (and only if the count is non-zero)."""
recs = self.records[kind]
if kind == "now_rank":
return recs if self.counts[kind] else []
return recs[:self.counts[kind]]
def problems(self, list_kinds):
out = []
for kind in ("last_rank", "list", "plteamid"):
if self.counts[kind] > len(self.records[kind]):
out.append("%s count %d > %d records" % (kind, self.counts[kind],
len(self.records[kind])))
# NOW_RANK records naming a UID that isn't loaded are skipped
# (0x20a69c), so several may target one slot; the others may not.
taken = Counter()
for kind in self.KINDS:
for r in self.used(kind):
if kind != "now_rank":
taken[r[0]] += 1
if r[0] >= self.slots:
out.append("%s slot %d >= %d" % (kind, r[0], self.slots))
if kind == "last_rank" and not 1 <= r[1] <= 32:
out.append("last_rank rank %d" % r[1])
if kind == "list":
k = s16(r, 4)
if k >= list_kinds:
out.append("list kind %d" % k)
dup = sorted(s for s, n in taken.items() if n > 1)
if dup:
out.append("slots filled twice: %s" % " ".join(map(str, dup)))
return out
def describe(kind, r):
if kind == "last_rank":
return "rank %d of compe %d last season" % (r[1], s16(r, 4))
if kind == "now_rank":
return "rank %d of UID %d%s" % (r[1], s16(r, 4), "" if r[3] else " (keeps UID)")
if kind == "list":
k = s16(r, 4)
if k in LIST_SPECIAL:
return LIST_SPECIAL[k]
if k < 0:
return "left empty (kind %d)" % k
return "random pick from ranks %d-%d of make_list %d" % (r[1], r[2], k)
t = u16(r, 4)
return "team %d" % t if 1 <= t <= MAX_TEAM else "left empty (team %d)" % t
# --- loading -----------------------------------------------------------------
def read_pack(path):
h = pac.load_header(path)
if not isinstance(h, pac.BinPac):
raise ValueError("not a BINPAC")
with open(pac.data_path(path, h), "rb") as f:
out = []
for off, size, name, _ in h.entries:
f.seek(off)
out.append((name, f.read(size)))
return out
def build_pack(path, blobs):
"""(new .PAC bytes, new .HED bytes) for a schedule pack holding `blobs`.
The game reads offsets from the .HED (a copy of the header, padded to
its size; the copies in PRELOAD/STATIONFILE.PAC are what it loads) and
the entries from the .PAC, so both must be written together."""
with open(path, "rb") as f:
data = f.read()
h = pac.BinPac(data[:struct.unpack_from("<I", data)[0]])
out = pac.build_binpac(data[:h.header_size], blobs)
hed_path = path[:-4] + ".HED"
hed_size = os.path.getsize(hed_path)
head = out[:h.header_size]
if len(head) > hed_size:
raise ValueError("%s: the header no longer fits its .HED" % path)
return out, head + bytes(hed_size - len(head))
def find(root, name):
p = os.path.join(root, name)
if not os.path.exists(p):
raise SystemExit("%s: not found" % p)
return p
# --- commands ----------------------------------------------------------------
def cmd_info(root):
sysp = find(root, SYSTEM_PAC)
try:
system = System(read_pack(sysp))
except (ValueError, struct.error) as e:
print("%-45s !! %s" % (sysp, e))
return
uids = year_uids(system.year)
probs = []
count = len(system.savectrl)
if count not in LAYOUTS:
probs.append("savectrl has %d bytes" % count)
elif sorted(uids) != LAYOUTS[count]:
probs.append("UIDs are not 0-%d%s" % (UID_COUNT - 1, "" if count == UID_COUNT
else " and %d-%d" % (UID_COUNT + 1, count - 1)))
for r in system.year:
if r.uid >= 0 and r.kind not in LOAD_KIND:
probs.append("UID %d load kind %d" % (r.uid, r.kind))
if r.uid >= 0 and not 0 <= r.compe < len(system.open_nation):
probs.append("UID %d compe %d" % (r.uid, r.compe))