aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-14 15:35:44 +0300
committerValentin Popov <valentin@popov.link>2026-11-14 15:35:44 +0300
commit406d17ca79a0b29e062c60ad87c1dbe44f844444 (patch)
tree7e10c7a740b827eb987492803f1fe9a781284827 /crates/fparkan-runtime/src
parentda458f8a991644a4033d3b529f23a2dd98a0329d (diff)
downloadfparkan-406d17ca79a0b29e062c60ad87c1dbe44f844444.tar.xz
fparkan-406d17ca79a0b29e062c60ad87c1dbe44f844444.zip
feat(ai): route skirmish units toward hostile factories
Diffstat (limited to 'crates/fparkan-runtime/src')
-rw-r--r--crates/fparkan-runtime/src/autodemo_combat.rs2
-rw-r--r--crates/fparkan-runtime/src/lib.rs109
-rw-r--r--crates/fparkan-runtime/src/unit_patrol.rs82
3 files changed, 184 insertions, 9 deletions
diff --git a/crates/fparkan-runtime/src/autodemo_combat.rs b/crates/fparkan-runtime/src/autodemo_combat.rs
index 1779d136..ddf83a50 100644
--- a/crates/fparkan-runtime/src/autodemo_combat.rs
+++ b/crates/fparkan-runtime/src/autodemo_combat.rs
@@ -292,7 +292,7 @@ impl AutoDemoCombat {
};
let targets = self.targets(&engine.world, &mission.mission_assets);
for unit in &mut self.units {
- // shortcut: armed AI units hold position and defend it while their Init is incomplete.
+ // shortcut: armed AI units defend their position while their Init is incomplete.
let guard = identity_metadata(&engine.world, unit.handle)
.ok()
.and_then(|identity| identity.owner_id)
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 232df8b0..d5b1a254 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -2423,7 +2423,7 @@ fn load_mission_with_options(
script_varset_state_count: loaded_scripts.varset_states.len(),
};
- let unit_patrol = if options.start_autodemo {
+ let mut unit_patrol = if options.start_autodemo {
match request.mode {
MissionMode::AutoDemo => unit_patrol::UnitPatrol::new(
&mission,
@@ -2468,6 +2468,41 @@ fn load_mission_with_options(
} else {
Vec::new()
};
+ let standalone_mission = mission_path
+ .as_str()
+ .split('/')
+ .nth(1)
+ .is_some_and(|directory| {
+ directory
+ .get(..7)
+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case("Single."))
+ });
+ if let Some(varset) = loaded_scripts
+ .varset
+ .as_ref()
+ .filter(|_| standalone_mission)
+ {
+ let scripted_patrol = unit_patrol.is_some();
+ let mut patrol = unit_patrol
+ .take()
+ .unwrap_or_else(unit_patrol::UnitPatrol::scripted);
+ for bundle in &loaded_scripts.bundles {
+ if guard_clans.get(bundle.clan_index) != Some(&true) {
+ continue;
+ }
+ patrol.approximate_factory_raid(
+ &new_runtime_world,
+ &mission,
+ &object_drafts[..reserve_start],
+ &handles[..reserve_start],
+ bundle,
+ &varset.declarations,
+ );
+ }
+ if patrol.factory_raid_clans != 0 || scripted_patrol {
+ unit_patrol = Some(patrol);
+ }
+ }
let autodemo_combat = (unit_patrol.is_some() || guard_clans.contains(&true)).then(|| {
autodemo_combat::AutoDemoCombat::new(
&vfs,
@@ -2867,7 +2902,7 @@ pub fn autodemo_combat_unavailable(engine: &Engine) -> usize {
.map_or(0, |combat| combat.unavailable)
}
-/// Counts AI clans using the stationary defense fallback in this mission.
+/// Counts AI clans using the defense fallback in this mission.
#[must_use]
pub fn mission_guard_fallback_count(engine: &Engine) -> usize {
engine
@@ -2876,6 +2911,16 @@ pub fn mission_guard_fallback_count(engine: &Engine) -> usize {
.map_or(0, autodemo_combat::AutoDemoCombat::guard_clan_count)
}
+/// Counts AI clans approximating the scripted raid on a hostile factory.
+#[must_use]
+pub fn mission_factory_raid_count(engine: &Engine) -> usize {
+ engine
+ .loaded
+ .as_ref()
+ .and_then(|mission| mission.unit_patrol.as_ref())
+ .map_or(0, |patrol| patrol.factory_raid_clans)
+}
+
/// Returns the loaded mission summary.
#[must_use]
pub fn loaded_mission(engine: &Engine) -> Option<&LoadedMission> {
@@ -18159,6 +18204,62 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_two_fortresses_ai_reaches_the_player_side_from_stock_start() {
+ let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS")));
+ let mut engine = create(EngineServices::new(vfs)).unwrap();
+ load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS\\Single.01\\data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(mission_factory_raid_count(&engine), 1);
+ let hero = starting_cockpit(&engine).unwrap();
+ let start = transform_state(&engine.world, hero.handle).unwrap();
+ let factory = mission_object_handle(&engine, OriginalObjectId(5)).unwrap();
+ let [x, y, _] = transform_state(&engine.world, factory)
+ .unwrap()
+ .position
+ .map(f32::from_bits);
+ let mut first_shot = None;
+ for now in (0..=300_000).step_by(100) {
+ let step = frame(&mut engine, now).unwrap();
+ for event in step.autodemo_combat_events {
+ if let AutoDemoCombatEvent::Shot { shooter, .. } = event {
+ assert_eq!(
+ fparkan_world::identity_metadata(&engine.world, shooter)
+ .unwrap()
+ .owner_id,
+ Some(fparkan_world::OwnerId(1))
+ );
+ let [sx, sy, _] = transform_state(&engine.world, shooter)
+ .unwrap()
+ .position
+ .map(f32::from_bits);
+ if (sx - x).hypot(sy - y) < 400.0 {
+ first_shot = Some(now);
+ break;
+ }
+ }
+ }
+ if first_shot.is_some() {
+ break;
+ }
+ }
+ assert!(first_shot.is_some(), "no shots on the player side");
+ println!("first raid shot in range of the player factory: {first_shot:?} ms");
+ assert_eq!(transform_state(&engine.world, hero.handle).unwrap(), start);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_two_fortresses_ai_defends_when_the_player_approaches() {
let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS")));
let mut engine = create(EngineServices::new(vfs)).unwrap();
@@ -18228,10 +18329,6 @@ mod tests {
);
assert!(!shots.iter().any(|event| matches!(event,
AutoDemoCombatEvent::Shot { shooter, .. } if *shooter == hero.handle)));
- assert_eq!(
- transform_state(&engine.world, enemy).unwrap().position,
- enemy_pose.position
- );
assert!(transform_state(&engine.world, hero.handle).is_err());
assert_eq!(player_status(&engine, hero.handle), None);
assert_eq!(failures, 1);
diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs
index 8f1fcb03..6c30e566 100644
--- a/crates/fparkan-runtime/src/unit_patrol.rs
+++ b/crates/fparkan-runtime/src/unit_patrol.rs
@@ -1,7 +1,11 @@
use super::{
- autodemo::MOBILE_UNIT, autodemo_combat::CombatTarget, next_crt_rand, EngineError,
- MissionDocument, MissionObjectDraft, ObjectHandle, TerrainWorld, TransformState, World,
+ autodemo::{MOBILE_UNIT, PLANT_CLASS},
+ autodemo_combat::CombatTarget,
+ boarding::WARBOT_CLASS,
+ next_crt_rand, EngineError, MissionDocument, MissionObjectDraft, MissionScriptBundle,
+ ObjectHandle, TerrainWorld, TransformState, World,
};
+use fparkan_script::{Handler15TargetPayload, ScriptDispatchSelector, VarSet};
use fparkan_terrain::{NavigationQuery, RouteRequest, SurfaceQuery};
use fparkan_world::{set_transform, transform_state};
use std::collections::VecDeque;
@@ -12,6 +16,7 @@ pub(super) struct UnitPatrol {
units: Vec<PatrollingUnit>,
clock_ms: u32,
rng: u32,
+ pub(super) factory_raid_clans: usize,
}
#[derive(Clone)]
@@ -30,12 +35,84 @@ pub(super) struct PreparedPatrol {
}
impl UnitPatrol {
+ pub(super) fn approximate_factory_raid(
+ &mut self,
+ world: &World,
+ mission: &MissionDocument,
+ drafts: &[MissionObjectDraft],
+ handles: &[ObjectHandle],
+ bundle: &MissionScriptBundle,
+ declarations: &VarSet,
+ ) {
+ let attacks_factory = bundle
+ .package
+ .events
+ .iter()
+ .filter(|event| event.name_raw == b"PBM_BUILDING_ATTACK_Start\0")
+ .flat_map(|event| &event.instructions)
+ .filter(|instruction| {
+ instruction.dispatch_selector() == ScriptDispatchSelector::Handler(28)
+ })
+ .any(|instruction| {
+ declarations
+ .resolve_handler15(instruction)
+ .is_ok_and(|order| {
+ order.word_1 == 3
+ && order.word_2 == 3
+ && order.word_3 == PLANT_CLASS
+ && matches!(order.target, Handler15TargetPayload::ByLogicId(_))
+ })
+ });
+ if !attacks_factory {
+ return;
+ }
+
+ let clan = &mission.clans[bundle.clan_index];
+ let factories = drafts.iter().filter(|draft| {
+ draft.unit_dat_header_flags == Some(PLANT_CLASS)
+ && mission
+ .clans
+ .get(draft.raw_after_resource as usize)
+ .is_some_and(|owner| {
+ clan.relations.iter().any(|relation| {
+ relation.relation_value == 0
+ && relation.other_clan_name.raw == owner.name.raw
+ })
+ })
+ });
+ // shortcut: route placed battle robots toward the nearest hostile factory until
+ // the problem scheduler can select and dispatch a native attack group.
+ let mut ordered = false;
+ for (draft, &handle) in drafts.iter().zip(handles).filter(|(draft, _)| {
+ draft.raw_after_resource as usize == bundle.clan_index
+ && draft.unit_dat_header_flags == Some(WARBOT_CLASS)
+ }) {
+ let distance = |target: &MissionObjectDraft| {
+ (draft.position[0] - target.position[0])
+ .hypot(draft.position[1] - target.position[1])
+ };
+ if let Some(factory) = factories
+ .clone()
+ .min_by(|a, b| distance(a).total_cmp(&distance(b)))
+ {
+ ordered |= self.order(
+ world,
+ handle,
+ [factory.position[0], factory.position[1]],
+ 60.0,
+ );
+ }
+ }
+ self.factory_raid_clans += usize::from(ordered);
+ }
+
pub(super) fn scripted() -> Self {
Self {
center: None,
units: Vec::new(),
clock_ms: 0,
rng: 1,
+ factory_raid_clans: 0,
}
}
@@ -110,6 +187,7 @@ impl UnitPatrol {
units,
clock_ms: 0,
rng: 1,
+ factory_raid_clans: 0,
})
}