aboutsummaryrefslogtreecommitdiff
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
parent5f4850555ac2fd62009cffd5e98ea04c081bbaf7 (diff)
downloadfparkan-f7c5c3bffd565bb6b0995a220ecb7788471b7848.tar.xz
fparkan-f7c5c3bffd565bb6b0995a220ecb7788471b7848.zip
fix(control): select authored drive states for mobile power demand
-rw-r--r--apps/fparkan-game/src/main.rs2
-rw-r--r--crates/fparkan-assets/src/control_drive.rs224
-rw-r--r--crates/fparkan-assets/src/lib.rs21
-rw-r--r--crates/fparkan-runtime/src/control_resources.rs33
-rw-r--r--crates/fparkan-runtime/src/lib.rs4
-rw-r--r--crates/fparkan-runtime/src/mobile_budget.rs128
-rw-r--r--docs/appendices/knowledge-boundaries.md7
-rw-r--r--docs/appendices/script-vm.md16
-rw-r--r--docs/tomes/06-behavior.md15
9 files changed, 411 insertions, 39 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index fed48e88..787ba07c 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -14269,7 +14269,7 @@ mod tests {
type_id: None,
},
native_profile_words: [0; 27],
- uniform_drive_factor_bits: None,
+ drive: Default::default(),
model_node_count: 2,
bindings: vec![],
timeline_rows: vec![PreparedControlTimelineRow {
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,
diff --git a/crates/fparkan-runtime/src/control_resources.rs b/crates/fparkan-runtime/src/control_resources.rs
index 0b1f853b..095ac3ab 100644
--- a/crates/fparkan-runtime/src/control_resources.rs
+++ b/crates/fparkan-runtime/src/control_resources.rs
@@ -1,5 +1,6 @@
use crate::{
- control_profile, control_resource_budget_pass_with_motion, mobile_budget::DriveMotion,
+ control_profile, control_resource_budget_pass_with_motion,
+ mobile_budget::{DriveMotion, DriveStateSelection},
repair_zone, ControlProfileReport, Engine, MissionControlDeviceTableStatus, MobileBudgetReport,
};
use fparkan_world::{transform_state, ObjectHandle, TransformState};
@@ -111,6 +112,22 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) {
};
let frame_seconds = (now_ms as f32 - clock.frame_ms) * 0.001;
let previous_pose = clock.previous_pose.replace(pose);
+ let motion = previous_pose
+ .filter(|_| mobile_owner && frame_seconds > 0.0)
+ .and_then(|previous| {
+ let can_fly = table
+ .original_id
+ .and_then(|id| mission.unit_chassis_flags.get(&id.0))
+ .and_then(|flags| flags.can_fly)?;
+ DriveMotion::sample(
+ table,
+ &mission.mission_assets,
+ [previous, pose],
+ frame_seconds,
+ can_fly,
+ &mut clock.drive_state,
+ )
+ });
// Control.dll+0x42480: default resource period; this is a separate RNG from Behavior.
let Some(seconds) = clock.step(now_ms as f32, true, 250.0, &mut state.rng) else {
continue;
@@ -162,19 +179,6 @@ pub(super) fn tick(engine: &mut Engine, now_ms: u32) {
}
}
}
- let motion = previous_pose.filter(|_| mobile_owner).and_then(|previous| {
- let can_fly = table
- .original_id
- .and_then(|id| mission.unit_chassis_flags.get(&id.0))
- .and_then(|flags| flags.can_fly)?;
- DriveMotion::sample(
- table,
- &mission.mission_assets,
- [previous, pose],
- frame_seconds,
- can_fly,
- )
- });
match control_resource_budget_pass_with_motion(table, seconds, motion) {
Ok(()) => {
state
@@ -240,6 +244,7 @@ struct ResourceClock {
resource_ms: f32,
forced: u32,
alarm: control_profile::DamageAlarm,
+ drive_state: DriveStateSelection,
}
impl ResourceClock {
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 3374e599..e6c53a20 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -8433,7 +8433,7 @@ mod tests {
PreparedComponentControl {
source: synthetic_resource_key(940),
native_profile_words: [0; 27],
- uniform_drive_factor_bits: None,
+ drive: Default::default(),
model_node_count: 3,
bindings: Vec::new(),
timeline_rows: Vec::new(),
@@ -8941,7 +8941,7 @@ mod tests {
PreparedComponentControl {
source: synthetic_resource_key(100 + index),
native_profile_words: [0; 27],
- uniform_drive_factor_bits: None,
+ drive: Default::default(),
model_node_count: 0,
bindings: Vec::new(),
timeline_rows: Vec::new(),
diff --git a/crates/fparkan-runtime/src/mobile_budget.rs b/crates/fparkan-runtime/src/mobile_budget.rs
index 1df2ab80..32e81eae 100644
--- a/crates/fparkan-runtime/src/mobile_budget.rs
+++ b/crates/fparkan-runtime/src/mobile_budget.rs
@@ -7,6 +7,7 @@ use crate::{
ControlResourceAccessError, EffectiveControlDevice, MissionAssets,
MissionControlDeviceTableState, MissionControlDeviceTableStatus, TransformState,
};
+use fparkan_assets::{ControlDriveStates, PreparedControlDrive};
use std::collections::BTreeMap;
#[derive(Clone, Debug)]
@@ -172,6 +173,30 @@ pub(super) fn unmodeled_motion_rate() -> f32 {
0.0
}
+#[derive(Default)]
+pub(super) struct DriveStateSelection {
+ current: usize,
+ destination: Option<usize>,
+}
+
+impl DriveStateSelection {
+ fn advance(&mut self, states: &ControlDriveStates, velocity: [f32; 6]) -> Option<f32> {
+ if let Some(destination) = states.destination(self.current, velocity) {
+ self.destination = Some(destination);
+ }
+ if let Some(destination) = self.destination {
+ let next = states.next_state(self.current, destination);
+ self.destination = next
+ .filter(|&next| next != destination)
+ .map(|_| destination);
+ if let Some(next) = next {
+ self.current = next;
+ }
+ }
+ states.factor(self.current)
+ }
+}
+
#[derive(Clone, Copy)]
pub(super) struct DriveMotion {
local_speed: f32,
@@ -186,6 +211,7 @@ impl DriveMotion {
[previous, current]: [TransformState; 2],
frame_seconds: f32,
can_fly: bool,
+ selection: &mut DriveStateSelection,
) -> Option<Self> {
let object = table.original_id?.0 as usize;
let profile = table.owner_profile.as_ref()?;
@@ -194,7 +220,6 @@ impl DriveMotion {
.get(object)?
.get(profile.unit_component_index)?
.as_ref()?;
- let state_factor = f32::from_bits(control.uniform_drive_factor_bits?);
let limits = profile.original_words[6..9]
.iter()
.map(|&word| f32::from_bits(word));
@@ -204,11 +229,26 @@ impl DriveMotion {
});
let (sin, cos) = f32::from_bits(current.orientation[2]).sin_cos();
// shortcut: use the frame's realized displacement until native motion publishes its local vector.
- let local_speed = largest_component([
+ let local_velocity = [
(cos * dx + sin * dy) / frame_seconds,
(-sin * dx + cos * dy) / frame_seconds,
if can_fly { dz / frame_seconds } else { 0.0 },
- ])?;
+ ];
+ let local_speed = largest_component(local_velocity)?;
+ let state_factor = match &control.drive {
+ PreparedControlDrive::Uniform(bits) => f32::from_bits(*bits),
+ PreparedControlDrive::Automatic(states) => {
+ let [x, y, z] = local_velocity;
+ let [roll, pitch, yaw] = std::array::from_fn(|axis| {
+ let delta = f32::from_bits(current.orientation[axis])
+ - f32::from_bits(previous.orientation[axis]);
+ use std::f32::consts::{PI, TAU};
+ ((delta + PI).rem_euclid(TAU) - PI) / frame_seconds
+ });
+ selection.advance(states, [x, y, z, roll, pitch, yaw])?
+ }
+ PreparedControlDrive::Unavailable => return None,
+ };
(profile_limit > 0.0 && state_factor.is_finite() && !state_factor.is_subnormal()).then_some(
Self {
local_speed,
@@ -441,6 +481,88 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_spider_drive_uses_the_authored_gait_and_resource_budget() {
+ use crate::{
+ create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
+ MissionStartupInput,
+ };
+ use fparkan_vfs::DirectoryVfs;
+ use fparkan_world::OriginalObjectId;
+ use std::sync::Arc;
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
+ 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 mission = engine.loaded.as_ref().unwrap();
+ let control = mission.mission_assets.object_component_controls[58][0]
+ .as_ref()
+ .expect("stock 12spd1 chassis CTL");
+ let PreparedControlDrive::Automatic(states) = &control.drive else {
+ panic!("stock spider selects its drive state using velocity");
+ };
+ let mut selection = DriveStateSelection::default();
+ // Consecutive 0x51c0 calls on the GOG profile, applying the first
+ // queued state after each call as in 0xc317–0xc37a.
+ for (forward, yaw, expected) in [
+ (0.0, 0.0, &[0, 0][..]),
+ (0.5, 0.0, &[0, 0]),
+ (6.0, 0.0, &[15, 16, 15, 16, 15]),
+ (6.0, 0.25, &[16, 15, 16, 15, 16]),
+ (13.0, 0.0, &[19, 20, 21, 22, 19]),
+ (0.0, 0.0, &[20, 21, 22, 0, 0, 0]),
+ (-6.0, 0.0, &[17, 18, 17, 18, 17]),
+ (0.0, 0.0, &[18, 0, 0, 0, 0, 0]),
+ (0.0, 0.25, &[8, 9, 10, 11, 12]),
+ (0.0, 0.0, &[13, 14, 0, 0, 0, 0]),
+ ] {
+ let velocity = [0.0, forward, 0.0, 0.0, 0.0, yaw];
+ for &state in expected {
+ let factor = selection.advance(states, velocity).unwrap();
+ assert_eq!(selection.current, state, "{velocity:?}");
+ assert_eq!(factor, if state == 0 { 0.0 } else { 1.0 });
+ }
+ }
+
+ let mut first_position = None;
+ let mut moving_budget = false;
+ for now in (0..=40_000).step_by(100) {
+ frame(&mut engine, now).unwrap();
+ let mission = engine.loaded.as_ref().unwrap();
+ if let Some(table) = mission.control_device_tables.iter().find(|table| {
+ table.original_id == Some(OriginalObjectId(58))
+ && fparkan_world::transform_state(&engine.world, table.handle).is_ok()
+ }) {
+ let position = fparkan_world::transform_state(&engine.world, table.handle)
+ .unwrap()
+ .position;
+ let initial = first_position.get_or_insert(position);
+ let horizontal_move = position[..2] != initial[..2];
+ moving_budget |=
+ horizontal_move && f32::from_bits(table.current_output_rate_5e0_bits) > 0.0;
+ }
+ }
+ let report = &engine.loaded.as_ref().unwrap().control_resources.mobile;
+ assert!(!report.stubs.contains_key(&(58, "motion_factory_5".into())));
+ assert!(
+ moving_budget,
+ "the first released spider must spend power while walking"
+ );
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_autodemo_flyer_uses_its_drive_budget_in_motion() {
use crate::{
create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index f4d5b30a..d176c34e 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -267,9 +267,10 @@ seed и общий порядок Control RNG открыты. `control_resource_
неподдержанные шаги по объектам и сохраняет первую причину отказа.
`control_mobile_budget_approx` считает мобильные бюджетные шаги. `control_mobile_budget_stub`
считает нулевую подмену расхода при недоступном состоянии ходовой, открытый
-режим оружия и отказы бюджета/связи орудия. Для одинакового коэффициента CTL
-расход уже учитывается, локальная скорость берётся из перемещения за кадр;
-при отказе бюджета ограничение стрельбы зарядом отключается до успешного шага.
+режим оружия и отказы бюджета/связи орудия. Поддержаны единый коэффициент CTL
+и граф состояний с условиями по скоростям кадра. Условия по таймеру, команде
+и узлам пока открыты. При отказе бюджета ограничение стрельбы зарядом
+отключается до успешного шага.
`mission_patrol_approx` отмечает приказы варботам патрулировать точку из
`Mission`. Маршрут и бой используют текущую модель AutoDemo. Темп, профиль,
diff --git a/docs/appendices/script-vm.md b/docs/appendices/script-vm.md
index 733ae173..80e6334d 100644
--- a/docs/appendices/script-vm.md
+++ b/docs/appendices/script-vm.md
@@ -1272,8 +1272,20 @@ charge и M. При неположительной ёмкости update сохÑ
В единственном состоянии `r_b_02.ctl` коэффициент равен `1`. У `r_b_01.ctl`
состояние 0 даёт `0`, а состояние 19 даёт `1`. Переходы наблюдались на
живых варботах, в том числе при ненулевом векторе движения.
-FParkan использует подтверждённое поле, если все состояния дают одинаковый
-коэффициент, и оценивает локальный вектор по перемещению за кадр.
+Селектор по RVA `0x51c0` оставляет допустимое текущее состояние. Иначе среди
+кандидатов с битом `+0x04 & 1` он выбирает достижимый с наименьшей стоимостью.
+`0x1000` проверяет включённые оси линейной и угловой скорости включительно
+между нижней и верхней границами. `0x19d0` строит маршрут от цели по входящим
+рёбрам, включая заданную диагональ. Переход к тому же состоянию может
+поэтому включать несколько фаз шага. Состояния без бита автоматического
+выбора продолжают очередь.
+
+Вызов `0x51c0` на исходном `r_t_01.ctl` с применением очереди по
+`0xc317–0xc37a` дал `0 → 15 → 16` для местной продольной скорости 6
+и `20 → 21 → 22 → 0` при остановке из состояния 19. Коэффициент `+0x54`
+в состояниях шага равен 1, в состоянии 0 равен 0. FParkan переносит условия
+по скорости и граф для состояний без срока, внешней команды и проверок
+узлов. Источником скоростей служат перемещение и поворот корпуса за кадр.
#### Генератор tag 19 в том же бюджетном проходе
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index 1f922edf..f0f27d52 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -373,10 +373,17 @@ Control. Снаряд использует скорость, время жизн
ставке 2,5, половине предельной скорости, коэффициенте 0,8 и шаге в
четверть секунды ходовая запрашивает 0,25 единицы питания.
-В FParkan этот расчёт работает у машин, у которых коэффициент одинаков во
-всех записанных состояниях CTL. Скорость по осям считается по фактическому
-перемещению за кадр. Переключения состояний с разными коэффициентами пока
-отмечаются заглушкой.
+Если коэффициент зависит от состояния, Control сверяет местные скорости
+хода и разворота с диапазонами из CTL. Выход из диапазона запускает переход
+минимальной стоимости между подходящими состояниями. Промежуточные кадры
+могут закончить шаг до возврата в покой. Так у паука `12spd1` коэффициент
+равен нулю в покое, становится единицей при ходе и остаётся единицей до
+завершения шага при остановке. На устройстве ходовой это меняет долю
+питания, которая достаётся зарядке оружия.
+
+FParkan выбирает состояния с проверенными условиями по перемещению и
+повороту за кадр. Состояния, которым нужны таймеры, команды или состояние
+узлов модели, остаются отмеченными заглушкой.
Активный режим tag 10 и неполные бюджетные таблицы останавливаются явно;
для такого владельца ограничение стрельбы зарядом временно отключается.
Поэтому этот путь ещё не устанавливает точный энергетический баланс боя.