]> git.localhorst.tv Git - blank.git/blob - src/world/World.cpp
move client update throttling to state
[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 Entity &World::ForceAddEntity(std::uint32_t id) {
118         if (entities.empty() || entities.back().ID() < id) {
119                 entities.emplace_back();
120                 entities.back().ID(id);
121                 return entities.back();
122         }
123
124         auto position = entities.begin();
125         auto end = entities.end();
126         while (position != end && position->ID() < id) {
127                 ++position;
128         }
129         if (position != end && position->ID() == id) {
130                 return *position;
131         }
132         auto entity = entities.emplace(position);
133         entity->ID(id);
134         return *entity;
135 }
136
137
138 namespace {
139
140 struct Candidate {
141         Chunk *chunk;
142         float dist;
143 };
144
145 bool CandidateLess(const Candidate &a, const Candidate &b) {
146         return a.dist < b.dist;
147 }
148
149 std::vector<Candidate> candidates;
150
151 }
152
153 bool World::Intersection(
154         const Ray &ray,
155         const glm::mat4 &M,
156         const Chunk::Pos &reference,
157         WorldCollision &coll
158 ) {
159         candidates.clear();
160
161         for (Chunk &cur_chunk : chunks) {
162                 float cur_dist;
163                 if (cur_chunk.Intersection(ray, M * cur_chunk.Transform(reference), cur_dist)) {
164                         candidates.push_back({ &cur_chunk, cur_dist });
165                 }
166         }
167
168         if (candidates.empty()) return false;
169
170         std::sort(candidates.begin(), candidates.end(), CandidateLess);
171
172         coll.chunk = nullptr;
173         coll.block = -1;
174         coll.depth = std::numeric_limits<float>::infinity();
175
176         for (Candidate &cand : candidates) {
177                 if (cand.dist > coll.depth) continue;
178                 WorldCollision cur_coll;
179                 if (cand.chunk->Intersection(ray, M * cand.chunk->Transform(reference), cur_coll)) {
180                         if (cur_coll.depth < coll.depth) {
181                                 coll = cur_coll;
182                         }
183                 }
184         }
185
186         return coll.chunk;
187 }
188
189 bool World::Intersection(
190         const Ray &ray,
191         const glm::mat4 &M,
192         const Entity &reference,
193         EntityCollision &coll
194 ) {
195         coll.entity = nullptr;
196         coll.depth = std::numeric_limits<float>::infinity();
197         for (Entity &cur_entity : entities) {
198                 if (&cur_entity == &reference) {
199                         continue;
200                 }
201                 float cur_dist;
202                 glm::vec3 cur_normal;
203                 if (blank::Intersection(ray, cur_entity.Bounds(), M * cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
204                         // TODO: fine grained check goes here? maybe?
205                         if (cur_dist < coll.depth) {
206                                 coll.entity = &cur_entity;
207                                 coll.depth = cur_dist;
208                                 coll.normal = cur_normal;
209                         }
210                 }
211         }
212
213         return coll.entity;
214 }
215
216 bool World::Intersection(const Entity &e, std::vector<WorldCollision> &col) {
217         AABB box = e.Bounds();
218         Chunk::Pos reference = e.ChunkCoords();
219         glm::mat4 M = e.Transform(reference);
220         bool any = false;
221         for (Chunk &cur_chunk : chunks) {
222                 if (manhattan_radius(cur_chunk.Position() - e.ChunkCoords()) > 1) {
223                         // chunk is not one of the 3x3x3 surrounding the entity
224                         // since there's no entity which can extent over 16 blocks, they can be skipped
225                         continue;
226                 }
227                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
228                         any = true;
229                 }
230         }
231         return any;
232 }
233
234
235 namespace {
236
237 std::vector<WorldCollision> col;
238
239 }
240
241 void World::Update(int dt) {
242         for (Entity &entity : entities) {
243                 entity.Update(dt);
244         }
245         for (Entity &entity : entities) {
246                 col.clear();
247                 if (entity.WorldCollidable() && Intersection(entity, col)) {
248                         // entity collides with the world
249                         Resolve(entity, col);
250                 }
251         }
252         for (Player &player : players) {
253                 player.chunks->Rebase(player.entity->ChunkCoords());
254         }
255         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
256                 if (iter->CanRemove()) {
257                         iter = RemoveEntity(iter);
258                 } else {
259                         ++iter;
260                 }
261         }
262 }
263
264 void World::Resolve(Entity &e, std::vector<WorldCollision> &col) {
265         // determine displacement for each cardinal axis and move entity accordingly
266         glm::vec3 min_disp(0.0f);
267         glm::vec3 max_disp(0.0f);
268         for (const WorldCollision &c : col) {
269                 if (!c.Blocks()) continue;
270                 glm::vec3 local_disp(c.normal * c.depth);
271                 // swap if neccessary (normal may point away from the entity)
272                 if (dot(c.normal, e.Position() - c.BlockCoords()) < 0) {
273                         local_disp *= -1;
274                 }
275                 min_disp = min(min_disp, local_disp);
276                 max_disp = max(max_disp, local_disp);
277         }
278         // for each axis
279         // if only one direction is set, use that as the final
280         // if both directions are set, use average
281         glm::vec3 final_disp(0.0f);
282         for (int axis = 0; axis < 3; ++axis) {
283                 if (std::abs(min_disp[axis]) > std::numeric_limits<float>::epsilon()) {
284                         if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
285                                 final_disp[axis] = (min_disp[axis] + max_disp[axis]) * 0.5f;
286                         } else {
287                                 final_disp[axis] = min_disp[axis];
288                         }
289                 } else if (std::abs(max_disp[axis]) > std::numeric_limits<float>::epsilon()) {
290                         final_disp[axis] = max_disp[axis];
291                 }
292         }
293         e.Move(final_disp);
294 }
295
296 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
297         // check for player
298         for (auto player = players.begin(), end = players.end(); player != end;) {
299                 if (player->entity == &*eh) {
300                         chunks.UnregisterIndex(*player->chunks);
301                         player = players.erase(player);
302                         end = players.end();
303                 } else {
304                         ++player;
305                 }
306         }
307         return entities.erase(eh);
308 }
309
310
311 void World::Render(Viewport &viewport) {
312         DirectionalLighting &entity_prog = viewport.EntityProgram();
313         entity_prog.SetLightDirection(light_direction);
314         entity_prog.SetFogDensity(fog_density);
315
316         for (Entity &entity : entities) {
317                 entity.Render(entity.ChunkTransform(players[0].entity->ChunkCoords()), entity_prog);
318         }
319 }
320
321 }