aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-14 23:18:34 +0300
committerValentin Popov <valentin@popov.link>2026-11-14 23:18:34 +0300
commit66c02b87b96e63d3cfce29c8ca33a2bb28662ec6 (patch)
treec949f84e12efad4126851bc61eb617ccc87c3948
parentbbd6088b7fb1162a976bcfa1ca6720c2c91e8a72 (diff)
downloadfparkan-66c02b87b96e63d3cfce29c8ca33a2bb28662ec6.tar.xz
fparkan-66c02b87b96e63d3cfce29c8ca33a2bb28662ec6.zip
feat(ai): execute tower construction orders
Use the first BuildDat scheme for the requested class, check learned components, and route the builder before spending onboard ore. The Behavior.dll oracle rejected the stock scheme and returned 1100 ore after unlocking the components. The stock mission 28 window showed the refusal with its original tech tree. A licensed prepared test exercised construction and ore deduction. Onboard supply remains required pending warehouse refill.
-rw-r--r--apps/fparkan-game/src/main.rs7
-rw-r--r--apps/fparkan-game/src/script_coverage.rs8
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs64
-rw-r--r--crates/fparkan-runtime/src/clan_problem_conditions.rs6
-rw-r--r--crates/fparkan-runtime/src/construction.rs420
-rw-r--r--crates/fparkan-runtime/src/construction_site.rs42
-rw-r--r--crates/fparkan-runtime/src/lib.rs21
-rw-r--r--crates/fparkan-runtime/src/production.rs6
-rw-r--r--crates/fparkan-runtime/src/unit_patrol.rs2
-rw-r--r--docs/appendices/knowledge-boundaries.md6
-rw-r--r--docs/tomes/06-behavior.md13
11 files changed, 554 insertions, 41 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 68b99426..8949b135 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -7769,10 +7769,13 @@ fn mission_basement_footprints(
) -> Result<Vec<MissionBasementFootprint>, String> {
let mut footprints = Vec::new();
for (object_index, mission_root) in roots.iter().enumerate() {
- // shortcut: deployed mines lack a live BAS cut until terrain can
+ // shortcut: newly built structures lack a live BAS cut until terrain can
// rebuild the affected cells when a building enters the world.
if mission_root.raw_after_resource == u32::MAX
- && mission_root.unit_dat_header_flags == Some(0x8000_0004)
+ && matches!(
+ mission_root.unit_dat_header_flags,
+ Some(0x8000_0004 | 0x8010_0000 | 0x8020_0000)
+ )
{
continue;
}
diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs
index a67ddde3..247d8cff 100644
--- a/apps/fparkan-game/src/script_coverage.rs
+++ b/apps/fparkan-game/src/script_coverage.rs
@@ -50,6 +50,14 @@ pub(super) fn log_clan_ai_stops(report: &SimulationReport) {
"sim_coverage script_building_site_approx={count} clan={clan} class={class:#010x}"
);
}
+ for &(clan, builder, class, accepted, rejected) in &report.script_construction_orders {
+ if accepted != 0 {
+ eprintln!("sim_coverage script_building_order_approx={accepted} clan={clan} builder={builder} class={class:#010x}");
+ }
+ if rejected != 0 {
+ eprintln!("sim_coverage script_building_rejected={rejected} clan={clan} builder={builder} class={class:#010x}");
+ }
+ }
for &(clan, count) in &report.script_capturer_queries {
eprintln!("sim_coverage script_nearest_capturer_approx={count} clan={clan}");
}
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs
index 17aab8a9..0ecea127 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -82,6 +82,7 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) {
let Some(loaded) = &mut engine.loaded else {
return;
};
+ crate::construction::tick(loaded, &mut engine.world, now_ms);
loaded.clan_ai_events.groups.retain(|&(clan, _), group| {
if !identity_metadata(&engine.world, group.target)
.is_ok_and(|identity| identity.owner_id == group.target_owner)
@@ -130,7 +131,7 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) {
OwnerId(clan as u16),
loaded.unit_patrol.as_ref(),
group,
- |unit| ai.transports.iter().any(|(job, task)| *job == (clan, key) && task.unit == unit),
+ |unit| loaded.construction.active(unit) || ai.transports.iter().any(|(job, task)| *job == (clan, key) && task.unit == unit),
)
});
if ready {
@@ -157,7 +158,12 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) {
.as_ref()
.is_some_and(|production| production.is_building_at(*plant, OwnerId(*clan)))
});
- for order in loaded.tick_clan_ai_events(&engine.world, engine.production.as_ref(), now_ms) {
+ for order in loaded.tick_clan_ai_events(
+ &engine.world,
+ engine.production.as_ref(),
+ engine.services.vfs.as_deref(),
+ now_ms,
+ ) {
match crate::production::order_script_factory(
engine,
order.owner,
@@ -235,6 +241,7 @@ pub(super) struct ClanAiEvents {
wait_starts: BTreeMap<(usize, u32), u64>,
building_sites: crate::construction_site::SiteReservations,
building_site_queries: BTreeMap<(usize, u32), u64>,
+ construction_orders: BTreeMap<(usize, u32, u32), (u64, u64)>,
patrol_continues: BTreeMap<(usize, u32), u64>,
group_orders: BTreeMap<(usize, u32), u64>,
}
@@ -244,6 +251,7 @@ impl LoadedMissionState {
&mut self,
world: &World,
production: Option<&crate::production::Production>,
+ vfs: Option<&dyn fparkan_vfs::Vfs>,
now_ms: u32,
) -> Vec<ScriptFactoryOrder> {
let mut orders = Vec::new();
@@ -540,12 +548,36 @@ 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 (7, 3, Handler15TargetPayload::ByPlace { first, second }) =
+ (order.word_1, order.word_2, order.target)
+ {
+ if !problem.as_ref().is_some_and(|p| p.key.word_0 == BUILDING_NEEDED)
+ || !matches!(order.word_3, 0x8010_0000 | 0x8020_0000)
+ {
+ return Err("ORDER_ROBOT_BUILD requires a supported defensive tower scheme".into());
+ }
+ let owner = OwnerId(clan as u16);
+ let builder = self.mission_events.logic_objects(&self.mission, world, order.word_0)
+ .find(|&handle| identity_metadata(world, handle).is_ok_and(|identity| identity.owner_id == Some(owner)));
+ let result = crate::construction::order(
+ &mut self.construction, &mut self.unit_patrol, world, &self.terrain, &self.mission,
+ &self.object_drafts, &self.behavior_ore_states, &self.free_research,
+ vfs, builder, owner, order.word_3, [first, second],
+ );
+ let rates = self.clan_ai_events.construction_orders.entry((clan, order.word_0, order.word_3)).or_default();
+ match result {
+ Ok(()) => {
+ rates.0 += 1;
+ eprintln!("sim_coverage script_building_order_approx=1 clan={clan} builder={} class={:#010x} site=[{first}, {second}]", order.word_0, order.word_3);
+ }
+ Err(ref reason) => {
+ rates.1 += 1;
+ if rates.1 == 1 {
+ eprintln!("sim_coverage script_building_rejected=1 clan={clan} builder={} class={:#010x} reason={reason}", order.word_0, order.word_3);
+ }
+ }
+ }
+ return Ok(Some(VarSetDefault::Dword(u32::from(result.is_ok()))));
}
if let (6, 3, Handler15TargetPayload::NotDefined(_), Some(problem)) =
(order.word_1, order.word_2, order.target, problem.as_ref())
@@ -732,11 +764,11 @@ impl LoadedMissionState {
};
let key = problem.as_ref().expect("condition requires a problem").key;
let condition = match (action, mode) {
- (2, 0) if key.word_0 == OPTIMAL_TRANSPORT && solving => {
+ (2, 0) if key.word_0 == BUILDING_NEEDED || (key.word_0 == OPTIMAL_TRANSPORT && solving) => {
let unit = assignment.filter(|&unit| self.mission_events
.logic_objects(&self.mission, world, id).any(|handle| handle == unit))
- .ok_or("Handler(27) transport wait requires the assigned unit")?;
- Some(Condition::TransportInactive(unit))
+ .ok_or("Handler(27) task wait requires the assigned unit")?;
+ Some(Condition::TaskInactive(unit))
}
(1 | 3, 0) if matches!(key.word_0, 7 | 9) || (action == 1 && key.word_0 == BUILDING_PROTECT) => {
let target = crate::mission_events::placed_logic_objects(
@@ -1235,6 +1267,16 @@ impl ClanAiEvents {
.map(|(&(clan, class), &count)| (clan, class, count))
}
+ pub(super) fn construction_orders(
+ &self,
+ ) -> impl Iterator<Item = (usize, u32, u32, u64, u64)> + '_ {
+ self.construction_orders
+ .iter()
+ .map(|(&(clan, unit, class), &(accepted, rejected))| {
+ (clan, unit, class, accepted, rejected)
+ })
+ }
+
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/clan_problem_conditions.rs b/crates/fparkan-runtime/src/clan_problem_conditions.rs
index 00d39173..e0d11336 100644
--- a/crates/fparkan-runtime/src/clan_problem_conditions.rs
+++ b/crates/fparkan-runtime/src/clan_problem_conditions.rs
@@ -8,7 +8,7 @@ pub(super) enum Condition {
BuildingCaptured(ObjectHandle),
GroupDestroyed,
GroupIdle,
- TransportInactive(ObjectHandle),
+ TaskInactive(ObjectHandle),
}
impl Condition {
@@ -18,7 +18,7 @@ impl Condition {
clan: OwnerId,
patrol: Option<&UnitPatrol>,
group: Option<&CombatGroup>,
- transport_active: impl Fn(ObjectHandle) -> bool,
+ task_active: impl Fn(ObjectHandle) -> bool,
) -> bool {
let live =
|unit| registration_sequence(world, unit).is_ok_and(|sequence| sequence.is_some());
@@ -32,7 +32,7 @@ impl Condition {
Self::GroupDestroyed => {
group.is_none_or(|group| group.members.iter().all(|&unit| !live(unit)))
}
- Self::TransportInactive(unit) => !live(unit) || !transport_active(unit),
+ Self::TaskInactive(unit) => !live(unit) || !task_active(unit),
Self::GroupIdle => group.is_none_or(|group| {
group.members.iter().all(|&unit| {
!live(unit) || patrol.is_none_or(|patrol| !patrol.is_patrolling(unit))
diff --git a/crates/fparkan-runtime/src/construction.rs b/crates/fparkan-runtime/src/construction.rs
new file mode 100644
index 00000000..afeff2e5
--- /dev/null
+++ b/crates/fparkan-runtime/src/construction.rs
@@ -0,0 +1,420 @@
+use crate::autodemo::spawn_prepared_unit;
+use crate::{LoadedMissionState, MissionScriptBundle};
+use fparkan_path::ResourceName;
+use fparkan_script::ScriptDispatchSelector;
+use fparkan_terrain::SurfaceQuery;
+use fparkan_world::{
+ handle_by_original_id, identity_metadata, transform_state, ObjectHandle, OwnerId, World,
+};
+
+pub(super) const BUILDER_CLASS: u32 = 0x0100_4000;
+const SLOTS_PER_CLASS: usize = 3;
+const WAIT_MS: u32 = 1_000;
+const ARRIVAL_RADIUS: f32 = 1.0;
+
+pub(super) fn reserve_schemes(
+ categories: &[crate::BuildCategory],
+ bundles: &[MissionScriptBundle],
+) -> Vec<ResourceName> {
+ let enabled = bundles.iter().any(|bundle| {
+ bundle.package.events.iter().any(|event| {
+ event.name_raw == b"PBM_BUILDING_NEEDED_Start\0"
+ && event.instructions.iter().any(|instruction| {
+ instruction.dispatch_selector() == ScriptDispatchSelector::Handler(18)
+ })
+ })
+ });
+ // shortcut: prepare the defensive tower schemes exercised by the site query.
+ categories
+ .iter()
+ .filter(move |category| enabled && matches!(category.mask, 0x8010_0000 | 0x8020_0000))
+ .filter_map(|category| category.unit_paths.first())
+ .flat_map(|path| (0..SLOTS_PER_CLASS).map(move |_| crate::resource_name(path.as_bytes())))
+ .collect()
+}
+
+#[derive(Default)]
+pub(super) struct Construction {
+ first_slot: usize,
+ controls: Vec<crate::MissionControlDeviceTableState>,
+ tasks: Vec<Task>,
+}
+
+struct Task {
+ builder: ObjectHandle,
+ owner: OwnerId,
+ slot: usize,
+ position: [f32; 3],
+ cost: f32,
+ arrived_at: Option<u32>,
+}
+
+impl Construction {
+ pub(super) fn new(
+ first_slot: usize,
+ controls: Vec<crate::MissionControlDeviceTableState>,
+ ) -> Self {
+ Self {
+ first_slot,
+ controls,
+ tasks: Vec::new(),
+ }
+ }
+
+ pub(super) fn active(&self, builder: ObjectHandle) -> bool {
+ self.tasks.iter().any(|task| task.builder == builder)
+ }
+
+ fn available_slot(
+ &self,
+ world: &World,
+ drafts: &[crate::MissionObjectDraft],
+ class: u32,
+ ) -> Option<usize> {
+ (self.first_slot..self.first_slot + self.controls.len()).find(|&index| {
+ let draft = &drafts[index];
+ draft.unit_dat_header_flags == Some(class)
+ && draft
+ .original_id
+ .is_some_and(|id| handle_by_original_id(world, id).is_none())
+ && !self.tasks.iter().any(|task| task.slot == index)
+ })
+ }
+
+ fn start(
+ &mut self,
+ builder: ObjectHandle,
+ owner: OwnerId,
+ slot: usize,
+ position: [f32; 3],
+ cost: f32,
+ ) {
+ self.tasks.push(Task {
+ builder,
+ owner,
+ slot,
+ position,
+ cost,
+ arrived_at: None,
+ });
+ }
+}
+
+pub(super) fn order(
+ construction: &mut Construction,
+ patrol: &mut Option<crate::unit_patrol::UnitPatrol>,
+ world: &World,
+ terrain: &fparkan_terrain::TerrainWorld,
+ mission: &crate::MissionDocument,
+ drafts: &[crate::MissionObjectDraft],
+ ores: &[crate::BehaviorOreState],
+ research: &crate::research::FreeResearch,
+ vfs: Option<&dyn fparkan_vfs::Vfs>,
+ builder: Option<ObjectHandle>,
+ owner: OwnerId,
+ class: u32,
+ xy: [u32; 2],
+) -> Result<(), String> {
+ let builder = builder.ok_or("builder is unavailable")?;
+ if construction.active(builder) {
+ return Err("builder is busy".into());
+ }
+ if patrol
+ .as_ref()
+ .is_some_and(|patrol| patrol.is_shut_down(builder))
+ {
+ return Err("builder is shut down".into());
+ }
+ let cargo = ores
+ .iter()
+ .find(|ore| ore.handle == builder && ore.class_flags == BUILDER_CLASS)
+ .ok_or("unit has no builder ore state")?;
+ let slot = construction
+ .available_slot(world, drafts, class)
+ .ok_or("no free prepared tower slot")?;
+ let table = crate::research::load_technology_table(
+ vfs.ok_or("no clan technology provider")?,
+ mission,
+ owner,
+ )
+ .map_err(|err| err.to_string())?;
+ let cost = crate::production::scheme_cost(&drafts[slot].unit_components, &table, |row| {
+ research.learned.contains(&(owner, row))
+ })
+ .map_err(|err| err.to_string())?
+ .ore;
+ let stock = f32::from_bits(cargo.current_ore_bits);
+ // shortcut: require ore onboard until the builder can fetch it from a warehouse.
+ if !stock.is_finite() || stock < cost {
+ return Err("builder has insufficient ore".into());
+ }
+ let from = transform_state(world, builder)
+ .map_err(|err| err.to_string())?
+ .position
+ .map(f32::from_bits);
+ let position = destination(terrain, from, xy).ok_or("no route to the building site")?;
+ patrol
+ .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted)
+ .move_to(world, builder, [position[0], position[1]], false);
+ construction.start(builder, owner, slot, position, cost);
+ Ok(())
+}
+
+pub(super) fn tick(mission: &mut LoadedMissionState, world: &mut World, now_ms: u32) {
+ let mut index = 0;
+ while let Some(task) = mission.construction.tasks.get_mut(index) {
+ let owned =
+ identity_metadata(world, task.builder).is_ok_and(|id| id.owner_id == Some(task.owner));
+ let running = !mission
+ .unit_patrol
+ .as_ref()
+ .is_some_and(|patrol| patrol.is_shut_down(task.builder));
+ let mut finish = false;
+ if let Some(pose) = transform_state(world, task.builder)
+ .ok()
+ .filter(|_| owned && running)
+ {
+ let [x, y, _] = pose.position.map(f32::from_bits);
+ let [a, b, _] = task.position;
+ if (x - a).hypot(y - b) > ARRIVAL_RADIUS {
+ task.arrived_at = None;
+ if mission
+ .unit_patrol
+ .as_ref()
+ .is_some_and(|patrol| patrol.is_moving_to_destination(task.builder))
+ {
+ index += 1;
+ continue;
+ }
+ } else {
+ let arrived_at = *task.arrived_at.get_or_insert(now_ms);
+ if now_ms.wrapping_sub(arrived_at) < WAIT_MS {
+ index += 1;
+ continue;
+ }
+ finish = true;
+ }
+ }
+ let task = mission.construction.tasks.remove(index);
+ if let Some(patrol) = &mut mission.unit_patrol {
+ patrol.clear_move(task.builder);
+ }
+ if finish {
+ if let Err(error) = complete(mission, world, &task) {
+ eprintln!(
+ "script_building_construction_failed clan={} builder={} reason={error}",
+ task.owner.0, task.builder.slot
+ );
+ }
+ }
+ }
+}
+
+fn complete(
+ mission: &mut LoadedMissionState,
+ world: &mut World,
+ task: &Task,
+) -> Result<(), crate::EngineError> {
+ let index = crate::behavior_ore_index_for_handle(&mission.behavior_ore_states, task.builder)
+ .map_err(crate::EngineError::Production)?;
+ let stock = f32::from_bits(mission.behavior_ore_states[index].current_ore_bits);
+ if !stock.is_finite() || stock < task.cost {
+ return Err(crate::EngineError::Production(
+ "builder has insufficient ore".into(),
+ ));
+ }
+ let [x, y, _] = task.position;
+ if !crate::construction_site::building_centers(world, &mission.object_drafts)
+ .all(|other| crate::construction_site::separated([x, y], other))
+ {
+ return Err(crate::EngineError::Production(
+ "building site is occupied".into(),
+ ));
+ }
+ let draft = &mission.object_drafts[task.slot];
+ let id = draft.original_id.expect("prepared building has an ID");
+ let class = draft
+ .unit_dat_header_flags
+ .expect("prepared building has a class");
+ let profile = mission
+ .behavior_profiles
+ .iter()
+ .position(|profile| profile.original_id == id);
+ let control =
+ mission.construction.controls[task.slot - mission.construction.first_slot].clone();
+ let handle = spawn_prepared_unit(
+ world,
+ mission,
+ task.slot,
+ task.owner.0,
+ task.position,
+ control,
+ )?;
+ mission.behavior_ore_states[index].current_ore_bits = (stock - task.cost).to_bits();
+ mission
+ .behavior_ore_states
+ .retain(|ore| ore.original_id != id);
+ mission
+ .behavior_ore_states
+ .push(crate::initialize_behavior_ore_state(id, handle, class, &[]));
+ if let Some(profile) = profile {
+ mission.behavior_profiles[profile].handle = handle;
+ }
+ if let Some(distributor) = mission.behavior_distributors.get_mut(task.owner.0 as usize) {
+ distributor
+ .registered_objects
+ .retain(|entry| entry.original_id != id);
+ crate::add_behavior_registered_object(
+ distributor,
+ crate::BehaviorRegisteredObject {
+ original_id: id,
+ handle,
+ selector: u32::from(task.owner.0),
+ class_flags: class,
+ share: 0.0,
+ native_tail: [0; 5],
+ },
+ );
+ }
+ mission
+ .mission_events
+ .issue_logic_id(&mission.mission, world, handle);
+ eprintln!(
+ "script_building_constructed clan={} builder={} building={} class={class:#010x}",
+ task.owner.0, task.builder.slot, handle.slot
+ );
+ Ok(())
+}
+
+fn destination(
+ terrain: &fparkan_terrain::TerrainWorld,
+ from: [f32; 3],
+ xy: [u32; 2],
+) -> Option<[f32; 3]> {
+ let [x, y] = xy.map(|x| x as f32);
+ let position = [x, y, terrain.height_at([x, y]).ok()??];
+ crate::unit_patrol::route_points(terrain, from, position).ok()??;
+ Some(position)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{
+ create, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
+ MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use std::sync::Arc;
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn tower_order_rejects_unresearched_parts_and_spawns_when_available() {
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
+ let vfs = Arc::new(DirectoryVfs::new(root));
+ let mut engine = create(EngineServices::new(vfs.clone())).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();
+ let owner = OwnerId(1);
+ let class = 0x8010_0000;
+ let mission = engine.loaded.as_mut().unwrap();
+ let builder_ore = mission
+ .behavior_ore_states
+ .iter()
+ .position(|ore| {
+ ore.class_flags == BUILDER_CLASS
+ && identity_metadata(&engine.world, ore.handle)
+ .is_ok_and(|id| id.owner_id == Some(owner))
+ })
+ .unwrap();
+ let builder = mission.behavior_ore_states[builder_ore].handle;
+ let site = crate::construction_site::SiteReservations::default()
+ .find(
+ &mission.terrain,
+ &engine.world,
+ &mission.object_drafts,
+ &mission.mine_sites,
+ mission.mission.clans[1].anchor.map(f32::round_ties_even),
+ 7_000,
+ )
+ .unwrap();
+ let slot = mission
+ .construction
+ .available_slot(&engine.world, &mission.object_drafts, class)
+ .unwrap();
+ let id = mission.object_drafts[slot].original_id.unwrap();
+ let order_for = |mission: &mut LoadedMissionState, world: &World| {
+ order(
+ &mut mission.construction,
+ &mut mission.unit_patrol,
+ world,
+ &mission.terrain,
+ &mission.mission,
+ &mission.object_drafts,
+ &mission.behavior_ore_states,
+ &mission.free_research,
+ Some(vfs.as_ref()),
+ Some(builder),
+ owner,
+ class,
+ site,
+ )
+ };
+ assert!(order_for(mission, &engine.world)
+ .unwrap_err()
+ .contains("unavailable for construction"));
+ let table =
+ crate::research::load_technology_table(vfs.as_ref(), &mission.mission, owner).unwrap();
+ // Set up a supplied builder after testing the unchanged mission's research gate.
+ for component in &mission.object_drafts[slot].unit_components {
+ if let Some(row) = table.find_key(&component.resource_raw).unwrap() {
+ mission.free_research.learned.insert((owner, row));
+ }
+ }
+ assert_eq!(
+ order_for(mission, &engine.world).unwrap_err(),
+ "builder has insufficient ore"
+ );
+ let stock_before = 2000.0_f32;
+ mission.behavior_ore_states[builder_ore].current_ore_bits = stock_before.to_bits();
+ order_for(mission, &engine.world).unwrap();
+ assert!(mission.construction.active(builder));
+ assert!(handle_by_original_id(&engine.world, id).is_none());
+ let cost = mission.construction.tasks[0].cost;
+ assert_eq!(cost, 1100.0);
+ let pose = transform_state(&engine.world, builder).unwrap();
+ fparkan_world::set_transform(
+ &mut engine.world,
+ builder,
+ fparkan_world::TransformState {
+ position: mission.construction.tasks[0].position.map(f32::to_bits),
+ ..pose
+ },
+ )
+ .unwrap();
+ tick(mission, &mut engine.world, 8_000);
+ assert!(handle_by_original_id(&engine.world, id).is_none());
+ tick(mission, &mut engine.world, 9_000);
+ let building = handle_by_original_id(&engine.world, id).unwrap();
+ assert_eq!(
+ identity_metadata(&engine.world, building).unwrap().owner_id,
+ Some(owner)
+ );
+ assert_eq!(
+ f32::from_bits(mission.behavior_ore_states[builder_ore].current_ore_bits),
+ stock_before - cost
+ );
+ assert!(!mission.construction.active(builder));
+ }
+}
diff --git a/crates/fparkan-runtime/src/construction_site.rs b/crates/fparkan-runtime/src/construction_site.rs
index 5993d244..ddb92a8e 100644
--- a/crates/fparkan-runtime/src/construction_site.rs
+++ b/crates/fparkan-runtime/src/construction_site.rs
@@ -6,6 +6,28 @@ use crate::{mining::MineSite, MissionObjectDraft};
#[derive(Default)]
pub(super) struct SiteReservations(Vec<([u32; 2], u32)>);
+pub(super) fn building_centers<'a>(
+ world: &'a World,
+ drafts: &'a [MissionObjectDraft],
+) -> impl Iterator<Item = [f32; 2]> + 'a {
+ 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])
+ })
+}
+
+pub(super) fn separated([x, y]: [f32; 2], [a, b]: [f32; 2]) -> bool {
+ (x - a).trunc().hypot((y - b).trunc()) >= 250.0
+}
+
impl SiteReservations {
pub(super) fn find(
&mut self,
@@ -18,18 +40,7 @@ impl SiteReservations {
) -> 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 occupied = building_centers(world, drafts);
let deposits = mines.iter().filter_map(|site| {
let [x, y, _] = site.position;
site.live_mine(world).is_none().then_some([x, y])
@@ -68,12 +79,7 @@ fn find_site(
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)
- {
+ if x > 0.0 && y > 0.0 && occupied.iter().all(|&other| separated([x, y], other)) {
let corners = [
[x + 75.0, y + 75.0],
[x - 75.0, y - 75.0],
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 0261b1b0..81f6e899 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;
mod construction_site;
mod mesh_collision;
mod mining;
@@ -1365,6 +1366,7 @@ struct LoadedMissionState {
mission_events: MissionEvents,
clan_ai_events: clan_ai_events::ClanAiEvents,
mine_sites: Vec<mining::MineSite>,
+ construction: construction::Construction,
unit_patrol: Option<unit_patrol::UnitPatrol>,
player_pitch_bits: u32,
boarding: Option<boarding::Boarding>,
@@ -1990,6 +1992,13 @@ fn load_mission_with_options(
.take(production::RESERVE_SLOTS),
);
}
+ let construction_reserve_start = graph_roots.len();
+ if options.start_autodemo && request.mode == MissionMode::SingleMission {
+ graph_roots.extend(construction::reserve_schemes(
+ &build_categories,
+ &loaded_scripts.bundles,
+ ));
+ }
let mine_reserve_start = graph_roots.len();
let mine_scheme = (options.start_autodemo && request.mode == MissionMode::SingleMission)
.then(|| {
@@ -2654,6 +2663,10 @@ fn load_mission_with_options(
Vec::new()
};
let mine_controls = reserve_controls.split_off(mine_reserve_start - reserve_start);
+ let construction_controls =
+ reserve_controls.split_off(construction_reserve_start - reserve_start);
+ let construction =
+ construction::Construction::new(construction_reserve_start, construction_controls);
for (site, control) in mine_sites.iter_mut().zip(mine_controls) {
site.control = Some(control);
}
@@ -2667,7 +2680,7 @@ fn load_mission_with_options(
player_scheme_count,
transport_schemes,
reserve_controls,
- &object_drafts[..mine_reserve_start],
+ &object_drafts[..construction_reserve_start],
)?),
)
} else {
@@ -2723,6 +2736,7 @@ fn load_mission_with_options(
mission_events,
clan_ai_events,
mine_sites,
+ construction,
unit_patrol,
player_pitch_bits: 0,
boarding: None,
@@ -2955,6 +2969,7 @@ pub struct SimulationReport {
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_construction_orders: Vec<(usize, u32, u32, u64, u64)>,
pub script_capturer_queries: Vec<(usize, u64)>,
pub script_capture_approaches: Vec<(u32, u32, u64)>,
/// First factory completion by clan, in milliseconds.
@@ -3008,6 +3023,7 @@ pub fn simulate_mission_report(
script_factory_patrol_continues: Vec::new(),
script_ore_transport_orders: Vec::new(),
script_building_site_queries: Vec::new(),
+ script_construction_orders: Vec::new(),
script_capturer_queries: Vec::new(),
script_capture_approaches: Vec::new(),
first_factory_completion_ms: Default::default(),
@@ -3117,6 +3133,9 @@ pub fn simulate_mission_report(
.script_building_site_queries
.extend(loaded.clan_ai_events.building_site_queries());
report
+ .script_construction_orders
+ .extend(loaded.clan_ai_events.construction_orders());
+ report
.script_capturer_queries
.extend(loaded.clan_ai_events.capturer_queries());
report
diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs
index 6bc3e306..c144eb43 100644
--- a/crates/fparkan-runtime/src/production.rs
+++ b/crates/fparkan-runtime/src/production.rs
@@ -86,8 +86,8 @@ struct Order {
}
#[derive(Default)]
-struct Cost {
- ore: f32,
+pub(super) struct Cost {
+ pub(super) ore: f32,
power: f32,
}
@@ -614,7 +614,7 @@ fn production_error(error: impl std::fmt::Display) -> EngineError {
EngineError::Production(error.to_string())
}
-fn scheme_cost(
+pub(super) fn scheme_cost(
records: &[UnitComponentRecord],
research: &ResearchTrfDocument,
learned: impl Fn(usize) -> bool,
diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs
index 149f466b..6fb1c92a 100644
--- a/crates/fparkan-runtime/src/unit_patrol.rs
+++ b/crates/fparkan-runtime/src/unit_patrol.rs
@@ -662,7 +662,7 @@ fn choose_route(
Ok(VecDeque::new())
}
-fn route_points(
+pub(super) fn route_points(
terrain: &TerrainWorld,
from: [f32; 3],
goal: [f32; 3],
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 8a5156d5..fa3284f0 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -458,8 +458,10 @@ core и `ResearchCandidateSet::refresh_selection`: последний получ
`script_ore_transport_approx` считает принятые приказы по клану и машине.
ID выпущенной машины внутренний. Подъезд, выбор порта и темп перегрузки приближённые.
`script_building_site_approx` считает поиск площадок по клану и классу строения.
-Проверка проходимости использует полигоны навигации FParkan. Нативный флаг
-площадки, выбор схемы и исполнение `ORDER_ROBOT_BUILD` открыты.
+Проверка проходимости использует полигоны навигации FParkan.
+`script_building_order_approx` и `script_building_rejected` учитывают приказы
+строителям. Подключены башни и руда на борту. Подвоз руды, прочие строения,
+фундамент и боевое поведение новой башни открыты.
Разные заводы могут собирать одновременно.
`script_factory_rejections` считает отклонения по клану и заводу.
`script_combat_strength_approx` считает запросы `Handler(38)` по паре кланов.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 4250d8e7..33852bb9 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -405,6 +405,19 @@ GOG `ai.dll` по RVA `0xa148` проверяет четыре угла квад
повторный вызов с активным резервом выбрал точку на следующем допустимом
кольце. При недоступных областях вызов вернул `(0, 0)`.
+Строитель получает первую схему категории из `BuildDat.lst` через
+`ArealMap.dll` по RVA `0x20e80` (SHA-256
+`a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea`).
+Задача из GOG `Behavior.dll` по
+RVA `0x28800` проверяет детали и считает цену. Когда деталей нет в
+технологиях клана, приказ возвращает отказ. Задача может пополнить руду
+на складе, затем едет на площадку. Через секунду ожидания на месте
+создание объекта списывает руду (RVA `0x28e89` и `0x29240`).
+В FParkan строителю пока нужен запас на борту. Штатный приказ на среднюю
+башню в «Двух крепостях» получает отказ из-за деталей, которых ещё нет у клана.
+Изолированный вызов расчёта цены по RVA `0x29810` подтвердил отказ по
+штатным флагам и цену 1100 руды после открытия деталей.
+
### Первый запуск сценария