use super::{
EMPTY_START_PREFORM, NEW_DESIGN_CREATED,
goal::{Goal, MeetKind},
model::Guide,
perform_table::{self, Action},
solving_events::{SNAPSHOT_TAKEN, SOLVE_REQUESTED},
viewing_events::{
HELP_OPENED, LIVE_RENDER_OPENED, SHORTCUTS_OPENED, SLICE_STARTED, SNAP_TOGGLED,
},
};
use indicatrix::geometry::meet_solver::MeetConstraint;
use indicatrix_cut_core::{
ConstraintTier, Design, FreshDesignSpec, MaterialSelection, TierTarget, design::ConcaveTier,
};
pub const CMD_SOLVE: &str = "solve.run";
pub const CMD_UNDO: &str = "edit.undo";
pub const CMD_DUPLICATE: &str = "tiers.duplicate";
pub const CMD_DELETE: &str = "tiers.delete";
pub const CMD_MOVE_UP: &str = "tiers.move_up";
pub const CMD_MOVE_DOWN: &str = "tiers.move_down";
pub const CMD_ADOPT_ALL: &str = "tiers.adopt_all";
pub const CMD_COMPARE: &str = "solve.compare";
pub const COMMANDS: &[&str] = &[
CMD_SOLVE,
CMD_UNDO,
CMD_DUPLICATE,
CMD_DELETE,
CMD_MOVE_UP,
CMD_MOVE_DOWN,
CMD_ADOPT_ALL,
"solve.snapshot",
CMD_COMPARE,
"view.live_render",
"view.snap",
"view.slice",
"help.shortcuts",
"help.manual",
];
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TierEntry {
pub edit: Option<String>,
pub angle: Option<String>,
pub name: Option<String>,
pub indices: Option<String>,
pub meets: Option<(i32, String)>,
}
impl TierEntry {
#[must_use]
pub fn add(angle: &str, meets_kind: i32, meets_text: &str, name: &str, indices: &str) -> Self {
Self {
edit: None,
angle: Some(angle.to_owned()),
name: Some(name.to_owned()),
indices: Some(indices.to_owned()),
meets: Some((meets_kind, meets_text.to_owned())),
}
}
#[must_use]
pub fn of(name: &str) -> Self {
Self {
edit: Some(name.to_owned()),
..Self::default()
}
}
#[must_use]
pub fn angle(mut self, text: &str) -> Self {
self.angle = Some(text.to_owned());
self
}
#[must_use]
pub fn rename(mut self, name: &str) -> Self {
self.name = Some(name.to_owned());
self
}
#[must_use]
pub fn indices(mut self, text: &str) -> Self {
self.indices = Some(text.to_owned());
self
}
#[must_use]
pub fn meets(mut self, kind: i32, text: &str) -> Self {
self.meets = Some((kind, text.to_owned()));
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TierSave {
pub index: i32,
pub angle: String,
pub constraint_kind: i32,
pub constraint_text: String,
pub name: String,
pub indices: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StepSeries {
pub name: String,
pub start: String,
pub step: String,
pub count: i32,
pub indices: String,
pub anchor: String,
pub linked: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Perform {
NewDesign {
template_index: i32,
spec: Box<FreshDesignSpec>,
},
Tier(TierEntry),
ConcaveTier {
edit: Option<String>,
tier: Box<ConcaveTier>,
},
SelectTier(String),
Steps(StepSeries),
MirrorTier {
tier: String,
suffix: String,
},
ClearRelation(String),
TierNote {
tier: String,
text: String,
},
CheaterOffset {
tier: String,
text: String,
},
Material(String),
Yield {
girdle_diameter_mm: f64,
},
ViewMode(i32),
InspectorTab(i32),
Command(String),
Sequence(Vec<Self>),
}
impl Perform {
#[must_use]
pub fn command(id: &str) -> Self {
Self::Command(id.to_owned())
}
#[must_use]
pub fn solve() -> Self {
Self::command(CMD_SOLVE)
}
#[must_use]
pub fn undo() -> Self {
Self::command(CMD_UNDO)
}
#[must_use]
pub fn select(name: &str) -> Self {
Self::SelectTier(name.to_owned())
}
#[must_use]
pub fn add_tier(
angle: &str,
meets_kind: i32,
meets_text: &str,
name: &str,
indices: &str,
) -> Self {
Self::Tier(TierEntry::add(angle, meets_kind, meets_text, name, indices))
}
#[must_use]
pub fn move_up(name: &str, times: usize) -> Self {
let mut parts = vec![Self::select(name)];
parts.extend((0..times).map(|_| Self::command(CMD_MOVE_UP)));
Self::Sequence(parts)
}
#[must_use]
pub fn delete(name: &str) -> Self {
Self::select(name).then(Self::command(CMD_DELETE))
}
#[must_use]
pub fn then(self, next: Self) -> Self {
let mut parts = match self {
Self::Sequence(parts) => parts,
other => vec![other],
};
parts.push(next);
Self::Sequence(parts)
}
#[must_use]
pub fn problem(&self) -> Option<String> {
match self {
Self::NewDesign { spec, .. } => (spec.gear_teeth == 0 || spec.symmetry_order == 0)
.then(|| "a new design needs a gear and a symmetry order".to_owned()),
Self::Tier(entry) => entry_problem(entry),
Self::ConcaveTier { edit, tier } => {
if tier.name.trim().is_empty() {
Some("a concave tier needs a name".to_owned())
} else if edit.as_deref().is_some_and(|name| name.trim().is_empty()) {
Some("a concave edit needs the name of the row".to_owned())
} else {
None
}
}
Self::SelectTier(name)
| Self::ClearRelation(name)
| Self::MirrorTier { tier: name, .. }
| Self::TierNote { tier: name, .. }
| Self::CheaterOffset { tier: name, .. }
| Self::Material(name) => name
.trim()
.is_empty()
.then(|| "a perform needs a non-empty name".to_owned()),
Self::Steps(series) => (series.count < 1 || series.name.trim().is_empty())
.then(|| "a step series needs a name and at least one rung".to_owned()),
Self::Yield { girdle_diameter_mm } => (!girdle_diameter_mm.is_finite()
|| *girdle_diameter_mm <= 0.0)
.then(|| "a girdle diameter must be a positive number".to_owned()),
Self::ViewMode(mode) => {
(!(0..=3).contains(mode)).then(|| format!("view mode {mode} does not exist"))
}
Self::InspectorTab(tab) => {
(!(0..=4).contains(tab)).then(|| format!("inspector tab {tab} does not exist"))
}
Self::Command(id) => (!COMMANDS.contains(&id.as_str()))
.then(|| format!("{id:?} is not a command a perform may run")),
Self::Sequence(parts) => {
if parts.is_empty() {
Some("an empty sequence does nothing".to_owned())
} else {
parts.iter().find_map(Self::problem)
}
}
}
}
}
fn entry_problem(entry: &TierEntry) -> Option<String> {
match entry.edit.as_deref() {
None => {
if entry
.angle
.as_deref()
.is_none_or(|angle| angle.trim().is_empty())
{
Some("a new tier needs an angle".to_owned())
} else {
None
}
}
Some(name) if name.trim().is_empty() => {
Some("an edit needs the name of the row".to_owned())
}
Some(_) => None,
}
}
#[must_use]
pub fn tier_position(design: &Design, name: &str) -> Option<usize> {
design.tiers.iter().position(|tier| has_name(tier, name))
}
#[must_use]
pub fn concave_position(design: &Design, name: &str) -> Option<usize> {
design
.concave_tiers
.iter()
.position(|tier| tier.name.trim().eq_ignore_ascii_case(name.trim()))
}
fn has_name(tier: &ConstraintTier, name: &str) -> bool {
tier.names()
.into_iter()
.any(|known| known.trim().eq_ignore_ascii_case(name.trim()))
}
fn form_meets(design: &Design, index: usize) -> (i32, String) {
if let Some(target) = design.tier_target(index) {
return match target {
TierTarget::DepthMm(mm) => (3, mm.to_string()),
TierTarget::GirdleThicknessMm(mm) => (4, mm.to_string()),
TierTarget::TableWidthMm(mm) => (5, mm.to_string()),
};
}
match design.tiers.get(index).map(|tier| &tier.constraint) {
Some(MeetConstraint::MeetNamed(names)) => (1, names.join(", ")),
Some(MeetConstraint::ScaleReference(value)) => (2, value.to_string()),
Some(MeetConstraint::MeetExisting) | None => (0, String::new()),
}
}
fn index_text(indices: &[f64]) -> String {
indices
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
}
pub fn resolve_tier(design: &Design, entry: &TierEntry) -> Result<TierSave, String> {
let Some(wanted) = entry.edit.as_deref() else {
let angle = entry
.angle
.clone()
.ok_or_else(|| "A new tier needs an angle.".to_owned())?;
let (constraint_kind, constraint_text) = entry.meets.clone().unwrap_or((0, String::new()));
return Ok(TierSave {
index: -1,
angle,
constraint_kind,
constraint_text,
name: entry.name.clone().unwrap_or_default(),
indices: entry.indices.clone().unwrap_or_default(),
});
};
let position = tier_position(design, wanted)
.ok_or_else(|| format!("There is no tier called '{}' to change.", wanted.trim()))?;
let tier = &design.tiers[position];
let (constraint_kind, constraint_text) = entry
.meets
.clone()
.unwrap_or_else(|| form_meets(design, position));
Ok(TierSave {
index: i32::try_from(position).map_err(|_| "The design has too many tiers.".to_owned())?,
angle: entry
.angle
.clone()
.unwrap_or_else(|| tier.angle_deg.abs().to_string()),
constraint_kind,
constraint_text,
name: entry.name.clone().unwrap_or_else(|| tier.name.clone()),
indices: entry
.indices
.clone()
.unwrap_or_else(|| index_text(&tier.indices)),
})
}
fn event_command(name: &str) -> Option<&'static str> {
match name {
SOLVE_REQUESTED => Some(CMD_SOLVE),
SNAPSHOT_TAKEN => Some("solve.snapshot"),
LIVE_RENDER_OPENED => Some("view.live_render"),
SHORTCUTS_OPENED => Some("help.shortcuts"),
HELP_OPENED => Some("help.manual"),
SNAP_TOGGLED => Some("view.snap"),
SLICE_STARTED => Some("view.slice"),
_ => None,
}
}
fn fresh_design(gear_teeth: u32, symmetry_order: u32, mirror: bool) -> Option<Perform> {
Some(Perform::NewDesign {
template_index: 0,
spec: Box::new(FreshDesignSpec {
gear_teeth: i32::try_from(gear_teeth).ok()?,
symmetry_order,
mirror,
material: MaterialSelection::none(),
preform: EMPTY_START_PREFORM,
}),
})
}
fn default_parts(goal: &Goal) -> Option<Vec<Perform>> {
match goal {
Goal::Manual
| Goal::TierExists(_)
| Goal::TierCountAtLeast(_)
| Goal::ConcaveTiersAtLeast(_)
| Goal::DesignRebuilt { .. }
| Goal::YieldApplied
| Goal::Check { .. }
| Goal::Any(_) => None,
Goal::Event(name) => event_command(name).map(|id| vec![Perform::command(id)]),
Goal::TierMatches {
name,
angle_deg,
indices,
constraint_kind,
..
} => {
let mut entry = TierEntry::of(name).angle(&angle_deg.abs().to_string());
match constraint_kind {
None => {}
Some(MeetKind::Unspecified) => entry = entry.meets(0, ""),
Some(MeetKind::Named | MeetKind::ExactScale) => return None,
}
if let Some(list) = indices {
entry = entry.indices(&index_text(list));
}
Some(vec![Perform::Tier(entry)])
}
Goal::Material(name) => Some(vec![Perform::Material(name.clone())]),
Goal::SolvedClosed => Some(vec![Perform::solve()]),
Goal::ViewMode(mode) => Some(vec![Perform::ViewMode(*mode)]),
Goal::InspectorTab(tab) => Some(vec![Perform::InspectorTab(*tab)]),
Goal::FreshDesign {
gear_teeth,
symmetry_order,
mirror,
} => fresh_design(*gear_teeth, *symmetry_order, *mirror).map(|design| vec![design]),
Goal::All(goals) => {
let mut parts: Vec<Perform> = Vec::new();
let mut events: Vec<&str> = Vec::new();
for goal in goals {
if let Goal::Event(name) = goal {
events.push(name);
} else {
parts.extend(default_parts(goal)?);
}
}
for name in events {
let raised_by_parts = (name == NEW_DESIGN_CREATED
&& parts
.iter()
.any(|part| matches!(part, Perform::NewDesign { .. })))
|| event_command(name).is_some_and(|id| {
parts
.iter()
.any(|part| matches!(part, Perform::Command(known) if known == id))
});
if !raised_by_parts {
parts.extend(default_parts(&Goal::Event(name.to_owned()))?);
}
}
Some(parts)
}
}
}
#[must_use]
pub fn default_perform(goal: &Goal) -> Option<Perform> {
let mut parts = default_parts(goal)?;
match parts.len() {
0 => None,
1 => parts.pop(),
_ => Some(Perform::Sequence(parts)),
}
}
pub(super) fn attach_performs(guides: &mut [Guide]) {
let table = perform_table::entries();
for guide in guides.iter_mut() {
for step in &mut guide.steps {
if step.perform.is_some() || step.is_manual() {
continue;
}
let listed = table
.iter()
.find(|entry| entry.guide == guide.id && entry.step == step.title);
step.perform = match listed {
Some(entry) => match &entry.action {
Action::Do(perform) => Some(perform.clone()),
Action::SkipOnly => None,
},
None => default_perform(&step.goal),
};
}
}
}