3#include <external/cgltf.h>
14#include "absl/strings/str_cat.h"
26constexpr std::array<const char*, 5> kClips = {
"idle",
"walk",
"run",
"attac",
29constexpr std::string_view kRightHand =
"RightHand";
30constexpr std::string_view kLeftFoot =
"LeftFoot";
31constexpr std::string_view kRightFoot =
"RightFoot";
35constexpr Vector3 kFist = {-0.06f, -0.01f, 0.0f};
39constexpr float kFlash = 2.5f;
40constexpr float kGhostGlow = 1.5f;
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));
48 return name.contains(word);
53float FrameAt(
const ModelAnimation& clip,
float time,
bool loops) {
54 const int frames = clip.keyframeCount > 1 ? clip.keyframeCount - 1 : 1;
56 return std::min(time * 60.0f,
static_cast<float>(frames - 1));
58 return std::fmod(time * 60.0f,
static_cast<float>(frames));
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]};
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) {
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];
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());
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())) {
95 MatrixMultiply(MatrixInvert(FromGltf(inverse)), FromGltf(world));
96 Transform& pose = model.skeleton.bindPose[i];
97 MatrixDecompose(bind, &pose.translation, &pose.rotation, &pose.scale);
107 return std::string(GetApplicationDirectory()) +
"monsters";
111 return std::string(GetApplicationDirectory()) +
"weapons";
115 return std::string(GetApplicationDirectory()) +
"content";
119 const figures::Figures& figures)
122 emission_(GetShaderLocation(shader,
"emission")) {
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()) {
129 Character character{.model =
RigModel(joints)};
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");
140 character.clip_for = {0, 1, 2, 0, 3};
141 Ready(character, shader);
142 characters_.push_back(character);
147 const std::vector<std::string>& files,
float height,
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())) {
155 Character character{.model = LoadModel(path.c_str())};
156 ReadBindPose(path, character.model);
157 character.clips = LoadModelAnimations(path.c_str(), &character.clip_count);
159 for (std::size_t motion = 0; motion < kClips.size(); ++motion) {
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])) {
167 character.clip_for[motion] = found;
171 auto& [idle, walk, run, attack, death] = character.clip_for;
172 if (walk < 0 && run >= 0) {
174 character.speed[protocol::MOTION_WALK] = 0.4f;
175 character.speed[protocol::MOTION_RUN] = 0.7f;
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);
187 Ready(character, shader);
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);
196void Characters::Ready(Character& character, Shader shader) {
197 for (
int i = 0; i < character.model.materialCount; ++i) {
198 character.model.materials[i].shader = shader;
202 for (
int i = 0; i < static_cast<int>(character.model.skeleton.boneCount);
204 const std::string_view bone = character.model.skeleton.bones[i].name;
205 if (bone == kRightHand) {
207 }
else if (bone == kLeftFoot) {
209 }
else if (bone == kRightFoot) {
213 for (
const protocol::Motion motion :
214 {protocol::MOTION_WALK, protocol::MOTION_RUN}) {
216 character.clips[character.clip_for[motion]], left_foot, right_foot);
218 character.joints =
FindJoints(character.model);
221void Characters::Dress(Character& character,
const figures::Figures& figures) {
222 character.hull = character.model;
223 if (figures.body().empty()) {
226 const float metre = 1.0f / character.scale;
227 const std::vector<figures::Part> body =
Unfold(figures.body());
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()) {
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;
247 character.dressed =
true;
251 for (Character& character : characters_) {
254 for (
auto& [
id, weapon] : weapons_) {
255 UnloadModel(weapon.model);
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);
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);
272 if (character.dressed) {
273 UnloadMesh(character.hull.meshes[0]);
274 MemFree(character.hull.meshes);
276 UnloadModelAnimations(character.clips, character.clip_count);
277 UnloadModel(character.model);
281 const std::string path =
WeaponsFolder() +
"/" + look.model();
282 if (look.model().empty() || !FileExists(path.c_str())) {
285 Model weapon = LoadModel(path.c_str());
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});
297 if (look.has_tint()) {
298 color = ColorTint(color, GetColor(look.tint()));
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));
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));
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;
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}};
325 if (look.parts().empty()) {
328 const std::vector<figures::Part> parts =
Unfold(look.parts());
329 for (Character& character : characters_) {
330 const float metre = 1.0f / character.scale;
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;
344 if (!look.move().keys().empty()) {
345 moves_[skill] = look.move();
350Characters::Pose Characters::PoseFor(
const Character& character,
351 protocol::Motion motion,
float time) {
352 if (motion == protocol::MOTION_SKILL) {
353 motion = protocol::MOTION_IDLE;
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)};
362 if (characters_.empty() || (figure.
to != protocol::MOTION_WALK &&
363 figure.
to != protocol::MOTION_RUN)) {
366 const Character& character = For(figure);
367 const ModelAnimation& clip = character.clips[character.clip_for[figure.
to]];
369 const float frames =
static_cast<float>(std::max(clip.keyframeCount - 1, 1));
371 .loops = figure.
to_time * character.speed[figure.
to] * 60.0f / frames,
372 .footfalls = character.footfalls[figure.
to]};
375const Characters::Character& Characters::For(
const Figure& figure)
const {
378 uint32_t which = figure.
npc ? figure.
kind : figure.
id;
382 return characters_[which % characters_.size()];
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);
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);
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,
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);
425 const Figure& figure)
const {
426 const auto held = weapons_.find(figure.
weapon);
427 if (characters_.empty() || held == weapons_.end()) {
430 const Character& character = For(figure);
431 if (character.hand < 0) {
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)};
442 const Outline* outline)
const {
443 const Character& character = For(figure);
444 PoseAs(character, figure);
445 const Matrix placed = Placed(character, figure);
447 const float flash = figure.
flash * kFlash;
448 SetShaderValue(shader_, emission_, &flash, SHADER_UNIFORM_FLOAT);
451 auto draw = [&](Model model,
const Model& hull, Color tint) {
452 if (outline !=
nullptr) {
455 model.transform = MatrixMultiply(model.transform, placed);
456 DrawModel(model, {0.0f, 0.0f, 0.0f}, 1.0f, tint);
458 if (!character.dressed) {
459 draw(character.model, character.hull, color);
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,
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);
480 const auto held = weapons_.find(figure.
weapon);
481 if (held != weapons_.end() && character.hand >= 0) {
482 Model weapon = held->second.model;
484 MatrixMultiply(InHand(character, held->second.grip), placed);
485 if (outline !=
nullptr) {
488 DrawModel(weapon, {0.0f, 0.0f, 0.0f}, 1.0f, WHITE);
490 constexpr float kNone = 0.0f;
491 SetShaderValue(shader_, emission_, &kNone, SHADER_UNIFORM_FLOAT);
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;
507 MatrixMultiply(InHand(character, held->second.grip), placed);
508 DrawModel(weapon, {0.0f, 0.0f, 0.0f}, 1.0f, color);
510 constexpr float kNone = 0.0f;
511 SetShaderValue(shader_, emission_, &kNone, SHADER_UNIFORM_FLOAT);
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)
void Draw(const Figure &figure, Color color, const Outline *outline) const
void DrawOutline(const Model &model, const Matrix &transform, Shader shader)
Model RigModel(const std::vector< rig::Joint > &joints)
void Dress(Model &model, const std::vector< figures::Part > &parts, float metre)
Mesh Hull(const Model &model, const std::vector< figures::Part > &parts, float metre)
ModelAnimation * Bake(const rig::Rig &rig, const Model &model, int *count)
void Apply(const Bend &bend, const Joints &joints, float metre, Model &model)
std::array< float, 2 > Footfalls(const ModelAnimation &clip, int left, int right)
std::vector< rig::Joint > Skeleton(const rig::Rig &rig, int build)
Mesh Parts(const Model &model, const std::vector< figures::Part > &parts, float metre)
std::string ContentFolder()
Joints FindJoints(const Model &model)
std::vector< figures::Part > Unfold(const google::protobuf::RepeatedPtrField< figures::Part > &parts)
std::string WeaponsFolder()
Features FeaturesOf(const figures::Figures &figures, uint32_t id)
std::string MonstersFolder()
Bend BendAt(const skills::Move &move, float ms)
The move, ms into it, between the keys either side.
uint32_t skin
As 0xRRGGBBAA: white, when there are none to pick from.