2 #include "EntityDerivative.hpp"
3 #include "EntityState.hpp"
7 #include "ChunkIndex.hpp"
8 #include "EntityCollision.hpp"
9 #include "WorldCollision.hpp"
10 #include "../app/Assets.hpp"
11 #include "../graphics/Format.hpp"
12 #include "../graphics/Viewport.hpp"
18 #include <glm/gtx/io.hpp>
19 #include <glm/gtx/quaternion.hpp>
20 #include <glm/gtx/transform.hpp>
25 Entity::Entity() noexcept
33 , world_collision(false)
38 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
43 void Entity::Position(const glm::vec3 &pos) noexcept {
44 state.block_pos = pos;
45 state.AdjustPosition();
48 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
49 glm::mat4 transform = Transform(chunk_offset);
50 glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
52 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
54 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
58 EntityState::EntityState()
62 , orient(1.0f, 0.0f, 0.0f, 0.0f)
67 void EntityState::AdjustPosition() noexcept {
68 while (block_pos.x >= Chunk::width) {
69 block_pos.x -= Chunk::width;
72 while (block_pos.x < 0) {
73 block_pos.x += Chunk::width;
76 while (block_pos.y >= Chunk::height) {
77 block_pos.y -= Chunk::height;
80 while (block_pos.y < 0) {
81 block_pos.y += Chunk::height;
84 while (block_pos.z >= Chunk::depth) {
85 block_pos.z -= Chunk::depth;
88 while (block_pos.z < 0) {
89 block_pos.z += Chunk::depth;
94 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
95 const glm::vec3 translation = RelativePosition(reference);
96 glm::mat4 transform(toMat4(orient));
97 transform[3].x = translation.x;
98 transform[3].y = translation.y;
99 transform[3].z = translation.z;
104 Player::Player(Entity &e, ChunkIndex &c)
115 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
116 if (!spawn_block || spawn_block.GetType().collide_block) {
120 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
121 if (!head_block || head_block.GetType().collide_block) {
128 void Player::Update(int dt) {
129 chunks.Rebase(entity.ChunkCoords());
133 World::World(const BlockTypeRegistry &types, const Config &config)
139 , light_direction(config.light_direction)
140 , fog_density(config.fog_density) {
149 Player *World::AddPlayer(const std::string &name) {
150 for (Player &p : players) {
151 if (p.Name() == name) {
155 Entity &entity = AddEntity();
157 entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
158 entity.WorldCollidable(true);
159 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
160 players.emplace_back(entity, index);
161 return &players.back();
164 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
165 for (Player &p : players) {
166 if (p.Name() == name) {
170 Entity *entity = AddEntity(id);
175 entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
176 entity->WorldCollidable(true);
177 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
178 players.emplace_back(*entity, index);
179 return &players.back();
182 Entity &World::AddEntity() {
183 if (entities.empty()) {
184 entities.emplace_back();
185 entities.back().ID(1);
186 return entities.back();
188 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
189 std::uint32_t id = entities.back().ID() + 1;
190 entities.emplace_back();
191 entities.back().ID(id);
192 return entities.back();
194 std::uint32_t id = 1;
195 auto position = entities.begin();
196 auto end = entities.end();
197 while (position != end && position->ID() == id) {
201 auto entity = entities.emplace(position);
206 Entity *World::AddEntity(std::uint32_t id) {
207 if (entities.empty() || entities.back().ID() < id) {
208 entities.emplace_back();
209 entities.back().ID(id);
210 return &entities.back();
213 auto position = entities.begin();
214 auto end = entities.end();
215 while (position != end && position->ID() < id) {
218 if (position != end && position->ID() == id) {
221 auto entity = entities.emplace(position);
226 Entity &World::ForceAddEntity(std::uint32_t id) {
227 if (entities.empty() || entities.back().ID() < id) {
228 entities.emplace_back();
229 entities.back().ID(id);
230 return entities.back();
233 auto position = entities.begin();
234 auto end = entities.end();
235 while (position != end && position->ID() < id) {
238 if (position != end && position->ID() == id) {
241 auto entity = entities.emplace(position);
254 bool CandidateLess(const Candidate &a, const Candidate &b) {
255 return a.dist < b.dist;
258 std::vector<Candidate> candidates;
262 bool World::Intersection(
265 const Chunk::Pos &reference,
270 for (Chunk &cur_chunk : chunks) {
272 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
273 candidates.push_back({ &cur_chunk, cur_dist });
277 if (candidates.empty()) return false;
279 std::sort(candidates.begin(), candidates.end(), CandidateLess);
281 coll.chunk = nullptr;
283 coll.depth = std::numeric_limits<float>::infinity();
285 for (Candidate &cand : candidates) {
286 if (cand.dist > coll.depth) continue;
287 WorldCollision cur_coll;
288 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
289 if (cur_coll.depth < coll.depth) {
298 bool World::Intersection(
301 const Entity &reference,
302 EntityCollision &coll
304 coll.entity = nullptr;
305 coll.depth = std::numeric_limits<float>::infinity();
306 for (Entity &cur_entity : entities) {
307 if (&cur_entity == &reference) {
311 glm::vec3 cur_normal;
312 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
313 // TODO: fine grained check goes here? maybe?
314 if (cur_dist < coll.depth) {
315 coll.entity = &cur_entity;
316 coll.depth = cur_dist;
317 coll.normal = cur_normal;
325 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
326 AABB box = e.Bounds();
327 Chunk::Pos reference = s.chunk_pos;
328 glm::mat4 M = s.Transform(reference);
330 for (Chunk &cur_chunk : chunks) {
331 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
332 // chunk is not one of the 3x3x3 surrounding the entity
333 // since there's no entity which can extent over 16 blocks, they can be skipped
336 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
344 void World::Update(int dt) {
345 float fdt(dt * 0.001f);
346 for (Entity &entity : entities) {
349 for (Player &player : players) {
352 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
353 if (iter->CanRemove()) {
354 iter = RemoveEntity(iter);
363 glm::quat delta_rot(const glm::vec3 &av, float dt) {
364 glm::vec3 half(av * dt * 0.5f);
365 float mag = length(half);
367 float smag = std::sin(mag) / mag;
368 return glm::quat(std::cos(mag), half * smag);
370 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
376 void World::Update(Entity &entity, float dt) {
377 EntityState state(entity.GetState());
379 EntityDerivative a(CalculateStep(entity, state, 0.0f, EntityDerivative()));
380 EntityDerivative b(CalculateStep(entity, state, dt * 0.5f, a));
381 EntityDerivative c(CalculateStep(entity, state, dt * 0.5f, b));
382 EntityDerivative d(CalculateStep(entity, state, dt, c));
385 constexpr float sixth = 1.0f / 6.0f;
386 f.position = sixth * ((a.position + 2.0f * (b.position + c.position)) + d.position);
387 f.velocity = sixth * ((a.velocity + 2.0f * (b.velocity + c.velocity)) + d.velocity);
388 f.orient = sixth * ((a.orient + 2.0f * (b.orient + c.orient)) + d.orient);
390 state.block_pos += f.position * dt;
391 state.velocity += f.velocity * dt;
392 state.orient = delta_rot(f.orient, dt) * state.orient;
393 state.AdjustPosition();
395 entity.SetState(state);
398 EntityDerivative World::CalculateStep(
399 const Entity &entity,
400 const EntityState &cur,
402 const EntityDerivative &delta
404 EntityState next(cur);
405 next.block_pos += delta.position * dt;
406 next.velocity += delta.velocity * dt;
407 next.orient = delta_rot(cur.ang_vel, dt) * cur.orient;
408 next.AdjustPosition();
410 EntityDerivative out;
411 out.position = next.velocity;
412 out.velocity = CalculateForce(entity, next); // by mass = 1kg
416 glm::vec3 World::CalculateForce(
417 const Entity &entity,
418 const EntityState &state
420 return ControlForce(entity, state) + CollisionForce(entity, state) + Gravity(entity, state);
423 glm::vec3 World::ControlForce(
424 const Entity &entity,
425 const EntityState &state
427 constexpr float k = 10.0f; // spring constant
428 constexpr float b = 10.0f; // damper constant
429 const glm::vec3 x(-entity.TargetVelocity()); // endpoint displacement from equilibrium, by 1s, in m
430 const glm::vec3 v(state.velocity); // relative velocity between endpoints in m/s
431 return ((-k) * x) - (b * v); // times 1kg/s, in kg*m/s²
436 std::vector<WorldCollision> col;
440 glm::vec3 World::CollisionForce(
441 const Entity &entity,
442 const EntityState &state
445 if (entity.WorldCollidable() && Intersection(entity, state, col)) {
446 // determine displacement for each cardinal axis and move entity accordingly
447 glm::vec3 min_pen(0.0f);
448 glm::vec3 max_pen(0.0f);
449 for (const WorldCollision &c : col) {
450 if (!c.Blocks()) continue;
451 glm::vec3 local_pen(c.normal * c.depth);
452 // swap if neccessary (normal may point away from the entity)
453 if (dot(c.normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) > 0) {
456 min_pen = min(min_pen, local_pen);
457 max_pen = max(max_pen, local_pen);
459 glm::vec3 penetration(min_pen + max_pen);
460 glm::vec3 normal(normalize(penetration) * -1.0f);
461 glm::vec3 normal_velocity(normal * dot(state.velocity, normal));
462 // apply force proportional to penetration
463 // use velocity projected onto normal as damper
464 constexpr float k = 1000.0f; // spring constant
465 constexpr float b = 100.0f; // damper constant
466 const glm::vec3 x(penetration); // endpoint displacement from equilibrium in m
467 const glm::vec3 v(normal_velocity); // relative velocity between endpoints in m/s
468 return (((-k) * x) - (b * v)); // times 1kg/s, in kg*m/s²
470 return glm::vec3(0.0f);
474 glm::vec3 World::Gravity(
475 const Entity &entity,
476 const EntityState &state
478 return glm::vec3(0.0f);
481 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
483 for (auto player = players.begin(), end = players.end(); player != end;) {
484 if (&player->GetEntity() == &*eh) {
485 chunks.UnregisterIndex(player->GetChunks());
486 player = players.erase(player);
492 return entities.erase(eh);
496 void World::Render(Viewport &viewport) {
497 DirectionalLighting &entity_prog = viewport.EntityProgram();
498 entity_prog.SetLightDirection(light_direction);
499 entity_prog.SetFogDensity(fog_density);
501 for (Entity &entity : entities) {
502 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);