veloren_common/comp/
agent.rs

1use crate::{
2    comp::{
3        Body, UtteranceKind, biped_large, biped_small, bird_medium, humanoid, quadruped_low,
4        quadruped_medium, quadruped_small, ship,
5    },
6    path::Chaser,
7    rtsim::{self, NpcInput, RtSimController},
8    trade::{PendingTrade, ReducedInventory, SiteId, SitePrices, TradeId, TradeResult},
9    uid::Uid,
10};
11use serde::{Deserialize, Serialize};
12use specs::{Component, DerefFlaggedStorage, Entity as EcsEntity};
13use std::{collections::VecDeque, fmt};
14use strum::{EnumIter, IntoEnumIterator};
15use vek::*;
16
17use super::{Group, Pos};
18
19pub const DEFAULT_INTERACTION_TIME: f32 = 3.0;
20pub const TRADE_INTERACTION_TIME: f32 = 300.0;
21const SECONDS_BEFORE_FORGET_SOUNDS: f64 = 180.0;
22
23//intentionally very few concurrent action state variables are allowed. This is
24// to keep the complexity of our AI from getting too large, too quickly.
25// Originally I was going to provide 30 of these, but if we decide later that
26// this is too many and somebody is already using 30 in one of their AI, it will
27// be difficult to go back.
28
29/// The number of timers that a single Action node can track concurrently
30/// Define constants within a given action node to index between them.
31const ACTIONSTATE_NUMBER_OF_CONCURRENT_TIMERS: usize = 5;
32/// The number of float counters that a single Action node can track
33/// concurrently Define constants within a given action node to index between
34/// them.
35const ACTIONSTATE_NUMBER_OF_CONCURRENT_COUNTERS: usize = 5;
36/// The number of integer counters that a single Action node can track
37/// concurrently Define constants within a given action node to index between
38/// them.
39const ACTIONSTATE_NUMBER_OF_CONCURRENT_INT_COUNTERS: usize = 5;
40/// The number of booleans that a single Action node can track concurrently
41/// Define constants within a given action node to index between them.
42const ACTIONSTATE_NUMBER_OF_CONCURRENT_CONDITIONS: usize = 5;
43/// The number of positions that can be remembered by an agent
44const ACTIONSTATE_NUMBER_OF_CONCURRENT_POSITIONS: usize = 5;
45
46#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
47pub enum Alignment {
48    /// Wild animals and gentle giants
49    Wild,
50    /// Dungeon cultists and bandits
51    Enemy,
52    /// Friendly folk in villages
53    Npc,
54    /// Farm animals and pets of villagers
55    Tame,
56    /// Pets you've tamed with a collar
57    Owned(Uid),
58    /// Passive objects like training dummies
59    Passive,
60}
61
62#[derive(Copy, Clone, Debug, PartialEq, Eq)]
63pub enum Mark {
64    Merchant,
65    Guard,
66}
67
68impl Alignment {
69    // Always attacks
70    pub fn hostile_towards(self, other: Alignment) -> bool {
71        match (self, other) {
72            (Alignment::Passive, _) => false,
73            (_, Alignment::Passive) => false,
74            (Alignment::Enemy, Alignment::Enemy) => false,
75            (Alignment::Enemy, Alignment::Wild) => false,
76            (Alignment::Wild, Alignment::Enemy) => false,
77            (Alignment::Wild, Alignment::Wild) => false,
78            (Alignment::Npc, Alignment::Wild) => false,
79            (Alignment::Npc, Alignment::Enemy) => true,
80            (_, Alignment::Enemy) => true,
81            (Alignment::Enemy, _) => true,
82            _ => false,
83        }
84    }
85
86    // Usually never attacks
87    pub fn passive_towards(self, other: Alignment) -> bool {
88        match (self, other) {
89            (Alignment::Enemy, Alignment::Enemy) => true,
90            (Alignment::Owned(a), Alignment::Owned(b)) if a == b => true,
91            (Alignment::Npc, Alignment::Npc) => true,
92            (Alignment::Npc, Alignment::Tame) => true,
93            (Alignment::Enemy, Alignment::Wild) => true,
94            (Alignment::Wild, Alignment::Enemy) => true,
95            (Alignment::Tame, Alignment::Npc) => true,
96            (Alignment::Tame, Alignment::Tame) => true,
97            (_, Alignment::Passive) => true,
98            _ => false,
99        }
100    }
101
102    // Never attacks
103    pub fn friendly_towards(self, other: Alignment) -> bool {
104        match (self, other) {
105            (Alignment::Enemy, Alignment::Enemy) => true,
106            (Alignment::Owned(a), Alignment::Owned(b)) if a == b => true,
107            (Alignment::Npc, Alignment::Npc) => true,
108            (Alignment::Npc, Alignment::Tame) => true,
109            (Alignment::Tame, Alignment::Npc) => true,
110            (Alignment::Tame, Alignment::Tame) => true,
111            (_, Alignment::Passive) => true,
112            _ => false,
113        }
114    }
115
116    /// Default group for this alignment
117    // NOTE: This is a HACK
118    pub fn group(&self) -> Option<Group> {
119        match self {
120            Alignment::Wild => None,
121            Alignment::Passive => None,
122            Alignment::Enemy => Some(super::group::ENEMY),
123            Alignment::Npc | Alignment::Tame => Some(super::group::NPC),
124            Alignment::Owned(_) => None,
125        }
126    }
127}
128
129impl Component for Alignment {
130    type Storage = DerefFlaggedStorage<Self, specs::VecStorage<Self>>;
131}
132
133bitflags::bitflags! {
134    #[derive(Clone, Copy, Debug, Default)]
135    pub struct BehaviorCapability: u8 {
136        const SPEAK = 0b00000001;
137        const TRADE = 0b00000010;
138    }
139}
140bitflags::bitflags! {
141    #[derive(Clone, Copy, Debug, Default)]
142    pub struct BehaviorState: u8 {
143        const TRADING        = 0b00000001;
144        const TRADING_ISSUER = 0b00000010;
145    }
146}
147
148#[derive(Default, Copy, Clone, Debug)]
149pub enum TradingBehavior {
150    #[default]
151    None,
152    RequireBalanced {
153        trade_site: SiteId,
154    },
155    AcceptFood,
156}
157
158impl TradingBehavior {
159    fn can_trade(&self, alignment: Option<Alignment>, counterparty: Uid) -> bool {
160        match self {
161            TradingBehavior::RequireBalanced { .. } => true,
162            TradingBehavior::AcceptFood => alignment == Some(Alignment::Owned(counterparty)),
163            TradingBehavior::None => false,
164        }
165    }
166}
167
168/// # Behavior Component
169/// This component allow an Entity to register one or more behavior tags.
170/// These tags act as flags of what an Entity can do, or what it is doing.
171/// Behaviors Tags can be added and removed as the Entity lives, to update its
172/// state when needed
173#[derive(Default, Copy, Clone, Debug)]
174pub struct Behavior {
175    capabilities: BehaviorCapability,
176    state: BehaviorState,
177    pub trading_behavior: TradingBehavior,
178}
179
180impl From<BehaviorCapability> for Behavior {
181    fn from(capabilities: BehaviorCapability) -> Self {
182        Behavior {
183            capabilities,
184            state: BehaviorState::default(),
185            trading_behavior: TradingBehavior::None,
186        }
187    }
188}
189
190impl Behavior {
191    /// Builder function
192    /// Set capabilities if Option is Some
193    #[must_use]
194    pub fn maybe_with_capabilities(
195        mut self,
196        maybe_capabilities: Option<BehaviorCapability>,
197    ) -> Self {
198        if let Some(capabilities) = maybe_capabilities {
199            self.allow(capabilities)
200        }
201        self
202    }
203
204    /// Builder function
205    /// Set trade_site if Option is Some
206    #[must_use]
207    pub fn with_trade_site(mut self, trade_site: Option<SiteId>) -> Self {
208        if let Some(trade_site) = trade_site {
209            self.trading_behavior = TradingBehavior::RequireBalanced { trade_site };
210        }
211        self
212    }
213
214    /// Set capabilities to the Behavior
215    pub fn allow(&mut self, capabilities: BehaviorCapability) {
216        self.capabilities.set(capabilities, true)
217    }
218
219    /// Unset capabilities to the Behavior
220    pub fn deny(&mut self, capabilities: BehaviorCapability) {
221        self.capabilities.set(capabilities, false)
222    }
223
224    /// Check if the Behavior is able to do something
225    pub fn can(&self, capabilities: BehaviorCapability) -> bool {
226        self.capabilities.contains(capabilities)
227    }
228
229    /// Check if the Behavior is able to trade
230    pub fn can_trade(&self, alignment: Option<Alignment>, counterparty: Uid) -> bool {
231        self.trading_behavior.can_trade(alignment, counterparty)
232    }
233
234    /// Set a state to the Behavior
235    pub fn set(&mut self, state: BehaviorState) { self.state.set(state, true) }
236
237    /// Unset a state to the Behavior
238    pub fn unset(&mut self, state: BehaviorState) { self.state.set(state, false) }
239
240    /// Check if the Behavior has a specific state
241    pub fn is(&self, state: BehaviorState) -> bool { self.state.contains(state) }
242
243    /// Get the trade site at which this behavior evaluates prices, if it does
244    pub fn trade_site(&self) -> Option<SiteId> {
245        if let TradingBehavior::RequireBalanced { trade_site } = self.trading_behavior {
246            Some(trade_site)
247        } else {
248            None
249        }
250    }
251}
252
253#[derive(Clone, Debug, Default)]
254pub struct Psyche {
255    /// The proportion of health below which entities will start fleeing.
256    /// 0.0 = never flees, 1.0 = always flees, 0.5 = flee at 50% health.
257    pub flee_health: f32,
258    /// The distance below which the agent will see enemies if it has line of
259    /// sight.
260    pub sight_dist: f32,
261    /// The distance below which the agent can hear enemies without seeing them.
262    pub listen_dist: f32,
263    /// The distance below which the agent will attack enemies. Should be lower
264    /// than `sight_dist`. `None` implied that the agent is always aggro
265    /// towards enemies that it is aware of.
266    pub aggro_dist: Option<f32>,
267    /// A factor that controls how much further an agent will wander when in the
268    /// idle state. `1.0` is normal.
269    pub idle_wander_factor: f32,
270    /// Aggro range is multiplied by this factor. `1.0` is normal.
271    ///
272    /// This includes scaling the effective `sight_dist` and `listen_dist`
273    /// when finding new targets to attack, adjusting the strength of
274    /// wandering behavior in the idle state, and scaling `aggro_dist` in
275    /// certain situations.
276    pub aggro_range_multiplier: f32,
277    /// Whether this entity should *intelligently* decide to loose aggro based
278    /// on distance from agent home and health, this is not suitable for world
279    /// bosses and roaming entities
280    pub should_stop_pursuing: bool,
281}
282
283impl<'a> From<&'a Body> for Psyche {
284    fn from(body: &'a Body) -> Self {
285        Self {
286            flee_health: match body {
287                Body::Humanoid(humanoid) => match humanoid.species {
288                    humanoid::Species::Danari => 0.4,
289                    humanoid::Species::Dwarf => 0.3,
290                    humanoid::Species::Elf => 0.4,
291                    humanoid::Species::Human => 0.4,
292                    humanoid::Species::Orc => 0.3,
293                    humanoid::Species::Draugr => 0.3,
294                },
295                Body::QuadrupedSmall(quadruped_small) => match quadruped_small.species {
296                    quadruped_small::Species::Pig => 0.5,
297                    quadruped_small::Species::Fox => 0.3,
298                    quadruped_small::Species::Sheep => 0.25,
299                    quadruped_small::Species::Boar => 0.1,
300                    quadruped_small::Species::Skunk => 0.4,
301                    quadruped_small::Species::Cat => 0.99,
302                    quadruped_small::Species::Batfox => 0.1,
303                    quadruped_small::Species::Raccoon => 0.4,
304                    quadruped_small::Species::Hyena => 0.1,
305                    quadruped_small::Species::Dog => 0.8,
306                    quadruped_small::Species::Rabbit | quadruped_small::Species::Jackalope => 0.25,
307                    quadruped_small::Species::Truffler => 0.08,
308                    quadruped_small::Species::Hare => 0.3,
309                    quadruped_small::Species::Goat => 0.3,
310                    quadruped_small::Species::Porcupine => 0.2,
311                    quadruped_small::Species::Turtle => 0.4,
312                    quadruped_small::Species::Beaver => 0.2,
313                    // FIXME: This is to balance for enemy rats in dungeons
314                    // Normal rats should probably always flee.
315                    quadruped_small::Species::Rat
316                    | quadruped_small::Species::TreantSapling
317                    | quadruped_small::Species::Holladon
318                    | quadruped_small::Species::MossySnail => 0.0,
319                    _ => 1.0,
320                },
321                Body::QuadrupedMedium(quadruped_medium) => match quadruped_medium.species {
322                    // T1
323                    quadruped_medium::Species::Antelope => 0.15,
324                    quadruped_medium::Species::Donkey => 0.05,
325                    quadruped_medium::Species::Horse => 0.15,
326                    quadruped_medium::Species::Mouflon => 0.1,
327                    quadruped_medium::Species::Zebra => 0.1,
328                    // T2
329                    // Should probably not have non-grouped, hostile animals flee until fleeing is
330                    // improved.
331                    quadruped_medium::Species::Barghest
332                    | quadruped_medium::Species::Bear
333                    | quadruped_medium::Species::Bristleback
334                    | quadruped_medium::Species::Bonerattler => 0.0,
335                    quadruped_medium::Species::Cattle => 0.1,
336                    quadruped_medium::Species::Frostfang => 0.07,
337                    quadruped_medium::Species::Grolgar => 0.0,
338                    quadruped_medium::Species::Highland => 0.05,
339                    quadruped_medium::Species::Kelpie => 0.35,
340                    quadruped_medium::Species::Lion => 0.0,
341                    quadruped_medium::Species::Moose => 0.15,
342                    quadruped_medium::Species::Panda => 0.35,
343                    quadruped_medium::Species::Saber
344                    | quadruped_medium::Species::Tarasque
345                    | quadruped_medium::Species::Tiger => 0.0,
346                    quadruped_medium::Species::Tuskram => 0.1,
347                    quadruped_medium::Species::Wolf => 0.2,
348                    quadruped_medium::Species::Yak => 0.09,
349                    // T3A
350                    quadruped_medium::Species::Akhlut
351                    | quadruped_medium::Species::Catoblepas
352                    | quadruped_medium::Species::ClaySteed
353                    | quadruped_medium::Species::Dreadhorn
354                    | quadruped_medium::Species::Hirdrasil
355                    | quadruped_medium::Species::Mammoth
356                    | quadruped_medium::Species::Ngoubou
357                    | quadruped_medium::Species::Roshwalr => 0.0,
358                    _ => 0.15,
359                },
360                Body::QuadrupedLow(quadruped_low) => match quadruped_low.species {
361                    // T1
362                    quadruped_low::Species::Pangolin => 0.3,
363                    // T2,
364                    quadruped_low::Species::Tortoise => 0.1,
365                    // There are a lot of hostile, solo entities.
366                    _ => 0.0,
367                },
368                Body::BipedSmall(biped_small) => match biped_small.species {
369                    biped_small::Species::Gnarling => 0.2,
370                    biped_small::Species::Mandragora => 0.1,
371                    biped_small::Species::Adlet => 0.2,
372                    biped_small::Species::Haniwa => 0.1,
373                    biped_small::Species::Sahagin => 0.1,
374                    biped_small::Species::Myrmidon => 0.0,
375                    biped_small::Species::TreasureEgg => 9.9,
376                    biped_small::Species::Husk
377                    | biped_small::Species::Boreal
378                    | biped_small::Species::IronDwarf
379                    | biped_small::Species::Flamekeeper
380                    | biped_small::Species::Irrwurz
381                    | biped_small::Species::GoblinThug
382                    | biped_small::Species::GoblinChucker
383                    | biped_small::Species::GoblinRuffian
384                    | biped_small::Species::GreenLegoom
385                    | biped_small::Species::OchreLegoom
386                    | biped_small::Species::PurpleLegoom
387                    | biped_small::Species::RedLegoom
388                    | biped_small::Species::ShamanicSpirit
389                    | biped_small::Species::Jiangshi
390                    | biped_small::Species::Bushly
391                    | biped_small::Species::Cactid
392                    | biped_small::Species::BloodmoonHeiress
393                    | biped_small::Species::Bloodservant
394                    | biped_small::Species::Harlequin
395                    | biped_small::Species::GnarlingChieftain => 0.0,
396
397                    _ => 0.5,
398                },
399                Body::BirdMedium(bird_medium) => match bird_medium.species {
400                    bird_medium::Species::SnowyOwl => 0.4,
401                    bird_medium::Species::HornedOwl => 0.4,
402                    bird_medium::Species::Duck => 0.6,
403                    bird_medium::Species::Cockatiel => 0.6,
404                    bird_medium::Species::Chicken => 0.5,
405                    bird_medium::Species::Bat => 0.1,
406                    bird_medium::Species::Penguin => 0.5,
407                    bird_medium::Species::Goose => 0.4,
408                    bird_medium::Species::Peacock => 0.3,
409                    bird_medium::Species::Eagle => 0.2,
410                    bird_medium::Species::Parrot => 0.8,
411                    bird_medium::Species::Crow => 0.4,
412                    bird_medium::Species::Dodo => 0.8,
413                    bird_medium::Species::Parakeet => 0.8,
414                    bird_medium::Species::Puffin => 0.8,
415                    bird_medium::Species::Toucan => 0.4,
416                    bird_medium::Species::BloodmoonBat => 0.0,
417                    bird_medium::Species::VampireBat => 0.0,
418                },
419                Body::BirdLarge(_) => 0.0,
420                Body::FishSmall(_) => 1.0,
421                Body::FishMedium(_) => 0.75,
422                Body::BipedLarge(_) => 0.0,
423                Body::Object(_) => 0.0,
424                Body::Item(_) => 0.0,
425                Body::Golem(_) => 0.0,
426                Body::Theropod(_) => 0.0,
427                Body::Ship(_) => 0.0,
428                Body::Dragon(_) => 0.0,
429                Body::Arthropod(_) => 0.0,
430                Body::Crustacean(_) => 0.0,
431                Body::Plugin(body) => body.flee_health(),
432            },
433            sight_dist: match body {
434                Body::BirdLarge(_) => 250.0,
435                Body::BipedLarge(biped_large) => match biped_large.species {
436                    biped_large::Species::Gigasfrost => 200.0,
437                    _ => 100.0,
438                },
439                _ => 40.0,
440            },
441            listen_dist: 30.0,
442            aggro_dist: match body {
443                Body::Humanoid(_) => Some(20.0),
444                _ => None, // Always aggressive if detected
445            },
446            idle_wander_factor: 1.0,
447            aggro_range_multiplier: 1.0,
448            should_stop_pursuing: match body {
449                Body::BirdLarge(_) => false,
450                Body::BipedLarge(biped_large) => {
451                    !matches!(biped_large.species, biped_large::Species::Gigasfrost)
452                },
453                Body::BirdMedium(bird_medium) => {
454                    // Skip stop_pursuing, as that function breaks when the health fraction is 0.0
455                    // (to keep aggro after death transform)
456                    !matches!(bird_medium.species, bird_medium::Species::BloodmoonBat)
457                },
458                _ => true,
459            },
460        }
461    }
462}
463
464impl Psyche {
465    /// The maximum distance that targets to attack might be detected by this
466    /// agent.
467    pub fn search_dist(&self) -> f32 {
468        self.sight_dist.max(self.listen_dist) * self.aggro_range_multiplier
469    }
470}
471
472#[derive(Clone, Debug)]
473/// Events that affect agent behavior from other entities/players/environment
474pub enum AgentEvent {
475    /// Engage in conversation with entity with Uid
476    Talk(Uid),
477    TradeInvite(Uid),
478    TradeAccepted(Uid),
479    FinishedTrade(TradeResult),
480    UpdatePendingTrade(
481        // This data structure is large so box it to keep AgentEvent small
482        Box<(
483            TradeId,
484            PendingTrade,
485            SitePrices,
486            [Option<ReducedInventory>; 2],
487        )>,
488    ),
489    ServerSound(Sound),
490    Hurt,
491    Dialogue(Uid, rtsim::Dialogue<true>),
492}
493
494#[derive(Copy, Clone, Debug)]
495pub struct Sound {
496    pub kind: SoundKind,
497    pub pos: Vec3<f32>,
498    pub vol: f32,
499    pub time: f64,
500}
501
502impl Sound {
503    pub fn new(kind: SoundKind, pos: Vec3<f32>, vol: f32, time: f64) -> Self {
504        Sound {
505            kind,
506            pos,
507            vol,
508            time,
509        }
510    }
511
512    #[must_use]
513    pub fn with_new_vol(mut self, new_vol: f32) -> Self {
514        self.vol = new_vol;
515
516        self
517    }
518}
519
520#[derive(Copy, Clone, Debug)]
521pub enum SoundKind {
522    Unknown,
523    Utterance(UtteranceKind, Body),
524    Movement,
525    Melee,
526    Projectile,
527    Explosion,
528    Beam,
529    Shockwave,
530    Mine,
531    Trap,
532}
533
534#[derive(Clone, Copy, Debug)]
535pub struct Target {
536    pub target: EcsEntity,
537    /// Whether the target is hostile
538    pub hostile: bool,
539    /// The time at which the target was selected
540    pub selected_at: f64,
541    /// Whether the target has come close enough to trigger aggro.
542    pub aggro_on: bool,
543    pub last_known_pos: Option<Vec3<f32>>,
544}
545
546impl Target {
547    pub fn new(
548        target: EcsEntity,
549        hostile: bool,
550        selected_at: f64,
551        aggro_on: bool,
552        last_known_pos: Option<Vec3<f32>>,
553    ) -> Self {
554        Self {
555            target,
556            hostile,
557            selected_at,
558            aggro_on,
559            last_known_pos,
560        }
561    }
562}
563
564#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, EnumIter)]
565pub enum TimerAction {
566    Interact,
567}
568
569/// A time used for managing agent-related timeouts. The timer is designed to
570/// keep track of the start of any number of previous actions. However,
571/// starting/progressing an action will end previous actions. Therefore, the
572/// timer should be used for actions that are mutually-exclusive.
573#[derive(Clone, Debug)]
574pub struct Timer {
575    action_starts: Vec<Option<f64>>,
576    last_action: Option<TimerAction>,
577}
578
579impl Default for Timer {
580    fn default() -> Self {
581        Self {
582            action_starts: TimerAction::iter().map(|_| None).collect(),
583            last_action: None,
584        }
585    }
586}
587
588impl Timer {
589    fn idx_for(action: TimerAction) -> usize {
590        TimerAction::iter()
591            .enumerate()
592            .find(|(_, a)| a == &action)
593            .unwrap()
594            .0 // Can't fail, EnumIter is exhaustive
595    }
596
597    /// Reset the timer for the given action, returning true if the timer was
598    /// not already reset.
599    pub fn reset(&mut self, action: TimerAction) -> bool {
600        self.action_starts[Self::idx_for(action)].take().is_some()
601    }
602
603    /// Start the timer for the given action, even if it was already started.
604    pub fn start(&mut self, time: f64, action: TimerAction) {
605        self.action_starts[Self::idx_for(action)] = Some(time);
606        self.last_action = Some(action);
607    }
608
609    /// Continue timing the given action, starting it if it was not already
610    /// started.
611    pub fn progress(&mut self, time: f64, action: TimerAction) {
612        if self.last_action != Some(action) {
613            self.start(time, action);
614        }
615    }
616
617    /// Return the time that the given action was last performed at.
618    pub fn time_of_last(&self, action: TimerAction) -> Option<f64> {
619        self.action_starts[Self::idx_for(action)]
620    }
621
622    /// Return `true` if the time since the action was last started exceeds the
623    /// given timeout.
624    pub fn time_since_exceeds(&self, time: f64, action: TimerAction, timeout: f64) -> bool {
625        self.time_of_last(action)
626            .is_none_or(|last_time| (time - last_time).max(0.0) > timeout)
627    }
628
629    /// Return `true` while the time since the action was last started is less
630    /// than the given period. Once the time has elapsed, reset the timer.
631    pub fn timeout_elapsed(
632        &mut self,
633        time: f64,
634        action: TimerAction,
635        timeout: f64,
636    ) -> Option<bool> {
637        if self.time_since_exceeds(time, action, timeout) {
638            Some(self.reset(action))
639        } else {
640            self.progress(time, action);
641            None
642        }
643    }
644}
645
646/// For use with the builder pattern <https://doc.rust-lang.org/1.0.0/style/ownership/builders.html>
647#[derive(Clone, Debug)]
648pub struct Agent {
649    pub rtsim_controller: RtSimController,
650    pub patrol_origin: Option<Vec3<f32>>,
651    pub target: Option<Target>,
652    pub chaser: Chaser,
653    pub behavior: Behavior,
654    pub psyche: Psyche,
655    pub inbox: VecDeque<AgentEvent>,
656    pub combat_state: ActionState,
657    pub behavior_state: ActionState,
658    pub timer: Timer,
659    pub bearing: Vec2<f32>,
660    pub sounds_heard: Vec<Sound>,
661    pub multi_pid_controllers: Option<PidControllers<16>>,
662    /// Position from which to flee. Intended to be the agent's position plus a
663    /// random position offset, to be used when a random flee direction is
664    /// required and reset each time the flee timer is reset.
665    pub flee_from_pos: Option<Pos>,
666    pub awareness: Awareness,
667    pub stay_pos: Option<Pos>,
668    /// Inputs sent up to rtsim
669    pub rtsim_outbox: Option<VecDeque<NpcInput>>,
670}
671
672#[derive(Serialize, Deserialize)]
673pub struct SharedChaser {
674    pub nodes: Vec<Vec3<f32>>,
675    pub goal: Option<Vec3<f32>>,
676}
677
678#[derive(Clone, Debug)]
679/// Always clamped between `0.0` and `1.0`.
680pub struct Awareness {
681    level: f32,
682    reached: bool,
683}
684impl fmt::Display for Awareness {
685    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:.2}", self.level) }
686}
687impl Awareness {
688    const ALERT: f32 = 1.0;
689    const HIGH: f32 = 0.6;
690    const LOW: f32 = 0.1;
691    const MEDIUM: f32 = 0.3;
692    const UNAWARE: f32 = 0.0;
693
694    pub fn new(level: f32) -> Self {
695        Self {
696            level: level.clamp(Self::UNAWARE, Self::ALERT),
697            reached: false,
698        }
699    }
700
701    /// The level of awareness as a decimal.
702    pub fn level(&self) -> f32 { self.level }
703
704    /// The level of awareness in English. To see if awareness has been fully
705    /// reached, use `self.reached()`.
706    pub fn state(&self) -> AwarenessState {
707        if self.level == Self::ALERT {
708            AwarenessState::Alert
709        } else if self.level.is_between(Self::HIGH, Self::ALERT) {
710            AwarenessState::High
711        } else if self.level.is_between(Self::MEDIUM, Self::HIGH) {
712            AwarenessState::Medium
713        } else if self.level.is_between(Self::LOW, Self::MEDIUM) {
714            AwarenessState::Low
715        } else {
716            AwarenessState::Unaware
717        }
718    }
719
720    /// Awareness was reached at some point and has not been reset.
721    pub fn reached(&self) -> bool { self.reached }
722
723    pub fn change_by(&mut self, amount: f32) {
724        self.level = (self.level + amount).clamp(Self::UNAWARE, Self::ALERT);
725
726        if self.state() == AwarenessState::Alert {
727            self.reached = true;
728        } else if self.state() == AwarenessState::Unaware {
729            self.reached = false;
730        }
731    }
732
733    pub fn set_maximally_aware(&mut self) {
734        self.reached = true;
735        self.level = Self::ALERT;
736    }
737}
738
739#[derive(Clone, Debug, PartialOrd, PartialEq, Eq)]
740pub enum AwarenessState {
741    Unaware = 0,
742    Low = 1,
743    Medium = 2,
744    High = 3,
745    Alert = 4,
746}
747
748/// State persistence object for the behavior tree
749/// Allows for state to be stored between subsequent, sequential calls of a
750/// single action node. If the executed action node changes between ticks, then
751/// the state should be considered lost.
752#[derive(Clone, Debug, Default)]
753pub struct ActionState {
754    pub timers: [f32; ACTIONSTATE_NUMBER_OF_CONCURRENT_TIMERS],
755    pub counters: [f32; ACTIONSTATE_NUMBER_OF_CONCURRENT_COUNTERS],
756    pub conditions: [bool; ACTIONSTATE_NUMBER_OF_CONCURRENT_CONDITIONS],
757    pub int_counters: [u8; ACTIONSTATE_NUMBER_OF_CONCURRENT_INT_COUNTERS],
758    pub positions: [Option<Vec3<f32>>; ACTIONSTATE_NUMBER_OF_CONCURRENT_POSITIONS],
759    pub initialized: bool,
760}
761
762impl Agent {
763    /// Instantiates agent from body using the body's psyche
764    pub fn from_body(body: &Body) -> Self {
765        Agent {
766            rtsim_controller: RtSimController::default(),
767            patrol_origin: None,
768            target: None,
769            chaser: Chaser::default(),
770            behavior: Behavior::default(),
771            psyche: Psyche::from(body),
772            inbox: VecDeque::new(),
773            combat_state: ActionState::default(),
774            behavior_state: ActionState::default(),
775            timer: Timer::default(),
776            bearing: Vec2::zero(),
777            sounds_heard: Vec::new(),
778            multi_pid_controllers: None,
779            flee_from_pos: None,
780            stay_pos: None,
781            awareness: Awareness::new(0.0),
782            rtsim_outbox: None,
783        }
784    }
785
786    #[must_use]
787    pub fn with_patrol_origin(mut self, origin: Vec3<f32>) -> Self {
788        self.patrol_origin = Some(origin);
789        self
790    }
791
792    #[must_use]
793    pub fn with_behavior(mut self, behavior: Behavior) -> Self {
794        self.behavior = behavior;
795        self
796    }
797
798    #[must_use]
799    pub fn with_no_flee_if(mut self, condition: bool) -> Self {
800        if condition {
801            self.psyche.flee_health = 0.0;
802        }
803        self
804    }
805
806    pub fn set_no_flee(&mut self) { self.psyche.flee_health = 0.0; }
807
808    // FIXME: Only one of *three* things in this method sets a location.
809    #[must_use]
810    pub fn with_destination(mut self, pos: Vec3<f32>) -> Self {
811        self.psyche.flee_health = 0.0;
812        self.rtsim_controller = RtSimController::with_destination(pos);
813        self.behavior.allow(BehaviorCapability::SPEAK);
814        self
815    }
816
817    #[must_use]
818    pub fn with_idle_wander_factor(mut self, idle_wander_factor: f32) -> Self {
819        self.psyche.idle_wander_factor = idle_wander_factor;
820        self
821    }
822
823    pub fn with_aggro_range_multiplier(mut self, aggro_range_multiplier: f32) -> Self {
824        self.psyche.aggro_range_multiplier = aggro_range_multiplier;
825        self
826    }
827
828    #[must_use]
829    pub fn with_altitude_pid_controller(mut self, mpid: PidControllers<16>) -> Self {
830        self.multi_pid_controllers = Some(mpid);
831        self
832    }
833
834    /// Makes agent aggressive without warning
835    #[must_use]
836    pub fn with_aggro_no_warn(mut self) -> Self {
837        self.psyche.aggro_dist = None;
838        self
839    }
840
841    pub fn forget_old_sounds(&mut self, time: f64) {
842        if !self.sounds_heard.is_empty() {
843            // Keep (retain) only newer sounds
844            self.sounds_heard
845                .retain(|&sound| time - sound.time <= SECONDS_BEFORE_FORGET_SOUNDS);
846        }
847    }
848
849    pub fn allowed_to_speak(&self) -> bool { self.behavior.can(BehaviorCapability::SPEAK) }
850}
851
852impl Component for Agent {
853    type Storage = specs::DenseVecStorage<Self>;
854}
855
856#[cfg(test)]
857mod tests {
858    use super::{Agent, Behavior, BehaviorCapability, BehaviorState, Body, humanoid};
859
860    /// Test to verify that Behavior is working correctly at its most basic
861    /// usages
862    #[test]
863    pub fn behavior_basic() {
864        let mut b = Behavior::default();
865        // test capabilities
866        assert!(!b.can(BehaviorCapability::SPEAK));
867        b.allow(BehaviorCapability::SPEAK);
868        assert!(b.can(BehaviorCapability::SPEAK));
869        b.deny(BehaviorCapability::SPEAK);
870        assert!(!b.can(BehaviorCapability::SPEAK));
871        // test states
872        assert!(!b.is(BehaviorState::TRADING));
873        b.set(BehaviorState::TRADING);
874        assert!(b.is(BehaviorState::TRADING));
875        b.unset(BehaviorState::TRADING);
876        assert!(!b.is(BehaviorState::TRADING));
877        // test `from`
878        let b = Behavior::from(BehaviorCapability::SPEAK);
879        assert!(b.can(BehaviorCapability::SPEAK));
880    }
881
882    /// Makes agent flee
883    #[test]
884    pub fn enable_flee() {
885        let body = Body::Humanoid(humanoid::Body::random());
886        let mut agent = Agent::from_body(&body);
887
888        agent.psyche.flee_health = 1.0;
889        agent = agent.with_no_flee_if(false);
890        assert_eq!(agent.psyche.flee_health, 1.0);
891    }
892
893    /// Makes agent not flee
894    #[test]
895    pub fn set_no_flee() {
896        let body = Body::Humanoid(humanoid::Body::random());
897        let mut agent = Agent::from_body(&body);
898
899        agent.psyche.flee_health = 1.0;
900        agent.set_no_flee();
901        assert_eq!(agent.psyche.flee_health, 0.0);
902    }
903
904    #[test]
905    pub fn with_aggro_no_warn() {
906        let body = Body::Humanoid(humanoid::Body::random());
907        let mut agent = Agent::from_body(&body);
908
909        agent.psyche.aggro_dist = Some(1.0);
910        agent = agent.with_aggro_no_warn();
911        assert_eq!(agent.psyche.aggro_dist, None);
912    }
913}
914
915/// PID controllers (Proportional–integral–derivative controllers) are used for
916/// automatically adapting nonlinear controls (like buoyancy for balloons)
917/// and for damping out oscillations in control feedback loops (like vehicle
918/// cruise control). PID controllers can monitor an error signal between a
919/// setpoint and a process variable, and use that error to adjust a control
920/// variable. A PID controller can only control one variable at a time.
921#[derive(Clone)]
922pub struct PidController<F: Fn(f32, f32) -> f32, const NUM_SAMPLES: usize> {
923    /// The coefficient of the proportional term
924    pub kp: f32,
925    /// The coefficient of the integral term
926    pub ki: f32,
927    /// The coefficient of the derivative term
928    pub kd: f32,
929    /// The setpoint that the process has as its goal
930    pub sp: f32,
931    /// A ring buffer of the last NUM_SAMPLES measured process variables
932    pv_samples: [(f64, f32); NUM_SAMPLES],
933    /// The index into the ring buffer of process variables
934    pv_idx: usize,
935    /// The total integral error
936    integral_error: f64,
937    /// The error function, to change how the difference between the setpoint
938    /// and process variables are calculated
939    e: F,
940}
941
942impl<F: Fn(f32, f32) -> f32, const NUM_SAMPLES: usize> fmt::Debug
943    for PidController<F, NUM_SAMPLES>
944{
945    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
946        f.debug_struct("PidController")
947            .field("kp", &self.kp)
948            .field("ki", &self.ki)
949            .field("kd", &self.kd)
950            .field("sp", &self.sp)
951            .field("pv_samples", &self.pv_samples)
952            .field("pv_idx", &self.pv_idx)
953            .finish()
954    }
955}
956
957impl<F: Fn(f32, f32) -> f32, const NUM_SAMPLES: usize> PidController<F, NUM_SAMPLES> {
958    /// Constructs a PidController with the specified weights, setpoint,
959    /// starting time, and error function
960    pub fn new(kp: f32, ki: f32, kd: f32, sp: f32, time: f64, e: F) -> Self {
961        Self {
962            kp,
963            ki,
964            kd,
965            sp,
966            pv_samples: [(time, sp); NUM_SAMPLES],
967            pv_idx: 0,
968            integral_error: 0.0,
969            e,
970        }
971    }
972
973    /// Adds a measurement of the process variable to the ringbuffer
974    pub fn add_measurement(&mut self, time: f64, pv: f32) {
975        self.pv_idx += 1;
976        self.pv_idx %= NUM_SAMPLES;
977        self.pv_samples[self.pv_idx] = (time, pv);
978        self.update_integral_err();
979    }
980
981    /// The amount to set the control variable to is a weighed sum of the
982    /// proportional error, the integral error, and the derivative error.
983    /// <https://en.wikipedia.org/wiki/PID_controller#Mathematical_form>
984    pub fn calc_err(&self) -> f32 {
985        self.kp * self.proportional_err()
986            + self.ki * self.integral_err()
987            + self.kd * self.derivative_err()
988    }
989
990    /// The proportional error is the error function applied to the set point
991    /// and the most recent process variable measurement
992    pub fn proportional_err(&self) -> f32 { (self.e)(self.sp, self.pv_samples[self.pv_idx].1) }
993
994    /// The integral error is the error function integrated over all previous
995    /// values, updated per point. The trapezoid rule for numerical integration
996    /// was chosen because it's fairly easy to calculate and sufficiently
997    /// accurate. <https://en.wikipedia.org/wiki/Trapezoidal_rule#Uniform_grid>
998    pub fn integral_err(&self) -> f32 { self.integral_error as f32 }
999
1000    fn update_integral_err(&mut self) {
1001        let f = |x| (self.e)(self.sp, x) as f64;
1002        let (a, x0) = self.pv_samples[(self.pv_idx + NUM_SAMPLES - 1) % NUM_SAMPLES];
1003        let (b, x1) = self.pv_samples[self.pv_idx];
1004        let dx = b - a;
1005        // Discard updates with too long between them, likely caused by either
1006        // initialization or latency, since they're likely to be spurious
1007        if dx < 5.0 {
1008            self.integral_error += dx * (f(x1) + f(x0)) / 2.0;
1009        }
1010    }
1011
1012    /// The integral error accumulates over time, and can get to the point where
1013    /// the output of the controller is saturated. This is called integral
1014    /// windup, and it commonly occurs when the controller setpoint is
1015    /// changed. To limit the integral error signal, this function can be
1016    /// called with a fn/closure that can modify the integral_error value.
1017    pub fn limit_integral_windup<W>(&mut self, f: W)
1018    where
1019        W: Fn(&mut f64),
1020    {
1021        f(&mut self.integral_error);
1022    }
1023
1024    /// The derivative error is the numerical derivative of the error function
1025    /// based on the most recent 2 samples. Using more than 2 samples might
1026    /// improve the accuracy of the estimate of the derivative, but it would be
1027    /// an estimate of the derivative error further in the past.
1028    /// <https://en.wikipedia.org/wiki/Numerical_differentiation#Finite_differences>
1029    pub fn derivative_err(&self) -> f32 {
1030        let f = |x| (self.e)(self.sp, x);
1031        let (a, x0) = self.pv_samples[(self.pv_idx + NUM_SAMPLES - 1) % NUM_SAMPLES];
1032        let (b, x1) = self.pv_samples[self.pv_idx];
1033        let h = b - a;
1034        if h == 0.0 {
1035            0.0
1036        } else {
1037            (f(x1) - f(x0)) / h as f32
1038        }
1039    }
1040}
1041
1042/// The desired flight behavior when an entity is approaching a target position.
1043#[derive(Copy, Clone, Debug, PartialEq)]
1044pub enum FlightMode {
1045    /// The agent should cause the entity to decelerate and stop at the target
1046    /// position.
1047    Braking(BrakingMode),
1048    /// The agent should cause the entity to fly to and through the target
1049    /// position without slowing.
1050    FlyThrough,
1051}
1052
1053/// When FlightMode is Braking, the agent can use different braking modes to
1054/// control the amount of overshoot and oscillation.
1055#[derive(Default, Copy, Clone, Debug, PartialEq)]
1056pub enum BrakingMode {
1057    /// Oscillation around the target position is acceptable, with slow damping.
1058    /// This mode is useful for when the entity is not expected to fully stop at
1059    /// the target position, and arrival near the target position is more
1060    /// important than precision.
1061    #[default]
1062    Normal,
1063    /// Prefer faster damping of position error, reducing overshoot and
1064    /// oscillation around the target position. This mode is useful for when
1065    /// the entity is expected to fully stop at the target and precision is
1066    /// most important.
1067    Precise,
1068}
1069
1070/// A Mulit-PID controller that can control the acceleration/velocity in one or
1071/// all three axes.
1072#[derive(Clone)]
1073pub struct PidControllers<const NUM_SAMPLES: usize> {
1074    pub mode: FlightMode,
1075    /// This is ignored unless the mode FixedDirection.
1076    pub x_controller: Option<PidController<fn(f32, f32) -> f32, NUM_SAMPLES>>,
1077    pub y_controller: Option<PidController<fn(f32, f32) -> f32, NUM_SAMPLES>>,
1078    pub z_controller: Option<PidController<fn(f32, f32) -> f32, NUM_SAMPLES>>,
1079}
1080
1081impl<const NUM_SAMPLES: usize> fmt::Debug for PidControllers<NUM_SAMPLES> {
1082    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1083        f.debug_struct("PidControllers")
1084            .field("mode", &self.mode)
1085            .field("x_controller", &self.x_controller)
1086            .field("y_controller", &self.y_controller)
1087            .field("z_controller", &self.z_controller)
1088            .finish()
1089    }
1090}
1091
1092/// A collection of PidControllers, one for each 3D axis.
1093/// Airships use either one or three PidControllers, depending on the mode
1094/// (see action_nodes.rs for details of Airship modes).
1095impl<const NUM_SAMPLES: usize> PidControllers<NUM_SAMPLES> {
1096    pub fn new(mode: FlightMode) -> Self {
1097        Self {
1098            mode,
1099            x_controller: None,
1100            y_controller: None,
1101            z_controller: None,
1102        }
1103    }
1104
1105    pub fn new_multi_pid_controllers(mode: FlightMode, travel_to: Vec3<f32>) -> PidControllers<16> {
1106        let mut mpid = PidControllers::new(mode);
1107        // FixedDirection requires x and y and z controllers
1108        // PureZ requires only z controller
1109        if matches!(mode, FlightMode::Braking(_)) {
1110            // Add x_controller && y_controller
1111            let (kp, ki, kd) = pid_coefficients_for_mode(mode, false);
1112            mpid.x_controller = Some(PidController::new(
1113                kp,
1114                ki,
1115                kd,
1116                travel_to.x,
1117                0.0,
1118                |sp, pv| sp - pv,
1119            ));
1120            mpid.y_controller = Some(PidController::new(
1121                kp,
1122                ki,
1123                kd,
1124                travel_to.y,
1125                0.0,
1126                |sp, pv| sp - pv,
1127            ));
1128        }
1129        // Add z_controller
1130        let (kp, ki, kd) = pid_coefficients_for_mode(mode, true);
1131        mpid.z_controller = Some(PidController::new(
1132            kp,
1133            ki,
1134            kd,
1135            travel_to.z,
1136            0.0,
1137            |sp, pv| sp - pv,
1138        ));
1139        mpid
1140    }
1141
1142    #[inline(always)]
1143    pub fn add_x_measurement(&mut self, time: f64, pv: f32) {
1144        if let Some(controller) = &mut self.x_controller {
1145            controller.add_measurement(time, pv);
1146        }
1147    }
1148
1149    #[inline(always)]
1150    pub fn add_y_measurement(&mut self, time: f64, pv: f32) {
1151        if let Some(controller) = &mut self.y_controller {
1152            controller.add_measurement(time, pv);
1153        }
1154    }
1155
1156    #[inline(always)]
1157    pub fn add_z_measurement(&mut self, time: f64, pv: f32) {
1158        if let Some(controller) = &mut self.z_controller {
1159            controller.add_measurement(time, pv);
1160        }
1161    }
1162
1163    #[inline(always)]
1164    pub fn add_measurement(&mut self, time: f64, pos: Vec3<f32>) {
1165        if let Some(controller) = &mut self.x_controller {
1166            controller.add_measurement(time, pos.x);
1167        }
1168        if let Some(controller) = &mut self.y_controller {
1169            controller.add_measurement(time, pos.y);
1170        }
1171        if let Some(controller) = &mut self.z_controller {
1172            controller.add_measurement(time, pos.z);
1173        }
1174    }
1175
1176    #[inline(always)]
1177    pub fn calc_err_x(&self) -> Option<f32> {
1178        self.x_controller
1179            .as_ref()
1180            .map(|controller| controller.calc_err())
1181    }
1182
1183    #[inline(always)]
1184    pub fn calc_err_y(&self) -> Option<f32> {
1185        self.y_controller
1186            .as_ref()
1187            .map(|controller| controller.calc_err())
1188    }
1189
1190    #[inline(always)]
1191    pub fn calc_err_z(&self) -> Option<f32> {
1192        self.z_controller
1193            .as_ref()
1194            .map(|controller| controller.calc_err())
1195    }
1196
1197    #[inline(always)]
1198    pub fn limit_windup_x<F>(&mut self, f: F)
1199    where
1200        F: Fn(&mut f64),
1201    {
1202        if let Some(controller) = &mut self.x_controller {
1203            controller.limit_integral_windup(f);
1204        }
1205    }
1206
1207    #[inline(always)]
1208    pub fn limit_windup_y<F>(&mut self, f: F)
1209    where
1210        F: Fn(&mut f64),
1211    {
1212        if let Some(controller) = &mut self.y_controller {
1213            controller.limit_integral_windup(f);
1214        }
1215    }
1216
1217    #[inline(always)]
1218    pub fn limit_windup_z<F>(&mut self, f: F)
1219    where
1220        F: Fn(&mut f64),
1221    {
1222        if let Some(controller) = &mut self.z_controller {
1223            controller.limit_integral_windup(f);
1224        }
1225    }
1226}
1227
1228/// Get the PID coefficients associated with some Body, since it will likely
1229/// need to be tuned differently for each body type
1230pub fn pid_coefficients(body: &Body) -> Option<(f32, f32, f32)> {
1231    // A pure-proportional controller is { kp: 1.0, ki: 0.0, kd: 0.0 }
1232    match body {
1233        Body::Ship(ship::Body::AirBalloon) => {
1234            let kp = 1.0;
1235            let ki = 0.1;
1236            let kd = 0.8;
1237            Some((kp, ki, kd))
1238        },
1239        _ => None,
1240    }
1241}
1242
1243/// Get the PID coefficients (for the airship, for now) by PID modes.
1244pub fn pid_coefficients_for_mode(mode: FlightMode, z_axis: bool) -> (f32, f32, f32) {
1245    match mode {
1246        FlightMode::FlyThrough => {
1247            if z_axis {
1248                (1.0, 0.4, 0.25)
1249            } else {
1250                (0.0, 0.0, 0.0)
1251            }
1252        },
1253        FlightMode::Braking(braking_mode) => match braking_mode {
1254            BrakingMode::Normal => (1.0, 0.3, 0.4),
1255            BrakingMode::Precise => (0.9, 0.3, 1.0),
1256        },
1257    }
1258}