]> git.localhorst.tv Git - blank.git/blob - src/world/World.cpp
fix loop removing players from world
[blank.git] / src / world / World.cpp
1 #include "World.hpp"
2
3 #include "ChunkIndex.hpp"
4 #include "EntityCollision.hpp"
5 #include "WorldCollision.hpp"
6 #include "../app/Assets.hpp"
7 #include "../graphics/Format.hpp"
8 #include "../graphics/Viewport.hpp"
9
10 #include <algorithm>
11 #include <limits>
12 #include <glm/gtx/io.hpp>
13 #include <glm/gtx/transform.hpp>
14
15
16 namespace blank {
17
18 World::World(const BlockTypeRegistry &types, const Config &config)
19 : config(config)
20 , block_type(types)
21 , chunks(types)
22 // TODO: set spawn base and extent from config
23 , spawn_index(chunks.MakeIndex(Chunk::Pos(0, 0, 0), 3))
24 , players()
25 , entities()
26 , light_direction(config.light_direction)
27 , fog_density(config.fog_density) {
28
29 }
30
31 World::~World() {
32         chunks.UnregisterIndex(spawn_index);
33 }
34
35
36 Player World::AddPlayer(const std::string &name) {
37         for (Player &p : players) {
38                 if (p.entity->Name() == name) {
39                         return { nullptr, nullptr };
40                 }
41         }
42         Entity &entity = AddEntity();
43         entity.Name(name);
44         // TODO: load from save file here
45         entity.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
46         entity.WorldCollidable(true);
47         entity.Position(config.spawn);
48         ChunkIndex *index = &chunks.MakeIndex(entity.ChunkCoords(), 6);
49         players.emplace_back(&entity, index);
50         return players.back();
51 }
52
53 Player World::AddPlayer(const std::string &name, std::uint32_t id) {
54         for (Player &p : players) {
55                 if (p.entity->Name() == name) {
56                         return { nullptr, nullptr };
57                 }
58         }
59         Entity *entity = AddEntity(id);
60         if (!entity) {
61                 return { nullptr, nullptr };
62         }
63         entity->Name(name);
64         // TODO: load from save file here
65         entity->Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
66         entity->WorldCollidable(true);
67         entity->Position(config.spawn);
68         ChunkIndex *index = &chunks.MakeIndex(entity->ChunkCoords(), 6);
69         players.emplace_back(entity, index);
70         return players.back();
71 }
72
73 Entity &World::AddEntity() {
74         if (entities.empty()) {
75                 entities.emplace_back();
76                 entities.back().ID(1);
77                 return entities.back();
78         }
79         if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
80                 std::uint32_t id = entities.back().ID() + 1;
81                 entities.emplace_back();
82                 entities.back().ID(id);
83                 return entities.back();
84         }
85         std::uint32_t id = 1;
86         auto position = entities.begin();
87         auto end = entities.end();
88         while (position != end && position->ID() == id) {
89                 ++id;
90                 ++position;
91         }
92         auto entity = entities.emplace(position);
93         entity->ID(id);
94         return *entity;
95 }
96
97 Entity *World::AddEntity(std::uint32_t id) {
98         if (entities.empty() || entities.back().ID() < id) {
99                 entities.emplace_back();
100                 entities.back().ID(id);
101                 return &entities.back();
102         }
103
104         auto position = entities.begin();
105         auto end = entities.end();
106         while (position != end && position->ID() < id) {
107                 ++position;
108         }
109         if (position != end && position->ID() == id) {
110                 return nullptr;
111         }
112         auto entity = entities.emplace(position);
113         entity->ID(id);
114         return &*entity;
115 }
116
117
118 namespace {
119
120 struct Candidate {
121         Chunk *chunk;
122         float dist;
123 };
124
125 bool CandidateLess(const Candidate &a, const Candidate &b) {
126         return a.dist < b.dist;
127 }
128
129 std::vector<Candidate> candidates;
130
131 }
132
133 bool World::Intersection(
134         const Ray &ray,
135         const glm::mat4 &M,
136         const Chunk::Pos &reference,
137         WorldCollision &coll
138 ) {
139         candidates.clear();
140
141         for (Chunk &cur_chunk : chunks) {
142                 float cur_dist;
143                 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
144                         candidates.push_back({ &cur_chunk, cur_dist });
145                 }
146         }
147
148         if (candidates.empty()) return false;
149
150         std::sort(candidates.begin(), candidates.end(), CandidateLess);
151
152         coll.chunk = nullptr;
153         coll.block = -1;
154         coll.depth = std::numeric_limits<float>::infinity();
155
156         for (Candidate &cand : candidates) {
157                 if (cand.dist > coll.depth) continue;
158                 WorldCollision cur_coll;
159                 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
160                         if (cur_coll.depth < coll.depth) {
161                                 coll = cur_coll;
162                         }
163                 }
164         }
165
166         return coll.chunk;
167 }
168
169 bool World::Intersection(
170         const Ray &ray,
171         const glm::mat4 &M,
172         const Entity &reference,
173         EntityCollision &coll
174 ) {
175         coll.entity = nullptr;
176         coll.depth = std::numeric_limits<float>::infinity();
177         for (Entity &cur_entity : entities) {
178                 if (&cur_entity == &reference) {
179                         continue;
180                 }
181                 float cur_dist;
182                 glm::vec3 cur_normal;
183                 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
184                         // TODO: fine grained check goes here? maybe?
185                         if (cur_dist < coll.depth) {
186                                 coll.entity = &cur_entity;
187                                 coll.depth = cur_dist;
188                                 coll.normal = cur_normal;
189                         }
190                 }
191         }
192
193         return coll.entity;
194 }
195
196 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
197         AABB box = e.Bounds();
198         Chunk::Pos reference = e.ChunkCoords();
199         glm::mat4 M = e.Transform(reference);
200         bool any = false;
201         for (Chunk &cur_chunk : chunks) {
202                 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
203                         // chunk is not one of the 3x3x3 surrounding the entity
204                         // since there's no entity which can extent over 16 blocks, they can be skipped
205                         continue;
206                 }
207                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
208                         any = true;
209                 }
210         }
211         return any;
212 }
213
214
215 namespace {
216
217 std::vector<WorldCollision> col;
218
219 }
220
221 void World::Update(int dt) {
222         for (Entity &entity : entities) {
223                 entity.Update(dt);
224         }
225         for (Entity &entity : entities) {
226                 col.clear();
227                 if (entity.WorldCollidable() && Intersection(entity, col)) {
228                         // entity collides with the world
229                         Resolve(entity, col);
230                 }
231         }
232         for (Player &player : players) {
233                 player.chunks->Rebase(player.entity->ChunkCoords());
234         }
235         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
236                 if (iter->CanRemove()) {
237                         iter = RemoveEntity(iter);
238                 } else {
239                         ++iter;
240                 }
241         }
242 }
243
244 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
245         // determine displacement for each cardinal axis and move entity accordingly
246         glm::vec3 min_disp(0.0f);
247         glm::vec3 max_disp(0.0f);
248         for (const WorldCollision &c : col) {
249                 if (!c.Blocks()) continue;
250                 glm::vec3 local_disp(c.normal * c.depth);
251                 // swap if neccessary (normal may point away from the entity)
252                 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
253                         local_disp *= -1;
254                 }
255                 min_disp = min(min_disp, local_disp);
256                 max_disp = max(max_disp, local_disp);
257         }
258         // for each axis
259         // if only one direction is set, use that as the final
260         // if both directions are set, use average
261         glm::vec3 final_disp(0.0f);
262         for (int axis = 0; axis < 3; ++axis) {
263                 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
264                         if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
265                                 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
266                         } else {
267                                 final_disp[axis] = min_disp[axis];
268                         }
269                 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
270                         final_disp[axis] = max_disp[axis];
271                 }
272         }
273         e.Move(final_disp);
274 }
275
276 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
277         // check for player
278         for (auto player = players.begin(), end = players.end(); player != end;) {
279                 if (player->entity == &*eh) {
280                         chunks.UnregisterIndex(*player->chunks);
281                         player = players.erase(player);
282                         end = players.end();
283                 } else {
284                         ++player;
285                 }
286         }
287         return entities.erase(eh);
288 }
289
290
291 void World::Render(Viewport &viewport) {
292         DirectionalLighting &entity_prog = viewport.EntityProgram();
293         entity_prog.SetLightDirection(light_direction);
294         entity_prog.SetFogDensity(fog_density);
295
296         for (Entity &entity : entities) {
297                 entity.Render(entity.ChunkTransform(players[0].entity->ChunkCoords()), entity_prog);
298         }
299 }
300
301 }