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