aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apps/fparkan-game/src/control_effects.rs44
-rw-r--r--apps/fparkan-game/src/main.rs47
-rw-r--r--crates/fparkan-assets/src/lib.rs74
-rw-r--r--crates/fparkan-runtime/src/control_profile.rs2
-rw-r--r--crates/fparkan-runtime/src/control_resources.rs6
-rw-r--r--crates/fparkan-runtime/src/lib.rs12
-rw-r--r--docs/appendices/knowledge-boundaries.md18
-rw-r--r--docs/tomes/06-behavior.md12
8 files changed, 193 insertions, 22 deletions
diff --git a/apps/fparkan-game/src/control_effects.rs b/apps/fparkan-game/src/control_effects.rs
index 910bba81..4cee2c16 100644
--- a/apps/fparkan-game/src/control_effects.rs
+++ b/apps/fparkan-game/src/control_effects.rs
@@ -5,7 +5,8 @@ use super::{
};
use fparkan_fx::clock::{FxInstanceClock, FxPhaseProvider};
use fparkan_runtime::{
- loaded_mission_control_device_tables, AutoDemoCombatEvent, Engine, FiringEffectInstance,
+ control_damage_alarm_active, loaded_mission_assets, loaded_mission_control_device_tables,
+ AutoDemoCombatEvent, Engine, FiringEffectInstance,
};
use std::collections::{HashMap, HashSet};
@@ -24,6 +25,29 @@ fn owner_control_capacity(
))
}
+fn owner_alarm_effect(
+ engine: &Engine,
+ roots: &[Option<MissionRenderRoot>],
+ effect: ControlEffectInstanceKey,
+) -> Option<bool> {
+ let control = loaded_mission_assets(engine)?
+ .object_component_controls
+ .get(effect.object_index)?
+ .get(effect.component_index)?
+ .as_ref()?;
+ if control.initial_effect_group != Some(effect.table_index)
+ || !control.alarm_effect_rows.contains(&effect.row_index)
+ {
+ return None;
+ }
+ Some(
+ roots
+ .get(effect.object_index)
+ .and_then(Option::as_ref)
+ .is_some_and(|root| control_damage_alarm_active(engine, root.handle)),
+ )
+}
+
impl From<FiringEffectInstance> for ControlEffectInstanceKey {
fn from(effect: FiringEffectInstance) -> Self {
Self {
@@ -73,6 +97,13 @@ impl StaticVulkanApp {
},
|index| self.motion_effects.provider(index),
|key| weapon_phases.get(&key).copied(),
+ |key| {
+ owner_alarm_effect(
+ self.mission_engine.as_ref()?,
+ &self.mission_render_roots,
+ key,
+ )
+ },
);
let mut direct_shot_sounds = activate_firing_flashes(
&mut samples,
@@ -160,6 +191,7 @@ pub(super) fn advance_control_effect_instances(
owner_capacity: impl Fn(usize) -> Option<(f32, f32)>,
owner_motion: impl Fn(usize) -> Option<FxPhaseProvider>,
owner_effect_phase: impl Fn(ControlEffectInstanceKey) -> Option<f32>,
+ owner_damage_alarm: impl Fn(ControlEffectInstanceKey) -> Option<bool>,
) -> HashMap<ControlEffectInstanceKey, ControlEffectFrameSample> {
let mut specifications = HashMap::new();
for slot in ambient_slots {
@@ -202,13 +234,17 @@ pub(super) fn advance_control_effect_instances(
let idle = FxPhaseProvider::idle();
let mut provider = idle;
let mut resolved = false;
+ let alarm = (mode == 14 && flags & 0x40 != 0)
+ .then(|| owner_damage_alarm(key)).flatten();
if mode == 14 {
let capacity = owner_capacity(key.object_index)
.and_then(|(remaining, capacity)| idle.with_control_capacity(remaining, capacity));
provider = capacity.unwrap_or(idle);
if state.clock.is_none() {
- eprintln!("render_coverage control_damage_fx_activation_approx=1 (instance={key:?})");
- if capacity.is_none() {
+ if alarm.is_none() {
+ eprintln!("render_coverage control_damage_fx_activation_approx=1 (instance={key:?})");
+ }
+ if capacity.is_none() && alarm != Some(false) {
eprintln!("render_coverage control_fx_owner_state_stub=1 (missing Control capacity; instance={key:?} mode={mode})");
}
}
@@ -232,7 +268,7 @@ pub(super) fn advance_control_effect_instances(
.expect("prepared FX clock metadata")
});
let now_ms = control_clock_ms as f32;
- let active = provider.control_effect_active(mode);
+ let active = alarm.unwrap_or_else(|| provider.control_effect_active(mode));
let phase = clock.update(now_ms).and_then(|()| {
clock.phase(now_ms, manager_flag, Some(&provider))
});
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 6f050780..8075ef2c 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -5706,6 +5706,7 @@ fn append_initial_control_effect_slots(
let group_index = row.table_index;
let archive = fixed_effect_field(&row.resource.archive);
let name = fixed_effect_field(&row.resource.name);
+ let alarm_controlled = control.alarm_effect_rows.contains(&row.row_index);
let windup = row.opcode == 3
&& control.typed_records.iter().any(|record| {
control
@@ -5723,8 +5724,7 @@ fn append_initial_control_effect_slots(
)
})?)
} else {
- // Chassis engine loops use the root. Weapon sounds use their authored node.
- if !windup && row.point_offsets[0] != 0 {
+ if !windup && !alarm_controlled && row.point_offsets[0] != 0 {
continue;
}
None
@@ -5754,7 +5754,8 @@ fn append_initial_control_effect_slots(
.get(&key)
.ok_or_else(|| format!("Control FX {key} was not cached"))?;
let header = document.header();
- if row.opcode == 3 && !windup && !matches!(header.time_mode, 5 | 15) {
+ let alarm_effect = alarm_controlled && header.time_mode == 14 && header.flags & 0x40 != 0;
+ if row.opcode == 3 && !windup && !alarm_effect && !matches!(header.time_mode, 5 | 15) {
continue;
}
let sound_commands = document
@@ -5850,7 +5851,7 @@ fn append_initial_control_effect_slots(
);
for (command_index, command) in document.commands().iter().enumerate() {
- if row.opcode == 3 && command.opcode != FxOpcode::Op2 {
+ if row.opcode == 3 && !alarm_effect && command.opcode != FxOpcode::Op2 {
continue;
}
if ambient_effect_op1_supported(command) || command.opcode == FxOpcode::Op2 {
@@ -5893,7 +5894,6 @@ fn append_initial_control_effect_slots(
}
continue;
}
- let Some(points) = points else { continue };
let Some(kind) = ambient_effect_command_kind(command) else {
record_skip("opcode_or_body", 1, false, Some(command_index));
continue;
@@ -6071,7 +6071,10 @@ fn append_initial_control_effect_slots(
control_table_index: row.table_index,
control_row_index: row.row_index,
control_point_indices: row.point_offsets,
- control_point_owners: points.map(|point| point.raw_signed_field_04),
+ control_point_owners: match points {
+ Some(points) => points.map(|point| point.raw_signed_field_04),
+ None => [owner_node_index as i32, -1, -1],
+ },
command: command.clone(),
command_index,
duration_seconds,
@@ -14437,6 +14440,7 @@ mod tests {
node_data: None,
effect_section: PreparedControlEffectSection::Absent,
initial_effect_group: None,
+ alarm_effect_rows: Vec::new(),
node_effect_links: Vec::new(),
effect_modes: Vec::new(),
point_list: None,
@@ -19272,6 +19276,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
assert!(update_control_point_lights(
&mut [inactive],
@@ -19294,6 +19299,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
let lights = update_control_point_lights(
std::slice::from_mut(&mut slot),
@@ -19341,6 +19347,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(first.len(), 1);
let key = slot.random_instance_key;
@@ -19370,6 +19377,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
)[&key],
first_sample,
"a repeated read of the same captured update reuses the shared sample"
@@ -19385,6 +19393,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
let expected = expected_state.advance(SceneSampleId::Replay(8), 500, 1.0);
assert_eq!(second[&key].phase_jitter, expected.phase_jitter);
@@ -19412,6 +19421,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(later[&key].phase, Some(1.0));
assert_eq!(later[&key].elapsed_seconds, 0.5);
@@ -19426,6 +19436,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(restarted[&key].phase, Some(0.0));
assert_eq!(restarted[&key].elapsed_seconds, 0.0);
@@ -19466,6 +19477,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(samples[&key].phase, Some(expected));
}
@@ -19484,6 +19496,7 @@ mod tests {
|_| None,
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(
samples[&key].phase,
@@ -19509,12 +19522,34 @@ mod tests {
|_| Some((remaining, 100.0)),
|_| None,
|_| None,
+ |_| None,
);
assert_eq!(samples[&key].phase, expected);
if expected.is_none() {
assert_eq!(samples[&key].phase_jitter, 0.0);
}
}
+
+ slot.header_flags = 0x49;
+ let mut alarm_states = HashMap::new();
+ for (frame, active, expected) in
+ [(15, false, None), (16, true, Some(0.25)), (17, false, None)]
+ {
+ let samples = advance_control_effect_instances(
+ &mut alarm_states,
+ &[],
+ std::slice::from_ref(&slot),
+ &[],
+ SceneSampleId::Replay(frame),
+ 5_000 + frame as u32 * 100,
+ false,
+ |_| Some((75.0, 100.0)),
+ |_| None,
+ |_| None,
+ |_| Some(active),
+ );
+ assert_eq!(samples[&key].phase, expected);
+ }
}
#[test]
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs
index d98bff3d..4738f175 100644
--- a/crates/fparkan-assets/src/lib.rs
+++ b/crates/fparkan-assets/src/lib.rs
@@ -45,7 +45,7 @@ pub use research::{
calc_full_research_cost, research_project_rows, ResearchCandidate, ResearchCandidateSet,
ResearchCompletion, ResearchCost, ResearchError, ResearchTrfDocument,
};
-use std::collections::{hash_map::Entry, HashMap};
+use std::collections::{hash_map::Entry, BTreeMap, HashMap};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
@@ -1055,6 +1055,8 @@ pub struct PreparedComponentControl {
/// Validated group selected by native Control's first effect-group
/// header word; `None` is the native no-group sentinel or an invalid index.
pub initial_effect_group: Option<usize>,
+ /// Rows in the initial group enabled by the alarm and disabled on recovery.
+ pub alarm_effect_rows: Vec<usize>,
/// Node-to-effect links from Control opcode 14, resolved within each group.
pub node_effect_links: Vec<(usize, u32, u32)>,
/// Changes to the clocks of existing effect instances, from opcode 10.
@@ -3903,6 +3905,7 @@ const CONTROL_EFFECT_ROW_BYTES: usize = 100;
struct DecodedComponentEffectSection {
section: PreparedControlEffectSection,
initial_effect_group: Option<usize>,
+ alarm_effect_rows: Vec<usize>,
initial_group_opcodes: Option<Vec<u32>>,
typed_records: Vec<PreparedControlTypedRecord>,
node_effect_links: Vec<(usize, u32, u32)>,
@@ -3930,6 +3933,7 @@ where
}
},
initial_effect_group: None,
+ alarm_effect_rows: Vec::new(),
initial_group_opcodes: (cursor == payload.len()).then(Vec::new),
typed_records: Vec::new(),
node_effect_links: Vec::new(),
@@ -3954,6 +3958,7 @@ where
typed_record_tag: Some(tag),
},
initial_effect_group: None,
+ alarm_effect_rows: Vec::new(),
initial_group_opcodes: None,
typed_records,
node_effect_links: Vec::new(),
@@ -4057,6 +4062,7 @@ where
}
},
initial_effect_group: None,
+ alarm_effect_rows: Vec::new(),
initial_group_opcodes: complete.then(Vec::new),
typed_records,
node_effect_links: Vec::new(),
@@ -4076,6 +4082,11 @@ where
)
.ok()
.filter(|group| *group < effect_group_count);
+ // The native group table copies these two references to owner +0x4f4/+0x4f8.
+ let alarm_groups = [0x18, 0x1c].map(|offset| {
+ control_u32_at(payload, cursor + offset).expect("validated effect group header") as usize
+ });
+ let mut alarm_switches = [BTreeMap::new(), BTreeMap::new()];
cursor = group_header_end;
let mut initial_group_opcodes = Some(Vec::new());
@@ -4119,6 +4130,16 @@ where
.expect("valid initial group has an opcode list")
.push(opcode);
}
+ if matches!(opcode, 0x12 | 0x13)
+ && control_u32_at(row, 0).expect("fixed effect condition") & 0xf000_0000 == 0
+ {
+ let selector = control_u32_at(row, 0x10).expect("fixed effect selector");
+ for (&group, switches) in alarm_groups.iter().zip(&mut alarm_switches) {
+ if group == table_index {
+ switches.insert(selector, opcode == 0x12);
+ }
+ }
+ }
if !matches!(opcode, 3 | 4 | 10) {
continue;
}
@@ -4168,15 +4189,26 @@ where
typed_record_tag: None,
},
initial_effect_group: None,
+ alarm_effect_rows: Vec::new(),
initial_group_opcodes: None,
typed_records,
node_effect_links: Vec::new(),
effect_modes: Vec::new(),
});
}
+ let alarm_effect_rows = effect_rows
+ .iter()
+ .filter(|row| {
+ Some(row.table_index) == initial_effect_group
+ && alarm_switches[0].get(&row.selector) == Some(&true)
+ && alarm_switches[1].get(&row.selector) == Some(&false)
+ })
+ .map(|row| row.row_index)
+ .collect();
Ok(DecodedComponentEffectSection {
section: PreparedControlEffectSection::Parsed(effect_rows),
initial_effect_group,
+ alarm_effect_rows,
initial_group_opcodes,
typed_records,
node_effect_links,
@@ -4360,6 +4392,7 @@ fn decode_component_control_payload_with_opcodes(
node_data: None,
effect_section: decoded_effect.section,
initial_effect_group: decoded_effect.initial_effect_group,
+ alarm_effect_rows: decoded_effect.alarm_effect_rows,
node_effect_links: decoded_effect.node_effect_links,
effect_modes: decoded_effect.effect_modes,
point_list: None,
@@ -6971,6 +7004,45 @@ mod tests {
}
#[test]
+ fn component_control_pairs_alarm_switches_by_selector() {
+ let source = ResourceKey {
+ archive: parse_path("bases.rlb").unwrap(),
+ name: resource_name(b"warbot.ctl"),
+ type_id: None,
+ };
+ let mut payload = component_control_payload(&[]);
+ payload[16..20].copy_from_slice(&3_u32.to_le_bytes());
+ let header = payload.len();
+ payload.resize(header + CONTROL_EFFECT_GROUP_HEADER_BYTES, 0);
+ payload[header + 0x18..header + 0x1c].copy_from_slice(&1_u32.to_le_bytes());
+ payload[header + 0x1c..header + 0x20].copy_from_slice(&2_u32.to_le_bytes());
+ append_effect_table(
+ &mut payload,
+ &[1, 2, 3].map(|selector| {
+ effect_row(3, [0; 3], [0; 3], selector, "effects.rlb", "smoke_fr_01")
+ }),
+ );
+ let switch = |opcode, selector, condition| {
+ effect_row(opcode, [condition, 0, 0], [selector, 0, 0], 0, "", "")
+ };
+ append_effect_table(
+ &mut payload,
+ &[
+ switch(0x12, 1, 0),
+ switch(0x12, 2, 0),
+ switch(0x13, 2, 0),
+ switch(0x12, 3, 0x8000_0000),
+ ],
+ );
+ append_effect_table(
+ &mut payload,
+ &[1, 2, 3].map(|selector| switch(0x13, selector, 0)),
+ );
+ let control = decode_component_control_payload(&payload, source, 1, 0).unwrap();
+ assert_eq!(control.alarm_effect_rows, [0]);
+ }
+
+ #[test]
fn initial_control_effect_opcodes_keep_raw_selected_rows_in_order() {
let source = ResourceKey {
archive: parse_path("controls.rlb").expect("archive"),
diff --git a/crates/fparkan-runtime/src/control_profile.rs b/crates/fparkan-runtime/src/control_profile.rs
index 236d523b..21c54607 100644
--- a/crates/fparkan-runtime/src/control_profile.rs
+++ b/crates/fparkan-runtime/src/control_profile.rs
@@ -63,7 +63,7 @@ pub(super) fn project_initial(
#[derive(Default)]
pub(super) struct DamageAlarm {
threshold: Option<f32>,
- active: bool,
+ pub(super) active: bool,
}
#[derive(Default)]
diff --git a/crates/fparkan-runtime/src/control_resources.rs b/crates/fparkan-runtime/src/control_resources.rs
index b9958229..e34a3dfc 100644
--- a/crates/fparkan-runtime/src/control_resources.rs
+++ b/crates/fparkan-runtime/src/control_resources.rs
@@ -34,6 +34,12 @@ impl Default for Resources {
}
impl Resources {
+ pub(super) fn alarm_active(&self, handle: ObjectHandle) -> bool {
+ self.clocks
+ .iter()
+ .any(|(owner, clock)| *owner == handle && clock.alarm.active)
+ }
+
pub(super) fn energy_available(&self, handle: ObjectHandle) -> bool {
!self.blocked_budgets.contains(&handle)
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 3b097acd..e6fe77af 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -3875,6 +3875,16 @@ pub fn loaded_mission_control_device_tables(
.map(|state| state.control_device_tables.as_slice())
}
+/// Whether Control has switched this live object into its damage alarm.
+#[must_use]
+pub fn control_damage_alarm_active(engine: &Engine, handle: ObjectHandle) -> bool {
+ transform_state(&engine.world, handle).is_ok()
+ && engine
+ .loaded
+ .as_ref()
+ .is_some_and(|mission| mission.control_resources.alarm_active(handle))
+}
+
/// Returns the initial prepared Control grouping for full-load mission objects.
#[must_use]
pub fn loaded_mission_behavior_control_groupings(
@@ -8606,6 +8616,7 @@ mod tests {
node_data: None,
effect_section: PreparedControlEffectSection::Parsed(rows),
initial_effect_group,
+ alarm_effect_rows: Vec::new(),
node_effect_links: Vec::new(),
effect_modes: Vec::new(),
point_list: point_count.map(|count| PreparedControlPointList {
@@ -9112,6 +9123,7 @@ mod tests {
node_data: None,
effect_section,
initial_effect_group: None,
+ alarm_effect_rows: Vec::new(),
node_effect_links: Vec::new(),
effect_modes: Vec::new(),
point_list: None,
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 90464c8c..78192231 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -423,13 +423,14 @@ preview создаёт их в момент ноль; планирование Ð
Manager A8 получает дневной бит по яркости небесного источника. Порядок сообщений
при одновременных солнце и луне неизвестен: сохраняется прежний бит с
`control_fx_manager_order_unsupported`; в расписаниях 29 миссий пересечения нет.
-Режим 14 читает оставшуюся долю общей прочности узлов. Включение по первому
-повреждению считается в `control_damage_fx_activation_approx`; нативные переходы
-ещё не сверены. Режимы 5 и 15 берут скорости по двум соседним позам.
+Режим 14 читает оставшуюся долю общей прочности узлов. Парные переключатели
+аварии проверены для варботов. Для остальных эффектов включение по первому
+повреждению считается в `control_damage_fx_activation_approx`. Режимы 5 и 15
+берут скорости по двум соседним позам.
Остальные режимы без известного состояния владельца используют покой
(`control_fx_owner_state_stub`).
-CTL-строки типа 3 подключают корневой звук двигателя. Другие смещения
-узлов и визуальные команды этих строк ещё открыты.
+CTL-строки типа 3 подключают корневой звук двигателя, а также дым и свет
+аварии на узле. Прочие визуальные команды строк типа 3 ещё открыты.
Op9 modes 0/2 поддерживают generated mesh; mode 0 поворачивается к камере. Игровой запуск `B_Sphere_Start` и native выбор detail category остаются открыты; остальные modes учитываются в `control_fx_unsupported`.
При расширении выбранных начальных строк все пропущенные команды считаются
в `control_fx_unsupported`, а условные строки состояния — в `control_fx_requires_game_state`;
@@ -1349,9 +1350,10 @@ Unit DAT loader-а или gameplay. Rust helper поддерживает толÑ
Полный динамический жизненный цикл после начальной загрузки не подтверждён:
activation, placement и полный Control tick не сведены в одну проверенную трассу.
Dirty-ветвь `0x12a40` обновляет means и FCA0, включая аварийную потерю прочности.
-Эффекты при входе и выходе из аварии и каскад стадий узлов остаются в
-`control_damage_fx_activation_approx`. Аварийное истощение использует общее
-удаление корпуса. Изменения scalar и расход ходовой ещё открыты.
+Парные безусловные команды CTL управляют дымом и светом варботов при аварии.
+Для остальных эффектов режима 14 остаётся `control_damage_fx_activation_approx`.
+Каскад стадий узлов открыт. Аварийное истощение использует общее удаление
+корпуса. Изменения scalar и расход ходовой ещё открыты.
Отдельные constructor, setter и loader-пути уже прослежены; физические единицы
слов профиля и накопителей остаются неизвестны. Для закрытия границы нужны
динамическая трассировка и сравнение полного Unit DAT load с оригинальным
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 1371f6e7..0282a2b2 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -1682,9 +1682,17 @@ Rust хранит исходные слова отдельно, считает Ð
Запас 80 за 0,25 секунды снижается до 78, а за следующие 0,5 секунды до 74.
Предел хода с двумя исчерпанными группами равен нулю. Восстановление обеих
групп до 30% прекращает потерю прочности и возвращает ход. Бортовой ремонт
-остаётся выключенным. Сигнал аварии и полная цепочка разрушения узлов
-остаются приближёнными. Динамический расход ходовой пока открыт. Заряд
+остаётся выключенным. Полная цепочка разрушения узлов остаётся приближённой.
+Динамический расход ходовой пока открыт. Заряд
орудий и их пополнение уже участвуют в общем бюджете владельца.
+
+У варботов AutoDemo первая группа CTL создаёт `smoke_fr_01` на узле корпуса.
+Заголовок FXID с флагом `0x40` оставляет его выключенным. Ссылки CTL по
+смещениям `0x18` и `0x1c` в заголовке групп выбирают команды при начале и
+окончании аварии. Команды `0x12` и `0x13` включают и выключают тот же экземпляр
+по селектору. Вызов `Control.dll` RVA `0x2800` и `Effect.dll` RVA `0x4bd0` и
+`0x4c10` подтвердил переключение выбранного экземпляра. Штатный дым и свет
+включаются при аварии. Их фаза по-прежнему определяется долей прочности.
Отчёт считает ресурсные проверки, обновления и отказы по объектам и
сохраняет эти числа после уничтожения робота.