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
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
//! Central CAD document structure.
//!
//! [`CadDocument`] is the top-level container that holds everything in a
//! drawing: header variables, tables (layers, line types, text styles, …),
//! entities, non-graphical objects, block definitions, and classes.
//!
//! # Creating a document
//!
//! ```rust
//! use acadrust::CadDocument;
//!
//! // Default version (R2018 / AC1032)
//! let doc = CadDocument::new();
//!
//! // Specific version
//! use acadrust::types::DxfVersion;
//! let doc = CadDocument::with_version(DxfVersion::AC1015); // R2000
//! ```
use crate::classes::DxfClassCollection;
use crate::entities::{EntityCommon, EntityType};
use crate::objects::{
BlockEvaluationEdge, BlockEvaluationGraph, BlockEvaluationNode, DataObjectData,
DynamicBlockData, DynamicBlockObject, MaterialColor, MaterialTexture, ObjectType,
SolidHistory, SolidHistoryNodeBase, SolidHistoryOperation, XRecordEntry,
};
use crate::tables::*;
use crate::types::{Color, DxfVersion, Handle, Vector2, Vector3};
use crate::xdata::XDataValue;
use crate::Result;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
#[cfg(test)]
#[path = "document/evaluated_block_tests.rs"]
mod evaluated_block_tests;
fn material_checker_texture(entries: &[XRecordEntry]) -> Option<MaterialTexture> {
if !entries.iter().any(|entry| {
entry.code == 301
&& entry
.value
.as_string()
.is_some_and(|value| value.eq_ignore_ascii_case("Checker"))
}) {
return None;
}
let mut active_color = None;
let mut colors = [None, None];
for entry in entries {
if entry.code == 300 {
active_color = match entry.value.as_string() {
Some(value) if value.eq_ignore_ascii_case("Map1") => Some(0),
Some(value) if value.eq_ignore_ascii_case("Map2") => Some(1),
Some(value) if value.eq_ignore_ascii_case("Mapper") => None,
_ => active_color,
};
} else if entry.code == 420 {
if let (Some(index), Some(value)) = (active_color, entry.value.as_i32()) {
colors[index] = Some(value);
}
}
}
Some(MaterialTexture {
color1: MaterialColor {
flag: 1,
factor: 1.0,
rgb: Some(colors[0]?),
},
color2: MaterialColor {
flag: 1,
factor: 1.0,
rgb: Some(colors[1]?),
},
..MaterialTexture::default()
})
}
mod semantic_inventory;
pub use semantic_inventory::*;
#[cfg(feature = "serde")]
fn default_sketch_tolerance() -> f64 {
0.5
}
#[cfg(feature = "serde")]
fn default_show_history_mode() -> i16 {
1
}
#[derive(Default)]
struct EntityChangeRecorderInner {
before: HashMap<Handle, Option<Arc<EntityType>>>,
order: Vec<Handle>,
}
/// First-touch entity recorder used by document transactions.
///
/// It lives outside `CadDocument`, so serialization/equality and ordinary
/// document clones remain pure drawing data. The active recorder is associated
/// with a document address only for the synchronous mutation scope.
#[derive(Default)]
pub struct EntityChangeRecorder {
inner: Mutex<EntityChangeRecorderInner>,
}
impl EntityChangeRecorder {
fn record(&self, handle: Handle, before: Option<Arc<EntityType>>) {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
if !inner.before.contains_key(&handle) {
inner.order.push(handle);
inner.before.insert(handle, before);
}
}
pub fn take_before_images(&self) -> Vec<(Handle, Option<Arc<EntityType>>)> {
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
let order = std::mem::take(&mut inner.order);
order
.into_iter()
.map(|handle| (handle, inner.before.remove(&handle).flatten()))
.collect()
}
}
thread_local! {
static ENTITY_CHANGE_RECORDERS:
std::cell::RefCell<HashMap<usize, Arc<EntityChangeRecorder>>> =
std::cell::RefCell::new(HashMap::new());
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SolidHistoryGraph {
pub root: Handle,
pub nodes: Vec<Handle>,
#[cfg_attr(feature = "serde", serde(default))]
pub evaluation_graph: Option<Handle>,
}
const SOLID_HISTORY_NODE_FLAGS: i32 = 32;
fn solid_history_node_id(base: &SolidHistoryNodeBase) -> i32 {
if base.eval.node_id > 0 {
base.eval.node_id
} else {
base.step_id
}
}
/// DWG header variables containing drawing settings
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HeaderVariables {
// ==================== Version-specific Flags ====================
/// REQUIREDVERSIONS (R2013+) - Bit coded required versions
pub required_versions: i64,
// ==================== Drawing Mode Flags ====================
/// DIMASO - Associates dimensions with geometry
pub associate_dimensions: bool,
/// DIMSHO - Updates dimensions while dragging
pub update_dimensions_while_dragging: bool,
/// ORTHOMODE - Orthogonal mode on/off
pub ortho_mode: bool,
/// FILLMODE - Fill mode for solids/hatches
pub fill_mode: bool,
/// QTEXTMODE - Quick text mode (boxes instead of text)
pub quick_text_mode: bool,
/// MIRRTEXT - Mirror text on/off
pub mirror_text: bool,
/// REGENMODE - Auto regeneration mode
pub regen_mode: bool,
/// LIMCHECK - Limits checking on/off
pub limit_check: bool,
/// PLIMCHECK - Paper space limits checking
pub paper_space_limit_check: bool,
/// PLINEGEN - Line type pattern generation for polylines
pub polyline_linetype_generation: bool,
/// PSLTSCALE - Paper space line type scaling (0=viewport, 1=normal)
pub paper_space_linetype_scaling: bool,
/// TILEMODE - Show model space (tile mode)
pub show_model_space: bool,
/// USRTIMER - User timer on/off
pub user_timer: bool,
/// SKPOLY - Object type generated by SKETCH (0=line, 1=polyline, 2=spline)
#[cfg_attr(feature = "serde", serde(default))]
pub sketch_type: i16,
/// WORLDVIEW - World view on/off
pub world_view: bool,
/// VISRETAIN - Retain xref visibility settings
pub retain_xref_visibility: bool,
/// DISPSILH - Silhouette display for 3D objects
pub display_silhouette: bool,
/// SPLFRAME - Display spline control polygon
pub spline_frame: bool,
/// DELOBJ - Delete source objects for regions/solids
pub delete_objects: bool,
/// SOLIDHIST - Record construction history for subsequently created solids
#[cfg_attr(feature = "serde", serde(default))]
pub record_solid_history: bool,
/// SHOWHIST - Global solid-history display override (0=hide, 1=per-object, 2=show)
#[cfg_attr(feature = "serde", serde(default = "default_show_history_mode"))]
pub show_solid_history: i16,
/// DRAGMODE - Drag mode (0=off, 1=on request, 2=auto)
pub drag_mode: i16,
/// BLIPMODE - Blip mode on/off
pub blip_mode: bool,
/// ATTREQ - Attribute entry dialogs
pub attribute_request: bool,
/// ATTDIA - Attribute dialog mode
pub attribute_dialog: bool,
// ==================== Unit Settings ====================
/// LUNITS - Linear units format (0=Scientific, 1=Decimal, 2=Engineering, 3=Architectural, 4=Fractional)
pub linear_unit_format: i16,
/// LUPREC - Linear unit precision (0-8)
pub linear_unit_precision: i16,
/// AUNITS - Angular units format (0=Decimal degrees, 1=DMS, 2=Gradians, 3=Radians, 4=Surveyor)
pub angular_unit_format: i16,
/// AUPREC - Angular unit precision (0-8)
pub angular_unit_precision: i16,
/// INSUNITS - Insertion units (0=Unitless, 1=Inches, 2=Feet, etc.)
pub insertion_units: i16,
/// ATTMODE - Attribute display mode (0=off, 1=normal, 2=all)
pub attribute_visibility: i16,
/// PDMODE - Point display mode
pub point_display_mode: i16,
/// USERI1-5 - User integer variables
pub user_int1: i16,
pub user_int2: i16,
pub user_int3: i16,
pub user_int4: i16,
pub user_int5: i16,
/// COORDS - Coordinate display mode
pub coords_mode: i16,
/// OSMODE - Object snap mode bits
pub object_snap_mode: i32,
/// PICKSTYLE - Pick style
pub pick_style: i16,
/// SPLINETYPE - Spline type (5=quadratic, 6=cubic)
pub spline_type: i16,
/// SPLINESEGS - Spline segments for approximation
pub spline_segments: i16,
/// SPLINESEGQS - Spline segments for surface fit
pub spline_segs_surface: i16,
/// SURFU - Surface U density
pub surface_u_density: i16,
/// SURFV - Surface V density
pub surface_v_density: i16,
/// SURFTYPE - Surface type
pub surface_type: i16,
/// SURFTAB1 - Surface tabulation 1
pub surface_tab1: i16,
/// SURFTAB2 - Surface tabulation 2
pub surface_tab2: i16,
/// SHADEDGE - Shade edge mode
pub shade_edge: i16,
/// SHADEDIF - Shade diffuse percentage
pub shade_diffuse: i16,
/// MAXACTVP - Maximum active viewports
pub max_active_viewports: i16,
/// ISOLINES - Isolines on surfaces
pub isolines: i16,
/// CMLJUST - Multiline justification
pub multiline_justification: i16,
/// TEXTQLTY - Text quality for TrueType
pub text_quality: i16,
/// SORTENTS - Entity sort flags
pub sort_entities: i16,
/// INDEXCTL - Index control flags
pub index_control: i16,
/// HIDETEXT - Hide text during HIDE command
pub hide_text: i16,
/// XCLIPFRAME - Xref clipping frame visibility
pub xclip_frame: i16,
pub dwf_frame: i16,
pub dgn_frame: i16,
/// HALOGAP - Halo gap percentage
pub halo_gap: i16,
/// OBSCOLOR - Obscured line color
pub obscured_color: i16,
/// OBSLTYPE - Obscured line type
pub obscured_linetype: i16,
/// INTERSECTIONDISPLAY - Intersection polyline display
pub intersection_display: i16,
/// INTERSECTIONCOLOR - Intersection polyline color
pub intersection_color: i16,
/// DIMASSOC - Dimension associativity (0=no, 1=non-exploded, 2=associative)
pub dimension_associativity: i16,
/// PROJECTNAME - Project name
pub project_name: String,
// ==================== Scale/Size Defaults ====================
/// LTSCALE - Global linetype scale
pub linetype_scale: f64,
/// TEXTSIZE - Default text height
pub text_height: f64,
/// TRACEWID - Default trace width
pub trace_width: f64,
/// SKETCHINC - Sketch increment
pub sketch_increment: f64,
/// SKTOLERANCE - Fit tolerance used when SKETCH creates splines
#[cfg_attr(feature = "serde", serde(default = "default_sketch_tolerance"))]
pub sketch_tolerance: f64,
/// THICKNESS - Default thickness
pub thickness: f64,
/// PDSIZE - Point display size
pub point_display_size: f64,
/// PLINEWID - Default polyline width
pub polyline_width: f64,
/// CELTSCALE - Current entity linetype scale
pub current_entity_linetype_scale: f64,
/// VIEWTWIST - View twist angle
pub view_twist: f64,
/// FILLETRAD - Fillet radius
pub fillet_radius: f64,
/// CHAMFERA - Chamfer distance A
pub chamfer_distance_a: f64,
/// CHAMFERB - Chamfer distance B
pub chamfer_distance_b: f64,
/// CHAMFERC - Chamfer length
pub chamfer_length: f64,
/// CHAMFERD - Chamfer angle
pub chamfer_angle: f64,
/// ANGBASE - Base angle
pub angle_base: f64,
/// ANGDIR - Angular direction (0=counterclockwise, 1=clockwise)
pub angle_direction: i16,
/// ELEVATION - Current elevation
pub elevation: f64,
/// PELEVATION - Paper space elevation
pub paper_elevation: f64,
/// FACETRES - Facet resolution
pub facet_resolution: f64,
/// CMLSCALE - Multiline scale
pub multiline_scale: f64,
/// USERR1-5 - User real variables
pub user_real1: f64,
pub user_real2: f64,
pub user_real3: f64,
pub user_real4: f64,
pub user_real5: f64,
/// PSVPSCALE - Viewport default view scale factor (R2000+)
pub viewport_scale_factor: f64,
/// CANNOSCALE - Name of the current annotation scale for the active
/// space, e.g. "1:50" (R2008+). Default "1:1".
pub current_annotation_scale: String,
/// CANNOSCALEVALUE - Value of the current annotation scale as a
/// paper/drawing factor: 1:50 -> 0.02, 2:1 -> 2.0 (R2008+). Default 1.0.
pub annotation_scale_value: f64,
/// SHADOWPLANELOCATION - Shadow plane Z location
pub shadow_plane_location: f64,
/// LOFTANG1 - Loft angle 1
pub loft_angle1: f64,
/// LOFTANG2 - Loft angle 2
pub loft_angle2: f64,
/// LOFTMAG1 - Loft magnitude 1
pub loft_magnitude1: f64,
/// LOFTMAG2 - Loft magnitude 2
pub loft_magnitude2: f64,
/// LOFTPARAM - Loft parameters
pub loft_param: i16,
/// LOFTNORMALS - Loft normals mode
pub loft_normals: i16,
/// LATITUDE - Geographic latitude
pub latitude: f64,
/// LONGITUDE - Geographic longitude
pub longitude: f64,
/// NORTHDIRECTION - North direction angle
pub north_direction: f64,
/// TIMEZONE - Time zone
pub timezone: i32,
/// STEPSPERSEC - Steps per second for walk/fly
pub steps_per_second: f64,
/// STEPSIZE - Step size for walk/fly
pub step_size: f64,
/// LENSLENGTH - Camera lens length
pub lens_length: f64,
/// CAMERAHEIGHT - Camera height
pub camera_height: f64,
/// CAMERADISPLAY - Camera display mode
pub camera_display: bool,
// ==================== Current Entity Settings ====================
/// CECOLOR - Current entity color
pub current_entity_color: Color,
/// CELWEIGHT - Current line weight
pub current_line_weight: i16,
/// CEPSNTYPE - Current plot style name type
pub current_plotstyle_type: i16,
/// ENDCAPS - Line end cap style
pub end_caps: i16,
/// JOINSTYLE - Line join style
pub join_style: i16,
/// LWDISPLAY - Lineweight display on/off
pub lineweight_display: bool,
/// XEDIT - In-place xref editing
pub xedit: bool,
/// EXTNAMES - Extended symbol names (R2000+)
pub extended_names: bool,
/// PSTYLEMODE - Plot style mode (0=named, 1=color-dependent)
pub plotstyle_mode: bool,
/// OLESTARTUP - OLE startup
pub ole_startup: bool,
// ==================== Dimension Variables ====================
/// DIMSCALE - Overall dimension scale factor
pub dim_scale: f64,
/// DIMASZ - Dimension arrow size
pub dim_arrow_size: f64,
/// DIMEXO - Extension line offset
pub dim_ext_line_offset: f64,
/// DIMDLI - Dimension line increment
pub dim_line_increment: f64,
/// DIMEXE - Extension line extension
pub dim_ext_line_extension: f64,
/// DIMRND - Dimension rounding
pub dim_rounding: f64,
/// DIMDLE - Dimension line extension
pub dim_line_extension: f64,
/// DIMTP - Dimension tolerance plus
pub dim_tolerance_plus: f64,
/// DIMTM - Dimension tolerance minus
pub dim_tolerance_minus: f64,
/// DIMTXT - Dimension text height
pub dim_text_height: f64,
/// DIMCEN - Center mark size
pub dim_center_mark: f64,
/// DIMTSZ - Tick size
pub dim_tick_size: f64,
/// DIMALTF - Alternate unit scale factor
pub dim_alt_scale: f64,
/// DIMLFAC - Linear measurements scale factor
pub dim_linear_scale: f64,
/// DIMTVP - Text vertical position
pub dim_text_vertical_pos: f64,
/// DIMTFAC - Tolerance text height scale factor
pub dim_tolerance_scale: f64,
/// DIMGAP - Dimension line gap
pub dim_line_gap: f64,
/// DIMALTRND - Alternate units rounding
pub dim_alt_rounding: f64,
/// DIMTOL - Tolerance generation on/off
pub dim_tolerance: bool,
/// DIMLIM - Limits generation on/off
pub dim_limits: bool,
/// DIMTIH - Text inside horizontal
pub dim_text_inside_horizontal: bool,
/// DIMTOH - Text outside horizontal
pub dim_text_outside_horizontal: bool,
/// DIMSE1 - Suppress extension line 1
pub dim_suppress_ext1: bool,
/// DIMSE2 - Suppress extension line 2
pub dim_suppress_ext2: bool,
/// DIMTAD - Text above dimension line
pub dim_text_above: i16,
/// DIMZIN - Zero suppression
pub dim_zero_suppression: i16,
/// DIMAZIN - Alternate zero suppression
pub dim_alt_zero_suppression: i16,
/// DIMALT - Alternate units on/off
pub dim_alternate_units: bool,
/// DIMALTD - Alternate decimal places
pub dim_alt_decimal_places: i16,
/// DIMTOFL - Force line inside
pub dim_force_line_inside: bool,
/// DIMSAH - Separate arrow blocks
pub dim_separate_arrows: bool,
/// DIMTIX - Force text inside
pub dim_force_text_inside: bool,
/// DIMSOXD - Suppress outside extension dim
pub dim_suppress_outside_ext: bool,
/// DIMCLRD - Dimension line color
pub dim_line_color: Color,
/// DIMCLRE - Extension line color
pub dim_ext_line_color: Color,
/// DIMCLRT - Dimension text color
pub dim_text_color: Color,
/// DIMADEC - Angular decimal places
pub dim_angular_decimal_places: i16,
/// DIMDEC - Decimal places
pub dim_decimal_places: i16,
/// DIMTDEC - Tolerance decimal places
pub dim_tolerance_decimal_places: i16,
/// DIMALTU - Alternate units format
pub dim_alt_units_format: i16,
/// DIMALTTD - Alternate tolerance decimal places
pub dim_alt_tolerance_decimal_places: i16,
/// DIMAUNIT - Angular units format
pub dim_angular_units: i16,
/// DIMFRAC - Fraction format
pub dim_fraction_format: i16,
/// DIMLUNIT - Linear unit format
pub dim_linear_unit_format: i16,
/// DIMDSEP - Decimal separator
pub dim_decimal_separator: char,
/// DIMTMOVE - Text movement
pub dim_text_movement: i16,
/// DIMJUST - Horizontal text justification
pub dim_horizontal_justification: i16,
/// DIMSD1 - Suppress dimension line 1
pub dim_suppress_line1: bool,
/// DIMSD2 - Suppress dimension line 2
pub dim_suppress_line2: bool,
/// DIMTOLJ - Tolerance vertical justification
pub dim_tolerance_justification: i16,
/// DIMTZIN - Tolerance zero suppression
pub dim_tolerance_zero_suppression: i16,
/// DIMALTZ - Alternate tolerance zero suppression
pub dim_alt_tolerance_zero_suppression: i16,
/// DIMALTTZ - Alternate tolerance zero suppression (tight)
pub dim_alt_tolerance_zero_tight: i16,
/// DIMFIT/DIMATFIT - Fit options
pub dim_fit: i16,
/// DIMUPT - User positioned text
pub dim_user_positioned_text: bool,
/// DIMPOST - Primary units suffix
pub dim_post: String,
/// DIMAPOST - Alternate units suffix
pub dim_alt_post: String,
/// DIMBLK - Arrow block name
pub dim_arrow_block: String,
/// DIMBLK1 - First arrow block name
pub dim_arrow_block1: String,
/// DIMBLK2 - Second arrow block name
pub dim_arrow_block2: String,
/// DIMLDRBLK - Leader arrow block name
pub dim_leader_arrow_block: String,
// ==================== Extents and Limits ====================
/// INSBASE - Model space insertion base point
pub model_space_insertion_base: Vector3,
/// EXTMIN - Model space extents min
pub model_space_extents_min: Vector3,
/// EXTMAX - Model space extents max
pub model_space_extents_max: Vector3,
/// LIMMIN - Model space limits min
pub model_space_limits_min: Vector2,
/// LIMMAX - Model space limits max
pub model_space_limits_max: Vector2,
/// Paper space insertion base point
pub paper_space_insertion_base: Vector3,
/// Paper space extents min
pub paper_space_extents_min: Vector3,
/// Paper space extents max
pub paper_space_extents_max: Vector3,
/// Paper space limits min
pub paper_space_limits_min: Vector2,
/// Paper space limits max
pub paper_space_limits_max: Vector2,
// ==================== UCS Settings ====================
/// UCSBASE - UCS base name
pub ucs_base: String,
/// Model space UCS name
pub model_space_ucs_name: String,
/// Paper space UCS name
pub paper_space_ucs_name: String,
/// Model space UCS origin
pub model_space_ucs_origin: Vector3,
/// Model space UCS X axis
pub model_space_ucs_x_axis: Vector3,
/// Model space UCS Y axis
pub model_space_ucs_y_axis: Vector3,
/// Paper space UCS origin
pub paper_space_ucs_origin: Vector3,
/// Paper space UCS X axis
pub paper_space_ucs_x_axis: Vector3,
/// Paper space UCS Y axis
pub paper_space_ucs_y_axis: Vector3,
/// UCSORTHOREF - UCS orthographic reference
pub ucs_ortho_ref: Handle,
/// UCSORTHOVIEW - UCS orthographic view type
pub ucs_ortho_view: i16,
/// PUCSORTHOREF - Paper space UCS orthographic reference
pub paper_ucs_ortho_ref: Handle,
/// PUCSORTHOVIEW - Paper space UCS orthographic view type
pub paper_ucs_ortho_view: i16,
// ==================== Handles/References ====================
/// HANDSEED - Next available handle
pub handle_seed: u64,
/// Current layer handle
pub current_layer_handle: Handle,
/// Current text style handle
pub current_text_style_handle: Handle,
/// Current linetype handle
pub current_linetype_handle: Handle,
/// Current dimension style handle
pub current_dimstyle_handle: Handle,
/// Current multiline style handle
pub current_multiline_style_handle: Handle,
/// Current material handle
pub current_material_handle: Handle,
/// Dimension text style handle
pub dim_text_style_handle: Handle,
/// Dimension linetype handle
pub dim_linetype_handle: Handle,
/// Dimension linetype 1 handle
pub dim_linetype1_handle: Handle,
/// Dimension linetype 2 handle
pub dim_linetype2_handle: Handle,
/// Dimension arrow block handle
pub dim_arrow_block_handle: Handle,
/// Dimension arrow block 1 handle
pub dim_arrow_block1_handle: Handle,
/// Dimension arrow block 2 handle
pub dim_arrow_block2_handle: Handle,
/// DIMLWD - Dimension line weight
pub dim_line_weight: i16,
/// DIMLWE - Extension line weight
pub dim_ext_line_weight: i16,
// ==================== Table Control Object Handles ====================
/// Block table control object
pub block_control_handle: Handle,
/// Layer table control object
pub layer_control_handle: Handle,
/// Text style table control object
pub style_control_handle: Handle,
/// Linetype table control object
pub linetype_control_handle: Handle,
/// View table control object
pub view_control_handle: Handle,
/// UCS table control object
pub ucs_control_handle: Handle,
/// Viewport table control object
pub vport_control_handle: Handle,
/// AppId table control object
pub appid_control_handle: Handle,
/// Dimension style table control object
pub dimstyle_control_handle: Handle,
/// VPEntHdr table control object
pub vpent_hdr_control_handle: Handle,
/// Current legacy viewport-entity table record (R13-R2000)
pub current_vx_handle: Handle,
// ==================== Dictionary Handles ====================
/// Named objects dictionary
pub named_objects_dict_handle: Handle,
/// ACAD_GROUP dictionary
pub acad_group_dict_handle: Handle,
/// ACAD_MLINESTYLE dictionary
pub acad_mlinestyle_dict_handle: Handle,
/// ACAD_LAYOUT dictionary (R2000+)
pub acad_layout_dict_handle: Handle,
/// ACAD_PLOTSETTINGS dictionary (R2000+)
pub acad_plotsettings_dict_handle: Handle,
/// ACAD_PLOTSTYLENAME dictionary (R2000+)
pub acad_plotstylename_dict_handle: Handle,
/// ACAD_MATERIAL dictionary (R2007+)
pub acad_material_dict_handle: Handle,
/// ACAD_COLOR dictionary (R2007+)
pub acad_color_dict_handle: Handle,
/// ACAD_VISUALSTYLE dictionary (R2007+)
pub acad_visualstyle_dict_handle: Handle,
// ==================== Block Record Handles ====================
/// *MODEL_SPACE block record
pub model_space_block_handle: Handle,
/// *PAPER_SPACE block record
pub paper_space_block_handle: Handle,
/// BYLAYER linetype
pub bylayer_linetype_handle: Handle,
/// BYBLOCK linetype
pub byblock_linetype_handle: Handle,
/// CONTINUOUS linetype
pub continuous_linetype_handle: Handle,
// ==================== Date/Time ====================
/// Document creation time (Julian date)
pub create_date_julian: f64,
/// Document update time (Julian date)
pub update_date_julian: f64,
pub universal_create_date_julian: f64,
pub universal_update_date_julian: f64,
/// Total editing time in days
pub total_editing_time: f64,
/// User elapsed time in days
pub user_elapsed_time: f64,
// ==================== Metadata ====================
/// Fingerprint GUID
pub fingerprint_guid: String,
/// Version GUID
pub version_guid: String,
/// Menu file name
pub menu_name: String,
/// DWGCODEPAGE
pub code_page: String,
/// LASTSAVEDBY
pub last_saved_by: String,
/// HYPERLINKBASE
pub hyperlink_base: String,
/// STYLESHEET
pub stylesheet: String,
// ==================== Misc ====================
/// MEASUREMENT - Drawing units (0=English, 1=Metric)
pub measurement: i16,
/// PROXYGRAPHICS - Show proxy graphics
pub proxy_graphics: i16,
/// TREEDEPTH - Tree depth for spatial index
pub tree_depth: i16,
/// CMLSTYLE - Current multiline style name
pub multiline_style: String,
/// CELTYPE - Current linetype name
pub current_linetype_name: String,
/// CLAYER - Current layer name
pub current_layer_name: String,
/// TEXTSTYLE - Current text style name
pub current_text_style_name: String,
/// DIMSTYLE - Current dimension style name
pub current_dimstyle_name: String,
/// CTABLESTYLE - Current table style name
pub current_table_style_name: String,
/// CMLEADERSTYLE - Current multileader style name
pub current_mleader_style_name: String,
}
impl HeaderVariables {
pub fn universal_create_or_local(&self) -> f64 {
if self.universal_create_date_julian != 0.0 {
self.universal_create_date_julian
} else {
self.create_date_julian
}
}
pub fn universal_update_or_local(&self) -> f64 {
if self.universal_update_date_julian != 0.0 {
self.universal_update_date_julian
} else {
self.update_date_julian
}
}
}
impl Default for HeaderVariables {
fn default() -> Self {
Self {
// Version-specific flags
required_versions: 0,
// Drawing mode flags
associate_dimensions: true,
update_dimensions_while_dragging: true,
ortho_mode: false,
fill_mode: true,
quick_text_mode: false,
mirror_text: false,
regen_mode: true,
limit_check: false,
paper_space_limit_check: false,
polyline_linetype_generation: false,
paper_space_linetype_scaling: true,
show_model_space: true,
user_timer: true,
sketch_type: 0,
world_view: true,
retain_xref_visibility: true,
display_silhouette: true,
spline_frame: false,
delete_objects: true,
record_solid_history: false,
show_solid_history: 1,
drag_mode: 2,
blip_mode: false,
attribute_request: true,
attribute_dialog: true,
// Unit settings
linear_unit_format: 2, // Decimal
linear_unit_precision: 4,
angular_unit_format: 0, // Decimal degrees
angular_unit_precision: 0,
insertion_units: 0, // Unitless
attribute_visibility: 1,
point_display_mode: 0,
user_int1: 0,
user_int2: 0,
user_int3: 0,
user_int4: 0,
user_int5: 0,
coords_mode: 2,
object_snap_mode: 0,
pick_style: 1,
spline_type: 6,
spline_segments: 8,
spline_segs_surface: 6,
surface_u_density: 6,
surface_v_density: 6,
surface_type: 6,
surface_tab1: 6,
surface_tab2: 6,
shade_edge: 3,
shade_diffuse: 70,
max_active_viewports: 64,
isolines: 4,
multiline_justification: 0,
text_quality: 50,
sort_entities: 127,
index_control: 0,
hide_text: 1,
// AutoCAD's default: clip frames display (not plotted). Older
// headers (R2000) don't carry the variable at all, so the default
// must match what AutoCAD shows for them.
xclip_frame: 2,
// New drawings show DWF frames without plotting them and hide
// DGN frames.
dwf_frame: 2,
dgn_frame: 0,
halo_gap: 0,
obscured_color: 257,
obscured_linetype: 0,
intersection_display: 0,
intersection_color: 257,
dimension_associativity: 2,
project_name: String::new(),
// Scale/size defaults
linetype_scale: 1.0,
text_height: 2.5,
trace_width: 0.05,
sketch_increment: 0.1,
sketch_tolerance: 0.5,
thickness: 0.0,
point_display_size: 0.0,
polyline_width: 0.0,
current_entity_linetype_scale: 1.0,
view_twist: 0.0,
fillet_radius: 0.0,
chamfer_distance_a: 0.0,
chamfer_distance_b: 0.0,
chamfer_length: 0.0,
chamfer_angle: 0.0,
angle_base: 0.0,
angle_direction: 0,
elevation: 0.0,
paper_elevation: 0.0,
facet_resolution: 0.5,
multiline_scale: 1.0,
user_real1: 0.0,
user_real2: 0.0,
user_real3: 0.0,
user_real4: 0.0,
user_real5: 0.0,
viewport_scale_factor: 0.0,
current_annotation_scale: "1:1".to_string(),
annotation_scale_value: 1.0,
shadow_plane_location: 0.0,
loft_angle1: std::f64::consts::FRAC_PI_2,
loft_angle2: std::f64::consts::FRAC_PI_2,
loft_magnitude1: 0.0,
loft_magnitude2: 0.0,
loft_param: 7,
loft_normals: 1,
latitude: 37.795,
longitude: -122.394,
north_direction: 0.0,
timezone: -8000,
steps_per_second: 2.0,
step_size: 6.0,
lens_length: 50.0,
camera_height: 0.0,
camera_display: false,
// Current entity settings
current_entity_color: Color::ByLayer,
current_line_weight: -1, // ByLayer
current_plotstyle_type: 0,
end_caps: 0,
join_style: 0,
lineweight_display: false,
xedit: true,
extended_names: true,
plotstyle_mode: true,
ole_startup: false,
// Dimension variables
dim_scale: 1.0,
dim_arrow_size: 0.18,
dim_ext_line_offset: 0.0625,
dim_line_increment: 0.38,
dim_ext_line_extension: 0.18,
dim_rounding: 0.0,
dim_line_extension: 0.0,
dim_tolerance_plus: 0.0,
dim_tolerance_minus: 0.0,
dim_text_height: 0.18,
dim_center_mark: 0.09,
dim_tick_size: 0.0,
dim_alt_scale: 25.4,
dim_linear_scale: 1.0,
dim_text_vertical_pos: 0.0,
dim_tolerance_scale: 1.0,
dim_line_gap: 0.09,
dim_alt_rounding: 0.0,
dim_tolerance: false,
dim_limits: false,
dim_text_inside_horizontal: true,
dim_text_outside_horizontal: true,
dim_suppress_ext1: false,
dim_suppress_ext2: false,
dim_text_above: 0,
dim_zero_suppression: 0,
dim_alt_zero_suppression: 0,
dim_alternate_units: false,
dim_alt_decimal_places: 2,
dim_force_line_inside: false,
dim_separate_arrows: false,
dim_force_text_inside: false,
dim_suppress_outside_ext: false,
dim_line_color: Color::ByBlock,
dim_ext_line_color: Color::ByBlock,
dim_text_color: Color::ByBlock,
dim_angular_decimal_places: 0,
dim_decimal_places: 4,
dim_tolerance_decimal_places: 4,
dim_alt_units_format: 2,
dim_alt_tolerance_decimal_places: 4,
dim_angular_units: 0,
dim_fraction_format: 0,
dim_linear_unit_format: 2,
dim_decimal_separator: '.',
dim_text_movement: 0,
dim_horizontal_justification: 0,
dim_suppress_line1: false,
dim_suppress_line2: false,
dim_tolerance_justification: 1,
dim_tolerance_zero_suppression: 0,
dim_alt_tolerance_zero_suppression: 0,
dim_alt_tolerance_zero_tight: 0,
dim_fit: 3,
dim_user_positioned_text: false,
dim_post: String::new(),
dim_alt_post: String::new(),
dim_arrow_block: String::new(),
dim_arrow_block1: String::new(),
dim_arrow_block2: String::new(),
dim_leader_arrow_block: String::new(),
// Extents and limits - Model space
model_space_insertion_base: Vector3::ZERO,
model_space_extents_min: Vector3::new(1e20, 1e20, 1e20),
model_space_extents_max: Vector3::new(-1e20, -1e20, -1e20),
model_space_limits_min: Vector2::new(0.0, 0.0),
model_space_limits_max: Vector2::new(0.0, 0.0),
// Extents and limits - Paper space
paper_space_insertion_base: Vector3::ZERO,
paper_space_extents_min: Vector3::new(1e20, 1e20, 1e20),
paper_space_extents_max: Vector3::new(-1e20, -1e20, -1e20),
paper_space_limits_min: Vector2::new(0.0, 0.0),
paper_space_limits_max: Vector2::new(0.0, 0.0),
// UCS settings
ucs_base: String::new(),
model_space_ucs_name: String::new(),
paper_space_ucs_name: String::new(),
model_space_ucs_origin: Vector3::ZERO,
model_space_ucs_x_axis: Vector3::new(1.0, 0.0, 0.0),
model_space_ucs_y_axis: Vector3::new(0.0, 1.0, 0.0),
paper_space_ucs_origin: Vector3::ZERO,
paper_space_ucs_x_axis: Vector3::new(1.0, 0.0, 0.0),
paper_space_ucs_y_axis: Vector3::new(0.0, 1.0, 0.0),
ucs_ortho_ref: Handle::NULL,
ucs_ortho_view: 0,
paper_ucs_ortho_ref: Handle::NULL,
paper_ucs_ortho_view: 0,
// Handles
handle_seed: 1,
current_layer_handle: Handle::NULL,
current_text_style_handle: Handle::NULL,
current_linetype_handle: Handle::NULL,
current_dimstyle_handle: Handle::NULL,
current_multiline_style_handle: Handle::NULL,
current_material_handle: Handle::NULL,
dim_text_style_handle: Handle::NULL,
dim_linetype_handle: Handle::NULL,
dim_linetype1_handle: Handle::NULL,
dim_linetype2_handle: Handle::NULL,
dim_arrow_block_handle: Handle::NULL,
dim_arrow_block1_handle: Handle::NULL,
dim_arrow_block2_handle: Handle::NULL,
dim_line_weight: -2, // ByBlock
dim_ext_line_weight: -2, // ByBlock
// Table control handles
block_control_handle: Handle::NULL,
layer_control_handle: Handle::NULL,
style_control_handle: Handle::NULL,
linetype_control_handle: Handle::NULL,
view_control_handle: Handle::NULL,
ucs_control_handle: Handle::NULL,
vport_control_handle: Handle::NULL,
appid_control_handle: Handle::NULL,
dimstyle_control_handle: Handle::NULL,
vpent_hdr_control_handle: Handle::NULL,
current_vx_handle: Handle::NULL,
// Dictionary handles
named_objects_dict_handle: Handle::NULL,
acad_group_dict_handle: Handle::NULL,
acad_mlinestyle_dict_handle: Handle::NULL,
acad_layout_dict_handle: Handle::NULL,
acad_plotsettings_dict_handle: Handle::NULL,
acad_plotstylename_dict_handle: Handle::NULL,
acad_material_dict_handle: Handle::NULL,
acad_color_dict_handle: Handle::NULL,
acad_visualstyle_dict_handle: Handle::NULL,
// Block record handles
model_space_block_handle: Handle::NULL,
paper_space_block_handle: Handle::NULL,
bylayer_linetype_handle: Handle::NULL,
byblock_linetype_handle: Handle::NULL,
continuous_linetype_handle: Handle::NULL,
// Date/time
create_date_julian: 0.0,
update_date_julian: 0.0,
universal_create_date_julian: 0.0,
universal_update_date_julian: 0.0,
total_editing_time: 0.0,
user_elapsed_time: 0.0,
// Metadata
fingerprint_guid: String::new(),
version_guid: String::new(),
menu_name: String::new(),
code_page: String::from("ANSI_1252"),
last_saved_by: String::new(),
hyperlink_base: String::new(),
stylesheet: String::new(),
// Misc
measurement: 0,
proxy_graphics: 1,
tree_depth: 3020,
multiline_style: String::from("Standard"),
current_linetype_name: String::from("ByLayer"),
current_layer_name: String::from("0"),
current_text_style_name: String::from("Standard"),
current_dimstyle_name: String::from("Standard"),
current_table_style_name: String::from("Standard"),
current_mleader_style_name: String::from("Standard"),
}
}
}
/// Format of an embedded DWG preview/thumbnail image.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PreviewFormat {
/// Windows DIB — a `BITMAPINFOHEADER` + palette + pixels, WITHOUT the
/// 14-byte `BITMAPFILEHEADER`. Prepend a file header to save as `.bmp`.
Bmp,
/// Windows Metafile.
Wmf,
/// PNG (written by R2013+).
Png,
}
/// An embedded preview/thumbnail image stored in a DWG file.
///
/// DWG files carry a small raster preview of the drawing, shown by file
/// browsers and the Open dialog. `data` holds the raw stored image bytes in
/// `format`. `None` on [`CadDocument::preview`] means the file has no preview;
/// the writer then emits an empty preview section (the previous behaviour).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Preview {
/// Image encoding of `data`.
pub format: PreviewFormat,
/// Raw image bytes exactly as stored in the file (a DIB for `Bmp`).
pub data: Vec<u8>,
}
/// A decoded `AcDbField` definition (a dynamic text field).
///
/// `evaluator` is the field's evaluator id (DXF 1) — e.g. `"AcVar"` or
/// `"AcDiesel"`. `code` is the field-code string (DXF 2): for a *leaf* field it
/// is the expression to evaluate (e.g. `\AcDiesel $(getvar,"cdate")`); for a
/// *container* field it is the display template with `%<\_FldIdx N>%` markers
/// that reference child fields. Child fields are the fields whose `owner` is
/// this field's handle.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FieldDef {
pub handle: Handle,
pub owner: Handle,
pub evaluator: String,
pub code: String,
/// Referenced-object handles targeted by `%<\_ObjIdx N>%` markers in an
/// `AcObjProp` field code. Empty for other field kinds.
pub objects: Vec<Handle>,
}
/// Document summary information (the DWG `SummaryInfo` section — the same
/// properties AutoCAD's DWGPROPS dialog edits). Backs the Document-category
/// dynamic-text fields (Author, Title, Subject, Keywords, Comments,
/// HyperlinkBase, RevisionNumber) plus arbitrary custom properties.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SummaryInfo {
pub title: String,
pub subject: String,
pub author: String,
pub keywords: String,
pub comments: String,
pub last_saved_by: String,
pub revision_number: String,
pub hyperlink_base: String,
/// Custom document properties as `(name, value)` pairs.
pub custom_properties: Vec<(String, String)>,
}
/// A CAD document containing all drawing data
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CadDocument {
/// Document version
pub version: DxfVersion,
/// AutoCAD maintenance release version (from file header byte 0x0B).
///
/// Used to determine encoding variations within a major DWG version.
/// For AC1024 (R2010), maintenance > 3 triggers an extra 4-byte RL field
/// in the Classes and Header sections. Preserved during roundtrip.
pub maintenance_version: u8,
/// Header variables containing drawing settings
pub header: HeaderVariables,
/// Layer table
pub layers: Table<Layer>,
/// Line type table
pub line_types: Table<LineType>,
/// Text style table
pub text_styles: Table<TextStyle>,
/// Block record table
pub block_records: Table<BlockRecord>,
/// Dimension style table
pub dim_styles: Table<DimStyle>,
/// Application ID table
pub app_ids: Table<AppId>,
/// View table
pub views: Table<View>,
/// Viewport table
pub vports: Table<VPort>,
/// UCS table
pub ucss: Table<Ucs>,
/// Legacy viewport-entity table (R13-R2000)
pub vx_table: Table<VxTableRecord>,
/// Ordered soft-owner references stored by VX_CONTROL. This preserves
/// dangling records and source ordering as well as the decoded records.
pub vx_control_entries: Vec<Handle>,
/// DXF class definitions (CLASSES section)
pub classes: DxfClassCollection,
/// Notifications collected during the last read/write operation
pub notifications: crate::notification::NotificationCollection,
/// All entities in the document (contiguous storage for cache locality).
/// Each entity is behind an `Arc` so cloning the whole document — the undo
/// snapshot on every edit — is O(entities) atomic bumps that structurally
/// share the geometry, not an O(entities) deep copy. A single-entity edit
/// (`get_entity_mut`) copies just that one entity out of the shared Arc
/// (`Arc::make_mut`), so the snapshot and the live doc diverge only where
/// they actually differ.
pub(crate) entities: Vec<Arc<EntityType>>,
/// Handle → index mapping for O(1) entity lookup by handle.
pub(crate) entity_index: foldhash::HashMap<Handle, usize>,
/// All objects in the document (indexed by handle)
pub objects: HashMap<Handle, ObjectType>,
/// Parsed dynamic-block visibility parameters, keyed by parameter handle.
/// A *side* view: the objects themselves are still kept verbatim in
/// `objects` as `ObjectType::Unknown` for DWG round-trip. Lets consumers
/// enumerate visibility states and their per-state visible-entity sets
/// without re-decoding the raw object stream.
pub block_visibility_params: HashMap<Handle, crate::objects::BlockVisibilityParameter>,
/// Annotation-scale handle for each annotative object-context leaf (an
/// `*OBJECTCONTEXTDATA` object). A *side* view: the leaves stay verbatim in
/// `objects` as `ObjectType::Unknown` for DWG round-trip. Maps the context
/// object handle → its `AcDbScale` handle (in `ACAD_SCALELIST`), so a
/// consumer can resolve an annotative entity's applied annotation scale.
pub context_scales: HashMap<Handle, Handle>,
/// AcDbBlockRepresentationData link: representation-object handle → the
/// dynamic block-definition handle it represents (group code 340). Lets a
/// consumer connect an anonymous evaluated block to its dynamic definition
/// (and thus to that definition's visibility parameter). Side view; the
/// objects stay verbatim as `ObjectType::Unknown`.
pub block_representations: HashMap<Handle, Handle>,
/// AcDbField definitions, keyed by field-object handle. A *side* view: the
/// FIELD objects stay verbatim in `objects` as `ObjectType::Unknown` for DWG
/// round-trip, while this exposes the evaluator id and field-code string so
/// a consumer can (re-)evaluate dynamic text fields without decoding the raw
/// object stream. The container→child link is recovered from each field's
/// `owner` (a child field is owned by its container field).
pub fields: HashMap<Handle, FieldDef>,
/// Document summary information (Author, Title, Subject, …) from the DWG
/// SummaryInfo section. Backs the Document-category dynamic-text fields.
pub summary_info: SummaryInfo,
/// Filesystem path the document was read from, when known (set by the DWG /
/// DXF file readers). Backs the `Filename` / `FilePath` dynamic-text fields.
/// `None` for documents built in memory or read from a bare stream.
pub source_path: Option<String>,
/// DGN line-style definitions (`AcDbLSDefinition`), keyed by handle. Present
/// for drawings converted from MicroStation DGN, whose custom linetypes are
/// empty in the standard `LTYPE` table and defined here instead. Read-side
/// view; the objects stay verbatim as `ObjectType::Unknown` for round-trip.
/// See [`crate::objects::DgnLsDefinition`].
pub dgn_ls_definitions: HashMap<Handle, crate::objects::DgnLsDefinition>,
/// DGN line-style components (`AcDbLS{Compound,StrokePattern,Point,Symbol}
/// Component`), keyed by handle — the nodes of a [`crate::objects::DgnLsDefinition`]'s
/// component tree. Read-side view; objects stay verbatim as `Unknown`.
pub dgn_ls_components: HashMap<Handle, crate::objects::DgnLsComponent>,
/// Raw EED blobs per handle — populated during DWG read, consumed during DWG write.
/// Keyed by the object/table-entry handle. Not serialized.
pub(crate) eed_by_handle: HashMap<Handle, Vec<(u64, Vec<u8>)>>,
pub(crate) object_xdata: HashMap<Handle, crate::xdata::ExtendedData>,
/// Non-entity object xdictionary handles — populated during DWG read, consumed during DWG write.
pub(crate) xdic_by_handle: HashMap<Handle, Handle>,
/// Non-entity object reactors — populated during DWG read, consumed during DWG write.
pub(crate) reactors_by_handle: HashMap<Handle, Vec<Handle>>,
/// Original BLOCK_HEADER entity handles from the DWG binary — includes sub-entity handles
/// (vertices, faces, SEQENDs). Keyed by BlockRecord handle. Used by the writer to produce
/// correct owned_object_count without re-expanding from the document model.
pub(crate) block_entity_handles: HashMap<Handle, Vec<Handle>>,
/// DWG version this document was read from (set by the DWG reader).
/// Verbatim raw blobs (Unknown objects, EED) are encoded for this version
/// and cannot be re-emitted to a different encoding family without
/// corruption; the writer drops them on an incompatible cross-version save.
/// `None` when not loaded from DWG (new/DXF).
pub dwg_source_version: Option<DxfVersion>,
/// Embedded preview/thumbnail image. Populated by the DWG reader from the
/// file's preview section; the DWG writer embeds it when `Some` and emits an
/// empty preview when `None`. Not part of DXF.
pub preview: Option<Preview>,
/// Modeler-entity handles (3DSOLID/REGION/BODY/SURFACE) whose geometry is
/// stored as SAB blobs in the `AcDb:AcDsPrototype_1b` data-store section,
/// in object-stream (file-offset) order. Populated by the DWG reader so the
/// blob→entity attach step pairs each SAB blob with the correct entity
/// regardless of the document's handle-sorted entity order. Transient DWG
/// read artifact; empty for new/DXF documents.
pub(crate) acis_sab_handles: Vec<Handle>,
/// Original decompressed `AcDb:AcDsPrototype_1b` section. Same-version
/// saves can reuse it when every attached SAB body is still unchanged.
/// Shared so document snapshots do not duplicate large modeler data.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) raw_acds_data: Option<Arc<Vec<u8>>>,
/// Debug aid: every record of the source DWG, verbatim, keyed by handle
/// (type code, bytes). Only filled when `ACADRUST_RAW_ALL` is set in the
/// environment; the writer then re-emits these instead of re-serialising
/// so that a writer defect can be bisected by object type
/// (`ACADRUST_RAW_EXCLUDE`).
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) raw_records: HashMap<u64, (i16, Arc<crate::entities::RawRecord>)>,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) original_objects: HashMap<Handle, ObjectType>,
/// Child record -> compound entity handle, captured with `raw_records`.
/// Exclusions must serialize each compound entity and its children together.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) raw_record_owners: HashMap<u64, u64>,
/// `(handle, byte length, hash)` of SAB bodies when `raw_acds_data` was
/// captured. Used to reject stale section passthrough after geometry edits.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) raw_acds_fingerprint: Vec<(u64, usize, u64)>,
/// Non-entity objects whose source record points into the AcDs data store.
/// Retained for same-version saves together with the original section.
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) dwg_data_store_handles: HashSet<Handle>,
/// Section-view style (`AcDbSectionViewStyle`) display fields, decoded from
/// the DWG for rendering section marks (arrow size, label height, …). A file
/// normally has one; the first decoded is kept. `None` for new/DXF documents
/// or files without section views.
pub section_view_style: Option<crate::entities::SectionViewStyle>,
/// Model-documentation drawing-view graph, decoded from the DWG so section
/// marks can derive their true viewing direction. Empty for new/DXF files.
///
/// `AcDbViewRep` handle → its object-specific handle references (they
/// include the view's `AcDbViewBorder` entity, its template viewport, its
/// block reference, and — for the parent of a section — the section
/// symbol).
pub view_rep_refs: std::collections::HashMap<Handle, Vec<Handle>>,
/// `AcDbViewRep` handles that own an `AcDbViewRepSectionDefinition` —
/// i.e. the section (result) views.
pub section_view_reps: Vec<Handle>,
/// Next handle to assign
next_handle: u64,
}
impl CadDocument {
fn active_entity_change_recorder(&self) -> Option<Arc<EntityChangeRecorder>> {
let key = self as *const Self as usize;
ENTITY_CHANGE_RECORDERS.with(|recorders| recorders.borrow().get(&key).cloned())
}
fn record_entity_before(&self, handle: Handle, before: Option<Arc<EntityType>>) {
if let Some(recorder) = self.active_entity_change_recorder() {
recorder.record(handle, before);
}
}
/// Begin automatic first-touch recording for entity mutations performed
/// through this document's public mutation APIs.
pub fn begin_entity_change_recording(&mut self) -> Arc<EntityChangeRecorder> {
let key = self as *const Self as usize;
let recorder = Arc::new(EntityChangeRecorder::default());
ENTITY_CHANGE_RECORDERS.with(|recorders| {
recorders.borrow_mut().insert(key, Arc::clone(&recorder));
});
recorder
}
/// End automatic entity recording for this document.
pub fn end_entity_change_recording(&mut self) {
let key = self as *const Self as usize;
ENTITY_CHANGE_RECORDERS.with(|recorders| {
recorders.borrow_mut().remove(&key);
});
}
/// Record every currently stored entity without detaching any `Arc`.
/// Needed before a whole-document replacement such as CLEAR.
pub fn record_all_entities_for_transaction(&self) {
if let Some(recorder) = self.active_entity_change_recorder() {
for entity in &self.entities {
recorder.record(entity.common().handle, Some(Arc::clone(entity)));
}
}
}
/// Remove entity-add bookkeeping from a structure snapshot.
///
/// `add_entity` appends the new handle to an existing block record and
/// advances HANDSEED. Entity undo deliberately leaves that membership
/// dangling while the entity is absent, so redo can restore the flat store
/// without re-linking. Align those intrinsic add-side fields to the after
/// structure; unrelated block reorders/record creation remain undoable.
pub fn align_added_entity_structure(before: &mut Self, after: &Self, added_handles: &[Handle]) {
if added_handles.is_empty() {
return;
}
let added: std::collections::HashSet<Handle> = added_handles.iter().copied().collect();
before.next_handle = after.next_handle;
before.header.handle_seed = after.header.handle_seed;
for before_record in before.block_records.iter_mut() {
let Some(after_record) = after
.block_records
.iter()
.find(|record| record.handle == before_record.handle)
else {
continue;
};
let before_without_added: Vec<Handle> = before_record
.entity_handles
.iter()
.copied()
.filter(|handle| !added.contains(handle))
.collect();
let after_without_added: Vec<Handle> = after_record
.entity_handles
.iter()
.copied()
.filter(|handle| !added.contains(handle))
.collect();
if before_without_added == after_without_added {
before_record.entity_handles = after_record.entity_handles.clone();
}
}
}
/// Clone every document component except the flat entity store/index.
///
/// This is the structural half of a transaction snapshot: layers, tables,
/// block records, objects, header variables and handle allocation state are
/// preserved without walking or incrementing every entity `Arc`.
pub fn snapshot_structure(&mut self) -> Self {
let entities = std::mem::take(&mut self.entities);
let entity_index = std::mem::take(&mut self.entity_index);
let snapshot = self.clone();
self.entities = entities;
self.entity_index = entity_index;
snapshot
}
/// Swap a structure-only snapshot into the document while keeping the live
/// flat entity store/index. Returns the displaced structure as another
/// structure-only snapshot, so undo/redo can move the same allocation back
/// and forth without cloning it on every step.
pub fn swap_structure(&mut self, mut snapshot: Self) -> Self {
debug_assert!(snapshot.entities.is_empty());
debug_assert!(snapshot.entity_index.is_empty());
let entities = std::mem::take(&mut self.entities);
let entity_index = std::mem::take(&mut self.entity_index);
std::mem::swap(self, &mut snapshot);
self.entities = entities;
self.entity_index = entity_index;
snapshot
}
/// Create a new empty CAD document
pub fn new() -> Self {
let mut doc = CadDocument {
version: DxfVersion::AC1032, // DXF 2018
maintenance_version: 0,
header: HeaderVariables::default(),
layers: Table::new(),
line_types: Table::new(),
text_styles: Table::new(),
block_records: Table::new(),
dim_styles: Table::new(),
app_ids: Table::new(),
views: Table::new(),
vports: Table::new(),
ucss: Table::new(),
vx_table: Table::new(),
vx_control_entries: Vec::new(),
classes: DxfClassCollection::new(),
notifications: crate::notification::NotificationCollection::new(),
entities: Vec::new(),
entity_index: foldhash::HashMap::default(),
objects: HashMap::new(),
block_visibility_params: HashMap::new(),
context_scales: HashMap::new(),
block_representations: HashMap::new(),
fields: HashMap::new(),
summary_info: SummaryInfo::default(),
source_path: None,
dgn_ls_definitions: HashMap::new(),
dgn_ls_components: HashMap::new(),
eed_by_handle: HashMap::new(),
object_xdata: HashMap::new(),
xdic_by_handle: HashMap::new(),
reactors_by_handle: HashMap::new(),
block_entity_handles: HashMap::new(),
dwg_source_version: None,
preview: None,
acis_sab_handles: Vec::new(),
raw_acds_data: None,
raw_records: HashMap::new(),
original_objects: HashMap::new(),
raw_record_owners: HashMap::new(),
raw_acds_fingerprint: Vec::new(),
dwg_data_store_handles: HashSet::new(),
section_view_style: None,
view_rep_refs: std::collections::HashMap::new(),
section_view_reps: Vec::new(),
// Start handle allocation above reserved table handles (0x1-0xA)
// Table handles are well-known fixed values used by AutoCAD
next_handle: 0x10,
};
// Initialize with standard entries
doc.initialize_defaults();
doc
}
/// Create a document with a specific version
pub fn with_version(version: DxfVersion) -> Self {
let mut doc = Self::new();
doc.version = version;
doc
}
/// Rename a layer and every name-based reference to it.
pub fn rename_layer(
&mut self,
old_name: &str,
new_name: &str,
) -> std::result::Result<Handle, String> {
if old_name == new_name || !valid_symbol_table_name(new_name) {
return Err("Invalid layer rename".to_string());
}
let Some(source) = self.layers.get(old_name) else {
return Err(format!("Layer '{old_name}' does not exist"));
};
let source_name = source.name.clone();
let source_handle = source.handle;
let source_key = normalize_name(&source_name);
if source_key == "0"
|| source_key == normalize_name("Defpoints")
|| source_name.contains('|')
{
return Err(format!("Layer '{source_name}' cannot be renamed"));
}
let app_handles: HashMap<String, u64> = self
.app_ids
.iter()
.map(|app| (normalize_name(&app.name), app.handle.value()))
.collect();
let affected: Vec<Handle> = self
.entities
.iter()
.filter(|entity| {
let common = entity.common();
normalize_name(&common.layer) == source_key
|| common.extended_data.records().iter().any(|record| {
record.values.iter().any(|value| {
matches!(value, XDataValue::LayerName(name) if normalize_name(name) == source_key)
})
})
})
.map(|entity| entity.common().handle)
.collect();
let current = normalize_name(&self.header.current_layer_name) == source_key
|| (source_handle.is_valid() && self.header.current_layer_handle == source_handle);
self.layers.rename(&source_name, new_name.to_string())?;
let needs_handle = self
.layers
.get(new_name)
.is_some_and(|layer| !layer.handle.is_valid());
let layer_handle = if needs_handle {
let handle = self.allocate_handle();
self.layers.get_mut(new_name).unwrap().handle = handle;
handle
} else {
self.layers.get(new_name).unwrap().handle
};
self.rename_layer_state_references(&source_key, new_name);
for handle in affected {
if let Some(entity) = self.get_entity_mut(handle) {
let common = entity.common_mut();
if normalize_name(&common.layer) == source_key {
common.layer = new_name.to_string();
}
let mut changed_apps = Vec::new();
for record in common.extended_data.records_mut() {
let mut changed = false;
for value in &mut record.values {
let XDataValue::LayerName(name) = value else {
continue;
};
if normalize_name(name) == source_key {
*name = new_name.to_string();
changed = true;
}
}
if changed {
if let Some(handle) =
app_handles.get(&normalize_name(&record.application_name))
{
changed_apps.push(*handle);
}
}
}
if layer_handle != source_handle && !changed_apps.is_empty() {
common
.extended_data
.raw_dwg_eed
.retain(|(handle, _)| !changed_apps.contains(handle));
}
}
}
if current {
self.header.current_layer_name = new_name.to_string();
self.header.current_layer_handle = layer_handle;
}
Ok(layer_handle)
}
/// Whether writing this document to `target` would lose or corrupt data
/// that was captured verbatim from the source DWG version.
///
/// Unsupported objects (e.g. AEC/Civil3D), unknown graphical records and
/// EED blobs are stored as the source version's bytes; they can only be
/// re-emitted to the exact source version. When `target` differs the writer must drop
/// them, so a caller that wants a lossless round-trip should save in
/// [`dwg_source_version`](Self::dwg_source_version) instead. Returns false
/// when there is nothing version-locked (or the document is not from DWG).
pub fn has_version_locked_data(&self, target: DxfVersion) -> bool {
let src = match self.dwg_source_version {
Some(v) => v,
None => return false,
};
if src == target {
return false;
}
// Unsupported non-graphical objects preserved as raw bytes.
let raw_objects = self.objects.values().any(|o| {
matches!(
o,
crate::objects::ObjectType::Unknown {
raw_dwg_data: Some(_),
..
}
)
});
if raw_objects {
return true;
}
// Unknown graphical records + per-entity EED.
let raw_entities = self.entities.iter().any(|e| {
let raw = match e.as_ref() {
crate::entities::EntityType::Unknown(u) => u.raw_dwg_data.is_some(),
_ => false,
};
raw || !e.common().extended_data.raw_dwg_eed.is_empty()
});
raw_entities || self.eed_by_handle.values().any(|v| !v.is_empty())
}
/// Initialize default tables with standard entries
fn initialize_defaults(&mut self) {
// Allocate table control handles first (these are well-known handles in DWG)
self.header.block_control_handle = Handle::new(0x01);
self.header.layer_control_handle = Handle::new(0x02);
self.header.style_control_handle = Handle::new(0x03);
self.header.linetype_control_handle = Handle::new(0x05);
self.header.view_control_handle = Handle::new(0x06);
self.header.ucs_control_handle = Handle::new(0x07);
self.header.vport_control_handle = Handle::new(0x08);
self.header.appid_control_handle = Handle::new(0x09);
self.header.dimstyle_control_handle = Handle::new(0x0A);
self.header.vpent_hdr_control_handle = Handle::new(0x0B);
self.header.named_objects_dict_handle = Handle::new(0x0C);
// Assign allocated table control handles TO the Table objects so the
// object writer uses the same handles the header section references.
// Without this, Table<T>.handle() returns Handle::NULL and every
// table control is written with handle 0, not registered in the
// handle map, and unreachable by readers → "invalid data" for all objects.
self.block_records
.set_handle(self.header.block_control_handle);
self.layers.set_handle(self.header.layer_control_handle);
self.text_styles
.set_handle(self.header.style_control_handle);
self.line_types
.set_handle(self.header.linetype_control_handle);
self.views.set_handle(self.header.view_control_handle);
self.ucss.set_handle(self.header.ucs_control_handle);
self.vports.set_handle(self.header.vport_control_handle);
self.app_ids.set_handle(self.header.appid_control_handle);
self.dim_styles
.set_handle(self.header.dimstyle_control_handle);
self.vx_table
.set_handle(self.header.vpent_hdr_control_handle);
// Add standard layer "0"
let mut layer0 = Layer::layer_0();
layer0.set_handle(self.allocate_handle());
// Store the layer handle for CLAYER
self.header.current_layer_handle = layer0.handle;
self.layers.add(layer0).ok();
// Add standard line types
let mut continuous = LineType::continuous();
continuous.set_handle(self.allocate_handle());
self.header.continuous_linetype_handle = continuous.handle;
self.line_types.add(continuous).ok();
let mut by_layer = LineType::by_layer();
by_layer.set_handle(self.allocate_handle());
self.header.bylayer_linetype_handle = by_layer.handle;
self.header.current_linetype_handle = by_layer.handle; // Default linetype is ByLayer
self.line_types.add(by_layer).ok();
let mut by_block = LineType::by_block();
by_block.set_handle(self.allocate_handle());
self.header.byblock_linetype_handle = by_block.handle;
self.line_types.add(by_block).ok();
// Add standard text style
let mut standard_style = TextStyle::standard();
standard_style.set_handle(self.allocate_handle());
self.header.current_text_style_handle = standard_style.handle;
self.text_styles.add(standard_style).ok();
// Add model space and paper space blocks
let mut model_space = BlockRecord::model_space();
model_space.set_handle(self.allocate_handle());
model_space.block_entity_handle = self.allocate_handle();
model_space.block_end_handle = self.allocate_handle();
self.header.model_space_block_handle = model_space.handle;
self.block_records.add(model_space).ok();
let mut paper_space = BlockRecord::paper_space();
paper_space.set_handle(self.allocate_handle());
paper_space.block_entity_handle = self.allocate_handle();
paper_space.block_end_handle = self.allocate_handle();
self.header.paper_space_block_handle = paper_space.handle;
self.block_records.add(paper_space).ok();
// Add standard dimension style
let mut standard_dimstyle = DimStyle::standard();
standard_dimstyle.set_handle(self.allocate_handle());
// DIMTXSTY must reference the Standard text style
standard_dimstyle.dimtxsty_handle = self.header.current_text_style_handle;
self.header.current_dimstyle_handle = standard_dimstyle.handle;
// Header dim text style handle must also point to Standard
self.header.dim_text_style_handle = self.header.current_text_style_handle;
// Dim linetype handles: reference ByBlock linetype for R2007+
self.header.dim_linetype_handle = self.header.byblock_linetype_handle;
self.header.dim_linetype1_handle = self.header.byblock_linetype_handle;
self.header.dim_linetype2_handle = self.header.byblock_linetype_handle;
self.dim_styles.add(standard_dimstyle).ok();
// Add standard application ID
let mut acad = AppId::acad();
acad.set_handle(self.allocate_handle());
self.app_ids.add(acad).ok();
// Application ID under which annotative styles store their flag (XDATA).
let mut annotative = AppId::new("AcadAnnotative");
annotative.set_handle(self.allocate_handle());
self.app_ids.add(annotative).ok();
// Layer transparency is stored as AcCmTransparency XDATA/EED.
let mut layer_transparency = AppId::new("AcCmTransparency");
layer_transparency.set_handle(self.allocate_handle());
self.app_ids.add(layer_transparency).ok();
// ... and a layer description as AcAecLayerStandard XDATA/EED. On DWG
// an EED block is keyed by the application's handle, so the entry has
// to exist before a description can be written at all.
let mut layer_description = AppId::new(crate::tables::layer::LAYER_DESCRIPTION_APP);
layer_description.set_handle(self.allocate_handle());
self.app_ids.add(layer_description).ok();
// Add standard viewport
let mut active_vport = VPort::active();
active_vport.set_handle(self.allocate_handle());
self.vports.add(active_vport).ok();
// ── Standard dictionary objects (required for DWG format) ────
// Allocate handles for core dictionaries
self.header.acad_group_dict_handle = self.allocate_handle();
self.header.acad_mlinestyle_dict_handle = self.allocate_handle();
self.header.acad_layout_dict_handle = self.allocate_handle();
self.header.acad_plotsettings_dict_handle = self.allocate_handle();
self.header.acad_plotstylename_dict_handle = self.allocate_handle();
// R2004+/R2007+ dictionaries (AutoCAD requires these even if empty)
self.header.acad_material_dict_handle = self.allocate_handle();
self.header.acad_color_dict_handle = self.allocate_handle();
self.header.acad_visualstyle_dict_handle = self.allocate_handle();
// Allocate handles for objects that live inside dictionaries
let mleaderstyle_dict_handle = self.allocate_handle();
let tablestyle_dict_handle = self.allocate_handle();
let mlinestyle_std_handle = self.allocate_handle();
let mleaderstyle_std_handle = self.allocate_handle();
let tablestyle_std_handle = self.allocate_handle();
let model_layout_handle = self.allocate_handle();
let paper_layout_handle = self.allocate_handle();
let plotstylename_placeholder_handle = self.allocate_handle();
// Store the current MLineStyle handle in the header (for CMLSTYLE)
self.header.current_multiline_style_handle = mlinestyle_std_handle;
// Link block records to their layouts
if let Some(ms) = self.block_records.get_mut("*Model_Space") {
ms.layout = model_layout_handle;
}
if let Some(ps) = self.block_records.get_mut("*Paper_Space") {
ps.layout = paper_layout_handle;
}
// -- Root dictionary (NAMED_OBJECTS_DICTIONARY) --
let root_dict_handle = self.header.named_objects_dict_handle;
let mut root_dict = crate::objects::Dictionary::new();
root_dict.handle = root_dict_handle;
root_dict.owner = Handle::NULL; // owned by document
root_dict.add_entry("ACAD_GROUP", self.header.acad_group_dict_handle);
root_dict.add_entry("ACAD_MLINESTYLE", self.header.acad_mlinestyle_dict_handle);
root_dict.add_entry("ACAD_LAYOUT", self.header.acad_layout_dict_handle);
root_dict.add_entry(
"ACAD_PLOTSETTINGS",
self.header.acad_plotsettings_dict_handle,
);
root_dict.add_entry(
"ACAD_PLOTSTYLENAME",
self.header.acad_plotstylename_dict_handle,
);
root_dict.add_entry("ACAD_MATERIAL", self.header.acad_material_dict_handle);
root_dict.add_entry("ACAD_COLOR", self.header.acad_color_dict_handle);
root_dict.add_entry("ACAD_VISUALSTYLE", self.header.acad_visualstyle_dict_handle);
root_dict.add_entry("ACAD_MLEADERSTYLE", mleaderstyle_dict_handle);
root_dict.add_entry("ACAD_TABLESTYLE", tablestyle_dict_handle);
self.objects
.insert(root_dict_handle, ObjectType::Dictionary(root_dict));
// -- ACAD_GROUP dictionary (empty) --
let mut group_dict = crate::objects::Dictionary::new();
group_dict.handle = self.header.acad_group_dict_handle;
group_dict.owner = root_dict_handle;
self.objects
.insert(group_dict.handle, ObjectType::Dictionary(group_dict));
// -- ACAD_MLINESTYLE dictionary (contains "Standard") --
let mut mlinestyle_dict = crate::objects::Dictionary::new();
mlinestyle_dict.handle = self.header.acad_mlinestyle_dict_handle;
mlinestyle_dict.owner = root_dict_handle;
mlinestyle_dict.add_entry("Standard", mlinestyle_std_handle);
self.objects.insert(
mlinestyle_dict.handle,
ObjectType::Dictionary(mlinestyle_dict),
);
// -- MLineStyle Standard object --
let mut mlinestyle_std = crate::objects::MLineStyle::standard();
mlinestyle_std.handle = mlinestyle_std_handle;
mlinestyle_std.owner = self.header.acad_mlinestyle_dict_handle;
self.objects.insert(
mlinestyle_std_handle,
ObjectType::MLineStyle(mlinestyle_std),
);
// -- ACAD_MLEADERSTYLE dictionary (contains "Standard") --
let mut mleaderstyle_dict = crate::objects::Dictionary::new();
mleaderstyle_dict.handle = mleaderstyle_dict_handle;
mleaderstyle_dict.owner = root_dict_handle;
mleaderstyle_dict.add_entry("Standard", mleaderstyle_std_handle);
self.objects.insert(
mleaderstyle_dict_handle,
ObjectType::Dictionary(mleaderstyle_dict),
);
// -- MultiLeaderStyle Standard object --
let mut mleaderstyle_std = crate::objects::MultiLeaderStyle::standard();
mleaderstyle_std.handle = mleaderstyle_std_handle;
mleaderstyle_std.owner_handle = mleaderstyle_dict_handle;
mleaderstyle_std.text_style_handle = Some(self.header.current_text_style_handle);
self.objects.insert(
mleaderstyle_std_handle,
ObjectType::MultiLeaderStyle(mleaderstyle_std),
);
// -- ACAD_TABLESTYLE dictionary (contains "Standard") --
let mut tablestyle_dict = crate::objects::Dictionary::new();
tablestyle_dict.handle = tablestyle_dict_handle;
tablestyle_dict.owner = root_dict_handle;
tablestyle_dict.add_entry("Standard", tablestyle_std_handle);
self.objects.insert(
tablestyle_dict_handle,
ObjectType::Dictionary(tablestyle_dict),
);
// -- TableStyle Standard object --
let mut tablestyle_std = crate::objects::TableStyle::standard();
tablestyle_std.handle = tablestyle_std_handle;
tablestyle_std.owner_handle = tablestyle_dict_handle;
tablestyle_std.set_all_text_styles("Standard", Some(self.header.current_text_style_handle));
self.objects.insert(
tablestyle_std_handle,
ObjectType::TableStyle(tablestyle_std),
);
// -- ACAD_LAYOUT dictionary (Model + Layout1) --
let mut layout_dict = crate::objects::Dictionary::new();
layout_dict.handle = self.header.acad_layout_dict_handle;
layout_dict.owner = root_dict_handle;
layout_dict.add_entry("Model", model_layout_handle);
layout_dict.add_entry("Layout1", paper_layout_handle);
self.objects
.insert(layout_dict.handle, ObjectType::Dictionary(layout_dict));
// -- Layout: Model --
let mut model_layout = crate::objects::Layout::new("Model");
model_layout.handle = model_layout_handle;
model_layout.owner = self.header.acad_layout_dict_handle;
model_layout.tab_order = 0;
model_layout.flags = 1; // model space
model_layout.block_record = self.header.model_space_block_handle;
self.objects
.insert(model_layout_handle, ObjectType::Layout(model_layout));
// -- Layout: Layout1 (paper space) --
let mut paper_layout = crate::objects::Layout::new("Layout1");
paper_layout.handle = paper_layout_handle;
paper_layout.owner = self.header.acad_layout_dict_handle;
paper_layout.tab_order = 1;
paper_layout.block_record = self.header.paper_space_block_handle;
self.objects
.insert(paper_layout_handle, ObjectType::Layout(paper_layout));
// -- ACAD_PLOTSETTINGS dictionary (empty) --
let mut plotsettings_dict = crate::objects::Dictionary::new();
plotsettings_dict.handle = self.header.acad_plotsettings_dict_handle;
plotsettings_dict.owner = root_dict_handle;
self.objects.insert(
plotsettings_dict.handle,
ObjectType::Dictionary(plotsettings_dict),
);
// -- ACAD_MATERIAL dictionary (empty, required R2004+) --
let mut material_dict = crate::objects::Dictionary::new();
material_dict.handle = self.header.acad_material_dict_handle;
material_dict.owner = root_dict_handle;
self.objects
.insert(material_dict.handle, ObjectType::Dictionary(material_dict));
// -- ACAD_COLOR dictionary (empty, required R2004+) --
let mut color_dict = crate::objects::Dictionary::new();
color_dict.handle = self.header.acad_color_dict_handle;
color_dict.owner = root_dict_handle;
self.objects
.insert(color_dict.handle, ObjectType::Dictionary(color_dict));
// -- ACAD_VISUALSTYLE dictionary (empty, required R2007+) --
let mut visualstyle_dict = crate::objects::Dictionary::new();
visualstyle_dict.handle = self.header.acad_visualstyle_dict_handle;
visualstyle_dict.owner = root_dict_handle;
self.objects.insert(
visualstyle_dict.handle,
ObjectType::Dictionary(visualstyle_dict),
);
// -- ACAD_PLOTSTYLENAME dictionary (DictionaryWithDefault with PlaceHolder) --
let mut plotstyle_dict = crate::objects::DictionaryWithDefault::new();
plotstyle_dict.handle = self.header.acad_plotstylename_dict_handle;
plotstyle_dict.owner = root_dict_handle;
plotstyle_dict.default_handle = plotstylename_placeholder_handle;
plotstyle_dict
.entries
.push(("Normal".to_string(), plotstylename_placeholder_handle));
self.objects.insert(
plotstyle_dict.handle,
ObjectType::DictionaryWithDefault(plotstyle_dict),
);
// -- PlaceHolder for ACAD_PLOTSTYLENAME "Normal" --
let mut placeholder = crate::objects::PlaceHolder::new();
placeholder.handle = plotstylename_placeholder_handle;
placeholder.owner = self.header.acad_plotstylename_dict_handle;
self.objects.insert(
plotstylename_placeholder_handle,
ObjectType::PlaceHolder(placeholder),
);
// Register standard DXF classes required by the DWG format.
// For pre-R2004, "unlisted" object types (LAYOUT, PLOTSETTINGS, etc.)
// need a class entry so the writer can emit the class number instead of
// the R2004+ fixed type code.
use crate::classes::{DxfClass, ProxyFlags};
let standard_classes = [
DxfClass {
dxf_name: "ACDBDICTIONARYWDFLT".to_string(),
cpp_class_name: "AcDbDictionaryWithDefault".to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags: ProxyFlags::NONE,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0, // will be assigned (500+)
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
},
DxfClass {
dxf_name: "DICTIONARYVAR".to_string(),
cpp_class_name: "AcDbDictionaryVar".to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags: ProxyFlags::NONE,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0,
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
},
DxfClass {
dxf_name: "LAYOUT".to_string(),
cpp_class_name: "AcDbLayout".to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags: ProxyFlags::NONE,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0,
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
},
DxfClass {
dxf_name: "ACDBPLACEHOLDER".to_string(),
cpp_class_name: "AcDbPlaceHolder".to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags: ProxyFlags::NONE,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0,
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
},
DxfClass {
dxf_name: "PLOTSETTINGS".to_string(),
cpp_class_name: "AcDbPlotSettings".to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags: ProxyFlags::NONE,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0,
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
},
DxfClass {
dxf_name: "SCALE".to_string(),
cpp_class_name: "AcDbScale".to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags: ProxyFlags::NONE,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0,
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
},
];
for cls in standard_classes {
self.classes.add_or_update(cls);
}
// Register default DXF classes for all entity/object types.
// Unlisted types like MESH, MULTILEADER, IMAGE need class entries
// so the writer emits the correct 500+ type code instead of a
// wrong fixed code.
self.classes.update_defaults();
}
/// Ensure the CLASSES table carries the entry for an annotative
/// `AcDb*ObjectContextData` leaf class, so the DWG/DXF writer can emit its
/// 500+ class number. Call this when synthesizing a per-object annotation
/// context whose class the drawing does not already declare. No-op if the
/// class is already present or the name is unrecognised.
///
/// Deliberately *not* part of [`initialize_defaults`](Self::initialize_defaults):
/// the DWG writer emits every class in this table, so auto-registering these
/// would inject spurious CLASSES entries into files that carry no annotative
/// context objects.
pub fn register_object_context_class(&mut self, dxf_name: &str) {
let cpp = match dxf_name {
"ACDB_BLKREFOBJECTCONTEXTDATA_CLASS" => "AcDbBlkRefObjectContextData",
"ACDB_TEXTOBJECTCONTEXTDATA_CLASS" => "AcDbTextObjectContextData",
"ACDB_MTEXTOBJECTCONTEXTDATA_CLASS" => "AcDbMTextObjectContextData",
"ACDB_ALDIMOBJECTCONTEXTDATA_CLASS" => "AcDbAlignedDimensionObjectContextData",
"ACDB_ANGDIMOBJECTCONTEXTDATA_CLASS" => "AcDbAngularDimensionObjectContextData",
"ACDB_DMDIMOBJECTCONTEXTDATA_CLASS" => "AcDbDiametricDimensionObjectContextData",
"ACDB_RADIMOBJECTCONTEXTDATA_CLASS" => "AcDbRadialDimensionObjectContextData",
"ACDB_RADIMLGOBJECTCONTEXTDATA_CLASS" => "AcDbRadialDimensionLargeObjectContextData",
"ACDB_ORDDIMOBJECTCONTEXTDATA_CLASS" => "AcDbOrdinateDimensionObjectContextData",
"ACDB_HATCHSCALECONTEXTDATA_CLASS" => "AcDbHatchScaleContextData",
"ACDB_HATCHVIEWCONTEXTDATA_CLASS" => "AcDbHatchViewContextData",
_ => return,
};
if self.classes.get_by_name(dxf_name).is_some() {
return;
}
use crate::classes::{DxfClass, ProxyFlags};
// Erase | Cloning | DisablesProxyWarningDialog — the flags real files
// carry on these proxy classes.
let proxy_flags = ProxyFlags(
ProxyFlags::ERASE_ALLOWED.0
| ProxyFlags::CLONING_ALLOWED.0
| ProxyFlags::DISABLES_PROXY_WARNING_DIALOG.0,
);
self.classes.add_or_update(DxfClass {
dxf_name: dxf_name.to_string(),
cpp_class_name: cpp.to_string(),
application_name: "ObjectDBX Classes".to_string(),
proxy_flags,
instance_count: 0,
was_zombie: false,
is_an_entity: false,
class_number: 0,
item_class_id: 0x1F3,
dwg_version: 0,
maintenance_version: 0,
unknown1: 0,
unknown2: 0,
});
}
/// Allocate a new unique handle
pub fn allocate_handle(&mut self) -> Handle {
// The DWG reader inserts objects straight into `objects` without
// bumping `next_handle`, but it does fix `header.handle_seed` up to the
// true max+1. Respect that as a floor so a post-load add (a new
// linetype, a drawn entity) never re-issues a higher-handled existing
// object's handle — which silently overwrites it and corrupts the file.
if self.header.handle_seed > self.next_handle {
self.next_handle = self.header.handle_seed;
}
let handle = Handle::new(self.next_handle);
self.next_handle += 1;
// Keep HANDSEED in sync — DWG header requires this to be ≥ next_handle
self.header.handle_seed = self.next_handle;
handle
}
/// Advance the allocator above every stored record identity.
///
/// File readers populate tables and objects through several paths, not all
/// of which call `allocate_handle()`. Synchronizing before a repair pass
/// prevents freshly assigned handles from colliding with parsed records.
pub(crate) fn synchronize_handle_allocator(&mut self) {
let mut next_handle = self.next_handle;
macro_rules! include_handle {
($handle:expr) => {{
next_handle = next_handle.max($handle.value().saturating_add(1));
}};
}
macro_rules! include_table {
($table:expr) => {{
include_handle!($table.handle());
for entry in $table.iter() {
include_handle!(entry.handle());
}
}};
}
include_table!(self.layers);
include_table!(self.line_types);
include_table!(self.text_styles);
include_table!(self.dim_styles);
include_table!(self.app_ids);
include_table!(self.views);
include_table!(self.vports);
include_table!(self.ucss);
include_table!(self.vx_table);
include_table!(self.block_records);
for record in self.block_records.iter() {
include_handle!(record.block_entity_handle);
include_handle!(record.block_end_handle);
for handle in &record.entity_handles {
include_handle!(*handle);
}
}
for entity in &self.entities {
include_handle!(entity.common().handle);
}
for handle in self.objects.keys() {
include_handle!(*handle);
}
self.next_handle = next_handle;
self.header.handle_seed = self.header.handle_seed.max(next_handle);
}
/// Get the next handle value (without allocating)
pub fn next_handle(&self) -> u64 {
self.next_handle
}
fn entity_history_handle(&self, handle: Handle) -> Option<Handle> {
match self.get_entity(handle)? {
EntityType::Solid3D(value) => value.history_handle,
EntityType::Region(value) => value.history_handle,
EntityType::Body(value) => value.history_handle,
EntityType::Surface(value) => value.history_handle,
_ => None,
}
.filter(|value| value.is_valid())
}
fn set_entity_history_handle(&mut self, handle: Handle, history: Option<Handle>) -> bool {
match self.get_entity_mut(handle) {
Some(EntityType::Solid3D(value)) => value.history_handle = history,
Some(EntityType::Region(value)) => value.history_handle = history,
Some(EntityType::Body(value)) => value.history_handle = history,
Some(EntityType::Surface(value)) => value.history_handle = history,
_ => return false,
}
true
}
pub fn solid_history_graph(&self, entity: Handle) -> Option<SolidHistoryGraph> {
let root = self.entity_history_handle(entity)?;
let ObjectType::DynamicBlock(root_object) = self.objects.get(&root)? else {
return None;
};
if !matches!(root_object.data, DynamicBlockData::SolidHistory(_)) {
return None;
}
let mut nodes = self
.objects
.iter()
.filter_map(|(handle, object)| match object {
ObjectType::DynamicBlock(value)
if matches!(value.data, DynamicBlockData::SolidHistoryNode(_))
&& self.owner_chain_reaches(value.owner, root) =>
{
Some(*handle)
}
_ => None,
})
.collect::<Vec<_>>();
nodes.sort_by_key(|handle| {
let step = match self.objects.get(handle) {
Some(ObjectType::DynamicBlock(value)) => match &value.data {
DynamicBlockData::SolidHistoryNode(operation) => operation
.base()
.map(|base| base.step_id)
.unwrap_or(i32::MAX),
_ => i32::MAX,
},
_ => i32::MAX,
};
(step, handle.value())
});
let evaluation_graph = self.solid_history_evaluation_graph(root);
Some(SolidHistoryGraph {
root,
nodes,
evaluation_graph,
})
}
fn solid_history_evaluation_graph(&self, root: Handle) -> Option<Handle> {
let ObjectType::DynamicBlock(root_object) = self.objects.get(&root)? else {
return None;
};
let DynamicBlockData::SolidHistory(history) = &root_object.data else {
return None;
};
match self.objects.get(&history.owner) {
Some(ObjectType::DynamicBlock(value))
if matches!(value.data, DynamicBlockData::EvaluationGraph(_)) =>
{
Some(history.owner)
}
_ => None,
}
}
fn solid_history_node_operation(&self, handle: Handle) -> Option<&SolidHistoryOperation> {
match self.objects.get(&handle)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistoryNode(operation) => Some(operation),
_ => None,
},
_ => None,
}
}
fn solid_history_active_node(&self, graph: &SolidHistoryGraph) -> Option<Handle> {
let active = match self.objects.get(&graph.root)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistory(history) => history.history_node_id,
_ => return None,
},
_ => return None,
};
let mut matches = graph.nodes.iter().copied().filter(|handle| {
self.solid_history_node_operation(*handle)
.and_then(SolidHistoryOperation::base)
.is_some_and(|base| solid_history_node_id(base) == active)
});
let node = matches.next()?;
matches.next().is_none().then_some(node)
}
fn solid_history_graph_chain(&self, graph: &SolidHistoryGraph) -> Option<Vec<Handle>> {
let ObjectType::DynamicBlock(object) = self.objects.get(&graph.evaluation_graph?)? else {
return None;
};
let DynamicBlockData::EvaluationGraph(evaluation) = &object.data else {
return None;
};
let active = self.solid_history_active_node(graph)?;
let mut node = evaluation
.nodes
.iter()
.find(|node| node.expression == active)?;
let mut chain = Vec::new();
loop {
if chain.contains(&node.expression) {
return None;
}
chain.push(node.expression);
let first_in = node.node_data[0];
if first_in < 0 {
break;
}
let source = evaluation
.edges
.iter()
.find(|edge| edge.id == first_in)?
.source_node;
node = evaluation.nodes.iter().find(|node| node.id == source)?;
}
chain.reverse();
Some(chain)
}
pub(crate) fn ensure_solid_history_evaluation_graph(
&mut self,
entity: Handle,
) -> Option<SolidHistoryGraph> {
let graph = self.solid_history_graph(entity)?;
if graph.evaluation_graph.is_some() {
return Some(graph);
}
let chain = self.solid_history_operations(entity)?;
if chain.len() != graph.nodes.len() {
return None;
}
let handles = chain
.iter()
.map(|operation| {
let id = solid_history_node_id(operation.base()?);
graph.nodes.iter().copied().find(|handle| {
self.solid_history_node_operation(*handle)
.and_then(SolidHistoryOperation::base)
.is_some_and(|base| solid_history_node_id(base) == id)
})
})
.collect::<Option<Vec<_>>>()?;
let count = handles.len() as i32;
let evaluation = self.allocate_handle();
let mut nodes = Vec::with_capacity(handles.len());
let mut edges = Vec::new();
for (index, handle) in handles.iter().enumerate() {
let id = index as i32;
let incoming = if id > 0 { id - 1 } else { -1 };
let outgoing = if id + 1 < count { id } else { -1 };
nodes.push(BlockEvaluationNode {
id,
edge_flags: SOLID_HISTORY_NODE_FLAGS,
next_id: id + 1,
expression: *handle,
node_data: [incoming, incoming, outgoing, outgoing],
active_cycles: None,
});
if id + 1 < count {
edges.push(Self::solid_history_edge(id, id, id + 1));
}
let ObjectType::DynamicBlock(value) = self.objects.get_mut(handle)? else {
return None;
};
value.owner = evaluation;
if let DynamicBlockData::SolidHistoryNode(operation) = &mut value.data {
let base = operation.base_mut()?;
base.eval.node_id = id + 1;
base.eval.parent_id = SolidHistoryNodeBase::ROOT_PARENT;
}
}
self.insert_solid_history_evaluation_graph(
evaluation,
graph.root,
BlockEvaluationGraph {
first_node_id: count,
first_node_id_copy: count,
nodes,
edges,
},
);
if let Some(ObjectType::DynamicBlock(value)) = self.objects.get_mut(&graph.root) {
if let DynamicBlockData::SolidHistory(history) = &mut value.data {
history.owner = evaluation;
history.history_node_id = count;
}
}
self.solid_history_graph(entity)
}
pub(crate) fn legacy_solid_history_entities(&self) -> Vec<Handle> {
self.entities()
.map(|entity| entity.common().handle)
.filter(|handle| {
self.entity_history_handle(*handle).is_some_and(|root| {
matches!(self.objects.get(&root), Some(ObjectType::DynamicBlock(value))
if matches!(value.data, DynamicBlockData::SolidHistory(_)))
&& self.solid_history_evaluation_graph(root).is_none()
})
})
.collect()
}
fn solid_history_edge(id: i32, source: i32, destination: i32) -> BlockEvaluationEdge {
BlockEvaluationEdge {
id,
next_id: 0,
incoming_edge: 1,
source_node: source,
destination_node: destination,
outgoing_edges: [-1; 5],
}
}
fn insert_solid_history_evaluation_graph(
&mut self,
handle: Handle,
root: Handle,
graph: BlockEvaluationGraph,
) {
if !self.classes.contains("ACAD_EVALUATION_GRAPH") {
self.classes.add_or_update(crate::classes::DxfClass::new(
"ACAD_EVALUATION_GRAPH",
"AcDbEvalGraph",
));
}
let mut object = DynamicBlockObject::new("ACAD_EVALUATION_GRAPH", "AcDbEvalGraph");
object.handle = handle;
object.owner = root;
object.data = DynamicBlockData::EvaluationGraph(graph);
self.objects.insert(handle, ObjectType::DynamicBlock(object));
}
pub fn solid_history_operation(&self, entity: Handle) -> Option<&SolidHistoryOperation> {
let graph = self.solid_history_graph(entity)?;
let history_node_id = match self.objects.get(&graph.root)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistory(history) => history.history_node_id,
_ => return None,
},
_ => return None,
};
graph
.nodes
.iter()
.filter_map(|handle| match self.objects.get(handle) {
Some(ObjectType::DynamicBlock(value)) => match &value.data {
DynamicBlockData::SolidHistoryNode(operation) => Some(operation),
_ => None,
},
_ => None,
})
.find(|operation| {
operation.base().is_some_and(|base| {
if base.eval.node_id > 0 {
base.eval.node_id == history_node_id
} else {
base.step_id == history_node_id
}
})
})
.or_else(|| {
graph
.nodes
.last()
.and_then(|handle| match self.objects.get(handle) {
Some(ObjectType::DynamicBlock(value)) => match &value.data {
DynamicBlockData::SolidHistoryNode(operation) => Some(operation),
_ => None,
},
_ => None,
})
})
}
/// Return the active solid-history chain in root-to-active order.
///
/// Parent evaluation ids, rather than step ordering, determine the chain.
/// Missing, cyclic, or ambiguous links make the graph unusable.
pub fn solid_history_operations(&self, entity: Handle) -> Option<Vec<SolidHistoryOperation>> {
let graph = self.solid_history_graph(entity)?;
if graph.evaluation_graph.is_some() {
return self
.solid_history_graph_chain(&graph)?
.into_iter()
.map(|handle| self.solid_history_node_operation(handle).cloned())
.collect();
}
let active_step = match self.objects.get(&graph.root)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistory(history) => history.history_node_id,
_ => return None,
},
_ => return None,
};
let operations = graph
.nodes
.iter()
.filter_map(|handle| match self.objects.get(handle) {
Some(ObjectType::DynamicBlock(value)) => match &value.data {
DynamicBlockData::SolidHistoryNode(operation) => Some(operation),
_ => None,
},
_ => None,
})
.collect::<Vec<_>>();
let mut active_matches = operations.iter().copied().filter(|operation| {
operation.base().is_some_and(|base| {
if base.eval.node_id > 0 {
base.eval.node_id == active_step
} else {
base.step_id == active_step
}
})
});
let mut current = active_matches.next()?;
if active_matches.next().is_some() {
return None;
}
let mut reversed = Vec::new();
let mut visited = Vec::new();
loop {
let base = current.base()?;
let node_id = if base.eval.node_id > 0 {
base.eval.node_id
} else {
base.step_id
};
let parent_id = base.eval.parent_id;
if node_id <= 0 || visited.contains(&node_id) {
return None;
}
visited.push(node_id);
reversed.push((*current).clone());
if parent_id <= 0 {
break;
}
let mut parent_matches = operations.iter().copied().filter(|operation| {
operation.base().is_some_and(|candidate| {
let node_id = if candidate.eval.node_id > 0 {
candidate.eval.node_id
} else {
candidate.step_id
};
node_id == parent_id
})
});
current = parent_matches.next()?;
if parent_matches.next().is_some() {
return None;
}
}
reversed.reverse();
Some(reversed)
}
pub fn create_solid_history(
&mut self,
entity: Handle,
mut operation: SolidHistoryOperation,
) -> Option<SolidHistoryGraph> {
self.get_entity(entity)?;
let (dxf_name, cpp_class_name) = operation.class_names()?;
let base = operation.base_mut()?;
if base.step_id <= 0 {
base.step_id = 1;
}
// Node ids follow the evaluation graph: the first node is 1.
base.eval.node_id = 1;
base.eval.parent_id = SolidHistoryNodeBase::ROOT_PARENT;
self.delete_solid_history(entity);
let root = self.allocate_handle();
let evaluation = self.allocate_handle();
let node = self.allocate_handle();
if !self.classes.contains("ACSH_HISTORY_CLASS") {
self.classes.add_or_update(crate::classes::DxfClass::new(
"ACSH_HISTORY_CLASS",
"AcDbShHistory",
));
}
if !self.classes.contains(dxf_name) {
self.classes
.add_or_update(crate::classes::DxfClass::new(dxf_name, cpp_class_name));
}
let mut root_object = DynamicBlockObject::new("ACSH_HISTORY_CLASS", "AcDbShHistory");
root_object.handle = root;
root_object.owner = entity;
root_object.data = DynamicBlockData::SolidHistory(SolidHistory {
major: 1,
owner: evaluation,
history_node_id: 1,
record_history: self.header.record_solid_history,
..SolidHistory::default()
});
let mut node_object = DynamicBlockObject::new(dxf_name, cpp_class_name);
node_object.handle = node;
node_object.owner = evaluation;
node_object.data = DynamicBlockData::SolidHistoryNode(operation);
self.objects
.insert(root, ObjectType::DynamicBlock(root_object));
self.insert_solid_history_evaluation_graph(
evaluation,
root,
BlockEvaluationGraph {
first_node_id: 1,
first_node_id_copy: 1,
nodes: vec![BlockEvaluationNode {
id: 0,
edge_flags: SOLID_HISTORY_NODE_FLAGS,
next_id: 1,
expression: node,
node_data: [-1; 4],
active_cycles: None,
}],
edges: Vec::new(),
},
);
self.objects
.insert(node, ObjectType::DynamicBlock(node_object));
if !self.set_entity_history_handle(entity, Some(root)) {
self.objects.remove(&root);
self.objects.remove(&evaluation);
self.objects.remove(&node);
return None;
}
Some(SolidHistoryGraph {
root,
nodes: vec![node],
evaluation_graph: Some(evaluation),
})
}
/// Append a new operation to an entity's existing solid-history graph.
///
/// The existing root and nodes remain intact. The appended operation is
/// assigned a new step/evaluation id, linked to the active node, and made
/// the graph's active operation.
pub fn append_solid_history(
&mut self,
entity: Handle,
mut operation: SolidHistoryOperation,
) -> Option<SolidHistoryGraph> {
let (dxf_name, cpp_class_name) = operation.class_names()?;
self.solid_history_operations(entity)?;
let mut graph = self.ensure_solid_history_evaluation_graph(entity)?;
let evaluation = graph.evaluation_graph?;
let parent = self.solid_history_active_node(&graph)?;
let bases = graph
.nodes
.iter()
.filter_map(|handle| self.solid_history_node_operation(*handle)?.base())
.collect::<Vec<_>>();
let node_id = bases
.iter()
.map(|base| solid_history_node_id(base))
.max()
.unwrap_or(0)
.checked_add(1)?;
let step_id = bases
.iter()
.flat_map(|base| [base.step_id.max(0), base.eval.node_id.max(0)])
.max()
.unwrap_or(0)
.checked_add(1)?;
let base = operation.base_mut()?;
base.step_id = step_id;
base.eval.node_id = node_id;
base.eval.parent_id = SolidHistoryNodeBase::ROOT_PARENT;
let node = self.allocate_handle();
let ObjectType::DynamicBlock(object) = self.objects.get_mut(&evaluation)? else {
return None;
};
let DynamicBlockData::EvaluationGraph(evaluation_data) = &mut object.data else {
return None;
};
let source = evaluation_data
.nodes
.iter()
.position(|item| item.expression == parent)?;
// The active node is the latest result and so has no outgoing edge.
if evaluation_data.nodes[source].node_data[2] >= 0 {
return None;
}
let id = evaluation_data.nodes.iter().map(|item| item.id).max()? + 1;
let edge = evaluation_data
.edges
.iter()
.map(|item| item.id)
.max()
.map_or(0, |value| value + 1);
let source_id = evaluation_data.nodes[source].id;
evaluation_data.nodes[source].node_data[2] = edge;
evaluation_data.nodes[source].node_data[3] = edge;
evaluation_data.nodes.push(BlockEvaluationNode {
id,
edge_flags: SOLID_HISTORY_NODE_FLAGS,
next_id: id + 1,
expression: node,
node_data: [edge, edge, -1, -1],
active_cycles: None,
});
evaluation_data
.edges
.push(Self::solid_history_edge(edge, source_id, id));
evaluation_data.first_node_id = id + 1;
evaluation_data.first_node_id_copy = id + 1;
if !self.classes.contains(dxf_name) {
self.classes
.add_or_update(crate::classes::DxfClass::new(dxf_name, cpp_class_name));
}
let mut node_object = DynamicBlockObject::new(dxf_name, cpp_class_name);
node_object.handle = node;
node_object.owner = evaluation;
node_object.data = DynamicBlockData::SolidHistoryNode(operation);
self.objects
.insert(node, ObjectType::DynamicBlock(node_object));
if let Some(ObjectType::DynamicBlock(value)) = self.objects.get_mut(&graph.root) {
if let DynamicBlockData::SolidHistory(history) = &mut value.data {
history.history_node_id = node_id;
}
}
graph.nodes.push(node);
Some(graph)
}
pub fn update_solid_history(
&mut self,
entity: Handle,
mut operation: SolidHistoryOperation,
) -> Option<SolidHistoryOperation> {
let (dxf_name, cpp_class_name) = operation.class_names()?;
let graph = self.solid_history_graph(entity)?;
let current_id = match self.objects.get(&graph.root)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistory(history) => history.history_node_id,
_ => return None,
},
_ => return None,
};
let node = graph
.nodes
.iter()
.copied()
.find(|handle| match self.objects.get(handle) {
Some(ObjectType::DynamicBlock(value)) => match &value.data {
DynamicBlockData::SolidHistoryNode(current) => {
current.base().is_some_and(|base| {
if base.eval.node_id > 0 {
base.eval.node_id == current_id
} else {
base.step_id == current_id
}
})
}
_ => false,
},
_ => false,
})
.or_else(|| graph.nodes.last().copied())?;
let old_step = match self.objects.get(&node)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistoryNode(current) => current.base()?.step_id,
_ => return None,
},
_ => return None,
};
let base = operation.base_mut()?;
if base.step_id <= 0 {
base.step_id = old_step;
}
if base.eval.node_id <= 0 {
base.eval.node_id = base.step_id;
}
let step_id = base.step_id;
if !self.classes.contains(dxf_name) {
self.classes
.add_or_update(crate::classes::DxfClass::new(dxf_name, cpp_class_name));
}
if let Some(ObjectType::DynamicBlock(value)) = self.objects.get_mut(&graph.root) {
if let DynamicBlockData::SolidHistory(history) = &mut value.data {
history.history_node_id = step_id;
}
}
let ObjectType::DynamicBlock(value) = self.objects.get_mut(&node)? else {
return None;
};
value.dxf_name = dxf_name.to_string();
value.cpp_class_name = cpp_class_name.to_string();
let DynamicBlockData::SolidHistoryNode(current) = &mut value.data else {
return None;
};
Some(std::mem::replace(current, operation))
}
/// Replace one existing operation in the active history chain without
/// changing which node is active.
///
/// The operation's evaluation node id identifies the node to replace. Its
/// step id is used for older histories that do not carry evaluation ids.
pub fn update_solid_history_step(
&mut self,
entity: Handle,
mut operation: SolidHistoryOperation,
) -> Option<SolidHistoryOperation> {
let (dxf_name, cpp_class_name) = operation.class_names()?;
let chain = self.solid_history_operations(entity)?;
let graph = self.solid_history_graph(entity)?;
let replacement_base = operation.base()?;
let replacement_id = if replacement_base.eval.node_id > 0 {
replacement_base.eval.node_id
} else {
replacement_base.step_id
};
if replacement_id <= 0 {
return None;
}
let mut chain_matches = chain.iter().filter(|current| {
current.base().is_some_and(|base| {
let node_id = if base.eval.node_id > 0 {
base.eval.node_id
} else {
base.step_id
};
node_id == replacement_id
})
});
chain_matches.next()?;
if chain_matches.next().is_some() {
return None;
}
let mut node_matches = graph.nodes.iter().copied().filter(|handle| {
let Some(ObjectType::DynamicBlock(value)) = self.objects.get(handle) else {
return false;
};
let DynamicBlockData::SolidHistoryNode(current) = &value.data else {
return false;
};
current.base().is_some_and(|base| {
let node_id = if base.eval.node_id > 0 {
base.eval.node_id
} else {
base.step_id
};
node_id == replacement_id
})
});
let node = node_matches.next()?;
if node_matches.next().is_some() {
return None;
}
let current_base = match self.objects.get(&node)? {
ObjectType::DynamicBlock(value) => match &value.data {
DynamicBlockData::SolidHistoryNode(current) => current.base()?.clone(),
_ => return None,
},
_ => return None,
};
let replacement_base = operation.base_mut()?;
replacement_base.step_id = current_base.step_id;
replacement_base.eval.node_id = current_base.eval.node_id;
replacement_base.eval.parent_id = current_base.eval.parent_id;
if !self.classes.contains(dxf_name) {
self.classes
.add_or_update(crate::classes::DxfClass::new(dxf_name, cpp_class_name));
}
let ObjectType::DynamicBlock(value) = self.objects.get_mut(&node)? else {
return None;
};
value.dxf_name = dxf_name.to_string();
value.cpp_class_name = cpp_class_name.to_string();
let DynamicBlockData::SolidHistoryNode(current) = &mut value.data else {
return None;
};
Some(std::mem::replace(current, operation))
}
pub fn copy_solid_history(
&mut self,
source: Handle,
target: Handle,
) -> Option<SolidHistoryGraph> {
if source == target {
return self.solid_history_graph(source);
}
self.get_entity(target)?;
let graph = self.solid_history_graph(source)?;
let mut source_handles = Vec::with_capacity(graph.nodes.len() + 2);
source_handles.push(graph.root);
source_handles.extend(graph.evaluation_graph);
source_handles.extend(graph.nodes.iter().copied());
let source_objects = source_handles
.iter()
.map(|handle| Some((*handle, self.objects.get(handle)?.clone())))
.collect::<Option<Vec<_>>>()?;
if self.entity_history_handle(target) == Some(graph.root) {
self.set_entity_history_handle(target, None);
} else {
self.delete_solid_history(target);
}
let mut remap = HashMap::new();
for (handle, _) in &source_objects {
remap.insert(*handle, self.allocate_handle());
}
let new_root = remap[&graph.root];
let mut new_nodes = Vec::with_capacity(graph.nodes.len());
for (old_handle, mut object) in source_objects {
let new_handle = remap[&old_handle];
let ObjectType::DynamicBlock(value) = &mut object else {
return None;
};
value.handle = new_handle;
if old_handle == graph.root {
value.owner = target;
// Without an evaluation graph (older releases of this crate)
// the root's handle names the solid.
if graph.evaluation_graph.is_none() {
if let DynamicBlockData::SolidHistory(history) = &mut value.data {
history.owner = target;
}
}
} else {
value.owner = remap.get(&value.owner).copied().unwrap_or(value.owner);
if Some(old_handle) != graph.evaluation_graph {
new_nodes.push(new_handle);
}
}
value.visit_handles_mut(&mut |handle| {
if let Some(mapped) = remap.get(handle) {
*handle = *mapped;
}
});
self.objects.insert(new_handle, object);
// Node XDATA (e.g. loft end-profile data) travels with the node.
if let Some(eed) = self.eed_by_handle.get(&old_handle).cloned() {
self.eed_by_handle.insert(new_handle, eed);
}
if let Some(xdata) = self.object_xdata.get(&old_handle).cloned() {
self.object_xdata.insert(new_handle, xdata);
}
}
let new_evaluation = graph.evaluation_graph.map(|handle| remap[&handle]);
if !self.set_entity_history_handle(target, Some(new_root)) {
self.objects.remove(&new_root);
for handle in new_nodes.iter().chain(&new_evaluation) {
self.objects.remove(handle);
}
return None;
}
Some(SolidHistoryGraph {
root: new_root,
nodes: new_nodes,
evaluation_graph: new_evaluation,
})
}
pub fn delete_solid_history(&mut self, entity: Handle) -> Vec<(Handle, ObjectType)> {
let Some(root) = self.entity_history_handle(entity) else {
return Vec::new();
};
let mut handles = self
.objects
.keys()
.copied()
.filter(|handle| self.owner_chain_reaches(*handle, root))
.collect::<Vec<_>>();
handles.sort_by_key(|handle| handle.value());
let removed = handles
.into_iter()
.filter_map(|handle| self.objects.remove(&handle).map(|value| (handle, value)))
.collect();
self.set_entity_history_handle(entity, None);
removed
}
/// Add an entity to the document (model space).
///
/// The entity is stored in both the flat entity map (used by the DXF
/// writer) and the *Model_Space block record (used by the DWG writer).
pub fn add_entity(&mut self, mut entity: EntityType) -> Result<Handle> {
entity.common_mut().raw_record = None; // (re)placed in the document: owner/handle may differ from the source bytes
// Allocate a handle if the entity doesn't have one
let handle = if entity.common().handle.is_null() {
let h = self.allocate_handle();
entity.as_entity_mut().set_handle(h);
h
} else {
let h = entity.common().handle;
// Ensure the handle counter stays above this handle so
// future allocations (e.g., vertex sub-entities) don't
// collide with it.
if h.value() >= self.next_handle {
self.next_handle = h.value() + 1;
self.header.handle_seed = self.header.handle_seed.max(self.next_handle);
}
h
};
self.record_entity_before(handle, None);
// Default an unowned entity to model space — or paper space when it
// carries the paper-space flag (R12 code 67 → entity_mode 1). Without
// the paper-space branch, R12 paper-space entities (layout viewports,
// etc.) fall into model space.
let ms_handle = self.header.model_space_block_handle;
let ps_handle = self.header.paper_space_block_handle;
if entity.common().owner_handle.is_null() {
let target = if entity.common().entity_mode == Some(1) && !ps_handle.is_null() {
ps_handle
} else {
ms_handle
};
if !target.is_null() {
entity.common_mut().owner_handle = target;
}
}
// AttributeEntity is a sub-entity owned by INSERT, not a direct
// block-record child. Never add it to entity_handles.
// Block/BlockEnd are structural markers with separate handle fields.
let is_excluded = matches!(
&entity,
EntityType::AttributeEntity(_) | EntityType::Block(_) | EntityType::BlockEnd(_)
);
// Route entity handle to the correct block record based on owner handle.
let owner = entity.common().owner_handle;
let mut added_to_block = false;
if !is_excluded && !owner.is_null() {
for br in self.block_records.iter_mut() {
if br.handle == owner {
br.entity_handles.push(handle);
added_to_block = true;
break;
}
}
}
// Fallback: add to *Model_Space if owner didn't match any block record
if !is_excluded && !added_to_block {
if let Some(ms) = self.block_records.get_mut("*Model_Space") {
ms.entity_handles.push(handle);
// Fix the entity's owner so the writer can determine
// entity_mode correctly (model-space = 2).
entity.common_mut().owner_handle = ms.handle;
}
}
// Store in the flat entity map (DXF writer reads from here)
let idx = self.entities.len();
self.entities.push(Arc::new(entity));
self.entity_index.insert(handle, idx);
Ok(handle)
}
/// Reserve and append entities decoded by the DWG loader without routing
/// each one through a linear block-record scan. The loader rebuilds block
/// membership once after all owner handles are available.
pub(crate) fn reserve_loaded_entities(&mut self, additional: usize) {
self.entities.reserve(additional);
self.entity_index.reserve(additional);
}
pub(crate) fn add_loaded_entity(&mut self, mut entity: EntityType) -> Handle {
let handle = if entity.common().handle.is_null() {
let handle = self.allocate_handle();
entity.as_entity_mut().set_handle(handle);
handle
} else {
let handle = entity.common().handle;
if handle.value() >= self.next_handle {
self.next_handle = handle.value() + 1;
self.header.handle_seed = self.header.handle_seed.max(self.next_handle);
}
handle
};
let index = self.entities.len();
self.entities.push(Arc::new(entity));
self.entity_index.insert(handle, index);
handle
}
pub(crate) fn add_loaded_entity_batch(&mut self, entities: &mut Vec<Arc<EntityType>>) {
if entities.is_empty() {
return;
}
let mut next_handle = self.next_handle.max(self.header.handle_seed);
for entity in entities.iter_mut() {
let handle = entity.common().handle;
if handle.is_null() {
let handle = Handle::new(next_handle);
next_handle += 1;
Arc::make_mut(entity).as_entity_mut().set_handle(handle);
} else {
next_handle = next_handle.max(handle.value() + 1);
}
}
let base = self.entities.len();
self.entities.append(entities);
for (offset, entity) in self.entities[base..].iter().enumerate() {
self.entity_index
.insert(entity.common().handle, base + offset);
}
self.next_handle = next_handle;
self.header.handle_seed = self.header.handle_seed.max(next_handle);
}
/// Get an entity by handle
pub fn get_entity(&self, handle: Handle) -> Option<&EntityType> {
self.entity_index
.get(&handle)
.map(|&idx| self.entities[idx].as_ref())
}
/// Get a shared entity image without cloning its geometry.
///
/// History/transaction users can retain this `Arc` as a before/after image.
/// A later [`get_entity_mut`](Self::get_entity_mut) call copy-on-writes only
/// that entity, leaving the retained image unchanged.
pub fn get_entity_arc(&self, handle: Handle) -> Option<Arc<EntityType>> {
let idx = *self.entity_index.get(&handle)?;
Some(Arc::clone(&self.entities[idx]))
}
/// Get a mutable entity by handle. Copies just this entity out of any shared
/// Arc (`Arc::make_mut`), so an undo snapshot that shares it keeps the old
/// value while the live doc gets a private, mutable copy.
pub fn get_entity_mut(&mut self, handle: Handle) -> Option<&mut EntityType> {
let idx = *self.entity_index.get(&handle)?;
self.record_entity_before(handle, Some(Arc::clone(&self.entities[idx])));
let entity = Arc::make_mut(&mut self.entities[idx]);
entity.common_mut().raw_record = None; // may be modified: verbatim bytes no longer trustworthy
Some(entity)
}
/// Replace an existing entity with a shared image, preserving its storage
/// slot and block-record membership.
pub fn replace_entity_arc(
&mut self,
handle: Handle,
entity: Arc<EntityType>,
) -> Option<Arc<EntityType>> {
if entity.common().handle != handle {
return None;
}
let idx = *self.entity_index.get(&handle)?;
self.record_entity_before(handle, Some(Arc::clone(&self.entities[idx])));
Some(std::mem::replace(&mut self.entities[idx], entity))
}
/// Restore an entity removed by [`remove_entity_arc`](Self::remove_entity_arc)
/// without adding its handle to a block record again.
///
/// Removal deliberately leaves the original block-record membership in
/// place. Re-linking through `add_entity` would duplicate that handle and
/// would require an O(all block members) cleanup pass. This method restores
/// only the flat entity storage/index and therefore keeps the exact existing
/// owner membership.
pub fn restore_entity_arc(&mut self, entity: Arc<EntityType>) -> Option<Handle> {
let handle = entity.common().handle;
if handle.is_null() || self.entity_index.contains_key(&handle) {
return None;
}
self.record_entity_before(handle, None);
if handle.value() >= self.next_handle {
self.next_handle = handle.value() + 1;
self.header.handle_seed = self.header.handle_seed.max(self.next_handle);
}
let idx = self.entities.len();
self.entities.push(entity);
self.entity_index.insert(handle, idx);
Some(handle)
}
/// Explode an entity into simpler primitives, allocating valid handles.
///
/// Each resulting entity receives a unique handle from the document's
/// handle allocator and inherits the original entity's owner handle.
/// The caller can then add the returned entities to the document via
/// [`add_entity`](Self::add_entity) or use them directly.
///
/// Returns an empty `Vec` for atomic entities that cannot be decomposed.
pub fn explode_entity(&mut self, entity: &EntityType) -> Vec<EntityType> {
let mut parts = entity.explode();
let owner = entity.common().owner_handle;
for part in &mut parts {
let h = self.allocate_handle();
part.as_entity_mut().set_handle(h);
if !owner.is_null() && part.common().owner_handle.is_null() {
part.common_mut().owner_handle = owner;
}
}
parts
}
/// Add an entity to the default paper space (`*Paper_Space` / "Layout1").
///
/// This sets the entity's owner to the `*Paper_Space` block record and
/// stores it there. Viewports must be placed in paper space to be
/// visible in a layout.
///
/// For documents with multiple layouts, use
/// [`add_entity_to_layout`](Self::add_entity_to_layout) instead.
pub fn add_paper_space_entity(&mut self, entity: EntityType) -> Result<Handle> {
self.add_entity_to_block(entity, "*Paper_Space")
}
/// Add an entity to a named layout.
///
/// Looks up the [`Layout`](crate::objects::Layout) object by name (e.g.
/// `"Layout1"`, `"Layout2"`) and adds the entity to the layout's
/// backing block record. Returns an error if the layout is not found.
///
/// # Example
/// ```ignore
/// use acadrust::entities::{Viewport, EntityType};
///
/// let vp = Viewport::new();
/// document.add_entity_to_layout(EntityType::Viewport(vp), "Layout1")?;
/// ```
pub fn add_entity_to_layout(
&mut self,
mut entity: EntityType,
layout_name: &str,
) -> Result<Handle> {
if let EntityType::Viewport(viewport) = &mut entity {
if viewport.id > 1 && viewport.frozen_layers.is_empty() {
viewport.frozen_layers = self
.layers
.iter()
.filter(|layer| layer.flags.frozen_in_new_viewport)
.map(|layer| layer.handle)
.collect();
}
}
// Find the Layout object by name to get its block_record handle
let block_handle = self
.objects
.values()
.find_map(|obj| match obj {
ObjectType::Layout(layout) if layout.name == layout_name => {
Some(layout.block_record)
}
_ => None,
})
.ok_or_else(|| {
crate::error::DxfError::Custom(format!("Layout '{}' not found", layout_name))
})?;
// Find the block record name for this handle
let block_name = self
.block_records
.iter()
.find(|br| br.handle == block_handle)
.map(|br| br.name().to_string())
.ok_or_else(|| {
crate::error::DxfError::Custom(format!(
"Block record for layout '{}' not found",
layout_name
))
})?;
let is_viewport = matches!(&entity, EntityType::Viewport(_));
let handle = self.add_entity_to_block(entity, &block_name)?;
if is_viewport {
if let Some(ObjectType::Layout(layout)) = self.objects.values_mut().find(|object| {
matches!(
object,
ObjectType::Layout(layout)
if layout.name == layout_name
)
}) {
if !layout.viewports.contains(&handle) {
layout.viewports.push(handle);
}
if layout.viewport.is_null() {
layout.viewport = handle;
}
}
}
Ok(handle)
}
/// Add an entity to a named block record.
///
/// Sets the entity's owner handle and routes it to the specified block
/// record. Used internally by [`add_entity`](Self::add_entity),
/// [`add_paper_space_entity`](Self::add_paper_space_entity), and
/// [`add_entity_to_layout`](Self::add_entity_to_layout).
fn add_entity_to_block(&mut self, mut entity: EntityType, block_name: &str) -> Result<Handle> {
entity.common_mut().raw_record = None;
// Allocate a handle if the entity doesn't have one
let handle = if entity.common().handle.is_null() {
let h = self.allocate_handle();
entity.as_entity_mut().set_handle(h);
h
} else {
let h = entity.common().handle;
if h.value() >= self.next_handle {
self.next_handle = h.value() + 1;
self.header.handle_seed = self.header.handle_seed.max(self.next_handle);
}
h
};
self.record_entity_before(handle, None);
// Set owner to the target block record
if let Some(br) = self.block_records.get(block_name) {
entity.common_mut().owner_handle = br.handle;
}
// Route entity handle to the block record
let owner = entity.common().owner_handle;
let mut added_to_block = false;
if !owner.is_null() {
for br in self.block_records.iter_mut() {
if br.handle == owner {
br.entity_handles.push(handle);
added_to_block = true;
break;
}
}
}
if !added_to_block {
if let Some(target) = self.block_records.get_mut(block_name) {
target.entity_handles.push(handle);
}
}
// Store in the flat entity map
let idx = self.entities.len();
self.entities.push(Arc::new(entity));
self.entity_index.insert(handle, idx);
Ok(handle)
}
/// Remove an entity by handle while retaining its shared allocation.
///
/// The owner block record intentionally keeps the handle so an undo can
/// restore the flat entity storage with [`restore_entity_arc`](Self::restore_entity_arc)
/// without scanning or rewriting large block membership lists.
pub fn remove_entity_arc(&mut self, handle: Handle) -> Option<Arc<EntityType>> {
let idx = *self.entity_index.get(&handle)?;
self.record_entity_before(handle, Some(Arc::clone(&self.entities[idx])));
self.entity_index.remove(&handle);
let entity = self.entities.swap_remove(idx);
// If the swap moved an element, update its index
if idx < self.entities.len() {
let moved_handle = self.entities[idx].common().handle;
self.entity_index.insert(moved_handle, idx);
}
Some(entity)
}
/// Remove an entity by handle
pub fn remove_entity(&mut self, handle: Handle) -> Option<EntityType> {
let entity = self.remove_entity_arc(handle)?;
// Hand back an owned entity: take it out of the Arc if we hold the last
// reference (a snapshot may still share it), else clone.
Some(Arc::try_unwrap(entity).unwrap_or_else(|a| (*a).clone()))
}
/// Add a new paper space layout to the document.
///
/// Creates the backing `*Paper_Space<N>` block record, a [`Layout`]
/// object, and registers both in the ACAD_LAYOUT dictionary. Returns
/// the layout handle.
///
/// # Example
/// ```ignore
/// let layout_handle = document.add_layout("Layout2")?;
/// // Then add entities to it:
/// document.add_entity_to_layout(EntityType::Viewport(vp), "Layout2")?;
/// ```
pub fn add_layout(&mut self, name: &str) -> Result<Handle> {
// Check for duplicate layout name
let already_exists = self
.objects
.values()
.any(|obj| matches!(obj, ObjectType::Layout(l) if l.name == name));
if already_exists {
return Err(crate::error::DxfError::Custom(format!(
"Layout '{}' already exists",
name
)));
}
// Determine the next *Paper_Space block name.
// AutoCAD uses: *Paper_Space, *Paper_Space0, *Paper_Space1, …
let ps_count = self
.block_records
.iter()
.filter(|br| br.is_paper_space())
.count();
let block_name = if ps_count == 0 {
"*Paper_Space".to_string()
} else {
format!("*Paper_Space{}", ps_count - 1)
};
// Create the block record
let mut block_record = BlockRecord::new(&block_name);
block_record.set_handle(self.allocate_handle());
block_record.block_entity_handle = self.allocate_handle();
block_record.block_end_handle = self.allocate_handle();
let br_handle = block_record.handle;
// Create the Layout object
let layout_handle = self.allocate_handle();
let mut layout = crate::objects::Layout::new(name);
layout.handle = layout_handle;
layout.owner = self.header.acad_layout_dict_handle;
layout.tab_order = ps_count as i16 + 1;
layout.block_record = br_handle;
// Link block record → layout
block_record.layout = layout_handle;
self.block_records
.add(block_record)
.map_err(|e| crate::error::DxfError::Custom(e))?;
// Create the overall paper space viewport (ID=1) for this layout.
// Every paper space layout requires this entity.
let mut overall_vp = crate::entities::Viewport::new();
overall_vp.id = 1;
overall_vp.status = crate::entities::ViewportStatusFlags::default_on();
let overall_vp_handle = self.allocate_handle();
overall_vp.common.handle = overall_vp_handle;
overall_vp.common.owner_handle = br_handle;
layout.viewport = overall_vp_handle;
layout.viewports.push(overall_vp_handle);
if let Some(br) = self.block_records.get_mut(&block_name) {
br.entity_handles.push(overall_vp_handle);
}
self.record_entity_before(overall_vp_handle, None);
let idx = self.entities.len();
self.entities
.push(Arc::new(EntityType::Viewport(overall_vp)));
self.entity_index.insert(overall_vp_handle, idx);
// Register in ACAD_LAYOUT dictionary
if let Some(ObjectType::Dictionary(dict)) =
self.objects.get_mut(&self.header.acad_layout_dict_handle)
{
dict.add_entry(name, layout_handle);
}
// Store the Layout object
self.objects
.insert(layout_handle, ObjectType::Layout(layout));
Ok(layout_handle)
}
pub fn ensure_model_layout(&mut self) {
// Layouts name their record; a record left without the back link
// (R13/R14 block headers have none) takes it from its layout.
let owners: HashMap<Handle, Handle> = self
.objects
.iter()
.filter_map(|(handle, object)| match object {
ObjectType::Layout(layout) => Some((layout.block_record, *handle)),
_ => None,
})
.collect();
for record in self.block_records.iter_mut() {
if !matches!(self.objects.get(&record.layout), Some(ObjectType::Layout(_))) {
record.layout = owners.get(&record.handle).copied().unwrap_or(Handle::NULL);
}
}
let Some(model) = self
.block_records
.iter()
.find(|record| record.is_model_space())
.map(|record| record.handle)
else {
return;
};
let has_layout = self.objects.values().any(|object| {
matches!(object, ObjectType::Layout(layout) if layout.block_record == model)
});
if has_layout {
return;
}
let dict_handle = self.header.acad_layout_dict_handle;
let dict_handle = if matches!(self.objects.get(&dict_handle), Some(ObjectType::Dictionary(_))) {
dict_handle
} else {
let handle = self.allocate_handle();
let root = self.header.named_objects_dict_handle;
let mut dict = crate::objects::Dictionary::new();
dict.handle = handle;
dict.owner = root;
if let Some(ObjectType::Dictionary(root)) = self.objects.get_mut(&root) {
root.add_entry("ACAD_LAYOUT", handle);
}
self.objects.insert(handle, ObjectType::Dictionary(dict));
self.header.acad_layout_dict_handle = handle;
handle
};
let handle = self.allocate_handle();
let mut layout = crate::objects::Layout::new("Model");
layout.handle = handle;
layout.owner = dict_handle;
layout.tab_order = 0;
layout.flags = 1; // model space
layout.block_record = model;
if let Some(ObjectType::Dictionary(dict)) = self.objects.get_mut(&dict_handle) {
dict.add_entry("Model", handle);
}
if let Some(record) = self.block_records.iter_mut().find(|r| r.handle == model) {
record.layout = handle;
}
self.objects.insert(handle, ObjectType::Layout(layout));
}
/// Get the number of entities.
///
/// Structural BLOCK/ENDBLK markers are not counted — they delimit block
/// definitions and are emitted from block records, not the entity list.
pub fn entity_count(&self) -> usize {
self.entities().count()
}
/// Iterate over all drawing entities.
///
/// Structural BLOCK/ENDBLK markers are stored in the backing vector (the
/// DWG reader records them so block base points etc. survive a round-trip)
/// but are hidden here: they are block delimiters, not drawing entities, so
/// a freshly-built document and a round-tripped one report the same set.
///
/// Note that this covers *every* entity in the document, including geometry
/// stored inside block definitions (the BLOCKS section). CAD applications
/// only draw model-space (and paper-space) entities plus inserted block
/// references, so use [`model_space_entities`](Self::model_space_entities)
/// or [`entities_in_block`](Self::entities_in_block) to iterate the drawable
/// set (issue #52).
pub fn entities(&self) -> impl Iterator<Item = &EntityType> {
self.entities
.iter()
.map(|e| e.as_ref())
.filter(|e| !matches!(e, EntityType::Block(_) | EntityType::BlockEnd(_)))
}
/// Iterate over all entities mutably. Copy-on-write per entity: iterating
/// this after an undo snapshot detaches each entity from the shared Arc, so
/// it is O(entities) deep only for bulk passes (save prep, handle reassign),
/// not the single-entity edit path (which uses `get_entity_mut`).
pub fn entities_mut(&mut self) -> impl Iterator<Item = &mut EntityType> {
if let Some(recorder) = self.active_entity_change_recorder() {
for entity in &self.entities {
recorder.record(entity.common().handle, Some(Arc::clone(entity)));
}
}
self.entities.iter_mut().map(|entity| { let e = Arc::make_mut(entity); e.common_mut().raw_record = None; e })
}
/// Like [`entities_mut`](Self::entities_mut) but keeps `raw_record`: for
/// read-time passes that only fill in *derived* fields (names resolved from
/// handles, colour-book lookups) and never change what the record encodes.
pub(crate) fn entities_mut_keep_raw(&mut self) -> impl Iterator<Item = &mut EntityType> {
if let Some(recorder) = self.active_entity_change_recorder() {
for entity in &self.entities {
recorder.record(entity.common().handle, Some(Arc::clone(entity)));
}
}
self.entities.iter_mut().map(Arc::make_mut)
}
/// Iterate over the entities belonging to a named block record.
///
/// This is the set of entities a CAD application associates with that
/// block — for `*Model_Space` (and the `*Paper_Space*` layout records)
/// this is what gets drawn; for regular block names it is the geometry of
/// the block *definition*, which is only rendered when the block is
/// INSERTed (issue #52).
pub fn entities_in_block(&self, block_name: &str) -> impl Iterator<Item = &EntityType> + '_ {
self.block_records
.get(block_name)
.into_iter()
.flat_map(|br| br.entity_handles.iter())
.filter_map(|handle| self.get_entity(*handle))
}
/// Iterate over the model-space entities — the primary drawable set.
///
/// Equivalent to [`entities_in_block`](Self::entities_in_block) for
/// `*Model_Space`. Block-definition geometry and paper-space entities are
/// excluded, matching what CAD applications render by default (issue #52).
pub fn model_space_entities(&self) -> impl Iterator<Item = &EntityType> + '_ {
self.entities_in_block("*Model_Space")
}
/// Owner handle of a database object, for ownership-chain walks.
///
/// Dynamic-block, associative and context records are normally reached
/// through several typed dictionaries/objects. Keeping this exhaustive for
/// native object families lets consumers resolve those graphs without
/// depending on their original raw-object representation.
pub fn object_owner(&self, h: Handle) -> Option<Handle> {
match self.objects.get(&h)? {
ObjectType::Dictionary(d) => Some(d.owner),
ObjectType::Layout(value) => Some(value.owner),
ObjectType::XRecord(value) => Some(value.owner),
ObjectType::Group(value) => Some(value.owner),
ObjectType::MLineStyle(value) => Some(value.owner),
ObjectType::ImageDefinition(value) => Some(value.owner),
ObjectType::PlotSettings(value) => Some(value.owner),
ObjectType::MultiLeaderStyle(value) => Some(value.owner_handle),
ObjectType::TableStyle(value) => Some(value.owner_handle),
ObjectType::TableContent(value) => Some(value.common.owner_handle),
ObjectType::Scale(value) => Some(value.owner_handle),
ObjectType::ObjectContextData(value) => Some(value.owner_handle),
ObjectType::SortEntitiesTable(value) => Some(value.owner_handle),
ObjectType::DictionaryVariable(value) => Some(value.owner_handle),
ObjectType::VisualStyle(value) => Some(value.owner),
ObjectType::Material(value) => Some(value.owner),
ObjectType::ImageDefinitionReactor(value) => Some(value.owner),
ObjectType::GeoData(value) => Some(value.owner),
ObjectType::SpatialFilter(value) => Some(value.owner),
ObjectType::RasterVariables(value) => Some(value.owner),
ObjectType::BookColor(value) => Some(value.owner),
ObjectType::PlaceHolder(value) => Some(value.owner),
ObjectType::DictionaryWithDefault(value) => Some(value.owner),
ObjectType::WipeoutVariables(value) => Some(value.owner),
ObjectType::BlockVisibilityParameter(value) => Some(value.owner),
ObjectType::DynamicBlock(value) => Some(value.owner),
ObjectType::Associative(value) => Some(value.owner),
ObjectType::ClassObject(value) => Some(value.owner),
ObjectType::DataObject(value) => Some(value.owner),
ObjectType::Field(value) => Some(value.owner),
ObjectType::FieldList(value) => Some(value.owner),
ObjectType::RegisteredClass(value) => Some(value.owner),
ObjectType::DgnLineStyle(value) => Some(value.owner),
ObjectType::ProxyObject(value) => Some(value.owner),
ObjectType::Unknown { owner, .. } => Some(*owner),
ObjectType::UnderlayDefinition(_) => None,
}
}
/// Resolve the extension dictionary attached to an entity, table record or
/// non-graphical object.
pub fn extension_dictionary_handle(&self, owner: Handle) -> Option<Handle> {
if let Some(entity) = self.get_entity(owner) {
if let Some(handle) = entity.common().xdictionary_handle {
return (!handle.is_null()).then_some(handle);
}
}
if let Some(handle) = self.xdic_by_handle.get(&owner).copied() {
return (!handle.is_null()).then_some(handle);
}
if let Some(handle) = match self.objects.get(&owner) {
Some(ObjectType::Dictionary(value)) => value.xdictionary_handle,
Some(ObjectType::Layout(value)) => value.xdictionary_handle,
Some(ObjectType::XRecord(value)) => value.xdictionary_handle,
Some(ObjectType::PlotSettings(value)) => value.xdictionary_handle,
Some(ObjectType::VisualStyle(value)) => value.xdictionary_handle,
Some(ObjectType::Material(value)) => value.xdictionary_handle,
Some(ObjectType::ProxyObject(value)) => value.xdictionary_handle,
_ => None,
} {
if !handle.is_null() {
return Some(handle);
}
}
// A dictionary can own ordinary child dictionaries, so ownership alone
// is not sufficient to identify an extension dictionary for that
// specific owner type. Other objects and symbol-table records have at
// most one owned dictionary here: their extension dictionary.
if matches!(self.objects.get(&owner), Some(ObjectType::Dictionary(_))) {
return None;
}
self.objects
.iter()
.find_map(|(handle, object)| match object {
ObjectType::Dictionary(dictionary)
if dictionary.owner == owner && !handle.is_null() =>
{
Some(*handle)
}
_ => None,
})
}
/// Resolve a named XRecord in `owner`'s extension dictionary.
pub fn xrecord(&self, owner: Handle, key: &str) -> Option<&crate::objects::XRecord> {
let dictionary_handle = self.extension_dictionary_handle(owner)?;
let record_handle = match self.objects.get(&dictionary_handle)? {
ObjectType::Dictionary(dictionary) => dictionary.get(key)?,
_ => return None,
};
match self.objects.get(&record_handle)? {
ObjectType::XRecord(record) => Some(record),
_ => None,
}
}
/// Mutable counterpart of [`CadDocument::xrecord`].
pub fn xrecord_mut(
&mut self,
owner: Handle,
key: &str,
) -> Option<&mut crate::objects::XRecord> {
let dictionary_handle = self.extension_dictionary_handle(owner)?;
let record_handle = match self.objects.get(&dictionary_handle)? {
ObjectType::Dictionary(dictionary) => dictionary.get(key)?,
_ => return None,
};
match self.objects.get_mut(&record_handle)? {
ObjectType::XRecord(record) => Some(record),
_ => None,
}
}
/// Ensure an extension dictionary exists for `owner`.
pub fn ensure_extension_dictionary(&mut self, owner: Handle) -> Handle {
if let Some(handle) = self.extension_dictionary_handle(owner) {
return handle;
}
let handle = self.allocate_handle();
let mut dictionary = crate::objects::Dictionary::new();
dictionary.handle = handle;
dictionary.owner = owner;
dictionary.hard_owner = true;
self.objects
.insert(handle, ObjectType::Dictionary(dictionary));
if let Some(entity) = self.get_entity_mut(owner) {
entity.common_mut().xdictionary_handle = Some(handle);
}
self.xdic_by_handle.insert(owner, handle);
handle
}
/// Ensure a named XRecord and its extension dictionary exist.
///
/// The created dictionary owns its records and is attached through both
/// the entity common data and the non-entity side map so DWG and DXF
/// writers observe the same graph.
pub fn ensure_xrecord(&mut self, owner: Handle, key: &str) -> Handle {
let dictionary_handle = self.ensure_extension_dictionary(owner);
if let Some(ObjectType::Dictionary(dictionary)) = self.objects.get(&dictionary_handle) {
if let Some(handle) = dictionary.get(key) {
if matches!(self.objects.get(&handle), Some(ObjectType::XRecord(_))) {
return handle;
}
}
}
let record_handle = self.allocate_handle();
let mut record = crate::objects::XRecord::named(key);
record.handle = record_handle;
record.owner = dictionary_handle;
self.objects
.insert(record_handle, ObjectType::XRecord(record));
if let Some(ObjectType::Dictionary(dictionary)) = self.objects.get_mut(&dictionary_handle) {
if let Some((_, handle)) = dictionary
.entries
.iter_mut()
.find(|(name, _)| name.eq_ignore_ascii_case(key))
{
*handle = record_handle;
} else {
dictionary.add_entry(key, record_handle);
}
}
record_handle
}
/// Assign dictionary keys to XRecord objects after file loading.
pub fn resolve_xrecord_names(&mut self) {
let mut names: Vec<(Handle, String)> = self
.objects
.values()
.filter_map(|object| match object {
ObjectType::Dictionary(dictionary) => Some(
dictionary
.entries
.iter()
.map(|(name, handle)| (*handle, name.clone()))
.collect::<Vec<_>>(),
),
_ => None,
})
.flatten()
.collect();
names.sort_by_key(|(handle, name)| (handle.value(), name.clone()));
for (handle, name) in names {
if let Some(ObjectType::XRecord(record)) = self.objects.get_mut(&handle) {
record.name = name;
}
}
}
/// Project typed properties whose authoritative storage is a named
/// XRecord onto their public object models.
pub fn resolve_xrecord_backed_properties(&mut self) {
let advanced_values: HashMap<Handle, Vec<XRecordEntry>> = self
.objects
.values()
.filter_map(|object| match object {
ObjectType::Dictionary(dictionary) => {
dictionary.get("ADVMATERIAL").and_then(|record| {
match self.objects.get(&record) {
Some(ObjectType::XRecord(xrecord)) => {
Some((dictionary.handle, xrecord.entries.clone()))
}
_ => None,
}
})
}
_ => None,
})
.collect();
let mut material_maps = HashMap::new();
for object in self.objects.values() {
let ObjectType::Dictionary(dictionary) = object else {
continue;
};
for name in [
"DIFFUSE",
"SPECULAR",
"REFLECTION",
"OPACITY",
"BUMP",
"REFRACTION",
"NORMAL",
] {
let Some(record) = dictionary.get(name) else {
continue;
};
let Some(ObjectType::XRecord(xrecord)) = self.objects.get(&record) else {
continue;
};
if let Some(texture) = material_checker_texture(&xrecord.entries) {
material_maps.insert((dictionary.handle, name), texture);
}
}
}
for object in self.objects.values_mut() {
let ObjectType::Material(material) = object else {
continue;
};
let Some(dictionary) = material.xdictionary_handle else {
continue;
};
if let Some(entries) = advanced_values.get(&dictionary) {
material.advanced_data_present = true;
for entry in entries {
match (entry.code, &entry.value) {
(460, crate::objects::XRecordValue::Double(value)) => {
material.color_bleed_scale = *value / 100.0;
}
(461, crate::objects::XRecordValue::Double(value)) => {
material.indirect_bump_scale = *value / 100.0;
}
(462, crate::objects::XRecordValue::Double(value)) => {
material.reflectance_scale = *value / 100.0;
}
(463, crate::objects::XRecordValue::Double(value)) => {
material.transmittance_scale = *value / 100.0;
}
(464, crate::objects::XRecordValue::Double(value)) => {
material.luminance = *value;
}
(270, crate::objects::XRecordValue::Int16(value)) => {
material.luminance_mode = *value;
}
(290, crate::objects::XRecordValue::Bool(value)) => {
material.two_sided_material = *value;
}
(293, crate::objects::XRecordValue::Bool(value)) => {
material.is_anonymous = *value;
}
(272, crate::objects::XRecordValue::Int16(value)) => {
material.global_illumination = *value;
}
(273, crate::objects::XRecordValue::Int16(value)) => {
material.final_gather = *value;
}
_ => {}
}
}
}
for (name, map) in [
("DIFFUSE", &mut material.diffuse_map),
("SPECULAR", &mut material.specular_map),
("REFLECTION", &mut material.reflection_map),
("OPACITY", &mut material.opacity_map),
("BUMP", &mut material.bump_map),
("REFRACTION", &mut material.refraction_map),
("NORMAL", &mut material.normal_map),
] {
if let Some(texture) = material_maps.get(&(dictionary, name)) {
map.source = 2;
map.file_name.clear();
map.texture = Some(texture.clone());
}
}
}
}
/// Read the annotation scale attached to a viewport.
pub fn viewport_annotation_scale(&self, viewport: Handle) -> Option<Handle> {
self.xrecord(viewport, "ASDK_XREC_ANNOTATION_SCALE_INFO")?
.annotation_scale_handle()
}
/// Set the annotation scale attached to a viewport.
pub fn set_viewport_annotation_scale(&mut self, viewport: Handle, scale: Handle) {
self.ensure_xrecord(viewport, "ASDK_XREC_ANNOTATION_SCALE_INFO");
if let Some(record) = self.xrecord_mut(viewport, "ASDK_XREC_ANNOTATION_SCALE_INFO") {
record.set_annotation_scale_handle(scale);
}
}
/// Read Autodesk subdivision-mesh UVW coordinates.
pub fn mesh_texture_coordinates(&self, mesh: Handle) -> Vec<Vector3> {
self.xrecord(mesh, "ADSK_XREC_SUBDVERTEXTEXCOORDS")
.map(|record| record.mesh_texture_coordinates())
.unwrap_or_default()
}
/// Replace Autodesk subdivision-mesh UVW coordinates.
pub fn set_mesh_texture_coordinates(&mut self, mesh: Handle, coordinates: &[Vector3]) {
self.ensure_xrecord(mesh, "ADSK_XREC_SUBDVERTEXTEXCOORDS");
if let Some(record) = self.xrecord_mut(mesh, "ADSK_XREC_SUBDVERTEXTEXCOORDS") {
record.set_mesh_texture_coordinates(coordinates);
}
}
/// Set an Autodesk viewport-specific layer override.
pub fn set_layer_viewport_override(
&mut self,
layer: Handle,
kind: crate::objects::KnownXRecordKind,
viewport: Handle,
value: crate::objects::XRecordValue,
) -> bool {
let (key, section, value_code) = match kind {
crate::objects::KnownXRecordKind::LayerViewportAlphaOverride => {
("ADSK_XREC_LAYER_ALPHA_OVR", "ADSK_LYR_ALPHA_OVERRIDE", 440)
}
crate::objects::KnownXRecordKind::LayerViewportColorOverride => {
("ADSK_XREC_LAYER_COLOR_OVR", "ADSK_LYR_COLOR_OVERRIDE", 420)
}
crate::objects::KnownXRecordKind::LayerViewportLinetypeOverride => (
"ADSK_XREC_LAYER_LINETYPE_OVR",
"ADSK_LYR_LINETYPE_OVERRIDE",
343,
),
crate::objects::KnownXRecordKind::LayerViewportLineweightOverride => {
("ADSK_XREC_LAYER_LINEWT_OVR", "ADSK_LYR_LINEWT_OVERRIDE", 91)
}
_ => return false,
};
let valid_value = match value_code {
343 => matches!(value, crate::objects::XRecordValue::Handle(_)),
91 | 420 | 440 => {
matches!(value, crate::objects::XRecordValue::Int32(_))
}
_ => false,
};
if !valid_value {
return false;
}
self.ensure_xrecord(layer, key);
if let Some(record) = self.xrecord_mut(layer, key) {
record.set_layer_viewport_override(section, value_code, viewport, value);
true
} else {
false
}
}
/// Read all viewport-specific overrides of one kind from a layer.
pub fn layer_viewport_overrides(
&self,
layer: Handle,
kind: crate::objects::KnownXRecordKind,
) -> Vec<(Handle, crate::objects::XRecordValue)> {
let (key, value_code) = match kind {
crate::objects::KnownXRecordKind::LayerViewportAlphaOverride => {
("ADSK_XREC_LAYER_ALPHA_OVR", 440)
}
crate::objects::KnownXRecordKind::LayerViewportColorOverride => {
("ADSK_XREC_LAYER_COLOR_OVR", 420)
}
crate::objects::KnownXRecordKind::LayerViewportLinetypeOverride => {
("ADSK_XREC_LAYER_LINETYPE_OVR", 343)
}
crate::objects::KnownXRecordKind::LayerViewportLineweightOverride => {
("ADSK_XREC_LAYER_LINEWT_OVR", 91)
}
_ => return Vec::new(),
};
self.xrecord(layer, key)
.map(|record| record.layer_viewport_overrides(value_code))
.unwrap_or_default()
}
/// Walk the ownership chain upward from `start` (inclusive) and report
/// whether it passes through `target`. Bounded to avoid cycles.
pub fn owner_chain_reaches(&self, start: Handle, target: Handle) -> bool {
let mut cur = start;
for _ in 0..16 {
if cur == target {
return true;
}
match self.object_owner(cur) {
Some(next) if next != cur && next.value() != 0 => cur = next,
_ => break,
}
}
cur == target
}
/// Resolve the visibility parameter governing a dynamic block definition,
/// if that block carries one (via its ACAD_ENHANCEDBLOCK evaluation graph).
pub fn block_visibility_param_for_def(
&self,
def_block: Handle,
) -> Option<&crate::objects::BlockVisibilityParameter> {
self.block_visibility_params
.values()
.find(|p| self.owner_chain_reaches(p.owner, def_block))
}
/// Resolve the dynamic visibility parameter for a block reference (INSERT),
/// returning `(dynamic_definition_block, parameter)`.
///
/// An evaluated (anonymous) block reference records its dynamic definition
/// through an `AcDbBlockRepresentationData` object reachable from the
/// INSERT's extension dictionary. That definition's enhanced-block graph
/// then carries the visibility parameter.
pub fn dynamic_visibility_for_insert(
&self,
insert_handle: Handle,
) -> Option<(Handle, &crate::objects::BlockVisibilityParameter)> {
let def_block = self.dynamic_definition_for_insert(insert_handle)?;
let param = self.block_visibility_param_for_def(def_block)?;
Some((def_block, param))
}
/// Resolve the original dynamic definition of an INSERT.
///
/// Evaluated anonymous blocks point back through an
/// `AcDbBlockRepresentationData` object. A direct reference to the
/// definition needs no representation object and falls back to the INSERT
/// block-record handle.
pub fn dynamic_definition_for_insert(&self, insert_handle: Handle) -> Option<Handle> {
let EntityType::Insert(insert) = self.get_entity(insert_handle)? else {
return None;
};
if let Some(xdict) = insert.common.xdictionary_handle {
if let Some(definition) = self
.block_representations
.iter()
.find(|(rep, _)| self.owner_chain_reaches(**rep, xdict))
.map(|(_, definition)| *definition)
{
return Some(definition);
}
}
self.block_records
.get(&insert.block_name)
.map(|record| record.handle)
}
pub fn copy_evaluated_block_metadata(&mut self, source: Handle, target: Handle) -> Result<()> {
for handle in [source, target] {
if !self.block_records.iter().any(|b| b.handle == handle && b.name.starts_with("*U")) {
return Err("Expected an evaluated anonymous block record".into());
}
}
let dictionary = if let Some(handle) = self.extension_dictionary_handle(source) {
match self.objects.get(&handle) {
Some(ObjectType::Dictionary(d)) if d.entries.is_empty() && d.xdictionary_handle.is_none() => Some(d.clone()),
_ => return Err("Evaluated block has additional object relationships".into()),
}
} else { None };
if let Some(data) = self.eed_by_handle.get(&source).cloned() {
self.eed_by_handle.insert(target, data);
}
if let Some(mut dictionary) = dictionary {
let handle = self.allocate_handle();
dictionary.handle = handle;
dictionary.owner = target;
dictionary.reactors.clear();
self.objects.insert(handle, ObjectType::Dictionary(dictionary));
self.xdic_by_handle.insert(target, handle);
}
Ok(())
}
/// Resolve handle references after reading a DXF file.
///
/// This performs a simplified version of the two-phase build:
///
/// Whether any symbol-table entry carries a NULL handle (typical for
/// programmatically added entries: `Layer::new` + `layers.add` never
/// assigns one).
pub(crate) fn has_null_table_entries(&self) -> bool {
macro_rules! has_null {
($table:expr) => {
$table.iter().any(|e| e.handle().is_null())
};
}
has_null!(self.layers)
|| has_null!(self.line_types)
|| has_null!(self.text_styles)
|| has_null!(self.dim_styles)
|| has_null!(self.app_ids)
|| has_null!(self.views)
|| has_null!(self.vports)
|| has_null!(self.ucss)
|| has_null!(self.vx_table)
|| has_null!(self.block_records)
}
/// Re-key symbol-table entries renamed in place through `iter_mut` /
/// `get_mut`, so name-based lookups resolve them again.
///
/// Tables key entries by the normalized name captured at insertion.
/// Assigning `layer.name` directly leaves the entry reachable only under
/// its old name, and every later name lookup misses — the DWG writer then
/// emits a NULL layer hard pointer for entities on that layer, leaving an
/// invalid drawing (issue #80). The DWG and
/// DXF writers call this on their output copy; call it directly after an
/// in-place rename to repair the live document too.
///
/// [`rename_layer`](Self::rename_layer) and [`Table::rename`] keep keys in
/// sync on their own, so this is a no-op after either. Returns the number
/// of re-keyed entries.
///
/// Entities, and the header's current-layer/style names, are updated to the
/// new name where the rename is unambiguous, so an in-place rename keeps
/// the drawing's appearance rather than dropping entities to layer "0".
pub fn resync_table_keys(&mut self) -> usize {
let layers = self.layers.resync_keys();
let line_types = self.line_types.resync_keys();
let text_styles = self.text_styles.resync_keys();
let renamed = layers.len()
+ line_types.len()
+ text_styles.len()
+ self.dim_styles.resync_keys().len()
+ self.app_ids.resync_keys().len()
+ self.views.resync_keys().len()
+ self.vports.resync_keys().len()
+ self.ucss.resync_keys().len()
+ self.vx_table.resync_keys().len()
+ self.block_records.resync_keys().len();
if renamed == 0 {
return 0;
}
self.apply_table_renames(&layers, &line_types, &text_styles);
renamed
}
/// Re-point name-based references at the entries `resync_keys` moved.
///
/// A pair is applied only when the old name no longer resolves in its
/// table: if some other entry still owns that name, references to it are
/// legitimate and must stay put.
fn apply_table_renames(
&mut self,
layers: &[(String, String)],
line_types: &[(String, String)],
text_styles: &[(String, String)],
) {
// The stored key is already normalized; strip any duplicate-name suffix
// `add_allow_duplicate` appended so the lookup key is comparable.
let resolvable = |pairs: &[(String, String)], exists: &dyn Fn(&str) -> bool| {
let map: HashMap<String, String> = pairs
.iter()
.filter_map(|(old_key, new_name)| {
let old = old_key.split('\u{0}').next().unwrap_or(old_key);
(!exists(old) && normalize_name(new_name) != old)
.then(|| (old.to_string(), new_name.clone()))
})
.collect();
map
};
let layer_renames = resolvable(layers, &|name| self.layers.contains(name));
let linetype_renames = resolvable(line_types, &|name| self.line_types.contains(name));
let style_renames = resolvable(text_styles, &|name| self.text_styles.contains(name));
if layer_renames.is_empty() && linetype_renames.is_empty() && style_renames.is_empty() {
return;
}
if let Some(name) = layer_renames.get(&normalize_name(&self.header.current_layer_name)) {
self.header.current_layer_name = name.clone();
}
if let Some(name) =
linetype_renames.get(&normalize_name(&self.header.current_linetype_name))
{
self.header.current_linetype_name = name.clone();
}
if let Some(name) = style_renames.get(&normalize_name(&self.header.current_text_style_name))
{
self.header.current_text_style_name = name.clone();
}
for index in 0..self.entities.len() {
let common = self.entities[index].common();
let layer = layer_renames.get(&normalize_name(&common.layer));
let linetype = linetype_renames.get(&normalize_name(&common.linetype));
if layer.is_none() && linetype.is_none() {
continue;
}
let layer = layer.cloned();
let linetype = linetype.cloned();
let common = Arc::make_mut(&mut self.entities[index]).common_mut();
if let Some(name) = layer {
common.layer = name;
}
if let Some(name) = linetype {
common.linetype = name;
}
}
// A layer's own linetype reference is a name too.
for layer in self.layers.iter_mut() {
if let Some(name) = linetype_renames.get(&normalize_name(&layer.line_type)) {
layer.line_type = name.clone();
}
}
}
/// Whether any symbol-table entry was renamed in place and is now
/// unreachable under its own name. See [`resync_table_keys`](Self::resync_table_keys).
pub fn has_stale_table_keys(&self) -> bool {
macro_rules! stale {
($table:expr) => {
$table.has_stale_keys()
};
}
stale!(self.layers)
|| stale!(self.line_types)
|| stale!(self.text_styles)
|| stale!(self.dim_styles)
|| stale!(self.app_ids)
|| stale!(self.views)
|| stale!(self.vports)
|| stale!(self.ucss)
|| stale!(self.vx_table)
|| stale!(self.block_records)
}
/// Assigns fresh handles to every symbol-table entry that still carries
/// a NULL handle.
///
/// DWG table records must each carry a real handle - a record written
/// with handle 0 is dropped by the handle map and disappears from the
/// re-opened drawing. Programmatically added entries (e.g.
/// `Layer::new` + `layers.add`) arrive without one, so the DWG writer
/// calls this on a cloned document before writing (issue #51/#64
/// class of bug).
pub fn assign_table_entry_handles(&mut self) {
let mut missing_handles: Vec<(&'static str, String)> = Vec::new();
macro_rules! collect_missing {
($tag:literal, $table:expr) => {
for entry in $table.iter() {
if entry.handle().is_null() {
missing_handles.push(($tag, entry.name().to_string()));
}
}
};
}
collect_missing!("layers", self.layers);
collect_missing!("line_types", self.line_types);
collect_missing!("text_styles", self.text_styles);
collect_missing!("dim_styles", self.dim_styles);
collect_missing!("app_ids", self.app_ids);
collect_missing!("views", self.views);
collect_missing!("vports", self.vports);
collect_missing!("ucss", self.ucss);
collect_missing!("vx_table", self.vx_table);
collect_missing!("block_records", self.block_records);
for (tag, name) in missing_handles.drain(..) {
let new = self.allocate_handle();
macro_rules! apply_missing {
($t:literal, $table:expr) => {
if tag == $t {
if let Some(entry) = $table.get_mut(&name) {
entry.set_handle(new);
}
}
};
}
apply_missing!("layers", self.layers);
apply_missing!("line_types", self.line_types);
apply_missing!("text_styles", self.text_styles);
apply_missing!("dim_styles", self.dim_styles);
apply_missing!("app_ids", self.app_ids);
apply_missing!("views", self.views);
apply_missing!("vports", self.vports);
apply_missing!("ucss", self.ucss);
apply_missing!("vx_table", self.vx_table);
apply_missing!("block_records", self.block_records);
}
}
/// 1. Assigns owner handles on model-space entities (owner = model space
/// block record handle) when the entity has no owner set.
/// 2. Assigns owner handles on block-owned entities (owner = the block
/// record handle) when the entity has no owner set.
/// 3. Updates `next_handle` to be above the maximum handle seen in the
/// document so that subsequent `allocate_handle()` calls produce unique
/// values.
///
/// Call this once after loading (the DXF reader calls it automatically).
pub fn resolve_references(&mut self) {
self.synchronize_handle_allocator();
// --- 1. Find the max handle in use across the whole document ---
let mut max_handle: u64 = self.next_handle;
// Check entities
for entity in self.entities.iter() {
let h = entity.common().handle.value();
if h >= max_handle {
max_handle = h + 1;
}
}
// Check objects
for (handle, _) in &self.objects {
let h = handle.value();
if h >= max_handle {
max_handle = h + 1;
}
}
// Check block record handles
for br in self.block_records.iter() {
let h = br.handle.value();
if h >= max_handle {
max_handle = h + 1;
}
for eh in &br.entity_handles {
let h = eh.value();
if h >= max_handle {
max_handle = h + 1;
}
}
}
// Check table entries — without this, object handle remapping in
// section 1d can assign handles that collide with table entry handles.
macro_rules! scan_table {
($tbl:expr) => {
for e in $tbl.iter() {
let h = e.handle().value();
if h >= max_handle {
max_handle = h + 1;
}
}
};
}
scan_table!(self.layers);
scan_table!(self.line_types);
scan_table!(self.text_styles);
scan_table!(self.dim_styles);
scan_table!(self.app_ids);
scan_table!(self.views);
scan_table!(self.vports);
scan_table!(self.ucss);
scan_table!(self.vx_table);
self.next_handle = max_handle;
// --- 1a. Assign handles to records the file left without one ---
// Handle-less sources (R12 and earlier carry no handle records at
// all) leave table entries and objects with NULL handles; writing
// them would emit invalid `5 / 0` handle records that CAD
// applications reject (issue #51 comment by Apicqq). Entities
// already receive handles in `add_entity`, so only table entries
// and objects need this pass. Running after the max-handle scan
// above keeps the fresh handles clear of file-sourced ones.
let mut missing_handles: Vec<(&'static str, String)> = Vec::new();
macro_rules! collect_missing {
($tag:literal, $table:expr) => {
for entry in $table.iter() {
if entry.handle().is_null() {
missing_handles.push(($tag, entry.name().to_string()));
}
}
};
}
collect_missing!("layers", self.layers);
collect_missing!("line_types", self.line_types);
collect_missing!("text_styles", self.text_styles);
collect_missing!("dim_styles", self.dim_styles);
collect_missing!("app_ids", self.app_ids);
collect_missing!("views", self.views);
collect_missing!("vports", self.vports);
collect_missing!("ucss", self.ucss);
collect_missing!("vx_table", self.vx_table);
collect_missing!("block_records", self.block_records);
let null_object_keys: Vec<Handle> = self
.objects
.keys()
.filter(|handle| handle.is_null())
.copied()
.collect();
// Objects whose record handle is NULL but whose map key is valid:
// align the record with its key (the key is the object's identity).
let misaligned_object_keys: Vec<Handle> = self
.objects
.iter()
.filter(|(key, object)| !key.is_null() && object.has_null_handle())
.map(|(key, _)| *key)
.collect();
for (tag, name) in missing_handles.drain(..) {
let new = self.allocate_handle();
macro_rules! apply_missing {
($t:literal, $table:expr) => {
if tag == $t {
if let Some(entry) = $table.get_mut(&name) {
entry.set_handle(new);
}
}
};
}
apply_missing!("layers", self.layers);
apply_missing!("line_types", self.line_types);
apply_missing!("text_styles", self.text_styles);
apply_missing!("dim_styles", self.dim_styles);
apply_missing!("app_ids", self.app_ids);
apply_missing!("views", self.views);
apply_missing!("vports", self.vports);
apply_missing!("ucss", self.ucss);
apply_missing!("vx_table", self.vx_table);
apply_missing!("block_records", self.block_records);
}
for _ in null_object_keys.iter() {
let new = self.allocate_handle();
if let Some(mut object) = self.objects.remove(&Handle::NULL) {
object.set_handle(new);
self.objects.insert(new, object);
}
}
for key in misaligned_object_keys {
if let Some(object) = self.objects.get_mut(&key) {
object.set_handle(key);
}
}
// --- 1a-bis. The ACAD RegApp record must be the first APPID entry ---
// Applications map XDATA applications by table index and require the
// ACAD record at index 0 (issue #51 BricsCAD audit: "RegApp ACAD has
// invalid index 1").
if !self
.app_ids
.iter()
.next()
.is_some_and(|entry| entry.name().eq_ignore_ascii_case("ACAD"))
&& self.app_ids.get("ACAD").is_some()
{
let acad = self.app_ids.remove("ACAD").unwrap();
let previous = std::mem::take(&mut self.app_ids);
self.app_ids.set_handle(previous.handle());
self.app_ids.add_or_replace(acad);
for entry in previous.iter() {
self.app_ids.add_or_replace(entry.clone());
}
}
// --- 1b. Resolve table handle collisions ---
// Collect ALL handles used by entries, entities, and objects so we can
// detect when a table control handle collides with ANY of them.
let mut used_handles = std::collections::HashSet::new();
for e in self.layers.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.line_types.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.text_styles.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.vports.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.views.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.ucss.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.app_ids.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.dim_styles.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.vx_table.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.block_records.iter() {
if !e.handle().is_null() {
used_handles.insert(e.handle().value());
}
}
for e in self.entities.iter() {
let h = e.common().handle.value();
if h > 0 {
used_handles.insert(h);
}
}
// Snapshot the handles used by NON-object records. Object keys are
// unique in `self.objects`, so an object can only truly collide with a
// record of a different kind (entity, table entry, block record). The
// object-collision pass (1d) must decide against THIS set — using the
// full `used_handles` (which also contains every object handle, added
// just below) makes the check trivially true and remaps every object,
// orphaning entity->object links like Underlay/RasterImage definitions.
let non_object_used = used_handles.clone();
for (h, _) in &self.objects {
let v = h.value();
if v > 0 {
used_handles.insert(v);
}
}
// Reassign any table control handle that collides with a used handle
if used_handles.contains(&self.vports.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.vports.set_handle(h);
self.header.vport_control_handle = h;
}
if used_handles.contains(&self.line_types.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.line_types.set_handle(h);
self.header.linetype_control_handle = h;
}
if used_handles.contains(&self.layers.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.layers.set_handle(h);
self.header.layer_control_handle = h;
}
if used_handles.contains(&self.text_styles.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.text_styles.set_handle(h);
self.header.style_control_handle = h;
}
if used_handles.contains(&self.views.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.views.set_handle(h);
self.header.view_control_handle = h;
}
if used_handles.contains(&self.ucss.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.ucss.set_handle(h);
self.header.ucs_control_handle = h;
}
if used_handles.contains(&self.app_ids.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.app_ids.set_handle(h);
self.header.appid_control_handle = h;
}
if used_handles.contains(&self.dim_styles.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.dim_styles.set_handle(h);
self.header.dimstyle_control_handle = h;
}
if used_handles.contains(&self.block_records.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.block_records.set_handle(h);
self.header.block_control_handle = h;
}
if used_handles.contains(&self.vx_table.handle().value()) {
let h = Handle::new(self.next_handle);
self.next_handle += 1;
self.vx_table.set_handle(h);
self.header.vpent_hdr_control_handle = h;
}
// --- 1c. Resolve missing or colliding BLOCK/ENDBLK handles ---
// Reserve table controls as well as entry/entity/object identities,
// then reserve each marker as it is accepted. This catches collisions
// between two markers, not just marker-to-record collisions.
for handle in [
self.vports.handle(),
self.line_types.handle(),
self.layers.handle(),
self.text_styles.handle(),
self.views.handle(),
self.ucss.handle(),
self.app_ids.handle(),
self.dim_styles.handle(),
self.block_records.handle(),
self.vx_table.handle(),
] {
if !handle.is_null() {
used_handles.insert(handle.value());
}
}
for br in self.block_records.iter_mut() {
if br.block_entity_handle.is_null()
|| used_handles.contains(&br.block_entity_handle.value())
{
let h = Handle::new(self.next_handle);
self.next_handle += 1;
br.block_entity_handle = h;
}
used_handles.insert(br.block_entity_handle.value());
if br.block_end_handle.is_null() || used_handles.contains(&br.block_end_handle.value())
{
let h = Handle::new(self.next_handle);
self.next_handle += 1;
br.block_end_handle = h;
}
used_handles.insert(br.block_end_handle.value());
}
// --- 1d. Resolve object handle collisions ---
// Dictionary and other objects created by initialize_defaults() may
// have handles that collide with file-sourced handles.
let mut remap: Vec<(Handle, Handle)> = Vec::new();
let mut obj_handles: Vec<Handle> = self.objects.keys().copied().collect();
obj_handles.sort_by_key(|handle| handle.value());
for old_h in obj_handles {
if non_object_used.contains(&old_h.value()) {
let new_h = Handle::new(self.next_handle);
self.next_handle += 1;
remap.push((old_h, new_h));
}
}
for (old_h, new_h) in &remap {
if let Some(mut obj) = self.objects.remove(old_h) {
obj.set_handle(*new_h);
self.objects.insert(*new_h, obj);
}
}
// Update cross-references: dictionary entries and owner handles
if !remap.is_empty() {
let remap_map: std::collections::HashMap<u64, Handle> =
remap.iter().map(|(o, n)| (o.value(), *n)).collect();
let mut remap_object_handle = |handle: &mut Handle| {
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
};
// Update dictionary entry values that reference remapped handles
for (_, obj) in self.objects.iter_mut() {
match obj {
ObjectType::Dictionary(d) => {
if let Some(new_owner) = remap_map.get(&d.owner.value()) {
d.owner = *new_owner;
}
for (_, entry_handle) in d.entries.iter_mut() {
if let Some(new_h) = remap_map.get(&entry_handle.value()) {
*entry_handle = *new_h;
}
}
}
ObjectType::XRecord(x) => {
if let Some(new_owner) = remap_map.get(&x.owner.value()) {
x.owner = *new_owner;
}
for reactor in &mut x.reactors {
if let Some(new_handle) = remap_map.get(&reactor.value()) {
*reactor = *new_handle;
}
}
if let Some(xdictionary) = x.xdictionary_handle.as_mut() {
if let Some(new_handle) = remap_map.get(&xdictionary.value()) {
*xdictionary = *new_handle;
}
}
for entry in &mut x.entries {
if let crate::objects::XRecordValue::Handle(handle) = &mut entry.value {
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
}
}
for reference in &mut x.object_references {
if let Some(new_handle) = remap_map.get(&reference.handle.value()) {
reference.handle = *new_handle;
}
}
}
ObjectType::Layout(l) => {
remap_object_handle(&mut l.owner);
for reactor in &mut l.reactors {
remap_object_handle(reactor);
}
if let Some(xdictionary) = l.xdictionary_handle.as_mut() {
remap_object_handle(xdictionary);
}
remap_object_handle(&mut l.block_record);
remap_object_handle(&mut l.viewport);
for viewport in &mut l.viewports {
remap_object_handle(viewport);
}
remap_object_handle(&mut l.base_ucs);
remap_object_handle(&mut l.named_ucs);
remap_object_handle(&mut l.plot_view_handle);
remap_object_handle(&mut l.visual_style_handle);
if let Some(codes) = l.raw_plot_settings_codes.as_mut() {
for (code, value) in codes {
if *code == 333 {
if let Ok(old_handle) = u64::from_str_radix(value, 16) {
if let Some(new_handle) = remap_map.get(&old_handle) {
*value = format!("{:X}", new_handle.value(),);
}
}
}
}
}
}
ObjectType::PlotSettings(p) => {
remap_object_handle(&mut p.owner);
for reactor in &mut p.reactors {
remap_object_handle(reactor);
}
if let Some(xdictionary) = p.xdictionary_handle.as_mut() {
remap_object_handle(xdictionary);
}
remap_object_handle(&mut p.plot_view_handle);
remap_object_handle(&mut p.visual_style_handle);
}
ObjectType::MLineStyle(m) => {
if let Some(new_owner) = remap_map.get(&m.owner.value()) {
m.owner = *new_owner;
}
}
ObjectType::PlaceHolder(p) => {
if let Some(new_owner) = remap_map.get(&p.owner.value()) {
p.owner = *new_owner;
}
}
ObjectType::DictionaryWithDefault(d) => {
if let Some(new_owner) = remap_map.get(&d.owner.value()) {
d.owner = *new_owner;
}
for (_, entry_handle) in d.entries.iter_mut() {
if let Some(new_h) = remap_map.get(&entry_handle.value()) {
*entry_handle = *new_h;
}
}
// The default entry (code 340) must follow its
// object when that object is remapped; leaving it
// behind points the dictionary at a handle that no
// longer exists (issue #51 comment by Apicqq).
if let Some(new_h) = remap_map.get(&d.default_handle.value()) {
d.default_handle = *new_h;
}
}
ObjectType::GeoData(g) => {
if let Some(new_owner) = remap_map.get(&g.owner.value()) {
g.owner = *new_owner;
}
for reactor in &mut g.reactors {
if let Some(new_handle) = remap_map.get(&reactor.value()) {
*reactor = *new_handle;
}
}
if let Some(xdictionary) = g.xdictionary_handle.as_mut() {
if let Some(new_handle) = remap_map.get(&xdictionary.value()) {
*xdictionary = *new_handle;
}
}
if let Some(new_host) = remap_map.get(&g.host_block.value()) {
g.host_block = *new_host;
}
}
ObjectType::DynamicBlock(d) => {
d.visit_handles_mut(&mut remap_object_handle);
}
ObjectType::DataObject(d) => {
if let Some(new_owner) = remap_map.get(&d.owner.value()) {
d.owner = *new_owner;
}
for reactor in &mut d.reactors {
if let Some(new_handle) = remap_map.get(&reactor.value()) {
*reactor = *new_handle;
}
}
if let Some(xdictionary) = d.xdictionary_handle.as_mut() {
if let Some(new_handle) = remap_map.get(&xdictionary.value()) {
*xdictionary = *new_handle;
}
}
match &mut d.data {
DataObjectData::BreakData(value) => {
if let Some(new_handle) =
remap_map.get(&value.dimension_reference.value())
{
value.dimension_reference = *new_handle;
}
if let Some(new_handle) =
remap_map.get(&value.reserved_reference.value())
{
value.reserved_reference = *new_handle;
}
}
DataObjectData::IdBuffer(value) => {
for reference in &mut value.object_ids {
if let Some(new_handle) = remap_map.get(&reference.value()) {
*reference = *new_handle;
}
}
}
DataObjectData::LayerIndex(value) => {
for entry in &mut value.entries {
if let Some(new_handle) =
remap_map.get(&entry.id_buffer.value())
{
entry.id_buffer = *new_handle;
}
}
}
DataObjectData::CellStyleMap(value) => {
for cell in &mut value.cells {
let format = &mut cell.cell_style.content_format;
if let Some(new_handle) =
remap_map.get(&format.text_style.value())
{
format.text_style = *new_handle;
}
for border in &mut cell.cell_style.borders {
if let Some(new_handle) =
remap_map.get(&border.line_type.value())
{
border.line_type = *new_handle;
}
}
}
}
DataObjectData::TableGeometry(value) => {
for cell in &mut value.cells {
if let Some(new_handle) =
remap_map.get(&cell.table_geometry.value())
{
cell.table_geometry = *new_handle;
}
}
}
DataObjectData::BreakPointRef
| DataObjectData::AcDsRecord
| DataObjectData::AcDsSchema
| DataObjectData::Dummy
| DataObjectData::Index(_)
| DataObjectData::LongTransaction
| DataObjectData::ObjectPointer
| DataObjectData::PartialViewingFilter(_) => {}
}
}
ObjectType::ClassObject(value) => {
value.visit_handles_mut(&mut remap_object_handle);
}
ObjectType::RegisteredClass(value) => {
if let Some(new_handle) = remap_map.get(&value.owner.value()) {
value.owner = *new_handle;
}
for reactor in &mut value.reactors {
if let Some(new_handle) = remap_map.get(&reactor.value()) {
*reactor = *new_handle;
}
}
if let Some(xdictionary) = value.xdictionary_handle.as_mut() {
if let Some(new_handle) = remap_map.get(&xdictionary.value()) {
*xdictionary = *new_handle;
}
}
for property in &mut value.properties {
if let crate::objects::SemanticPropertyValue::Handle(handle) =
&mut property.value
{
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
}
}
for reference in &mut value.object_ids {
if let Some(new_handle) = remap_map.get(&reference.handle.value()) {
reference.handle = *new_handle;
}
}
}
ObjectType::DgnLineStyle(value) => {
if let Some(new_handle) = remap_map.get(&value.owner.value()) {
value.owner = *new_handle;
}
for reactor in &mut value.reactors {
if let Some(new_handle) = remap_map.get(&reactor.value()) {
*reactor = *new_handle;
}
}
if let Some(xdictionary) = value.xdictionary_handle.as_mut() {
if let Some(new_handle) = remap_map.get(&xdictionary.value()) {
*xdictionary = *new_handle;
}
}
match &mut value.data {
crate::objects::DgnLineStyleData::Definition {
root_component,
properties,
..
} => {
if let Some(new_handle) = remap_map.get(&root_component.value()) {
*root_component = *new_handle;
}
for property in properties {
if let crate::objects::SemanticPropertyValue::Handle(handle) =
&mut property.value
{
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
}
}
}
crate::objects::DgnLineStyleData::Component {
component,
properties,
..
} => {
match component {
crate::objects::DgnLsComponentData::Symbol(value) => {
if let Some(new_handle) =
remap_map.get(&value.block.value())
{
value.block = *new_handle;
}
}
crate::objects::DgnLsComponentData::Compound(value) => {
for entry in &mut value.entries {
if let Some(new_handle) =
remap_map.get(&entry.component.value())
{
entry.component = *new_handle;
}
}
}
crate::objects::DgnLsComponentData::Point(value) => {
if let Some(new_handle) =
remap_map.get(&value.stroke_component.value())
{
value.stroke_component = *new_handle;
}
for symbol in &mut value.symbols {
if let Some(new_handle) =
remap_map.get(&symbol.symbol_component.value())
{
symbol.symbol_component = *new_handle;
}
}
}
crate::objects::DgnLsComponentData::Stroke(_)
| crate::objects::DgnLsComponentData::Internal(_) => {}
}
for property in properties {
if let crate::objects::SemanticPropertyValue::Handle(handle) =
&mut property.value
{
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
}
}
}
crate::objects::DgnLineStyleData::Registered {
properties,
object_ids,
..
} => {
for property in properties {
if let crate::objects::SemanticPropertyValue::Handle(handle) =
&mut property.value
{
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
}
}
for reference in object_ids {
if let Some(new_handle) =
remap_map.get(&reference.handle.value())
{
reference.handle = *new_handle;
}
}
}
}
}
ObjectType::ObjectContextData(value) => {
remap_object_handle(&mut value.owner_handle);
for reactor in &mut value.reactors {
remap_object_handle(reactor);
}
if let Some(xdictionary) = value.xdictionary_handle.as_mut() {
remap_object_handle(xdictionary);
}
remap_object_handle(&mut value.scale);
match &mut value.kind {
crate::objects::ObjectContextKind::Dim(dimension) => {
remap_object_handle(&mut dimension.block);
}
crate::objects::ObjectContextKind::HatchView(hatch) => {
remap_object_handle(&mut hatch.view);
}
crate::objects::ObjectContextKind::MTextAttribute(attribute) => {
if let Some(context) = attribute.context.as_mut() {
remap_object_handle(&mut context.scale);
}
}
crate::objects::ObjectContextKind::MLeader(context) => {
if let Some(handle) = context.text_style_handle.as_mut() {
remap_object_handle(handle);
}
if let Some(handle) = context.block_content_handle.as_mut() {
remap_object_handle(handle);
}
if let Some(handle) = context.scale_handle.as_mut() {
remap_object_handle(handle);
}
for root in &mut context.leader_roots {
for line in &mut root.lines {
if let Some(handle) = line.line_type_handle.as_mut() {
remap_object_handle(handle);
}
if let Some(handle) = line.arrowhead_handle.as_mut() {
remap_object_handle(handle);
}
}
}
}
_ => {}
}
}
ObjectType::DictionaryVariable(value) => {
remap_object_handle(&mut value.owner_handle);
}
ObjectType::TableContent(value) => {
value.visit_object_handles_mut(&mut remap_object_handle);
}
ObjectType::BlockVisibilityParameter(value) => {
value.visit_handles_mut(&mut remap_object_handle);
}
ObjectType::Associative(value) => {
value.visit_handles_mut(&mut remap_object_handle);
}
ObjectType::Field(value) => {
value.visit_handles_mut(&mut remap_object_handle);
}
ObjectType::FieldList(value) => {
value.visit_handles_mut(&mut remap_object_handle);
}
ObjectType::ProxyObject(value) => {
if let Some(new_handle) = remap_map.get(&value.owner.value()) {
value.owner = *new_handle;
}
for reactor in &mut value.reactors {
if let Some(new_handle) = remap_map.get(&reactor.value()) {
*reactor = *new_handle;
}
}
if let Some(xdictionary) = value.xdictionary_handle.as_mut() {
if let Some(new_handle) = remap_map.get(&xdictionary.value()) {
*xdictionary = *new_handle;
}
}
for reference in &mut value.object_ids {
if let Some(new_handle) = remap_map.get(&reference.handle.value()) {
reference.handle = *new_handle;
}
}
}
_ => {}
}
}
for (old_handle, new_handle) in &remap {
if let Some(mut value) = self.block_visibility_params.remove(old_handle) {
value.visit_handles_mut(&mut remap_object_handle);
self.block_visibility_params.insert(*new_handle, value);
}
if let Some(mut value) = self.fields.remove(old_handle) {
remap_object_handle(&mut value.handle);
remap_object_handle(&mut value.owner);
for handle in &mut value.objects {
remap_object_handle(handle);
}
self.fields.insert(*new_handle, value);
}
if let Some(mut value) = self.context_scales.remove(old_handle) {
remap_object_handle(&mut value);
self.context_scales.insert(*new_handle, value);
}
if let Some(mut value) = self.block_representations.remove(old_handle) {
remap_object_handle(&mut value);
self.block_representations.insert(*new_handle, value);
}
if let Some(value) = self.eed_by_handle.remove(old_handle) {
self.eed_by_handle.insert(*new_handle, value);
}
if let Some(value) = self.object_xdata.remove(old_handle) {
self.object_xdata.insert(*new_handle, value);
}
if let Some(mut value) = self.xdic_by_handle.remove(old_handle) {
remap_object_handle(&mut value);
self.xdic_by_handle.insert(*new_handle, value);
}
if let Some(mut values) = self.reactors_by_handle.remove(old_handle) {
for handle in &mut values {
remap_object_handle(handle);
}
self.reactors_by_handle.insert(*new_handle, values);
}
}
for value in self.block_visibility_params.values_mut() {
value.visit_handles_mut(&mut remap_object_handle);
}
for value in self.fields.values_mut() {
remap_object_handle(&mut value.owner);
for handle in &mut value.objects {
remap_object_handle(handle);
}
}
for value in self.context_scales.values_mut() {
remap_object_handle(value);
}
for value in self.block_representations.values_mut() {
remap_object_handle(value);
}
for value in self.xdic_by_handle.values_mut() {
remap_object_handle(value);
}
for values in self.reactors_by_handle.values_mut() {
for handle in values {
remap_object_handle(handle);
}
}
// Update header handles that reference remapped objects
let header_handles = [
&mut self.header.named_objects_dict_handle,
&mut self.header.acad_group_dict_handle,
&mut self.header.acad_mlinestyle_dict_handle,
&mut self.header.acad_layout_dict_handle,
&mut self.header.acad_plotsettings_dict_handle,
&mut self.header.acad_plotstylename_dict_handle,
&mut self.header.acad_material_dict_handle,
&mut self.header.acad_color_dict_handle,
&mut self.header.acad_visualstyle_dict_handle,
&mut self.header.current_multiline_style_handle,
];
for handle in header_handles {
if let Some(new_h) = remap_map.get(&handle.value()) {
*handle = *new_h;
}
}
// Update block record layout references
for br in self.block_records.iter_mut() {
if let Some(new_h) = remap_map.get(&br.layout.value()) {
br.layout = *new_h;
}
}
for view in self.views.iter_mut() {
remap_object_handle(&mut view.background_handle);
remap_object_handle(&mut view.live_section_handle);
remap_object_handle(&mut view.visual_style_handle);
remap_object_handle(&mut view.sun_handle);
}
for vport in self.vports.iter_mut() {
remap_object_handle(&mut vport.background_handle);
remap_object_handle(&mut vport.visual_style_handle);
remap_object_handle(&mut vport.sun_handle);
}
// Update entity -> object references so a genuinely remapped
// definition object stays linked (RasterImage/Underlay renderers
// look the definition up by this handle to find the file path).
for entity in self.entities.iter_mut() {
let entity = Arc::make_mut(entity);
if let Some(handle) = entity.common_mut().color_book_handle.as_mut() {
remap_object_handle(handle);
}
if let Some(handle) = entity.common_mut().xdictionary_handle.as_mut() {
remap_object_handle(handle);
}
match entity {
EntityType::Insert(insert) => {
if let Some(handle) = &mut insert.view_rep_handle {
remap_object_handle(handle);
}
}
EntityType::Underlay(u) => {
if let Some(new_h) = remap_map.get(&u.definition_handle.value()) {
u.definition_handle = *new_h;
}
}
EntityType::RasterImage(img) => {
if let Some(dh) = img.definition_handle {
if let Some(new_h) = remap_map.get(&dh.value()) {
img.definition_handle = Some(*new_h);
}
}
}
EntityType::SectionSymbol(symbol) => {
if let Some(new_handle) = remap_map.get(&symbol.style_handle.value()) {
symbol.style_handle = *new_handle;
}
if let Some(new_handle) = remap_map.get(&symbol.view_rep_handle.value()) {
symbol.view_rep_handle = *new_handle;
}
}
EntityType::ViewBorder(border) => {
if let Some(new_handle) = remap_map.get(&border.active_viewport.value()) {
border.active_viewport = *new_handle;
}
if let Some(new_handle) = remap_map.get(&border.scale_handle.value()) {
border.scale_handle = *new_handle;
}
}
EntityType::Extended(entity) => match &mut entity.data {
crate::entities::ExtendedEntityData::RegisteredClass(value) => {
for property in &mut value.properties {
if let crate::objects::SemanticPropertyValue::Handle(handle) =
&mut property.value
{
if let Some(new_handle) = remap_map.get(&handle.value()) {
*handle = *new_handle;
}
}
}
for reference in &mut value.object_ids {
if let Some(new_handle) = remap_map.get(&reference.handle.value()) {
reference.handle = *new_handle;
}
}
}
crate::entities::ExtendedEntityData::Proxy(value) => {
for reference in &mut value.object_ids {
if let Some(new_handle) = remap_map.get(&reference.handle.value()) {
reference.handle = *new_handle;
}
}
}
_ => {}
},
_ => {}
}
}
}
let model_handle = self.header.model_space_block_handle;
let paper_handle = self.header.paper_space_block_handle;
let paper_handles: std::collections::HashSet<Handle> = self
.block_records
.iter()
.filter_map(|record| {
let name = record.name.to_ascii_uppercase();
(name == "*PAPER_SPACE"
|| (name.starts_with("*PAPER_SPACE")
&& name.len() > 12
&& name[12..].bytes().all(|b| b.is_ascii_digit())))
.then_some(record.handle)
})
.collect();
// Block record entities — set owner handle on entities looked up from
// the entity map. This MUST run before the model-space default below:
// an R12 DXF carries no per-entity owner (code 330), so block content
// starts null-owner; if the model-space default claimed it first, block
// definitions would leak into model space and their block-local
// geometry would pile up at the origin.
for br in self.block_records.iter() {
let br_handle = br.handle;
for eh in &br.entity_handles {
if let Some(&idx) = self.entity_index.get(eh) {
let entity = Arc::make_mut(&mut self.entities[idx]);
let common = match entity {
EntityType::Dimension(d) => {
let base = d.base_mut();
&mut base.common
}
_ => get_common_mut(entity),
};
if common.owner_handle.is_null() {
common.owner_handle = br_handle;
}
}
}
}
// Default owner for anything still unowned after block assignment:
// paper space when the entity carried the R12 paper-space flag
// (code 67 → entity_mode 1), model space otherwise.
for entity in self.entities.iter_mut() {
let entity = Arc::make_mut(entity);
let common = match entity {
EntityType::Dimension(d) => {
let base = d.base_mut();
&mut base.common
}
_ => {
// For all other entity types, use as_entity_mut().set_handle pattern
// but we need &mut EntityCommon directly — use a helper
get_common_mut(entity)
}
};
if common.owner_handle.is_null() {
common.owner_handle = if common.entity_mode == Some(1) {
paper_handle
} else {
model_handle
};
}
common.entity_mode = Some(if common.owner_handle == model_handle {
2
} else if paper_handles.contains(&common.owner_handle) {
1
} else {
0
});
}
// Paper-space entities — if an entity's owner is the paper space block,
// the entity is already correctly assigned by the reader.
// We just skip further assignment here.
let _ = paper_handle; // suppress unused warning; future: paper space logic
// Cache each RasterImage's file path from its IMAGEDEF object. The OCS
// renderer reads `RasterImage.file_path`, but DXF stores the path only
// on the AcDbRasterImageDef object (code 1), so copy it across by the
// image's definition handle. Mirrors the DWG builder's post-pass; runs
// after the object-handle remap so definition handles are current.
let def_paths: std::collections::HashMap<Handle, String> = self
.objects
.iter()
.filter_map(|(h, o)| match o {
ObjectType::ImageDefinition(d) if !d.file_name.is_empty() => {
Some((*h, d.file_name.clone()))
}
_ => None,
})
.collect();
if !def_paths.is_empty() {
for entity in self.entities.iter_mut() {
let needs = matches!(&**entity, EntityType::RasterImage(im)
if im.file_path.is_empty()
&& im.definition_handle.is_some_and(|h| def_paths.contains_key(&h)));
if !needs {
continue;
}
if let EntityType::RasterImage(im) = Arc::make_mut(entity) {
if let Some(p) = im.definition_handle.and_then(|h| def_paths.get(&h)) {
im.file_path = p.clone();
}
}
}
}
self.resolve_book_colors();
self.resolve_xrecord_names();
self.resolve_xrecord_backed_properties();
self.header.handle_seed = self.header.handle_seed.max(self.next_handle);
}
pub(crate) fn resolve_book_colors(&mut self) {
let colors: Vec<(Handle, Color, String, String)> = self
.objects
.iter()
.filter_map(|(handle, object)| match object {
ObjectType::BookColor(color) => Some((
*handle,
color.color,
color.book_name.clone(),
color.color_name.clone(),
)),
_ => None,
})
.collect();
if colors.is_empty() {
return;
}
for entity in self.entities_mut_keep_raw() { // derived colour names only; record bytes untouched
let common = entity.common_mut();
let resolved = common
.color_book_handle
.and_then(|handle| colors.iter().find(|entry| entry.0 == handle))
.or_else(|| {
let identity = common.color_name.as_deref()?;
let (book_name, color_name) = crate::io::dxf::split_color_book_name(identity);
let book_name = book_name.as_deref()?;
let color_name = color_name.as_deref()?;
colors.iter().find(|entry| {
entry.2.eq_ignore_ascii_case(book_name)
&& entry.3.eq_ignore_ascii_case(color_name)
})
});
if let Some((handle, color, book_name, color_name)) = resolved {
common.color_book_handle = Some(*handle);
common.color = *color;
common.color_name =
crate::io::dxf::join_color_book_name(Some(book_name), Some(color_name));
}
}
}
}
/// Helper to get a mutable reference to EntityCommon for non-Dimension entities.
fn get_common_mut(entity: &mut EntityType) -> &mut EntityCommon {
match entity {
EntityType::Point(e) => &mut e.common,
EntityType::Line(e) => &mut e.common,
EntityType::Circle(e) => &mut e.common,
EntityType::Arc(e) => &mut e.common,
EntityType::Ellipse(e) => &mut e.common,
EntityType::Polyline(e) => &mut e.common,
EntityType::Polyline2D(e) => &mut e.common,
EntityType::Polyline3D(e) => &mut e.common,
EntityType::LwPolyline(e) => &mut e.common,
EntityType::Text(e) => &mut e.common,
EntityType::MText(e) => &mut e.common,
EntityType::Spline(e) => &mut e.common,
EntityType::Helix(e) => &mut e.common,
EntityType::Dimension(d) => &mut d.base_mut().common,
EntityType::Hatch(e) => &mut e.common,
EntityType::Solid(e) => &mut e.common,
EntityType::Face3D(e) => &mut e.common,
EntityType::Insert(e) => &mut e.common,
EntityType::Block(e) => &mut e.common,
EntityType::BlockEnd(e) => &mut e.common,
EntityType::Ray(e) => &mut e.common,
EntityType::XLine(e) => &mut e.common,
EntityType::Viewport(e) => &mut e.common,
EntityType::AttributeDefinition(e) => &mut e.common,
EntityType::AttributeEntity(e) => &mut e.common,
EntityType::Leader(e) => &mut e.common,
EntityType::MultiLeader(e) => &mut e.common,
EntityType::MLine(e) => &mut e.common,
EntityType::Mesh(e) => &mut e.common,
EntityType::RasterImage(e) => &mut e.common,
EntityType::Solid3D(e) => &mut e.common,
EntityType::Region(e) => &mut e.common,
EntityType::Body(e) => &mut e.common,
EntityType::Surface(e) => &mut e.common,
EntityType::Table(e) => &mut e.common,
EntityType::Tolerance(e) => &mut e.common,
EntityType::PolyfaceMesh(e) => &mut e.common,
EntityType::Wipeout(e) => &mut e.common,
EntityType::Shape(e) => &mut e.common,
EntityType::Underlay(e) => &mut e.common,
EntityType::Light(e) => &mut e.common,
EntityType::SectionSymbol(e) => &mut e.common,
EntityType::ViewBorder(e) => &mut e.common,
EntityType::Seqend(e) => &mut e.common,
EntityType::Ole2Frame(e) => &mut e.common,
EntityType::PolygonMesh(e) => &mut e.common,
EntityType::Extended(e) => &mut e.common,
EntityType::Unknown(e) => &mut e.common,
}
}
impl Default for CadDocument {
fn default() -> Self {
Self::new()
}
}
fn valid_symbol_table_name(name: &str) -> bool {
!name.is_empty()
&& !name.chars().any(|character| {
character.is_control()
|| matches!(
character,
'<' | '>' | '/' | '\\' | '"' | ':' | ';' | '?' | '*' | '|' | ',' | '=' | '`'
)
})
}