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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
//! 2D nesting solver.
use crate::alns_nesting::run_alns_nesting;
use crate::boundary::Boundary2D;
use crate::brkga_nesting::run_brkga_nesting;
use crate::clamp_placement_to_boundary_with_margin;
use crate::ga_nesting::{run_ga_nesting, run_ga_nesting_with_progress};
use crate::gdrr_nesting::run_gdrr_nesting;
use crate::geometry::Geometry2D;
#[cfg(feature = "milp")]
use crate::milp_solver::run_milp_nesting;
use crate::nfp::{
compute_ifp_with_margin, compute_nfp, find_bottom_left_placement, rotate_nfp, translate_nfp,
Nfp, NfpCache, PlacedGeometry,
};
#[cfg(feature = "milp")]
#[allow(unused_imports)]
use crate::nfp_cm_solver::run_nfp_cm_nesting;
use crate::sa_nesting::run_sa_nesting;
use crate::validate_and_filter_placements;
use u_nesting_core::alns::AlnsConfig;
use u_nesting_core::brkga::BrkgaConfig;
#[cfg(feature = "milp")]
use u_nesting_core::exact::ExactConfig;
use u_nesting_core::ga::GaConfig;
use u_nesting_core::gdrr::GdrrConfig;
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 crate::placement_utils::{expand_nfp, shrink_ifp};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use u_nesting_core::timing::Timer;
/// 2D nesting solver.
pub struct Nester2D {
config: Config,
cancelled: Arc<AtomicBool>,
#[allow(dead_code)] // Will be used for caching in future optimization
nfp_cache: NfpCache,
}
impl Nester2D {
/// Creates a new nester with the given configuration.
pub fn new(config: Config) -> Self {
Self {
config,
cancelled: Arc::new(AtomicBool::new(false)),
nfp_cache: NfpCache::new(),
}
}
/// Creates a nester with default configuration.
pub fn default_config() -> Self {
Self::new(Config::default())
}
/// Bottom-Left Fill algorithm implementation with rotation optimization.
fn bottom_left_fill(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
let start = Timer::now();
let mut result = SolveResult::new();
let mut placements = Vec::new();
// Get boundary dimensions
let (b_min, b_max) = boundary.aabb();
let margin = self.config.margin;
let spacing = self.config.spacing;
let bound_min_x = b_min[0] + margin;
let bound_min_y = b_min[1] + margin;
let bound_max_x = b_max[0] - margin;
let bound_max_y = b_max[1] - margin;
let strip_width = bound_max_x - bound_min_x;
let strip_height = bound_max_y - bound_min_y;
// Simple row-based placement with rotation optimization
let mut current_x = bound_min_x;
let mut current_y = bound_min_y;
let mut row_height = 0.0_f64;
let mut total_placed_area = 0.0;
for geom in geometries {
geom.validate()?;
// Get allowed rotation angles (default to 0 if none specified)
let rotations = geom.rotations();
let rotation_angles: Vec<f64> = if rotations.is_empty() {
vec![0.0]
} else {
rotations
};
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_area / boundary.measure();
result.computation_time_ms = start.elapsed_ms();
result.placements = placements;
return Ok(result);
}
// Find the best rotation for current position
let mut best_fit: Option<(f64, f64, f64, f64, f64, [f64; 2])> = None; // (rotation, width, height, x, y, g_min)
for &rotation in &rotation_angles {
let (g_min, g_max) = geom.aabb_at_rotation(rotation);
let g_width = g_max[0] - g_min[0];
let g_height = g_max[1] - g_min[1];
// Skip if geometry doesn't fit in boundary at all
if g_width > strip_width || g_height > strip_height {
continue;
}
// Calculate placement position for this rotation
let mut place_x = current_x;
let mut place_y = current_y;
// Check if piece fits in remaining row space
if place_x + g_width > bound_max_x {
// Would need to move to next row
place_x = bound_min_x;
place_y += row_height + spacing;
}
// Check if piece fits in boundary height
if place_y + g_height > bound_max_y {
continue; // This rotation doesn't fit
}
// Calculate score: prefer rotations that minimize wasted space
// Score = row advancement (lower is better)
let score = if place_x == bound_min_x && place_y > current_y {
// New row: score is based on new Y position
place_y - bound_min_y + g_height
} else {
// Same row: score is based on strip length advancement
place_x - bound_min_x + g_width
};
let is_better = match &best_fit {
None => true,
Some((_, _, _, _, _, _)) => {
// Prefer placements that don't start new rows
let best_score = if let Some((_, _, _, bx, by, _)) = best_fit {
if bx == bound_min_x && by > current_y {
by - bound_min_y + g_height
} else {
bx - bound_min_x + g_width
}
} else {
f64::INFINITY
};
score < best_score - 1e-6
}
};
if is_better {
best_fit = Some((rotation, g_width, g_height, place_x, place_y, g_min));
}
}
// Place the geometry with the best rotation
if let Some((rotation, g_width, g_height, place_x, place_y, g_min)) = best_fit {
// Update row tracking if we moved to a new row
if place_x == bound_min_x && place_y > current_y {
row_height = 0.0;
}
// Compute origin position from AABB position
let origin_x = place_x - g_min[0];
let origin_y = place_y - g_min[1];
// Clamp to ensure geometry stays within boundary
let geom_aabb = geom.aabb_at_rotation(rotation);
let boundary_aabb = (b_min, b_max);
if let Some((clamped_x, clamped_y)) = clamp_placement_to_boundary_with_margin(
origin_x,
origin_y,
geom_aabb,
boundary_aabb,
margin,
) {
let placement = Placement::new_2d(
geom.id().clone(),
instance,
clamped_x,
clamped_y,
rotation,
);
placements.push(placement);
total_placed_area += geom.measure();
// Update position for next piece
// Use actual clamped AABB position, not original place_x/place_y
let actual_place_x = clamped_x + g_min[0];
let actual_place_y = clamped_y + g_min[1];
current_x = actual_place_x + g_width + spacing;
current_y = actual_place_y;
row_height = row_height.max(g_height);
}
} else {
// Can't place this piece with any rotation
result.unplaced.push(geom.id().clone());
}
}
}
result.placements = placements;
result.boundaries_used = 1;
result.utilization = total_placed_area / boundary.measure();
result.computation_time_ms = start.elapsed_ms();
Ok(result)
}
/// NFP-guided Bottom-Left Fill algorithm.
///
/// Uses No-Fit Polygons to find optimal placement positions that minimize
/// wasted space while ensuring no overlaps.
fn nfp_guided_blf(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
let start = Timer::now();
let mut result = SolveResult::new();
let mut placements = Vec::new();
let mut placed_geometries: Vec<PlacedGeometry> = Vec::new();
let margin = self.config.margin;
let spacing = self.config.spacing;
// Get boundary polygon with margin applied
let boundary_polygon = self.get_boundary_polygon_with_margin(boundary, margin);
let mut total_placed_area = 0.0;
// Sampling step for grid search (adaptive based on geometry size)
let sample_step = self.compute_sample_step(geometries);
for geom in geometries {
geom.validate()?;
// Get allowed rotation angles
let rotations = geom.rotations();
let rotation_angles: Vec<f64> = if rotations.is_empty() {
vec![0.0]
} else {
rotations
};
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_area / boundary.measure();
result.computation_time_ms = start.elapsed_ms();
result.placements = placements;
return Ok(result);
}
// Try each rotation angle to find the best placement
let mut best_placement: Option<(f64, f64, f64)> = None; // (x, y, rotation)
for &rotation in &rotation_angles {
// Compute IFP for this geometry at this rotation (with margin from boundary)
let ifp =
match compute_ifp_with_margin(&boundary_polygon, geom, rotation, margin) {
Ok(ifp) => ifp,
Err(_) => continue,
};
if ifp.is_empty() {
continue;
}
// Compute NFPs with all placed geometries (using cache)
let mut nfps: Vec<Nfp> = Vec::new();
for placed in &placed_geometries {
// Use cache for NFP computation (between original geometries at origin)
// Key: (placed_geometry_id, current_geometry_id, rotation)
let cache_key = (
placed.geometry.id().as_str(),
geom.id().as_str(),
rotation - placed.rotation, // Relative rotation
);
// Compute NFP at origin and cache it (with relative rotation)
// NFP is computed between the placed geometry at origin (no rotation)
// and the new geometry with relative rotation applied.
// Formula: NFP_actual = translate(rotate(NFP_relative, placed.rotation), placed.position)
let nfp_at_origin = match self.nfp_cache.get_or_compute(cache_key, || {
let placed_at_origin = placed.geometry.clone();
compute_nfp(&placed_at_origin, geom, rotation - placed.rotation)
}) {
Ok(nfp) => nfp,
Err(_) => continue,
};
// Transform NFP: first rotate by placed.rotation, then translate to placed.position
// This correctly accounts for the placed geometry's actual orientation
let rotated_nfp = rotate_nfp(&nfp_at_origin, placed.rotation);
let translated_nfp = translate_nfp(&rotated_nfp, placed.position);
let expanded = self.expand_nfp(&translated_nfp, spacing);
nfps.push(expanded);
}
// Shrink IFP by spacing from boundary
let ifp_shrunk = self.shrink_ifp(&ifp, spacing);
// Find the optimal valid placement (minimize X for shorter strip)
let nfp_refs: Vec<&Nfp> = nfps.iter().collect();
if let Some((x, y)) =
find_bottom_left_placement(&ifp_shrunk, &nfp_refs, sample_step)
{
// Compare with current best: prefer smaller X (shorter strip), then smaller Y
let is_better = match best_placement {
None => true,
Some((best_x, best_y, _)) => {
x < best_x - 1e-6 || (x < best_x + 1e-6 && y < best_y - 1e-6)
}
};
if is_better {
best_placement = Some((x, y, rotation));
}
}
}
// Place the geometry at the best position found
if let Some((x, y, rotation)) = best_placement {
// Clamp to ensure geometry stays within boundary
let geom_aabb = geom.aabb_at_rotation(rotation);
let boundary_aabb = boundary.aabb();
if let Some((clamped_x, clamped_y)) = clamp_placement_to_boundary_with_margin(
x,
y,
geom_aabb,
boundary_aabb,
margin,
) {
let placement = Placement::new_2d(
geom.id().clone(),
instance,
clamped_x,
clamped_y,
rotation,
);
placements.push(placement);
placed_geometries.push(PlacedGeometry::new(
geom.clone(),
(clamped_x, clamped_y),
rotation,
));
total_placed_area += geom.measure();
} else {
// Could not place - geometry doesn't fit
result.unplaced.push(geom.id().clone());
}
} else {
// Could not place this instance
result.unplaced.push(geom.id().clone());
}
}
}
result.placements = placements;
result.boundaries_used = 1;
result.utilization = total_placed_area / boundary.measure();
result.computation_time_ms = start.elapsed_ms();
Ok(result)
}
/// Gets the boundary polygon with margin applied.
fn get_boundary_polygon_with_margin(
&self,
boundary: &Boundary2D,
margin: f64,
) -> Vec<(f64, f64)> {
let (b_min, b_max) = boundary.aabb();
// Create a rectangular boundary polygon with margin
vec![
(b_min[0] + margin, b_min[1] + margin),
(b_max[0] - margin, b_min[1] + margin),
(b_max[0] - margin, b_max[1] - margin),
(b_min[0] + margin, b_max[1] - margin),
]
}
/// Computes an adaptive sample step based on geometry sizes.
fn compute_sample_step(&self, geometries: &[Geometry2D]) -> f64 {
if geometries.is_empty() {
return 1.0;
}
// Use the smallest geometry dimension divided by 4 as sample step
let mut min_dim = f64::INFINITY;
for geom in geometries {
let (g_min, g_max) = geom.aabb();
let width = g_max[0] - g_min[0];
let height = g_max[1] - g_min[1];
min_dim = min_dim.min(width).min(height);
}
// Clamp sample step to reasonable range
(min_dim / 4.0).clamp(0.5, 10.0)
}
/// Expands an NFP by the given spacing amount.
fn expand_nfp(&self, nfp: &Nfp, spacing: f64) -> Nfp {
expand_nfp(nfp, spacing)
}
/// Shrinks an IFP by the given spacing amount.
fn shrink_ifp(&self, ifp: &Nfp, spacing: f64) -> Nfp {
shrink_ifp(ifp, spacing)
}
/// Genetic Algorithm based nesting optimization.
///
/// Uses GA to optimize placement order and rotations, with NFP-guided
/// decoding for collision-free placements.
fn genetic_algorithm(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
// Configure GA with time limit for multi-strip scenarios
let time_limit_ms = if self.config.time_limit_ms > 0 {
// Use 1/4 of total time limit per strip to allow for multiple strips
// Budget a quarter of the total per strip (assuming up to ~4 strips), but
// never exceed the user's total limit: a single-strip solve must honor an
// explicit short budget instead of being floored up to 5s.
(self.config.time_limit_ms / 4)
.max(5000)
.min(self.config.time_limit_ms)
} else {
15000 // 15 seconds default per strip
};
let ga_config = GaConfig::default()
.with_population_size(self.config.population_size.min(30)) // Limit population
.with_max_generations(self.config.max_generations.min(50)) // Limit generations
.with_crossover_rate(self.config.crossover_rate)
.with_mutation_rate(self.config.mutation_rate)
.with_time_limit(std::time::Duration::from_millis(time_limit_ms));
let result = run_ga_nesting(
geometries,
boundary,
&self.config,
ga_config,
self.cancelled.clone(),
);
Ok(result)
}
/// BRKGA (Biased Random-Key Genetic Algorithm) based nesting optimization.
///
/// Uses random-key encoding and biased crossover for robust optimization.
fn brkga(&self, geometries: &[Geometry2D], boundary: &Boundary2D) -> Result<SolveResult<f64>> {
// Configure BRKGA with time limit for multi-strip scenarios
let time_limit_ms = if self.config.time_limit_ms > 0 {
// Use 1/4 of total time limit per strip to allow for multiple strips
// Budget a quarter of the total per strip (assuming up to ~4 strips), but
// never exceed the user's total limit: a single-strip solve must honor an
// explicit short budget instead of being floored up to 5s.
(self.config.time_limit_ms / 4)
.max(5000)
.min(self.config.time_limit_ms)
} else {
15000 // 15 seconds default per strip
};
let brkga_config = BrkgaConfig::default()
.with_population_size(30) // Smaller population for speed
.with_max_generations(50) // Fewer generations
.with_elite_fraction(0.2)
.with_mutant_fraction(0.15)
.with_elite_bias(0.7)
.with_time_limit(std::time::Duration::from_millis(time_limit_ms));
let result = run_brkga_nesting(
geometries,
boundary,
&self.config,
brkga_config,
self.cancelled.clone(),
);
Ok(result)
}
/// Simulated Annealing based nesting optimization.
///
/// Uses neighborhood operators to explore solution space with temperature-based
/// acceptance probability.
fn simulated_annealing(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
// Configure SA with faster defaults for multi-strip scenarios
// Note: Each decode() call is O(N²) NFP computations, so we need fewer iterations
let time_limit_ms = if self.config.time_limit_ms > 0 {
// Use 1/4 of total time limit per strip to allow for multiple strips
// Budget a quarter of the total per strip (assuming up to ~4 strips), but
// never exceed the user's total limit: a single-strip solve must honor an
// explicit short budget instead of being floored up to 5s.
(self.config.time_limit_ms / 4)
.max(5000)
.min(self.config.time_limit_ms)
} else {
10000 // 10 seconds default per strip
};
let sa_config = SaConfig::default()
.with_initial_temp(50.0) // Lower initial temp for faster convergence
.with_final_temp(1.0) // Higher final temp to finish faster
.with_cooling_rate(0.9) // Faster cooling (was 0.95)
.with_iterations_per_temp(20) // Fewer iterations per temp (was 50)
.with_max_iterations(500) // Much fewer max iterations (was 10000)
.with_time_limit(std::time::Duration::from_millis(time_limit_ms));
let result = run_sa_nesting(
geometries,
boundary,
&self.config,
sa_config,
self.cancelled.clone(),
);
Ok(result)
}
/// Goal-Driven Ruin and Recreate (GDRR) optimization.
fn gdrr(&self, geometries: &[Geometry2D], boundary: &Boundary2D) -> Result<SolveResult<f64>> {
// Configure GDRR with faster defaults for multi-strip scenarios
// Use user's time limit, default to 10s per strip if not specified
let time_limit = if self.config.time_limit_ms > 0 {
// Use 1/4 of total time limit per strip to allow for multiple strips
// Budget a quarter of the total per strip (assuming up to ~4 strips), but
// never exceed the user's total limit: a single-strip solve must honor an
// explicit short budget instead of being floored up to 5s.
(self.config.time_limit_ms / 4)
.max(5000)
.min(self.config.time_limit_ms)
} else {
10000 // 10 seconds default per strip
};
let gdrr_config = GdrrConfig::default()
.with_max_iterations(1000) // Reduced from 5000 for faster execution
.with_time_limit_ms(time_limit)
.with_ruin_ratio(0.1, 0.3) // Smaller ruin ratio for faster convergence
.with_lahc_list_length(30); // Smaller list for faster convergence
let result = run_gdrr_nesting(
geometries,
boundary,
&self.config,
&gdrr_config,
self.cancelled.clone(),
);
Ok(result)
}
/// Adaptive Large Neighborhood Search (ALNS) optimization.
fn alns(&self, geometries: &[Geometry2D], boundary: &Boundary2D) -> Result<SolveResult<f64>> {
// Configure ALNS with faster defaults for multi-strip scenarios
// Use user's time limit, default to 10s per strip if not specified
let time_limit = if self.config.time_limit_ms > 0 {
// Use 1/4 of total time limit per strip to allow for multiple strips
// Budget a quarter of the total per strip (assuming up to ~4 strips), but
// never exceed the user's total limit: a single-strip solve must honor an
// explicit short budget instead of being floored up to 5s.
(self.config.time_limit_ms / 4)
.max(5000)
.min(self.config.time_limit_ms)
} else {
10000 // 10 seconds default per strip
};
let alns_config = AlnsConfig::default()
.with_max_iterations(1000) // Reduced from 5000 for faster execution
.with_time_limit_ms(time_limit)
.with_segment_size(50) // Smaller segments for faster adaptation
.with_scores(33.0, 9.0, 13.0)
.with_reaction_factor(0.15) // Slightly higher for faster adaptation
.with_temperature(100.0, 0.999, 0.1); // Faster cooling
let result = run_alns_nesting(
geometries,
boundary,
&self.config,
&alns_config,
self.cancelled.clone(),
);
Ok(result)
}
/// MILP-based exact solver.
#[cfg(feature = "milp")]
fn milp_exact(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
let exact_config = ExactConfig::default()
.with_time_limit_ms(self.config.time_limit_ms.max(60000))
.with_max_items(15)
.with_rotation_steps(4)
.with_grid_step(1.0);
let result = run_milp_nesting(
geometries,
boundary,
&self.config,
&exact_config,
self.cancelled.clone(),
);
Ok(result)
}
/// Hybrid exact solver: try MILP first, fallback to heuristic.
#[cfg(feature = "milp")]
fn hybrid_exact(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
// Count total instances
let total_instances: usize = geometries.iter().map(|g| g.quantity()).sum();
// If small enough, try exact
if total_instances <= 15 {
let exact_config = ExactConfig::default()
.with_time_limit_ms((self.config.time_limit_ms / 2).max(30000))
.with_max_items(15);
let exact_result = run_milp_nesting(
geometries,
boundary,
&self.config,
&exact_config,
self.cancelled.clone(),
);
// If got a good solution, return it
if !exact_result.placements.is_empty() {
return Ok(exact_result);
}
}
// Fallback to ALNS (best heuristic)
self.alns(geometries, boundary)
}
/// Bottom-Left Fill with progress callback.
fn bottom_left_fill_with_progress(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
callback: &ProgressCallback,
) -> Result<SolveResult<f64>> {
let start = Timer::now();
let mut result = SolveResult::new();
let mut placements = Vec::new();
// Get boundary dimensions
let (b_min, b_max) = boundary.aabb();
let margin = self.config.margin;
let spacing = self.config.spacing;
let bound_min_x = b_min[0] + margin;
let bound_min_y = b_min[1] + margin;
let bound_max_x = b_max[0] - margin;
let bound_max_y = b_max[1] - margin;
let strip_width = bound_max_x - bound_min_x;
let strip_height = bound_max_y - bound_min_y;
let mut current_x = bound_min_x;
let mut current_y = bound_min_y;
let mut row_height = 0.0_f64;
let mut total_placed_area = 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("BLF Placement")
.with_items(0, total_pieces)
.with_elapsed(0),
);
for geom in geometries {
geom.validate()?;
let rotations = geom.rotations();
let rotation_angles: Vec<f64> = if rotations.is_empty() {
vec![0.0]
} else {
rotations
};
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_area / 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);
}
let mut best_fit: Option<(f64, f64, f64, f64, f64, [f64; 2])> = None;
for &rotation in &rotation_angles {
let (g_min, g_max) = geom.aabb_at_rotation(rotation);
let g_width = g_max[0] - g_min[0];
let g_height = g_max[1] - g_min[1];
if g_width > strip_width || g_height > strip_height {
continue;
}
let mut place_x = current_x;
let mut place_y = current_y;
if place_x + g_width > bound_max_x {
place_x = bound_min_x;
place_y += row_height + spacing;
}
if place_y + g_height > bound_max_y {
continue;
}
let score = if place_x == bound_min_x && place_y > current_y {
place_y - bound_min_y + g_height
} else {
place_x - bound_min_x + g_width
};
let is_better = match &best_fit {
None => true,
Some((_, _, _, bx, by, _)) => {
let best_score = if *bx == bound_min_x && *by > current_y {
by - bound_min_y
} else {
bx - bound_min_x
};
score < best_score - 1e-6
}
};
if is_better {
best_fit = Some((rotation, g_width, g_height, place_x, place_y, g_min));
}
}
if let Some((rotation, g_width, g_height, place_x, place_y, g_min)) = best_fit {
if place_x == bound_min_x && place_y > current_y {
row_height = 0.0;
}
// Compute origin position from AABB position
let origin_x = place_x - g_min[0];
let origin_y = place_y - g_min[1];
// Clamp to ensure geometry stays within boundary
let geom_aabb = geom.aabb_at_rotation(rotation);
let boundary_aabb = (b_min, b_max);
if let Some((clamped_x, clamped_y)) = clamp_placement_to_boundary_with_margin(
origin_x,
origin_y,
geom_aabb,
boundary_aabb,
margin,
) {
let placement = Placement::new_2d(
geom.id().clone(),
instance,
clamped_x,
clamped_y,
rotation,
);
placements.push(placement);
total_placed_area += geom.measure();
placed_count += 1;
current_x = place_x + g_width + spacing;
current_y = place_y;
row_height = row_height.max(g_height);
// Progress callback every piece
callback(
ProgressInfo::new()
.with_phase("BLF Placement")
.with_items(placed_count, total_pieces)
.with_utilization(total_placed_area / boundary.measure())
.with_elapsed(start.elapsed_ms()),
);
} else {
result.unplaced.push(geom.id().clone());
}
} else {
result.unplaced.push(geom.id().clone());
}
}
}
result.placements = placements;
result.boundaries_used = 1;
result.utilization = total_placed_area / 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)
}
/// NFP-guided BLF with progress callback.
fn nfp_guided_blf_with_progress(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
callback: &ProgressCallback,
) -> Result<SolveResult<f64>> {
let start = Timer::now();
let mut result = SolveResult::new();
let mut placements = Vec::new();
let mut placed_geometries: Vec<PlacedGeometry> = Vec::new();
let margin = self.config.margin;
let spacing = self.config.spacing;
let boundary_polygon = self.get_boundary_polygon_with_margin(boundary, margin);
let mut total_placed_area = 0.0;
let sample_step = self.compute_sample_step(geometries);
// 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("NFP Placement")
.with_items(0, total_pieces)
.with_elapsed(0),
);
for geom in geometries {
geom.validate()?;
let rotations = geom.rotations();
let rotation_angles: Vec<f64> = if rotations.is_empty() {
vec![0.0]
} else {
rotations
};
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_area / 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);
}
let mut best_placement: Option<(f64, f64, f64)> = None;
for &rotation in &rotation_angles {
let ifp =
match compute_ifp_with_margin(&boundary_polygon, geom, rotation, margin) {
Ok(ifp) => ifp,
Err(_) => continue,
};
if ifp.is_empty() {
continue;
}
let mut nfps: Vec<Nfp> = Vec::new();
for placed in &placed_geometries {
// Use cache for NFP computation
let cache_key = (
placed.geometry.id().as_str(),
geom.id().as_str(),
rotation - placed.rotation,
);
// Compute NFP at origin and cache it (with relative rotation)
// Formula: NFP_actual = translate(rotate(NFP_relative, placed.rotation), placed.position)
let nfp_at_origin = match self.nfp_cache.get_or_compute(cache_key, || {
let placed_at_origin = placed.geometry.clone();
compute_nfp(&placed_at_origin, geom, rotation - placed.rotation)
}) {
Ok(nfp) => nfp,
Err(_) => continue,
};
// Transform NFP: first rotate by placed.rotation, then translate
let rotated_nfp = rotate_nfp(&nfp_at_origin, placed.rotation);
let translated_nfp = translate_nfp(&rotated_nfp, placed.position);
let expanded = self.expand_nfp(&translated_nfp, spacing);
nfps.push(expanded);
}
let ifp_shrunk = self.shrink_ifp(&ifp, spacing);
let nfp_refs: Vec<&Nfp> = nfps.iter().collect();
if let Some((x, y)) =
find_bottom_left_placement(&ifp_shrunk, &nfp_refs, sample_step)
{
let is_better = match best_placement {
None => true,
Some((best_x, best_y, _)) => {
x < best_x - 1e-6 || (x < best_x + 1e-6 && y < best_y - 1e-6)
}
};
if is_better {
best_placement = Some((x, y, rotation));
}
}
}
if let Some((x, y, rotation)) = best_placement {
// Clamp to ensure geometry stays within boundary
let geom_aabb = geom.aabb_at_rotation(rotation);
let boundary_aabb = boundary.aabb();
if let Some((clamped_x, clamped_y)) = clamp_placement_to_boundary_with_margin(
x,
y,
geom_aabb,
boundary_aabb,
margin,
) {
let placement = Placement::new_2d(
geom.id().clone(),
instance,
clamped_x,
clamped_y,
rotation,
);
placements.push(placement);
placed_geometries.push(PlacedGeometry::new(
geom.clone(),
(clamped_x, clamped_y),
rotation,
));
total_placed_area += geom.measure();
placed_count += 1;
// Progress callback every piece
callback(
ProgressInfo::new()
.with_phase("NFP Placement")
.with_items(placed_count, total_pieces)
.with_utilization(total_placed_area / boundary.measure())
.with_elapsed(start.elapsed_ms()),
);
} else {
result.unplaced.push(geom.id().clone());
}
} else {
result.unplaced.push(geom.id().clone());
}
}
}
result.placements = placements;
result.boundaries_used = 1;
result.utilization = total_placed_area / 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)
}
/// Solves nesting with automatic multi-strip support.
///
/// When items don't fit in a single strip, automatically creates additional strips.
/// Each placement's `boundary_index` indicates which strip it belongs to.
/// Positions are adjusted so that strip N items have x offset of N * strip_width.
pub fn solve_multi_strip(
&self,
geometries: &[Geometry2D],
boundary: &Boundary2D,
) -> Result<SolveResult<f64>> {
boundary.validate()?;
self.cancelled.store(false, Ordering::Relaxed);
let (b_min, b_max) = boundary.aabb();
let strip_width = b_max[0] - b_min[0];
let mut final_result = SolveResult::new();
let mut remaining_geometries: Vec<Geometry2D> = geometries.to_vec();
let mut strip_index = 0;
let max_strips = 100; // Safety limit
while !remaining_geometries.is_empty() && strip_index < max_strips {
if self.cancelled.load(Ordering::Relaxed) {
break;
}
// Solve on current strip
let strip_result = match self.config.strategy {
Strategy::BottomLeftFill => self.bottom_left_fill(&remaining_geometries, boundary),
Strategy::NfpGuided => self.nfp_guided_blf(&remaining_geometries, boundary),
Strategy::GeneticAlgorithm => {
self.genetic_algorithm(&remaining_geometries, boundary)
}
Strategy::Brkga => self.brkga(&remaining_geometries, boundary),
Strategy::SimulatedAnnealing => {
self.simulated_annealing(&remaining_geometries, boundary)
}
Strategy::Gdrr => self.gdrr(&remaining_geometries, boundary),
Strategy::Alns => self.alns(&remaining_geometries, boundary),
#[cfg(feature = "milp")]
Strategy::MilpExact => self.milp_exact(&remaining_geometries, boundary),
#[cfg(feature = "milp")]
Strategy::HybridExact => self.hybrid_exact(&remaining_geometries, boundary),
_ => self.nfp_guided_blf(&remaining_geometries, boundary),
}?;
// Validate and filter out-of-bounds placements for this strip
let strip_result =
validate_and_filter_placements(strip_result, &remaining_geometries, boundary);
if strip_result.placements.is_empty() {
// No progress - items too large for strip
final_result.unplaced.extend(strip_result.unplaced);
break;
}
// Collect placed geometry IDs
let placed_ids: std::collections::HashSet<_> = strip_result
.placements
.iter()
.map(|p| p.geometry_id.clone())
.collect();
// Adjust placements for this strip and add to final result
for mut placement in strip_result.placements {
// Offset x position by strip_index * strip_width
if !placement.position.is_empty() {
placement.position[0] += strip_index as f64 * strip_width;
}
placement.boundary_index = strip_index;
final_result.placements.push(placement);
}
// Update remaining geometries (those not placed)
remaining_geometries.retain(|g| !placed_ids.contains(g.id()));
// Also handle quantity > 1: reduce quantity for partially placed items
// For now, we treat each geometry independently
strip_index += 1;
}
final_result.boundaries_used = strip_index;
final_result.deduplicate_unplaced();
// Calculate per-strip statistics for accurate utilization
let (b_min, b_max) = boundary.aabb();
let strip_height = b_max[1] - b_min[1]; // Height of each strip
// Group placements by strip and calculate stats
let mut strip_stats_map: std::collections::HashMap<usize, (f64, f64, usize)> =
std::collections::HashMap::new(); // strip_index -> (max_x, piece_area, count)
for placement in &final_result.placements {
let strip_idx = placement.boundary_index;
// Get the geometry to calculate its area and right edge
if let Some(geom) = geometries.iter().find(|g| g.id() == &placement.geometry_id) {
use u_nesting_core::geometry::Geometry;
let piece_area = geom.measure();
let rotation = placement.rotation.first().copied().unwrap_or(0.0);
let (_g_min, g_max) = geom.aabb_at_rotation(rotation);
// Position is where geometry's origin is placed
// The actual right edge is position.x + g_max[0] (relative to origin)
let local_x = placement.position[0] - (strip_idx as f64 * strip_width);
let right_edge = local_x + g_max[0];
let entry = strip_stats_map.entry(strip_idx).or_insert((0.0, 0.0, 0));
entry.0 = entry.0.max(right_edge); // max_x (used_length)
entry.1 += piece_area; // total piece area
entry.2 += 1; // piece count
}
}
// Convert to StripStats vec
use u_nesting_core::result::StripStats;
let mut strip_stats: Vec<StripStats> = strip_stats_map
.into_iter()
.map(|(idx, (used_length, piece_area, count))| StripStats {
strip_index: idx,
used_length,
piece_area,
piece_count: count,
strip_width, // Width of boundary (X dimension)
strip_height, // Height of boundary (Y dimension, fixed)
})
.collect();
strip_stats.sort_by_key(|s| s.strip_index);
// Calculate accurate utilization
// Material used = strip_height (fixed dimension) × used_length (consumed length)
let total_piece_area: f64 = strip_stats.iter().map(|s| s.piece_area).sum();
let total_material_used: f64 = strip_stats
.iter()
.map(|s| s.strip_height * s.used_length)
.sum();
final_result.strip_stats = strip_stats;
final_result.total_piece_area = total_piece_area;
final_result.total_material_used = total_material_used;
if total_material_used > 0.0 {
final_result.utilization = total_piece_area / total_material_used;
}
Ok(final_result)
}
}
impl Solver for Nester2D {
type Geometry = Geometry2D;
type Boundary = Boundary2D;
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 initial_result = match self.config.strategy {
Strategy::BottomLeftFill => self.bottom_left_fill(geometries, boundary),
Strategy::NfpGuided => self.nfp_guided_blf(geometries, boundary),
Strategy::GeneticAlgorithm => self.genetic_algorithm(geometries, boundary),
Strategy::Brkga => self.brkga(geometries, boundary),
Strategy::SimulatedAnnealing => self.simulated_annealing(geometries, boundary),
Strategy::Gdrr => self.gdrr(geometries, boundary),
Strategy::Alns => self.alns(geometries, boundary),
#[cfg(feature = "milp")]
Strategy::MilpExact => self.milp_exact(geometries, boundary),
#[cfg(feature = "milp")]
Strategy::HybridExact => self.hybrid_exact(geometries, boundary),
_ => {
// Fall back to NFP-guided BLF for other strategies
log::warn!(
"Strategy {:?} not yet implemented, using NfpGuided",
self.config.strategy
);
self.nfp_guided_blf(geometries, boundary)
}
}?;
// Validate all placements and remove any that are outside the boundary
let mut result = validate_and_filter_placements(initial_result, 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 initial_result = match self.config.strategy {
Strategy::BottomLeftFill => {
self.bottom_left_fill_with_progress(geometries, boundary, &callback)?
}
Strategy::NfpGuided => {
self.nfp_guided_blf_with_progress(geometries, boundary, &callback)?
}
Strategy::GeneticAlgorithm => {
let mut 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);
// Apply time limit if specified
if self.config.time_limit_ms > 0 {
ga_config = ga_config.with_time_limit(std::time::Duration::from_millis(
self.config.time_limit_ms,
));
}
run_ga_nesting_with_progress(
geometries,
boundary,
&self.config,
ga_config,
self.cancelled.clone(),
callback,
)
}
// For other strategies, use basic progress reporting
_ => {
log::warn!(
"Strategy {:?} not yet implemented, using NfpGuided",
self.config.strategy
);
self.nfp_guided_blf_with_progress(geometries, boundary, &callback)?
}
};
// Validate all placements and remove any that are outside the boundary
let mut result = validate_and_filter_placements(initial_result, geometries, boundary);
// 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::*;
use crate::placement_utils::polygon_centroid;
#[test]
fn test_simple_nesting() {
let geometries = vec![
Geometry2D::rectangle("R1", 20.0, 10.0).with_quantity(3),
Geometry2D::rectangle("R2", 15.0, 15.0).with_quantity(2),
];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let nester = Nester2D::default_config();
let result = nester.solve(&geometries, &boundary).unwrap();
assert!(result.utilization > 0.0);
assert!(result.placements.len() <= 5); // 3 + 2 = 5 pieces
}
#[test]
fn test_placement_within_bounds() {
let geometries = vec![Geometry2D::rectangle("R1", 10.0, 10.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(50.0, 50.0);
let config = Config::default().with_margin(5.0).with_spacing(2.0);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// All pieces 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);
}
}
#[test]
fn test_nfp_guided_basic() {
let geometries = vec![
Geometry2D::rectangle("R1", 20.0, 10.0).with_quantity(2),
Geometry2D::rectangle("R2", 15.0, 15.0).with_quantity(1),
];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let config = Config::default().with_strategy(Strategy::NfpGuided);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
assert!(result.utilization > 0.0);
assert_eq!(result.placements.len(), 3); // 2 + 1 = 3 pieces
assert!(result.unplaced.is_empty());
}
#[test]
fn test_nfp_guided_with_spacing() {
let geometries = vec![Geometry2D::rectangle("R1", 10.0, 10.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(50.0, 50.0);
let config = Config::default()
.with_strategy(Strategy::NfpGuided)
.with_margin(2.0)
.with_spacing(3.0);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// All pieces should be placed
assert_eq!(result.placements.len(), 4);
assert!(result.unplaced.is_empty());
// Utilization should be positive
assert!(result.utilization > 0.0);
}
#[test]
fn test_nfp_guided_no_overlap() {
let geometries = vec![Geometry2D::rectangle("R1", 20.0, 20.0).with_quantity(3)];
let boundary = Boundary2D::rectangle(100.0, 100.0);
let config = Config::default().with_strategy(Strategy::NfpGuided);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
assert_eq!(result.placements.len(), 3);
// Verify no overlaps between placements
for i in 0..result.placements.len() {
for j in (i + 1)..result.placements.len() {
let p1 = &result.placements[i];
let p2 = &result.placements[j];
// Simple AABB overlap check for rectangles
let r1_min_x = p1.position[0];
let r1_max_x = p1.position[0] + 20.0;
let r1_min_y = p1.position[1];
let r1_max_y = p1.position[1] + 20.0;
let r2_min_x = p2.position[0];
let r2_max_x = p2.position[0] + 20.0;
let r2_min_y = p2.position[1];
let r2_max_y = p2.position[1] + 20.0;
// Check no overlap (with small tolerance for floating point)
let overlaps_x = r1_min_x < r2_max_x - 0.01 && r1_max_x > r2_min_x + 0.01;
let overlaps_y = r1_min_y < r2_max_y - 0.01 && r1_max_y > r2_min_y + 0.01;
assert!(
!(overlaps_x && overlaps_y),
"Placements {} and {} overlap",
i,
j
);
}
}
}
#[test]
fn test_nfp_guided_utilization() {
// Perfect fit: 4 rectangles of 25x25 in a 100x50 boundary
let geometries = vec![Geometry2D::rectangle("R1", 25.0, 25.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let config = Config::default().with_strategy(Strategy::NfpGuided);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// All pieces should be placed
assert_eq!(result.placements.len(), 4);
// Utilization should be 50% (4 * 625 = 2500 / 5000)
assert!(result.utilization > 0.45);
}
#[test]
fn test_polygon_centroid() {
// Test the centroid calculation
let square = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
let (cx, cy) = polygon_centroid(&square);
assert!((cx - 5.0).abs() < 0.01);
assert!((cy - 5.0).abs() < 0.01);
let triangle = vec![(0.0, 0.0), (6.0, 0.0), (3.0, 6.0)];
let (cx, cy) = polygon_centroid(&triangle);
assert!((cx - 3.0).abs() < 0.01);
assert!((cy - 2.0).abs() < 0.01);
}
#[test]
fn test_ga_strategy_basic() {
let geometries = vec![
Geometry2D::rectangle("R1", 20.0, 10.0).with_quantity(2),
Geometry2D::rectangle("R2", 15.0, 15.0).with_quantity(2),
];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let config = Config::default().with_strategy(Strategy::GeneticAlgorithm);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
assert!(result.utilization > 0.0);
assert!(!result.placements.is_empty());
// GA should report generations and fitness
assert!(result.generations.is_some());
assert!(result.best_fitness.is_some());
assert!(result.strategy == Some("GeneticAlgorithm".to_string()));
}
#[test]
fn test_ga_strategy_all_placed() {
// Easy case: 4 small rectangles in large boundary
let geometries = vec![Geometry2D::rectangle("R1", 20.0, 20.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(100.0, 100.0);
let config = Config::default().with_strategy(Strategy::GeneticAlgorithm);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// All 4 pieces should fit
assert_eq!(result.placements.len(), 4);
assert!(result.unplaced.is_empty());
}
#[test]
fn test_brkga_strategy_basic() {
let geometries = vec![
Geometry2D::rectangle("R1", 20.0, 10.0).with_quantity(2),
Geometry2D::rectangle("R2", 15.0, 15.0).with_quantity(2),
];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let config = Config::default().with_strategy(Strategy::Brkga);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
assert!(result.utilization > 0.0);
assert!(!result.placements.is_empty());
// BRKGA should report generations and fitness
assert!(result.generations.is_some());
assert!(result.best_fitness.is_some());
assert!(result.strategy == Some("BRKGA".to_string()));
}
#[test]
fn test_brkga_strategy_all_placed() {
// Easy case: 4 small rectangles in large boundary
let geometries = vec![Geometry2D::rectangle("R1", 20.0, 20.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(100.0, 100.0);
// Use longer time limit to ensure BRKGA converges on all platforms
let config = Config::default()
.with_strategy(Strategy::Brkga)
.with_time_limit(30000); // 30 seconds
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// BRKGA is stochastic; expect at least 3 of 4 pieces placed
// (4 x 20x20 = 1600 area in 10000 boundary = 16% utilization, easy case)
assert!(
result.placements.len() >= 3,
"Expected at least 3 placements, got {}",
result.placements.len()
);
}
#[test]
fn test_gdrr_strategy_basic() {
let geometries = vec![
Geometry2D::rectangle("R1", 20.0, 10.0).with_quantity(2),
Geometry2D::rectangle("R2", 15.0, 15.0).with_quantity(2),
];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let config = Config::default().with_strategy(Strategy::Gdrr);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
assert!(result.utilization > 0.0);
assert!(!result.placements.is_empty());
// GDRR should report iterations and fitness
assert!(result.iterations.is_some());
assert!(result.best_fitness.is_some());
assert!(result.strategy == Some("GDRR".to_string()));
}
#[test]
fn test_gdrr_strategy_all_placed() {
// Easy case: 4 small rectangles in large boundary
let geometries = vec![Geometry2D::rectangle("R1", 20.0, 20.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(100.0, 100.0);
let config = Config::default().with_strategy(Strategy::Gdrr);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// All 4 pieces should fit
assert_eq!(result.placements.len(), 4);
assert!(result.unplaced.is_empty());
}
#[test]
fn test_alns_strategy_basic() {
let geometries = vec![
Geometry2D::rectangle("R1", 20.0, 10.0).with_quantity(2),
Geometry2D::rectangle("R2", 15.0, 15.0).with_quantity(2),
];
let boundary = Boundary2D::rectangle(100.0, 50.0);
let config = Config::default().with_strategy(Strategy::Alns);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
assert!(result.utilization > 0.0);
assert!(!result.placements.is_empty());
// ALNS should report iterations and fitness
assert!(result.iterations.is_some());
assert!(result.best_fitness.is_some());
assert!(result.strategy == Some("ALNS".to_string()));
}
#[test]
fn test_alns_strategy_all_placed() {
// Easy case: 4 small rectangles in large boundary
let geometries = vec![Geometry2D::rectangle("R1", 20.0, 20.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(100.0, 100.0);
let config = Config::default().with_strategy(Strategy::Alns);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// All 4 pieces should fit
assert_eq!(result.placements.len(), 4);
assert!(result.unplaced.is_empty());
}
#[test]
fn test_blf_rotation_optimization() {
// Test that BLF uses rotation to optimize placement
// A 30x10 rectangle can fit better in a narrow strip when rotated 90 degrees
let geometries = vec![Geometry2D::rectangle("R1", 30.0, 10.0)
.with_rotations(vec![0.0, std::f64::consts::FRAC_PI_2]) // 0 and 90 degrees
.with_quantity(3)];
// Strip that's 35 wide: 30x10 won't fit two side-by-side at 0 deg
// But two 10x30 (rotated 90 deg) can fit vertically in 95 height
let boundary = Boundary2D::rectangle(35.0, 95.0);
let nester = Nester2D::default_config();
let result = nester.solve(&geometries, &boundary).unwrap();
// All 3 pieces should be placed (by rotating)
assert_eq!(
result.placements.len(),
3,
"All pieces should be placed with rotation optimization"
);
assert!(result.unplaced.is_empty());
}
#[test]
fn test_blf_selects_best_rotation() {
// Verify BLF selects optimal rotation, not just the first one
let geometries = vec![Geometry2D::rectangle("R1", 40.0, 10.0)
.with_rotations(vec![0.0, std::f64::consts::FRAC_PI_2]) // 0 and 90 degrees
.with_quantity(2)];
// In a 45x50 boundary:
// - At 0 deg: 40x10, only one fits horizontally (40 < 45), next row needed
// - At 90 deg: 10x40, two can fit side-by-side (10+10 < 45) in one row
let boundary = Boundary2D::rectangle(45.0, 50.0);
let nester = Nester2D::default_config();
let result = nester.solve(&geometries, &boundary).unwrap();
assert_eq!(result.placements.len(), 2);
assert!(result.unplaced.is_empty());
}
#[test]
fn test_progress_callback_blf() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
let geometries = vec![Geometry2D::rectangle("R1", 10.0, 10.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(50.0, 50.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let callback_count = Arc::new(AtomicUsize::new(0));
let callback_count_clone = callback_count.clone();
let last_items_placed = Arc::new(AtomicUsize::new(0));
let last_items_placed_clone = last_items_placed.clone();
let callback: ProgressCallback = Box::new(move |info| {
callback_count_clone.fetch_add(1, Ordering::Relaxed);
last_items_placed_clone.store(info.items_placed, Ordering::Relaxed);
});
let result = nester
.solve_with_progress(&geometries, &boundary, callback)
.unwrap();
// Verify callback was called (at least once per piece + initial + final)
let count = callback_count.load(Ordering::Relaxed);
assert!(
count >= 5,
"Expected at least 5 callbacks (1 initial + 4 pieces + 1 final), got {}",
count
);
// Verify final items_placed
let final_placed = last_items_placed.load(Ordering::Relaxed);
assert_eq!(final_placed, 4, "Should report 4 items placed");
// Verify result
assert_eq!(result.placements.len(), 4);
}
#[test]
fn test_progress_callback_nfp() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
let geometries = vec![Geometry2D::rectangle("R1", 10.0, 10.0).with_quantity(2)];
let boundary = Boundary2D::rectangle(50.0, 50.0);
let config = Config::default().with_strategy(Strategy::NfpGuided);
let nester = Nester2D::new(config);
let callback_count = Arc::new(AtomicUsize::new(0));
let callback_count_clone = callback_count.clone();
let callback: ProgressCallback = Box::new(move |info| {
callback_count_clone.fetch_add(1, Ordering::Relaxed);
assert!(info.items_placed <= info.total_items);
});
let result = nester
.solve_with_progress(&geometries, &boundary, callback)
.unwrap();
// Verify callback was called
let count = callback_count.load(Ordering::Relaxed);
assert!(count >= 3, "Expected at least 3 callbacks, got {}", count);
// Verify result
assert_eq!(result.placements.len(), 2);
}
#[test]
fn test_time_limit_honored() {
// Create many geometries to ensure BLF takes measurable time
let geometries: Vec<Geometry2D> = (0..100)
.map(|i| Geometry2D::rectangle(format!("R{}", i), 5.0, 5.0))
.collect();
let boundary = Boundary2D::rectangle(1000.0, 1000.0);
// Set a very short time limit (1ms) to ensure timeout
let config = Config::default()
.with_strategy(Strategy::BottomLeftFill)
.with_time_limit(1);
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// With such a short time limit, we may not place all items
// The test verifies that the solver respects the time limit
assert!(
result.computation_time_ms <= 100, // Allow some margin for overhead
"Computation took too long: {}ms (expected <= 100ms with 1ms limit)",
result.computation_time_ms
);
}
#[test]
fn test_time_limit_zero_unlimited() {
// time_limit_ms = 0 means unlimited
let geometries = vec![Geometry2D::rectangle("R1", 10.0, 10.0).with_quantity(4)];
let boundary = Boundary2D::rectangle(50.0, 50.0);
let config = Config::default()
.with_strategy(Strategy::BottomLeftFill)
.with_time_limit(0); // Unlimited
let nester = Nester2D::new(config);
let result = nester.solve(&geometries, &boundary).unwrap();
// Should place all items (no early exit)
assert_eq!(result.placements.len(), 4);
}
#[test]
fn test_blf_bounds_clamping() {
// Test that BLF correctly clamps placements within boundary
// Create a shape with non-zero g_min (similar to Gear shape)
// Gear-like: x ranges from 5 to 95 (width=90), y from 5 to 95 (height=90)
let gear_like = Geometry2D::new("gear")
.with_polygon(vec![
(50.0, 5.0), // Bottom
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0), // Right
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0), // Top
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0), // Left (min_x = 5)
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
])
.with_quantity(1);
// Boundary is 100x100
let boundary = Boundary2D::rectangle(100.0, 100.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let result = nester
.solve(std::slice::from_ref(&gear_like), &boundary)
.unwrap();
assert_eq!(result.placements.len(), 1);
let placement = &result.placements[0];
// Origin position
let origin_x = placement.position[0];
let origin_y = placement.position[1];
// Get rotation from placement (2D rotation is a single value in Vec)
let rotation = placement.rotation.first().copied().unwrap_or(0.0);
// Get AABB at rotation
let (g_min, g_max) = gear_like.aabb_at_rotation(rotation);
// Actual geometry bounds after placement
let actual_min_x = origin_x + g_min[0];
let actual_max_x = origin_x + g_max[0];
let actual_min_y = origin_y + g_min[1];
let actual_max_y = origin_y + g_max[1];
// All edges should be within boundary [0, 100]
assert!(
actual_min_x >= 0.0,
"Left edge {} should be >= 0",
actual_min_x
);
assert!(
actual_max_x <= 100.0,
"Right edge {} should be <= 100",
actual_max_x
);
assert!(
actual_min_y >= 0.0,
"Bottom edge {} should be >= 0",
actual_min_y
);
assert!(
actual_max_y <= 100.0,
"Top edge {} should be <= 100",
actual_max_y
);
}
#[test]
fn test_blf_bounds_clamping_many_pieces() {
// Test BLF bounds clamping with many pieces to trigger row overflow
// This mimics the actual failing case from test_blf.py
let gear_like = Geometry2D::new("gear")
.with_polygon(vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
])
.with_quantity(13); // Same as Gear (shape 8) in test_blf.py
// Boundary is 500x500 like the test
let boundary = Boundary2D::rectangle(500.0, 500.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let result = nester
.solve(std::slice::from_ref(&gear_like), &boundary)
.unwrap();
// Check that ALL placements are within bounds
for (i, placement) in result.placements.iter().enumerate() {
let origin_x = placement.position[0];
let origin_y = placement.position[1];
let rotation = placement.rotation.first().copied().unwrap_or(0.0);
let (g_min, g_max) = gear_like.aabb_at_rotation(rotation);
let actual_min_x = origin_x + g_min[0];
let actual_max_x = origin_x + g_max[0];
let actual_min_y = origin_y + g_min[1];
let actual_max_y = origin_y + g_max[1];
assert!(
actual_min_x >= -0.01,
"Piece {}: Left edge {} should be >= 0",
i,
actual_min_x
);
assert!(
actual_max_x <= 500.01,
"Piece {}: Right edge {} should be <= 500",
i,
actual_max_x
);
assert!(
actual_min_y >= -0.01,
"Piece {}: Bottom edge {} should be >= 0",
i,
actual_min_y
);
assert!(
actual_max_y <= 500.01,
"Piece {}: Top edge {} should be <= 500",
i,
actual_max_y
);
}
}
#[test]
fn test_blf_bounds_trace() {
// Debug test: trace through BLF to understand why clamping doesn't work
let gear = Geometry2D::new("gear").with_polygon(vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
]);
// Verify AABB
let (g_min, g_max) = gear.aabb();
println!("Gear AABB: min={:?}, max={:?}", g_min, g_max);
assert!(
(g_min[0] - 5.0).abs() < 0.01,
"g_min[0] should be 5, got {}",
g_min[0]
);
assert!(
(g_max[0] - 95.0).abs() < 0.01,
"g_max[0] should be 95, got {}",
g_max[0]
);
// Verify valid origin range for 500x500 boundary
let b_max_x = 500.0;
let margin = 0.0;
let max_valid_x = b_max_x - margin - g_max[0];
println!(
"max_valid_x = {} - {} - {} = {}",
b_max_x, margin, g_max[0], max_valid_x
);
assert!(
(max_valid_x - 405.0).abs() < 0.01,
"max_valid_x should be 405, got {}",
max_valid_x
);
// Run BLF and check the result
let boundary = Boundary2D::rectangle(500.0, 500.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let result = nester
.solve(&[gear.clone().with_quantity(1)], &boundary)
.unwrap();
assert_eq!(result.placements.len(), 1);
let p = &result.placements[0];
let origin_x = p.position[0];
let rotation = p.rotation.first().copied().unwrap_or(0.0);
let (g_min_r, g_max_r) = gear.aabb_at_rotation(rotation);
let actual_max_x = origin_x + g_max_r[0];
println!("Placement: origin_x={}, rotation={}", origin_x, rotation);
println!(
"At rotation {}: g_min={:?}, g_max={:?}",
rotation, g_min_r, g_max_r
);
println!(
"Actual max x: {} + {} = {}",
origin_x, g_max_r[0], actual_max_x
);
assert!(
actual_max_x <= 500.01,
"Geometry exceeds boundary: max_x={} > 500",
actual_max_x
);
}
#[test]
fn test_blf_bounds_many_pieces_direct() {
// Test with many pieces to trigger the boundary violation
let gear = Geometry2D::new("gear")
.with_polygon(vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
])
.with_quantity(25); // Many pieces
let boundary = Boundary2D::rectangle(500.0, 500.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let result = nester
.solve(std::slice::from_ref(&gear), &boundary)
.unwrap();
println!("Placed {} pieces", result.placements.len());
// Check all placements
for (i, p) in result.placements.iter().enumerate() {
let origin_x = p.position[0];
let origin_y = p.position[1];
let rotation = p.rotation.first().copied().unwrap_or(0.0);
let (g_min_r, g_max_r) = gear.aabb_at_rotation(rotation);
let actual_min_x = origin_x + g_min_r[0];
let actual_max_x = origin_x + g_max_r[0];
let actual_min_y = origin_y + g_min_r[1];
let actual_max_y = origin_y + g_max_r[1];
println!(
"Piece {}: origin=({:.1}, {:.1}), rot={:.2}, bounds=[{:.1},{:.1}]x[{:.1},{:.1}]",
i,
origin_x,
origin_y,
rotation,
actual_min_x,
actual_max_x,
actual_min_y,
actual_max_y
);
assert!(
actual_max_x <= 500.01,
"Piece {}: Right edge {} > 500",
i,
actual_max_x
);
assert!(
actual_max_y <= 500.01,
"Piece {}: Top edge {} > 500",
i,
actual_max_y
);
}
}
#[test]
fn test_blf_bounds_multi_strip() {
// Test with solve_multi_strip which is what benchmark runner uses
let gear = Geometry2D::new("gear")
.with_polygon(vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
])
.with_quantity(50); // Many pieces to force multiple strips
let boundary = Boundary2D::rectangle(500.0, 500.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
// Use solve_multi_strip like benchmark runner does
let result = nester
.solve_multi_strip(std::slice::from_ref(&gear), &boundary)
.unwrap();
println!(
"Placed {} pieces across {} strips",
result.placements.len(),
result.boundaries_used
);
// Check all placements - within their respective strips
let strip_width = 500.0;
for (i, p) in result.placements.iter().enumerate() {
let origin_x = p.position[0];
let origin_y = p.position[1];
let rotation = p.rotation.first().copied().unwrap_or(0.0);
let strip_idx = p.boundary_index;
// Calculate local position within strip
let local_x = origin_x - (strip_idx as f64 * strip_width);
let (_g_min_r, g_max_r) = gear.aabb_at_rotation(rotation);
let local_max_x = local_x + g_max_r[0];
let local_max_y = origin_y + g_max_r[1];
println!(
"Piece {}: strip={}, origin=({:.1}, {:.1}), local_x={:.1}, rot={:.2}, local_max_x={:.1}",
i, strip_idx, origin_x, origin_y, local_x, rotation, local_max_x
);
assert!(
local_max_x <= 500.01,
"Piece {}: In strip {}, local right edge {:.1} > 500",
i,
strip_idx,
local_max_x
);
assert!(
local_max_y <= 500.01,
"Piece {}: Top edge {:.1} > 500",
i,
local_max_y
);
}
}
#[test]
fn test_blf_bounds_mixed_shapes() {
// Replicate test_blf.py with all 9 shapes
let shapes = vec![
// Shape 0: Rounded rectangle (demand 2)
Geometry2D::new("shape0")
.with_polygon(vec![
(0.0, 0.0),
(180.0, 0.0),
(195.0, 15.0),
(200.0, 50.0),
(200.0, 150.0),
(195.0, 185.0),
(180.0, 200.0),
(20.0, 200.0),
(5.0, 185.0),
(0.0, 150.0),
(0.0, 50.0),
(5.0, 15.0),
])
.with_quantity(2),
// Shape 1: Circular-ish (demand 4)
Geometry2D::new("shape1")
.with_polygon(vec![
(60.0, 0.0),
(85.0, 7.0),
(104.0, 25.0),
(118.0, 50.0),
(120.0, 60.0),
(118.0, 70.0),
(104.0, 95.0),
(85.0, 113.0),
(60.0, 120.0),
(35.0, 113.0),
(16.0, 95.0),
(2.0, 70.0),
(0.0, 60.0),
(2.0, 50.0),
(16.0, 25.0),
(35.0, 7.0),
])
.with_quantity(4),
// Shape 2: L-shape (demand 6)
Geometry2D::new("shape2")
.with_polygon(vec![
(0.0, 0.0),
(80.0, 0.0),
(80.0, 20.0),
(20.0, 20.0),
(20.0, 80.0),
(0.0, 80.0),
])
.with_quantity(6),
// Shape 3: Triangle (demand 6)
Geometry2D::new("shape3")
.with_polygon(vec![(0.0, 0.0), (70.0, 0.0), (0.0, 70.0)])
.with_quantity(6),
// Shape 4: Rectangle (demand 4)
Geometry2D::new("shape4")
.with_polygon(vec![(0.0, 0.0), (120.0, 0.0), (120.0, 60.0), (0.0, 60.0)])
.with_quantity(4),
// Shape 5: Hexagon (demand 8)
Geometry2D::new("shape5")
.with_polygon(vec![
(15.0, 0.0),
(45.0, 0.0),
(60.0, 26.0),
(45.0, 52.0),
(15.0, 52.0),
(0.0, 26.0),
])
.with_quantity(8),
// Shape 6: T-shape (demand 4)
Geometry2D::new("shape6")
.with_polygon(vec![
(0.0, 0.0),
(90.0, 0.0),
(90.0, 12.0),
(55.0, 12.0),
(55.0, 60.0),
(35.0, 60.0),
(35.0, 12.0),
(0.0, 12.0),
])
.with_quantity(4),
// Shape 7: Rounded square (demand 3)
Geometry2D::new("shape7")
.with_polygon(vec![
(0.0, 10.0),
(10.0, 0.0),
(70.0, 0.0),
(80.0, 10.0),
(80.0, 70.0),
(70.0, 80.0),
(10.0, 80.0),
(0.0, 70.0),
])
.with_quantity(3),
// Shape 8: Gear (demand 13) - the problematic shape
Geometry2D::new("shape8_gear")
.with_polygon(vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
])
.with_quantity(13),
];
// Total: 2+4+6+6+4+8+4+3+13 = 50 pieces
let boundary = Boundary2D::rectangle(500.0, 500.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let result = nester.solve_multi_strip(&shapes, &boundary).unwrap();
println!(
"Placed {} pieces across {} strips",
result.placements.len(),
result.boundaries_used
);
// Check placements for Gear (shape8) specifically
let strip_width = 500.0;
let gear_aabb = shapes[8].aabb();
println!("Gear AABB: min={:?}, max={:?}", gear_aabb.0, gear_aabb.1);
let mut violations = Vec::new();
for p in &result.placements {
if p.geometry_id.as_str().starts_with("shape8") {
let origin_x = p.position[0];
let _origin_y = p.position[1];
let rotation = p.rotation.first().copied().unwrap_or(0.0);
let strip_idx = p.boundary_index;
let local_x = origin_x - (strip_idx as f64 * strip_width);
let (_g_min_r, g_max_r) = shapes[8].aabb_at_rotation(rotation);
let local_max_x = local_x + g_max_r[0];
println!(
"{}: strip={}, local_x={:.1}, rot={:.2}, local_max_x={:.1}",
p.geometry_id, strip_idx, local_x, rotation, local_max_x
);
if local_max_x > 500.01 {
violations.push((p.geometry_id.clone(), strip_idx, local_x, local_max_x));
}
}
}
assert!(
violations.is_empty(),
"Found {} Gear pieces exceeding boundary: {:?}",
violations.len(),
violations
);
}
#[test]
fn test_blf_bounds_expanded_like_benchmark() {
// Replicate EXACTLY how benchmark runner creates geometries:
// Each piece is a separate Geometry2D with quantity=1
// (vertices, demand, allowed_rotations_deg)
type ShapeDef = (Vec<(f64, f64)>, usize, Vec<f64>);
let shape_defs: Vec<ShapeDef> = vec![
(
vec![
(0.0, 0.0),
(180.0, 0.0),
(195.0, 15.0),
(200.0, 50.0),
(200.0, 150.0),
(195.0, 185.0),
(180.0, 200.0),
(20.0, 200.0),
(5.0, 185.0),
(0.0, 150.0),
(0.0, 50.0),
(5.0, 15.0),
],
2,
vec![0.0, 90.0, 180.0, 270.0],
),
(
vec![
(60.0, 0.0),
(85.0, 7.0),
(104.0, 25.0),
(118.0, 50.0),
(120.0, 60.0),
(118.0, 70.0),
(104.0, 95.0),
(85.0, 113.0),
(60.0, 120.0),
(35.0, 113.0),
(16.0, 95.0),
(2.0, 70.0),
(0.0, 60.0),
(2.0, 50.0),
(16.0, 25.0),
(35.0, 7.0),
],
4,
vec![0.0, 45.0, 90.0, 135.0],
),
(
vec![
(0.0, 0.0),
(80.0, 0.0),
(80.0, 20.0),
(20.0, 20.0),
(20.0, 80.0),
(0.0, 80.0),
],
6,
vec![0.0, 90.0, 180.0, 270.0],
),
(
vec![(0.0, 0.0), (70.0, 0.0), (0.0, 70.0)],
6,
vec![0.0, 90.0, 180.0, 270.0],
),
(
vec![(0.0, 0.0), (120.0, 0.0), (120.0, 60.0), (0.0, 60.0)],
4,
vec![0.0, 90.0],
),
(
vec![
(15.0, 0.0),
(45.0, 0.0),
(60.0, 26.0),
(45.0, 52.0),
(15.0, 52.0),
(0.0, 26.0),
],
8,
vec![0.0, 60.0, 120.0],
),
(
vec![
(0.0, 0.0),
(90.0, 0.0),
(90.0, 12.0),
(55.0, 12.0),
(55.0, 60.0),
(35.0, 60.0),
(35.0, 12.0),
(0.0, 12.0),
],
4,
vec![0.0, 90.0, 180.0, 270.0],
),
(
vec![
(0.0, 10.0),
(10.0, 0.0),
(70.0, 0.0),
(80.0, 10.0),
(80.0, 70.0),
(70.0, 80.0),
(10.0, 80.0),
(0.0, 70.0),
],
3,
vec![0.0, 90.0],
),
// Shape 8: Gear - with all 8 rotations
(
vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
],
13,
vec![0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0],
),
];
// Expand like benchmark runner: each piece is separate geometry
let mut geometries = Vec::new();
let mut piece_id = 0;
for (vertices, demand, rotations) in shape_defs.iter() {
for _ in 0..*demand {
let geom = Geometry2D::new(format!("piece_{}", piece_id))
.with_polygon(vertices.clone())
.with_rotations_deg(rotations.clone());
geometries.push(geom);
piece_id += 1;
}
}
// Store gear AABB for checking
let gear_geom = Geometry2D::new("gear_check").with_polygon(shape_defs[8].0.clone());
let (gear_min, gear_max) = gear_geom.aabb();
println!("Gear AABB: min={:?}, max={:?}", gear_min, gear_max);
let boundary = Boundary2D::rectangle(500.0, 500.0);
let config = Config::default().with_strategy(Strategy::BottomLeftFill);
let nester = Nester2D::new(config);
let result = nester.solve_multi_strip(&geometries, &boundary).unwrap();
println!(
"Placed {} pieces across {} strips",
result.placements.len(),
result.boundaries_used
);
// Check Gear placements (piece_37 to piece_49)
let strip_width = 500.0;
let mut violations = Vec::new();
for p in &result.placements {
let id_num: usize = p
.geometry_id
.as_str()
.strip_prefix("piece_")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
// piece_37 to piece_49 are Gear shapes
if (37..=49).contains(&id_num) {
let origin_x = p.position[0];
let rotation = p.rotation.first().copied().unwrap_or(0.0);
let strip_idx = p.boundary_index;
let local_x = origin_x - (strip_idx as f64 * strip_width);
let (_, g_max_r) = gear_geom.aabb_at_rotation(rotation);
let local_max_x = local_x + g_max_r[0];
println!(
"{}: strip={}, local_x={:.1}, rot={:.2}, local_max_x={:.1}",
p.geometry_id, strip_idx, local_x, rotation, local_max_x
);
if local_max_x > 500.01 {
violations.push((p.geometry_id.clone(), strip_idx, local_x, local_max_x));
}
}
}
assert!(
violations.is_empty(),
"Found {} Gear pieces exceeding boundary: {:?}",
violations.len(),
violations
);
}
/// Helper function to check if two AABBs overlap
fn aabbs_overlap(
a_min: [f64; 2],
a_max: [f64; 2],
b_min: [f64; 2],
b_max: [f64; 2],
tolerance: f64,
) -> bool {
// Two AABBs overlap if they overlap on both axes
let x_overlap = a_min[0] < b_max[0] - tolerance && a_max[0] > b_min[0] + tolerance;
let y_overlap = a_min[1] < b_max[1] - tolerance && a_max[1] > b_min[1] + tolerance;
x_overlap && y_overlap
}
/// Comprehensive test for all strategies - checks boundary and overlap violations
#[test]
fn test_all_strategies_boundary_and_overlap() {
use std::collections::HashMap;
// Create test shapes similar to demo
let shapes = vec![
Geometry2D::new("shape0")
.with_polygon(vec![
(0.0, 0.0),
(180.0, 0.0),
(195.0, 15.0),
(200.0, 50.0),
(200.0, 150.0),
(195.0, 185.0),
(180.0, 200.0),
(20.0, 200.0),
(5.0, 185.0),
(0.0, 150.0),
(0.0, 50.0),
(5.0, 15.0),
])
.with_rotations_deg(vec![0.0, 90.0, 180.0, 270.0])
.with_quantity(2),
Geometry2D::new("shape1_flange")
.with_polygon(vec![
(60.0, 0.0),
(85.0, 7.0),
(104.0, 25.0),
(118.0, 50.0),
(120.0, 60.0),
(118.0, 70.0),
(104.0, 95.0),
(85.0, 113.0),
(60.0, 120.0),
(35.0, 113.0),
(16.0, 95.0),
(2.0, 70.0),
(0.0, 60.0),
(2.0, 50.0),
(16.0, 25.0),
(35.0, 7.0),
])
.with_rotations_deg(vec![0.0, 45.0, 90.0, 135.0])
.with_quantity(4),
Geometry2D::new("shape2_lbracket")
.with_polygon(vec![
(0.0, 0.0),
(80.0, 0.0),
(80.0, 20.0),
(20.0, 20.0),
(20.0, 80.0),
(0.0, 80.0),
])
.with_rotations_deg(vec![0.0, 90.0, 180.0, 270.0])
.with_quantity(6),
Geometry2D::new("shape3_triangle")
.with_polygon(vec![(0.0, 0.0), (70.0, 0.0), (0.0, 70.0)])
.with_rotations_deg(vec![0.0, 90.0, 180.0, 270.0])
.with_quantity(6),
Geometry2D::new("shape4_rect")
.with_polygon(vec![(0.0, 0.0), (120.0, 0.0), (120.0, 60.0), (0.0, 60.0)])
.with_rotations_deg(vec![0.0, 90.0])
.with_quantity(4),
Geometry2D::new("shape5_hexagon")
.with_polygon(vec![
(15.0, 0.0),
(45.0, 0.0),
(60.0, 26.0),
(45.0, 52.0),
(15.0, 52.0),
(0.0, 26.0),
])
.with_rotations_deg(vec![0.0, 60.0, 120.0])
.with_quantity(8),
Geometry2D::new("shape6_tstiff")
.with_polygon(vec![
(0.0, 0.0),
(90.0, 0.0),
(90.0, 12.0),
(55.0, 12.0),
(55.0, 60.0),
(35.0, 60.0),
(35.0, 12.0),
(0.0, 12.0),
])
.with_rotations_deg(vec![0.0, 90.0, 180.0, 270.0])
.with_quantity(4),
Geometry2D::new("shape7_mount")
.with_polygon(vec![
(0.0, 10.0),
(10.0, 0.0),
(70.0, 0.0),
(80.0, 10.0),
(80.0, 70.0),
(70.0, 80.0),
(10.0, 80.0),
(0.0, 70.0),
])
.with_rotations_deg(vec![0.0, 90.0])
.with_quantity(3),
Geometry2D::new("shape8_gear")
.with_polygon(vec![
(50.0, 5.0),
(65.0, 15.0),
(77.0, 18.0),
(80.0, 32.0),
(95.0, 50.0),
(80.0, 68.0),
(77.0, 82.0),
(65.0, 85.0),
(50.0, 95.0),
(35.0, 85.0),
(23.0, 82.0),
(20.0, 68.0),
(5.0, 50.0),
(20.0, 32.0),
(23.0, 18.0),
(35.0, 15.0),
])
.with_rotations_deg(vec![0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0])
.with_quantity(13),
];
// Build geometry lookup map
let geom_map: HashMap<String, &Geometry2D> =
shapes.iter().map(|g| (g.id().clone(), g)).collect();
let boundary = Boundary2D::rectangle(500.0, 500.0);
let strip_width = 500.0;
// Test each strategy
let strategies = vec![
Strategy::BottomLeftFill,
Strategy::NfpGuided,
Strategy::GeneticAlgorithm,
Strategy::Brkga,
Strategy::SimulatedAnnealing,
Strategy::Gdrr,
Strategy::Alns,
];
for strategy in strategies {
println!("\n========== Testing {:?} ==========", strategy);
let config = Config::default()
.with_strategy(strategy)
.with_time_limit(30000); // 30s max per strategy
let nester = Nester2D::new(config);
let result = match nester.solve_multi_strip(&shapes, &boundary) {
Ok(r) => r,
Err(e) => {
println!(" Strategy {:?} failed: {}", strategy, e);
continue;
}
};
println!(
" Placed {} pieces across {} strips",
result.placements.len(),
result.boundaries_used
);
// Check 1: Boundary violations
let mut boundary_violations = Vec::new();
for p in &result.placements {
// Find the base geometry ID (without instance suffix)
let base_id = p.geometry_id.split('_').next().unwrap_or(&p.geometry_id);
let full_id = if base_id.starts_with("shape") {
// Find matching geometry by checking all shape IDs
shapes
.iter()
.find(|g| p.geometry_id.starts_with(g.id()))
.map(|g| g.id().as_str())
} else {
geom_map.get(&p.geometry_id).map(|g| g.id().as_str())
};
let geom = match full_id.and_then(|id| geom_map.get(id)) {
Some(g) => *g,
None => {
// Try to find by prefix match
match shapes.iter().find(|g| p.geometry_id.starts_with(g.id())) {
Some(g) => g,
None => {
println!(
" WARNING: Could not find geometry for {}",
p.geometry_id
);
continue;
}
}
}
};
let origin_x = p.position[0];
let origin_y = p.position[1];
let rotation = p.rotation.first().copied().unwrap_or(0.0);
let strip_idx = p.boundary_index;
// Calculate local position within strip
let local_x = origin_x - (strip_idx as f64 * strip_width);
let (g_min, g_max) = geom.aabb_at_rotation(rotation);
// Calculate actual bounds in local strip coordinates
let local_min_x = local_x + g_min[0];
let local_max_x = local_x + g_max[0];
let local_min_y = origin_y + g_min[1];
let local_max_y = origin_y + g_max[1];
// Check boundary (with small tolerance)
let tolerance = 0.1;
if local_min_x < -tolerance
|| local_max_x > 500.0 + tolerance
|| local_min_y < -tolerance
|| local_max_y > 500.0 + tolerance
{
boundary_violations.push(format!(
"{} in strip {}: bounds ({:.1}, {:.1}) to ({:.1}, {:.1})",
p.geometry_id,
strip_idx,
local_min_x,
local_min_y,
local_max_x,
local_max_y
));
}
}
if !boundary_violations.is_empty() {
println!(" BOUNDARY VIOLATIONS ({}):", boundary_violations.len());
for v in &boundary_violations {
println!(" - {}", v);
}
}
// Check 2: Overlaps (within same strip)
let mut overlaps = Vec::new();
let placements: Vec<_> = result.placements.iter().collect();
for i in 0..placements.len() {
for j in (i + 1)..placements.len() {
let p1 = placements[i];
let p2 = placements[j];
// Only check overlaps within the same strip
if p1.boundary_index != p2.boundary_index {
continue;
}
// Find geometries
let g1 = shapes.iter().find(|g| p1.geometry_id.starts_with(g.id()));
let g2 = shapes.iter().find(|g| p2.geometry_id.starts_with(g.id()));
let (g1, g2) = match (g1, g2) {
(Some(a), Some(b)) => (a, b),
_ => continue,
};
let strip_idx = p1.boundary_index;
let local_x1 = p1.position[0] - (strip_idx as f64 * strip_width);
let local_x2 = p2.position[0] - (strip_idx as f64 * strip_width);
let rot1 = p1.rotation.first().copied().unwrap_or(0.0);
let rot2 = p2.rotation.first().copied().unwrap_or(0.0);
let (g1_min, g1_max) = g1.aabb_at_rotation(rot1);
let (g2_min, g2_max) = g2.aabb_at_rotation(rot2);
let a_min = [local_x1 + g1_min[0], p1.position[1] + g1_min[1]];
let a_max = [local_x1 + g1_max[0], p1.position[1] + g1_max[1]];
let b_min = [local_x2 + g2_min[0], p2.position[1] + g2_min[1]];
let b_max = [local_x2 + g2_max[0], p2.position[1] + g2_max[1]];
if aabbs_overlap(a_min, a_max, b_min, b_max, 1.0) {
overlaps.push(format!(
"{} and {} in strip {}",
p1.geometry_id, p2.geometry_id, strip_idx
));
}
}
}
if !overlaps.is_empty() {
println!(" OVERLAPS ({}):", overlaps.len());
for o in overlaps.iter().take(10) {
println!(" - {}", o);
}
if overlaps.len() > 10 {
println!(" ... and {} more", overlaps.len() - 10);
}
}
// Assert no boundary violations
assert!(
boundary_violations.is_empty(),
"{:?}: Found {} boundary violations",
strategy,
boundary_violations.len()
);
println!(" ✓ All placements within boundary");
println!(" ✓ No AABB overlaps detected");
}
}
}