gdtf 0.2.0

Tools to read and inspect General Device Type Format (GDTF) files.
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
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
//! Physical descriptions of the individual parts of a device.

use crate::description::parse_helper::Parse;
use crate::description::util::IterUtil;
use crate::fixture_type::FixtureType;
use crate::model::Model;
use crate::physical_descriptions::Emitter;
use crate::validation::{ValidationError, ValidationErrorType, ValidationObject, ValidationResult};
use crate::values::{DmxAddress, Matrix, Name, Node, NodeExt, Vector3};
use serde::{Deserialize, Serialize};

/// Defines methods common to all [Geometry] types.
pub trait AnyGeometry {
    /// The unique name of the geometry.
    fn name(&self) -> Option<&Name>;

    /// Name of the [Model] used by the geometry.
    fn model_name(&self) -> Option<&Name>;

    /// Children of the geometry.
    fn children(&self) -> &[Geometry];

    /// Looks up the [Model] linked by this geometry.
    fn model<'s>(&self, parent_fixture_type: &'s FixtureType) -> Option<&'s Model> {
        parent_fixture_type.model(self.model_name()?)
    }

    /// Looks up a direct child [Geometry] by [name](Geometry::name).
    fn child(&self, name: &str) -> Option<&Geometry> {
        self.children()
            .iter()
            .find(|child| child.name().map(Name::as_ref) == Some(name))
    }

    /// Looks up a nested child [Geometry] by [name](Geometry::name).
    fn nested_child(&self, name: &str) -> Option<&Geometry> {
        for child in self.children() {
            if child.name().map(Name::as_ref) == Some(name) {
                return Some(child);
            };
            if let Some(nested_child) = child.nested_child(name) {
                return Some(nested_child);
            }
        }
        None
    }

    /// Looks up a child [Geometry] by [name](Geometry::name) from a path.
    fn child_node(&self, node: &[Name]) -> Option<&Geometry> {
        let (name, tail) = node.split_first()?;
        let geometry = self.child(name)?;

        if tail.is_empty() {
            Some(geometry)
        } else {
            geometry.child_node(tail)
        }
    }

    /// To be overridden by an implementor: implement custom validation checks in addition to those
    /// performed by [validate](Self::validate).
    #[doc(hidden)]
    fn validate_custom(&self, _parent_fixture_type: &FixtureType, _result: &mut ValidationResult) {}

    /// Performs validation checks on the object.
    fn validate(&self, parent_fixture_type: &FixtureType, result: &mut ValidationResult) {
        if self.name().is_none() {
            result.errors.push(ValidationError::new(
                ValidationObject::Geometry,
                None,
                ValidationErrorType::MissingName,
            ));
        }

        if let (Some(model_name), None) = (self.model_name(), self.model(parent_fixture_type)) {
            result.errors.push(ValidationError::new(
                ValidationObject::Geometry,
                self.name().map(Name::to_string),
                ValidationErrorType::LinkNotFound(
                    ValidationObject::Model,
                    Node::new([model_name.clone()]),
                ),
            ));
        }

        self.validate_custom(parent_fixture_type, result);

        for child in self.children() {
            child.validate(parent_fixture_type, result);
        }
    }
}

/// Defines the physical description of a device's parts.
///
/// Geometry is organised in a tree with each geometry having zero or more child geometries.
// Clippy generates a false positive for `large_enum_variant` due to recursive types.
// See https://github.com/rust-lang/rust-clippy/issues/9798
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Geometry {
    /// Basic geometry without specification.
    #[serde(rename = "Geometry")]
    Generic(GenericGeometry),

    /// Defines device parts with a rotation axis.
    Axis(AxisGeometry),

    /// Defines device parts with a beam filter.
    FilterBeam(BeamFilterGeometry),

    /// Defines device parts with a color filter.
    FilterColor(ColorFilterGeometry),

    /// Defines device parts with gobo wheels.
    FilterGobo(GoboFilterGeometry),

    /// Defines device parts with a shaper.
    FilterShaper(ShaperFilterGeometry),

    /// Defines device parts with a light source.
    Beam(BeamGeometry),

    /// Defines device parts with a layer of a media device that is used for displaying media files.
    MediaServerLayer(MediaServerLayerGeometry),

    /// Defines device parts with a camera or output of a media device.
    MediaServerCamera(MediaServerCameraGeometry),

    /// Defines device parts with a master control of one or several media devices.
    MediaServerMaster(MediaServerMasterGeometry),

    /// Defines device parts with a self-emitting surface used to display visual media.
    Display(DisplayGeometry),

    /// Defines an instance of the same geometry.
    #[serde(rename = "GeometryReference")]
    Reference(ReferenceGeometry),

    /// Defines device parts with a laser's light output.
    Laser(LaserGeometry),

    /// Defines device parts with an electrical device that can be wired.
    WiringObject(WiringObjectGeometry),

    /// Defines an inventory of device parts.
    Inventory(InventoryGeometry),

    /// Defines device parts with a structure.
    Structure(StructureGeometry),

    /// Defines device parts with a support.
    Support(SupportGeometry),

    /// Defines device parts with a magnet.
    Magnet(MagnetGeometry),
}

