20constexpr float kPi = std::numbers::pi_v<float>;
21constexpr float kFramesPerSecond = 60.0f;
25constexpr float kHeel = 0.04f;
28constexpr float kToesOut = 6.0f * DEG2RAD;
31constexpr float kLookUp = 0.6f;
34constexpr float kWrist = 0.8f;
38constexpr float kStraight = 0.97f;
42constexpr float kFlat = 0.15f;
43constexpr float kRoll = 0.6f;
45using Pose = std::vector<Transform>;
47float Smooth(
float t) {
48 t = std::clamp(t, 0.0f, 1.0f);
49 return t * t * (3.0f - 2.0f * t);
52int BoneNamed(
const ModelSkeleton& skeleton, std::string_view name) {
53 for (
int i = 0; i < static_cast<int>(skeleton.boneCount); ++i) {
54 if (name == skeleton.bones[i].name) {
63Quaternion Aim(Vector3 from, Vector3 from_front, Vector3 to, Vector3 to_front) {
66 auto frame = [](Vector3 along, Vector3 front) {
67 const Vector3 y = Vector3Normalize(along);
68 const Vector3 z = Vector3Normalize(
69 Vector3Subtract(front, Vector3Scale(y, Vector3DotProduct(front, y))));
70 const Vector3 x = Vector3CrossProduct(y, z);
71 return QuaternionFromMatrix(Matrix{x.x, y.x, z.x, 0.0f, x.y, y.y, z.y, 0.0f,
72 x.z, y.z, z.z, 0.0f, 0.0f, 0.0f, 0.0f,
75 return QuaternionNormalize(QuaternionMultiply(
76 frame(to, to_front), QuaternionInvert(frame(from, from_front))));
98 Poser(
const rig::Rig& rig,
const Model& model)
99 : skeleton_(model.skeleton),
100 rest_(model.skeleton.bindPose,
101 model.skeleton.bindPose + model.skeleton.boneCount),
103 for (
const float side : {1.0f, -1.0f}) {
104 const std::string prefix = side > 0.0f ?
"Left" :
"Right";
105 legs_.push_back({.hip = Bone(prefix +
"UpLeg"),
106 .knee = Bone(prefix +
"Leg"),
107 .ankle = Bone(prefix +
"Foot"),
108 .ball = Bone(prefix +
"ToeBase"),
109 .tip = Bone(prefix +
"Toe_End"),
113 *stance.add_keys() = rig.stance();
115 Turn(
BendAt(stance, 0.0f), joints_, 1.0f, skeleton_, standing_.data());
118 bool HasLegs()
const {
119 return std::ranges::all_of(legs_, [](
const Leg& leg) {
120 return leg.hip >= 0 && leg.knee >= 0 && leg.ankle >= 0;
124 const std::vector<Leg>& legs()
const {
return legs_; }
127 Pose Bent(
const Bend& bend)
const {
128 Pose pose = standing_;
129 Turn(bend, joints_, 1.0f, skeleton_, pose.data());
134 Vector3 Under(
const Leg& leg)
const {
135 const Vector3 ankle = rest_[leg.ankle].translation;
136 return {ankle.x, 0.0f, ankle.z};
142 Step Place(
const Leg& leg, Vector3 ground,
float pitch)
const {
143 const Vector3 rest_ankle = rest_[leg.ankle].translation;
144 const Vector3 under = {rest_ankle.x, 0.0f, rest_ankle.z};
145 const Vector3 end = pitch > 0.0f && leg.tip >= 0
146 ? Vector3{rest_[leg.tip].translation.x, 0.0f,
147 rest_[leg.tip].translation.z}
148 : Vector3{under.x, 0.0f, under.z - kHeel};
149 const Vector3 touch = Vector3Add(
151 Vector3RotateByQuaternion(Vector3Subtract(end, under), Yaw(leg)));
152 return {.ankle = Vector3Add(
153 touch, Vector3RotateByQuaternion(
154 Vector3Subtract(rest_ankle, end), Foot(leg, pitch))),
160 void Reach(Pose& pose,
const Leg& leg,
const Step& step)
const {
161 const Vector3 rest_ankle = rest_[leg.ankle].translation;
162 const Quaternion yaw = Yaw(leg);
163 const Quaternion foot = Foot(leg, step.pitch);
164 const Vector3 ankle = step.ankle;
165 const Vector3 hip = pose[leg.hip].translation;
166 const Vector3 rest_hip = rest_[leg.hip].translation;
167 const Vector3 rest_knee = rest_[leg.knee].translation;
168 const float thigh = Vector3Distance(rest_hip, rest_knee);
169 const float shin = Vector3Distance(rest_knee, rest_ankle);
170 const Vector3 front = Vector3RotateByQuaternion({0.0f, 0.0f, 1.0f}, yaw);
173 const Vector3 gap = Vector3Subtract(ankle, hip);
176 const float length = thigh + shin;
177 const float soft = kStraight * length;
178 float reach = std::max(Vector3Length(gap), std::fabs(thigh - shin));
180 const float rest = length - soft;
181 reach = soft + rest * (1.0f - std::exp(-(reach - soft) / rest));
183 const Vector3 along = Vector3Normalize(gap);
184 const Vector3 out = Vector3Normalize(Vector3Subtract(
185 front, Vector3Scale(along, Vector3DotProduct(front, along))));
187 (thigh * thigh + reach * reach - shin * shin) / (2.0f * thigh * reach);
188 const float sine = std::sqrt(std::max(0.0f, 1.0f - cosine * cosine));
190 Vector3Add(hip, Vector3Add(Vector3Scale(along, thigh * cosine),
191 Vector3Scale(out, thigh * sine)));
192 const Vector3 placed = Vector3Add(hip, Vector3Scale(along, reach));
194 const Vector3 ahead{0.0f, 0.0f, 1.0f};
195 pose[leg.hip].rotation = Aim(Vector3Subtract(rest_knee, rest_hip), ahead,
196 Vector3Subtract(knee, hip), front);
199 .rotation = Aim(Vector3Subtract(rest_ankle, rest_knee), ahead,
200 Vector3Subtract(placed, knee), front),
201 .scale = {1.0f, 1.0f, 1.0f}};
203 .translation = placed, .rotation = foot, .scale = {1.0f, 1.0f, 1.0f}};
207 .translation = Vector3Add(
209 Vector3RotateByQuaternion(
210 Vector3Subtract(rest_[leg.ball].translation, rest_ankle),
213 .scale = {1.0f, 1.0f, 1.0f}};
215 if (leg.ball >= 0 && leg.tip >= 0) {
216 pose[leg.tip] = {.translation = Vector3Add(
217 pose[leg.ball].translation,
218 Vector3RotateByQuaternion(
219 Vector3Subtract(rest_[leg.tip].translation,
220 rest_[leg.ball].translation),
223 .scale = {1.0f, 1.0f, 1.0f}};
228 int Bone(
const std::string& name)
const {
return BoneNamed(skeleton_, name); }
230 static Quaternion Yaw(
const Leg& leg) {
231 return QuaternionFromAxisAngle({0.0f, 1.0f, 0.0f}, leg.side * kToesOut);
234 static Quaternion Foot(
const Leg& leg,
float pitch) {
235 return QuaternionMultiply(
236 Yaw(leg), QuaternionFromAxisAngle({1.0f, 0.0f, 0.0f}, pitch));
239 ModelSkeleton skeleton_;
243 std::vector<Leg> legs_;
248Bend Swing(
const rig::Gait& gait,
float phase) {
249 const float wave = std::cos(2.0f * kPi * phase);
251 auto turn = [&key](skills::Joint joint,
float pitch,
float yaw) {
252 skills::Turn& turn = *key.add_turns();
253 turn.set_joint(joint);
254 turn.set_pitch(pitch);
260 const float hips = -gait.hips_turn() * wave;
261 const float chest = gait.chest_turn() * wave;
262 turn(skills::HIPS, gait.lean() / 2.0f, hips);
263 turn(skills::SPINE, gait.lean() / 2.0f, chest / 2.0f - hips);
264 turn(skills::CHEST, 0.0f, chest / 2.0f);
265 turn(skills::HEAD, -gait.lean() * kLookUp, -chest);
268 const float left_forward = (1.0f - wave) / 2.0f;
269 const float left_elbow = gait.elbow() * (0.7f + 0.6f * left_forward);
270 const float right_elbow =
271 gait.elbow() * (0.7f + 0.6f * (1.0f - left_forward));
272 turn(skills::LEFT_ARM, gait.arms_back() + gait.arm_swing() * wave, 0.0f);
273 turn(skills::RIGHT_ARM, gait.arms_back() - gait.arm_swing() * wave, 0.0f);
274 turn(skills::LEFT_FOREARM, -left_elbow, 0.0f);
275 turn(skills::RIGHT_FOREARM, -right_elbow, 0.0f);
276 turn(skills::RIGHT_HAND, right_elbow * kWrist, 0.0f);
278 *move.add_keys() = key;
282 const float middle = phase - gait.stance() / 2.0f;
283 bend.shift = {gait.sway() * std::cos(2.0f * kPi * middle),
285 gait.bob() * (1.0f + std::cos(4.0f * kPi * middle)) / 2.0f,
293Step Footing(
const Poser& poser,
const Leg& leg,
const rig::Gait& gait,
294 float seconds,
float phase,
float centre) {
295 const float stance = gait.stance();
296 const float down = gait.speed() * stance * seconds;
297 const Vector3 under = poser.Under(leg);
298 const float x = leg.side * gait.width() / 2.0f;
299 const float heel = gait.heel_strike() * DEG2RAD;
300 const float toes = gait.toe_off() * DEG2RAD;
301 auto on_ground = [&](
float share) {
304 pitch = -heel * (1.0f - Smooth(share / kFlat));
305 }
else if (share > kRoll) {
306 pitch = toes * Smooth((share - kRoll) / (1.0f - kRoll));
308 return poser.Place(leg, {x, 0.0f, under.z + centre + down * (0.5f - share)},
311 if (phase < stance) {
312 return on_ground(phase / stance);
316 const float t = (phase - stance) / (1.0f - stance);
317 const Step from = on_ground(1.0f);
318 const Step to = on_ground(0.0f);
320 const float moving = -gait.speed() * (1.0f - stance) * seconds / 2.0f;
321 const float t2 = t * t;
322 const float t3 = t2 * t;
323 const float z = (2 * t3 - 3 * t2 + 1) * from.ankle.z +
324 (t3 - 2 * t2 + t) * moving + (-2 * t3 + 3 * t2) * to.ankle.z +
328 std::sin(kPi * std::pow(t, std::log(0.5f) / std::log(0.4f)));
329 return {.ankle = {Lerp(from.ankle.x, to.ankle.x, Smooth(t)),
330 Lerp(from.ankle.y, to.ankle.y, Smooth(t)) + lift, z},
331 .pitch = Lerp(from.pitch, to.pitch, Smooth(t))};
334ModelAnimation
Clip(
const char* name,
const std::vector<Pose>& frames) {
335 ModelAnimation clip{};
336 std::strncpy(clip.name, name,
sizeof(clip.name) - 1);
337 clip.boneCount = frames.empty() ? 0 : frames[0].size();
338 clip.keyframeCount =
static_cast<int>(frames.size());
340 static_cast<Transform**
>(MemAlloc(frames.size() *
sizeof(Transform*)));
341 for (std::size_t i = 0; i < frames.size(); ++i) {
342 clip.keyframePoses[i] =
343 static_cast<Transform*
>(MemAlloc(frames[i].size() *
sizeof(Transform)));
344 std::ranges::copy(frames[i], clip.keyframePoses[i]);
349int Frames(
float ms) {
351 1,
static_cast<int>(std::lround(ms * kFramesPerSecond / 1000.0f)));
356float Centre(
const Poser& poser,
const rig::Gait& gait,
float seconds) {
357 const Leg& leg = poser.legs()[0];
358 const Vector3 landing = poser.Bent(Swing(gait, 0.0f))[leg.hip].translation;
359 const Vector3 leaving =
360 poser.Bent(Swing(gait, gait.stance()))[leg.hip].translation;
363 for (
int i = 0; i < 30; ++i) {
364 const float centre = (low + high) / 2.0f;
365 const float ahead = Vector3Distance(
366 landing, Footing(poser, leg, gait, seconds, 0.0f, centre).ankle);
367 const float behind = Vector3Distance(
369 Footing(poser, leg, gait, seconds, gait.stance() * 0.9999f, centre)
371 (ahead > behind ? high : low) = centre;
373 return (low + high) / 2.0f;
376std::vector<Pose> Loop(
const Poser& poser,
const rig::Gait& gait) {
377 const int frames = Frames(
static_cast<float>(gait.cycle_ms()));
379 const float seconds =
static_cast<float>(frames) / kFramesPerSecond;
380 const float centre = Centre(poser, gait, seconds);
381 std::vector<Pose> poses;
382 for (
int frame = 0; frame <= frames; ++frame) {
383 const float phase =
static_cast<float>(frame % frames) / frames;
384 Pose pose = poser.Bent(Swing(gait, phase));
385 for (
const Leg& leg : poser.legs()) {
388 std::fmod(phase + (leg.side > 0.0f ? 0.0f : 0.5f), 1.0f);
389 poser.Reach(pose, leg, Footing(poser, leg, gait, seconds, own, centre));
391 poses.push_back(std::move(pose));
396std::vector<Pose> Idle(
const Poser& poser,
const skills::Move& idle) {
397 const float ms = idle.keys().empty()
399 :
static_cast<float>(idle.keys().rbegin()->at_ms());
400 const int frames = Frames(ms);
401 std::vector<Pose> poses;
402 for (
int frame = 0; frame <= frames; ++frame) {
403 const float at = ms *
static_cast<float>(frame % frames) / frames;
404 Pose pose = poser.Bent(
BendAt(idle, at));
406 for (
const Leg& leg : poser.legs()) {
407 poser.Reach(pose, leg, poser.Place(leg, poser.Under(leg), 0.0f));
409 poses.push_back(std::move(pose));
416float Sunk(
const Model& model,
const Pose& pose) {
419 for (
int m = 0; m < model.meshCount; ++m) {
420 const Mesh& mesh = model.meshes[m];
421 if (mesh.vertices ==
nullptr || mesh.boneIndices ==
nullptr) {
424 for (
int v = 0; v < mesh.vertexCount; ++v) {
425 const int bone = mesh.boneIndices[4 * v];
426 const Vector3 corner{mesh.vertices[3 * v], mesh.vertices[3 * v + 1],
427 mesh.vertices[3 * v + 2]};
430 Vector3Add(Vector3RotateByQuaternion(
432 corner, model.skeleton.bindPose[bone].translation),
433 pose[bone].rotation),
434 pose[bone].translation)
436 lowest = any ? std::min(lowest, y) : y;
440 return any ? -lowest : 0.0f;
443std::vector<Pose> Fall(
const Poser& poser,
const Model& model,
444 const skills::Move& death) {
445 const float ms = death.keys().empty()
447 :
static_cast<float>(death.keys().rbegin()->at_ms());
448 const int frames = Frames(ms);
449 std::vector<Pose> poses;
451 for (
int frame = 0; frame <= frames + 1; ++frame) {
452 const float at = std::min(ms, frame * 1000.0f / kFramesPerSecond);
453 Pose pose = poser.Bent(
BendAt(death, at));
456 const float sunk = Sunk(model, pose);
458 for (Transform& bone : pose) {
459 bone.translation.y += sunk;
462 poses.push_back(std::move(pose));
469Model
RigModel(
const std::vector<rig::Joint>& joints) {
471 model.transform = MatrixIdentity();
472 model.materialCount = 1;
473 model.materials =
static_cast<Material*
>(MemAlloc(
sizeof(Material)));
474 model.materials[0] = LoadMaterialDefault();
475 const int count =
static_cast<int>(joints.size());
476 model.skeleton.boneCount = count;
477 model.skeleton.bones =
478 static_cast<BoneInfo*
>(MemAlloc(count *
sizeof(BoneInfo)));
479 model.skeleton.bindPose =
480 static_cast<Transform*
>(MemAlloc(count *
sizeof(Transform)));
482 static_cast<Transform*
>(MemAlloc(count *
sizeof(Transform)));
483 model.boneMatrices =
static_cast<Matrix*
>(MemAlloc(count *
sizeof(Matrix)));
484 for (
int i = 0; i < count; ++i) {
485 const rig::Joint& joint = joints[i];
486 BoneInfo& bone = model.skeleton.bones[i];
487 std::strncpy(bone.name, joint.name().c_str(),
sizeof(bone.name) - 1);
489 for (
int j = 0; j < i; ++j) {
490 if (joints[j].name() == joint.parent()) {
494 model.skeleton.bindPose[i] = {
495 .translation = {joint.at().x(), joint.at().y(), joint.at().z()},
496 .rotation = QuaternionIdentity(),
497 .scale = {1.0f, 1.0f, 1.0f}};
498 model.currentPose[i] = model.skeleton.bindPose[i];
499 model.boneMatrices[i] = MatrixIdentity();
504ModelAnimation*
Bake(
const rig::Rig& rig,
const Model& model,
int* count) {
505 const Poser poser(rig, model);
506 std::vector<ModelAnimation> clips;
507 if (poser.HasLegs()) {
508 clips = {
Clip(
"idle", Idle(poser, rig.idle())),
509 Clip(
"walk", Loop(poser, rig.walk())),
510 Clip(
"run", Loop(poser, rig.run())),
511 Clip(
"death", Fall(poser, model, rig.death()))};
513 *count =
static_cast<int>(clips.size());
514 auto* baked =
static_cast<ModelAnimation*
>(MemAlloc(
515 std::max<std::size_t>(clips.size(), 1) *
sizeof(ModelAnimation)));
516 std::ranges::copy(clips, baked);
Vector3 Place(const Point &point, const Terrain &terrain)
void Turn(const Bend &bend, const Joints &joints, float metre, const ModelSkeleton &skeleton, Transform *pose)
Model RigModel(const std::vector< rig::Joint > &joints)
ModelAnimation * Bake(const rig::Rig &rig, const Model &model, int *count)
Samples Step(Ground ground, uint32_t seed)
Joints FindJoints(const Model &model)
Bend BendAt(const skills::Move &move, float ms)
The move, ms into it, between the keys either side.
std::array< int, kJointBones.size()> Joints
Where a model's bones are, by joint, or -1 for one it doesn't have.