use glam::DVec3;
use indicatrix::geometry::{
meet_solver::SolvedTier,
stone_metrics::{SolidMesh, SolidStatus, StoneProportions, build_solid_mesh, measure_solid},
};
use indicatrix_cut_core::{
DEFAULT_MIN_FACET_AREA_FRACTION_OF_W2, Design, ManufacturabilityWarning,
check_manufacturability,
design::{
girdle_band::girdle_band_in,
hinge::{
FacetSide, SolidFacets, TierHinge, solid_facets_in, tier_hinges_in, tier_plane_ranges,
},
},
optics_hints::is_horizontal_angle_deg,
};
use std::{
collections::{BTreeMap, BTreeSet},
ops::Range,
};
pub const MIN_GIRDLE_FRACTION: f64 = 0.5;
pub const KNIFE_EDGE_PERCENT: f64 = 1e-4;
const THINNEST_SHOWN_FROM: f64 = 0.05;
const GIRDLE_COS_EPS: f64 = 1e-6;
const MIN_WIDTH: f64 = 1e-9;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FlatRing {
pub tier_index: usize,
pub side: FacetSide,
pub area: f64,
pub height: f64,
}
#[derive(Debug, Clone)]
pub struct StoneAnalysis {
pub solved: Vec<SolvedTier>,
pub planes: Vec<(DVec3, f64)>,
pub ranges: Vec<Range<usize>>,
pub girdle_percent: Option<f64>,
pub girdle_thinnest_percent: Option<f64>,
pub table_percent: Option<f64>,
pub crown_height: Option<f64>,
pub pavilion_depth: Option<f64>,
pub crown_to_pavilion: Option<f64>,
pub depth_percent: Option<f64>,
pub facets: SolidFacets,
pub flats: Vec<FlatRing>,
pub girdle_band: Option<(f64, f64)>,
pub undersized: BTreeSet<usize>,
pub hinges: BTreeMap<usize, TierHinge>,
}
impl StoneAnalysis {
#[must_use]
pub fn split_at_girdle(&self, delta: f64) -> Self {
let half = 0.5 * delta;
let shift_of = |side: FacetSide| match side {
FacetSide::Crown => half,
FacetSide::Pavilion => -half,
};
let mut split = self.clone();
for hinge in split.hinges.values_mut() {
hinge.point.y += shift_of(hinge.side);
}
for flat in &mut split.flats {
flat.height += shift_of(flat.side);
}
for (tier_index, range) in self.ranges.iter().enumerate() {
let tier_side = self
.hinges
.get(&tier_index)
.map(|hinge| hinge.side)
.or_else(|| {
self.flats
.iter()
.find(|flat| flat.tier_index == tier_index)
.map(|flat| flat.side)
});
for index in range.clone() {
if let Some((normal, offset)) = split.planes.get_mut(index) {
let shift = if let Some(side) = tier_side {
shift_of(side)
} else if normal.y > MIN_VERTICAL_NORMAL {
half
} else if normal.y < -MIN_VERTICAL_NORMAL {
-half
} else {
continue;
};
*offset = normal.y.mul_add(shift, *offset);
}
}
}
split.girdle_band = split
.girdle_band
.map(|(low, high)| (low - half, high + half));
split
}
}
const MIN_VERTICAL_NORMAL: f64 = 1e-9;
#[derive(Debug, Clone, PartialEq)]
pub enum InvalidReason {
DoesNotSolve(String),
NotClosed,
GirdleGone,
GirdleTooThin {
was_percent: f64,
now_percent: f64,
},
GirdleThinAtCorners {
was_percent: f64,
now_percent: f64,
},
FlatOffGirdle {
side: FacetSide,
},
TierLost {
name: String,
},
TierPartlyLost {
name: String,
lost: usize,
total: usize,
},
FacetsTooSmall {
name: String,
},
RelationFails(String),
}
impl InvalidReason {
#[must_use]
pub fn message(&self) -> String {
match self {
Self::DoesNotSolve(why) => {
format!("The retargeted design cannot be solved ({why}).")
}
Self::NotClosed => "The retargeted facets no longer enclose a stone.".to_string(),
Self::GirdleGone => "The girdle disappears.".to_string(),
Self::GirdleTooThin {
was_percent,
now_percent,
} => format!(
"The girdle gets much thinner: {now_percent:.1} % of the width, was {was_percent:.1} %."
),
Self::GirdleThinAtCorners {
was_percent,
now_percent,
} if *now_percent <= KNIFE_EDGE_PERCENT => format!(
"The girdle runs to a knife edge at its corners (was {was_percent:.2} % of the width at its thinnest point)."
),
Self::GirdleThinAtCorners {
was_percent,
now_percent,
} => format!(
"The girdle gets too thin at its corners: {now_percent:.2} % of the width at its thinnest point, was {was_percent:.2} %."
),
Self::FlatOffGirdle {
side: FacetSide::Crown,
} => "The table would sit below the top of the girdle.".to_string(),
Self::FlatOffGirdle {
side: FacetSide::Pavilion,
} => "The culet would sit above the bottom of the girdle.".to_string(),
Self::TierLost { name } => format!("{name}: all its facets disappear."),
Self::TierPartlyLost { name, lost, total } => {
format!("{name}: {lost} of {total} facets disappear.")
}
Self::FacetsTooSmall { name } => {
format!("{name}: its facets become too small to cut.")
}
Self::RelationFails(why) => format!(
"A tier that follows a relation cannot follow it after this change ({}).",
why.trim_end_matches('.')
),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetargetStrategy {
AnglesOnly,
Anchored,
AnchoredRefit,
Optimized,
}
impl RetargetStrategy {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::AnglesOnly => "Only the angles change; the facets re-solve from their meets.",
Self::Anchored => "Each facet turns about its girdle edge, so the girdle stays.",
Self::AnchoredRefit => {
"Each facet turns about its girdle edge, and the table and culet heights are refitted to keep their size."
}
Self::Optimized => {
"Each crown and pavilion angle was searched within your range. Every facet turns about its girdle edge, so the girdle stays, and the table and culet heights are refitted to keep their size."
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidityStatus {
Valid,
Invalid,
Unchecked,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ValidityFigures {
pub girdle_was: Option<f64>,
pub girdle_now: Option<f64>,
pub thinnest_was: Option<f64>,
pub thinnest_now: Option<f64>,
pub table_was: Option<f64>,
pub table_now: Option<f64>,
pub ratio_was: Option<f64>,
pub ratio_now: Option<f64>,
pub depth_was: Option<f64>,
pub depth_now: Option<f64>,
pub girdle_thickened_percent: Option<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RetargetValidity {
pub status: ValidityStatus,
pub reasons: Vec<InvalidReason>,
pub warnings: Vec<String>,
pub figures: ValidityFigures,
pub strategy: RetargetStrategy,
}
fn percent(value: Option<f64>, decimals: usize) -> String {
value.map_or_else(|| "none".to_string(), |v| format!("{v:.decimals$} %"))
}
impl RetargetValidity {
#[must_use]
pub fn unchecked(note: &InvalidReason) -> Self {
Self {
status: ValidityStatus::Unchecked,
reasons: vec![note.clone()],
warnings: Vec::new(),
figures: ValidityFigures::default(),
strategy: RetargetStrategy::AnglesOnly,
}
}
#[must_use]
pub fn judged(
original: &StoneAnalysis,
candidate: &Result<StoneAnalysis, InvalidReason>,
reasons: Vec<InvalidReason>,
strategy: RetargetStrategy,
) -> Self {
let now = candidate.as_ref().ok();
let girdle_now = now.and_then(|analysis| analysis.girdle_percent);
let thinnest_now = now.and_then(|analysis| analysis.girdle_thinnest_percent);
let table_now = now.and_then(|analysis| analysis.table_percent);
let ratio_now = now.and_then(|analysis| analysis.crown_to_pavilion);
let depth_now = now.and_then(|analysis| analysis.depth_percent);
let warnings = now.map_or_else(Vec::new, |analysis| warnings_for(original, analysis));
Self {
status: if reasons.is_empty() {
ValidityStatus::Valid
} else {
ValidityStatus::Invalid
},
reasons,
warnings,
figures: ValidityFigures {
girdle_was: original.girdle_percent,
girdle_now,
thinnest_was: original.girdle_thinnest_percent,
thinnest_now,
table_was: original.table_percent,
table_now,
ratio_was: original.crown_to_pavilion,
ratio_now,
depth_was: original.depth_percent,
depth_now,
girdle_thickened_percent: None,
},
strategy,
}
}
#[must_use]
pub fn with_girdle_thickened(mut self, fraction: Option<f64>) -> Self {
self.figures.girdle_thickened_percent = fraction
.filter(|fraction| fraction.is_finite() && *fraction > 0.0)
.map(|fraction| 100.0 * fraction);
self
}
#[must_use]
pub fn allows_apply(&self) -> bool {
self.status != ValidityStatus::Invalid
}
fn thinnest_clause(&self) -> String {
let figures = &self.figures;
let (Some(now), Some(was)) = (figures.thinnest_now, figures.thinnest_was) else {
return String::new();
};
let adds_nothing = figures
.girdle_now
.is_some_and(|girdle| (girdle - now).abs() <= THINNEST_SHOWN_FROM);
if adds_nothing {
String::new()
} else {
format!(", thinnest point {now:.2} % (was {was:.2} %)")
}
}
fn depth_clause(&self) -> String {
match (self.figures.depth_now, self.figures.depth_was) {
(Some(now), Some(was)) => format!(", depth {now:.0} % (was {was:.0} %)"),
_ => String::new(),
}
}
#[must_use]
pub fn headline(&self) -> String {
match self.status {
ValidityStatus::Valid => format!(
"Valid: girdle {} (was {}){}, table {} (was {}){}",
percent(self.figures.girdle_now, 1),
percent(self.figures.girdle_was, 1),
self.thinnest_clause(),
percent(self.figures.table_now, 0),
percent(self.figures.table_was, 0),
self.depth_clause(),
),
ValidityStatus::Invalid => {
let first = self
.reasons
.first()
.map_or_else(String::new, InvalidReason::message);
format!("Not valid: {first}")
}
ValidityStatus::Unchecked => {
let why = self
.reasons
.first()
.map_or_else(String::new, InvalidReason::message);
format!("Could not check this change. The current design has a problem: {why}")
}
}
}
#[must_use]
pub fn detail_lines(&self) -> Vec<String> {
let skip = usize::from(self.status == ValidityStatus::Invalid);
let mut lines: Vec<String> = if self.status == ValidityStatus::Unchecked {
Vec::new()
} else {
self.reasons
.iter()
.skip(skip)
.map(InvalidReason::message)
.collect()
};
if self.status != ValidityStatus::Unchecked
&& let (Some(now), Some(was)) = (self.figures.ratio_now, self.figures.ratio_was)
{
lines.push(format!("Crown-to-pavilion ratio {now:.2} (was {was:.2})."));
}
if self.status == ValidityStatus::Valid
&& let Some(percent) = self.figures.girdle_thickened_percent
{
lines.push(format!(
"The girdle was thickened by {percent:.0} % so its corners keep their thickness; plan view, table and culet size and crown-to-pavilion ratio are unchanged."
));
}
lines.extend(self.warnings.iter().cloned());
lines
}
}
#[must_use]
pub fn polygon_area(ring: &[DVec3]) -> f64 {
let Some(&origin) = ring.first() else {
return 0.0;
};
let mut sum = DVec3::ZERO;
for pair in ring.windows(2).skip(1) {
sum += (pair[0] - origin).cross(pair[1] - origin);
}
0.5 * sum.length()
}
fn rings_by_plane(mesh: &SolidMesh) -> BTreeMap<usize, &Vec<DVec3>> {
mesh.rings
.iter()
.filter(|(_, ring)| ring.len() >= 3)
.map(|(plane, ring)| (*plane, ring))
.collect()
}
fn mean_height(ring: &[DVec3]) -> f64 {
ring.iter().map(|v| v.y).sum::<f64>() / ring.len().max(1) as f64
}
pub fn analyze(design: &Design, with_hinges: bool) -> Result<StoneAnalysis, InvalidReason> {
let solved = design
.solve()
.map_err(|err| InvalidReason::DoesNotSolve(err.to_string()))?;
analyze_solved(design, solved, with_hinges)
}
pub fn analyze_solved(
design: &Design,
solved: Vec<SolvedTier>,
with_hinges: bool,
) -> Result<StoneAnalysis, InvalidReason> {
let planes = design.planes_from_solved(&solved);
let SolidStatus::Closed(mesh) = build_solid_mesh(&planes) else {
return Err(InvalidReason::NotClosed);
};
let metrics = measure_solid(&planes).ok_or(InvalidReason::NotClosed)?;
let proportions = StoneProportions::from_solid(&metrics, &mesh, &planes);
let facets = solid_facets_in(design, &solved, &planes, &mesh);
let ranges = tier_plane_ranges(design, &solved);
let girdle_thinnest_percent = girdle_band_in(design, &ranges, &planes, &mesh)
.filter(|_| metrics.width_axis > MIN_WIDTH)
.map(|band| 100.0 * band.min_thickness / metrics.width_axis);
let rings = rings_by_plane(&mesh);
let mut flats = Vec::new();
let mut band: Option<(f64, f64)> = None;
for (tier_index, (tier, range)) in design.tiers.iter().zip(&ranges).enumerate() {
if is_horizontal_angle_deg(tier.angle_deg) {
let ring = range.clone().find_map(|plane| rings.get(&plane));
if let Some(ring) = ring {
flats.push(FlatRing {
tier_index,
side: FacetSide::of_angle_deg(tier.angle_deg),
area: polygon_area(ring),
height: mean_height(ring),
});
}
} else if tier.angle_deg.abs().to_radians().cos().abs() <= GIRDLE_COS_EPS {
for plane in range.clone() {
if let Some(&ring) = rings.get(&plane) {
for vertex in ring {
band = Some(band.map_or((vertex.y, vertex.y), |(lo, hi)| {
(lo.min(vertex.y), hi.max(vertex.y))
}));
}
}
}
}
}
let undersized =
check_manufacturability(design, &solved, DEFAULT_MIN_FACET_AREA_FRACTION_OF_W2)
.into_iter()
.filter_map(|warning| match warning {
ManufacturabilityWarning::UndersizedFacet { tier_index, .. } => Some(tier_index),
_ => None,
})
.collect();
let hinges = if with_hinges {
tier_hinges_in(design, &solved, &planes, &mesh)
} else {
BTreeMap::new()
};
let crown_to_pavilion = match (proportions.crown_height, proportions.pavilion_depth) {
(Some(crown), Some(pavilion)) if pavilion > MIN_WIDTH => Some(crown / pavilion),
_ => None,
};
let depth_percent = (metrics.width_axis > MIN_WIDTH)
.then(|| 100.0 * proportions.total_depth / metrics.width_axis);
Ok(StoneAnalysis {
girdle_percent: proportions.girdle_to_width_percent,
girdle_thinnest_percent,
table_percent: proportions.table_percent,
crown_height: proportions.crown_height,
pavilion_depth: proportions.pavilion_depth,
crown_to_pavilion,
depth_percent,
facets,
flats,
girdle_band: band,
undersized,
hinges,
ranges,
solved,
planes,
})
}
fn thins_out_at_corners(was_percent: f64, now_percent: f64) -> bool {
was_percent > KNIFE_EDGE_PERCENT
&& (now_percent <= KNIFE_EDGE_PERCENT || now_percent < MIN_GIRDLE_FRACTION * was_percent)
}
#[must_use]
pub fn judge(
design: &Design,
original: &StoneAnalysis,
candidate: &Result<StoneAnalysis, InvalidReason>,
) -> Vec<InvalidReason> {
let candidate = match candidate {
Ok(analysis) => analysis,
Err(reason) => return vec![reason.clone()],
};
let name_of = |index: usize| {
design
.tiers
.get(index)
.map_or_else(String::new, |tier| tier.name.clone())
};
let mut reasons = Vec::new();
if let Some(was) = original.girdle_percent {
match candidate.girdle_percent {
None => reasons.push(InvalidReason::GirdleGone),
Some(now) if now < MIN_GIRDLE_FRACTION * was => {
reasons.push(InvalidReason::GirdleTooThin {
was_percent: was,
now_percent: now,
});
}
Some(_) => {}
}
}
if let (Some(was), Some(now)) = (
original.girdle_thinnest_percent,
candidate.girdle_thinnest_percent,
) && thins_out_at_corners(was, now)
{
reasons.push(InvalidReason::GirdleThinAtCorners {
was_percent: was,
now_percent: now,
});
}
if let Some((low, high)) = candidate.girdle_band {
for flat in &original.flats {
let Some(now) = candidate
.flats
.iter()
.find(|other| other.tier_index == flat.tier_index)
else {
continue;
};
let off_side = match flat.side {
FacetSide::Crown => now.height <= high,
FacetSide::Pavilion => now.height >= low,
};
if off_side {
reasons.push(InvalidReason::FlatOffGirdle { side: flat.side });
}
}
}
let mut reported = BTreeSet::new();
for (index, (was, now)) in original
.facets
.tiers
.iter()
.zip(&candidate.facets.tiers)
.enumerate()
{
if was.alive > 0 && now.alive == 0 {
reported.insert(index);
reasons.push(InvalidReason::TierLost {
name: name_of(index),
});
} else if now.alive < was.alive {
reported.insert(index);
reasons.push(InvalidReason::TierPartlyLost {
name: name_of(index),
lost: was.alive - now.alive,
total: was.total,
});
}
}
for &index in &candidate.undersized {
if !original.undersized.contains(&index) && !reported.contains(&index) {
reasons.push(InvalidReason::FacetsTooSmall {
name: name_of(index),
});
}
}
reasons
}
#[must_use]
pub fn warnings_for(original: &StoneAnalysis, candidate: &StoneAnalysis) -> Vec<String> {
let mut warnings = Vec::new();
if candidate.facets.preform_alive > original.facets.preform_alive {
warnings.push(
"The retargeted stone touches the rough in places it did not before.".to_string(),
);
}
warnings
}
#[cfg(test)]
mod tests;