File size: 20,187 Bytes
a54e6a7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | """Effector-keyframe moves evaluated one frame at a time (real-time). An agent designs a move as phases of body-part
goals; this module turns it into a pose each frame from the live world state, with automatic feet (plant / step /
tuck in the air), a smoothed balance correction and floor clamping. No clip library is involved.
Conventions: cm, UE axes (+X forward at yaw 0, +Y right, +Z up). Body-frame points are [forward, right, up] from the
root joint (pelvis). Pitch > 0 tips a bone nose-down / tail-up; yaw > 0 turns left (counter-clockwise from above);
roll > 0 leans left. A bone rotates about its parent joint unless "pivot" names another joint.
MoveSpec (JSON-able dict); every list is aligned with `keys`:
name, design: str (why the move fits the character), keys: [0, k1, ..., duration] frame offsets, ease: per segment
root: {"points": [P, ...], "arc": [apex cm per segment], "yaw": [rad, ...], "face": [0..1 per key], "retarget": k}
Root points place the body CENTRE (mid torso); z is relative to standing height. P = [f, r, u] in the
move-start body frame, or {"space": "target", "p": [...]}: origin at the target's centre, +x from mover to
target, sampled at move start and re-sampled when segment `retarget` begins (so a feint tracks a dodge; keep
target-space points off key `retarget`). "face" blends the base yaw from the start yaw (0) to the target (1).
spine / neck: {"joint": name, "pivot": name, "pitch": [...], "yaw": [...], "roll": [...]} added to the posture
chains: {"tail" | "wing_l" | "wing_r" | "body": {"pitch": [...], "yaw": [...]}} spread evenly over the chain
limbs: {limb: [P | {"space": "body"|"target"|"start", "p": [...]} | None, ...]} limb = hand_l/hand_r/foot_l/foot_r
(humanoid), front_l/front_r/hind_l/hind_r (quadruped). None = not driven: feet plant / step by themselves,
hands keep the posture. A None key before a goal starts from wherever the limb is; a foot released in the air
steps back down.
weapon: {"dir": [[f, r, u] | None, ...]} blade direction in the body frame (None = posture)
hit: {"window": [from, to], "parts": [joint names] | ["weapon"], "radius": cm, "damage": n}
invulnerable: [from, to]
Posture (idle, per character): {"spine": {...}, "neck": {...}, "chains": {...}, "limbs": {hand: [f, r, u]},
"weapon_dir": [f, r, u], "root_z": cm, "stance": {foot: [f, r]}} with single values instead of lists.
"""
import json
import numpy as np
from .geometry import rot_axis, UP
EASE = {"io": lambda u: u * u * (3 - 2 * u), "i": lambda u: u * u, "o": lambda u: 1 - (1 - u) ** 2, "l": lambda u: u}
TORSO = ("pelvis", "spine_01", "spine_02")
flat = lambda v: np.array([v[0], v[1], 0.0])
wrap = lambda a: float((a + np.pi) % (2 * np.pi) - np.pi)
def axes(yaw):
return np.array([np.cos(yaw), np.sin(yaw), 0.0]), np.array([-np.sin(yaw), np.cos(yaw), 0.0])
def body_to_world(origin, yaw, p):
f, r = axes(yaw)
return np.asarray(origin, float) + f * p[0] + r * p[1] + UP * p[2]
def mirror(spec):
"""Left-right mirrored copy of a MoveSpec."""
s = json.loads(json.dumps(spec))
def flip_p(P):
if P is not None:
(P["p"] if isinstance(P, dict) else P)[1] *= -1
for P in s.get("root", {}).get("points", []):
flip_p(P)
if "yaw" in s.get("root", {}):
s["root"]["yaw"] = [-v for v in s["root"]["yaw"]]
for name in ("spine", "neck"):
for a in ("yaw", "roll"):
if a in s.get(name, {}):
s[name][a] = [-v for v in s[name][a]]
for g in s.get("chains", {}):
if "yaw" in s["chains"][g]:
s["chains"][g]["yaw"] = [-v for v in s["chains"][g]["yaw"]]
swap = lambda n: n[:-1] + {"l": "r", "r": "l"}.get(n[-1], n[-1])
s["limbs"] = {swap(k): v for k, v in s.get("limbs", {}).items()}
for vals in s["limbs"].values():
for P in vals:
flip_p(P)
for d in s.get("weapon", {}).get("dir", []):
if d is not None:
d[1] *= -1
return s
# ---------------------------------------------------------------------------------------------------- pose utilities
def rotate_subtree(pose, sk, joint, R, pivot=None):
idx = sk.descendants(joint)
p = pose[sk.index[pivot] if pivot else sk.parent_idx[sk.index[joint]]].copy()
pose[idx] = (pose[idx] - p) @ R.T + p
def ik2(pose, sk, chain, target, pole):
"""Two-bone IK with exact bone lengths; the end joint's subtree moves with it."""
i0, i1, i2 = (sk.index[n] for n in chain)
L1 = np.linalg.norm(sk.rest[i1] - sk.rest[i0]); L2 = np.linalg.norm(sk.rest[i2] - sk.rest[i1])
a = pose[i0].copy(); d = np.asarray(target, float) - a
n = np.linalg.norm(d); dn = d / max(n, 1e-6)
dist = float(np.clip(n, abs(L1 - L2) + 1e-3, (L1 + L2) * 0.999))
cos_a = np.clip((L1 * L1 + dist * dist - L2 * L2) / (2 * L1 * dist), -1, 1)
pole = np.asarray(pole, float); pole = pole - dn * (pole @ dn); pn = np.linalg.norm(pole)
if pn < 1e-6:
pole = np.cross(dn, UP); pn = max(np.linalg.norm(pole), 1e-6)
pole = pole / pn
pose[i1] = a + dn * L1 * cos_a + pole * L1 * np.sqrt(max(0.0, 1 - cos_a ** 2))
pose[sk.descendants(chain[2])] += a + dn * dist - pose[i2]
def limb_chain(sk, limb):
if sk.family == "humanoid":
side = limb[-1]
return {"hand": (f"upperarm_{side}", f"lowerarm_{side}", f"hand_{side}"),
"foot": (f"thigh_{side}", f"calf_{side}", f"foot_{side}")}[limb[:-2]]
if limb.startswith("leg"):
return (f"{limb}_hip", f"{limb}_knee", f"{limb}_foot")
return (f"{limb}_upper", f"{limb}_lower", f"{limb}_foot")
def foot_limbs(sk):
if sk.family == "humanoid":
return ["foot_l", "foot_r"]
return sorted({n.rsplit("_", 1)[0] for n in sk.joints if n.endswith("_foot")})
def chain_group(sk, group):
pre = {"tail": "tail_", "wing_l": "wing_l_", "wing_r": "wing_r_", "body": "body_"}[group]
return [n for n in sk.joints if n.startswith(pre)]
# -------------------------------------------------------------------------------------------------------- move runs
class MoveRun:
"""One execution of a MoveSpec by an actor, started at world frame t0 against a target actor."""
def __init__(self, spec, actor, target, t0):
self.spec, self.actor, self.target, self.t0 = spec, actor, target, t0
self.keys = list(spec["keys"]); self.duration = self.keys[-1]
self.ease = spec.get("ease") or ["io"] * (len(self.keys) - 1)
self.start_yaw = actor.yaw
self.start_center = body_to_world(flat(actor.root), actor.yaw, [actor.center_offset, 0, 0]) + UP * (actor.root[2] - actor.base_z)
self._sample_target()
self.retarget = spec.get("root", {}).get("retarget"); self.retargeted = False
self.captured = {}
self.hit_done = False
def _sample_target(self):
me = flat(self.actor.center())
tp = flat(self.target.center()) if self.target is not None else me + axes(self.start_yaw)[0] * 300
d = tp - me
yaw = float(np.arctan2(d[1], d[0])) if np.linalg.norm(d) > 1 else self.start_yaw
self.target_origin, self.target_yaw = tp, self.start_yaw + wrap(yaw - self.start_yaw)
# ---- time
def seg(self, t):
tau = min(max(t - self.t0, 0), self.duration)
k = int(max(0, min(len(self.keys) - 2, np.searchsorted(self.keys, tau, side="right") - 1)))
if self.retarget is not None and not self.retargeted and k >= self.retarget:
self._sample_target(); self.retargeted = True
span = max(1, self.keys[k + 1] - self.keys[k])
u = EASE[self.ease[k] if k < len(self.ease) else "io"](min(1.0, (tau - self.keys[k]) / span))
return k, u, tau
def done(self, t):
return t - self.t0 >= self.duration
def in_window(self, t, window):
return window is not None and window[0] <= t - self.t0 <= window[1]
def phase(self, t):
"""'windup' before the hit window, 'active' inside it, 'recovery' after it (None if the move has no hit)."""
h = self.spec.get("hit")
if not h:
return None
tau = t - self.t0
return "windup" if tau < h["window"][0] else "active" if tau <= h["window"][1] else "recovery"
# ---- channels
@staticmethod
def _lerp(vals, k, u):
return vals[k] * (1 - u) + vals[k + 1] * u
def start_root(self):
return flat(self.start_center) - axes(self.start_yaw)[0] * self.actor.center_offset + UP * self.actor.base_z
def point(self, P, now_root, now_yaw):
sp, p = (P.get("space", "start"), P["p"]) if isinstance(P, dict) else ("start", P)
if sp == "target":
return body_to_world(self.target_origin, self.target_yaw, p)
if sp == "body":
return body_to_world(now_root, now_yaw, p)
return body_to_world(self.start_root(), self.start_yaw, p)
def _yaw_at(self, k):
r = self.spec.get("root", {})
face = r.get("face", [0.0] * len(self.keys))[k]
return self.start_yaw * (1 - face) + self.target_yaw * face + (r["yaw"][k] if r.get("yaw") else 0.0)
def _center_at(self, k):
P = self.spec["root"]["points"][k]
if isinstance(P, dict) and P.get("space") == "target":
p = P["p"]; c = body_to_world(self.target_origin, self.target_yaw, [p[0], p[1], 0.0])
c[2] = p[2]
return c
p = P["p"] if isinstance(P, dict) else P
return body_to_world(self.start_center, self.start_yaw, p)
def root_pose(self, t):
k, u, _ = self.seg(t)
r = self.spec.get("root", {})
yaw = self._yaw_at(k) * (1 - u) + self._yaw_at(k + 1) * u
if r.get("points"):
c = self._center_at(k) * (1 - u) + self._center_at(k + 1) * u
arc = r.get("arc")
if arc and k < len(arc):
c[2] += 4 * arc[k] * u * (1 - u)
else:
c = self.start_center.copy()
root = c - axes(yaw)[0] * self.actor.center_offset
root[2] = self.actor.base_z + c[2]
return root, yaw
def rot(self, name, t):
ch = self.spec.get(name)
if not ch:
return {}
k, u, _ = self.seg(t)
return {a: self._lerp(ch[a], k, u) for a in ("pitch", "yaw", "roll") if a in ch}
def chains(self, t):
k, u, _ = self.seg(t)
return {g: {a: self._lerp(v[a], k, u) for a in ("pitch", "yaw") if a in v} for g, v in self.spec.get("chains", {}).items()}
def limb_target(self, limb, t, current_world, now_root, now_yaw):
vals = self.spec.get("limbs", {}).get(limb)
if vals is None:
return None
k, u, _ = self.seg(t)
a, b = vals[k], vals[k + 1]
if b is None:
return None
if a is None:
if (limb, k) not in self.captured:
self.captured[(limb, k)] = np.asarray(current_world, float).copy()
wa = self.captured[(limb, k)]
else:
wa = self.point(a, now_root, now_yaw)
return wa * (1 - u) + self.point(b, now_root, now_yaw) * u
def weapon_dir(self, t, default):
vals = self.spec.get("weapon", {}).get("dir")
if not vals:
return None
k, u, _ = self.seg(t)
a = np.asarray(vals[k] if vals[k] is not None else default, float)
b = np.asarray(vals[k + 1] if vals[k + 1] is not None else default, float)
v = a * (1 - u) + b * u
return v / max(np.linalg.norm(v), 1e-6)
# ------------------------------------------------------------------------------------------------------------ actor
class Actor:
"""Live character state: root/yaw, posture, planted feet and steps, current move, weapon, hp."""
def __init__(self, name, skeleton, slot, center_xy, yaw, posture=None, hp=10):
self.name, self.sk, self.slot = name, skeleton, slot
self.posture = posture or {}
sk = skeleton
torso = [sk.index[j] for j in TORSO if j in sk.index]
self.center_offset = float(sk.rest[torso, 0].mean() - sk.rest[0, 0])
self.base_z = float(sk.rest[0, 2] + self.posture.get("root_z", 0.0))
self.yaw = float(yaw)
self.root = body_to_world([center_xy[0], center_xy[1], self.base_z], self.yaw, [-self.center_offset, 0, 0])
self.move = None; self.last_root = self.root.copy()
self.pose = sk.place(self.root, self.yaw)
self.feet = foot_limbs(sk)
st = self.posture.get("stance") or {}
self.foot_offset = {}
for ft in self.feet:
rel = sk.rest[sk.index[limb_chain(sk, ft)[2]]] - sk.rest[0]
self.foot_offset[ft] = np.array([st[ft][0], st[ft][1], 0.0]) if ft in st else flat(rel)
self.plants = {ft: flat(body_to_world(self.root, self.yaw, self.foot_offset[ft])) for ft in self.feet}
self.steps, self.driven = {}, set()
bl = sk.bone_lengths
self.leg_len = {ft: float(sum(bl[sk.index[j]] for j in limb_chain(sk, ft)[1:])) for ft in self.feet}
self.step_frames = 6 if sk.family == "humanoid" else 7
self.balance = np.zeros(3)
self.weapon = None
self.hp = hp; self.invulnerable = False; self.floor_clamps = 0
def center(self):
return self.pose[[self.sk.index[j] for j in TORSO if j in self.sk.index]].mean(axis=0)
def start(self, spec, target, t):
self.move = MoveRun(spec, self, target, t)
def shift(self, v):
"""External displacement (collision push, arena bounds); keeps a running move consistent."""
v = flat(v)
self.root += v; self.last_root += v; self.pose += v
if self.weapon is not None:
self.weapon += v
if self.move is not None:
self.move.start_center += v
# ---- one frame
def evaluate(self, t):
sk, mv, prev = self.sk, self.move, self.pose
if mv is not None:
self.root, self.yaw = mv.root_pose(t)
lift = self.root[2] - self.base_z
air = lift > 1.0
vel = flat(self.root - self.last_root); self.last_root = self.root.copy()
pose = sk.place(self.root, self.yaw)
f, r = axes(self.yaw)
for name, default in (("spine", "spine_01"), ("neck", "neck_01")):
base = self.posture.get(name, {}); add = mv.rot(name, t) if mv else {}
ms = mv.spec.get(name, {}) if mv else {}
joint = ms.get("joint") or base.get("joint", default)
if joint not in sk.index:
continue
ang = {a: base.get(a, 0.0) + add.get(a, 0.0) for a in ("pitch", "yaw", "roll")}
if any(abs(v) > 1e-9 for v in ang.values()):
R = rot_axis(UP, ang["yaw"]) @ rot_axis(r, ang["pitch"]) @ rot_axis(f, ang["roll"])
rotate_subtree(pose, sk, joint, R, ms.get("pivot") or base.get("pivot"))
mch = mv.chains(t) if mv else {}
for group in sorted(set(self.posture.get("chains", {})) | set(mch)):
js = chain_group(sk, group)
if not js:
continue
base = self.posture.get("chains", {}).get(group, {}); add = mch.get(group, {})
pitch = (base.get("pitch", 0.0) + add.get("pitch", 0.0)) / len(js)
yaw_ = (base.get("yaw", 0.0) + add.get("yaw", 0.0)) / len(js)
R = rot_axis(UP, yaw_) @ rot_axis(r, pitch)
for j in js:
rotate_subtree(pose, sk, j, R)
move_limbs = mv.spec.get("limbs", {}) if mv else {}
for limb in sorted((set(self.posture.get("limbs", {})) | set(move_limbs)) - set(self.feet)):
chain = limb_chain(sk, limb)
tgt = mv.limb_target(limb, t, prev[sk.index[chain[2]]], self.root, self.yaw) if mv else None
if tgt is None and limb in self.posture.get("limbs", {}):
tgt = body_to_world(self.root, self.yaw, self.posture["limbs"][limb])
if tgt is not None:
ik2(pose, sk, chain, tgt, pole=-UP + r * (0.4 if limb.endswith("r") else -0.4) - f * 0.2)
driven = set()
for ft in self.feet:
chain = limb_chain(sk, ft); prev_end = prev[sk.index[chain[2]]]
tgt = mv.limb_target(ft, t, prev_end, self.root, self.yaw) if mv else None
if tgt is not None:
driven.add(ft); self.steps.pop(ft, None)
tgt = np.array(tgt, float); tgt[2] = max(tgt[2], 0.0)
ik2(pose, sk, chain, tgt, pole=f + UP * 0.2)
continue
desired = flat(body_to_world(self.root, self.yaw, self.foot_offset[ft])) + vel * 3
if ft in self.driven: # released this frame: step down from where it was
self.steps[ft] = [prev_end.copy(), desired, t, self.step_frames]
if air:
self.steps.pop(ft, None)
self.plants[ft] = self.plants[ft] + 0.35 * (desired - self.plants[ft])
target = self.plants[ft] + UP * (lift + min(0.4 * lift, 0.3 * self.leg_len[ft]))
elif ft in self.steps:
st = self.steps[ft]; st[1] = desired
s = min(1.0, (t - st[2]) / st[3]); e = EASE["io"](s)
target = st[0] * (1 - e) + st[1] * e + UP * 0.1 * min(sk.height, 200.0) * np.sin(np.pi * s)
if s >= 1.0:
self.plants[ft] = flat(st[1]); del self.steps[ft]
else:
target = self.plants[ft]
hip = pose[sk.index[chain[0]]]
err = np.linalg.norm(self.plants[ft] - desired)
reach = np.linalg.norm(hip - self.plants[ft]) / max(self.leg_len[ft], 1e-6)
if (err > 0.3 * self.leg_len[ft] or reach > 0.98) and len(self.steps) < max(1, len(self.feet) // 2):
self.steps[ft] = [self.plants[ft].copy(), desired, t, self.step_frames]
target = np.array(target, float); target[2] = max(target[2], 0.0)
ik2(pose, sk, chain, target, pole=f + UP * 0.2)
self.driven = driven
if sk.weapon is not None:
default = self.posture.get("weapon_dir", [0.94, 0.0, 0.34])
d = mv.weapon_dir(t, default) if mv else None
d = np.asarray(default, float) if d is None else d
dw = f * d[0] + r * d[1] + UP * d[2]; dw = dw / np.linalg.norm(dw)
butt = pose[sk.index[sk.weapon.hand]] - dw * sk.weapon.grip_offset
self.weapon = np.stack([butt, butt + dw * sk.weapon.length])
# balance: ease the torso back over the grounded, non-driven feet (smoothed, recomputed each frame)
want = np.zeros(3)
support = [self.plants[ft] for ft in self.feet if ft not in self.steps and ft not in driven]
if not air and support:
com = flat(pose[[sk.index[j] for j in TORSO if j in sk.index]].mean(axis=0)); cen = np.mean(support, axis=0)
radius = max(max(np.linalg.norm(s - cen) for s in support), 0.12 * sk.height)
off = com - cen; dist = np.linalg.norm(off)
if dist > radius:
want = -off / dist * min(dist - radius, 0.2 * sk.height)
self.balance = self.balance + 0.25 * (want - self.balance)
if np.linalg.norm(self.balance) > 0.5:
pose += self.balance
for ft in self.feet:
if ft not in driven:
chain = limb_chain(sk, ft)
ik2(pose, sk, chain, pose[sk.index[chain[2]]] - self.balance, pole=f + UP * 0.2)
if self.weapon is not None:
self.weapon += self.balance
below = pose[:, 2] < 0.0
if below.any():
self.floor_clamps += int(below.sum()); pose[below, 2] = 0.0
if self.weapon is not None:
self.weapon[:, 2] = np.maximum(self.weapon[:, 2], 0.0)
self.pose = pose
self.invulnerable = bool(mv and mv.in_window(t, mv.spec.get("invulnerable")))
if mv is not None and mv.done(t):
self.root[2] = self.base_z
self.move = None
return pose
def capsules(self):
return self.sk.capsules(self.pose, self.slot, self.weapon)
|