impl AnyGeometry for Geometry {
    fn name(&self) -> Option<&Name> {
        match self {
            Geometry::Generic(g) => g.name(),
            Geometry::Axis(g) => g.name(),
            Geometry::FilterBeam(g) => g.name(),
            Geometry::FilterColor(g) => g.name(),
            Geometry::FilterGobo(g) => g.name(),
            Geometry::FilterShaper(g) => g.name(),
            Geometry::Beam(g) => g.name(),
            Geometry::MediaServerLayer(g) => g.name(),
            Geometry::MediaServerCamera(g) => g.name(),
            Geometry::MediaServerMaster(g) => g.name(),
            Geometry::Display(g) => g.name(),
            Geometry::Reference(g) => g.name(),
            Geometry::Laser(g) => g.name(),
            Geometry::WiringObject(g) => g.name(),
            Geometry::Inventory(g) => g.name(),
            Geometry::Structure(g) => g.name(),
            Geometry::Support(g) => g.name(),
            Geometry::Magnet(g) => g.name(),
        }
    }

    fn model_name(&self) -> Option<&Name> {
        match self {
            Geometry::Generic(g) => g.model_name(),
            Geometry::Axis(g) => g.model_name(),
            Geometry::FilterBeam(g) => g.model_name(),
            Geometry::FilterColor(g) => g.model_name(),
            Geometry::FilterGobo(g) => g.model_name(),
            Geometry::FilterShaper(g) => g.model_name(),
            Geometry::Beam(g) => g.model_name(),
            Geometry::MediaServerLayer(g) => g.model_name(),
            Geometry::MediaServerCamera(g) => g.model_name(),
            Geometry::MediaServerMaster(g) => g.model_name(),
            Geometry::Display(g) => g.model_name(),
            Geometry::Reference(g) => g.model_name(),
            Geometry::Laser(g) => g.model_name(),
            Geometry::WiringObject(g) => g.model_name(),
            Geometry::Inventory(g) => g.model_name(),
            Geometry::Structure(g) => g.model_name(),
            Geometry::Support(g) => g.model_name(),
            Geometry::Magnet(g) => g.model_name(),
        }
    }

    fn children(&self) -> &[Geometry] {
        match self {
            Geometry::Generic(g) => g.children(),
            Geometry::Axis(g) => g.children(),
            Geometry::FilterBeam(g) => g.children(),
            Geometry::FilterColor(g) => g.children(),
            Geometry::FilterGobo(g) => g.children(),
            Geometry::FilterShaper(g) => g.children(),
            Geometry::Beam(g) => g.children(),
            Geometry::MediaServerLayer(g) => g.children(),
            Geometry::MediaServerCamera(g) => g.children(),
            Geometry::MediaServerMaster(g) => g.children(),
            Geometry::Display(g) => g.children(),
            Geometry::Reference(g) => g.children(),
            Geometry::Laser(g) => g.children(),
            Geometry::WiringObject(g) => g.children(),
            Geometry::Inventory(g) => g.children(),
            Geometry::Structure(g) => g.children(),
            Geometry::Support(g) => g.children(),
            Geometry::Magnet(g) => g.children(),
        }
    }
}

macro_rules! impl_any_geometry {
    ($str:ident) => {
        impl AnyGeometry for $str {
            fn name(&self) -> Option<&Name> {
                self.name.as_ref()
            }
            fn model_name(&self) -> Option<&Name> {
                self.model.as_ref()
            }
            fn children(&self) -> &[Geometry] {
                &self.children
            }
        }
    };
}

/// Basic geometry without specification.
///
/// Corresponds to a `<Geometry>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GenericGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for a conventional is "Body".
    /// Recommended name for a geometry representing the base housing of a moving head is "Base".
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(GenericGeometry);

/// Defines device parts with a rotation axis.
///
/// Corresponds to an `<Axis>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AxisGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for an axis-geometry is "Yoke".
    /// Recommended name for an axis-geometry representing the lamp housing of a moving head is
    /// "Head".
    /// Note: The Head of a moving head is usually mounted to the Yoke.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(AxisGeometry);

/// Defines device parts with a beam filter.
///
/// Corresponds to a `<FilterBeam>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BeamFilterGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for a beam filter limiting the diffusion of light is "BarnDoor".
    /// Recommended name for a beam filter adjusting the diameter of the beam is "Iris".
    /// Note: BarnDoor and Iris are usually mounted to a conventional.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(BeamFilterGeometry);

/// Defines device parts with a color filter.
///
/// Corresponds to a `<FilterColor>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ColorFilterGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for a filter of a color or a mechanical color changer is "FilterColor".
    /// Note: FilterColor is usually mounted to a conventional.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(ColorFilterGeometry);

/// Defines device parts with gobo wheels.
///
/// Corresponds to a `<FilterGobo>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GoboFilterGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for a filter of a gobo or mechanical gobo changer is "FilterGobo".
    /// Note: FilterGobo is uaually mounted to a conventional.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(GoboFilterGeometry);

/// Defines device parts with a shaper.
///
/// Corresponds to a `<FilterShaper>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShaperFilterGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for a filter used to form the beam to a framed, triangular or
    /// trapezoid shape is "Shaper".
    /// Note: Shaper is usually mounted to a conventional.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(ShaperFilterGeometry);

