Skip to main content

u_nesting_d2/
lib.rs

1//! # U-Nesting 2D
2//!
3//! 2D nesting algorithms for the U-Nesting spatial optimization engine.
4//!
5//! This crate provides polygon-based 2D nesting with NFP (No-Fit Polygon) computation
6//! and various placement algorithms.
7//!
8//! ## Features
9//!
10//! - Polygon geometry with holes support
11//! - Multiple placement strategies (BLF, NFP-guided, GA, BRKGA, SA)
12//! - Convex hull and convexity detection
13//! - Configurable rotation and mirroring constraints
14//! - NFP-based collision-free placement
15//! - Spatial indexing for fast queries
16//!
17//! ## Quick Start
18//!
19//! ```rust
20//! use u_nesting_d2::{Geometry2D, Boundary2D, Nester2D, Config, Strategy, Solver};
21//!
22//! // Create geometries
23//! let rect = Geometry2D::rectangle("rect1", 100.0, 50.0)
24//!     .with_quantity(5)
25//!     .with_rotations_deg(vec![0.0, 90.0]);
26//!
27//! // Create boundary
28//! let boundary = Boundary2D::rectangle(500.0, 300.0);
29//!
30//! // Configure and solve
31//! let config = Config::new()
32//!     .with_strategy(Strategy::NfpGuided)
33//!     .with_spacing(2.0);
34//!
35//! let nester = Nester2D::new(config);
36//! let result = nester.solve(&[rect], &boundary).unwrap();
37//!
38//! println!("Placed {} items, utilization: {:.1}%",
39//!     result.placements.len(),
40//!     result.utilization * 100.0);
41//! ```
42//!
43//! ## Geometry Creation
44//!
45//! ```rust
46//! use u_nesting_d2::Geometry2D;
47//!
48//! // Rectangle
49//! let rect = Geometry2D::rectangle("r1", 100.0, 50.0);
50//!
51//! // Circle (approximated)
52//! let circle = Geometry2D::circle("c1", 25.0, 32);
53//!
54//! // L-shape
55//! let l_shape = Geometry2D::l_shape("l1", 100.0, 80.0, 30.0, 30.0);
56//!
57//! // Custom polygon
58//! let custom = Geometry2D::new("custom")
59//!     .with_polygon(vec![(0.0, 0.0), (100.0, 0.0), (50.0, 80.0)])
60//!     .with_quantity(3);
61//! ```
62
63pub mod alns_nesting;
64pub mod boundary;
65pub mod brkga_nesting;
66pub mod ga_nesting;
67pub mod gdrr_nesting;
68pub mod geometry;
69pub mod nester;
70pub mod nfp;
71#[cfg(feature = "milp")]
72pub mod nfp_cm_solver;
73pub mod nfp_sliding;
74pub mod placement_utils;
75pub(crate) mod polygon_ops;
76pub mod sa_nesting;
77pub mod spatial_index;
78
79/// Computes valid placement bounds and clamps a position to keep geometry within boundary.
80///
81/// Returns `Some((clamped_x, clamped_y))` if the geometry can fit in the boundary,
82/// `None` if the geometry is too large to fit.
83///
84/// # Arguments
85/// * `x`, `y` - The proposed placement position for the geometry's origin
86/// * `geom_aabb` - The AABB `(min, max)` of the geometry at the given rotation
87/// * `boundary_aabb` - The AABB `(min, max)` of the boundary
88pub fn clamp_placement_to_boundary(
89    x: f64,
90    y: f64,
91    geom_aabb: ([f64; 2], [f64; 2]),
92    boundary_aabb: ([f64; 2], [f64; 2]),
93) -> Option<(f64, f64)> {
94    let (g_min, g_max) = geom_aabb;
95    let (b_min, b_max) = boundary_aabb;
96
97    // Calculate valid position bounds
98    // For geometry to stay inside boundary:
99    // - x + g_min[0] >= b_min[0]  => x >= b_min[0] - g_min[0]
100    // - x + g_max[0] <= b_max[0]  => x <= b_max[0] - g_max[0]
101    let min_valid_x = b_min[0] - g_min[0];
102    let max_valid_x = b_max[0] - g_max[0];
103    let min_valid_y = b_min[1] - g_min[1];
104    let max_valid_y = b_max[1] - g_max[1];
105
106    // Check if geometry can fit
107    if max_valid_x < min_valid_x || max_valid_y < min_valid_y {
108        // Geometry is too large to fit in boundary
109        return None;
110    }
111
112    let clamped_x = x.clamp(min_valid_x, max_valid_x);
113    let clamped_y = y.clamp(min_valid_y, max_valid_y);
114
115    Some((clamped_x, clamped_y))
116}
117
118/// Computes valid placement bounds with margin and clamps a position to keep geometry within boundary.
119///
120/// Returns `Some((clamped_x, clamped_y))` if the geometry can fit in the boundary (with margin),
121/// `None` if the geometry is too large to fit.
122///
123/// # Arguments
124/// * `x`, `y` - The proposed placement position for the geometry's origin
125/// * `geom_aabb` - The AABB `(min, max)` of the geometry at the given rotation
126/// * `boundary_aabb` - The AABB `(min, max)` of the boundary
127/// * `margin` - The margin to apply inside the boundary
128pub fn clamp_placement_to_boundary_with_margin(
129    x: f64,
130    y: f64,
131    geom_aabb: ([f64; 2], [f64; 2]),
132    boundary_aabb: ([f64; 2], [f64; 2]),
133    margin: f64,
134) -> Option<(f64, f64)> {
135    let (g_min, g_max) = geom_aabb;
136    let (b_min, b_max) = boundary_aabb;
137
138    // Calculate valid position bounds (with margin applied to effective boundary)
139    // Effective boundary: [b_min + margin, b_max - margin]
140    // For geometry to stay inside effective boundary:
141    // - x + g_min[0] >= b_min[0] + margin  => x >= b_min[0] + margin - g_min[0]
142    // - x + g_max[0] <= b_max[0] - margin  => x <= b_max[0] - margin - g_max[0]
143    let min_valid_x = b_min[0] + margin - g_min[0];
144    let max_valid_x = b_max[0] - margin - g_max[0];
145    let min_valid_y = b_min[1] + margin - g_min[1];
146    let max_valid_y = b_max[1] - margin - g_max[1];
147
148    // Check if geometry can fit
149    if max_valid_x < min_valid_x || max_valid_y < min_valid_y {
150        // Geometry is too large to fit in boundary with the given margin
151        return None;
152    }
153
154    let clamped_x = x.clamp(min_valid_x, max_valid_x);
155    let clamped_y = y.clamp(min_valid_y, max_valid_y);
156
157    Some((clamped_x, clamped_y))
158}
159
160/// Checks if a placement is within the boundary.
161///
162/// Returns `true` if the geometry at the given placement is fully within the boundary,
163/// `false` otherwise.
164///
165/// # Arguments
166/// * `placement` - The placement to validate (contains position and rotation)
167/// * `geometry` - The geometry being placed
168/// * `boundary` - The boundary to check against
169/// * `tolerance` - Small tolerance for floating point comparison (e.g., 1e-6)
170pub fn is_placement_within_bounds(
171    placement: &Placement<f64>,
172    geometry: &Geometry2D,
173    boundary: &Boundary2D,
174    tolerance: f64,
175) -> bool {
176    use u_nesting_core::geometry::Boundary;
177    use u_nesting_core::Boundary2DExt;
178
179    // Extract position (Vec<f64> with [x, y] for 2D)
180    let x = placement.position.first().copied().unwrap_or(0.0);
181    let y = placement.position.get(1).copied().unwrap_or(0.0);
182
183    // Extract rotation (Vec<f64> with [θ] for 2D)
184    let rotation = placement.rotation.first().copied().unwrap_or(0.0);
185
186    // Get geometry AABB at the placement rotation
187    let (g_min, g_max) = geometry.aabb_at_rotation(rotation);
188
189    // Get boundary AABB
190    let (b_min, b_max) = boundary.aabb();
191
192    // Calculate the actual bounds of the placed geometry
193    let placed_min_x = x + g_min[0];
194    let placed_max_x = x + g_max[0];
195    let placed_min_y = y + g_min[1];
196    let placed_max_y = y + g_max[1];
197
198    // AABB containment — a necessary condition, and *exact* for a hole-free
199    // axis-aligned rectangular boundary.
200    let aabb_inside = placed_min_x >= b_min[0] - tolerance
201        && placed_max_x <= b_max[0] + tolerance
202        && placed_min_y >= b_min[1] - tolerance
203        && placed_max_y <= b_max[1] + tolerance;
204
205    // Fast reject and the exact-boundary shortcut.
206    //
207    // For a plain rectangle (width & height set, no holes) the AABB check is the
208    // exact answer. Infinite strips must also stay on the AABB path: their
209    // exterior carries `f64::MAX` vertices, so ray-cast polygon containment is
210    // meaningless. Everything else — an arbitrary boundary polygon, or a
211    // rectangle carrying holes — needs true polygon-in-polygon containment,
212    // because the AABB of a triangular/concave/holed boundary spans empty
213    // regions where a piece would sit fully inside the box yet outside the shape.
214    let plain_rectangle =
215        boundary.width().is_some() && boundary.height().is_some() && boundary.holes().is_empty();
216    if boundary.is_infinite() || plain_rectangle {
217        return aabb_inside;
218    }
219    if !aabb_inside {
220        return false;
221    }
222
223    let piece = geometry.transformed_exterior(x, y, rotation);
224    boundary.contains_polygon(&piece)
225}
226
227/// Validates all placements in a SolveResult and removes any that are outside the boundary.
228///
229/// Returns a new SolveResult with only valid placements, updated utilization,
230/// and invalid placements added to the unplaced list.
231///
232/// # Arguments
233/// * `result` - The solve result to validate
234/// * `geometries` - The geometries that were being placed
235/// * `boundary` - The boundary to check against
236pub fn validate_and_filter_placements(
237    mut result: SolveResult<f64>,
238    geometries: &[Geometry2D],
239    boundary: &Boundary2D,
240) -> SolveResult<f64> {
241    use std::collections::HashMap;
242    use u_nesting_core::geometry::{Boundary, Geometry};
243
244    const TOLERANCE: f64 = 1e-6;
245
246    // Build a map from geometry ID to geometry for quick lookup
247    let geom_map: HashMap<_, _> = geometries.iter().map(|g| (g.id().clone(), g)).collect();
248
249    let (b_min, b_max) = boundary.aabb();
250    log::debug!(
251        "Validating placements against boundary: ({:.2}, {:.2}) to ({:.2}, {:.2})",
252        b_min[0],
253        b_min[1],
254        b_max[0],
255        b_max[1]
256    );
257
258    let mut valid_placements = Vec::new();
259    let mut total_valid_area = 0.0;
260    let mut filtered_count = 0;
261    // Used-footprint accumulator: the AABB union of the placed pieces, which is
262    // boundary-padding independent (unlike `utilization`, which divides by the
263    // full boundary and shrinks arbitrarily as boundary height grows).
264    let mut used_min_x = f64::INFINITY;
265    let mut used_min_y = f64::INFINITY;
266    let mut used_max_x = f64::NEG_INFINITY;
267    let mut used_max_y = f64::NEG_INFINITY;
268
269    for placement in result.placements {
270        if let Some(geom) = geom_map.get(&placement.geometry_id) {
271            let px = placement.position.first().copied().unwrap_or(0.0);
272            let py = placement.position.get(1).copied().unwrap_or(0.0);
273            let rot = placement.rotation.first().copied().unwrap_or(0.0);
274
275            if is_placement_within_bounds(&placement, geom, boundary, TOLERANCE) {
276                total_valid_area += geom.measure();
277                let (pg_min, pg_max) = geom.aabb_at_rotation(rot);
278                used_min_x = used_min_x.min(px + pg_min[0]);
279                used_min_y = used_min_y.min(py + pg_min[1]);
280                used_max_x = used_max_x.max(px + pg_max[0]);
281                used_max_y = used_max_y.max(py + pg_max[1]);
282                valid_placements.push(placement);
283            } else {
284                // Calculate actual bounds for debugging
285                let (g_min, g_max) = geom.aabb_at_rotation(rot);
286                let placed_min_x = px + g_min[0];
287                let placed_max_x = px + g_max[0];
288                let placed_min_y = py + g_min[1];
289                let placed_max_y = py + g_max[1];
290
291                log::warn!(
292                    "FILTERED: {} at ({:.2}, {:.2}) rot={:.2}° - bounds ({:.2}, {:.2}) to ({:.2}, {:.2}) outside boundary",
293                    placement.geometry_id,
294                    px, py,
295                    rot.to_degrees(),
296                    placed_min_x, placed_min_y, placed_max_x, placed_max_y
297                );
298                filtered_count += 1;
299                // Add to unplaced list
300                result.unplaced.push(placement.geometry_id.clone());
301            }
302        } else {
303            // Geometry not found - shouldn't happen but handle gracefully
304            log::warn!("Geometry {} not found in lookup map", placement.geometry_id);
305            result.unplaced.push(placement.geometry_id.clone());
306        }
307    }
308
309    if filtered_count > 0 {
310        log::warn!(
311            "Validation filtered out {} placements as out-of-bounds",
312            filtered_count
313        );
314    }
315
316    // Update result with valid placements only
317    result.placements = valid_placements;
318    result.utilization = total_valid_area / boundary.measure();
319
320    // Record the used-footprint metrics (padding-independent). `total_piece_area`
321    // is otherwise only populated on the multi-strip path; set it here so the
322    // single-sheet `used_utilization = piece_area / used_bbox_area` is meaningful.
323    result.total_piece_area = total_valid_area;
324    if result.placements.is_empty() {
325        result.used_bounding_box = [0.0, 0.0];
326    } else {
327        result.used_bounding_box = [used_max_x - used_min_x, used_max_y - used_min_y];
328    }
329
330    result
331}
332
333// Re-exports
334pub use boundary::Boundary2D;
335pub use geometry::Geometry2D;
336pub use nester::Nester2D;
337pub use nfp::{NfpConfig, NfpMethod};
338pub use spatial_index::{SpatialEntry2D, SpatialIndex2D};
339pub use u_nesting_core::{
340    Boundary, Boundary2DExt, Config, Error, Geometry, Geometry2DExt, Placement, Result,
341    RotationConstraint, SolveResult, Solver, Strategy, Transform2D, AABB2D,
342};