aorecomp

Anarchy Online classic in the browser

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


tools/data/extract_backyards.py (12442B)


      1 import collections
      2 import hashlib
      3 import json
      4 import math
      5 import pathlib
      6 import struct
      7 
      8 import ao_database
      9 import extract_whompahs
     10 
     11 
     12 class Reader:
     13     def __init__(self, data):
     14         self.data = data
     15         self.offset = 0
     16 
     17     def take(self, size):
     18         if size < 0 or self.offset + size > len(self.data):
     19             raise ValueError(('truncated statel descriptor', self.offset, size))
     20         value = self.data[self.offset:self.offset + size]
     21         self.offset += size
     22         return value
     23 
     24     def word(self):
     25         return struct.unpack('>I', self.take(4))[0]
     26 
     27 
     28 def parse_descriptor(data):
     29     reader = Reader(data)
     30     assert [reader.word() for _ in range(3)] == [102, 103, 1009]
     31     attributes = []
     32     for _ in range(reader.word()):
     33         attribute = reader.word()
     34         if attribute == 2:
     35             event, encoded = reader.word(), reader.word()
     36             assert encoded >= 1009 and encoded % 1009 == 0
     37             functions = []
     38             for _ in range(encoded // 1009 - 1):
     39                 function = dict(id=reader.word(), header_words=[reader.word(), reader.word()])
     40                 function['requirements'] = [dict(zip(('stat', 'value', 'operator'), struct.unpack('>iii', reader.take(12)))) for _ in range(reader.word())]
     41                 function['tick_count'], function['tick_interval'], function['target'], function['argument_header'] = [reader.word() for _ in range(4)]
     42 
     43                 # Preserve the complete selected HighLow argument layouts.
     44                 layouts = {53016: ('4n',), 53059: ('3n', '4x'), 53082: ('4n', '8x'),
     45                            53083: ('4n', '12x'), 53109: (), 53134: ('2s', '4x')}
     46                 assert function['id'] in layouts, ('unsupported statel function', function['id'])
     47                 arguments = []
     48                 for layout in layouts[function['id']]:
     49                     count = int(layout[:-1])
     50                     if layout[-1] == 'x':
     51                         arguments.append(dict(bytes_hex=reader.take(count).hex()))
     52                         continue
     53                     for _ in range(count):
     54                         if layout[-1] == 'n':
     55                             arguments.append(dict(integer=struct.unpack('>i', reader.take(4))[0]))
     56                         else:
     57                             value = reader.take(reader.word())
     58                             assert not value or value[-1] == 0
     59                             arguments.append(dict(string=value[:-1].decode('latin1')))
     60                 function['arguments'] = arguments
     61                 functions.append(function)
     62             attributes.append(dict(event=event, functions=functions))
     63         elif attribute == 15:
     64             assert reader.word() == 24
     65             encoded = reader.word()
     66             assert encoded >= 1009 and encoded % 1009 == 0
     67             attributes.append(dict(stats=[list(struct.unpack('>II', reader.take(8))) for _ in range(encoded // 1009 - 1)]))
     68         else:
     69             assert attribute == 21 and reader.word() == 33
     70             length, description_length = struct.unpack('>HH', reader.take(4))
     71             attributes.append(dict(name=reader.take(length).decode('latin1'), description=reader.take(description_length).decode('latin1')))
     72     assert reader.word() == 0 and reader.offset == len(data)
     73     return attributes
     74 
     75 
     76 def update_routes(routes):
     77     path = pathlib.Path('server/assets/zone_links.yaml')
     78     text = path.read_bytes().decode('ascii')
     79     newline = '\r\n' if '\r\n' in text else '\n'
     80     original, target = text.split('target:' + newline)
     81     lines = target.splitlines()
     82     pending = {(route['playfield'], route['door']['id']): route['door'] for route in routes}
     83     playfield = None
     84     index = 0
     85     while index < len(lines):
     86         if lines[index].startswith('  ') and not lines[index].startswith('   ') and lines[index].endswith(':'):
     87             playfield = int(lines[index].strip()[:-1])
     88         if lines[index].startswith('    - id: '):
     89             identity = int(lines[index].split(': ')[1])
     90             door = pending.pop((playfield, identity), None)
     91             if door is not None:
     92                 end = index + 1
     93                 while end < len(lines) and lines[end].startswith('      '):
     94                     if not lines[end].startswith('       '):
     95                         assert lines[end].strip().split(':')[0] in ('position', 'rotation', 'destination', 'destination_door', 'return', 'requirements', 'refusal_message', 'arrival')
     96                     end += 1
     97 
     98                 # Replace only these already-present doors, retaining the rest verbatim.
     99                 replacement = ['    - id: ' + str(identity)]
    100                 for field in ('position', 'rotation', 'destination', 'destination_door', 'return', 'requirements', 'refusal_message'):
    101                     if field in door:
    102                         replacement.append('      ' + field + ': ' + json.dumps(door[field]))
    103                 if 'arrival' in door:
    104                     replacement.append('      arrival:')
    105                     for field, value in door['arrival'].items():
    106                         replacement.append('        ' + field + ': ' + json.dumps(value))
    107                 lines[index:end] = replacement
    108                 index += len(replacement)
    109                 continue
    110         index += 1
    111     assert not pending, ('missing configured backyard doors', sorted(pending))
    112     path.write_bytes((original + 'target:' + newline + newline.join(lines) + newline).encode('ascii'))
    113 
    114 
    115 def main():
    116     client = pathlib.Path('anarchy-vanilla-14.9.1')
    117     assert (client / 'version.id').read_text().strip() == '14.9.1'
    118     database = ao_database.Database(client)
    119     backyards = {}
    120     for kind, identity in sorted(database.records):
    121         if kind == 1000001:
    122             payload = database.read(kind, identity)
    123             name = payload[8:40].split(b'\0', 1)[0].decode('ascii').strip()
    124             if 'Backyard' in name:
    125                 backyards[identity] = name
    126 
    127     routes, training = [], []
    128     for kind, playfield in sorted(database.records):
    129         if kind != 1000026:
    130             continue
    131         payload = database.read(kind, playfield)
    132         offset = 4
    133         for ordinal in range(struct.unpack_from('<I', payload)[0]):
    134             size = struct.unpack_from('<I', payload, offset)[0]
    135             offset += 4
    136             raw = payload[offset:offset + size]
    137             offset += size
    138             assert len(raw) == size and size == 64 + struct.unpack_from('<I', raw, 60)[0]
    139             if len(raw) < 140 or struct.unpack_from('<I', raw)[0] != 51016:
    140                 continue
    141             words = struct.unpack_from('>19I', raw, 64)
    142             if words[:3] != (102, 103, 1009) or words[4:6] != (2, 16) or words[7] not in (53059, 53082):
    143                 continue
    144             first = struct.unpack_from('>4I', raw, 64 + (15 + 3 * words[10]) * 4)
    145             destination = first[2] if words[7] == 53059 else first[1]
    146             if playfield not in backyards and destination not in backyards:
    147                 continue
    148 
    149             # Validate the entire selected descriptor before admitting any route.
    150             attributes = parse_descriptor(raw[64:])
    151             functions = attributes[0]['functions']
    152             for function in functions:
    153                 assert function['header_words'] == [0, 4] and function['tick_count'] == 1 and function['tick_interval'] == 0 and function['target'] == 2 and function['argument_header'] == 0
    154             door = dict(id=struct.unpack_from('<I', raw, 4)[0], position=list(struct.unpack_from('<3f', raw, 24)), rotation=list(reversed(struct.unpack_from('<4f', raw, 36))), destination=destination)
    155             record = dict(playfield=playfield, ordinal=ordinal, door=door, attributes=attributes, raw_hex=raw.hex(), record_sha256=hashlib.sha256(raw).hexdigest(), resource_sha256=hashlib.sha256(payload).hexdigest())
    156             if functions[0]['id'] == 53082:
    157                 assert len(functions) == 1 and not functions[0]['requirements'] and first[0] == 51102
    158                 assert first[2] == 0 and first[3] == door['id']
    159                 training.append(record)
    160                 continue
    161             assert functions[0]['id'] == 53059 and first[0] == 100001 and first[1] & 65535 == destination and first[3] == 0
    162             assert len(functions) in (1, 2)
    163             if len(functions) == 2:
    164                 assert functions[0]['requirements'] == [dict(stat=54, value=1, operator=2), dict(stat=61, value=999, operator=2), dict(stat=0, value=0, operator=3)]
    165                 assert functions[1]['id'] == 53134 and functions[1]['requirements'] == [dict(stat=61, value=1000, operator=1), dict(stat=54, value=2, operator=1), dict(stat=0, value=0, operator=4)]
    166                 assert functions[1]['arguments'] == [dict(string='You need to be level 2 or have at least 1000 credits to exit to the outside.'), dict(string=''), dict(bytes_hex='00000000')]
    167                 door['requirements'] = functions[0]['requirements']
    168                 door['refusal_message'] = functions[1]['arguments'][0]['string']
    169             else:
    170                 assert not functions[0]['requirements']
    171 
    172             # Use the same authored-line arrival policy as existing whom-pahs.
    173             destination_payload = database.read(1000001, destination)
    174             start, end = extract_whompahs.destination_lines(destination_payload, destination)[first[1]]
    175             position = [(a + b) / 2 for a, b in zip(start, end)]
    176             position[1] += 0.5
    177             heading = math.atan2(start[2] - end[2], end[0] - start[0])
    178             door['arrival'] = dict(position=position, rotation=[0, math.sin(heading / 2), 0, math.cos(heading / 2)])
    179             record.update(arrival_start=start, arrival_end=end, destination_sha256=hashlib.sha256(destination_payload).hexdigest())
    180             routes.append(record)
    181         assert offset == len(payload)
    182     assert len(backyards) == 130 and len(routes) == 260 and len(training) == 130
    183     assert collections.Counter(row['door']['destination'] for row in routes if row['door']['destination'] in backyards) == collections.Counter(backyards.keys())
    184     assert collections.Counter(row['playfield'] for row in routes if row['playfield'] in backyards) == collections.Counter(backyards.keys())
    185     assert collections.Counter(row['playfield'] for row in training) == collections.Counter(backyards.keys())
    186 
    187     # Resolve each training return to its actual statel, not a synthesized identity.
    188     exits = []
    189     for playfield in sorted({row['door']['destination'] for row in training}):
    190         payload = database.read(1000026, playfield)
    191         offset = 4
    192         for ordinal in range(struct.unpack_from('<I', payload)[0]):
    193             size = struct.unpack_from('<I', payload, offset)[0]
    194             offset += 4
    195             raw = payload[offset:offset + size]
    196             offset += size
    197             assert len(raw) == size and size == 64 + struct.unpack_from('<I', raw, 60)[0]
    198             if struct.unpack_from('<I', raw)[0] != 51016:
    199                 continue
    200             attributes = parse_descriptor(raw[64:])
    201             if not any(attribute.get('name', '').startswith('Exit To ') for attribute in attributes):
    202                 continue
    203             assert len(attributes) == 2 and attributes[0]['stats'][1] == [189, 1]
    204             door = dict(id=struct.unpack_from('<I', raw, 4)[0], position=list(struct.unpack_from('<3f', raw, 24)), rotation=list(reversed(struct.unpack_from('<4f', raw, 36))))
    205             door['return'] = True
    206             exits.append(dict(playfield=playfield, ordinal=ordinal, door=door, attributes=attributes, raw_hex=raw.hex(), record_sha256=hashlib.sha256(raw).hexdigest(), resource_sha256=hashlib.sha256(payload).hexdigest()))
    207         assert offset == len(payload)
    208     assert len(exits) == 3 and len({row['playfield'] for row in exits}) == 3
    209     for row in training:
    210         row['door']['destination_door'] = next(exit['door']['id'] for exit in exits if exit['playfield'] == row['door']['destination'])
    211     database.close()
    212     output = pathlib.Path('local/reports/backyards-14.9.1.json')
    213     output.parent.mkdir(parents=True, exist_ok=True)
    214     output.write_text(json.dumps(dict(index_sha256=hashlib.sha256(database.index).hexdigest(), backyards=backyards, routes=routes, training=training, exits=exits), indent=2) + '\n')
    215     update_routes(routes + training + exits)
    216     print('Updated 260 city/backyard routes, 130 training entrances and three returns:', output)
    217 
    218 
    219 if __name__ == '__main__':
    220     main()