2 #include "EntityController.hpp"
3 #include "EntityDerivative.hpp"
4 #include "EntityState.hpp"
8 #include "ChunkIndex.hpp"
9 #include "EntityCollision.hpp"
10 #include "WorldCollision.hpp"
11 #include "../app/Assets.hpp"
12 #include "../geometry/const.hpp"
13 #include "../geometry/distance.hpp"
14 #include "../graphics/Format.hpp"
15 #include "../graphics/Viewport.hpp"
21 #include <glm/gtx/euler_angles.hpp>
22 #include <glm/gtx/io.hpp>
23 #include <glm/gtx/quaternion.hpp>
24 #include <glm/gtx/rotate_vector.hpp>
25 #include <glm/gtx/transform.hpp>
30 Entity::Entity() noexcept
37 , heading(0.0f, 0.0f, -1.0f)
41 , world_collision(false)
43 , owns_controller(false) {
47 Entity::~Entity() noexcept {
51 Entity::Entity(const Entity &other) noexcept
56 , bounds(other.bounds)
58 , model_transform(1.0f)
59 , view_transform(1.0f)
61 , heading(0.0f, 0.0f, -1.0f)
62 , max_vel(other.max_vel)
63 , max_force(other.max_force)
65 , world_collision(other.world_collision)
67 , owns_controller(false) {
71 void Entity::SetController(EntityController *c) noexcept {
74 owns_controller = true;
77 void Entity::SetController(EntityController &c) noexcept {
80 owns_controller = false;
83 void Entity::UnsetController() noexcept {
84 if (ctrl && owns_controller) {
90 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
91 if (HasController()) {
92 return GetController().ControlForce(*this, s);
98 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
103 void Entity::Position(const glm::vec3 &pos) noexcept {
104 state.pos.block = pos;
105 state.AdjustPosition();
108 void Entity::TurnHead(float dp, float dy) noexcept {
109 SetHead(state.pitch + dp, state.yaw + dy);
112 void Entity::SetHead(float p, float y) noexcept {
117 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
118 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
121 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
122 return Transform(reference) * view_transform;
125 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
126 glm::mat4 transform = ViewTransform(chunk_offset);
127 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
130 void Entity::Update(float dt) {
133 if (HasController()) {
134 GetController().Update(*this, dt);
139 void Entity::UpdateTransforms() noexcept {
140 // model transform is the one given by current state
141 model_transform = state.Transform(state.pos.chunk);
142 // view transform is either the model's eyes transform or,
143 // should the entity have no model, the pitch (yaw already is
144 // in model transform)
146 view_transform = model.EyesTransform();
148 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
152 void Entity::UpdateHeading() noexcept {
153 speed = length(Velocity());
154 if (speed > std::numeric_limits<float>::epsilon()) {
155 heading = Velocity() / speed;
158 // use -Z (forward axis) of model transform (our "chest")
159 heading = -glm::vec3(model_transform[2]);
163 void Entity::UpdateModel(float dt) noexcept {
164 // first, sanitize the pitch and yaw fields of state (our input)
165 // those indicate the head orientation in the entity's local cosystem
166 state.AdjustHeading();
167 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
172 void Entity::OrientBody(float dt) noexcept {
173 // maximum body rotation per second (due to velocity orientation) (90°)
174 constexpr float max_body_turn_per_second = PI_0p5;
175 const float max_body_turn = max_body_turn_per_second * dt;
176 // minimum speed to apply body correction
177 constexpr float min_speed = 0.0625f;
179 const glm::vec3 up(model_transform[1]);
180 if (speed > min_speed) {
181 // check if our orientation and velocity are aligned
182 const glm::vec3 forward(-model_transform[2]);
183 // facing is local -Z rotated about local Y by yaw and transformed into world space
184 const glm::vec3 facing(normalize(glm::vec3(glm::vec4(rotateY(glm::vec3(0.0f, 0.0f, -1.0f), state.yaw), 0.0f) * transpose(model_transform))));
185 // only adjust if velocity isn't almost parallel to up
186 float vel_dot_up = dot(Velocity(), up);
187 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
188 // get direction of velocity projected onto model plane
189 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
190 // if velocity points away from our facing (with a little bias), flip it around
191 // (the entity is "walking backwards")
192 if (dot(facing, direction) < -0.1f) {
193 direction = -direction;
195 // calculate the difference between forward and direction
196 const float absolute_difference = std::acos(dot(forward, direction));
197 // if direction is clockwise with respect to up vector, invert the angle
198 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
199 ? -absolute_difference
200 : absolute_difference;
201 // only correct by half the difference max
202 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
204 std::cout << "orientation before: " << state.orient << std::endl;
205 std::cout << "up: " << up << std::endl;
206 std::cout << "forward: " << forward << std::endl;
207 std::cout << "facing: " << facing << std::endl;
208 std::cout << "direction: " << direction << std::endl;
209 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
210 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
211 std::cout << std::endl;
213 // now rotate body by correction and head by -correction
214 state.orient = rotate(state.orient, correction, up);
215 state.yaw -= correction;
220 void Entity::OrientHead(float dt) noexcept {
221 // maximum yaw of head (90°)
222 constexpr float max_head_yaw = PI_0p5;
224 const glm::vec3 up(model_transform[1]);
225 // if yaw is bigger than max, rotate the body to accomodate
226 if (std::abs(state.yaw) > max_head_yaw) {
227 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
228 // rotate the entity by deviation about local Y
229 state.orient = rotate(state.orient, deviation, up);
230 // and remove from head yaw
231 state.yaw -= deviation;
232 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
233 state.AdjustHeading();
235 // update model if any
237 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
242 EntityController::~EntityController() {
246 bool EntityController::MaxOutForce(
248 const glm::vec3 &add,
251 if (iszero(add) || any(isnan(add))) {
254 float current = iszero(out) ? 0.0f : length(out);
255 float remain = max - current;
256 if (remain <= 0.0f) {
259 float additional = length(add);
260 if (additional > remain) {
261 out += normalize(add) * remain;
270 EntityState::EntityState()
273 , orient(1.0f, 0.0f, 0.0f, 0.0f)
279 void EntityState::AdjustPosition() noexcept {
283 void EntityState::AdjustHeading() noexcept {
284 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
293 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
294 const glm::vec3 translation = RelativePosition(reference);
295 glm::mat4 transform(toMat4(orient));
296 transform[3] = glm::vec4(translation, 1.0f);
301 Player::Player(Entity &e, ChunkIndex &c)
312 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
313 if (!spawn_block || spawn_block.GetType().collide_block) {
317 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
318 if (!head_block || head_block.GetType().collide_block) {
325 void Player::Update(int dt) {
326 chunks.Rebase(entity.ChunkCoords());
330 World::World(const BlockTypeRegistry &types, const Config &config)
336 , light_direction(config.light_direction)
337 , fog_density(config.fog_density) {
346 Player *World::AddPlayer(const std::string &name) {
347 for (Player &p : players) {
348 if (p.Name() == name) {
352 Entity &entity = AddEntity();
354 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
355 entity.WorldCollidable(true);
356 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
357 players.emplace_back(entity, index);
358 return &players.back();
361 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
362 for (Player &p : players) {
363 if (p.Name() == name) {
367 Entity *entity = AddEntity(id);
372 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
373 entity->WorldCollidable(true);
374 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
375 players.emplace_back(*entity, index);
376 return &players.back();
379 Entity &World::AddEntity() {
380 if (entities.empty()) {
381 entities.emplace_back();
382 entities.back().ID(1);
383 return entities.back();
385 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
386 std::uint32_t id = entities.back().ID() + 1;
387 entities.emplace_back();
388 entities.back().ID(id);
389 return entities.back();
391 std::uint32_t id = 1;
392 auto position = entities.begin();
393 auto end = entities.end();
394 while (position != end && position->ID() == id) {
398 auto entity = entities.emplace(position);
403 Entity *World::AddEntity(std::uint32_t id) {
404 if (entities.empty() || entities.back().ID() < id) {
405 entities.emplace_back();
406 entities.back().ID(id);
407 return &entities.back();
410 auto position = entities.begin();
411 auto end = entities.end();
412 while (position != end && position->ID() < id) {
415 if (position != end && position->ID() == id) {
418 auto entity = entities.emplace(position);
423 Entity &World::ForceAddEntity(std::uint32_t id) {
424 if (entities.empty() || entities.back().ID() < id) {
425 entities.emplace_back();
426 entities.back().ID(id);
427 return entities.back();
430 auto position = entities.begin();
431 auto end = entities.end();
432 while (position != end && position->ID() < id) {
435 if (position != end && position->ID() == id) {
438 auto entity = entities.emplace(position);
451 bool CandidateLess(const Candidate &a, const Candidate &b) {
452 return a.dist < b.dist;
455 std::vector<Candidate> candidates;
459 bool World::Intersection(
462 const ExactLocation::Coarse &reference,
467 for (Chunk &cur_chunk : chunks) {
469 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
470 candidates.push_back({ &cur_chunk, cur_dist });
474 if (candidates.empty()) return false;
476 std::sort(candidates.begin(), candidates.end(), CandidateLess);
478 coll.chunk = nullptr;
480 coll.depth = std::numeric_limits<float>::infinity();
482 for (Candidate &cand : candidates) {
483 if (cand.dist > coll.depth) continue;
484 WorldCollision cur_coll;
485 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
486 if (cur_coll.depth < coll.depth) {
495 bool World::Intersection(
498 const Entity &reference,
499 EntityCollision &coll
501 coll.entity = nullptr;
502 coll.depth = std::numeric_limits<float>::infinity();
503 for (Entity &cur_entity : entities) {
504 if (&cur_entity == &reference) {
508 glm::vec3 cur_normal;
509 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
510 // TODO: fine grained check goes here? maybe?
511 if (cur_dist < coll.depth) {
512 coll.entity = &cur_entity;
513 coll.depth = cur_dist;
514 coll.normal = cur_normal;
522 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
523 AABB box = e.Bounds();
524 glm::ivec3 reference = s.pos.chunk;
525 glm::mat4 M = s.Transform(reference);
526 return Intersection(box, M, reference, col);
529 bool World::Intersection(
532 const glm::ivec3 &reference,
533 std::vector<WorldCollision> &col
536 for (Chunk &cur_chunk : chunks) {
537 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
538 // chunk is not one of the 3x3x3 surrounding the entity
539 // since there's no entity which can extent over 16 blocks, they can be skipped
542 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
549 void World::Update(int dt) {
550 float fdt(dt * 0.001f);
551 for (Entity &entity : entities) {
554 for (Entity &entity : entities) {
557 for (Player &player : players) {
560 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
561 if (iter->CanRemove()) {
562 iter = RemoveEntity(iter);
569 void World::Update(Entity &entity, float dt) {
570 EntityState state(entity.GetState());
572 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
573 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
574 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
575 EntityDerivative d(CalculateStep(entity, state, dt, c));
578 constexpr float sixth = 1.0f / 6.0f;
579 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
580 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
582 state.pos.block += f.position * dt;
583 state.velocity += f.velocity * dt;
584 state.AdjustPosition();
586 entity.SetState(state);
589 EntityDerivative World::CalculateStep(
590 const Entity &entity,
591 const EntityState &cur,
593 const EntityDerivative &delta
595 EntityState next(cur);
596 next.pos.block += delta.position * dt;
597 next.velocity += delta.velocity * dt;
598 next.AdjustPosition();
600 if (dot(next.velocity, next.velocity) > entity.MaxVelocity() * entity.MaxVelocity()) {
601 next.velocity = normalize(next.velocity) * entity.MaxVelocity();
604 EntityDerivative out;
605 out.position = next.velocity;
606 out.velocity = CalculateForce(entity, next); // by mass = 1kg
610 glm::vec3 World::CalculateForce(
611 const Entity &entity,
612 const EntityState &state
614 glm::vec3 force(ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state));
615 if (dot(force, force) > entity.MaxControlForce() * entity.MaxControlForce()) {
616 return normalize(force) * entity.MaxControlForce();
622 glm::vec3 World::ControlForce(
623 const Entity &entity,
624 const EntityState &state
626 return entity.ControlForce(state);
631 std::vector<WorldCollision> col;
635 glm::vec3 World::CollisionForce(
636 const Entity &entity,
637 const EntityState &state
640 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
641 // determine displacement for each cardinal axis and move entity accordingly
642 glm::vec3 min_pen(0.0f);
643 glm::vec3 max_pen(0.0f);
644 for (const WorldCollision &c : col) {
645 if (!c.Blocks()) continue;
646 glm::vec3 local_pen(c.normal * c.depth);
647 // swap if neccessary (normal may point away from the entity)
648 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
651 min_pen = min(min_pen, local_pen);
652 max_pen = max(max_pen, local_pen);
654 glm::vec3 correction(0.0f);
655 // only apply correction for axes where penetration is only in one direction
656 for (std::size_t i = 0; i < 3; ++i) {
657 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
658 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
659 correction[i] = -min_pen[i];
662 correction[i] = -max_pen[i];
665 // correction may be zero in which case normalize() returns NaNs
666 if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
667 return glm::vec3(0.0f);
669 glm::vec3 normal(normalize(correction));
670 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
671 // apply force proportional to penetration
672 // use velocity projected onto normal as damper
673 constexpr float k = 1000.0f; // spring constant
674 constexpr float b = 10.0f; // damper constant
675 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
676 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
677 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
679 return glm::vec3(0.0f);
683 glm::vec3 World::Gravity(
684 const Entity &entity,
685 const EntityState &state
687 return glm::vec3(0.0f);
690 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
692 for (auto player = players.begin(), end = players.end(); player != end;) {
693 if (&player->GetEntity() == &*eh) {
694 chunks.UnregisterIndex(player->GetChunks());
695 player = players.erase(player);
701 return entities.erase(eh);
705 void World::Render(Viewport &viewport) {
706 DirectionalLighting &entity_prog = viewport.EntityProgram();
707 entity_prog.SetFogDensity(fog_density);
711 glm::vec3 ambient_col;
712 for (Entity &entity : entities) {
713 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
714 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
715 GetLight(entity, light_dir, light_col, ambient_col);
716 entity_prog.SetLightDirection(light_dir);
717 entity_prog.SetLightColor(light_col);
718 entity_prog.SetAmbientColor(ambient_col);
719 entity.Render(M, entity_prog);
724 // this should interpolate based on the fractional part of entity's block position
725 void World::GetLight(
731 Chunk *chunk = chunks.Get(e.ChunkCoords());
733 // chunk unavailable, so make it really dark and from
734 // some arbitrary direction
735 dir = glm::vec3(1.0f, 2.0f, 3.0f);
736 col = glm::vec3(0.025f); // ~0.8^15
739 glm::ivec3 base(e.Position());
740 int base_light = chunk->GetLight(base);
743 glm::ivec3 acc(0, 0, 0);
744 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
745 for (offset.y = -1; offset.y < 2; ++offset.y) {
746 for (offset.x = -1; offset.x < 2; ++offset.x) {
747 BlockLookup block(chunk, base + offset);
749 // missing, just ignore it
752 // otherwise, accumulate the difference times direction
753 acc += offset * (base_light - block.GetLight());
754 max_light = std::max(max_light, block.GetLight());
755 min_light = std::min(min_light, block.GetLight());
760 col = glm::vec3(std::pow(0.8f, 15 - max_light));
761 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
766 PrimitiveMesh::Buffer debug_buf;
770 void World::RenderDebug(Viewport &viewport) {
771 PrimitiveMesh debug_mesh;
772 PlainColor &prog = viewport.WorldColorProgram();
773 for (const Entity &entity : entities) {
774 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
775 debug_mesh.Update(debug_buf);
776 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
777 debug_mesh.DrawLines();