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(_entity: EcsEntity, _read_data: &ReadData) -> bool {
121    // FIXME: We need to be able to change the name of a guard without
122    // breaking this logic.
123    // The `Mark` enum from common::agent could be used to match with
124    // `agent::Mark::Guard`
125    false
126    /*
127    read_data
128        .stats
129        .get(entity)
130        .is_some_and(|stats| stats.name == "Guard")
131    */
132}
133
134pub fn are_our_owners_hostile(
135    our_alignment: Option<&Alignment>,
136    their_alignment: Option<&Alignment>,
137    read_data: &ReadData,
138) -> bool {
139    try_owner_alignment(our_alignment, read_data).is_some_and(|our_owners_alignment| {
140        try_owner_alignment(their_alignment, read_data).is_some_and(|their_owners_alignment| {
141            our_owners_alignment.hostile_towards(*their_owners_alignment)
142        })
143    })
144}
145
146pub fn entities_have_line_of_sight(
147    pos: &Pos,
148    body: Option<&Body>,
149    scale: f32,
150    other_pos: &Pos,
151    other_body: Option<&Body>,
152    other_scale: Option<&Scale>,
153    read_data: &ReadData,
154) -> bool {
155    let get_eye_pos = |pos: &Pos, body: Option<&Body>, scale: f32| {
156        let eye_offset = body.map_or(0.0, |b| b.eye_height(scale));
157
158        Pos(pos.0.with_z(pos.0.z + eye_offset))
159    };
160    let eye_pos = get_eye_pos(pos, body, scale);
161    let other_eye_pos = get_eye_pos(other_pos, other_body, other_scale.map_or(1.0, |s| s.0));
162
163    positions_have_line_of_sight(&eye_pos, &other_eye_pos, read_data)
164}
165
166pub fn positions_have_line_of_sight(pos_a: &Pos, pos_b: &Pos, read_data: &ReadData) -> bool {
167    let dist_sqrd = pos_b.0.distance_squared(pos_a.0);
168
169    read_data
170        .terrain
171        .ray(pos_a.0, pos_b.0)
172        .until(Block::is_opaque)
173        .cast()
174        .0
175        .powi(2)
176        >= (dist_sqrd - 0.01)
177}
178
179pub fn is_dressed_as_cultist(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::Cultist))
184            .count()
185            > 2
186    })
187}
188
189pub fn is_dressed_as_witch(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::Witch))
194            .count()
195            > 3
196    })
197}
198
199pub fn is_dressed_as_pirate(entity: EcsEntity, read_data: &ReadData) -> bool {
200    read_data.inventories.get(entity).is_some_and(|inventory| {
201        inventory
202            .equipped_items()
203            .filter(|item| item.tags().contains(&ItemTag::Pirate))
204            .count()
205            > 4
206    })
207}
208
209pub fn get_attacker(entity: EcsEntity, read_data: &ReadData) -> Option<EcsEntity> {
210    read_data
211        .healths
212        .get(entity)
213        .filter(|health| health.last_change.amount < 0.0)
214        .and_then(|health| health.last_change.damage_by())
215        .and_then(|damage_contributor| get_entity_by_id(damage_contributor.uid(), read_data))
216}
217
218impl AgentData<'_> {
219    pub fn has_buff(&self, read_data: &ReadData, buff: BuffKind) -> bool {
220        read_data
221            .buffs
222            .get(*self.entity)
223            .is_some_and(|b| b.kinds[buff].is_some())
224    }
225
226    pub fn extract_ability(&self, input: AbilityInput) -> Option<AbilityData> {
227        AbilityData::from_ability(
228            &self
229                .active_abilities
230                .activate_ability(
231                    input,
232                    Some(self.inventory),
233                    self.skill_set,
234                    self.body,
235                    Some(self.char_state),
236                    self.stance,
237                    self.combo,
238                    self.stats,
239                    self.buffs,
240                )
241                .map_or(Default::default(), |a| a.0),
242        )
243    }
244}
245
246// Probably works best for melee (or maybe only for melee considering its
247// reliance on blocking?)
248/// Handles whether an agent should attack and how the agent moves around.
249/// Returns whether the agent should attack (so that individual tactics can
250/// determine what specific attack to use)
251pub fn handle_attack_aggression(
252    agent_data: &AgentData,
253    agent: &mut Agent,
254    controller: &mut Controller,
255    attack_data: &AttackData,
256    tgt_data: &TargetData,
257    read_data: &ReadData,
258    rng: &mut impl RngExt,
259    timer_pos_timeout_index: usize,
260    timer_guarded_cycle_index: usize,
261    fcounter_guarded_timer_index: usize,
262    icounter_action_mode_index: usize,
263    condition_guarded_defend_index: usize,
264    condition_rolling_breakthrough_index: usize,
265    position_guarded_cover_index: usize,
266    position_flee_index: usize,
267) -> bool {
268    if let Some(health) = agent_data.health {
269        agent.combat_state.int_counters[icounter_action_mode_index] = if health.fraction() < 0.1 {
270            agent.combat_state.positions[position_guarded_cover_index] = None;
271            ActionMode::Fleeing as u8
272        } else if health.fraction() < 0.9 {
273            agent.combat_state.positions[position_flee_index] = None;
274            ActionMode::Guarded as u8
275        } else {
276            agent.combat_state.positions[position_guarded_cover_index] = None;
277            agent.combat_state.positions[position_flee_index] = None;
278            ActionMode::Reckless as u8
279        };
280    }
281
282    // If agent has not moved, assume agent was unable to move and reset attempted
283    // path positions if occurs for too long
284    if agent_data.vel.0.magnitude_squared() < 1_f32.powi(2) {
285        agent.combat_state.timers[timer_pos_timeout_index] += read_data.dt.0;
286    } else {
287        agent.combat_state.timers[timer_pos_timeout_index] = 0.0;
288    }
289
290    if agent.combat_state.timers[timer_pos_timeout_index] > 2.0 {
291        agent.combat_state.positions[position_guarded_cover_index] = None;
292        agent.combat_state.positions[position_flee_index] = None;
293        agent.combat_state.timers[timer_pos_timeout_index] = 0.0;
294    }
295
296    match ActionMode::from_u8(agent.combat_state.int_counters[icounter_action_mode_index]) {
297        ActionMode::Reckless => true,
298        ActionMode::Guarded => {
299            agent.combat_state.timers[timer_guarded_cycle_index] += read_data.dt.0;
300            if agent.combat_state.timers[timer_guarded_cycle_index]
301                > agent.combat_state.counters[fcounter_guarded_timer_index]
302            {
303                agent.combat_state.timers[timer_guarded_cycle_index] = 0.0;
304                agent.combat_state.conditions[condition_guarded_defend_index] ^= true;
305                agent.combat_state.counters[fcounter_guarded_timer_index] =
306                    if agent.combat_state.conditions[condition_guarded_defend_index] {
307                        rng.random_range(3.0..6.0)
308                    } else {
309                        rng.random_range(6.0..10.0)
310                    };
311            }
312            if let Some(pos) = agent.combat_state.positions[position_guarded_cover_index]
313                && pos.distance_squared(agent_data.pos.0) < 3_f32.powi(2)
314            {
315                agent.combat_state.positions[position_guarded_cover_index] = None;
316            }
317            if !agent.combat_state.conditions[condition_guarded_defend_index] {
318                agent.combat_state.positions[position_guarded_cover_index] = None;
319                true
320            } else {
321                if attack_data.dist_sqrd > 10_f32.powi(2) {
322                    // Choose random point to either side when looking at target and move
323                    // towards it
324                    if let Some(pos) = agent.combat_state.positions[position_guarded_cover_index] {
325                        if pos.distance_squared(agent_data.pos.0) < 5_f32.powi(2) {
326                            agent.combat_state.positions[position_guarded_cover_index] = None;
327                        }
328                        agent_data.path_toward_target(
329                            agent,
330                            controller,
331                            pos,
332                            read_data,
333                            Path::Separate,
334                            None,
335                        );
336                    } else {
337                        agent.combat_state.positions[position_guarded_cover_index] = {
338                            let rand_dir = {
339                                let dir = (tgt_data.pos.0 - agent_data.pos.0)
340                                    .try_normalized()
341                                    .unwrap_or(Vec3::unit_x())
342                                    .xy();
343                                if rng.random_bool(0.5) {
344                                    dir.rotated_z(PI / 2.0 + rng.random_range(-0.75..0.0))
345                                } else {
346                                    dir.rotated_z(-PI / 2.0 + rng.random_range(-0.0..0.75))
347                                }
348                            };
349                            let attempted_dist = rng.random_range(6.0..16.0);
350                            let actual_dist = read_data
351                                .terrain
352                                .ray(
353                                    agent_data.pos.0 + Vec3::unit_z() * 0.5,
354                                    agent_data.pos.0
355                                        + Vec3::unit_z() * 0.5
356                                        + rand_dir * attempted_dist,
357                                )
358                                .until(Block::is_solid)
359                                .cast()
360                                .0
361                                - 1.0;
362                            Some(agent_data.pos.0 + rand_dir * actual_dist)
363                        };
364                    }
365                } else if let Some(pos) = agent.combat_state.positions[position_guarded_cover_index]
366                {
367                    agent_data.path_toward_target(
368                        agent,
369                        controller,
370                        pos,
371                        read_data,
372                        Path::Separate,
373                        None,
374                    );
375                    if agent.combat_state.conditions[condition_rolling_breakthrough_index] {
376                        controller.push_basic_input(InputKind::Roll);
377                        agent.combat_state.conditions[condition_rolling_breakthrough_index] = false;
378                    }
379                    if tgt_data.char_state.is_some_and(|cs| {
380                        cs.is_melee_attack() && cs.is_blockable().unwrap_or(false)
381                    }) {
382                        controller.push_basic_input(InputKind::Block);
383                    }
384                } else {
385                    agent.combat_state.positions[position_guarded_cover_index] = {
386                        let backwards = (agent_data.pos.0 - tgt_data.pos.0)
387                            .try_normalized()
388                            .unwrap_or(Vec3::unit_x())
389                            .xy();
390                        let pos = if read_data
391                            .terrain
392                            .ray(
393                                agent_data.pos.0 + Vec3::unit_z() * 0.5,
394                                agent_data.pos.0 + Vec3::unit_z() * 0.5 + backwards * 6.0,
395                            )
396                            .until(Block::is_solid)
397                            .cast()
398                            .0
399                            > 5.0
400                        {
401                            agent_data.pos.0 + backwards * 5.0
402                        } else {
403                            agent.combat_state.conditions[condition_rolling_breakthrough_index] =
404                                true;
405                            agent_data.pos.0
406                                - backwards
407                                    * read_data
408                                        .terrain
409                                        .ray(
410                                            agent_data.pos.0 + Vec3::unit_z() * 0.5,
411                                            agent_data.pos.0 + Vec3::unit_z() * 0.5
412                                                - backwards * 10.0,
413                                        )
414                                        .until(Block::is_solid)
415                                        .cast()
416                                        .0
417                                - 1.0
418                        };
419                        Some(pos)
420                    }
421                }
422                false
423            }
424        },
425        ActionMode::Fleeing => {
426            if agent.combat_state.conditions[condition_rolling_breakthrough_index] {
427                controller.push_basic_input(InputKind::Roll);
428                agent.combat_state.conditions[condition_rolling_breakthrough_index] = false;
429            }
430            if let Some(pos) = agent.combat_state.positions[position_flee_index] {
431                if let Some(dir) = Dir::from_unnormalized(pos - agent_data.pos.0) {
432                    controller.inputs.look_dir = dir;
433                }
434                if pos.distance_squared(agent_data.pos.0) < 5_f32.powi(2) {
435                    agent.combat_state.positions[position_flee_index] = None;
436                }
437                agent_data.path_toward_target(
438                    agent,
439                    controller,
440                    pos,
441                    read_data,
442                    Path::Separate,
443                    None,
444                );
445            } else {
446                agent.combat_state.positions[position_flee_index] = {
447                    let rand_dir = {
448                        let dir = (agent_data.pos.0 - tgt_data.pos.0)
449                            .try_normalized()
450                            .unwrap_or(Vec3::unit_x())
451                            .xy();
452                        dir.rotated_z(rng.random_range(-0.75..0.75))
453                    };
454                    let attempted_dist = rng.random_range(16.0..26.0);
455                    let actual_dist = read_data
456                        .terrain
457                        .ray(
458                            agent_data.pos.0 + Vec3::unit_z() * 0.5,
459                            agent_data.pos.0 + Vec3::unit_z() * 0.5 + rand_dir * attempted_dist,
460                        )
461                        .until(Block::is_solid)
462                        .cast()
463                        .0
464                        - 1.0;
465                    if actual_dist < 10.0 {
466                        let dist = read_data
467                            .terrain
468                            .ray(
469                                agent_data.pos.0 + Vec3::unit_z() * 0.5,
470                                agent_data.pos.0 + Vec3::unit_z() * 0.5 - rand_dir * attempted_dist,
471                            )
472                            .until(Block::is_solid)
473                            .cast()
474                            .0
475                            - 1.0;
476                        agent.combat_state.conditions[condition_rolling_breakthrough_index] = true;
477                        Some(agent_data.pos.0 - rand_dir * dist)
478                    } else {
479                        Some(agent_data.pos.0 + rand_dir * actual_dist)
480                    }
481                };
482            }
483            false
484        },
485    }
486}