/// Defines device parts with a light source.
///
/// Beam geometry describes the position of the fixture's light output (usually the position of the
/// lens) and not the position of the light source inside the device.
///
/// Corresponds to a `<Beam>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BeamGeometry {
    /// The unique name of the geometry.
    ///
    /// Recommended name for a light source of a conventional or moving head or a projector is
    /// "Beam".
    /// Note 1: Beam is usually mounted to Head or Body.
    ///
    /// Recommended name for a self-emitting single light source is "Pixel".
    /// Note 2: Pixel is usually mounted to Head or Body.
    ///
    /// Recommended name for a number of Pixels that are controlled at the same time is "Array".
    /// Note 3: Array is usually mounted to Head or Body.
    ///
    /// Recommended name for a light source of a moving mirror is "Mirror".
    /// Note 4: Mirror is usually mounted to Yoke.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// Defines the type of light source.
    ///
    /// Corresponds to the `LampType` XML attribute.
    #[serde(rename = "@LampType", default)]
    pub lamp_type: LampType,

    /// Power consumption in watts.
    ///
    /// Corresponds to the `PowerConsumption` XML attribute.
    #[serde(rename = "@PowerConsumption", default = "default_power_consumption")]
    pub power_consumption: f64,

    /// Intensity of all the represented light emitters in lumens.
    ///
    /// Corresponds to the `LuminousFlux` XML attribute.
    #[serde(rename = "@LuminousFlux", default = "default_luminous_flux")]
    pub luminous_flux: f64,

    /// Color temperature in kelvin.
    ///
    /// Corresponds to the `ColorTemperature` XML attribute.
    #[serde(rename = "@ColorTemperature", default = "default_color_temperature")]
    pub color_temperature: f64,

    /// The angle of the light output at which the intensity is 50% of the maximum intensity
    /// corresponding to the center of the beam.
    ///
    /// Corresponds to the `BeamAngle` XML attribute.
    #[serde(rename = "@BeamAngle", default = "default_beam_angle")]
    pub beam_angle: f64,

    /// The angle of the light output at which the intensity is 10% of the maximum intensity
    /// corresponding to the center of the beam.
    ///
    /// Corresponds to the `FieldAngle` XML attribute.
    #[serde(rename = "@FieldAngle", default = "default_field_angle")]
    pub field_angle: f64,

    /// Throw ratio of the lens for rectangle beam types.
    ///
    /// Corresponds to the `ThrowRatio` XML attribute.
    #[serde(rename = "@ThrowRatio", default = "default_throw_ratio")]
    pub throw_ratio: f64,

    /// Ratio from width to height of rectangle beam types.
    ///
    /// Corresponds to the `RectangleRatio` XML attribute.
    #[serde(rename = "@RectangleRatio", default = "default_rectangle_ratio")]
    pub rectangle_ratio: f64,

    /// Defines the radius of the light output of the lamp instance.
    ///
    /// Corresponds to the `BeamRadius` XML attribute.
    #[serde(rename = "@BeamRadius", default = "default_beam_radius")]
    pub beam_radius: f64,

    /// Describes how the beam will be rendered.
    ///
    /// Corresponds to the `BeamType` XML attribute.
    #[serde(rename = "@BeamType", default)]
    pub beam_type: BeamType,

    /// The CRI according to TM-30.
    ///
    /// A quantitative measure of the ability of the light source to show an object color
    /// compared to a daylight reference.
    ///
    /// Corresponds to the `ColorRenderingIndex` XML attribute.
    #[serde(
        rename = "@ColorRenderingIndex",
        default = "default_color_rendering_index"
    )]
    pub color_rendering_index: u8,

    /// Optional link to an emitter defining the white light source of a subtractive color mixing
    /// system.
    ///
    /// The default spectrum is a black-body with the defined color temperature.
    ///
    /// Corresponds to the `EmitterSpectrum` XML attribute.
    #[serde(rename = "@EmitterSpectrum", skip_serializing_if = "Option::is_none")]
    pub emitter_spectrum: Option<Node>,
}

impl AnyGeometry for BeamGeometry {
    fn name(&self) -> Option<&Name> {
        self.name.as_ref()
    }
    fn model_name(&self) -> Option<&Name> {
        self.model.as_ref()
    }
    fn children(&self) -> &[Geometry] {
        &self.children
    }

    fn validate_custom(&self, parent_fixture_type: &FixtureType, result: &mut ValidationResult) {
        if let (Some(emitter_spectrum), None) = (
            &self.emitter_spectrum,
            self.emitter_spectrum(parent_fixture_type),
        ) {
            result.errors.push(ValidationError::new(
                ValidationObject::Geometry,
                self.name().map(Name::to_string),
                ValidationErrorType::LinkNotFound(
                    ValidationObject::Emitter,
                    emitter_spectrum.clone(),
                ),
            ));
        }
    }
}

impl BeamGeometry {
    /// Looks up the optional [Emitter] linked by this geometry.
    pub fn emitter_spectrum<'s>(
        &self,
        parent_fixture_type: &'s FixtureType,
    ) -> Option<&'s Emitter> {
        let name = self.emitter_spectrum.as_ref()?.single()?;
        parent_fixture_type.physical_descriptions.emitter(name)
    }
}

fn default_color_temperature() -> f64 {
    6000.
}
fn default_color_rendering_index() -> u8 {
    100
}

