use super::{
gesture::{AppliedEdit, GestureInputs, Step, tier_label},
projection::{ScreenPoint, ScreenSize},
slice::{SliceSide, SnappedFacet, slice_normal, slice_tier, snap_to_gear, tangency_mast},
target::{CAMERA_FOV_DEG, HandleTarget, ids_aligned, target_for},
text,
};
use crate::session::clamp_nudge_to_side;
use glam::Vec3;
use indicatrix::{
geometry::meet_solver::{MeetConstraint, SolveStrategy, SolvedTier},
optics::raytracer::Camera,
};
use indicatrix_cut_core::{
ConstraintTier, Design, Edit, design::TierRef, expected_orbit, rotate_indices,
};
use indicatrix_solid::{facet_map::FacetMap, preview::FrameGeometry};
use std::{collections::BTreeSet, rc::Rc, sync::Arc};
pub const SLICE_ANGLE_STEP_DEG: f64 = 0.1;
pub type CornerPoints = Arc<Vec<Vec3>>;
pub const PROVISIONAL_GENERATION: u64 = u64::MAX - 1;
#[must_use]
pub const fn frame_updates_mast_cache(generation: u64) -> bool {
generation != PROVISIONAL_GENERATION
}
#[must_use]
pub const fn session_outlives(base_generation: u64, current_generation: u64) -> bool {
base_generation == current_generation
}
#[must_use]
pub fn wheel_turn(more: i64, gear: u32) -> Option<u32> {
if gear == 0 {
return None;
}
u32::try_from(more.rem_euclid(i64::from(gear)))
.ok()
.filter(|&teeth| teeth != 0)
}
#[must_use]
pub fn surviving_facets(
tier_facets: &[u32],
centroids: &[Option<Vec3>],
map_facets: usize,
) -> Option<usize> {
ids_aligned(map_facets, centroids.len()).then(|| {
tier_facets
.iter()
.filter(|&&id| centroids.get(id as usize).is_some_and(Option::is_some))
.count()
})
}
pub const CUT_ROUGH: i32 = -2;
#[must_use]
pub fn cut_hides_tier(cutoff: i32, step: usize) -> bool {
cutoff == CUT_ROUGH || usize::try_from(cutoff).is_ok_and(|through| through < step)
}
#[must_use]
pub fn tier_step(design: &Design, tier_index: usize) -> Option<usize> {
design
.preview_steps()
.iter()
.position(|step| *step == TierRef::Flat(tier_index))
}
#[must_use]
pub const fn keep_allowed(surviving: Option<usize>) -> bool {
matches!(surviving, Some(count) if count > 0)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscardReason {
User,
DesignChanged,
SelectionChanged,
}
impl DiscardReason {
#[must_use]
pub const fn replans(self) -> bool {
!matches!(self, Self::SelectionChanged)
}
#[must_use]
pub fn toast(self, label: &str) -> String {
match self {
Self::User => text::slice_discarded_toast(label),
Self::DesignChanged => text::SLICE_CHANGED_TOAST.to_string(),
Self::SelectionChanged => text::SLICE_SELECTION_TOAST.to_string(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SliceLine {
pub a: ScreenPoint,
pub b: ScreenPoint,
pub size: ScreenSize,
pub pose: (f32, f32, f32),
}
impl SliceLine {
#[must_use]
pub const fn new(a: ScreenPoint, b: ScreenPoint, geometry: &FrameGeometry) -> Self {
Self {
a,
b,
size: ScreenSize::new(geometry.size.0 as f32, geometry.size.1 as f32),
pose: (
geometry.camera.yaw,
geometry.camera.pitch,
geometry.camera.distance,
),
}
}
#[must_use]
pub fn normal(&self, side: SliceSide) -> Option<Vec3> {
let (yaw, pitch, distance) = self.pose;
let camera = Camera::new(yaw, pitch, distance, CAMERA_FOV_DEG);
slice_normal(&camera, self.a, self.b, self.size, side)
}
}
#[derive(Debug, Clone)]
pub struct SlicePlan {
pub snapped: SnappedFacet,
pub tier: ConstraintTier,
}
#[must_use]
pub fn plan_slice(
line: &SliceLine,
side: SliceSide,
corners: &[Vec3],
design: &Design,
symmetric: bool,
) -> Option<SlicePlan> {
let normal = line.normal(side)?;
let snapped = snap_to_gear(normal, design.meta.gear_teeth_abs(), SLICE_ANGLE_STEP_DEG);
let mast = tangency_mast(snapped.normal, corners);
let names: Vec<String> = design
.tiers
.iter()
.flat_map(|tier| tier.names().into_iter().map(str::to_string))
.collect();
let tier = slice_tier(&snapped, mast, &design.meta, symmetric, &names);
Some(SlicePlan { snapped, tier })
}
#[must_use]
pub fn with_provisional_tier(design: &Design, tier: ConstraintTier) -> Option<(Design, usize)> {
let mut provisional = design.clone();
let index = provisional.tiers.len();
provisional.apply_edit(Edit::AddTier { index, tier }).ok()?;
Some((provisional, index))
}
#[derive(Debug, Clone)]
pub struct Snapshot {
pub tier: ConstraintTier,
pub snapped: SnappedFacet,
}
#[derive(Debug)]
pub struct ProvisionalSlice {
pub base_generation: u64,
pub design: Arc<Design>,
pub tier_index: usize,
pub side: SliceSide,
pub snapped: SnappedFacet,
pub line: SliceLine,
pub base_corners: CornerPoints,
pub masts: Option<Vec<SolvedTier>>,
facet_map: Option<Rc<FacetMap>>,
outline: Vec<u32>,
masts_new: bool,
surviving: Option<usize>,
}
impl ProvisionalSlice {
#[must_use]
pub fn build(
line: SliceLine,
side: SliceSide,
corners: CornerPoints,
design: &Design,
base_generation: u64,
symmetric: bool,
) -> Option<Self> {
let plan = plan_slice(&line, side, &corners, design, symmetric)?;
let (provisional, tier_index) = with_provisional_tier(design, plan.tier)?;
Some(Self {
base_generation,
design: Arc::new(provisional),
tier_index,
side,
snapped: plan.snapped,
line,
base_corners: corners,
masts: None,
facet_map: None,
outline: Vec::new(),
masts_new: false,
surviving: None,
})
}
#[must_use]
pub fn tier(&self) -> Option<&ConstraintTier> {
self.design.tiers.get(self.tier_index)
}
#[must_use]
pub fn label(&self) -> Option<String> {
self.tier().map(|tier| tier_label(tier, self.tier_index))
}
pub fn facet_map(&mut self) -> Option<Rc<FacetMap>> {
if self.facet_map.is_none() {
let masts = self
.masts
.as_ref()
.filter(|masts| masts.len() == self.design.tiers.len())?;
self.facet_map = Some(Rc::new(FacetMap::from_design(&self.design, masts)));
}
self.facet_map.clone()
}
#[must_use]
pub fn facet_count(&self) -> usize {
self.surviving
.unwrap_or_else(|| self.tier().map_or(0, |tier| tier.indices.len()))
}
#[must_use]
pub const fn may_keep(&self) -> bool {
keep_allowed(self.surviving)
}
#[must_use]
pub fn hint(&self) -> String {
let Some(tier) = self.tier() else {
return String::new();
};
if self.surviving == Some(0) {
return format!(
"New tier {}: {}. Esc discards it.",
tier_label(tier, self.tier_index),
text::SLICE_NO_DEPTH_HINT
);
}
text::slice_provisional_hint(
&tier_label(tier, self.tier_index),
self.facet_count(),
tier.angle_deg,
self.snapped.index,
)
}
pub fn place(&mut self, geometry: &FrameGeometry) -> Option<HandleTarget> {
let map = self.facet_map()?;
target_for(geometry, &map, &self.design, self.tier_index, None, true)
}
#[must_use]
pub fn snapshot(&self) -> Option<Snapshot> {
self.tier().map(|tier| Snapshot {
tier: tier.clone(),
snapped: self.snapped,
})
}
#[must_use]
pub fn gesture_inputs(&self) -> Option<GestureInputs> {
let tier = self.tier()?;
Some(GestureInputs {
start_angle_deg: tier.angle_deg,
masts: self.masts.clone(),
restore: self.snapshot(),
})
}
#[must_use]
pub fn replan_chain(
&self,
committed_masts: Option<&[SolvedTier]>,
) -> (Option<Vec<SolvedTier>>, BTreeSet<usize>) {
let tier_count = self.design.tiers.len();
if let Some(masts) = self.masts.as_deref().filter(|m| m.len() == tier_count) {
return (Some(masts.to_vec()), BTreeSet::from([self.tier_index]));
}
let pinned = match self.tier().map(|tier| &tier.constraint) {
Some(MeetConstraint::ScaleReference(mast)) => Some(*mast),
_ => None,
};
match (committed_masts, pinned) {
(Some(committed), Some(mast)) if committed.len() + 1 == tier_count => {
let mut masts = committed.to_vec();
masts.push(SolvedTier {
mast,
strategy: SolveStrategy::ScaleReference,
detail: "given (scale reference)".to_string(),
});
(Some(masts), BTreeSet::from([self.tier_index]))
}
_ => (None, BTreeSet::new()),
}
}
pub fn note_masts(&mut self, masts: Vec<SolvedTier>) {
if masts.len() == self.design.tiers.len() {
self.masts = Some(masts);
self.facet_map = None;
self.masts_new = true;
}
}
pub fn take_outline_update(
&mut self,
geometry: Option<&FrameGeometry>,
) -> Option<(bool, Vec<u32>)> {
if !std::mem::take(&mut self.masts_new) {
return None;
}
let map = self.facet_map()?;
let ids = map.facets_of_tier(self.tier_index).to_vec();
if let Some(geometry) = geometry {
self.surviving = surviving_facets(&ids, &geometry.facet_centroids, map.facet_count());
}
let changed = ids != self.outline;
if changed {
self.outline.clone_from(&ids);
}
Some((changed, ids))
}
pub fn apply_step(&mut self, step: Step) -> Option<AppliedEdit> {
let changed = match step {
Step::Angle(deg) => self.set_angle(deg),
Step::Mast(mast) => self.set_mast(mast),
Step::Teeth(more) => self.turn(more),
};
if changed {
self.facet_map = None;
}
changed.then_some(AppliedEdit {
generation: 0,
replaced_meet: None,
})
}
fn set_angle(&mut self, deg: f64) -> bool {
let index = self.tier_index;
let Some(tier) = Arc::make_mut(&mut self.design).tiers.get_mut(index) else {
return false;
};
let new = clamp_nudge_to_side(tier.angle_deg, deg);
if !new.is_finite() || new.to_bits() == tier.angle_deg.to_bits() {
return false;
}
tier.angle_deg = new;
self.snapped.angle_deg = new;
true
}
fn set_mast(&mut self, mast: f64) -> bool {
let index = self.tier_index;
let Some(tier) = Arc::make_mut(&mut self.design).tiers.get_mut(index) else {
return false;
};
let unchanged = matches!(&tier.constraint, MeetConstraint::ScaleReference(m) if m.to_bits() == mast.to_bits());
if !mast.is_finite() || unchanged {
return false;
}
tier.constraint = MeetConstraint::ScaleReference(mast);
true
}
fn turn(&mut self, more: i64) -> bool {
let gear = self.design.meta.gear_teeth_abs();
let Some(teeth) = wheel_turn(more, gear).map(f64::from) else {
return false;
};
let index = self.tier_index;
let Some(tier) = Arc::make_mut(&mut self.design).tiers.get_mut(index) else {
return false;
};
let mut indices = rotate_indices(&tier.indices, teeth, gear);
indices.sort_by(f64::total_cmp);
tier.indices = indices;
let anchor = rotate_indices(&[self.snapped.index], teeth, gear);
self.snapped.index = anchor.first().copied().unwrap_or(self.snapped.index);
true
}
pub fn restore(&mut self, snapshot: Snapshot) -> bool {
let index = self.tier_index;
let Some(slot) = Arc::make_mut(&mut self.design).tiers.get_mut(index) else {
return false;
};
*slot = snapshot.tier;
self.snapped = snapshot.snapped;
self.facet_map = None;
true
}
pub fn rebuild_indices(&mut self, symmetric: bool) -> bool {
let indices = {
let meta = &self.design.meta;
if symmetric {
expected_orbit(
self.snapped.index,
meta.symmetry_order,
meta.mirror,
meta.gear_teeth_abs(),
)
} else {
vec![self.snapped.index]
}
};
let index = self.tier_index;
let Some(tier) = Arc::make_mut(&mut self.design).tiers.get_mut(index) else {
return false;
};
tier.indices = indices;
tier.detached.clear();
self.facet_map = None;
true
}
}
#[must_use]
pub fn resting_hint(
provisional: Option<&ProvisionalSlice>,
cutoff: i32,
slice_mode: bool,
symmetric: bool,
) -> String {
provisional
.filter(|p| {
tier_step(&p.design, p.tier_index).is_some_and(|step| cut_hides_tier(cutoff, step))
})
.map(|_| text::SLICE_CUT_SLIDER_HINT.to_string())
.or_else(|| provisional.map(ProvisionalSlice::hint))
.or_else(|| slice_mode.then(|| text::slice_mode_hint(symmetric)))
.unwrap_or_default()
}