mdl_bones.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #!/usr/bin/env python3
  2. """Dumps a puppet .mdl file's MDLS bone array: parent index, bind-pose matrix determinant
  3. (to spot a mirrored/negative-scale bone), and translation - without needing a debug build.
  4. Mirrors the parsing in CImage.cpp's parsePuppetBones()/readPuppetMeshData(): MDLS header is
  5. 9 bytes, then nextSectionOffset(u32) + boneCount(u32), then per bone: null-terminated name
  6. + type(u32) + parent(i32) + matrixBytes(u32) + [16 floats if matrixBytes==64] + null-terminated
  7. extra string (empty for most rigs, jiggle/physics JSON for some). The 16 floats are the file's
  8. row-major matrix - reshaping them row-major (not glm's column-major convention) gives the actual authored matrix back, which is what this script does.
  9. With MDLS version 2+ and its flag byte set, a second matrix per bone follows: the rest pose the animation starts
  10. from (the records above are the bind pose the vertices and inverse bind matrices are in, wallpaper64.exe 2.8.42
  11. sub_1401FBAE0/sub_1401FDF90). Those are printed next to the record's translation. The MDLV header (version,
  12. format, materials, vertex/index byte counts per mesh) is printed first.
  13. Usage:
  14. mdl_bones.py <path-to-puppet.mdl>
  15. mdl_bones.py --scan [workshop dir] every .mdl inside the installed scene.pkg files whose rest pose differs
  16. from the bind pose (default dir: the sandbox workshop library)
  17. Needs: pip install numpy
  18. """
  19. import glob
  20. import os
  21. import struct
  22. import sys
  23. import numpy as np
  24. def read_cstr(data, offset):
  25. end = data.index(b'\x00', offset)
  26. return data[offset:end].decode('latin1', errors='replace'), end + 1
  27. def print_meshes(data):
  28. tag, offset = read_cstr(data, 0)
  29. if not tag.startswith('MDLV'):
  30. return
  31. version = int(tag[4:])
  32. default_format, materials_per_mesh, mesh_count = struct.unpack_from('<III', data, offset)
  33. offset += 12
  34. print(tag, 'defaultFormat', hex(default_format), 'meshes', mesh_count)
  35. for mesh in range(mesh_count):
  36. materials = []
  37. for _ in range(materials_per_mesh):
  38. material, offset = read_cstr(data, offset)
  39. materials.append(material)
  40. flags = struct.unpack_from('<I', data, offset)[0]
  41. offset += 4
  42. if flags & 4:
  43. offset += 4
  44. if version >= 17:
  45. offset += 24
  46. vertex_format = default_format
  47. if version >= 15:
  48. vertex_format = struct.unpack_from('<I', data, offset)[0]
  49. offset += 4
  50. vertex_bytes = struct.unpack_from('<I', data, offset)[0]
  51. offset += 4 + vertex_bytes
  52. index_bytes = struct.unpack_from('<I', data, offset)[0]
  53. offset += 4 + index_bytes
  54. print(f' mesh {mesh} {materials} flags={hex(flags)} format={hex(vertex_format)} '
  55. f'vertexBytes={vertex_bytes} indexBytes={index_bytes}')
  56. if version >= 21:
  57. print(' (version 21+ trailing per-mesh records not walked, only the first mesh is reliable)')
  58. break
  59. def read_bones(data, mdls_offset):
  60. """Returns (version, [(name, parent, matrix or None, extra)], [rest matrices] or None)."""
  61. version = int(data[mdls_offset + 4:mdls_offset + 8])
  62. offset = mdls_offset + 13
  63. bone_count = struct.unpack_from('<I', data, offset)[0]
  64. offset += 4
  65. bones = []
  66. for i in range(bone_count):
  67. name, offset = read_cstr(data, offset)
  68. offset += 4
  69. parent, matrix_bytes = struct.unpack_from('<iI', data, offset)
  70. offset += 8
  71. matrix = None
  72. if matrix_bytes == 64:
  73. matrix = np.array(struct.unpack_from('<16f', data, offset), dtype=float).reshape(4, 4)
  74. elif matrix_bytes > 4096:
  75. raise ValueError(f"bone {i} has an implausible matrix byte count ({matrix_bytes}), layout desynced")
  76. offset += matrix_bytes
  77. extra, offset = read_cstr(data, offset)
  78. bones.append((name, parent, matrix, extra))
  79. if version < 2:
  80. return version, bones, None
  81. extra_count = struct.unpack_from('<H', data, offset)[0]
  82. offset += 2
  83. for _ in range(extra_count):
  84. _, offset = read_cstr(data, offset)
  85. offset += 8 + 64
  86. if not data[offset]:
  87. return version, bones, None
  88. offset += 1
  89. rest = [np.array(struct.unpack_from('<16f', data, offset + 64 * i), dtype=float).reshape(4, 4)
  90. for i in range(bone_count)]
  91. return version, bones, rest
  92. def scan(workshop):
  93. for pkg in sorted(glob.glob(os.path.join(workshop, '*', 'scene.pkg'))):
  94. with open(pkg, 'rb') as f:
  95. f.read(struct.unpack('<I', f.read(4))[0])
  96. entries = []
  97. for _ in range(struct.unpack('<I', f.read(4))[0]):
  98. name = f.read(struct.unpack('<I', f.read(4))[0]).decode('utf-8', errors='replace')
  99. entries.append((name, *struct.unpack('<II', f.read(8))))
  100. base = f.tell()
  101. for name, offset, length in entries:
  102. if not name.endswith('.mdl'):
  103. continue
  104. f.seek(base + offset)
  105. data = f.read(length)
  106. mdls = data.find(b'MDLS')
  107. if mdls < 0:
  108. continue
  109. try:
  110. _, bones, rest = read_bones(data, mdls)
  111. except (ValueError, struct.error) as ex:
  112. print(pkg.split(os.sep)[-2], name, 'ERROR', ex)
  113. continue
  114. if rest is None:
  115. continue
  116. difference = max(np.abs(r - b[2]).max() for r, b in zip(rest, bones) if b[2] is not None)
  117. if difference > 0.01:
  118. print(pkg.split(os.sep)[-2], name, f'rest pose differs from bind pose by up to {difference:.1f}')
  119. def main(path):
  120. data = open(path, 'rb').read()
  121. print_meshes(data)
  122. marker_size = 9
  123. mdls_offset = data.find(b'MDLS', marker_size)
  124. if mdls_offset < 0:
  125. raise SystemExit("no MDLS section found - not a puppet mesh, or a layout this script doesn't handle")
  126. print('MDLS at', mdls_offset, 'file size', len(data))
  127. offset = mdls_offset + 9 # skip the MDLS0001-style 9-byte magic
  128. next_section_offset = struct.unpack_from('<I', data, offset)[0]
  129. offset += 4
  130. bone_count = struct.unpack_from('<I', data, offset)[0]
  131. offset += 4
  132. print('nextSectionOffset', next_section_offset, 'boneCount', bone_count)
  133. _, bones, rest = read_bones(data, mdls_offset)
  134. for i, (name, parent, matrix, extra) in enumerate(bones):
  135. extra_note = f" extra={extra}" if extra else ""
  136. if matrix is None:
  137. print(f"{i} parent={parent} name={name!r} NO MATRIX{extra_note}")
  138. continue
  139. det = np.linalg.det(matrix[:3, :3])
  140. translation = matrix[3, :3] # row-vector convention: translation lives in the last row
  141. flag = " <-- MIRRORED/NEGATIVE SCALE" if det < 0 else ""
  142. rest_note = f" rest={rest[i][3, :3]}" if rest is not None else ""
  143. print(f"{i} parent={parent} name={name!r} det3x3={det:.5f} translation={translation}{rest_note}{flag}"
  144. f"{extra_note}")
  145. if __name__ == '__main__':
  146. if len(sys.argv) >= 2 and sys.argv[1] == '--scan':
  147. scan(sys.argv[2] if len(sys.argv) > 2 else '/workspace/SteamLibrary/steamapps/workshop/content/431960')
  148. elif len(sys.argv) == 2:
  149. main(sys.argv[1])
  150. else:
  151. print(__doc__)
  152. raise SystemExit(1)