/// Defines the type of a light source represented by a [BeamGeometry].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum LampType {
    /// Tungsten lamp.
    Tungsten,

    /// Halogen lamp.
    Halogen,

    /// LED lamp.
    #[serde(rename = "LED")]
    Led,

    /// Discharge lamp.
    #[default]
    #[serde(other)]
    Discharge,
}

/// Describes how the beam represented by a [BeamGeometry] will be rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum BeamType {
    /// Rendered as a conical beam with hard edges.
    Spot,
    /// No beam will be drawn, only the geometry will emit light itself.
    None,
    /// Rendered as a pyramid-shaped beam with hard edges.
    Rectangle,
    /// Rendered as a conical beam with soft edges and softened field projection.
    #[serde(rename = "PC")]
    Pc,
    /// Rendered as a conical beam with soft edges and softened field projection.
    Fresnel,
    /// No beam will be drawn, only the geometry will emit light itself.
    Glow,

    /// Rendered as a conical beam with soft edges and softened field projection.
    #[default]
    #[serde(other)]
    Wash,
}

/// Defines device parts with a layer of a media device that is used for displaying media files.
///
/// Corresponds to a `<MediaServerLayer>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaServerLayerGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model that will be used to display the alignment in media server
    /// space.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(MediaServerLayerGeometry);

/// Defines device parts with a camera or output of a media device.
///
///
/// Corresponds to a `<MediaServerCamera>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaServerCameraGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model that will be used to display the alignment in media server
    /// space.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(MediaServerCameraGeometry);

/// Defines device parts with a master control of one or several media devices.
///
/// Corresponds to a `<MediaServerMaster>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaServerMasterGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(MediaServerMasterGeometry);

/// Defines device parts with a self-emitting surface used to display visual media.
///
/// Corresponds to a `<Display>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DisplayGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// Name of the mapped texture in the model file that will be swapped out for the media
    /// resource.
    ///
    /// Corresponds to the `Texture` XML attribute.
    #[serde(rename = "@Texture")]
    pub texture: String,
}

impl_any_geometry!(DisplayGeometry);

/// Defines an instance of the same geometry.
///
/// For example: an LED panel with multiple pixels.
///
/// Corresponds to a `<GeometryReference>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReferenceGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// An optional link to a corresponding model.
    ///
    /// The model replaces the model of the parent of the referenced geometry. The models of the
    /// children are not affected. If the model is not set, the model is taken from the referenced
    /// geometry.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Name of the referenced geometry.
    ///
    /// Only top level geometries can be referenced.
    ///
    /// Corresponds to the `Geometry` XML attribute.
    #[serde(rename = "@Geometry")]
    pub geometry: Option<Name>,

    /// Specifies DMX offsets for the DMX channels of the referenced geometry.
    ///
    /// The number of breaks here depends on the number of different breaks in the DMX channels of
    /// the referenced geometry. For example, if the referenced geometry has DMX channels with DMX
    /// break 2 and 4, this geometry must have 2 breaks, the first with the DMX offset for DMX break
    /// 2 and the second for DMX break 4.
    ///
    /// If one or more of the DMX channels of the referenced geometry has the special value
    /// "Overwrite" as a DMX break, the DMX break for those channels and the DMX offsets needs to be
    /// defined.
    ///
    /// Corresponds to all `<Break>` XML child nodes.
    #[serde(rename = "Break", skip_serializing_if = "Vec::is_empty", default)]
    pub breaks: Vec<Break>,
}

impl AnyGeometry for ReferenceGeometry {
    fn name(&self) -> Option<&Name> {
        self.name.as_ref()
    }

    fn model_name(&self) -> Option<&Name> {
        self.model.as_ref()
    }

    fn children(&self) -> &[Geometry] {
        &[]
    }

    fn validate_custom(&self, parent_fixture_type: &FixtureType, result: &mut ValidationResult) {
        if let (Some(geometry), None) = (&self.geometry, self.geometry(parent_fixture_type)) {
            result.errors.push(ValidationError::new(
                ValidationObject::Geometry,
                self.name().map(Name::to_string),
                ValidationErrorType::LinkNotFound(
                    ValidationObject::Geometry,
                    Node::new([geometry.clone()]),
                ),
            ));
        }
    }
}

impl ReferenceGeometry {
    /// Looks up the [Geometry] linked by this geometry.
    pub fn geometry<'s>(&self, parent_fixture_type: &'s FixtureType) -> Option<&'s Geometry> {
        parent_fixture_type.root_geometry(self.geometry.as_ref()?)
    }
}

/// Specifies the DMX offset for the DMX channel of the referenced geometry.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Break {
    /// DMX offset.
    ///
    /// A value of 1 means no offset for the corresponding DMX channel.
    ///
    /// Corresponds to the `DMXOffset` XML attribute.
    #[serde(rename = "@DMXOffset", default = "default_break_dmx_offset")]
    pub dmx_offset: DmxAddress,

    /// Defines the unique number of the DMX break for which the offset is given.
    ///
    /// Corresponds to the `DMXBreak` XML attribute.
    #[serde(rename = "@DMXBreak", default = "default_break_dmx_break")]
    pub dmx_break: u8,
}

fn default_break_dmx_offset() -> DmxAddress {
    DmxAddress::from_absolute(1)
}
fn default_break_dmx_break() -> u8 {
    1
}

