use core::borrow::Borrow;
use bevy::prelude::*;
use crate::actions;
use crate::ai::{AIController};
use crate::context_fetchers::{ContextFetcherKeyToSystemMap, ShouldReinitCfQueries};
use crate::considerations::{ConsiderationKeyToSystemMap, ShouldReinitConsiderationQueries};
use crate::curves::{SupportedUtilityCurve, UtilityCurve, UtilityCurveRegistry, resolve_curve_from_name};
use crate::errors::NoCurveMatchStrategyConfig;
use crate::events::{AiActionPicked, AiDecisionInitiated, AiDecisionRequested, SomeAiDecisionProcessed};
use crate::lods::{AiLevelOfDetail};
use crate::pawn::Pawn;
use crate::smart_object::ActionSetStore;
use crate::types::{self, ActionContextRef, ActionScore, ActionTemplateRef, ThreadSafeRef};
fn consideration_adjustment(
score: types::ActionScore,
num_considerations: usize,
) -> types::ActionScore {
if score <= types::MIN_CONSIDERATION_SCORE {
return types::MIN_CONSIDERATION_SCORE
}
if score >= types::MAX_CONSIDERATION_SCORE {
return types::MAX_CONSIDERATION_SCORE
}
if num_considerations <= 0 {
return score
}
let floaty_num_considerations = num_considerations as f32;
let modification_factor = 1. - (1. / floaty_num_considerations);
let makeup_val = (1. - score) * modification_factor;
let adjusted_score = score + (makeup_val * score);
#[cfg(feature = "logging")]
bevy::log::debug!(
"Adjusted raw score {:?} w/ {:?} Considerations (float: {:?}) to {:?}",
score,
num_considerations,
floaty_num_considerations,
adjusted_score,
);
adjusted_score
}
pub fn prepare_ai(
event: On<AiDecisionRequested>,
should_reinit_cf_queries: Option<ResMut<ShouldReinitCfQueries>>,
should_reinit_cons_queries: Option<ResMut<ShouldReinitConsiderationQueries>>,
mut commands: Commands,
) {
should_reinit_cf_queries.map(|mut res| {
res.set(true);
});
should_reinit_cons_queries.map(|mut res| {
res.set(true);
});
commands.trigger(AiDecisionInitiated {
entity: event.entity,
smart_objects: event.smart_objects.clone(),
});
}
pub fn disable_cf_reinit(
_event: On<crate::events::SomeAiDecisionProcessed>,
should_reinit_cf_queries: Option<ResMut<ShouldReinitCfQueries>>,
) {
should_reinit_cf_queries.map(|mut res| {
res.set(false);
});
}
pub fn disable_consideration_reinit(
_event: On<crate::events::SomeAiDecisionProcessed>,
should_reinit_cons_queries: Option<ResMut<ShouldReinitConsiderationQueries>>,
) {
should_reinit_cons_queries.map(|mut res| {
res.set(false);
});
}
pub fn decision_engine(
event: On<AiDecisionInitiated>,
world_ref: &World,
actionset_store: Res<ActionSetStore>,
context_fetcher_system_map: Res<ContextFetcherKeyToSystemMap>,
consideration_system_map: Res<ConsiderationKeyToSystemMap>,
entity_checker: Query<Entity, With<AIController>>,
lod_query: Query<Option<&AiLevelOfDetail>>,
pawn_query: Query<Option<&Pawn>>,
utility_curve_registry: Option<Res<UtilityCurveRegistry>>,
no_match_strategy_config: Option<Res<NoCurveMatchStrategyConfig>>,
mut commands: Commands,
) {
commands.trigger(SomeAiDecisionProcessed);
let audience = event.event_target();
let exist_check = entity_checker.get(audience);
if exist_check.is_err() {
#[cfg(feature = "logging")]
bevy::log::debug!("decision_engine: Decision request target {:?} is not an AI - ignoring the request.", audience);
return;
}
let lod_level = lod_query
.get(audience)
.ok()
.flatten()
.map(|lod| lod.get_current_lod())
;
let is_disabled = lod_level.map(|lod| lod.is_inactive() ).unwrap_or(false);
if is_disabled {
#[cfg(feature = "logging")]
bevy::log::debug!("decision_engine: AI {:?} disabled by LOD - ignoring decision request.", audience);
return;
}
let mut best_scoring_triple: Option<(ActionScore, ActionTemplateRef, ActionContextRef)> = None;
let mut best_scoring_template: Option<(ActionTemplateRef, ActionScore)> = None;
let maybe_smartobjects = &event.smart_objects;
let maybe_pawn = pawn_query.get(audience).ok().flatten().cloned();
let smartobjects = match maybe_smartobjects {
None => {
#[cfg(feature = "logging")]
bevy::log::debug!("decision_engine: AI {:?} - no SmartObjects available, idling", audience);
return;
}
Some(sos) => sos
};
let available_actions = smartobjects.actionset_refs.iter().filter_map(
|actionset_key| {
let maybe_act = actionset_store.map_by_name.get(actionset_key);
maybe_act
}
)
.flat_map(|acts| {
acts.actions
.iter()
.cloned()
.map(|act| ThreadSafeRef::new(act))
});
#[cfg(feature = "logging")]
bevy::log::debug!(
"decision_engine: AI {:?} - available Actions are: {:#?}",
audience, &smartobjects.actionset_refs
);
for action_template in available_actions {
if !action_template.is_within_lod_range(&lod_level) {
#[cfg(feature = "logging")]
bevy::log::debug!(
"decision_engine: AI {:?} - skipping Template {:?} - current LOD {:?} does not allow for processing.",
&action_template.name, &audience, &lod_level,
);
continue;
}
#[cfg(feature = "logging")]
bevy::log::debug!(
"decision_engine: AI {:?} - requesting Contexts for Template {:?} from CF {:?}",
&audience, &action_template.name, &action_template.context_fetcher_name,
);
let cf_system = context_fetcher_system_map.mapping
.get(&action_template.context_fetcher_name.0)
;
let contexts = match cf_system {
Some(system_guard) => {
let res = {
let res = system_guard.write().map(|mut cf_system| {
cf_system.run_readonly(
(
audience,
maybe_pawn.clone().map(|p| p.to_entity()).flatten(),
),
world_ref,
)
});
if res.is_err() {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - ContextFetcher '{:?}' errored - lock poisoned ({:?})!",
&audience,
&action_template.context_fetcher_name,
&res,
);
panic!("decision_engine: ContextFetcher failed - lock poisoned!");
};
res.unwrap()
};
if res.is_err() {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - ContextFetcher '{:?}' errored: {:?}",
&audience,
&action_template.context_fetcher_name,
&res,
);
continue;
};
res.expect("decision_engine: ContextFetcher result is Err - this should not be possible!")
},
None => {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - ContextFetcher key '{:?}' could not be resolved to a System!",
&audience,
&action_template.context_fetcher_name,
);
continue;
}
};
for ctx in contexts {
let mut skip_this_context = false;
let ctx_ref = ctx;
#[cfg(feature = "logging")]
bevy::log::debug!("decision_engine: AI {:?} - processing Ctx {:?} for Action {:?}",
&audience,
&ctx_ref,
&action_template,
);
let curr_best_for_ai = best_scoring_triple
.as_ref()
.map(|tup| tup.0)
;
if let Some(some_curr_best) = &curr_best_for_ai {
if some_curr_best >= &action_template.priority {
continue;
}
}
let mut curr_score = types::MAX_CONSIDERATION_SCORE;
let mut consideration_count: usize = 0;
for (cons_cnt, cons) in action_template.considerations.iter().enumerate() {
let mut maybe_resolved_curve: Option<SupportedUtilityCurve> = utility_curve_registry
.as_ref()
.map(|curve_mapping|
curve_mapping.get_curve_by_name(&cons.curve_name)
)
.flatten()
.or_else(|| resolve_curve_from_name(&cons.curve_name))
;
if maybe_resolved_curve.is_none() {
let curve_miss_strategy = no_match_strategy_config
.as_ref()
.map(|conf| conf.get_current_value())
;
match curve_miss_strategy {
None => {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - Failed to resolve Curve key {:?} to a SupportedUtilityCurve, default behavior - panicking!",
&audience,
&cons.curve_name
);
panic!("decision_engine: Failed to resolve Curve key to a SupportedUtilityCurve!");
},
Some(crate::errors::NoCurveMatchStrategy::Panic) => {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - Failed to resolve Curve key {:?} to a SupportedUtilityCurve, panicking!",
&audience,
&cons.curve_name
);
panic!("decision_engine: Failed to resolve Curve key to a SupportedUtilityCurve!");
},
Some(crate::errors::NoCurveMatchStrategy::SkipConsiderationWithLog) => {
#[cfg(feature = "logging")]
bevy::log::warn!(
"decision_engine: AI {:?} - failed to resolve Curve key {:?} to a SupportedUtilityCurve, skipping Consideration {:?}!",
&audience,
&cons.curve_name,
&cons.consideration_name,
);
continue;
},
Some(crate::errors::NoCurveMatchStrategy::SkipActionWithLog) => {
#[cfg(feature = "logging")]
bevy::log::warn!(
"decision_engine: AI {:?} - failed to resolve Curve key {:?} to a SupportedUtilityCurve, skipping ActionTemplate {:?}!",
&audience,
&cons.curve_name,
&action_template.name,
);
break;
},
Some(crate::errors::NoCurveMatchStrategy::DefaultCurveWithLog(curve_resolver)) => {
let resolved = curve_resolver(cons.curve_name.borrow());
#[cfg(feature = "logging")]
bevy::log::warn!(
"AI {:?} - Curve key {:?} resolved using fallback Curve {:?}",
&audience,
&cons.curve_name,
&resolved,
);
maybe_resolved_curve = Some(resolved)
},
Some(crate::errors::NoCurveMatchStrategy::DefaultCurveWithoutLog(curve_resolver)) => {
let resolved = curve_resolver(cons.curve_name.borrow());
maybe_resolved_curve = Some(resolved)
},
}
}
let resolved_curve = maybe_resolved_curve.unwrap();
let consideration_system = consideration_system_map.mapping
.get(&cons.consideration_name)
;
match consideration_system {
None => {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - Failed to resolve Consideration '{:}' to a System!",
&audience,
&cons.consideration_name
);
panic!("Consideration failed - could not resolve to a System!");
},
Some(system_guard) => {
let system_state = system_guard.write();
let res = {
let res = system_state
.map(|mut consideration_system| {
consideration_system.run_readonly(
(
audience.entity(),
maybe_pawn.clone().map(|p| p.to_entity()).flatten(),
ctx_ref.clone(),
),
world_ref,
)
})
;
if res.is_err() {
#[cfg(feature = "logging")]
bevy::log::error!(
"AI {:?} - Consideration '{:}' errored - lock poisoned ({:?})!",
&audience,
&cons.consideration_name,
&res
);
panic!("Consideration failed - lock poisoned!");
};
res.unwrap()
};
if res.is_err() {
curr_score = types::MIN_CONSIDERATION_SCORE - 1.;
break;
};
let raw_score = match res {
Err(_err) => {
#[cfg(feature = "logging")]
bevy::log::error!(
"decision_engine: AI {:?} - Consideration '{:}' errored: {:?}",
&audience,
&cons.consideration_name,
&_err
);
curr_score = types::MIN_CONSIDERATION_SCORE;
break;
},
Ok(maybe_val) => match maybe_val {
Some(val) => val,
None => {
#[cfg(feature = "logging")]
bevy::log::info!(
"decision_engine: AI {:?} - Consideration '{:}' returned a None score, indicating a nonfatal error. Defaulting to zero score.",
&audience,
&cons.consideration_name,
);
curr_score = types::MIN_CONSIDERATION_SCORE;
skip_this_context = true; break;
}
}
};
let (true_min, true_max) = match cons.min <= cons.max {
true => (cons.min, cons.max),
false => {
#[cfg(feature = "logging")]
bevy::log::error!(
"Min/Max values for Consideration {:?} in Action {:?}
were flipped, min={:?} > max={:?}.
They have been flipped back so Min<=Max for you for now.
This fixup is not guaranteed to be in place in future versions of the library!",
cons.consideration_name,
&action_template.name,
cons.min,
cons.max,
);
(cons.max, cons.min)
}
};
let rescaled_score = (raw_score - true_min).clamp(true_min, true_max) / (true_max - true_min);
let score = resolved_curve.sample_safe(rescaled_score);
curr_score *= score;
#[cfg(feature = "logging")]
bevy::log::debug!(
"decision_engine: AI {:?} - Consideration '{:}' for Action {:?}:
- Raw score => {:?}
- Rescaled w/ min/max => {:?}
- Adjusted w/ Curve {:?} => {:?}
- Current running total score for Action => {:?}",
audience,
cons.consideration_name,
&action_template.name,
raw_score,
rescaled_score,
cons.curve_name,
score,
curr_score,
);
let curr_beats_old_best = match &best_scoring_template {
None => true,
Some((_old_best_tmpl, old_best_score)) => &curr_score > old_best_score,
};
if !curr_beats_old_best {
#[cfg(feature = "logging")]
bevy::log::debug!(
"decision_engine: AI {:?} - Consideration '{:}' for Action {:?} - curr_score {:?} is below the template best of {:?}, discarding the Context.",
audience,
cons.consideration_name,
&action_template.name,
curr_score,
best_scoring_template,
);
skip_this_context = true; break;
}
consideration_count = cons_cnt + 1;
}
}
}
if skip_this_context {
continue;
}
let curr_beats_old_best = match &best_scoring_template {
None => true,
Some((_old_best_tmpl, old_best_score)) => &curr_score > old_best_score,
};
if curr_beats_old_best {
let _ = best_scoring_template.insert((
action_template.to_owned(),
curr_score.to_owned()
));
}
let adjusted_score = consideration_adjustment(
curr_score,
consideration_count,
);
let prioritized_score = adjusted_score * action_template.priority;
match prioritized_score > curr_best_for_ai.unwrap_or(types::MIN_CONSIDERATION_SCORE) {
false => {
#[cfg(feature = "logging")]
bevy::log::debug!(
"AI {:?} - Score for Action {:?} = {:?} is below the current best of {:?}. Ignoring.",
&audience,
&action_template.name,
prioritized_score,
curr_best_for_ai,
);
},
true => {
#[cfg(feature = "logging")]
bevy::log::debug!(
"AI {:?} - Score for Action {:?} = {:?} beats the current best of {:?}. Promoting to new best.",
&audience,
&action_template.name,
prioritized_score,
curr_best_for_ai,
);
best_scoring_triple = Some((prioritized_score, action_template.clone(), ctx_ref))
}
}
}
}
match best_scoring_triple {
None => {
#[cfg(feature = "logging")]
bevy::log::info!(
"decision_engine: AI {:?} - no suitable Actions found.",
&audience,
);
panic!("decision_engine: AI {:?} - no suitable Actions found.", audience)
}
Some(best_tuple) => {
let (
best_score,
best_template,
best_context
) = best_tuple;
#[cfg(feature = "logging")]
bevy::log::info!(
"decision_engine: AI {:?} - Picking Action {:?} w/ Score {:?}.",
&audience,
&best_template.name,
&best_score,
);
let pick_evt = AiActionPicked {
entity: audience.entity(),
action_key: best_template.action_key.to_owned(),
action_name: best_template.name.to_owned(),
action_context: best_context.to_owned(),
action_score: best_score,
};
commands.trigger(pick_evt);
}
}
}
pub fn trigger_dispatch_to_user_actions(
trigger: On<crate::events::AiActionPicked>,
mut writer: MessageWriter<crate::events::AiActionDispatchToUserCode>,
) {
let event = trigger.event();
let action_key = &event.action_key;
#[cfg(feature = "logging")]
bevy::log::debug!(
"dispatch_to_user_actions - Running for Action {:?} for Pick Event {:?}",
action_key, event
);
let message = crate::events::AiActionDispatchToUserCode::new(
event.entity,
action_key.to_owned(),
event.action_name.to_owned(),
event.action_context,
event.action_score
);
writer.write(message);
}
pub fn handle_dispatch_to_user_actions(
pawn_query: Query<Option<&Pawn>>,
mut commands: Commands,
mut reader: MessageReader<crate::events::AiActionDispatchToUserCode>,
mut callback_registry: ResMut<actions::ActionHandlerKeyToSystemMap>,
) {
for msg in reader.read() {
let action_key = &msg.action_key;
#[cfg(feature = "logging")]
bevy::log::debug!(
"dispatch_to_user_actions - Running for Action {:?} for message {:?}",
&action_key, &msg
);
let callback = match callback_registry.mapping.get_mut(action_key) {
Some(cb) => cb,
None => {
#[cfg(feature = "logging")]
bevy::log::error!(
"dispatch_to_user_actions - Could not resolve ActionKey {:?} to a registered ActionPickCallback, skipping!",
action_key
);
continue;
}
};
let ai = msg.entity;
let ctx = msg.action_context;
let pawn = pawn_query
.get(ai)
.ok().flatten()
.map(|p| p.clone().to_entity())
.flatten()
;
callback.call((ai, pawn, ctx), commands.reborrow());
}
}