bevy_tnua/control_helpers/
blip_reuse_avoidance.rs1use std::marker::PhantomData;
2
3use bevy::platform::collections::HashMap;
4use bevy::prelude::*;
5use bevy_tnua_physics_integration_layer::obstacle_radar::TnuaObstacleRadar;
6
7use crate::TnuaScheme;
8use crate::controller::TnuaActionFlowStatus;
9use crate::prelude::TnuaController;
10
11#[derive(Component, Reflect)]
17pub struct TnuaBlipReuseAvoidance<S: TnuaScheme> {
18 current_entity: Option<Entity>,
19 entities_to_avoid: HashMap<Entity, S::ActionDiscriminant>,
20}
21
22impl<S: TnuaScheme> FromTemplate for TnuaBlipReuseAvoidance<S> {
23 type Template = TnuaBlipReuseAvoidanceTemplate<S>;
24}
25
26pub struct TnuaBlipReuseAvoidanceTemplate<S> {
27 _phantom: PhantomData<S>,
28}
29
30impl<S> Default for TnuaBlipReuseAvoidanceTemplate<S> {
31 fn default() -> Self {
32 Self {
33 _phantom: PhantomData,
34 }
35 }
36}
37
38impl<S: TnuaScheme> Template for TnuaBlipReuseAvoidanceTemplate<S> {
39 type Output = TnuaBlipReuseAvoidance<S>;
40
41 fn build_template(&self, _: &mut bevy::ecs::template::TemplateContext) -> Result<Self::Output> {
42 Ok(Default::default())
43 }
44
45 fn clone_template(&self) -> Self {
46 Self {
47 _phantom: PhantomData,
48 }
49 }
50}
51
52impl<S: TnuaScheme> Default for TnuaBlipReuseAvoidance<S> {
53 fn default() -> Self {
54 Self {
55 current_entity: None,
56 entities_to_avoid: Default::default(),
57 }
58 }
59}
60
61pub trait TnuaHasTargetEntity: TnuaScheme {
63 fn target_entity(action_state: &Self::ActionState) -> Option<Entity>;
69}
70
71impl<S> TnuaBlipReuseAvoidance<S>
72where
73 S: TnuaScheme + TnuaHasTargetEntity,
74{
75 pub fn update(&mut self, controller: &TnuaController<S>, radar: &TnuaObstacleRadar) {
77 let current_entity = controller
78 .current_action
79 .as_ref()
80 .and_then(S::target_entity);
81
82 if current_entity != self.current_entity
83 && let Some(old_entity) = self.current_entity.as_ref()
84 && let TnuaActionFlowStatus::ActionEnded(action_discriminant)
85 | TnuaActionFlowStatus::Cancelled {
86 old: action_discriminant,
87 new: _,
88 } = controller.action_flow_status()
89 {
90 self.entities_to_avoid
91 .insert(*old_entity, *action_discriminant);
92 }
93
94 self.entities_to_avoid
95 .retain(|entity, _| radar.has_blip(*entity));
96
97 self.current_entity = current_entity;
98 }
99
100 pub fn should_avoid(&self, entity: Entity) -> bool {
103 self.entities_to_avoid.contains_key(&entity)
104 }
105}