Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

76.5 KB
Raw Blame
//! Watertight topological & geometric modeling operations operating via semantic selectors.
//! Includes: extrude, inset, bevel (exact circular/chamfer fillets + general polyhedral bevel),
//! Catmull-Clark subdivision, shell/hollow, mirror, linear/radial/grid arrays, and relational placement.

use crate::boolean::{boolean_op, BoolOp};
use crate::curves::{make_extrude_2d_with_holes, poly_area_2d, segs_properly_intersect};
use crate::math::Vec3;
use crate::mesh::{edge_key, Face, PolyMesh};
use crate::primitives::make_extrude_2d;
use crate::selector::{EdgeSelector, FaceSelector};
use smallvec::{smallvec, SmallVec};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;

/// Extrude selected faces along their average normal (or explicit offset vector),
/// replacing the selected patch with clean side walls and an extruded cap.
pub fn extrude_faces(
    mesh: &PolyMesh,
    sel: &FaceSelector,
    dist: f64,
    dir: Option<Vec3>,
    op_id: u32,
) -> Result<PolyMesh, String> {
    let selected: HashSet<usize> = sel.select(mesh).into_iter().collect();
    if selected.is_empty() {
        return Err("extrude: face selector matched 0 faces".into());
    }
    let avg_normal = if let Some(d) = dir {
        d.normalized()
    } else {
        let mut s = Vec3::ZERO;
        for &fi in &selected {
            s += mesh.face_normal(fi);
        }
        s.normalized()
    };
    if avg_normal.len_sq() < 1e-12 {
        return Err("extrude: selected faces have zero average normal".into());
    }
    let offset = avg_normal * dist;
    if !offset.is_finite() {
        return Err(format!("extrude: distance must be finite (got {dist})"));
    }

    // Inward extrusion (offset against the selected faces' own normals) cannot be built by
    // stitching walls: they would fold back through the solid and the moved cap would pass
    // through it. It is a pocket: subtract the swept prism from the part instead.
    let mut own_normal = Vec3::ZERO;
    for &fi in &selected {
        own_normal += mesh.face_normal(fi) * mesh.face_area(fi);
    }
    if offset.dot(own_normal) < 0.0 {
        return extrude_inward_pocket(mesh, &selected, offset, dist, op_id);
    }

    let mut out = mesh.clone();
    // Collect boundary directed edges of the selected region
    let mut sel_dir_edges: HashSet<(usize, usize)> = HashSet::new();
    let mut sel_verts: HashSet<usize> = HashSet::new();
    for &fi in &selected {
        let fv = &mesh.faces[fi].verts;
        let n = fv.len();
        for i in 0..n {
            sel_verts.insert(fv[i]);
            sel_dir_edges.insert((fv[i], fv[(i + 1) % n]));
        }
    }

    // Duplicate vertices belonging to the selected patch
    let mut dup_map: HashMap<usize, usize> = HashMap::new();
    let mut sorted_verts: Vec<usize> = sel_verts.into_iter().collect();
    sorted_verts.sort_unstable();
    for v in sorted_verts {
        let nv = out.add_vert(mesh.verts[v] + offset);
        dup_map.insert(v, nv);
    }

    // Move selected faces onto duplicated vertices (preserving tags + adding "cap")
    for &fi in &selected {
        for vi in &mut out.faces[fi].verts {
            *vi = dup_map[vi];
        }
        out.faces[fi].add_tag("cap");
        out.faces[fi].op_id = op_id;
    }

    // Stitch boundary edges of the selected region with quad walls
    let mut wall_edges: Vec<(usize, usize)> = sel_dir_edges
        .iter()
        .copied()
        .filter(|&(u, v)| !sel_dir_edges.contains(&(v, u)))
        .collect();
    wall_edges.sort_unstable();
    for (u, v) in wall_edges {
        let nu = dup_map[&u];
        let nv = dup_map[&v];
        out.add_face(smallvec![u, v, nv, nu], op_id, Some("wall"));
    }

    out.compact_unused_verts();
    out.ensure_outward_winding();
    Ok(out)
}

/// Inward `extrude`: removes the prism swept by the selected faces along `offset`.
fn extrude_inward_pocket(
    mesh: &PolyMesh,
    selected: &HashSet<usize>,
    offset: Vec3,
    dist: f64,
    op_id: u32,
) -> Result<PolyMesh, String> {
    let mut sel_sorted: Vec<usize> = selected.iter().copied().collect();
    sel_sorted.sort_unstable();
    let mut tool = PolyMesh::new();
    let mut top: HashMap<usize, usize> = HashMap::new();
    let mut bot: HashMap<usize, usize> = HashMap::new();
    let mut dir_edges: HashSet<(usize, usize)> = HashSet::new();
    for &fi in &sel_sorted {
        let fv = &mesh.faces[fi].verts;
        let n = fv.len();
        for i in 0..n {
            let v = fv[i];
            top.entry(v).or_insert_with(|| {
                let t = tool.add_vert(mesh.verts[v]);
                let b = tool.add_vert(mesh.verts[v] + offset);
                bot.insert(v, b);
                t
            });
            dir_edges.insert((v, fv[(i + 1) % n]));
        }
    }
    for &fi in &sel_sorted {
        let fv = &mesh.faces[fi].verts;
        let up: SmallVec<[usize; 4]> = fv.iter().map(|v| top[v]).collect();
        let down: SmallVec<[usize; 4]> = fv.iter().rev().map(|v| bot[v]).collect();
        tool.add_face(up, op_id, None);
        tool.add_face(down, op_id, None);
    }
    let mut walls: Vec<(usize, usize)> = dir_edges.iter().copied().filter(|&(u, v)| !dir_edges.contains(&(v, u))).collect();
    walls.sort_unstable();
    for (u, v) in walls {
        tool.add_face(smallvec![top[&v], top[&u], bot[&u], bot[&v]], op_id, None);
    }
    let tool_vol = tool.signed_volume();
    if !tool_vol.is_finite() || tool_vol.abs() < 1e-300 {
        return Err(format!("extrude: distance {dist} sweeps no volume (selected faces are parallel to the extrusion direction)"));
    }
    if tool_vol < 0.0 {
        tool.flip_winding();
    }
    let mut out = crate::boolean::boolean_op(mesh, &tool, crate::boolean::BoolOp::Difference, Some("extrude"), op_id)
        .map_err(|e| format!("extrude: inward distance {dist} could not be cut as a pocket ({e})"))?;
    if out.faces.is_empty() {
        return Err(format!("extrude: inward distance {dist} pushes the selected faces through the whole part (nothing would remain)"));
    }
    let dir = offset.normalized();
    for fi in 0..out.faces.len() {
        if out.faces[fi].has_tag("bool:extrude") {
            let tag = if out.face_normal(fi).dot(dir) < -0.5 { "cap" } else { "wall" };
            out.faces[fi].add_tag(tag);
        }
    }
    Ok(out)
}

/// Inset each selected face by a uniform border `amount` wide (every edge offset inward by
/// `amount` in the face plane), optionally offsetting the inner face along its normal by `depth`.
/// Errors when the amount is not positive or does not fit the face.
pub fn inset_faces(
    mesh: &PolyMesh,
    sel: &FaceSelector,
    amount: f64,
    depth: f64,
    op_id: u32,
) -> Result<PolyMesh, String> {
    let selected: Vec<usize> = sel.select(mesh);
    if selected.is_empty() {
        return Err("inset: face selector matched 0 faces".into());
    }
    if !amount.is_finite() || amount <= 0.0 {
        return Err(format!("inset: amount must be a finite distance > 0 (got {amount})"));
    }
    if !depth.is_finite() {
        return Err(format!("inset: depth must be finite (got {depth})"));
    }
    let sel_set: HashSet<usize> = selected.iter().copied().collect();
    let mut out = PolyMesh::new();
    out.verts = mesh.verts.clone();
    out.materials = mesh.materials.clone();
    out.smooth_angle_deg = mesh.smooth_angle_deg;
    out.weighted_normals = mesh.weighted_normals;

    for (fi, f) in mesh.faces.iter().enumerate() {
        if !sel_set.contains(&fi) {
            out.faces.push(f.clone());
            continue;
        }
        let nrm = mesh.face_normal(fi);
        let n = f.verts.len();
        // True polygon offset: every edge moves inward by `amount` in the face plane, so the
        // border is `amount` wide on every side (mitered corners).
        let mut edge_dir: SmallVec<[Vec3; 4]> = SmallVec::with_capacity(n);
        let mut edge_len: SmallVec<[f64; 4]> = SmallVec::with_capacity(n);
        for i in 0..n {
            let e = mesh.verts[f.verts[(i + 1) % n]] - mesh.verts[f.verts[i]];
            // Keep the direction in the face plane (faces may be slightly non-planar).
            let e = e - nrm * e.dot(nrm);
            let l = e.len();
            if n < 3 || !l.is_finite() || l < 1e-12 || nrm.len_sq() < 0.5 {
                return Err(format!("inset: face {fi} is degenerate (zero-length edge or zero area)"));
            }
            edge_dir.push(e / l);
            edge_len.push(l);
        }
        // Per-unit-amount displacement of each corner (miter of its two edge offsets).
        let mut corner: SmallVec<[Vec3; 4]> = SmallVec::with_capacity(n);
        for i in 0..n {
            let n_prev = nrm.cross(edge_dir[(i + n - 1) % n]);
            let n_next = nrm.cross(edge_dir[i]);
            let denom = 1.0 + n_prev.dot(n_next);
            if denom < 1e-6 {
                return Err(format!("inset: face {fi} has a corner that folds back on itself; it cannot be offset"));
            }
            corner.push((n_prev + n_next) / denom);
        }
        // Each edge shrinks linearly with the amount; the first edge to reach zero sets the limit.
        let mut max_amount = f64::INFINITY;
        for i in 0..n {
            let rate = (corner[(i + 1) % n] - corner[i]).dot(edge_dir[i]);
            if rate < -1e-12 {
                max_amount = max_amount.min(edge_len[i] / -rate);
            }
        }
        if amount >= max_amount * (1.0 - 1e-9) {
            return Err(format!(
                "inset: amount {amount} does not fit face {fi} (a uniform border on it must be narrower than {max_amount:.6})"
            ));
        }

        let mut inner_verts: SmallVec<[usize; 4]> = SmallVec::with_capacity(n);
        for (i, &vi) in f.verts.iter().enumerate() {
            let p = mesh.verts[vi];
            let np = p + corner[i] * amount + nrm * depth;
            inner_verts.push(out.add_vert(np));
        }
        // Rim quads
        for i in 0..n {
            let j = (i + 1) % n;
            let rim_fi = out.add_face(
                smallvec![f.verts[i], f.verts[j], inner_verts[j], inner_verts[i]],
                op_id,
                Some("rim"),
            );
            out.faces[rim_fi].mat_id = f.mat_id;
        }
        // Inner face
        let mut inner_tags = f.tags.clone();
        if !inner_tags.iter().any(|t| t == "inner") {
            inner_tags.push("inner".into());
        }
        let inner_fi = out.add_face_with_tags(inner_verts, op_id, Some(f.lineage), &inner_tags);
        out.faces[inner_fi].mat_id = f.mat_id;
    }
    out.compact_unused_verts();
    out.ensure_outward_winding();
    Ok(out)
}

