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