nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
characters.cc
Go to the documentation of this file.
1#include "client/characters.h"
2
3#include <external/cgltf.h>
4#include <raymath.h>
5
6#include <algorithm>
7#include <array>
8#include <cctype>
9#include <cmath>
10#include <string>
11#include <string_view>
12#include <vector>
13
14#include "absl/strings/str_cat.h"
15#include "client/figures.h"
16#include "client/rig.h"
17#include "content/figures.h"
18#include "content/rig.h"
19
20namespace nanommo {
21
22namespace {
23
24// In the protocol's order of motions, with attac for the skeleton's attack,
25// whose name raylib cuts at 31 characters.
26constexpr std::array<const char*, 5> kClips = {"idle", "walk", "run", "attac",
27 "death"};
28
29constexpr std::string_view kRightHand = "RightHand";
30constexpr std::string_view kLeftFoot = "LeftFoot";
31constexpr std::string_view kRightFoot = "RightFoot";
32
33// The middle of the fist, from the wrist: along the fingers, and a little
34// towards the palm, in metres.
35constexpr Vector3 kFist = {-0.06f, -0.01f, 0.0f};
36
37// The light a blow's flash gives off at its brightest, on top of the sun's,
38// and a copy left behind's: enough to bloom.
39constexpr float kFlash = 2.5f;
40constexpr float kGhostGlow = 1.5f;
41
42// raylib cuts clip names at 31 characters, so the skeleton's run ends in
43// Runni, which still has the word run in it.
44bool HasWord(std::string name, std::string_view word) {
45 std::ranges::transform(name, name.begin(), [](unsigned char c) {
46 return static_cast<char>(std::tolower(c));
47 });
48 return name.contains(word);
49}
50
51// raylib samples glTF clips 60 times a second, and the last frame is the
52// first again, so a loop skips it, and the death stops just before it.
53float FrameAt(const ModelAnimation& clip, float time, bool loops) {
54 const int frames = clip.keyframeCount > 1 ? clip.keyframeCount - 1 : 1;
55 if (!loops) {
56 return std::min(time * 60.0f, static_cast<float>(frames - 1));
57 }
58 return std::fmod(time * 60.0f, static_cast<float>(frames));
59}
60
61// glTF stores a matrix a column at a time, and raylib's Matrix lists its
62// fields a row at a time.
63Matrix FromGltf(const std::array<float, 16>& m) {
64 return {m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13],
65 m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15]};
66}
67
68// raylib takes the pose the bones rest in as the one the mesh was bound in,
69// but the skeleton's arms rest about 70 degrees away from it. glTF keeps the
70// bind pose as each bone's inverse bind matrix, so we read it from those.
71void ReadBindPose(const std::string& path, Model& model) {
72 cgltf_options options{};
73 cgltf_data* data = nullptr;
74 if (cgltf_parse_file(&options, path.c_str(), &data) != cgltf_result_success) {
75 return;
76 }
77 const cgltf_node* mesh = nullptr;
78 for (cgltf_size i = 0; i < data->nodes_count && mesh == nullptr; ++i) {
79 if (data->nodes[i].skin != nullptr) {
80 mesh = &data->nodes[i];
81 }
82 }
83 if (mesh != nullptr && mesh->skin->inverse_bind_matrices != nullptr &&
84 cgltf_load_buffers(&options, data, path.c_str()) ==
85 cgltf_result_success) {
86 std::array<float, 16> world{};
87 cgltf_node_transform_world(mesh, world.data());
88 // raylib moves the mesh to where its node puts it in the world as it
89 // loads it, so the bind pose goes there too.
90 for (int i = 0; i < static_cast<int>(model.skeleton.boneCount); ++i) {
91 std::array<float, 16> inverse{};
92 if (cgltf_accessor_read_float(mesh->skin->inverse_bind_matrices, i,
93 inverse.data(), inverse.size())) {
94 const Matrix bind =
95 MatrixMultiply(MatrixInvert(FromGltf(inverse)), FromGltf(world));
96 Transform& pose = model.skeleton.bindPose[i];
97 MatrixDecompose(bind, &pose.translation, &pose.rotation, &pose.scale);
98 }
99 }
100 }
101 cgltf_free(data);
102}
103
104} // namespace
105
106std::string MonstersFolder() {
107 return std::string(GetApplicationDirectory()) + "monsters";
108}
109
110std::string WeaponsFolder() {
111 return std::string(GetApplicationDirectory()) + "weapons";
112}
113
114std::string ContentFolder() {
115 return std::string(GetApplicationDirectory()) + "content";
116}
117
118Characters::Characters(const rig::Rig& rig, Shader shader,
119 const figures::Figures& figures)
120 : figures_(figures),
121 shader_(shader),
122 emission_(GetShaderLocation(shader, "emission")) {
123 // The rig as it is, without a build.
124 for (int build = 0; build < std::max(rig.builds_size(), 1); ++build) {
125 const std::vector<rig::Joint> joints = Skeleton(rig, build);
126 if (joints.empty()) {
127 return;
128 }
129 Character character{.model = RigModel(joints)};
130 // The body first, which the death keeps out of the ground.
131 Dress(character, figures);
132 character.clips = Bake(rig, character.model, &character.clip_count);
133 if (character.clip_count < 4) {
134 TraceLog(LOG_WARNING, "the rig doesn't have the legs it needs to move");
135 Unload(character);
136 return;
137 }
138 // A player's swing is a skill, with a move of its own, so it stands
139 // without one.
140 character.clip_for = {0, 1, 2, 0, 3};
141 Ready(character, shader);
142 characters_.push_back(character);
143 }
144}
145
146Characters::Characters(const std::string& folder,
147 const std::vector<std::string>& files, float height,
148 Shader shader)
149 : shader_(shader), emission_(GetShaderLocation(shader, "emission")) {
150 for (const std::string& file : files) {
151 const std::string path = absl::StrCat(folder, "/", file);
152 if (!FileExists(path.c_str())) {
153 continue;
154 }
155 Character character{.model = LoadModel(path.c_str())};
156 ReadBindPose(path, character.model);
157 character.clips = LoadModelAnimations(path.c_str(), &character.clip_count);
158
159 for (std::size_t motion = 0; motion < kClips.size(); ++motion) {
160 int found = -1;
161 for (int i = 0; i < character.clip_count; ++i) {
162 if (HasWord(character.clips[i].name, kClips[motion]) &&
163 IsModelAnimationValid(character.model, character.clips[i])) {
164 found = i;
165 }
166 }
167 character.clip_for[motion] = found;
168 }
169 // Without a walk, a character walks with its run, played slower. The
170 // skeleton's feet keep up with our walk at 0.4, and with our run at 0.7.
171 auto& [idle, walk, run, attack, death] = character.clip_for;
172 if (walk < 0 && run >= 0) {
173 walk = run;
174 character.speed[protocol::MOTION_WALK] = 0.4f;
175 character.speed[protocol::MOTION_RUN] = 0.7f;
176 }
177 // Without an attack, it stands as it strikes.
178 if (attack < 0) {
179 attack = idle;
180 }
181 if (idle < 0 || walk < 0 || run < 0 || death < 0) {
182 TraceLog(LOG_WARNING, "%s doesn't have the clips we need", file.c_str());
183 UnloadModelAnimations(character.clips, character.clip_count);
184 UnloadModel(character.model);
185 continue;
186 }
187 Ready(character, shader);
188 // Sized by the model's own mesh, so a figure is as tall as the model.
189 const BoundingBox box = GetModelBoundingBox(character.model);
190 character.scale = height / (box.max.y - box.min.y);
191 character.hull = character.model;
192 characters_.push_back(character);
193 }
194}
195
196void Characters::Ready(Character& character, Shader shader) {
197 for (int i = 0; i < character.model.materialCount; ++i) {
198 character.model.materials[i].shader = shader;
199 }
200 int left_foot = -1;
201 int right_foot = -1;
202 for (int i = 0; i < static_cast<int>(character.model.skeleton.boneCount);
203 ++i) {
204 const std::string_view bone = character.model.skeleton.bones[i].name;
205 if (bone == kRightHand) {
206 character.hand = i;
207 } else if (bone == kLeftFoot) {
208 left_foot = i;
209 } else if (bone == kRightFoot) {
210 right_foot = i;
211 }
212 }
213 for (const protocol::Motion motion :
214 {protocol::MOTION_WALK, protocol::MOTION_RUN}) {
215 character.footfalls[motion] = Footfalls(
216 character.clips[character.clip_for[motion]], left_foot, right_foot);
217 }
218 character.joints = FindJoints(character.model);
219}
220
221void Characters::Dress(Character& character, const figures::Figures& figures) {
222 character.hull = character.model;
223 if (figures.body().empty()) {
224 return;
225 }
226 const float metre = 1.0f / character.scale;
227 const std::vector<figures::Part> body = Unfold(figures.body());
228 nanommo::Dress(character.model, body, metre);
229 // The hull shares the model's bones, so the clips pose it too.
230 character.hull = character.model;
231 character.hull.meshes = static_cast<Mesh*>(MemAlloc(sizeof(Mesh)));
232 character.hull.meshes[0] = Hull(character.model, body, metre);
233 for (int i = 0; i < figures.hairs_size(); ++i) {
234 if (figures.hairs(i).parts().empty()) {
235 continue;
236 }
237 // Copies of the model, with the hair for their meshes, so they move with
238 // its bones.
239 const std::vector<figures::Part> parts = Unfold(figures.hairs(i).parts());
240 Garment hair{.model = character.model, .hull = character.model};
241 hair.model.meshes = static_cast<Mesh*>(MemAlloc(sizeof(Mesh)));
242 hair.model.meshes[0] = Parts(character.model, parts, metre);
243 hair.hull.meshes = static_cast<Mesh*>(MemAlloc(sizeof(Mesh)));
244 hair.hull.meshes[0] = Hull(character.model, parts, metre);
245 character.hairs[i] = hair;
246 }
247 character.dressed = true;
248}
249
251 for (Character& character : characters_) {
252 Unload(character);
253 }
254 for (auto& [id, weapon] : weapons_) {
255 UnloadModel(weapon.model);
256 }
257}
258
259void Characters::Unload(Character& character) {
260 for (auto& [id, garment] : character.garments) {
261 UnloadMesh(garment.model.meshes[0]);
262 MemFree(garment.model.meshes);
263 UnloadMesh(garment.hull.meshes[0]);
264 MemFree(garment.hull.meshes);
265 }
266 for (auto& [i, hair] : character.hairs) {
267 UnloadMesh(hair.model.meshes[0]);
268 MemFree(hair.model.meshes);
269 UnloadMesh(hair.hull.meshes[0]);
270 MemFree(hair.hull.meshes);
271 }
272 if (character.dressed) {
273 UnloadMesh(character.hull.meshes[0]);
274 MemFree(character.hull.meshes);
275 }
276 UnloadModelAnimations(character.clips, character.clip_count);
277 UnloadModel(character.model);
278}
279
280void Characters::Hold(uint32_t id, const items::Look& look, Shader shader) {
281 const std::string path = WeaponsFolder() + "/" + look.model();
282 if (look.model().empty() || !FileExists(path.c_str())) {
283 return;
284 }
285 Model weapon = LoadModel(path.c_str());
286 // glTF colours are linear, and our shader writes them out as they are, so
287 // we turn them into sRGB, or the sword comes out nearly black.
288 for (int i = 0; i < weapon.materialCount; ++i) {
289 weapon.materials[i].shader = shader;
290 Color& color = weapon.materials[i].maps[MATERIAL_MAP_DIFFUSE].color;
291 const Vector4 linear = ColorNormalize(color);
292 color = ColorFromNormalized({std::pow(linear.x, 1.0f / 2.2f),
293 std::pow(linear.y, 1.0f / 2.2f),
294 std::pow(linear.z, 1.0f / 2.2f), linear.w});
295 // A tint makes another item of the same model, such as the Ash Blade of
296 // the sword.
297 if (look.has_tint()) {
298 color = ColorTint(color, GetColor(look.tint()));
299 }
300 }
301 const BoundingBox box = GetModelBoundingBox(weapon);
302 const float height = box.max.y - box.min.y;
303 const float scale = look.length() / height;
304 const Matrix sized = MatrixMultiply(
305 MatrixTranslate(0.0f, -(box.min.y + look.grip() * height), 0.0f),
306 MatrixScale(scale, scale, scale));
307 // The rig's right hand rests with its fingers out to the right, the palm
308 // down and the thumb ahead. The fist holds the blade out past the thumb,
309 // leaning 20 degrees towards the fingers.
310 const Matrix along = MatrixMultiply(MatrixRotateX(90.0f * DEG2RAD),
311 MatrixRotateY(-20.0f * DEG2RAD));
312 const Matrix in_hand =
313 MatrixMultiply(along, MatrixTranslate(kFist.x, kFist.y, kFist.z));
314 // The blade runs up the middle of the model, from the grip to the top.
315 const float middle_x = (box.min.x + box.max.x) / 2.0f;
316 const float middle_z = (box.min.z + box.max.z) / 2.0f;
317 weapons_[id] = {
318 .model = weapon,
319 .grip = MatrixMultiply(sized, in_hand),
320 .hilt = {middle_x, box.min.y + 1.5f * look.grip() * height, middle_z},
321 .tip = {middle_x, box.max.y, middle_z}};
322}
323
324void Characters::Wear(uint32_t id, const items::Look& look) {
325 if (look.parts().empty()) {
326 return;
327 }
328 const std::vector<figures::Part> parts = Unfold(look.parts());
329 for (Character& character : characters_) {
330 const float metre = 1.0f / character.scale;
331 // Copies of the model, with the item's parts for meshes, so they move
332 // with its bones.
333 Garment garment{
334 .model = character.model, .hull = character.model, .dyed = look.dyed()};
335 garment.model.meshes = static_cast<Mesh*>(MemAlloc(sizeof(Mesh)));
336 garment.model.meshes[0] = Parts(character.model, parts, metre);
337 garment.hull.meshes = static_cast<Mesh*>(MemAlloc(sizeof(Mesh)));
338 garment.hull.meshes[0] = Hull(character.model, parts, metre);
339 character.garments[id] = garment;
340 }
341}
342
343void Characters::Learn(uint32_t skill, const skills::Look& look) {
344 if (!look.move().keys().empty()) {
345 moves_[skill] = look.move();
346 }
347}
348
349// A skill plays its move, over the character standing.
350Characters::Pose Characters::PoseFor(const Character& character,
351 protocol::Motion motion, float time) {
352 if (motion == protocol::MOTION_SKILL) {
353 motion = protocol::MOTION_IDLE;
354 }
355 const int index = motion >= 0 && motion < std::ssize(kClips) ? motion : 0;
356 const ModelAnimation& clip = character.clips[character.clip_for[index]];
357 return {&clip, FrameAt(clip, time * character.speed[index],
358 index != protocol::MOTION_DEAD)};
359}
360
361std::optional<Gait> Characters::GaitOf(const Figure& figure) const {
362 if (characters_.empty() || (figure.to != protocol::MOTION_WALK &&
363 figure.to != protocol::MOTION_RUN)) {
364 return std::nullopt;
365 }
366 const Character& character = For(figure);
367 const ModelAnimation& clip = character.clips[character.clip_for[figure.to]];
368 // As FrameAt plays it, sixty frames a second, and the last is the first.
369 const float frames = static_cast<float>(std::max(clip.keyframeCount - 1, 1));
370 return Gait{
371 .loops = figure.to_time * character.speed[figure.to] * 60.0f / frames,
372 .footfalls = character.footfalls[figure.to]};
373}
374
375const Characters::Character& Characters::For(const Figure& figure) const {
376 // A player who chose their build has it. An NPC looks the same wherever it
377 // stands, so it goes by its kind, and anyone else by their id.
378 uint32_t which = figure.npc ? figure.kind : figure.id;
379 if (figure.features && figure.features->build) {
380 which = *figure.features->build;
381 }
382 return characters_[which % characters_.size()];
383}
384
385void Characters::PoseAs(const Character& character,
386 const Figure& figure) const {
387 const Pose from = PoseFor(character, figure.from, figure.from_time);
388 const Pose to = PoseFor(character, figure.to, figure.to_time);
389 // Players share the model's bones, so we pose them right before each draw.
390 UpdateModelAnimationEx(character.model, *from.clip, from.frame, *to.clip,
391 to.frame, figure.blend);
392 const auto move = moves_.find(figure.to_skill);
393 if (figure.to == protocol::MOTION_SKILL && move != moves_.end()) {
394 Model model = character.model;
395 Apply(BendAt(move->second, figure.to_time * 1000.0f), character.joints,
396 1.0f / character.scale, model);
397 }
398}
399
400// Turned, then tipped over towards its lean's way, about its feet, and up
401// off the ground by its lift.
402Matrix Characters::Placed(const Character& character, const Figure& figure) {
403 const float scale = character.scale;
404 const Vector3 across{std::cos(figure.lean_yaw), 0.0f,
405 -std::sin(figure.lean_yaw)};
406 return MatrixMultiply(
407 MatrixMultiply(MatrixMultiply(MatrixScale(scale, scale, scale),
408 MatrixRotateY(figure.yaw)),
409 MatrixRotate(across, figure.lean)),
410 MatrixTranslate(figure.position.x, figure.position.y + figure.lift,
411 figure.position.z));
412}
413
414Matrix Characters::InHand(const Character& character, const Matrix& grip) {
415 const Transform& hand = character.model.currentPose[character.hand];
416 const Matrix bone = MatrixMultiply(
417 MatrixMultiply(MatrixScale(hand.scale.x, hand.scale.y, hand.scale.z),
418 QuaternionToMatrix(hand.rotation)),
419 MatrixTranslate(hand.translation.x, hand.translation.y,
420 hand.translation.z));
421 return MatrixMultiply(grip, bone);
422}
423
424std::optional<std::pair<Vector3, Vector3>> Characters::Blade(
425 const Figure& figure) const {
426 const auto held = weapons_.find(figure.weapon);
427 if (characters_.empty() || held == weapons_.end()) {
428 return std::nullopt;
429 }
430 const Character& character = For(figure);
431 if (character.hand < 0) {
432 return std::nullopt;
433 }
434 PoseAs(character, figure);
435 const Matrix world = MatrixMultiply(InHand(character, held->second.grip),
436 Placed(character, figure));
437 return std::pair{Vector3Transform(held->second.hilt, world),
438 Vector3Transform(held->second.tip, world)};
439}
440
441void Characters::Draw(const Figure& figure, Color color,
442 const Outline* outline) const {
443 const Character& character = For(figure);
444 PoseAs(character, figure);
445 const Matrix placed = Placed(character, figure);
446 // A blow just landed lights it up.
447 const float flash = figure.flash * kFlash;
448 SetShaderValue(shader_, emission_, &flash, SHADER_UNIFORM_FLOAT);
449 // Each with its outline first, at the figure's place, its turn and its
450 // scale.
451 auto draw = [&](Model model, const Model& hull, Color tint) {
452 if (outline != nullptr) {
453 DrawOutline(hull, placed, outline->skinned);
454 }
455 model.transform = MatrixMultiply(model.transform, placed);
456 DrawModel(model, {0.0f, 0.0f, 0.0f}, 1.0f, tint);
457 };
458 if (!character.dressed) {
459 draw(character.model, character.hull, color);
460 } else {
461 const Features features =
462 figure.features ? *figure.features : FeaturesOf(figures_, figure.id);
463 draw(character.model, character.hull, GetColor(features.skin));
464 const auto hair = character.hairs.find(features.hair);
465 if (hair != character.hairs.end()) {
466 draw(hair->second.model, hair->second.hull,
467 GetColor(features.hair_color));
468 }
469 }
470 // What it wears has colours of its own, over the figure's, or takes on
471 // the colour it's given.
472 for (const uint32_t item : figure.wearing) {
473 const auto worn = character.garments.find(item);
474 if (worn != character.garments.end()) {
475 draw(worn->second.model, worn->second.hull,
476 worn->second.dyed ? color : WHITE);
477 }
478 }
479
480 const auto held = weapons_.find(figure.weapon);
481 if (held != weapons_.end() && character.hand >= 0) {
482 Model weapon = held->second.model;
483 weapon.transform =
484 MatrixMultiply(InHand(character, held->second.grip), placed);
485 if (outline != nullptr) {
486 DrawOutline(weapon, MatrixIdentity(), outline->still);
487 }
488 DrawModel(weapon, {0.0f, 0.0f, 0.0f}, 1.0f, WHITE);
489 }
490 constexpr float kNone = 0.0f;
491 SetShaderValue(shader_, emission_, &kNone, SHADER_UNIFORM_FLOAT);
492}
493
494// The body alone, in the colour, its weapon too, lit so that it glows.
495void Characters::DrawGhost(const Figure& figure, Color color) const {
496 const Character& character = For(figure);
497 PoseAs(character, figure);
498 const Matrix placed = Placed(character, figure);
499 SetShaderValue(shader_, emission_, &kGhostGlow, SHADER_UNIFORM_FLOAT);
500 Model body = character.model;
501 body.transform = MatrixMultiply(body.transform, placed);
502 DrawModel(body, {0.0f, 0.0f, 0.0f}, 1.0f, color);
503 const auto held = weapons_.find(figure.weapon);
504 if (held != weapons_.end() && character.hand >= 0) {
505 Model weapon = held->second.model;
506 weapon.transform =
507 MatrixMultiply(InHand(character, held->second.grip), placed);
508 DrawModel(weapon, {0.0f, 0.0f, 0.0f}, 1.0f, color);
509 }
510 constexpr float kNone = 0.0f;
511 SetShaderValue(shader_, emission_, &kNone, SHADER_UNIFORM_FLOAT);
512}
513
514} // namespace nanommo
void Learn(uint32_t skill, const skills::Look &look)
Keeps the skill's move, for the players who use it.
std::optional< Gait > GaitOf(const Figure &figure) const
Where the figure is in its walk or run: none, if it's doing neither.
void DrawGhost(const Figure &figure, Color color) const
void Wear(uint32_t id, const items::Look &look)
std::optional< std::pair< Vector3, Vector3 > > Blade(const Figure &figure) const
void Hold(uint32_t id, const items::Look &look, Shader shader)
Characters(Database &database)
Definition characters.h:24
void Draw(const Figure &figure, Color color, const Outline *outline) const
Definition chat.cc:9
void DrawOutline(const Model &model, const Matrix &transform, Shader shader)
Definition outline.cc:11
Model RigModel(const std::vector< rig::Joint > &joints)
Definition rig.cc:469
void Dress(Model &model, const std::vector< figures::Part > &parts, float metre)
Definition figures.cc:253
Mesh Hull(const Model &model, const std::vector< figures::Part > &parts, float metre)
Definition figures.cc:273
ModelAnimation * Bake(const rig::Rig &rig, const Model &model, int *count)
Definition rig.cc:504
void Apply(const Bend &bend, const Joints &joints, float metre, Model &model)
Definition moves.cc:107
std::array< float, 2 > Footfalls(const ModelAnimation &clip, int left, int right)
Definition soundscape.cc:57
std::vector< rig::Joint > Skeleton(const rig::Rig &rig, int build)
Definition rig.cc:101
Mesh Parts(const Model &model, const std::vector< figures::Part > &parts, float metre)
Definition figures.cc:268
std::string ContentFolder()
Joints FindJoints(const Model &model)
Definition moves.cc:34
std::vector< figures::Part > Unfold(const google::protobuf::RepeatedPtrField< figures::Part > &parts)
Definition figures.cc:96
std::string WeaponsFolder()
Features FeaturesOf(const figures::Figures &figures, uint32_t id)
Definition figures.cc:74
std::string MonstersFolder()
Bend BendAt(const skills::Move &move, float ms)
The move, ms into it, between the keys either side.
Definition moves.cc:49
uint32_t hair_color
Definition figures.h:31
uint32_t skin
As 0xRRGGBBAA: white, when there are none to pick from.
Definition figures.h:30
uint32_t id
Definition animator.h:21
uint32_t kind
A monster's or an NPC's kind, by its id in the content folder.
Definition animator.h:33
float flash
How lit up it is from a blow just landed, from 0 to 1.
Definition animator.h:72
uint32_t weapon
What a player holds, by its id in the items file.
Definition animator.h:56
protocol::Motion to
Definition animator.h:77
std::vector< uint32_t > wearing
What else a player wears, by its ids in the items file.
Definition animator.h:58
std::optional< Features > features
Definition animator.h:38
Shader skinned
Definition outline.h:14