/// Exact polyhedral edge bevel supporting:
/// - Vertical edges on box/prismatic solids (exact circular corner fillet with `segments`)
/// - Top / bottom / outer rim edges on boxes, prisms, and cylinders (exact chamfer/fillet profile)
/// - General sharp-edge bevels on arbitrary convex/manifold polyhedra.
pub fn bevel_edges(
    mesh: &PolyMesh,
    sel: &EdgeSelector,
    width: f64,
    segments: usize,
    op_id: u32,
) -> Result<PolyMesh, String> {
    bevel_edges_with_warning(mesh, sel, width, segments, op_id).map(|(m, _)| m)
}

/// Bevel selected edges, optionally returning a non-fatal warning (e.g. when `segments > 1`
/// is requested on the general 1-segment chamfer fallback).
pub fn bevel_edges_with_warning(
    mesh: &PolyMesh,
    sel: &EdgeSelector,
    width: f64,
    segments: usize,
    op_id: u32,
) -> Result<(PolyMesh, Option<String>), String> {
    if width <= 1e-7 {
        return Ok((mesh.clone(), None));
    }
    let mut warnings: Vec<String> = Vec::new();
    let clamped_segs = segments.clamp(1, 8);
    if segments != clamped_segs {
        warnings.push(format!(
            "bevel: segs={segments} clamped to {clamped_segs} (supported range 1..=8)"
        ));
    }
    let segments = clamped_segs;
    let edges = sel.select(mesh);
    if edges.is_empty() {
        return Err("bevel: edge selector matched 0 edges".into());
    }

    let join_warnings = |ws: Vec<String>| -> Option<String> {
        if ws.is_empty() {
            None
        } else {
            Some(ws.join("; "))
        }
    };

    // Specialized exact path 1: Vertical edges of a Z-prism/box (with or without holes)
    if matches!(sel, EdgeSelector::Vertical) {
        if let Some((filleted, clamped_w)) = try_bevel_vertical_prism(mesh, width, segments, op_id) {
            if let Some(w_used) = clamped_w {
                warnings.push(format!(
                    "bevel: width={width} clamped to {w_used:.4} to fit edge geometry"
                ));
            }
            return Ok((filleted, join_warnings(warnings)));
        }
    }

    // Specialized exact path 2: TopRim / BottomRim / OuterRim on a Z-prism/box/cylinder
    if matches!(
        sel,
        EdgeSelector::TopRim | EdgeSelector::BottomRim | EdgeSelector::OuterRim
    ) {
        let do_top = matches!(sel, EdgeSelector::TopRim | EdgeSelector::OuterRim);
        let do_bot = matches!(sel, EdgeSelector::BottomRim | EdgeSelector::OuterRim);
        if let Some((beveled, clamped_w)) = try_bevel_z_rims(mesh, width, segments, do_top, do_bot, op_id) {
            if let Some(w_used) = clamped_w {
                warnings.push(format!(
                    "bevel: width={width} clamped to {w_used:.4} to fit edge geometry"
                ));
            }
            return Ok((beveled, join_warnings(warnings)));
        }
    }

    // General path: chamfer/bevel arbitrary selected edges via vertex-split & corner bridging
    if segments > 1 {
        warnings.push(format!(
            "bevel: segs={segments} is only supported on prism/rim edges; fell back to 1-segment chamfer"
        ));
    }
    let (out, clamped_w) = bevel_general_polyhedron(mesh, &edges, width, op_id)?;
    if let Some(w_used) = clamped_w {
        warnings.push(format!(
            "bevel: width={width} clamped to {w_used:.4} to fit edge geometry"
        ));
    }
    Ok((out, join_warnings(warnings)))
}

fn simplify_collinear_2d(pts: &[(f64, f64)], rel_eps: f64) -> Vec<(f64, f64)> {
    let mut cur: Vec<(f64, f64)> = Vec::with_capacity(pts.len());
    for &p in pts {
        if cur.last().is_none_or(|&q| (p.0 - q.0).hypot(p.1 - q.1) > 1e-12) {
            cur.push(p);
        }
    }
    if cur.len() > 1
        && cur
            .last()
            .is_some_and(|&last| (cur[0].0 - last.0).hypot(cur[0].1 - last.1) <= 1e-12)
    {
        cur.pop();
    }
    let mut changed = true;
    while changed && cur.len() >= 3 {
        changed = false;
        let n = cur.len();
        let mut next_pts = Vec::with_capacity(n);
        for i in 0..n {
            let a = cur[(i + n - 1) % n];
            let b = cur[i];
            let c = cur[(i + 1) % n];
            let dx1 = b.0 - a.0;
            let dy1 = b.1 - a.1;
            let dx2 = c.0 - b.0;
            let dy2 = c.1 - b.1;
            let l1 = dx1.hypot(dy1);
            let l2 = dx2.hypot(dy2);
            if l1 < 1e-12 || l2 < 1e-12 {
                changed = true;
                continue;
            }
            let cross = (dx1 * dy2 - dy1 * dx2).abs();
            let dot = dx1 * dx2 + dy1 * dy2;
            if cross <= rel_eps * l1 * l2 && dot > 0.0 {
                changed = true;
                continue;
            }
            next_pts.push(b);
        }
        cur = next_pts;
    }
    cur
}

fn point_in_poly_2d(p: (f64, f64), poly: &[(f64, f64)]) -> bool {
    let n = poly.len();
    let mut inside = false;
    let mut j = n.saturating_sub(1);
    for i in 0..n {
        let (xi, yi) = poly[i];
        let (xj, yj) = poly[j];
        if ((yi > p.1) != (yj > p.1)) && (p.0 < (xj - xi) * (p.1 - yi) / (yj - yi) + xi) {
            inside = !inside;
        }
        j = i;
    }
    inside
}

fn poly_has_self_intersection_2d(poly: &[(f64, f64)]) -> bool {
    let n = poly.len();
    for i in 0..n {
        let a = poly[i];
        let b = poly[(i + 1) % n];
        for j in (i + 2)..n {
            if i == 0 && j == n - 1 {
                continue;
            }
            if segs_properly_intersect(a, b, poly[j], poly[(j + 1) % n]) {
                return true;
            }
        }
    }
    false
}

fn loops_disjoint_and_contained(outer: &[(f64, f64)], hole: &[(f64, f64)]) -> bool {
    if hole.is_empty() || outer.len() < 3 {
        return false;
    }
    if !hole.iter().all(|&p| point_in_poly_2d(p, outer)) {
        return false;
    }
    let no = outer.len();
    let nh = hole.len();
    for i in 0..no {
        let a = outer[i];
        let b = outer[(i + 1) % no];
        for j in 0..nh {
            if segs_properly_intersect(a, b, hole[j], hole[(j + 1) % nh]) {
                return false;
            }
        }
    }
    true
}

struct ZPrismFootprint {
    z0: f64,
    z1: f64,
    outer: Vec<(f64, f64)>,
    holes: Vec<Vec<(f64, f64)>>,
}

/// Extract the 2D footprint if `mesh` is a watertight axis-aligned Z-prism
/// (possibly with triangulated caps and up to 32 inner through-holes).
fn extract_z_prism_footprint(mesh: &PolyMesh) -> Option<ZPrismFootprint> {
    let bb = mesh.aabb();
    if !bb.is_valid() {
        return None;
    }
    let z0 = bb.min.z;
    let z1 = bb.max.z;
    let h = z1 - z0;
    if h < 1e-9 {
        return None;
    }
    let z_tol = (1e-4 * h).max(1e-9);

    let mut top_faces: Vec<usize> = Vec::new();
    let mut bot_count = 0usize;
    for (fi, f) in mesh.faces.iter().enumerate() {
        if f.verts.len() < 3 {
            return None;
        }
        let all_top = f.verts.iter().all(|&vi| (mesh.verts[vi].z - z1).abs() < z_tol);
        let all_bot = f.verts.iter().all(|&vi| (mesh.verts[vi].z - z0).abs() < z_tol);
        let fnrm = mesh.face_normal(fi);
        if all_top && (fnrm.z > 0.99 || fnrm.len_sq() < 1e-12) {
            top_faces.push(fi);
        } else if all_bot && (fnrm.z < -0.99 || fnrm.len_sq() < 1e-12) {
            bot_count += 1;
        } else {
            let vertical_face = fnrm.z.abs() < 0.02 || fnrm.len_sq() < 1e-12;
            let verts_on_caps = f
                .verts
                .iter()
                .all(|&vi| (mesh.verts[vi].z - z0).abs() < z_tol || (mesh.verts[vi].z - z1).abs() < z_tol);
            if !vertical_face || !verts_on_caps {
                return None;
            }
        }
    }
    if top_faces.is_empty() || bot_count == 0 {
        return None;
    }

    let mut top_dir: HashSet<(usize, usize)> = HashSet::new();
    for &fi in &top_faces {
        let fv = &mesh.faces[fi].verts;
        let k = fv.len();
        for i in 0..k {
            let u = fv[i];
            let v = fv[(i + 1) % k];
            if u != v {
                top_dir.insert((u, v));
            }
        }
    }

    let mut next_v: HashMap<usize, usize> = HashMap::new();
    for &(u, v) in &top_dir {
        if !top_dir.contains(&(v, u)) && next_v.insert(u, v).is_some() {
            return None; // non-manifold boundary pinch on top cap
        }
    }
    if next_v.is_empty() {
        return None;
    }

    let mut starts: Vec<usize> = next_v.keys().copied().collect();
    starts.sort_unstable();
    let mut visited: HashSet<usize> = HashSet::new();
    let mut outer_ccw: Option<Vec<(f64, f64)>> = None;
    let mut holes_cw: Vec<Vec<(f64, f64)>> = Vec::new();
    let rel_eps = 1e-7;

    for s in starts {
        if visited.contains(&s) {
            continue;
        }
        let mut loop_v = Vec::new();
        let mut cur = s;
        while !visited.contains(&cur) {
            visited.insert(cur);
            loop_v.push((mesh.verts[cur].x, mesh.verts[cur].y));
            cur = *next_v.get(&cur)?;
        }
        if cur != s {
            return None;
        }
        let simp = simplify_collinear_2d(&loop_v, rel_eps);
        if simp.len() < 3 {
            return None;
        }
        let area = poly_area_2d(&simp);
        if area > 1e-12 {
            if outer_ccw.is_some() {
                return None; // multiple disconnected islands
            }
            outer_ccw = Some(simp);
        } else if area < -1e-12 {
            holes_cw.push(simp);
        } else {
            return None;
        }
    }

    if holes_cw.len() > 32 {
        return None;
    }
    let outer = outer_ccw?;
    Some(ZPrismFootprint {
        z0,
        z1,
        outer,
        holes: holes_cw,
    })
}

