u-nesting-d3 0.3.2

3D bin packing algorithms for U-Nesting spatial optimization engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! 3D bin packing solver.

use crate::boundary::Boundary3D;
use crate::brkga_packing::run_brkga_packing;
use crate::extreme_point::run_ep_packing;
use crate::ga_packing::run_ga_packing;
use crate::geometry::Geometry3D;
use crate::physics::{PhysicsConfig, PhysicsSimulator};
use crate::sa_packing::run_sa_packing;
use crate::stability::{PlacedBox, StabilityAnalyzer, StabilityConstraint, StabilityReport};
use u_nesting_core::brkga::BrkgaConfig;
use u_nesting_core::ga::GaConfig;
use u_nesting_core::geom::nalgebra_types::{NaPoint3 as Point3, NaVector3 as Vector3};
use u_nesting_core::geometry::{Boundary, Geometry};
use u_nesting_core::sa::SaConfig;
use u_nesting_core::solver::{Config, ProgressCallback, ProgressInfo, Solver, Strategy};
use u_nesting_core::{Placement, Result, SolveResult};

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use u_nesting_core::timing::Timer;

/// Best fit candidate for 3D placement.
/// (orientation_idx, width, depth, height, place_x, place_y, place_z, new_row_depth, new_layer_height)
type BestFit3D = Option<(usize, f64, f64, f64, f64, f64, f64, f64, f64)>;

/// 3D bin packing solver.
pub struct Packer3D {
    config: Config,
    cancelled: Arc<AtomicBool>,
}

