veloren_server_agent/
action_nodes.rs

1use crate::{
2    consts::{
3        AVG_FOLLOW_DIST, DEFAULT_ATTACK_RANGE, IDLE_HEALING_ITEM_THRESHOLD, MAX_PATROL_DIST,
4        SEPARATION_BIAS, SEPARATION_DIST, STD_AWARENESS_DECAY_RATE,
5    },
6    data::{AgentData, AgentEmitters, AttackData, Path, ReadData, Tactic, TargetData},
7    util::{
8        aim_projectile, are_our_owners_hostile, entities_have_line_of_sight, get_attacker,
9        get_entity_by_id, is_dead_or_invulnerable, is_dressed_as_cultist, is_dressed_as_pirate,
10        is_dressed_as_witch, is_invulnerable, is_steering, is_village_guard, is_villager,
11    },
12};
13use common::{
14    combat::perception_dist_multiplier_from_stealth,
15    comp::{
16        self, Agent, Alignment, Body, CharacterState, Content, ControlAction, ControlEvent,
17        Controller, HealthChange, InputKind, InventoryAction, Pos, PresenceKind, Scale,
18        UnresolvedChatMsg, UtteranceKind,
19        ability::BASE_ABILITY_LIMIT,
20        agent::{FlightMode, PidControllers, Sound, SoundKind, Target},
21        biped_large, body,
22        inventory::slot::EquipSlot,
23        item::{
24            ConsumableKind, Effects, Item, ItemDesc, ItemKind,
25            tool::{AbilitySpec, ToolKind},
26        },
27        projectile::ProjectileConstructorKind,
28    },
29    consts::MAX_MOUNT_RANGE,
30    effect::{BuffEffect, Effect},
31    event::{ChatEvent, EmitExt, SoundEvent},
32    interaction::InteractionKind,
33    match_some,
34    mounting::VolumePos,
35    path::TraversalConfig,
36    rtsim::NpcActivity,
37    states::basic_beam,
38    terrain::Block,
39    time::DayPeriod,
40    util::Dir,
41    vol::ReadVol,
42};
43use itertools::Itertools;
44use rand::{Rng, rng};
45use specs::Entity as EcsEntity;
46use vek::*;
47
48#[cfg(feature = "use-dyn-lib")]
49use {crate::LIB, std::ffi::CStr};
50
51impl AgentData<'_> {
52    ////////////////////////////////////////
53    // Action Nodes
54    ////////////////////////////////////////
55    pub fn glider_equip(&self, controller: &mut Controller, read_data: &ReadData) {
56        self.dismount(controller, read_data);
57        controller.push_action(ControlAction::GlideWield);
58    }
59
60    // TODO: add the ability to follow the target?
61    pub fn glider_flight(&self, controller: &mut Controller, _read_data: &ReadData) {
62        let Some(fluid) = self.physics_state.in_fluid else {
63            return;
64        };
65
66        let vel = self.vel;
67
68        let comp::Vel(rel_flow) = fluid.relative_flow(vel);
69
70        let is_wind_downwards = rel_flow.z.is_sign_negative();
71
72        let look_dir = if is_wind_downwards {
73            Vec3::from(-rel_flow.xy())
74        } else {
75            -rel_flow
76        };
77
78        controller.inputs.look_dir = Dir::from_unnormalized(look_dir).unwrap_or_else(Dir::forward);
79    }
80
81    pub fn fly_upward(&self, controller: &mut Controller, read_data: &ReadData) {
82        self.dismount(controller, read_data);
83
84        controller.push_basic_input(InputKind::Fly);
85        controller.inputs.move_z = 1.0;
86    }
87
88    /// Directs the entity to path and move toward the target
89    /// If path is not Full, the entity will path to a location 50 units along
90    /// the vector between the entity and the target. The speed multiplier
91    /// multiplies the movement speed by a value less than 1.0.
92    /// A `None` value implies a multiplier of 1.0.
93    /// Returns `false` if the pathfinding algorithm fails to return a path
94    pub fn path_toward_target(
95        &self,
96        agent: &mut Agent,
97        controller: &mut Controller,
98        tgt_pos: Vec3<f32>,
99        read_data: &ReadData,
100        path: Path,
101        speed_multiplier: Option<f32>,
102    ) -> Option<Vec3<f32>> {
103        self.dismount_uncontrollable(controller, read_data);
104
105        let pos_difference = tgt_pos - self.pos.0;
106        let pathing_pos = match path {
107            Path::Separate => {
108                let mut sep_vec: Vec3<f32> = Vec3::zero();
109
110                for entity in read_data
111                    .cached_spatial_grid
112                    .0
113                    .in_circle_aabr(self.pos.0.xy(), SEPARATION_DIST)
114                {
115                    if let (Some(alignment), Some(other_alignment)) =
116                        (self.alignment, read_data.alignments.get(entity))
117                        && Alignment::passive_towards(*alignment, *other_alignment)
118                        && let (Some(pos), Some(body), Some(other_body)) = (
119                            read_data.positions.get(entity),
120                            self.body,
121                            read_data.bodies.get(entity),
122                        )
123                    {
124                        let dist_xy = self.pos.0.xy().distance(pos.0.xy());
125                        let spacing = body.spacing_radius() + other_body.spacing_radius();
126                        if dist_xy < spacing {
127                            let pos_diff = self.pos.0.xy() - pos.0.xy();
128                            sep_vec += pos_diff.try_normalized().unwrap_or_else(Vec2::zero)
129                                * ((spacing - dist_xy) / spacing);
130                        }
131                    }
132                }
133
134                tgt_pos + sep_vec * SEPARATION_BIAS + pos_difference * (1.0 - SEPARATION_BIAS)
135            },
136            Path::AtTarget => tgt_pos,
137        };
138        let speed_multiplier = speed_multiplier.unwrap_or(1.0).min(1.0);
139
140        let in_loaded_chunk = |pos: Vec3<f32>| {
141            read_data
142                .terrain
143                .contains_key(read_data.terrain.pos_key(pos.map(|e| e.floor() as i32)))
144        };
145
146        // If current position lies inside a loaded chunk, we need to plan routes using
147        // voxel info. If target happens to be in an unloaded chunk,
148        // we need to make our way to the current chunk border, and
149        // then reroute if needed.
150        let is_target_loaded = in_loaded_chunk(pathing_pos);
151
152        if let Some((bearing, speed, stuck)) = agent.chaser.chase(
153            &*read_data.terrain,
154            self.pos.0,
155            self.vel.0,
156            pathing_pos,
157            TraversalConfig {
158                min_tgt_dist: 0.25,
159                is_target_loaded,
160                ..self.traversal_config
161            },
162            &read_data.time,
163        ) {
164            self.unstuck_if(stuck, controller);
165            self.traverse(controller, bearing, speed * speed_multiplier);
166            Some(bearing)
167        } else {
168            None
169        }
170    }
171
172    fn traverse(&self, controller: &mut Controller, bearing: Vec3<f32>, speed: f32) {
173        controller.inputs.move_dir =
174            bearing.xy().try_normalized().unwrap_or_else(Vec2::zero) * speed;
175
176        // Only jump if we are grounded and can't blockhop or if we can fly
177        self.jump_if(
178            (self.physics_state.on_ground.is_some() && bearing.z > 1.5)
179                || self.traversal_config.can_fly,
180            controller,
181        );
182        controller.inputs.move_z = bearing.z;
183    }
184
185    pub fn unstuck_if(&self, condition: bool, controller: &mut Controller) {
186        if condition && rng().random_bool(0.05) {
187            if matches!(self.char_state, CharacterState::Climb(_)) || rng().random_bool(0.5) {
188                controller.push_basic_input(InputKind::Jump);
189            } else {
190                controller.push_basic_input(InputKind::Roll);
191            }
192        } else {
193            if controller.queued_inputs.contains_key(&InputKind::Jump) {
194                controller.push_cancel_input(InputKind::Jump);
195            }
196            if controller.queued_inputs.contains_key(&InputKind::Roll) {
197                controller.push_cancel_input(InputKind::Roll);
198            }
199        }
200    }
201
202    pub fn jump_if(&self, condition: bool, controller: &mut Controller) {
203        if condition {
204            controller.push_basic_input(InputKind::Jump);
205        } else if controller.queued_inputs.contains_key(&InputKind::Jump) {
206            controller.push_cancel_input(InputKind::Jump)
207        }
208    }
209
210    pub fn idle(
211        &self,
212        agent: &mut Agent,
213        controller: &mut Controller,
214        read_data: &ReadData,
215        _emitters: &mut AgentEmitters,
216        rng: &mut impl Rng,
217    ) {
218        enum ActionTimers {
219            TimerIdle = 0,
220        }
221
222        agent
223            .awareness
224            .change_by(STD_AWARENESS_DECAY_RATE * read_data.dt.0);
225
226        // Light lanterns at night
227        // TODO Add a method to turn on NPC lanterns underground
228        let lantern_equipped = self
229            .inventory
230            .equipped(EquipSlot::Lantern)
231            .as_ref()
232            .is_some_and(|item| matches!(&*item.kind(), comp::item::ItemKind::Lantern(_)));
233        let lantern_turned_on = self.light_emitter.is_some();
234        let day_period = DayPeriod::from(read_data.time_of_day.0);
235        // Only emit event for agents that have a lantern equipped
236        if lantern_equipped && rng.random_bool(0.001) {
237            if day_period.is_dark() && !lantern_turned_on {
238                // Agents with turned off lanterns turn them on randomly once it's
239                // nighttime and keep them on.
240                // Only emit event for agents that sill need to
241                // turn on their lantern.
242                controller.push_event(ControlEvent::EnableLantern)
243            } else if lantern_turned_on && day_period.is_light() {
244                // agents with turned on lanterns turn them off randomly once it's
245                // daytime and keep them off.
246                controller.push_event(ControlEvent::DisableLantern)
247            }
248        };
249
250        if let Some(body) = self.body {
251            let attempt_heal = if matches!(body, Body::Humanoid(_)) {
252                self.damage < IDLE_HEALING_ITEM_THRESHOLD
253            } else {
254                true
255            };
256            if attempt_heal && self.heal_self(agent, controller, true) {
257                agent.behavior_state.timers[ActionTimers::TimerIdle as usize] = 0.01;
258                return;
259            }
260        } else {
261            agent.behavior_state.timers[ActionTimers::TimerIdle as usize] = 0.01;
262            return;
263        }
264
265        agent.behavior_state.timers[ActionTimers::TimerIdle as usize] = 0.0;
266
267        'activity: {
268            match agent.rtsim_controller.activity {
269                Some(NpcActivity::Goto(travel_to, speed_factor)) => {
270                    self.dismount_uncontrollable(controller, read_data);
271
272                    agent.bearing = Vec2::zero();
273
274                    // If it has an rtsim destination and can fly, then it should.
275                    // If it is flying and bumps something above it, then it should move down.
276                    if self.traversal_config.can_fly
277                        && !read_data
278                            .terrain
279                            .ray(self.pos.0, self.pos.0 + (Vec3::unit_z() * 3.0))
280                            .until(Block::is_solid)
281                            .cast()
282                            .1
283                            .map_or(true, |b| b.is_some())
284                    {
285                        controller.push_basic_input(InputKind::Fly);
286                    } else {
287                        controller.push_cancel_input(InputKind::Fly)
288                    }
289
290                    if let Some(bearing) = self.path_toward_target(
291                        agent,
292                        controller,
293                        travel_to,
294                        read_data,
295                        Path::AtTarget,
296                        Some(speed_factor),
297                    ) {
298                        let height_offset = bearing.z
299                            + if self.traversal_config.can_fly {
300                                // NOTE: costs 4 us (imbris)
301                                let obstacle_ahead = read_data
302                                    .terrain
303                                    .ray(
304                                        self.pos.0 + Vec3::unit_z(),
305                                        self.pos.0
306                                            + bearing.try_normalized().unwrap_or_else(Vec3::unit_y)
307                                                * 80.0
308                                            + Vec3::unit_z(),
309                                    )
310                                    .until(Block::is_solid)
311                                    .cast()
312                                    .1
313                                    .map_or(true, |b| b.is_some());
314
315                                let mut ground_too_close = self
316                                    .body
317                                    .map(|body| {
318                                        #[cfg(feature = "worldgen")]
319                                        let height_approx = self.pos.0.z
320                                            - read_data
321                                                .world
322                                                .sim()
323                                                .get_alt_approx(
324                                                    self.pos.0.xy().map(|x: f32| x as i32),
325                                                )
326                                                .unwrap_or(0.0);
327                                        #[cfg(not(feature = "worldgen"))]
328                                        let height_approx = self.pos.0.z;
329
330                                        height_approx < body.flying_height()
331                                    })
332                                    .unwrap_or(false);
333
334                                const NUM_RAYS: usize = 5;
335
336                                // NOTE: costs 15-20 us (imbris)
337                                for i in 0..=NUM_RAYS {
338                                    let magnitude = self.body.map_or(20.0, |b| b.flying_height());
339                                    // Lerp between a line straight ahead and straight down to
340                                    // detect a
341                                    // wedge of obstacles we might fly into (inclusive so that both
342                                    // vectors are sampled)
343                                    if let Some(dir) = Lerp::lerp(
344                                        -Vec3::unit_z(),
345                                        Vec3::new(bearing.x, bearing.y, 0.0),
346                                        i as f32 / NUM_RAYS as f32,
347                                    )
348                                    .try_normalized()
349                                    {
350                                        ground_too_close |= read_data
351                                            .terrain
352                                            .ray(self.pos.0, self.pos.0 + magnitude * dir)
353                                            .until(|b: &Block| b.is_solid() || b.is_liquid())
354                                            .cast()
355                                            .1
356                                            .is_ok_and(|b| b.is_some())
357                                    }
358                                }
359
360                                if obstacle_ahead || ground_too_close {
361                                    5.0 //fly up when approaching obstacles
362                                } else {
363                                    -2.0
364                                } //flying things should slowly come down from the stratosphere
365                            } else {
366                                0.05 //normal land traveller offset
367                            };
368
369                        if let Some(mpid) = agent.multi_pid_controllers.as_mut() {
370                            if let Some(z_controller) = mpid.z_controller.as_mut() {
371                                z_controller.sp = self.pos.0.z + height_offset;
372                                controller.inputs.move_z = z_controller.calc_err();
373                                // when changing setpoints, limit PID windup
374                                z_controller.limit_integral_windup(|z| *z = z.clamp(-10.0, 10.0));
375                            } else {
376                                controller.inputs.move_z = 0.0;
377                            }
378                        } else {
379                            controller.inputs.move_z = height_offset;
380                        }
381                    }
382
383                    // Put away weapon
384                    if rng.random_bool(0.1)
385                        && matches!(
386                            read_data.char_states.get(*self.entity),
387                            Some(CharacterState::Wielding(_))
388                        )
389                    {
390                        controller.push_action(ControlAction::Unwield);
391                    }
392                    break 'activity; // Don't fall through to idle wandering
393                },
394
395                Some(NpcActivity::GotoFlying(
396                    travel_to,
397                    speed_factor,
398                    height_offset,
399                    direction_override,
400                    flight_mode,
401                )) => {
402                    self.dismount_uncontrollable(controller, read_data);
403
404                    if self.traversal_config.vectored_propulsion {
405                        // This is the action for Airships.
406
407                        // Note - when the Agent code is run, the entity will be the captain that is
408                        // mounted on the ship and the movement calculations
409                        // must be done relative to the captain's position
410                        // which is offset from the ship's position and apparently scaled.
411                        // When the State system runs to apply the movement accel and velocity, the
412                        // ship entity will be the subject entity.
413
414                        // entities that have vectored propulsion should always be flying
415                        // and do not depend on forward movement or displacement to move.
416                        // E.g., Airships.
417                        controller.push_basic_input(InputKind::Fly);
418
419                        // These entities can either:
420                        // - Move in any direction, following the terrain
421                        // - Move essentially vertically, as in
422                        //   - Hover in place (station-keeping), like at a dock
423                        //   - Move straight up or down, as when taking off or landing
424
425                        // If there is lateral movement, then the entity's direction should be
426                        // aligned with that movement direction. If there is
427                        // no or minimal lateral movement, then the entity
428                        // is either hovering or moving vertically, and the entity's direction
429                        // should not change. This is indicated by the direction_override parameter.
430
431                        // If a direction override is provided, attempt to orient the entity in that
432                        // direction.
433                        if let Some(direction) = direction_override {
434                            controller.inputs.look_dir = direction;
435                        } else {
436                            // else orient the entity in the direction of travel, but keep it level
437                            controller.inputs.look_dir =
438                                Dir::from_unnormalized((travel_to - self.pos.0).xy().with_z(0.0))
439                                    .unwrap_or_default();
440                        }
441
442                        // the look_dir will be used as the orientation override. Orientation
443                        // override is always enabled for airships, so this
444                        // code must set controller.inputs.look_dir for
445                        // all cases (vertical or lateral movement).
446
447                        // When pid_mode is PureZ, only the z component of movement is is adjusted
448                        // by the PID controller.
449
450                        // If the PID controller is not set or the mode or gain has changed, create
451                        // a new one. PidControllers is a wrapper around one
452                        // or more PID controllers. Each controller acts on
453                        // one axis of movement. There are three controllers for FixedDirection mode
454                        // and one for PureZ mode.
455                        if agent
456                            .multi_pid_controllers
457                            .as_ref()
458                            .is_some_and(|mpid| mpid.mode != flight_mode)
459                        {
460                            agent.multi_pid_controllers = None;
461                        }
462                        let mpid = agent.multi_pid_controllers.get_or_insert_with(|| {
463                            PidControllers::<16>::new_multi_pid_controllers(flight_mode, travel_to)
464                        });
465                        let sample_time = read_data.time.0;
466
467                        #[allow(unused_variables)]
468                        let terrain_alt_with_lookahead = |dist: f32| -> f32 {
469                            // look ahead some blocks to sample the terrain altitude
470                            #[cfg(feature = "worldgen")]
471                            let terrain_alt = read_data
472                                .world
473                                .sim()
474                                .get_alt_approx(
475                                    (self.pos.0.xy()
476                                        + controller.inputs.look_dir.to_vec().xy() * dist)
477                                        .map(|x: f32| x as i32),
478                                )
479                                .unwrap_or(0.0);
480                            #[cfg(not(feature = "worldgen"))]
481                            let terrain_alt = 0.0;
482                            terrain_alt
483                        };
484
485                        if flight_mode == FlightMode::FlyThrough {
486                            let travel_vec = travel_to - self.pos.0;
487                            let bearing =
488                                travel_vec.xy().try_normalized().unwrap_or_else(Vec2::zero);
489                            controller.inputs.move_dir = bearing * speed_factor;
490                            let terrain_alt = terrain_alt_with_lookahead(32.0);
491                            let height = height_offset.unwrap_or(100.0);
492                            if let Some(z_controller) = mpid.z_controller.as_mut() {
493                                z_controller.sp = terrain_alt + height;
494                            }
495                            mpid.add_measurement(sample_time, self.pos.0);
496                            // check if getting close to terrain
497                            if terrain_alt >= self.pos.0.z - 32.0 {
498                                // It's likely the airship will hit an upslope. Maximize the climb
499                                // rate.
500                                controller.inputs.move_z = 1.0 * speed_factor;
501                                // try to stop forward movement
502                                controller.inputs.move_dir =
503                                    self.vel.0.xy().try_normalized().unwrap_or_else(Vec2::zero)
504                                        * -1.0
505                                        * speed_factor;
506                            } else {
507                                controller.inputs.move_z =
508                                    mpid.calc_err_z().unwrap_or(0.0).min(1.0) * speed_factor;
509                            }
510                            // PID controllers that change the setpoint suffer from "windup", where
511                            // the integral term accumulates error.
512                            // There are several ways to compensate for this. One way is to limit
513                            // the integral term to a range.
514                            mpid.limit_windup_z(|z| *z = z.clamp(-20.0, 20.0));
515                        } else {
516                            // When doing step-wise movement, the target waypoint changes. Make sure
517                            // the PID controller setpoints keep up with
518                            // the changes.
519                            if let Some(x_controller) = mpid.x_controller.as_mut() {
520                                x_controller.sp = travel_to.x;
521                            }
522                            if let Some(y_controller) = mpid.y_controller.as_mut() {
523                                y_controller.sp = travel_to.y;
524                            }
525
526                            // If terrain following, get the terrain altitude at the current
527                            // position. Set the z setpoint to the max
528                            // of terrain alt + height offset or the
529                            // target z.
530                            let z_setpoint = if let Some(height) = height_offset {
531                                let clearance_alt = terrain_alt_with_lookahead(16.0) + height;
532                                clearance_alt.max(travel_to.z)
533                            } else {
534                                travel_to.z
535                            };
536                            if let Some(z_controller) = mpid.z_controller.as_mut() {
537                                z_controller.sp = z_setpoint;
538                            }
539
540                            mpid.add_measurement(sample_time, self.pos.0);
541                            controller.inputs.move_dir.x =
542                                mpid.calc_err_x().unwrap_or(0.0).min(1.0) * speed_factor;
543                            controller.inputs.move_dir.y =
544                                mpid.calc_err_y().unwrap_or(0.0).min(1.0) * speed_factor;
545                            controller.inputs.move_z =
546                                mpid.calc_err_z().unwrap_or(0.0).min(1.0) * speed_factor;
547
548                            // Limit the integral term to a range to prevent windup.
549                            mpid.limit_windup_x(|x| *x = x.clamp(-1.0, 1.0));
550                            mpid.limit_windup_y(|y| *y = y.clamp(-1.0, 1.0));
551                            mpid.limit_windup_z(|z| *z = z.clamp(-1.0, 1.0));
552                        }
553                    }
554                    break 'activity; // Don't fall through to idle wandering
555                },
556                Some(NpcActivity::Gather(_resources)) => {
557                    // TODO: Implement
558                    controller.push_action(ControlAction::Dance);
559                    break 'activity; // Don't fall through to idle wandering
560                },
561                Some(NpcActivity::Dance(dir)) => {
562                    // Look at targets specified by rtsim
563                    if let Some(look_dir) = dir {
564                        controller.inputs.look_dir = look_dir;
565                        if self.ori.look_dir().dot(look_dir.to_vec()) < 0.95 {
566                            controller.inputs.move_dir = look_dir.to_vec().xy() * 0.01;
567                            break 'activity;
568                        } else {
569                            controller.inputs.move_dir = Vec2::zero();
570                        }
571                    }
572                    controller.push_action(ControlAction::Dance);
573                    break 'activity; // Don't fall through to idle wandering
574                },
575                Some(NpcActivity::Cheer(dir)) => {
576                    if let Some(look_dir) = dir {
577                        controller.inputs.look_dir = look_dir;
578                        if self.ori.look_dir().dot(look_dir.to_vec()) < 0.95 {
579                            controller.inputs.move_dir = look_dir.to_vec().xy() * 0.01;
580                            break 'activity;
581                        } else {
582                            controller.inputs.move_dir = Vec2::zero();
583                        }
584                    }
585                    controller.push_action(ControlAction::Talk(None));
586                    break 'activity; // Don't fall through to idle wandering
587                },
588                Some(NpcActivity::Sit(dir, pos)) => {
589                    if let Some(pos) =
590                        pos.filter(|p| read_data.terrain.get(*p).is_ok_and(|b| b.is_mountable()))
591                    {
592                        if !read_data.is_volume_riders.contains(*self.entity) {
593                            controller
594                                .push_event(ControlEvent::MountVolume(VolumePos::terrain(pos)));
595                        }
596                    } else {
597                        if let Some(look_dir) = dir {
598                            controller.inputs.look_dir = look_dir;
599                            if self.ori.look_dir().dot(look_dir.to_vec()) < 0.95 {
600                                controller.inputs.move_dir = look_dir.to_vec().xy() * 0.01;
601                                break 'activity;
602                            } else {
603                                controller.inputs.move_dir = Vec2::zero();
604                            }
605                        }
606                        controller.push_action(ControlAction::Sit);
607                    }
608                    break 'activity; // Don't fall through to idle wandering
609                },
610                Some(NpcActivity::HuntAnimals) => {
611                    if rng.random::<f32>() < 0.1 {
612                        self.choose_target(
613                            agent,
614                            controller,
615                            read_data,
616                            AgentData::is_hunting_animal,
617                        );
618                    }
619                },
620                Some(NpcActivity::Talk(target)) => {
621                    if agent.target.is_none()
622                        && let Some(target) = read_data.id_maps.actor_entity(target)
623                        && let Some(target_uid) = read_data.uids.get(target)
624                    {
625                        // We're always aware of someone we're talking to
626                        controller.push_action(ControlAction::Stand);
627                        self.look_toward(controller, read_data, target);
628                        controller.push_action(ControlAction::Talk(Some(*target_uid)));
629                        break 'activity;
630                    }
631                },
632                None => {},
633            }
634
635            let owner_uid = self
636                .alignment
637                .and_then(|alignment| match_some!(alignment, Alignment::Owned(uid) => uid));
638
639            let owner = owner_uid.and_then(|owner_uid| get_entity_by_id(*owner_uid, read_data));
640
641            let is_being_pet = read_data
642                .interactors
643                .get(*self.entity)
644                .and_then(|interactors| interactors.get(*owner_uid?))
645                .is_some_and(|interaction| matches!(interaction.kind, InteractionKind::Pet));
646
647            let is_in_range = owner
648                .and_then(|owner| read_data.positions.get(owner))
649                .is_some_and(|pos| pos.0.distance_squared(self.pos.0) < MAX_MOUNT_RANGE.powi(2));
650
651            // Idle NPCs should try to jump on the shoulders of their owner, sometimes.
652            if read_data.is_riders.contains(*self.entity) {
653                if rng.random_bool(0.0001) {
654                    self.dismount_uncontrollable(controller, read_data);
655                } else {
656                    break 'activity;
657                }
658            } else if let Some(owner_uid) = owner_uid
659                && is_in_range
660                && !is_being_pet
661                && rng.random_bool(0.01)
662            {
663                controller.push_event(ControlEvent::Mount(*owner_uid));
664                break 'activity;
665            }
666
667            // Bats should fly
668            // Use a proportional controller as the bouncing effect mimics bat flight
669            if self.traversal_config.can_fly
670                && self
671                    .inventory
672                    .equipped(EquipSlot::ActiveMainhand)
673                    .as_ref()
674                    .is_some_and(|item| {
675                        item.ability_spec().is_some_and(|a_s| match &*a_s {
676                            AbilitySpec::Custom(spec) => {
677                                matches!(
678                                    spec.as_str(),
679                                    "Simple Flying Melee"
680                                        | "Bloodmoon Bat"
681                                        | "Vampire Bat"
682                                        | "Flame Wyvern"
683                                        | "Frost Wyvern"
684                                        | "Cloud Wyvern"
685                                        | "Sea Wyvern"
686                                        | "Weald Wyvern"
687                                )
688                            },
689                            _ => false,
690                        })
691                    })
692            {
693                // Bats don't like the ground, so make sure they are always flying
694                controller.push_basic_input(InputKind::Fly);
695                // Use a proportional controller with a coefficient of 1.0 to
696                // maintain altitude
697                let alt = read_data
698                    .terrain
699                    .ray(self.pos.0, self.pos.0 - (Vec3::unit_z() * 7.0))
700                    .until(Block::is_solid)
701                    .cast()
702                    .0;
703                let set_point = 5.0;
704                let error = set_point - alt;
705                controller.inputs.move_z = error;
706                // If on the ground, jump
707                if self.physics_state.on_ground.is_some() {
708                    controller.push_basic_input(InputKind::Jump);
709                }
710            }
711
712            let diff = Vec2::new(rng.random::<f32>() - 0.5, rng.random::<f32>() - 0.5);
713            agent.bearing += (diff * 0.1 - agent.bearing * 0.01)
714                * agent.psyche.idle_wander_factor.max(0.0).sqrt()
715                * agent.psyche.aggro_range_multiplier.max(0.0).sqrt();
716            if let Some(patrol_origin) = agent.patrol_origin
717                // Use owner as patrol origin otherwise
718                .or_else(|| if let Some(Alignment::Owned(owner_uid)) = self.alignment
719                    && let Some(owner) = get_entity_by_id(*owner_uid, read_data)
720                    && let Some(pos) = read_data.positions.get(owner)
721                {
722                    Some(pos.0)
723                } else {
724                    None
725                })
726            {
727                agent.bearing += ((patrol_origin.xy() - self.pos.0.xy())
728                    / (0.01 + MAX_PATROL_DIST * agent.psyche.idle_wander_factor))
729                    * 0.015
730                    * agent.psyche.idle_wander_factor;
731            }
732
733            // Stop if we're too close to a wall
734            // or about to walk off a cliff
735            // NOTE: costs 1 us (imbris) <- before cliff raycast added
736            agent.bearing *= 0.1
737                + if read_data
738                    .terrain
739                    .ray(
740                        self.pos.0 + Vec3::unit_z(),
741                        self.pos.0
742                            + Vec3::from(agent.bearing)
743                                .try_normalized()
744                                .unwrap_or_else(Vec3::unit_y)
745                                * 5.0
746                            + Vec3::unit_z(),
747                    )
748                    .until(Block::is_solid)
749                    .cast()
750                    .1
751                    .map_or(true, |b| b.is_none())
752                    && read_data
753                        .terrain
754                        .ray(
755                            self.pos.0
756                                + Vec3::from(agent.bearing)
757                                    .try_normalized()
758                                    .unwrap_or_else(Vec3::unit_y),
759                            self.pos.0
760                                + Vec3::from(agent.bearing)
761                                    .try_normalized()
762                                    .unwrap_or_else(Vec3::unit_y)
763                                - Vec3::unit_z() * 4.0,
764                        )
765                        .until(Block::is_solid)
766                        .cast()
767                        .0
768                        < 3.0
769                {
770                    0.9
771                } else {
772                    0.0
773                };
774
775            if agent.bearing.magnitude_squared() > 0.5f32.powi(2) {
776                controller.inputs.move_dir = agent.bearing;
777            }
778
779            // Put away weapon
780            if rng.random_bool(0.1)
781                && matches!(
782                    read_data.char_states.get(*self.entity),
783                    Some(CharacterState::Wielding(_))
784                )
785            {
786                controller.push_action(ControlAction::Unwield);
787            }
788
789            if rng.random::<f32>() < 0.0015 {
790                controller.push_utterance(UtteranceKind::Calm);
791            }
792
793            // Sit
794            if rng.random::<f32>() < 0.0035 {
795                controller.push_action(ControlAction::Sit);
796            }
797        }
798    }
799
800    pub fn follow(
801        &self,
802        agent: &mut Agent,
803        controller: &mut Controller,
804        read_data: &ReadData,
805        tgt_pos: &Pos,
806    ) {
807        self.dismount_uncontrollable(controller, read_data);
808
809        if let Some((bearing, speed, stuck)) = agent.chaser.chase(
810            &*read_data.terrain,
811            self.pos.0,
812            self.vel.0,
813            tgt_pos.0,
814            TraversalConfig {
815                min_tgt_dist: AVG_FOLLOW_DIST,
816                ..self.traversal_config
817            },
818            &read_data.time,
819        ) {
820            self.unstuck_if(stuck, controller);
821            let dist_sqrd = self.pos.0.distance_squared(tgt_pos.0);
822            self.traverse(
823                controller,
824                bearing,
825                speed.min(0.2 + (dist_sqrd - AVG_FOLLOW_DIST.powi(2)) / 8.0),
826            );
827        }
828    }
829
830    pub fn look_toward(
831        &self,
832        controller: &mut Controller,
833        read_data: &ReadData,
834        target: EcsEntity,
835    ) -> bool {
836        if let Some(tgt_pos) = read_data.positions.get(target)
837            && !is_steering(*self.entity, read_data)
838            && let Some(dir) = Dir::look_toward(
839                self.pos,
840                self.body,
841                Some(&comp::Scale(self.scale)),
842                tgt_pos,
843                read_data.bodies.get(target),
844                read_data.scales.get(target),
845            )
846        {
847            controller.inputs.look_dir = dir;
848            true
849        } else {
850            false
851        }
852    }
853
854    pub fn flee(
855        &self,
856        agent: &mut Agent,
857        controller: &mut Controller,
858        read_data: &ReadData,
859        tgt_pos: &Pos,
860    ) {
861        // Proportion of full speed
862        const MAX_FLEE_SPEED: f32 = 0.65;
863
864        self.dismount_uncontrollable(controller, read_data);
865
866        if let Some(body) = self.body
867            && body.can_strafe()
868            && !self.is_gliding
869        {
870            controller.push_action(ControlAction::Unwield);
871        }
872
873        if let Some((bearing, speed, stuck)) = agent.chaser.chase(
874            &*read_data.terrain,
875            self.pos.0,
876            self.vel.0,
877            // Away from the target (ironically)
878            self.pos.0
879                + (self.pos.0 - tgt_pos.0)
880                    .try_normalized()
881                    .unwrap_or_else(Vec3::unit_y)
882                    * 50.0,
883            TraversalConfig {
884                min_tgt_dist: 1.25,
885                ..self.traversal_config
886            },
887            &read_data.time,
888        ) {
889            self.unstuck_if(stuck, controller);
890            self.traverse(controller, bearing, speed.min(MAX_FLEE_SPEED));
891        }
892    }
893
894    /// Attempt to consume a healing item, and return whether any healing items
895    /// were queued. Callers should use this to implement a delay so that
896    /// the healing isn't interrupted. If `relaxed` is `true`, we allow eating
897    /// food and prioritise healing.
898    pub fn heal_self(
899        &self,
900        _agent: &mut Agent,
901        controller: &mut Controller,
902        relaxed: bool,
903    ) -> bool {
904        // If we already have a healing buff active, don't start another one.
905        if self.buffs.is_some_and(|buffs| {
906            buffs.iter_active().flatten().any(|buff| {
907                buff.kind.effects(&buff.data).iter().any(|effect| {
908                    if let comp::BuffEffect::HealthChangeOverTime { rate, .. } = effect
909                        && *rate > 0.0
910                    {
911                        true
912                    } else {
913                        false
914                    }
915                })
916            })
917        }) {
918            return false;
919        }
920
921        // Wait for potion sickness to wear off if potions are less than 50% effective.
922        let heal_multiplier = self.stats.map_or(1.0, |s| s.item_effect_reduction);
923        if heal_multiplier < 0.5 {
924            return false;
925        }
926        // (healing_value, heal_reduction)
927        let effect_healing_value = |effect: &Effect| -> (f32, f32) {
928            let mut value = 0.0;
929            let mut heal_reduction = 0.0;
930            match effect {
931                Effect::Health(HealthChange { amount, .. }) => {
932                    value += *amount;
933                },
934                Effect::Buff(BuffEffect { kind, data, .. }) => {
935                    if let Some(duration) = data.duration {
936                        for effect in kind.effects(data) {
937                            match effect {
938                                comp::BuffEffect::HealthChangeOverTime { rate, kind, .. } => {
939                                    let amount = match kind {
940                                        comp::ModifierKind::Additive => rate * duration.0 as f32,
941                                        comp::ModifierKind::Multiplicative => {
942                                            (1.0 + rate).powf(duration.0 as f32)
943                                        },
944                                    };
945
946                                    value += amount;
947                                },
948                                comp::BuffEffect::ItemEffectReduction(amount) => {
949                                    heal_reduction =
950                                        heal_reduction + amount - heal_reduction * amount;
951                                },
952                                _ => {},
953                            }
954                        }
955                        value += data.strength * data.duration.map_or(0.0, |d| d.0 as f32);
956                    }
957                },
958
959                _ => {},
960            }
961
962            (value, heal_reduction)
963        };
964        let healing_value = |item: &Item| {
965            let mut value = 0.0;
966            let mut heal_multiplier_value = 1.0;
967
968            if let ItemKind::Consumable { kind, effects, .. } = &*item.kind()
969                && (matches!(kind, ConsumableKind::Drink)
970                    || (relaxed && matches!(kind, ConsumableKind::Food)))
971            {
972                match effects {
973                    Effects::Any(effects) => {
974                        // Add the average of all effects.
975                        for effect in effects.iter() {
976                            let (add, red) = effect_healing_value(effect);
977                            value += add / effects.len() as f32;
978                            heal_multiplier_value *= 1.0 - red / effects.len() as f32;
979                        }
980                    },
981                    Effects::All(_) | Effects::One(_) => {
982                        for effect in effects.effects() {
983                            let (add, red) = effect_healing_value(effect);
984                            value += add;
985                            heal_multiplier_value *= 1.0 - red;
986                        }
987                    },
988                }
989            }
990            // Prefer non-potion sources of healing when under at least one stack of potion
991            // sickness, or when incurring potion sickness is unnecessary
992            if heal_multiplier_value < 1.0 && (heal_multiplier < 1.0 || relaxed) {
993                value *= 0.1;
994            }
995            value as i32
996        };
997
998        let item = self
999            .inventory
1000            .slots_with_id()
1001            .filter_map(|(id, slot)| match slot {
1002                Some(item) if healing_value(item) > 0 => Some((id, item)),
1003                _ => None,
1004            })
1005            .max_by_key(|(_, item)| {
1006                if relaxed {
1007                    -healing_value(item)
1008                } else {
1009                    healing_value(item)
1010                }
1011            });
1012
1013        if let Some((id, _)) = item {
1014            use comp::inventory::slot::Slot;
1015            controller.push_action(ControlAction::InventoryAction(InventoryAction::Use(
1016                Slot::Inventory(id),
1017            )));
1018            true
1019        } else {
1020            false
1021        }
1022    }
1023
1024    pub fn choose_target(
1025        &self,
1026        agent: &mut Agent,
1027        controller: &mut Controller,
1028        read_data: &ReadData,
1029        is_enemy: fn(&Self, EcsEntity, &ReadData) -> bool,
1030    ) {
1031        enum ActionStateTimers {
1032            TimerChooseTarget = 0,
1033        }
1034        agent.behavior_state.timers[ActionStateTimers::TimerChooseTarget as usize] = 0.0;
1035        let mut aggro_on = false;
1036
1037        // Search the area.
1038        // TODO: choose target by more than just distance
1039        let common::CachedSpatialGrid(grid) = self.cached_spatial_grid;
1040
1041        let entities_nearby = grid
1042            .in_circle_aabr(self.pos.0.xy(), agent.psyche.search_dist())
1043            .collect_vec();
1044
1045        let get_pos = |entity| read_data.positions.get(entity);
1046        let get_enemy = |(entity, attack_target): (EcsEntity, bool)| {
1047            if attack_target {
1048                if is_enemy(self, entity, read_data) {
1049                    Some((entity, true))
1050                } else if self.should_defend(entity, read_data) {
1051                    if let Some(attacker) = get_attacker(entity, read_data) {
1052                        if !self.passive_towards(attacker, read_data) {
1053                            // aggro_on: attack immediately, do not warn/menace.
1054                            aggro_on = true;
1055                            Some((attacker, true))
1056                        } else {
1057                            None
1058                        }
1059                    } else {
1060                        None
1061                    }
1062                } else {
1063                    None
1064                }
1065            } else {
1066                Some((entity, false))
1067            }
1068        };
1069        let is_valid_target = |entity: EcsEntity| match read_data.bodies.get(entity) {
1070            Some(Body::Item(item)) => {
1071                if !matches!(item, body::item::Body::Thrown(_)) {
1072                    let is_humanoid = matches!(self.body, Some(Body::Humanoid(_)));
1073                    let avoids_item_drops = matches!(
1074                        self.body,
1075                        Some(Body::BipedLarge(biped_large::Body {
1076                            species: biped_large::Species::Gigasfrost
1077                                | biped_large::Species::Gigasfire,
1078                            ..
1079                        }))
1080                    );
1081                    // If the agent is humanoid, it will pick up all kinds of item drops. If the
1082                    // agent isn't humanoid, it will pick up only consumable item drops.
1083                    let wants_pickup = !avoids_item_drops
1084                        && (is_humanoid || matches!(item, body::item::Body::Consumable));
1085
1086                    // The agent will attempt to pickup the item if it wants to pick it up and
1087                    // is allowed to
1088                    let attempt_pickup = wants_pickup
1089                    && read_data
1090                        .loot_owners
1091                        .get(entity).is_none_or(|loot_owner| {
1092                            !(is_humanoid
1093                                && loot_owner.can_pickup(
1094                                    *self.uid,
1095                                    read_data.groups.get(entity),
1096                                    self.alignment,
1097                                    self.body,
1098                                    None,
1099                                )
1100                                && (
1101                                    !loot_owner.is_soft() ||
1102                                    // If we are hostile towards the owner, ignore their wish to not pick up the loot
1103                                    loot_owner
1104                                        .uid()
1105                                        .and_then(|uid| read_data.id_maps.uid_entity(uid)).is_none_or(|entity| !is_enemy(self, entity, read_data)))
1106                                )
1107                        });
1108
1109                    if attempt_pickup {
1110                        Some((entity, false))
1111                    } else {
1112                        None
1113                    }
1114                } else {
1115                    None
1116                }
1117            },
1118            _ => {
1119                if read_data
1120                    .healths
1121                    .get(entity)
1122                    .is_some_and(|health| !health.is_dead && !is_invulnerable(entity, read_data))
1123                {
1124                    let needs_saving = comp::is_downed(
1125                        read_data.healths.get(entity),
1126                        read_data.char_states.get(entity),
1127                    );
1128
1129                    let wants_to_save = match (self.alignment, read_data.alignments.get(entity)) {
1130                        // Npcs generally do want to save players. Could have extra checks for
1131                        // sentiment in the future.
1132                        (Some(Alignment::Npc), _) if read_data.presences.get(entity).is_some_and(|presence| matches!(presence.kind, PresenceKind::Character(_))) => true,
1133                        (Some(Alignment::Npc), Some(Alignment::Npc)) => true,
1134                        (Some(Alignment::Enemy), Some(Alignment::Enemy)) => true,
1135                        _ => false,
1136                    } && agent.allowed_to_speak()
1137                        // Check that anyone else isn't already saving them.
1138                        && read_data
1139                            .interactors
1140                            .get(entity).is_none_or(|interactors| {
1141                                !interactors.has_interaction(InteractionKind::HelpDowned)
1142                            }) && self.char_state.can_interact();
1143
1144                    // TODO: Make targets that need saving have less priority as a target.
1145                    Some((entity, !(needs_saving && wants_to_save)))
1146                } else {
1147                    None
1148                }
1149            },
1150        };
1151
1152        let is_detected = |entity: &EcsEntity, e_pos: &Pos, e_scale: Option<&Scale>| {
1153            self.detects_other(agent, controller, entity, e_pos, e_scale, read_data)
1154        };
1155
1156        let target = entities_nearby
1157            .iter()
1158            .filter_map(|e| is_valid_target(*e))
1159            .filter_map(get_enemy)
1160            .filter_map(|(entity, attack_target)| {
1161                get_pos(entity).map(|pos| (entity, pos, attack_target))
1162            })
1163            .filter(|(entity, e_pos, _)| is_detected(entity, e_pos, read_data.scales.get(*entity)))
1164            .min_by_key(|(_, e_pos, attack_target)| {
1165                (
1166                    *attack_target,
1167                    (e_pos.0.distance_squared(self.pos.0) * 100.0) as i32,
1168                )
1169            })
1170            .map(|(entity, _, attack_target)| (entity, attack_target));
1171
1172        if agent.target.is_none() && target.is_some() {
1173            if aggro_on {
1174                controller.push_utterance(UtteranceKind::Angry);
1175            } else {
1176                controller.push_utterance(UtteranceKind::Surprised);
1177            }
1178        }
1179        if agent.psyche.should_stop_pursuing || target.is_some() {
1180            agent.target = target.map(|(entity, attack_target)| Target {
1181                target: entity,
1182                hostile: attack_target,
1183                selected_at: read_data.time.0,
1184                aggro_on,
1185                last_known_pos: get_pos(entity).map(|pos| pos.0),
1186            })
1187        }
1188    }
1189
1190    pub fn attack(
1191        &self,
1192        agent: &mut Agent,
1193        controller: &mut Controller,
1194        tgt_data: &TargetData,
1195        read_data: &ReadData,
1196        rng: &mut impl Rng,
1197    ) {
1198        #[cfg(any(feature = "be-dyn-lib", feature = "use-dyn-lib"))]
1199        let _rng = rng;
1200
1201        #[cfg(not(feature = "use-dyn-lib"))]
1202        {
1203            #[cfg(not(feature = "be-dyn-lib"))]
1204            self.attack_inner(agent, controller, tgt_data, read_data, rng);
1205            #[cfg(feature = "be-dyn-lib")]
1206            self.attack_inner(agent, controller, tgt_data, read_data);
1207        }
1208        #[cfg(feature = "use-dyn-lib")]
1209        {
1210            let lock = LIB.lock().unwrap();
1211            let lib = &lock.as_ref().unwrap().lib;
1212            const ATTACK_FN: &[u8] = b"attack_inner\0";
1213
1214            let attack_fn: common_dynlib::Symbol<
1215                fn(&Self, &mut Agent, &mut Controller, &TargetData, &ReadData),
1216            > = unsafe { lib.get(ATTACK_FN) }.unwrap_or_else(|e| {
1217                panic!(
1218                    "Trying to use: {} but had error: {:?}",
1219                    CStr::from_bytes_with_nul(ATTACK_FN)
1220                        .map(CStr::to_str)
1221                        .unwrap()
1222                        .unwrap(),
1223                    e
1224                )
1225            });
1226            attack_fn(self, agent, controller, tgt_data, read_data);
1227        }
1228    }
1229
1230    #[cfg_attr(feature = "be-dyn-lib", unsafe(export_name = "attack_inner"))]
1231    pub fn attack_inner(
1232        &self,
1233        agent: &mut Agent,
1234        controller: &mut Controller,
1235        tgt_data: &TargetData,
1236        read_data: &ReadData,
1237        #[cfg(not(feature = "be-dyn-lib"))] rng: &mut impl Rng,
1238    ) {
1239        #[cfg(feature = "be-dyn-lib")]
1240        let rng = &mut rng();
1241
1242        self.dismount_uncontrollable(controller, read_data);
1243
1244        let tool_tactic = |tool_kind| match tool_kind {
1245            ToolKind::Bow => Tactic::Bow,
1246            ToolKind::Staff => Tactic::Staff,
1247            ToolKind::Sceptre => Tactic::Sceptre,
1248            ToolKind::Hammer => Tactic::Hammer,
1249            ToolKind::Sword | ToolKind::Blowgun => Tactic::Sword,
1250            ToolKind::Axe => Tactic::Axe,
1251            _ => Tactic::SimpleMelee,
1252        };
1253
1254        let tactic = self
1255            .inventory
1256            .equipped(EquipSlot::ActiveMainhand)
1257            .as_ref()
1258            .map(|item| {
1259                if let Some(ability_spec) = item.ability_spec() {
1260                    match &*ability_spec {
1261                        AbilitySpec::Custom(spec) => match spec.as_str() {
1262                            "Oni" | "Sword Simple" | "BipedLargeCultistSword" => {
1263                                Tactic::SwordSimple
1264                            },
1265                            "Staff Simple" | "BipedLargeCultistStaff" => Tactic::Staff,
1266                            "BipedLargeCultistHammer" => Tactic::Hammer,
1267                            "Simple Flying Melee" => Tactic::SimpleFlyingMelee,
1268                            "Bow Simple" | "BipedLargeCultistBow" => Tactic::Bow,
1269                            "Stone Golem" | "Coral Golem" => Tactic::StoneGolem,
1270                            "Iron Golem" => Tactic::IronGolem,
1271                            "Quad Med Quick" => Tactic::CircleCharge {
1272                                radius: 5,
1273                                circle_time: 2,
1274                            },
1275                            "Quad Med Jump" | "Darkhound" => Tactic::QuadMedJump,
1276                            "Quad Med Charge" => Tactic::CircleCharge {
1277                                radius: 6,
1278                                circle_time: 1,
1279                            },
1280                            "Quad Med Basic" => Tactic::QuadMedBasic,
1281                            "Quad Med Hoof" => Tactic::QuadMedHoof,
1282                            "ClaySteed" => Tactic::ClaySteed,
1283                            "Rocksnapper" => Tactic::Rocksnapper,
1284                            "Roshwalr" => Tactic::Roshwalr,
1285                            "Asp" | "Maneater" => Tactic::QuadLowRanged,
1286                            "Quad Low Breathe" | "Quad Low Beam" | "Basilisk" => {
1287                                Tactic::QuadLowBeam
1288                            },
1289                            "Organ" => Tactic::OrganAura,
1290                            "Quad Low Tail" | "Husk Brute" => Tactic::TailSlap,
1291                            "Quad Low Quick" => Tactic::QuadLowQuick,
1292                            "Quad Low Basic" => Tactic::QuadLowBasic,
1293                            "Theropod Basic" | "Theropod Bird" | "Theropod Small" => {
1294                                Tactic::Theropod
1295                            },
1296                            // Arthropods
1297                            "Antlion" => Tactic::ArthropodMelee,
1298                            "Tarantula" | "Horn Beetle" => Tactic::ArthropodAmbush,
1299                            "Weevil" | "Black Widow" | "Crawler" => Tactic::ArthropodRanged,
1300                            "Theropod Charge" => Tactic::CircleCharge {
1301                                radius: 6,
1302                                circle_time: 1,
1303                            },
1304                            "Turret" => Tactic::RadialTurret,
1305                            "Flamethrower" => Tactic::RadialTurret,
1306                            "Haniwa Sentry" => Tactic::RotatingTurret,
1307                            "Bird Large Breathe" => Tactic::BirdLargeBreathe,
1308                            "Bird Large Fire" => Tactic::BirdLargeFire,
1309                            "Bird Large Basic" => Tactic::BirdLargeBasic,
1310                            "Flame Wyvern" | "Frost Wyvern" | "Cloud Wyvern" | "Sea Wyvern"
1311                            | "Weald Wyvern" => Tactic::Wyvern,
1312                            "Bird Medium Basic" => Tactic::BirdMediumBasic,
1313                            "Bushly" | "Cactid" | "Irrwurz" | "Driggle" | "Mossy Snail"
1314                            | "Strigoi Claws" | "Harlequin" => Tactic::SimpleDouble,
1315                            "Clay Golem" => Tactic::ClayGolem,
1316                            "Ancient Effigy" => Tactic::AncientEffigy,
1317                            "TerracottaStatue" | "Mogwai" => Tactic::TerracottaStatue,
1318                            "TerracottaBesieger" => Tactic::Bow,
1319                            "TerracottaDemolisher" => Tactic::SimpleDouble,
1320                            "TerracottaPunisher" => Tactic::SimpleMelee,
1321                            "TerracottaPursuer" => Tactic::SwordSimple,
1322                            "Cursekeeper" => Tactic::Cursekeeper,
1323                            "CursekeeperFake" => Tactic::CursekeeperFake,
1324                            "ShamanicSpirit" => Tactic::ShamanicSpirit,
1325                            "Jiangshi" => Tactic::Jiangshi,
1326                            "Mindflayer" => Tactic::Mindflayer,
1327                            "Flamekeeper" => Tactic::Flamekeeper,
1328                            "Forgemaster" => Tactic::Forgemaster,
1329                            "Minotaur" => Tactic::Minotaur,
1330                            "Cyclops" => Tactic::Cyclops,
1331                            "Dullahan" => Tactic::Dullahan,
1332                            "Grave Warden" => Tactic::GraveWarden,
1333                            "Tidal Warrior" => Tactic::TidalWarrior,
1334                            "Karkatha" => Tactic::Karkatha,
1335                            "Tidal Totem"
1336                            | "Tornado"
1337                            | "Gnarling Totem Red"
1338                            | "Gnarling Totem Green"
1339                            | "Gnarling Totem White" => Tactic::RadialTurret,
1340                            "FieryTornado" => Tactic::FieryTornado,
1341                            "Yeti" => Tactic::Yeti,
1342                            "Harvester" => Tactic::Harvester,
1343                            "Cardinal" => Tactic::Cardinal,
1344                            "Sea Bishop" => Tactic::SeaBishop,
1345                            "Dagon" => Tactic::Dagon,
1346                            "Snaretongue" => Tactic::Snaretongue,
1347                            "Dagonite" => Tactic::ArthropodAmbush,
1348                            "Gnarling Dagger" => Tactic::SimpleBackstab,
1349                            "Gnarling Blowgun" => Tactic::ElevatedRanged,
1350                            "Deadwood" => Tactic::Deadwood,
1351                            "Mandragora" => Tactic::Mandragora,
1352                            "Wood Golem" => Tactic::WoodGolem,
1353                            "Gnarling Chieftain" => Tactic::GnarlingChieftain,
1354                            "Frost Gigas" => Tactic::FrostGigas,
1355                            "Boreal Hammer" => Tactic::BorealHammer,
1356                            "Boreal Bow" => Tactic::BorealBow,
1357                            "Fire Gigas" => Tactic::FireGigas,
1358                            "Ashen Axe" => Tactic::AshenAxe,
1359                            "Ashen Staff" => Tactic::AshenStaff,
1360                            "Adlet Hunter" => Tactic::AdletHunter,
1361                            "Adlet Icepicker" => Tactic::AdletIcepicker,
1362                            "Adlet Tracker" => Tactic::AdletTracker,
1363                            "Hydra" => Tactic::Hydra,
1364                            "Ice Drake" => Tactic::IceDrake,
1365                            "Frostfang" => Tactic::RandomAbilities {
1366                                primary: 1,
1367                                secondary: 3,
1368                                abilities: [0; BASE_ABILITY_LIMIT],
1369                            },
1370                            "Tursus Claws" => Tactic::RandomAbilities {
1371                                primary: 2,
1372                                secondary: 1,
1373                                abilities: [4, 0, 0, 0, 0],
1374                            },
1375                            "Adlet Elder" => Tactic::AdletElder,
1376                            "Haniwa Soldier" => Tactic::HaniwaSoldier,
1377                            "Haniwa Guard" => Tactic::HaniwaGuard,
1378                            "Haniwa Archer" => Tactic::HaniwaArcher,
1379                            "Bloodmoon Bat" => Tactic::BloodmoonBat,
1380                            "Vampire Bat" => Tactic::VampireBat,
1381                            "Bloodmoon Heiress" => Tactic::BloodmoonHeiress,
1382
1383                            _ => Tactic::SimpleMelee,
1384                        },
1385                        AbilitySpec::Tool(tool_kind) => tool_tactic(*tool_kind),
1386                    }
1387                } else if let ItemKind::Tool(tool) = &*item.kind() {
1388                    tool_tactic(tool.kind)
1389                } else {
1390                    Tactic::SimpleMelee
1391                }
1392            })
1393            .unwrap_or(Tactic::SimpleMelee);
1394
1395        // Wield the weapon as running towards the target
1396        controller.push_action(ControlAction::Wield);
1397
1398        // Information for attack checks
1399        // 'min_attack_dist' uses DEFAULT_ATTACK_RANGE, while 'body_dist' does not
1400        let self_radius = self.body.map_or(0.5, |b| b.max_radius()) * self.scale;
1401        let self_attack_range =
1402            (self.body.map_or(0.5, |b| b.front_radius()) + DEFAULT_ATTACK_RANGE) * self.scale;
1403        let tgt_radius =
1404            tgt_data.body.map_or(0.5, |b| b.max_radius()) * tgt_data.scale.map_or(1.0, |s| s.0);
1405        let min_attack_dist = self_attack_range + tgt_radius;
1406        let body_dist = self_radius + tgt_radius;
1407        let dist_sqrd = self.pos.0.distance_squared(tgt_data.pos.0);
1408        let angle = self
1409            .ori
1410            .look_vec()
1411            .angle_between(tgt_data.pos.0 - self.pos.0)
1412            .to_degrees();
1413        let angle_xy = self
1414            .ori
1415            .look_vec()
1416            .xy()
1417            .angle_between((tgt_data.pos.0 - self.pos.0).xy())
1418            .to_degrees();
1419
1420        let eye_offset = self.body.map_or(0.0, |b| b.eye_height(self.scale));
1421
1422        let tgt_eye_height = tgt_data
1423            .body
1424            .map_or(0.0, |b| b.eye_height(tgt_data.scale.map_or(1.0, |s| s.0)));
1425        let tgt_eye_offset = tgt_eye_height +
1426                   // Special case for jumping attacks to jump at the body
1427                   // of the target and not the ground around the target
1428                   // For the ranged it is to shoot at the feet and not
1429                   // the head to get splash damage
1430                   if tactic == Tactic::QuadMedJump {
1431                       1.0
1432                   } else if matches!(tactic, Tactic::QuadLowRanged) {
1433                       -1.0
1434                   } else {
1435                       0.0
1436                   };
1437
1438        // FIXME:
1439        // 1) Retrieve actual projectile speed!
1440        // We have to assume projectiles are faster than base speed because there are
1441        // skills that increase it, and in most cases this will cause agents to
1442        // overshoot
1443        //
1444        // 2) We use eye_offset-s which isn't actually ideal.
1445        // Some attacks (beam for example) may use different offsets,
1446        // we should probably use offsets from corresponding states.
1447        //
1448        // 3) Should we even have this big switch?
1449        // Not all attacks may want their direction overwritten.
1450        // And this is quite hard to debug when you don't see it in actual
1451        // attack handler.
1452        if let Some(dir) = match self.char_state {
1453            CharacterState::ChargedRanged(c) if dist_sqrd > 0.0 => {
1454                let charge_factor =
1455                    c.timer.as_secs_f32() / c.static_data.charge_duration.as_secs_f32();
1456                let projectile_speed = c.static_data.initial_projectile_speed
1457                    + charge_factor * c.static_data.scaled_projectile_speed;
1458                aim_projectile(
1459                    projectile_speed,
1460                    self.pos.0
1461                        + self.body.map_or(Vec3::zero(), |body| {
1462                            body.projectile_offsets(self.ori.look_vec(), self.scale)
1463                        }),
1464                    Vec3::new(
1465                        tgt_data.pos.0.x,
1466                        tgt_data.pos.0.y,
1467                        tgt_data.pos.0.z + tgt_eye_offset,
1468                    ),
1469                )
1470            },
1471            CharacterState::BasicRanged(c) => {
1472                let offset_z = match c.static_data.projectile.kind {
1473                    // Aim explosives and hazards at feet instead of eyes for splash damage
1474                    ProjectileConstructorKind::Explosive { .. }
1475                    | ProjectileConstructorKind::ExplosiveHazard { .. }
1476                    | ProjectileConstructorKind::Hazard { .. } => 0.0,
1477                    _ => tgt_eye_offset,
1478                };
1479                let projectile_speed = c.static_data.projectile_speed;
1480                aim_projectile(
1481                    projectile_speed,
1482                    self.pos.0
1483                        + self.body.map_or(Vec3::zero(), |body| {
1484                            body.projectile_offsets(self.ori.look_vec(), self.scale)
1485                        }),
1486                    Vec3::new(
1487                        tgt_data.pos.0.x,
1488                        tgt_data.pos.0.y,
1489                        tgt_data.pos.0.z + offset_z,
1490                    ),
1491                )
1492            },
1493            CharacterState::RepeaterRanged(c) => {
1494                let projectile_speed = c.static_data.projectile_speed;
1495                aim_projectile(
1496                    projectile_speed,
1497                    self.pos.0
1498                        + self.body.map_or(Vec3::zero(), |body| {
1499                            body.projectile_offsets(self.ori.look_vec(), self.scale)
1500                        }),
1501                    Vec3::new(
1502                        tgt_data.pos.0.x,
1503                        tgt_data.pos.0.y,
1504                        tgt_data.pos.0.z + tgt_eye_offset,
1505                    ),
1506                )
1507            },
1508            CharacterState::LeapMelee(_)
1509                if matches!(tactic, Tactic::Hammer | Tactic::BorealHammer | Tactic::Axe) =>
1510            {
1511                let direction_weight = match tactic {
1512                    Tactic::Hammer | Tactic::BorealHammer => 0.1,
1513                    Tactic::Axe => 0.3,
1514                    _ => unreachable!("Direction weight called on incorrect tactic."),
1515                };
1516
1517                let tgt_pos = tgt_data.pos.0;
1518                let self_pos = self.pos.0;
1519
1520                let delta_x = (tgt_pos.x - self_pos.x) * direction_weight;
1521                let delta_y = (tgt_pos.y - self_pos.y) * direction_weight;
1522
1523                Dir::from_unnormalized(Vec3::new(delta_x, delta_y, -1.0))
1524            },
1525            CharacterState::BasicBeam(_) => {
1526                let aim_from = self.body.map_or(self.pos.0, |body| {
1527                    self.pos.0
1528                        + basic_beam::beam_offsets(
1529                            body,
1530                            controller.inputs.look_dir,
1531                            self.ori.look_vec(),
1532                            // Try to match animation by getting some context
1533                            self.vel.0 - self.physics_state.ground_vel,
1534                            self.physics_state.on_ground,
1535                        )
1536                });
1537                let aim_to = Vec3::new(
1538                    tgt_data.pos.0.x,
1539                    tgt_data.pos.0.y,
1540                    tgt_data.pos.0.z + tgt_eye_offset,
1541                );
1542                Dir::from_unnormalized(aim_to - aim_from)
1543            },
1544            _ => {
1545                let aim_from = Vec3::new(self.pos.0.x, self.pos.0.y, self.pos.0.z + eye_offset);
1546                let aim_to = Vec3::new(
1547                    tgt_data.pos.0.x,
1548                    tgt_data.pos.0.y,
1549                    tgt_data.pos.0.z + tgt_eye_offset,
1550                );
1551                Dir::from_unnormalized(aim_to - aim_from)
1552            },
1553        } {
1554            controller.inputs.look_dir = dir;
1555        }
1556
1557        let attack_data = AttackData {
1558            body_dist,
1559            min_attack_dist,
1560            dist_sqrd,
1561            angle,
1562            angle_xy,
1563        };
1564
1565        // Match on tactic. Each tactic has different controls depending on the distance
1566        // from the agent to the target.
1567        match tactic {
1568            Tactic::SimpleFlyingMelee => self.handle_simple_flying_melee(
1569                agent,
1570                controller,
1571                &attack_data,
1572                tgt_data,
1573                read_data,
1574                rng,
1575            ),
1576            Tactic::SimpleMelee => {
1577                self.handle_simple_melee(agent, controller, &attack_data, tgt_data, read_data, rng)
1578            },
1579            Tactic::Axe => {
1580                self.handle_axe_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1581            },
1582            Tactic::Hammer => {
1583                self.handle_hammer_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1584            },
1585            Tactic::Sword => {
1586                self.handle_sword_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1587            },
1588            Tactic::Bow => {
1589                self.handle_bow_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1590            },
1591            Tactic::Staff => {
1592                self.handle_staff_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1593            },
1594            Tactic::Sceptre => self.handle_sceptre_attack(
1595                agent,
1596                controller,
1597                &attack_data,
1598                tgt_data,
1599                read_data,
1600                rng,
1601            ),
1602            Tactic::StoneGolem => {
1603                self.handle_stone_golem_attack(agent, controller, &attack_data, tgt_data, read_data)
1604            },
1605            Tactic::IronGolem => {
1606                self.handle_iron_golem_attack(agent, controller, &attack_data, tgt_data, read_data)
1607            },
1608            Tactic::CircleCharge {
1609                radius,
1610                circle_time,
1611            } => self.handle_circle_charge_attack(
1612                agent,
1613                controller,
1614                &attack_data,
1615                tgt_data,
1616                read_data,
1617                radius,
1618                circle_time,
1619                rng,
1620            ),
1621            Tactic::QuadLowRanged => self.handle_quadlow_ranged_attack(
1622                agent,
1623                controller,
1624                &attack_data,
1625                tgt_data,
1626                read_data,
1627            ),
1628            Tactic::TailSlap => {
1629                self.handle_tail_slap_attack(agent, controller, &attack_data, tgt_data, read_data)
1630            },
1631            Tactic::QuadLowQuick => self.handle_quadlow_quick_attack(
1632                agent,
1633                controller,
1634                &attack_data,
1635                tgt_data,
1636                read_data,
1637            ),
1638            Tactic::QuadLowBasic => self.handle_quadlow_basic_attack(
1639                agent,
1640                controller,
1641                &attack_data,
1642                tgt_data,
1643                read_data,
1644            ),
1645            Tactic::QuadMedJump => self.handle_quadmed_jump_attack(
1646                agent,
1647                controller,
1648                &attack_data,
1649                tgt_data,
1650                read_data,
1651            ),
1652            Tactic::QuadMedBasic => self.handle_quadmed_basic_attack(
1653                agent,
1654                controller,
1655                &attack_data,
1656                tgt_data,
1657                read_data,
1658            ),
1659            Tactic::QuadMedHoof => self.handle_quadmed_hoof_attack(
1660                agent,
1661                controller,
1662                &attack_data,
1663                tgt_data,
1664                read_data,
1665            ),
1666            Tactic::QuadLowBeam => self.handle_quadlow_beam_attack(
1667                agent,
1668                controller,
1669                &attack_data,
1670                tgt_data,
1671                read_data,
1672            ),
1673            Tactic::Rocksnapper => {
1674                self.handle_rocksnapper_attack(agent, controller, &attack_data, tgt_data, read_data)
1675            },
1676            Tactic::Roshwalr => {
1677                self.handle_roshwalr_attack(agent, controller, &attack_data, tgt_data, read_data)
1678            },
1679            Tactic::OrganAura => {
1680                self.handle_organ_aura_attack(agent, controller, &attack_data, tgt_data, read_data)
1681            },
1682            Tactic::Theropod => {
1683                self.handle_theropod_attack(agent, controller, &attack_data, tgt_data, read_data)
1684            },
1685            Tactic::ArthropodMelee => self.handle_arthropod_melee_attack(
1686                agent,
1687                controller,
1688                &attack_data,
1689                tgt_data,
1690                read_data,
1691            ),
1692            Tactic::ArthropodAmbush => self.handle_arthropod_ambush_attack(
1693                agent,
1694                controller,
1695                &attack_data,
1696                tgt_data,
1697                read_data,
1698                rng,
1699            ),
1700            Tactic::ArthropodRanged => self.handle_arthropod_ranged_attack(
1701                agent,
1702                controller,
1703                &attack_data,
1704                tgt_data,
1705                read_data,
1706            ),
1707            Tactic::Turret => {
1708                self.handle_turret_attack(agent, controller, &attack_data, tgt_data, read_data)
1709            },
1710            Tactic::FixedTurret => self.handle_fixed_turret_attack(
1711                agent,
1712                controller,
1713                &attack_data,
1714                tgt_data,
1715                read_data,
1716            ),
1717            Tactic::RotatingTurret => {
1718                self.handle_rotating_turret_attack(agent, controller, tgt_data, read_data)
1719            },
1720            Tactic::Mindflayer => self.handle_mindflayer_attack(
1721                agent,
1722                controller,
1723                &attack_data,
1724                tgt_data,
1725                read_data,
1726                rng,
1727            ),
1728            Tactic::Flamekeeper => {
1729                self.handle_flamekeeper_attack(agent, controller, &attack_data, tgt_data, read_data)
1730            },
1731            Tactic::Forgemaster => {
1732                self.handle_forgemaster_attack(agent, controller, &attack_data, tgt_data, read_data)
1733            },
1734            Tactic::BirdLargeFire => self.handle_birdlarge_fire_attack(
1735                agent,
1736                controller,
1737                &attack_data,
1738                tgt_data,
1739                read_data,
1740                rng,
1741            ),
1742            // Mostly identical to BirdLargeFire but tweaked for flamethrower instead of shockwave
1743            Tactic::BirdLargeBreathe => self.handle_birdlarge_breathe_attack(
1744                agent,
1745                controller,
1746                &attack_data,
1747                tgt_data,
1748                read_data,
1749                rng,
1750            ),
1751            Tactic::BirdLargeBasic => self.handle_birdlarge_basic_attack(
1752                agent,
1753                controller,
1754                &attack_data,
1755                tgt_data,
1756                read_data,
1757            ),
1758            Tactic::Wyvern => {
1759                self.handle_wyvern_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1760            },
1761            Tactic::BirdMediumBasic => {
1762                self.handle_simple_melee(agent, controller, &attack_data, tgt_data, read_data, rng)
1763            },
1764            Tactic::SimpleDouble => self.handle_simple_double_attack(
1765                agent,
1766                controller,
1767                &attack_data,
1768                tgt_data,
1769                read_data,
1770            ),
1771            Tactic::Jiangshi => {
1772                self.handle_jiangshi_attack(agent, controller, &attack_data, tgt_data, read_data)
1773            },
1774            Tactic::ClayGolem => {
1775                self.handle_clay_golem_attack(agent, controller, &attack_data, tgt_data, read_data)
1776            },
1777            Tactic::ClaySteed => {
1778                self.handle_clay_steed_attack(agent, controller, &attack_data, tgt_data, read_data)
1779            },
1780            Tactic::AncientEffigy => self.handle_ancient_effigy_attack(
1781                agent,
1782                controller,
1783                &attack_data,
1784                tgt_data,
1785                read_data,
1786            ),
1787            Tactic::TerracottaStatue => {
1788                self.handle_terracotta_statue_attack(agent, controller, &attack_data, read_data)
1789            },
1790            Tactic::Minotaur => {
1791                self.handle_minotaur_attack(agent, controller, &attack_data, tgt_data, read_data)
1792            },
1793            Tactic::Cyclops => {
1794                self.handle_cyclops_attack(agent, controller, &attack_data, tgt_data, read_data)
1795            },
1796            Tactic::Dullahan => {
1797                self.handle_dullahan_attack(agent, controller, &attack_data, tgt_data, read_data)
1798            },
1799            Tactic::GraveWarden => self.handle_grave_warden_attack(
1800                agent,
1801                controller,
1802                &attack_data,
1803                tgt_data,
1804                read_data,
1805            ),
1806            Tactic::TidalWarrior => self.handle_tidal_warrior_attack(
1807                agent,
1808                controller,
1809                &attack_data,
1810                tgt_data,
1811                read_data,
1812            ),
1813            Tactic::Karkatha => self.handle_karkatha_attack(
1814                agent,
1815                controller,
1816                &attack_data,
1817                tgt_data,
1818                read_data,
1819                rng,
1820            ),
1821            Tactic::RadialTurret => self.handle_radial_turret_attack(controller),
1822            Tactic::FieryTornado => self.handle_fiery_tornado_attack(agent, controller),
1823            Tactic::Yeti => {
1824                self.handle_yeti_attack(agent, controller, &attack_data, tgt_data, read_data)
1825            },
1826            Tactic::Harvester => self.handle_harvester_attack(
1827                agent,
1828                controller,
1829                &attack_data,
1830                tgt_data,
1831                read_data,
1832                rng,
1833            ),
1834            Tactic::Cardinal => self.handle_cardinal_attack(
1835                agent,
1836                controller,
1837                &attack_data,
1838                tgt_data,
1839                read_data,
1840                rng,
1841            ),
1842            Tactic::SeaBishop => self.handle_sea_bishop_attack(
1843                agent,
1844                controller,
1845                &attack_data,
1846                tgt_data,
1847                read_data,
1848                rng,
1849            ),
1850            Tactic::Cursekeeper => self.handle_cursekeeper_attack(
1851                agent,
1852                controller,
1853                &attack_data,
1854                tgt_data,
1855                read_data,
1856                rng,
1857            ),
1858            Tactic::CursekeeperFake => {
1859                self.handle_cursekeeper_fake_attack(controller, &attack_data)
1860            },
1861            Tactic::ShamanicSpirit => self.handle_shamanic_spirit_attack(
1862                agent,
1863                controller,
1864                &attack_data,
1865                tgt_data,
1866                read_data,
1867            ),
1868            Tactic::Dagon => {
1869                self.handle_dagon_attack(agent, controller, &attack_data, tgt_data, read_data)
1870            },
1871            Tactic::Snaretongue => {
1872                self.handle_snaretongue_attack(agent, controller, &attack_data, read_data)
1873            },
1874            Tactic::SimpleBackstab => {
1875                self.handle_simple_backstab(agent, controller, &attack_data, tgt_data, read_data)
1876            },
1877            Tactic::ElevatedRanged => {
1878                self.handle_elevated_ranged(agent, controller, &attack_data, tgt_data, read_data)
1879            },
1880            Tactic::Deadwood => {
1881                self.handle_deadwood(agent, controller, &attack_data, tgt_data, read_data)
1882            },
1883            Tactic::Mandragora => {
1884                self.handle_mandragora(agent, controller, &attack_data, tgt_data, read_data)
1885            },
1886            Tactic::WoodGolem => {
1887                self.handle_wood_golem(agent, controller, &attack_data, tgt_data, read_data, rng)
1888            },
1889            Tactic::GnarlingChieftain => self.handle_gnarling_chieftain(
1890                agent,
1891                controller,
1892                &attack_data,
1893                tgt_data,
1894                read_data,
1895                rng,
1896            ),
1897            Tactic::FrostGigas => self.handle_frostgigas_attack(
1898                agent,
1899                controller,
1900                &attack_data,
1901                tgt_data,
1902                read_data,
1903                rng,
1904            ),
1905            Tactic::BorealHammer => self.handle_boreal_hammer_attack(
1906                agent,
1907                controller,
1908                &attack_data,
1909                tgt_data,
1910                read_data,
1911                rng,
1912            ),
1913            Tactic::BorealBow => self.handle_boreal_bow_attack(
1914                agent,
1915                controller,
1916                &attack_data,
1917                tgt_data,
1918                read_data,
1919                rng,
1920            ),
1921            Tactic::FireGigas => self.handle_firegigas_attack(
1922                agent,
1923                controller,
1924                &attack_data,
1925                tgt_data,
1926                read_data,
1927                rng,
1928            ),
1929            Tactic::AshenAxe => self.handle_ashen_axe_attack(
1930                agent,
1931                controller,
1932                &attack_data,
1933                tgt_data,
1934                read_data,
1935                rng,
1936            ),
1937            Tactic::AshenStaff => self.handle_ashen_staff_attack(
1938                agent,
1939                controller,
1940                &attack_data,
1941                tgt_data,
1942                read_data,
1943                rng,
1944            ),
1945            Tactic::SwordSimple => self.handle_sword_simple_attack(
1946                agent,
1947                controller,
1948                &attack_data,
1949                tgt_data,
1950                read_data,
1951            ),
1952            Tactic::AdletHunter => {
1953                self.handle_adlet_hunter(agent, controller, &attack_data, tgt_data, read_data, rng)
1954            },
1955            Tactic::AdletIcepicker => {
1956                self.handle_adlet_icepicker(agent, controller, &attack_data, tgt_data, read_data)
1957            },
1958            Tactic::AdletTracker => {
1959                self.handle_adlet_tracker(agent, controller, &attack_data, tgt_data, read_data)
1960            },
1961            Tactic::IceDrake => {
1962                self.handle_icedrake(agent, controller, &attack_data, tgt_data, read_data, rng)
1963            },
1964            Tactic::Hydra => {
1965                self.handle_hydra(agent, controller, &attack_data, tgt_data, read_data, rng)
1966            },
1967            Tactic::BloodmoonBat => self.handle_bloodmoon_bat_attack(
1968                agent,
1969                controller,
1970                &attack_data,
1971                tgt_data,
1972                read_data,
1973                rng,
1974            ),
1975            Tactic::VampireBat => self.handle_vampire_bat_attack(
1976                agent,
1977                controller,
1978                &attack_data,
1979                tgt_data,
1980                read_data,
1981                rng,
1982            ),
1983            Tactic::BloodmoonHeiress => self.handle_bloodmoon_heiress_attack(
1984                agent,
1985                controller,
1986                &attack_data,
1987                tgt_data,
1988                read_data,
1989                rng,
1990            ),
1991            Tactic::RandomAbilities {
1992                primary,
1993                secondary,
1994                abilities,
1995            } => self.handle_random_abilities(
1996                agent,
1997                controller,
1998                &attack_data,
1999                tgt_data,
2000                read_data,
2001                rng,
2002                primary,
2003                secondary,
2004                abilities,
2005            ),
2006            Tactic::AdletElder => {
2007                self.handle_adlet_elder(agent, controller, &attack_data, tgt_data, read_data, rng)
2008            },
2009            Tactic::HaniwaSoldier => {
2010                self.handle_haniwa_soldier(agent, controller, &attack_data, tgt_data, read_data)
2011            },
2012            Tactic::HaniwaGuard => {
2013                self.handle_haniwa_guard(agent, controller, &attack_data, tgt_data, read_data, rng)
2014            },
2015            Tactic::HaniwaArcher => {
2016                self.handle_haniwa_archer(agent, controller, &attack_data, tgt_data, read_data)
2017            },
2018        }
2019    }
2020
2021    pub fn handle_sounds_heard(
2022        &self,
2023        agent: &mut Agent,
2024        controller: &mut Controller,
2025        read_data: &ReadData,
2026        emitters: &mut AgentEmitters,
2027        rng: &mut impl Rng,
2028    ) {
2029        agent.forget_old_sounds(read_data.time.0);
2030
2031        if is_invulnerable(*self.entity, read_data) || is_steering(*self.entity, read_data) {
2032            self.idle(agent, controller, read_data, emitters, rng);
2033            return;
2034        }
2035
2036        if let Some(sound) = agent.sounds_heard.last() {
2037            let sound_pos = Pos(sound.pos);
2038            let dist_sqrd = self.pos.0.distance_squared(sound_pos.0);
2039            // NOTE: There is an implicit distance requirement given that sound volume
2040            // dissipates as it travels, but we will not want to flee if a sound is super
2041            // loud but heard from a great distance, regardless of how loud it was.
2042            // `is_close` is this limiter.
2043            let is_close = dist_sqrd < 35.0_f32.powi(2);
2044
2045            let sound_was_loud = sound.vol >= 10.0;
2046            let sound_was_threatening = sound_was_loud
2047                || matches!(sound.kind, SoundKind::Utterance(UtteranceKind::Scream, _));
2048
2049            let has_enemy_alignment = matches!(self.alignment, Some(Alignment::Enemy));
2050            let follows_threatening_sounds =
2051                has_enemy_alignment || is_village_guard(*self.entity, read_data);
2052
2053            if sound_was_threatening && is_close {
2054                if !self.below_flee_health(agent) && follows_threatening_sounds {
2055                    self.follow(agent, controller, read_data, &sound_pos);
2056                } else if self.below_flee_health(agent) || !follows_threatening_sounds {
2057                    self.flee(agent, controller, read_data, &sound_pos);
2058                } else {
2059                    self.idle(agent, controller, read_data, emitters, rng);
2060                }
2061            } else {
2062                self.idle(agent, controller, read_data, emitters, rng);
2063            }
2064        } else {
2065            self.idle(agent, controller, read_data, emitters, rng);
2066        }
2067    }
2068
2069    pub fn attack_target_attacker(
2070        &self,
2071        agent: &mut Agent,
2072        read_data: &ReadData,
2073        controller: &mut Controller,
2074        emitters: &mut AgentEmitters,
2075        rng: &mut impl Rng,
2076    ) {
2077        if let Some(Target { target, .. }) = agent.target
2078            && let Some(tgt_health) = read_data.healths.get(target)
2079            && let Some(by) = tgt_health.last_change.damage_by()
2080            && let Some(attacker) = get_entity_by_id(by.uid(), read_data)
2081        {
2082            if agent.target.is_none() {
2083                controller.push_utterance(UtteranceKind::Angry);
2084            }
2085
2086            let attacker_pos = read_data.positions.get(attacker).map(|pos| pos.0);
2087            agent.target = Some(Target::new(
2088                attacker,
2089                true,
2090                read_data.time.0,
2091                true,
2092                attacker_pos,
2093            ));
2094
2095            if let Some(tgt_pos) = read_data.positions.get(attacker) {
2096                if is_dead_or_invulnerable(attacker, read_data) {
2097                    agent.target = Some(Target::new(
2098                        target,
2099                        false,
2100                        read_data.time.0,
2101                        false,
2102                        Some(tgt_pos.0),
2103                    ));
2104
2105                    self.idle(agent, controller, read_data, emitters, rng);
2106                } else {
2107                    let target_data = TargetData::new(tgt_pos, target, read_data);
2108                    // TODO: Reimplement this in rtsim
2109                    // if let Some(tgt_name) =
2110                    //     read_data.stats.get(target).map(|stats| stats.name.clone())
2111                    // {
2112                    //     agent.add_fight_to_memory(&tgt_name, read_data.time.0)
2113                    // }
2114                    self.attack(agent, controller, &target_data, read_data, rng);
2115                }
2116            }
2117        }
2118    }
2119
2120    // TODO: Pass a localisation key instead of `Content` to avoid allocating if
2121    // we're not permitted to speak.
2122    pub fn chat_npc_if_allowed_to_speak(
2123        &self,
2124        msg: Content,
2125        agent: &Agent,
2126        emitters: &mut AgentEmitters,
2127    ) -> bool {
2128        if agent.allowed_to_speak() {
2129            self.chat_npc(msg, emitters);
2130            true
2131        } else {
2132            false
2133        }
2134    }
2135
2136    pub fn chat_npc(&self, content: Content, emitters: &mut AgentEmitters) {
2137        emitters.emit(ChatEvent {
2138            msg: UnresolvedChatMsg::npc(*self.uid, content),
2139            from_client: false,
2140        });
2141    }
2142
2143    fn emit_scream(&self, time: f64, emitters: &mut AgentEmitters) {
2144        if let Some(body) = self.body {
2145            emitters.emit(SoundEvent {
2146                sound: Sound::new(
2147                    SoundKind::Utterance(UtteranceKind::Scream, *body),
2148                    self.pos.0,
2149                    13.0,
2150                    time,
2151                ),
2152            });
2153        }
2154    }
2155
2156    pub fn cry_out(&self, agent: &Agent, emitters: &mut AgentEmitters, read_data: &ReadData) {
2157        let has_enemy_alignment = matches!(self.alignment, Some(Alignment::Enemy));
2158        let is_below_flee_health = self.below_flee_health(agent);
2159
2160        if has_enemy_alignment && is_below_flee_health {
2161            self.chat_npc_if_allowed_to_speak(
2162                Content::localized("npc-speech-cultist_low_health_fleeing"),
2163                agent,
2164                emitters,
2165            );
2166        } else if is_villager(self.alignment) {
2167            self.chat_npc_if_allowed_to_speak(
2168                Content::localized("npc-speech-villager_under_attack"),
2169                agent,
2170                emitters,
2171            );
2172            self.emit_scream(read_data.time.0, emitters);
2173        }
2174    }
2175
2176    pub fn exclaim_relief_about_enemy_dead(&self, agent: &Agent, emitters: &mut AgentEmitters) {
2177        if is_villager(self.alignment) {
2178            self.chat_npc_if_allowed_to_speak(
2179                Content::localized("npc-speech-villager_enemy_killed"),
2180                agent,
2181                emitters,
2182            );
2183        }
2184    }
2185
2186    pub fn below_flee_health(&self, agent: &Agent) -> bool {
2187        self.damage.min(1.0) < agent.psyche.flee_health
2188    }
2189
2190    pub fn is_more_dangerous_than_target(
2191        &self,
2192        entity: EcsEntity,
2193        target: Target,
2194        read_data: &ReadData,
2195    ) -> bool {
2196        let entity_pos = read_data.positions.get(entity);
2197        let target_pos = read_data.positions.get(target.target);
2198
2199        entity_pos.is_some_and(|entity_pos| {
2200            target_pos.is_none_or(|target_pos| {
2201                // Fuzzy factor that makes it harder for players to cheese enemies by making
2202                // them quickly flip aggro between two players.
2203                // It does this by only switching aggro if the entity is closer to the enemy by
2204                // a specific proportional threshold.
2205                const FUZZY_DIST_COMPARISON: f32 = 0.8;
2206
2207                let is_target_further = target_pos.0.distance(entity_pos.0)
2208                    < target_pos.0.distance(entity_pos.0) * FUZZY_DIST_COMPARISON;
2209                let is_entity_hostile = read_data
2210                    .alignments
2211                    .get(entity)
2212                    .zip(self.alignment)
2213                    .is_some_and(|(entity, me)| me.hostile_towards(*entity));
2214
2215                // Consider entity more dangerous than target if entity is closer or if target
2216                // had not triggered aggro.
2217                !target.aggro_on || (is_target_further && is_entity_hostile)
2218            })
2219        })
2220    }
2221
2222    pub fn is_enemy(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2223        let other_alignment = read_data.alignments.get(entity);
2224
2225        (entity != *self.entity)
2226            && !self.passive_towards(entity, read_data)
2227            && (are_our_owners_hostile(self.alignment, other_alignment, read_data)
2228                || (is_villager(self.alignment) && is_dressed_as_cultist(entity, read_data)
2229                    || (is_villager(self.alignment) && is_dressed_as_witch(entity, read_data))
2230                    || (is_villager(self.alignment) && is_dressed_as_pirate(entity, read_data))))
2231    }
2232
2233    pub fn is_hunting_animal(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2234        (entity != *self.entity)
2235            && !self.friendly_towards(entity, read_data)
2236            && matches!(read_data.bodies.get(entity), Some(Body::QuadrupedSmall(_)))
2237    }
2238
2239    fn should_defend(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2240        let entity_alignment = read_data.alignments.get(entity);
2241
2242        let we_are_friendly = entity_alignment.is_some_and(|entity_alignment| {
2243            self.alignment
2244                .is_some_and(|alignment| !alignment.hostile_towards(*entity_alignment))
2245        });
2246        let we_share_species = read_data.bodies.get(entity).is_some_and(|entity_body| {
2247            self.body.is_some_and(|body| {
2248                entity_body.is_same_species_as(body)
2249                    || (entity_body.is_humanoid() && body.is_humanoid())
2250            })
2251        });
2252        let self_owns_entity =
2253            matches!(entity_alignment, Some(Alignment::Owned(ouid)) if *self.uid == *ouid);
2254
2255        (we_are_friendly && we_share_species)
2256            || (is_village_guard(*self.entity, read_data) && is_villager(entity_alignment))
2257            || self_owns_entity
2258    }
2259
2260    fn passive_towards(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2261        if let (Some(self_alignment), Some(other_alignment)) =
2262            (self.alignment, read_data.alignments.get(entity))
2263        {
2264            self_alignment.passive_towards(*other_alignment)
2265        } else {
2266            false
2267        }
2268    }
2269
2270    fn friendly_towards(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2271        if let (Some(self_alignment), Some(other_alignment)) =
2272            (self.alignment, read_data.alignments.get(entity))
2273        {
2274            self_alignment.friendly_towards(*other_alignment)
2275        } else {
2276            false
2277        }
2278    }
2279
2280    pub fn can_see_entity(
2281        &self,
2282        agent: &Agent,
2283        controller: &Controller,
2284        other: EcsEntity,
2285        other_pos: &Pos,
2286        other_scale: Option<&Scale>,
2287        read_data: &ReadData,
2288    ) -> bool {
2289        let other_stealth_multiplier = {
2290            let other_inventory = read_data.inventories.get(other);
2291            let other_char_state = read_data.char_states.get(other);
2292
2293            perception_dist_multiplier_from_stealth(other_inventory, other_char_state, self.msm)
2294        };
2295
2296        let within_sight_dist = {
2297            let sight_dist = agent.psyche.sight_dist * other_stealth_multiplier;
2298            let dist_sqrd = other_pos.0.distance_squared(self.pos.0);
2299
2300            dist_sqrd < sight_dist.powi(2)
2301        };
2302
2303        let within_fov = (other_pos.0 - self.pos.0)
2304            .try_normalized()
2305            .is_some_and(|v| v.dot(*controller.inputs.look_dir) > 0.15);
2306
2307        let other_body = read_data.bodies.get(other);
2308
2309        (within_sight_dist)
2310            && within_fov
2311            && entities_have_line_of_sight(
2312                self.pos,
2313                self.body,
2314                self.scale,
2315                other_pos,
2316                other_body,
2317                other_scale,
2318                read_data,
2319            )
2320    }
2321
2322    pub fn detects_other(
2323        &self,
2324        agent: &Agent,
2325        controller: &Controller,
2326        other: &EcsEntity,
2327        other_pos: &Pos,
2328        other_scale: Option<&Scale>,
2329        read_data: &ReadData,
2330    ) -> bool {
2331        self.can_sense_directly_near(other_pos)
2332            || self.can_see_entity(agent, controller, *other, other_pos, other_scale, read_data)
2333    }
2334
2335    pub fn can_sense_directly_near(&self, e_pos: &Pos) -> bool {
2336        let chance = rng().random_bool(0.3);
2337        e_pos.0.distance_squared(self.pos.0) < 5_f32.powi(2) && chance
2338    }
2339
2340    pub fn menacing(
2341        &self,
2342        agent: &mut Agent,
2343        controller: &mut Controller,
2344        target: EcsEntity,
2345        tgt_data: &TargetData,
2346        read_data: &ReadData,
2347        emitters: &mut AgentEmitters,
2348        remembers_fight_with_target: bool,
2349    ) {
2350        let max_move = 0.5;
2351        let move_dir = controller.inputs.move_dir;
2352        let move_dir_mag = move_dir.magnitude();
2353        let mut chat = |agent: &mut Agent, content: Content| {
2354            self.chat_npc_if_allowed_to_speak(content, agent, emitters);
2355        };
2356        let mut chat_villager_remembers_fighting = |agent: &mut Agent| {
2357            let tgt_name = read_data.stats.get(target).map(|stats| stats.name.clone());
2358
2359            // TODO: Localise
2360            // Is this thing even used??
2361            if let Some(tgt_name) = tgt_name.as_ref().and_then(|name| name.as_plain()) {
2362                chat(
2363                    agent,
2364                    Content::localized_with_args("npc-speech-remembers-fight", [(
2365                        "name", tgt_name,
2366                    )]),
2367                )
2368            } else {
2369                chat(
2370                    agent,
2371                    Content::localized("npc-speech-remembers-fight-no-name"),
2372                );
2373            }
2374        };
2375
2376        self.look_toward(controller, read_data, target);
2377        controller.push_action(ControlAction::Wield);
2378
2379        if move_dir_mag > max_move {
2380            controller.inputs.move_dir = max_move * move_dir / move_dir_mag;
2381        }
2382
2383        match agent
2384            .timer
2385            .timeout_elapsed(read_data.time.0, comp::agent::TimerAction::Warn, 5.0)
2386        {
2387            Some(true) | None => {
2388                self.path_toward_target(
2389                    agent,
2390                    controller,
2391                    tgt_data.pos.0,
2392                    read_data,
2393                    Path::AtTarget,
2394                    Some(0.4),
2395                );
2396            },
2397            Some(false) => {
2398                agent
2399                    .timer
2400                    .start(read_data.time.0, comp::agent::TimerAction::Warn);
2401                controller.push_utterance(UtteranceKind::Angry);
2402                if is_villager(self.alignment) {
2403                    if remembers_fight_with_target {
2404                        chat_villager_remembers_fighting(agent);
2405                    } else if is_dressed_as_cultist(target, read_data) {
2406                        chat(
2407                            agent,
2408                            Content::localized("npc-speech-villager_cultist_alarm"),
2409                        );
2410                    } else if is_dressed_as_witch(target, read_data) {
2411                        chat(agent, Content::localized("npc-speech-villager_witch_alarm"));
2412                    } else if is_dressed_as_pirate(target, read_data) {
2413                        chat(
2414                            agent,
2415                            Content::localized("npc-speech-villager_pirate_alarm"),
2416                        );
2417                    } else {
2418                        chat(agent, Content::localized("npc-speech-menacing"));
2419                    }
2420                } else {
2421                    chat(agent, Content::localized("npc-speech-menacing"));
2422                }
2423            },
2424        }
2425    }
2426
2427    /// Dismount if riding something the agent can't control.
2428    pub fn dismount_uncontrollable(&self, controller: &mut Controller, read_data: &ReadData) {
2429        if read_data.is_riders.get(*self.entity).is_some_and(|mount| {
2430            read_data
2431                .id_maps
2432                .uid_entity(mount.mount)
2433                .and_then(|e| read_data.bodies.get(e))
2434                .is_none_or(|b| b.has_free_will())
2435        }) || read_data
2436            .is_volume_riders
2437            .get(*self.entity)
2438            .is_some_and(|r| !r.is_steering_entity())
2439        {
2440            controller.push_event(ControlEvent::Unmount);
2441        }
2442    }
2443
2444    /// Dismount if riding something.
2445    ///
2446    /// Currently there's an exception for if the agent is steering a volume
2447    /// entity.
2448    pub fn dismount(&self, controller: &mut Controller, read_data: &ReadData) {
2449        if read_data.is_riders.contains(*self.entity)
2450            || read_data
2451                .is_volume_riders
2452                .get(*self.entity)
2453                .is_some_and(|r| !r.is_steering_entity())
2454        {
2455            controller.push_event(ControlEvent::Unmount);
2456        }
2457    }
2458}