/// Defines device parts with a laser's light output.
///
/// Corresponds to a `<Laser>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LaserGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// Type of color emitted by the laser.
    ///
    /// Corresponds to the `ColorType` XML attribute.
    #[serde(flatten, default)]
    pub color_type: ColorType,

    /// Output strength of the laser in watts.
    ///
    /// Corresponds to the `OutputStrength` XML attribute.
    #[serde(rename = "@OutputStrength")]
    pub output_strength: f64,

    /// Optional link to the emitter group.
    ///
    /// Corresponds to the `Emitter` XML attribute.
    #[serde(rename = "@Emitter", skip_serializing_if = "Option::is_none")]
    pub emitter: Option<Node>,

    /// Beam diameter where it leaves the projector in meters.
    ///
    /// Corresponds to the `BeamDiameter` XML attribute.
    #[serde(rename = "@BeamDiameter")]
    pub beam_diameter: f64,

    /// Minimum beam divergence in milliradians.
    ///
    /// Corresponds to the `BeamDivergenceMin` XML attribute.
    #[serde(rename = "@BeamDivergenceMin")]
    pub beam_divergence_min: f64,

    /// Maximum beam divergence in milliradians.
    ///
    /// Corresponds to the `BeamDivergenceMax` XML attribute.
    #[serde(rename = "@BeamDivergenceMax")]
    pub beam_divergence_max: f64,

    /// Possible total scan angle pan of the beam in degrees.
    ///
    /// Corresponds to the `ScanAnglePan` XML attribute.
    #[serde(rename = "@ScanAnglePan")]
    pub scan_angle_pan: f64,

    /// Possible total scan angle tilt of the beam in degrees.
    ///
    /// Corresponds to the `ScanAngleTilt` XML attribute.
    #[serde(rename = "@ScanAngleTilt")]
    pub scan_angle_tilt: f64,

    /// Speed of the beam in kilo points per second.
    ///
    /// Corresponds to the `ScanSpeed` XML attribute.
    #[serde(rename = "@ScanSpeed")]
    pub scan_speed: f64,

    /// Supported protocols of the laser.
    ///
    /// Corresponds to all `<Protocol>` XML child nodes.
    #[serde(rename = "Protocol", skip_serializing_if = "Vec::is_empty", default)]
    pub protocols: Vec<LaserProtocol>,
}

impl AnyGeometry for LaserGeometry {
    fn name(&self) -> Option<&Name> {
        self.name.as_ref()
    }
    fn model_name(&self) -> Option<&Name> {
        self.model.as_ref()
    }
    fn children(&self) -> &[Geometry] {
        &self.children
    }

    fn validate_custom(&self, parent_fixture_type: &FixtureType, result: &mut ValidationResult) {
        if let (Some(emitter), None) = (&self.emitter, self.emitter(parent_fixture_type)) {
            result.errors.push(ValidationError::new(
                ValidationObject::Geometry,
                self.name().map(Name::to_string),
                ValidationErrorType::LinkNotFound(ValidationObject::Emitter, emitter.clone()),
            ));
        }

        let duplicate_protocol_name = self
            .protocols
            .iter()
            .filter_map(|protocol| protocol.name.as_ref())
            .find_duplicate();
        if let Some(name) = duplicate_protocol_name {
            result.errors.push(ValidationError::new(
                ValidationObject::LaserProtocol,
                name.to_string(),
                ValidationErrorType::DuplicateName,
            ));
        }

        for protocol in &self.protocols {
            protocol.validate(result);
        }
    }
}

impl LaserGeometry {
    /// Looks up the optional [Emitter] linked by this geometry.
    pub fn emitter<'s>(&self, parent_fixture_type: &'s FixtureType) -> Option<&'s Emitter> {
        let name = self.emitter.as_ref()?.single()?;
        parent_fixture_type.physical_descriptions.emitter(name)
    }
}

/// Type of color emitted by a laser represented by a [LaserGeometry].
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
#[serde(tag = "@ColorType")]
pub enum ColorType {
    /// The laser geometry emits a single wavelength only.
    SingleWaveLength(
        /// Color in nanometers.
        ///
        /// Corresponds to the `Color` XML attribute.
        #[serde(rename = "@Color", deserialize_with = "Parse::deserialize")]
        f64,
    ),

    /// The laser geometry emits an additive RGB color.
    #[default]
    #[serde(other, rename = "RGB")]
    Rgb,
}

