diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-14 22:44:04 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-14 22:44:04 +0300 |
| commit | d43524a8e40bb923d9275e17d3dc586701f08bbf (patch) | |
| tree | cf60379bbb567ebb31d2089d39c23ae42af3f2eb /crates | |
| parent | 947be441148cea94b2a847268b885cc20d36b2aa (diff) | |
| download | fparkan-d43524a8e40bb923d9275e17d3dc586701f08bbf.tar.xz fparkan-d43524a8e40bb923d9275e17d3dc586701f08bbf.zip | |
feat(ai): build the clan transport from the AI catalog
Let a scripted transport order survive a busy factory and use the unique eligible design from the clan technology table. The AI reserves its transport independently of the player scheme list.
Two Fortresses released sml_cargo.dat from the stock start in the FParkan window and the licensed regression covers both factories. The x86 DLL chooser confirmed class, readiness, and fastest selection. Transport routes and live timing parity remain open.
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 50 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_transport_schemes.rs | 68 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 17 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 71 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/research.rs | 19 |
5 files changed, 199 insertions, 26 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index e28343cf..03ac552c 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -1,4 +1,5 @@ use crate::clan_problem_conditions::Condition; +use crate::clan_transport_schemes::TRANSPORT_CLASS; use crate::{clan_combat_groups::CombatGroup, clan_targeting::CaptureApproach}; use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop}; use fparkan_script::{ @@ -11,11 +12,13 @@ use std::collections::BTreeMap; const STORAGE_CLASS: u32 = 0x8000_0008; const RESOURCE_ORE: u32 = 0x0200_0100; const BUILDING_PROTECT: u32 = 8; +const OPTIMAL_TRANSPORT: u32 = 4; pub(super) struct ScriptFactoryOrder { pub owner: OwnerId, pub plant: ObjectHandle, pub class: u32, + selection: u32, problem: Handler2RecordKey, wait_for_factory: bool, } @@ -106,7 +109,13 @@ pub(super) fn tick(engine: &mut crate::Engine, now_ms: u32) { && !crate::mission_events::placed_logic_objects(&loaded.mission, &engine.world, key.argument_0) .any(|target| identity_metadata(&engine.world, target) .is_ok_and(|identity| identity.owner_id == Some(OwnerId(clan as u16)))); - let ready = lost_building || conditions.iter().any(|&condition| { + // shortcut: recheck the request when a transport arrives until native problem aging is wired. + let transport_arrived = key.word_0 == OPTIMAL_TRANSPORT && conditions.is_empty() + && loaded.mission_events.clan_units(&engine.world, OwnerId(clan as u16), false) + .any(|unit| identity_metadata(&engine.world, unit).ok().and_then(|meta| meta.original_id) + .and_then(|id| loaded.object_drafts.get(id.0 as usize)) + .is_some_and(|draft| draft.unit_dat_header_flags == Some(TRANSPORT_CLASS))); + let ready = lost_building || transport_arrived || conditions.iter().any(|&condition| { condition.met( &engine.world, OwnerId(clan as u16), @@ -138,12 +147,13 @@ 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, now_ms) { + for order in loaded.tick_clan_ai_events(&engine.world, engine.production.as_ref(), now_ms) { match crate::production::order_script_factory( engine, order.owner, order.plant, order.class, + order.selection, now_ms, ) { Ok(duration) => { @@ -216,6 +226,7 @@ impl LoadedMissionState { pub(super) fn tick_clan_ai_events( &mut self, world: &World, + production: Option<&crate::production::Production>, now_ms: u32, ) -> Vec<ScriptFactoryOrder> { let mut orders = Vec::new(); @@ -320,6 +331,7 @@ impl LoadedMissionState { break; }; let mut solved = false; + let mut transport_factory_busy = false; let mut assignment = None; let mut solving = false; let mut capturer = None; @@ -556,13 +568,15 @@ impl LoadedMissionState { if problem.is_none() { return Err("Handler(15) order is unavailable in Problems0".into()); } + let Handler15TargetPayload::ByName(selection) = order.target else { + return Err("Handler(15) factory order requires design selection".into()); + }; if order.word_1 != 0x0c || order.word_2 != 1 - || order.word_3 != crate::boarding::WARBOT_CLASS - || !matches!(order.target, Handler15TargetPayload::ByName(_)) + || !matches!(order.word_3, crate::boarding::WARBOT_CLASS | TRANSPORT_CLASS) { return Err( - "Handler(15) only supports the scripted warbot factory order" + "Handler(15) factory order class or insertion mode is unsupported" .into(), ); } @@ -579,10 +593,17 @@ impl LoadedMissionState { let Some(plant) = plant else { return Ok(Some(VarSetDefault::Dword(5))); }; + if production.is_some_and(|queue| queue.is_building_at(plant, owner)) + || orders.iter().any(|order: &ScriptFactoryOrder| order.plant == plant) + { + transport_factory_busy = order.word_3 == TRANSPORT_CLASS; + return Ok(Some(VarSetDefault::Dword(0))); + } orders.push(ScriptFactoryOrder { owner, plant, class: order.word_3, + selection, problem: problem .as_ref() .expect("factory order requires a current problem") @@ -640,7 +661,7 @@ impl LoadedMissionState { Some(1) if problem .as_ref() - .is_some_and(|record| matches!(record.key.word_0, 6 | BUILDING_PROTECT)) + .is_some_and(|record| matches!(record.key.word_0, OPTIMAL_TRANSPORT | 6 | BUILDING_PROTECT)) || !conditions.is_empty() => { solving = true @@ -736,13 +757,14 @@ impl LoadedMissionState { if mode != 2 { return Err("Handler(14) only supports UNIT_ANY_UNIT".into()); } - // shortcut: only unassigned placed objects until PBM owns roster slots. let id = self.mission_events.first_available_placed_unit( - &self.mission, - world, - clan, - class, + &self.mission, world, clan, class, ); + if class == TRANSPORT_CLASS && id.is_none() + && self.mission_events.count_clan_class(world, OwnerId(clan as u16), class) != 0 + { + return Err("Handler(14) needs a runtime logic ID for the produced transport".into()); + } Ok(Some(VarSetDefault::Dword(id.unwrap_or(u32::MAX)))) } ScriptDispatchSelector::Handler(29) => { @@ -958,14 +980,16 @@ impl LoadedMissionState { } } if let Some(problem) = problem { - if solved { + // shortcut: keep transport demand queued until the factory can accept it. + if solved && !transport_factory_busy { self.clan_ai_events .problems .entry(clan) .or_default() .remove(problem.key); } else if solving - && (!conditions.is_empty() || problem.key.word_0 == BUILDING_PROTECT) + && (!conditions.is_empty() + || matches!(problem.key.word_0, OPTIMAL_TRANSPORT | BUILDING_PROTECT)) { let count = self .clan_ai_events diff --git a/crates/fparkan-runtime/src/clan_transport_schemes.rs b/crates/fparkan-runtime/src/clan_transport_schemes.rs new file mode 100644 index 00000000..63ae7d40 --- /dev/null +++ b/crates/fparkan-runtime/src/clan_transport_schemes.rs @@ -0,0 +1,68 @@ +use crate::{MissionDocument, MissionScriptBundle}; +use fparkan_assets::{ResearchCandidate, ResearchCandidateSet}; +use fparkan_path::NormalizedPath; +use fparkan_vfs::Vfs; +use fparkan_world::OwnerId; + +pub(super) const TRANSPORT_CLASS: u32 = 0x0100_2000; +pub(super) const SELECT_FASTEST: u32 = 4; + +pub(super) fn available( + vfs: &dyn Vfs, + mission: &MissionDocument, + bundles: &[MissionScriptBundle], +) -> Vec<(OwnerId, NormalizedPath)> { + let clans = bundles.iter().filter(|bundle| { + mission.clans[bundle.clan_index].mode == 2 + && bundle.package.events.iter().any(|event| { + event.name_raw == b"PBM_N_OPTIMAL_TRANSPORT_Start\0" + && !event.instructions.is_empty() + }) + }); + let mut clans = clans.peekable(); + if clans.peek().is_none() { + return Vec::new(); + } + let directory = crate::normalize_engine_path("AI transport", "UNITS/UNITS/AI") + .expect("static AI catalog path"); + let paths = vfs.list(&directory).unwrap_or_default(); + let entries: Vec<_> = paths + .into_iter() + .filter_map(|entry| { + let relative = entry.path.as_str().rsplit_once('/')?; + if !relative.0.eq_ignore_ascii_case(directory.as_str()) + || !relative.1.to_ascii_lowercase().ends_with(".dat") + { + return None; + } + let bytes = vfs.read(&entry.path).ok()?; + let header = fparkan_prototype::decode_unit_dat(&bytes) + .ok()? + .header_opaque; + let class = u32::from_le_bytes(header[4..].try_into().unwrap()); + (class == TRANSPORT_CLASS).then_some(ResearchCandidate { + path: entry.path, + status: 0, + }) + }) + .collect(); + clans + .filter_map(|bundle| { + let owner = OwnerId(u16::try_from(bundle.clan_index).ok()?); + let research = crate::research::load_technology_table(vfs, mission, owner).ok()?; + let mut catalog = ResearchCandidateSet { + entries: entries.clone(), + loaded: true, + ..Default::default() + }; + catalog.refresh_selection(vfs, Some(&research)).ok()?; + // shortcut: a unique qualified design needs no speed ranking or random policy. + let mut available = catalog + .entries + .into_iter() + .filter(|entry| entry.status != 0); + let selected = available.next()?; + available.next().is_none().then_some((owner, selected.path)) + }) + .collect() +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 6f2f6439..d93a5e5a 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -50,6 +50,7 @@ mod clan_combat_strength; mod clan_problem_conditions; mod clan_script_init; mod clan_targeting; +mod clan_transport_schemes; mod mesh_collision; mod mining; mod mission_events; @@ -1879,7 +1880,7 @@ fn load_mission_with_options( } else { Arc::from(&[][..]) }; - let build_schemes = if let Some(scheme) = build_scheme { + let mut build_schemes = if let Some(scheme) = build_scheme { vec![scheme.clone()] } else if options.start_autodemo && request.mode == MissionMode::SingleMission { production::mission_prebuilds(&config)? @@ -1933,6 +1934,18 @@ fn load_mission_with_options( } })?; let mut loaded_scripts = load_mission_scripts(&vfs, &mission, options.asset_scope)?; + let player_scheme_count = build_schemes.len(); + let transport_schemes = if options.start_autodemo && request.mode == MissionMode::SingleMission + { + clan_transport_schemes::available(vfs.as_ref(), &mission, &loaded_scripts.bundles) + } else { + Vec::new() + }; + for (_, path) in &transport_schemes { + if !build_schemes.contains(path) { + build_schemes.push(path.clone()); + } + } let research_trf_tables = if options.asset_scope == MissionAssetScope::Full && startup_input.is_some_and(|input| input.research_creation_gate) { @@ -2649,6 +2662,8 @@ fn load_mission_with_options( Some(production::Production::new( reserve_start, build_schemes, + player_scheme_count, + transport_schemes, reserve_controls, &object_drafts[..mine_reserve_start], )?), diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index ab6b38e7..8781febd 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -67,6 +67,8 @@ pub(super) fn mission_prebuilds(config: &[u8]) -> Result<Vec<NormalizedPath>, En pub(super) struct Production { reserve_start: usize, schemes: Vec<NormalizedPath>, + player_scheme_count: usize, + transport_schemes: Vec<(OwnerId, NormalizedPath)>, controls: Vec<MissionControlDeviceTableState>, plants: Vec<(usize, u32)>, pending: VecDeque<Order>, @@ -142,6 +144,8 @@ impl Production { pub(super) fn new( reserve_start: usize, schemes: Vec<NormalizedPath>, + player_scheme_count: usize, + transport_schemes: Vec<(OwnerId, NormalizedPath)>, controls: Vec<MissionControlDeviceTableState>, drafts: &[MissionObjectDraft], ) -> Result<Self, EngineError> { @@ -182,6 +186,8 @@ impl Production { Ok(Self { reserve_start, schemes, + player_scheme_count, + transport_schemes, controls, plants, pending: VecDeque::new(), @@ -310,7 +316,9 @@ pub fn factory_schemes( ) -> Result<Vec<(usize, &str)>, EngineError> { let (mission, production) = loaded_production(engine)?; let (plant, _) = factory_at_communicator(&engine.world, mission, production, cockpit)?; - Ok(schemes_for_plant(mission, production, plant).collect()) + Ok(schemes_for_plant(mission, production, plant) + .filter(|&(scheme, _)| scheme < production.player_scheme_count) + .collect()) } /// Lists the live factories of the player's clan and matching configured schemes. @@ -323,6 +331,7 @@ pub fn clan_factory_schemes( Ok(owned_factories(&engine.world, mission, production, owner) .flat_map(|(index, factory, _)| { schemes_for_plant(mission, production, index) + .filter(|&(scheme, _)| scheme < production.player_scheme_count) .map(move |(scheme, path)| (factory, scheme, path)) }) .collect()) @@ -366,6 +375,13 @@ pub fn order_clan_factory_scheme( now_ms: u32, ) -> Result<u32, EngineError> { let owner = player_owner(&engine.world, cockpit)?; + if engine + .production + .as_ref() + .is_some_and(|production| scheme >= production.player_scheme_count) + { + return Err(production_error("unknown factory scheme")); + } order_owned_factory(engine, owner, plant, scheme, now_ms) } @@ -485,19 +501,33 @@ pub(super) fn order_script_factory( owner: OwnerId, plant: ObjectHandle, class: u32, + selection: u32, now_ms: u32, ) -> Result<u32, EngineError> { let (mission, production) = loaded_production(engine)?; let (index, _, _) = owned_factories(&engine.world, mission, production, owner) .find(|&(_, handle, _)| handle == plant) .ok_or_else(|| production_error("script factory is unavailable"))?; - // shortcut: use the mission's first compatible prebuild until AI design selection is linked. + let transport = class == crate::clan_transport_schemes::TRANSPORT_CLASS; + let transport_scheme = + if transport && selection == crate::clan_transport_schemes::SELECT_FASTEST { + production + .transport_schemes + .iter() + .find_map(|(clan, path)| (*clan == owner).then_some(path)) + } else { + None + }; + // shortcut: warbots use the first compatible prebuild until AI combat ranking is wired. let scheme = schemes_for_plant(mission, production, index) - .map(|(scheme, _)| scheme) - .find(|&scheme| { + .find(|&(scheme, path)| { + if transport { + return transport_scheme.is_some_and(|selected| selected.as_str() == path); + } let draft = &mission.object_drafts[production.reserve_start + scheme * RESERVE_SLOTS]; - draft.unit_dat_header_flags == Some(class) + scheme < production.player_scheme_count && draft.unit_dat_header_flags == Some(class) }) + .map(|(scheme, _)| scheme) .ok_or_else(|| production_error("script factory has no compatible prepared scheme"))?; order_owned_factory(engine, owner, plant, scheme, now_ms) } @@ -739,22 +769,47 @@ mod tests { assert!(report.script_factory_rejections.is_empty(), "{report:?}"); let cockpit = super::super::starting_cockpit(&engine).unwrap(); let factory = handle_by_original_id(&engine.world, OriginalObjectId(5)).unwrap(); + let production = engine.production.as_ref().unwrap(); + let [(owner, transport)] = production.transport_schemes.as_slice() else { + panic!("expected one eligible AI transport"); + }; + assert_eq!(*owner, OwnerId(1)); + assert!(transport.as_str().ends_with("/sml_cargo.dat")); + let transport_index = production + .schemes + .iter() + .position(|path| path == transport) + .unwrap(); + assert_eq!(clan_factory_schemes(&engine, cockpit).unwrap().len(), 2); + assert!( + order_clan_factory_scheme(&mut engine, cockpit, factory, transport_index, 40_000) + .is_err() + ); let duration = order_clan_factory_scheme(&mut engine, cockpit, factory, 0, 40_000).unwrap(); assert!(duration > 0); let production = engine.production.as_ref().unwrap(); assert_eq!(production.pending.len(), 2); assert_ne!(production.pending[0].slot, production.pending[1].slot); + let cargo_slots = production.reserve_start + transport_index * RESERVE_SLOTS; + assert!((cargo_slots..cargo_slots + RESERVE_SLOTS).contains(&production.pending[0].slot)); let mut completed = Vec::new(); for time in (40_016..=40_000 + duration + 2000).step_by(16) { if let Some(unit) = step_headless(&mut engine, InputSnapshot::default(), time) .unwrap() .produced_unit { - completed.push(unit.clan); + completed.push((unit.clan, unit.object_index)); } } - assert!(completed.contains(&0), "{completed:?}"); - assert!(completed.contains(&1), "{completed:?}"); + assert!( + completed.iter().any(|&(clan, _)| clan == 0), + "{completed:?}" + ); + assert!( + completed.iter().any(|&(clan, index)| clan == 1 + && (cargo_slots..cargo_slots + RESERVE_SLOTS).contains(&index)), + "{completed:?}" + ); } #[test] diff --git a/crates/fparkan-runtime/src/research.rs b/crates/fparkan-runtime/src/research.rs index c9f0084e..94f5d55a 100644 --- a/crates/fparkan-runtime/src/research.rs +++ b/crates/fparkan-runtime/src/research.rs @@ -1,6 +1,6 @@ use super::{ - mission_events::on_communicator, normalize_engine_path, read_vfs, ClanBody, Engine, - EngineError, LoadedMissionState, MissionObjectDraft, StartingCockpit, + mission_events::on_communicator, normalize_engine_path, ClanBody, Engine, EngineError, + LoadedMissionState, MissionObjectDraft, StartingCockpit, }; use fparkan_assets::ResearchTrfDocument; use fparkan_vfs::Vfs; @@ -235,8 +235,15 @@ pub(super) fn load_clan_table( mission: &LoadedMissionState, owner: OwnerId, ) -> Result<ResearchTrfDocument, EngineError> { + load_technology_table(vfs.as_ref(), &mission.mission, owner) +} + +pub(super) fn load_technology_table( + vfs: &dyn Vfs, + mission: &crate::MissionDocument, + owner: OwnerId, +) -> Result<ResearchTrfDocument, EngineError> { let clan = mission - .mission .clans .get(usize::from(owner.0)) .ok_or_else(|| research_error("clan is unavailable"))?; @@ -254,7 +261,11 @@ pub(super) fn load_clan_table( return Err(research_error("clan has no technology table")); } let path = normalize_engine_path("clan technology table", path)?; - ResearchTrfDocument::decode(read_vfs(vfs, &path)?).map_err(research_error) + let bytes = vfs.read(&path).map_err(|source| EngineError::Vfs { + path: path.as_str().into(), + source, + })?; + ResearchTrfDocument::decode(bytes).map_err(research_error) } fn research_error(error: impl std::fmt::Display) -> EngineError { |
