use manifold_csg_sys::*;
use crate::cross_section::build_polygons_ffi;
pub fn triangulate_polygons(polygons: &[Vec<[f64; 2]>], epsilon: f64) -> Option<Vec<[u32; 3]>> {
if polygons.is_empty() {
return None;
}
let (polys_ptr, simple_ptrs) = build_polygons_ffi(polygons);
let tri_ptr = unsafe { manifold_alloc_triangulation() };
unsafe { manifold_triangulate(tri_ptr, polys_ptr, epsilon) };
let n_tris = unsafe { manifold_triangulation_num_tri(tri_ptr) };
let result = if n_tris > 0 {
let mut indices = vec![0i32; n_tris * 3];
unsafe { manifold_triangulation_tri_verts(indices.as_mut_ptr(), tri_ptr) };
let triangles: Vec<[u32; 3]> = indices
.chunks(3)
.map(|c| {
assert!(
c[0] >= 0 && c[1] >= 0 && c[2] >= 0,
"negative triangle index from C API"
);
[c[0] as u32, c[1] as u32, c[2] as u32]
})
.collect();
Some(triangles)
} else {
None
};
unsafe { manifold_delete_triangulation(tri_ptr) };
unsafe { manifold_delete_polygons(polys_ptr) };
for sp in simple_ptrs {
unsafe { manifold_delete_simple_polygon(sp) };
}
result
}