acadrust 0.6.7

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

use crate::entities::{Arc, Ellipse};
use crate::entities::{AttributeEntity, Entity, EntityCommon, EntityType};
use crate::types::{
    BoundingBox3D, Color, Handle, LineWeight, Matrix3, Matrix4, Transform, Vector3,
};

/// Minimum absolute value accepted for scale factors (avoids degenerate geometry).
const SCALE_EPSILON: f64 = 1e-12;

/// Insert entity - a reference to a block definition
///
/// An Insert entity places an instance of a block at a specified location
/// with optional scaling, rotation, and array properties.
///
/// When the block contains attribute definitions, the insert holds a
/// collection of [`AttributeEntity`] instances with the concrete values.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Insert {
    pub common: EntityCommon,
    /// Block name (references a BlockRecord)
    pub block_name: String,
    /// Insertion point (in WCS)
    pub insert_point: Vector3,
    /// X scale factor (must not be zero)
    x_scale: f64,
    /// Y scale factor (must not be zero)
    y_scale: f64,
    /// Z scale factor (must not be zero)
    z_scale: f64,
    /// Rotation angle in radians
    pub rotation: f64,
    /// Normal vector (extrusion direction)
    pub normal: Vector3,
    /// Column count (for array inserts / MINSERT)
    pub column_count: u16,
    /// Row count (for array inserts / MINSERT)
    pub row_count: u16,
    /// Column spacing (for array inserts)
    pub column_spacing: f64,
    /// Row spacing (for array inserts)
    pub row_spacing: f64,
    /// Preserve the fixed DWG MINSERT type even for a 1×1 array.
    dwg_minsert: bool,
    /// Attribute entities attached to this insert
    pub attributes: Vec<AttributeEntity>,
    /// Model-documentation viewport referenced by
    /// `AcDbViewRepBlockReference`; `None` for ordinary INSERT entities.
    pub view_rep_handle: Option<Handle>,
    /// SEQEND handle terminating the attribute sequence.
    ///
    /// Older DWG versions require this structural record to remain adjacent
    /// to the INSERT/ATTRIB handle chain. Preserve its source handle when the
    /// insert came from a file; newly created inserts leave it unset.
    pub seqend_handle: Option<Handle>,
}

impl Insert {
    /// Hard upper bound for detached MINSERT expansion.  ACAD's command
    /// refuses MINSERT references; the context-free helper keeps support for
    /// ordinary arrays while refusing pathological work that would otherwise
    /// materialize billions of transforms or entities.
    const MAX_EXPLODE_ARRAY_INSTANCES: usize = 1_000_000;

    /// Create a new insert entity
    pub fn new(block_name: impl Into<String>, insert_point: Vector3) -> Self {
        Self {
            common: EntityCommon::default(),
            block_name: block_name.into(),
            insert_point,
            x_scale: 1.0,
            y_scale: 1.0,
            z_scale: 1.0,
            rotation: 0.0,
            normal: Vector3::new(0.0, 0.0, 1.0),
            column_count: 1,
            row_count: 1,
            column_spacing: 0.0,
            row_spacing: 0.0,
            dwg_minsert: false,
            attributes: Vec::new(),
            view_rep_handle: None,
            seqend_handle: None,
        }
    }

    // ── Scale accessors with zero-guard ─────────────────────────

    /// Get X scale factor
    pub fn x_scale(&self) -> f64 {
        self.x_scale
    }

    /// Set X scale factor. Rejects zero (uses [`SCALE_EPSILON`] instead).
    pub fn set_x_scale(&mut self, value: f64) {
        self.x_scale = if value.abs() < SCALE_EPSILON {
            SCALE_EPSILON
        } else {
            value
        };
    }

    /// Get Y scale factor
    pub fn y_scale(&self) -> f64 {
        self.y_scale
    }

    /// Set Y scale factor. Rejects zero (uses [`SCALE_EPSILON`] instead).
    pub fn set_y_scale(&mut self, value: f64) {
        self.y_scale = if value.abs() < SCALE_EPSILON {
            SCALE_EPSILON
        } else {
            value
        };
    }

    /// Get Z scale factor
    pub fn z_scale(&self) -> f64 {
        self.z_scale
    }

    /// Set Z scale factor. Rejects zero (uses [`SCALE_EPSILON`] instead).
    pub fn set_z_scale(&mut self, value: f64) {
        self.z_scale = if value.abs() < SCALE_EPSILON {
            SCALE_EPSILON
        } else {
            value
        };
    }

    // ── Builder helpers ─────────────────────────────────────────

    /// Builder: Set the scale factors
    pub fn with_scale(mut self, x: f64, y: f64, z: f64) -> Self {
        self.set_x_scale(x);
        self.set_y_scale(y);
        self.set_z_scale(z);
        self
    }

    /// Builder: Set uniform scale
    pub fn with_uniform_scale(mut self, scale: f64) -> Self {
        self.set_x_scale(scale);
        self.set_y_scale(scale);
        self.set_z_scale(scale);
        self
    }

    /// Builder: Set the rotation angle
    pub fn with_rotation(mut self, angle: f64) -> Self {
        self.rotation = angle;
        self
    }

    /// Builder: Set the normal vector
    pub fn with_normal(mut self, normal: Vector3) -> Self {
        self.normal = normal;
        self
    }

    /// Builder: Set array properties
    pub fn with_array(
        mut self,
        columns: u16,
        rows: u16,
        col_spacing: f64,
        row_spacing: f64,
    ) -> Self {
        self.column_count = columns;
        self.row_count = rows;
        self.column_spacing = col_spacing;
        self.row_spacing = row_spacing;
        self.dwg_minsert = true;
        self
    }

    /// Preserve this block reference as the DWG MINSERT fixed type.
    pub fn mark_as_minsert(&mut self) {
        self.dwg_minsert = true;
    }

    // ── Queries ─────────────────────────────────────────────────

    /// True when the insert has attribute entities attached.
    ///
    /// Corresponds to DXF group code 66.
    pub fn has_attributes(&self) -> bool {
        !self.attributes.is_empty()
    }

    /// Check if this is an array insert (MINSERT)
    pub fn is_array(&self) -> bool {
        self.column_count > 1 || self.row_count > 1
    }

    /// True when DXF object type is MINSERT (array insert).
    pub fn is_minsert(&self) -> bool {
        self.dwg_minsert || self.is_array()
    }

    /// Get the total number of instances in the array
    pub fn instance_count(&self) -> usize {
        (self.column_count as usize).saturating_mul(self.row_count as usize)
    }

    /// Initial capacity for per-instance vectors. Large MINSERT arrays grow
    /// on demand instead of reserving `rows * columns` elements up front,
    /// which can abort the process for arrays such as 65535 x 65535.
    fn array_capacity_hint(&self) -> usize {
        const MAX_PRERESERVE: usize = 4096;
        self.instance_count().min(MAX_PRERESERVE)
    }

    /// Get all insertion points for array instances
    pub fn array_points(&self) -> Vec<Vector3> {
        if self.instance_count() > Self::MAX_EXPLODE_ARRAY_INSTANCES {
            return Vec::new();
        }
        let mut points = Vec::with_capacity(self.array_capacity_hint());

        for row in 0..self.row_count {
            for col in 0..self.column_count {
                points.push(self.array_point(row, col));
            }
        }

        points
    }

    fn array_point(&self, row: u16, column: u16) -> Vector3 {
        let x = column as f64 * self.column_spacing;
        let y = row as f64 * self.row_spacing;
        let (sin, cos) = self.rotation.sin_cos();
        self.insert_point + Vector3::new(x * cos - y * sin, x * sin + y * cos, 0.0)
    }

