]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
store players in world save
[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 // TODO: set spawn base and extent from config
149 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
150 , players()
151 , entities()
152 , light_direction(config.light_direction)
153 , fog_density(config.fog_density) {
154
155 }
156
157 World::~World() {
158         chunks.UnregisterIndex(spawn_index);
159 }
160
161
162 Player *World::AddPlayer(const std::string &name) {
163         for (Player &p : players) {
164                 if (p.Name() == name) {
165                         return nullptr;
166                 }
167         }
168         Entity &entity = AddEntity();
169         entity.Name(name);
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();
176 }
177
178 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
179         for (Player &p : players) {
180                 if (p.Name() == name) {
181                         return nullptr;
182                 }
183         }
184         Entity *entity = AddEntity(id);
185         if (!entity) {
186                 return nullptr;
187         }
188         entity->Name(name);
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();
195 }
196
197 Entity &World::AddEntity() {
198         if (entities.empty()) {
199                 entities.emplace_back();
200                 entities.back().ID(1);
201                 return entities.back();
202         }
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();
208         }
209         std::uint32_t id = 1;
210         auto position = entities.begin();
211         auto end = entities.end();
212         while (position != end && position->ID() == id) {
213                 ++id;
214                 ++position;
215         }
216         auto entity = entities.emplace(position);
217         entity->ID(id);
218         return *entity;
219 }
220
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();
226         }
227
228         auto position = entities.begin();
229         auto end = entities.end();
230         while (position != end && position->ID() < id) {
231                 ++position;
232         }
233         if (position != end && position->ID() == id) {
234                 return nullptr;
235         }
236         auto entity = entities.emplace(position);
237         entity->ID(id);
238         return &*entity;
239 }
240
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();
246         }
247
248         auto position = entities.begin();
249         auto end = entities.end();
250         while (position != end && position->ID() < id) {
251                 ++position;
252         }
253         if (position != end && position->ID() == id) {
254                 return *position;
255         }
256         auto entity = entities.emplace(position);
257         entity->ID(id);
258         return *entity;
259 }
260
261
262 namespace {
263
264 struct Candidate {
265         Chunk *chunk;
266         float dist;
267 };
268
269 bool CandidateLess(const Candidate &a, const Candidate &b) {
270         return a.dist < b.dist;
271 }
272
273 std::vector<Candidate> candidates;
274
275 }
276
277 bool World::Intersection(
278         const Ray &ray,
279         const glm::mat4 &M,
280         const Chunk::Pos &reference,
281         WorldCollision &coll
282 ) {
283         candidates.clear();
284
285         for (Chunk &cur_chunk : chunks) {
286                 float cur_dist;
287                 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
288                         candidates.push_back({ &cur_chunk, cur_dist });
289                 }
290         }
291
292         if (candidates.empty()) return false;
293
294         std::sort(candidates.begin(), candidates.end(), CandidateLess);
295
296         coll.chunk = nullptr;
297         coll.block = -1;
298         coll.depth = std::numeric_limits<float>::infinity();
299
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) {
305                                 coll = cur_coll;
306                         }
307                 }
308         }
309
310         return coll.chunk;
311 }
312
313 bool World::Intersection(
314         const Ray &ray,
315         const glm::mat4 &M,
316         const Entity &reference,
317         EntityCollision &coll
318 ) {
319         coll.entity = nullptr;
320         coll.depth = std::numeric_limits<float>::infinity();
321         for (Entity &cur_entity : entities) {
322                 if (&cur_entity == &reference) {
323                         continue;
324                 }
325                 float cur_dist;
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;
333                         }
334                 }
335         }
336
337         return coll.entity;
338 }
339
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);
344         bool any = false;
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
349                         continue;
350                 }
351                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
352                         any = true;
353                 }
354         }
355         return any;
356 }
357
358
359 namespace {
360
361 std::vector<WorldCollision> col;
362
363 }
364
365 void World::Update(int dt) {
366         for (Entity &entity : entities) {
367                 entity.Update(dt);
368         }
369         for (Entity &entity : entities) {
370                 col.clear();
371                 if (entity.WorldCollidable() && Intersection(entity, col)) {
372                         // entity collides with the world
373                         Resolve(entity, col);
374                 }
375         }
376         for (Player &player : players) {
377                 player.Update(dt);
378         }
379         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
380                 if (iter->CanRemove()) {
381                         iter = RemoveEntity(iter);
382                 } else {
383                         ++iter;
384                 }
385         }
386 }
387
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) {
397                         local_disp *= -1;
398                 }
399                 min_disp = min(min_disp, local_disp);
400                 max_disp = max(max_disp, local_disp);
401         }
402         // for each axis
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;
410                         } else {
411                                 final_disp[axis] = min_disp[axis];
412                         }
413                 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
414                         final_disp[axis] = max_disp[axis];
415                 }
416         }
417         e.Position(e.Position() + final_disp);
418 }
419
420 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
421         // check for player
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);
426                         end = players.end();
427                 } else {
428                         ++player;
429                 }
430         }
431         return entities.erase(eh);
432 }
433
434
435 void World::Render(Viewport &viewport) {
436         DirectionalLighting &entity_prog = viewport.EntityProgram();
437         entity_prog.SetLightDirection(light_direction);
438         entity_prog.SetFogDensity(fog_density);
439
440         for (Entity &entity : entities) {
441                 entity.Render(entity.Transform(players.front().GetEntity().ChunkCoords()), entity_prog);
442         }
443 }
444
445 }