Skip to main content

veloren_server_agent/
util.rs

1use crate::data::{AbilityData, ActionMode, AgentData, AttackData, Path, ReadData, TargetData};
2use common::{
3    comp::{
4        Agent, Alignment, Body, Controller, InputKind, Pos, Scale,
5        ability::AbilityInput,
6        agent::Psyche,
7        buff::BuffKind,
8        item::{ItemDesc, ItemTag},
9    },
10    terrain::Block,
11    uid::Uid,
12    util::Dir,
13    vol::ReadVol,
14};
15use core::f32::consts::PI;
16use rand::RngExt;
17use specs::Entity as EcsEntity;
18use vek::*;
19
20pub fn is_dead_or_invulnerable(entity: EcsEntity, read_data: &ReadData) -> bool {
21    is_dead(entity, read_data) || is_invulnerable(entity, read_data)
22}
23
24pub fn is_dead(entity: EcsEntity, read_data: &ReadData) -> bool {
25    let health = read_data.healths.get(entity);
26    health.is_some_and(|a| a.is_dead)
27}
28
29// FIXME: The logic that is used in this function and throughout the code
30// shouldn't be used to mean that a character is in a safezone.
31pub fn is_invulnerable(entity: EcsEntity, read_data: &ReadData) -> bool {
32    let buffs = read_data.buffs.get(entity);
33
34    buffs.is_some_and(|b| b.kinds[BuffKind::Invulnerability].is_some())
35}
36
37pub fn is_steering(entity: EcsEntity, read_data: &ReadData) -> bool {
38    read_data
39        .is_volume_riders
40        .get(entity)
41        .is_some_and(|r| r.is_steering_entity())
42}
43
44/// Gets alignment of owner if alignment given is `Owned`.
45/// Returns original alignment if not owned.
46pub fn try_owner_alignment<'a>(
47    alignment: Option<&'a Alignment>,
48    read_data: &'a ReadData,
49) -> Option<&'a Alignment> {
50    if let Some(&Alignment::Owned(owner_uid)) = alignment
51        && let Some(owner) = get_entity_by_id(owner_uid, read_data)
52    {
53        return read_data.alignments.get(owner);
54    }
55    alignment
56}
57
58pub fn get_entity_by_id(uid: Uid, read_data: &ReadData) -> Option<EcsEntity> {
59    read_data.id_maps.uid_entity(uid)
60}
61
62/// Calculates whether the agent should continue chase or let the target escape.
63///
64/// Will return true when score of letting target escape is higher then the
65/// score of continuing the pursue, false otherwise.
66pub fn stop_pursuing(
67    dist_to_target_sqrd: f32,
68    dist_to_home_sqrd: f32,
69    own_health_fraction: f32,
70    target_health_fraction: f32,
71    dur_since_last_attacked: f64,
72    psyche: &Psyche,
73) -> bool {
74    psyche.should_stop_pursuing
75        && should_let_target_escape(
76            dist_to_home_sqrd,
77            dur_since_last_attacked,
78            own_health_fraction,
79        ) > should_continue_to_pursue(dist_to_target_sqrd, psyche, target_health_fraction)
80}
81
82/// Scores the benefit of continuing the pursue in value from 0 to infinity.
83fn should_continue_to_pursue(
84    dist_to_target_sqrd: f32,
85    psyche: &Psyche,
86    target_health_fraction: f32,
87) -> f32 {
88    let aggression_score = (1.0 / psyche.flee_health.max(0.25))
89        * psyche.aggro_dist.unwrap_or(psyche.sight_dist)
90        * psyche.sight_dist;
91
92    (100.0 * aggression_score) / (dist_to_target_sqrd * target_health_fraction)
93}
94
95/// Scores the benefit of letting the target escape in a value from 0 to
96/// infinity.
97fn should_let_target_escape(
98    dist_to_home_sqrd: f32,
99    dur_since_last_attacked: f64,
100    own_health_fraction: f32,
101) -> f32 {
102    (dist_to_home_sqrd / own_health_fraction) * dur_since_last_attacked as f32 * 0.005
103}
104
105pub fn entity_looks_like_cultist(entity: EcsEntity, read_data: &ReadData) -> bool {
106    let number_of_cultist_items_equipped = read_data.inventories.get(entity).map_or(0, |inv| {
107        inv.equipped_items()
108            .filter(|item| item.tags().contains(&ItemTag::Cultist))
109            .count()
110    });
111
112    number_of_cultist_items_equipped > 2
113}
114
115// FIXME: `Alignment::Npc` doesn't necessarily mean villager.
116pub fn is_villager(alignment: Option<&Alignment>) -> bool {
117    alignment.is_some_and(|alignment| matches!(alignment, Alignment::Npc))
118}
119
120pub fn is_village_guard(agent: &Agent) -> bool {
121    agent.mark == Some(common::comp::agent::Mark::Guard)
122}
123
124pub fn are_our_owners_hostile(
125    our_alignment: Option<&Alignment>,
126    their_alignment: Option<&Alignment>,
127    read_data: &ReadData,
128) -> bool {
129    try_owner_alignment(our_alignment, read_data).is_some_and(|our_owners_alignment| {
130        try_owner_alignment(their_alignment, read_data).is_some_and(|their_owners_alignment| {
131            our_owners_alignment.hostile_towards(*their_owners_alignment)
132        })
133    })
134}
135
136pub fn entities_have_line_of_sight(
137    pos: &Pos,
138    body: Option<&Body>,
139    scale: f32,
140    other_pos: &Pos,
141    other_body: Option<&Body>,
142    other_scale: Option<&Scale>,
143    read_data: &ReadData,
144) -> bool {
145    let get_eye_pos = |pos: &Pos, body: Option<&Body>, scale: f32| {
146        let eye_offset = body.map_or(0.0, |b| b.eye_height(scale));
147
148        Pos(pos.0.with_z(pos.0.z + eye_offset))
149    };
150    let eye_pos = get_eye_pos(pos, body, scale);
151    let other_eye_pos = get_eye_pos(other_pos, other_body, other_scale.map_or(1.0, |s| s.0));
152
153    positions_have_line_of_sight(&eye_pos, &other_eye_pos, read_data)
154}
155
156pub fn positions_have_line_of_sight(pos_a: &Pos, pos_b: &Pos, read_data: &ReadData) -> bool {
157    let dist_sqrd = pos_b.0.distance_squared(pos_a.0);
158
159    read_data
160        .terrain
161        .ray(pos_a.0, pos_b.0)
162        .until(Block::is_opaque)
163        .cast()
164        .0
165        .powi(2)
166        >= (dist_sqrd - 0.01)
167}
168
169pub fn is_dressed_as_cultist(entity: EcsEntity, read_data: &ReadData) -> bool {
170    read_data.inventories.get(entity).is_some_and(|inventory| {
171        inventory
172            .equipped_items()
173            .filter(|item| item.tags().contains(&ItemTag::Cultist))
174            .count()
175            > 2
176    })
177}
178
179pub fn is_dressed_as_witch(entity: EcsEntity, read_data: &ReadData) -> bool {
180    read_data.inventories.get(entity).is_some_and(|inventory| {
181        inventory
182            .equipped_items()
183            .filter(|item| item.tags().contains(&ItemTag::Witch))
184            .count()
185            > 3
186    })
187}
188
189pub fn is_dressed_as_pirate(entity: EcsEntity, read_data: &ReadData) -> bool {
190    read_data.inventories.get(entity).is_some_and(|inventory| {
191        inventory
192            .equipped_items()
193            .filter(|item| item.tags().contains(&ItemTag::Pirate))
194            .count()
195            > 4
196    })
197}
198
199pub fn get_attacker(entity: EcsEntity, read_data: &ReadData) -> Option<EcsEntity> {
200    read_data
201        .healths
202        .get(entity)
203        .filter(|health| health.last_change.amount < 0.0)
204        .and_then(|health| health.last_change.damage_by())
205        .and_then(|damage_contributor| get_entity_by_id(damage_contributor.uid(), read_data))
206}
207
208impl AgentData<'_> {
209    pub fn has_buff(&self, read_data: &ReadData, buff: BuffKind) -> bool {
210        read_data
211            .buffs
212            .get(*self.entity)
213            .is_some_and(|b| b.kinds[buff].is_some())
214    }
215
216    pub fn extract_ability(&self, input: AbilityInput) -> Option<AbilityData> {
217        AbilityData::from_ability(
218            &self
219                .active_abilities
220                .activate_ability(
221                    input,
222                    Some(self.inventory),
223                    self.skill_set,
224                    self.body,
225                    Some(self.char_state),
226                    self.stance,
227                    self.combo,
228                    self.stats,
229                    self.buffs,
230                )
231                .map_or(Default::default(), |a| a.0),
232        )
233    }
234}
235
236// Probably works best for melee (or maybe only for melee considering its
237// reliance on blocking?)
238/// Handles whether an agent should attack and how the agent moves around.
239/// Returns whether the agent should attack (so that individual tactics can
240/// determine what specific attack to use)
241pub fn handle_attack_aggression(
242    agent_data: &AgentData,
243    agent: &mut Agent,
244    controller: &mut Controller,
245    attack_data: &AttackData,
246    tgt_data: &TargetData,
247    read_data: &ReadData,
248    rng: &mut impl RngExt,
249    timer_pos_timeout_index: usize,
250    timer_guarded_cycle_index: usize,
251    fcounter_guarded_timer_index: usize,
252    icounter_action_mode_index: usize,
253    condition_guarded_defend_index: usize,
254    condition_rolling_breakthrough_index: usize,
255    position_guarded_cover_index: usize,
256    position_flee_index: usize,
257) -> bool {
258    if let Some(health) = agent_data.health {
259        agent.combat_state.int_counters[icounter_action_mode_index] = if health.fraction() < 0.1 {
260            agent.combat_state.positions[position_guarded_cover_index] = None;
261            ActionMode::Fleeing as u8
262        } else if health.fraction() < 0.9 {
263            agent.combat_state.positions[position_flee_index] = None;
264            ActionMode::Guarded as u8
265        } else {
266            agent.combat_state.positions[position_guarded_cover_index] = None;
267            agent.combat_state.positions[position_flee_index] = None;
268            ActionMode::Reckless as u8
269        };
270    }
271
272    // If agent has not moved, assume agent was unable to move and reset attempted
273    // path positions if occurs for too long
274    if agent_data.vel.0.magnitude_squared() < 1_f32.powi(2) {
275        agent.combat_state.timers[timer_pos_timeout_index] += read_data.dt.0;
276    } else {
277        agent.combat_state.timers[timer_pos_timeout_index] = 0.0;
278    }
279
280    if agent.combat_state.timers[timer_pos_timeout_index] > 2.0 {
281        agent.combat_state.positions[position_guarded_cover_index] = None;
282        agent.combat_state.positions[position_flee_index] = None;
283        agent.combat_state.timers[timer_pos_timeout_index] = 0.0;
284    }
285
286    match ActionMode::from_u8(agent.combat_state.int_counters[icounter_action_mode_index]) {
287        ActionMode::Reckless => true,
288        ActionMode::Guarded => {
289            agent.combat_state.timers[timer_guarded_cycle_index] += read_data.dt.0;
290            if agent.combat_state.timers[timer_guarded_cycle_index]
291                > agent.combat_state.counters[fcounter_guarded_timer_index]
292            {
293                agent.combat_state.timers[timer_guarded_cycle_index] = 0.0;
294                agent.combat_state.conditions[condition_guarded_defend_index] ^= true;
295                agent.combat_state.counters[fcounter_guarded_timer_index] =
296                    if agent.combat_state.conditions[condition_guarded_defend_index] {
297                        rng.random_range(3.0..6.0)
298                    } else {
299                        rng.random_range(6.0..10.0)
300                    };
301            }
302            if let Some(pos) = agent.combat_state.positions[position_guarded_cover_index]
303                && pos.distance_squared(agent_data.pos.0) < 3_f32.powi(2)
304            {
305                agent.combat_state.positions[position_guarded_cover_index] = None;
306            }
307            if !agent.combat_state.conditions[condition_guarded_defend_index] {
308                agent.combat_state.positions[position_guarded_cover_index] = None;
309                true
310            } else {
311                if attack_data.dist_sqrd > 10_f32.powi(2) {
312                    // Choose random point to either side when looking at target and move
313                    // towards it
314                    if let Some(pos) = agent.combat_state.positions[position_guarded_cover_index] {
315                        if pos.distance_squared(agent_data.pos.0) < 5_f32.powi(2) {
316                            agent.combat_state.positions[position_guarded_cover_index] = None;
317                        }
318                        agent_data.path_toward_target(
319                            agent,
320                            controller,
321                            pos,
322                            read_data,
323                            Path::Separate,
324                            None,
325                        );
326                    } else {
327                        agent.combat_state.positions[position_guarded_cover_index] = {
328                            let rand_dir = {
329                                let dir = (tgt_data.pos.0 - agent_data.pos.0)
330                                    .try_normalized()
331                                    .unwrap_or(Vec3::unit_x())
332                                    .xy();
333                                if rng.random_bool(0.5) {
334                                    dir.rotated_z(PI / 2.0 + rng.random_range(-0.75..0.0))
335                                } else {
336                                    dir.rotated_z(-PI / 2.0 + rng.random_range(-0.0..0.75))
337                                }
338                            };
339                            let attempted_dist = rng.random_range(6.0..16.0);
340                            let actual_dist = read_data
341                                .terrain
342                                .ray(
343                                    agent_data.pos.0 + Vec3::unit_z() * 0.5,
344                                    agent_data.pos.0
345                                        + Vec3::unit_z() * 0.5
346                                        + rand_dir * attempted_dist,
347                                )
348                                .until(Block::is_solid)
349                                .cast()
350                                .0
351                                - 1.0;
352                            Some(agent_data.pos.0 + rand_dir * actual_dist)
353                        };
354                    }
355                } else if let Some(pos) = agent.combat_state.positions[position_guarded_cover_index]
356                {
357                    agent_data.path_toward_target(
358                        agent,
359                        controller,
360                        pos,
361                        read_data,
362                        Path::Separate,
363                        None,
364                    );
365                    if agent.combat_state.conditions[condition_rolling_breakthrough_index] {
366                        controller.push_basic_input(InputKind::Roll);
367                        agent.combat_state.conditions[condition_rolling_breakthrough_index] = false;
368                    }
369                    if tgt_data.char_state.is_some_and(|cs| {
370                        cs.is_melee_attack() && cs.is_blockable().unwrap_or(false)
371                    }) {
372                        controller.push_basic_input(InputKind::Block);
373                    }
374                } else {
375                    agent.combat_state.positions[position_guarded_cover_index] = {
376                        let backwards = (agent_data.pos.0 - tgt_data.pos.0)
377                            .try_normalized()
378                            .unwrap_or(Vec3::unit_x())
379                            .xy();
380                        let pos = if read_data
381                            .terrain
382                            .ray(
383                                agent_data.pos.0 + Vec3::unit_z() * 0.5,
384                                agent_data.pos.0 + Vec3::unit_z() * 0.5 + backwards * 6.0,
385                            )
386                            .until(Block::is_solid)
387                            .cast()
388                            .0
389                            > 5.0
390                        {
391                            agent_data.pos.0 + backwards * 5.0
392                        } else {
393                            agent.combat_state.conditions[condition_rolling_breakthrough_index] =
394                                true;
395                            agent_data.pos.0
396                                - backwards
397                                    * read_data
398                                        .terrain
399                                        .ray(
400                                            agent_data.pos.0 + Vec3::unit_z() * 0.5,
401                                            agent_data.pos.0 + Vec3::unit_z() * 0.5
402                                                - backwards * 10.0,
403                                        )
404                                        .until(Block::is_solid)
405                                        .cast()
406                                        .0
407                                - 1.0
408                        };
409                        Some(pos)
410                    }
411                }
412                false
413            }
414        },
415        ActionMode::Fleeing => {
416            if agent.combat_state.conditions[condition_rolling_breakthrough_index] {
417                controller.push_basic_input(InputKind::Roll);
418                agent.combat_state.conditions[condition_rolling_breakthrough_index] = false;
419            }
420            if let Some(pos) = agent.combat_state.positions[position_flee_index] {
421                if let Some(dir) = Dir::from_unnormalized(pos - agent_data.pos.0) {
422                    controller.inputs.look_dir = dir;
423                }
424                if pos.distance_squared(agent_data.pos.0) < 5_f32.powi(2) {
425                    agent.combat_state.positions[position_flee_index] = None;
426                }
427                agent_data.path_toward_target(
428                    agent,
429                    controller,
430                    pos,
431                    read_data,
432                    Path::Separate,
433                    None,
434                );
435            } else {
436                agent.combat_state.positions[position_flee_index] = {
437                    let rand_dir = {
438                        let dir = (agent_data.pos.0 - tgt_data.pos.0)
439                            .try_normalized()
440                            .unwrap_or(Vec3::unit_x())
441                            .xy();
442                        dir.rotated_z(rng.random_range(-0.75..0.75))
443                    };
444                    let attempted_dist = rng.random_range(16.0..26.0);
445                    let actual_dist = read_data
446                        .terrain
447                        .ray(
448                            agent_data.pos.0 + Vec3::unit_z() * 0.5,
449                            agent_data.pos.0 + Vec3::unit_z() * 0.5 + rand_dir * attempted_dist,
450                        )
451                        .until(Block::is_solid)
452                        .cast()
453                        .0
454                        - 1.0;
455                    if actual_dist < 10.0 {
456                        let dist = read_data
457                            .terrain
458                            .ray(
459                                agent_data.pos.0 + Vec3::unit_z() * 0.5,
460                                agent_data.pos.0 + Vec3::unit_z() * 0.5 - rand_dir * attempted_dist,
461                            )
462                            .until(Block::is_solid)
463                            .cast()
464                            .0
465                            - 1.0;
466                        agent.combat_state.conditions[condition_rolling_breakthrough_index] = true;
467                        Some(agent_data.pos.0 - rand_dir * dist)
468                    } else {
469                        Some(agent_data.pos.0 + rand_dir * actual_dist)
470                    }
471                };
472            }
473            false
474        },
475    }
476}