impl Packer3D {
    /// Creates a new packer with the given configuration.
    pub fn new(config: Config) -> Self {
        Self {
            config,
            cancelled: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Creates a packer with default configuration.
    pub fn default_config() -> Self {
        Self::new(Config::default())
    }

    /// Validates the stability of a packing result.
    ///
    /// Analyzes each placement to ensure boxes are properly supported.
    pub fn validate_stability(
        &self,
        result: &SolveResult<f64>,
        geometries: &[Geometry3D],
        _boundary: &Boundary3D,
        constraint: StabilityConstraint,
    ) -> StabilityReport {
        // Convert placements to PlacedBox format
        let placed_boxes = self.placements_to_boxes(result, geometries);
        let analyzer = StabilityAnalyzer::new(constraint);
        analyzer.analyze(&placed_boxes, 0.0)
    }

    /// Validates stability using physics simulation.
    ///
    /// Runs a physics simulation to detect boxes that would fall or tip.
    pub fn validate_stability_physics(
        &self,
        result: &SolveResult<f64>,
        geometries: &[Geometry3D],
        boundary: &Boundary3D,
    ) -> StabilityReport {
        let placed_boxes = self.placements_to_boxes(result, geometries);
        let container = Vector3::new(boundary.width(), boundary.depth(), boundary.height());

        let config = PhysicsConfig::default().with_max_time(2.0);
        let simulator = PhysicsSimulator::new(config);
        simulator.validate_stability(&placed_boxes, container, 0.0)
    }

    /// Converts placements to PlacedBox format for stability analysis.
    fn placements_to_boxes(
        &self,
        result: &SolveResult<f64>,
        geometries: &[Geometry3D],
    ) -> Vec<PlacedBox> {
        let geom_map: std::collections::HashMap<&str, &Geometry3D> =
            geometries.iter().map(|g| (g.id().as_str(), g)).collect();

        result
            .placements
            .iter()
            .filter_map(|p| {
                let geom = geom_map.get(p.geometry_id.as_str())?;
                let ori_idx = p.rotation_index.unwrap_or(0);
                let dims = geom.dimensions_for_orientation(ori_idx);

                let mut placed = PlacedBox::new(
                    p.geometry_id.clone(),
                    p.instance,
                    Point3::new(p.position[0], p.position[1], p.position[2]),
                    dims,
                );

                if let Some(mass) = geom.mass() {
                    placed = placed.with_mass(mass);
                }

                Some(placed)
            })
            .collect()
    }

    /// Simple layer-based packing algorithm.
    fn layer_packing(
        &self,
        geometries: &[Geometry3D],
        boundary: &Boundary3D,
    ) -> Result<SolveResult<f64>> {
        let start = Timer::now();
        let mut result = SolveResult::new();
        let mut placements = Vec::new();

        let margin = self.config.margin;
        let spacing = self.config.spacing;

        let bound_max_x = boundary.width() - margin;
        let bound_max_y = boundary.depth() - margin;
        let bound_max_z = boundary.height() - margin;

        // Simple layer-based placement
        let mut current_x = margin;
        let mut current_y = margin;
        let mut current_z = margin;
        let mut row_depth = 0.0_f64;
        let mut layer_height = 0.0_f64;

        let mut total_placed_volume = 0.0;
        let mut total_placed_mass = 0.0;

        for geom in geometries {
            geom.validate()?;

            for instance in 0..geom.quantity() {
                if self.cancelled.load(Ordering::Relaxed) {
                    result.computation_time_ms = start.elapsed_ms();
                    return Ok(result);
                }

                // Check time limit (0 = unlimited)
                if self.config.time_limit_ms > 0 && start.elapsed_ms() >= self.config.time_limit_ms
                {
                    result.boundaries_used = if placements.is_empty() { 0 } else { 1 };
                    result.utilization = total_placed_volume / boundary.measure();
                    result.computation_time_ms = start.elapsed_ms();
                    result.placements = placements;
                    return Ok(result);
                }

                // Check mass constraint
                if let (Some(max_mass), Some(item_mass)) = (boundary.max_mass(), geom.mass()) {
                    if total_placed_mass + item_mass > max_mass {
                        result.unplaced.push(geom.id().clone());
                        continue;
                    }
                }

                // Try all allowed orientations to find the best fit
                let orientations = geom.allowed_orientations();
                let mut best_fit: BestFit3D = None;
                // (orientation_idx, width, depth, height, place_x, place_y, place_z, new_row_depth, new_layer_height)

                for (ori_idx, _) in orientations.iter().enumerate() {
                    let dims = geom.dimensions_for_orientation(ori_idx);
                    let g_width = dims.x;
                    let g_depth = dims.y;
                    let g_height = dims.z;

                    // Try current position first
                    let mut try_x = current_x;
                    let mut try_y = current_y;
                    let mut try_z = current_z;
                    let mut try_row_depth = row_depth;
                    let mut try_layer_height = layer_height;

                    // Check if fits in current row
                    if try_x + g_width > bound_max_x {
                        try_x = margin;
                        try_y += row_depth + spacing;
                        try_row_depth = 0.0;
                    }

                    // Check if fits in current layer
                    if try_y + g_depth > bound_max_y {
                        try_x = margin;
                        try_y = margin;
                        try_z += layer_height + spacing;
                        try_row_depth = 0.0;
                        try_layer_height = 0.0;
                    }

                    // Check if fits in container
                    if try_z + g_height > bound_max_z {
                        continue; // This orientation doesn't fit
                    }

                    // Score: prefer placements that use less vertical space (height)
                    // and stay in current row (lower y advancement)
                    let score = try_z * 1000000.0 + try_y * 1000.0 + try_x + g_height * 0.1;

                    let is_better = match &best_fit {
                        None => true,
                        Some((_, _, _, bg_height, bx, by, bz, _, _)) => {
                            let best_score = bz * 1000000.0 + by * 1000.0 + bx + bg_height * 0.1;
                            score < best_score
                        }
                    };

                    if is_better {
                        best_fit = Some((
                            ori_idx,
                            g_width,
                            g_depth,
                            g_height,
                            try_x,
                            try_y,
                            try_z,
                            try_row_depth,
                            try_layer_height,
                        ));
                    }
                }

                if let Some((
                    ori_idx,
                    g_width,
                    g_depth,
                    g_height,
                    place_x,
                    place_y,
                    place_z,
                    new_row_depth,
                    new_layer_height,
                )) = best_fit
                {
                    // Convert orientation index to rotation angles
                    // For simplicity, we encode orientation in rotation_index
                    let placement = Placement::new_3d(
                        geom.id().clone(),
                        instance,
                        place_x,
                        place_y,
                        place_z,
                        0.0, // Orientation is encoded via rotation_index
                        0.0,
                        0.0,
                    )
                    .with_rotation_index(ori_idx);

                    placements.push(placement);
                    total_placed_volume += geom.measure();
                    if let Some(mass) = geom.mass() {
                        total_placed_mass += mass;
                    }

                    // Update position for next item
                    current_x = place_x + g_width + spacing;
                    current_y = place_y;
                    current_z = place_z;
                    row_depth = new_row_depth.max(g_depth);
                    layer_height = new_layer_height.max(g_height);
                } else {
                    result.unplaced.push(geom.id().clone());
                }
            }
        }

        result.placements = placements;
        result.boundaries_used = 1;
        result.utilization = total_placed_volume / boundary.measure();
        result.computation_time_ms = start.elapsed_ms();

        Ok(result)
    }

    /// Genetic Algorithm based packing optimization.
    ///
    /// Uses GA to optimize placement order and orientations, with layer-based
    /// decoding for collision-free placements.
    fn genetic_algorithm(
        &self,
        geometries: &[Geometry3D],
        boundary: &Boundary3D,
    ) -> Result<SolveResult<f64>> {
        // Configure GA from solver config
        let ga_config = GaConfig::default()
            .with_population_size(self.config.population_size)
            .with_max_generations(self.config.max_generations)
            .with_crossover_rate(self.config.crossover_rate)
            .with_mutation_rate(self.config.mutation_rate);

        let result = run_ga_packing(
            geometries,
            boundary,
            &self.config,
            ga_config,
            self.cancelled.clone(),
        );

        Ok(result)
    }

    /// BRKGA (Biased Random-Key Genetic Algorithm) based packing optimization.
    ///
    /// Uses random-key encoding and biased crossover for robust optimization.
    fn brkga(&self, geometries: &[Geometry3D], boundary: &Boundary3D) -> Result<SolveResult<f64>> {
        // Configure BRKGA with reasonable defaults
        let brkga_config = BrkgaConfig::default()
            .with_population_size(50)
            .with_max_generations(100)
            .with_elite_fraction(0.2)
            .with_mutant_fraction(0.15)
            .with_elite_bias(0.7);

        let result = run_brkga_packing(
            geometries,
            boundary,
            &self.config,
            brkga_config,
            self.cancelled.clone(),
        );

        Ok(result)
    }

    /// Simulated Annealing based packing optimization.
    ///
    /// Uses neighborhood operators to explore solution space with temperature-based
    /// acceptance probability.
    fn simulated_annealing(
        &self,
        geometries: &[Geometry3D],
        boundary: &Boundary3D,
    ) -> Result<SolveResult<f64>> {
        // Configure SA with reasonable defaults
        let sa_config = SaConfig::default()
            .with_initial_temp(100.0)
            .with_final_temp(0.1)
            .with_cooling_rate(0.95)
            .with_iterations_per_temp(50)
            .with_max_iterations(10000);

        let result = run_sa_packing(
            geometries,
            boundary,
            &self.config,
            sa_config,
            self.cancelled.clone(),
        );

        Ok(result)
    }

    /// Extreme Point heuristic-based packing.
    ///
    /// Places boxes at extreme points (positions touching at least two surfaces).
    /// More efficient than layer-based packing for many scenarios.
    fn extreme_point(
        &self,
        geometries: &[Geometry3D],
        boundary: &Boundary3D,
    ) -> Result<SolveResult<f64>> {
        let start = Timer::now();

        let (ep_placements, utilization) = run_ep_packing(
            geometries,
            boundary,
            self.config.margin,
            self.config.spacing,
            boundary.max_mass(),
        );

        // Convert EP placements to Placement structs
        let mut placements = Vec::new();
        for (id, instance, position, _orientation) in ep_placements {
            let placement = Placement::new_3d(
                id, instance, position.x, position.y, position.z, 0.0, // rotation_x
                0.0, // rotation_y
                0.0, // rotation_z (orientation handled internally)
            );
            placements.push(placement);
        }

        // Collect unplaced items
        let mut placed_ids: std::collections::HashSet<(String, usize)> =
            std::collections::HashSet::new();
        for p in &placements {
            placed_ids.insert((p.geometry_id.clone(), p.instance));
        }

        let mut unplaced = Vec::new();
        for geom in geometries {
            for instance in 0..geom.quantity() {
                if !placed_ids.contains(&(geom.id().clone(), instance)) {
                    unplaced.push(geom.id().clone());
                }
            }
        }

        let mut result = SolveResult::new();
        result.placements = placements;
        result.boundaries_used = 1;
        result.utilization = utilization;
        result.unplaced = unplaced;
        result.computation_time_ms = start.elapsed_ms();
        result.strategy = Some("ExtremePoint".to_string());

        Ok(result)
    }

    /// Layer packing with progress callback.
    fn layer_packing_with_progress(
        &self,
        geometries: &[Geometry3D],
        boundary: &Boundary3D,
        callback: &ProgressCallback,
    ) -> Result<SolveResult<f64>> {
        let start = Timer::now();
        let mut result = SolveResult::new();
        let mut placements = Vec::new();

        let margin = self.config.margin;
        let spacing = self.config.spacing;

        let bound_max_x = boundary.width() - margin;
        let bound_max_y = boundary.depth() - margin;
        let bound_max_z = boundary.height() - margin;

        let mut current_x = margin;
        let mut current_y = margin;
        let mut current_z = margin;
        let mut row_depth = 0.0_f64;
        let mut layer_height = 0.0_f64;

        let mut total_placed_volume = 0.0;
        let mut total_placed_mass = 0.0;

        // Count total pieces for progress
        let total_pieces: usize = geometries.iter().map(|g| g.quantity()).sum();
        let mut placed_count = 0usize;

        // Initial progress callback
        callback(
            ProgressInfo::new()
                .with_phase("Layer Packing")
                .with_items(0, total_pieces)
                .with_elapsed(0),
        );

        for geom in geometries {
            geom.validate()?;

            for instance in 0..geom.quantity() {
                if self.cancelled.load(Ordering::Relaxed) {
                    result.computation_time_ms = start.elapsed_ms();
                    callback(
                        ProgressInfo::new()
                            .with_phase("Cancelled")
                            .with_items(placed_count, total_pieces)
                            .with_elapsed(result.computation_time_ms)
                            .finished(),
                    );
                    return Ok(result);
                }

                // Check time limit (0 = unlimited)
                if self.config.time_limit_ms > 0 && start.elapsed_ms() >= self.config.time_limit_ms
                {
                    result.boundaries_used = if placements.is_empty() { 0 } else { 1 };
                    result.utilization = total_placed_volume / boundary.measure();
                    result.computation_time_ms = start.elapsed_ms();
                    result.placements = placements;
                    callback(
                        ProgressInfo::new()
                            .with_phase("Time Limit Reached")
                            .with_items(placed_count, total_pieces)
                            .with_elapsed(result.computation_time_ms)
                            .finished(),
                    );
                    return Ok(result);
                }

                // Check mass constraint
                if let (Some(max_mass), Some(item_mass)) = (boundary.max_mass(), geom.mass()) {
                    if total_placed_mass + item_mass > max_mass {
                        result.unplaced.push(geom.id().clone());
                        continue;
                    }
                }

                // Try all allowed orientations to find the best fit
                let orientations = geom.allowed_orientations();
                let mut best_fit: BestFit3D = None;

                for (ori_idx, _) in orientations.iter().enumerate() {
                    let dims = geom.dimensions_for_orientation(ori_idx);
                    let g_width = dims.x;
                    let g_depth = dims.y;
                    let g_height = dims.z;

                    let mut try_x = current_x;
                    let mut try_y = current_y;
                    let mut try_z = current_z;
                    let mut try_row_depth = row_depth;
                    let mut try_layer_height = layer_height;

                    if try_x + g_width > bound_max_x {
                        try_x = margin;
                        try_y += row_depth + spacing;
                        try_row_depth = 0.0;
                    }

                    if try_y + g_depth > bound_max_y {
                        try_x = margin;
                        try_y = margin;
                        try_z += layer_height + spacing;
                        try_row_depth = 0.0;
                        try_layer_height = 0.0;
                    }

                    if try_z + g_height > bound_max_z {
                        continue;
                    }

                    let score = try_z * 1000000.0 + try_y * 1000.0 + try_x + g_height * 0.1;

                    let is_better = match &best_fit {
                        None => true,
                        Some((_, _, _, bg_height, bx, by, bz, _, _)) => {
                            let best_score = bz * 1000000.0 + by * 1000.0 + bx + bg_height * 0.1;
                            score < best_score
                        }
                    };

                    if is_better {
                        best_fit = Some((
                            ori_idx,
                            g_width,
                            g_depth,
                            g_height,
                            try_x,
                            try_y,
                            try_z,
                            try_row_depth,
                            try_layer_height,
                        ));
                    }
                }

                if let Some((
                    ori_idx,
                    g_width,
                    g_depth,
                    g_height,
                    place_x,
                    place_y,
                    place_z,
                    new_row_depth,
                    new_layer_height,
                )) = best_fit
                {
                    let placement = Placement::new_3d(
                        geom.id().clone(),
                        instance,
                        place_x,
                        place_y,
                        place_z,
                        0.0,
                        0.0,
                        0.0,
                    )
                    .with_rotation_index(ori_idx);

                    placements.push(placement);
                    total_placed_volume += geom.measure();
                    if let Some(mass) = geom.mass() {
                        total_placed_mass += mass;
                    }
                    placed_count += 1;

                    current_x = place_x + g_width + spacing;
                    current_y = place_y;
                    current_z = place_z;
                    row_depth = new_row_depth.max(g_depth);
                    layer_height = new_layer_height.max(g_height);

                    // Progress callback every piece
                    callback(
                        ProgressInfo::new()
                            .with_phase("Layer Packing")
                            .with_items(placed_count, total_pieces)
                            .with_utilization(total_placed_volume / boundary.measure())
                            .with_elapsed(start.elapsed_ms()),
                    );
                } else {
                    result.unplaced.push(geom.id().clone());
                }
            }
        }

        result.placements = placements;
        result.boundaries_used = 1;
        result.utilization = total_placed_volume / boundary.measure();
        result.computation_time_ms = start.elapsed_ms();

        // Final progress callback
        callback(
            ProgressInfo::new()
                .with_phase("Complete")
                .with_items(placed_count, total_pieces)
                .with_utilization(result.utilization)
                .with_elapsed(result.computation_time_ms)
                .finished(),
        );

        Ok(result)
    }
}

impl Solver for Packer3D {
    type Geometry = Geometry3D;
    type Boundary = Boundary3D;
    type Scalar = f64;

    fn solve(
        &self,
        geometries: &[Self::Geometry],
        boundary: &Self::Boundary,
    ) -> Result<SolveResult<f64>> {
        boundary.validate()?;

        // Reset cancellation flag
        self.cancelled.store(false, Ordering::Relaxed);

        let mut result = match self.config.strategy {
            Strategy::BottomLeftFill => self.layer_packing(geometries, boundary),
            Strategy::ExtremePoint => self.extreme_point(geometries, boundary),
            Strategy::GeneticAlgorithm => self.genetic_algorithm(geometries, boundary),
            Strategy::Brkga => self.brkga(geometries, boundary),
            Strategy::SimulatedAnnealing => self.simulated_annealing(geometries, boundary),
            _ => {
                // Fall back to layer packing for unimplemented strategies
                log::warn!(
                    "Strategy {:?} not yet implemented, using layer packing",
                    self.config.strategy
                );
                self.layer_packing(geometries, boundary)
            }
        }?;

        // Remove duplicate entries from unplaced list
        result.deduplicate_unplaced();
        Ok(result)
    }

    fn solve_with_progress(
        &self,
        geometries: &[Self::Geometry],
        boundary: &Self::Boundary,
        callback: ProgressCallback,
    ) -> Result<SolveResult<f64>> {
        boundary.validate()?;

        // Reset cancellation flag
        self.cancelled.store(false, Ordering::Relaxed);

        let mut result = match self.config.strategy {
            Strategy::BottomLeftFill | Strategy::ExtremePoint => {
                self.layer_packing_with_progress(geometries, boundary, &callback)?
            }
            // Other strategies fall back to basic progress reporting
            _ => {
                log::warn!(
                    "Strategy {:?} progress not yet implemented, using layer packing",
                    self.config.strategy
                );
                self.layer_packing_with_progress(geometries, boundary, &callback)?
            }
        };

        // Remove duplicate entries from unplaced list
        result.deduplicate_unplaced();
        Ok(result)
    }

    fn cancel(&self) {
        self.cancelled.store(true, Ordering::Relaxed);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_packing() {
        let geometries = vec![
            Geometry3D::new("B1", 20.0, 20.0, 20.0).with_quantity(3),
            Geometry3D::new("B2", 15.0, 15.0, 15.0).with_quantity(2),
        ];

        let boundary = Boundary3D::new(100.0, 80.0, 50.0);
        let packer = Packer3D::default_config();

        let result = packer.solve(&geometries, &boundary).unwrap();

        assert!(result.utilization > 0.0);
        assert!(result.placements.len() <= 5);
    }

    #[test]
    fn test_mass_constraint() {
        let geometries = vec![Geometry3D::new("B1", 20.0, 20.0, 20.0)
            .with_quantity(10)
            .with_mass(100.0)];

        let boundary = Boundary3D::new(100.0, 80.0, 50.0).with_max_mass(350.0);

        let packer = Packer3D::default_config();
        let result = packer.solve(&geometries, &boundary).unwrap();

        // Should only place 3 boxes (300 mass) due to 350 mass limit
        assert!(result.placements.len() <= 3);
    }

    #[test]
    fn test_placement_within_bounds() {
        let geometries = vec![Geometry3D::new("B1", 10.0, 10.0, 10.0).with_quantity(4)];

        let boundary = Boundary3D::new(50.0, 50.0, 50.0);
        let config = Config::default().with_margin(5.0).with_spacing(2.0);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // All boxes should be placed
        assert_eq!(result.placements.len(), 4);
        assert!(result.unplaced.is_empty());

        // Verify placements are within bounds (with margin)
        for p in &result.placements {
            assert!(p.position[0] >= 5.0);
            assert!(p.position[1] >= 5.0);
            assert!(p.position[2] >= 5.0);
        }
    }

    #[test]
    fn test_ga_strategy_basic() {
        let geometries = vec![
            Geometry3D::new("B1", 20.0, 20.0, 20.0).with_quantity(2),
            Geometry3D::new("B2", 15.0, 15.0, 15.0).with_quantity(2),
        ];

        let boundary = Boundary3D::new(100.0, 80.0, 50.0);
        let config = Config::default().with_strategy(Strategy::GeneticAlgorithm);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // GA should place items and achieve positive utilization
        assert!(result.utilization > 0.0);
        assert!(!result.placements.is_empty());
    }

    #[test]
    fn test_ga_strategy_all_placed() {
        // Small number of boxes that should all fit
        let geometries = vec![Geometry3D::new("B1", 10.0, 10.0, 10.0).with_quantity(4)];

        let boundary = Boundary3D::new(100.0, 100.0, 100.0);
        let config = Config::default().with_strategy(Strategy::GeneticAlgorithm);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // All 4 boxes should be placed
        assert_eq!(result.placements.len(), 4);
        assert!(result.unplaced.is_empty());
    }

    #[test]
    fn test_ga_strategy_with_orientations() {
        use crate::geometry::OrientationConstraint;

        // Box that fits better when rotated
        let geometries = vec![Geometry3D::new("B1", 50.0, 10.0, 10.0)
            .with_quantity(2)
            .with_orientation(OrientationConstraint::Any)];

        // Container where orientation matters
        let boundary = Boundary3D::new(60.0, 60.0, 60.0);
        let config = Config::default().with_strategy(Strategy::GeneticAlgorithm);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // GA should find a way to place both boxes
        assert_eq!(result.placements.len(), 2);
    }

    #[test]
    fn test_brkga_strategy_basic() {
        let geometries = vec![
            Geometry3D::new("B1", 20.0, 20.0, 20.0).with_quantity(2),
            Geometry3D::new("B2", 15.0, 15.0, 15.0).with_quantity(2),
        ];

        let boundary = Boundary3D::new(100.0, 80.0, 50.0);
        let config = Config::default().with_strategy(Strategy::Brkga);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // BRKGA should place items and achieve positive utilization
        assert!(result.utilization > 0.0);
        assert!(!result.placements.is_empty());
        assert_eq!(result.strategy, Some("BRKGA".to_string()));
    }

    #[test]
    fn test_brkga_strategy_all_placed() {
        // Small number of boxes that should all fit
        let geometries = vec![Geometry3D::new("B1", 10.0, 10.0, 10.0).with_quantity(4)];

        let boundary = Boundary3D::new(100.0, 100.0, 100.0);
        let config = Config::default().with_strategy(Strategy::Brkga);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // All 4 boxes should be placed
        assert_eq!(result.placements.len(), 4);
        assert!(result.unplaced.is_empty());
    }

    #[test]
    fn test_ep_strategy_basic() {
        let geometries = vec![
            Geometry3D::new("B1", 20.0, 20.0, 20.0).with_quantity(2),
            Geometry3D::new("B2", 15.0, 15.0, 15.0).with_quantity(2),
        ];

        let boundary = Boundary3D::new(100.0, 80.0, 50.0);
        let config = Config::default().with_strategy(Strategy::ExtremePoint);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // EP should place items and achieve positive utilization
        assert!(result.utilization > 0.0);
        assert!(!result.placements.is_empty());
        assert_eq!(result.strategy, Some("ExtremePoint".to_string()));
    }

    #[test]
    fn test_ep_strategy_all_placed() {
        // Small number of boxes that should all fit
        let geometries = vec![Geometry3D::new("B1", 10.0, 10.0, 10.0).with_quantity(4)];

        let boundary = Boundary3D::new(100.0, 100.0, 100.0);
        let config = Config::default().with_strategy(Strategy::ExtremePoint);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // All 4 boxes should be placed
        assert_eq!(result.placements.len(), 4);
        assert!(result.unplaced.is_empty());
    }

    #[test]
    fn test_ep_strategy_with_margin() {
        let geometries = vec![Geometry3D::new("B1", 20.0, 20.0, 20.0).with_quantity(4)];

        let boundary = Boundary3D::new(100.0, 100.0, 100.0);
        let config = Config::default()
            .with_strategy(Strategy::ExtremePoint)
            .with_margin(5.0);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // Verify placements start at margin
        for p in &result.placements {
            assert!(p.position[0] >= 4.9);
            assert!(p.position[1] >= 4.9);
            assert!(p.position[2] >= 4.9);
        }
    }

    #[test]
    fn test_ep_strategy_with_orientations() {
        use crate::geometry::OrientationConstraint;

        // Long box that benefits from rotation
        let geometries = vec![Geometry3D::new("B1", 80.0, 10.0, 10.0)
            .with_quantity(2)
            .with_orientation(OrientationConstraint::Any)];

        let boundary = Boundary3D::new(100.0, 100.0, 100.0);
        let config = Config::default().with_strategy(Strategy::ExtremePoint);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // EP should find a way to place both boxes
        assert_eq!(result.placements.len(), 2);
    }

    #[test]
    fn test_layer_packing_orientation_optimization() {
        use crate::geometry::OrientationConstraint;

        // A box 50x10x10 that won't fit in 45 width without rotation
        // But at orientation (1,0,2) it becomes 10x50x10, width=10, which fits
        let geometries = vec![Geometry3D::new("B1", 50.0, 10.0, 10.0)
            .with_quantity(2)
            .with_orientation(OrientationConstraint::Any)];

        // Narrow container: width=45, depth=80, height=80
        let boundary = Boundary3D::new(45.0, 80.0, 80.0);
        let config = Config::default().with_strategy(Strategy::BottomLeftFill);
        let packer = Packer3D::new(config);

        let result = packer.solve(&geometries, &boundary).unwrap();

        // Both boxes should be placed via orientation change
        assert_eq!(
            result.placements.len(),
            2,
            "Both boxes should be placed by using rotation"
        );
        assert!(result.unplaced.is_empty());

        // Verify orientation index is set for placements
        for p in &result.placements {
            assert!(
                p.rotation_index.is_some(),
                "Placement should have rotation_index set"
            );
        }
    }

    #[test]
    fn test_layer_packing_selects_best_orientation() {
        use crate::geometry::OrientationConstraint;

        // Box 30x20x10 in container 35x50x100
        // Original orientation (30x20x10): fits in row, leaves 5 spare width
        // Rotated (20x30x10): fits but uses more depth
        // Best: original orientation to minimize vertical space usage
        let geometries = vec![Geometry3D::new("B1", 30.0, 20.0, 10.0)
            .with_quantity(1)
            .with_orientation(OrientationConstraint::Any)];

        let boundary = Boundary3D::new(35.0, 50.0, 100.0);
        let packer = Packer3D::default_config();

        let result = packer.solve(&geometries, &boundary).unwrap();

        assert_eq!(result.placements.len(), 1);
        assert!(result.unplaced.is_empty());
    }
}