]> git.localhorst.tv Git - blank.git/blob - src/world/world.cpp
make collisions reference their entity
[blank.git] / src / world / world.cpp
1 #include "Entity.hpp"
2 #include "EntityCollision.hpp"
3 #include "EntityController.hpp"
4 #include "EntityDerivative.hpp"
5 #include "EntityState.hpp"
6 #include "Player.hpp"
7 #include "World.hpp"
8
9 #include "ChunkIndex.hpp"
10 #include "EntityCollision.hpp"
11 #include "WorldCollision.hpp"
12 #include "../app/Assets.hpp"
13 #include "../geometry/const.hpp"
14 #include "../geometry/distance.hpp"
15 #include "../graphics/Format.hpp"
16 #include "../graphics/Viewport.hpp"
17
18 #include <algorithm>
19 #include <cmath>
20 #include <iostream>
21 #include <limits>
22 #include <glm/gtx/euler_angles.hpp>
23 #include <glm/gtx/io.hpp>
24 #include <glm/gtx/projection.hpp>
25 #include <glm/gtx/quaternion.hpp>
26 #include <glm/gtx/rotate_vector.hpp>
27 #include <glm/gtx/transform.hpp>
28
29
30 namespace blank {
31
32 Entity::Entity() noexcept
33 : ctrl(nullptr)
34 , model()
35 , id(-1)
36 , name("anonymous")
37 , bounds()
38 , radius(0.0f)
39 , state()
40 , heading(0.0f, 0.0f, -1.0f)
41 , max_vel(5.0f)
42 , max_force(25.0f)
43 , ref_count(0)
44 , world_collision(false)
45 , dead(false)
46 , owns_controller(false) {
47
48 }
49
50 Entity::~Entity() noexcept {
51         UnsetController();
52 }
53
54 Entity::Entity(const Entity &other) noexcept
55 : ctrl(other.ctrl)
56 , model(other.model)
57 , id(-1)
58 , name(other.name)
59 , bounds(other.bounds)
60 , state(other.state)
61 , model_transform(1.0f)
62 , view_transform(1.0f)
63 , speed(0.0f)
64 , heading(0.0f, 0.0f, -1.0f)
65 , max_vel(other.max_vel)
66 , max_force(other.max_force)
67 , ref_count(0)
68 , world_collision(other.world_collision)
69 , dead(other.dead)
70 , owns_controller(false) {
71
72 }
73
74 void Entity::SetController(EntityController *c) noexcept {
75         UnsetController();
76         ctrl = c;
77         owns_controller = true;
78 }
79
80 void Entity::SetController(EntityController &c) noexcept {
81         UnsetController();
82         ctrl = &c;
83         owns_controller = false;
84 }
85
86 void Entity::UnsetController() noexcept {
87         if (ctrl && owns_controller) {
88                 delete ctrl;
89         }
90         ctrl = nullptr;
91 }
92
93 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
94         glm::vec3 force;
95         if (HasController()) {
96                 force = GetController().ControlForce(*this, s);
97         } else {
98                 force = -s.velocity;
99         }
100         limit(force, max_force);
101         return force;
102 }
103
104 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
105         state.pos.chunk = c;
106         state.pos.block = b;
107 }
108
109 void Entity::Position(const glm::vec3 &pos) noexcept {
110         state.pos.block = pos;
111         state.AdjustPosition();
112 }
113
114 void Entity::TurnHead(float dp, float dy) noexcept {
115         SetHead(state.pitch + dp, state.yaw + dy);
116 }
117
118 void Entity::SetHead(float p, float y) noexcept {
119         state.pitch = p;
120         state.yaw = y;
121 }
122
123 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
124         return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
125 }
126
127 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
128         return Transform(reference) * view_transform;
129 }
130
131 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
132         glm::mat4 transform = ViewTransform(chunk_offset);
133         return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
134 }
135
136 void Entity::Update(World &world, float dt) {
137         if (HasController()) {
138                 GetController().Update(*this, dt);
139         }
140         UpdatePhysics(world, dt);
141         UpdateTransforms();
142         UpdateHeading();
143         UpdateModel(dt);
144 }
145
146 void Entity::UpdatePhysics(World &world, float dt) {
147         EntityState s(state);
148
149         EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
150         EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
151         EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
152         EntityDerivative d(CalculateStep(world, s, dt, c));
153
154         EntityDerivative f;
155         constexpr float sixth = 1.0f / 6.0f;
156         f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
157         f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
158
159         s.pos.block += f.position * dt;
160         s.velocity += f.velocity * dt;
161         limit(s.velocity, max_vel);
162         world.ResolveWorldCollision(*this, s);
163         s.AdjustPosition();
164
165         SetState(s);
166 }
167
168 EntityDerivative Entity::CalculateStep(
169         World &world,
170         const EntityState &cur,
171         float dt,
172         const EntityDerivative &delta
173 ) const {
174         EntityState next(cur);
175         next.pos.block += delta.position * dt;
176         next.velocity += delta.velocity * dt;
177         limit(next.velocity, max_vel);
178         world.ResolveWorldCollision(*this, next);
179         next.AdjustPosition();
180
181         EntityDerivative out;
182         out.position = next.velocity;
183         out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
184         return out;
185 }
186
187
188 void Entity::UpdateTransforms() noexcept {
189         // model transform is the one given by current state
190         model_transform = state.Transform(state.pos.chunk);
191         // view transform is either the model's eyes transform or,
192         // should the entity have no model, the pitch (yaw already is
193         // in model transform)
194         if (model) {
195                 view_transform = model.EyesTransform();
196         } else {
197                 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
198         }
199 }
200
201 void Entity::UpdateHeading() noexcept {
202         speed = length(Velocity());
203         if (speed > std::numeric_limits<float>::epsilon()) {
204                 heading = Velocity() / speed;
205         } else {
206                 speed = 0.0f;
207                 // use -Z (forward axis) of model transform (our "chest")
208                 heading = -glm::vec3(model_transform[2]);
209         }
210 }
211
212 void Entity::UpdateModel(float dt) noexcept {
213         // first, sanitize the pitch and yaw fields of state (our input)
214         // those indicate the head orientation in the entity's local cosystem
215         state.AdjustHeading();
216         // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
217         //OrientBody(dt);
218         OrientHead(dt);
219 }
220
221 void Entity::OrientBody(float dt) noexcept {
222         // maximum body rotation per second (due to velocity orientation) (90°)
223         constexpr float max_body_turn_per_second = PI_0p5;
224         const float max_body_turn = max_body_turn_per_second * dt;
225         // minimum speed to apply body correction
226         constexpr float min_speed = 0.0625f;
227         // use local Y as up
228         const glm::vec3 up(model_transform[1]);
229         if (speed > min_speed) {
230                 // check if our orientation and velocity are aligned
231                 const glm::vec3 forward(-model_transform[2]);
232                 // facing is local -Z rotated about local Y by yaw and transformed into world space
233                 const glm::vec3 facing(normalize(glm::vec3(glm::vec4(rotateY(glm::vec3(0.0f, 0.0f, -1.0f), state.yaw), 0.0f) * transpose(model_transform))));
234                 // only adjust if velocity isn't almost parallel to up
235                 float vel_dot_up = dot(Velocity(), up);
236                 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
237                         // get direction of velocity projected onto model plane
238                         glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
239                         // if velocity points away from our facing (with a little bias), flip it around
240                         // (the entity is "walking backwards")
241                         if (dot(facing, direction) < -0.1f) {
242                                 direction = -direction;
243                         }
244                         // calculate the difference between forward and direction
245                         const float absolute_difference = std::acos(dot(forward, direction));
246                         // if direction is clockwise with respect to up vector, invert the angle
247                         const float relative_difference = dot(cross(forward, direction), up) < 0.0f
248                                 ? -absolute_difference
249                                 : absolute_difference;
250                         // only correct by half the difference max
251                         const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
252                         if (ID() == 1) {
253                                 std::cout << "orientation before: " << state.orient << std::endl;
254                                 std::cout << "up:        " << up << std::endl;
255                                 std::cout << "forward:   " << forward << std::endl;
256                                 std::cout << "facing:    " << facing << std::endl;
257                                 std::cout << "direction: " << direction << std::endl;
258                                 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
259                                 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
260                                 std::cout << std::endl;
261                         }
262                         // now rotate body by correction and head by -correction
263                         state.orient = rotate(state.orient, correction, up);
264                         state.yaw -= correction;
265                 }
266         }
267 }
268
269 void Entity::OrientHead(float dt) noexcept {
270         // maximum yaw of head (60°)
271         constexpr float max_head_yaw = PI / 3.0f;
272         // use local Y as up
273         const glm::vec3 up(model_transform[1]);
274         // if yaw is bigger than max, rotate the body to accomodate
275         if (std::abs(state.yaw) > max_head_yaw) {
276                 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
277                 // rotate the entity by deviation about local Y
278                 state.orient = rotate(state.orient, deviation, up);
279                 // and remove from head yaw
280                 state.yaw -= deviation;
281                 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
282                 state.AdjustHeading();
283         }
284         // update model if any
285         if (model) {
286                 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
287         }
288 }
289
290
291 EntityCollision::EntityCollision(Entity *e, float d, const glm::vec3 &n)
292 : depth(d)
293 , normal(n)
294 , entity(e) {
295         if (entity) {
296                 entity->Ref();
297         }
298 }
299
300 EntityCollision::~EntityCollision() {
301         if (entity) {
302                 entity->UnRef();
303         }
304 }
305
306 EntityCollision::EntityCollision(const EntityCollision &other)
307 : depth(other.depth)
308 , normal(other.normal)
309 , entity(other.entity) {
310         if (entity) {
311                 entity->Ref();
312         }
313 }
314
315 EntityCollision &EntityCollision::operator =(const EntityCollision &other) {
316         if (entity) {
317                 entity->UnRef();
318         }
319         depth = other.depth;
320         normal = other.normal;
321         entity = other.entity;
322         if (entity) {
323                 entity->Ref();
324         }
325         return *this;
326 }
327
328
329 EntityController::~EntityController() {
330
331 }
332
333 bool EntityController::MaxOutForce(
334         glm::vec3 &out,
335         const glm::vec3 &add,
336         float max
337 ) noexcept {
338         if (iszero(add) || any(isnan(add))) {
339                 return false;
340         }
341         float current = iszero(out) ? 0.0f : length(out);
342         float remain = max - current;
343         if (remain <= 0.0f) {
344                 return true;
345         }
346         float additional = length(add);
347         if (additional > remain) {
348                 out += normalize(add) * remain;
349                 return true;
350         } else {
351                 out += add;
352                 return false;
353         }
354 }
355
356
357 EntityState::EntityState()
358 : pos()
359 , velocity(0.0f)
360 , orient(1.0f, 0.0f, 0.0f, 0.0f)
361 , pitch(0.0f)
362 , yaw(0.0f) {
363
364 }
365
366 void EntityState::AdjustPosition() noexcept {
367         pos.Correct();
368 }
369
370 void EntityState::AdjustHeading() noexcept {
371         pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
372         while (yaw > PI) {
373                 yaw -= PI_2p0;
374         }
375         while (yaw < -PI) {
376                 yaw += PI_2p0;
377         }
378 }
379
380 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
381         const glm::vec3 translation = RelativePosition(reference);
382         glm::mat4 transform(toMat4(orient));
383         transform[3] = glm::vec4(translation, 1.0f);
384         return transform;
385 }
386
387
388 Player::Player(Entity &e, ChunkIndex &c)
389 : entity(e)
390 , chunks(c)
391 , inv_slot(0) {
392
393 }
394
395 Player::~Player() {
396
397 }
398
399 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
400         if (!spawn_block || spawn_block.GetType().collide_block) {
401                 return false;
402         }
403
404         BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
405         if (!head_block || head_block.GetType().collide_block) {
406                 return false;
407         }
408
409         return true;
410 }
411
412 void Player::Update(int dt) {
413         chunks.Rebase(entity.ChunkCoords());
414 }
415
416
417 World::World(const BlockTypeRegistry &types, const Config &config)
418 : config(config)
419 , block_type(types)
420 , chunks(types)
421 , players()
422 , entities()
423 , light_direction(config.light_direction)
424 , fog_density(config.fog_density) {
425
426 }
427
428 World::~World() {
429         for (Entity &e : entities) {
430                 e.Kill();
431         }
432         std::size_t removed = 0;
433         do {
434                 removed = 0;
435                 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
436                         if (e->CanRemove()) {
437                                 e = RemoveEntity(e);
438                                 end = entities.end();
439                                 ++removed;
440                         }
441                 }
442         } while (removed > 0 && !entities.empty());
443 }
444
445
446 Player *World::AddPlayer(const std::string &name) {
447         for (Player &p : players) {
448                 if (p.Name() == name) {
449                         return nullptr;
450                 }
451         }
452         Entity &entity = AddEntity();
453         entity.Name(name);
454         entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
455         entity.WorldCollidable(true);
456         ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
457         players.emplace_back(entity, index);
458         return &players.back();
459 }
460
461 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
462         for (Player &p : players) {
463                 if (p.Name() == name) {
464                         return nullptr;
465                 }
466         }
467         Entity *entity = AddEntity(id);
468         if (!entity) {
469                 return nullptr;
470         }
471         entity->Name(name);
472         entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
473         entity->WorldCollidable(true);
474         ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
475         players.emplace_back(*entity, index);
476         return &players.back();
477 }
478
479 Entity &World::AddEntity() {
480         if (entities.empty()) {
481                 entities.emplace_back();
482                 entities.back().ID(1);
483                 return entities.back();
484         }
485         if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
486                 std::uint32_t id = entities.back().ID() + 1;
487                 entities.emplace_back();
488                 entities.back().ID(id);
489                 return entities.back();
490         }
491         std::uint32_t id = 1;
492         auto position = entities.begin();
493         auto end = entities.end();
494         while (position != end && position->ID() == id) {
495                 ++id;
496                 ++position;
497         }
498         auto entity = entities.emplace(position);
499         entity->ID(id);
500         return *entity;
501 }
502
503 Entity *World::AddEntity(std::uint32_t id) {
504         if (entities.empty() || entities.back().ID() < id) {
505                 entities.emplace_back();
506                 entities.back().ID(id);
507                 return &entities.back();
508         }
509
510         auto position = entities.begin();
511         auto end = entities.end();
512         while (position != end && position->ID() < id) {
513                 ++position;
514         }
515         if (position != end && position->ID() == id) {
516                 return nullptr;
517         }
518         auto entity = entities.emplace(position);
519         entity->ID(id);
520         return &*entity;
521 }
522
523 Entity &World::ForceAddEntity(std::uint32_t id) {
524         if (entities.empty() || entities.back().ID() < id) {
525                 entities.emplace_back();
526                 entities.back().ID(id);
527                 return entities.back();
528         }
529
530         auto position = entities.begin();
531         auto end = entities.end();
532         while (position != end && position->ID() < id) {
533                 ++position;
534         }
535         if (position != end && position->ID() == id) {
536                 return *position;
537         }
538         auto entity = entities.emplace(position);
539         entity->ID(id);
540         return *entity;
541 }
542
543
544 namespace {
545
546 struct Candidate {
547         Chunk *chunk;
548         float dist;
549 };
550
551 bool CandidateLess(const Candidate &a, const Candidate &b) {
552         return a.dist < b.dist;
553 }
554
555 std::vector<Candidate> candidates;
556
557 }
558
559 bool World::Intersection(
560         const Ray &ray,
561         const ExactLocation::Coarse &reference,
562         WorldCollision &coll
563 ) {
564         candidates.clear();
565
566         for (Chunk &cur_chunk : chunks) {
567                 float cur_dist;
568                 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
569                         candidates.push_back({ &cur_chunk, cur_dist });
570                 }
571         }
572
573         if (candidates.empty()) return false;
574
575         std::sort(candidates.begin(), candidates.end(), CandidateLess);
576
577         coll.chunk = nullptr;
578         coll.block = -1;
579         coll.depth = std::numeric_limits<float>::infinity();
580
581         for (Candidate &cand : candidates) {
582                 if (cand.dist > coll.depth) continue;
583                 WorldCollision cur_coll;
584                 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
585                         if (cur_coll.depth < coll.depth) {
586                                 coll = cur_coll;
587                         }
588                 }
589         }
590
591         return coll.chunk;
592 }
593
594 bool World::Intersection(
595         const Ray &ray,
596         const Entity &reference,
597         EntityCollision &coll
598 ) {
599         coll = EntityCollision(nullptr, std::numeric_limits<float>::infinity(), glm::vec3(0.0f));
600         for (Entity &cur_entity : entities) {
601                 if (&cur_entity == &reference) {
602                         continue;
603                 }
604                 float cur_dist;
605                 glm::vec3 cur_normal;
606                 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
607                         // TODO: fine grained check goes here? maybe?
608                         if (cur_dist < coll.depth) {
609                                 coll = EntityCollision(&cur_entity, cur_dist, cur_normal);
610                         }
611                 }
612         }
613
614         return coll;
615 }
616
617 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
618         glm::ivec3 reference = s.pos.chunk;
619         glm::mat4 M = s.Transform(reference);
620
621         ExactLocation::Coarse begin(reference - 1);
622         ExactLocation::Coarse end(reference + 2);
623
624         bool any = false;
625         for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
626                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
627                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
628                                 Chunk *chunk = chunks.Get(pos);
629                                 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
630                                         any = true;
631                                 }
632                         }
633                 }
634         }
635         return any;
636 }
637
638 bool World::Intersection(
639         const AABB &box,
640         const glm::mat4 &M,
641         const glm::ivec3 &reference,
642         std::vector<WorldCollision> &col
643 ) {
644         bool any = false;
645         for (Chunk &cur_chunk : chunks) {
646                 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
647                         // chunk is not one of the 3x3x3 surrounding the entity
648                         // since there's no entity which can extent over 16 blocks, they can be skipped
649                         // TODO: change to indexed (like with entity)
650                         continue;
651                 }
652                 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
653                         any = true;
654                 }
655         }
656         return any;
657 }
658
659 void World::Update(int dt) {
660         float fdt(dt * 0.001f);
661         for (Entity &entity : entities) {
662                 entity.Update(*this, fdt);
663         }
664         for (Player &player : players) {
665                 player.Update(dt);
666         }
667         for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
668                 if (iter->CanRemove()) {
669                         iter = RemoveEntity(iter);
670                 } else {
671                         ++iter;
672                 }
673         }
674 }
675
676 namespace {
677
678 std::vector<WorldCollision> col;
679
680 }
681
682 void World::ResolveWorldCollision(
683         const Entity &entity,
684         EntityState &state
685 ) {
686         col.clear();
687         if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
688                 // no collision, no fix
689                 return;
690         }
691         glm::vec3 correction = CombinedInterpenetration(state, col);
692         // correction may be zero in which case normalize() returns NaNs
693         if (iszero(correction)) {
694                 return;
695         }
696         // if entity is already going in the direction of correction,
697         // let the problem resolve itself
698         if (dot(state.velocity, correction) >= 0.0f) {
699                 return;
700         }
701         // apply correction, maybe could use some damping, gotta test
702         state.pos.block += correction;
703         // kill velocity?
704         glm::vec3 normal_velocity(proj(state.velocity, correction));
705         state.velocity -= normal_velocity;
706 }
707
708 glm::vec3 World::CombinedInterpenetration(
709         const EntityState &state,
710         const std::vector<WorldCollision> &col
711 ) noexcept {
712         // determine displacement for each cardinal axis and move entity accordingly
713         glm::vec3 min_pen(0.0f);
714         glm::vec3 max_pen(0.0f);
715         for (const WorldCollision &c : col) {
716                 if (!c.Blocks()) continue;
717                 glm::vec3 normal(c.normal);
718                 // swap if neccessary (normal may point away from the entity)
719                 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
720                         normal = -normal;
721                 }
722                 // check if block surface is "inside"
723                 Block::Face coll_face = Block::NormalFace(normal);
724                 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
725                 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
726                         // yep, so ignore this contact
727                         continue;
728                 }
729                 glm::vec3 local_pen(normal * c.depth);
730                 min_pen = min(min_pen, local_pen);
731                 max_pen = max(max_pen, local_pen);
732         }
733         glm::vec3 pen(0.0f);
734         // only apply correction for axes where penetration is only in one direction
735         for (std::size_t i = 0; i < 3; ++i) {
736                 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
737                         if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
738                                 pen[i] = min_pen[i];
739                         }
740                 } else {
741                         pen[i] = max_pen[i];
742                 }
743         }
744         return pen;
745 }
746
747 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
748         glm::vec3 force(0.0f);
749         ExactLocation::Coarse begin(loc.chunk - 1);
750         ExactLocation::Coarse end(loc.chunk + 2);
751
752         for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
753                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
754                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
755                                 const Chunk *chunk = chunks.Get(pos);
756                                 if (chunk) {
757                                         force += chunk->GravityAt(loc);
758                                 }
759                         }
760                 }
761         }
762
763         return force;
764 }
765
766 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
767         // check for player
768         for (auto player = players.begin(), end = players.end(); player != end;) {
769                 if (&player->GetEntity() == &*eh) {
770                         chunks.UnregisterIndex(player->GetChunks());
771                         player = players.erase(player);
772                         end = players.end();
773                 } else {
774                         ++player;
775                 }
776         }
777         return entities.erase(eh);
778 }
779
780
781 void World::Render(Viewport &viewport) {
782         DirectionalLighting &entity_prog = viewport.EntityProgram();
783         entity_prog.SetFogDensity(fog_density);
784
785         glm::vec3 light_dir;
786         glm::vec3 light_col;
787         glm::vec3 ambient_col;
788         for (Entity &entity : entities) {
789                 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
790                 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
791                         GetLight(entity, light_dir, light_col, ambient_col);
792                         entity_prog.SetLightDirection(light_dir);
793                         entity_prog.SetLightColor(light_col);
794                         entity_prog.SetAmbientColor(ambient_col);
795                         entity.Render(M, entity_prog);
796                 }
797         }
798 }
799
800 // this should interpolate based on the fractional part of entity's block position
801 void World::GetLight(
802         const Entity &e,
803         glm::vec3 &dir,
804         glm::vec3 &col,
805         glm::vec3 &amb
806 ) {
807         BlockLookup center(chunks.Get(e.ChunkCoords()), e.Position());
808         if (!center) {
809                 // chunk unavailable, so make it really dark and from
810                 // some arbitrary direction
811                 dir = glm::vec3(1.0f, 2.0f, 3.0f);
812                 col = glm::vec3(0.025f); // ~0.8^15
813                 return;
814         }
815         glm::ivec3 base(center.GetBlockPos());
816         int base_light = center.GetLight();
817         int max_light = 0;
818         int min_light = 15;
819         glm::ivec3 acc(0, 0, 0);
820         for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
821                 for (offset.y = -1; offset.y < 2; ++offset.y) {
822                         for (offset.x = -1; offset.x < 2; ++offset.x) {
823                                 BlockLookup block(&center.GetChunk(), center.GetBlockPos() + offset);
824                                 if (!block) {
825                                         // missing, just ignore it
826                                         continue;
827                                 }
828                                 // otherwise, accumulate the difference times direction
829                                 acc += offset * (base_light - block.GetLight());
830                                 max_light = std::max(max_light, block.GetLight());
831                                 min_light = std::min(min_light, block.GetLight());
832                         }
833                 }
834         }
835         dir = acc;
836         col = glm::vec3(std::pow(0.8f, 15 - max_light));
837         amb = glm::vec3(std::pow(0.8f, 15 - min_light));
838 }
839
840 namespace {
841
842 PrimitiveMesh::Buffer debug_buf;
843
844 }
845
846 void World::RenderDebug(Viewport &viewport) {
847         PrimitiveMesh debug_mesh;
848         PlainColor &prog = viewport.WorldColorProgram();
849         for (const Entity &entity : entities) {
850                 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
851                 debug_mesh.Update(debug_buf);
852                 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
853                 debug_mesh.DrawLines();
854         }
855 }
856
857 }