use crate::core::auto_trace_bezier::{reparameterize_newton, solve_schneider_cubic_lsq};
use crate::core::bezier_ops::{align_collinear_opposite, Node, NodeId, NodeType};
use crate::core::coordinates::FontPoint;
use crate::core::curve_manipulation::ContourSegment;
use crate::core::math_consts::{
COLLINEAR_MIN_LEN_EPSILON, CUBIC_ONE_THIRD, CUBIC_TWO_THIRDS, FIT_SAMPLES_PER_SEGMENT,
NEWTON_REPARAM_ITERATIONS, PARAM_CLAMP_MAX, PARAM_CLAMP_MIN, SPLIT_RATIO_MIN,
};
use kurbo::{ParamCurve, Point, Vec2};
#[must_use]
pub fn expanded_nodes_with_attached_handles(
contours: &[Vec<Node>],
closed_flags: &[bool],
selected: &[NodeId],
include_attached: bool,
) -> Vec<NodeId> {
let mut result: Vec<NodeId> = Vec::new();
for &id in selected {
if !result.contains(&id) {
result.push(id);
}
}
if !include_attached {
return result;
}
for (c_idx, contour) in contours.iter().enumerate() {
let n = contour.len();
if n < 2 {
continue;
}
let closed = closed_flags.get(c_idx).copied().unwrap_or(true);
for (i, node) in contour.iter().enumerate() {
if node.node_type == NodeType::OffCurve || !selected.contains(&node.id) {
continue;
}
if closed || i > 0 {
let prev_idx = (i + n - 1) % n;
if contour[prev_idx].node_type == NodeType::OffCurve {
let pid = contour[prev_idx].id;
if !result.contains(&pid) {
result.push(pid);
}
}
}
if closed || i + 1 < n {
let next_idx = (i + 1) % n;
if contour[next_idx].node_type == NodeType::OffCurve {
let nid = contour[next_idx].id;
if !result.contains(&nid) {
result.push(nid);
}
}
}
}
}
result
}
pub fn enforce_smooth_collinearity_on_handle_drag(
contour: &mut [Node],
closed: bool,
moved_handle_id: NodeId,
alt_held: bool,
) {
let n = contour.len();
if n < 3 {
return;
}
let Some(h_idx) = contour.iter().position(|nd| nd.id == moved_handle_id) else {
return;
};
if contour[h_idx].node_type != NodeType::OffCurve {
return;
}
let prev_candidate = if closed || h_idx > 0 {
Some((h_idx + n - 1) % n)
} else {
None
};
let next_candidate = if closed || h_idx + 1 < n {
Some((h_idx + 1) % n)
} else {
None
};
let anchor_and_opp = if let Some(p_idx) =
prev_candidate.filter(|&i| contour[i].node_type != NodeType::OffCurve)
{
let opp = if closed || p_idx > 0 {
Some((p_idx + n - 1) % n)
} else {
None
};
Some((p_idx, opp))
} else if let Some(n_idx) =
next_candidate.filter(|&i| contour[i].node_type != NodeType::OffCurve)
{
let opp = if closed || n_idx + 1 < n {
Some((n_idx + 1) % n)
} else {
None
};
Some((n_idx, opp))
} else {
None
};
let Some((anchor_idx, opp_opt)) = anchor_and_opp else {
return;
};
if contour[anchor_idx].node_type != NodeType::Smooth {
return;
}
if alt_held {
contour[anchor_idx].node_type = NodeType::Corner;
return;
}
if let Some(opp_idx) = opp_opt {
if opp_idx != h_idx && contour[opp_idx].node_type == NodeType::OffCurve {
let new_opp = align_collinear_opposite(
contour[anchor_idx].point,
contour[opp_idx].point,
contour[h_idx].point,
);
contour[opp_idx].point = new_opp;
}
}
}
pub fn convert_line_segment_to_cubic(
contour: &mut Vec<Node>,
segment: &ContourSegment,
next_node_id: &mut u64,
) -> Option<(NodeId, NodeId)> {
convert_line_segment_to_cubic_with_grid(contour, segment, next_node_id, 0.0)
}
pub fn convert_line_segment_to_cubic_with_grid(
contour: &mut Vec<Node>,
segment: &ContourSegment,
next_node_id: &mut u64,
grid_step_upm: f64,
) -> Option<(NodeId, NodeId)> {
let ContourSegment::Line {
start_idx,
end_idx,
line,
} = *segment
else {
return None;
};
let max_existing = contour.iter().map(|n| n.id.0).max().unwrap_or(0);
if *next_node_id <= max_existing {
*next_node_id = max_existing + 1;
}
let p1 = FontPoint::new(line.eval(CUBIC_ONE_THIRD).x, line.eval(CUBIC_ONE_THIRD).y)
.round_to_grid_step(grid_step_upm);
let p2 = FontPoint::new(line.eval(CUBIC_TWO_THIRDS).x, line.eval(CUBIC_TWO_THIRDS).y)
.round_to_grid_step(grid_step_upm);
let h1_id = NodeId(*next_node_id);
*next_node_id += 1;
let h2_id = NodeId(*next_node_id);
*next_node_id += 1;
let h1 = Node::new(h1_id, p1.x.0, p1.y.0, NodeType::OffCurve);
let h2 = Node::new(h2_id, p2.x.0, p2.y.0, NodeType::OffCurve);
let insert_pos = if end_idx > start_idx {
end_idx
} else {
contour.len()
};
contour.insert(insert_pos, h1);
contour.insert(insert_pos + 1, h2);
Some((h1_id, h2_id))
}
#[must_use]
pub fn cycle_selection_tab(
contours: &[Vec<Node>],
selected: &[NodeId],
reverse: bool,
) -> Option<NodeId> {
let target = *selected.first()?;
for contour in contours {
let n = contour.len();
if n == 0 {
continue;
}
if let Some(idx) = contour.iter().position(|nd| nd.id == target) {
let next_idx = if reverse {
(idx + n - 1) % n
} else {
(idx + 1) % n
};
return Some(contour[next_idx].id);
}
}
None
}
pub fn toggle_selected_on_curve_smooth(
contours: &mut [Vec<Node>],
closed_flags: &[bool],
selected: &[NodeId],
) -> bool {
let mut changed = false;
for (c_idx, contour) in contours.iter_mut().enumerate() {
let n = contour.len();
let closed = closed_flags.get(c_idx).copied().unwrap_or(true);
for i in 0..n {
if !selected.contains(&contour[i].id) || contour[i].node_type == NodeType::OffCurve {
continue;
}
contour[i].node_type = match contour[i].node_type {
NodeType::Corner => NodeType::Smooth,
NodeType::Smooth | NodeType::HobbyStar { .. } | NodeType::EulerSpiro { .. } => {
NodeType::Corner
}
NodeType::OffCurve => NodeType::OffCurve,
};
changed = true;
if contour[i].node_type == NodeType::Smooth && n >= 3 {
let prev_idx = (i + n - 1) % n;
let next_idx = (i + 1) % n;
if (closed || (i > 0 && i + 1 < n))
&& contour[prev_idx].node_type == NodeType::OffCurve
&& contour[next_idx].node_type == NodeType::OffCurve
{
let aligned = align_collinear_opposite(
contour[i].point,
contour[prev_idx].point,
contour[next_idx].point,
);
contour[prev_idx].point = aligned;
}
}
}
}
changed
}
fn seg_endpoints_and_tangents(seg: &ContourSegment) -> (Point, Point, Vec2, Vec2) {
match *seg {
ContourSegment::Line { line, .. } => {
let v = line.p1 - line.p0;
(line.p0, line.p1, v, -v)
}
ContourSegment::Cubic { cubic, .. } => {
let mut v1 = cubic.p1 - cubic.p0;
if v1.hypot() <= COLLINEAR_MIN_LEN_EPSILON {
v1 = cubic.p3 - cubic.p0;
}
let mut v2 = cubic.p2 - cubic.p3;
if v2.hypot() <= COLLINEAR_MIN_LEN_EPSILON {
v2 = cubic.p0 - cubic.p3;
}
(cubic.p0, cubic.p3, v1, v2)
}
}
}
fn sample_segment_chain_for_fit(segments: &[ContourSegment]) -> (Vec<Point>, Vec<f64>) {
let mut weights = vec![1.0_f64; segments.len()];
for idx in 0..segments.len().saturating_sub(1) {
let d_in = match segments[idx] {
ContourSegment::Cubic { cubic, .. } => (cubic.p3 - cubic.p2).hypot(),
ContourSegment::Line { line, .. } => (line.p1 - line.p0).hypot() * CUBIC_ONE_THIRD,
};
let d_out = match segments[idx + 1] {
ContourSegment::Cubic { cubic, .. } => (cubic.p1 - cubic.p0).hypot(),
ContourSegment::Line { line, .. } => (line.p1 - line.p0).hypot() * CUBIC_ONE_THIRD,
};
let ratio = if d_in > COLLINEAR_MIN_LEN_EPSILON && d_out > COLLINEAR_MIN_LEN_EPSILON {
(d_out / d_in).clamp(SPLIT_RATIO_MIN, 1.0 / SPLIT_RATIO_MIN)
} else {
1.0
};
weights[idx + 1] = weights[idx] * ratio;
}
let weight_sum: f64 = weights.iter().sum::<f64>().max(COLLINEAR_MIN_LEN_EPSILON);
let mut pts: Vec<Point> = Vec::new();
let mut params: Vec<f64> = Vec::new();
let mut u_acc = 0.0;
for (seg, &w) in segments.iter().zip(&weights) {
let span = w / weight_sum;
for k in 0..FIT_SAMPLES_PER_SEGMENT {
if u_acc == 0.0 && k == 0 {
continue;
}
let local_t = (k as f64) / (FIT_SAMPLES_PER_SEGMENT as f64);
let u = (u_acc + span * local_t).clamp(PARAM_CLAMP_MIN, PARAM_CLAMP_MAX);
let pt = match *seg {
ContourSegment::Line { line, .. } => line.eval(local_t),
ContourSegment::Cubic { cubic, .. } => cubic.eval(local_t),
};
pts.push(pt);
params.push(u);
}
if (u_acc..=u_acc + span).contains(&0.5) {
let lt = ((0.5 - u_acc) / span).clamp(0.0, 1.0);
let pt = match *seg {
ContourSegment::Line { line, .. } => line.eval(lt),
ContourSegment::Cubic { cubic, .. } => cubic.eval(lt),
};
pts.push(pt);
params.push(0.5);
}
u_acc += span;
}
(pts, params)
}
#[must_use]
pub fn fit_cubic_to_segment_chain(segments: &[ContourSegment]) -> (FontPoint, FontPoint) {
debug_assert!(!segments.is_empty());
let (p0, _, v1_raw, _) = seg_endpoints_and_tangents(&segments[0]);
let (_, p3, _, v2_raw) = seg_endpoints_and_tangents(&segments[segments.len() - 1]);
let chord = (p3 - p0).hypot().max(1.0);
let t1 = if v1_raw.hypot() > COLLINEAR_MIN_LEN_EPSILON {
v1_raw / v1_raw.hypot()
} else {
(p3 - p0) / chord
};
let t2 = if v2_raw.hypot() > COLLINEAR_MIN_LEN_EPSILON {
v2_raw / v2_raw.hypot()
} else {
(p0 - p3) / chord
};
let (pts, mut params) = sample_segment_chain_for_fit(segments);
if segments.len() >= 2 && t1.cross(t2).abs() <= COLLINEAR_MIN_LEN_EPSILON && t1.dot(t2) > 0.0 {
let mid_chord = p0 + (p3 - p0) * 0.5;
let arch_h = pts
.iter()
.map(|&pt| (pt - mid_chord).dot(t1))
.fold(0.0_f64, f64::max);
if arch_h > COLLINEAR_MIN_LEN_EPSILON {
let alpha_arch = 2.0 * CUBIC_TWO_THIRDS * arch_h;
let h1_u = p0 + t1 * alpha_arch;
let h2_u = p3 + t2 * alpha_arch;
return (
FontPoint::new(h1_u.x, h1_u.y),
FontPoint::new(h2_u.x, h2_u.y),
);
}
}
let mut alpha1 = chord * CUBIC_ONE_THIRD;
let mut alpha2 = chord * CUBIC_ONE_THIRD;
let tan_l = (t1.x, t1.y);
let tan_r = (t2.x, t2.y);
for _ in 0..=NEWTON_REPARAM_ITERATIONS {
let (a1, a2, cand) = solve_schneider_cubic_lsq(
(p0, p3),
&pts,
¶ms,
tan_l,
tan_r,
COLLINEAR_MIN_LEN_EPSILON,
(alpha1, alpha2),
);
alpha1 = a1;
alpha2 = a2;
reparameterize_newton(
cand,
&pts,
&mut params,
false,
(PARAM_CLAMP_MIN, PARAM_CLAMP_MAX),
);
}
let h1_final = p0 + t1 * alpha1;
let h2_final = p3 + t2 * alpha2;
(
FontPoint::new(h1_final.x, h1_final.y),
FontPoint::new(h2_final.x, h2_final.y),
)
}