/// Defines device parts with an electrical device that can be wired.
///
/// Corresponds to a `<WiringObject>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WiringObjectGeometry {
    /// The unique name of the geometry.
    ///
    /// This name is also the name of the interface to the outside.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// The type of the connector.
    ///
    /// A list of predefined types is defined in [Annex D](https://gdtf.eu/gdtf/annex/annex-d/) of
    /// the GDTF specification. Custom types of connector can also be defined, for example
    /// "Loose End".
    ///
    /// Corresponds to the `ConnectorType` XML attribute.
    #[serde(rename = "@ConnectorType")]
    pub connector_type: String,

    /// The type of the electrical component used.
    ///
    /// Corresponds to the `ComponentType` XML attribute.
    #[serde(flatten)]
    pub component_type: ComponentType,

    /// The type of the signal used.
    ///
    /// Predefined values are "Power", "DMX512", "Protocol", "AES", "AnalogVideo", "AnalogAudio".
    /// Custom protocols can also be used here.
    ///
    /// Corresponds to the `SignalType` XML attribute.
    #[serde(rename = "@SignalType")]
    pub signal_type: String,

    /// The number of available pins of the connector type to connect internal wiring to it.
    ///
    /// Corresponds to the `PinCount` XML attribute.
    #[serde(rename = "@PinCount")]
    pub pin_count: i32,

    /// The layer of the signal type.
    ///
    /// In one device, all wiring geometry that uses the same signal layer is connected.
    ///
    /// The special value of "0" indicates the wiring geometry is connected to all geometries.
    ///
    /// Corresponds to the `SignalLayer` XML attribute.
    #[serde(rename = "@SignalLayer")]
    pub signal_layer: i32,

    /// Where the pins are placed on the object.
    ///
    /// Corresponds to the `Orientation` XML attribute.
    #[serde(rename = "@Orientation")]
    pub orientation: Orientation,

    /// Name of the group to which this wiring object belongs.
    ///
    /// Corresponds to the `WireGroup` XML attribute.
    #[serde(rename = "@WireGroup")]
    pub wire_group: String,

    /// A list of patches specifying how different sockets are connected to the pins of other
    /// wiring objects.
    ///
    /// Corresponds to all `<PinPatch>` XML child nodes.
    #[serde(rename = "PinPatch", skip_serializing_if = "Vec::is_empty", default)]
    pub pin_patches: Vec<PinPatch>,
}

impl AnyGeometry for WiringObjectGeometry {
    fn name(&self) -> Option<&Name> {
        self.name.as_ref()
    }
    fn model_name(&self) -> Option<&Name> {
        self.model.as_ref()
    }
    fn children(&self) -> &[Geometry] {
        &self.children
    }

    fn validate_custom(&self, parent_fixture_type: &FixtureType, result: &mut ValidationResult) {
        for pin_patch in &self.pin_patches {
            pin_patch.validate(parent_fixture_type, result);
        }
    }
}

/// The type of electrical component used in a wiring object represented by a
/// [WiringObjectGeometry].
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "@ComponentType")]
pub enum ComponentType {
    /// Input component.
    Input,

    /// Output component.
    Output,

    /// Power source component.
    PowerSource {
        /// The maximum electrical payload that this power source can handle in voltamperes.
        ///
        /// Only for Power Source connector types.
        ///
        /// Corresponds to the `MaxPayLoad` XML attribute.
        #[serde(
            rename = "@MaxPayLoad",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        max_pay_load: Option<f64>,

        /// The voltage output that this power source can handle in volts.
        ///
        /// Only for Power Source connector types.
        ///
        /// Corresponds to the `Voltage` XML attribute.
        #[serde(
            rename = "@Voltage",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        voltage: Option<f64>,
    },

    /// Consumer component.
    Consumer {
        /// The electrical consumption in watts.
        ///
        /// Only for Consumer connector types.
        ///
        /// Corresponds to the `ElectricalPayLoad` XML attribute.
        #[serde(
            rename = "@ElectricalPayLoad",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        electrical_pay_load: Option<f64>,

        /// The voltage range's maximum value in volts.
        ///
        /// Only for Consumer connector types.
        ///
        /// Corresponds to the `VoltageRangeMax` XML attribute.
        #[serde(
            rename = "@VoltageRangeMax",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        voltage_range_max: Option<f64>,

        /// The voltage range's minimum value in volts.
        ///
        /// Only for Consumer connector types.
        ///
        /// Corresponds to the `VoltageRangeMin` XML attribute.
        #[serde(
            rename = "@VoltageRangeMin",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        voltage_range_min: Option<f64>,

        /// The frequency range's maximum value in hertz.
        ///
        /// Only for Consumer connector types.
        ///
        /// Corresponds to the `FrequencyRangeMax` XML attribute.
        #[serde(
            rename = "@FrequencyRangeMax",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        frequency_range_max: Option<f64>,

        /// The frequency range's minimum value in hertz.
        ///
        /// Only for Consumer connector types.
        ///
        /// Corresponds to the `FrequencyRangeMin` XML attribute.
        #[serde(
            rename = "@FrequencyRangeMin",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        frequency_range_min: Option<f64>,

        /// The Power Factor of the device.
        ///
        /// Only for Consumer connector types.
        ///
        /// Corresponds to the `CosPhi` XML attribute.
        #[serde(
            rename = "@CosPhi",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        cos_phi: Option<f64>,
    },

    /// Fuse component.
    Fuse {
        /// The fuse value in amperes.
        ///
        /// Only for Fuse connector types.
        ///
        /// Corresponds to the `FuseCurrent` XML attribute.
        #[serde(
            rename = "@FuseCurrent",
            skip_serializing_if = "Option::is_none",
            deserialize_with = "Parse::deserialize"
        )]
        fuse_current: Option<f64>,

        /// Fuse rating.
        ///
        /// Only for Fuse connector types.
        ///
        /// Corresponds to the `FuseRating` XML attribute.
        #[serde(rename = "@FuseRating", skip_serializing_if = "Option::is_none")]
        fuse_rating: Option<FuseRating>,
    },

    /// Network provider component.
    NetworkProvider,

    /// Network input component.
    NetworkInput,

    /// Network output component.
    NetworkOutput,

    /// Network input/output component.
    NetworkInOut,
}

