diff options
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 1 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/route_motion.rs | 24 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/route_obstacles.rs | 62 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/route_traffic.rs | 213 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_patrol.rs | 37 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 10 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 12 |
7 files changed, 309 insertions, 50 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 606b0987..309ff388 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -95,6 +95,7 @@ mod research; mod resource_distribution; mod route_motion; mod route_obstacles; +mod route_traffic; use resource_distribution::advance_behavior_distributor_tick; mod script_host; mod script_patrol; diff --git a/crates/fparkan-runtime/src/route_motion.rs b/crates/fparkan-runtime/src/route_motion.rs index be57affb..b02a4f2c 100644 --- a/crates/fparkan-runtime/src/route_motion.rs +++ b/crates/fparkan-runtime/src/route_motion.rs @@ -7,6 +7,8 @@ use crate::{ use fparkan_terrain::{NavigationQuery, RouteRequest}; use std::collections::VecDeque; +pub(super) const WAYPOINT_TOLERANCE: f32 = 0.05; + pub(super) fn route_points( terrain: &TerrainWorld, from: [f32; 3], @@ -42,21 +44,25 @@ pub(super) fn follow_route( points: &mut VecDeque<[f32; 2]>, speed: f32, mut seconds: f32, - obstacles: &[Footprint], + buildings: &[Footprint], + traffic: &[Footprint], mut height_at: impl FnMut([f32; 2]) -> Result<Option<f32>, EngineError>, -) -> Result<TransformState, EngineError> { +) -> Result<(TransformState, Footprint), EngineError> { let [mut x, mut y, mut z] = pose.position.map(f32::from_bits); + let mut swept = Footprint::point([x, y]); while seconds > 0.0 && !points.is_empty() { - if !open_leg([x, y], points, obstacles, |point| { + if !open_leg([x, y], points, buildings, traffic, |point| { height_at(point).map(|z| z.is_some()) })? { - points.clear(); + if traffic.is_empty() { + points.clear(); + } break; } let Some(&target) = points.front() else { break }; let [dx, dy] = [target[0] - x, target[1] - y]; let distance = dx.hypot(dy); - if distance <= 0.05 { + if distance <= WAYPOINT_TOLERANCE { points.pop_front(); continue; } @@ -80,6 +86,7 @@ pub(super) fn follow_route( }; let offset = height_at([x, y])?.map_or(0.0, |height| z - height); [x, y] = xy; + swept.include(xy); z = ground + offset; pose.position = [x, y, z].map(f32::to_bits); if !reached { @@ -88,7 +95,7 @@ pub(super) fn follow_route( points.pop_front(); seconds -= travel_time; } - Ok(pose) + Ok((pose, swept)) } #[cfg(test)] @@ -102,7 +109,10 @@ mod tests { ..Default::default() }; let mut route = VecDeque::from([[0.0, 0.0], [0.0, 1.0], [4.0, 1.0]]); - let end = follow_route(start, &mut route, 2.0, 2.0, &[], |[x, y]| Ok(Some(x + y))).unwrap(); + let (end, _) = follow_route(start, &mut route, 2.0, 2.0, &[], &[], |[x, y]| { + Ok(Some(x + y)) + }) + .unwrap(); let [x, y, z] = end.position.map(f32::from_bits); let expected_x = 3.0 - std::f32::consts::FRAC_PI_2; assert!((x - expected_x).abs() < 0.000_01); diff --git a/crates/fparkan-runtime/src/route_obstacles.rs b/crates/fparkan-runtime/src/route_obstacles.rs index 1eab5543..a5737399 100644 --- a/crates/fparkan-runtime/src/route_obstacles.rs +++ b/crates/fparkan-runtime/src/route_obstacles.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeMap, VecDeque}; // skip a node without putting the next leg back inside the obstacle. const CORNER_GAP: f32 = 0.1; -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct Footprint { min: [f32; 2], max: [f32; 2], @@ -118,18 +118,29 @@ fn model_footprint( } impl Footprint { - fn expanded(self, margin: f32) -> Self { + pub(super) fn point(xy: [f32; 2]) -> Self { + Self { min: xy, max: xy } + } + + pub(super) fn include(&mut self, xy: [f32; 2]) { + for (axis, value) in xy.into_iter().enumerate() { + self.min[axis] = self.min[axis].min(value); + self.max[axis] = self.max[axis].max(value); + } + } + + pub(super) fn expanded(self, margin: f32) -> Self { Self { min: self.min.map(|v| v - margin), max: self.max.map(|v| v + margin), } } - fn contains(self, p: [f32; 2]) -> bool { + pub(super) fn contains(self, p: [f32; 2]) -> bool { (0..2).all(|axis| p[axis] >= self.min[axis] && p[axis] <= self.max[axis]) } - fn intersects(self, from: [f32; 2], to: [f32; 2]) -> bool { + pub(super) fn intersects(self, from: [f32; 2], to: [f32; 2]) -> bool { let (mut first, mut last) = (0.0_f32, 1.0_f32); for axis in 0..2 { let delta = to[axis] - from[axis]; @@ -176,29 +187,31 @@ fn distance(a: [f32; 2], b: [f32; 2]) -> f32 { pub(super) fn open_leg( from: [f32; 2], points: &mut VecDeque<[f32; 2]>, - obstacles: &[Footprint], + buildings: &[Footprint], + traffic: &[Footprint], mut walkable: impl FnMut([f32; 2]) -> Result<bool, EngineError>, ) -> Result<bool, EngineError> { - while points.len() > 1 && obstacles.iter().any(|o| o.contains(points[0])) { + let obstacles = buildings.iter().chain(traffic); + while points.len() > 1 && obstacles.clone().any(|o| o.contains(points[0])) { points.pop_front(); } let Some(&goal) = points.front() else { return Ok(false); }; - if !obstacles.iter().any(|o| o.intersects(from, goal)) { + if !obstacles.clone().any(|o| o.intersects(from, goal)) { return Ok(true); } - let contains = |point| obstacles.iter().any(|o| o.contains(point)); + let contains = |point| obstacles.clone().any(|o| o.contains(point)); if contains(from) { let mut exits: Vec<_> = obstacles - .iter() + .clone() .filter(|o| o.contains(from)) .flat_map(|o| o.exits(from)) .filter(|&p| { !contains(p) && !obstacles - .iter() + .clone() .any(|o| !o.contains(from) && o.intersects(from, p)) }) .collect(); @@ -216,9 +229,10 @@ pub(super) fn open_leg( let mut nodes = vec![from]; let mut end = goal; + let occupied = traffic.iter().any(|body| body.contains(goal)); if contains(goal) { let mut exits: Vec<_> = obstacles - .iter() + .clone() .filter(|o| o.contains(goal)) .flat_map(|o| o.exits(goal)) .filter(|&p| !contains(p)) @@ -236,10 +250,13 @@ pub(super) fn open_leg( }; end = exit; } + if occupied && distance(from, end) <= crate::route_motion::WAYPOINT_TOLERANCE { + return Ok(false); + } nodes.push(end); - if obstacles.iter().any(|o| o.intersects(from, end)) { + if obstacles.clone().any(|o| o.intersects(from, end)) { for p in obstacles - .iter() + .clone() .flat_map(|o| o.corners()) .filter(|&p| !contains(p)) { @@ -251,7 +268,9 @@ pub(super) fn open_leg( let Some(path) = shortest_path(&nodes, obstacles) else { return Ok(false); }; - points.pop_front(); + if !occupied { + points.pop_front(); + } for p in path { points.push_front(p); } @@ -260,7 +279,10 @@ pub(super) fn open_leg( // Dijkstra over the visibility graph. Edges are built on demand and a node // may connect to any other visible node, including corners on another box. -fn shortest_path(nodes: &[[f32; 2]], obstacles: &[Footprint]) -> Option<Vec<[f32; 2]>> { +fn shortest_path<'a>( + nodes: &[[f32; 2]], + obstacles: impl Iterator<Item = &'a Footprint> + Clone, +) -> Option<Vec<[f32; 2]>> { let mut distance_to = vec![f32::INFINITY; nodes.len()]; let mut parent = vec![None; nodes.len()]; let mut settled = vec![false; nodes.len()]; @@ -275,7 +297,7 @@ fn shortest_path(nodes: &[[f32; 2]], obstacles: &[Footprint]) -> Option<Vec<[f32 settled[next] = true; for (i, &to) in nodes.iter().enumerate().filter(|&(i, _)| !settled[i]) { let cost = distance_to[next] + distance(nodes[next], to); - if cost < distance_to[i] && !obstacles.iter().any(|o| o.intersects(nodes[next], to)) { + if cost < distance_to[i] && !obstacles.clone().any(|o| o.intersects(nodes[next], to)) { distance_to[i] = cost; parent[i] = Some(next); } @@ -309,7 +331,7 @@ mod tests { let start = [0.0, 0.0]; let goal = [9.0, 0.0]; let mut route = VecDeque::from([goal]); - assert!(open_leg(start, &mut route, &[a, b], |_| Ok(true)).unwrap()); + assert!(open_leg(start, &mut route, &[a, b], &[], |_| Ok(true)).unwrap()); assert!(route.len() >= 3); assert_eq!(route.back(), Some(&goal)); let mut from = start; @@ -328,9 +350,9 @@ mod tests { }; let goal = [10.0, 0.0]; let mut route = VecDeque::from([goal]); - assert!(open_leg([1.0, 0.0], &mut route, &[building], |_| Ok(true)).unwrap()); + assert!(open_leg([1.0, 0.0], &mut route, &[building], &[], |_| Ok(true)).unwrap()); assert_eq!(route, [[-CORNER_GAP, 0.0], goal]); - assert!(open_leg([0.5, 0.0], &mut route, &[building], |_| Ok(true)).unwrap()); + assert!(open_leg([0.5, 0.0], &mut route, &[building], &[], |_| Ok(true)).unwrap()); assert_eq!(route.len(), 2); } @@ -371,7 +393,7 @@ mod tests { let goal = [outline.max[0] + 8.0, y]; assert!(outline.intersects(start, goal)); let mut route = VecDeque::from([goal]); - assert!(open_leg(start, &mut route, &[outline], |p| { + assert!(open_leg(start, &mut route, &[outline], &[], |p| { mission .terrain .height_at(p) diff --git a/crates/fparkan-runtime/src/route_traffic.rs b/crates/fparkan-runtime/src/route_traffic.rs new file mode 100644 index 00000000..26116ceb --- /dev/null +++ b/crates/fparkan-runtime/src/route_traffic.rs @@ -0,0 +1,213 @@ +//! Temporary ground occupancy during one autonomous movement step. + +use crate::{ + autodemo::MOBILE_UNIT, projectile::unit_sphere, route_obstacles::Footprint, LoadedMissionState, + MissionAssets, ObjectHandle, TransformState, World, +}; +use fparkan_world::{handle_by_original_id, transform_state}; + +struct Body { + handle: ObjectHandle, + radius: f32, + swept: Footprint, + moved: bool, +} + +#[derive(Default)] +pub(super) struct FrameTraffic { + bodies: Vec<Body>, +} + +fn body_radius(assets: &MissionAssets, index: usize, pose: TransformState) -> Option<f32> { + let (center, radius) = unit_sphere(assets, index, pose)?; + let [x, y, _] = pose.position.map(f32::from_bits); + let radius = radius + (center[0] - x).hypot(center[1] - y); + (radius.is_finite() && radius > 0.0).then_some(radius) +} + +impl FrameTraffic { + pub(super) fn read(world: &World, mission: &LoadedMissionState) -> Self { + let bodies = mission + .object_drafts + .iter() + .enumerate() + .filter_map(|(index, draft)| { + (draft.unit_dat_header_flags? & MOBILE_UNIT != 0).then_some(())?; + let handle = handle_by_original_id(world, draft.original_id?)?; + let pose = transform_state(world, handle).ok()?; + let [x, y, _] = pose.position.map(f32::from_bits); + Some(Body { + handle, + radius: body_radius(&mission.mission_assets, index, pose)?, + swept: Footprint::point([x, y]), + moved: false, + }) + }) + .collect(); + Self { bodies } + } + + pub(super) fn radius(&self, handle: ObjectHandle) -> f32 { + self.bodies + .iter() + .find(|body| body.handle == handle) + .map_or(0.0, |body| body.radius) + } + + /// None means the unit's starting point is inside a trajectory that was + /// already accepted this frame. It can try again with a fresh snapshot. + pub(super) fn blockers( + &self, + handle: ObjectHandle, + from: [f32; 2], + radius: f32, + ) -> Option<Vec<Footprint>> { + self.bodies + .iter() + .filter(|body| body.handle != handle) + .map(|body| { + let bounds = body.swept.expanded(radius + body.radius); + (!body.moved || !bounds.contains(from)).then_some(bounds) + }) + .collect() + } + + pub(super) fn reserve(&mut self, handle: ObjectHandle, swept: Footprint) { + if let Some(body) = self.bodies.iter_mut().find(|body| body.handle == handle) { + if body.swept != swept { + body.swept = swept; + body.moved = true; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::route_motion::follow_route; + use std::{collections::VecDeque, f32::consts::FRAC_PI_2}; + + fn pose(xy: [f32; 2], yaw: f32) -> TransformState { + TransformState { + position: [xy[0], xy[1], 0.0].map(f32::to_bits), + orientation: [0.0, 0.0, yaw].map(f32::to_bits), + ..Default::default() + } + } + + fn xy(pose: TransformState) -> [f32; 2] { + [ + f32::from_bits(pose.position[0]), + f32::from_bits(pose.position[1]), + ] + } + + #[test] + fn two_units_swap_positions_without_intersecting() { + let handles = [1, 2].map(|slot| ObjectHandle { + slot, + generation: 1, + }); + let destinations = [[7.0, 0.0], [-7.0, 0.0]]; + let mut poses = [ + pose(destinations[1], -FRAC_PI_2), + pose(destinations[0], FRAC_PI_2), + ]; + let mut routes = destinations.map(|target| VecDeque::from([target])); + for _ in 0..250 { + let mut traffic = FrameTraffic { + bodies: handles + .into_iter() + .zip(poses) + .map(|(handle, pose)| Body { + handle, + radius: 0.5, + swept: Footprint::point(xy(pose)), + moved: false, + }) + .collect(), + }; + for i in 0..2 { + let Some(blockers) = traffic.blockers(handles[i], xy(poses[i]), 0.5) else { + continue; + }; + let (after, sweep) = + follow_route(poses[i], &mut routes[i], 3.0, 0.1, &[], &blockers, |_| { + Ok(Some(0.0)) + }) + .unwrap(); + poses[i] = after; + traffic.reserve(handles[i], sweep); + } + let [[a, b], [c, d]] = poses.map(xy); + assert!( + (a - c).hypot(b - d) > 1.0, + "units overlapped at {a},{b} and {c},{d}" + ); + if routes.iter().all(VecDeque::is_empty) { + break; + } + } + assert_eq!(poses.map(xy), destinations, "remaining routes: {routes:?}"); + } + + #[test] + fn later_unit_avoids_the_first_units_crossing_during_a_long_frame() { + let [first, second] = [1, 2].map(|slot| ObjectHandle { + slot, + generation: 1, + }); + let start = [pose([-4.0, 0.0], -FRAC_PI_2), pose([0.0, -4.0], 0.0)]; + let mut traffic = FrameTraffic { + bodies: [first, second] + .into_iter() + .zip(start) + .map(|(handle, at)| Body { + handle, + radius: 0.5, + swept: Footprint::point(xy(at)), + moved: false, + }) + .collect(), + }; + let flat = |_| Ok(Some(0.0)); + let first_blockers = traffic.blockers(first, xy(start[0]), 0.5).unwrap(); + let (after, swept) = follow_route( + start[0], + &mut VecDeque::from([[4.0, 0.0]]), + 10.0, + 1.0, + &[], + &first_blockers, + flat, + ) + .unwrap(); + assert_eq!(xy(after), [4.0, 0.0]); + traffic.reserve(first, swept); + let second_blockers = traffic.blockers(second, xy(start[1]), 0.5).unwrap(); + let mut route = VecDeque::from([[0.0, 4.0]]); + let (after, _) = + follow_route(start[1], &mut route, 10.0, 1.0, &[], &second_blockers, flat).unwrap(); + assert!(xy(after)[1] < -1.0); + assert_eq!(route.back(), Some(&[0.0, 4.0])); + } + + #[test] + fn stopped_vehicle_does_not_erase_an_occupied_destination() { + let position = [0.0, 0.0]; + let target = [0.0, 5.0]; + let mut route = VecDeque::from([target]); + let start = pose(position, 0.0); + let bounds = Footprint::point(target).expanded(1.0); + let flat = |_| Ok(Some(0.0)); + let (waiting, _) = + follow_route(start, &mut route, 10.0, 2.0, &[], &[bounds], flat).unwrap(); + assert!(xy(waiting)[1] > 3.0); + assert!(!bounds.contains(xy(waiting))); + assert_eq!(route, [target]); + let (arrived, _) = follow_route(waiting, &mut route, 10.0, 2.0, &[], &[], flat).unwrap(); + assert_eq!(xy(arrived), target); + assert!(route.is_empty()); + } +} diff --git a/crates/fparkan-runtime/src/unit_patrol.rs b/crates/fparkan-runtime/src/unit_patrol.rs index e8f94b3f..5479ef95 100644 --- a/crates/fparkan-runtime/src/unit_patrol.rs +++ b/crates/fparkan-runtime/src/unit_patrol.rs @@ -3,9 +3,9 @@ use super::{ boarding::WARBOT_CLASS, next_crt_rand, patrol_points::{PatrolPointReport, PatrolPoints}, - projectile::unit_sphere, route_motion::{follow_route, route_points, turn_toward}, route_obstacles::BuildingFootprints, + route_traffic::FrameTraffic, unit_combat::CombatTarget, unit_speed::{order_speed, UnitSpeedKind, UnitSpeedReport}, EngineError, LoadedMissionState, MissionDocument, MissionObjectDraft, MissionScriptBundle, @@ -430,9 +430,12 @@ impl UnitPatrol { }); let seconds = now_ms.saturating_sub(state.clock_ms) as f32 * 0.001; state.clock_ms = state.clock_ms.max(now_ms); - if seconds > 0.0 && !state.units.is_empty() { + let mut traffic = if seconds > 0.0 && !state.units.is_empty() { state.buildings.refresh(world, mission); - } + FrameTraffic::read(world, mission) + } else { + FrameTraffic::default() + }; let mut poses = Vec::new(); for unit in &mut state.units { let Ok(before) = transform_state(world, unit.handle) else { @@ -619,18 +622,22 @@ impl UnitPatrol { } else { 9.0 }; - let clearance = motion_object - .original_id - .and_then(|id| { - let (center, radius) = - unit_sphere(&mission.mission_assets, id as usize, before)?; - Some(radius + (center[0] - from[0]).hypot(center[1] - from[1])) - }) - .unwrap_or(0.0); - let obstacles = state.buildings.with_clearance(clearance); - let after = follow_route(before, &mut unit.points, speed, seconds, &obstacles, |xy| { - terrain.height_at(xy).map_err(EngineError::Terrain) - })?; + let clearance = traffic.radius(unit.handle); + let Some(neighbors) = traffic.blockers(unit.handle, [from[0], from[1]], clearance) + else { + continue; + }; + let buildings = state.buildings.with_clearance(clearance); + let (after, swept) = follow_route( + before, + &mut unit.points, + speed, + seconds, + &buildings, + &neighbors, + |xy| terrain.height_at(xy).map_err(EngineError::Terrain), + )?; + traffic.reserve(unit.handle, swept); if after != before { poses.push((unit.handle, before, after)); } diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index eebf8944..c4081364 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -75,17 +75,17 @@ authoring API без динамического подтверждения. исчерпании запаса и ошибках размещения. Заводское производство ещё открыто. `autodemo_patrol_approx` отмечает приближения центра приказа, RNG, маршрута и физики. Границы атаки проверяются в плоскости карты, пока приказ патруля -не хранит исходную высоту. Анимация ходьбы и локальный обход открыты. +не хранит исходную высоту. Анимация ходьбы и проходы в тесноте открыты. `unit_motion_controller_stub` считает обновления временного контроллера по объекту и поколению. Нативный MWalker и передача движения в Control открыты. -Обход строений проверяет проекции основной модели. Формы дверей и проёмов, -составные корпуса, проверка проходимости всего отрезка и обход юнитов открыты. +Обход проверяет проекции основных моделей и участки, занятые машинами за кадр. +Открыты формы проёмов, проверка проходимости всего отрезка и разъезд в тесноте. `go_speed_profile_approx` считает кадровые запросы Go по текущему пределу Control и коэффициенту Behavior; `go_speed_stub` считает подмену 9 при отсутствии данных. Удержание запроса MWalker входит в незавершённый `unit_motion_controller_stub`. `autodemo_combat_approx` отмечает выбор цели, наведение и -приближённый урон. Звуки и эффекты боя, уклонение и столкновения со -строениями открыты. Счётчики `autodemo_weapon_unavailable` и +приближённый урон. Звуки, эффекты боя и боевое уклонение открыты. +Счётчики `autodemo_weapon_unavailable` и `autodemo_combat_unavailable` отмечают пропуски подготовки и расчёта попаданий. `unit_combat_unavailable` считает эти пропуски по объекту, поколению и причине; `empty_weapon_bank` включает штатные невооружённые машины. `sim_combat` diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index f4798500..4d50660f 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2389,9 +2389,15 @@ Go, Patrol и сближение с целью передают маршрут Ð Если машина уже находится внутри проекции, первая цель лежит у ближайшей доступной стороны. Цель внутри здания даёт точку подхода снаружи. -`unit_motion_controller_stub` остаётся в отчёте. Сейчас препятствие имеет -прямоугольную форму и строится по начальной позе модели. Открыты узкие -проезды, обход других машин, высота полёта и связь движения с анимацией. +Другие машины тоже занимают место на пути. Перед ходом берётся снимок их +позиций. За уже сдвинувшейся машиной до конца кадра сохраняется весь +пройденный участок с запасом под корпус. Это позволяет избежать пересечения +маршрутов при длинном кадре. Если конечная точка занята, машина подходит +к свободному краю и продолжает приказ после освобождения цели. + +`unit_motion_controller_stub` остаётся в отчёте. Препятствия имеют +прямоугольную форму, а очередь хода машин влияет на разъезд. Открыты узкие +проезды, высота полёта и связь движения с анимацией. В GOG `Behavior.dll` ([сборка](../reference/original-binaries.md)) задача Go (RVA `0x2b670`) обращается к MWalker, а не изменяет transform сама. |
