]> git.localhorst.tv Git - blank.git/blobdiff - src/world/world.cpp
better stability of collision response
[blank.git] / src / world / world.cpp
index 242da2796af047fc0e41f472fdb5b20126009b05..8f22f0c091645486c99913cfa4925bdc1533e5be 100644 (file)
@@ -1,4 +1,5 @@
 #include "Entity.hpp"
+#include "EntityDerivative.hpp"
 #include "EntityState.hpp"
 #include "Player.hpp"
 #include "World.hpp"
@@ -12,6 +13,7 @@
 
 #include <algorithm>
 #include <cmath>
+#include <iostream>
 #include <limits>
 #include <glm/gtx/io.hpp>
 #include <glm/gtx/quaternion.hpp>
@@ -26,13 +28,13 @@ Entity::Entity() noexcept
 , name("anonymous")
 , bounds()
 , state()
+, tgt_vel(0.0f)
 , ref_count(0)
 , world_collision(false)
 , dead(false) {
 
 }
 
-
 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
        state.chunk_pos = c;
        state.block_pos = b;
@@ -43,8 +45,20 @@ void Entity::Position(const glm::vec3 &pos) noexcept {
        state.AdjustPosition();
 }
 
+glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
+       return state.Transform(reference);
+}
+
+glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
+       glm::mat4 transform = Transform(reference);
+       if (model) {
+               transform *= model.EyesTransform();
+       }
+       return transform;
+}
+
 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
-       glm::mat4 transform = Transform(chunk_offset);
+       glm::mat4 transform = ViewTransform(chunk_offset);
        glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
        from /= from.w;
        glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
@@ -52,25 +66,6 @@ Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
        return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
 }
 
-namespace {
-
-glm::quat delta_rot(const glm::vec3 &av, float dt) {
-       glm::vec3 half(av * dt * 0.5f);
-       float mag = length(half);
-       if (mag > 0.0f) {
-               float smag = std::sin(mag) / mag;
-               return glm::quat(std::cos(mag), half * smag);
-       } else {
-               return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
-       }
-}
-
-}
-
-void Entity::Update(int dt) noexcept {
-       state.Update(dt);
-}
-
 
 EntityState::EntityState()
 : chunk_pos(0)
@@ -81,13 +76,6 @@ EntityState::EntityState()
 
 }
 
-void EntityState::Update(int dt) noexcept {
-       float fdt = float(dt);
-       block_pos += velocity * fdt;
-       orient = delta_rot(ang_vel, fdt) * orient;
-       AdjustPosition();
-}
-
 void EntityState::AdjustPosition() noexcept {
        while (block_pos.x >= Chunk::width) {
                block_pos.x -= Chunk::width;
@@ -127,7 +115,8 @@ glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
 
 Player::Player(Entity &e, ChunkIndex &c)
 : entity(e)
-, chunks(c) {
+, chunks(c)
+, inv_slot(0) {
 
 }
 
@@ -135,6 +124,19 @@ Player::~Player() {
 
 }
 
+bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
+       if (!spawn_block || spawn_block.GetType().collide_block) {
+               return false;
+       }
+
+       BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
+       if (!head_block || head_block.GetType().collide_block) {
+               return false;
+       }
+
+       return true;
+}
+
 void Player::Update(int dt) {
        chunks.Rebase(entity.ChunkCoords());
 }
@@ -144,8 +146,6 @@ World::World(const BlockTypeRegistry &types, const Config &config)
 : config(config)
 , block_type(types)
 , chunks(types)
-// TODO: set spawn base and extent from config
-, spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
 , players()
 , entities()
 , light_direction(config.light_direction)
@@ -154,7 +154,7 @@ World::World(const BlockTypeRegistry &types, const Config &config)
 }
 
 World::~World() {
-       chunks.UnregisterIndex(spawn_index);
+
 }
 
 
@@ -166,10 +166,8 @@ Player *World::AddPlayer(const std::string &name) {
        }
        Entity &entity = AddEntity();
        entity.Name(name);
-       // TODO: load from save file here
        entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
        entity.WorldCollidable(true);
-       entity.Position(config.spawn);
        ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
        players.emplace_back(entity, index);
        return &players.back();
@@ -186,10 +184,8 @@ Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
                return nullptr;
        }
        entity->Name(name);
-       // TODO: load from save file here
        entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
        entity->WorldCollidable(true);
-       entity->Position(config.spawn);
        ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
        players.emplace_back(*entity, index);
        return &players.back();
@@ -338,13 +334,13 @@ bool World::Intersection(
        return coll.entity;
 }
 
-bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
+bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
        AABB box = e.Bounds();
-       Chunk::Pos reference = e.ChunkCoords();
-       glm::mat4 M = e.Transform(reference);
+       Chunk::Pos reference = s.chunk_pos;
+       glm::mat4 M = s.Transform(reference);
        bool any = false;
        for (Chunk &cur_chunk : chunks) {
-               if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
+               if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
                        // chunk is not one of the 3x3x3 surrounding the entity
                        // since there's no entity which can extent over 16 blocks, they can be skipped
                        continue;
@@ -357,22 +353,10 @@ bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
 }
 
 
