2 #include "EntityCollision.hpp"
3 #include "EntityController.hpp"
4 #include "EntityDerivative.hpp"
5 #include "EntityState.hpp"
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 "../geometry/rotation.hpp"
16 #include "../graphics/Format.hpp"
17 #include "../graphics/Viewport.hpp"
23 #include <glm/gtx/euler_angles.hpp>
24 #include <glm/gtx/io.hpp>
25 #include <glm/gtx/projection.hpp>
26 #include <glm/gtx/quaternion.hpp>
27 #include <glm/gtx/rotate_vector.hpp>
28 #include <glm/gtx/transform.hpp>
35 /// used as a buffer for merging collisions
36 std::vector<WorldCollision> col;
40 Entity::Entity() noexcept
49 , heading(0.0f, 0.0f, -1.0f)
53 , world_collision(false)
55 , owns_controller(false) {
59 Entity::~Entity() noexcept {
63 Entity::Entity(const Entity &other) noexcept
69 , bounds(other.bounds)
71 , model_transform(1.0f)
72 , view_transform(1.0f)
74 , heading(0.0f, 0.0f, -1.0f)
75 , max_vel(other.max_vel)
76 , max_force(other.max_force)
78 , world_collision(other.world_collision)
80 , owns_controller(false) {
84 void Entity::SetController(EntityController *c) noexcept {
87 owns_controller = true;
90 void Entity::SetController(EntityController &c) noexcept {
93 owns_controller = false;
96 void Entity::UnsetController() noexcept {
97 if (ctrl && owns_controller) {
103 glm::vec3 Entity::ControlForce(const EntityState &s) const noexcept {
104 return steering.Force(s);
107 void Entity::Position(const glm::ivec3 &c, const glm::vec3 &b) noexcept {
112 void Entity::Position(const glm::vec3 &pos) noexcept {
113 state.pos.block = pos;
114 state.AdjustPosition();
117 void Entity::TurnHead(float dp, float dy) noexcept {
118 SetHead(state.pitch + dp, state.yaw + dy);
121 void Entity::SetHead(float p, float y) noexcept {
126 glm::mat4 Entity::Transform(const glm::ivec3 &reference) const noexcept {
127 return glm::translate(glm::vec3((state.pos.chunk - reference) * ExactLocation::Extent())) * model_transform;
130 glm::mat4 Entity::ViewTransform(const glm::ivec3 &reference) const noexcept {
131 return Transform(reference) * view_transform;
134 Ray Entity::Aim(const ExactLocation::Coarse &chunk_offset) const noexcept {
135 glm::mat4 transform = ViewTransform(chunk_offset);
136 return Ray{ glm::vec3(transform[3]), -glm::vec3(transform[2]) };
139 void Entity::Update(World &world, float dt) {
140 if (HasController()) {
141 GetController().Update(*this, dt);
143 steering.Update(world, dt);
144 UpdatePhysics(world, dt);
150 void Entity::UpdatePhysics(World &world, float dt) {
151 EntityState s(state);
153 EntityDerivative a(CalculateStep(world, s, 0.0f, EntityDerivative()));
154 EntityDerivative b(CalculateStep(world, s, dt * 0.5f, a));
155 EntityDerivative c(CalculateStep(world, s, dt * 0.5f, b));
156 EntityDerivative d(CalculateStep(world, s, dt, c));
159 constexpr float sixth = 1.0f / 6.0f;
160 f.position = sixth * (a.position + 2.0f * (b.position + c.position) + d.position);
161 f.velocity = sixth * (a.velocity + 2.0f * (b.velocity + c.velocity) + d.velocity);
163 s.pos.block += f.position * dt;
164 s.velocity += f.velocity * dt;
165 limit(s.velocity, max_vel);
166 world.ResolveWorldCollision(*this, s);
172 EntityDerivative Entity::CalculateStep(
174 const EntityState &cur,
176 const EntityDerivative &delta
178 EntityState next(cur);
179 next.pos.block += delta.position * dt;
180 next.velocity += delta.velocity * dt;
181 limit(next.velocity, max_vel);
182 world.ResolveWorldCollision(*this, next);
183 next.AdjustPosition();
185 EntityDerivative out;
186 out.position = next.velocity;
187 out.velocity = ControlForce(next) + world.GravityAt(next.pos); // by mass = 1kg
192 void Entity::UpdateTransforms() noexcept {
193 // model transform is the one given by current state
194 model_transform = state.Transform(state.pos.chunk);
195 // view transform is either the model's eyes transform or,
196 // should the entity have no model, the pitch (yaw already is
197 // in model transform)
199 view_transform = model.EyesTransform();
201 view_transform = toMat4(glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f)));
205 void Entity::UpdateHeading() noexcept {
206 speed = length(Velocity());
207 if (speed > std::numeric_limits<float>::epsilon()) {
208 heading = Velocity() / speed;
211 // use -Z (forward axis) of model transform (our "chest")
212 heading = -glm::vec3(model_transform[2]);
216 void Entity::UpdateModel(float dt) noexcept {
217 // first, sanitize the pitch and yaw fields of state (our input)
218 // those indicate the head orientation in the entity's local cosystem
219 state.AdjustHeading();
220 // TODO: this flickers horrible and also shouldn't be based on velocity, but on control force
225 void Entity::OrientBody(float dt) noexcept {
226 // maximum body rotation per second (due to velocity orientation) (90°)
227 constexpr float max_body_turn_per_second = PI_0p5;
228 const float max_body_turn = max_body_turn_per_second * dt;
229 // minimum speed to apply body correction
230 constexpr float min_speed = 0.0625f;
232 const glm::vec3 up(model_transform[1]);
233 if (speed > min_speed) {
234 // check if our orientation and velocity are aligned
235 const glm::vec3 forward(-model_transform[2]);
236 // facing is local -Z rotated about local Y by yaw and transformed into world space
237 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))));
238 // only adjust if velocity isn't almost parallel to up
239 float vel_dot_up = dot(Velocity(), up);
240 if (std::abs(1.0f - std::abs(vel_dot_up)) > std::numeric_limits<float>::epsilon()) {
241 // get direction of velocity projected onto model plane
242 glm::vec3 direction(normalize(Velocity() - (Velocity() * vel_dot_up)));
243 // if velocity points away from our facing (with a little bias), flip it around
244 // (the entity is "walking backwards")
245 if (dot(facing, direction) < -0.1f) {
246 direction = -direction;
248 // calculate the difference between forward and direction
249 const float absolute_difference = std::acos(dot(forward, direction));
250 // if direction is clockwise with respect to up vector, invert the angle
251 const float relative_difference = dot(cross(forward, direction), up) < 0.0f
252 ? -absolute_difference
253 : absolute_difference;
254 // only correct by half the difference max
255 const float correction = glm::clamp(relative_difference * 0.5f, -max_body_turn, max_body_turn);
257 std::cout << "orientation before: " << state.orient << std::endl;
258 std::cout << "up: " << up << std::endl;
259 std::cout << "forward: " << forward << std::endl;
260 std::cout << "facing: " << facing << std::endl;
261 std::cout << "direction: " << direction << std::endl;
262 std::cout << "difference: " << glm::degrees(relative_difference) << "°" << std::endl;
263 std::cout << "correction: " << glm::degrees(correction) << "°" << std::endl;
264 std::cout << std::endl;
266 // now rotate body by correction and head by -correction
267 state.orient = rotate(state.orient, correction, up);
268 state.yaw -= correction;
273 void Entity::OrientHead(float dt) noexcept {
274 // maximum yaw of head (60°)
275 constexpr float max_head_yaw = PI / 3.0f;
277 const glm::vec3 up(model_transform[1]);
278 // if yaw is bigger than max, rotate the body to accomodate
279 if (std::abs(state.yaw) > max_head_yaw) {
280 float deviation = state.yaw < 0.0f ? state.yaw + max_head_yaw : state.yaw - max_head_yaw;
281 // rotate the entity by deviation about local Y
282 state.orient = rotate(state.orient, deviation, up);
283 // and remove from head yaw
284 state.yaw -= deviation;
285 // shouldn't be necessary if max_head_yaw is < PI, but just to be sure :p
286 state.AdjustHeading();
288 // update model if any
290 model.EyesState().orientation = glm::quat(glm::vec3(state.pitch, state.yaw, 0.0f));
295 EntityCollision::EntityCollision(Entity *e, float d, const glm::vec3 &n)
304 EntityCollision::~EntityCollision() {
310 EntityCollision::EntityCollision(const EntityCollision &other)
312 , normal(other.normal)
313 , entity(other.entity) {
319 EntityCollision &EntityCollision::operator =(const EntityCollision &other) {
324 normal = other.normal;
325 entity = other.entity;
333 EntityController::~EntityController() {
338 EntityState::EntityState()
341 , orient(1.0f, 0.0f, 0.0f, 0.0f)
347 void EntityState::AdjustPosition() noexcept {
351 void EntityState::AdjustHeading() noexcept {
352 pitch = glm::clamp(pitch, -PI_0p5, PI_0p5);
361 glm::mat4 EntityState::Transform(const glm::ivec3 &reference) const noexcept {
362 const glm::vec3 translation = RelativePosition(reference);
363 glm::mat4 transform(toMat4(orient));
364 transform[3] = glm::vec4(translation, 1.0f);
369 Player::Player(Entity &e, ChunkIndex &c)
380 bool Player::SuitableSpawn(BlockLookup &spawn_block) const noexcept {
381 if (!spawn_block || spawn_block.GetType().collide_block) {
385 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
386 if (!head_block || head_block.GetType().collide_block) {
393 void Player::Update(int dt) {
394 chunks.Rebase(entity.ChunkCoords());
398 Steering::Steering(const Entity &e)
400 , target_entity(nullptr)
401 , target_velocity(0.0f)
403 , speed(entity.MaxVelocity())
404 , wander_radius(1.0f)
407 , wander_pos(1.0f, 0.0f, 0.0f)
413 Steering::~Steering() {
417 Steering &Steering::SetTargetEntity(Entity &e) noexcept {
424 Steering &Steering::ClearTargetEntity() noexcept {
426 target_entity->UnRef();
427 target_entity = nullptr;
432 void Steering::Update(World &world, float dt) {
433 if (AnyEnabled(WANDER)) {
434 UpdateWander(world, dt);
436 if (AnyEnabled(OBSTACLE_AVOIDANCE)) {
437 UpdateObstacle(world);
441 void Steering::UpdateWander(World &world, float dt) {
442 glm::vec3 displacement(
443 world.Random().SNorm() * wander_disp,
444 world.Random().SNorm() * wander_disp,
445 world.Random().SNorm() * wander_disp
447 if (!iszero(displacement)) {
448 wander_pos = normalize(wander_pos + displacement * dt) * wander_radius;
452 void Steering::UpdateObstacle(World &world) {
453 if (!entity.Moving()) {
454 obstacle_dir = glm::vec3(0.0f);
457 AABB box(entity.Bounds());
458 box.min.z = -entity.Speed();
460 glm::mat4 transform(find_rotation(glm::vec3(0.0f, 0.0f, -1.0f), entity.Heading()));
461 transform[3] = glm::vec4(entity.Position(), 1.0f);
462 // check if that box intersects with any blocks
464 if (!world.Intersection(box, transform, entity.ChunkCoords(), col)) {
465 obstacle_dir = glm::vec3(0.0f);
468 // if so, pick the nearest collision
469 const WorldCollision *nearest = nullptr;
470 glm::vec3 difference(0.0f);
471 float distance = std::numeric_limits<float>::infinity();
472 for (const WorldCollision &c : col) {
473 // diff points from block to state
474 glm::vec3 diff = entity.GetState().RelativePosition(c.ChunkPos()) - c.BlockCoords();
475 float dist = length2(diff);
476 if (dist < distance) {
483 // intersection test lied to us
484 obstacle_dir = glm::vec3(0.0f);
487 // and try to avoid it
488 float to_go = dot(difference, entity.Heading());
489 glm::vec3 point(entity.Position() + entity.Heading() * to_go);
490 obstacle_dir = normalize(point - nearest->BlockCoords()) * (entity.Speed() / std::sqrt(distance));
493 glm::vec3 Steering::Force(const EntityState &state) const noexcept {
494 glm::vec3 force(0.0f);
498 const float max = entity.MaxControlForce();
499 if (AnyEnabled(HALT)) {
500 if (SumForce(force, Halt(state), max)) {
504 if (AnyEnabled(TARGET_VELOCITY)) {
505 if (SumForce(force, TargetVelocity(state, target_velocity), max)) {
509 if (AnyEnabled(OBSTACLE_AVOIDANCE)) {
510 if (SumForce(force, ObstacleAvoidance(state), max)) {
514 if (AnyEnabled(EVADE_TARGET)) {
515 if (HasTargetEntity()) {
516 if (SumForce(force, Evade(state, GetTargetEntity()), max)) {
520 std::cout << "Steering: evade enabled, but target entity not set" << std::endl;
523 if (AnyEnabled(PURSUE_TARGET)) {
524 if (HasTargetEntity()) {
525 if (SumForce(force, Pursuit(state, GetTargetEntity()), max)) {
529 std::cout << "Steering: pursuit enabled, but target entity not set" << std::endl;
532 if (AnyEnabled(WANDER)) {
533 if (SumForce(force, Wander(state), max)) {
540 bool Steering::SumForce(glm::vec3 &out, const glm::vec3 &in, float max) noexcept {
541 if (iszero(in) || any(isnan(in))) {
544 float current = iszero(out) ? 0.0f : length(out);
545 float remain = max - current;
546 if (remain <= 0.0f) {
549 float additional = length(in);
550 if (additional > remain) {
551 out += normalize(in) * remain;
559 glm::vec3 Steering::Halt(const EntityState &state) const noexcept {
560 return state.velocity * -accel;
563 glm::vec3 Steering::TargetVelocity(const EntityState &state, const glm::vec3 &vel) const noexcept {
564 return (vel - state.velocity) * accel;
567 glm::vec3 Steering::Seek(const EntityState &state, const ExactLocation &loc) const noexcept {
568 const glm::vec3 diff(loc.Difference(state.pos).Absolute());
570 return glm::vec3(0.0f);
572 return TargetVelocity(state, normalize(diff) * speed);
576 glm::vec3 Steering::Flee(const EntityState &state, const ExactLocation &loc) const noexcept {
577 const glm::vec3 diff(state.pos.Difference(loc).Absolute());
579 return glm::vec3(0.0f);
581 return TargetVelocity(state, normalize(diff) * speed);
585 glm::vec3 Steering::Arrive(const EntityState &state, const ExactLocation &loc) const noexcept {
586 const glm::vec3 diff(loc.Difference(state.pos).Absolute());
587 const float dist = length(diff);
588 if (dist < std::numeric_limits<float>::epsilon()) {
589 return glm::vec3(0.0f);
591 const float att_speed = std::min(dist * accel, speed);
592 return TargetVelocity(state, diff * att_speed / dist);
596 glm::vec3 Steering::Pursuit(const EntityState &state, const Entity &other) const noexcept {
597 const glm::vec3 diff(state.Diff(other.GetState()));
599 return TargetVelocity(state, other.Velocity());
601 const float time_estimate = length(diff) / speed;
602 ExactLocation prediction(other.ChunkCoords(), other.Position() + (other.Velocity() * time_estimate));
603 return Seek(state, prediction);
607 glm::vec3 Steering::Evade(const EntityState &state, const Entity &other) const noexcept {
608 const glm::vec3 diff(state.Diff(other.GetState()));
610 return TargetVelocity(state, -other.Velocity());
612 const float time_estimate = length(diff) / speed;
613 ExactLocation prediction(other.ChunkCoords(), other.Position() + (other.Velocity() * time_estimate));
614 return Flee(state, prediction);
618 glm::vec3 Steering::Wander(const EntityState &state) const noexcept {
619 return TargetVelocity(state, normalize(entity.Heading() * wander_dist + wander_pos) * speed);
622 glm::vec3 Steering::ObstacleAvoidance(const EntityState &state) const noexcept {
627 World::World(const BlockTypeRegistry &types, const Config &config)
634 #ifdef BLANK_PROFILING
640 , light_direction(config.light_direction)
641 , fog_density(config.fog_density) {
642 for (int i = 0; i < 4; ++i) {
648 for (Entity &e : entities) {
651 std::size_t removed = 0;
654 for (auto e = entities.begin(), end = entities.end(); e != end; ++e) {
655 if (e->CanRemove()) {
657 end = entities.end();
661 } while (removed > 0 && !entities.empty());
665 Player *World::AddPlayer(const std::string &name) {
666 for (Player &p : players) {
667 if (p.Name() == name) {
671 Entity &entity = AddEntity();
673 entity.Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
674 entity.WorldCollidable(true);
675 ChunkIndex &index = chunks.MakeIndex(entity.ChunkCoords(), 6);
676 players.emplace_back(entity, index);
677 return &players.back();
680 Player *World::AddPlayer(const std::string &name, std::uint32_t id) {
681 for (Player &p : players) {
682 if (p.Name() == name) {
686 Entity *entity = AddEntity(id);
691 entity->Bounds({ { -0.4f, -0.9f, -0.4f }, { 0.4f, 0.9f, 0.4f } });
692 entity->WorldCollidable(true);
693 ChunkIndex &index = chunks.MakeIndex(entity->ChunkCoords(), 6);
694 players.emplace_back(*entity, index);
695 return &players.back();
698 Entity &World::AddEntity() {
699 if (entities.empty()) {
700 entities.emplace_back();
701 entities.back().ID(1);
702 return entities.back();
704 if (entities.back().ID() < std::numeric_limits<std::uint32_t>::max()) {
705 std::uint32_t id = entities.back().ID() + 1;
706 entities.emplace_back();
707 entities.back().ID(id);
708 return entities.back();
710 std::uint32_t id = 1;
711 auto position = entities.begin();
712 auto end = entities.end();
713 while (position != end && position->ID() == id) {
717 auto entity = entities.emplace(position);
722 Entity *World::AddEntity(std::uint32_t id) {
723 if (entities.empty() || entities.back().ID() < id) {
724 entities.emplace_back();
725 entities.back().ID(id);
726 return &entities.back();
729 auto position = entities.begin();
730 auto end = entities.end();
731 while (position != end && position->ID() < id) {
734 if (position != end && position->ID() == id) {
737 auto entity = entities.emplace(position);
742 Entity &World::ForceAddEntity(std::uint32_t id) {
743 if (entities.empty() || entities.back().ID() < id) {
744 entities.emplace_back();
745 entities.back().ID(id);
746 return entities.back();
749 auto position = entities.begin();
750 auto end = entities.end();
751 while (position != end && position->ID() < id) {
754 if (position != end && position->ID() == id) {
757 auto entity = entities.emplace(position);
770 bool CandidateLess(const Candidate &a, const Candidate &b) {
771 return a.dist < b.dist;
774 std::vector<Candidate> candidates;
778 bool World::Intersection(
780 const ExactLocation::Coarse &reference,
785 for (Chunk &cur_chunk : chunks) {
787 if (cur_chunk.Intersection(ray, reference, cur_dist)) {
788 candidates.push_back({ &cur_chunk, cur_dist });
792 if (candidates.empty()) return false;
794 std::sort(candidates.begin(), candidates.end(), CandidateLess);
796 coll.chunk = nullptr;
798 coll.depth = std::numeric_limits<float>::infinity();
800 for (Candidate &cand : candidates) {
801 if (cand.dist > coll.depth) continue;
802 WorldCollision cur_coll;
803 if (cand.chunk->Intersection(ray, reference, cur_coll)) {
804 if (cur_coll.depth < coll.depth) {
813 bool World::Intersection(
815 const Entity &reference,
816 EntityCollision &coll
818 coll = EntityCollision(nullptr, std::numeric_limits<float>::infinity(), glm::vec3(0.0f));
819 for (Entity &cur_entity : entities) {
820 if (&cur_entity == &reference) {
824 glm::vec3 cur_normal;
825 if (blank::Intersection(ray, cur_entity.Bounds(), cur_entity.Transform(reference.ChunkCoords()), &cur_dist, &cur_normal)) {
826 // TODO: fine grained check goes here? maybe?
827 if (cur_dist < coll.depth) {
828 coll = EntityCollision(&cur_entity, cur_dist, cur_normal);
836 bool World::Intersection(const Entity &e, const EntityState &s, std::vector<WorldCollision> &col) {
837 glm::ivec3 reference = s.pos.chunk;
838 glm::mat4 M = s.Transform(reference);
840 ExactLocation::Coarse begin(reference - 1);
841 ExactLocation::Coarse end(reference + 2);
844 for (ExactLocation::Coarse pos(begin); pos.z < end.y; ++pos.z) {
845 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
846 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
847 Chunk *chunk = chunks.Get(pos);
848 if (chunk && chunk->Intersection(e, M, chunk->Transform(reference), col)) {
857 bool World::Intersection(
860 const glm::ivec3 &reference,
861 std::vector<WorldCollision> &col
864 for (Chunk &cur_chunk : chunks) {
865 if (manhattan_radius(cur_chunk.Position() - reference) > 1) {
866 // chunk is not one of the 3x3x3 surrounding the entity
867 // since there's no entity which can extent over 16 blocks, they can be skipped
868 // TODO: change to indexed (like with entity)
871 if (cur_chunk.Intersection(box, M, cur_chunk.Transform(reference), col)) {
878 void World::Update(int dt) {
879 float fdt(dt * 0.001f);
880 for (Entity &entity : entities) {
881 entity.Update(*this, fdt);
883 for (Player &player : players) {
886 for (auto iter = entities.begin(), end = entities.end(); iter != end;) {
887 if (iter->CanRemove()) {
888 iter = RemoveEntity(iter);
895 void World::ResolveWorldCollision(
896 const Entity &entity,
900 if (!entity.WorldCollidable() || !Intersection(entity, state, col)) {
901 // no collision, no fix
904 glm::vec3 correction = CombinedInterpenetration(state, col);
905 // correction may be zero in which case normalize() returns NaNs
906 if (iszero(correction)) {
909 // if entity is already going in the direction of correction,
910 // let the problem resolve itself
911 if (dot(state.velocity, correction) >= 0.0f) {
914 // apply correction, maybe could use some damping, gotta test
915 state.pos.block += correction;
917 glm::vec3 normal_velocity(proj(state.velocity, correction));
918 state.velocity -= normal_velocity;
921 glm::vec3 World::CombinedInterpenetration(
922 const EntityState &state,
923 const std::vector<WorldCollision> &col
925 // determine displacement for each cardinal axis and move entity accordingly
926 glm::vec3 min_pen(0.0f);
927 glm::vec3 max_pen(0.0f);
928 for (const WorldCollision &c : col) {
929 if (!c.Blocks()) continue;
930 glm::vec3 normal(c.normal);
931 // swap if neccessary (normal may point away from the entity)
932 if (dot(normal, state.RelativePosition(c.ChunkPos()) - c.BlockCoords()) < 0) {
935 // check if block surface is "inside"
936 Block::Face coll_face = Block::NormalFace(normal);
937 BlockLookup neighbor(c.chunk, c.BlockPos(), coll_face);
938 if (neighbor && neighbor.FaceFilled(Block::Opposite(coll_face))) {
939 // yep, so ignore this contact
942 glm::vec3 local_pen(normal * c.depth);
943 min_pen = min(min_pen, local_pen);
944 max_pen = max(max_pen, local_pen);
947 // only apply correction for axes where penetration is only in one direction
948 for (std::size_t i = 0; i < 3; ++i) {
949 if (min_pen[i] < -std::numeric_limits<float>::epsilon()) {
950 if (max_pen[i] < std::numeric_limits<float>::epsilon()) {
960 glm::vec3 World::GravityAt(const ExactLocation &loc) const noexcept {
961 glm::vec3 force(0.0f);
962 ExactLocation::Coarse begin(loc.chunk - 1);
963 ExactLocation::Coarse end(loc.chunk + 2);
965 for (ExactLocation::Coarse pos(begin); pos.z < end.z; ++pos.z) {
966 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
967 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
968 const Chunk *chunk = chunks.Get(pos);
970 force += chunk->GravityAt(loc);
979 World::EntityHandle World::RemoveEntity(EntityHandle &eh) {
981 for (auto player = players.begin(), end = players.end(); player != end;) {
982 if (&player->GetEntity() == &*eh) {
983 chunks.UnregisterIndex(player->GetChunks());
984 player = players.erase(player);
990 return entities.erase(eh);
994 void World::Render(Viewport &viewport) {
995 DirectionalLighting &entity_prog = viewport.EntityProgram();
996 entity_prog.SetFogDensity(fog_density);
1000 glm::vec3 ambient_col;
1001 for (Entity &entity : entities) {
1002 glm::mat4 M(entity.Transform(players.front().GetEntity().ChunkCoords()));
1003 if (!CullTest(entity.Bounds(), entity_prog.GetVP() * M)) {
1004 GetLight(entity, light_dir, light_col, ambient_col);
1005 entity_prog.SetLightDirection(light_dir);
1006 entity_prog.SetLightColor(light_col);
1007 entity_prog.SetAmbientColor(ambient_col);
1008 entity.Render(M, entity_prog);
1013 // this should interpolate based on the fractional part of entity's block position
1014 void World::GetLight(
1020 BlockLookup center(chunks.Get(e.ChunkCoords()), e.Position());
1022 // chunk unavailable, so make it really dark and from
1023 // some arbitrary direction
1024 dir = glm::vec3(1.0f, 2.0f, 3.0f);
1025 col = glm::vec3(0.025f); // ~0.8^15
1028 glm::ivec3 base(center.GetBlockPos());
1029 int base_light = center.GetLight();
1032 glm::ivec3 acc(0, 0, 0);
1033 for (glm::ivec3 offset(-1, -1, -1); offset.z < 2; ++offset.z) {
1034 for (offset.y = -1; offset.y < 2; ++offset.y) {
1035 for (offset.x = -1; offset.x < 2; ++offset.x) {
1036 BlockLookup block(¢er.GetChunk(), center.GetBlockPos() + offset);
1038 // missing, just ignore it
1041 // otherwise, accumulate the difference times direction
1042 acc += offset * (base_light - block.GetLight());
1043 max_light = std::max(max_light, block.GetLight());
1044 min_light = std::min(min_light, block.GetLight());
1049 col = glm::vec3(std::pow(0.8f, 15 - max_light));
1050 amb = glm::vec3(std::pow(0.8f, 15 - min_light));
1055 PrimitiveMesh::Buffer debug_buf;
1059 void World::RenderDebug(Viewport &viewport) {
1060 PrimitiveMesh debug_mesh;
1061 PlainColor &prog = viewport.WorldColorProgram();
1062 for (const Entity &entity : entities) {
1063 debug_buf.OutlineBox(entity.Bounds(), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
1064 debug_mesh.Update(debug_buf);
1065 prog.SetM(entity.Transform(players.front().GetEntity().ChunkCoords()));
1066 debug_mesh.DrawLines();