use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap};
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Reverse;
use heuristic_search::{Budget, Stats};
use super::collision::CollisionSet;
use super::context::{Context, LimitReached};
use super::state::{Choice, JointState, Key, collide};
use crate::graph::Graph;
use crate::instance::AgentId;
#[derive(Debug, Clone)]
struct Node {
key: Key,
h: u32,
collision: CollisionSet,
version: u32,
back: BTreeSet<usize>,
query: u32,
g: u32,
parent: Option<usize>,
expanded_at: Option<(u32, u32)>,
}
type Entry = Reverse<(u32, Reverse<u32>, u64, usize)>;
#[derive(Debug, Clone)]
pub(super) struct Planner {
agents: Vec<AgentId>,
nodes: Vec<Node>,
index: BTreeMap<Key, usize>,
open: BinaryHeap<Entry>,
query: u32,
pushes: u64,
forward: BTreeMap<Key, Option<(Key, u32)>>,
}
impl Planner {
pub(super) fn new(agents: Vec<AgentId>) -> Self {
Self {
agents,
nodes: Vec::new(),
index: BTreeMap::new(),
open: BinaryHeap::new(),
query: 0,
pushes: 0,
forward: BTreeMap::new(),
}
}
pub(super) fn policy<G: Graph>(
&mut self,
cx: &mut Context<'_, G>,
key: Key,
budget: &mut impl Budget<Stats>,
) -> Result<Option<Key>, LimitReached> {
if let Some(next) = self.forward.get(&key) {
return Ok(next.as_ref().map(|(next, _)| next.clone()));
}
let Some(path) = self.search(cx, key.clone(), budget)? else {
self.forward.insert(key, None);
return Ok(None);
};
Ok(path.get(1).cloned())
}
fn exact(&self, key: &Key) -> Option<u32> {
if key.is_goal() {
return Some(0);
}
self.forward.get(key)?.as_ref().map(|&(_, cost)| cost)
}
fn finish(&mut self, id: usize, rest: u32) -> Vec<Key> {
let chain: Vec<usize> = core::iter::successors(Some(id), |&id| self.nodes[id].parent)
.filter(|&id| self.nodes[id].key.is_standard())
.collect();
let total = self.nodes[id].g + rest;
for pair in chain.windows(2) {
let (next, here) = (pair[0], pair[1]);
let to_go = total - self.nodes[here].g;
let entry = (self.nodes[next].key.clone(), to_go);
self.forward
.insert(self.nodes[here].key.clone(), Some(entry));
self.nodes[here].h = to_go;
}
let mut path: Vec<Key> = chain
.iter()
.rev()
.map(|&id| self.nodes[id].key.clone())
.collect();
while let Some(Some((next, _))) = path.last().and_then(|last| self.forward.get(last)) {
path.push(next.clone());
}
path
}
pub(super) fn search<G: Graph>(
&mut self,
cx: &mut Context<'_, G>,
start: Key,
budget: &mut impl Budget<Stats>,
) -> Result<Option<Vec<Key>>, LimitReached> {
self.query += 1;
self.open.clear();
let Some(root) = self.node(cx, start) else {
return Ok(None);
};
self.touch(root);
self.nodes[root].g = 0;
self.push(root);
while let Some(Reverse((_, Reverse(g), _, id))) = self.open.pop() {
if self.is_stale(id, g) {
continue;
}
if let Some(rest) = self.exact(&self.nodes[id].key) {
return Ok(Some(self.finish(id, rest)));
}
if budget.exhausted(&cx.stats) {
return Err(LimitReached);
}
self.expand(cx, id, budget)?;
}
Ok(None)
}
fn is_stale(&self, id: usize, g: u32) -> bool {
let node = &self.nodes[id];
g != node.g || node.expanded_at == Some((node.g, node.version))
}
fn expand<G: Graph>(
&mut self,
cx: &mut Context<'_, G>,
id: usize,
budget: &mut impl Budget<Stats>,
) -> Result<(), LimitReached> {
cx.stats.expanded += 1;
let node = &mut self.nodes[id];
if node.expanded_at.is_some() {
cx.stats.reopened += 1;
}
node.expanded_at = Some((node.g, node.version));
if self.decomposes(cx, id) {
self.expand_one(cx, id);
return Ok(());
}
let Some(options) = self.options(cx, id, budget)? else {
return Ok(());
};
let mut steps = Vec::new();
cartesian(&options, &mut Vec::with_capacity(options.len()), &mut steps);
for step in steps {
self.step(cx, id, &step);
}
Ok(())
}
fn decomposes<G>(&self, cx: &Context<'_, G>, id: usize) -> bool {
let node = &self.nodes[id];
if !node.key.is_standard() {
return true;
}
let groups = node.collision.groups();
cx.decompose
&& if cx.recursive {
groups.iter().any(|group| group.len() == self.agents.len())
} else {
!groups.is_empty()
}
}
fn expand_one<G: Graph>(&mut self, cx: &mut Context<'_, G>, id: usize) {
let key = self.nodes[id].key.clone();
let k = key.moved.len();
let agent = self.agents[k];
let branch = self.nodes[id].collision.contains(agent);
let from = key.base[k];
for choice in cx.choices(from, agent, branch, key.time) {
let colliders: Vec<AgentId> = (0..k)
.filter(|&j| collide((key.base[j].0, key.moved[j].0), (from.0, choice.next)))
.map(|j| self.agents[j])
.collect();
if !colliders.is_empty() {
for other in colliders {
self.pass_back(cx, id, &CollisionSet::of(vec![other, agent]));
}
continue;
}
let mut moved = key.moved.clone();
moved.push(choice.position());
let target = if moved.len() == self.agents.len() {
Key::standard(cx.next_time(key.time), moved)
} else {
Key {
time: key.time,
base: key.base.clone(),
moved,
}
};
self.link(cx, id, target, choice.cost);
}
}
fn options<G: Graph>(
&self,
cx: &mut Context<'_, G>,
id: usize,
budget: &mut impl Budget<Stats>,
) -> Result<Option<Vec<Vec<Choice>>>, LimitReached> {
let node = &self.nodes[id];
let (time, state) = (node.key.time, &node.key.base);
let mut options: Vec<Vec<Choice>> = self
.agents
.iter()
.zip(state)
.map(|(&agent, &at)| {
let branch = !cx.recursive && node.collision.contains(agent);
cx.choices(at, agent, branch, time)
})
.collect();
if !cx.recursive {
return Ok(Some(options));
}
for group in node.collision.groups() {
let locals: Vec<usize> = group.iter().map(|&agent| self.local(agent)).collect();
if group.len() == self.agents.len() {
for (&agent, &local) in group.iter().zip(&locals) {
options[local] = cx.choices(state[local], agent, true, time);
}
continue;
}
let from: JointState = locals.iter().map(|&local| state[local]).collect();
let Some(to) = cx.group_step(group, Key::standard(time, from.clone()), budget)? else {
return Ok(None);
};
for ((&local, &before), &after) in locals.iter().zip(&from).zip(&to.base) {
options[local] = vec![Choice::between(before, after)];
}
}
Ok(Some(options))
}
fn step<G: Graph>(&mut self, cx: &mut Context<'_, G>, id: usize, step: &[Choice]) {
let key = &self.nodes[id].key;
let collisions = self.collisions(&key.base, step);
if !collisions.is_empty() {
for pair in collisions {
self.pass_back(cx, id, &CollisionSet::of(pair));
}
return;
}
let target = Key::standard(
cx.next_time(key.time),
step.iter().map(|c| c.position()).collect(),
);
let cost = step.iter().map(|c| c.cost).sum();
self.link(cx, id, target, cost);
}
fn link<G: Graph>(&mut self, cx: &mut Context<'_, G>, id: usize, target: Key, cost: u32) {
let Some(target) = self.node(cx, target) else {
return;
};
self.nodes[target].back.insert(id);
let inherited = self.nodes[target].collision.clone();
self.pass_back(cx, id, &inherited);
self.touch(target);
let g = self.nodes[id].g + cost;
if g < self.nodes[target].g {
self.nodes[target].g = g;
self.nodes[target].parent = Some(id);
self.push(target);
}
}
fn pass_back<G: Graph>(&mut self, cx: &Context<'_, G>, id: usize, set: &CollisionSet) {
let single = !cx.recursive;
let mut work = vec![(id, set.clone())];
while let Some((id, set)) = work.pop() {
let node = &mut self.nodes[id];
if !node.collision.merge_all(&set, single) {
continue;
}
node.version += 1;
let merged = node.collision.clone();
work.extend(node.back.iter().map(|&back| (back, merged.clone())));
if node.query == self.query && node.g != u32::MAX {
self.push(id);
}
}
}
fn collisions(&self, state: &JointState, step: &[Choice]) -> Vec<Vec<AgentId>> {
let mut pairs = Vec::new();
for (a, choice_a) in step.iter().enumerate() {
for (b, choice_b) in step.iter().enumerate().skip(a + 1) {
if collide((state[a].0, choice_a.next), (state[b].0, choice_b.next)) {
pairs.push(vec![self.agents[a], self.agents[b]]);
}
}
}
pairs
}
fn node<G: Graph>(&mut self, cx: &mut Context<'_, G>, key: Key) -> Option<usize> {
if let Some(&id) = self.index.get(&key) {
return Some(id);
}
let estimate = cx.heuristic(&self.agents, &key)?;
let h = self.exact(&key).unwrap_or(estimate);
let id = self.nodes.len();
cx.stats.generated += 1;
self.index.insert(key.clone(), id);
self.nodes.push(Node {
key,
h,
collision: CollisionSet::default(),
version: 0,
back: BTreeSet::new(),
query: 0,
g: u32::MAX,
parent: None,
expanded_at: None,
});
Some(id)
}
fn touch(&mut self, id: usize) {
let node = &mut self.nodes[id];
if node.query != self.query {
node.query = self.query;
node.g = u32::MAX;
node.parent = None;
node.expanded_at = None;
}
}
fn push(&mut self, id: usize) {
let node = &self.nodes[id];
let key = (node.g + node.h, Reverse(node.g), self.pushes, id);
self.pushes += 1;
self.open.push(Reverse(key));
}
fn local(&self, agent: AgentId) -> usize {
self.agents
.binary_search(&agent)
.expect("collision groups hold the planner's agents")
}
}
fn cartesian(options: &[Vec<Choice>], picked: &mut Vec<Choice>, out: &mut Vec<Vec<Choice>>) {
let Some(choices) = options.get(picked.len()) else {
out.push(picked.clone());
return;
};
for &choice in choices {
picked.push(choice);
cartesian(options, picked, out);
picked.pop();
}
}