use super::{
anchors::{
AnchorChange, anchored_candidate_for, anchored_candidate_split, scale_reference_mast,
},
metrics::{MetricColumn, RetargetMetrics, measure_column},
plan::RetargetPlan,
refit::refit_flats,
validity::{
InvalidReason, MIN_GIRDLE_FRACTION, RetargetStrategy, RetargetValidity, StoneAnalysis,
analyze, judge,
},
};
use indicatrix::{
geometry::meet_solver::MeetConstraint,
optics::{LightingPreset, materials::GemMaterial},
};
use indicatrix_cut_core::{Design, design::RelationError};
use std::sync::Arc;
pub type AnalysisResult = Result<StoneAnalysis, InvalidReason>;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GirdleAllowance {
pub max_fraction: f64,
}
impl GirdleAllowance {
pub const DEFAULT_MAX_FRACTION: f64 = 0.10;
#[must_use]
pub const fn standard() -> Self {
Self {
max_fraction: Self::DEFAULT_MAX_FRACTION,
}
}
#[must_use]
pub fn rungs(self) -> [f64; 2] {
let max = self.max_fraction.max(0.0);
[0.5 * max, max]
}
}
#[derive(Debug, Clone, Copy)]
pub struct CheckInputs<'a> {
pub girdle: Option<GirdleAllowance>,
pub design: &'a Design,
pub plan: &'a RetargetPlan,
pub current_gem: Option<&'a GemMaterial>,
pub lighting: LightingPreset,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RetargetCheck {
pub validity: RetargetValidity,
pub anchors: Vec<AnchorChange>,
pub metrics: RetargetMetrics,
}
impl RetargetCheck {
#[must_use]
pub fn allows_apply(&self) -> bool {
self.validity.allows_apply()
}
}
pub(super) struct Attempt {
pub(super) design: Design,
pub(super) anchors: Vec<AnchorChange>,
pub(super) strategy: RetargetStrategy,
pub(super) analysis: AnalysisResult,
pub(super) reasons: Vec<InvalidReason>,
pub(super) girdle_step: Option<f64>,
}
impl Attempt {
fn new(
original_design: &Design,
original: &StoneAnalysis,
design: Design,
anchors: Vec<AnchorChange>,
strategy: RetargetStrategy,
) -> Self {
let analysis = analyze(&design, false);
let reasons = judge(original_design, original, &analysis);
Self {
design,
anchors,
strategy,
analysis,
reasons,
girdle_step: None,
}
}
pub(super) fn unchanged(design: &Design, original: &StoneAnalysis) -> Self {
Self {
design: design.clone(),
anchors: Vec::new(),
strategy: RetargetStrategy::AnglesOnly,
analysis: Ok(original.clone()),
reasons: Vec::new(),
girdle_step: None,
}
}
}
fn refit_attempt(
live: &Design,
original: &StoneAnalysis,
base: &Attempt,
should_stop: &dyn Fn() -> bool,
) -> Option<Attempt> {
let Ok(candidate) = &base.analysis else {
return None;
};
let refits = refit_flats(
&base.design,
&candidate.solved,
&candidate.flats,
original,
should_stop,
);
if refits.is_empty() || should_stop() {
return None;
}
let mut design = base.design.clone();
let mut anchors = base.anchors.clone();
for refit in &refits {
let Some(old_mast) = scale_reference_mast(live, refit.tier_index) else {
continue;
};
design.tiers[refit.tier_index].constraint = MeetConstraint::ScaleReference(refit.new_mast);
anchors.retain(|anchor| anchor.tier_index != refit.tier_index);
anchors.push(AnchorChange {
tier_index: refit.tier_index,
old_mast,
new_mast: refit.new_mast,
});
}
Some(Attempt::new(
live,
original,
design,
anchors,
RetargetStrategy::AnchoredRefit,
))
}
pub(super) fn best_attempt(
live: &Design,
moves: &[(usize, f64)],
original: &StoneAnalysis,
girdle: Option<GirdleAllowance>,
should_stop: &dyn Fn() -> bool,
) -> Result<Option<Attempt>, RelationError> {
let Some(plain) = attempt_at(live, moves, original, None, should_stop)? else {
return Ok(None);
};
let Some(allowance) = girdle else {
return Ok(Some(plain));
};
if !plain
.reasons
.iter()
.any(|reason| thickening_can_cure(reason, allowance))
{
return Ok(Some(plain));
}
let Some((low, high)) = original.girdle_band else {
return Ok(Some(plain));
};
let band = high - low;
if !band.is_finite() || band <= 0.0 {
return Ok(Some(plain));
}
for fraction in allowance.rungs() {
if should_stop() {
return Ok(None);
}
let Some(mut attempt) = attempt_at(
live,
moves,
original,
Some((fraction, fraction * band)),
should_stop,
)?
else {
return Ok(None);
};
if attempt.reasons.is_empty() {
attempt.girdle_step = Some(fraction);
return Ok(Some(attempt));
}
}
Ok(Some(plain))
}
fn thickening_can_cure(reason: &InvalidReason, allowance: GirdleAllowance) -> bool {
match reason {
InvalidReason::GirdleTooThin {
was_percent,
now_percent,
} => {
allowance
.max_fraction
.max(0.0)
.mul_add(*was_percent, *now_percent)
>= MIN_GIRDLE_FRACTION * was_percent
}
InvalidReason::GirdleThinAtCorners { .. } | InvalidReason::GirdleGone => true,
_ => false,
}
}
fn attempt_at(
live: &Design,
moves: &[(usize, f64)],
original: &StoneAnalysis,
thicken: Option<(f64, f64)>,
should_stop: &dyn Fn() -> bool,
) -> Result<Option<Attempt>, RelationError> {
let (hinge_design, hinge_anchors) = match thicken {
None => anchored_candidate_for(live, moves, original)?,
Some((_, delta)) => {
let split = original.split_at_girdle(delta);
anchored_candidate_split(live, moves, &split, 0.5 * delta)?
}
};
let base_strategy = if hinge_anchors.is_empty() {
RetargetStrategy::AnglesOnly
} else {
RetargetStrategy::Anchored
};
let mut best = Attempt::new(live, original, hinge_design, hinge_anchors, base_strategy);
if should_stop() {
return Ok(None);
}
if !original.flats.is_empty() {
if let Some(refitted) = refit_attempt(live, original, &best, should_stop) {
if refitted.reasons.is_empty() || !best.reasons.is_empty() {
best = refitted;
}
}
if should_stop() {
return Ok(None);
}
}
Ok(Some(best))
}
fn measure(
inputs: &CheckInputs<'_>,
original: &StoneAnalysis,
candidate: &AnalysisResult,
) -> RetargetMetrics {
let target = &inputs.plan.target.gem;
let column = |planes: &[(glam::DVec3, f64)], gem: &GemMaterial| -> MetricColumn {
measure_column(planes, gem, inputs.lighting)
};
RetargetMetrics {
current_in_current: inputs.current_gem.map(|gem| column(&original.planes, gem)),
current_in_target: Some(column(&original.planes, target)),
retargeted_in_target: candidate
.as_ref()
.ok()
.map(|analysis| column(&analysis.planes, target)),
}
}
fn check_against(
inputs: &CheckInputs<'_>,
original: &StoneAnalysis,
should_stop: &dyn Fn() -> bool,
) -> Option<RetargetCheck> {
let moves = inputs.plan.moving_angles();
let best = match best_attempt(inputs.design, &moves, original, inputs.girdle, should_stop) {
Ok(Some(best)) => best,
Ok(None) => return None,
Err(error) => return Some(relation_failure(inputs, original, &error)),
};
let validity = RetargetValidity::judged(original, &best.analysis, best.reasons, best.strategy)
.with_girdle_thickened(best.girdle_step);
Some(RetargetCheck {
validity,
anchors: best.anchors,
metrics: measure(inputs, original, &best.analysis),
})
}
fn relation_failure(
inputs: &CheckInputs<'_>,
original: &StoneAnalysis,
error: &RelationError,
) -> RetargetCheck {
let reason = InvalidReason::RelationFails(error.to_string());
let none: AnalysisResult = Err(reason.clone());
RetargetCheck {
validity: RetargetValidity::judged(
original,
&none,
vec![reason],
RetargetStrategy::AnglesOnly,
),
anchors: Vec::new(),
metrics: measure(inputs, original, &none),
}
}
fn unchecked(reason: &InvalidReason) -> RetargetCheck {
RetargetCheck {
validity: RetargetValidity::unchecked(reason),
anchors: Vec::new(),
metrics: RetargetMetrics::default(),
}
}
#[must_use]
pub fn run_check(
inputs: &CheckInputs<'_>,
cached: Option<Arc<AnalysisResult>>,
should_stop: &dyn Fn() -> bool,
) -> Option<(Arc<AnalysisResult>, RetargetCheck)> {
let original = cached.unwrap_or_else(|| Arc::new(analyze(inputs.design, true)));
if should_stop() {
return None;
}
let check = match original.as_ref() {
Ok(analysis) => check_against(inputs, analysis, should_stop)?,
Err(reason) => unchecked(reason),
};
Some((original, check))
}
#[must_use]
pub fn check_retarget(inputs: &CheckInputs<'_>) -> RetargetCheck {
run_check(inputs, None, &|| false)
.map_or_else(|| unchecked(&InvalidReason::NotClosed), |(_, check)| check)
}
#[cfg(test)]
mod tests;