/// Left-hand 2D polygon offset by `dist` (inward for CCW outer polygons, outward-into-solid for CW holes).
/// Trims locally inverted short edges (e.g. corner fillets with `radius <= dist`) cleanly.
fn offset_polygon_2d(pts: &[(f64, f64)], dist: f64) -> Option<Vec<(f64, f64)>> {
    let n = pts.len();
    if n < 3 {
        return None;
    }
    // Each active line: (origin on offset line, unit direction vector)
    let mut lines: Vec<((f64, f64), (f64, f64))> = Vec::with_capacity(n);
    for i in 0..n {
        let a = pts[i];
        let b = pts[(i + 1) % n];
        let dx = b.0 - a.0;
        let dy = b.1 - a.1;
        let len = dx.hypot(dy);
        if len < 1e-12 {
            continue;
        }
        let dir = (dx / len, dy / len);
        let left_n = (-dir.1, dir.0);
        lines.push(((a.0 + left_n.0 * dist, a.1 + left_n.1 * dist), dir));
    }
    let orig_area = poly_area_2d(pts);

    for _iter in 0..=n {
        let m = lines.len();
        if m < 3 {
            return None;
        }
        let mut merged_parallel = false;
        let mut q: Vec<(f64, f64)> = Vec::with_capacity(m);
        for i in 0..m {
            let j = (i + 1) % m;
            let (o1, d1) = lines[i];
            let (o2, d2) = lines[j];
            let det = d1.0 * d2.1 - d1.1 * d2.0;
            if det.abs() < 1e-9 {
                if d1.0 * d2.0 + d1.1 * d2.1 > 0.0 {
                    lines.remove(j);
                    merged_parallel = true;
                    break;
                } else {
                    return None;
                }
            }
            let diff = (o2.0 - o1.0, o2.1 - o1.1);
            let t = (diff.0 * d2.1 - diff.1 * d2.0) / det;
            q.push((o1.0 + t * d1.0, o1.1 + t * d1.1));
        }
        if merged_parallel {
            continue;
        }

        let mut drop_idx = None;
        for i in 0..m {
            let p_start = q[(i + m - 1) % m];
            let p_end = q[i];
            let dir = lines[i].1;
            let proj = (p_end.0 - p_start.0) * dir.0 + (p_end.1 - p_start.1) * dir.1;
            if proj <= 1e-9 {
                drop_idx = Some(i);
                break;
            }
        }
        if let Some(idx) = drop_idx {
            lines.remove(idx);
            continue;
        }

        let ordered: Vec<(f64, f64)> = (0..m).map(|i| q[(i + m - 1) % m]).collect();
        let simp = simplify_collinear_2d(&ordered, 1e-7);
        if simp.len() < 3 {
            return None;
        }
        let new_area = poly_area_2d(&simp);
        if (orig_area > 0.0 && new_area <= 1e-12) || (orig_area < 0.0 && new_area >= -1e-12) {
            return None;
        }
        if poly_has_self_intersection_2d(&simp) {
            return None;
        }
        return Some(simp);
    }
    None
}

/// Exact 2D corner-fillet + Z-extrusion for vertical edges of an axis-aligned Z-prism/box
/// (including triangulated prisms and prisms with inner through-holes).
fn try_bevel_vertical_prism(
    mesh: &PolyMesh,
    radius: f64,
    segments: usize,
    op_id: u32,
) -> Option<(PolyMesh, Option<f64>)> {
    let ZPrismFootprint { z0, z1, outer: poly, holes } = extract_z_prism_footprint(mesh)?;
    let n = poly.len();
    let mut rounded: Vec<(f64, f64)> = Vec::with_capacity(n * (segments + 1));
    let cos_sharp_thresh = 20.0_f64.to_radians().cos();
    let mut beveled_any = false;
    let mut min_clamped_d: Option<f64> = None;

    for i in 0..n {
        let prev = poly[(i + n - 1) % n];
        let curr = poly[i];
        let next = poly[(i + 1) % n];
        let e1 = (prev.0 - curr.0, prev.1 - curr.1);
        let e2 = (next.0 - curr.0, next.1 - curr.1);
        let l1 = e1.0.hypot(e1.1);
        let l2 = e2.0.hypot(e2.1);
        if l1 < 1e-6 || l2 < 1e-6 {
            return None;
        }
        let u1 = (e1.0 / l1, e1.1 / l1);
        let u2 = (e2.0 / l2, e2.1 / l2);
        // Skip nearly straight / smooth-curve vertices (turning angle < 20 deg)
        let cos_turn = -(u1.0 * u2.0 + u1.1 * u2.1);
        if cos_turn > cos_sharp_thresh {
            rounded.push(curr);
            continue;
        }
        beveled_any = true;

        let d = radius.min(l1 * 0.45).min(l2 * 0.45);
        if d < radius - 1e-9 {
            min_clamped_d = Some(min_clamped_d.map_or(d, |m| m.min(d)));
        }
        let p_start = (curr.0 + u1.0 * d, curr.1 + u1.1 * d);
        let p_end = (curr.0 + u2.0 * d, curr.1 + u2.1 * d);

        if segments == 1 {
            rounded.push(p_start);
            rounded.push(p_end);
        } else {
            // Circular fillet tangent to both edges at p_start and p_end
            let dot = (u1.0 * u2.0 + u1.1 * u2.1).clamp(-0.999, 0.999);
            let half_angle = dot.acos() * 0.5;
            let tan_half = half_angle.tan();
            let arc_r = d * tan_half;
            // Bisector direction pointing inward
            let bis = (u1.0 + u2.0, u1.1 + u2.1);
            let bl = bis.0.hypot(bis.1);
            if bl < 1e-6 {
                rounded.push(p_start);
                rounded.push(p_end);
                continue;
            }
            let dist_c = d / half_angle.cos();
            let center = (curr.0 + (bis.0 / bl) * dist_c, curr.1 + (bis.1 / bl) * dist_c);
            let a0 = (p_start.1 - center.1).atan2(p_start.0 - center.0);
            let mut a1 = (p_end.1 - center.1).atan2(p_end.0 - center.0);
            let mut da = a1 - a0;
            while da > PI {
                da -= 2.0 * PI;
            }
            while da < -PI {
                da += 2.0 * PI;
            }
            a1 = a0 + da;
            for s in 0..=segments {
                let t = (s as f64) / (segments as f64);
                let a = a0 + (a1 - a0) * t;
                rounded.push((center.0 + arc_r * a.cos(), center.1 + arc_r * a.sin()));
            }
        }
    }
    if !beveled_any {
        return None;
    }
    let rounded = simplify_collinear_2d(&rounded, 1e-8);
    if rounded.len() < 3 || poly_has_self_intersection_2d(&rounded) {
        return None;
    }
    for hole in &holes {
        if !loops_disjoint_and_contained(&rounded, hole) {
            return None;
        }
    }
    let mut res = if holes.is_empty() {
        make_extrude_2d(&rounded, z0, z1, op_id).ok()?
    } else {
        make_extrude_2d_with_holes(&rounded, &holes, z0, z1, op_id).ok()?
    };
    res.tag_all_faces("bevel");
    if mesh.materials.len() == 1 {
        res.assign_material(mesh.materials[0].clone(), None);
    }
    res.smooth_angle_deg = mesh.smooth_angle_deg;
    res.weighted_normals = mesh.weighted_normals;
    Some((res, min_clamped_d))
}

type ZPrismRing = (Vec<(f64, f64)>, f64);
type TaggedZPrismRing<'a> = (Vec<(f64, f64)>, f64, &'a str);

/// Extract ordered horizontal rings `(poly_xy, z)` from bottom face to top face on a Z-prism
/// (including prisms that already have a top or bottom bevel!). Returns `None` if mesh is not a layered Z-prism.
fn extract_z_prism_rings(mesh: &PolyMesh, bot_fi: usize, top_fi: usize, z_tol: f64) -> Option<Vec<ZPrismRing>> {
    let bot_raw = &mesh.faces[bot_fi].verts;
    let top_raw = &mesh.faces[top_fi].verts;
    let n = bot_raw.len();
    if n < 3 || top_raw.len() != n {
        return None;
    }
    // Bottom face normal points -Z, so reversing gives CCW order looking from +Z
    let mut cur_ring: Vec<usize> = bot_raw.iter().rev().copied().collect();
    let mut visited_faces = vec![false; mesh.faces.len()];
    visited_faces[bot_fi] = true;
    visited_faces[top_fi] = true;

    // Build fast edge -> incident faces lookup
    let adj = mesh.build_adjacency();
    let mut rings: Vec<(Vec<(f64, f64)>, f64)> = Vec::new();
    let ring_to_xy_z = |ring: &[usize]| -> Option<(Vec<(f64, f64)>, f64)> {
        let z = mesh.verts[ring[0]].z;
        let mut pts = Vec::with_capacity(ring.len());
        for &vi in ring {
            let p = mesh.verts[vi];
            if (p.z - z).abs() > z_tol {
                return None;
            }
            pts.push((p.x, p.y));
        }
        Some((pts, z))
    };
    rings.push(ring_to_xy_z(&cur_ring)?);

    let top_set: HashSet<usize> = top_raw.iter().copied().collect();
    for _step in 0..64 {
        if cur_ring.iter().all(|v| top_set.contains(v)) {
            break;
        }
        let mut next_ring = vec![usize::MAX; n];
        for j in 0..n {
            let u = cur_ring[j];
            let v = cur_ring[(j + 1) % n];
            let inc = adj.edge_faces.get(&edge_key(u, v))?;
            let quad_fi = *inc.iter().find(|&&fi| !visited_faces[fi])?;
            let qv = &mesh.faces[quad_fi].verts;
            if qv.len() != 4 {
                return None;
            }
            // Find the edge opposite to (u, v) in quad `qv`
            let pos_u = qv.iter().position(|&x| x == u)?;
            let pos_v = qv.iter().position(|&x| x == v)?;
            let (u_up, v_up) = if (pos_u + 1) % 4 == pos_v {
                (qv[(pos_u + 3) % 4], qv[(pos_v + 1) % 4])
            } else if (pos_v + 1) % 4 == pos_u {
                (qv[(pos_u + 1) % 4], qv[(pos_v + 3) % 4])
            } else {
                return None;
            };
            if next_ring[j] != usize::MAX && next_ring[j] != u_up {
                return None;
            }
            next_ring[j] = u_up;
            let nj = (j + 1) % n;
            if next_ring[nj] != usize::MAX && next_ring[nj] != v_up {
                return None;
            }
            next_ring[nj] = v_up;
        }
        if next_ring.contains(&usize::MAX) {
            return None;
        }
        // Mark strip quads visited
        for j in 0..n {
            let u = cur_ring[j];
            let v = cur_ring[(j + 1) % n];
            if let Some(inc) = adj.edge_faces.get(&edge_key(u, v)) {
                for &fi in inc {
                    visited_faces[fi] = true;
                }
            }
        }
        rings.push(ring_to_xy_z(&next_ring)?);
        cur_ring = next_ring;
    }
    if rings.len() < 2 || !cur_ring.iter().all(|v| top_set.contains(v)) {
        return None;
    }
    Some(rings)
}

