use std::cmp::Ordering;
use std::collections::{BTreeMap, BinaryHeap, VecDeque};
use glam::{DVec2, DVec3};
use crate::grid::{GroundRoute, GroundRouteError};
pub const MAX_SPAN_COLUMN_COUNT: usize = 1 << 22;
pub const MAX_EROSION_REACH_CELLS: usize = 64;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NavAgent {
pub radius_m: f64,
pub height_m: f64,
pub max_climb_m: f64,
pub min_floor_normal_y: f64,
}
#[cfg(feature = "phys")]
impl NavAgent {
#[must_use]
pub fn from_character(config: &crcbl_phys::character::CharacterConfig) -> Self {
Self {
radius_m: config.radius,
height_m: 2.0 * (config.half_height + config.radius),
max_climb_m: config.step_offset,
min_floor_normal_y: config.min_ground_normal_y,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpanGridConfig {
pub origin: DVec2,
pub cell_size_m: f64,
pub width: usize,
pub height: usize,
}
impl SpanGridConfig {
#[must_use]
pub fn cell_center(&self, column: usize, row: usize) -> DVec2 {
self.origin + (DVec2::new(column as f64, row as f64) + 0.5) * self.cell_size_m
}
fn column_count(self) -> Result<usize, SpanGridError> {
if !self.origin.is_finite() {
return Err(SpanGridError::InvalidOrigin);
}
if !self.cell_size_m.is_finite() || self.cell_size_m <= 0.0 {
return Err(SpanGridError::InvalidCellSize);
}
if self.width == 0 || self.height == 0 {
return Err(SpanGridError::InvalidDimensions);
}
self.width
.checked_mul(self.height)
.filter(|&count| count <= MAX_SPAN_COLUMN_COUNT)
.ok_or(SpanGridError::TooManyColumns)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ProbedFloor {
pub y: f64,
pub normal_y: f64,
pub headroom_clear: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum SpanGridError {
#[error("the grid origin is not a finite position")]
InvalidOrigin,
#[error("the cell size is not a finite positive length")]
InvalidCellSize,
#[error("the grid has a zero width or height")]
InvalidDimensions,
#[error("the grid has more columns than MAX_SPAN_COLUMN_COUNT allows")]
TooManyColumns,
#[error("the agent's limits are not finite lengths and a normal's Y")]
InvalidAgent,
#[error("the agent's radius spans more cells than MAX_EROSION_REACH_CELLS")]
RadiusTooWide,
#[error("the probe reported a floor that is not finite")]
InvalidFloor,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpanGrid {
config: SpanGridConfig,
agent: NavAgent,
column_start: Vec<usize>,
floors: Vec<f64>,
}
type SpanId = usize;
impl SpanGrid {
pub fn build(
config: SpanGridConfig,
agent: NavAgent,
mut probe: impl FnMut(DVec2) -> Vec<ProbedFloor>,
) -> Result<Self, SpanGridError> {
let column_count = config.column_count()?;
let finite = [
agent.radius_m,
agent.height_m,
agent.max_climb_m,
agent.min_floor_normal_y,
]
.iter()
.all(|value| value.is_finite());
if !finite
|| agent.radius_m < 0.0
|| agent.height_m <= 0.0
|| agent.max_climb_m < 0.0
|| !(-1.0..=1.0).contains(&agent.min_floor_normal_y)
{
return Err(SpanGridError::InvalidAgent);
}
let reach = agent.radius_m / config.cell_size_m;
if reach > MAX_EROSION_REACH_CELLS as f64 {
return Err(SpanGridError::RadiusTooWide);
}
#[allow(clippy::cast_possible_truncation)]
let steps = (reach + 0.5).ceil() as isize;
let offsets: Vec<(isize, isize)> = (-steps..=steps)
.flat_map(|dz| (-steps..=steps).map(move |dx| (dx, dz)))
.filter(|&(dx, dz)| {
let gap = DVec2::new(dx.unsigned_abs() as f64, dz.unsigned_abs() as f64) - 0.5;
gap.max(DVec2::ZERO).length() < reach
})
.collect();
let mut probed: Vec<Vec<f64>> = Vec::with_capacity(column_count);
for row in 0..config.height {
for column in 0..config.width {
let mut floors = Vec::new();
for floor in probe(config.cell_center(column, row)) {
if !floor.y.is_finite() || !floor.normal_y.is_finite() {
return Err(SpanGridError::InvalidFloor);
}
if floor.headroom_clear && floor.normal_y >= agent.min_floor_normal_y {
floors.push(floor.y);
}
}
floors.sort_by(f64::total_cmp);
probed.push(floors);
}
}
let mut column_start = Vec::with_capacity(column_count + 1);
let mut floors = Vec::new();
for row in 0..config.height {
for column in 0..config.width {
column_start.push(floors.len());
for &y in &probed[row * config.width + column] {
let clear = offsets.iter().all(|&(dx, dz)| {
let (Some(x), Some(z)) = (
column.checked_add_signed(dx).filter(|&x| x < config.width),
row.checked_add_signed(dz).filter(|&z| z < config.height),
) else {
return false;
};
probed[z * config.width + x]
.iter()
.any(|&other| (other - y).abs() <= agent.max_climb_m)
});
if clear {
floors.push(y);
}
}
}
}
column_start.push(floors.len());
Ok(Self {
config,
agent,
column_start,
floors,
})
}
#[must_use]
pub fn config(&self) -> SpanGridConfig {
self.config
}
#[must_use]
pub fn agent(&self) -> NavAgent {
self.agent
}
#[must_use]
pub fn cell_size_m(&self) -> f64 {
self.config.cell_size_m
}
#[must_use]
pub fn span_count(&self) -> usize {
self.floors.len()
}
#[must_use]
pub fn floors_at(&self, position: DVec3) -> &[f64] {
self.column_at(position)
.map_or(&[], |column| &self.floors[self.spans_of(column)])
}
pub fn plan(
&self,
start_world_position: DVec3,
goal_world_position: DVec3,
) -> Result<GroundRoute, GroundRouteError> {
let from = self.span_at(start_world_position)?;
let to = self.span_at(goal_world_position)?;
let (Some(from), Some(to)) = (from, to) else {
return Err(GroundRouteError::NoRoute);
};
let target = self.feet_of(to);
let mut reached: BTreeMap<SpanId, (f64, SpanId)> = BTreeMap::from([(from, (0.0, from))]);
let mut open = BinaryHeap::from([Open {
estimate: self.feet_of(from).distance(target),
span: from,
}]);
while let Some(Open { span, .. }) = open.pop() {
if span == to {
let mut waypoints = Vec::new();
let mut at = to;
while at != from {
waypoints.push(self.feet_of(at));
at = reached[&at].1;
}
waypoints.reverse();
return Ok(GroundRoute { waypoints });
}
let here = self.feet_of(span);
let so_far = reached[&span].0;
for next in self.neighbours(span) {
let there = self.feet_of(next);
let through = so_far + here.distance(there);
if reached.get(&next).is_none_or(|&(cost, _)| through < cost) {
reached.insert(next, (through, span));
open.push(Open {
estimate: through + there.distance(target),
span: next,
});
}
}
}
Err(GroundRouteError::NoRoute)
}
pub fn reachable_within(
&self,
start_world_position: DVec3,
max_steps: usize,
) -> Result<Vec<(DVec3, usize)>, GroundRouteError> {
let from = self
.span_at(start_world_position)?
.ok_or(GroundRouteError::NoRoute)?;
let mut steps = BTreeMap::from([(from, 0)]);
let mut frontier = VecDeque::from([from]);
let mut reached = Vec::new();
while let Some(span) = frontier.pop_front() {
let here = steps[&span];
reached.push((self.feet_of(span), here));
if here == max_steps {
continue;
}
for next in self.neighbours(span) {
steps.entry(next).or_insert_with(|| {
frontier.push_back(next);
here + 1
});
}
}
Ok(reached)
}
fn column_at(&self, position: DVec3) -> Option<usize> {
let local =
(DVec2::new(position.x, position.z) - self.config.origin) / self.config.cell_size_m;
if !local.is_finite() || local.x < 0.0 || local.y < 0.0 {
return None;
}
let (column, row) = (local.x.floor(), local.y.floor());
if column >= self.config.width as f64 || row >= self.config.height as f64 {
return None;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Some(row as usize * self.config.width + column as usize)
}
fn span_at(&self, position: DVec3) -> Result<Option<SpanId>, GroundRouteError> {
if !position.is_finite() {
return Err(GroundRouteError::InvalidWorldPosition);
}
let column = self
.column_at(position)
.ok_or(GroundRouteError::OutsideGrid)?;
Ok(self
.spans_of(column)
.rev()
.find(|&span| (position.y - self.floors[span]).abs() <= self.agent.max_climb_m))
}
fn spans_of(&self, column: usize) -> std::ops::Range<SpanId> {
self.column_start[column]..self.column_start[column + 1]
}
fn column_of(&self, span: SpanId) -> usize {
self.column_start.partition_point(|&start| start <= span) - 1
}
fn feet_of(&self, span: SpanId) -> DVec3 {
let column = self.column_of(span);
let at = self
.config
.cell_center(column % self.config.width, column / self.config.width);
DVec3::new(at.x, self.floors[span], at.y)
}
fn neighbours(&self, span: SpanId) -> Vec<SpanId> {
let column = self.column_of(span);
let (x, z) = (column % self.config.width, column / self.config.width);
let y = self.floors[span];
let step = |dx: isize, dz: isize| -> Vec<SpanId> {
let (Some(nx), Some(nz)) = (
x.checked_add_signed(dx).filter(|&v| v < self.config.width),
z.checked_add_signed(dz).filter(|&v| v < self.config.height),
) else {
return Vec::new();
};
self.spans_of(nz * self.config.width + nx)
.filter(|&other| (self.floors[other] - y).abs() <= self.agent.max_climb_m)
.collect()
};
let mut out = Vec::new();
for (dx, dz) in [(0, 1), (1, 0), (0, -1), (-1, 0)] {
out.extend(step(dx, dz));
}
for (dx, dz) in [(1, 1), (1, -1), (-1, -1), (-1, 1)] {
if !step(dx, 0).is_empty() && !step(0, dz).is_empty() {
out.extend(step(dx, dz));
}
}
out
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Open {
estimate: f64,
span: SpanId,
}
impl Eq for Open {}
impl Ord for Open {
fn cmp(&self, other: &Self) -> Ordering {
other
.estimate
.total_cmp(&self.estimate)
.then_with(|| other.span.cmp(&self.span))
}
}
impl PartialOrd for Open {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(test)]
#[path = "spans/tests.rs"]
mod tests;