use rayon::prelude::*;
use crate::classify::{decode, Label, Status};
use crate::error::{Error, Result};
use crate::intern;
use crate::trace::{Line, Tracer, NO_SURFACE};
use crate::vec3::Vec3;
use crate::Model;
#[derive(Clone, Debug)]
pub struct Visibility {
pub cells: Vec<bool>,
pub gaps: bool,
pub problems: bool,
pub level: Option<usize>,
pub ghosts: Vec<bool>,
pub veil: bool,
pub problem_cells: Vec<bool>,
}
impl Visibility {
pub fn all(m: &Model) -> Visibility {
Visibility {
cells: vec![true; m.cells.len()],
gaps: true,
problems: true,
level: None,
ghosts: Vec::new(),
veil: false,
problem_cells: Vec::new(),
}
}
pub fn solid(m: &Model) -> Visibility {
Visibility {
cells: m
.cells
.iter()
.map(|c| c.material != 0 || c.fill.is_some())
.collect(),
gaps: true,
problems: true,
level: None,
ghosts: Vec::new(),
veil: false,
problem_cells: Vec::new(),
}
}
pub fn hide(&mut self, m: &Model, ids: &[i64]) -> Result<()> {
for &id in ids {
let c = m.cell_index(id).ok_or(Error::NoCell(id))?;
self.cells[c as usize] = false;
}
Ok(())
}
pub fn hide_universe(&mut self, m: &Model, u: i64) -> Result<()> {
let unit = m
.units()
.iter()
.find(|x| x.universe == u)
.ok_or(Error::NoUniverse(u))?;
for &c in &unit.cells {
self.cells[c as usize] = false;
}
Ok(())
}
pub fn ghost(&mut self, m: &Model, ids: &[i64]) -> Result<()> {
for &id in ids {
let c = m.cell_index(id).ok_or(Error::NoCell(id))?;
if self.ghosts.is_empty() {
self.ghosts = vec![false; m.cells.len()];
}
self.ghosts[c as usize] = true;
}
Ok(())
}
#[inline]
pub fn is_ghost(&self, c: u32) -> bool {
self.ghosts.get(c as usize).copied().unwrap_or(false)
}
pub fn has_ghosts(&self) -> bool {
self.ghosts.iter().any(|&g| g)
}
pub(crate) fn veils(&self, status: Status) -> bool {
self.veil && matches!(status, Status::Gap | Status::Overlap) && self.shows(status)
}
pub(crate) fn check(&self, n: usize) -> Result<()> {
if self.cells.len() != n {
return Err(Error::Invalid(format!(
"visibility has {} cell flags for a model of {} cells",
self.cells.len(),
n
)));
}
if !self.ghosts.is_empty() && self.ghosts.len() != n {
return Err(Error::Invalid(format!(
"visibility has {} ghost flags for a model of {} cells",
self.ghosts.len(),
n
)));
}
if !self.problem_cells.is_empty() && self.problem_cells.len() != n {
return Err(Error::Invalid(format!(
"visibility has {} problem cell flags for a model of {} cells",
self.problem_cells.len(),
n
)));
}
Ok(())
}
pub fn owns_problem(&self, l: &Label) -> bool {
self.owns(l.status, l.path.last().map(|s| s.cell), &l.involved)
}
pub(crate) fn owns(&self, status: Status, holder: Option<u32>, cells: &[u32]) -> bool {
let mask = |c: u32| self.problem_cells.get(c as usize).copied().unwrap_or(false);
match status {
_ if self.problem_cells.is_empty() => true,
Status::Inside | Status::OnSurface => true,
Status::Overlap | Status::Unsupported => cells.iter().any(|&c| mask(c)),
Status::Gap | Status::TooDeep => holder.is_some_and(mask),
}
}
pub(crate) fn shows(&self, status: Status) -> bool {
match status {
Status::Inside => true,
Status::Gap => self.gaps,
Status::Overlap | Status::Unsupported | Status::TooDeep => self.problems,
Status::OnSurface => false,
}
}
}
pub const NO_HIT: u32 = u32::MAX;
pub const NO_CELL: u32 = u32::MAX;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Veils {
pub gap: bool,
pub overlap: bool,
}
impl Veils {
pub fn any(self) -> bool {
self.gap || self.overlap
}
pub fn or(self, later: Veils) -> Veils {
Veils {
gap: self.gap || later.gap,
overlap: self.overlap || later.overlap,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ghost {
pub count: u32,
pub cell: u32,
pub t: f64,
pub normal: Vec3,
}
impl Default for Ghost {
fn default() -> Ghost {
Ghost {
count: 0,
cell: NO_CELL,
t: f64::INFINITY,
normal: [0.0; 3],
}
}
}
impl Ghost {
pub fn then(self, later: Ghost) -> Ghost {
Ghost {
count: self.count + later.count,
..if self.count > 0 { self } else { later }
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Hits {
pub t: Vec<f64>,
pub ids: Vec<u32>,
pub surface: Vec<u32>,
pub normal: Vec<Vec3>,
pub labels: Vec<Label>,
pub ghosts: Vec<Ghost>,
pub veils: Vec<Veils>,
}
#[derive(Default)]
struct Part {
chunk: intern::Chunk,
t: Vec<f64>,
hit: Vec<bool>,
surface: Vec<u32>,
normal: Vec<Vec3>,
ghosts: Vec<Ghost>,
veils: Vec<Veils>,
}
impl Model {
pub fn first_hits(
&self,
rays: &[Line],
vis: &Visibility,
skip: Option<&crate::Skip>,
) -> Result<Hits> {
if skip.is_some_and(|s| s.worth.len() != self.cells.len()) {
return Err(Error::Invalid("a skip of another model".into()));
}
let skip = skip.filter(|_| !vis.gaps && !vis.problems);
vis.check(self.cells.len())?;
crate::trace::check_lines(rays)?;
let ghosts = vis.has_ghosts();
let parts: Vec<Part> = rays
.par_chunks(crate::trace::chunk_len(rays.len()))
.map_init(
|| {
let mut tr = Tracer::new(self, false);
tr.set_level(vis.level);
tr.hit = Some(crate::trace::HitSearch {
vis,
skip,
found: None,
ghosts: ghosts.then(Vec::new),
veils: Default::default(),
});
tr
},
|tr, chunk| {
let mut part = Part::default();
for r in chunk {
let found = tr.first_hit(r);
if ghosts {
let t = found.as_ref().map_or(f64::INFINITY, |h| h.t);
part.ghosts.push(tr.ghost(t));
}
if vis.veil {
part.veils.push(tr.veils());
}
match found {
Some(h) => {
part.chunk.push(&tr.keys()[h.key.0..h.key.1]);
part.t.push(h.t);
part.hit.push(true);
part.surface.push(h.surface);
part.normal.push(h.normal);
}
None => {
part.t.push(f64::INFINITY);
part.hit.push(false);
part.surface.push(NO_SURFACE);
part.normal.push([0.0; 3]);
}
}
}
part
},
)
.collect();
let mut out = Hits::default();
let mut chunks = Vec::with_capacity(parts.len());
let mut hit = Vec::with_capacity(rays.len());
for p in parts {
out.t.extend(p.t);
out.surface.extend(p.surface);
out.normal.extend(p.normal);
out.ghosts.extend(p.ghosts);
out.veils.extend(p.veils);
hit.extend(p.hit);
chunks.push(p.chunk);
}
let (ids, keys) = intern::merge(&chunks);
let mut next = ids.into_iter();
out.ids = hit
.iter()
.map(|&h| if h { next.next().unwrap() } else { NO_HIT })
.collect();
out.labels = keys.par_iter().map(|k| decode(k)).collect();
Ok(out)
}
}