aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-26 04:58:15 +0300
committerValentin Popov <valentin@popov.link>2026-11-26 04:58:15 +0300
commit4e4a0795fccbcc4a2dd2f4b51c8f8f7802812791 (patch)
tree3cd67b59d94feb1fd1515be4f0c69134a86a6cde /crates/fparkan-runtime
parent531753ef5fbfa846b4291864458f511d5c7e1b59 (diff)
downloadfparkan-4e4a0795fccbcc4a2dd2f4b51c8f8f7802812791.tar.xz
fparkan-4e4a0795fccbcc4a2dd2f4b51c8f8f7802812791.zip
feat(movement): play authored walking cycles from chassis travel
Select a closed forward stride from the model for explicit walking profiles. Drive it from world displacement and subtract baked forward travel before updating geometry, mounts and shadows. Verified light, medium and heavy stock model cycles and watched leg poses change from the normal AutoDemo start with Vulkan validation clean. Stop transitions and terrain-adaptive feet remain open.
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/flight_altitude.rs10
-rw-r--r--crates/fparkan-runtime/src/lib.rs9
-rw-r--r--crates/fparkan-runtime/src/unit_chassis.rs28
-rw-r--r--crates/fparkan-runtime/src/unit_patrol.rs4
-rw-r--r--crates/fparkan-runtime/src/walk_animation.rs239
5 files changed, 279 insertions, 11 deletions
diff --git a/crates/fparkan-runtime/src/flight_altitude.rs b/crates/fparkan-runtime/src/flight_altitude.rs
index d5276b46..4bf5f7a9 100644
--- a/crates/fparkan-runtime/src/flight_altitude.rs
+++ b/crates/fparkan-runtime/src/flight_altitude.rs
@@ -75,8 +75,14 @@ mod tests {
.unwrap();
let id = OriginalObjectId(2);
assert_eq!(
- engine.loaded.as_ref().unwrap().unit_can_fly.get(&id.0),
- Some(&Some(true))
+ engine
+ .loaded
+ .as_ref()
+ .unwrap()
+ .unit_chassis_flags
+ .get(&id.0)
+ .and_then(|flags| flags.can_fly),
+ Some(true)
);
let handle = handle_by_original_id(&engine.world, id).unwrap();
let [a, b, initial_z] = transform_state(&engine.world, handle)
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 991e5efc..9fb9a262 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -103,12 +103,15 @@ mod script_host;
mod script_patrol;
mod script_time;
mod unit_chassis;
+pub use unit_chassis::loaded_walk_chassis;
mod unit_combat;
mod unit_motion;
pub use unit_motion::{loaded_mission_unit_motion_report, UnitMotionReport, UnitMotionSample};
mod unit_patrol;
mod unit_size_class;
mod unit_spawn;
+mod walk_animation;
+pub use walk_animation::WalkAnimation;
mod weapon_pose;
mod wheel_animation;
pub use weapon_pose::{initial_component_node_times, WeaponPoseReport};
@@ -1400,7 +1403,7 @@ struct LoadedMissionState {
mission_assets: MissionAssets,
asset_plan: MissionAssetPlan,
object_drafts: Vec<MissionObjectDraft>,
- unit_can_fly: std::collections::BTreeMap<u32, Option<bool>>,
+ unit_chassis_flags: std::collections::BTreeMap<u32, fparkan_assets::ChassisFlags>,
behavior_distributors: Vec<BehaviorDistributorState>,
behavior_ore_states: Vec<BehaviorOreState>,
behavior_profiles: Vec<BehaviorProfileState>,
@@ -2726,7 +2729,7 @@ node_provider_distribution_suspended: false,
engine.production = production;
let free_research = research::FreeResearch::new(&object_drafts[..reserve_start]);
let chassis_resources = CachedResourceRepository::new(vfs.clone());
- let unit_can_fly = unit_chassis::load_flags(&chassis_resources, &object_drafts);
+ let unit_chassis_flags = unit_chassis::load_flags(&chassis_resources, &object_drafts);
engine.loaded = Some(LoadedMissionState {
summary: summary.clone(),
mission,
@@ -2737,7 +2740,7 @@ node_provider_distribution_suspended: false,
mission_assets,
asset_plan: mission_asset_plan,
object_drafts,
- unit_can_fly,
+ unit_chassis_flags,
behavior_distributors,
behavior_ore_states,
behavior_profiles,
diff --git a/crates/fparkan-runtime/src/unit_chassis.rs b/crates/fparkan-runtime/src/unit_chassis.rs
index 88b5a3c9..25020a4f 100644
--- a/crates/fparkan-runtime/src/unit_chassis.rs
+++ b/crates/fparkan-runtime/src/unit_chassis.rs
@@ -1,12 +1,13 @@
//! Chassis behavior flags shared by autonomous and player control.
-use crate::MissionObjectDraft;
+use crate::{Engine, MissionObjectDraft};
+use fparkan_assets::{decode_chassis_flags, ChassisFlags};
use fparkan_resource::{resource_name, CachedResourceRepository, ResourceRepository};
use std::collections::BTreeMap;
pub(super) fn load_flags(
resources: &CachedResourceRepository,
drafts: &[MissionObjectDraft],
-) -> BTreeMap<u32, Option<bool>> {
+) -> BTreeMap<u32, ChassisFlags> {
drafts
.iter()
.filter(|draft| {
@@ -17,7 +18,7 @@ pub(super) fn load_flags(
.filter_map(|draft| {
draft
.original_id
- .map(|id| (id.0, can_fly(resources, draft)))
+ .map(|id| (id.0, load_profile(resources, draft).unwrap_or_default()))
})
.collect()
}
@@ -26,6 +27,25 @@ pub(super) fn can_fly(
resources: &CachedResourceRepository,
draft: &MissionObjectDraft,
) -> Option<bool> {
+ load_profile(resources, draft)?.can_fly
+}
+
+/// Returns whether a loaded draft has an explicit walking chassis profile.
+pub fn loaded_walk_chassis(engine: &Engine, object_index: usize) -> bool {
+ engine.loaded.as_ref().is_some_and(|mission| {
+ mission
+ .object_drafts
+ .get(object_index)
+ .and_then(|draft| draft.original_id)
+ .and_then(|id| mission.unit_chassis_flags.get(&id.0))
+ .is_some_and(|flags| flags.walk_chassis == Some(true))
+ })
+}
+
+fn load_profile(
+ resources: &CachedResourceRepository,
+ draft: &MissionObjectDraft,
+) -> Option<ChassisFlags> {
let chassis = draft.unit_components.first()?;
let archive = crate::bounded_ascii_c_string(&chassis.archive_raw)?;
let registry_path = crate::normalize_engine_path("chassis archive", &archive).ok()?;
@@ -45,5 +65,5 @@ pub(super) fn can_fly(
let entry = resources
.find(archive, &resource_name(name.as_bytes()))
.ok()??;
- fparkan_assets::decode_chassis_can_fly(resources.read(entry).ok()?.as_slice()).ok()?
+ decode_chassis_flags(resources.read(entry).ok()?.as_slice()).ok()
}
diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs
index 57e01b78..0eaf04fc 100644
--- a/crates/fparkan-runtime/src/unit_patrol.rs
+++ b/crates/fparkan-runtime/src/unit_patrol.rs
@@ -424,7 +424,7 @@ impl UnitPatrol {
count_rng: &mut u32,
) -> Result<PreparedPatrol, EngineError> {
let terrain = &mission.terrain;
- let chassis = &mission.unit_can_fly;
+ let chassis = &mission.unit_chassis_flags;
let mut state = self.clone();
state.advance_script_orders(world, &mission.control_device_tables);
state.units.retain(|unit| {
@@ -449,7 +449,7 @@ impl UnitPatrol {
let from = before.position.map(f32::from_bits);
let motion_object = crate::CombatObject::read(world, unit.handle);
let original_id = motion_object.original_id.unwrap_or(unit.handle.slot);
- let can_fly = chassis.get(&original_id).copied().flatten();
+ let can_fly = chassis.get(&original_id).and_then(|flags| flags.can_fly);
if let Some(destinations) = &mut unit.destinations {
if destinations
.front()
diff --git a/crates/fparkan-runtime/src/walk_animation.rs b/crates/fparkan-runtime/src/walk_animation.rs
new file mode 100644
index 00000000..5fa7ca55
--- /dev/null
+++ b/crates/fparkan-runtime/src/walk_animation.rs
@@ -0,0 +1,239 @@
+//! Play a closed authored stride in place, using locomotion from the world.
+
+use crate::{ObjectHandle, TransformState};
+use fparkan_animation::{NodePoseBuffer, Pose};
+use fparkan_msh::{node38_sampled_hierarchy, ModelAsset};
+use fparkan_world::Tick;
+use std::sync::Arc;
+
+/// Per-instance playback of a walking chassis's first closed forward stride.
+#[derive(Clone)]
+pub struct WalkAnimation {
+ clip: Arc<Stride>,
+ distance: f32,
+ moving: bool,
+ previous: Option<(ObjectHandle, Tick, [f32; 2])>,
+}
+
+struct Stride {
+ first_frame: u16,
+ rest_forward: f32,
+ advances: Vec<f32>,
+}
+
+impl WalkAnimation {
+ /// Finds a complete stride in a model with forward root motion. Call only
+ /// for models whose chassis profile explicitly declares walking.
+ pub fn prepare(model: &ModelAsset) -> Option<Self> {
+ let clip = Stride::prepare(model)?;
+ Some(Self {
+ clip: Arc::new(clip),
+ distance: 0.0,
+ moving: false,
+ previous: None,
+ })
+ }
+
+ /// A new tick advances the stride by actual forward displacement. A
+ /// retained snapshot keeps the same pose, including during pause.
+ pub fn sample(
+ &mut self,
+ handle: ObjectHandle,
+ tick: Tick,
+ pose: TransformState,
+ ) -> Option<f32> {
+ let [x, y, _] = pose.position.map(f32::from_bits);
+ match self.previous {
+ Some((owner, frame, [old_x, old_y])) if owner == handle => {
+ if tick != frame {
+ let yaw = f32::from_bits(pose.orientation[2]);
+ let forward = (old_x - x) * yaw.sin() + (y - old_y) * yaw.cos();
+ let advance = forward / f32::from_bits(pose.scale[1]).abs();
+ self.moving = advance.is_finite() && advance > 0.0;
+ self.distance = if self.moving {
+ let period = f64::from(*self.clip.advances.last()?);
+ (f64::from(self.distance) + f64::from(advance)).rem_euclid(period) as f32
+ } else {
+ 0.0
+ };
+ self.previous = Some((handle, tick, [x, y]));
+ }
+ }
+ _ => {
+ self.previous = Some((handle, tick, [x, y]));
+ self.moving = false;
+ self.distance = 0.0;
+ }
+ }
+ self.moving.then(|| self.clip.frame_at(self.distance))
+ }
+
+ /// Removes baked forward translation after sampling, so world movement
+ /// owns the distance travelled. Local bob and sway remain in the pose.
+ pub fn remove_root_progress(&self, hierarchy: &mut NodePoseBuffer) {
+ if let Some(root) = hierarchy.poses.first() {
+ let displacement = root.translation[1] - self.clip.rest_forward;
+ for pose in &mut hierarchy.poses {
+ pose.translation[1] -= displacement;
+ }
+ }
+ }
+}
+
+impl Stride {
+ fn prepare(model: &ModelAsset) -> Option<Self> {
+ let frames = u16::try_from(model.animation.as_ref()?.frame_count).ok()?;
+ let rest = node38_sampled_hierarchy(model, 0)?.poses;
+ let rest_forward = rest.first()?.translation[1];
+ let radius = model.bounding_sphere_radius;
+ if !radius.is_finite() || radius <= 0.0 {
+ return None;
+ }
+ let tolerance = (radius * 0.0001).powi(2);
+ let mut run = vec![rest];
+ for frame in 1..frames {
+ let poses = node38_sampled_hierarchy(model, frame)?.poses;
+ if run.last()?.first()?.translation[1] >= poses.first()?.translation[1] {
+ run.clear();
+ }
+ run.push(poses);
+ let (last, prefix) = run.split_last()?;
+ for (i, first) in prefix.iter().enumerate() {
+ let span = prefix.len() - i;
+ let forward = last[0].translation[1] - first[0].translation[1];
+ if span < 4 || forward < radius || !same_stride_pose(first, last, tolerance) {
+ continue;
+ }
+ // Moving every bone rigidly together would preserve the
+ // endpoints but would still be a sliding chassis.
+ if !prefix[i + 1..]
+ .iter()
+ .any(|middle| !same_stride_pose(first, middle, tolerance))
+ {
+ continue;
+ }
+ let advances = run[i..]
+ .iter()
+ .map(|pose| pose[0].translation[1] - first[0].translation[1])
+ .collect();
+ return Some(Self {
+ first_frame: frame - span as u16,
+ rest_forward,
+ advances,
+ });
+ }
+ }
+ None
+ }
+
+ fn frame_at(&self, distance: f32) -> f32 {
+ let end = self
+ .advances
+ .partition_point(|&advance| advance <= distance)
+ .clamp(1, self.advances.len() - 1);
+ let start = end - 1;
+ let fraction =
+ (distance - self.advances[start]) / (self.advances[end] - self.advances[start]);
+ f32::from(self.first_frame) + start as f32 + fraction
+ }
+}
+
+fn same_stride_pose(first: &[Pose], second: &[Pose], tolerance_squared: f32) -> bool {
+ let forward = second[0].translation[1] - first[0].translation[1];
+ first.iter().zip(second).all(|(a, b)| {
+ let [x, y, z] = a.translation;
+ let [nx, ny, nz] = b.translation;
+ let shift = (x - nx).powi(2) + (y + forward - ny).powi(2) + (z - nz).powi(2);
+ let angle: f32 = a
+ .rotation
+ .into_iter()
+ .zip(b.rotation)
+ .map(|(a, b)| a * b)
+ .sum();
+ shift <= tolerance_squared && angle.abs() >= 0.99999
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn stride_uses_world_displacement_and_keeps_phase_on_repeated_ticks() {
+ let mut walk = WalkAnimation {
+ clip: Arc::new(Stride {
+ first_frame: 10,
+ rest_forward: 0.0,
+ advances: vec![0.0, 1.0, 3.0],
+ }),
+ distance: 0.0,
+ moving: false,
+ previous: None,
+ };
+ let handle = ObjectHandle {
+ slot: 0,
+ generation: 1,
+ };
+ let pose = |y| TransformState {
+ position: [0.0, y, 0.0].map(f32::to_bits),
+ scale: [1.0, 2.0, 1.0].map(f32::to_bits),
+ ..TransformState::default()
+ };
+ assert_eq!(walk.sample(handle, Tick(0), pose(0.0)), None);
+ assert_eq!(walk.sample(handle, Tick(1), pose(4.0)), Some(11.5));
+ assert_eq!(walk.sample(handle, Tick(1), pose(4.0)), Some(11.5));
+ assert_eq!(walk.sample(handle, Tick(2), pose(6.0)), Some(10.0));
+ assert_eq!(walk.sample(handle, Tick(3), pose(6.0)), None);
+ let replacement = ObjectHandle {
+ generation: 2,
+ ..handle
+ };
+ assert_eq!(walk.sample(replacement, Tick(4), pose(12.0)), None);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn stock_walkers_have_closed_forward_strides() {
+ use fparkan_assets::decode_nres_payload;
+ use fparkan_msh::{decode_msh, validate_msh};
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
+ let bases = std::path::PathBuf::from(root).join("bases.rlb");
+ let bases = decode_nres_payload(std::fs::read(bases).unwrap().into()).unwrap();
+ for (name, first, last, distance) in [
+ ("r_l_01.msh", 10, 18, 5.118131),
+ ("r_m_01.msh", 16, 24, 7.68),
+ ("r_b_01.msh", 29, 41, 12.8),
+ ] {
+ let bytes = bases.payload(bases.find(name).unwrap()).unwrap();
+ let msh = decode_nres_payload(bytes.to_vec().into()).unwrap();
+ let model = validate_msh(&decode_msh(&msh).unwrap()).unwrap();
+ let walk = WalkAnimation::prepare(&model).unwrap();
+ assert_eq!(walk.clip.first_frame, first, "{name}");
+ assert_eq!(
+ walk.clip.advances.len(),
+ usize::from(last - first + 1),
+ "{name}"
+ );
+ assert!(
+ (walk.clip.advances.last().unwrap() - distance).abs() < 0.001,
+ "{name}"
+ );
+
+ let mut start = node38_sampled_hierarchy(&model, first).unwrap();
+ let mut middle = node38_sampled_hierarchy(&model, (first + last) / 2).unwrap();
+ let mut end = node38_sampled_hierarchy(&model, last).unwrap();
+ for hierarchy in [&mut start, &mut middle, &mut end] {
+ walk.remove_root_progress(hierarchy);
+ assert!(
+ (hierarchy.poses[0].translation[1] - walk.clip.rest_forward).abs() < 0.0001
+ );
+ }
+ assert!(same_stride_pose(&start.poses, &end.poses, 1e-6), "{name}");
+ assert!(
+ !same_stride_pose(&start.poses, &middle.poses, 1e-6),
+ "{name}"
+ );
+ }
+ }
+}