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 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 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 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 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 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 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 if lantern_equipped && rng.random_bool(0.001) {
237 if day_period.is_dark() && !lantern_turned_on {
238 controller.push_event(ControlEvent::EnableLantern)
243 } else if lantern_turned_on && day_period.is_light() {
244 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 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 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 for i in 0..=NUM_RAYS {
338 let magnitude = self.body.map_or(20.0, |b| b.flying_height());
339 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 } else {
363 -2.0
364 } } else {
366 0.05 };
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 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 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; },
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 controller.push_basic_input(InputKind::Fly);
418
419 if let Some(direction) = direction_override {
434 controller.inputs.look_dir = direction;
435 } else {
436 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 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 #[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 if terrain_alt >= self.pos.0.z - 32.0 {
498 controller.inputs.move_z = 1.0 * speed_factor;
501 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 mpid.limit_windup_z(|z| *z = z.clamp(-20.0, 20.0));
515 } else {
516 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 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 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; },
556 Some(NpcActivity::Gather(_resources)) => {
557 controller.push_action(ControlAction::Dance);
559 break 'activity; },
561 Some(NpcActivity::Dance(dir)) => {
562 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; },
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; },
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; },
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 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 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 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 controller.push_basic_input(InputKind::Fly);
695 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 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 .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 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 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 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 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 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 pub fn heal_self(
899 &self,
900 _agent: &mut Agent,
901 controller: &mut Controller,
902 relaxed: bool,
903 ) -> bool {
904 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 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 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 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 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 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 = 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 let wants_pickup = !avoids_item_drops
1084 && (is_humanoid || matches!(item, body::item::Body::Consumable));
1085
1086 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 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 (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 && 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 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 "Elephant" => Tactic::Elephant,
1284 "Rocksnapper" => Tactic::Rocksnapper,
1285 "Roshwalr" => Tactic::Roshwalr,
1286 "Asp" | "Maneater" => Tactic::QuadLowRanged,
1287 "Quad Low Breathe" | "Quad Low Beam" | "Basilisk" => {
1288 Tactic::QuadLowBeam
1289 },
1290 "Organ" => Tactic::OrganAura,
1291 "Quad Low Tail" | "Husk Brute" => Tactic::TailSlap,
1292 "Quad Low Quick" => Tactic::QuadLowQuick,
1293 "Quad Low Basic" => Tactic::QuadLowBasic,
1294 "Theropod Basic" | "Theropod Bird" | "Theropod Small" => {
1295 Tactic::Theropod
1296 },
1297 "Antlion" => Tactic::ArthropodMelee,
1299 "Tarantula" | "Horn Beetle" => Tactic::ArthropodAmbush,
1300 "Weevil" | "Black Widow" | "Crawler" => Tactic::ArthropodRanged,
1301 "Theropod Charge" => Tactic::CircleCharge {
1302 radius: 6,
1303 circle_time: 1,
1304 },
1305 "Turret" => Tactic::RadialTurret,
1306 "Flamethrower" => Tactic::RadialTurret,
1307 "Haniwa Sentry" => Tactic::RotatingTurret,
1308 "Bird Large Breathe" => Tactic::BirdLargeBreathe,
1309 "Bird Large Fire" => Tactic::BirdLargeFire,
1310 "Bird Large Basic" => Tactic::BirdLargeBasic,
1311 "Flame Wyvern" | "Frost Wyvern" | "Cloud Wyvern" | "Sea Wyvern"
1312 | "Weald Wyvern" => Tactic::Wyvern,
1313 "Bird Medium Basic" => Tactic::BirdMediumBasic,
1314 "Bushly" | "Cactid" | "Irrwurz" | "Driggle" | "Mossy Snail"
1315 | "Strigoi Claws" | "Harlequin" => Tactic::SimpleDouble,
1316 "Clay Golem" => Tactic::ClayGolem,
1317 "Ancient Effigy" => Tactic::AncientEffigy,
1318 "TerracottaStatue" | "Mogwai" => Tactic::TerracottaStatue,
1319 "TerracottaBesieger" => Tactic::Bow,
1320 "TerracottaDemolisher" => Tactic::SimpleDouble,
1321 "TerracottaPunisher" => Tactic::SimpleMelee,
1322 "TerracottaPursuer" => Tactic::SwordSimple,
1323 "Cursekeeper" => Tactic::Cursekeeper,
1324 "CursekeeperFake" => Tactic::CursekeeperFake,
1325 "ShamanicSpirit" => Tactic::ShamanicSpirit,
1326 "Jiangshi" => Tactic::Jiangshi,
1327 "Mindflayer" => Tactic::Mindflayer,
1328 "Flamekeeper" => Tactic::Flamekeeper,
1329 "Forgemaster" => Tactic::Forgemaster,
1330 "Minotaur" => Tactic::Minotaur,
1331 "Cyclops" => Tactic::Cyclops,
1332 "Dullahan" => Tactic::Dullahan,
1333 "Grave Warden" => Tactic::GraveWarden,
1334 "Tidal Warrior" => Tactic::TidalWarrior,
1335 "Karkatha" => Tactic::Karkatha,
1336 "Tidal Totem"
1337 | "Tornado"
1338 | "Gnarling Totem Red"
1339 | "Gnarling Totem Green"
1340 | "Gnarling Totem White" => Tactic::RadialTurret,
1341 "FieryTornado" => Tactic::FieryTornado,
1342 "Yeti" => Tactic::Yeti,
1343 "Harvester" => Tactic::Harvester,
1344 "Cardinal" => Tactic::Cardinal,
1345 "Sea Bishop" => Tactic::SeaBishop,
1346 "Dagon" => Tactic::Dagon,
1347 "Snaretongue" => Tactic::Snaretongue,
1348 "Dagonite" => Tactic::ArthropodAmbush,
1349 "Gnarling Dagger" => Tactic::SimpleBackstab,
1350 "Gnarling Blowgun" => Tactic::ElevatedRanged,
1351 "Deadwood" => Tactic::Deadwood,
1352 "Mandragora" => Tactic::Mandragora,
1353 "Wood Golem" => Tactic::WoodGolem,
1354 "Gnarling Chieftain" => Tactic::GnarlingChieftain,
1355 "Frost Gigas" => Tactic::FrostGigas,
1356 "Boreal Hammer" => Tactic::BorealHammer,
1357 "Boreal Bow" => Tactic::BorealBow,
1358 "Fire Gigas" => Tactic::FireGigas,
1359 "Ashen Axe" => Tactic::AshenAxe,
1360 "Ashen Staff" => Tactic::AshenStaff,
1361 "Adlet Hunter" => Tactic::AdletHunter,
1362 "Adlet Icepicker" => Tactic::AdletIcepicker,
1363 "Adlet Tracker" => Tactic::AdletTracker,
1364 "Hydra" => Tactic::Hydra,
1365 "Ice Drake" => Tactic::IceDrake,
1366 "Frostfang" => Tactic::RandomAbilities {
1367 primary: 1,
1368 secondary: 3,
1369 abilities: [0; BASE_ABILITY_LIMIT],
1370 },
1371 "Tursus Claws" => Tactic::RandomAbilities {
1372 primary: 2,
1373 secondary: 1,
1374 abilities: [4, 0, 0, 0, 0],
1375 },
1376 "Adlet Elder" => Tactic::AdletElder,
1377 "Haniwa Soldier" => Tactic::HaniwaSoldier,
1378 "Haniwa Guard" => Tactic::HaniwaGuard,
1379 "Haniwa Archer" => Tactic::HaniwaArcher,
1380 "Bloodmoon Bat" => Tactic::BloodmoonBat,
1381 "Vampire Bat" => Tactic::VampireBat,
1382 "Bloodmoon Heiress" => Tactic::BloodmoonHeiress,
1383
1384 _ => Tactic::SimpleMelee,
1385 },
1386 AbilitySpec::Tool(tool_kind) => tool_tactic(*tool_kind),
1387 }
1388 } else if let ItemKind::Tool(tool) = &*item.kind() {
1389 tool_tactic(tool.kind)
1390 } else {
1391 Tactic::SimpleMelee
1392 }
1393 })
1394 .unwrap_or(Tactic::SimpleMelee);
1395
1396 controller.push_action(ControlAction::Wield);
1398
1399 let self_radius = self.body.map_or(0.5, |b| b.max_radius()) * self.scale;
1402 let self_attack_range =
1403 (self.body.map_or(0.5, |b| b.front_radius()) + DEFAULT_ATTACK_RANGE) * self.scale;
1404 let tgt_radius =
1405 tgt_data.body.map_or(0.5, |b| b.max_radius()) * tgt_data.scale.map_or(1.0, |s| s.0);
1406 let min_attack_dist = self_attack_range + tgt_radius;
1407 let body_dist = self_radius + tgt_radius;
1408 let dist_sqrd = self.pos.0.distance_squared(tgt_data.pos.0);
1409 let angle = self
1410 .ori
1411 .look_vec()
1412 .angle_between(tgt_data.pos.0 - self.pos.0)
1413 .to_degrees();
1414 let angle_xy = self
1415 .ori
1416 .look_vec()
1417 .xy()
1418 .angle_between((tgt_data.pos.0 - self.pos.0).xy())
1419 .to_degrees();
1420
1421 let eye_offset = self.body.map_or(0.0, |b| b.eye_height(self.scale));
1422
1423 let tgt_eye_height = tgt_data
1424 .body
1425 .map_or(0.0, |b| b.eye_height(tgt_data.scale.map_or(1.0, |s| s.0)));
1426 let tgt_eye_offset = tgt_eye_height +
1427 if tactic == Tactic::QuadMedJump {
1432 1.0
1433 } else if matches!(tactic, Tactic::QuadLowRanged) {
1434 -1.0
1435 } else {
1436 0.0
1437 };
1438
1439 if let Some(dir) = match self.char_state {
1454 CharacterState::ChargedRanged(c) if dist_sqrd > 0.0 => {
1455 let charge_factor =
1456 c.timer.as_secs_f32() / c.static_data.charge_duration.as_secs_f32();
1457 let projectile_speed = c.static_data.initial_projectile_speed
1458 + charge_factor * c.static_data.scaled_projectile_speed;
1459 aim_projectile(
1460 projectile_speed,
1461 self.pos.0
1462 + self.body.map_or(Vec3::zero(), |body| {
1463 body.projectile_offsets(self.ori.look_vec(), self.scale)
1464 }),
1465 Vec3::new(
1466 tgt_data.pos.0.x,
1467 tgt_data.pos.0.y,
1468 tgt_data.pos.0.z + tgt_eye_offset,
1469 ),
1470 )
1471 },
1472 CharacterState::BasicRanged(c) => {
1473 let offset_z = match c.static_data.projectile.kind {
1474 ProjectileConstructorKind::Explosive { .. }
1476 | ProjectileConstructorKind::ExplosiveHazard { .. }
1477 | ProjectileConstructorKind::Hazard { .. } => 0.0,
1478 _ => tgt_eye_offset,
1479 };
1480 let projectile_speed = c.static_data.projectile_speed;
1481 aim_projectile(
1482 projectile_speed,
1483 self.pos.0
1484 + self.body.map_or(Vec3::zero(), |body| {
1485 body.projectile_offsets(self.ori.look_vec(), self.scale)
1486 }),
1487 Vec3::new(
1488 tgt_data.pos.0.x,
1489 tgt_data.pos.0.y,
1490 tgt_data.pos.0.z + offset_z,
1491 ),
1492 )
1493 },
1494 CharacterState::RepeaterRanged(c) => {
1495 let projectile_speed = c.static_data.projectile_speed;
1496 aim_projectile(
1497 projectile_speed,
1498 self.pos.0
1499 + self.body.map_or(Vec3::zero(), |body| {
1500 body.projectile_offsets(self.ori.look_vec(), self.scale)
1501 }),
1502 Vec3::new(
1503 tgt_data.pos.0.x,
1504 tgt_data.pos.0.y,
1505 tgt_data.pos.0.z + tgt_eye_offset,
1506 ),
1507 )
1508 },
1509 CharacterState::LeapMelee(_)
1510 if matches!(tactic, Tactic::Hammer | Tactic::BorealHammer | Tactic::Axe) =>
1511 {
1512 let direction_weight = match tactic {
1513 Tactic::Hammer | Tactic::BorealHammer => 0.1,
1514 Tactic::Axe => 0.3,
1515 _ => unreachable!("Direction weight called on incorrect tactic."),
1516 };
1517
1518 let tgt_pos = tgt_data.pos.0;
1519 let self_pos = self.pos.0;
1520
1521 let delta_x = (tgt_pos.x - self_pos.x) * direction_weight;
1522 let delta_y = (tgt_pos.y - self_pos.y) * direction_weight;
1523
1524 Dir::from_unnormalized(Vec3::new(delta_x, delta_y, -1.0))
1525 },
1526 CharacterState::BasicBeam(_) => {
1527 let aim_from = self.body.map_or(self.pos.0, |body| {
1528 self.pos.0
1529 + basic_beam::beam_offsets(
1530 body,
1531 controller.inputs.look_dir,
1532 self.ori.look_vec(),
1533 self.vel.0 - self.physics_state.ground_vel,
1535 self.physics_state.on_ground,
1536 )
1537 });
1538 let aim_to = Vec3::new(
1539 tgt_data.pos.0.x,
1540 tgt_data.pos.0.y,
1541 tgt_data.pos.0.z + tgt_eye_offset,
1542 );
1543 Dir::from_unnormalized(aim_to - aim_from)
1544 },
1545 _ => {
1546 let aim_from = Vec3::new(self.pos.0.x, self.pos.0.y, self.pos.0.z + eye_offset);
1547 let aim_to = Vec3::new(
1548 tgt_data.pos.0.x,
1549 tgt_data.pos.0.y,
1550 tgt_data.pos.0.z + tgt_eye_offset,
1551 );
1552 Dir::from_unnormalized(aim_to - aim_from)
1553 },
1554 } {
1555 controller.inputs.look_dir = dir;
1556 }
1557
1558 let attack_data = AttackData {
1559 body_dist,
1560 min_attack_dist,
1561 dist_sqrd,
1562 angle,
1563 angle_xy,
1564 };
1565
1566 match tactic {
1569 Tactic::SimpleFlyingMelee => self.handle_simple_flying_melee(
1570 agent,
1571 controller,
1572 &attack_data,
1573 tgt_data,
1574 read_data,
1575 rng,
1576 ),
1577 Tactic::SimpleMelee => {
1578 self.handle_simple_melee(agent, controller, &attack_data, tgt_data, read_data, rng)
1579 },
1580 Tactic::Axe => {
1581 self.handle_axe_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1582 },
1583 Tactic::Hammer => {
1584 self.handle_hammer_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1585 },
1586 Tactic::Sword => {
1587 self.handle_sword_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1588 },
1589 Tactic::Bow => {
1590 self.handle_bow_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1591 },
1592 Tactic::Staff => {
1593 self.handle_staff_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1594 },
1595 Tactic::Sceptre => self.handle_sceptre_attack(
1596 agent,
1597 controller,
1598 &attack_data,
1599 tgt_data,
1600 read_data,
1601 rng,
1602 ),
1603 Tactic::StoneGolem => {
1604 self.handle_stone_golem_attack(agent, controller, &attack_data, tgt_data, read_data)
1605 },
1606 Tactic::IronGolem => {
1607 self.handle_iron_golem_attack(agent, controller, &attack_data, tgt_data, read_data)
1608 },
1609 Tactic::CircleCharge {
1610 radius,
1611 circle_time,
1612 } => self.handle_circle_charge_attack(
1613 agent,
1614 controller,
1615 &attack_data,
1616 tgt_data,
1617 read_data,
1618 radius,
1619 circle_time,
1620 rng,
1621 ),
1622 Tactic::QuadLowRanged => self.handle_quadlow_ranged_attack(
1623 agent,
1624 controller,
1625 &attack_data,
1626 tgt_data,
1627 read_data,
1628 ),
1629 Tactic::TailSlap => {
1630 self.handle_tail_slap_attack(agent, controller, &attack_data, tgt_data, read_data)
1631 },
1632 Tactic::QuadLowQuick => self.handle_quadlow_quick_attack(
1633 agent,
1634 controller,
1635 &attack_data,
1636 tgt_data,
1637 read_data,
1638 ),
1639 Tactic::QuadLowBasic => self.handle_quadlow_basic_attack(
1640 agent,
1641 controller,
1642 &attack_data,
1643 tgt_data,
1644 read_data,
1645 ),
1646 Tactic::QuadMedJump => self.handle_quadmed_jump_attack(
1647 agent,
1648 controller,
1649 &attack_data,
1650 tgt_data,
1651 read_data,
1652 ),
1653 Tactic::QuadMedBasic => self.handle_quadmed_basic_attack(
1654 agent,
1655 controller,
1656 &attack_data,
1657 tgt_data,
1658 read_data,
1659 ),
1660 Tactic::QuadMedHoof => self.handle_quadmed_hoof_attack(
1661 agent,
1662 controller,
1663 &attack_data,
1664 tgt_data,
1665 read_data,
1666 ),
1667 Tactic::QuadLowBeam => self.handle_quadlow_beam_attack(
1668 agent,
1669 controller,
1670 &attack_data,
1671 tgt_data,
1672 read_data,
1673 ),
1674 Tactic::Elephant => self.handle_elephant_attack(
1675 agent,
1676 controller,
1677 &attack_data,
1678 tgt_data,
1679 read_data,
1680 rng,
1681 ),
1682 Tactic::Rocksnapper => {
1683 self.handle_rocksnapper_attack(agent, controller, &attack_data, tgt_data, read_data)
1684 },
1685 Tactic::Roshwalr => {
1686 self.handle_roshwalr_attack(agent, controller, &attack_data, tgt_data, read_data)
1687 },
1688 Tactic::OrganAura => {
1689 self.handle_organ_aura_attack(agent, controller, &attack_data, tgt_data, read_data)
1690 },
1691 Tactic::Theropod => {
1692 self.handle_theropod_attack(agent, controller, &attack_data, tgt_data, read_data)
1693 },
1694 Tactic::ArthropodMelee => self.handle_arthropod_melee_attack(
1695 agent,
1696 controller,
1697 &attack_data,
1698 tgt_data,
1699 read_data,
1700 ),
1701 Tactic::ArthropodAmbush => self.handle_arthropod_ambush_attack(
1702 agent,
1703 controller,
1704 &attack_data,
1705 tgt_data,
1706 read_data,
1707 rng,
1708 ),
1709 Tactic::ArthropodRanged => self.handle_arthropod_ranged_attack(
1710 agent,
1711 controller,
1712 &attack_data,
1713 tgt_data,
1714 read_data,
1715 ),
1716 Tactic::Turret => {
1717 self.handle_turret_attack(agent, controller, &attack_data, tgt_data, read_data)
1718 },
1719 Tactic::FixedTurret => self.handle_fixed_turret_attack(
1720 agent,
1721 controller,
1722 &attack_data,
1723 tgt_data,
1724 read_data,
1725 ),
1726 Tactic::RotatingTurret => {
1727 self.handle_rotating_turret_attack(agent, controller, tgt_data, read_data)
1728 },
1729 Tactic::Mindflayer => self.handle_mindflayer_attack(
1730 agent,
1731 controller,
1732 &attack_data,
1733 tgt_data,
1734 read_data,
1735 rng,
1736 ),
1737 Tactic::Flamekeeper => {
1738 self.handle_flamekeeper_attack(agent, controller, &attack_data, tgt_data, read_data)
1739 },
1740 Tactic::Forgemaster => {
1741 self.handle_forgemaster_attack(agent, controller, &attack_data, tgt_data, read_data)
1742 },
1743 Tactic::BirdLargeFire => self.handle_birdlarge_fire_attack(
1744 agent,
1745 controller,
1746 &attack_data,
1747 tgt_data,
1748 read_data,
1749 rng,
1750 ),
1751 Tactic::BirdLargeBreathe => self.handle_birdlarge_breathe_attack(
1753 agent,
1754 controller,
1755 &attack_data,
1756 tgt_data,
1757 read_data,
1758 rng,
1759 ),
1760 Tactic::BirdLargeBasic => self.handle_birdlarge_basic_attack(
1761 agent,
1762 controller,
1763 &attack_data,
1764 tgt_data,
1765 read_data,
1766 ),
1767 Tactic::Wyvern => {
1768 self.handle_wyvern_attack(agent, controller, &attack_data, tgt_data, read_data, rng)
1769 },
1770 Tactic::BirdMediumBasic => {
1771 self.handle_simple_melee(agent, controller, &attack_data, tgt_data, read_data, rng)
1772 },
1773 Tactic::SimpleDouble => self.handle_simple_double_attack(
1774 agent,
1775 controller,
1776 &attack_data,
1777 tgt_data,
1778 read_data,
1779 ),
1780 Tactic::Jiangshi => {
1781 self.handle_jiangshi_attack(agent, controller, &attack_data, tgt_data, read_data)
1782 },
1783 Tactic::ClayGolem => {
1784 self.handle_clay_golem_attack(agent, controller, &attack_data, tgt_data, read_data)
1785 },
1786 Tactic::ClaySteed => {
1787 self.handle_clay_steed_attack(agent, controller, &attack_data, tgt_data, read_data)
1788 },
1789 Tactic::AncientEffigy => self.handle_ancient_effigy_attack(
1790 agent,
1791 controller,
1792 &attack_data,
1793 tgt_data,
1794 read_data,
1795 ),
1796 Tactic::TerracottaStatue => {
1797 self.handle_terracotta_statue_attack(agent, controller, &attack_data, read_data)
1798 },
1799 Tactic::Minotaur => {
1800 self.handle_minotaur_attack(agent, controller, &attack_data, tgt_data, read_data)
1801 },
1802 Tactic::Cyclops => {
1803 self.handle_cyclops_attack(agent, controller, &attack_data, tgt_data, read_data)
1804 },
1805 Tactic::Dullahan => {
1806 self.handle_dullahan_attack(agent, controller, &attack_data, tgt_data, read_data)
1807 },
1808 Tactic::GraveWarden => self.handle_grave_warden_attack(
1809 agent,
1810 controller,
1811 &attack_data,
1812 tgt_data,
1813 read_data,
1814 ),
1815 Tactic::TidalWarrior => self.handle_tidal_warrior_attack(
1816 agent,
1817 controller,
1818 &attack_data,
1819 tgt_data,
1820 read_data,
1821 ),
1822 Tactic::Karkatha => self.handle_karkatha_attack(
1823 agent,
1824 controller,
1825 &attack_data,
1826 tgt_data,
1827 read_data,
1828 rng,
1829 ),
1830 Tactic::RadialTurret => self.handle_radial_turret_attack(controller),
1831 Tactic::FieryTornado => self.handle_fiery_tornado_attack(agent, controller),
1832 Tactic::Yeti => {
1833 self.handle_yeti_attack(agent, controller, &attack_data, tgt_data, read_data)
1834 },
1835 Tactic::Harvester => self.handle_harvester_attack(
1836 agent,
1837 controller,
1838 &attack_data,
1839 tgt_data,
1840 read_data,
1841 rng,
1842 ),
1843 Tactic::Cardinal => self.handle_cardinal_attack(
1844 agent,
1845 controller,
1846 &attack_data,
1847 tgt_data,
1848 read_data,
1849 rng,
1850 ),
1851 Tactic::SeaBishop => self.handle_sea_bishop_attack(
1852 agent,
1853 controller,
1854 &attack_data,
1855 tgt_data,
1856 read_data,
1857 rng,
1858 ),
1859 Tactic::Cursekeeper => self.handle_cursekeeper_attack(
1860 agent,
1861 controller,
1862 &attack_data,
1863 tgt_data,
1864 read_data,
1865 rng,
1866 ),
1867 Tactic::CursekeeperFake => {
1868 self.handle_cursekeeper_fake_attack(controller, &attack_data)
1869 },
1870 Tactic::ShamanicSpirit => self.handle_shamanic_spirit_attack(
1871 agent,
1872 controller,
1873 &attack_data,
1874 tgt_data,
1875 read_data,
1876 ),
1877 Tactic::Dagon => {
1878 self.handle_dagon_attack(agent, controller, &attack_data, tgt_data, read_data)
1879 },
1880 Tactic::Snaretongue => {
1881 self.handle_snaretongue_attack(agent, controller, &attack_data, read_data)
1882 },
1883 Tactic::SimpleBackstab => {
1884 self.handle_simple_backstab(agent, controller, &attack_data, tgt_data, read_data)
1885 },
1886 Tactic::ElevatedRanged => {
1887 self.handle_elevated_ranged(agent, controller, &attack_data, tgt_data, read_data)
1888 },
1889 Tactic::Deadwood => {
1890 self.handle_deadwood(agent, controller, &attack_data, tgt_data, read_data)
1891 },
1892 Tactic::Mandragora => {
1893 self.handle_mandragora(agent, controller, &attack_data, tgt_data, read_data)
1894 },
1895 Tactic::WoodGolem => {
1896 self.handle_wood_golem(agent, controller, &attack_data, tgt_data, read_data, rng)
1897 },
1898 Tactic::GnarlingChieftain => self.handle_gnarling_chieftain(
1899 agent,
1900 controller,
1901 &attack_data,
1902 tgt_data,
1903 read_data,
1904 rng,
1905 ),
1906 Tactic::FrostGigas => self.handle_frostgigas_attack(
1907 agent,
1908 controller,
1909 &attack_data,
1910 tgt_data,
1911 read_data,
1912 rng,
1913 ),
1914 Tactic::BorealHammer => self.handle_boreal_hammer_attack(
1915 agent,
1916 controller,
1917 &attack_data,
1918 tgt_data,
1919 read_data,
1920 rng,
1921 ),
1922 Tactic::BorealBow => self.handle_boreal_bow_attack(
1923 agent,
1924 controller,
1925 &attack_data,
1926 tgt_data,
1927 read_data,
1928 rng,
1929 ),
1930 Tactic::FireGigas => self.handle_firegigas_attack(
1931 agent,
1932 controller,
1933 &attack_data,
1934 tgt_data,
1935 read_data,
1936 rng,
1937 ),
1938 Tactic::AshenAxe => self.handle_ashen_axe_attack(
1939 agent,
1940 controller,
1941 &attack_data,
1942 tgt_data,
1943 read_data,
1944 rng,
1945 ),
1946 Tactic::AshenStaff => self.handle_ashen_staff_attack(
1947 agent,
1948 controller,
1949 &attack_data,
1950 tgt_data,
1951 read_data,
1952 rng,
1953 ),
1954 Tactic::SwordSimple => self.handle_sword_simple_attack(
1955 agent,
1956 controller,
1957 &attack_data,
1958 tgt_data,
1959 read_data,
1960 ),
1961 Tactic::AdletHunter => {
1962 self.handle_adlet_hunter(agent, controller, &attack_data, tgt_data, read_data, rng)
1963 },
1964 Tactic::AdletIcepicker => {
1965 self.handle_adlet_icepicker(agent, controller, &attack_data, tgt_data, read_data)
1966 },
1967 Tactic::AdletTracker => {
1968 self.handle_adlet_tracker(agent, controller, &attack_data, tgt_data, read_data)
1969 },
1970 Tactic::IceDrake => {
1971 self.handle_icedrake(agent, controller, &attack_data, tgt_data, read_data, rng)
1972 },
1973 Tactic::Hydra => {
1974 self.handle_hydra(agent, controller, &attack_data, tgt_data, read_data, rng)
1975 },
1976 Tactic::BloodmoonBat => self.handle_bloodmoon_bat_attack(
1977 agent,
1978 controller,
1979 &attack_data,
1980 tgt_data,
1981 read_data,
1982 rng,
1983 ),
1984 Tactic::VampireBat => self.handle_vampire_bat_attack(
1985 agent,
1986 controller,
1987 &attack_data,
1988 tgt_data,
1989 read_data,
1990 rng,
1991 ),
1992 Tactic::BloodmoonHeiress => self.handle_bloodmoon_heiress_attack(
1993 agent,
1994 controller,
1995 &attack_data,
1996 tgt_data,
1997 read_data,
1998 rng,
1999 ),
2000 Tactic::RandomAbilities {
2001 primary,
2002 secondary,
2003 abilities,
2004 } => self.handle_random_abilities(
2005 agent,
2006 controller,
2007 &attack_data,
2008 tgt_data,
2009 read_data,
2010 rng,
2011 primary,
2012 secondary,
2013 abilities,
2014 ),
2015 Tactic::AdletElder => {
2016 self.handle_adlet_elder(agent, controller, &attack_data, tgt_data, read_data, rng)
2017 },
2018 Tactic::HaniwaSoldier => {
2019 self.handle_haniwa_soldier(agent, controller, &attack_data, tgt_data, read_data)
2020 },
2021 Tactic::HaniwaGuard => {
2022 self.handle_haniwa_guard(agent, controller, &attack_data, tgt_data, read_data, rng)
2023 },
2024 Tactic::HaniwaArcher => {
2025 self.handle_haniwa_archer(agent, controller, &attack_data, tgt_data, read_data)
2026 },
2027 }
2028 }
2029
2030 pub fn handle_sounds_heard(
2031 &self,
2032 agent: &mut Agent,
2033 controller: &mut Controller,
2034 read_data: &ReadData,
2035 emitters: &mut AgentEmitters,
2036 rng: &mut impl Rng,
2037 ) {
2038 agent.forget_old_sounds(read_data.time.0);
2039
2040 if is_invulnerable(*self.entity, read_data) || is_steering(*self.entity, read_data) {
2041 self.idle(agent, controller, read_data, emitters, rng);
2042 return;
2043 }
2044
2045 if let Some(sound) = agent.sounds_heard.last() {
2046 let sound_pos = Pos(sound.pos);
2047 let dist_sqrd = self.pos.0.distance_squared(sound_pos.0);
2048 let is_close = dist_sqrd < 35.0_f32.powi(2);
2053
2054 let sound_was_loud = sound.vol >= 10.0;
2055 let sound_was_threatening = sound_was_loud
2056 || matches!(sound.kind, SoundKind::Utterance(UtteranceKind::Scream, _));
2057
2058 let has_enemy_alignment = matches!(self.alignment, Some(Alignment::Enemy));
2059 let follows_threatening_sounds =
2060 has_enemy_alignment || is_village_guard(*self.entity, read_data);
2061
2062 if sound_was_threatening && is_close {
2063 if !self.below_flee_health(agent) && follows_threatening_sounds {
2064 self.follow(agent, controller, read_data, &sound_pos);
2065 } else if self.below_flee_health(agent) || !follows_threatening_sounds {
2066 self.flee(agent, controller, read_data, &sound_pos);
2067 } else {
2068 self.idle(agent, controller, read_data, emitters, rng);
2069 }
2070 } else {
2071 self.idle(agent, controller, read_data, emitters, rng);
2072 }
2073 } else {
2074 self.idle(agent, controller, read_data, emitters, rng);
2075 }
2076 }
2077
2078 pub fn attack_target_attacker(
2079 &self,
2080 agent: &mut Agent,
2081 read_data: &ReadData,
2082 controller: &mut Controller,
2083 emitters: &mut AgentEmitters,
2084 rng: &mut impl Rng,
2085 ) {
2086 if let Some(Target { target, .. }) = agent.target
2087 && let Some(tgt_health) = read_data.healths.get(target)
2088 && let Some(by) = tgt_health.last_change.damage_by()
2089 && let Some(attacker) = get_entity_by_id(by.uid(), read_data)
2090 {
2091 if agent.target.is_none() {
2092 controller.push_utterance(UtteranceKind::Angry);
2093 }
2094
2095 let attacker_pos = read_data.positions.get(attacker).map(|pos| pos.0);
2096 agent.target = Some(Target::new(
2097 attacker,
2098 true,
2099 read_data.time.0,
2100 true,
2101 attacker_pos,
2102 ));
2103
2104 if let Some(tgt_pos) = read_data.positions.get(attacker) {
2105 if is_dead_or_invulnerable(attacker, read_data) {
2106 agent.target = Some(Target::new(
2107 target,
2108 false,
2109 read_data.time.0,
2110 false,
2111 Some(tgt_pos.0),
2112 ));
2113
2114 self.idle(agent, controller, read_data, emitters, rng);
2115 } else {
2116 let target_data = TargetData::new(tgt_pos, target, read_data);
2117 self.attack(agent, controller, &target_data, read_data, rng);
2124 }
2125 }
2126 }
2127 }
2128
2129 pub fn chat_npc_if_allowed_to_speak(
2132 &self,
2133 msg: Content,
2134 agent: &Agent,
2135 emitters: &mut AgentEmitters,
2136 ) -> bool {
2137 if agent.allowed_to_speak() {
2138 self.chat_npc(msg, emitters);
2139 true
2140 } else {
2141 false
2142 }
2143 }
2144
2145 pub fn chat_npc(&self, content: Content, emitters: &mut AgentEmitters) {
2146 emitters.emit(ChatEvent {
2147 msg: UnresolvedChatMsg::npc(*self.uid, content),
2148 from_client: false,
2149 });
2150 }
2151
2152 fn emit_scream(&self, time: f64, emitters: &mut AgentEmitters) {
2153 if let Some(body) = self.body {
2154 emitters.emit(SoundEvent {
2155 sound: Sound::new(
2156 SoundKind::Utterance(UtteranceKind::Scream, *body),
2157 self.pos.0,
2158 13.0,
2159 time,
2160 ),
2161 });
2162 }
2163 }
2164
2165 pub fn cry_out(&self, agent: &Agent, emitters: &mut AgentEmitters, read_data: &ReadData) {
2166 let has_enemy_alignment = matches!(self.alignment, Some(Alignment::Enemy));
2167 let is_below_flee_health = self.below_flee_health(agent);
2168
2169 if has_enemy_alignment && is_below_flee_health {
2170 self.chat_npc_if_allowed_to_speak(
2171 Content::localized("npc-speech-cultist_low_health_fleeing"),
2172 agent,
2173 emitters,
2174 );
2175 } else if is_villager(self.alignment) {
2176 self.chat_npc_if_allowed_to_speak(
2177 Content::localized("npc-speech-villager_under_attack"),
2178 agent,
2179 emitters,
2180 );
2181 self.emit_scream(read_data.time.0, emitters);
2182 }
2183 }
2184
2185 pub fn exclaim_relief_about_enemy_dead(&self, agent: &Agent, emitters: &mut AgentEmitters) {
2186 if is_villager(self.alignment) {
2187 self.chat_npc_if_allowed_to_speak(
2188 Content::localized("npc-speech-villager_enemy_killed"),
2189 agent,
2190 emitters,
2191 );
2192 }
2193 }
2194
2195 pub fn below_flee_health(&self, agent: &Agent) -> bool {
2196 self.damage.min(1.0) < agent.psyche.flee_health
2197 }
2198
2199 pub fn is_more_dangerous_than_target(
2200 &self,
2201 entity: EcsEntity,
2202 target: Target,
2203 read_data: &ReadData,
2204 ) -> bool {
2205 let entity_pos = read_data.positions.get(entity);
2206 let target_pos = read_data.positions.get(target.target);
2207
2208 entity_pos.is_some_and(|entity_pos| {
2209 target_pos.is_none_or(|target_pos| {
2210 const FUZZY_DIST_COMPARISON: f32 = 0.8;
2215
2216 let is_target_further = target_pos.0.distance(entity_pos.0)
2217 < target_pos.0.distance(entity_pos.0) * FUZZY_DIST_COMPARISON;
2218 let is_entity_hostile = read_data
2219 .alignments
2220 .get(entity)
2221 .zip(self.alignment)
2222 .is_some_and(|(entity, me)| me.hostile_towards(*entity));
2223
2224 !target.aggro_on || (is_target_further && is_entity_hostile)
2227 })
2228 })
2229 }
2230
2231 pub fn is_enemy(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2232 let other_alignment = read_data.alignments.get(entity);
2233
2234 (entity != *self.entity)
2235 && !self.passive_towards(entity, read_data)
2236 && (are_our_owners_hostile(self.alignment, other_alignment, read_data)
2237 || (is_villager(self.alignment) && is_dressed_as_cultist(entity, read_data)
2238 || (is_villager(self.alignment) && is_dressed_as_witch(entity, read_data))
2239 || (is_villager(self.alignment) && is_dressed_as_pirate(entity, read_data))))
2240 }
2241
2242 pub fn is_hunting_animal(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2243 (entity != *self.entity)
2244 && !self.friendly_towards(entity, read_data)
2245 && matches!(read_data.bodies.get(entity), Some(Body::QuadrupedSmall(_)))
2246 }
2247
2248 fn should_defend(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2249 let entity_alignment = read_data.alignments.get(entity);
2250
2251 let we_are_friendly = entity_alignment.is_some_and(|entity_alignment| {
2252 self.alignment
2253 .is_some_and(|alignment| !alignment.hostile_towards(*entity_alignment))
2254 });
2255 let we_share_species = read_data.bodies.get(entity).is_some_and(|entity_body| {
2256 self.body.is_some_and(|body| {
2257 entity_body.is_same_species_as(body)
2258 || (entity_body.is_humanoid() && body.is_humanoid())
2259 })
2260 });
2261 let self_owns_entity =
2262 matches!(entity_alignment, Some(Alignment::Owned(ouid)) if *self.uid == *ouid);
2263
2264 (we_are_friendly && we_share_species)
2265 || (is_village_guard(*self.entity, read_data) && is_villager(entity_alignment))
2266 || self_owns_entity
2267 }
2268
2269 fn passive_towards(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2270 if let (Some(self_alignment), Some(other_alignment)) =
2271 (self.alignment, read_data.alignments.get(entity))
2272 {
2273 self_alignment.passive_towards(*other_alignment)
2274 } else {
2275 false
2276 }
2277 }
2278
2279 fn friendly_towards(&self, entity: EcsEntity, read_data: &ReadData) -> bool {
2280 if let (Some(self_alignment), Some(other_alignment)) =
2281 (self.alignment, read_data.alignments.get(entity))
2282 {
2283 self_alignment.friendly_towards(*other_alignment)
2284 } else {
2285 false
2286 }
2287 }
2288
2289 pub fn can_see_entity(
2290 &self,
2291 agent: &Agent,
2292 controller: &Controller,
2293 other: EcsEntity,
2294 other_pos: &Pos,
2295 other_scale: Option<&Scale>,
2296 read_data: &ReadData,
2297 ) -> bool {
2298 let other_stealth_multiplier = {
2299 let other_inventory = read_data.inventories.get(other);
2300 let other_char_state = read_data.char_states.get(other);
2301
2302 perception_dist_multiplier_from_stealth(other_inventory, other_char_state, self.msm)
2303 };
2304
2305 let within_sight_dist = {
2306 let sight_dist = agent.psyche.sight_dist * other_stealth_multiplier;
2307 let dist_sqrd = other_pos.0.distance_squared(self.pos.0);
2308
2309 dist_sqrd < sight_dist.powi(2)
2310 };
2311
2312 let within_fov = (other_pos.0 - self.pos.0)
2313 .try_normalized()
2314 .is_some_and(|v| v.dot(*controller.inputs.look_dir) > 0.15);
2315
2316 let other_body = read_data.bodies.get(other);
2317
2318 (within_sight_dist)
2319 && within_fov
2320 && entities_have_line_of_sight(
2321 self.pos,
2322 self.body,
2323 self.scale,
2324 other_pos,
2325 other_body,
2326 other_scale,
2327 read_data,
2328 )
2329 }
2330
2331 pub fn detects_other(
2332 &self,
2333 agent: &Agent,
2334 controller: &Controller,
2335 other: &EcsEntity,
2336 other_pos: &Pos,
2337 other_scale: Option<&Scale>,
2338 read_data: &ReadData,
2339 ) -> bool {
2340 self.can_sense_directly_near(other_pos)
2341 || self.can_see_entity(agent, controller, *other, other_pos, other_scale, read_data)
2342 }
2343
2344 pub fn can_sense_directly_near(&self, e_pos: &Pos) -> bool {
2345 let chance = rng().random_bool(0.3);
2346 e_pos.0.distance_squared(self.pos.0) < 5_f32.powi(2) && chance
2347 }
2348
2349 pub fn menacing(
2350 &self,
2351 agent: &mut Agent,
2352 controller: &mut Controller,
2353 target: EcsEntity,
2354 tgt_data: &TargetData,
2355 read_data: &ReadData,
2356 emitters: &mut AgentEmitters,
2357 remembers_fight_with_target: bool,
2358 ) {
2359 let max_move = 0.5;
2360 let move_dir = controller.inputs.move_dir;
2361 let move_dir_mag = move_dir.magnitude();
2362 let mut chat = |agent: &mut Agent, content: Content| {
2363 self.chat_npc_if_allowed_to_speak(content, agent, emitters);
2364 };
2365 let mut chat_villager_remembers_fighting = |agent: &mut Agent| {
2366 let tgt_name = read_data.stats.get(target).map(|stats| stats.name.clone());
2367
2368 if let Some(tgt_name) = tgt_name.as_ref().and_then(|name| name.as_plain()) {
2371 chat(
2372 agent,
2373 Content::localized_with_args("npc-speech-remembers-fight", [(
2374 "name", tgt_name,
2375 )]),
2376 )
2377 } else {
2378 chat(
2379 agent,
2380 Content::localized("npc-speech-remembers-fight-no-name"),
2381 );
2382 }
2383 };
2384
2385 self.look_toward(controller, read_data, target);
2386 controller.push_action(ControlAction::Wield);
2387
2388 if move_dir_mag > max_move {
2389 controller.inputs.move_dir = max_move * move_dir / move_dir_mag;
2390 }
2391
2392 match agent
2393 .timer
2394 .timeout_elapsed(read_data.time.0, comp::agent::TimerAction::Warn, 5.0)
2395 {
2396 Some(true) | None => {
2397 self.path_toward_target(
2398 agent,
2399 controller,
2400 tgt_data.pos.0,
2401 read_data,
2402 Path::AtTarget,
2403 Some(0.4),
2404 );
2405 },
2406 Some(false) => {
2407 agent
2408 .timer
2409 .start(read_data.time.0, comp::agent::TimerAction::Warn);
2410 controller.push_utterance(UtteranceKind::Angry);
2411 if is_villager(self.alignment) {
2412 if remembers_fight_with_target {
2413 chat_villager_remembers_fighting(agent);
2414 } else if is_dressed_as_cultist(target, read_data) {
2415 chat(
2416 agent,
2417 Content::localized("npc-speech-villager_cultist_alarm"),
2418 );
2419 } else if is_dressed_as_witch(target, read_data) {
2420 chat(agent, Content::localized("npc-speech-villager_witch_alarm"));
2421 } else if is_dressed_as_pirate(target, read_data) {
2422 chat(
2423 agent,
2424 Content::localized("npc-speech-villager_pirate_alarm"),
2425 );
2426 } else {
2427 chat(agent, Content::localized("npc-speech-menacing"));
2428 }
2429 } else {
2430 chat(agent, Content::localized("npc-speech-menacing"));
2431 }
2432 },
2433 }
2434 }
2435
2436 pub fn dismount_uncontrollable(&self, controller: &mut Controller, read_data: &ReadData) {
2438 if read_data.is_riders.get(*self.entity).is_some_and(|mount| {
2439 read_data
2440 .id_maps
2441 .uid_entity(mount.mount)
2442 .and_then(|e| read_data.bodies.get(e))
2443 .is_none_or(|b| b.has_free_will())
2444 }) || read_data
2445 .is_volume_riders
2446 .get(*self.entity)
2447 .is_some_and(|r| !r.is_steering_entity())
2448 {
2449 controller.push_event(ControlEvent::Unmount);
2450 }
2451 }
2452
2453 pub fn dismount(&self, controller: &mut Controller, read_data: &ReadData) {
2458 if read_data.is_riders.contains(*self.entity)
2459 || read_data
2460 .is_volume_riders
2461 .get(*self.entity)
2462 .is_some_and(|r| !r.is_steering_entity())
2463 {
2464 controller.push_event(ControlEvent::Unmount);
2465 }
2466 }
2467}