fn inset_ccw_poly(poly: &[(f64, f64)], inset_d: f64) -> Vec<(f64, f64)> {
    if inset_d <= 1e-9 {
        return poly.to_vec();
    }
    let n = poly.len();
    let mut cx = 0.0;
    let mut cy = 0.0;
    for &(x, y) in poly {
        cx += x;
        cy += y;
    }
    cx /= n as f64;
    cy /= n as f64;
    let mut out = Vec::with_capacity(n);
    for i in 0..n {
        let prev = poly[(i + n - 1) % n];
        let curr = poly[i];
        let next = poly[(i + 1) % n];
        let e1 = (curr.0 - prev.0, curr.1 - prev.1);
        let e2 = (next.0 - curr.0, next.1 - curr.1);
        let l1 = e1.0.hypot(e1.1).max(1e-9);
        let l2 = e2.0.hypot(e2.1).max(1e-9);
        // Inward normals for CCW polygon: (-ey, ex)
        let n1 = (-e1.1 / l1, e1.0 / l1);
        let n2 = (-e2.1 / l2, e2.0 / l2);
        let denom = 1.0 + n1.0 * n2.0 + n1.1 * n2.1;
        if denom > 0.1 {
            let mx = (n1.0 + n2.0) / denom;
            let my = (n1.1 + n2.1) / denom;
            out.push((curr.0 + mx * inset_d, curr.1 + my * inset_d));
        } else {
            let dx = cx - curr.0;
            let dy = cy - curr.1;
            let dl = dx.hypot(dy).max(1e-9);
            out.push((curr.0 + dx / dl * inset_d, curr.1 + dy / dl * inset_d));
        }
    }
    out
}

/// Compute a conservative upper bound on inward 2D polygon inset distance so opposite edges
/// cannot cross and no edge can invert during `try_bevel_z_rims`.
fn max_safe_poly_inset(poly: &[(f64, f64)]) -> f64 {
    let n = poly.len();
    if n < 3 {
        return 0.0;
    }
    // Precompute miter directions matching `inset_ccw_poly`
    let mut cx = 0.0;
    let mut cy = 0.0;
    for &(x, y) in poly {
        cx += x;
        cy += y;
    }
    cx /= n as f64;
    cy /= n as f64;

    let mut miters = Vec::with_capacity(n);
    for i in 0..n {
        let prev = poly[(i + n - 1) % n];
        let curr = poly[i];
        let next = poly[(i + 1) % n];
        let e1 = (curr.0 - prev.0, curr.1 - prev.1);
        let e2 = (next.0 - curr.0, next.1 - curr.1);
        let l1 = e1.0.hypot(e1.1).max(1e-9);
        let l2 = e2.0.hypot(e2.1).max(1e-9);
        let n1 = (-e1.1 / l1, e1.0 / l1);
        let n2 = (-e2.1 / l2, e2.0 / l2);
        let denom = 1.0 + n1.0 * n2.0 + n1.1 * n2.1;
        if denom > 0.1 {
            miters.push(((n1.0 + n2.0) / denom, (n1.1 + n2.1) / denom));
        } else {
            let dx = cx - curr.0;
            let dy = cy - curr.1;
            let dl = dx.hypot(dy).max(1e-9);
            miters.push((dx / dl, dy / dl));
        }
    }

    let mut max_d = f64::INFINITY;
    // 1. Edge-collapse bound: keep every edge >= 10% of its original length
    for i in 0..n {
        let j = (i + 1) % n;
        let ex = poly[j].0 - poly[i].0;
        let ey = poly[j].1 - poly[i].1;
        let elen = ex.hypot(ey);
        if elen < 1e-12 {
            continue;
        }
        let tx = ex / elen;
        let ty = ey / elen;
        let shrink_rate = (miters[i].0 * tx + miters[i].1 * ty) - (miters[j].0 * tx + miters[j].1 * ty);
        if shrink_rate > 1e-9 {
            max_d = max_d.min(0.9 * elen / shrink_rate);
        }
    }

    // 2. Opposite-edge clearance bound: prevent vertex/edge collisions across thin walls & rods
    let point_seg_dist = |p: (f64, f64), a: (f64, f64), b: (f64, f64)| -> f64 {
        let dx = b.0 - a.0;
        let dy = b.1 - a.1;
        let l2 = dx * dx + dy * dy;
        if l2 < 1e-18 {
            return (p.0 - a.0).hypot(p.1 - a.1);
        }
        let t = (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0);
        let qx = a.0 + dx * t;
        let qy = a.1 + dy * t;
        (p.0 - qx).hypot(p.1 - qy)
    };
    if n <= 128 {
        for i in 0..n {
            let p = poly[i];
            let mi = miters[i];
            let prev_edge = (i + n - 1) % n;
            for e in 0..n {
                if e == i || e == prev_edge {
                    continue;
                }
                let a = poly[e];
                let b = poly[(e + 1) % n];
                let ex = b.0 - a.0;
                let ey = b.1 - a.1;
                let el = ex.hypot(ey);
                if el < 1e-12 {
                    continue;
                }
                // Only check opposing walls (whose inward normal faces opposite to vertex miter)
                let ne = (-ey / el, ex / el);
                if mi.0 * ne.0 + mi.1 * ne.1 >= -0.1 {
                    continue;
                }
                let dist = point_seg_dist(p, a, b);
                // Two opposite walls approach each other at speed ~2*d, so clamp at 0.45 * clearance
                max_d = max_d.min(0.45 * dist);
            }
        }
    } else {
        // O(n) fallback for very dense polygons: distance from centroid to each edge
        for e in 0..n {
            let dist = point_seg_dist((cx, cy), poly[e], poly[(e + 1) % n]);
            max_d = max_d.min(0.9 * dist);
        }
    }

    if max_d.is_finite() {
        max_d.max(0.0)
    } else {
        0.0
    }
}

/// Exact top and/or bottom perimeter bevel on a Z-prism (box, hex prism, cylinder, etc.).
/// Preserves any existing bevel on the opposite rim so chained `bevel(top_rim) | bevel(bottom_rim)`
/// produces exact, non-shrinking geometry identical to `bevel(outer_rim)`.
fn try_bevel_z_rims(
    mesh: &PolyMesh,
    width: f64,
    segments: usize,
    do_top: bool,
    do_bot: bool,
    op_id: u32,
) -> Option<(PolyMesh, Option<f64>)> {
    let bb = mesh.aabb();
    let z0 = bb.min.z;
    let z1 = bb.max.z;
    let h = z1 - z0;
    if h < 1e-9 {
        return None;
    }
    let z_tol = (1e-4 * h).max(1e-9);
    let xy_tol = (1e-5 * bb.size().x.max(bb.size().y)).max(1e-9);
    let top_faces: Vec<usize> = (0..mesh.faces.len())
        .filter(|&fi| mesh.face_normal(fi).z > 0.99 && (mesh.face_centroid(fi).z - z1).abs() < z_tol)
        .collect();
    let bot_faces: Vec<usize> = (0..mesh.faces.len())
        .filter(|&fi| mesh.face_normal(fi).z < -0.99 && (mesh.face_centroid(fi).z - z0).abs() < z_tol)
        .collect();
    if top_faces.len() != 1 || bot_faces.len() != 1 {
        return None;
    }

    let existing = extract_z_prism_rings(mesh, bot_faces[0], top_faces[0], z_tol)?;
    let n = existing[0].0.len();
    let k = existing.len();

    // Helper: check if two consecutive rings have identical XY (i.e. a vertical side wall)
    let is_same_xy = |a: &[(f64, f64)], b: &[(f64, f64)]| -> bool {
        a.iter().zip(b.iter()).all(|(p, q)| (p.0 - q.0).hypot(p.1 - q.1) < xy_tol)
    };

    // Build final ring stack `(poly_xy, z, tag_from_prev)` preserving untouched ends!
    let mut final_rings: Vec<TaggedZPrismRing<'_>> = Vec::new();

    // Determine vertical span available at bottom & top, AND clamp against 2D cap XY inradius!
    let bot_avail = existing[1].1 - existing[0].1;
    let top_avail = existing[k - 1].1 - existing[k - 2].1;
    let bot_is_vert = is_same_xy(&existing[0].0, &existing[1].0);
    let top_is_vert = is_same_xy(&existing[k - 2].0, &existing[k - 1].0);
    let bot_xy_max = max_safe_poly_inset(&existing[0].0);
    let top_xy_max = max_safe_poly_inset(&existing[k - 1].0);

    // If k == 2 and both ends requested, share available height symmetrically
    let (w_bot, w_top) = if k == 2 && do_top && do_bot {
        let w = width.min(h * 0.45).min(bot_xy_max).min(top_xy_max);
        (w, w)
    } else {
        let wb = width.min(bot_avail * 0.9).min(bot_xy_max);
        let wt = width.min(top_avail * 0.9).min(top_xy_max);
        (wb, wt)
    };

    let mut clamped_w: Option<f64> = None;
    if do_bot && bot_is_vert && w_bot < width - 1e-9 {
        clamped_w = Some(clamped_w.map_or(w_bot, |m| m.min(w_bot)));
    }
    if do_top && top_is_vert && w_top < width - 1e-9 {
        clamped_w = Some(clamped_w.map_or(w_top, |m| m.min(w_top)));
    }

    // Bottom end
    if do_bot && bot_is_vert && w_bot > 1e-7 {
        let base_poly = &existing[0].0;
        for s in 0..=segments {
            let t = (s as f64) / (segments as f64); // 0 = bottom cap inner, 1 = side start
            let (ins, dz) = if segments == 1 {
                (w_bot * (1.0 - t), w_bot * t)
            } else {
                let a = t * PI * 0.5;
                (w_bot * (1.0 - a.sin()), w_bot * (1.0 - a.cos()))
            };
            final_rings.push((inset_ccw_poly(base_poly, ins), z0 + dz, "bevel"));
        }
    } else {
        final_rings.push((existing[0].0.clone(), existing[0].1, "side"));
    }

    // Middle untouched rings (preserving any existing bevel on top or bottom!)
    for idx in 1..(k - 1) {
        let tag = if is_same_xy(&existing[idx - 1].0, &existing[idx].0) {
            "side"
        } else {
            "bevel"
        };
        final_rings.push((existing[idx].0.clone(), existing[idx].1, tag));
    }

    // Top end
    if do_top && top_is_vert && w_top > 1e-7 {
        let top_poly = &existing[k - 1].0;
        for s in 0..=segments {
            let t = (s as f64) / (segments as f64); // 0 = side end, 1 = top cap inner
            let (ins, dz) = if segments == 1 {
                (w_top * t, w_top * (1.0 - t))
            } else {
                let a = t * PI * 0.5;
                (w_top * (1.0 - a.cos()), w_top * (1.0 - a.sin()))
            };
            let tag = if s == 0 { "side" } else { "bevel" };
            final_rings.push((inset_ccw_poly(top_poly, ins), z1 - dz, tag));
        }
    } else {
        let tag = if is_same_xy(&existing[k - 2].0, &existing[k - 1].0) {
            "side"
        } else {
            "bevel"
        };
        final_rings.push((existing[k - 1].0.clone(), existing[k - 1].1, tag));
    }

    // Deduplicate consecutive rings at virtually identical Z & XY
    let mut clean_rings: Vec<TaggedZPrismRing<'_>> = Vec::with_capacity(final_rings.len());
    for r in final_rings {
        if let Some(prev) = clean_rings.last() {
            if (prev.1 - r.1).abs() < 1e-7 && is_same_xy(&prev.0, &r.0) {
                continue;
            }
        }
        clean_rings.push(r);
    }

    let mut m = PolyMesh::new();
    m.materials = mesh.materials.clone();
    m.smooth_angle_deg = mesh.smooth_angle_deg;
    m.weighted_normals = mesh.weighted_normals;
    let uniform_mat = if mesh.materials.len() == 1 { Some(0u16) } else { None };
    let mut rings: Vec<Vec<usize>> = Vec::with_capacity(clean_rings.len());
    for (p2, z, _) in &clean_rings {
        let mut ring = Vec::with_capacity(n);
        for &(x, y) in p2 {
            ring.push(m.add_vert(Vec3::new(x, y, *z)));
        }
        rings.push(ring);
    }

    // Bottom cap
    let bot_rev: SmallVec<[usize; 4]> = rings[0].iter().rev().copied().collect();
    m.add_face(bot_rev, op_id, Some("bottom"));
    // Side & bevel quad strips
    for i in 0..(rings.len() - 1) {
        let tag = clean_rings[i + 1].2;
        for j in 0..n {
            let nj = (j + 1) % n;
            m.add_face(
                smallvec![rings[i][j], rings[i][nj], rings[i + 1][nj], rings[i + 1][j]],
                op_id,
                Some(tag),
            );
        }
    }
    // Top cap
    let top_f: SmallVec<[usize; 4]> = rings
        .last()
        .expect("prism bevel produces at least two rings")
        .iter()
        .copied()
        .collect();
    m.add_face(top_f, op_id, Some("top"));
    if let Some(mid) = uniform_mat {
        for f in &mut m.faces {
            f.mat_id = mid;
        }
    }
    m.ensure_outward_winding();
    Some((m, clamped_w))
}