    /// Check if the insert has uniform scale
    pub fn has_uniform_scale(&self) -> bool {
        (self.x_scale - self.y_scale).abs() < 1e-10 && (self.y_scale - self.z_scale).abs() < 1e-10
    }

    /// Get the uniform scale factor (if uniform)
    pub fn uniform_scale(&self) -> Option<f64> {
        if self.has_uniform_scale() {
            Some(self.x_scale)
        } else {
            None
        }
    }

    /// Return the DXF subclass marker name.
    ///
    /// `AcDbBlockReference` for normal inserts, or a conceptual "MINSERT"
    /// distinction when array counts exceed 1.
    pub fn subclass_marker(&self) -> &'static str {
        if self.is_minsert() {
            "AcDbMInsertBlock"
        } else {
            "AcDbBlockReference"
        }
    }

    // ── Transform helpers ─────────────

    /// Build the full OCS → WCS transform that positions the block
    /// contents into world space.
    ///
    /// Order: **Scale → Rotate(Z) → ArbitraryAxis(Normal) → Translate**
    pub fn get_transform(&self) -> Transform {
        let ocs = Matrix4::from_matrix3(Matrix3::arbitrary_axis(self.normal));
        let translation = Matrix4::translation(
            self.insert_point.x,
            self.insert_point.y,
            self.insert_point.z,
        );
        let rotation = Matrix4::rotation_z(self.rotation);
        let scale = Matrix4::scaling(self.x_scale, self.y_scale, self.z_scale);

        // Combined: world = OCS * translate * rotate * scale
        Transform::from_matrix(ocs * translation * rotation * scale)
    }

    /// Transform a normal vector correctly for non-uniform scaling.
    ///
    /// Uses the inverse-transpose of the 3×3 rotation/scale portion of
    /// the transform, which is the geometrically correct approach for
    /// normals under non-uniform scale. Falls back to the original
    /// normal if the matrix is singular.
    fn transform_normal(transform: &Transform, normal: Vector3) -> Vector3 {
        let m4 = transform.matrix;
        let upper3x3 = Matrix3::from_rows(
            [m4.m[0][0], m4.m[0][1], m4.m[0][2]],
            [m4.m[1][0], m4.m[1][1], m4.m[1][2]],
            [m4.m[2][0], m4.m[2][1], m4.m[2][2]],
        );
        // Inverse-transpose is the correct normal transform
        if let Some(inv) = upper3x3.inverse() {
            let inv_t = inv.transpose();
            let transformed = inv_t.transform_point(normal);
            let len = transformed.length();
            if len < 1e-10 {
                normal
            } else {
                transformed * (1.0 / len)
            }
        } else {
            normal // fallback for singular matrix
        }
    }

    /// Resolve ByBlock / layer-"0" property inheritance for an exploded entity.
    ///
    /// ACAD convention:
    /// - Entities on layer `"0"` in the block inherit the Insert's layer.
    /// - `Color::ByBlock` inherits the Insert's color.
    /// - `LineWeight::ByBlock` inherits the Insert's line weight.
    /// - Empty/ByLayer linetype with ByBlock semantic: not changed (already
    ///   resolved to ByLayer at the entity level).
    /// - Transparency `ByBlock` inherits the Insert's transparency.
    /// - Linetype `ByBlock` inherits the Insert's linetype (name + handle).
    fn resolve_properties(&self, common: &mut EntityCommon) {
        // Layer "0" → inherit insert's layer
        if common.layer == "0" {
            common.layer = self.common.layer.clone();
            common.layer_handle = self.common.layer_handle;
        }
        // Color ByBlock → inherit insert's color
        if common.color == Color::ByBlock {
            common.color = self.common.color;
            common.color_name = self.common.color_name.clone();
            common.color_book_handle = self.common.color_book_handle;
        }
        // LineWeight ByBlock → inherit insert's line weight
        if common.line_weight == LineWeight::ByBlock {
            common.line_weight = self.common.line_weight;
        }
        // Transparency ByBlock → inherit the insert's transparency
        if common.transparency.is_by_block() {
            common.transparency = self.common.transparency;
        }
        // Linetype ByBlock → inherit the insert's linetype. The name and
        // handle move; the entity keeps its own linetype scale, which is a
        // separate property of the resulting entity.
        if common.linetype.eq_ignore_ascii_case("byblock") {
            common.linetype = self.common.linetype.clone();
            common.linetype_handle = self.common.linetype_handle;
        }
    }

    /// Apply this INSERT's layer/color/linetype inheritance to a detached
    /// member.  Document-level fallback blocks use this after baking nested
    /// geometry so inheritance is resolved through every containing INSERT.
    pub(crate) fn resolve_exploded_properties(&self, common: &mut EntityCommon) {
        self.resolve_properties(common);
    }

    // ── Explode ─────────────────────────────────────────────────

    /// Explode the block reference into individual entities.
    ///
    /// Returns clones (or converted equivalents) of the entities stored in
    /// the referenced block, with the insert's transform applied so they
    /// are positioned in world space.
    ///
    /// `block_entities` should be the `entities` vec from the corresponding
    /// [`BlockRecord`](crate::tables::BlockRecord), relative to the block's
    /// base point. Block/BlockEnd markers are skipped. Attribute definitions
    /// are restored as transformed definitions; instance attribute values
    /// are not included.
    ///
    /// **Property inheritance** (ACAD convention):
    /// - Entities on layer `"0"` → inherit the Insert's layer.
    /// - `Color::ByBlock` → inherit the Insert's color.
    /// - `LineWeight::ByBlock` → inherit the Insert's line weight.
    /// - `Transparency::ByBlock` → inherits the Insert's transparency.
    /// - Linetype `ByBlock` → inherits the Insert's linetype (name + handle).
    ///
    /// **MINSERT arrays**: When `column_count > 1` or `row_count > 1`,
    /// a full copy of every entity is produced at each array position.
    ///
    /// **Entity-specific handling**:
    /// * **Arc** — with uniform XY scale the arc is reconstructed from
    ///   transformed vertices.  With non-uniform XY scale the arc is
    ///   converted to an [`Ellipse`] (elliptical arc).
    /// * **Circle** — converted to an [`Ellipse`] with `ratio = 1.0`
    ///   so that non-uniform scales produce a correct ellipse.
    /// * All other entities are cloned and
    ///   [`apply_transform`](Entity::apply_transform) is called.
    pub fn explode(&self, block_entities: &[EntityType]) -> Vec<EntityType> {
        let transforms = self.array_transforms();
        let mut result = Vec::new();

        for transform in &transforms {
            for entity in block_entities {
                for mut part in self.explode_single_many(entity, transform) {
                    Self::detach_exploded_identity(&mut part);
                    result.push(part);
                }
            }
        }

        result
    }

    /// Clear source database identities from a detached clone.  Geometry and
    /// visual properties remain intact, while ownership, reactors, raw DWG
    /// provenance and embedded INSERT child IDs are regenerated by callers.
    pub(crate) fn detach_exploded_identity(entity: &mut EntityType) {
        let common = entity.common_mut();
        common.handle = Handle::NULL;
        common.owner_handle = Handle::NULL;
        common.xdictionary_handle = None;
        common.reactors.clear();
        common.graphic_data = None;
        common.raw_record = None;
        if let EntityType::Insert(insert) = entity {
            for attribute in &mut insert.attributes {
                attribute.common.handle = Handle::NULL;
                attribute.common.owner_handle = Handle::NULL;
                attribute.common.xdictionary_handle = None;
                attribute.common.reactors.clear();
                attribute.common.graphic_data = None;
                attribute.common.raw_record = None;
            }
            insert.view_rep_handle = None;
            insert.seqend_handle = None;
        }
    }

    /// Expand block members using one already-composed world transform.
    ///
    /// This is used by the document-aware EXPLODE path after it has resolved
    /// the block base point and validated the reference.  It deliberately
    /// bypasses MINSERT array generation; the caller has already applied
    /// ACAD's refusal rules for array references.
    pub(crate) fn explode_with_transform(
        &self,
        block_entities: &[EntityType],
        transform: &Transform,
        detach: bool,
    ) -> Vec<EntityType> {
        let mut result = Vec::new();
        for entity in block_entities {
            for mut part in self.explode_single_many(entity, transform) {
                if detach {
                    Self::detach_exploded_identity(&mut part);
                }
                result.push(part);
            }
        }
        result
    }

    /// Build a transform for each array cell (single transform when not MINSERT).
    fn array_transforms(&self) -> Vec<Transform> {
        if !self.is_minsert() {
            return vec![self.get_transform()];
        }
        if self.instance_count() > Self::MAX_EXPLODE_ARRAY_INSTANCES {
            return Vec::new();
        }

        let ocs = Matrix4::from_matrix3(Matrix3::arbitrary_axis(self.normal));
        let rotation = Matrix4::rotation_z(self.rotation);
        let scale = Matrix4::scaling(self.x_scale, self.y_scale, self.z_scale);

        let mut transforms = Vec::with_capacity(self.array_capacity_hint());
        for row in 0..self.row_count {
            for col in 0..self.column_count {
                let cell_pt = self.array_point(row, col);
                let translation = Matrix4::translation(cell_pt.x, cell_pt.y, cell_pt.z);
                transforms.push(Transform::from_matrix(ocs * translation * rotation * scale));
            }
        }
        transforms
    }

    /// Explode a single entity with the given transform, returning `None`
    /// for structural entities that should be skipped.
    fn explode_single(&self, entity: &EntityType, transform: &Transform) -> Option<EntityType> {
        match entity {
            // Skip structural / meta entities
            EntityType::Block(_) | EntityType::BlockEnd(_) => None,

            // Arc handling — uniform XY keeps Arc, non-uniform → Ellipse
            EntityType::Arc(arc) => {
                if Self::plane_is_similarity(transform, arc.normal) {
                    Some(self.explode_arc_uniform(arc, transform))
                } else {
                    Some(self.explode_arc_to_ellipse(arc, transform))
                }
            }

            // Circle → Ellipse so non-uniform scale works
            EntityType::Circle(circle) => {
                // CIRCLE stores `center` in OCS; ELLIPSE is a WCS entity —
                // convert on the way in (identity for the Z-up normal).
                if Self::plane_is_similarity(transform, circle.normal) {
                    let mut transformed = circle.clone();
                    super::transform::transform_circle(&mut transformed, transform);
                    transformed.thickness *= transform.apply_rotation(circle.normal).length();
                    self.resolve_properties(&mut transformed.common);
                    Some(EntityType::Circle(transformed))
                } else {
                    let ocs_to_wcs = Matrix3::arbitrary_axis(circle.normal);
                    let mut ellipse = Ellipse {
                        common: circle.common.clone(),
                        center: ocs_to_wcs * circle.center,
                        major_axis: ocs_to_wcs * (Vector3::UNIT_X * circle.radius),
                        minor_axis_ratio: 1.0,
                        start_parameter: 0.0,
                        end_parameter: std::f64::consts::TAU,
                        normal: circle.normal,
                    };
                    super::transform::transform_ellipse(&mut ellipse, transform);
                    self.resolve_properties(&mut ellipse.common);
                    Some(EntityType::Ellipse(ellipse))
                }
            }

            // Default path — clone + transform
            _ => {
                let mut cloned = entity.clone();
                cloned.as_entity_mut().apply_transform(transform);
                self.resolve_properties(cloned.common_mut());
                Some(cloned)
            }
        }
    }

    /// Expand bulged polylines before applying a non-uniform block transform.
    /// A retained bulge would still describe a circular arc after stretching,
    /// while ACAD emits an exact elliptical segment.
    fn explode_single_many(&self, entity: &EntityType, transform: &Transform) -> Vec<EntityType> {
        // Modeler entities are explodable when the block transform is a
        // rigid transform or uniform scale.  Under those transforms their
        // native region decomposition remains exact; non-uniform cases are
        // handled by the document-aware anonymous *E fallback instead.
        if matches!(
            entity,
            EntityType::Solid3D(_) | EntityType::Region(_) | EntityType::Body(_)
        ) && Self::linear_is_similarity(transform)
        {
            return entity
                .explode()
                .into_iter()
                .map(|mut piece| {
                    piece.as_entity_mut().apply_transform(transform);
                    piece
                })
                .collect();
        }
        let normal = match entity {
            EntityType::LwPolyline(polyline) => polyline.normal,
            EntityType::Polyline2D(polyline) => polyline.normal,
            _ => Vector3::UNIT_Z,
        };
        let has_bulge = match entity {
            EntityType::LwPolyline(polyline) => polyline
                .vertices
                .iter()
                .any(|vertex| vertex.bulge.abs() > 1e-10),
            EntityType::Polyline2D(polyline) => polyline
                .vertices
                .iter()
                .any(|vertex| vertex.bulge.abs() > 1e-10),
            _ => false,
        };
        if has_bulge && !Self::plane_is_similarity(transform, normal) {
            return entity
                .explode()
                .iter()
                .filter_map(|piece| self.explode_single(piece, transform))
                .collect();
        }
        self.explode_single(entity, transform).into_iter().collect()
    }

    /// Return true when a linear transform preserves circles in a plane.  The
    /// two transformed OCS basis vectors must remain perpendicular and have
    /// equal length; this also handles tilted source planes correctly.
    fn plane_is_similarity(transform: &Transform, normal: Vector3) -> bool {
        let basis = Matrix3::arbitrary_axis(normal);
        let x = transform.apply_rotation(basis * Vector3::UNIT_X);
        let y = transform.apply_rotation(basis * Vector3::UNIT_Y);
        let lx = x.length();
        let ly = y.length();
        lx > SCALE_EPSILON
            && ly > SCALE_EPSILON
            && (lx - ly).abs() <= 1e-10 * lx.max(ly)
            && x.dot(&y).abs() <= 1e-10 * lx * ly
    }

    fn linear_is_similarity(transform: &Transform) -> bool {
        let x = transform.apply_rotation(Vector3::UNIT_X);
        let y = transform.apply_rotation(Vector3::UNIT_Y);
        let z = transform.apply_rotation(Vector3::UNIT_Z);
        let vectors = [x, y, z];
        let lengths = vectors.map(|vector| vector.length());
        lengths.iter().all(|length| *length > SCALE_EPSILON)
            && (lengths[0] - lengths[1]).abs() <= 1e-10 * lengths[0].max(lengths[1])
            && (lengths[1] - lengths[2]).abs() <= 1e-10 * lengths[1].max(lengths[2])
            && x.dot(&y).abs() <= 1e-10 * lengths[0] * lengths[1]
            && x.dot(&z).abs() <= 1e-10 * lengths[0] * lengths[2]
            && y.dot(&z).abs() <= 1e-10 * lengths[1] * lengths[2]
    }

    /// Whether a linear transform introduces shear relative to an INSERT's
    /// orthogonal local axes.  INSERT can encode three signed scales and one
    /// rotation, so non-orthogonal transformed basis vectors require an
    /// anonymous fallback block in the document-aware EXPLODE path.
    pub(crate) fn has_unrepresentable_shear(transform: &Transform) -> bool {
        let x = transform.apply_rotation(Vector3::UNIT_X);
        let y = transform.apply_rotation(Vector3::UNIT_Y);
        let z = transform.apply_rotation(Vector3::UNIT_Z);
        let vectors = [x, y, z];
        for i in 0..vectors.len() {
            for j in (i + 1)..vectors.len() {
                let scale = vectors[i].length() * vectors[j].length();
                if scale > SCALE_EPSILON && vectors[i].dot(&vectors[j]).abs() > 1e-10 * scale {
                    return true;
                }
            }
        }
        false
    }

    /// Explode an arc with uniform XY scale — keeps it as an Arc.
    fn explode_arc_uniform(&self, arc: &Arc, transform: &Transform) -> EntityType {
        // DXF arcs store `center` in OCS (arbitrary-axis algorithm with the
        // arc's normal). Convert everything to WCS, apply the INSERT transform
        // in WCS, then project back into the new arc's OCS so the renderer
        // (which always treats `center` as OCS) reproduces the correct WCS
        // position regardless of normal direction.
        let ocs_to_wcs = Matrix3::arbitrary_axis(arc.normal);
        let center_wcs = ocs_to_wcs * arc.center;
        let wcs_start = center_wcs
            + ocs_to_wcs
                * Vector3::new(
                    arc.radius * arc.start_angle.cos(),
                    arc.radius * arc.start_angle.sin(),
                    0.0,
                );
        let wcs_end = center_wcs
            + ocs_to_wcs
                * Vector3::new(
                    arc.radius * arc.end_angle.cos(),
                    arc.radius * arc.end_angle.sin(),
                    0.0,
                );

        let new_center_wcs = transform.apply(center_wcs);
        let new_start_wcs = transform.apply(wcs_start);
        let new_end_wcs = transform.apply(wcs_end);

        let new_radius = (new_start_wcs - new_center_wcs).length();
        let mut new_normal = Self::transform_normal(transform, arc.normal);

        // Handedness correction: a transform with negative upper-3×3 determinant
        // (e.g. odd-count mirror in the INSERT scale) flips the OCS plane's
        // orientation. Arcs are always CCW around their normal, so to preserve
        // the visual sweep we flip the normal — the new OCS basis is then the
        // mirror of the old one and CCW around the flipped normal traces the
        // mirrored geometry.
        if Self::upper3x3_determinant(transform) < 0.0 {
            new_normal = new_normal * -1.0;
        }

        // Convert transformed WCS offsets back to OCS angles & center for the
        // new normal so to_truck()'s arc_pt (which applies the new OCS) gives
        // correct WCS points.
        let new_ocs_to_wcs = Matrix3::arbitrary_axis(new_normal);
        let new_wcs_to_ocs = new_ocs_to_wcs.transpose();
        let new_center_ocs = new_wcs_to_ocs * new_center_wcs;
        let ds_ocs = new_wcs_to_ocs * (new_start_wcs - new_center_wcs);
        let de_ocs = new_wcs_to_ocs * (new_end_wcs - new_center_wcs);
        let new_start_angle = ds_ocs.y.atan2(ds_ocs.x);
        let new_end_angle = de_ocs.y.atan2(de_ocs.x);

        let mut new_arc = Arc::from_center_radius_angles(
            new_center_ocs,
            new_radius,
            new_start_angle,
            new_end_angle,
        );
        new_arc.normal = new_normal;
        new_arc.thickness = arc.thickness * transform.apply_rotation(arc.normal).length();
        new_arc.common = arc.common.clone();
        self.resolve_properties(&mut new_arc.common);
        EntityType::Arc(new_arc)
    }

    /// Determinant of the upper-3×3 portion of a transform's matrix.
    /// Negative ⇒ the transform reverses handedness (a reflection).
    fn upper3x3_determinant(transform: &Transform) -> f64 {
        let m = transform.matrix.m;
        Matrix3::from_rows(
            [m[0][0], m[0][1], m[0][2]],
            [m[1][0], m[1][1], m[1][2]],
            [m[2][0], m[2][1], m[2][2]],
        )
        .determinant()
    }

    /// Explode an arc with non-uniform XY scale — converts to an elliptical arc (Ellipse).
    fn explode_arc_to_ellipse(&self, arc: &Arc, transform: &Transform) -> EntityType {
        // ARC stores `center` in OCS; ELLIPSE is a WCS entity. Convert on the
        // way in (identity for the common Z-up normal). The arc's angles are
        // measured against the OCS X axis, which becomes the ellipse's major
        // axis below — so the parameters carry over unchanged.
        let ocs_to_wcs = Matrix3::arbitrary_axis(arc.normal);
        let mut ellipse = Ellipse {
            common: arc.common.clone(),
            center: ocs_to_wcs * arc.center,
            major_axis: ocs_to_wcs * (Vector3::UNIT_X * arc.radius),
            minor_axis_ratio: 1.0,
            start_parameter: arc.start_angle,
            end_parameter: arc.end_angle,
            normal: arc.normal,
        };
        super::transform::transform_ellipse(&mut ellipse, transform);
        self.resolve_properties(&mut ellipse.common);
        EntityType::Ellipse(ellipse)
    }

    /// The entities of this insert's block, read from `document` and moved
    /// so the block's base point is at the origin, ready for
    /// [`explode`](Self::explode). `None` when the block record is missing,
    /// refuses explosion or is an external reference.
    pub fn block_entities_from_document(
        &self,
        document: &crate::document::CadDocument,
    ) -> Option<Vec<EntityType>> {
        let br = document.block_records.get(&self.block_name)?;
        if !br.explodable
            || br.flags.is_xref
            || br.flags.is_xref_overlay
            || br.flags.is_external
            || !br.xref_path.is_empty()
        {
            return None;
        }
        let base = document
            .get_entity(br.block_entity_handle)
            .and_then(|entity| match entity {
                EntityType::Block(block) => Some(block.base_point),
                _ => None,
            })
            .unwrap_or(br.base_point);
        let to_base = Transform::from_translation(base * -1.0);
        Some(
            br.entity_handles
                .iter()
                .filter_map(|h| {
                    document.entity_index.get(h).map(|&idx| {
                        let mut entity = document.entities[idx].as_ref().clone();
                        entity.as_entity_mut().apply_transform(&to_base);
                        entity
                    })
                })
                .collect(),
        )
    }

    /// Convenience wrapper that looks up the block in a
    /// [`CadDocument`](crate::document::CadDocument) by `block_name` and
    /// calls [`explode`](Self::explode) with contents relative to its base point.
    ///
    /// Returns an empty `Vec` when the block record is not found or refuses explosion.
    pub fn explode_from_document(
        &self,
        document: &crate::document::CadDocument,
    ) -> Vec<EntityType> {
        // ACAD's EXPLODE command refuses array inserts and external
        // references.  The context-aware document API applies the same rules;
        // keep this read-only convenience wrapper consistent as well.
        if self.is_minsert() {
            return Vec::new();
        }
        self.block_entities_from_document(document)
            .map(|entities| self.explode(&entities))
            .unwrap_or_default()
    }
}