-namespace {
-
-std::vector<WorldCollision> col;
-
-}
-
 void World::Update(int dt) {
+       float fdt(dt * 0.001f);
        for (Entity &entity : entities) {
-               entity.Update(dt);
-       }
-       for (Entity &entity : entities) {
-               col.clear();
-               if (entity.WorldCollidable() && Intersection(entity, col)) {
-                       // entity collides with the world
-                       Resolve(entity, col);
-               }
+               Update(entity, fdt);
        }
        for (Player &player : players) {
                player.Update(dt);
@@ -386,36 +370,138 @@ void World::Update(int dt) {
        }
 }
 
-void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
-       // determine displacement for each cardinal axis and move entity accordingly
-       glm::vec3 min_disp(0.0f);
-       glm::vec3 max_disp(0.0f);
-       for (const WorldCollision &c : col) {
-               if (!c.Blocks()) continue;
-               glm::vec3 local_disp(c.normal * c.depth);
-               // swap if neccessary (normal may point away from the entity)
-               if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
-                       local_disp *= -1;
+namespace {
+
+glm::quat delta_rot(const glm::vec3 &av, float dt) {
+       glm::vec3 half(av * dt * 0.5f);
+       float mag = length(half);
+       if (mag > 0.0f) {
+               float smag = std::sin(mag) / mag;
+               return glm::quat(std::cos(mag), half * smag);
+       } else {
+               return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
+       }
+}
+
+}
+
+void World::Update(Entity &entity, float dt) {
+       EntityState state(entity.GetState());
+
+       EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
+       EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
+       EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
+       EntityDerivative d(CalculateStep(entity, state, dt, c));
+
+       EntityDerivative f;
+       constexpr float sixth = 1.0f / 6.0f;
+       f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
+       f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
+       f.orient = sixth * ((a.orient + 2.0f * (b.orient + c.orient)) + d.orient);
+
+       state.block_pos += f.position * dt;
+       state.velocity += f.velocity * dt;
+       state.orient = delta_rot(f.orient, dt) * state.orient;
+       state.AdjustPosition();
+
+       entity.SetState(state);
+}
+
+EntityDerivative World::CalculateStep(
+       const Entity &entity,
+       const EntityState &cur,
+       float dt,
+       const EntityDerivative &delta
+) {
+       EntityState next(cur);
+       next.block_pos += delta.position * dt;
+       next.velocity += delta.velocity * dt;
+       next.orient = delta_rot(cur.ang_vel, dt) * cur.orient;
+       next.AdjustPosition();
+
+       EntityDerivative out;
+       out.position = next.velocity;
+       out.velocity = CalculateForce(entity, next); // by mass = 1kg
+       return out;
+}
+
+glm::vec3 World::CalculateForce(
+       const Entity &entity,
+       const EntityState &state
+) {
+       return ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state);
+}
+
+glm::vec3 World::ControlForce(
+       const Entity &entity,
+       const EntityState &state
+) {
+       constexpr float k = 10.0f; // spring constant
+       constexpr float b = 10.0f; // damper constant
+       const glm::vec3 x(-entity.TargetVelocity()); // endpoint displacement from equilibrium, by 1s, in m
+       const glm::vec3 v(state.velocity); // relative velocity between endpoints in m/s
+       return ((-k) * x) - (b * v); // times 1kg/s, in kg*m/s²
+}
+
+namespace {
+
+std::vector<WorldCollision> col;
+
+}
+
+glm::vec3 World::CollisionForce(
+       const Entity &entity,
+       const EntityState &state
+) {
+       col.clear();
+       if (entity.WorldCollidable() && Intersection(entity, state, col)) {
+               // determine displacement for each cardinal axis and move entity accordingly
+               glm::vec3 min_pen(0.0f);
+               glm::vec3 max_pen(0.0f);
+               for (const WorldCollision &c : col) {
+                       if (!c.Blocks()) continue;
+                       glm::vec3 local_pen(c.normal * c.depth);
+                       // swap if neccessary (normal may point away from the entity)
+                       if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
+                               local_pen *= -1;
+                       }
+                       min_pen = min(min_pen, local_pen);
+                       max_pen = max(max_pen, local_pen);
                }
-               min_disp = min(min_disp, local_disp);
-               max_disp = max(max_disp, local_disp);
-       }
-       // for each axis
-       // if only one direction is set, use that as the final
-       // if both directions are set, use average
-       glm::vec3 final_disp(0.0f);
-       for (int axis = 0; axis < 3; ++axis) {
-               if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
-                       if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
-                               final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
+               glm::vec3 correction(0.0f);
+               // only apply correction for axes where penetration is only in one direction
+               for (std::size_t i = 0; i < 3; ++i) {
+                       if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
+                               if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
+                                       correction[i] = -min_pen[i];
+                               }
                        } else {
-                               final_disp[axis] = min_disp[axis];
+                               correction[i] = -max_pen[i];
                        }
-               } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
-                       final_disp[axis] = max_disp[axis];
                }
+               // correction may be zero in which case normalize() returns NaNs
+               if (dot(correction, correction) < std::numeric_limits<float>::epsilon()) {
+                       return glm::vec3(0.0f);
+               }
+               glm::vec3 normal(normalize(correction));
+               glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
+               // apply force proportional to penetration
+               // use velocity projected onto normal as damper
+               constexpr float k = 1000.0f; // spring constant
+               constexpr float b = 10.0f; // damper constant
+               const glm::vec3 x(-correction); // endpoint displacement from equilibrium in m
+               const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
+               return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
+       } else {
+               return glm::vec3(0.0f);
        }
-       e.Position(e.Position() + final_disp);
+}
+
+glm::vec3 World::Gravity(
+       const Entity &entity,
+       const EntityState &state
+) {
+       return glm::vec3(0.0f);
 }
 
 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {