aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-01 17:52:41 +0300
committerValentin Popov <valentin@popov.link>2026-12-01 17:52:41 +0300
commitf7c5c3bffd565bb6b0995a220ecb7788471b7848 (patch)
tree09c33ae6a42b491035c3f0cf53bdefb604da72ff /crates/fparkan-assets/src
parent5f4850555ac2fd62009cffd5e98ea04c081bbaf7 (diff)
downloadfparkan-f7c5c3bffd565bb6b0995a220ecb7788471b7848.tar.xz
fparkan-f7c5c3bffd565bb6b0995a220ecb7788471b7848.zip
fix(control): select authored drive states for mobile power demand
Diffstat (limited to 'crates/fparkan-assets/src')
-rw-r--r--crates/fparkan-assets/src/control_drive.rs224
-rw-r--r--crates/fparkan-assets/src/lib.rs21
2 files changed, 235 insertions, 10 deletions
diff --git a/crates/fparkan-assets/src/control_drive.rs b/crates/fparkan-assets/src/control_drive.rs
new file mode 100644
index 00000000..3e2e32bc
--- /dev/null
+++ b/crates/fparkan-assets/src/control_drive.rs
@@ -0,0 +1,224 @@
+use std::sync::Arc;
+
+/// CTL drive multipliers and the authored transitions used to select them.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub enum PreparedControlDrive {
+ /// The state cannot affect demand when every record has this multiplier.
+ Uniform(u32),
+ /// States selected by linear and angular velocity and a transition graph.
+ Automatic(Arc<ControlDriveStates>),
+ /// The profile needs a selector beyond the velocity-based path.
+ #[default]
+ Unavailable,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct DriveState {
+ factor_bits: u32,
+ axes: u32,
+ automatic: bool,
+ minimum: [f32; 6],
+ maximum: [f32; 6],
+}
+
+impl DriveState {
+ fn matches(self, velocity: [f32; 6]) -> bool {
+ (0..6).all(|axis| {
+ let flag = if axis < 3 { 1 << axis } else { 2 << axis };
+ self.axes & flag == 0
+ || (self.minimum[axis]..=self.maximum[axis]).contains(&velocity[axis])
+ })
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct DriveRoute {
+ cost: f32,
+ next: usize,
+}
+
+const UNREACHABLE: f32 = 1_000_000.0;
+
+/// Velocity conditions and shortest transitions between the authored CTL states.
+#[derive(Debug, PartialEq)]
+pub struct ControlDriveStates {
+ states: Vec<DriveState>,
+ routes: Vec<DriveRoute>,
+}
+
+impl ControlDriveStates {
+ fn route(&self, current: usize, destination: usize) -> DriveRoute {
+ self.routes[destination * self.states.len() + current]
+ }
+
+ /// Chooses a new transition destination at a state that accepts automatic selection.
+ /// Other states finish their queued transition before they can choose again.
+ pub fn destination(&self, current: usize, velocity: [f32; 6]) -> Option<usize> {
+ let state = self.states.get(current)?;
+ if !state.automatic {
+ return None;
+ }
+ if state.matches(velocity) {
+ return Some(current);
+ }
+ let mut closest = UNREACHABLE;
+ let mut destination = current;
+ for (index, candidate) in self.states.iter().enumerate() {
+ if index != current && candidate.automatic && candidate.matches(velocity) {
+ let route = self.route(current, index);
+ if route.cost < closest {
+ closest = route.cost;
+ destination = index;
+ }
+ }
+ }
+ Some(destination)
+ }
+
+ /// Reads the first state in a reachable transition, which can be part of a gait loop.
+ pub fn next_state(&self, current: usize, destination: usize) -> Option<usize> {
+ self.states.get(current)?;
+ self.states.get(destination)?;
+ let route = self.route(current, destination);
+ (route.cost < UNREACHABLE).then_some(route.next)
+ }
+
+ /// Returns the drive multiplier from the selected state.
+ pub fn factor(&self, state: usize) -> Option<f32> {
+ Some(f32::from_bits(self.states.get(state)?.factor_bits))
+ }
+}
+
+pub(super) fn decode(
+ records: &[u8],
+ stride: usize,
+ transition_bytes: &[u8],
+) -> PreparedControlDrive {
+ let mut factors = records.chunks_exact(stride).map(|row| word(row, 0x54));
+ let Some(first) = factors.next() else {
+ return PreparedControlDrive::Unavailable;
+ };
+ if factors.all(|next| next == first) {
+ return PreparedControlDrive::Uniform(first);
+ }
+ let Some(states) = records
+ .chunks_exact(stride)
+ .map(decode_velocity_state)
+ .collect::<Option<Vec<_>>>()
+ else {
+ return PreparedControlDrive::Unavailable;
+ };
+ let edges: Vec<f32> = transition_bytes
+ .chunks_exact(4)
+ .map(|bytes| f32::from_bits(word(bytes, 0)))
+ .collect();
+ if edges.iter().any(|edge| !edge.is_finite() || *edge < 0.0) {
+ return PreparedControlDrive::Unavailable;
+ }
+ let routes = transition_routes(&edges, states.len());
+ PreparedControlDrive::Automatic(Arc::new(ControlDriveStates { states, routes }))
+}
+
+fn decode_velocity_state(row: &[u8]) -> Option<DriveState> {
+ // Timed eligibility, action selectors and node conditions use live Control inputs
+ // that the velocity controller does not publish.
+ if word(row, 0x94) != u32::MAX
+ || word(row, 0x98) != u32::MAX
+ || row[0x9c..]
+ .chunks_exact(16)
+ .any(|node| word(node, 4) & 0x300 != 0)
+ {
+ return None;
+ }
+ let limits = |linear, angular| {
+ std::array::from_fn(|axis| {
+ let offset = if axis < 3 {
+ linear + axis * 4
+ } else {
+ angular + (axis - 3) * 4
+ };
+ f32::from_bits(word(row, offset))
+ })
+ };
+ Some(DriveState {
+ factor_bits: word(row, 0x54),
+ axes: word(row, 0),
+ automatic: word(row, 4) & 1 != 0,
+ minimum: limits(0x24, 0x3c),
+ maximum: limits(0x30, 0x48),
+ })
+}
+
+fn transition_routes(edges: &[f32], count: usize) -> Vec<DriveRoute> {
+ let mut routes = Vec::with_capacity(edges.len());
+ for (destination, incoming) in edges.chunks_exact(count).enumerate() {
+ // Control.dll+0x19d0 starts with authored incoming edges, including the
+ // diagonal. There is no implicit zero-cost edge from a state to itself.
+ let mut paths: Vec<_> = incoming
+ .iter()
+ .map(|&cost| DriveRoute {
+ cost,
+ next: destination,
+ })
+ .collect();
+ let mut visited = vec![false; count];
+ loop {
+ let (Some(current), _) = paths.iter().enumerate().fold(
+ (None, UNREACHABLE),
+ |(best, cost), (index, path)| {
+ if !visited[index] && path.cost < cost {
+ (Some(index), path.cost)
+ } else {
+ (best, cost)
+ }
+ },
+ ) else {
+ break;
+ };
+ visited[current] = true;
+ let cost = paths[current].cost;
+ let incoming = &edges[current * count..][..count];
+ for (index, path) in paths
+ .iter_mut()
+ .enumerate()
+ .filter(|(index, _)| !visited[*index])
+ {
+ let through = cost + incoming[index];
+ if through < path.cost {
+ *path = DriveRoute {
+ cost: through,
+ next: current,
+ };
+ }
+ }
+ }
+ routes.extend(paths);
+ }
+ routes
+}
+
+fn word(bytes: &[u8], at: usize) -> u32 {
+ u32::from_le_bytes(bytes[at..at + 4].try_into().expect("complete CTL word"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn transition_cost_can_select_a_loop_instead_of_the_authored_diagonal() {
+ let inf = UNREACHABLE;
+ // Incoming edges by destination. State 1 is cheaper to repeat by
+ // visiting state 2 than by taking its authored diagonal edge.
+ let routes = transition_routes(&[1.0, 2.0, inf, inf, 5.0, 1.0, 1.0, 1.0, inf], 3);
+ let incoming_to_one = &routes[3..6];
+ assert_eq!(
+ incoming_to_one,
+ [
+ DriveRoute { cost: 2.0, next: 2 },
+ DriveRoute { cost: 2.0, next: 2 },
+ DriveRoute { cost: 1.0, next: 1 },
+ ]
+ );
+ }
+}
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs
index 4d2f7366..53f58568 100644
--- a/crates/fparkan-assets/src/lib.rs
+++ b/crates/fparkan-assets/src/lib.rs
@@ -32,6 +32,7 @@ pub use fparkan_texm::{PageRect, RgbaImage};
use fparkan_vfs::DirectoryVfs;
mod behavior_profile_values;
mod chassis_profile;
+mod control_drive;
mod control_weapon_sound;
mod explosion_profile;
mod turret_elevation;
@@ -39,6 +40,7 @@ pub use behavior_profile_values::{
decode_behavior_go_speed_percent, decode_behavior_work_rates, BehaviorWorkRates,
};
pub use chassis_profile::{decode_chassis_can_fly, decode_chassis_flags, ChassisFlags};
+pub use control_drive::{ControlDriveStates, PreparedControlDrive};
pub use explosion_profile::decode_explosion_effect;
pub use turret_elevation::{apply_manual_turret_elevation, turret_elevation_row};
mod research;
@@ -1040,8 +1042,8 @@ pub struct PreparedComponentControl {
pub source: ResourceKey,
/// The 27 raw native owner-profile words at CTLD bytes 20..128.
pub native_profile_words: [u32; 27],
- /// Drive demand multiplier when all authored CTL states agree.
- pub uniform_drive_factor_bits: Option<u32>,
+ /// Authored drive demand multipliers and their supported selection rules.
+ pub drive: PreparedControlDrive,
/// Number of nodes in the component model this control targets.
pub model_node_count: usize,
/// Enabled source rows in their original order, including duplicate nodes.
@@ -4383,19 +4385,18 @@ fn decode_component_control_payload_with_opcodes(
)?;
let initial_group_opcodes = decoded_effect.initial_group_opcodes;
- // Control copies CTL state +0x54 into the active owner field +0x154.
let state_start = HEADER_BYTES + FIXED_SECTION_BYTES;
- let mut factors = payload[state_start..state_start + section_bytes]
- .chunks_exact(section_stride)
- .map(|state| control_u32_at(state, 0x54).expect("complete CTL state"));
- let uniform_drive_factor_bits = factors
- .next()
- .filter(|&first| factors.all(|next| next == first));
+ let state_end = state_start + section_bytes;
+ let drive = control_drive::decode(
+ &payload[state_start..state_end],
+ section_stride,
+ &payload[state_end..row_start],
+ );
Ok((
PreparedComponentControl {
source,
native_profile_words,
- uniform_drive_factor_bits,
+ drive,
model_node_count,
bindings,
timeline_rows,