/// General polyhedral chamfer for arbitrary selected edges via per-face corner shrinking.
fn bevel_general_polyhedron(
    mesh: &PolyMesh,
    selected_edges: &[(usize, usize)],
    width: f64,
    op_id: u32,
) -> Result<(PolyMesh, Option<f64>), String> {
    let sel_set: HashSet<(usize, usize)> = selected_edges.iter().copied().collect();
    let mut out = PolyMesh::new();
    out.materials = mesh.materials.clone();
    out.smooth_angle_deg = mesh.smooth_angle_deg;
    out.weighted_normals = mesh.weighted_normals;
    let mut face_corner_map: HashMap<(usize, usize), usize> = HashMap::new(); // (fi, orig_v) -> new_v

    // Shrink corners of faces adjacent to selected edges
    let mut affected_verts: HashSet<usize> = HashSet::new();
    for &(u, v) in &sel_set {
        affected_verts.insert(u);
        affected_verts.insert(v);
    }

    let mut unaffected_map: HashMap<usize, usize> = HashMap::new();
    for (vi, &p) in mesh.verts.iter().enumerate() {
        if !affected_verts.contains(&vi) {
            unaffected_map.insert(vi, out.add_vert(p));
        }
    }

    let mut min_clamped_w: Option<f64> = None;

    for (fi, f) in mesh.faces.iter().enumerate() {
        let c = mesh.face_centroid(fi);
        let n = f.verts.len();
        let mut new_fv: SmallVec<[usize; 4]> = SmallVec::with_capacity(n);
        for i in 0..n {
            let v = f.verts[i];
            if !affected_verts.contains(&v) {
                new_fv.push(unaffected_map[&v]);
                continue;
            }
            let prev = f.verts[(i + n - 1) % n];
            let next = f.verts[(i + 1) % n];
            let e_prev_sel = sel_set.contains(&edge_key(prev, v));
            let e_next_sel = sel_set.contains(&edge_key(v, next));
            let p = mesh.verts[v];
            let np = if e_prev_sel || e_next_sel {
                let d_prev = (mesh.verts[prev] - p).normalized();
                let d_next = (mesh.verts[next] - p).normalized();
                let l_prev = (mesh.verts[prev] - p).len();
                let l_next = (mesh.verts[next] - p).len();
                let mut shift = Vec3::ZERO;
                if e_prev_sel {
                    let eff = width.min(l_prev * 0.35);
                    if eff < width - 1e-9 {
                        min_clamped_w = Some(min_clamped_w.map_or(eff, |m| m.min(eff)));
                    }
                    shift += d_prev * eff;
                }
                if e_next_sel {
                    let eff = width.min(l_next * 0.35);
                    if eff < width - 1e-9 {
                        min_clamped_w = Some(min_clamped_w.map_or(eff, |m| m.min(eff)));
                    }
                    shift += d_next * eff;
                }
                if shift.len_sq() < 1e-12 {
                    p.lerp(c, 0.1)
                } else {
                    p + shift
                }
            } else {
                let dist = (p - c).len().max(1e-6);
                let max_eff = dist * 0.35;
                if max_eff < width - 1e-9 {
                    min_clamped_w = Some(min_clamped_w.map_or(max_eff, |m| m.min(max_eff)));
                }
                p.lerp(c, (width / dist).min(0.35))
            };
            let nvi = out.add_vert(np);
            face_corner_map.insert((fi, v), nvi);
            new_fv.push(nvi);
        }
        let out_fi = out.add_face_with_tags(new_fv, op_id, Some(f.lineage), &f.tags);
        out.faces[out_fi].mat_id = f.mat_id;
    }

    // Bridge bevel quads across every edge touching affected vertices (sorted for deterministic output)
    let adj = mesh.build_adjacency();
    let mut sorted_edges: Vec<_> = adj.edge_faces.iter().collect();
    sorted_edges.sort_unstable_by_key(|(&k, _)| k);
    for (&(u, v), inc_faces) in sorted_edges {
        if inc_faces.len() != 2 {
            continue;
        }
        if !affected_verts.contains(&u) && !affected_verts.contains(&v) {
            continue;
        }
        let f0 = inc_faces[0];
        let f1 = inc_faces[1];
        // Determine orientation of (u, v) in f0
        let fv0 = &mesh.faces[f0].verts;
        let mut forward = false;
        for i in 0..fv0.len() {
            if fv0[i] == u && fv0[(i + 1) % fv0.len()] == v {
                forward = true;
                break;
            }
        }
        let (a, b) = if forward { (u, v) } else { (v, u) };
        let a0 = face_corner_map.get(&(f0, a)).copied().or_else(|| unaffected_map.get(&a).copied());
        let b0 = face_corner_map.get(&(f0, b)).copied().or_else(|| unaffected_map.get(&b).copied());
        let b1 = face_corner_map.get(&(f1, b)).copied().or_else(|| unaffected_map.get(&b).copied());
        let a1 = face_corner_map.get(&(f1, a)).copied().or_else(|| unaffected_map.get(&a).copied());
        if let (Some(a0), Some(b0), Some(b1), Some(a1)) = (a0, b0, b1, a1) {
            let mut quad: SmallVec<[usize; 4]> = SmallVec::new();
            for x in [a0, a1, b1, b0] {
                if quad.last().copied() != Some(x) {
                    quad.push(x);
                }
            }
            if quad.len() > 1 && quad.first() == quad.last() {
                quad.pop();
            }
            if quad.len() >= 3 {
                out.add_face(quad, op_id, Some("bevel"));
            }
        }
    }

    // Fill vertex corner patches for every affected vertex (BTreeMap for deterministic order)
    let mut v_to_faces: std::collections::BTreeMap<usize, Vec<usize>> = std::collections::BTreeMap::new();
    for (fi, f) in mesh.faces.iter().enumerate() {
        for &vi in &f.verts {
            if affected_verts.contains(&vi) {
                v_to_faces.entry(vi).or_default().push(fi);
            }
        }
    }
    for (v, inc) in v_to_faces {
        if inc.len() < 3 {
            continue;
        }
        // Order incident corners angularly around average vertex normal
        let mut vn = Vec3::ZERO;
        for &fi in &inc {
            vn += mesh.face_normal(fi);
        }
        let vn = vn.normalized();
        let u_ax = if vn.x.abs() < 0.9 {
            vn.cross(Vec3::X).normalized()
        } else {
            vn.cross(Vec3::Y).normalized()
        };
        let v_ax = vn.cross(u_ax).normalized();
        let center = mesh.verts[v];
        let mut corners: Vec<(f64, usize)> = inc
            .iter()
            .filter_map(|&fi| {
                let nvi = face_corner_map.get(&(fi, v)).copied()?;
                let d = out.verts[nvi] - center;
                Some((d.dot(v_ax).atan2(d.dot(u_ax)), nvi))
            })
            .collect();
        corners.sort_by(|a, b| a.0.total_cmp(&b.0));
        let poly: SmallVec<[usize; 4]> = corners.into_iter().map(|(_, vi)| vi).collect();
        if poly.len() >= 3 {
            out.add_face(poly, op_id, Some("bevel_corner"));
        }
    }

    out.weld_and_clean(1e-6);
    out.ensure_outward_winding();
    Ok((out, min_clamped_w))
}

