From: Daniel Karbach Date: Sun, 25 Oct 2015 16:05:44 +0000 (+0100) Subject: more fun with AI/steering X-Git-Url: https://git.localhorst.tv/?a=commitdiff_plain;h=4c34ddd7eeaa3cb71fc90bf76a0cd395682add66;p=blank.git more fun with AI/steering --- diff --git a/src/ai/AIController.hpp b/src/ai/AIController.hpp index c124196..bd88290 100644 --- a/src/ai/AIController.hpp +++ b/src/ai/AIController.hpp @@ -10,13 +10,16 @@ namespace blank { class AIState; +class Entity; class GaloisLFSR; +class Player; +class World; class AIController : public EntityController { public: - explicit AIController(GaloisLFSR &); + AIController(World &, GaloisLFSR &); ~AIController(); void SetState(const AIState &); @@ -27,6 +30,16 @@ public: static glm::vec3 Heading(const EntityState &) noexcept; + /// get the closest player that given entity can see + /// returns nullptr if none are in sight + Player *ClosestVisiblePlayer(const Entity &) noexcept; + /// true if to entity is in visible range of from entity + bool LineOfSight(const Entity &from, const Entity &to) const noexcept; + + /// true if the controller may do expensive calculations + bool MayThink() const noexcept; + void SetThinkInterval(float) noexcept; + /// schedule a decision in the next minimum ± variance seconds void CueDecision( float minimum, @@ -37,48 +50,96 @@ public: /// random choice of 0 to num_choices - 1 unsigned int Decide(unsigned int num_choices) noexcept; - void EnterHalt(float speed) noexcept; + void EnterHalt() noexcept; void ExitHalt() noexcept; bool IsHalted() const noexcept; + void SetHaltSpeed(float) noexcept; + glm::vec3 GetHaltForce(const EntityState &) const noexcept; - void StartFleeing(const Entity &, float speed) noexcept; + void StartFleeing() noexcept; void StopFleeing() noexcept; bool IsFleeing() const noexcept; + void SetFleeTarget(Entity &) noexcept; + void SetFleeSpeed(float) noexcept; + Entity &GetFleeTarget() noexcept; const Entity &GetFleeTarget() const noexcept; + glm::vec3 GetFleeForce(const EntityState &) const noexcept; - void StartSeeking(const Entity &, float speed) noexcept; + void StartSeeking() noexcept; void StopSeeking() noexcept; bool IsSeeking() const noexcept; + void SetSeekTarget(Entity &) noexcept; + void SetSeekSpeed(float) noexcept; + Entity &GetSeekTarget() noexcept; const Entity &GetSeekTarget() const noexcept; - - /// start wandering randomly at given speed + glm::vec3 GetSeekForce(const EntityState &) const noexcept; + + void StartEvading() noexcept; + void StopEvading() noexcept; + bool IsEvading() const noexcept; + void SetEvadeTarget(Entity &) noexcept; + void SetEvadeSpeed(float) noexcept; + Entity &GetEvadeTarget() noexcept; + const Entity &GetEvadeTarget() const noexcept; + glm::vec3 GetEvadeForce(const EntityState &) const noexcept; + + void StartPursuing() noexcept; + void StopPursuing() noexcept; + bool IsPursuing() const noexcept; + void SetPursuitTarget(Entity &) noexcept; + void SetPursuitSpeed(float) noexcept; + Entity &GetPursuitTarget() noexcept; + const Entity &GetPursuitTarget() const noexcept; + glm::vec3 GetPursuitForce(const EntityState &) const noexcept; + + /// start wandering randomly + void StartWandering() noexcept; + void StopWandering() noexcept; + bool IsWandering() const noexcept; + /// change how wandering is performed /// the trajectory is modified by targetting a blip on a sphere /// in front of the entity which moves randomly /// the displacement is given (roughly) in units per second - void StartWandering( + void SetWanderParams( float speed, float distance = 2.0f, float radius = 1.0f, float displacement = 1.0f ) noexcept; - void StopWandering() noexcept; - bool IsWandering() const noexcept; + glm::vec3 GetWanderForce(const EntityState &) const noexcept; private: + World &world; GaloisLFSR &random; const AIState *state; + /// how far controlled entities can see + float sight_dist; + /// cosine of the half angle of FOV of controlled entities + float sight_angle; + + FineTimer think_timer; FineTimer decision_timer; bool halted; float halt_speed; - const Entity *flee_target; + bool fleeing; + Entity *flee_target; float flee_speed; - const Entity *seek_target; + bool seeking; + Entity *seek_target; float seek_speed; + bool evading; + Entity *evade_target; + float evade_speed; + + bool pursuing; + Entity *pursuit_target; + float pursuit_speed; + bool wandering; glm::vec3 wander_pos; float wander_speed; diff --git a/src/ai/ChaseState.hpp b/src/ai/ChaseState.hpp new file mode 100644 index 0000000..97e6895 --- /dev/null +++ b/src/ai/ChaseState.hpp @@ -0,0 +1,25 @@ +#ifndef BLANK_AI_CHASESTATE_HPP_ +#define BLANK_AI_CHASESTATE_HPP_ + +#include "AIState.hpp" + + +namespace blank { + +/// stand around and do nothing +/// occasionally look in a different direction +/// start roaming at random +/// start chasing a player if one comes near + +class ChaseState +: public AIState { + + void Enter(AIController &) const override; + void Update(AIController &, Entity &, float dt) const override; + void Exit(AIController &) const override; + +}; + +} + +#endif diff --git a/src/ai/FleeState.hpp b/src/ai/FleeState.hpp new file mode 100644 index 0000000..8664e58 --- /dev/null +++ b/src/ai/FleeState.hpp @@ -0,0 +1,25 @@ +#ifndef BLANK_AI_FLEESTATE_HPP_ +#define BLANK_AI_FLEESTATE_HPP_ + +#include "AIState.hpp" + + +namespace blank { + +/// stand around and do nothing +/// occasionally look in a different direction +/// start roaming at random +/// start chasing a player if one comes near + +class FleeState +: public AIState { + + void Enter(AIController &) const override; + void Update(AIController &, Entity &, float dt) const override; + void Exit(AIController &) const override; + +}; + +} + +#endif diff --git a/src/ai/Spawner.cpp b/src/ai/Spawner.cpp index 6404e44..fabc6dd 100644 --- a/src/ai/Spawner.cpp +++ b/src/ai/Spawner.cpp @@ -127,7 +127,7 @@ void Spawner::Spawn(Entity &reference, const glm::ivec3 &chunk, const glm::vec3 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } }); e.WorldCollidable(true); RandomModel().Instantiate(e.GetModel()); - e.SetController(new AIController(random)); + e.SetController(new AIController(world, random)); e.Name("spawned"); e.Ref(); entities.emplace_back(&e); diff --git a/src/ai/ai.cpp b/src/ai/ai.cpp index 343bacf..11add89 100644 --- a/src/ai/ai.cpp +++ b/src/ai/ai.cpp @@ -1,4 +1,6 @@ #include "AIController.hpp" +#include "ChaseState.hpp" +#include "FleeState.hpp" #include "IdleState.hpp" #include "RoamState.hpp" @@ -17,27 +19,42 @@ namespace blank { namespace { +ChaseState chase; +FleeState flee; IdleState idle; RoamState roam; } -AIController::AIController(GaloisLFSR &rand) -: random(rand) +AIController::AIController(World &world, GaloisLFSR &rand) +: world(world) +, random(rand) , state(&idle) +, sight_dist(64.0f) +, sight_angle(0.707f) +, think_timer(0.5f) , decision_timer(1.0f) , halted(false) , halt_speed(1.0f) +, fleeing(false) , flee_target(nullptr) , flee_speed(5.0f) +, seeking(false) , seek_target(nullptr) , seek_speed(5.0f) +, evading(false) +, evade_target(nullptr) +, evade_speed(5.0f) +, pursuing(false) +, pursuit_target(nullptr) +, pursuit_speed(5.0f) , wandering(false) , wander_pos(1.0f, 0.0f, 0.0f) , wander_speed(1.0f) , wander_dist(2.0f) , wander_radius(1.5f) , wander_disp(1.0f) { + think_timer.Start(); state->Enter(*this); } @@ -52,6 +69,7 @@ void AIController::SetState(const AIState &s) { } void AIController::Update(Entity &e, float dt) { + think_timer.Update(dt); decision_timer.Update(dt); state->Update(*this, e, dt); @@ -77,24 +95,31 @@ void AIController::Update(Entity &e, float dt) { glm::vec3 AIController::ControlForce(const Entity &entity, const EntityState &state) const { if (IsHalted()) { - return Halt(state, halt_speed); + return GetHaltForce(state); } glm::vec3 force(0.0f); if (IsFleeing()) { - glm::vec3 diff(GetFleeTarget().GetState().Diff(state)); - if (MaxOutForce(force, TargetVelocity(normalize(diff) * flee_speed, state, 0.5f), entity.MaxControlForce())) { + if (MaxOutForce(force, GetFleeForce(state), entity.MaxControlForce())) { return force; } } if (IsSeeking()) { - glm::vec3 diff(state.Diff(GetSeekTarget().GetState())); - if (MaxOutForce(force, TargetVelocity(normalize(diff) * seek_speed, state, 0.5f), entity.MaxControlForce())) { + if (MaxOutForce(force, GetSeekForce(state), entity.MaxControlForce())) { + return force; + } + } + if (IsEvading()) { + if (MaxOutForce(force, GetEvadeForce(state), entity.MaxControlForce())) { + return force; + } + } + if (IsPursuing()) { + if (MaxOutForce(force, GetPursuitForce(state), entity.MaxControlForce())) { return force; } } if (IsWandering()) { - glm::vec3 wander_target(normalize(Heading(state) * wander_dist + wander_pos) * wander_speed); - if (MaxOutForce(force, TargetVelocity(wander_target, state, 2.0f), entity.MaxControlForce())) { + if (MaxOutForce(force, GetWanderForce(state), entity.MaxControlForce())) { return force; } } @@ -110,6 +135,65 @@ glm::vec3 AIController::Heading(const EntityState &state) noexcept { } } +Player *AIController::ClosestVisiblePlayer(const Entity &e) noexcept { + Player *target = nullptr; + float distance = sight_dist; + const glm::ivec3 &reference(e.ChunkCoords()); + Ray aim(e.Aim(reference)); + for (Player &p : world.Players()) { + const Entity &pe = p.GetEntity(); + + // distance test + const glm::vec3 diff(pe.AbsoluteDifference(e)); + float dist = length_squared(diff); + if (dist > distance) continue; + + // FOV test, 45° in each direction + if (dot(normalize(diff), aim.dir) < sight_angle) { + continue; + } + + // LOS test, assumes all entities are see-through + WorldCollision col; + if (world.Intersection(aim, glm::mat4(1.0f), reference, col) && col.depth * col.depth < dist) { + continue; + } + + // we got a match + target = &p; + distance = dist; + } + return target; +} + +bool AIController::LineOfSight(const Entity &from, const Entity &to) const noexcept { + const glm::ivec3 &reference(from.ChunkCoords()); + Ray aim(from.Aim(reference)); + const glm::vec3 diff(to.AbsoluteDifference(from)); + float dist = length(diff); + if (dist > sight_dist || dot(diff / dist, aim.dir) < sight_angle) { + return false; + } + WorldCollision col; + if (world.Intersection(aim, glm::mat4(1.0f), reference, col) && col.depth < dist) { + return false; + } + return true; +} + +// think + +bool AIController::MayThink() const noexcept { + return think_timer.Hit(); +} + +void AIController::SetThinkInterval(float i) noexcept { + think_timer = FineTimer(i); + think_timer.Start(); +} + +// decide + void AIController::CueDecision( float minimum, float variance @@ -126,9 +210,10 @@ unsigned int AIController::Decide(unsigned int num_choices) noexcept { return random.Next() % num_choices; } -void AIController::EnterHalt(float speed) noexcept { +// halt + +void AIController::EnterHalt() noexcept { halted = true; - halt_speed = speed; } void AIController::ExitHalt() noexcept { @@ -139,81 +224,307 @@ bool AIController::IsHalted() const noexcept { return halted; } -void AIController::StartFleeing(const Entity &e, float speed) noexcept { - flee_target = &e; - flee_speed = speed; +void AIController::SetHaltSpeed(float speed) noexcept { + halt_speed = speed; +} + +glm::vec3 AIController::GetHaltForce(const EntityState &state) const noexcept { + return Halt(state, halt_speed); +} + +// flee + +void AIController::StartFleeing() noexcept { + fleeing = true; } void AIController::StopFleeing() noexcept { - flee_target = nullptr; + fleeing = false; + if (flee_target) { + flee_target->UnRef(); + flee_target = nullptr; + } } bool AIController::IsFleeing() const noexcept { - return flee_target; + return fleeing && flee_target; +} + +void AIController::SetFleeTarget(Entity &e) noexcept { + if (flee_target) { + flee_target->UnRef(); + } + flee_target = &e; + flee_target->Ref(); +} + +void AIController::SetFleeSpeed(float speed) noexcept { + flee_speed = speed; +} + +Entity &AIController::GetFleeTarget() noexcept { + return *flee_target; } const Entity &AIController::GetFleeTarget() const noexcept { return *flee_target; } -void AIController::StartSeeking(const Entity &e, float speed) noexcept { - seek_target = &e; - seek_speed = speed; +glm::vec3 AIController::GetFleeForce(const EntityState &state) const noexcept { + return Flee(state, GetFleeTarget().GetState(), flee_speed, 2.0f); +} + +// seek + +void AIController::StartSeeking() noexcept { + seeking = true; } void AIController::StopSeeking() noexcept { - seek_target = nullptr; + seeking = false; + if (seek_target) { + seek_target->UnRef(); + seek_target = nullptr; + } } bool AIController::IsSeeking() const noexcept { - return seek_target; + return seeking && seek_target; +} + +void AIController::SetSeekTarget(Entity &e) noexcept { + if (seek_target) { + seek_target->UnRef(); + } + seek_target = &e; + seek_target->Ref(); +} + +void AIController::SetSeekSpeed(float speed) noexcept { + seek_speed = speed; +} + +Entity &AIController::GetSeekTarget() noexcept { + return *seek_target; } const Entity &AIController::GetSeekTarget() const noexcept { return *seek_target; } -void AIController::StartWandering( +glm::vec3 AIController::GetSeekForce(const EntityState &state) const noexcept { + return Seek(state, GetSeekTarget().GetState(), seek_speed, 2.0f); +} + +// evade + +void AIController::StartEvading() noexcept { + evading = true; +} + +void AIController::StopEvading() noexcept { + evading = false; + if (evade_target) { + evade_target->UnRef(); + evade_target = nullptr; + } +} + +bool AIController::IsEvading() const noexcept { + return evading && evade_target; +} + +void AIController::SetEvadeTarget(Entity &e) noexcept { + if (evade_target) { + evade_target->UnRef(); + } + evade_target = &e; + evade_target->Ref(); +} + +void AIController::SetEvadeSpeed(float speed) noexcept { + evade_speed = speed; +} + +Entity &AIController::GetEvadeTarget() noexcept { + return *evade_target; +} + +const Entity &AIController::GetEvadeTarget() const noexcept { + return *evade_target; +} + +glm::vec3 AIController::GetEvadeForce(const EntityState &state) const noexcept{ + glm::vec3 cur_diff(state.Diff(GetEvadeTarget().GetState())); + float time_estimate = length(cur_diff) / evade_speed; + EntityState pred_state(GetEvadeTarget().GetState()); + pred_state.block_pos += pred_state.velocity * time_estimate; + return Flee(state, pred_state, evade_speed, 2.0f); +} + +// pursuit + +void AIController::StartPursuing() noexcept { + pursuing = true; +} + +void AIController::StopPursuing() noexcept { + pursuing = false; + if (pursuit_target) { + pursuit_target->UnRef(); + pursuit_target = nullptr; + } +} + +bool AIController::IsPursuing() const noexcept { + return pursuing && pursuit_target; +} + +void AIController::SetPursuitTarget(Entity &e) noexcept { + if (pursuit_target) { + pursuit_target->UnRef(); + } + pursuit_target = &e; + pursuit_target->Ref(); +} + +void AIController::SetPursuitSpeed(float speed) noexcept { + pursuit_speed = speed; +} + +Entity &AIController::GetPursuitTarget() noexcept { + return *pursuit_target; +} + +const Entity &AIController::GetPursuitTarget() const noexcept { + return *pursuit_target; +} + +glm::vec3 AIController::GetPursuitForce(const EntityState &state) const noexcept { + glm::vec3 cur_diff(state.Diff(GetPursuitTarget().GetState())); + float time_estimate = length(cur_diff) / pursuit_speed; + EntityState pred_state(GetPursuitTarget().GetState()); + pred_state.block_pos += pred_state.velocity * time_estimate; + return Seek(state, pred_state, pursuit_speed, 2.0f); +} + +// wander + +void AIController::StartWandering() noexcept { + wandering = true; +} + +void AIController::StopWandering() noexcept { + wandering = false; +} + +bool AIController::IsWandering() const noexcept { + return wandering; +} + +void AIController::SetWanderParams( float speed, float distance, float radius, float displacement ) noexcept { - wandering = true; wander_speed = speed; wander_dist = distance; wander_radius = radius; wander_disp = displacement; } -void AIController::StopWandering() noexcept { - wandering = false; +glm::vec3 AIController::GetWanderForce(const EntityState &state) const noexcept { + glm::vec3 wander_target(normalize(Heading(state) * wander_dist + wander_pos) * wander_speed); + return TargetVelocity(wander_target, state, 0.5f); } -bool AIController::IsWandering() const noexcept { - return wandering; + +// chase + +void ChaseState::Enter(AIController &ctrl) const { + ctrl.SetHaltSpeed(2.0f); + ctrl.SetPursuitSpeed(4.0f); + ctrl.StartPursuing(); +} + +void ChaseState::Update(AIController &ctrl, Entity &e, float dt) const { + // check if target still alive and in sight + if (ctrl.GetPursuitTarget().Dead()) { + ctrl.SetState(idle); + return; + } + if (!ctrl.LineOfSight(e, ctrl.GetPursuitTarget())) { + ctrl.SetState(idle); + return; + } + // halt if we're close enough, flee if we're too close + float dist_sq = length_squared(e.AbsoluteDifference(ctrl.GetPursuitTarget())); + if (dist_sq < 8.0f) { + ctrl.SetFleeTarget(ctrl.GetPursuitTarget()); + ctrl.SetState(flee); + } else if (dist_sq < 25.0f) { + ctrl.EnterHalt(); + } else { + ctrl.ExitHalt(); + } +} + +void ChaseState::Exit(AIController &ctrl) const { + ctrl.StopPursuing(); + ctrl.ExitHalt(); +} + +// flee + +void FleeState::Enter(AIController &ctrl) const { + ctrl.CueDecision(6.0f, 3.0f); + ctrl.SetFleeSpeed(4.0f); + ctrl.StartFleeing(); +} + +void FleeState::Update(AIController &ctrl, Entity &e, float dt) const { + if (!ctrl.DecisionDue()) return; + ctrl.SetState(idle); +} + +void FleeState::Exit(AIController &ctrl) const { + ctrl.StopFleeing(); } +// idle void IdleState::Enter(AIController &ctrl) const { - ctrl.EnterHalt(2.0f); - ctrl.StartWandering(0.001f, 1.1f); + ctrl.SetHaltSpeed(0.5f); + ctrl.EnterHalt(); + ctrl.SetWanderParams(0.001f, 1.1f); ctrl.CueDecision(10.0f, 5.0f); } void IdleState::Update(AIController &ctrl, Entity &e, float dt) const { - // TODO: check for players + if (ctrl.MayThink()) { + const Player *player = ctrl.ClosestVisiblePlayer(e); + if (player) { + ctrl.SetPursuitTarget(player->GetEntity()); + ctrl.SetState(chase); + return; + } + } + if (!ctrl.DecisionDue()) return; unsigned int d = ctrl.Decide(10); - if (d == 0) { - // .1 chance to start going + if (d < 2) { + // .2 chance to start going ctrl.SetState(roam); - } else if (d < 3) { - // .2 chance of looking around + } else if (d < 5) { + // .3 chance of looking around ctrl.ExitHalt(); + ctrl.StartWandering(); } else { - ctrl.EnterHalt(2.0f); + // .5 chance of doing nothing + ctrl.StopWandering(); + ctrl.EnterHalt(); } ctrl.CueDecision(10.0f, 5.0f); } @@ -223,13 +534,24 @@ void IdleState::Exit(AIController &ctrl) const { ctrl.StopWandering(); } +// roam + void RoamState::Enter(AIController &ctrl) const { - ctrl.StartWandering(1.0f); + ctrl.SetWanderParams(1.0f); + ctrl.StartWandering(); ctrl.CueDecision(10.0f, 5.0f); } void RoamState::Update(AIController &ctrl, Entity &e, float dt) const { - // TODO: check for players + if (ctrl.MayThink()) { + const Player *player = ctrl.ClosestVisiblePlayer(e); + if (player) { + ctrl.SetPursuitTarget(player->GetEntity()); + ctrl.SetState(chase); + return; + } + } + if (!ctrl.DecisionDue()) return; unsigned int d = ctrl.Decide(10); diff --git a/src/model/geometry.hpp b/src/model/geometry.hpp index 0bc17c1..248ced3 100644 --- a/src/model/geometry.hpp +++ b/src/model/geometry.hpp @@ -20,29 +20,38 @@ constexpr float PI_0p5_inv = 1.0f / PI_0p5; constexpr float DEG_RAD_FACTOR = PI / 180.0f; constexpr float RAD_DEG_FACTOR = 180.0f / PI; -constexpr float deg2rad(float d) { +constexpr float deg2rad(float d) noexcept { return d * DEG_RAD_FACTOR; } -constexpr float rad2deg(float r) { +constexpr float rad2deg(float r) noexcept { return r * RAD_DEG_FACTOR; } +inline float length_squared(const glm::vec3 &v) noexcept { + return dot(v, v); +} + +inline float distance_squared(const glm::vec3 &a, const glm::vec3 &b) noexcept { + return length_squared(a - b); +} + + template -inline bool iszero(const T &v) { - return dot(v, v) < std::numeric_limits::epsilon(); +inline bool iszero(const T &v) noexcept { + return length_squared(v) < std::numeric_limits::epsilon(); } template -T manhattan_distance(const glm::tvec3 &a, const glm::tvec3 &b) { +T manhattan_distance(const glm::tvec3 &a, const glm::tvec3 &b) noexcept { glm::tvec3 diff(abs(a - b)); return diff.x + diff.y + diff.z; } template -T manhattan_radius(const glm::tvec3 &v) { +T manhattan_radius(const glm::tvec3 &v) noexcept { glm::tvec3 a(abs(v)); return std::max(a.x, std::max(a.y, a.z)); } diff --git a/src/world/EntityController.hpp b/src/world/EntityController.hpp index 3bfc10b..ce3d0cf 100644 --- a/src/world/EntityController.hpp +++ b/src/world/EntityController.hpp @@ -26,8 +26,15 @@ struct EntityController { const glm::vec3 &add, float max ) noexcept; - /// give a force that makes state's velocity converge with given target velocity - /// over 1/n seconds + /// give a force that makes state come to a halt over 1/n seconds + static inline glm::vec3 Halt( + const EntityState &state, + float n + ) noexcept { + return state.velocity * -n; + } + /// give a force that makes state's velocity converge with given + /// target velocity over 1/n seconds static inline glm::vec3 TargetVelocity( const glm::vec3 &target, const EntityState &state, @@ -35,12 +42,24 @@ struct EntityController { ) noexcept { return (target - state.velocity) * n; } - /// give a force that makes state come to a halt over 1/n seconds - static inline glm::vec3 Halt( + /// give a force that makes state go after target with an attempted + /// acceleration over 1/n seconds and a speed of s + static inline glm::vec3 Seek( const EntityState &state, + const EntityState &target, + float s, float n ) noexcept { - return state.velocity * -n; + return TargetVelocity(normalize(target.Diff(state)) * s, state, n); + } + /// opposite of seek + static inline glm::vec3 Flee( + const EntityState &state, + const EntityState &target, + float s, + float n + ) noexcept { + return TargetVelocity(normalize(state.Diff(target)) * s, state, n); } }; diff --git a/src/world/World.hpp b/src/world/World.hpp index 4755b18..ab563a7 100644 --- a/src/world/World.hpp +++ b/src/world/World.hpp @@ -85,6 +85,7 @@ public: /// returs an existing entity if ID is already taken Entity &ForceAddEntity(std::uint32_t id); + std::list &Players() noexcept { return players; } const std::list &Players() const noexcept { return players; } std::list &Entities() noexcept { return entities; } const std::list &Entities() const noexcept { return entities; }