nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
rig.cc
Go to the documentation of this file.
1#include "client/rig.h"
2
3#include <raymath.h>
4
5#include <algorithm>
6#include <cmath>
7#include <cstring>
8#include <numbers>
9#include <string>
10#include <string_view>
11#include <utility>
12#include <vector>
13
14#include "client/moves.h"
15
16namespace nanommo {
17
18namespace {
19
20constexpr float kPi = std::numbers::pi_v<float>;
21constexpr float kFramesPerSecond = 60.0f;
22
23// The heel is this far behind the ankle: where a foot lands, and rocks
24// forward from.
25constexpr float kHeel = 0.04f;
26
27// Each foot, and so each knee, points this far out from straight ahead.
28constexpr float kToesOut = 6.0f * DEG2RAD;
29
30// How much of the body's lean the head takes back, to look ahead.
31constexpr float kLookUp = 0.6f;
32
33// How far the sword hand bends back, as a share of how far its elbow bends.
34constexpr float kWrist = 0.8f;
35
36// The share of a leg's length past which it straightens more slowly than
37// its foot goes.
38constexpr float kStraight = 0.97f;
39
40// Into a foot's time on the ground, as shares of it: until here it rolls off
41// its heel, and from here onto its toes.
42constexpr float kFlat = 0.15f;
43constexpr float kRoll = 0.6f;
44
45using Pose = std::vector<Transform>;
46
47float Smooth(float t) {
48 t = std::clamp(t, 0.0f, 1.0f);
49 return t * t * (3.0f - 2.0f * t);
50}
51
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) {
55 return i;
56 }
57 }
58 return -1;
59}
60
61// A turn that takes one frame to another, each given by the way a bone goes
62// and the way its front faces, square to it.
63Quaternion Aim(Vector3 from, Vector3 from_front, Vector3 to, Vector3 to_front) {
64 // The turn from the rig's own axes to the frame: y along the bone, z to its
65 // 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,
73 1.0f});
74 };
75 return QuaternionNormalize(QuaternionMultiply(
76 frame(to, to_front), QuaternionInvert(frame(from, from_front))));
77}
78
79// A leg, by its bones, and which side it's on: one to the left, minus one to
80// the right.
81struct Leg {
82 int hip = -1;
83 int knee = -1;
84 int ankle = -1;
85 int ball = -1;
86 int tip = -1;
87 float side = 1.0f;
88};
89
90// Where a foot is: its ankle, and how far it tips, toes down.
91struct Step {
92 Vector3 ankle;
93 float pitch = 0.0f;
94};
95
96class Poser {
97 public:
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),
102 joints_(FindJoints(model)) {
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"),
110 .side = side});
111 }
112 skills::Move stance;
113 *stance.add_keys() = rig.stance();
114 standing_ = rest_;
115 Turn(BendAt(stance, 0.0f), joints_, 1.0f, skeleton_, standing_.data());
116 }
117
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;
121 });
122 }
123
124 const std::vector<Leg>& legs() const { return legs_; }
125
126 // The figure standing, turned by the bend.
127 Pose Bent(const Bend& bend) const {
128 Pose pose = standing_;
129 Turn(bend, joints_, 1.0f, skeleton_, pose.data());
130 return pose;
131 }
132
133 // Where the foot is when it stands: under its ankle in the rig.
134 Vector3 Under(const Leg& leg) const {
135 const Vector3 ankle = rest_[leg.ankle].translation;
136 return {ankle.x, 0.0f, ankle.z};
137 }
138
139 // Where the ankle is, for a foot whose point under its ankle, as it would
140 // be flat, is on the ground here, tipped so far onto its toes, or back onto
141 // its heel, which stays where it touches the ground.
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(
150 ground,
151 Vector3RotateByQuaternion(Vector3Subtract(end, under), Yaw(leg)));
152 return {.ankle = Vector3Add(
153 touch, Vector3RotateByQuaternion(
154 Vector3Subtract(rest_ankle, end), Foot(leg, pitch))),
155 .pitch = pitch};
156 }
157
158 // The leg bent to put its ankle where the step says, with the knee over the
159 // foot.
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);
171 // The knee bends forward, in the plane of the hip, the ankle and the way
172 // the foot points, as far as the two bones' lengths say.
173 const Vector3 gap = Vector3Subtract(ankle, hip);
174 // Past most of the leg's length, the foot falls a little short, more so
175 // the further it is, so the knee straightens smoothly rather than snap.
176 const float length = thigh + shin;
177 const float soft = kStraight * length;
178 float reach = std::max(Vector3Length(gap), std::fabs(thigh - shin));
179 if (reach > soft) {
180 const float rest = length - soft;
181 reach = soft + rest * (1.0f - std::exp(-(reach - soft) / rest));
182 }
183 const Vector3 along = Vector3Normalize(gap);
184 const Vector3 out = Vector3Normalize(Vector3Subtract(
185 front, Vector3Scale(along, Vector3DotProduct(front, along))));
186 const float cosine =
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));
189 const Vector3 knee =
190 Vector3Add(hip, Vector3Add(Vector3Scale(along, thigh * cosine),
191 Vector3Scale(out, thigh * sine)));
192 const Vector3 placed = Vector3Add(hip, Vector3Scale(along, reach));
193
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);
197 pose[leg.knee] = {
198 .translation = knee,
199 .rotation = Aim(Vector3Subtract(rest_ankle, rest_knee), ahead,
200 Vector3Subtract(placed, knee), front),
201 .scale = {1.0f, 1.0f, 1.0f}};
202 pose[leg.ankle] = {
203 .translation = placed, .rotation = foot, .scale = {1.0f, 1.0f, 1.0f}};
204 // The foot is one piece, toes and all.
205 if (leg.ball >= 0) {
206 pose[leg.ball] = {
207 .translation = Vector3Add(
208 placed,
209 Vector3RotateByQuaternion(
210 Vector3Subtract(rest_[leg.ball].translation, rest_ankle),
211 foot)),
212 .rotation = foot,
213 .scale = {1.0f, 1.0f, 1.0f}};
214 }
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),
221 foot)),
222 .rotation = foot,
223 .scale = {1.0f, 1.0f, 1.0f}};
224 }
225 }
226
227 private:
228 int Bone(const std::string& name) const { return BoneNamed(skeleton_, name); }
229
230 static Quaternion Yaw(const Leg& leg) {
231 return QuaternionFromAxisAngle({0.0f, 1.0f, 0.0f}, leg.side * kToesOut);
232 }
233
234 static Quaternion Foot(const Leg& leg, float pitch) {
235 return QuaternionMultiply(
236 Yaw(leg), QuaternionFromAxisAngle({1.0f, 0.0f, 0.0f}, pitch));
237 }
238
239 ModelSkeleton skeleton_;
240 Pose rest_;
241 Pose standing_;
242 Joints joints_;
243 std::vector<Leg> legs_;
244};
245
246// The turns of a gait's upper body, a share of the way round its cycle, from
247// when the left foot lands.
248Bend Swing(const rig::Gait& gait, float phase) {
249 const float wave = std::cos(2.0f * kPi * phase);
250 skills::Key key;
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);
255 turn.set_yaw(yaw);
256 };
257 // The hips turn with the leg that's forward, the left at first, and the
258 // chest the other way, with the arm that's forward, and the head looks
259 // ahead all the while.
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);
266 // Each arm swings against its leg, and bends more as it comes forward, and
267 // the sword hand bends back as its elbow does.
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);
277 skills::Move move;
278 *move.add_keys() = key;
279 Bend bend = BendAt(move, 0.0f);
280 // Highest, or lowest, as each foot passes under the hips, and over the
281 // side of the one that's down.
282 const float middle = phase - gait.stance() / 2.0f;
283 bend.shift = {gait.sway() * std::cos(2.0f * kPi * middle),
284 -gait.crouch() +
285 gait.bob() * (1.0f + std::cos(4.0f * kPi * middle)) / 2.0f,
286 0.0f};
287 return bend;
288}
289
290// Where a foot is, a share of the way round the gait's cycle from when it
291// lands. While it's down, it goes back as fast as the body goes forward, over a
292// stretch whose middle is the centre's distance ahead of where it stands.
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) {
302 float pitch = 0.0f;
303 if (share < kFlat) {
304 pitch = -heel * (1.0f - Smooth(share / kFlat));
305 } else if (share > kRoll) {
306 pitch = toes * Smooth((share - kRoll) / (1.0f - kRoll));
307 }
308 return poser.Place(leg, {x, 0.0f, under.z + centre + down * (0.5f - share)},
309 pitch);
310 };
311 if (phase < stance) {
312 return on_ground(phase / stance);
313 }
314 // Off the ground: from where it left it to where it lands, as fast as the
315 // ground at each end, lifted on the way, highest a little before halfway.
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);
319 // Half as fast as the ground, which eases the foot off it and onto it.
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 +
325 (t3 - t2) * moving;
326 const float lift =
327 gait.lift() *
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))};
332}
333
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());
339 clip.keyframePoses =
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]);
345 }
346 return clip;
347}
348
349int Frames(float ms) {
350 return std::max(
351 1, static_cast<int>(std::lround(ms * kFramesPerSecond / 1000.0f)));
352}
353
354// Where the middle of a foot's time down is, ahead of where it stands: so far
355// that the leg reaches as far to land as it does to leave the ground, behind.
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;
361 float low = -0.5f;
362 float high = 0.5f;
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(
368 leaving,
369 Footing(poser, leg, gait, seconds, gait.stance() * 0.9999f, centre)
370 .ankle);
371 (ahead > behind ? high : low) = centre;
372 }
373 return (low + high) / 2.0f;
374}
375
376std::vector<Pose> Loop(const Poser& poser, const rig::Gait& gait) {
377 const int frames = Frames(static_cast<float>(gait.cycle_ms()));
378 // A whole number of frames, so the cycle the feet keep up with is this.
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()) {
386 // The right foot is half a cycle behind the left.
387 const float own =
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));
390 }
391 poses.push_back(std::move(pose));
392 }
393 return poses;
394}
395
396std::vector<Pose> Idle(const Poser& poser, const skills::Move& idle) {
397 const float ms = idle.keys().empty()
398 ? 1000.0f
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));
405 // The feet stay where they stand, and the knees give.
406 for (const Leg& leg : poser.legs()) {
407 poser.Reach(pose, leg, poser.Place(leg, poser.Under(leg), 0.0f));
408 }
409 poses.push_back(std::move(pose));
410 }
411 return poses;
412}
413
414// How far below the ground the lowest corner of the model's body is, posed:
415// below zero when it's above it.
416float Sunk(const Model& model, const Pose& pose) {
417 float lowest = 0.0f;
418 bool any = false;
419 for (int m = 0; m < model.meshCount; ++m) {
420 const Mesh& mesh = model.meshes[m];
421 if (mesh.vertices == nullptr || mesh.boneIndices == nullptr) {
422 continue;
423 }
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]};
428 // Each bone rests unturned, so a corner moves as its bone does.
429 const float y =
430 Vector3Add(Vector3RotateByQuaternion(
431 Vector3Subtract(
432 corner, model.skeleton.bindPose[bone].translation),
433 pose[bone].rotation),
434 pose[bone].translation)
435 .y;
436 lowest = any ? std::min(lowest, y) : y;
437 any = true;
438 }
439 }
440 return any ? -lowest : 0.0f;
441}
442
443std::vector<Pose> Fall(const Poser& poser, const Model& model,
444 const skills::Move& death) {
445 const float ms = death.keys().empty()
446 ? 0.0f
447 : static_cast<float>(death.keys().rbegin()->at_ms());
448 const int frames = Frames(ms);
449 std::vector<Pose> poses;
450 // One more than the last key's, which the clip stops on.
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));
454 // The ground holds the body up: what the keys put under it comes up out
455 // of it.
456 const float sunk = Sunk(model, pose);
457 if (sunk > 0.0f) {
458 for (Transform& bone : pose) {
459 bone.translation.y += sunk;
460 }
461 }
462 poses.push_back(std::move(pose));
463 }
464 return poses;
465}
466
467} // namespace
468
469Model RigModel(const std::vector<rig::Joint>& joints) {
470 Model model{};
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)));
481 model.currentPose =
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);
488 bone.parent = -1;
489 for (int j = 0; j < i; ++j) {
490 if (joints[j].name() == joint.parent()) {
491 bone.parent = j;
492 }
493 }
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();
500 }
501 return model;
502}
503
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()))};
512 }
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);
517 return baked;
518}
519
520} // namespace nanommo
Vector3 Place(const Point &point, const Terrain &terrain)
Definition film.cc:212
Definition chat.cc:9
void Turn(const Bend &bend, const Joints &joints, float metre, const ModelSkeleton &skeleton, Transform *pose)
Definition moves.cc:76
Model RigModel(const std::vector< rig::Joint > &joints)
Definition rig.cc:469
ModelAnimation * Bake(const rig::Rig &rig, const Model &model, int *count)
Definition rig.cc:504
Samples Step(Ground ground, uint32_t seed)
Definition foley.cc:122
Joints FindJoints(const Model &model)
Definition moves.cc:34
Bend BendAt(const skills::Move &move, float ms)
The move, ms into it, between the keys either side.
Definition moves.cc:49
std::array< int, kJointBones.size()> Joints
Where a model's bones are, by joint, or -1 for one it doesn't have.
Definition moves.h:19