]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
move spawn index out of world
[blank.git] / src / world / world.cpp
1 #include "Entity.hpp"
2 #include "EntityState.hpp"
3 #include "Player.hpp"
4 #include "World.hpp"
5
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"
12
13 #include <algorithm>
14 #include <cmath>
15 #include <limits>
16 #include <glm/gtx/io.hpp>
17 #include <glm/gtx/quaternion.hpp>
18 #include <glm/gtx/transform.hpp>
19
20
21 namespace blank {
22
23 Entity::Entity() noexcept
24 : model()
25 , id(-1)
26 , name("anonymous")
27 , bounds()
28 , state()
29 , ref_count(0)
30 , world_collision(false)
31 , dead(false) {
32
33 }
34
35
36 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
37         state.chunk_pos = c;
38         state.block_pos = b;
39 }
40
41 void Entity::Position(const glm::vec3 &pos) noexcept {
42         state.block_pos = pos;
43         state.AdjustPosition();
44 }
45
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);
49         from /= from.w;
50         glm::vec4 to = transform * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
51         to /= to.w;
52         return Ray{ glm::vec3(from), glm::normalize(glm::vec3(to - from)) };
53 }
54
55 namespace {
56
57 glm::quat delta_rot(const glm::vec3 &av, float dt) {
58         glm::vec3 half(av * dt * 0.5f);
59         float mag = length(half);
60         if (mag > 0.0f) {
61                 float smag = std::sin(mag) / mag;
62                 return glm::quat(std::cos(mag), half * smag);
63         } else {
64                 return glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
65         }
66 }
67
68 }
69
70 void Entity::Update(int dt) noexcept {
71         state.Update(dt);
72 }
73
74
75 EntityState::EntityState()
76 : chunk_pos(0)
77 , block_pos(0.0f)
78 , velocity(0.0f)
79 , orient(1.0f, 0.0f, 0.0f, 0.0f)
80 , ang_vel(0.0f) {
81
82 }
83
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;
88         AdjustPosition();
89 }
90
91 void EntityState::AdjustPosition() noexcept {
92         while (block_pos.x >= Chunk::width) {
93                 block_pos.x -= Chunk::width;
94                 ++chunk_pos.x;
95         }
96         while (block_pos.x < 0) {
97                 block_pos.x += Chunk::width;
98                 --chunk_pos.x;
99         }
100         while (block_pos.y >= Chunk::height) {
101                 block_pos.y -= Chunk::height;
102                 ++chunk_pos.y;
103         }
104         while (block_pos.y < 0) {
105                 block_pos.y += Chunk::height;
106                 --chunk_pos.y;
107         }
108         while (block_pos.z >= Chunk::depth) {
109                 block_pos.z -= Chunk::depth;
110                 ++chunk_pos.z;
111         }
112         while (block_pos.z < 0) {
113                 block_pos.z += Chunk::depth;
114                 --chunk_pos.z;
115         }
116 }
117
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;
124         return transform;
125 }
126
127
128 Player::Player(Entity &e, ChunkIndex &c)
129 : entity(e)
130 , chunks(c)
131 , inv_slot(0) {
132
133 }
134
135 Player::~Player() {
136
137 }
138
139 void Player::Update(int dt) {
140         chunks.Rebase(entity.ChunkCoords());
141 }
142
143
144 World::World(const BlockTypeRegistry &types, const Config &config)
145 : config(config)
146 , block_type(types)
147 , chunks(types)
148 , players()
149 , entities()
150 , light_direction(config.light_direction)
151 , fog_density(config.fog_density) {
152
153 }
154
155 World::~World() {
156
157 }
158
159
160 Player *World::AddPlayer(const std::string &name) {
161         for (Player &p : players) {
162                 if (p.Name() == name) {
163                         return nullptr;
164                 }
165         }
166         Entity &entity = AddEntity();
167         entity.Name(name);
168         entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
169         entity.WorldCollidable(true);
170         ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
171         players.emplace_back(entity, index);
172         return &players.back();
173 }
174
175 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
176         for (Player &p : players) {
177                 if (p.Name() == name) {
178                         return nullptr;
179                 }
180         }
181         Entity *entity = AddEntity(id);
182         if (!entity) {
183                 return nullptr;
184         }
185         entity->Name(name);
186         entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
187         entity->WorldCollidable(true);
188         ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
189         players.emplace_back(*entity, index);
190         return &players.back();
191 }
192
193 Entity &World::AddEntity() {
194         if (entities.empty()) {
195                 entities.emplace_back();
196                 entities.back().ID(1);
197                 return entities.back();
198         }
199         if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
200                 std::uint32_t id = entities.back().ID() + 1;
201                 entities.emplace_back();
202                 entities.back().ID(id);
203                 return entities.back();
204         }
205         std::uint32_t id = 1;
206         auto position = entities.begin();
207         auto end = entities.end();
208         while (position != end && position->ID() == id) {
209                 ++id;
210                 ++position;
211         }
212         auto entity = entities.emplace(position);
213         entity->ID(id);
214         return *entity;
215 }
216
217 Entity *World::AddEntity(std::uint32_t id) {
218         if (entities.empty() || entities.back().ID() < id) {
219                 entities.emplace_back();
220                 entities.back().ID(id);
221                 return &entities.back();
222         }
223
224         auto position = entities.begin();
225         auto end = entities.end();
226         while (position != end && position->ID() < id) {
227                 ++position;
228         }
229         if (position != end && position->ID() == id) {
230                 return nullptr;
231         }
232         auto entity = entities.emplace(position);
233         entity->ID(id);
234         return &*entity;
235 }
236
237 Entity &World::ForceAddEntity(std::uint32_t id) {
238         if (entities.empty() || entities.back().ID() < id) {
239                 entities.emplace_back();
240                 entities.back().ID(id);
241                 return entities.back();
242         }
243
244         auto position = entities.begin();
245         auto end = entities.end();
246         while (position != end && position->ID() < id) {
247                 ++position;
248         }
249         if (position != end && position->ID() == id) {
250                 return *position;
251         }
252         auto entity = entities.emplace(position);
253         entity->ID(id);
254         return *entity;
255 }
256
257
258 namespace {
259
260 struct Candidate {
261         Chunk *chunk;
262         float dist;
263 };
264
265 bool CandidateLess(const Candidate &a, const Candidate &b) {
266         return a.dist < b.dist;
267 }
268
269 std::vector<Candidate> candidates;
270
271 }
272
273 bool World::Intersection(
274         const Ray &ray,
275         const glm::mat4 &M,
276         const Chunk::Pos &reference,
277         WorldCollision &coll
278 ) {
279         candidates.clear();
280
281         for (Chunk &cur_chunk : chunks) {
282                 float cur_dist;
283                 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
284                         candidates.push_back({ &cur_chunk, cur_dist });
285                 }
286         }
287
288         if (candidates.empty()) return false;
289
290         std::sort(candidates.begin(), candidates.end(), CandidateLess);
291
292         coll.chunk = nullptr;
293         coll.block = -1;
294         coll.depth = std::numeric_limits<float>::infinity();
295
296         for (Candidate &cand : candidates) {
297                 if (cand.dist > coll.depth) continue;
298                 WorldCollision cur_coll;
299                 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
300                         if (cur_coll.depth < coll.depth) {
301                                 coll = cur_coll;
302                         }
303                 }
304         }
305
306         return coll.chunk;
307 }
308
309 bool World::Intersection(
310         const Ray &ray,
311         const glm::mat4 &M,
312         const Entity &reference,
313         EntityCollision &coll
314 ) {
315         coll.entity = nullptr;
316         coll.depth = std::numeric_limits<float>::infinity();
317         for (Entity &cur_entity : entities) {
318                 if (&cur_entity == &reference) {
319                         continue;
320                 }
321                 float cur_dist;
322                 glm::vec3 cur_normal;
323                 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
324                         // TODO: fine grained check goes here? maybe?
325                         if (cur_dist < coll.depth) {
326                                 coll.entity = &cur_entity;
327                                 coll.depth = cur_dist;
328                                 coll.normal = cur_normal;
329                         }
330                 }
331         }
332
333         return coll.entity;
334 }
335
336 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
337         AABB box = e.Bounds();
338         Chunk::Pos reference = e.ChunkCoords();
339         glm::mat4 M = e.Transform(reference);
340         bool any = false;
341         for (Chunk &cur_chunk : chunks) {
342                 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
343                         // chunk is not one of the 3x3x3 surrounding the entity
344                         // since there's no entity which can extent over 16 blocks, they can be skipped
345                         continue;
346                 }
347                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
348                         any = true;
349                 }
350         }
351         return any;
352 }
353
354
355 namespace {
356
357 std::vector<WorldCollision> col;
358
359 }
360
361 void World::Update(int dt) {
362         for (Entity &entity : entities) {
363                 entity.Update(dt);
364         }
365         for (Entity &entity : entities) {
366                 col.clear();
367                 if (entity.WorldCollidable() && Intersection(entity, col)) {
368                         // entity collides with the world
369                         Resolve(entity, col);
370                 }
371         }
372         for (Player &player : players) {
373                 player.Update(dt);
374         }
375         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
376                 if (iter->CanRemove()) {
377                         iter = RemoveEntity(iter);
378                 } else {
379                         ++iter;
380                 }
381         }
382 }
383
384 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
385         // determine displacement for each cardinal axis and move entity accordingly
386         glm::vec3 min_disp(0.0f);
387         glm::vec3 max_disp(0.0f);
388         for (const WorldCollision &c : col) {
389                 if (!c.Blocks()) continue;
390                 glm::vec3 local_disp(c.normal * c.depth);
391                 // swap if neccessary (normal may point away from the entity)
392                 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
393                         local_disp *= -1;
394                 }
395                 min_disp = min(min_disp, local_disp);
396                 max_disp = max(max_disp, local_disp);
397         }
398         // for each axis
399         // if only one direction is set, use that as the final
400         // if both directions are set, use average
401         glm::vec3 final_disp(0.0f);
402         for (int axis = 0; axis < 3; ++axis) {
403                 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
404                         if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
405                                 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
406                         } else {
407                                 final_disp[axis] = min_disp[axis];
408                         }
409                 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
410                         final_disp[axis] = max_disp[axis];
411                 }
412         }
413         e.Position(e.Position() + final_disp);
414 }
415
416 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
417         // check for player
418         for (auto player = players.begin(), end = players.end(); player != end;) {
419                 if (&player->GetEntity() == &*eh) {
420                         chunks.UnregisterIndex(player->GetChunks());
421                         player = players.erase(player);
422                         end = players.end();
423                 } else {
424                         ++player;
425                 }
426         }
427         return entities.erase(eh);
428 }
429
430
431 void World::Render(Viewport &viewport) {
432         DirectionalLighting &entity_prog = viewport.EntityProgram();
433         entity_prog.SetLightDirection(light_direction);
434         entity_prog.SetFogDensity(fog_density);
435
436         for (Entity &entity : entities) {
437                 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);
438         }
439 }
440
441 }