aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/data/extract_items.py (9132B)


      1 import collections
      2 import hashlib
      3 import json
      4 import pathlib
      5 import struct
      6 
      7 import ao_database
      8 
      9 
     10 # Argument layouts documented by CellAO's Extractor Serializer/FunctionSets.cfg.
     11 # n = signed DWORD, h = reversed four-byte code, s = length-prefixed string,
     12 # x = uninterpreted bytes. These describe serialization, not effect behavior.
     13 argument_layouts = {}
     14 for layout, functions in {
     15     '4n': [53002, 53016, 53142, 53196],
     16     '5n': [53003, 53011, 53073, 53159, 53185],
     17     '2n': [53009, 53035, 53045, 53067, 53087, 53089, 53110, 53111,
     18            53139, 53140, 53149, 53162, 53175, 53177, 53184, 53189,
     19            53193, 53224, 53227, 53238, 53237, 53248, 53249, 53253, 53254],
     20     '2n,4x': [53012, 53028, 53039],
     21     '2n,8x,1n': [53014],
     22     '1n': [53019, 53051, 53066, 53078, 53107, 53133, 53181, 53206,
     23            53222, 53223, 53228, 53236, 53240, 53242, 53239, 53251,
     24            53243, 53250],
     25     '3n': [53025, 53105, 53187, 53230],
     26     '4x,2n': [53026, 53033],
     27     '1n,24x': [53030],
     28     '16x': [53032, 53065, 53075, 53076],
     29     '4x,1n': [53037, 53038, 53055],
     30     '1s,20x': [53044],
     31     '1s': [53054, 53200],
     32     '1s,1n': [53057, 53210, 53247],
     33     '3n,4x': [53059],
     34     '1n,4x': [53060, 53068],
     35     '1h,2n,28x': [53063],
     36     '1h,2n,20x': [53064],
     37     '0x': [53069, 53070, 53086, 53092, 53109, 53118, 53121, 53122,
     38            53126, 53127, 53128, 53130, 53138, 53144, 53153, 53154,
     39            53155, 53164, 53166, 53173, 53176, 53178, 53208, 53209,
     40            53225, 53231, 53232, 53234, 53191, 53241],
     41     '1n,8x': [53079],
     42     '4n,8x': [53082],
     43     '4n,12x': [53083],
     44     '1h': [53100, 53229],
     45     '1s,4x': [53104],
     46     '1s,8x': [53115],
     47     '8x,1n,8x': [53117],
     48     '4x,1h,2n,20x': [53124],
     49     '2s,4x': [53132],
     50     '4x': [53137],
     51     '1h,2n,52x': [53167],
     52     '1n,1h,2n': [53182],
     53     '1h,10n': [53192],
     54     '52x': [53204],
     55     '1h,8n': [53220],
     56     '3n,1s': [53221],
     57     '1h,2n': [53226],
     58     '8n': [53213],
     59     '7n': [53233],
     60     '2n,1x': [53235],
     61     '2s,3x': [53134],
     62     '1s,4n': [53244],
     63     '3s,1h': [53252],
     64 }.items():
     65     for function in functions:
     66         argument_layouts[function] = layout.split(',')
     67 
     68 
     69 class Reader:
     70     def __init__(self, data):
     71         self.data = data
     72         self.offset = 0
     73 
     74     def take(self, size):
     75         if size < 0 or self.offset + size > len(self.data):
     76             raise ValueError(('truncated item data', self.offset, size, len(self.data)))
     77         result = self.data[self.offset:self.offset + size]
     78         self.offset += size
     79         return result
     80 
     81     def word(self):
     82         return struct.unpack('<I', self.take(4))[0]
     83 
     84     def count(self):
     85         encoded = self.word()
     86         if encoded < 1009 or encoded % 1009:
     87             raise ValueError(('invalid serialized count', self.offset - 4, encoded))
     88         return encoded // 1009 - 1
     89 
     90     def pairs(self, count):
     91         return [list(struct.unpack('<II', self.take(8))) for _ in range(count)]
     92 
     93     def requirements(self, count):
     94         return [dict(zip(('stat', 'value', 'operator'),
     95                          struct.unpack('<iii', self.take(12)))) for _ in range(count)]
     96 
     97 
     98 def parse_section(reader, kind):
     99     section = {'type': kind, 'subtype': reader.word()}
    100     count = reader.count()
    101     if kind in (4, 14, 20):
    102         entries = []
    103         for _ in range(count):
    104             entry = {'type': reader.word()}
    105             size = reader.count()
    106             if kind == 4:
    107                 entry['stats'] = reader.pairs(size)
    108             else:
    109                 entry['values'] = [reader.word() for _ in range(size)]
    110             entries.append(entry)
    111         section['entries'] = entries
    112     elif kind == 6:
    113         section['stats'] = reader.pairs(count)
    114     elif kind == 22:
    115         if section['subtype'] != 36:
    116             raise ValueError(('unexpected action subtype', section['subtype']))
    117         section['actions'] = []
    118         for _ in range(count):
    119             action = {'type': reader.word()}
    120             action['requirements'] = reader.requirements(reader.count())
    121             section['actions'].append(action)
    122     elif kind == 23:
    123         section['entries'] = []
    124         for _ in range(count):
    125             entry = {'code': reader.take(4).decode('latin1'),
    126                      'byte_pair': list(reader.take(2))}
    127             entry['bytes_hex'] = reader.take(11).hex()
    128             section['entries'].append(entry)
    129     elif kind == 2:
    130         section['functions'] = []
    131         for _ in range(count):
    132             function = {'id': reader.word(), 'header_words': [reader.word(), reader.word()]}
    133             function['requirements'] = reader.requirements(reader.word())
    134             function['tick_count'] = reader.word()
    135             function['tick_interval'] = reader.word()
    136             function['target'] = reader.word()
    137             function['argument_header'] = reader.word()
    138             if function['id'] not in argument_layouts:
    139                 return None, 'unknown function argument layout %s' % function['id']
    140 
    141             # Preserve skipped bytes as well as typed arguments.
    142             function['arguments'] = []
    143             for layout in argument_layouts[function['id']]:
    144                 size = int(layout[:-1])
    145                 if layout[-1] == 'x':
    146                     function['arguments'].append({'bytes_hex': reader.take(size).hex()})
    147                     continue
    148                 for _ in range(size):
    149                     if layout[-1] == 'n':
    150                         argument = {'integer': struct.unpack('<i', reader.take(4))[0]}
    151                     elif layout[-1] == 'h':
    152                         argument = {'code': reader.take(4)[::-1].decode('latin1')}
    153                     else:
    154                         size_with_zero = reader.word()
    155                         value = reader.take(size_with_zero)
    156                         if value and value[-1] != 0:
    157                             raise ValueError(('unterminated function string', reader.offset))
    158                         argument = {'string': value[:-1].decode('latin1')}
    159                     function['arguments'].append(argument)
    160             section['functions'].append(function)
    161     return section, None
    162 
    163 
    164 def parse_item(payload, kind, identity):
    165     reader = Reader(payload)
    166     item = {'record_type': kind, 'id': identity,
    167             'payload_sha256': hashlib.sha256(payload).hexdigest()}
    168     item['header_words'] = [reader.word() for _ in range(4)]
    169     item['stats'] = reader.pairs(reader.count())
    170     item['quality'] = next((value for key, value in item['stats'] if key == 54), None)
    171     item['text_header'] = [reader.word(), reader.word()]
    172     name_size, description_size = struct.unpack('<HH', reader.take(4))
    173     item['name'] = reader.take(name_size).decode('latin1')
    174     item['description'] = reader.take(description_size).decode('latin1')
    175 
    176     # Stop at the first unknown section instead of guessing its length.
    177     item['sections'] = []
    178     while reader.offset < len(payload):
    179         offset = reader.offset
    180         if len(payload) - offset < 12:
    181             reason = 'trailing bytes'
    182         else:
    183             section_type = reader.word()
    184             if section_type not in (2, 4, 6, 14, 20, 22, 23):
    185                 reason = 'unknown section type %s' % section_type
    186             else:
    187                 section, reason = parse_section(reader, section_type)
    188                 if reason is None:
    189                     section['offset'] = offset
    190                     section['size'] = reader.offset - offset
    191                     item['sections'].append(section)
    192                     continue
    193         item['undecoded'] = {'offset': offset, 'reason': reason,
    194                              'bytes_hex': payload[offset:].hex()}
    195         break
    196     return item
    197 
    198 
    199 def main():
    200     # Read definitions from the selected client; do not mix in a modern item dump.
    201     assert pathlib.Path('anarchy-vanilla-14.9.1/version.id').read_text().strip() == '14.9.1'
    202     database = ao_database.Database('anarchy-vanilla-14.9.1')
    203     catalog = {'client': 'anarchy-vanilla-14.9.1',
    204                'version': pathlib.Path('anarchy-vanilla-14.9.1/version.id').read_text().strip(),
    205                'index_sha256': hashlib.sha256(database.index).hexdigest(),
    206                'text_encoding': 'latin1 (lossless byte mapping)', 'items': []}
    207     counts = collections.Counter()
    208     unknown = collections.Counter()
    209     for kind, identity in sorted(database.records):
    210         if kind not in (1000020, 1040005):
    211             continue
    212         item = parse_item(database.read(kind, identity), kind, identity)
    213         item['record_file_offset'] = database.records[kind, identity]
    214         catalog['items'].append(item)
    215         counts[str(kind)] += 1
    216         if 'undecoded' in item:
    217             unknown[item['undecoded']['reason']] += 1
    218     database.close()
    219 
    220     # Keep the generated catalog outside source control; report residual coverage.
    221     catalog['coverage'] = {'record_counts': dict(counts), 'undecoded_reasons': dict(unknown)}
    222     pathlib.Path('local/data').mkdir(parents=True, exist_ok=True)
    223     pathlib.Path('local/data/items.json').write_text(json.dumps(catalog, separators=(',', ':')) + '\n')
    224     print(json.dumps(catalog['coverage'], indent=2))
    225 
    226 
    227 if __name__ == '__main__':
    228     main()