/// Exact Catmull-Clark subdivision (`levels` iterations) on closed manifold polyhedral meshes.
pub fn subsurf_catmull_clark(mesh: &PolyMesh, levels: usize, op_id: u32) -> PolyMesh {
    subsurf_catmull_clark_creased(mesh, levels, None, op_id)
}

/// Crease-aware Catmull-Clark subdivision: when `crease_deg` is `Some(deg)` (e.g. `Some(55.0)`),
/// edges with dihedral angle >= `deg` act as sharp Hoppe/DeRose semi-sharp creases (preventing
/// rim/dimension shrinkage on bowls, housings, and mechanical solids).
pub fn subsurf_catmull_clark_creased(
    mesh: &PolyMesh,
    levels: usize,
    crease_deg: Option<f64>,
    op_id: u32,
) -> PolyMesh {
    let cos_thresh = crease_deg.map(|d| d.to_radians().cos());
    let mut curr = mesh.clone();
    for _ in 0..levels.min(4) {
        curr = catmull_clark_step(&curr, cos_thresh, op_id);
    }
    curr
}

/// Zero-HashMap, sort-based Catmull-Clark subdivision step (with optional sharp-crease preservation).
fn catmull_clark_step(mesh: &PolyMesh, crease_cos: Option<f64>, op_id: u32) -> PolyMesh {
    let n_verts = mesh.verts.len();
    let n_faces = mesh.faces.len();

    let face_normals: Vec<Vec3> = if crease_cos.is_some() {
        (0..n_faces).map(|fi| mesh.face_normal(fi)).collect()
    } else {
        Vec::new()
    };

    // 1. Face points & vertex-face accumulation in a single pass
    let mut face_pts: Vec<Vec3> = Vec::with_capacity(n_faces);
    let mut v_face_sum = vec![Vec3::ZERO; n_verts];
    let mut v_face_cnt = vec![0u32; n_verts];
    let mut half_edges: Vec<(u64, u32)> = Vec::with_capacity(n_faces * 4);

    for (fi, f) in mesh.faces.iter().enumerate() {
        let k = f.verts.len();
        let mut sum = Vec3::ZERO;
        for &vi in &f.verts {
            sum += mesh.verts[vi];
        }
        let fp = if k > 0 { sum / (k as f64) } else { Vec3::ZERO };
        face_pts.push(fp);
        for i in 0..k {
            let vi = f.verts[i];
            let vj = f.verts[(i + 1) % k];
            v_face_sum[vi] += fp;
            v_face_cnt[vi] += 1;
            if vi != vj {
                let (u, v) = if vi < vj { (vi, vj) } else { (vj, vi) };
                half_edges.push((((u as u64) << 32) | (v as u64), fi as u32));
            }
        }
    }

    // 2. Sort half-edges to find unique edges, edge points, and vertex-edge averages (zero HashMaps!)
    half_edges.sort_unstable_by_key(|&(k, _)| k);

    let mut v_edge_sum = vec![Vec3::ZERO; n_verts];
    let mut v_edge_cnt = vec![0u32; n_verts];
    let mut v_bnd_sum = vec![Vec3::ZERO; n_verts];
    let mut v_bnd_cnt = vec![0u32; n_verts];

    let mut edge_keys: Vec<u64> = Vec::with_capacity(half_edges.len() / 2 + 1);
    let mut edge_pts: Vec<Vec3> = Vec::with_capacity(half_edges.len() / 2 + 1);

    let mut i = 0;
    let m = half_edges.len();
    while i < m {
        let key = half_edges[i].0;
        let u = (key >> 32) as usize;
        let v = (key & 0xFFFF_FFFF) as usize;
        let mut j = i + 1;
        while j < m && half_edges[j].0 == key {
            j += 1;
        }
        let run = j - i;
        let mid = (mesh.verts[u] + mesh.verts[v]) * 0.5;
        let is_sharp_crease = if run == 2 {
            if let Some(ct) = crease_cos {
                let f0 = half_edges[i].1 as usize;
                let f1 = half_edges[i + 1].1 as usize;
                face_normals[f0].dot(face_normals[f1]) < ct
            } else {
                false
            }
        } else {
            true
        };
        let ep = if run == 2 && !is_sharp_crease {
            (mesh.verts[u] + mesh.verts[v] + face_pts[half_edges[i].1 as usize] + face_pts[half_edges[i + 1].1 as usize]) * 0.25
        } else {
            mid
        };
        edge_keys.push(key);
        edge_pts.push(ep);

        v_edge_sum[u] += mid;
        v_edge_cnt[u] += 1;
        v_edge_sum[v] += mid;
        v_edge_cnt[v] += 1;
        if run == 1 || is_sharp_crease {
            v_bnd_sum[u] += mid;
            v_bnd_cnt[u] += 1;
            v_bnd_sum[v] += mid;
            v_bnd_cnt[v] += 1;
        }
        i = j;
    }

    let n_edges = edge_keys.len();
    let mut out = PolyMesh::new();
    out.materials = mesh.materials.clone();
    out.smooth_angle_deg = mesh.smooth_angle_deg;
    out.weighted_normals = mesh.weighted_normals;
    out.verts.reserve(n_verts + n_faces + n_edges);
    out.faces.reserve(n_faces * 4);

    // 3. Updated original vertices at indices 0..n_verts (DeRose crease/corner rules!)
    for vi in 0..n_verts {
        let p = mesh.verts[vi];
        let np = if v_bnd_cnt[vi] >= 3 {
            // Sharp corner (3+ crease edges meet): pin exact vertex position!
            p
        } else if v_bnd_cnt[vi] == 2 {
            // Smooth crease curve: (6*P + v_prev + v_next)/8 = 0.5*P + 0.25*(mid0 + mid1)
            v_bnd_sum[vi] * 0.25 + p * 0.5
        } else if v_bnd_cnt[vi] == 1 {
            (v_bnd_sum[vi] + p) * 0.5
        } else if v_face_cnt[vi] > 0 && v_edge_cnt[vi] == v_face_cnt[vi] {
            let n = v_face_cnt[vi] as f64;
            let inv_n = 1.0 / n;
            let inv_n2 = inv_n * inv_n;
            (v_face_sum[vi] + v_edge_sum[vi] * 2.0) * inv_n2 + p * ((n - 3.0) * inv_n)
        } else {
            p
        };
        out.verts.push(np);
    }

    // 4. Face points at n_verts..n_verts+n_faces
    let face_pt_base = out.verts.len();
    out.verts.extend_from_slice(&face_pts);

    // 5. Edge points at edge_pt_base..edge_pt_base+n_edges (already sorted by edge_key!)
    let edge_pt_base = out.verts.len();
    out.verts.extend_from_slice(&edge_pts);

    // 6. Emit one quad per face corner using O(log E) binary search in sorted `edge_keys`
    for (fi, f) in mesh.faces.iter().enumerate() {
        let fp_idx = face_pt_base + fi;
        let k = f.verts.len();
        for ci in 0..k {
            let v_curr = f.verts[ci];
            let v_next = f.verts[(ci + 1) % k];
            let v_prev = f.verts[(ci + k - 1) % k];
            let k_next = if v_curr < v_next {
                ((v_curr as u64) << 32) | (v_next as u64)
            } else {
                ((v_next as u64) << 32) | (v_curr as u64)
            };
            let k_prev = if v_prev < v_curr {
                ((v_prev as u64) << 32) | (v_curr as u64)
            } else {
                ((v_curr as u64) << 32) | (v_prev as u64)
            };
            if v_curr == v_next || v_prev == v_curr {
                continue;
            }
            let Ok(idx_next) = edge_keys.binary_search(&k_next) else { continue };
            let Ok(idx_prev) = edge_keys.binary_search(&k_prev) else { continue };
            let e_next = edge_pt_base + idx_next;
            let e_prev = edge_pt_base + idx_prev;
            let mut nf = Face::new(smallvec![v_curr, e_next, fp_idx, e_prev], f.lineage, op_id);
            nf.tags = f.tags.clone();
            nf.mat_id = f.mat_id;
            out.faces.push(nf);
        }
    }
    out
}

/// Hollow a closed solid with wall thickness `t`, optionally opening the top face
/// (ideal for enclosures, cups, housings).
pub fn shell_solid(
    mesh: &PolyMesh,
    thickness: f64,
    open_top: bool,
    op_id: u32,
) -> Result<PolyMesh, String> {
    if !thickness.is_finite() || thickness <= 1e-9 {
        return Err("shell thickness must be positive".into());
    }
    let bb = mesh.aabb();
    let sz = bb.size();
    let sx = (sz.x - 2.0 * thickness) / sz.x.max(1e-9);
    let sy = (sz.y - 2.0 * thickness) / sz.y.max(1e-9);
    if sx <= 0.01 || sy <= 0.01 {
        return Err("shell thickness exceeds part dimensions".into());
    }
    if open_top {
        if thickness >= sz.z * 0.99 {
            return Err("shell thickness exceeds part height".into());
        }
    } else {
        let sz_s = (sz.z - 2.0 * thickness) / sz.z.max(1e-9);
        if sz_s <= 0.01 {
            return Err("shell thickness exceeds part height".into());
        }
    }

    if let Some(ZPrismFootprint { z0, z1, outer, holes }) = extract_z_prism_footprint(mesh) {
        let inner_outer = offset_polygon_2d(&outer, thickness)
            .ok_or_else(|| "shell thickness exceeds wall or notch width".to_string())?;
        let mut inner_holes: Vec<Vec<(f64, f64)>> = Vec::with_capacity(holes.len());
        for hole in &holes {
            let ih = offset_polygon_2d(hole, thickness)
                .ok_or_else(|| "shell thickness exceeds hole offset clearance".to_string())?;
            if !loops_disjoint_and_contained(&inner_outer, &ih) {
                return Err("shell thickness exceeds wall clearance around hole".into());
            }
            for prev in &inner_holes {
                let overlap = prev.iter().any(|&p| point_in_poly_2d(p, &ih))
                    || ih.iter().any(|&p| point_in_poly_2d(p, prev))
                    || (0..prev.len()).any(|i| {
                        let a = prev[i];
                        let b = prev[(i + 1) % prev.len()];
                        (0..ih.len()).any(|j| segs_properly_intersect(a, b, ih[j], ih[(j + 1) % ih.len()]))
                    });
                if overlap {
                    return Err("shell thickness exceeds clearance between adjacent holes".into());
                }
            }
            inner_holes.push(ih);
        }
        let z_floor = z0 + thickness;
        let z_top_ext = if open_top {
            z1 + thickness.max(0.05 * sz.z.max(1e-6))
        } else {
            z1 - thickness
        };
        let cavity = if inner_holes.is_empty() {
            make_extrude_2d(&inner_outer, z_floor, z_top_ext, op_id)?
        } else {
            make_extrude_2d_with_holes(&inner_outer, &inner_holes, z_floor, z_top_ext, op_id)?
        };
        return boolean_op(mesh, &cavity, BoolOp::Difference, Some("cavity"), op_id);
    }

    crate::deform::solidify_mesh(mesh, thickness, -1.0, open_top, op_id)
}