/// Fuse rating for a fuse represented by a [WiringObjectGeometry].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FuseRating {
    /// Type B fuse.
    B,

    /// Type C fuse.
    C,

    /// Type D fuse.
    D,

    /// Type K fuse.
    K,

    /// Type Z fuse.
    Z,
}

/// Where the pins represented by a [WiringObjectGeometry] are located.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Orientation {
    /// Pins face left.
    Left,

    /// Pins face right.
    Right,

    /// Pins face above.
    Top,

    /// Pins face below.
    Bottom,
}

/// Specifies how the different sockets of a wiring object are connected to the pins of other wiring
/// objects.
///
/// Corresponds to a `<PinPatch>` XML node.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PinPatch {
    /// Link to the wiring object connected through this pin patch.
    ///
    /// Corresponds to the `ToWiringObject` XML attribute.
    #[serde(rename = "@ToWiringObject")]
    to_wiring_object: Node,

    /// The pin number used by the parent wiring object to connect to the target wiring object.
    ///
    /// Corresponds to the `FromPin` XML attribute.
    #[serde(rename = "@FromPin")]
    from_pin: i32,

    /// The pin number used by the targeted wiring object to connect to the parent wiring object.
    ///
    /// Corresponds to the `ToPin` XML attribute.
    #[serde(rename = "@ToPin")]
    to_pin: i32,
}

impl PinPatch {
    /// Looks up the [WiringObjectGeometry] linked by this pin patch.
    pub fn to_wiring_object<'s>(
        &self,
        parent_fixture_type: &'s FixtureType,
    ) -> Option<&'s Geometry> {
        parent_fixture_type.geometry_node(&self.to_wiring_object)
    }

    /// Performs validation checks on the object.
    pub fn validate(&self, parent_fixture_type: &FixtureType, result: &mut ValidationResult) {
        if self.to_wiring_object(parent_fixture_type).is_none() {
            result.errors.push(ValidationError::new(
                ValidationObject::PinPatch,
                None,
                ValidationErrorType::LinkNotFound(
                    ValidationObject::Geometry,
                    self.to_wiring_object.clone(),
                ),
            ));
        }
    }
}

/// Defines an inventory of device parts.
///
/// Corresponds to an `<Inventory>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InventoryGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// The default count for new objects.
    ///
    /// Corresponds to the `Count` XML attribute.
    #[serde(rename = "@Count")]
    pub count: i32,
}

impl_any_geometry!(InventoryGeometry);

/// Defines device parts with a structure.
///
/// Corresponds to a `<Structure>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StructureGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// The linked geometry.
    ///
    /// Corresponds to the `LinkedGeometry` XML attribute.
    #[serde(rename = "@LinkedGeometry")]
    pub linked_geometry: Name,

    /// The type of structure.
    ///
    /// Corresponds to the `StructureType` XML attribute.
    #[serde(rename = "@StructureType")]
    pub structure_type: StructureType,

    /// The type of cross section.
    ///
    /// Corresponds to the `CrossSectionType` XML attribute.
    #[serde(flatten)]
    pub cross_section_type: CrossSectionType,
}

impl_any_geometry!(StructureGeometry);

impl StructureGeometry {
    /// Looks up the [Geometry] linked by this geometry.
    pub fn linked_geometry<'s>(
        &self,
        parent_fixture_type: &'s FixtureType,
    ) -> Option<&'s Geometry> {
        parent_fixture_type.nested_geometry(&self.linked_geometry)
    }
}

/// The type of structure represented by a [StructureGeometry].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StructureType {
    /// Structure describes a center line.
    CenterLineBased,

    /// Structure describes detail.
    Detail,
}

/// The type of cross section of the structure represented by a [StructureGeometry].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "@CrossSectionType")]
pub enum CrossSectionType {
    /// Structure has a truss framework cross section.
    TrussFramework {
        /// The name of the truss cross section.
        ///
        /// Corresponds to the `TrussCrossSection` XML attribute.
        #[serde(rename = "@TrussCrossSection")]
        section: String,
    },

    /// Structure has a tube cross section.
    Tube {
        /// The height of the cross section.
        ///
        /// Corresponds to the `CrossSectionHeight` XML attribute.
        #[serde(
            rename = "@CrossSectionHeight",
            deserialize_with = "Parse::deserialize"
        )]
        height: f64,

        /// The thickness of the wall of the cross section.
        ///
        /// Corresponds to the `CrossSectionWallThickness` XML attribute.
        #[serde(
            rename = "@CrossSectionWallThickness",
            deserialize_with = "Parse::deserialize"
        )]
        wall_thickness: f64,
    },
}

