pub mod dial;
pub mod display;
pub mod progress;
#[cfg(test)]
mod tests;
use crate::view_model::row_format::format_index_value;
use indicatrix::{
geometry::meet_solver::{Block, SolvedTier, classify_blocks},
optics::materials::GemMaterial,
};
use indicatrix_cut_core::{
ConcaveRowInfo, CutSheetRow, Design, TierId,
design::{ConcaveTier, TierRef},
};
use std::fmt::Write as _;
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepSide {
Crown,
Pavilion,
Girdle,
}
impl StepSide {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Crown => "Crown",
Self::Pavilion => "Pavilion",
Self::Girdle => "Girdle",
}
}
const fn from_block(block: Block) -> Self {
match block {
Block::Crown => Self::Crown,
Block::Pavilion => Self::Pavilion,
Block::Girdle => Self::Girdle,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StepIndex {
pub value: f64,
pub text: String,
pub key: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CuttingStep {
pub number: usize,
pub key: String,
pub signature: String,
pub tier: TierRef,
pub table_row: usize,
pub code: String,
pub name: String,
pub side: StepSide,
pub angle_deg: f64,
pub indices: Vec<StepIndex>,
pub meet: String,
pub mast: Option<f64>,
pub depth_mm: Option<f64>,
pub cheater_offset_deg: Option<f64>,
pub notes: String,
pub tool_line: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CuttingPlan {
pub steps: Vec<CuttingStep>,
pub gear_teeth: u32,
}
#[must_use]
pub fn build_plan(
design: &Design,
solved: &[SolvedTier],
custom: &[GemMaterial],
) -> Option<CuttingPlan> {
let sheet = design.try_cutting_sheet_with(solved, custom).ok()?;
let order = design.preview_steps();
if order.is_empty() || order.len() != sheet.rows.len() {
return None;
}
let blocks = classify_blocks(&design.meet_tier_inputs());
let steps = order
.into_iter()
.zip(sheet.rows)
.enumerate()
.map(|(position, (tier, row))| step_from_row(design, &blocks, position, tier, row))
.collect();
Some(CuttingPlan {
steps,
gear_teeth: design.meta.gear_teeth_abs(),
})
}
fn step_from_row(
design: &Design,
blocks: &[Block],
position: usize,
tier: TierRef,
row: CutSheetRow,
) -> CuttingStep {
let (key, side, table_row, notes) = match tier {
TierRef::Flat(i) => (
id_key('t', design.tier_id_at(i), i),
blocks
.get(i)
.copied()
.map_or(StepSide::Girdle, StepSide::from_block),
i,
design.tier_note(i).unwrap_or_default().trim().to_owned(),
),
TierRef::Concave(i) => (
id_key('c', design.concave_tier_ids.get(i).copied(), i),
if design
.concave_tiers
.get(i)
.is_some_and(ConcaveTier::is_crown_side)
{
StepSide::Crown
} else {
StepSide::Pavilion
},
design.tiers.len() + i,
String::new(),
),
};
let indices = step_indices(&key, &row.indices);
let signature = signature_of(design, side, &row, &indices);
let is_concave = row.concave.is_some();
let code = row.label().to_owned();
let instruction = row.instruction();
CuttingStep {
number: position + 1,
key,
signature,
tier,
table_row,
code,
name: if row.name.trim().is_empty() {
"(unnamed)".to_owned()
} else {
row.name
},
side,
angle_deg: row.angle_deg,
indices,
meet: instruction,
mast: (!is_concave).then_some(row.mast),
depth_mm: row.depth_mm,
cheater_offset_deg: row.cheater_offset_deg,
notes,
tool_line: row.concave.as_ref().map(|info| tool_line(design, info)),
}
}
fn id_key(prefix: char, id: Option<TierId>, position: usize) -> String {
id.map_or_else(
|| format!("{prefix}p{position}"),
|id| format!("{prefix}{}", id.value()),
)
}
fn step_indices(step_key: &str, listed: &[f64]) -> Vec<StepIndex> {
let values: &[f64] = if listed.is_empty() { &[0.0] } else { listed };
values
.iter()
.map(|&value| {
let text = format_index_value(value);
StepIndex {
value,
key: format!("{step_key}#{text}"),
text,
}
})
.collect()
}
fn tool_line(design: &Design, info: &ConcaveRowInfo) -> String {
let [code, theta, displacement, details] = info.second_line_fields();
let mut line = format!("Tool {code} · azimuth {theta} · {displacement} · {details}");
if let Some(width_mm) = design.girdle_diameter_mm {
let [x, y, z] = info.displacement.map(|ratio| ratio * width_mm);
let _ = write!(
line,
" · ({x:.2}, {y:.2}, {z:.2} mm), tool diameter {:.2} mm",
info.diameter_ratio * width_mm
);
}
line
}
fn signature_of(
design: &Design,
side: StepSide,
row: &CutSheetRow,
indices: &[StepIndex],
) -> String {
let mut sorted: Vec<f64> = indices.iter().map(|index| index.value).collect();
sorted.sort_by(f64::total_cmp);
let mut text = format!(
"{}|{}|{}|",
if row.concave.is_some() {
"concave"
} else {
"flat"
},
side.label(),
fixed(row.angle_deg, 4)
);
for value in sorted {
let _ = write!(text, "{},", fixed(value, 4));
}
let _ = write!(
text,
"|{}|{}|{}",
fixed(row.mast, 5),
row.depth_mm
.map_or_else(|| "-".to_owned(), |mm| fixed(mm, 4)),
row.cheater_offset_deg
.map_or_else(|| "-".to_owned(), |deg| fixed(deg, 4)),
);
if let Some(info) = &row.concave {
for field in info.second_line_fields() {
text.push('|');
text.push_str(&field);
}
let _ = write!(
text,
"|{}",
design
.girdle_diameter_mm
.map_or_else(|| "-".to_owned(), |mm| fixed(mm, 4))
);
}
format!("{:016x}", fnv1a(text.as_bytes()))
}
fn fixed(value: f64, precision: usize) -> String {
let text = format!("{value:.precision$}");
match text.strip_prefix('-') {
Some(rest) if rest.bytes().all(|b| b == b'0' || b == b'.') => rest.to_owned(),
_ => text,
}
}
fn fnv1a(bytes: &[u8]) -> u64 {
bytes.iter().fold(FNV_OFFSET, |hash, &byte| {
(hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME)
})
}