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/projection.hpp>
24 #include <glm/gtx/quaternion.hpp>
25 #include <glm/gtx/rotate_vector.hpp>
26 #include <glm/gtx/transform.hpp>
31 Entity::Entity() noexcept
39 , heading(0.0f, 0.0f, -1.0f)
43 , world_collision(false)
45 , owns_controller(false) {
49 Entity::~Entity() noexcept {
53 Entity::Entity(const Entity &other) noexcept
58 , bounds(other.bounds)
60 , model_transform(1.0f)
61 , view_transform(1.0f)
63 , heading(0.0f, 0.0f, -1.0f)
64 , max_vel(other.max_vel)
65 , max_force(other.max_force)
67 , world_collision(other.world_collision)
69 , owns_controller(false) {
73 void Entity::SetController(EntityController *c) noexcept {
76 owns_controller = true;
79 void Entity::SetController(EntityController &c) noexcept {
82 owns_controller = false;
85 void Entity::UnsetController() noexcept {
86 if (ctrl && owns_controller) {
92 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
94 if (HasController()) {
95 force = GetController().ControlForce(*this, s);
99 limit(force, max_force);
103 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
108 void Entity::Position(const glm::vec3 &pos) noexcept {
109 state.pos.block = pos;
110 state.AdjustPosition();
113 void Entity::TurnHead(float dp, float dy) noexcept {
114 SetHead(state.pitch + dp, state.yaw + dy);
117 void Entity::SetHead(float p, float y) noexcept {
122 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
123 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
126 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
127 return Transform(reference) * view_transform;
130 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
131 glm::mat4 transform = ViewTransform(chunk_offset);
132 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
135 void Entity::Update(World &world, float dt) {
136 if (HasController()) {
137 GetController().Update(*this, dt);
139 UpdatePhysics(world, dt);
145 void Entity::UpdatePhysics(World &world, float dt) {
146 EntityState s(state);
148 EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
149 EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
150 EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
151 EntityDerivative d(CalculateStep(world, s, dt, c));
154 constexpr float sixth = 1.0f / 6.0f;
155 f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
156 f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
158 s.pos.block += f.position * dt;
159 s.velocity += f.velocity * dt;
160 limit(s.velocity, max_vel);
161 world.ResolveWorldCollision(*this, s);
167 EntityDerivative Entity::CalculateStep(
169 const EntityState &cur,
171 const EntityDerivative &delta
173 EntityState next(cur);
174 next.pos.block += delta.position * dt;
175 next.velocity += delta.velocity * dt;
176 limit(next.velocity, max_vel);
177 world.ResolveWorldCollision(*this, next);
178 next.AdjustPosition();
180 EntityDerivative out;
181 out.position = next.velocity;
182 out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
187 void Entity::UpdateTransforms() noexcept {
188 // model transform is the one given by current state
189 model_transform = state.Transform(state.pos.chunk);
190 // view transform is either the model's eyes transform or,
191 // should the entity have no model, the pitch (yaw already is
192 // in model transform)
194 view_transform = model.EyesTransform();
196 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
200 void Entity::UpdateHeading() noexcept {
201 speed = length(Velocity());
202 if (speed > std::numeric_limits<float>::epsilon()) {
203 heading = Velocity() / speed;
206 // use -Z (forward axis) of model transform (our "chest")
207 heading = -glm::vec3(model_transform[2]);
211 void Entity::UpdateModel(float dt) noexcept {
212 // first, sanitize the pitch and yaw fields of state (our input)
213 // those indicate the head orientation in the entity's local cosystem
214 state.AdjustHeading();
215 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
220 void Entity::OrientBody(float dt) noexcept {
221 // maximum body rotation per second (due to velocity orientation) (90°)
222 constexpr float max_body_turn_per_second = PI_0p5;
223 const float max_body_turn = max_body_turn_per_second * dt;
224 // minimum speed to apply body correction
225 constexpr float min_speed = 0.0625f;
227 const glm::vec3 up(model_transform[1]);
228 if (speed > min_speed) {
229 // check if our orientation and velocity are aligned
230 const glm::vec3 forward(-model_transform[2]);
231 // facing is local -Z rotated about local Y by yaw and transformed into world space
232 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))));
233 // only adjust if velocity isn't almost parallel to up
234 float vel_dot_up = dot(Velocity(), up);
235 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
236 // get direction of velocity projected onto model plane
237 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
238 // if velocity points away from our facing (with a little bias), flip it around
239 // (the entity is "walking backwards")
240 if (dot(facing, direction) < -0.1f) {
241 direction = -direction;
243 // calculate the difference between forward and direction
244 const float absolute_difference = std::acos(dot(forward, direction));
245 // if direction is clockwise with respect to up vector, invert the angle
246 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
247 ? -absolute_difference
248 : absolute_difference;
249 // only correct by half the difference max
250 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
252 std::cout << "orientation before: " << state.orient << std::endl;
253 std::cout << "up: " << up << std::endl;
254 std::cout << "forward: " << forward << std::endl;
255 std::cout << "facing: " << facing << std::endl;
256 std::cout << "direction: " << direction << std::endl;
257 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
258 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
259 std::cout << std::endl;
261 // now rotate body by correction and head by -correction
262 state.orient = rotate(state.orient, correction, up);
263 state.yaw -= correction;
268 void Entity::OrientHead(float dt) noexcept {
269 // maximum yaw of head (60°)
270 constexpr float max_head_yaw = PI / 3.0f;
272 const glm::vec3 up(model_transform[1]);
273 // if yaw is bigger than max, rotate the body to accomodate
274 if (std::abs(state.yaw) > max_head_yaw) {
275 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
276 // rotate the entity by deviation about local Y
277 state.orient = rotate(state.orient, deviation, up);
278 // and remove from head yaw
279 state.yaw -= deviation;
280 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
281 state.AdjustHeading();
283 // update model if any
285 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
290 EntityController::~EntityController() {
294 bool EntityController::MaxOutForce(
296 const glm::vec3 &add,
299 if (iszero(add) || any(isnan(add))) {
302 float current = iszero(out) ? 0.0f : length(out);
303 float remain = max - current;
304 if (remain <= 0.0f) {
307 float additional = length(add);
308 if (additional > remain) {
309 out += normalize(add) * remain;
318 EntityState::EntityState()
321 , orient(1.0f, 0.0f, 0.0f, 0.0f)
327 void EntityState::AdjustPosition() noexcept {
331 void EntityState::AdjustHeading() noexcept {
332 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
341 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
342 const glm::vec3 translation = RelativePosition(reference);
343 glm::mat4 transform(toMat4(orient));
344 transform[3] = glm::vec4(translation, 1.0f);
349 Player::Player(Entity &e, ChunkIndex &c)
360 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
361 if (!spawn_block || spawn_block.GetType().collide_block) {
365 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
366 if (!head_block || head_block.GetType().collide_block) {
373 void Player::Update(int dt) {
374 chunks.Rebase(entity.ChunkCoords());
378 World::World(const BlockTypeRegistry &types, const Config &config)
384 , light_direction(config.light_direction)
385 , fog_density(config.fog_density) {
390 for (Entity &e : entities) {
393 std::size_t removed = 0;
396 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
397 if (e->CanRemove()) {
399 end = entities.end();
403 } while (removed > 0 && !entities.empty());
407 Player *World::AddPlayer(const std::string &name) {
408 for (Player &p : players) {
409 if (p.Name() == name) {
413 Entity &entity = AddEntity();
415 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
416 entity.WorldCollidable(true);
417 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
418 players.emplace_back(entity, index);
419 return &players.back();
422 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
423 for (Player &p : players) {
424 if (p.Name() == name) {
428 Entity *entity = AddEntity(id);
433 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
434 entity->WorldCollidable(true);
435 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
436 players.emplace_back(*entity, index);
437 return &players.back();
440 Entity &World::AddEntity() {
441 if (entities.empty()) {
442 entities.emplace_back();
443 entities.back().ID(1);
444 return entities.back();
446 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
447 std::uint32_t id = entities.back().ID() + 1;
448 entities.emplace_back();
449 entities.back().ID(id);
450 return entities.back();
452 std::uint32_t id = 1;
453 auto position = entities.begin();
454 auto end = entities.end();
455 while (position != end && position->ID() == id) {
459 auto entity = entities.emplace(position);
464 Entity *World::AddEntity(std::uint32_t id) {
465 if (entities.empty() || entities.back().ID() < id) {
466 entities.emplace_back();
467 entities.back().ID(id);
468 return &entities.back();
471 auto position = entities.begin();
472 auto end = entities.end();
473 while (position != end && position->ID() < id) {
476 if (position != end && position->ID() == id) {
479 auto entity = entities.emplace(position);
484 Entity &World::ForceAddEntity(std::uint32_t id) {
485 if (entities.empty() || entities.back().ID() < id) {
486 entities.emplace_back();
487 entities.back().ID(id);
488 return entities.back();
491 auto position = entities.begin();
492 auto end = entities.end();
493 while (position != end && position->ID() < id) {
496 if (position != end && position->ID() == id) {
499 auto entity = entities.emplace(position);
512 bool CandidateLess(const Candidate &a, const Candidate &b) {
513 return a.dist < b.dist;
516 std::vector<Candidate> candidates;
520 bool World::Intersection(
522 const ExactLocation::Coarse &reference,
527 for (Chunk &cur_chunk : chunks) {
529 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
530 candidates.push_back({ &cur_chunk, cur_dist });
534 if (candidates.empty()) return false;
536 std::sort(candidates.begin(), candidates.end(), CandidateLess);
538 coll.chunk = nullptr;
540 coll.depth = std::numeric_limits<float>::infinity();
542 for (Candidate &cand : candidates) {
543 if (cand.dist > coll.depth) continue;
544 WorldCollision cur_coll;
545 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
546 if (cur_coll.depth < coll.depth) {
555 bool World::Intersection(
557 const Entity &reference,
558 EntityCollision &coll
560 coll.entity = nullptr;
561 coll.depth = std::numeric_limits<float>::infinity();
562 for (Entity &cur_entity : entities) {
563 if (&cur_entity == &reference) {
567 glm::vec3 cur_normal;
568 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
569 // TODO: fine grained check goes here? maybe?
570 if (cur_dist < coll.depth) {
571 coll.entity = &cur_entity;
572 coll.depth = cur_dist;
573 coll.normal = cur_normal;
581 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
582 glm::ivec3 reference = s.pos.chunk;
583 glm::mat4 M = s.Transform(reference);
585 ExactLocation::Coarse begin(reference - 1);
586 ExactLocation::Coarse end(reference + 2);
589 for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
590 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
591 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
592 Chunk *chunk = chunks.Get(pos);
593 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
602 bool World::Intersection(
605 const glm::ivec3 &reference,
606 std::vector<WorldCollision> &col
609 for (Chunk &cur_chunk : chunks) {
610 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
611 // chunk is not one of the 3x3x3 surrounding the entity
612 // since there's no entity which can extent over 16 blocks, they can be skipped
613 // TODO: change to indexed (like with entity)
616 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
623 void World::Update(int dt) {
624 float fdt(dt * 0.001f);
625 for (Entity &entity : entities) {
626 entity.Update(*this, fdt);
628 for (Player &player : players) {
631 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
632 if (iter->CanRemove()) {
633 iter = RemoveEntity(iter);
642 std::vector<WorldCollision> col;
646 void World::ResolveWorldCollision(
647 const Entity &entity,
651 if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
652 // no collision, no fix
655 glm::vec3 correction = CombinedInterpenetration(state, col);
656 // correction may be zero in which case normalize() returns NaNs
657 if (iszero(correction)) {
660 // if entity is already going in the direction of correction,
661 // let the problem resolve itself
662 if (dot(state.velocity, correction) >= 0.0f) {
665 // apply correction, maybe could use some damping, gotta test
666 state.pos.block += correction;
668 glm::vec3 normal_velocity(proj(state.velocity, correction));
669 state.velocity -= normal_velocity;
672 glm::vec3 World::CombinedInterpenetration(
673 const EntityState &state,
674 const std::vector<WorldCollision> &col
676 // determine displacement for each cardinal axis and move entity accordingly
677 glm::vec3 min_pen(0.0f);
678 glm::vec3 max_pen(0.0f);
679 for (const WorldCollision &c : col) {
680 if (!c.Blocks()) continue;
681 glm::vec3 normal(c.normal);
682 // swap if neccessary (normal may point away from the entity)
683 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
686 // check if block surface is "inside"
687 Block::Face coll_face = Block::NormalFace(normal);
688 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
689 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
690 // yep, so ignore this contact
693 glm::vec3 local_pen(normal * c.depth);
694 min_pen = min(min_pen, local_pen);
695 max_pen = max(max_pen, local_pen);
698 // only apply correction for axes where penetration is only in one direction
699 for (std::size_t i = 0; i < 3; ++i) {
700 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
701 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
711 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
712 glm::vec3 force(0.0f);
713 ExactLocation::Coarse begin(loc.chunk - 1);
714 ExactLocation::Coarse end(loc.chunk + 2);
716 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
717 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
718 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
719 const Chunk *chunk = chunks.Get(pos);
721 force += chunk->GravityAt(loc);
730 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
732 for (auto player = players.begin(), end = players.end(); player != end;) {
733 if (&player->GetEntity() == &*eh) {
734 chunks.UnregisterIndex(player->GetChunks());
735 player = players.erase(player);
741 return entities.erase(eh);
745 void World::Render(Viewport &viewport) {
746 DirectionalLighting &entity_prog = viewport.EntityProgram();
747 entity_prog.SetFogDensity(fog_density);
751 glm::vec3 ambient_col;
752 for (Entity &entity : entities) {
753 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
754 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
755 GetLight(entity, light_dir, light_col, ambient_col);
756 entity_prog.SetLightDirection(light_dir);
757 entity_prog.SetLightColor(light_col);
758 entity_prog.SetAmbientColor(ambient_col);
759 entity.Render(M, entity_prog);
764 // this should interpolate based on the fractional part of entity's block position
765 void World::GetLight(
771 BlockLookup center(chunks.Get(e.ChunkCoords()), e.Position());
773 // chunk unavailable, so make it really dark and from
774 // some arbitrary direction
775 dir = glm::vec3(1.0f, 2.0f, 3.0f);
776 col = glm::vec3(0.025f); // ~0.8^15
779 glm::ivec3 base(center.GetBlockPos());
780 int base_light = center.GetLight();
783 glm::ivec3 acc(0, 0, 0);
784 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
785 for (offset.y = -1; offset.y < 2; ++offset.y) {
786 for (offset.x = -1; offset.x < 2; ++offset.x) {
787 BlockLookup block(¢er.GetChunk(), center.GetBlockPos() + offset);
789 // missing, just ignore it
792 // otherwise, accumulate the difference times direction
793 acc += offset * (base_light - block.GetLight());
794 max_light = std::max(max_light, block.GetLight());
795 min_light = std::min(min_light, block.GetLight());
800 col = glm::vec3(std::pow(0.8f, 15 - max_light));
801 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
806 PrimitiveMesh::Buffer debug_buf;
810 void World::RenderDebug(Viewport &viewport) {
811 PrimitiveMesh debug_mesh;
812 PlainColor &prog = viewport.WorldColorProgram();
813 for (const Entity &entity : entities) {
814 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
815 debug_mesh.Update(debug_buf);
816 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
817 debug_mesh.DrawLines();