Skip to main content

sim_components/
collision.rs

1//! Obstacles of the config and the clearance the machine keeps from them: along a path before it runs (`check_path`,
2//! `check_cycle`), and in the simulation as it runs (`Sim`). The machine tells which of its parts can hit an obstacle
3//! (`Machine::collision_bodies`, `collision_capsules`); obstacles are boxes along the scene's axes, the parts boxes too
4//! or, slanted, capsules.
5
6use crate::conveyor::Conveyor;
7use sim_core::{Aabb, Capsule, Config, ConfigError, Machine, MachineEntry, Obstacle};
8
9/// An obstacle's contact stiffness and damping where its entry gives none (effects.crash): [estimate] a fixture of
10/// steel profile on a machine bed, some 10 N/um at the point of contact, damped near critically for a few kilograms
11/// (2 sqrt(k m) = 2 sqrt(1e7 * 2.5) = 1e4 N s/m). [bounds] 1e6 to 1e8 N/m: from an aluminium profile on a slender
12/// stand to a solid steel block.
13pub const CONTACT_STIFFNESS: f64 = 1e7;
14pub const CONTACT_DAMPING: f64 = 1e4;
15
16/// The obstacles of the config: `obstacles`, a list of tables each with a `name`, the box's `centre_m` and `size_m`
17/// (three numbers each, in scene coordinates; the sizes above 0), and optionally its contact `stiffness_n_m` (above 0)
18/// and `damping_n_s_m` (not negative), by default `CONTACT_STIFFNESS` and `CONTACT_DAMPING`. A config without the
19/// list has none.
20pub fn obstacles(cfg: &Config) -> Result<Vec<Obstacle>, ConfigError> {
21    let Ok(list) = cfg.get("obstacles") else { return Ok(Vec::new()) };
22    let list = list.as_array().ok_or_else(|| ConfigError::Type("obstacles".into()))?;
23    list.iter()
24        .enumerate()
25        .map(|(i, item)| {
26            let bad = || ConfigError::Invalid(format!("obstacles[{i}]"));
27            let three = |key: &str| -> Option<[f64; 3]> {
28                let values: Vec<f64> = item
29                    .get(key)?
30                    .as_array()?
31                    .iter()
32                    .map(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64)))
33                    .collect::<Option<_>>()?;
34                values.try_into().ok().filter(|v: &[f64; 3]| v.iter().all(|x| x.is_finite()))
35            };
36            // A misspelt key in an entry would otherwise pass silently, as `Config::check_keys` leaves arrays out.
37            let keys = ["name", "centre_m", "size_m", "stiffness_n_m", "damping_n_s_m"];
38            if item.as_table().is_none_or(|t| t.keys().any(|k| !keys.contains(&k.as_str()))) {
39                return Err(bad());
40            }
41            let name = item.get("name").and_then(|n| n.as_str()).ok_or_else(bad)?;
42            let centre = three("centre_m").ok_or_else(bad)?;
43            let size = three("size_m").filter(|s| s.iter().all(|x| *x > 0.0)).ok_or_else(bad)?;
44            let number = |key: &str, default: f64| match item.get(key) {
45                None => Some(default),
46                Some(v) => v.as_float().or_else(|| v.as_integer().map(|i| i as f64)).filter(|x| x.is_finite()),
47            };
48            let stiffness = number("stiffness_n_m", CONTACT_STIFFNESS).filter(|k| *k > 0.0).ok_or_else(bad)?;
49            let damping = number("damping_n_s_m", CONTACT_DAMPING).filter(|c| *c >= 0.0).ok_or_else(bad)?;
50            Ok(Obstacle { name: name.into(), aabb: Aabb { centre, size }, contact: false, stiffness, damping })
51        })
52        .collect()
53}
54
55/// The parts of a machine that can hit an obstacle at a state: its boxes and its capsules.
56#[derive(Debug, Clone, Default, PartialEq)]
57pub struct Bodies {
58    pub boxes: Vec<Aabb>,
59    pub capsules: Vec<Capsule>,
60}
61
62impl Bodies {
63    pub fn of(machine: &dyn Machine, state: &[f64]) -> Self {
64        Self { boxes: machine.collision_bodies(state), capsules: machine.collision_capsules(state) }
65    }
66
67    /// The nearest points and the clearance (`Aabb::gap`, `Capsule::gap`) of the part nearest to the box `other`;
68    /// `None` without parts.
69    pub fn gap(&self, other: &Aabb) -> Option<([f64; 3], [f64; 3], f64)> {
70        let boxes = self.boxes.iter().map(|b| b.gap(other));
71        boxes.chain(self.capsules.iter().map(|c| c.gap(other))).min_by(|a, b| a.2.total_cmp(&b.2))
72    }
73}
74
75/// The least clearance between the parts `bodies` and the obstacles: which obstacle, the nearest points and the
76/// clearance (negative in an overlap). `None` without parts or obstacles.
77pub fn nearest(bodies: &Bodies, obstacles: &[Obstacle]) -> Option<(usize, ([f64; 3], [f64; 3], f64))> {
78    obstacles
79        .iter()
80        .enumerate()
81        .filter_map(|(k, o)| Some((k, bodies.gap(&o.aabb)?)))
82        .min_by(|a, b| a.1.2.total_cmp(&b.1.2))
83}
84
85/// One of the machine's own parts, by its place among `Machine::collision_bodies` (a box) or
86/// `Machine::self_collision_capsules` (a capsule), counted from 0.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
88pub enum Body {
89    Box(usize),
90    Capsule(usize),
91}
92
93/// The least clearance between two of the machine's own parts that are not joined along a path: m (negative in an
94/// overlap), the two parts, and the first pose at it.
95#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
96pub struct SelfClearance {
97    pub clearance: f64,
98    pub bodies: [Body; 2],
99    pub pose: Vec<f64>,
100}
101
102/// Which pairs of parts are joined (not checked) for a pose with `counts` boxes and capsules: `joined[i * n + j]`.
103#[derive(Debug, Clone, PartialEq)]
104struct Joined {
105    counts: (usize, usize),
106    joined: Vec<bool>,
107    /// Whether any pair is left to check.
108    open: bool,
109}
110
111/// What a path keeps from the obstacles before it runs: the least clearance along it (m, infinite without obstacles),
112/// the first pose at which a part of the machine touches one (clearance 0 or less), and the first pose at the least
113/// clearance (`None` without obstacles). `own` is the least clearance between the machine's own parts that are not
114/// joined (`Machine::connected_bodies`), a figure apart from the obstacles'; `None` where nothing was checked (fewer
115/// than two parts, or all of them joined), which is not the same as clear.
116#[derive(Debug, Clone, PartialEq)]
117pub struct PlanCheck {
118    pub clearance: f64,
119    pub contact: Option<Vec<f64>>,
120    pub nearest: Option<Vec<f64>>,
121    pub own: Option<SelfClearance>,
122    /// Parts closer than this at the start pose are taken as joined where the machine does not say
123    /// (`profile.min_clearance_m`).
124    join_below: f64,
125    /// The joined pairs for each number of boxes and capsules: those of the start pose (`at_start`), or of the first
126    /// pose seen with that number.
127    joins: Vec<Joined>,
128}
129
130impl Default for PlanCheck {
131    fn default() -> Self {
132        Self { clearance: f64::INFINITY, contact: None, nearest: None, own: None, join_below: 0.0, joins: Vec::new() }
133    }
134}
135
136impl PlanCheck {
137    /// A check that takes parts of the machine closer than `clearance` at the first pose as joined.
138    pub fn keeping(clearance: f64) -> Self {
139        Self { join_below: clearance, ..Self::default() }
140    }
141
142    /// `keeping`, with the parts joined as they are at the machine's start pose, whatever pose a path starts from:
143    /// `state` is `machine`'s there with the payload on (as the controller starts). Where the machine names its joined
144    /// pairs (`Machine::connected_bodies`) that is all; where the rule joins them by their distance, and some pair is
145    /// left to check, also with the payload off, on a machine of its own that `detached` builds (switching the payload
146    /// may leave more in a machine: a crane books a pick), at the start pose `start`.
147    pub fn at_start(
148        clearance: f64,
149        machine: &dyn Machine,
150        state: &[f64],
151        start: &[f64],
152        detached: impl FnOnce() -> Result<Box<dyn Machine>, ConfigError>,
153    ) -> Result<Self, ConfigError> {
154        let mut check = Self::keeping(clearance);
155        if !check.join_at(machine, state) && check.has_pairs() {
156            let mut other = detached()?;
157            other.set_payload_attached(false);
158            let (mut state, mut torque) = (Vec::new(), vec![0.0; other.motors().len()]);
159            other.equilibrium(start, &mut state, &mut torque);
160            check.join_at(other.as_ref(), &state);
161        }
162        Ok(check)
163    }
164
165    /// The joined pairs of `machine`'s parts at `state`; whether the machine named them.
166    fn join_at(&mut self, machine: &dyn Machine, state: &[f64]) -> bool {
167        let (boxes, capsules) = (machine.collision_bodies(state), machine.self_collision_capsules(state));
168        let named = machine.connected_bodies(state, boxes.len(), capsules.len());
169        let is_named = named.is_some();
170        self.joins_for(&boxes, &capsules, || named);
171        is_named
172    }
173
174    /// A check with the same joined pairs and nothing seen yet.
175    pub fn anew(&self) -> Self {
176        Self { join_below: self.join_below, joins: self.joins.clone(), ..Self::default() }
177    }
178
179    /// Whether the machine has two parts not joined to check, as far as the start pose tells (`at_start`).
180    pub fn has_pairs(&self) -> bool {
181        self.joins.iter().any(|j| j.open)
182    }
183
184    /// The joined pairs for parts of these numbers, found now where none are known for them.
185    fn joins_for(
186        &mut self,
187        boxes: &[Aabb],
188        capsules: &[Capsule],
189        connected: impl FnOnce() -> Option<Vec<(usize, usize)>>,
190    ) -> &Joined {
191        let counts = (boxes.len(), capsules.len());
192        let k = match self.joins.iter().position(|j| j.counts == counts) {
193            Some(k) => k,
194            None => {
195                self.joins.push(joined(connected(), boxes, capsules, self.join_below));
196                self.joins.len() - 1
197            }
198        };
199        &self.joins[k]
200    }
201
202    /// Whether the machine's own parts came nearer than `limit` (`profile.min_clearance_m`) or touched: as the check
203    /// "collision" judges the obstacles, a contact fails whatever the limit. Not checked is not failed.
204    pub fn own_fails(&self, limit: f64) -> bool {
205        self.own.as_ref().is_some_and(|own| own.clearance < limit || own.clearance <= 0.0)
206    }
207
208    /// The machine's own parts at `state` (its boxes `boxes`): the least clearance of the pairs not joined, if it is
209    /// below the least so far. Linear in the samples: a lower bound from the parts' extents spares most pairs, and no
210    /// pair allocates.
211    pub(crate) fn look_at_own(&mut self, machine: &dyn Machine, state: &[f64], boxes: &[Aabb], pose: &[f64]) {
212        let capsules = machine.self_collision_capsules(state);
213        let connected = || machine.connected_bodies(state, boxes.len(), capsules.len());
214        self.look_at_parts(boxes, &capsules, connected, pose);
215    }
216
217    /// `look_at_own` for parts given: `connected` tells the joined pairs of these parts where the machine knows them
218    /// (`Machine::connected_bodies`), asked once for each number of boxes and capsules that `at_start` did not see.
219    pub fn look_at_parts(
220        &mut self,
221        boxes: &[Aabb],
222        capsules: &[Capsule],
223        connected: impl FnOnce() -> Option<Vec<(usize, usize)>>,
224        pose: &[f64],
225    ) {
226        let n = boxes.len() + capsules.len();
227        if n < 2 {
228            return;
229        }
230        let mut best = self.own.as_ref().map_or(f64::INFINITY, |own| own.clearance);
231        let joins = self.joins_for(boxes, capsules, connected);
232        if !joins.open {
233            return;
234        }
235        let mut found = None;
236        for i in 0..n {
237            for j in i + 1..n {
238                if joins.joined[i * n + j] {
239                    continue;
240                }
241                let (a, b) = (part(boxes, capsules, i), part(boxes, capsules, j));
242                let bound = a.lower_bound(&b);
243                // Extents that overlap say nothing about the parts: only apart ones can be spared.
244                if bound > 0.0 && bound >= best {
245                    continue;
246                }
247                let gap = a.gap(&b);
248                if gap < best {
249                    (best, found) = (gap, Some((i, j)));
250                }
251            }
252        }
253        if let Some((i, j)) = found {
254            let body = |k: usize| if k < boxes.len() { Body::Box(k) } else { Body::Capsule(k - boxes.len()) };
255            self.own = Some(SelfClearance { clearance: best, bodies: [body(i), body(j)], pose: pose.to_vec() });
256        }
257    }
258}
259
260/// A part of the machine as a box or a capsule.
261#[derive(Clone, Copy)]
262enum Part<'a> {
263    Box(&'a Aabb),
264    Capsule(&'a Capsule),
265}
266
267fn part<'a>(boxes: &'a [Aabb], capsules: &'a [Capsule], i: usize) -> Part<'a> {
268    if i < boxes.len() { Part::Box(&boxes[i]) } else { Part::Capsule(&capsules[i - boxes.len()]) }
269}
270
271impl Part<'_> {
272    fn extent(&self) -> ([f64; 3], [f64; 3]) {
273        match self {
274            Part::Box(b) => b.extent(),
275            Part::Capsule(c) => c.extent(),
276        }
277    }
278
279    /// The distance of the two parts' extents: no more than their clearance where they are apart.
280    fn lower_bound(&self, other: &Part) -> f64 {
281        let ((lo, hi), (other_lo, other_hi)) = (self.extent(), other.extent());
282        (0..3).map(|i| (lo[i] - other_hi[i]).max(other_lo[i] - hi[i]).max(0.0).powi(2)).sum::<f64>().sqrt()
283    }
284
285    fn gap(&self, other: &Part) -> f64 {
286        match (self, other) {
287            (Part::Box(a), Part::Box(b)) => a.gap(b).2,
288            (Part::Capsule(c), Part::Box(b)) | (Part::Box(b), Part::Capsule(c)) => c.gap(b).2,
289            (Part::Capsule(a), Part::Capsule(b)) => a.gap_capsule(b),
290        }
291    }
292}
293
294/// How near two parts are to count as touching when they are joined (`joined`): faces drawn at the same place miss
295/// each other by rounding (a slide's payload on its carriage stands 7e-18 m off it), and a pair so joined by chance
296/// would be judged on that noise.
297const TOUCHING: f64 = 1e-9;
298
299/// The pairs of parts not to check against each other: those the machine names (`Machine::connected_bodies`), or else
300/// those that touch, overlap or lie closer than `below` to each other now.
301fn joined(named: Option<Vec<(usize, usize)>>, boxes: &[Aabb], capsules: &[Capsule], below: f64) -> Joined {
302    let n = boxes.len() + capsules.len();
303    let mut joined = vec![false; n * n];
304    match named {
305        Some(pairs) => {
306            for (i, j) in pairs.into_iter().filter(|(i, j)| *i < n && *j < n) {
307                (joined[i * n + j], joined[j * n + i]) = (true, true);
308            }
309        }
310        None => {
311            for i in 0..n {
312                for j in i + 1..n {
313                    let gap = part(boxes, capsules, i).gap(&part(boxes, capsules, j));
314                    let together = gap < below || gap <= TOUCHING;
315                    (joined[i * n + j], joined[j * n + i]) = (together, together);
316                }
317            }
318        }
319    }
320    let open = (0..n).any(|i| (i + 1..n).any(|j| !joined[i * n + j]));
321    Joined { counts: (boxes.len(), capsules.len()), joined, open }
322}
323
324/// Adds the path through `poses` to `check`: straight from pose to pose, looked at every millimetre (every
325/// thousandth of an axis unit) or closer, the machine at rest at each pose with the payload as it is set.
326pub fn check_path(machine: &dyn Machine, obstacles: &[Obstacle], poses: &[Vec<f64>], check: &mut PlanCheck) {
327    let (mut state, mut torque) = (Vec::new(), vec![0.0; machine.motors().len()]);
328    let mut at = |pose: &[f64]| {
329        machine.equilibrium(pose, &mut state, &mut torque);
330        let bodies = Bodies::of(machine, &state);
331        let gap = nearest(&bodies, obstacles).map_or(f64::INFINITY, |(_, (_, _, gap))| gap);
332        check.look_at_own(machine, &state, &bodies.boxes, pose);
333        if gap < check.clearance {
334            (check.clearance, check.nearest) = (gap, Some(pose.to_vec()));
335        }
336        if gap <= 0.0 && check.contact.is_none() {
337            check.contact = Some(pose.to_vec());
338        }
339    };
340    if let Some(first) = poses.first() {
341        at(first);
342    }
343    for pair in poses.windows(2) {
344        let length = pair[0].iter().zip(&pair[1]).map(|(a, b)| (b - a).powi(2)).sum::<f64>().sqrt();
345        let pieces = (length / 1e-3).ceil().max(1.0) as usize;
346        for k in 1..=pieces {
347            let f = k as f64 / pieces as f64;
348            let pose: Vec<f64> = pair[0].iter().zip(&pair[1]).map(|(a, b)| a + f * (b - a)).collect();
349            at(&pose);
350        }
351    }
352}
353
354/// The passes of a conveyor cycle checked as `check_path` does, before they run: planned as the controller plans them
355/// (`Conveyor::plan`, without input shaping) from `start` at time 0, each from where the one before ends, for two
356/// pitches' worth of parts (all parts of a pitch, twice, so that a pass from the start and one from the place are both
357/// there), the payload as the pass holds it. The path between samples 5 ms apart is taken as a line.
358fn check_passes(
359    machine: &mut dyn Machine,
360    obstacles: &[Obstacle],
361    conveyor: &mut Conveyor,
362    start: &[f64],
363    mut check: PlanCheck,
364) -> PlanCheck {
365    let axes = machine.axes().to_vec();
366    let reachable = |pose: &[f64]| crate::control::in_range(&*machine, pose);
367    let mut passes = Vec::new();
368    let (mut now, mut from) = (0.0, start.to_vec());
369    let none = (vec![0.0; axes.len()], 0.0);
370    while passes.len() < 2 * conveyor.arrivals.len()
371        && let Some(pass) = conveyor.plan(&axes, now, &from, &reachable, &none)
372    {
373        let n = from.len();
374        let (mut pos, mut vel, mut acc) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
375        pass.at(pass.duration(), &mut pos, &mut vel, &mut acc);
376        (now, from) = (pass.start + pass.duration(), pos);
377        passes.push(pass);
378    }
379    check_path(machine, obstacles, std::slice::from_ref(&start.to_vec()), &mut check);
380    for pass in &passes {
381        let samples = (pass.duration() / 0.005).ceil().max(1.0) as usize;
382        let n = start.len();
383        let (mut pos, mut vel, mut acc) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
384        let mut last: Option<Vec<f64>> = None;
385        for i in 0..=samples {
386            let t = pass.duration() * i as f64 / samples as f64;
387            pass.at(t, &mut pos, &mut vel, &mut acc);
388            machine.set_payload_attached(pass.holds(t));
389            if let Some(last) = &last {
390                check_path(machine, obstacles, &[last.clone(), pos.clone()], &mut check);
391            }
392            last = Some(pos.clone());
393        }
394    }
395    check
396}
397
398/// The configured cycle checked as `check_path` does, before it runs: from the start pose to the first segment's
399/// target with the payload attached (as the controller starts), then each segment from the target before it with the
400/// payload as that one left it, and round from the last to the first again. A segment with via points takes the path
401/// the planner times through them; the straight moves are taken as lines, which corner blending would cut short (the
402/// simulation itself is checked as it runs). The machine's own parts are checked against each other along the way
403/// (`PlanCheck::own`, with `profile.min_clearance_m` as the distance under which parts at the start pose are joined,
404/// `PlanCheck::at_start`).
405/// `None` without obstacles where the machine has no two parts to check (or the cycle cannot be read: then it is
406/// not checked, where with obstacles it is an error). With `[conveyor]` the passes are checked instead
407/// (`check_passes`).
408pub fn check_cycle(entry: &MachineEntry, cfg: &Config) -> Result<Option<PlanCheck>, ConfigError> {
409    let cfg = &crate::catalog::resolve(entry, cfg)?;
410    let obstacles = obstacles(cfg)?;
411    match cycle_check(entry, cfg, &obstacles) {
412        Ok(check) => Ok((!obstacles.is_empty() || check.own.is_some()).then_some(check)),
413        Err(_) if obstacles.is_empty() => Ok(None),
414        Err(e) => Err(e),
415    }
416}
417
418fn cycle_check(entry: &MachineEntry, cfg: &Config, obstacles: &[Obstacle]) -> Result<PlanCheck, ConfigError> {
419    let mut machine = (entry.build)(cfg)?;
420    let start = crate::sim::start_pose(cfg, machine.as_ref())?;
421    let (mut state, mut torque) = (Vec::new(), vec![0.0; machine.motors().len()]);
422    machine.set_payload_attached(true);
423    machine.equilibrium(&start, &mut state, &mut torque);
424    let clearance = cfg.non_negative("profile.min_clearance_m")?;
425    let mut check = PlanCheck::at_start(clearance, machine.as_ref(), &state, &start, || (entry.build)(cfg))?;
426    if obstacles.is_empty() && !check.has_pairs() {
427        return Ok(PlanCheck::default());
428    }
429    if let Some(mut conveyor) = crate::conveyor::Conveyor::from_config(cfg, machine.axes().len())? {
430        return Ok(check_passes(machine.as_mut(), obstacles, &mut conveyor, &start, check));
431    }
432    let (cycle, tolerance) = (
433        cfg.positive("profile.cycle_s")?,
434        crate::path::Tolerance {
435            path: cfg.non_negative("profile.path_tolerance_m")?,
436            corner: cfg.non_negative("profile.corner_tolerance_m")?,
437        },
438    );
439    let number = |v: &toml::Value| v.as_float().or_else(|| v.as_integer().map(|i| i as f64));
440    let mut segments = Vec::new();
441    for (i, segment) in cfg.array("cycle.segment")?.iter().enumerate() {
442        let bad = || ConfigError::Invalid(format!("cycle.segment[{i}]"));
443        let target: Vec<f64> =
444            segment.get("target").and_then(|t| t.as_array()).ok_or_else(bad)?.iter().filter_map(number).collect();
445        let payload = segment.get("payload").and_then(|p| p.as_bool()).ok_or_else(bad)?;
446        let via: Option<Vec<Vec<f64>>> = match segment.get("via") {
447            None => None,
448            Some(points) => Some(
449                points
450                    .as_array()
451                    .ok_or_else(bad)?
452                    .iter()
453                    .map(|p| p.as_array().map(|p| p.iter().filter_map(number).collect()))
454                    .collect::<Option<_>>()
455                    .ok_or_else(bad)?,
456            ),
457        };
458        // With `corners_m`: lines through the via points, their corners rounded within it (`control::lines_through`).
459        let corner = segment.get("corners_m").and_then(number);
460        segments.push((target, payload, via.map(|v| (v, corner)), i));
461    }
462    check_path(machine.as_ref(), obstacles, std::slice::from_ref(&start), &mut check);
463    let n = segments.len();
464    // Leg k ends at segment k; leg n is the way round from the last segment to the first.
465    for k in (0..=n).filter(|_| n > 0) {
466        let (from, payload) =
467            if k == 0 { (start.clone(), true) } else { (segments[k - 1].0.clone(), segments[k - 1].1) };
468        let (target, _, via, i) = &segments[k % n];
469        machine.set_payload_attached(payload);
470        let poses = match via {
471            None => vec![from, target.clone()],
472            Some((points, corner)) => {
473                let pieces = match corner {
474                    Some(_) => crate::control::lines_through(points, target),
475                    None => crate::control::via_pieces(points, target),
476                };
477                let tolerance = crate::path::Tolerance { corner: corner.unwrap_or(tolerance.corner), ..tolerance };
478                let planned =
479                    crate::path::plan(machine.axes(), &from, &pieces, cycle, tolerance, crate::path::ARC_SLACK)
480                        .map_err(|_| ConfigError::Invalid(format!("cycle.segment[{i}].via")))?;
481                std::iter::once(from).chain(planned.into_iter().map(|(_, pose)| pose)).collect()
482            }
483        };
484        check_path(machine.as_ref(), obstacles, &poses, &mut check);
485    }
486    Ok(check)
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492
493    fn cube(x: f64) -> Aabb {
494        Aabb { centre: [x, 0.0, 0.0], size: [0.1; 3] }
495    }
496
497    /// Two 0.1 m cubes, the second first 0.2 m clear of the first (x = 0.3: faces at 0.05 and 0.25) and then at
498    /// x = 0.103 (faces at 0.05 and 0.053): 3 mm apart. With 5 mm kept the 3 mm fails and names both boxes, the 0.2 m
499    /// before it does not; with 2 mm kept the 3 mm passes. Fails if the pair is not looked at, or is judged without the
500    /// limit.
501    #[test]
502    fn two_boxes_3_mm_apart_fail_a_clearance_of_5_mm_and_name_both() {
503        let mut check = PlanCheck::keeping(0.005);
504        check.look_at_parts(&[cube(0.0), cube(0.3)], &[], || None, &[0.3]);
505        let own = check.own.clone().unwrap();
506        assert!((own.clearance - 0.2).abs() < 1e-12 && !check.own_fails(0.005), "{own:?}");
507        check.look_at_parts(&[cube(0.0), cube(0.103)], &[], || None, &[0.103]);
508        let own = check.own.clone().unwrap();
509        assert!((own.clearance - 0.003).abs() < 1e-12, "{own:?}");
510        assert_eq!((own.bodies, own.pose), ([Body::Box(0), Body::Box(1)], vec![0.103]));
511        assert!(check.own_fails(0.005) && !check.own_fails(0.002));
512    }
513
514    /// The same two cubes but named as joined: nothing is left to check, which says "not checked", not "clear".
515    #[test]
516    fn joined_parts_are_skipped_and_leave_the_check_not_made() {
517        let mut check = PlanCheck::keeping(0.005);
518        check.look_at_parts(&[cube(0.0), cube(0.3)], &[], || Some(vec![(1, 0)]), &[0.3]);
519        check.look_at_parts(&[cube(0.0), cube(0.103)], &[], || panic!("asked again for the same parts"), &[0.1]);
520        assert_eq!(check.own, None);
521        assert!(!check.own_fails(0.005));
522    }
523
524    /// One part, none, or a part and nothing else: not checked, whatever the pose.
525    #[test]
526    fn fewer_than_two_parts_are_not_checked() {
527        let mut check = PlanCheck::keeping(0.005);
528        check.look_at_parts(&[cube(0.0)], &[], || None, &[0.0]);
529        check.look_at_parts(&[], &[], || None, &[0.0]);
530        assert_eq!(check.own, None);
531    }
532
533    /// Without a say of the machine, parts that touch or lie closer than the clearance at the first pose are joined: two
534    /// cubes 3 mm apart from the start are not reported at 3 mm (the rule cannot see them). Fails if the first pose
535    /// does not join.
536    #[test]
537    fn parts_in_contact_at_the_first_pose_are_taken_as_joined() {
538        let mut check = PlanCheck::keeping(0.005);
539        check.look_at_parts(&[cube(0.0), cube(0.103)], &[], || None, &[0.0]);
540        check.look_at_parts(&[cube(0.0), cube(0.101)], &[], || None, &[1.0]);
541        assert_eq!(check.own, None);
542        // Overlapping ones join with no clearance asked for as well.
543        let mut check = PlanCheck::default();
544        check.look_at_parts(&[cube(0.0), cube(0.05)], &[], || None, &[0.0]);
545        assert_eq!(check.own, None);
546    }
547
548    /// A capsule along x from the origin to (1, 0, 0), radius 0.01, and one along y through x = 0.5 at height 0.05,
549    /// radius 0.02: the segments cross 0.05 m apart in z, so the clearance is 0.05 - 0.01 - 0.02 = 0.02. A 0.1 m cube at
550    /// (0.5, 0.5, 0.5) has its lowest face at z = 0.45: 0.45 - 0.01 = 0.44 m from the first capsule and 0.4 - 0.02 =
551    /// 0.38 m from the second, so the capsules are the nearest pair.
552    #[test]
553    fn capsules_and_boxes_are_judged_by_their_surfaces() {
554        let along_x = Capsule { from: [0.0; 3], to: [1.0, 0.0, 0.0], radius: 0.01 };
555        let along_y = Capsule { from: [0.5, -1.0, 0.05], to: [0.5, 1.0, 0.05], radius: 0.02 };
556        let high = Aabb { centre: [0.5, 0.5, 0.5], size: [0.1; 3] };
557        let mut check = PlanCheck::default();
558        check.look_at_parts(&[high], &[along_x, along_y], || Some(Vec::new()), &[0.0]);
559        let own = check.own.unwrap();
560        assert!((own.clearance - 0.02).abs() < 1e-12, "{own:?}");
561        assert_eq!(own.bodies, [Body::Capsule(0), Body::Capsule(1)]);
562    }
563}