diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-26 11:36:35 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-26 11:36:35 +0300 |
| commit | f707bc6179521d316a93dde9beca2668115ad6cd (patch) | |
| tree | 125422ef403850a1d65527885d7755398413846c /crates/fparkan-runtime | |
| parent | dfbdef7d4d1d295ee962dd8aab754ce6be902f8d (diff) | |
| download | fparkan-f707bc6179521d316a93dde9beca2668115ad6cd.tar.xz fparkan-f707bc6179521d316a93dde9beca2668115ad6cd.zip | |
fix(factory): rank researched combat designs for clan orders
Use the clan technology table to qualify candidates for SELECT_STRONGEST, then compare their projected Control endurance and weapon banks. The stock Two Fortresses factory releases 12spd1.dat in about ten seconds. Checked the selector with the original DLL, the first release and reservation in licensed tests, and the new model in the game window.
Diffstat (limited to 'crates/fparkan-runtime')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_combat_strength.rs | 22 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_factory_schemes.rs | 124 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_minds.rs | 45 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 21 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/production.rs | 65 |
5 files changed, 218 insertions, 59 deletions
diff --git a/crates/fparkan-runtime/src/clan_combat_strength.rs b/crates/fparkan-runtime/src/clan_combat_strength.rs index 2ad01692..0dcbd7e2 100644 --- a/crates/fparkan-runtime/src/clan_combat_strength.rs +++ b/crates/fparkan-runtime/src/clan_combat_strength.rs @@ -1,6 +1,7 @@ use crate::{ - control_device_provider_value_from_status, MissionControlDeviceTableState, - MissionControlDeviceTableStatus, ObjectHandle, + control_device_provider_value_from_status, EffectiveControlDevice, + MissionControlDeviceTableState, MissionControlDeviceTableStatus, + MissionControlNodeProviderTableStatus, ObjectHandle, }; pub(super) fn unit_strength( @@ -14,6 +15,15 @@ pub(super) fn unit_strength( let MissionControlDeviceTableStatus::Available(devices) = &table.status else { return rating(capacity, 0.0); }; + // shortcut: assume full design ammunition and use the live Control amount + // until selector 0x36 scaling and live weapon counters are wired. + rating(capacity, weapon_power(devices, &table.node_provider_status)) +} + +pub(super) fn weapon_power( + devices: &[EffectiveControlDevice], + providers: &MissionControlNodeProviderTableStatus, +) -> f32 { let mut grouped = false; let mut weapon_power = 0.0; for device in devices { @@ -25,7 +35,7 @@ pub(super) fn unit_strength( else { continue; }; - if control_device_provider_value_from_status(&table.node_provider_status, device) + if control_device_provider_value_from_status(providers, device) .is_ok_and(|health| health == 0.0) { continue; @@ -39,12 +49,10 @@ pub(super) fn unit_strength( _ => {} } } - // shortcut: assume full design ammunition and use the live Control amount - // until selector 0x36 scaling and live weapon counters are wired. - rating(capacity, weapon_power) + weapon_power } -fn rating(capacity: f32, weapon_power: f32) -> f32 { +pub(super) fn rating(capacity: f32, weapon_power: f32) -> f32 { ((weapon_power + 0.8_f32) * capacity) * 0.00001_f32 } diff --git a/crates/fparkan-runtime/src/clan_factory_schemes.rs b/crates/fparkan-runtime/src/clan_factory_schemes.rs index e67b8088..8d6d9f47 100644 --- a/crates/fparkan-runtime/src/clan_factory_schemes.rs +++ b/crates/fparkan-runtime/src/clan_factory_schemes.rs @@ -1,15 +1,24 @@ -use crate::{MissionDocument, MissionScriptBundle}; -use fparkan_assets::{ResearchCandidate, ResearchCandidateSet}; +use crate::{ + boarding::WARBOT_CLASS, + clan_combat_strength::{rating, weapon_power}, + MissionDocument, MissionObjectDraft, MissionScriptBundle, +}; +use fparkan_assets::{AssetManager, ResearchCandidate, ResearchCandidateSet}; use fparkan_path::NormalizedPath; +use fparkan_prototype::build_prototype_graph_report; +use fparkan_resource::ResourceRepository; use fparkan_vfs::Vfs; use fparkan_world::OwnerId; +use std::collections::BTreeMap; pub(super) const TRANSPORT_CLASS: u32 = 0x0100_2000; pub(super) const SELECT_FASTEST: u32 = 4; +pub(super) const SELECT_STRONGEST: u32 = 5; pub(super) const AUXILIARY_CLASSES: [u32; 2] = [TRANSPORT_CLASS, crate::construction::BUILDER_CLASS]; -pub(super) fn available( +pub(super) fn available<R: ResourceRepository>( + assets: &AssetManager<R>, vfs: &dyn Vfs, mission: &MissionDocument, bundles: &[MissionScriptBundle], @@ -36,12 +45,12 @@ pub(super) fn available( .ok()? .header_opaque; let class = u32::from_le_bytes(header[4..].try_into().unwrap()); - AUXILIARY_CLASSES - .contains(&class) + (class == WARBOT_CLASS || AUXILIARY_CLASSES.contains(&class)) .then_some((class, ResearchCandidate { path, status: 0 })) }) .collect(); let mut selected = Vec::new(); + let mut ratings = BTreeMap::new(); for bundle in clans { let Ok(owner) = u16::try_from(bundle.clan_index).map(OwnerId) else { continue; @@ -49,7 +58,7 @@ pub(super) fn available( let Ok(research) = crate::research::load_technology_table(vfs, mission, owner) else { continue; }; - for class in AUXILIARY_CLASSES { + for class in AUXILIARY_CLASSES.into_iter().chain([WARBOT_CLASS]) { let mut catalog = ResearchCandidateSet { entries: entries .iter() @@ -62,15 +71,112 @@ pub(super) fn available( if catalog.refresh_selection(vfs, Some(&research)).is_err() { continue; } - // shortcut: select unique qualified designs until native ranking and RNG are wired. let mut available = catalog .entries .into_iter() .filter(|entry| entry.status != 0); - if let Some(entry) = available.next().filter(|_| available.next().is_none()) { - selected.push((owner, class, entry.path)); + let design = if class == WARBOT_CLASS { + let candidates = available.filter_map(|entry| { + let score = *ratings + .entry(entry.path.clone()) + .or_insert_with(|| combat_rating(assets, vfs, &entry.path)); + Some((entry.path, score?)) + }); + best_design(candidates) + } else { + // shortcut: select the sole qualified auxiliary until those ranks are wired. + available + .next() + .filter(|_| available.next().is_none()) + .map(|entry| entry.path) + }; + if let Some(path) = design { + selected.push((owner, class, path)); } } } selected } + +fn best_design(candidates: impl Iterator<Item = (NormalizedPath, f32)>) -> Option<NormalizedPath> { + // The original keeps the earliest candidate when scores tie. + candidates + .reduce(|best, next| if next.1 > best.1 { next } else { best }) + .map(|(path, _)| path) +} + +fn combat_rating<R: ResourceRepository>( + assets: &AssetManager<R>, + vfs: &dyn Vfs, + path: &NormalizedPath, +) -> Option<f32> { + let root = crate::resource_name(path.as_bytes()); + let (graph, prototypes, report) = + build_prototype_graph_report(assets.repository(), vfs, &[root]); + if !report.is_success() { + return None; + } + let span = graph.root_prototype_request_spans.first()?; + let flags = *graph.root_unit_dat_header_flags.first()?; + let mission_assets = assets + .prepare_mission_assets(&graph.root_prototype_request_spans, &prototypes) + .ok()?; + let draft = MissionObjectDraft { + original_id: None, + resource_name_raw: path.as_bytes().to_vec(), + raw_after_resource: u32::MAX, + identity_or_clan_raw: u32::MAX, + raw_after_name: 0, + unit_dat_header_flags: flags, + position: [0.0; 3], + orientation_raw: [0.0; 3], + scale: [1.0; 3], + visual_ids: mission_assets.visuals_for_object(0).to_vec(), + properties: Vec::new(), + unit_components: graph.root_unit_components.into_iter().next()?, + }; + let class = crate::native_control_class_for_root(flags, Some(span), &prototypes); + let projection = crate::build_control_device_projection_with_class( + 0, + &draft, + &mission_assets, + Some(span), + &prototypes, + class, + &mut |pair| { + crate::resolve_factory2_pair_from_assets(assets, vfs, pair) + .unwrap_or(crate::Factory2PairOutcome::Unrepresentable) + }, + ) + .ok()?; + let volume = f32::from_bits(crate::initial_node_provider_amount( + &projection.node_provider_status, + )?); + let resistance = projection + .projectile_resistance_bits + .map_or(1.0, |[factor, _]| f32::from_bits(factor)); + // shortcut: selector 0x36 adds a shield term and selector 0x204 reads native bank totals. + let score = rating( + volume / resistance, + weapon_power(&projection.devices, &projection.node_provider_status), + ); + score.is_finite().then_some(score) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strongest_design_keeps_the_first_tied_entry() { + let candidates = [("light.dat", 4.0), ("heavy.dat", 8.0), ("other.dat", 8.0)] + .into_iter() + .map(|(name, score)| { + ( + crate::normalize_engine_path("test design", name).unwrap(), + score, + ) + }); + assert_eq!(best_design(candidates).unwrap().as_str(), "heavy.dat"); + } +} diff --git a/crates/fparkan-runtime/src/clan_minds.rs b/crates/fparkan-runtime/src/clan_minds.rs index 0f14f0a4..1a216b7d 100644 --- a/crates/fparkan-runtime/src/clan_minds.rs +++ b/crates/fparkan-runtime/src/clan_minds.rs @@ -103,41 +103,30 @@ mod tests { .reserved_minds(&engine.world, owner), ) }; - assert_eq!(available(&engine, OwnerId(0)), 3); - assert_eq!(available(&engine, OwnerId(1)), 4); - frame(&mut engine, 0).unwrap(); - assert_eq!( + let reserved = |engine: &crate::Engine| { engine .production .as_ref() .unwrap() - .reserved_minds(&engine.world, OwnerId(1)), - 1 - ); + .reserved_minds(&engine.world, OwnerId(1)) + }; + assert_eq!(available(&engine, OwnerId(0)), 3); + assert_eq!(available(&engine, OwnerId(1)), 4); + frame(&mut engine, 0).unwrap(); + assert_eq!(reserved(&engine), 1); assert_eq!(available(&engine, OwnerId(1)), 3); - for now_ms in (100..=20_000).step_by(100) { - frame(&mut engine, now_ms).unwrap(); - } - assert_eq!( - engine - .production - .as_ref() - .unwrap() - .reserved_minds(&engine.world, OwnerId(1)), - 0 - ); + let first_release = (100..=22_000) + .step_by(100) + .find(|&now_ms| { + frame(&mut engine, now_ms).unwrap(); + reserved(&engine) == 0 + }) + .expect("the first build converted its reservation into a robot"); assert_eq!(available(&engine, OwnerId(1)), 3); - for now_ms in (20_100..=28_000).step_by(100) { + assert!(((first_release + 100)..=32_000).step_by(100).any(|now_ms| { frame(&mut engine, now_ms).unwrap(); - } - assert_eq!( - engine - .production - .as_ref() - .unwrap() - .reserved_minds(&engine.world, OwnerId(1)), - 1 - ); + reserved(&engine) == 1 + })); assert_eq!(available(&engine, OwnerId(1)), 2); let loaded = engine.loaded.as_ref().unwrap(); let plant = loaded diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index fb21af54..f7e73665 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -2025,9 +2025,19 @@ fn load_mission_with_options( } })?; let mut loaded_scripts = load_mission_scripts(&vfs, &mission, options.asset_scope)?; + let asset_manager = AssetManager::new(CachedResourceRepository::with_payload_cache_budget( + vfs.clone(), + MISSION_DECODED_PAYLOAD_CACHE_ENTRIES, + )); + let repository = asset_manager.repository(); let player_scheme_count = build_schemes.len(); let ai_schemes = if options.start_autodemo && request.mode == MissionMode::SingleMission { - clan_factory_schemes::available(vfs.as_ref(), &mission, &loaded_scripts.bundles) + clan_factory_schemes::available( + &asset_manager, + vfs.as_ref(), + &mission, + &loaded_scripts.bundles, + ) } else { Vec::new() }; @@ -2043,10 +2053,6 @@ fn load_mission_with_options( } else { Vec::new() }; - let repository = CachedResourceRepository::with_payload_cache_budget( - vfs.clone(), - MISSION_DECODED_PAYLOAD_CACHE_ENTRIES, - ); let mut graph_roots: Vec<_> = mission .objects .iter() @@ -2113,9 +2119,9 @@ fn load_mission_with_options( .unwrap_or_default(), }; let (mut prototype_graph, resolved_prototypes, mut prototype_report) = - build_prototype_graph_report(&repository, vfs.as_ref(), scoped_graph_roots); + build_prototype_graph_report(repository, vfs.as_ref(), scoped_graph_roots); extend_graph_report_with_visual_dependencies( - &repository, + repository, &mut prototype_report, &mut prototype_graph, &resolved_prototypes, @@ -2125,7 +2131,6 @@ fn load_mission_with_options( failures: prototype_report.failures.clone(), }); } - let asset_manager = AssetManager::new(repository); let mission_assets = match options.asset_scope { MissionAssetScope::Full => asset_manager.prepare_mission_assets( &prototype_graph.root_prototype_request_spans, diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index b8e33e00..1af9e6c7 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -595,7 +595,10 @@ pub(super) fn order_script_factory( .find(|&(_, handle, _)| handle == plant) .ok_or_else(|| production_error("script factory is unavailable"))?; let auxiliary = crate::clan_factory_schemes::AUXILIARY_CLASSES.contains(&class); - let ai_scheme = if auxiliary && selection == crate::clan_factory_schemes::SELECT_FASTEST { + let use_catalog = (auxiliary && selection == crate::clan_factory_schemes::SELECT_FASTEST) + || (class == crate::boarding::WARBOT_CLASS + && selection == crate::clan_factory_schemes::SELECT_STRONGEST); + let ai_scheme = if use_catalog { production .ai_schemes .iter() @@ -603,14 +606,22 @@ pub(super) fn order_script_factory( } else { None }; - // shortcut: warbots use the first compatible prebuild until AI combat ranking is wired. - let scheme = schemes_for_plant(mission, production, index) - .find(|&(scheme, path)| { + let scheme = ai_scheme + .and_then(|selected| { + schemes_for_plant(mission, production, index) + .find(|&(_, path)| selected.as_str() == path) + }) + .or_else(|| { if auxiliary { - return ai_scheme.is_some_and(|selected| selected.as_str() == path); + return None; } - let draft = &mission.object_drafts[production.reserve_start + scheme * RESERVE_SLOTS]; - scheme < production.player_scheme_count && draft.unit_dat_header_flags == Some(class) + // shortcut: retain the compatible reserve for unsupported catalog requests. + schemes_for_plant(mission, production, index).find(|&(scheme, _)| { + let draft = + &mission.object_drafts[production.reserve_start + scheme * RESERVE_SLOTS]; + 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"))?; @@ -802,6 +813,46 @@ mod tests { }; use fparkan_vfs::DirectoryVfs; use fparkan_world::{set_transform, InputSnapshot, OriginalObjectId}; + use std::sync::Arc; + + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_stock_factory_releases_the_ranked_combat_design() { + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus"); + let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).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 placed_count = engine.loaded.as_ref().unwrap().mission.objects.len(); + for tick in 0..=60 * 12 { + let now = tick * 1000 / 60; + let frame = crate::frame(&mut engine, now).unwrap(); + let first_build = frame.snapshot.transforms.iter().find_map(|(handle, _)| { + let identity = identity_metadata(&engine.world, *handle).ok()?; + let index = identity.original_id?.0 as usize; + (identity.owner_id == Some(OwnerId(1)) && index >= placed_count).then_some(index) + }); + if let Some(index) = first_build { + let draft = &engine.loaded.as_ref().unwrap().object_drafts[index]; + assert!(draft + .resource_name_raw + .eq_ignore_ascii_case(b"UNITS/UNITS/AI/12spd1.dat")); + assert!((10_000..=10_200).contains(&now), "release at {now} ms"); + return; + } + } + panic!("stock AI did not release a combat design in the opening"); + } #[test] fn mission_prebuilds_preserve_order_and_skip_duplicates() { |
