mod fix;
mod gather;
#[cfg(test)]
mod tests;
use crate::retarget::metrics::MetricColumn;
use indicatrix_cut_core::ManufacturabilityWarning;
use std::{
cmp::Reverse,
collections::{BTreeMap, BTreeSet},
};
pub use fix::{FixPlan, QUICK_ADD_TABLE_MAST, plan_fix, steep_target_deg};
pub use gather::gather;
pub const WINDOWING_CHECK_PCT: f32 = 15.0;
pub const WINDOWING_PROBLEM_PCT: f32 = 30.0;
pub const EXTINCTION_CHECK_PCT: f32 = 40.0;
pub const EXTINCTION_PROBLEM_PCT: f32 = 60.0;
pub const BRILLIANCE_CHECK_BELOW_PCT: f32 = 25.0;
pub const BRILLIANCE_PROBLEM_BELOW_PCT: f32 = 10.0;
pub const SAFE_MARGIN_DEG: f64 = 2.0;
pub const MAX_LISTED_WINDOWING_TIERS: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Level {
Good,
Check,
Problem,
}
impl Level {
#[must_use]
pub const fn word(self) -> &'static str {
match self {
Self::Good => "Good",
Self::Check => "Check",
Self::Problem => "Problem",
}
}
#[must_use]
pub const fn code(self) -> i32 {
match self {
Self::Good => 0,
Self::Check => 1,
Self::Problem => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReasonKind {
DoesNotSolve,
NotClosed,
Vanished,
Undersized,
OffGear,
OutOfOrder,
NameNotSafe,
Concave,
Windowing,
MissingTable,
Proportion,
OpticalWindowing,
OpticalExtinction,
OpticalBrilliance,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FixAction {
SnapToTeeth {
tier: usize,
},
RemoveVanished {
tier: usize,
},
MoveAfter {
tier: usize,
after: usize,
},
SteepenPavilion {
tier: usize,
},
AddTable,
}
impl FixAction {
#[must_use]
pub const fn label(&self) -> &'static str {
match self {
Self::SnapToTeeth { .. } => "Snap to teeth",
Self::RemoveVanished { .. } => "Remove",
Self::MoveAfter { .. } => "Move later",
Self::SteepenPavilion { .. } => "Steepen",
Self::AddTable => "Add a table",
}
}
#[must_use]
pub const fn hint(&self) -> &'static str {
match self {
Self::SnapToTeeth { .. } => {
"Moves each index position of this tier to the nearest gear tooth."
}
Self::RemoveVanished { .. } => {
"Removes the facets that are cut away. One undo brings them back."
}
Self::MoveAfter { .. } => {
"Moves this tier to just after the tier it meets, so that tier is cut first."
}
Self::SteepenPavilion { .. } => {
"Raises this facet to the critical angle plus 2 degrees. It turns about its \
girdle edge, so the girdle stays where it is."
}
Self::AddTable => {
"Adds a flat table facet at a height that keeps all the crown facets."
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reason {
pub kind: ReasonKind,
pub level: Level,
pub text: String,
pub tier: Option<usize>,
pub fix: Option<FixAction>,
pub confirm: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verdict {
pub level: Level,
pub headline: String,
pub reasons: Vec<Reason>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SolveFacts {
#[default]
Empty,
DoesNotSolve(String),
NotClosed(String),
Closed,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TierWindowing {
pub tier: usize,
pub name: String,
pub angle_deg: f64,
pub critical_deg: f64,
pub margin_deg: f64,
pub crown_estimate: bool,
pub fixable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProportionFact {
pub label: &'static str,
pub level: i32,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct VerdictInputs {
pub solve: SolveFacts,
pub warnings: Vec<ManufacturabilityWarning>,
pub partial_vanish_fixable: BTreeSet<usize>,
pub windowing: Vec<TierWindowing>,
pub proportions: Vec<ProportionFact>,
pub missing_table: bool,
pub optics: Option<MetricColumn>,
pub tier_names: Vec<String>,
}
impl VerdictInputs {
fn label(&self, name: &str, tier: usize) -> String {
self.tier_names
.get(tier)
.filter(|shown| !shown.trim().is_empty())
.map_or_else(|| label_of(name, tier), Clone::clone)
}
#[must_use]
pub fn with_optics(&self, optics: Option<MetricColumn>) -> Self {
Self {
optics,
..self.clone()
}
}
#[must_use]
pub const fn is_empty(&self) -> bool {
matches!(self.solve, SolveFacts::Empty)
}
}
fn label_of(name: &str, tier: usize) -> String {
if name.trim().is_empty() {
format!("Tier {}", tier + 1)
} else {
name.to_string()
}
}
fn sentence(text: &str) -> String {
let trimmed = text.trim();
if trimmed.is_empty() || trimmed.ends_with(['.', '!', '?']) {
trimmed.to_string()
} else {
format!("{trimmed}.")
}
}
const fn plural(count: usize) -> &'static str {
if count == 1 { "" } else { "s" }
}
const fn reason(kind: ReasonKind, level: Level, text: String) -> Reason {
Reason {
kind,
level,
text,
tier: None,
fix: None,
confirm: None,
}
}
fn vanished_reasons(inputs: &VerdictInputs) -> Vec<Reason> {
inputs
.warnings
.iter()
.filter_map(|warning| {
let ManufacturabilityWarning::VanishingFacet {
tier_index,
tier_name,
vanished,
total,
..
} = warning
else {
return None;
};
let label = inputs.label(tier_name, *tier_index);
let all_gone = vanished >= total;
let text = if all_gone && *total == 1 {
format!("{label}: its facet is cut away by a later tier.")
} else if all_gone {
format!("{label}: all {total} of its facets are cut away by later tiers.")
} else {
format!("{label}: {vanished} of {total} facets are cut away by later tiers.")
};
let fixable = all_gone || inputs.partial_vanish_fixable.contains(tier_index);
let mut found = reason(ReasonKind::Vanished, Level::Check, text);
found.tier = Some(*tier_index);
if fixable {
found.fix = Some(FixAction::RemoveVanished { tier: *tier_index });
found.confirm = Some(if all_gone {
format!("Remove {label} from the schedule? It adds nothing to the stone.")
} else {
format!(
"Remove the {vanished} cut-away facet{} of {label}? The other {} stay.",
plural(*vanished),
total - vanished
)
});
}
Some(found)
})
.collect()
}
fn undersized_reasons(inputs: &VerdictInputs) -> Vec<Reason> {
let mut groups: BTreeMap<usize, (String, usize, f64)> = BTreeMap::new();
for warning in &inputs.warnings {
if let ManufacturabilityWarning::UndersizedFacet {
tier_index,
tier_name,
area,
width_axis,
..
} = warning
{
let percent = if *width_axis > 0.0 {
100.0 * area.sqrt() / width_axis
} else {
f64::NAN
};
let entry = groups
.entry(*tier_index)
.or_insert_with(|| (tier_name.clone(), 0, f64::INFINITY));
entry.1 += 1;
if percent.is_finite() {
entry.2 = entry.2.min(percent);
}
}
}
groups
.into_iter()
.map(|(tier, (name, count, smallest))| {
let label = inputs.label(&name, tier);
let text = match (count, smallest.is_finite()) {
(1, true) => format!(
"{label}: a facet is only {smallest:.1} % of the stone's width, too small to polish."
),
(1, false) => format!("{label}: a facet is too small to polish."),
(_, true) => format!(
"{label}: {count} facets are too small to polish (the smallest is {smallest:.1} % of the stone's width)."
),
(_, false) => format!("{label}: {count} facets are too small to polish."),
};
let mut found = reason(ReasonKind::Undersized, Level::Check, text);
found.tier = Some(tier);
found
})
.collect()
}
fn off_gear_reasons(inputs: &VerdictInputs) -> Vec<Reason> {
let mut groups: BTreeMap<usize, (String, usize, f64)> = BTreeMap::new();
for warning in &inputs.warnings {
if let ManufacturabilityWarning::FractionalIndex {
tier_index,
tier_name,
achievable,
..
} = warning
{
let entry = groups
.entry(*tier_index)
.or_insert_with(|| (tier_name.clone(), 0, *achievable));
entry.1 += 1;
}
}
groups
.into_iter()
.map(|(tier, (name, count, tooth))| {
let label = inputs.label(&name, tier);
let text = if count == 1 {
format!(
"{label}: an index position sits between gear teeth (the nearest tooth is {tooth})."
)
} else {
format!("{label}: {count} index positions sit between gear teeth.")
};
let mut found = reason(ReasonKind::OffGear, Level::Check, text);
found.tier = Some(tier);
found.fix = Some(FixAction::SnapToTeeth { tier });
found
})
.collect()
}
fn out_of_order_reasons(inputs: &VerdictInputs) -> Vec<Reason> {
let mut groups: BTreeMap<usize, (String, usize, usize, String)> = BTreeMap::new();
for warning in &inputs.warnings {
if let ManufacturabilityWarning::OutOfOrderMeet {
tier_index,
tier_name,
target_tier_index,
target_tier_name,
..
} = warning
{
let entry = groups.entry(*tier_index).or_insert_with(|| {
(
tier_name.clone(),
0,
*target_tier_index,
target_tier_name.clone(),
)
});
entry.1 += 1;
if *target_tier_index > entry.2 {
entry.2 = *target_tier_index;
entry.3.clone_from(target_tier_name);
}
}
}
groups
.into_iter()
.map(|(tier, (name, count, latest, latest_name))| {
let label = inputs.label(&name, tier);
let target = inputs.label(&latest_name, latest);
let text = if count == 1 {
format!("{label} meets {target}, which is cut later.")
} else {
format!("{label} meets {count} tiers that are cut later (the last is {target}).")
};
let mut found = reason(ReasonKind::OutOfOrder, Level::Check, text);
found.tier = Some(tier);
if latest > tier {
found.fix = Some(FixAction::MoveAfter {
tier,
after: latest,
});
}
found
})
.collect()
}
fn other_warning_reasons(inputs: &VerdictInputs) -> Vec<Reason> {
inputs
.warnings
.iter()
.filter_map(|warning| match warning {
ManufacturabilityWarning::MeetNameNotAscSafe {
tier_index,
tier_name,
unsafe_names,
..
} => {
let label = inputs.label(tier_name, *tier_index);
let mut found = reason(
ReasonKind::NameNotSafe,
Level::Check,
format!(
"{label}: the meet name(s) {} would not survive saving as plain .asc text. \
Rename them without spaces, commas or semicolons.",
unsafe_names.join(", ")
),
);
found.tier = Some(*tier_index);
Some(found)
}
ManufacturabilityWarning::ConcaveTiersOmittedFromExport { .. }
| ManufacturabilityWarning::VanishingFacet { .. }
| ManufacturabilityWarning::UndersizedFacet { .. }
| ManufacturabilityWarning::FractionalIndex { .. }
| ManufacturabilityWarning::OutOfOrderMeet { .. } => None,
ManufacturabilityWarning::ToolMissesStone { .. }
| ManufacturabilityWarning::ToolBreaksThrough { .. }
| ManufacturabilityWarning::ToolRemovesMeet { .. }
| ManufacturabilityWarning::ToolsOverlap { .. }
| ManufacturabilityWarning::ConcaveSliver { .. }
| ManufacturabilityWarning::ToolRemovesHullVertex { .. }
| ManufacturabilityWarning::ToolEnclosed { .. } => Some(reason(
ReasonKind::Concave,
Level::Check,
sentence(&capitalised(&warning.to_string())),
)),
})
.collect()
}
fn windowing_reasons(inputs: &VerdictInputs) -> Vec<Reason> {
let mut tiers: Vec<&TierWindowing> = inputs.windowing.iter().collect();
tiers.sort_by(|a, b| {
a.crown_estimate
.cmp(&b.crown_estimate)
.then_with(|| a.margin_deg.total_cmp(&b.margin_deg))
});
let mut reasons: Vec<Reason> = tiers
.iter()
.take(MAX_LISTED_WINDOWING_TIERS)
.map(|tier| {
let label = inputs.label(&tier.name, tier.tier);
let text = if tier.crown_estimate {
format!(
"{label}: estimated {:+.1}\u{b0} from the critical angle, so some light may leak out through the crown. The estimate follows one ray through this facet and the main pavilion facet on the same side, not the whole stone.",
tier.margin_deg
)
} else {
format!(
"{label}: at {:.1}\u{b0} it is below the critical angle ({:.1}\u{b0} for this material), so light leaks out of the bottom.",
tier.angle_deg, tier.critical_deg
)
};
let mut found = reason(ReasonKind::Windowing, Level::Check, text);
found.tier = Some(tier.tier);
if tier.fixable {
found.fix = Some(FixAction::SteepenPavilion { tier: tier.tier });
}
found
})
.collect();
let more = tiers.len().saturating_sub(MAX_LISTED_WINDOWING_TIERS);
if more > 0 {
reasons.push(reason(
ReasonKind::Windowing,
Level::Check,
format!(
"{more} more tier{} let{} light out; the tier table shows which.",
plural(more),
if more == 1 { "s" } else { "" }
),
));
}
reasons
}
fn optics_reasons(optics: &MetricColumn) -> Vec<Reason> {
let mut reasons = Vec::new();
let windowing = optics.windowing_pct;
if windowing > WINDOWING_CHECK_PCT {
let level = if windowing > WINDOWING_PROBLEM_PCT {
Level::Problem
} else {
Level::Check
};
reasons.push(reason(
ReasonKind::OpticalWindowing,
level,
format!(
"About {windowing:.0} % of the stone leaks light straight out of the bottom (windowing)."
),
));
}
let extinction = optics.extinction_pct;
if extinction > EXTINCTION_CHECK_PCT {
let level = if extinction > EXTINCTION_PROBLEM_PCT {
Level::Problem
} else {
Level::Check
};
reasons.push(reason(
ReasonKind::OpticalExtinction,
level,
format!("About {extinction:.0} % of the light is lost inside the stone (extinction)."),
));
}
let brilliance = optics.brilliance_pct;
if brilliance < BRILLIANCE_CHECK_BELOW_PCT {
let level = if brilliance < BRILLIANCE_PROBLEM_BELOW_PCT {
Level::Problem
} else {
Level::Check
};
reasons.push(reason(
ReasonKind::OpticalBrilliance,
level,
format!(
"Only about {brilliance:.0} % of the light returns to the eye with the table up."
),
));
}
reasons
}
fn headline_for(level: Level, reasons: &[Reason], with_optics: bool) -> String {
match level {
Level::Good if with_optics => "Looks good: closes, no warnings, little windowing.".into(),
Level::Good => "Looks good: closes, no warnings.".into(),
Level::Check => format!("Check {} thing{}.", reasons.len(), plural(reasons.len())),
Level::Problem => {
if let Some(first) = reasons
.first()
.filter(|r| matches!(r.kind, ReasonKind::DoesNotSolve | ReasonKind::NotClosed))
{
return first.text.clone();
}
let problems = reasons.iter().filter(|r| r.level == Level::Problem).count();
let checks = reasons.len() - problems;
if checks > 0 {
format!(
"{problems} problem{} to fix, {checks} more thing{} to check.",
plural(problems),
plural(checks)
)
} else {
format!("{problems} problem{} to fix.", plural(problems))
}
}
}
}
fn capitalised(text: &str) -> String {
let mut chars = text.chars();
chars.next().map_or_else(String::new, |first| {
first.to_uppercase().chain(chars).collect()
})
}
#[must_use]
pub fn evaluate(inputs: &VerdictInputs) -> Verdict {
if inputs.is_empty() {
return Verdict {
level: Level::Good,
headline: "Nothing to check yet: add some tiers.".into(),
reasons: Vec::new(),
};
}
let mut reasons = Vec::new();
match &inputs.solve {
SolveFacts::DoesNotSolve(why) => reasons.push(reason(
ReasonKind::DoesNotSolve,
Level::Problem,
format!("Does not solve: {}", sentence(why)),
)),
SolveFacts::NotClosed(why) => reasons.push(reason(
ReasonKind::NotClosed,
Level::Problem,
format!("Does not close: {}", sentence(why)),
)),
SolveFacts::Empty | SolveFacts::Closed => {}
}
reasons.extend(vanished_reasons(inputs));
reasons.extend(undersized_reasons(inputs));
reasons.extend(off_gear_reasons(inputs));
reasons.extend(out_of_order_reasons(inputs));
reasons.extend(other_warning_reasons(inputs));
reasons.extend(windowing_reasons(inputs));
if inputs.missing_table {
let mut found = reason(
ReasonKind::MissingTable,
Level::Check,
"The crown has no table: nothing is cut flat across the top.".into(),
);
found.fix = Some(FixAction::AddTable);
reasons.push(found);
}
for fact in inputs.proportions.iter().filter(|fact| fact.level >= 2) {
reasons.push(reason(
ReasonKind::Proportion,
Level::Check,
format!(
"{} is outside the usual range: {}",
fact.label,
sentence(&fact.reason)
),
));
}
if let Some(optics) = &inputs.optics {
reasons.extend(optics_reasons(optics));
}
reasons.sort_by_key(|r| Reverse(r.level));
let level = reasons.first().map_or(Level::Good, |r| r.level);
let headline = headline_for(level, &reasons, inputs.optics.is_some());
Verdict {
level,
headline,
reasons,
}
}