impl Entity for Insert {
    fn common(&self) -> &super::EntityCommon {
        &self.common
    }

    fn common_mut(&mut self) -> &mut super::EntityCommon {
        &mut self.common
    }

    fn bounding_box(&self) -> BoundingBox3D {
        // For now, return a bounding box at the insertion point
        // In a full implementation, this would need to reference the block definition
        BoundingBox3D::from_point(self.insert_point)
    }

    fn translate(&mut self, offset: Vector3) {
        super::translate::translate_insert(self, offset);
    }

    fn entity_type(&self) -> &'static str {
        if self.is_minsert() {
            "MINSERT"
        } else {
            "INSERT"
        }
    }

    fn apply_transform(&mut self, transform: &Transform) {
        super::transform::transform_insert(self, transform);
    }

    fn apply_mirror(&mut self, transform: &Transform) {
        super::mirror::mirror_insert(self, transform);
    }

    fn apply_mirror_with_options(&mut self, transform: &Transform, options: super::MirrorOptions) {
        super::mirror::mirror_insert_with_options(self, transform, options);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entities::{AttributeDefinition, Block, BlockEnd, Circle, Line};
    use crate::types::Transparency;
    use std::f64::consts::{FRAC_PI_2, PI, TAU};

    #[test]
    fn huge_minsert_does_not_prereserve_full_array() {
        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.row_count = u16::MAX;
        insert.column_count = u16::MAX;
        assert_eq!(insert.instance_count(), 65535 * 65535);
        assert!(insert.array_capacity_hint() <= 4096);
        assert!(insert.array_points().is_empty());
        assert!(insert.explode(&[EntityType::Line(Line::new())]).is_empty());
    }

    /// Helper – approximate equality for f64
    fn approx(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-6
    }

    /// Helper – approximate equality for Vector3
    fn approx_vec(a: Vector3, b: Vector3) -> bool {
        approx(a.x, b.x) && approx(a.y, b.y) && approx(a.z, b.z)
    }

    // ── basic explode ───────────────────────────────────────────

    #[test]
    fn explode_empty_block_returns_empty() {
        let insert = Insert::new("TestBlock", Vector3::ZERO);
        let result = insert.explode(&[]);
        assert!(result.is_empty());
    }

    #[test]
    fn explode_skips_block_markers_and_restores_attdefs() {
        let block_entities = vec![
            EntityType::Block(Block::new("TestBlock", Vector3::ZERO)),
            EntityType::Line(Line::from_points(
                Vector3::ZERO,
                Vector3::new(1.0, 0.0, 0.0),
            )),
            EntityType::AttributeDefinition(AttributeDefinition::new(
                "TAG".into(),
                "prompt".into(),
                "default".into(),
            )),
            EntityType::BlockEnd(BlockEnd::new()),
        ];

        let mut insert = Insert::new("TestBlock", Vector3::ZERO);
        insert
            .attributes
            .push(crate::entities::AttributeEntity::new(
                "TAG".into(),
                "instance value".into(),
            ));
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 2);
        assert!(matches!(result[0], EntityType::Line(_)));
        let EntityType::AttributeDefinition(definition) = &result[1] else {
            panic!("expected the attribute definition");
        };
        assert_eq!(definition.default_value, "default");
        assert_eq!(insert.attributes[0].get_value(), "instance value");
    }

    #[test]
    fn explode_minsert_transforms_attdefs_at_every_cell() {
        let mut definition =
            AttributeDefinition::new("TAG".into(), "Prompt".into(), "Default".into());
        definition.insertion_point = Vector3::new(2.0, 3.0, 0.0);
        definition.alignment_point = Vector3::new(4.0, 3.0, 0.0);
        definition.height = 1.5;
        definition.common.color = Color::ByBlock;
        definition.common.line_weight = LineWeight::ByBlock;
        definition.flags.constant = true;
        let input = vec![EntityType::AttributeDefinition(definition.clone())];
        let mut insert = Insert::new("B", Vector3::new(100.0, 100.0, 0.0))
            .with_uniform_scale(2.0)
            .with_rotation(FRAC_PI_2)
            .with_array(2, 2, 10.0, 20.0);
        insert.common.layer = "Labels".into();
        insert.common.color = Color::from_index(3);
        insert.common.line_weight = LineWeight::from_value(50);

        let pieces = insert.explode(&input);
        assert_eq!(pieces.len(), 4);
        let expected = [(94.0, 104.0), (94.0, 114.0), (74.0, 104.0), (74.0, 114.0)];
        for (piece, (x, y)) in pieces.iter().zip(expected) {
            let EntityType::AttributeDefinition(actual) = piece else {
                panic!("expected an attribute definition in every array cell");
            };
            assert!(approx_vec(actual.insertion_point, Vector3::new(x, y, 0.0)));
            assert!(approx_vec(
                actual.alignment_point,
                Vector3::new(x, y + 4.0, 0.0)
            ));
            assert!(approx(actual.height, 3.0));
            assert!(approx(actual.rotation, FRAC_PI_2));
            assert_eq!(actual.common.layer, "Labels");
            assert_eq!(actual.common.color, insert.common.color);
            assert_eq!(actual.common.line_weight, insert.common.line_weight);
            assert!(actual.flags.constant);
            assert_eq!(actual.tag, "TAG");
            assert_eq!(actual.prompt, "Prompt");
            assert_eq!(actual.default_value, "Default");
        }
        let EntityType::AttributeDefinition(unchanged) = &input[0] else {
            unreachable!()
        };
        assert_eq!(unchanged.insertion_point, definition.insertion_point);
        assert_eq!(unchanged.height, definition.height);
        assert_eq!(unchanged.common.layer, definition.common.layer);
    }

    #[test]
    fn explode_from_document_uses_block_base_and_explodable_flag() {
        let mut document = crate::CadDocument::new();
        let mut record = crate::tables::BlockRecord::new("B");
        record.handle = document.allocate_handle();
        record.base_point = Vector3::new(40.0, 50.0, 0.0);
        let owner = record.handle;
        document.block_records.add(record).unwrap();
        let mut block = Block::new("B", Vector3::new(10.0, 5.0, 0.0));
        block.common.owner_handle = owner;
        let marker = document.add_entity(EntityType::Block(block)).unwrap();
        document
            .block_records
            .get_mut("B")
            .unwrap()
            .block_entity_handle = marker;
        let mut definition =
            AttributeDefinition::new("TAG".into(), "Prompt".into(), "Default".into());
        definition.common.owner_handle = owner;
        definition.insertion_point = Vector3::new(12.0, 8.0, 0.0);
        document
            .add_entity(EntityType::AttributeDefinition(definition))
            .unwrap();
        let insert = Insert::new("b", Vector3::new(100.0, 100.0, 0.0))
            .with_uniform_scale(2.0)
            .with_rotation(FRAC_PI_2);
        let pieces = insert.explode_from_document(&document);
        assert_eq!(pieces.len(), 1);
        let EntityType::AttributeDefinition(actual) = &pieces[0] else {
            panic!("expected an attribute definition");
        };
        assert!(approx_vec(
            actual.insertion_point,
            Vector3::new(94.0, 104.0, 0.0)
        ));
        document
            .block_records
            .get_mut("B")
            .unwrap()
            .block_entity_handle = Handle::NULL;
        let fallback = insert.explode_from_document(&document);
        let EntityType::AttributeDefinition(actual) = &fallback[0] else {
            panic!("expected an attribute definition using the record base");
        };
        assert!(approx_vec(
            actual.insertion_point,
            Vector3::new(184.0, 44.0, 0.0)
        ));
        document.block_records.get_mut("B").unwrap().explodable = false;
        assert!(insert.explode_from_document(&document).is_empty());
        assert!(Insert::new("missing", Vector3::ZERO)
            .explode_from_document(&document)
            .is_empty());
    }

    // ── identity insert ─────────────────────────────────────────

    #[test]
    fn explode_identity_insert_preserves_line() {
        let line = Line::from_points(Vector3::new(0.0, 0.0, 0.0), Vector3::new(10.0, 0.0, 0.0));
        let block_entities = vec![EntityType::Line(line)];

        let insert = Insert::new("B", Vector3::ZERO);
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 1);
        if let EntityType::Line(l) = &result[0] {
            assert!(approx_vec(l.start, Vector3::new(0.0, 0.0, 0.0)));
            assert!(approx_vec(l.end, Vector3::new(10.0, 0.0, 0.0)));
        } else {
            panic!("expected Line");
        }
    }

    // ── translation ─────────────────────────────────────────────

    #[test]
    fn explode_with_translation() {
        let line = Line::from_points(Vector3::ZERO, Vector3::new(5.0, 0.0, 0.0));
        let block_entities = vec![EntityType::Line(line)];

        let insert = Insert::new("B", Vector3::new(10.0, 20.0, 0.0));
        let result = insert.explode(&block_entities);

        if let EntityType::Line(l) = &result[0] {
            assert!(approx_vec(l.start, Vector3::new(10.0, 20.0, 0.0)));
            assert!(approx_vec(l.end, Vector3::new(15.0, 20.0, 0.0)));
        } else {
            panic!("expected Line");
        }
    }

    // ── uniform scale ───────────────────────────────────────────

    #[test]
    fn explode_with_uniform_scale() {
        let line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        let block_entities = vec![EntityType::Line(line)];

        let insert = Insert::new("B", Vector3::ZERO).with_uniform_scale(3.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Line(l) = &result[0] {
            assert!(approx_vec(l.end, Vector3::new(3.0, 0.0, 0.0)));
        } else {
            panic!("expected Line");
        }
    }

    // ── rotation ────────────────────────────────────────────────

    #[test]
    fn explode_with_90_degree_rotation() {
        let line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        let block_entities = vec![EntityType::Line(line)];

        let insert = Insert::new("B", Vector3::ZERO).with_rotation(FRAC_PI_2);
        let result = insert.explode(&block_entities);

        if let EntityType::Line(l) = &result[0] {
            assert!(approx_vec(l.end, Vector3::new(0.0, 1.0, 0.0)));
        } else {
            panic!("expected Line");
        }
    }

    // ── combined scale + translation ────────────────────────────

    #[test]
    fn explode_with_scale_and_translation() {
        let line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 1.0, 0.0));
        let block_entities = vec![EntityType::Line(line)];

        let insert = Insert::new("B", Vector3::new(5.0, 5.0, 0.0)).with_scale(2.0, 3.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Line(l) = &result[0] {
            assert!(approx_vec(l.start, Vector3::new(5.0, 5.0, 0.0)));
            assert!(approx_vec(l.end, Vector3::new(7.0, 8.0, 0.0)));
        } else {
            panic!("expected Line");
        }
    }

    // ── Circle → Ellipse conversion ─────────────────────────────

    #[test]
    fn explode_circle_uniform_preserves_circle() {
        let circle = Circle::from_center_radius(Vector3::ZERO, 5.0);
        let block_entities = vec![EntityType::Circle(circle)];

        let insert = Insert::new("B", Vector3::ZERO);
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 1);
        assert!(matches!(result[0], EntityType::Circle(_)));

        if let EntityType::Circle(e) = &result[0] {
            assert!(approx(e.radius, 5.0));
        } else {
            panic!("expected Circle");
        }
    }

    #[test]
    fn explode_circle_with_non_uniform_scale() {
        let circle = Circle::from_center_radius(Vector3::ZERO, 1.0);
        let block_entities = vec![EntityType::Circle(circle)];

        // Scale X by 2, Y by 1 → ellipse with major=2, minor=1
        let insert = Insert::new("B", Vector3::ZERO).with_scale(2.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Ellipse(e) = &result[0] {
            let major_len = e.major_axis.length();
            let minor_len = major_len * e.minor_axis_ratio;
            assert!(approx(major_len, 2.0));
            assert!(approx(minor_len, 1.0));
            assert!(approx(e.minor_axis_ratio, 0.5));
        } else {
            panic!("expected Ellipse");
        }
    }

    #[test]
    fn explode_circle_non_uniform_scale_minor_becomes_major() {
        let circle = Circle::from_center_radius(Vector3::ZERO, 1.0);
        let block_entities = vec![EntityType::Circle(circle)];

        // Scale X by 1, Y by 3 → original minor direction (Y) becomes major
        let insert = Insert::new("B", Vector3::ZERO).with_scale(1.0, 3.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Ellipse(e) = &result[0] {
            let major_len = e.major_axis.length();
            let minor_len = major_len * e.minor_axis_ratio;
            // Major should be 3 (the larger), minor should be 1
            assert!(approx(major_len, 3.0));
            assert!(approx(minor_len, 1.0));
        } else {
            panic!("expected Ellipse");
        }
    }

    // ── Arc reconstruction ──────────────────────────────────────

    #[test]
    fn explode_arc_identity() {
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 5.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc.clone())];

        let insert = Insert::new("B", Vector3::ZERO);
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 1);
        if let EntityType::Arc(a) = &result[0] {
            assert!(approx(a.radius, 5.0));
            assert!(approx(a.start_angle, 0.0));
            assert!(approx(a.end_angle, FRAC_PI_2));
            assert!(approx_vec(a.center, Vector3::ZERO));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_with_translation() {
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 10.0, 0.0, PI);
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::new(100.0, 200.0, 0.0));
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            assert!(approx_vec(a.center, Vector3::new(100.0, 200.0, 0.0)));
            assert!(approx(a.radius, 10.0));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_with_uniform_scale() {
        let arc = Arc::from_center_radius_angles(Vector3::new(1.0, 1.0, 0.0), 2.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::ZERO).with_uniform_scale(3.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            assert!(approx(a.radius, 6.0)); // 2 * 3
            assert!(approx_vec(a.center, Vector3::new(3.0, 3.0, 0.0)));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_non_uniform_becomes_ellipse() {
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 5.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        // Non-uniform scale → arc must become an elliptical arc
        let insert = Insert::new("B", Vector3::ZERO).with_scale(2.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 1);
        if let EntityType::Ellipse(e) = &result[0] {
            // Major axis should be 10 (5*2), minor 5 (5*1)
            let major_len = e.major_axis.length();
            let minor_len = major_len * e.minor_axis_ratio;
            assert!(approx(major_len, 10.0));
            assert!(approx(minor_len, 5.0));
            // It's a partial ellipse (not full)
            assert!(!e.is_full());
        } else {
            panic!("expected Ellipse for non-uniform arc");
        }
    }

    // ── multiple entities ───────────────────────────────────────

    #[test]
    fn explode_multiple_entities() {
        let block_entities = vec![
            EntityType::Line(Line::from_points(
                Vector3::ZERO,
                Vector3::new(1.0, 0.0, 0.0),
            )),
            EntityType::Circle(Circle::from_center_radius(Vector3::ZERO, 1.0)),
            EntityType::Arc(Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, PI)),
        ];

        let insert = Insert::new("B", Vector3::new(10.0, 0.0, 0.0));
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 3);
        assert!(matches!(result[0], EntityType::Line(_)));
        assert!(matches!(result[1], EntityType::Circle(_))); // uniform circle is preserved
        assert!(matches!(result[2], EntityType::Arc(_))); // uniform scale → stays Arc
    }

    // ── Layer "0" inheritance ───────────────────────────────────

    #[test]
    fn explode_layer_zero_inherits_insert_layer() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.layer = "0".to_string(); // layer "0" in block
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.layer = "Walls".to_string();
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().layer, "Walls");
    }

    #[test]
    fn explode_named_layer_preserved() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.layer = "Hidden".to_string();
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.layer = "Walls".to_string();
        let result = insert.explode(&block_entities);

        // Named layer stays — NOT replaced by insert's layer
        assert_eq!(result[0].common().layer, "Hidden");
    }

    // ── ByBlock property resolution ─────────────────────────────

    #[test]
    fn explode_byblock_color_inherits_insert_color() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.color = Color::ByBlock;
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.color = Color::from_index(1); // Red
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().color, Color::from_index(1));
    }

    #[test]
    fn explode_byblock_lineweight_inherits_insert_lineweight() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.line_weight = LineWeight::ByBlock;
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.line_weight = LineWeight::from_value(50); // 0.50mm
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().line_weight, LineWeight::from_value(50));
    }

    #[test]
    fn explode_non_byblock_color_preserved() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.color = Color::from_index(3); // Green
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.color = Color::from_index(1); // Red
        let result = insert.explode(&block_entities);

        // Green stays — NOT replaced
        assert_eq!(result[0].common().color, Color::from_index(3));
    }

    #[test]
    fn explode_byblock_transparency_inherits_insert_transparency() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.transparency = Transparency::ByBlock;
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.transparency = Transparency::new(96);
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().transparency, Transparency::new(96));
    }

    #[test]
    fn explode_byblock_linetype_inherits_insert_linetype() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.linetype = "ByBlock".to_string();
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.linetype = "DASHED".to_string();
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().linetype, "DASHED");
    }

    #[test]
    fn explode_byblock_linetype_matches_name_case_insensitively() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.linetype = "byblock".to_string();
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.linetype = "DASHED".to_string();
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().linetype, "DASHED");
    }

    #[test]
    fn explode_byblock_linetype_keeps_the_entities_own_scale() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.linetype = "ByBlock".to_string();
        line.common.linetype_scale = 2.0;
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.linetype = "DASHED".to_string();
        insert.common.linetype_scale = 0.5;
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().linetype, "DASHED");
        assert_eq!(result[0].common().linetype_scale, 2.0);
    }

    #[test]
    fn explode_non_byblock_transparency_preserved() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.transparency = Transparency::new(25);
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.transparency = Transparency::new(96);
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().transparency, Transparency::new(25));
    }

    #[test]
    fn explode_non_byblock_linetype_preserved() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.linetype = "CONTINUOUS".to_string();
        let block_entities = vec![EntityType::Line(line)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.linetype = "DASHED".to_string();
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().linetype, "CONTINUOUS");
    }

    // ── MINSERT array ───────────────────────────────────────────

    #[test]
    fn explode_minsert_produces_array_copies() {
        let line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        let block_entities = vec![EntityType::Line(line)];

        // 2 columns × 3 rows = 6 copies
        let insert = Insert::new("B", Vector3::new(0.0, 0.0, 0.0)).with_array(2, 3, 10.0, 20.0);
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 6);
        // All should be Lines
        for e in &result {
            assert!(matches!(e, EntityType::Line(_)));
        }
    }

    #[test]
    fn explode_minsert_positions_correct() {
        let line = Line::from_points(Vector3::ZERO, Vector3::ZERO); // zero-length line at origin
        let block_entities = vec![EntityType::Line(line)];

        // 2 columns, 1 row, spacing 10
        let insert = Insert::new("B", Vector3::new(5.0, 0.0, 0.0)).with_array(2, 1, 10.0, 0.0);
        let result = insert.explode(&block_entities);

        assert_eq!(result.len(), 2);
        if let EntityType::Line(l0) = &result[0] {
            assert!(approx_vec(l0.start, Vector3::new(5.0, 0.0, 0.0)));
        }
        if let EntityType::Line(l1) = &result[1] {
            // Second column: insert_point.x + column_spacing = 5 + 10 = 15
            assert!(approx_vec(l1.start, Vector3::new(15.0, 0.0, 0.0)));
        }
    }

    #[test]
    fn explode_minsert_positions_follow_rotated_spacing_without_scaling_it() {
        let input = vec![EntityType::Line(Line::from_points(
            Vector3::ZERO,
            Vector3::ZERO,
        ))];
        let insert = Insert::new("B", Vector3::new(100.0, 100.0, 0.0))
            .with_rotation(FRAC_PI_2)
            .with_uniform_scale(3.0)
            .with_array(2, 2, 10.0, 20.0);
        let pieces = insert.explode(&input);
        assert_eq!(pieces.len(), 4);
        for (piece, (x, y)) in
            pieces
                .iter()
                .zip([(100.0, 100.0), (100.0, 110.0), (80.0, 100.0), (80.0, 110.0)])
        {
            let EntityType::Line(line) = piece else {
                panic!("expected LINE");
            };
            assert!(approx_vec(line.start, Vector3::new(x, y, 0.0)));
        }
    }

    // ── Arc + Circle property inheritance ───────────────────────

    #[test]
    fn explode_arc_layer_zero_inherits() {
        let mut arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, PI);
        arc.common.layer = "0".to_string();
        let block_entities = vec![EntityType::Arc(arc)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.layer = "Pipes".to_string();
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().layer, "Pipes");
    }

    #[test]
    fn explode_circle_byblock_color_inherits() {
        let mut circle = Circle::from_center_radius(Vector3::ZERO, 1.0);
        circle.common.color = Color::ByBlock;
        let block_entities = vec![EntityType::Circle(circle)];

        let mut insert = Insert::new("B", Vector3::ZERO);
        insert.common.color = Color::from_index(5); // Blue
        let result = insert.explode(&block_entities);

        if let EntityType::Circle(e) = &result[0] {
            assert_eq!(e.common.color, Color::from_index(5));
        } else {
            panic!("expected Circle");
        }
    }

    #[test]
    fn explode_preserves_entity_layer() {
        let mut line = Line::from_points(Vector3::ZERO, Vector3::new(1.0, 0.0, 0.0));
        line.common.layer = "MyLayer".to_string();
        let block_entities = vec![EntityType::Line(line)];

        let insert = Insert::new("B", Vector3::ZERO);
        let result = insert.explode(&block_entities);

        assert_eq!(result[0].common().layer, "MyLayer");
    }

    #[test]
    fn explode_arc_preserves_layer() {
        let mut arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, PI);
        arc.common.layer = "ArcLayer".to_string();
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::ZERO);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            assert_eq!(a.common.layer, "ArcLayer");
        } else {
            panic!("expected Arc");
        }
    }

    // ── Mirrored INSERT arc handedness ──────────────────────────
    //
    // The visual sweep direction of an arc inside a mirrored block must match
    // the mirror of the original sweep. acadrust encodes this by emitting a
    // flipped normal so that the CCW (around-normal) parameterization traces
    // the mirrored geometry.

    /// Reconstruct an arc's three sample points (start, midpoint, end) in WCS,
    /// using the renderer's OCS-axis convention. `arc.center` is interpreted as
    /// OCS coordinates (per DXF arbitrary-axis algorithm).
    fn arc_sample_points(arc: &Arc) -> (Vector3, Vector3, Vector3) {
        let basis = Matrix3::arbitrary_axis(arc.normal);
        let center_wcs = basis * arc.center;
        let ccw_end = if arc.end_angle >= arc.start_angle {
            arc.end_angle
        } else {
            arc.end_angle + TAU
        };
        let mid = arc.start_angle + (ccw_end - arc.start_angle) * 0.5;
        let pt = |a: f64| {
            center_wcs + basis * Vector3::new(arc.radius * a.cos(), arc.radius * a.sin(), 0.0)
        };
        (pt(arc.start_angle), pt(mid), pt(arc.end_angle))
    }

    #[test]
    fn explode_arc_mirror_x_preserves_sweep_direction() {
        // Original arc traces Q1 from (r,0) through (~0.707r, ~0.707r) to (0,r).
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        // Mirror-X (x_scale = -1) should produce a CCW arc through Q2.
        let insert = Insert::new("B", Vector3::ZERO).with_scale(-1.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            let (start, mid, end) = arc_sample_points(a);
            // Endpoints land at the mirrored positions.
            assert!(approx_vec(start, Vector3::new(-1.0, 0.0, 0.0)));
            assert!(approx_vec(end, Vector3::new(0.0, 1.0, 0.0)));
            // Crucially, the midpoint is in Q2 (mirror of the original Q1 midpoint),
            // not Q4 (which is what you would see if the sweep went the wrong way).
            let inv_sqrt2 = std::f64::consts::FRAC_1_SQRT_2;
            assert!(approx_vec(mid, Vector3::new(-inv_sqrt2, inv_sqrt2, 0.0)));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_mirror_y_preserves_sweep_direction() {
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        // Mirror-Y (y_scale = -1) → mirrored arc should trace Q4.
        let insert = Insert::new("B", Vector3::ZERO).with_scale(1.0, -1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            let (start, mid, end) = arc_sample_points(a);
            assert!(approx_vec(start, Vector3::new(1.0, 0.0, 0.0)));
            assert!(approx_vec(end, Vector3::new(0.0, -1.0, 0.0)));
            let inv_sqrt2 = std::f64::consts::FRAC_1_SQRT_2;
            assert!(approx_vec(mid, Vector3::new(inv_sqrt2, -inv_sqrt2, 0.0)));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_double_mirror_is_rotation() {
        // x_scale = -1, y_scale = -1 has det = +1 (a 180° rotation), so the
        // normal must NOT be flipped and the arc should land in Q3.
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::ZERO).with_scale(-1.0, -1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            // Normal stays (0,0,1).
            assert!(approx_vec(a.normal, Vector3::new(0.0, 0.0, 1.0)));
            let (start, mid, end) = arc_sample_points(a);
            assert!(approx_vec(start, Vector3::new(-1.0, 0.0, 0.0)));
            assert!(approx_vec(end, Vector3::new(0.0, -1.0, 0.0)));
            let inv_sqrt2 = std::f64::consts::FRAC_1_SQRT_2;
            assert!(approx_vec(mid, Vector3::new(-inv_sqrt2, -inv_sqrt2, 0.0)));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_mirror_x_offset_center_position_preserved() {
        // Regression: when the normal flips, `arc.center` (stored in OCS) must
        // be projected into the new OCS so the renderer reconstructs the WCS
        // position correctly. Earlier the center was stored as WCS, which made
        // the renderer apply the new OCS basis a second time and flip the X
        // back — placing the arc at the mirror of where it should be.
        let arc = Arc::from_center_radius_angles(Vector3::new(5.0, 3.0, 0.0), 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::ZERO).with_scale(-1.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            // Original arc centered at (5,3,0) sweeps Q1-of-center: start (6,3) → end (5,4).
            // Mirror-X: centered at (-5,3,0), start (-6,3) → end (-5,4), midpoint upper-left.
            assert!(approx_vec(a.normal, Vector3::new(0.0, 0.0, -1.0)));
            let (start, mid, end) = arc_sample_points(a);
            assert!(approx_vec(start, Vector3::new(-6.0, 3.0, 0.0)));
            assert!(approx_vec(end, Vector3::new(-5.0, 4.0, 0.0)));
            let inv_sqrt2 = std::f64::consts::FRAC_1_SQRT_2;
            assert!(approx_vec(
                mid,
                Vector3::new(-5.0 - inv_sqrt2, 3.0 + inv_sqrt2, 0.0)
            ));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_mirror_x_with_translation_position_preserved() {
        // Same regression but with both mirror and INSERT translation —
        // catches any leftover confusion between WCS/OCS center.
        let arc = Arc::from_center_radius_angles(Vector3::new(2.0, 0.0, 0.0), 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::new(10.0, 20.0, 0.0)).with_scale(-1.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            let (start, mid, end) = arc_sample_points(a);
            // The block arc at (2,0,0) gets mirrored to (-2,0,0) then translated to (8,20,0).
            // Sweep: start (3,0)→mirror→(−3,0)→translate→(7,20).
            //        end   (2,1)→mirror→(−2,1)→translate→(8,21).
            assert!(approx_vec(start, Vector3::new(7.0, 20.0, 0.0)));
            assert!(approx_vec(end, Vector3::new(8.0, 21.0, 0.0)));
            let inv_sqrt2 = std::f64::consts::FRAC_1_SQRT_2;
            assert!(approx_vec(
                mid,
                Vector3::new(8.0 - inv_sqrt2, 20.0 + inv_sqrt2, 0.0)
            ));
        } else {
            panic!("expected Arc");
        }
    }

    #[test]
    fn explode_arc_mirror_flips_normal() {
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        let insert = Insert::new("B", Vector3::ZERO).with_scale(-1.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Arc(a) = &result[0] {
            // A single-axis mirror should flip the arc normal so the renderer's
            // CCW sweep matches the mirrored geometry.
            assert!(approx_vec(a.normal, Vector3::new(0.0, 0.0, -1.0)));
        } else {
            panic!("expected Arc");
        }
    }

    // ── Mirrored INSERT ellipse handedness ──────────────────────

    /// Reconstruct an ellipse's three sample points at t = start, mid, end in WCS.
    /// ELLIPSE is a WCS entity: `center` and `major_axis` are world coordinates.
    fn ellipse_sample_points(e: &Ellipse) -> (Vector3, Vector3, Vector3) {
        let center_wcs = e.center;
        let major_wcs = e.major_axis;
        let major_len = major_wcs.length();
        let u = major_wcs * (1.0 / major_len.max(1e-12));
        let v = e.normal.cross(&u);
        let minor_len = major_len * e.minor_axis_ratio;
        let mut t1 = e.end_parameter;
        if t1 <= e.start_parameter {
            t1 += TAU;
        }
        let pt = |t: f64| center_wcs + u * (major_len * t.cos()) + v * (minor_len * t.sin());
        let mid = e.start_parameter + (t1 - e.start_parameter) * 0.5;
        (pt(e.start_parameter), pt(mid), pt(t1))
    }

    #[test]
    fn explode_arc_mirror_x_nonuniform_to_ellipse() {
        // Non-uniform XY scale with mirror: arc → ellipse, sweep preserved.
        let arc = Arc::from_center_radius_angles(Vector3::ZERO, 1.0, 0.0, FRAC_PI_2);
        let block_entities = vec![EntityType::Arc(arc)];

        // Mirror-X plus stretch X by 2: total X factor = -2, Y factor = 1.
        let insert = Insert::new("B", Vector3::ZERO).with_scale(-2.0, 1.0, 1.0);
        let result = insert.explode(&block_entities);

        if let EntityType::Ellipse(e) = &result[0] {
            let (start, mid, end) = ellipse_sample_points(e);
            // Apply the transform manually to the original arc samples to derive expectations:
            //  start (1,0) → (-2,0)
            //  mid   (~0.707, ~0.707) → (~-1.414, ~0.707)
            //  end   (0,1) → (0,1)
            let inv_sqrt2 = std::f64::consts::FRAC_1_SQRT_2;
            assert!(approx_vec(start, Vector3::new(-2.0, 0.0, 0.0)));
            assert!(approx_vec(
                mid,
                Vector3::new(-2.0 * inv_sqrt2, inv_sqrt2, 0.0)
            ));
            assert!(approx_vec(end, Vector3::new(0.0, 1.0, 0.0)));
        } else {
            panic!("expected Ellipse for non-uniform mirrored scale");
        }
    }
}