aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs40
-rw-r--r--crates/fparkan-runtime/src/construction_site.rs123
-rw-r--r--crates/fparkan-runtime/src/lib.rs6
-rw-r--r--crates/fparkan-runtime/src/mining.rs2
4 files changed, 170 insertions, 1 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs
index 676db9cf..17aab8a9 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -13,6 +13,7 @@ const STORAGE_CLASS: u32 = 0x8000_0008;
const RESOURCE_ORE: u32 = 0x0200_0100;
const BUILDING_PROTECT: u32 = 8;
const OPTIMAL_TRANSPORT: u32 = 4;
+const BUILDING_NEEDED: u32 = 3;
pub(super) struct ScriptFactoryOrder {
pub owner: OwnerId,
@@ -232,6 +233,8 @@ pub(super) struct ClanAiEvents {
groups: BTreeMap<(usize, Handler2RecordKey), CombatGroup>,
waits: BTreeMap<(usize, Handler2RecordKey), Vec<Condition>>,
wait_starts: BTreeMap<(usize, u32), u64>,
+ building_sites: crate::construction_site::SiteReservations,
+ building_site_queries: BTreeMap<(usize, u32), u64>,
patrol_continues: BTreeMap<(usize, u32), u64>,
group_orders: BTreeMap<(usize, u32), u64>,
}
@@ -537,6 +540,13 @@ impl LoadedMissionState {
.declarations
.resolve_handler15_with_values(instruction, values)
.map_err(|error| error.to_string())?;
+ if matches!((order.word_1, order.word_2, order.target),
+ (7, 3, Handler15TargetPayload::ByPlace { .. })) {
+ return Err(format!(
+ "ORDER_ROBOT_BUILD needs prepared scheme and builder task (builder={} class={:#010x})",
+ order.word_0, order.word_3,
+ ));
+ }
if let (6, 3, Handler15TargetPayload::NotDefined(_), Some(problem)) =
(order.word_1, order.word_2, order.target, problem.as_ref())
{
@@ -902,6 +912,30 @@ impl LoadedMissionState {
crate::mining::remaining_for_clan(&self.mine_sites, world, owner);
Ok(Some(VarSetDefault::FloatBits(remaining.to_bits())))
}
+ ScriptDispatchSelector::Handler(18)
+ if problem.as_ref().is_some_and(|record| record.key.word_0 == BUILDING_NEEDED) =>
+ {
+ let &[x, y] = instruction.references.as_slice() else {
+ return Err("Handler(18) requires two DWORD outputs".into());
+ };
+ if x == y || [x, y].into_iter().any(|index| !matches!(values.get(index as usize), Some(VarSetDefault::Dword(_)))) {
+ return Err("Handler(18) requires two distinct DWORD outputs".into());
+ }
+ let base = self.mission.clans[clan].anchor.map(f32::round_ties_even);
+ let position = self.clan_ai_events.building_sites.find(
+ &self.terrain, world, &self.object_drafts, &self.mine_sites, base, now_ms,
+ );
+ let [px, py] = position.unwrap_or([0, 0]);
+ values[x as usize] = VarSetDefault::Dword(px);
+ values[y as usize] = VarSetDefault::Dword(py);
+ let class = problem.as_ref().unwrap().key.argument_0;
+ let count = self.clan_ai_events.building_site_queries.entry((clan, class)).or_default();
+ *count += 1;
+ if *count == 1 {
+ eprintln!("sim_coverage script_building_site_approx=1 clan={clan} class={class:#010x} site={position:?}");
+ }
+ Ok(Some(VarSetDefault::Dword(1)))
+ }
ScriptDispatchSelector::Handler(49)
if instruction.references.is_empty() =>
{
@@ -1195,6 +1229,12 @@ impl ClanAiEvents {
.map(|(&(clan, unit), &count)| (clan, unit, count))
}
+ pub(super) fn building_site_queries(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
+ self.building_site_queries
+ .iter()
+ .map(|(&(clan, class), &count)| (clan, class, count))
+ }
+
pub(super) fn set_base_radius(&mut self, clan: usize, limit: f32) {
if limit.is_finite() && limit > 0.0 {
self.base_radius_limits.insert(clan, limit);
diff --git a/crates/fparkan-runtime/src/construction_site.rs b/crates/fparkan-runtime/src/construction_site.rs
new file mode 100644
index 00000000..5993d244
--- /dev/null
+++ b/crates/fparkan-runtime/src/construction_site.rs
@@ -0,0 +1,123 @@
+use fparkan_terrain::{NavigationQuery, SurfaceQuery, TerrainWorld};
+use fparkan_world::{handle_by_original_id, registration_sequence, transform_state, World};
+
+use crate::{mining::MineSite, MissionObjectDraft};
+
+#[derive(Default)]
+pub(super) struct SiteReservations(Vec<([u32; 2], u32)>);
+
+impl SiteReservations {
+ pub(super) fn find(
+ &mut self,
+ terrain: &TerrainWorld,
+ world: &World,
+ drafts: &[MissionObjectDraft],
+ mines: &[MineSite],
+ base: [f32; 2],
+ now_ms: u32,
+ ) -> Option<[u32; 2]> {
+ self.0
+ .retain(|&(_, time)| now_ms.wrapping_sub(time) <= 60_000);
+ let occupied = drafts.iter().filter_map(|draft| {
+ if draft.unit_dat_header_flags? & 0x8000_0000 == 0 {
+ return None;
+ }
+ let handle = handle_by_original_id(world, draft.original_id?)?;
+ registration_sequence(world, handle).ok()??;
+ let [x, y, _] = transform_state(world, handle)
+ .ok()?
+ .position
+ .map(f32::from_bits);
+ Some([x, y])
+ });
+ let deposits = mines.iter().filter_map(|site| {
+ let [x, y, _] = site.position;
+ site.live_mine(world).is_none().then_some([x, y])
+ });
+ let occupied = occupied
+ .chain(deposits)
+ .chain(
+ self.0
+ .iter()
+ .map(|&(position, _)| position.map(|axis| axis as f32)),
+ )
+ .collect::<Vec<_>>();
+ let position = find_site(base, &occupied, |[x, y]| {
+ // shortcut: use navigable terrain polygons until the ArealMap placement bit is mapped.
+ terrain.locate_areal([x, y, 0.0]).ok()??;
+ terrain.height_at([x, y]).ok()?
+ })?;
+ if self.0.len() < 20 {
+ self.0.push((position, now_ms));
+ }
+ Some(position)
+ }
+}
+
+fn find_site(
+ base: [f32; 2],
+ occupied: &[[f32; 2]],
+ mut ground: impl FnMut([f32; 2]) -> Option<f32>,
+) -> Option<[u32; 2]> {
+ let [base_x, base_y] = base.map(f32::trunc);
+ for ring in 0..10 {
+ let radius = ring as f64 * 150.0;
+ let step = (150.0 / radius).atan() as f32;
+ let mut angle = 0.0_f32;
+ while angle < 2.0 * (31415.0 / 10000.0) {
+ let (sin, cos) = f64::from(angle).sin_cos();
+ let x = base_x + (radius * cos).trunc() as f32;
+ let y = base_y + (radius * sin).trunc() as f32;
+ if x > 0.0
+ && y > 0.0
+ && occupied
+ .iter()
+ .all(|&[a, b]| (x - a).trunc().hypot((y - b).trunc()) >= 250.0)
+ {
+ let corners = [
+ [x + 75.0, y + 75.0],
+ [x - 75.0, y - 75.0],
+ [x + 75.0, y - 75.0],
+ [x - 75.0, y + 75.0],
+ ];
+ let [Some(a), Some(b), Some(c), Some(d)] = corners.map(&mut ground) else {
+ angle += step;
+ continue;
+ };
+ let mean = (a + b + c + d) * 0.25;
+ if [a, b, c, d]
+ .into_iter()
+ .map(|height| (height - mean).abs())
+ .sum::<f32>()
+ * 0.25
+ <= 20.0
+ {
+ return Some([x as u32, y as u32]);
+ }
+ }
+ angle += step;
+ }
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn site_checks_the_footprint_and_clearance_in_base_ring_order() {
+ let flat = |_| Some(10.0);
+ assert_eq!(find_site([600.8, 600.9], &[], flat), Some([600, 600]));
+ assert_eq!(
+ find_site([600.0, 600.0], &[[600.0, 600.0]], flat),
+ Some([900, 600])
+ );
+ assert_eq!(
+ find_site([600.0, 600.0], &[[350.0, 600.0]], flat),
+ Some([600, 600])
+ );
+ assert!(find_site([600.0, 600.0], &[], |_| None).is_none());
+ assert!(find_site([600.0, 600.0], &[], |[x, _]| Some(x)).is_none());
+ }
+}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 9dba33cb..0261b1b0 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -51,6 +51,7 @@ mod clan_problem_conditions;
mod clan_script_init;
mod clan_targeting;
mod clan_transport_schemes;
+mod construction_site;
mod mesh_collision;
mod mining;
mod mission_events;
@@ -2953,6 +2954,7 @@ pub struct SimulationReport {
pub script_problem_waits: Vec<(usize, u32, u64)>,
pub script_factory_patrol_continues: Vec<(usize, u32, u64)>,
pub script_ore_transport_orders: Vec<(usize, u32, u64)>,
+ pub script_building_site_queries: Vec<(usize, u32, u64)>,
pub script_capturer_queries: Vec<(usize, u64)>,
pub script_capture_approaches: Vec<(u32, u32, u64)>,
/// First factory completion by clan, in milliseconds.
@@ -3005,6 +3007,7 @@ pub fn simulate_mission_report(
script_problem_waits: Vec::new(),
script_factory_patrol_continues: Vec::new(),
script_ore_transport_orders: Vec::new(),
+ script_building_site_queries: Vec::new(),
script_capturer_queries: Vec::new(),
script_capture_approaches: Vec::new(),
first_factory_completion_ms: Default::default(),
@@ -3111,6 +3114,9 @@ pub fn simulate_mission_report(
.script_ore_transport_orders
.extend(loaded.clan_ai_events.transport_orders());
report
+ .script_building_site_queries
+ .extend(loaded.clan_ai_events.building_site_queries());
+ report
.script_capturer_queries
.extend(loaded.clan_ai_events.capturer_queries());
report
diff --git a/crates/fparkan-runtime/src/mining.rs b/crates/fparkan-runtime/src/mining.rs
index 6448dc13..61266b9d 100644
--- a/crates/fparkan-runtime/src/mining.rs
+++ b/crates/fparkan-runtime/src/mining.rs
@@ -70,7 +70,7 @@ impl MineSite {
}
}
- fn live_mine(&self, world: &World) -> Option<ObjectHandle> {
+ pub(super) fn live_mine(&self, world: &World) -> Option<ObjectHandle> {
self.placed_mine
.and_then(|id| handle_by_original_id(world, id))
.or_else(|| handle_by_original_id(world, self.control.as_ref()?.original_id?))