aorecomp

Anarchy Online classic in the browser

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


tools/data/extract_maps.py (11831B)


      1 import hashlib
      2 import io
      3 import json
      4 import math
      5 import pathlib
      6 import struct
      7 import zlib
      8 
      9 import PIL.Image
     10 import ruamel.yaml
     11 import PIL.ImageChops
     12 import PIL.ImageOps
     13 
     14 import ao_database
     15 
     16 
     17 def read_planet_index(text):
     18     name = ''
     19     levels = []
     20     for line in text.splitlines():
     21         fields = line.split()
     22         if not fields:
     23             continue
     24         if fields[0] == 'Name':
     25             name = line.split(' ', 1)[1].strip('"')
     26         elif fields[0] == 'File':
     27             levels.append({'file': fields[1].replace('\\', '/'), 'order': 'column', 'offsets': []})
     28         elif fields[0] == 'TextureSize':
     29             levels[-1]['tile_size'] = int(fields[1])
     30         elif fields[0] == 'Size':
     31             levels[-1]['width'], levels[-1]['height'] = map(int, fields[1:])
     32         elif fields[0] == 'Tiles':
     33             levels[-1]['columns'], levels[-1]['rows'] = map(int, fields[1:])
     34         elif fields[0] == 'MapRect':
     35             levels[-1]['rect'] = list(map(int, fields[1:]))
     36         elif fields[0] == 'FilePos':
     37             levels[-1]['offsets'].append(int(fields[1]))
     38         else:
     39             raise ValueError('Unknown map index field: ' + fields[0])
     40     for level in levels:
     41         assert len(level['offsets']) == level['columns'] * level['rows']
     42     return name, levels
     43 
     44 
     45 def read_png(blob, offset):
     46     assert blob[offset:offset + 8] == b'\x89PNG\r\n\x1a\n', ('PNG signature', offset)
     47     cursor = offset + 8
     48     assert blob[cursor + 4:cursor + 8] == b'IHDR'
     49     width, height = struct.unpack_from('>II', blob, cursor + 8)
     50     while cursor < len(blob):
     51         length = struct.unpack_from('>I', blob, cursor)[0]
     52         kind = blob[cursor + 4:cursor + 8]
     53         cursor += length + 12
     54         assert cursor <= len(blob), ('truncated PNG', offset)
     55         if kind == b'IEND':
     56             assert length == 0
     57             return blob[offset:cursor], width, height
     58     raise ValueError('Missing PNG end chunk')
     59 
     60 
     61 def export_planet(client, output, coordinates):
     62     root = pathlib.Path(client) / 'cd_image/textures/PlanetMap'
     63     name, levels = read_planet_index((root / 'normal/PlanetMapIndexNormal.txt').read_text())
     64     for number, level in enumerate(levels):
     65         blob = (root / level.pop('file')).read_bytes()
     66         directory = output / 'planet' / str(number)
     67         directory.mkdir(parents=True, exist_ok=True)
     68         level['tiles'] = []
     69         for tile, offset in enumerate(level.pop('offsets')):
     70             png, width, height = read_png(blob, offset)
     71             assert width == height == level['tile_size']
     72             path = directory / (str(tile) + '-' + hashlib.sha256(png).hexdigest()[:16] + '.png')
     73             path.write_bytes(png)
     74             level['tiles'].append(path.relative_to(output).as_posix())
     75     return {'name': name, 'bounds': coordinates['planet_bounds'], 'levels': levels}
     76 
     77 
     78 def read_zones(database, coordinates):
     79     zones = []
     80     for kind, identity in sorted(database.records):
     81         if kind != 1000009 or (1000001, identity) not in database.records or identity in [100, 101, 102, 103, 105, 1410]:
     82             continue
     83         ground = database.read(kind, identity)
     84         assert ground[:4] in [b'CHGA', b'GNDA']
     85         width, height, spacing = struct.unpack_from('<HHf', ground, 12)
     86         marker = ground.find(b'\x08\x09\0\0\0\0\0\0\0')
     87         if marker >= 0:
     88             dimensions = []
     89             for field in [4, 5]:
     90                 offset = marker - (8 - field) * 17
     91                 assert ground[offset:offset + 13] == bytes([field]) + struct.pack('<III', 3, 4, 4)
     92                 dimensions.append(struct.unpack_from('<I', ground, offset + 13)[0] - 1)
     93             width, height = dimensions
     94         name = database.read(1000001, identity)[8:40].split(b'\0', 1)[0].decode('ascii').strip()
     95         zone = {'id': identity, 'name': name, 'width': width * spacing, 'height': height * spacing, 'levels': []}
     96         if identity in coordinates['playfields']:
     97             zone['origin'] = coordinates['playfields'][identity]
     98         zones.append(zone)
     99     return zones
    100 
    101 
    102 def ground_image(database, identity):
    103     ground = database.read(1000009, identity)
    104     assert ground[:4] == b'CHGA'
    105     # Archive fields 4 and 5 contain vertex dimensions, including shared edges.
    106     height_table = ground.index(b'\x08\x09\0\0\0\0\0\0\0')
    107     width = struct.unpack_from('<I', ground, height_table - 55)[0] - 1
    108     height = struct.unpack_from('<I', ground, height_table - 38)[0] - 1
    109     block_cells = min(width & -width, height & -height, 64)
    110     texture_count = struct.unpack_from('<H', ground, 24)[0]
    111     identities = struct.unpack_from('<' + str(texture_count) + 'H', ground, 26)
    112 
    113     # Native bbr.dll AnarchyGroundData_t::GenerateTexture (0x1004e0d0)
    114     # selects the texture with the low byte and transforms it with bits 14-15.
    115     textures = []
    116     for texture in identities:
    117         raw = database.read(1010006, texture)
    118         image = PIL.Image.open(io.BytesIO(raw[24:])).convert('RGB')
    119         image = image.resize((4, 4), PIL.Image.Resampling.LANCZOS)
    120         textures.append([image.transpose(transform) for transform in [
    121             PIL.Image.Transpose.FLIP_TOP_BOTTOM, PIL.Image.Transpose.TRANSVERSE,
    122             PIL.Image.Transpose.FLIP_LEFT_RIGHT, PIL.Image.Transpose.TRANSPOSE]])
    123 
    124     # The ground archive has row-major blocks of row-major uint16 tile cells.
    125     image = PIL.Image.new('RGB', (width * 4, height * 4))
    126     marker = ground.index(b'\x0a\x09\0\0\0\0\0\0\0')
    127     size = struct.unpack_from('<I', ground, marker + 9)[0]
    128     cursor = marker + 13
    129     end = cursor + size
    130     block = 0
    131     while cursor < end:
    132         length = struct.unpack_from('<I', ground, cursor)[0]
    133         cells = zlib.decompress(ground[cursor + 4:cursor + 4 + length])
    134         assert len(cells) == block_cells * block_cells * 2
    135         cursor += length + 4
    136         block_x = block % (width // block_cells) * block_cells
    137         block_z = block // (width // block_cells) * block_cells
    138         for cell in range(block_cells * block_cells):
    139             texture = cells[cell * 2]
    140             rotation = cells[cell * 2 + 1] >> 6
    141             x = (block_x + cell % block_cells) * 4
    142             z = (block_z + cell // block_cells) * 4
    143             image.paste(textures[texture][rotation], (x, z))
    144         block += 1
    145     assert cursor == end
    146     assert block == width // block_cells * (height // block_cells)
    147 
    148     # Native bbr.dll AnarchyGroundData_t::CreateBuildingMap (0x1004ba40)
    149     # expands MSB-first building bits into a multiplicative black/white mask.
    150     marker = ground.index(b'\x0b\x09\0\0\0\0\0\0\0')
    151     size = struct.unpack_from('<I', ground, marker + 9)[0]
    152     cursor = marker + 13
    153     end = cursor + size
    154     block = 0
    155     mask = PIL.Image.new('L', image.size, 255)
    156     while cursor < end:
    157         length = struct.unpack_from('<I', ground, cursor)[0]
    158         bits = zlib.decompress(ground[cursor + 4:cursor + 4 + length])
    159         side = block_cells * 2
    160         assert len(bits) == side * side // 8
    161         cursor += length + 4
    162         tile = PIL.Image.frombytes('1', (side, side), bits).convert('L')
    163         tile = PIL.ImageOps.invert(tile).resize((side * 2, side * 2), PIL.Image.Resampling.NEAREST)
    164         x = block % (width // block_cells) * block_cells * 4
    165         z = block // (width // block_cells) * block_cells * 4
    166         mask.paste(tile, (x, z))
    167         block += 1
    168     assert cursor == end
    169     assert block == width // block_cells * (height // block_cells)
    170     image = PIL.ImageChops.multiply(image, mask.convert('RGB'))
    171     return image.transpose(PIL.Image.Transpose.FLIP_TOP_BOTTOM)
    172 
    173 
    174 def read_boundary(database, identity):
    175     # ResourceDatabase 1000021 stores complete closed wall groups, including
    176     # vertices with no destination. Keep the largest positive-area outer group
    177     # as an imagery clip; internal walls and holes do not establish ownership.
    178     if (1000021, identity) not in database.records:
    179         return []
    180     payload = database.read(1000021, identity)
    181     groups = struct.unpack_from('<I', payload)[0]
    182     offset = 4
    183     boundary = []
    184     largest_area = 0
    185     for _ in range(groups):
    186         filler, count = struct.unpack_from('<II', payload, offset)
    187         offset += 8
    188         vertices = [struct.unpack_from('<hBB3f', payload, offset + index * 16) for index in range(count)]
    189         offset += count * 16
    190         polygon = [[vertex[3], vertex[5]] for vertex in vertices]
    191         area = sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(polygon[-1:] + polygon[:-1], polygon)) / 2
    192         if area > largest_area:
    193             largest_area = area
    194             boundary = polygon
    195     assert offset == len(payload)
    196     return boundary
    197 
    198 
    199 def export_ground(database, zone, output):
    200     image = ground_image(database, zone['id'])
    201     levels = []
    202     # Large outdoor maps need a coarse level to keep regional views lightweight.
    203     scales = [16, 4, 1] if max(image.size) > 1536 else [4, 1]
    204     for number, scale in enumerate(scales):
    205         reduced = image.resize((image.width // scale, image.height // scale), PIL.Image.Resampling.LANCZOS)
    206         directory = output / 'zones' / str(zone['id']) / str(number)
    207         directory.mkdir(parents=True, exist_ok=True)
    208         level = {'width': reduced.width, 'height': reduced.height, 'tile_size': 1024,
    209                  'columns': math.ceil(reduced.width / 1024), 'rows': math.ceil(reduced.height / 1024),
    210                  'rect': [0, 0, reduced.width, reduced.height], 'order': 'row', 'tiles': []}
    211         for y in range(level['rows']):
    212             for x in range(level['columns']):
    213                 tile = reduced.crop((x * 1024, y * 1024, min((x + 1) * 1024, reduced.width), min((y + 1) * 1024, reduced.height)))
    214                 buffer = io.BytesIO()
    215                 tile.save(buffer, format='PNG')
    216                 png = buffer.getvalue()
    217                 path = directory / (str(y * level['columns'] + x) + '-' + hashlib.sha256(png).hexdigest()[:16] + '.png')
    218                 path.write_bytes(png)
    219                 level['tiles'].append(path.relative_to(output).as_posix())
    220         levels.append(level)
    221     zone['imagery'] = 'native area map'
    222     zone['levels'] = levels
    223     boundary = read_boundary(database, zone['id'])
    224     if boundary:
    225         zone['boundary'] = boundary
    226 
    227 
    228 def remove_unused_tiles(output, manifest):
    229     # Keep only images referenced by the newly written manifest.
    230     output = output.resolve()
    231     levels = manifest['planet']['levels'] + [level for zone in manifest['zones'] for level in zone['levels']]
    232     referenced = {output / tile for level in levels for tile in level['tiles']}
    233     unused = [path for path in output.rglob('*.png') if path not in referenced]
    234     for path in unused:
    235         assert path.resolve().is_relative_to(output), ('tile outside map directory', path)
    236     removed_bytes = sum(path.stat().st_size for path in unused)
    237     for path in unused:
    238         path.unlink()
    239     return len(unused), removed_bytes
    240 
    241 
    242 def main():
    243     output = pathlib.Path('data/maps')
    244     coordinates = ruamel.yaml.YAML(typ='safe').load(pathlib.Path('server/gamedata/map_coordinates.yaml').read_text())
    245     database = ao_database.Database('anarchy-vanilla-14.9.1')
    246     zones = read_zones(database, coordinates)
    247     for zone in zones:
    248         export_ground(database, zone, output)
    249         print('Exported ground map', zone['id'], zone['name'], flush=True)
    250     database.close()
    251     manifest = {'source': '14.9.1', 'planet': export_planet('anarchy-vanilla-14.9.1', output, coordinates), 'zones': zones}
    252     (output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
    253     removed, removed_bytes = remove_unused_tiles(output, manifest)
    254     print('Removed', removed, 'obsolete tiles:', round(removed_bytes / 1048576, 1), 'MiB')
    255     print('Exported', sum(len(level['tiles']) for level in manifest['planet']['levels']), 'planet map tiles')
    256 
    257 
    258 if __name__ == '__main__':
    259     main()