]> git.localhorst.tv Git - blank.git/blobdiff - src/ai/ai.cpp
fix divide by zero in Chaser AI
[blank.git] / src / ai / ai.cpp
index b3e1a0ceae5fb852c2f8fd653bfa2675cd193022..8cd4f1411abb1b9b21be99edb5e679a947c1c4e9 100644 (file)
@@ -2,34 +2,53 @@
 #include "Controller.hpp"
 #include "RandomWalk.hpp"
 
+#include "../model/geometry.hpp"
 #include "../world/Entity.hpp"
+#include "../world/World.hpp"
+#include "../world/WorldCollision.hpp"
 
 #include <glm/glm.hpp>
 
 
 namespace blank {
 
-Chaser::Chaser(Entity &ctrl, Entity &tgt) noexcept
+Chaser::Chaser(World &world, Entity &ctrl, Entity &tgt) noexcept
 : Controller(ctrl)
+, world(world)
 , tgt(tgt)
-, speed(0.002f)
-, stop_dist(5 * 5)
-, flee_dist(3 * 3) {
-
+, chase_speed(0.002f)
+, flee_speed(-0.005f)
+, stop_dist(10)
+, flee_dist(5) {
+       tgt.Ref();
 }
 
 Chaser::~Chaser() {
-
+       tgt.UnRef();
 }
 
 void Chaser::Update(int dt) {
        glm::vec3 diff(Target().AbsoluteDifference(Controlled()));
-       float dist = dot (diff, diff);
-       // TODO: line of sight test
-       if (dist > stop_dist) {
-               Controlled().Velocity(normalize(diff) * speed);
+       float dist = length(diff);
+       if (dist < std::numeric_limits<float>::epsilon()) {
+               Controlled().Velocity(glm::vec3(0.0f));
+               return;
+       }
+       glm::vec3 norm_diff(diff / dist);
+
+       bool line_of_sight = true;
+       Ray aim{Target().Position() - diff, norm_diff};
+       WorldCollision coll;
+       if (world.Intersection(aim, glm::mat4(1.0f), Target().ChunkCoords(), coll)) {
+               line_of_sight = coll.depth > dist;
+       }
+
+       if (!line_of_sight) {
+               Controlled().Velocity(glm::vec3(0.0f));
+       } else if (dist > stop_dist) {
+               Controlled().Velocity(norm_diff * chase_speed);
        } else if (dist < flee_dist) {
-               Controlled().Velocity(normalize(diff) * -speed);
+               Controlled().Velocity(norm_diff * flee_speed);
        } else {
                Controlled().Velocity(glm::vec3(0.0f));
        }
@@ -38,16 +57,17 @@ void Chaser::Update(int dt) {
 
 Controller::Controller(Entity &e) noexcept
 : entity(e) {
-
+       entity.Ref();
 }
 
 Controller::~Controller() {
-
+       entity.UnRef();
 }
 
 
-RandomWalk::RandomWalk(Entity &e) noexcept
+RandomWalk::RandomWalk(Entity &e, std::uint64_t seed) noexcept
 : Controller(e)
+, random(seed)
 , time_left(0) {
 
 }
@@ -59,13 +79,13 @@ RandomWalk::~RandomWalk() {
 void RandomWalk::Update(int dt) {
        time_left -= dt;
        if (time_left > 0) return;
-       time_left += 2500 + (rand() % 5000);
+       time_left += 2500 + (random.Next<unsigned short>() % 5000);
 
        constexpr float move_vel = 0.0005f;
 
        glm::vec3 new_vel = Controlled().Velocity();
 
-       switch (rand() % 9) {
+       switch (random.Next<unsigned char>() % 9) {
                case 0:
                        new_vel.x = -move_vel;
                        break;