aorecomp

Anarchy Online classic in the browser

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


tools/data/extract_corpse_poses.py (7104B)


      1 import hashlib
      2 import json
      3 import math
      4 import pathlib
      5 import struct
      6 import zlib
      7 
      8 import yaml
      9 
     10 import ao_database
     11 
     12 
     13 class DeltaStream:
     14     def __init__(self, data, bits):
     15         self.data = data
     16         self.width = (bits + 7) // 8
     17         self.mask = (1 << bits) - 1
     18         self.value = 0
     19         self.cursor = 0
     20 
     21     def read(self):
     22         self.value = (self.value + int.from_bytes(self.data[self.cursor:self.cursor + self.width], 'big')) & self.mask
     23         self.cursor += self.width
     24         assert self.cursor <= len(self.data)
     25         return self.value
     26 
     27     def floating(self):
     28         return struct.unpack('<f', struct.pack('<I', self.read()))[0]
     29 
     30 
     31 def final_keys(payload):
     32     # Source: client/game/bbr.dll/lifted-0070.c,
     33     # sub_251176C0, sub_25118180 and sub_251180A0 (compressed CAT animation).
     34     bits_q, bits_p = payload[60:62]
     35     cursor = 62
     36     streams = []
     37     for bits in (32, 20, bits_q, bits_q, bits_q, bits_q, 32, bits_p, bits_p, bits_p):
     38         compressed, size = struct.unpack_from('<II', payload, cursor)
     39         data = zlib.decompress(payload[cursor + 8:cursor + 8 + compressed])
     40         assert len(data) == size
     41         streams.append(DeltaStream(data, bits))
     42         cursor += 8 + compressed
     43     assert cursor == len(payload)
     44 
     45     keys = {}
     46     for _ in range(struct.unpack_from('<I', payload, 56)[0]):
     47         index, unknown, unsupported, count = [streams[0].read() for _ in range(4)]
     48         assert count > 0
     49         for _ in range(count):
     50             stamp = streams[1].read()
     51             assert stamp <= struct.unpack_from('<I', payload, 44)[0]
     52             rotation = [stream.read() - (1 << (bits_q - 1)) for stream in streams[2:6]]
     53         length = math.sqrt(sum(value * value for value in rotation))
     54         rotation = [f32(value / length) for value in rotation]
     55         bounds = [streams[6].floating() for _ in range(6)]
     56         count = streams[0].read()
     57         assert count > 0
     58         for _ in range(count):
     59             stamp = streams[1].read()
     60             assert stamp <= struct.unpack_from('<I', payload, 44)[0]
     61             position = [f32(bounds[n * 2] + stream.read() / ((1 << bits_p) - 1) *
     62                             (bounds[n * 2 + 1] - bounds[n * 2])) for n, stream in enumerate(streams[7:10])]
     63         assert index not in keys
     64         keys[index] = rotation, position
     65     assert all(stream.cursor == len(stream.data) for stream in streams)
     66     return keys
     67 
     68 
     69 def f32(value):
     70     return struct.unpack('<f', struct.pack('<f', value))[0]
     71 
     72 
     73 def transform(point, matrix):
     74     return [sum(point[i] * matrix[i * 3 + n] for i in range(3)) + matrix[9 + n] for n in range(3)]
     75 
     76 
     77 def held_vertices(mesh, keys):
     78     # The CIR's named root starts the validated hierarchy, followed by mesh sections.
     79     assert mesh.count(b'-nobone-') == 1
     80     cursor = mesh.index(b'-nobone-') - 8
     81     count = struct.unpack_from('<I', mesh, cursor)[0]
     82     assert set(keys) == set(range(count))
     83     cursor += 4
     84     hierarchy = []
     85     for _ in range(count):
     86         size = struct.unpack_from('<I', mesh, cursor)[0]
     87         cursor += 4 + size
     88         scale, children = struct.unpack_from('<fI', mesh, cursor)
     89         cursor += 8
     90         hierarchy.append((scale, struct.unpack_from('<' + 'I' * children, mesh, cursor)))
     91         cursor += children * 4
     92 
     93     # Row-vector hierarchy composition with float32 rounding.
     94     # Source: client/game/bbr.dll/lifted-0061.c, sub_250F5FF0/sub_250F6070.
     95     matrices = {}
     96 
     97     def compose(index, parent, scale):
     98         assert index not in matrices
     99         x, y, z, w = keys[index][0]
    100         rotation = [1-2*y*y-2*z*z, 2*x*y+2*z*w, 2*x*z-2*y*w,
    101                     2*x*y-2*z*w, 1-2*x*x-2*z*z, 2*y*z+2*x*w,
    102                     2*x*z+2*y*w, 2*y*z-2*x*w, 1-2*x*x-2*y*y]
    103         matrix = [f32(sum(rotation[r*3+k] * parent[k*3+c] for k in range(3))) for r in range(3) for c in range(3)]
    104         matrix += [f32(value) for value in transform([f32(value * scale) for value in keys[index][1]], parent)]
    105         matrices[index] = matrix
    106         for child in hierarchy[index][1]:
    107             compose(child, matrix, f32(scale * hierarchy[index][0]))
    108 
    109     compose(0, [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], 1)
    110     assert len(matrices) == count
    111     sections = struct.unpack_from('<I', mesh, cursor)[0]
    112     cursor += 4
    113     points = set()
    114     for section in range(sections):
    115         size = struct.unpack_from('<I', mesh, cursor)[0]
    116         cursor += 4 + size
    117         parts = struct.unpack_from('<I', mesh, cursor)[0]
    118         cursor += 4
    119         for _ in range(parts):
    120             material, vertices = struct.unpack_from('<II', mesh, cursor)
    121             cursor += 8
    122             for _ in range(vertices):
    123                 values = struct.unpack_from('<14f2If', mesh, cursor)
    124                 cursor += 68
    125                 first, second, weight = values[14:]
    126                 assert 0 <= weight <= 1 and first < count and second < count
    127                 point = transform(values[:3], matrices[first])
    128                 if weight <= .99:
    129                     other = transform(values[3:6], matrices[second])
    130                     point = [point[n] * weight + other[n] * (1 - weight) for n in range(3)]
    131                 points.add(tuple(round(f32(value), 6) for value in point))
    132             indices = struct.unpack_from('<I', mesh, cursor)[0]
    133             cursor += 4
    134             assert max(struct.unpack_from('<' + 'H' * indices, mesh, cursor)) < vertices
    135             cursor += indices * 2
    136         # Selected resources have two empty fields between selection groups.
    137         # Do not interpret an empty group's fields as the next group's header.
    138         if section < sections - 1:
    139             assert struct.unpack_from('<II', mesh, cursor) == (0, 0)
    140             cursor += 8
    141     assert points
    142     return sorted(points)
    143 
    144 
    145 # Held poses use the original sampler and skeleton conventions, with native corpse checks.
    146 assert pathlib.Path('anarchy-vanilla-14.9.1/version.id').read_text().strip() == '14.9.1'
    147 database = ao_database.Database('anarchy-vanilla-14.9.1')
    148 monsters = yaml.safe_load(pathlib.Path('server/gamedata/monsters.yaml').read_text())
    149 selected = {17649, 17655, 26088, 26147, 30369, 38387}
    150 lines = ['# Generated by tools/data/extract_corpse_poses.py from original 14.9.1 resources.',
    151          '# Held-pose vertices at unit scale; this is geometry, not an original server placement rule.']
    152 for monster in monsters:
    153     if monster['monster_data'] not in selected:
    154         continue
    155     mesh = database.read(1010002, monster['mesh'])
    156     animation = database.read(1010003, monster['death_animations'][0])
    157     points = held_vertices(mesh, final_keys(animation))
    158     lines += [f"{monster['monster_data']}:", f"  mesh: {monster['mesh']}",
    159               f"  animation: {monster['death_animations'][0]}",
    160               f"  # Mesh SHA-256: {hashlib.sha256(mesh).hexdigest()}",
    161               f"  # Animation SHA-256: {hashlib.sha256(animation).hexdigest()}", '  vertices:']
    162     lines += ['    - ' + json.dumps(point) for point in points]
    163     print(monster['monster_data'], len(points))
    164 database.close()
    165 pathlib.Path('server/gamedata/corpse_poses.yaml').write_text('\n'.join(lines) + '\n')