Files
gs5579andDevin AI 3d75165ce4 Add IK solving and VMD motion playback with timeline
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:14:40 +00:00

69 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Writes VMD motions: tests/data/column.vmd for the unit tests, or a demo dance for MMD-rigged
models with --demo OUT (standard Japanese bone/morph names; unknown names are ignored)."""
import math
import os
import struct
import sys
LINEAR = bytes([20] * 8 + [107] * 8) + bytes(48)
def name(s, n):
b = s.encode("cp932")[:n]
return b + b"\0" * (n - len(b))
def quat(axis, deg):
# Right-handed rotation converted to MMD's left-handed space: (x, y, z, w) -> (-x, -y, z, w).
s, c = math.sin(math.radians(deg) / 2), math.cos(math.radians(deg) / 2)
x, y, z = (a * s for a in axis)
return (-x, -y, z, c)
def bone(nm, frame, pos=(0, 0, 0), rot=(0, 0, 0, 1)):
# pos is right-handed (+Z = forward), stored left-handed.
return name(nm, 15) + struct.pack("<I3f4f", frame, pos[0], pos[1], -pos[2], *rot) + LINEAR
def write(path, model, bones, morphs, iks=()):
out = b"Vocaloid Motion Data 0002".ljust(30, b"\0") + name(model, 20)
out += struct.pack("<I", len(bones)) + b"".join(bones)
out += struct.pack("<I", len(morphs)) + b"".join(name(n, 15) + struct.pack("<If", f, w) for n, f, w in morphs)
out += struct.pack("<III", 0, 0, 0) # camera, light, self shadow
out += struct.pack("<I", len(iks))
for frame, states in iks:
out += struct.pack("<IBI", frame, 1, len(states))
out += b"".join(name(n, 20) + bytes([on]) for n, on in states)
with open(path, "wb") as f:
f.write(out)
def column(path):
bones = [bone("上半身", 0), bone("上半身", 10, rot=quat((0, 0, 1), 90)), bone("上半身", 20, rot=quat((0, 0, 1), 90)),
bone("センター", 0), bone("センター", 10, pos=(0, 2, 0))]
write(path, "テスト", bones, [("あ", 0, 0.0), ("あ", 10, 1.0)], [(0, [("IK", 0)])])
def demo(path):
bones, morphs = [], []
for f in range(0, 121, 15):
down = (f // 15) % 2 == 1
bones.append(bone("センター", f, pos=(0, -0.8 if down else 0, 0)))
bones.append(bone("左腕", f, rot=quat((0, 0, 1), -35 if down else -20)))
bones.append(bone("右腕", f, rot=quat((0, 0, 1), 35 if down else 20)))
bones.append(bone("頭", f, rot=quat((1, 0, 0), 10 if down else -5)))
morphs += [("あ", f, 0.8 if down else 0.0)]
bones += [bone("左足IK", 0), bone("左足IK", 30, pos=(0, 1.5, 1.5)), bone("左足IK", 60),
bone("右足IK", 60), bone("右足IK", 90, pos=(0, 1.5, 1.5)), bone("右足IK", 120)]
for blink in ("まばたき", "blink"):
morphs += [(blink, 40, 0.0), (blink, 44, 1.0), (blink, 48, 0.0)]
write(path, "demo", bones, morphs)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--demo":
demo(sys.argv[2])
else:
column(os.path.join(os.path.dirname(__file__), "..", "tests", "data", "column.vmd"))