/// Defines device parts with a support.
///
/// Corresponds to a `<Support>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupportGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,

    /// The type of support.
    ///
    /// Corresponds to the `SupportType` XML attribute.
    #[serde(flatten)]
    pub support_type: SupportType,

    /// The allowable force on the X-axis applied to the object according to the Eurocode, in N.
    ///
    /// Corresponds to the `CapacityX` XML attribute.
    #[serde(rename = "@CapacityX")]
    pub capacity_x: f64,

    /// The allowable force on the Y-axis applied to the object according to the Eurocode, in N.
    ///
    /// Corresponds to the `CapacityY` XML attribute.
    #[serde(rename = "@CapacityY")]
    pub capacity_y: f64,

    /// The allowable force on the Z-axis applied to the object according to the Eurocode, in N.
    ///
    /// Corresponds to the `CapacityZ` XML attribute.
    #[serde(rename = "@CapacityZ")]
    pub capacity_z: f64,

    /// The allowable moment around the X-axis applied to the object according to the Eurocode, in
    /// N/m.
    ///
    /// Corresponds to the `CapacityXX` XML attribute.
    #[serde(rename = "@CapacityXX")]
    pub capacity_xx: f64,

    /// The allowable moment around the Y-axis applied to the object according to the Eurocode, in
    /// N/m.
    ///
    /// Corresponds to the `CapacityYY` XML attribute.
    #[serde(rename = "@CapacityYY")]
    pub capacity_yy: f64,

    /// The allowable moment around the Z-axis applied to the object according to the Eurocode, in
    /// N/m.
    ///
    /// Corresponds to the `CapacityZZ` XML attribute.
    #[serde(rename = "@CapacityZZ")]
    pub capacity_zz: f64,
}

impl_any_geometry!(SupportGeometry);

/// The type of support represented by a [SupportGeometry].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "@SupportType")]
pub enum SupportType {
    /// Support is a rope.
    Rope {
        /// The name of the rope cross section.
        ///
        /// Corresponds to the `RopeCrossSection` XML attribute.
        #[serde(rename = "@RopeCrossSection")]
        cross_section: String,

        /// The offset of the rope from bottom to top in meters.
        ///
        /// Corresponds to the `RopeOffset` XML attribute.
        #[serde(rename = "@RopeOffset")]
        offset: Vector3,
    },

    /// Support is on the ground.
    GroundSupport {
        /// The compression ratio for this support along the X-axis in N/m.
        ///
        /// Corresponds to the `ResistanceX` XML attribute.
        #[serde(rename = "@ResistanceX", deserialize_with = "Parse::deserialize")]
        resistance_x: f64,

        /// The compression ratio for this support along the Y-axis in N/m.
        ///
        /// Corresponds to the `ResistanceY` XML attribute.
        #[serde(rename = "@ResistanceY", deserialize_with = "Parse::deserialize")]
        resistance_y: f64,

        /// The compression ratio for this support along the Z-axis in N/m.
        ///
        /// Corresponds to the `ResistanceZ` XML attribute.
        #[serde(rename = "@ResistanceZ", deserialize_with = "Parse::deserialize")]
        resistance_z: f64,

        /// The compression ratio for this support around the X-axis in N/m.
        ///
        /// Corresponds to the `ResistanceXX` XML attribute.
        #[serde(rename = "@ResistanceXX", deserialize_with = "Parse::deserialize")]
        resistance_xx: f64,

        /// The compression ratio for this support around the Y-axis in N/m.
        ///
        /// Corresponds to the `ResistanceYY` XML attribute.
        #[serde(rename = "@ResistanceYY", deserialize_with = "Parse::deserialize")]
        resistance_yy: f64,

        /// The compression ratio for this support around the Z-axis in N/m.
        ///
        /// Corresponds to the `ResistanceZZ` XML attribute.
        #[serde(rename = "@ResistanceZZ", deserialize_with = "Parse::deserialize")]
        resistance_zz: f64,
    },
}

/// Defines device parts with a magnet.
///
/// A magnet is a point where other geometries should be attached.
///
/// Corresponds to a `<Magnet>` XML node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MagnetGeometry {
    /// The unique name of the geometry.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,

    /// Link to the corresponding model.
    ///
    /// Corresponds to the `Model` XML attribute.
    #[serde(rename = "@Model", skip_serializing_if = "Option::is_none")]
    pub model: Option<Name>,

    /// Relative position of the geometry.
    ///
    /// Corresponds to the `Position` XML attribute.
    #[serde(rename = "@Position")]
    pub position: Matrix,

    /// Children of the geometry.
    ///
    /// Corresponds to all [Geometry] XML child nodes.
    #[serde(rename = "$value", skip_serializing_if = "Vec::is_empty", default)]
    pub children: Vec<Geometry>,
}

impl_any_geometry!(MagnetGeometry);

fn default_power_consumption() -> f64 {
    1000.
}
fn default_luminous_flux() -> f64 {
    10000.
}
fn default_beam_angle() -> f64 {
    25.
}
fn default_field_angle() -> f64 {
    25.
}
fn default_throw_ratio() -> f64 {
    1.
}
fn default_rectangle_ratio() -> f64 {
    1.7777
}
fn default_beam_radius() -> f64 {
    0.05
}

/// Specifies the protocol for a Laser.
///
/// Corresponds to a `<Protocol>` XML node.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LaserProtocol {
    /// Name of the protocol.
    ///
    /// Corresponds to the `Name` XML attribute.
    #[serde(rename = "@Name", skip_serializing_if = "Option::is_none")]
    pub name: Option<Name>,
}

impl LaserProtocol {
    /// Performs validation checks on the object.
    pub fn validate(&self, result: &mut ValidationResult) {
        if self.name.is_none() {
            result.errors.push(ValidationError::new(
                ValidationObject::LaserProtocol,
                None,
                ValidationErrorType::MissingName,
            ));
        }
    }
}