/// Mirror a mesh across the X=0, Y=0, or Z=0 plane, optionally unioning with the original.
pub fn mirror_mesh(mesh: &PolyMesh, axis: char, union_with_orig: bool, op_id: u32) -> Result<PolyMesh, String> {
    let mut m = mesh.clone();
    match axis.to_ascii_lowercase() {
        'x' => m.scale(Vec3::new(-1.0, 1.0, 1.0)),
        'y' => m.scale(Vec3::new(1.0, -1.0, 1.0)),
        'z' => m.scale(Vec3::new(1.0, 1.0, -1.0)),
        _ => return Err(format!("invalid mirror axis '{axis}' (use x, y, z)")),
    }
    if union_with_orig {
        boolean_op(mesh, &m, BoolOp::Union, Some("mirror"), op_id)
    } else {
        Ok(m)
    }
}

/// Repeat a mesh linearly (defaulting to union for overlapping instances; pairwise-disjoint
/// instances use an O(1) AABB fast-path with zero CSG overhead).
/// Allows up to 256 total instances while bounding overlapping CSG unions at 64.
pub fn array_linear(
    mesh: &PolyMesh,
    count: usize,
    step: Vec3,
    union_all: bool,
    op_id: u32,
) -> Result<PolyMesh, String> {
    array_linear_bounded(mesh, count, step, union_all, 0, op_id)
}

pub fn array_linear_bounded(
    mesh: &PolyMesh,
    count: usize,
    step: Vec3,
    union_all: bool,
    max_faces: usize,
    op_id: u32,
) -> Result<PolyMesh, String> {
    if count == 0 {
        return Err("array count must be >= 1".into());
    }
    const MAX_TOTAL: usize = 256;
    const MAX_CSG_UNIONS: usize = 64;
    if count > MAX_TOTAL {
        return Err(format!("array count {count} exceeds limit ({MAX_TOTAL})"));
    }
    let mut acc = mesh.clone();
    let mut inst_bbs: Vec<crate::math::Aabb> = Vec::with_capacity(count);
    inst_bbs.push(mesh.aabb());
    let mut csg_unions = 0usize;
    for i in 1..count {
        let mut inst = mesh.clone();
        inst.translate(step * (i as f64));
        let ibb = inst.aabb();
        if union_all && inst_bbs.iter().any(|b| b.overlaps(&ibb, 1e-5)) {
            csg_unions += 1;
            if csg_unions > MAX_CSG_UNIONS {
                return Err(format!(
                    "overlapping array CSG unions exceed limit ({MAX_CSG_UNIONS}); separate instances or reduce count"
                ));
            }
            acc = boolean_op(&acc, &inst, BoolOp::Union, None, op_id)?;
            if max_faces > 0 && acc.faces.len() > max_faces {
                return Err(format!(
                    "array union exceeded face limit ({} > {max_faces}); reduce count or simplify input",
                    acc.faces.len()
                ));
            }
        } else {
            acc.append_mesh(&inst);
            if max_faces > 0 && acc.faces.len() > max_faces {
                return Err(format!(
                    "array exceeded face limit ({} > {max_faces}); reduce count or simplify input",
                    acc.faces.len()
                ));
            }
        }
        inst_bbs.push(ibb);
    }
    Ok(acc)
}

/// Repeat a mesh radially around the specified axis (`'x'`, `'y'`, or `'z'`), optionally
/// offset radially by `radius` before rotating.
/// Pairwise-disjoint instances use an O(1) AABB fast-path with zero CSG overhead (up to 256
/// total instances; overlapping CSG unions bounded at 64).
pub fn array_radial_ex(
    mesh: &PolyMesh,
    count: usize,
    radius: f64,
    axis: char,
    union_all: bool,
    op_id: u32,
) -> Result<PolyMesh, String> {
    array_radial_ex_bounded(mesh, count, radius, axis, union_all, 0, op_id)
}

pub fn array_radial_ex_bounded(
    mesh: &PolyMesh,
    count: usize,
    radius: f64,
    axis: char,
    union_all: bool,
    max_faces: usize,
    op_id: u32,
) -> Result<PolyMesh, String> {
    if count == 0 {
        return Err("radial array count must be >= 1".into());
    }
    if !radius.is_finite() {
        return Err("radial array radius must be finite".into());
    }
    let ax = axis.to_ascii_lowercase();
    if !matches!(ax, 'x' | 'y' | 'z') {
        return Err(format!("invalid radial array axis '{axis}' (use x, y, or z)"));
    }
    const MAX_TOTAL: usize = 256;
    const MAX_CSG_UNIONS: usize = 64;
    if count > MAX_TOTAL {
        return Err(format!("radial array count {count} exceeds limit ({MAX_TOTAL})"));
    }
    let mut base = mesh.clone();
    if radius.abs() > 1e-12 {
        let offset = match ax {
            'x' => Vec3::new(0.0, radius, 0.0),
            'y' => Vec3::new(radius, 0.0, 0.0),
            _ => Vec3::new(radius, 0.0, 0.0),
        };
        base.translate(offset);
    }
    let mut acc = base.clone();
    let mut inst_bbs: Vec<crate::math::Aabb> = Vec::with_capacity(count);
    inst_bbs.push(base.aabb());
    let mut csg_unions = 0usize;
    for i in 1..count {
        let mut inst = base.clone();
        let ang = 360.0 * (i as f64) / (count as f64);
        match ax {
            'x' => inst.rotate_deg(ang, 0.0, 0.0),
            'y' => inst.rotate_deg(0.0, ang, 0.0),
            _ => inst.rotate_deg(0.0, 0.0, ang),
        }
        let ibb = inst.aabb();
        if union_all && inst_bbs.iter().any(|b| b.overlaps(&ibb, 1e-5)) {
            csg_unions += 1;
            if csg_unions > MAX_CSG_UNIONS {
                return Err(format!(
                    "overlapping radial array CSG unions exceed limit ({MAX_CSG_UNIONS}); increase r or reduce count"
                ));
            }
            acc = boolean_op(&acc, &inst, BoolOp::Union, None, op_id)?;
            if max_faces > 0 && acc.faces.len() > max_faces {
                return Err(format!(
                    "radial array union exceeded face limit ({} > {max_faces}); reduce count or simplify input",
                    acc.faces.len()
                ));
            }
        } else {
            acc.append_mesh(&inst);
            if max_faces > 0 && acc.faces.len() > max_faces {
                return Err(format!(
                    "radial array exceeded face limit ({} > {max_faces}); reduce count or simplify input",
                    acc.faces.len()
                ));
            }
        }
        inst_bbs.push(ibb);
    }
    Ok(acc)
}

/// Repeat a mesh radially around the Z axis, optionally offset radially by `radius` along +X before rotating.
pub fn array_radial_with_radius(
    mesh: &PolyMesh,
    count: usize,
    radius: f64,
    union_all: bool,
    op_id: u32,
) -> Result<PolyMesh, String> {
    array_radial_ex(mesh, count, radius, 'z', union_all, op_id)
}

/// Repeat a mesh radially around the Z axis (zero radial offset).
pub fn array_radial(
    mesh: &PolyMesh,
    count: usize,
    union_all: bool,
    op_id: u32,
) -> Result<PolyMesh, String> {
    array_radial_ex(mesh, count, 0.0, 'z', union_all, op_id)
}

