use std::cell::Cell;
use crate::kernel::brep::Part;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum RunMode {
#[default]
Unknown,
Strict,
LocallyDegraded,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum EvidenceStatus {
Verified,
#[default]
Unproved,
}
internal_entry! {
pub fn strict_status(part: &Part, defining: &[usize], context: &[usize]) -> EvidenceStatus {
if !defining.is_empty()
&& strict_valid_solid(part, defining.iter().chain(context).copied()).is_some()
{
EvidenceStatus::Verified
} else {
EvidenceStatus::Unproved
}
}
}
fn strict_valid_solid(part: &Part, mut faces: impl Iterator<Item = usize>) -> Option<usize> {
let owner = part.faces.get(faces.next()?)?.solid?;
(part.solid_is_geometrically_valid(owner)
&& faces.all(|f| {
part.faces
.get(f)
.is_some_and(|face| face.solid == Some(owner))
}))
.then_some(owner)
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Occurrence<R> {
pub record: R,
pub defining: Vec<usize>,
pub context: Vec<usize>,
}
impl<R> Occurrence<R> {
pub fn new(record: R, defining: Vec<usize>, context: Vec<usize>) -> Self {
Self {
record,
defining,
context,
}
}
}
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EvidenceError {
NoValidSolid,
SharedEvidence,
AmbiguousProfile,
CompetingCaps,
MissingFloor,
}
impl std::fmt::Display for EvidenceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EvidenceError::NoValidSolid => {
write!(f, "defining face has no unambiguous valid solid")
}
EvidenceError::SharedEvidence => {
write!(f, "evidence faces are shared between occurrences")
}
EvidenceError::AmbiguousProfile => {
write!(f, "turned profile key identifies multiple valid solids")
}
EvidenceError::CompetingCaps => {
write!(f, "multiple obround cap clusters compete for one endpoint")
}
EvidenceError::MissingFloor => write!(f, "pocket floor faces are unavailable"),
}
}
}
impl std::error::Error for EvidenceError {}
thread_local! {
static LOCAL_DEGRADATION: Cell<bool> = const { Cell::new(false) };
}
internal_entry! {
pub fn local_degradation() -> bool {
LOCAL_DEGRADATION.with(Cell::get)
}
}
pub(crate) fn locally_degraded<T>(f: impl FnOnce() -> T) -> T {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
LOCAL_DEGRADATION.with(|mode| mode.set(self.0));
}
}
let _restore = Restore(LOCAL_DEGRADATION.with(|mode| mode.replace(true)));
f()
}
internal_entry! {
pub fn common_valid_solid(part: &Part, faces: &[usize]) -> Option<usize> {
if local_degradation() {
return locally_valid_solid(part, faces);
}
strict_valid_solid(part, faces.iter().copied())
}
}
const MAX_BAD_FACES: usize = 3;
internal_entry! {
pub fn locally_valid_solid(part: &Part, faces: &[usize]) -> Option<usize> {
let owner = part.faces[*faces.first()?].solid?;
if !faces.iter().all(|&f| part.faces[f].solid == Some(owner)) || !part.solid_is_valid(owner) {
return None;
}
let bad = part.bad_faces(owner);
if bad.is_empty() {
return Some(owner);
}
let admitted = bad.len() <= MAX_BAD_FACES
&& part.shell_count(owner) == 1
&& part
.solid_mass(owner)
.is_some_and(|(volume, _)| volume > 0.0);
let unsafe_face =
|f: usize| bad.contains(&f) || part.neighbours(f).iter().any(|n| bad.contains(n));
(admitted && !faces.iter().any(|&f| unsafe_face(f))).then_some(owner)
}
}
internal_entry! {
pub fn locally_proved<R>(part: &Part, o: &Occurrence<R>) -> bool {
let faces: Vec<usize> = o.defining.iter().chain(&o.context).copied().collect();
!o.defining.is_empty() && locally_valid_solid(part, &faces).is_some()
}
}
internal_entry! {
pub fn verified<R>(
part: &Part,
found: Vec<Occurrence<R>>,
) -> Result<Vec<Occurrence<R>>, EvidenceError> {
for o in &found {
let faces: Vec<usize> = o.defining.iter().chain(&o.context).copied().collect();
if o.defining.is_empty() || common_valid_solid(part, &faces).is_none() {
return Err(EvidenceError::NoValidSolid);
}
}
Ok(found)
}
}
#[cfg(test)]
mod trust_tests {
use super::*;
use std::path::Path;
#[test]
fn strict_status_checks_consulted_faces_and_never_relaxes_in_a_retry() {
let path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rejected_cylinder.step");
let mut part = crate::read_step_file(&path).unwrap();
assert_eq!(strict_status(&part, &[0], &[1]), EvidenceStatus::Verified);
part.faces[1].solid = None;
assert_eq!(strict_status(&part, &[0], &[1]), EvidenceStatus::Unproved);
assert_eq!(strict_status(&part, &[], &[0]), EvidenceStatus::Unproved);
assert_eq!(
strict_status(&part, &[usize::MAX], &[]),
EvidenceStatus::Unproved
);
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/broken/unresolved_surface.step");
let part = crate::read_step_file(&path).unwrap();
locally_degraded(|| {
assert!(local_degradation());
assert_eq!(strict_status(&part, &[0], &[]), EvidenceStatus::Unproved);
});
assert!(!local_degradation());
}
}