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