aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-25 14:20:46 +0300
committerValentin Popov <valentin@popov.link>2026-11-25 14:20:46 +0300
commit27d6ea19b0206b71ef6c309142e0875275882bf0 (patch)
tree2d99974f970ab652ec8fd799e26a0af4909b52bf
parent44320618ae750da0ab10e50439bf74405b9eacba (diff)
downloadfparkan-27d6ea19b0206b71ef6c309142e0875275882bf0.tar.xz
fparkan-27d6ea19b0206b71ef6c309142e0875275882bf0.zip
fix(ai): account for pending construction in class limits
Implement Handler(11) limits for the original class set, including hangar and laboratory counters. Keep owned-object caps separate from pending thresholds; medium and large towers allow three and one active builds. Record the ordered class on construction tasks and count queries by clan, class and result. Execute ai.dll RVA 0xc5e7 with the GOG hash guard and compare owned counts, maxima, pending counts and unknown classes. Preserve these native vectors in a Rust test. Extend the licensed construction test to require pending count before registration, owner isolation and reset after completion. Validate fmt, workspace check/tests, licensed construction, release build and stock mission 29 in simulation and its window. This removes the Handler(11) coverage blocker for the following construction work; generic building orders and Handler(40) are still open. Pending counter sources and lifecycle beyond active FParkan Construction tasks remain approximate.
-rw-r--r--apps/fparkan-game/src/script_coverage.rs3
-rw-r--r--crates/fparkan-runtime/src/clan_ai_events.rs52
-rw-r--r--crates/fparkan-runtime/src/clan_build_limits.rs60
-rw-r--r--crates/fparkan-runtime/src/construction.rs15
-rw-r--r--crates/fparkan-runtime/src/lib.rs6
-rw-r--r--docs/appendices/knowledge-boundaries.md3
-rw-r--r--docs/appendices/script-vm.md15
7 files changed, 123 insertions, 31 deletions
diff --git a/apps/fparkan-game/src/script_coverage.rs b/apps/fparkan-game/src/script_coverage.rs
index c7020e73..1f777186 100644
--- a/apps/fparkan-game/src/script_coverage.rs
+++ b/apps/fparkan-game/src/script_coverage.rs
@@ -21,6 +21,9 @@ pub(super) fn log_script_init(engine: &Engine, mission: &str) {
}
pub(super) fn log_clan_ai_stops(report: &SimulationReport) {
+ for &(clan, class, blocked, count) in &report.script_class_limit_queries {
+ eprintln!("sim_coverage script_class_limit_approx={count} clan={clan} class={class:#010x} blocked={blocked}");
+ }
for &(unit, order, count) in &report.script_unit_order_counts {
eprintln!("sim_coverage script_unit_queue_approx={count} unit={unit} order={order}");
}
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs
index bd87038e..67919fd3 100644
--- a/crates/fparkan-runtime/src/clan_ai_events.rs
+++ b/crates/fparkan-runtime/src/clan_ai_events.rs
@@ -258,6 +258,7 @@ pub(super) struct ClanAiEvents {
group_recruitments: BTreeMap<(usize, u32), u64>,
class_target_queries: BTreeMap<(usize, u32, u32), u64>,
size_class_queries: BTreeMap<(usize, u32), u64>,
+ class_limit_queries: BTreeMap<(usize, u32, bool), u64>,
}
impl LoadedMissionState {
@@ -633,29 +634,26 @@ impl LoadedMissionState {
ScriptDispatchSelector::Handler(11) => {
let class = single_dword(&instruction.references, values)
.ok_or("Handler(11) requires one DWORD class")?;
- if matches!(class, 0x8000_0040 | 0x8000_0400) {
- return Err(
- "Handler(11) requires the pending hangar or laboratory counter"
- .into(),
- );
- }
- let Some(limit_var) = class_limit_variable(class) else {
- return Ok(Some(VarSetDefault::Dword(0)));
- };
- let limit = varset
- .declarations
- .declarations
- .iter()
- .position(|entry| entry.name == limit_var)
- .and_then(|index| values.get(index)?.as_dword())
- .ok_or("Handler(11) class limit is unavailable")?;
+ let limit = crate::clan_build_limits::maximum_variable(class).map(|name| {
+ varset.declarations.declarations.iter()
+ .position(|entry| entry.name == name)
+ .and_then(|index| values.get(index)?.as_dword())
+ .ok_or("Handler(11) class limit is unavailable")
+ }).transpose()?;
let count = self.mission_events.count_clan_class(
world,
OwnerId(clan as u16),
class,
);
- // shortcut: include unfinished structures once construction registers with the roster.
- Ok(Some(VarSetDefault::Dword(u32::from(count >= limit))))
+ // shortcut: bind pending counters to active runtime construction until native task accounting is wired.
+ let pending = self.construction.pending_count(OwnerId(clan as u16), class);
+ let blocked = crate::clan_build_limits::at_limit(class, count, limit, pending);
+ let queries = self.clan_ai_events.class_limit_queries.entry((clan, class, blocked)).or_default();
+ *queries += 1;
+ if *queries == 1 {
+ eprintln!("sim_coverage script_class_limit_approx=1 clan={clan} class={class:#010x} blocked={blocked} owned={count} pending={pending}");
+ }
+ Ok(Some(VarSetDefault::Dword(u32::from(blocked))))
}
ScriptDispatchSelector::Handler(13) => {
let (mode, class) = instruction.dword_pair(values)
@@ -1271,18 +1269,6 @@ impl LoadedMissionState {
}
}
-fn class_limit_variable(class: u32) -> Option<&'static str> {
- match class {
- 0x0100_2000 => Some("dMaxTransport"),
- 0x0100_4000 => Some("dMaxBuilder"),
- crate::mining::MINE_CLASS => Some("dMaxMine"),
- STORAGE_CLASS => Some("dMaxStorage"),
- crate::autodemo::PLANT_CLASS => Some("dMaxPlant"),
- 0x8010_0000 | 0x8020_0000 => Some("dMaxTower"),
- _ => None,
- }
-}
-
fn ranked_problems(problems: &[Handler2Record]) -> Vec<Handler2Record> {
let mut pending: Vec<_> = problems
.iter()
@@ -1483,6 +1469,12 @@ impl ClanAiEvents {
.map(|(&(clan, class), &count)| (clan, class, count))
}
+ pub(super) fn class_limit_queries(&self) -> impl Iterator<Item = (usize, u32, bool, u64)> + '_ {
+ self.class_limit_queries
+ .iter()
+ .map(|(&(clan, class, blocked), &count)| (clan, class, blocked, count))
+ }
+
pub(super) fn construction_orders(
&self,
) -> impl Iterator<Item = (usize, u32, u32, u64, u64)> + '_ {
diff --git a/crates/fparkan-runtime/src/clan_build_limits.rs b/crates/fparkan-runtime/src/clan_build_limits.rs
new file mode 100644
index 00000000..b9599141
--- /dev/null
+++ b/crates/fparkan-runtime/src/clan_build_limits.rs
@@ -0,0 +1,60 @@
+pub(super) fn maximum_variable(class: u32) -> Option<&'static str> {
+ match class {
+ 0x0100_2000 => Some("dMaxTransport"),
+ 0x0100_4000 => Some("dMaxBuilder"),
+ 0x8000_0004 => Some("dMaxMine"),
+ 0x8000_0008 => Some("dMaxStorage"),
+ 0x8000_0010 => Some("dMaxPlant"),
+ 0x8010_0000 | 0x8020_0000 => Some("dMaxTower"),
+ _ => None,
+ }
+}
+
+pub(super) fn at_limit(class: u32, owned: u32, maximum: Option<u32>, pending: usize) -> bool {
+ let full = maximum.is_some_and(|maximum| owned >= maximum);
+ match class {
+ 0x0100_2000 | 0x0100_4000 => full,
+ 0x8000_0004 | 0x8000_0008 | 0x8000_0010 | 0x8020_0000 => full || pending >= 1,
+ 0x8010_0000 => full || pending >= 3,
+ 0x8000_0040 | 0x8000_0400 => pending >= 1,
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_class_limits_distinguish_owned_and_pending_buildings() {
+ for (class, owned, maximum, pending, expected) in [
+ (0x0100_4000, 0, 2, 9, false),
+ (0x0100_4000, 2, 2, 0, true),
+ (0x0100_2000, 1, 2, 9, false),
+ (0x0100_2000, 2, 2, 0, true),
+ (0x8000_0004, 0, 4, 0, false),
+ (0x8000_0004, 0, 4, 1, true),
+ (0x8000_0004, 2, 2, 0, true),
+ (0x8000_0008, 0, 4, 1, true),
+ (0x8000_0010, 0, 4, 1, true),
+ (0x8000_0040, 2, 0, 0, false),
+ (0x8000_0040, 0, 0, 1, true),
+ (0x8000_0400, 2, 0, 0, false),
+ (0x8000_0400, 0, 0, 1, true),
+ (0x8010_0000, 0, 9, 2, false),
+ (0x8010_0000, 0, 9, 3, true),
+ (0x8010_0000, 2, 2, 0, true),
+ (0x8020_0000, 0, 9, 0, false),
+ (0x8020_0000, 0, 9, 1, true),
+ (0x8000_0002, 2, 0, 9, false),
+ ] {
+ assert_eq!(
+ at_limit(class, owned, Some(maximum), pending),
+ expected,
+ "class={class:#x} owned={owned} max={maximum} pending={pending}"
+ );
+ }
+ assert_eq!(maximum_variable(0x8000_0040), None);
+ assert_eq!(maximum_variable(0x8000_0400), None);
+ }
+}
diff --git a/crates/fparkan-runtime/src/construction.rs b/crates/fparkan-runtime/src/construction.rs
index afeff2e5..f85d53d1 100644
--- a/crates/fparkan-runtime/src/construction.rs
+++ b/crates/fparkan-runtime/src/construction.rs
@@ -44,6 +44,7 @@ struct Task {
builder: ObjectHandle,
owner: OwnerId,
slot: usize,
+ class: u32,
position: [f32; 3],
cost: f32,
arrived_at: Option<u32>,
@@ -65,6 +66,13 @@ impl Construction {
self.tasks.iter().any(|task| task.builder == builder)
}
+ pub(super) fn pending_count(&self, owner: OwnerId, class: u32) -> usize {
+ self.tasks
+ .iter()
+ .filter(|task| task.owner == owner && task.class == class)
+ .count()
+ }
+
fn available_slot(
&self,
world: &World,
@@ -86,6 +94,7 @@ impl Construction {
builder: ObjectHandle,
owner: OwnerId,
slot: usize,
+ class: u32,
position: [f32; 3],
cost: f32,
) {
@@ -93,6 +102,7 @@ impl Construction {
builder,
owner,
slot,
+ class,
position,
cost,
arrived_at: None,
@@ -156,7 +166,7 @@ pub(super) fn order(
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);
+ construction.start(builder, owner, slot, class, position, cost);
Ok(())
}
@@ -390,6 +400,8 @@ mod tests {
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_eq!(mission.construction.pending_count(owner, class), 1);
+ assert_eq!(mission.construction.pending_count(OwnerId(0), class), 0);
assert!(handle_by_original_id(&engine.world, id).is_none());
let cost = mission.construction.tasks[0].cost;
assert_eq!(cost, 1100.0);
@@ -416,5 +428,6 @@ mod tests {
stock_before - cost
);
assert!(!mission.construction.active(builder));
+ assert_eq!(mission.construction.pending_count(owner, class), 0);
}
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 057ff7b8..0d43384f 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -46,6 +46,7 @@ mod boarding;
mod building_door;
mod clan_ai_events;
mod clan_area_strength;
+mod clan_build_limits;
mod clan_building_queries;
mod clan_combat_groups;
mod clan_combat_strength;
@@ -2935,6 +2936,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_class_limit_queries: Vec<(usize, u32, bool, 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)>,
@@ -2998,6 +3000,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_class_limit_queries: Vec::new(),
script_construction_orders: Vec::new(),
script_capturer_queries: Vec::new(),
script_capture_approaches: Vec::new(),
@@ -3142,6 +3145,9 @@ pub fn simulate_mission_report(
.script_building_site_queries
.extend(loaded.clan_ai_events.building_site_queries());
report
+ .script_class_limit_queries
+ .extend(loaded.clan_ai_events.class_limit_queries());
+ report
.script_construction_orders
.extend(loaded.clan_ai_events.construction_orders());
report
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 5ff31df3..1043ca6b 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -40,6 +40,9 @@ authoring API без динамического подтверждения.
`script_unit_queue_approx` считает принятые Go, Attack, ShutDown и добавленный Patrol по объекту
и типу приказа. Переход к следующей команде использует приближённое достижение
точки и удаление цели; нативное завершение задач и параметры профиля открыты.
+`script_class_limit_approx` считает запросы `Handler(11)` по клану, классу
+и ответу. Незавершённые постройки берутся из активных задач Construction;
+прочие источники нативных счётчиков и момент их обновления ещё открыты.
`mine_orders_approx` отмечает немедленное
развёртывание шахты по M на подготовленном месторождении. Подход
строителя, время и эффекты сборки, доля питания и динамический BAS
diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md
index defc74d0..37abdb78 100644
--- a/docs/appendices/script-vm.md
+++ b/docs/appendices/script-vm.md
@@ -2565,6 +2565,21 @@ FParkan вызывает числовой префикс этой секции Ñ
число шахт клана с текущим `dMaxMine`. Обработчик оригинала также
учитывает счётчики незавершённых построек.
+Та же команда ограничивает другие классы. Для шахты, склада и завода
+достаточно одной незавершённой стройки, чтобы вернуть 1 и снять повторную
+заявку. Для башен класса `0x80100000` порог равен трём, для `0x80200000` —
+одной. Дополнительно проверяется количество готовых объектов против
+текущего максимума из varset. Строители и транспорты проверяются только
+по этому максимуму.
+
+Ангар и лаборатория используют только порог одной незавершённой стройки:
+число готовых зданий здесь не задаёт общего потолка. Неизвестный класс
+возвращает 0. Прямой вызов GOG `ai.dll` по RVA `0xc5e7` подтвердил эти
+ветви, включая ангар и лабораторию при ненулевом числе готовых зданий.
+SHA-256 DLL: `c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`.
+FParkan связывает незавершённые постройки с активными задачами строительства
+своего клана; после регистрации здания такая задача перестаёт учитываться.
+
`Handler(56)` по RVA `0xe430` проверяет байт разрешения исследований
`AI+0x431`. Сценарий использует ответ при выборе действия для лаборатории.
Условный переход (control `3`, RVA `0x12258`) использует индекс инструкции