/// Topology-preserving Quadric Error Metric (QEM) mesh decimation with Edelsbrunner Link-Condition.
/// Reduces face count toward `target_ratio` (in `(0.05..=1.0]`) or `target_faces` while keeping
/// watertight manifold solids watertight (`NM=0`) and preventing normal flips.
pub fn decimate_mesh(
    mesh: &PolyMesh,
    target_ratio: f64,
    target_faces: Option<usize>,
    op_id: u32,
) -> Result<PolyMesh, String> {
    use std::cmp::Ordering;
    use std::collections::{BinaryHeap, HashSet};

    if mesh.faces.is_empty() || mesh.verts.is_empty() {
        return Err("decimate: empty mesh".into());
    }
    let ratio = target_ratio.clamp(0.05, 1.0);
    // Triangulate into working mesh
    let mut verts: Vec<Vec3> = mesh.verts.clone();
    let mut tris: Vec<([usize; 3], u16, SmallVec<[String; 2]>)> = Vec::new();
    for (fi, f) in mesh.faces.iter().enumerate() {
        for tri in mesh.triangulate_face(fi) {
            if tri[0] != tri[1] && tri[1] != tri[2] && tri[2] != tri[0] {
                tris.push((tri, f.mat_id, f.tags.clone()));
            }
        }
    }
    let orig_tris = tris.len();
    let goal = target_faces
        .map(|tf| tf.max(4))
        .unwrap_or_else(|| ((orig_tris as f64) * ratio).round().max(4.0) as usize);
    if orig_tris <= goal {
        return Ok(mesh.clone());
    }

    // Per-vertex 4x4 symmetric Quadric Error Matrix stored as 10 upper-triangular floats
    #[derive(Clone, Copy, Default)]
    struct Quadric([f64; 10]);
    impl Quadric {
        #[inline]
        fn from_plane(a: f64, b: f64, c: f64, d: f64) -> Self {
            Self([
                a * a, a * b, a * c, a * d,
                b * b, b * c, b * d,
                c * c, c * d,
                d * d,
            ])
        }
        #[inline]
        fn add_assign(&mut self, o: &Quadric) {
            for i in 0..10 { self.0[i] += o.0[i]; }
        }
        #[inline]
        fn add(&self, o: &Quadric) -> Quadric {
            let mut r = Quadric::default();
            for i in 0..10 { r.0[i] = self.0[i] + o.0[i]; }
            r
        }
        #[inline]
        fn eval(&self, p: Vec3) -> f64 {
            let (x, y, z) = (p.x, p.y, p.z);
            let q = &self.0;
            (x * (q[0] * x + 2.0 * (q[1] * y + q[2] * z + q[3]))
                + y * (q[4] * y + 2.0 * (q[5] * z + q[6]))
                + z * (q[7] * z + 2.0 * q[8])
                + q[9])
            .max(0.0)
        }
    }

    let mut quadrics = vec![Quadric::default(); verts.len()];
    let mut v_tris: Vec<Vec<usize>> = vec![Vec::new(); verts.len()];
    let mut alive_tri = vec![true; tris.len()];
    let mut alive_vert = vec![true; verts.len()];

    for (ti, (t, _, _)) in tris.iter().enumerate() {
        let p0 = verts[t[0]];
        let p1 = verts[t[1]];
        let p2 = verts[t[2]];
        let cr = (p1 - p0).cross(p2 - p0);
        let area2 = cr.len();
        if area2 > 1e-12 {
            let scale = (area2 * 0.5).sqrt().max(1e-4) / area2;
            let nw = cr * scale;
            let dw = -nw.dot(p0);
            let pq = Quadric::from_plane(nw.x, nw.y, nw.z, dw);
            for &vi in t {
                quadrics[vi].add_assign(&pq);
            }
        }
        for &vi in t {
            v_tris[vi].push(ti);
        }
    }

    #[derive(Clone, Copy)]
    struct EdgeItem {
        cost: f64,
        u: usize,
        v: usize,
        ver_u: u32,
        ver_v: u32,
        best_pt: Vec3,
    }
    impl PartialEq for EdgeItem {
        fn eq(&self, other: &Self) -> bool {
            self.cost.total_cmp(&other.cost) == Ordering::Equal
                && self.u == other.u
                && self.v == other.v
        }
    }
    impl Eq for EdgeItem {}
    impl PartialOrd for EdgeItem {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
    }
    impl Ord for EdgeItem {
        fn cmp(&self, other: &Self) -> Ordering {
            other.cost.total_cmp(&self.cost).then_with(|| self.u.cmp(&other.u)).then_with(|| self.v.cmp(&other.v))
        }
    }

    let qem_aabb_pad: f64 = 0.25;
    let qem_det_eps: f64 = 1e-8;
    let eval_edge = |u: usize, v: usize, verts: &[Vec3], quadrics: &[Quadric]| -> (f64, Vec3) {
        let q = quadrics[u].add(&quadrics[v]);
        let pu = verts[u];
        let pv = verts[v];
        let pm = (pu + pv) * 0.5;
        let mut best = (q.eval(pm), pm);
        let eu = q.eval(pu);
        if eu < best.0 { best = (eu, pu); }
        let ev = q.eval(pv);
        if ev < best.0 { best = (ev, pv); }

        // Exact Garland-Heckbert 3x3 symmetric QEM optimal point: A * x = -b
        let a00 = q.0[0]; let a01 = q.0[1]; let a02 = q.0[2]; let b0 = -q.0[3];
        let a11 = q.0[4]; let a12 = q.0[5]; let b1 = -q.0[6];
        let a22 = q.0[7]; let b2 = -q.0[8];
        let c00 = a11 * a22 - a12 * a12;
        let c01 = a02 * a12 - a01 * a22;
        let c02 = a01 * a12 - a02 * a11;
        let det = a00 * c00 + a01 * c01 + a02 * c02;
        if det.abs() > qem_det_eps {
            let inv_d = 1.0 / det;
            let c11 = a00 * a22 - a02 * a02;
            let c12 = a01 * a02 - a00 * a12;
            let c22 = a00 * a11 - a01 * a01;
            let opt = Vec3::new(
                (c00 * b0 + c01 * b1 + c02 * b2) * inv_d,
                (c01 * b0 + c11 * b1 + c12 * b2) * inv_d,
                (c02 * b0 + c12 * b1 + c22 * b2) * inv_d,
            );
            let elen = (pu - pv).len() * qem_aabb_pad;
            let mn = Vec3::new(pu.x.min(pv.x) - elen, pu.y.min(pv.y) - elen, pu.z.min(pv.z) - elen);
            let mx = Vec3::new(pu.x.max(pv.x) + elen, pu.y.max(pv.y) + elen, pu.z.max(pv.z) + elen);
            if opt.x.is_finite() && opt.y.is_finite() && opt.z.is_finite()
                && opt.x >= mn.x && opt.x <= mx.x
                && opt.y >= mn.y && opt.y <= mx.y
                && opt.z >= mn.z && opt.z <= mx.z
            {
                let eo = q.eval(opt);
                if eo < best.0 {
                    best = (eo, opt);
                }
            }
        }
        let len_pen = (pu - pv).len_sq() * 1e-10;
        (best.0 + len_pen, best.1)
    };

    let mut vert_ver = vec![0u32; verts.len()];
    let mut seen_edges: HashSet<(usize, usize)> = HashSet::with_capacity(tris.len() * 2);
    let mut heap: BinaryHeap<EdgeItem> = BinaryHeap::with_capacity(tris.len() * 2);

    for (t, _, _) in &tris {
        for &(a, b) in &[(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
            let e = if a < b { (a, b) } else { (b, a) };
            if seen_edges.insert(e) {
                let (cost, best_pt) = eval_edge(e.0, e.1, &verts, &quadrics);
                heap.push(EdgeItem { cost, u: e.0, v: e.1, ver_u: 0, ver_v: 0, best_pt });
            }
        }
    }

    let mut live_count = orig_tris;
    let mut nbrs_u: Vec<usize> = Vec::with_capacity(16);
    let mut nbrs_v: Vec<usize> = Vec::with_capacity(16);

    while live_count > goal {
        let Some(item) = heap.pop() else { break };
        let (u, v) = (item.u, item.v);
        if !alive_vert[u] || !alive_vert[v] || vert_ver[u] != item.ver_u || vert_ver[v] != item.ver_v {
            continue;
        }

        // Gather neighbors of u and v across live incident triangles
        nbrs_u.clear();
        nbrs_v.clear();
        let mut shared_tris = 0usize;
        for &ti in &v_tris[u] {
            if !alive_tri[ti] { continue; }
            let t = tris[ti].0;
            let has_v = t[0] == v || t[1] == v || t[2] == v;
            if has_v { shared_tris += 1; }
            for &w in &t {
                if w != u && !nbrs_u.contains(&w) { nbrs_u.push(w); }
            }
        }
        if shared_tris != 2 {
            // Skip boundary or non-2-manifold edges to guarantee closed manifold preservation
            continue;
        }
        for &ti in &v_tris[v] {
            if !alive_tri[ti] { continue; }
            for &w in &tris[ti].0 {
                if w != v && !nbrs_v.contains(&w) { nbrs_v.push(w); }
            }
        }

        // Full Edelsbrunner Link-Condition:
        // 0-simplex: lk(u) ∩ lk(v) must equal the 2 opposite vertices (c0, c1) of the shared tris.
        // 1-simplex: (c0, c1) cannot simultaneously form surviving triangles with both u and v
        // (which collapses a 4-tri tetrahedron component into two zero-volume opposing triangles).
        let mut common_verts = [0usize; 2];
        let mut common = 0usize;
        for &w in &nbrs_u {
            if w != v && nbrs_v.contains(&w) {
                if common < 2 {
                    common_verts[common] = w;
                }
                common += 1;
            }
        }
        if common != 2 {
            continue;
        }
        let (c0, c1) = (common_verts[0], common_verts[1]);
        let u_has_c0c1 = v_tris[u].iter().any(|&ti| {
            alive_tri[ti] && {
                let t = tris[ti].0;
                t.contains(&c0) && t.contains(&c1)
            }
        });
        let v_has_c0c1 = v_tris[v].iter().any(|&ti| {
            alive_tri[ti] && {
                let t = tris[ti].0;
                t.contains(&c0) && t.contains(&c1)
            }
        });
        if u_has_c0c1 && v_has_c0c1 {
            continue;
        }

        // Normal-flip & degeneracy check on all surviving incident triangles
        let new_p = item.best_pt;
        let mut bad = false;
        for &ti in v_tris[u].iter().chain(v_tris[v].iter()) {
            if !alive_tri[ti] { continue; }
            let t = tris[ti].0;
            if (t[0] == u || t[1] == u || t[2] == u) && (t[0] == v || t[1] == v || t[2] == v) {
                continue; // collapsed triangle
            }
            let old_n = (verts[t[1]] - verts[t[0]]).cross(verts[t[2]] - verts[t[0]]);
            let old_l = old_n.len();
            if old_l < 1e-12 { continue; }
            let p0 = if t[0] == u || t[0] == v { new_p } else { verts[t[0]] };
            let p1 = if t[1] == u || t[1] == v { new_p } else { verts[t[1]] };
            let p2 = if t[2] == u || t[2] == v { new_p } else { verts[t[2]] };
            let new_n = (p1 - p0).cross(p2 - p0);
            let new_l = new_n.len();
            if new_l < 1e-12 || (old_n.dot(new_n) / (old_l * new_l)) < 0.25 {
                bad = true;
                break;
            }
        }
        if bad {
            continue;
        }

        // Perform collapse: merge v into u at new_p
        verts[u] = new_p;
        quadrics[u] = quadrics[u].add(&quadrics[v]);
        alive_vert[v] = false;
        vert_ver[u] = vert_ver[u].wrapping_add(1);

        let moved = std::mem::take(&mut v_tris[v]);
        for ti in moved {
            if !alive_tri[ti] { continue; }
            let t = &mut tris[ti].0;
            if t[0] == u || t[1] == u || t[2] == u {
                alive_tri[ti] = false;
                live_count = live_count.saturating_sub(1);
            } else {
                for slot in t.iter_mut() {
                    if *slot == v { *slot = u; }
                }
                v_tris[u].push(ti);
            }
        }
        v_tris[u].retain(|&ti| alive_tri[ti]);

        // Re-score incident edges of u
        let mut uniq_n: Vec<usize> = Vec::with_capacity(16);
        for &ti in &v_tris[u] {
            for &w in &tris[ti].0 {
                if w != u && alive_vert[w] && !uniq_n.contains(&w) {
                    uniq_n.push(w);
                }
            }
        }
        for w in uniq_n {
            let (a, b) = if u < w { (u, w) } else { (w, u) };
            let (cost, best_pt) = eval_edge(a, b, &verts, &quadrics);
            heap.push(EdgeItem { cost, u: a, v: b, ver_u: vert_ver[a], ver_v: vert_ver[b], best_pt });
        }
    }

    // Compact live vertices and triangles into output PolyMesh
    let mut out = PolyMesh::new();
    out.materials = mesh.materials.clone();
    out.smooth_angle_deg = mesh.smooth_angle_deg;
    out.weighted_normals = mesh.weighted_normals;
    let mut remap: Vec<Option<usize>> = vec![None; verts.len()];
    for (ti, (t, mat_id, tags)) in tris.into_iter().enumerate() {
        if !alive_tri[ti] { continue; }
        let mut nv = SmallVec::<[usize; 4]>::new();
        for vi in t {
            let mapped = match remap[vi] {
                Some(id) => id,
                None => {
                    let id = out.add_vert(verts[vi]);
                    remap[vi] = Some(id);
                    id
                }
            };
            nv.push(mapped);
        }
        let fi = out.add_face(nv, op_id, None);
        out.faces[fi].mat_id = mat_id;
        out.faces[fi].tags = tags;
    }
    out.ensure_outward_winding();
    Ok(out)
}