2 #include "EntityState.hpp"
6 #include "ChunkIndex.hpp"
7 #include "EntityCollision.hpp"
8 #include "WorldCollision.hpp"
9 #include "../app/Assets.hpp"
10 #include "../graphics/Format.hpp"
11 #include "../graphics/Viewport.hpp"
16 #include <glm/gtx/io.hpp>
17 #include <glm/gtx/quaternion.hpp>
18 #include <glm/gtx/transform.hpp>
23 Entity::Entity() noexcept
30 , world_collision(false)
36 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
41 void Entity::Position(const glm::vec3 &pos) noexcept {
42 state.block_pos = pos;
43 state.AdjustPosition();
46 Ray Entity::Aim(const Chunk::Pos &chunk_offset) const noexcept {
47 glm::mat4 transform = Transform(chunk_offset);
48 glm::vec4 from = transform * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
50 glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
52 return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
57 glm::quat delta_rot(const glm::vec3 &av, float dt) {
58 glm::vec3 half(av * dt * 0.5f);
59 float mag = length(half);
61 float smag = std::sin(mag) / mag;
62 return glm::quat(std::cos(mag), half * smag);
64 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
70 void Entity::Update(int dt) noexcept {
75 EntityState::EntityState()
79 , orient(1.0f, 0.0f, 0.0f, 0.0f)
84 void EntityState::Update(int dt) noexcept {
85 float fdt = float(dt);
86 block_pos += velocity * fdt;
87 orient = delta_rot(ang_vel, fdt) * orient;
91 void EntityState::AdjustPosition() noexcept {
92 while (block_pos.x >= Chunk::width) {
93 block_pos.x -= Chunk::width;
96 while (block_pos.x < 0) {
97 block_pos.x += Chunk::width;
100 while (block_pos.y >= Chunk::height) {
101 block_pos.y -= Chunk::height;
104 while (block_pos.y < 0) {
105 block_pos.y += Chunk::height;
108 while (block_pos.z >= Chunk::depth) {
109 block_pos.z -= Chunk::depth;
112 while (block_pos.z < 0) {
113 block_pos.z += Chunk::depth;
118 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
119 const glm::vec3 translation = RelativePosition(reference);
120 glm::mat4 transform(toMat4(orient));
121 transform[3].x = translation.x;
122 transform[3].y = translation.y;
123 transform[3].z = translation.z;
128 Player::Player(Entity &e, ChunkIndex &c)
139 void Player::Update(int dt) {
140 chunks.Rebase(entity.ChunkCoords());
144 World::World(const BlockTypeRegistry &types, const Config &config)
148 // TODO: set spawn base and extent from config
149 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
152 , light_direction(config.light_direction)
153 , fog_density(config.fog_density) {
158 chunks.UnregisterIndex(spawn_index);
162 Player *World::AddPlayer(const std::string &name) {
163 for (Player &p : players) {
164 if (p.Name() == name) {
168 Entity &entity = AddEntity();
170 entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
171 entity.WorldCollidable(true);
172 entity.Position(config.spawn);
173 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
174 players.emplace_back(entity, index);
175 return &players.back();
178 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
179 for (Player &p : players) {
180 if (p.Name() == name) {
184 Entity *entity = AddEntity(id);
189 entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
190 entity->WorldCollidable(true);
191 entity->Position(config.spawn);
192 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
193 players.emplace_back(*entity, index);
194 return &players.back();
197 Entity &World::AddEntity() {
198 if (entities.empty()) {
199 entities.emplace_back();
200 entities.back().ID(1);
201 return entities.back();
203 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
204 std::uint32_t id = entities.back().ID() + 1;
205 entities.emplace_back();
206 entities.back().ID(id);
207 return entities.back();
209 std::uint32_t id = 1;
210 auto position = entities.begin();
211 auto end = entities.end();
212 while (position != end && position->ID() == id) {
216 auto entity = entities.emplace(position);
221 Entity *World::AddEntity(std::uint32_t id) {
222 if (entities.empty() || entities.back().ID() < id) {
223 entities.emplace_back();
224 entities.back().ID(id);
225 return &entities.back();
228 auto position = entities.begin();
229 auto end = entities.end();
230 while (position != end && position->ID() < id) {
233 if (position != end && position->ID() == id) {
236 auto entity = entities.emplace(position);
241 Entity &World::ForceAddEntity(std::uint32_t id) {
242 if (entities.empty() || entities.back().ID() < id) {
243 entities.emplace_back();
244 entities.back().ID(id);
245 return entities.back();
248 auto position = entities.begin();
249 auto end = entities.end();
250 while (position != end && position->ID() < id) {
253 if (position != end && position->ID() == id) {
256 auto entity = entities.emplace(position);
269 bool CandidateLess(const Candidate &a, const Candidate &b) {
270 return a.dist < b.dist;
273 std::vector<Candidate> candidates;
277 bool World::Intersection(
280 const Chunk::Pos &reference,
285 for (Chunk &cur_chunk : chunks) {
287 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
288 candidates.push_back({ &cur_chunk, cur_dist });
292 if (candidates.empty()) return false;
294 std::sort(candidates.begin(), candidates.end(), CandidateLess);
296 coll.chunk = nullptr;
298 coll.depth = std::numeric_limits<float>::infinity();
300 for (Candidate &cand : candidates) {
301 if (cand.dist > coll.depth) continue;
302 WorldCollision cur_coll;
303 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
304 if (cur_coll.depth < coll.depth) {
313 bool World::Intersection(
316 const Entity &reference,
317 EntityCollision &coll
319 coll.entity = nullptr;
320 coll.depth = std::numeric_limits<float>::infinity();
321 for (Entity &cur_entity : entities) {
322 if (&cur_entity == &reference) {
326 glm::vec3 cur_normal;
327 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
328 // TODO: fine grained check goes here? maybe?
329 if (cur_dist < coll.depth) {
330 coll.entity = &cur_entity;
331 coll.depth = cur_dist;
332 coll.normal = cur_normal;
340 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
341 AABB box = e.Bounds();
342 Chunk::Pos reference = e.ChunkCoords();
343 glm::mat4 M = e.Transform(reference);
345 for (Chunk &cur_chunk : chunks) {
346 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
347 // chunk is not one of the 3x3x3 surrounding the entity
348 // since there's no entity which can extent over 16 blocks, they can be skipped
351 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
361 std::vector<WorldCollision> col;
365 void World::Update(int dt) {
366 for (Entity &entity : entities) {
369 for (Entity &entity : entities) {
371 if (entity.WorldCollidable() && Intersection(entity, col)) {
372 // entity collides with the world
373 Resolve(entity, col);
376 for (Player &player : players) {
379 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
380 if (iter->CanRemove()) {
381 iter = RemoveEntity(iter);
388 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
389 // determine displacement for each cardinal axis and move entity accordingly
390 glm::vec3 min_disp(0.0f);
391 glm::vec3 max_disp(0.0f);
392 for (const WorldCollision &c : col) {
393 if (!c.Blocks()) continue;
394 glm::vec3 local_disp(c.normal * c.depth);
395 // swap if neccessary (normal may point away from the entity)
396 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
399 min_disp = min(min_disp, local_disp);
400 max_disp = max(max_disp, local_disp);
403 // if only one direction is set, use that as the final
404 // if both directions are set, use average
405 glm::vec3 final_disp(0.0f);
406 for (int axis = 0; axis < 3; ++axis) {
407 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
408 if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
409 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
411 final_disp[axis] = min_disp[axis];
413 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
414 final_disp[axis] = max_disp[axis];
417 e.Position(e.Position() + final_disp);
420 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
422 for (auto player = players.begin(), end = players.end(); player != end;) {
423 if (&player->GetEntity() == &*eh) {
424 chunks.UnregisterIndex(player->GetChunks());
425 player = players.erase(player);
431 return entities.erase(eh);
435 void World::Render(Viewport &viewport) {
436 DirectionalLighting &entity_prog = viewport.EntityProgram();
437 entity_prog.SetLightDirection(light_direction);
438 entity_prog.SetFogDensity(fog_density);
440 for (Entity &entity : entities) {
441 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);