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 "../graphics/Format.hpp"
13 #include "../graphics/Viewport.hpp"
19 #include <glm/gtx/io.hpp>
20 #include <glm/gtx/quaternion.hpp>
21 #include <glm/gtx/transform.hpp>
26 Entity::Entity() noexcept
36 , world_collision(false)
38 , owns_controller(false) {
42 Entity::~Entity() noexcept {
46 Entity::Entity(const Entity &other) noexcept
51 , bounds(other.bounds)
53 , max_vel(other.max_vel)
54 , max_force(other.max_force)
56 , world_collision(other.world_collision)
58 , owns_controller(false) {
62 void Entity::SetController(EntityController *c) noexcept {
65 owns_controller = true;
68 void Entity::SetController(EntityController &c) noexcept {
71 owns_controller = false;
74 void Entity::UnsetController() noexcept {
75 if (ctrl && owns_controller) {
81 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
82 if (HasController()) {
83 return GetController().ControlForce(s);
89 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
94 void Entity::Position(const glm::vec3 &pos) noexcept {
95 state.block_pos = pos;
96 state.AdjustPosition();
99 void Entity::TurnHead(float dp, float dy) noexcept {
100 SetHead(state.pitch + dp, state.yaw + dy);
103 void Entity::SetHead(float p, float y) noexcept {
106 // TODO: I feel like this could be delayed
110 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
111 return state.Transform(reference);
114 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
115 glm::mat4 transform = Transform(reference);
117 transform *= model.EyesTransform();
122 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
123 glm::mat4 transform = ViewTransform(chunk_offset);
124 glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
126 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
128 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
131 void Entity::UpdateModel() noexcept {
132 state.AdjustHeading();
134 Part::State &body_state = model.BodyState();
135 Part::State &eyes_state = model.EyesState();
136 if (&body_state != &eyes_state) {
137 body_state.orientation = glm::quat(glm::vec3(0.0f, state.yaw, 0.0f));
138 eyes_state.orientation = glm::quat(glm::vec3(state.pitch, 0.0f, 0.0f));
140 eyes_state.orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
145 void Entity::Update(float dt) {
146 if (HasController()) {
147 GetController().Update(*this, dt);
152 EntityController::~EntityController() {
157 EntityState::EntityState()
161 , orient(1.0f, 0.0f, 0.0f, 0.0f)
167 void EntityState::AdjustPosition() noexcept {
168 while (block_pos.x >= Chunk::width) {
169 block_pos.x -= Chunk::width;
172 while (block_pos.x < 0) {
173 block_pos.x += Chunk::width;
176 while (block_pos.y >= Chunk::height) {
177 block_pos.y -= Chunk::height;
180 while (block_pos.y < 0) {
181 block_pos.y += Chunk::height;
184 while (block_pos.z >= Chunk::depth) {
185 block_pos.z -= Chunk::depth;
188 while (block_pos.z < 0) {
189 block_pos.z += Chunk::depth;
194 void EntityState::AdjustHeading() noexcept {
195 while (pitch > PI / 2) {
198 while (pitch < -PI / 2) {
209 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
210 const glm::vec3 translation = RelativePosition(reference);
211 glm::mat4 transform(toMat4(orient));
212 transform[3].x = translation.x;
213 transform[3].y = translation.y;
214 transform[3].z = translation.z;
219 Player::Player(Entity &e, ChunkIndex &c)
230 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
231 if (!spawn_block || spawn_block.GetType().collide_block) {
235 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
236 if (!head_block || head_block.GetType().collide_block) {
243 void Player::Update(int dt) {
244 chunks.Rebase(entity.ChunkCoords());
248 World::World(const BlockTypeRegistry &types, const Config &config)
254 , light_direction(config.light_direction)
255 , fog_density(config.fog_density) {
264 Player *World::AddPlayer(const std::string &name) {
265 for (Player &p : players) {
266 if (p.Name() == name) {
270 Entity &entity = AddEntity();
272 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
273 entity.WorldCollidable(true);
274 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
275 players.emplace_back(entity, index);
276 return &players.back();
279 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
280 for (Player &p : players) {
281 if (p.Name() == name) {
285 Entity *entity = AddEntity(id);
290 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
291 entity->WorldCollidable(true);
292 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
293 players.emplace_back(*entity, index);
294 return &players.back();
297 Entity &World::AddEntity() {
298 if (entities.empty()) {
299 entities.emplace_back();
300 entities.back().ID(1);
301 return entities.back();
303 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
304 std::uint32_t id = entities.back().ID() + 1;
305 entities.emplace_back();
306 entities.back().ID(id);
307 return entities.back();
309 std::uint32_t id = 1;
310 auto position = entities.begin();
311 auto end = entities.end();
312 while (position != end && position->ID() == id) {
316 auto entity = entities.emplace(position);
321 Entity *World::AddEntity(std::uint32_t id) {
322 if (entities.empty() || entities.back().ID() < id) {
323 entities.emplace_back();
324 entities.back().ID(id);
325 return &entities.back();
328 auto position = entities.begin();
329 auto end = entities.end();
330 while (position != end && position->ID() < id) {
333 if (position != end && position->ID() == id) {
336 auto entity = entities.emplace(position);
341 Entity &World::ForceAddEntity(std::uint32_t id) {
342 if (entities.empty() || entities.back().ID() < id) {
343 entities.emplace_back();
344 entities.back().ID(id);
345 return entities.back();
348 auto position = entities.begin();
349 auto end = entities.end();
350 while (position != end && position->ID() < id) {
353 if (position != end && position->ID() == id) {
356 auto entity = entities.emplace(position);
369 bool CandidateLess(const Candidate &a, const Candidate &b) {
370 return a.dist < b.dist;
373 std::vector<Candidate> candidates;
377 bool World::Intersection(
380 const Chunk::Pos &reference,
385 for (Chunk &cur_chunk : chunks) {
387 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
388 candidates.push_back({ &cur_chunk, cur_dist });
392 if (candidates.empty()) return false;
394 std::sort(candidates.begin(), candidates.end(), CandidateLess);
396 coll.chunk = nullptr;
398 coll.depth = std::numeric_limits<float>::infinity();
400 for (Candidate &cand : candidates) {
401 if (cand.dist > coll.depth) continue;
402 WorldCollision cur_coll;
403 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
404 if (cur_coll.depth < coll.depth) {
413 bool World::Intersection(
416 const Entity &reference,
417 EntityCollision &coll
419 coll.entity = nullptr;
420 coll.depth = std::numeric_limits<float>::infinity();
421 for (Entity &cur_entity : entities) {
422 if (&cur_entity == &reference) {
426 glm::vec3 cur_normal;
427 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
428 // TODO: fine grained check goes here? maybe?
429 if (cur_dist < coll.depth) {
430 coll.entity = &cur_entity;
431 coll.depth = cur_dist;
432 coll.normal = cur_normal;
440 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
441 AABB box = e.Bounds();
442 Chunk::Pos reference = s.chunk_pos;
443 glm::mat4 M = s.Transform(reference);
445 for (Chunk &cur_chunk : chunks) {
446 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
447 // chunk is not one of the 3x3x3 surrounding the entity
448 // since there's no entity which can extent over 16 blocks, they can be skipped
451 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
459 void World::Update(int dt) {
460 float fdt(dt * 0.001f);
461 for (Entity &entity : entities) {
464 for (Entity &entity : entities) {
467 for (Player &player : players) {
470 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
471 if (iter->CanRemove()) {
472 iter = RemoveEntity(iter);
479 void World::Update(Entity &entity, float dt) {
480 EntityState state(entity.GetState());
482 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
483 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
484 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
485 EntityDerivative d(CalculateStep(entity, state, dt, c));
488 constexpr float sixth = 1.0f / 6.0f;
489 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
490 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
492 state.block_pos += f.position * dt;
493 state.velocity += f.velocity * dt;
494 state.AdjustPosition();
496 entity.SetState(state);
499 EntityDerivative World::CalculateStep(
500 const Entity &entity,
501 const EntityState &cur,
503 const EntityDerivative &delta
505 EntityState next(cur);
506 next.block_pos += delta.position * dt;
507 next.velocity += delta.velocity * dt;
508 next.AdjustPosition();
510 EntityDerivative out;
511 out.position = next.velocity;
512 out.velocity = CalculateForce(entity, next); // by mass = 1kg
516 glm::vec3 World::CalculateForce(
517 const Entity &entity,
518 const EntityState &state
520 return ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state);
523 glm::vec3 World::ControlForce(
524 const Entity &entity,
525 const EntityState &state
527 return entity.ControlForce(state);
532 std::vector<WorldCollision> col;
536 glm::vec3 World::CollisionForce(
537 const Entity &entity,
538 const EntityState &state
541 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
542 // determine displacement for each cardinal axis and move entity accordingly
543 glm::vec3 min_pen(0.0f);
544 glm::vec3 max_pen(0.0f);
545 for (const WorldCollision &c : col) {
546 if (!c.Blocks()) continue;
547 glm::vec3 local_pen(c.normal * c.depth);
548 // swap if neccessary (normal may point away from the entity)
549 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
552 min_pen = min(min_pen, local_pen);
553 max_pen = max(max_pen, local_pen);
555 glm::vec3 correction(0.0f);
556 // only apply correction for axes where penetration is only in one direction
557 for (std::size_t i = 0; i < 3; ++i) {
558 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
559 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
560 correction[i] = -min_pen[i];
563 correction[i] = -max_pen[i];
566 // correction may be zero in which case normalize() returns NaNs
567 if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
568 return glm::vec3(0.0f);
570 glm::vec3 normal(normalize(correction));
571 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
572 // apply force proportional to penetration
573 // use velocity projected onto normal as damper
574 constexpr float k = 1000.0f; // spring constant
575 constexpr float b = 10.0f; // damper constant
576 const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
577 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
578 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
580 return glm::vec3(0.0f);
584 glm::vec3 World::Gravity(
585 const Entity &entity,
586 const EntityState &state
588 return glm::vec3(0.0f);
591 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
593 for (auto player = players.begin(), end = players.end(); player != end;) {
594 if (&player->GetEntity() == &*eh) {
595 chunks.UnregisterIndex(player->GetChunks());
596 player = players.erase(player);
602 return entities.erase(eh);
606 void World::Render(Viewport &viewport) {
607 DirectionalLighting &entity_prog = viewport.EntityProgram();
608 entity_prog.SetLightDirection(light_direction);
609 entity_prog.SetFogDensity(fog_density);
611 for (Entity &entity : entities) {
612 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);