gdlib 0.3.3

Rust library for editing Geometry Dash savefiles
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
//! This module contains the GDObject struct, used for parsing to/from raw object strings
//! This module also contains the GDObjConfig struct for creating new GDObjects
use std::{
    fmt::{Debug, Display, Write},
    str::FromStr,
};

use crate::gdobj::{
    ids::properties::{
        CENTER_EFFECT, DONT_BOOST_X, DONT_BOOST_Y, DONT_ENTER, DONT_FADE, EDITOR_LAYER_1,
        EDITOR_LAYER_2, ENTER_EFFECT_CHANNEL, EXTRA_STICKY, GRIP_SLOPE, GROUPS,
        HAS_EXTENDED_COLLISION, HIDDEN, IS_AREA_PARENT, IS_GROUP_PARENT, IS_HIGH_DETAIL,
        IS_ICE_BLOCK, MATERIAL_CONTROL_ID, MULTITRIGGERABLE, NO_AUDIO_SCALE, NO_GLOW,
        NO_OBJECT_EFFECTS, NO_PARTICLES, NO_TOUCH, NONSTICK_X, NONSTICK_Y, OBJECT_COLOUR,
        OBJECT_ID, OBJECT_MATERIAL, PARENT_GROUPS, PASSABLE, REVERSES_GAMEPLAY, ROTATION,
        SCALE_STICK, SECONDARY_COLOUR, SINGLE_PLAYER_TOUCH, SPAWN_TRIGGERABLE, TOUCH_TRIGGERABLE,
        X_POS, X_SCALE, Y_POS, Y_SCALE, Z_LAYER, Z_ORDER,
    },
    lookup::get_property_type,
};
use bitflags::bitflags;
use itoa;
use smallvec::SmallVec;

pub mod defaults;
/// This file contains all supported block ids and property ids.
/// This file is autogenerated by the build script.
pub mod ids {
    #![allow(missing_docs)]
    include!(concat!(env!("OUT_DIR"), "/ids.rs"));
}
pub mod lookup;
pub mod misc;
pub mod triggers;

pub mod animation_ids {
    #![allow(missing_docs)]

    /// Animations for the big beast (chomper)
    #[repr(i32)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum BigBeast {
        Bite = 0,
        Attack01 = 1,
        Attack01End = 2,
        Idle01 = 3,
    }

    /// Animations for the bat
    #[repr(i32)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum Bat {
        Idle01 = 0,
        Idle02 = 1,
        Idle03 = 2,
        Attack01 = 3,
        Attack02 = 4,
        Attack02End = 5,
        Sleep = 6,
        SleepLoop = 7,
        SleepEnd = 8,
        Attack02Loop = 9,
    }

    /// Animations for the spike ball
    #[repr(i32)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum Spikeball {
        Idle01 = 0,
        Idle02 = 1,
        ToAttack01 = 2,
        Attack01 = 3,
        Attack02 = 4,
        ToAttack03 = 5,
        Attack03 = 6,
        Idle03 = 7,
        FromAttack03 = 8,
    }
}

#[derive(Debug, Clone, PartialEq)]
/// Enum for animation IDs
pub enum Anim {
    /// User-specified animation
    Other(i32),
    /// Built-ins for the big beast (chomper)
    BigBeast(animation_ids::BigBeast),
    /// Built-ins for the bat
    Bat(animation_ids::Bat),
    /// Built-ins for the spike ball
    Spikeball(animation_ids::Spikeball),
}

impl From<Anim> for i32 {
    fn from(value: Anim) -> i32 {
        match value {
            Anim::Bat(b) => b as i32,
            Anim::BigBeast(b) => b as i32,
            Anim::Spikeball(s) => s as i32,
            Anim::Other(i) => i,
        }
    }
}

/// In-level value container. Used in such triggers as item edit, item compare and item persisent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Item {
    Counter(i16),
    Timer(i16),
    Points,
    Attempts,
    MainTime,
}

impl Item {
    /// Returns this item's type
    pub fn get_type(&self) -> ItemType {
        match self {
            Self::Attempts => ItemType::Attempts,
            Self::Counter(_) => ItemType::Counter,
            Self::MainTime => ItemType::MainTime,
            Self::Points => ItemType::Points,
            Self::Timer(_) => ItemType::Timer,
        }
    }
    #[inline(always)]
    /// Returns this item's type as an i32
    pub fn get_type_as_i32(&self) -> i32 {
        self.get_type() as i32
    }
    /// Returns this item's special mode if it has one
    pub fn as_special_mode(&self) -> Option<CounterMode> {
        match self {
            Self::Attempts => Some(CounterMode::Attempts),
            Self::MainTime => Some(CounterMode::MainTime),
            Self::Points => Some(CounterMode::Points),
            _ => None,
        }
    }
    #[inline(always)]
    /// Returns this item's special mode if it has one as an i32
    pub fn as_special_mode_i32(&self) -> i32 {
        self.as_special_mode().unwrap() as i32
    }

    /// Returns this item's ID
    pub fn id(&self) -> i16 {
        match self {
            Self::Counter(c) => *c,
            Self::Timer(t) => *t,
            _ => 0,
        }
    }
}

/// Enum for counter types
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum ItemType {
    Counter = 1,
    Timer = 2,
    Points = 3,
    MainTime = 4,
    Attempts = 5,
}

/// Enum for counter modes
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum CounterMode {
    Attempts = -3,
    Points = -2,
    MainTime = -1,
}

/// Corresponding types for [`GDValue`]s.
#[repr(u8)]
#[derive(Debug, Clone, Eq, PartialEq, Hash, Copy)]
#[allow(missing_docs)]
pub enum GDObjPropType {
    Int,
    Float,
    Text,
    Bool,
    Group,
    Item,
    Easing,
    EventsList,
    ColourChannel,
    ProbabilitiesList,
    SpawnRemapsList,
    Toggle,
    Unknown,
}

#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[allow(missing_docs)]
pub enum ZLayer {
    B5 = -5,
    B4 = -3,
    B3 = -1,
    B2 = 1,
    B1 = 3,
    #[default]
    Default = 0,
    T1 = 5,
    T2 = 7,
    T3 = 9,
    T4 = 11,
}

impl From<i32> for ZLayer {
    fn from(int: i32) -> Self {
        match int {
            -5 => Self::B5,
            -3 => Self::B4,
            -1 => Self::B3,
            1 => Self::B2,
            3 => Self::B1,
            5 => Self::T1,
            7 => Self::T2,
            9 => Self::T3,
            11 => Self::T4,
            _ => Self::Default,
        }
    }
}

/// Enum for colour channels and their IDs
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[allow(missing_docs)]
pub enum ColourChannel {
    Channel(i16),
    Background,
    Ground1,
    Ground2,
    Line,
    #[default]
    Object,
    ThreeDLine,
    MiddleGround,
    MiddleGround2,
    P1,
    P2,
}

impl From<i16> for ColourChannel {
    fn from(c: i16) -> Self {
        match c {
            1000 => Self::Background,
            1001 => Self::Ground1,
            1009 => Self::Ground2,
            1002 => Self::Line,
            1004 => Self::Object,
            1003 => Self::ThreeDLine,
            1013 => Self::MiddleGround,
            1014 => Self::MiddleGround2,
            1005 => Self::P1,
            1006 => Self::P2,
            n => Self::Channel(n),
        }
    }
}

impl From<ColourChannel> for i16 {
    fn from(value: ColourChannel) -> Self {
        match value {
            ColourChannel::Channel(n) => n,
            ColourChannel::Background => 1000,
            ColourChannel::Ground1 => 1001,
            ColourChannel::Ground2 => 1009,
            ColourChannel::Line => 1002,
            ColourChannel::Object => 1004,
            ColourChannel::ThreeDLine => 1003,
            ColourChannel::MiddleGround => 1013,
            ColourChannel::MiddleGround2 => 1014,
            ColourChannel::P1 => 1005,
            ColourChannel::P2 => 1006,
        }
    }
}

/// Enum for all of the move easings
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[allow(missing_docs)]
pub enum MoveEasing {
    #[default]
    None = 0,
    EaseInOut = 1,
    EaseIn = 2,
    EaseOut = 3,
    ElasticInOut = 4,
    ElasticIn = 5,
    ElasticOut = 6,
    BounceInOut = 7,
    BounceIn = 8,
    BounceOut = 9,
    ExponentialInOut = 10,
    ExponentialIn = 11,
    ExponentialOut = 12,
    SineInOut = 13,
    SineIn = 14,
    SineOut = 15,
    BackInOut = 16,
    BackIn = 17,
    BackOut = 18,
}

impl From<i32> for MoveEasing {
    fn from(i: i32) -> Self {
        match i {
            1 => Self::EaseInOut,
            2 => Self::EaseIn,
            3 => Self::EaseOut,
            4 => Self::ElasticInOut,
            5 => Self::ElasticIn,
            6 => Self::ElasticOut,
            7 => Self::BounceInOut,
            8 => Self::BounceIn,
            9 => Self::BounceOut,
            10 => Self::ExponentialInOut,
            11 => Self::ExponentialIn,
            12 => Self::ExponentialOut,
            13 => Self::SineInOut,
            14 => Self::SineIn,
            15 => Self::SineOut,
            16 => Self::BackInOut,
            17 => Self::BackIn,
            18 => Self::BackOut,
            _ => Self::None,
        }
    }
}

const LIST_ALLOCSIZE: usize = 5;

/// Enum for all values represented by Geometry Dash.
/// All values are parsed according to their specified [`GDObjPropType`].
#[derive(Debug, Clone, PartialEq)]
pub enum GDValue {
    /// Any 32-bit signed integer. Fallback for ints.
    Int(i32),
    /// Any 16-bit signed integer.
    Short(i16),
    /// Any 64-bit signed float.
    Float(f64),
    /// Any boolean.
    Bool(bool),
    /// Alternative boolean form. It is serialised as -1 instead of 0 if false.
    Toggle(bool),
    /// Any group, which is represented by an `i16`.
    Group(i16),
    /// Any item ID, whcih is represented by an `i16`.
    Item(i16),
    /// A list of group IDs as i16, which is stored in a SmallVec.
    GroupList(smallvec::SmallVec<[i16; LIST_ALLOCSIZE]>),
    /// A list of probability pairs: (group id, relative chance). Used in the advanced random trigger
    ProbabilitiesList(smallvec::SmallVec<[(i16, i32); LIST_ALLOCSIZE]>),
    /// A list of spawn remap pairs: (old id, new id)
    SpawnRemapsList(smallvec::SmallVec<[(i16, i16); LIST_ALLOCSIZE]>),
    /// A [`MoveEasing`].
    Easing(MoveEasing),
    /// A [`ColourChannel`]. It may be any of the built in ones, or one with an ID in the range of \[1, 999]
    ColourChannel(ColourChannel),
    /// A [`ZLayer`].
    ZLayer(ZLayer),
    /// A list of [`Event`]s. Used in the event trigger.
    Events(Vec<Event>),
    /// A UTF-8 string. The fallback for any value that did not fit any of the aforementioned criteria.
    String(String), // fallback
}

#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
/// Enum for all events that the event trigger can listen for
pub enum Event {
    // zamn!! that's a lot of events
    Unknown = 0,
    TinyLanding = 1,
    FeatherLanding = 2,
    SoftLanding = 3,
    NormalLanding = 4,
    HardLanding = 5,
    HitHead = 6,
    OrbTouched = 7,
    OrbActivated = 8,
    PadActivated = 9,
    GravityInverted = 10,
    GravityRestored = 11,
    NormalJump = 12,
    RobotBoostStart = 13,
    RobotBoostStop = 14,
    UFOJump = 15,
    ShipBoostStart = 16,
    ShipBoostEnd = 17,
    SpiderTeleport = 18,
    BallSwitch = 19,
    SwingSwitch = 20,
    WavePush = 21,
    WaveRelease = 22,
    DashStart = 23,
    DashStop = 24,
    Teleported = 25,
    PortalNormal = 26,
    PortalShip = 27,
    PortalBall = 28,
    PortalUFO = 29,
    PortalWave = 30,
    PortalRobot = 31,
    PortalSpider = 32,
    PortalSwing = 33,
    YellowOrb = 34,
    PinkOrb = 35,
    RedOrb = 36,
    GravityOrb = 37,
    GreenOrb = 38,
    DropOrb = 39,
    CustomOrb = 40,
    DashOrb = 41,
    GravityDashOrb = 42,
    SpiderOrb = 43,
    TeleportOrb = 44,
    YellowPad = 45,
    PinkPad = 46,
    RedPad = 47,
    GravityPad = 48,
    SpiderPad = 49,
    PortalGravityFlip = 50,
    PortalGravityNormal = 51,
    PortalGravityInvert = 52,
    PoratlFlip = 53,
    PortalUnflip = 54,
    PortalNormalScale = 55,
    PortalMiniScale = 56,
    PortalDualOn = 57,
    PortalDualOff = 58,
    PortalTeleport = 59,
    Checkpoint = 60,
    DestroyBlock = 61,
    UserCoin = 62,
    PickupItem = 63,
    FallLow = 65,
    FallMed = 66,
    FallHigh = 67,
    FallVHigh = 68,
    JumpPush = 69,
    JumpRelease = 70,
    LeftPush = 71,
    LeftRelease = 72,
    RightPush = 73,
    RightRelease = 74,
    PlayerReversed = 75,
    CheckpointRespawn = 64, // <- intentionally placed here, the ordering follows that in gd.
    FallSpeedLow = 76,
    FallSpeedMed = 77,
    FallSpeedHigh = 78,
}

impl From<i32> for Event {
    /// Converts the event ID to the variant of the [`Event`] enum. Default to TinyLanding.
    fn from(i: i32) -> Self {
        match i {
            1 => Self::TinyLanding,
            2 => Self::FeatherLanding,
            3 => Self::SoftLanding,
            4 => Self::NormalLanding,
            5 => Self::HardLanding,
            6 => Self::HitHead,
            7 => Self::OrbTouched,
            8 => Self::OrbActivated,
            9 => Self::PadActivated,
            10 => Self::GravityInverted,
            11 => Self::GravityRestored,
            12 => Self::NormalJump,
            13 => Self::RobotBoostStart,
            14 => Self::RobotBoostStop,
            15 => Self::UFOJump,
            16 => Self::ShipBoostStart,
            17 => Self::ShipBoostEnd,
            18 => Self::SpiderTeleport,
            19 => Self::BallSwitch,
            20 => Self::SwingSwitch,
            21 => Self::WavePush,
            22 => Self::WaveRelease,
            23 => Self::DashStart,
            24 => Self::DashStop,
            25 => Self::Teleported,
            26 => Self::PortalNormal,
            27 => Self::PortalShip,
            28 => Self::PortalBall,
            29 => Self::PortalUFO,
            30 => Self::PortalWave,
            31 => Self::PortalRobot,
            32 => Self::PortalSpider,
            33 => Self::PortalSwing,
            34 => Self::YellowOrb,
            35 => Self::PinkOrb,
            36 => Self::RedOrb,
            37 => Self::GravityOrb,
            38 => Self::GreenOrb,
            39 => Self::DropOrb,
            40 => Self::CustomOrb,
            41 => Self::DashOrb,
            42 => Self::GravityDashOrb,
            43 => Self::SpiderOrb,
            44 => Self::TeleportOrb,
            45 => Self::YellowPad,
            46 => Self::PinkPad,
            47 => Self::RedPad,
            48 => Self::GravityPad,
            49 => Self::SpiderPad,
            50 => Self::PortalGravityFlip,
            51 => Self::PortalGravityNormal,
            52 => Self::PortalGravityInvert,
            53 => Self::PoratlFlip,
            54 => Self::PortalUnflip,
            55 => Self::PortalNormalScale,
            56 => Self::PortalMiniScale,
            57 => Self::PortalDualOn,
            58 => Self::PortalDualOff,
            59 => Self::PortalTeleport,
            60 => Self::Checkpoint,
            61 => Self::DestroyBlock,
            62 => Self::UserCoin,
            63 => Self::PickupItem,
            65 => Self::FallLow,
            66 => Self::FallMed,
            67 => Self::FallHigh,
            68 => Self::FallVHigh,
            69 => Self::JumpPush,
            70 => Self::JumpRelease,
            71 => Self::LeftPush,
            72 => Self::LeftRelease,
            73 => Self::RightPush,
            74 => Self::RightRelease,
            75 => Self::PlayerReversed,
            64 => Self::CheckpointRespawn,
            76 => Self::FallSpeedLow,
            77 => Self::FallSpeedMed,
            78 => Self::FallSpeedHigh,
            _ => Self::Unknown,
        }
    }
}

// for debug purposes

// fn parse_with_err_handle<T>(s: &str, p: u16) -> T
// where
//     T: FromStr + Default + Display,
//     <T as FromStr>::Err: Debug,
// {
//     match s.parse::<T>() {
//         Ok(n) => n,
//         Err(e) => {
//             println!(
//                 "Error with parsing property {p} with value {s}, type {} ({e:?})",
//                 type_name::<T>()
//             );
//             T::default()
//         }
//     }
// }

macro_rules! parse {
    ($v:expr => $t:ty) => {
        $v.parse::<$t>().unwrap_or_default()
    };
}

// helper function to parse strings of this formatting "k1.v1.k2.v2.etc.etc."
fn parse_sibling_items<T, S>(s: &str) -> Vec<(T, S)>
where
    T: Default + FromStr + Copy + Clone,
    S: Default + FromStr + Copy + Clone,
{
    let mut curr_group: T = T::default();
    let mut idx = 0;
    let mut tuples = vec![];
    s.split('.').for_each(|c| {
        match idx % 2 == 0 {
            true => {
                // at even idx, so this is a group
                curr_group = parse!(c => T)
            }
            false => {
                // at odd idx, so this is a chance
                tuples.push((curr_group, parse!(c => S)));
            }
        };
        idx += 1
    });
    tuples
}

impl GDValue {
    /// Converts input string to a variant of this enum based on the property type
    pub fn from(t: GDObjPropType, s: &str) -> Self {
        match t {
            GDObjPropType::Bool => Self::Bool(s == "1"),
            GDObjPropType::Toggle => Self::Toggle(s == "1"),
            GDObjPropType::ColourChannel => {
                Self::ColourChannel(ColourChannel::from(parse!(s => i16)))
            }
            GDObjPropType::Easing => Self::Easing(MoveEasing::from(parse!(s => i32))),
            GDObjPropType::Float => Self::Float(parse!(s => f64)),
            GDObjPropType::Int => Self::Int(parse!(s => i32)),
            GDObjPropType::EventsList => Self::Events(
                s.split('.')
                    .map(|i| Event::from(parse!(i => i32)))
                    .collect(),
            ),
            GDObjPropType::ProbabilitiesList => {
                let tuples = parse_sibling_items::<i16, i32>(s);
                Self::ProbabilitiesList(SmallVec::from_vec(tuples))
            }
            GDObjPropType::SpawnRemapsList => {
                let tuples = parse_sibling_items::<i16, i16>(s);
                Self::SpawnRemapsList(SmallVec::from_vec(tuples))
            }
            GDObjPropType::Group => Self::Group(parse!(s => i16)),
            GDObjPropType::Item => Self::Item(parse!(s => i16)),
            GDObjPropType::Text | GDObjPropType::Unknown => Self::String(s.to_owned()),
        }
    }

    #[inline(always)]
    /// Converts a vector of [`Group`]s to a [`GDValue`]
    pub fn from_group_list(g: Vec<Group>) -> Self {
        Self::GroupList(SmallVec::from_vec(g.iter().map(|&g| g.id()).collect()))
    }

    #[inline(always)]
    /// Converts a vector of parent [`Group`]s to a [`GDValue`]
    pub fn parents_group_list(g: Vec<Group>) -> Self {
        Self::GroupList(SmallVec::from_vec(
            g.iter()
                .filter_map(|g| match g {
                    Group::Parent(p) => Some(*p),
                    Group::Regular(_) => None,
                })
                .collect(),
        ))
    }

    #[inline(always)]
    /// Converts a probabilities list to a [`GDValue`].
    pub fn from_prob_list(g: Vec<(i16, i32)>) -> Self {
        Self::ProbabilitiesList(SmallVec::from_vec(g))
    }

    #[inline(always)]
    /// Converts a spawn remaps list to a [`GDValue`].
    pub fn from_spawn_remaps(g: Vec<(i16, i16)>) -> Self {
        Self::SpawnRemapsList(SmallVec::from_vec(g))
    }

    #[inline(always)]
    /// Converts a raw colour channel value to a [`GDValue`].
    pub fn colour_channel(s: &str) -> Self {
        Self::ColourChannel(ColourChannel::from(s.parse().unwrap_or(0)))
    }

    #[inline(always)]
    /// Converts a raw zlayer value to a [`GDValue`].
    pub fn zlayer(s: &str) -> Self {
        Self::ZLayer(ZLayer::from(s.parse().unwrap_or(0)))
    }
}

macro_rules! fmt_intlist {
    // Vec<int>
    ($vals:expr, $i_buf:expr) => {{
        let mut items_str = String::with_capacity($vals.len() * 4);
        for (idx, item) in $vals.iter().enumerate() {
            if idx != 0 {
                items_str.push('.');
            }
            items_str.push_str($i_buf.format(*item as i32));
        }
        items_str
    }};
}

macro_rules! fmt_inttuples {
    // Vec<(int, int)>
    ($vals:expr, $i_buf:expr) => {{
        let mut items_str = String::with_capacity($vals.len() * 8);
        for (idx, item) in $vals.iter().enumerate() {
            if idx != 0 {
                items_str.push('.');
            }
            items_str.push_str($i_buf.format(item.0));
            items_str.push('.');
            items_str.push_str($i_buf.format(item.1));
        }
        items_str
    }};
}

impl Display for GDValue {
    // also the serialisation
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut i_buf = itoa::Buffer::new();
        let mut d_buf = dtoa::Buffer::new();

        match self {
            GDValue::Bool(b) => write!(f, "{}", if *b { '1' } else { '0' }),
            GDValue::Toggle(b) => write!(
                f,
                "{}",
                match b {
                    true => "1",
                    false => "-1",
                }
            ),
            GDValue::ColourChannel(v) => write!(f, "{}", i_buf.format(Into::<i16>::into(*v))),
            GDValue::Easing(v) => write!(f, "{}", i_buf.format(*v as i32)),
            GDValue::Float(v) => write!(f, "{}", d_buf.format(*v)),
            GDValue::Group(v) | GDValue::Item(v) => write!(f, "{}", i_buf.format(*v)),
            GDValue::GroupList(v) => write!(f, "{}", fmt_intlist!(v, i_buf)),
            GDValue::ProbabilitiesList(v) => write!(f, "{}", fmt_inttuples!(v, i_buf)),
            GDValue::SpawnRemapsList(v) => write!(f, "{}", fmt_inttuples!(v, i_buf)),
            GDValue::Int(v) => write!(f, "{}", i_buf.format(*v)),
            GDValue::Short(v) => write!(f, "{}", i_buf.format(*v)),
            GDValue::String(v) => write!(f, "{v}"),
            GDValue::ZLayer(v) => write!(f, "{}", i_buf.format(*v as i32)),
            GDValue::Events(evts) => write!(f, "{}", fmt_intlist!(evts, i_buf)),
        }
    }
}

// Map of all object ids to names: (id, name)
const OBJECT_NAMES: &[(i32, &str)] = &[
    (1, "Default block"),
    (2, "Waffle block floor"),
    (3, "Waffle block corner"),
    (4, "Waffle block inner corner"),
    (5, "Waffle block filler"),
    (6, "Waffle block no bottom"),
    (7, "Waffle block straight"),
    (8, "Spike"),
    (9, "Ground spikes"),
    (10, "Normal gravity portal"),
    (11, "Flipped gravity portal"),
    (12, "Cube portal"),
    (13, "Ship portal"),
    (15, "Pulse pole tall"),
    (16, "Pulse pole medium"),
    (17, "Pulse pole short"),
    (18, "Transparent spikes huge"),
    (19, "Transparent spikes big"),
    (20, "Transparent spikes medium"),
    (21, "Transparent spikes small"),
    (22, "No block transition object"),
    (23, "Blocks from top transition object"),
    (24, "Blocks from bottom transition object"),
    (25, "Blocks from left transition object"),
    (26, "Blocks from right transition object"),
    (27, "Scale in transition object"),
    (28, "Scale out transition object"),
    // 29 + 30: mystery colour triggers
    (31, "Start pos"),
    (32, "Enable player trail"),
    (33, "Disable player trail"),
    (34, "Solid startpos"),
    (35, "Yellow pad"),
    (36, "Yellow orb"),
    (39, "Small spike"),
    (40, "Half block default"),
    (41, "Chain tall"),
    (45, "Mirror portal reverse"),
    (46, "Mirror portal normal"),
    (47, "Ball portal"),
    (48, "Transparent clouds big"),
    (49, "Transparent clouds small"),
    (50, "Pulse circle"),
    (51, "Pulse ring"),
    (52, "Pulse heart"),
    (53, "Pulse diamond"),
    (54, "Pulse star"),
    (55, "Random direction transition object"),
    (56, "Away to left transition object"),
    (57, "Away to right transition object"),
    (58, "Away from middle transition object"),
    (59, "Away to middle transition object"),
    (60, "Pulse music note"),
    (61, "Ground spikes wavy"),
    (62, "Wavy block floor"),
    (67, "Blue pad"),
    (83, "Waffle block"),
    (84, "Blue orb"),
    (88, "Buzzsaw big"),
    (89, "Buzzsaw medium"),
    (98, "Buzzsaw small"),
    (99, "Size portal normal"),
    (101, "Size portal small"),
    (111, "UFO portal"),
    (140, "Pink pad"),
    (141, "Pink orb"),
    (200, "Speed portal 0.5x"),
    (201, "Speed portal 1x"),
    (202, "Speed portal 2x"),
    (203, "Speed portal 3x"),
    (286, "Dual portal double"),
    (287, "Dual portal single"),
    (899, "Trigger Colour"),
    (901, "Trigger Move"),
    (914, "Text object"),
    (1006, "Trigger Pulse"),
    (1007, "Trigger Alpha"),
    (1049, "Trigger Toggle"),
    (1268, "Trigger Spawn"),
    (1346, "Trigger Rotation"),
    (1347, "Trigger Follow"),
    (1520, "Trigger Shake"),
    (1585, "Trigger Animate"),
    (1595, "Trigger Touch"),
    (1611, "Trigger Count"),
    (1615, "Counter"),
    (1616, "Trigger Stop"),
    (1812, "Trigger On death"),
    (1812, "Trigger follow player y"),
    (1815, "Trigger Collision"),
    (1816, "Collision block"),
    (1818, "BG effect on"),
    (1819, "BG effect off"),
    (1912, "Trigger Random"),
    (1913, "Trigger Camera zoom"),
    (1915, "Don't fade + don't enter transition object"),
    (1917, "Trigger Reverse gameplay"),
    (1932, "Trigger Player control"),
    (1934, "Trigger Song"),
    (1935, "Trigger Time warp"),
    (2016, "Camera guide"),
    (2066, "Trigger Gravity"),
    (2067, "Trigger Scale"),
    (2068, "Trigger Advanced random"),
    (2900, "Trigger rotate gameplay"),
    (2900, "Trigger Middleground config"),
    (3024, "Trigger Area stop"),
    (3031, "Trigger Middleground change"),
    (3600, "Trigger End"),
    (3604, "Trigger Event"),
    (3606, "BG speed config"),
    (3608, "Trigger Spawn particle"),
    (3609, "Trigger Instant collision"),
    (3612, "MG speed config"),
    (3613, "UI config"),
    (3614, "Trigger Time"),
    (3615, "Trigger Time event"),
    (3617, "Trigger Time control"),
    (3618, "Trigger Reset group"),
    (3619, "Trigger Item edit"),
    (3620, "Trigger Item compare"),
    (3640, "Collision state block"),
    (3641, "Trigger Persistent item"),
    (3643, "Toggle block"),
    (3662, "Trigger Link visible"),
];

/// Container for GD Object properties.
#[derive(Clone, PartialEq)]
pub struct GDObject {
    /// The object's ID.
    pub id: i32,
    /// General properties, such as position and scale.
    pub config: GDObjConfig,
    /// Object-specific properties
    pub properties: Vec<(u16, GDValue)>,
}

impl Display for GDObject {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let group_str = match !self.config.groups.is_empty() {
            true => &format!(
                " with groups: {}",
                self.config
                    .groups
                    .iter()
                    .map(|g| format!("{}", g.id()))
                    .collect::<Vec<String>>()
                    .join(", ")
            ),
            false => "",
        };

        let mut trigger_conf_str = String::new();
        if self.config.trigger_cfg.spawnable || self.config.trigger_cfg.touchable {
            if self.config.trigger_cfg.multitriggerable {
                trigger_conf_str += "Multi"
            }
            if self.config.trigger_cfg.touchable {
                trigger_conf_str += "touchable "
            } else if self.config.trigger_cfg.spawnable {
                trigger_conf_str += "spawnable "
            }
        }

        write!(
            f,
            "{trigger_conf_str}{} @ ({}, {}) scaled to ({}, {}){} angled to {}°",
            self.get_name(),
            self.config.pos.0,
            self.config.pos.1,
            self.config.scale.0,
            self.config.scale.1,
            group_str,
            self.config.angle
        )
    }
}

impl Debug for GDObject {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut property_str = String::with_capacity(self.properties.len() * 32);

        for (property, value) in self.properties.iter() {
            let desc = lookup::PROPERTY_TABLE.get(property).map(|p| p.0);
            if let Some(d) = desc {
                write!(property_str, "\n    - {d}: {value:?}")
            } else {
                write!(property_str, "\n    - {property}: {value:?}")
            }
            .unwrap();
        }

        write!(
            f,
            "{} with properties:{property_str}",
            <Self as ToString>::to_string(self),
        )
    }
}

impl GDObject {
    /// Parses raw object string to GDObject
    pub fn parse_str(s: &str) -> GDObject {
        let mut obj = GDObject {
            id: 1,
            config: GDObjConfig::default(),
            properties: vec![],
        };

        let mut iter = s.trim_end_matches(';').split(",");
        while let (Some(idx), Some(val)) = (iter.next(), iter.next()) {
            let idx_u16 = match idx.parse::<u16>() {
                Ok(n) => n,
                Err(_) => match idx[2..].parse::<u16>() {
                    Ok(n) => n + 10_000,
                    Err(_) => 65535,
                },
            };

            match idx_u16 {
                OBJECT_ID => obj.id = parse!(val => i32),
                X_POS => obj.config.pos.0 = val.parse().unwrap_or(0.0),
                Y_POS => obj.config.pos.1 = val.parse().unwrap_or(0.0),
                ROTATION => obj.config.angle = val.parse().unwrap_or(0.0),
                TOUCH_TRIGGERABLE => obj.config.trigger_cfg.touchable = parse!(val => bool),
                SPAWN_TRIGGERABLE => obj.config.trigger_cfg.spawnable = parse!(val => bool),
                MULTITRIGGERABLE => obj.config.trigger_cfg.multitriggerable = parse!(val => bool),
                GROUPS => {
                    obj.config.add_groups(
                        val.trim_matches('"')
                            .split(".")
                            .filter_map(|g| g.parse::<i16>().ok())
                            .map(Group::Regular)
                            .collect::<Vec<Group>>(),
                    );
                }
                X_SCALE => obj.config.scale.0 = val.parse().unwrap_or(1.0),
                Y_SCALE => obj.config.scale.1 = val.parse().unwrap_or(1.0),
                EDITOR_LAYER_1 => obj.config.editor_layers.0 = parse!(val => i16),
                EDITOR_LAYER_2 => obj.config.editor_layers.1 = parse!(val => i16),
                OBJECT_COLOUR => {
                    obj.config.colour_channels.0 = ColourChannel::from(parse!(val => i16))
                }
                SECONDARY_COLOUR => {
                    obj.config.colour_channels.1 = ColourChannel::from(parse!(val => i16))
                }
                Z_LAYER => obj.config.z_layer = ZLayer::from(parse!(val => i32)),
                Z_ORDER => obj.config.z_order = parse!(val => i32),
                ENTER_EFFECT_CHANNEL => obj.config.enter_effect_channel = parse!(val => i16),
                OBJECT_MATERIAL => obj.config.material_id = parse!(val => i16),
                DONT_FADE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_fade, parse!(val => bool)),
                DONT_ENTER => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_enter, parse!(val => bool)),
                NO_OBJECT_EFFECTS => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_effects, parse!(val => bool)),
                IS_GROUP_PARENT => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::is_group_parent, parse!(val => bool)),
                IS_AREA_PARENT => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::is_area_parent, parse!(val => bool)),
                DONT_BOOST_X => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_boost_x, parse!(val => bool)),
                DONT_BOOST_Y => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::dont_boost_y, parse!(val => bool)),
                IS_HIGH_DETAIL => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::high_detail, parse!(val => bool)),
                NO_TOUCH => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_touch, parse!(val => bool)),
                PASSABLE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::passable, parse!(val => bool)),
                HIDDEN => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::hidden, parse!(val => bool)),
                NONSTICK_X => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::non_stick_x, parse!(val => bool)),
                NONSTICK_Y => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::non_stick_y, parse!(val => bool)),
                EXTRA_STICKY => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::extra_sticky, parse!(val => bool)),
                HAS_EXTENDED_COLLISION => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::extended_collision, parse!(val => bool)),
                IS_ICE_BLOCK => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::is_ice_block, parse!(val => bool)),
                GRIP_SLOPE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::grip_slope, parse!(val => bool)),
                NO_GLOW => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_glow, parse!(val => bool)),
                NO_PARTICLES => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_particles, parse!(val => bool)),
                SCALE_STICK => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::scale_stick, parse!(val => bool)),
                NO_AUDIO_SCALE => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::no_audio_scale, parse!(val => bool)),
                SINGLE_PLAYER_TOUCH => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::single_ptouch, parse!(val => bool)),
                CENTER_EFFECT => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::center_effect, parse!(val => bool)),
                REVERSES_GAMEPLAY => obj
                    .config
                    .attributes
                    .set(GDObjAttributes::reverse, parse!(val => bool)),
                MATERIAL_CONTROL_ID => obj.config.control_id = parse!(val => i16),
                PARENT_GROUPS => {
                    // add groups method handles deduping
                    obj.config.add_groups(
                        val.trim_matches('"')
                            .split(".")
                            .filter_map(|g| g.parse::<i16>().ok())
                            .map(Group::Parent)
                            .collect::<Vec<Group>>(),
                    );
                }
                n => obj.set_property_raw(n, val),
            }
        }

        obj
    }

    fn set_property_raw(&mut self, p: u16, value: &str) {
        self.set_property(
            p,
            GDValue::from(
                get_property_type(p).unwrap_or(GDObjPropType::Unknown),
                value,
            ),
        );
    }

    /// Sets the prpoerty ID to the value, and craetes it if it doesn't exist
    pub fn set_property(&mut self, p: u16, val: GDValue) {
        if let Some(v) = self.properties.iter_mut().find(|(k, _)| *k == p) {
            v.1 = val;
        } else {
            let new_idx = self.properties.partition_point(|(k, _)| k < &p);
            self.properties.insert(new_idx, (p, val));
        }
    }

    /// Removes the property from this object's property map by its ID.
    pub fn del_property(&mut self, p: u16) {
        if let Ok(idx) = self.properties.binary_search_by_key(&p, |t| t.0) {
            self.properties.remove(idx);
        }
    }

    /// Returns this object as a property string
    pub fn serialise_to_string(&self) -> String {
        let mut properties_string = String::with_capacity(self.properties.len() * 8);
        for (idx, val) in self.properties.iter() {
            let (pref, id) = if *idx < 10_000 {
                ("", *idx)
            } else {
                ("kA", idx - 10_000) // also need to add a "kA" prepend
            };

            write!(properties_string, ",{pref}{id},{val}").unwrap();
        }
        let config_str = self.config.serialise_to_string();

        let raw_str = format!("1,{}{config_str}{properties_string}", self.id);
        raw_str.replace("\"", "") + ";"
    }

    /// Returns this object's name
    pub fn get_name(&self) -> String {
        OBJECT_NAMES
            .iter()
            .find(|&o| o.0 == self.id)
            .unwrap_or(&(0, format!("Object {}", self.id).as_str()))
            .1
            .to_string()
    }

    /// Creates a new GDObject from ID, config, and extra proerties
    #[inline(always)]
    pub fn new(id: i32, config: &GDObjConfig, properties: Vec<(u16, GDValue)>) -> Self {
        GDObject {
            id,
            config: config.clone(),
            properties,
        }
    }

    #[inline]
    /// Creates a default object from the specified ID
    pub fn default_from_id(id: i32) -> Self {
        defaults::default_object(id)
    }

    #[inline(always)]
    fn get_attr_as_gdvalue(&self, attr: GDObjAttributes) -> GDValue {
        GDValue::Bool(self.config.get_attribute_flag(attr))
    }

    /// Fetches a property from this object's configuration
    pub fn get_property(&self, p: u16) -> Option<GDValue> {
        match p {
            // one of the most fascinating matches of all time
            1 => Some(GDValue::Int(self.id)),
            2 => Some(GDValue::Float(self.config.pos.0)),
            3 => Some(GDValue::Float(self.config.pos.1)),
            6 => Some(GDValue::Float(self.config.angle)),
            11 => Some(GDValue::Bool(self.config.trigger_cfg.touchable)),
            57 => Some(GDValue::from_group_list(self.config.groups.clone())),
            62 => Some(GDValue::Bool(self.config.trigger_cfg.spawnable)),
            87 => Some(GDValue::Bool(self.config.trigger_cfg.multitriggerable)),
            128 => Some(GDValue::Float(self.config.scale.0)),
            129 => Some(GDValue::Float(self.config.scale.1)),
            20 => Some(GDValue::Short(self.config.editor_layers.0)),
            61 => Some(GDValue::Short(self.config.editor_layers.1)),
            21 => Some(GDValue::Short(self.config.colour_channels.0.into())),
            22 => Some(GDValue::Short(self.config.colour_channels.1.into())),
            24 => Some(GDValue::ZLayer(self.config.z_layer)),
            25 => Some(GDValue::Int(self.config.z_order)),
            343 => Some(GDValue::Short(self.config.enter_effect_channel)),
            446 => Some(GDValue::Short(self.config.material_id)),
            534 => Some(GDValue::Short(self.config.control_id)),
            64 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_fade)),
            67 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_enter)),
            116 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_effects)),
            34 => Some(self.get_attr_as_gdvalue(GDObjAttributes::is_group_parent)),
            279 => Some(self.get_attr_as_gdvalue(GDObjAttributes::is_area_parent)),
            509 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_boost_x)),
            496 => Some(self.get_attr_as_gdvalue(GDObjAttributes::dont_boost_y)),
            103 => Some(self.get_attr_as_gdvalue(GDObjAttributes::high_detail)),
            121 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_touch)),
            134 => Some(self.get_attr_as_gdvalue(GDObjAttributes::passable)),
            135 => Some(self.get_attr_as_gdvalue(GDObjAttributes::hidden)),
            136 => Some(self.get_attr_as_gdvalue(GDObjAttributes::non_stick_x)),
            289 => Some(self.get_attr_as_gdvalue(GDObjAttributes::non_stick_y)),
            495 => Some(self.get_attr_as_gdvalue(GDObjAttributes::extra_sticky)),
            511 => Some(self.get_attr_as_gdvalue(GDObjAttributes::extended_collision)),
            137 => Some(self.get_attr_as_gdvalue(GDObjAttributes::is_ice_block)),
            193 => Some(self.get_attr_as_gdvalue(GDObjAttributes::grip_slope)),
            96 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_glow)),
            507 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_particles)),
            356 => Some(self.get_attr_as_gdvalue(GDObjAttributes::scale_stick)),
            372 => Some(self.get_attr_as_gdvalue(GDObjAttributes::no_audio_scale)),
            284 => Some(self.get_attr_as_gdvalue(GDObjAttributes::single_ptouch)),
            369 => Some(self.get_attr_as_gdvalue(GDObjAttributes::center_effect)),
            117 => Some(self.get_attr_as_gdvalue(GDObjAttributes::reverse)),

            _ => self
                .properties
                .iter()
                .find(|pair| pair.0 == p)
                .map(|p| p.1.clone()),
        }
    }

    /// Set this object's internal config
    pub fn set_config(&mut self, config: GDObjConfig) {
        self.config = config;
    }
}

/// Trigger config, used for defining general properties of a trigger object
#[derive(Clone, Debug, PartialEq, Default)]
pub struct TriggerConfig {
    /// is touch triggerable?
    pub touchable: bool,
    /// is spawn triggerable?
    pub spawnable: bool,
    /// is multitriggerable?
    pub multitriggerable: bool,
}

/// Group ID container for regular and parent groups
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum Group {
    Regular(i16),
    Parent(i16),
}

impl Ord for Group {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // check ids first
        // check the types only if equal
        match self.id().cmp(&other.id()) {
            std::cmp::Ordering::Equal => self.get_type().cmp(&other.get_type()),
            o => o,
        }
    }
}

impl PartialOrd for Group {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
/// Group type enum
pub enum GroupType {
    Regular,
    Parent,
}

impl Ord for GroupType {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        if self == other {
            std::cmp::Ordering::Equal
        } else if *self == Self::Regular {
            // other is parent, so is less
            std::cmp::Ordering::Greater
        } else {
            std::cmp::Ordering::Less
        }
    }
}

impl PartialOrd for GroupType {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Group {
    /// Returns this group's ID
    pub fn id(&self) -> i16 {
        match self {
            Self::Regular(id) => *id,
            Self::Parent(id) => *id,
        }
    }
    /// Returns this group's type
    pub fn get_type(&self) -> GroupType {
        match self {
            Group::Parent(_) => GroupType::Parent,
            Group::Regular(_) => GroupType::Regular,
        }
    }
}

impl From<i16> for Group {
    fn from(value: i16) -> Self {
        Self::Regular(value)
    }
}

/// Object config, used for defining general properties of an object
#[derive(Clone, Debug, PartialEq)]
pub struct GDObjConfig {
    /// Position of this object
    pub pos: (f64, f64),
    /// Scale of this object
    pub scale: (f64, f64),
    /// Angle of rotation
    pub angle: f64,
    /// Groups (both parents and regular)
    pub groups: Vec<Group>,
    /// Trigger activation config
    pub trigger_cfg: TriggerConfig,
    /// Z order of this object
    pub z_order: i32,
    /// Z layer of this object
    pub z_layer: ZLayer,
    /// Editor layers of this object
    pub editor_layers: (i16, i16),
    /// Main and detail colour channels respectively
    pub colour_channels: (ColourChannel, ColourChannel),
    /// Enter effect channel
    pub enter_effect_channel: i16,
    /// Material ID
    pub material_id: i16,
    /// Control ID
    pub control_id: i16,
    /// Common attributes
    pub attributes: GDObjAttributes,
}

impl Default for GDObjConfig {
    fn default() -> Self {
        GDObjConfig {
            pos: (0.0, 0.0),
            scale: (1.0, 1.0),
            angle: 0.0,
            groups: vec![],
            trigger_cfg: TriggerConfig {
                touchable: false,
                spawnable: false,
                multitriggerable: false,
            },
            z_layer: ZLayer::T1,
            z_order: 0,
            editor_layers: (0, 0),
            colour_channels: (ColourChannel::Object, ColourChannel::Channel(1)),
            enter_effect_channel: 0,
            material_id: 0,
            control_id: 0,
            attributes: GDObjAttributes::new(),
        }
    }
}

impl GDObjConfig {
    /// Alias for default
    #[inline(always)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Serialises this config struct to a string
    pub fn serialise_to_string(&self) -> String {
        let mut properties = String::with_capacity(64);
        let _ = write!(
            properties,
            ",2,{},3,{}{}",
            self.pos.0,
            self.pos.1,
            self.attributes.get_property_str()
        );

        // bools
        serialise_bools(
            &[
                ("11", self.trigger_cfg.touchable),
                ("62", self.trigger_cfg.spawnable),
                ("87", self.trigger_cfg.multitriggerable),
            ],
            &mut properties,
        );

        // f64
        serialise_fields(
            &[
                ("6", self.angle, 0.0),
                ("128", self.scale.0, 1.0),
                ("129", self.scale.1, 1.0),
            ],
            &mut properties,
        );

        // i16
        serialise_fields(
            &[
                ("20", self.editor_layers.0, 0),
                ("61", self.editor_layers.1, 0),
                (
                    "21",
                    self.colour_channels.0.into(),
                    ColourChannel::Object.into(),
                ),
                ("22", self.colour_channels.1.into(), 1),
                ("24", self.z_layer as i16, ZLayer::T1 as i16),
                ("343", self.enter_effect_channel, 0),
                ("446", self.material_id, 0),
                ("534", self.control_id, 0),
            ],
            &mut properties,
        );

        serialise_fields(&[("25", self.z_order, 0)], &mut properties);

        if !self.groups.is_empty() {
            properties.push_str(",57,");
            let group_str = &self
                .groups
                .iter()
                .map(|g| g.id().to_string())
                .collect::<Vec<String>>()
                .join(".");
            properties.push_str(group_str);
        };

        properties
    }

    fn dedup_groups(&mut self) {
        // sort beforehand
        self.groups.sort();
        self.groups.dedup_by(|a, b| a.id() == b.id());
    }

    /// Sets groups of this object
    #[inline(always)]
    pub fn groups<T: IntoIterator<Item = I>, I: Into<Group>>(mut self, groups: T) -> Self {
        self.groups = groups.into_iter().map(|g| g.into()).collect();
        self.dedup_groups();
        self
    }
    /// Adds groups to this object's groups
    #[inline(always)]
    pub fn add_groups<T: AsRef<[Group]>>(&mut self, groups: T) {
        self.groups.extend_from_slice(groups.as_ref());
        self.dedup_groups();
    }
    /// Adds group to this object's groups
    #[inline(always)]
    pub fn add_group(&mut self, group: Group) {
        self.groups.push(group);
        self.dedup_groups();
    }
    /// Removes this group from this object's groups
    #[inline(always)]
    pub fn remove_group(&mut self, group: Group) {
        if let Some(idx) = self.groups.iter().position(|&g| g == group) {
            self.groups.swap_remove(idx);
        }
    }
    /// Clears all groups from this object
    #[inline(always)]
    pub fn clear_groups(&mut self) {
        self.groups.clear();
    }
    /// Sets x position of this object
    #[inline(always)]
    pub fn x(mut self, x: f64) -> Self {
        self.pos.0 = x;
        self
    }
    /// Sets y position of this object
    #[inline(always)]
    pub fn y(mut self, y: f64) -> Self {
        self.pos.1 = y;
        self
    }

    /// Applies a translation to this object's position
    pub fn translate(mut self, x: f64, y: f64) -> Self {
        self.pos.0 += x;
        self.pos.1 += y;
        self
    }

    /// Sets x and y position of this object
    #[inline(always)]
    pub fn pos(mut self, x: f64, y: f64) -> Self {
        self.pos = (x, y);
        self
    }
    /// Sets x scale of this object
    #[inline(always)]
    pub fn xscale(mut self, xscale: f64) -> Self {
        self.scale.0 = xscale;
        self
    }
    /// Sets y scale of this object
    #[inline(always)]
    pub fn yscale(mut self, yscale: f64) -> Self {
        self.scale.1 = yscale;
        self
    }
    /// Sets x and y scale of this object
    #[inline(always)]
    pub fn scale(mut self, x: f64, y: f64) -> Self {
        self.scale = (x, y);
        self
    }
    /// Sets rotation angle of this object
    #[inline(always)]
    pub fn angle(mut self, angle: f64) -> Self {
        self.angle = angle;
        self
    }
    /// Makes this object touch triggerable
    #[inline(always)]
    pub fn touchable(mut self, touchable: bool) -> Self {
        self.trigger_cfg.touchable = touchable;
        self
    }
    /// Makes this object spawn triggerable
    #[inline(always)]
    pub fn spawnable(mut self, spawnable: bool) -> Self {
        self.trigger_cfg.spawnable = spawnable;
        self
    }
    /// Makes this object multi-triggerable
    #[inline(always)]
    pub fn multitrigger(mut self, multi: bool) -> Self {
        self.trigger_cfg.multitriggerable = multi;
        self
    }
    /// Sets this object's base colour channel
    #[inline(always)]
    pub fn set_base_colour(mut self, channel: ColourChannel) -> Self {
        self.colour_channels.0 = channel;
        self
    }
    /// Sets this object's detail colour channel
    #[inline(always)]
    pub fn set_detail_colour(mut self, channel: ColourChannel) -> Self {
        self.colour_channels.1 = channel;
        self
    }
    /// Sets this object's Z-layer
    #[inline(always)]
    pub fn set_z_layer(mut self, z: ZLayer) -> Self {
        self.z_layer = z;
        self
    }
    /// Sets this object's Z-order
    #[inline(always)]
    pub fn set_z_order(mut self, z: i32) -> Self {
        self.z_order = z;
        self
    }
    /// Sets editor layer 1 of this object
    #[inline(always)]
    pub fn editor_layer_1(mut self, l: i16) -> Self {
        self.editor_layers.0 = l;
        self
    }
    /// Sets editor layer 2 of this object
    #[inline(always)]
    pub fn editor_layer_2(mut self, l: i16) -> Self {
        self.editor_layers.1 = l;
        self
    }
    /// Sets this object's material id
    #[inline(always)]
    pub fn set_material_id(mut self, material_id: i16) -> Self {
        self.material_id = material_id;
        self
    }
    /// Sets this object's enter effect channel
    #[inline(always)]
    pub fn set_enter_channel(mut self, channel: i16) -> Self {
        self.enter_effect_channel = channel;
        self
    }
    /// Sets this object's control ID
    #[inline(always)]
    pub fn set_control_id(mut self, id: i16) -> Self {
        self.control_id = id;
        self
    }

    /// Gets the value of a set attribute flag.  
    /// The flag is only true if it has been set as such. Unset flags return false.
    pub fn get_attribute_flag(&self, flag: GDObjAttributes) -> bool {
        self.attributes.contains(flag)
    }

    /// Sets the attribute of the specified flag. Function is useable in builder syntax.
    pub fn set_attribute_flag(mut self, flag: GDObjAttributes, toggle: bool) -> Self {
        self.attributes.set(flag, toggle);
        self
    }
}

bitflags! {
    /// Common attributes container struct
    #[derive(Debug, Clone, PartialEq, Default, Eq, Hash)]
    // #[allow(missing_docs)] won't work here for some odd reason
    pub struct GDObjAttributes: u32 {
        /// @nodoc
        const dont_fade          = 1;
        /// @nodoc
        const dont_enter         = 1 << 1;
        /// @nodoc
        const no_effects         = 1 << 2;
        /// @nodoc
        const is_group_parent    = 1 << 3;
        /// @nodoc
        const is_area_parent     = 1 << 4;
        /// @nodoc
        const dont_boost_x       = 1 << 5;
        /// @nodoc
        const dont_boost_y       = 1 << 6;
        /// @nodoc
        const high_detail        = 1 << 7;
        /// @nodoc
        const no_touch           = 1 << 8;
        /// @nodoc
        const passable           = 1 << 9;
        /// @nodoc
        const hidden             = 1 << 10;
        /// @nodoc
        const non_stick_x        = 1 << 11;
        /// @nodoc
        const non_stick_y        = 1 << 12;
        /// @nodoc
        const extra_sticky       = 1 << 13;
        /// @nodoc
        const extended_collision = 1 << 14;
        /// @nodoc
        const is_ice_block       = 1 << 15;
        /// @nodoc
        const grip_slope         = 1 << 16;
        /// @nodoc
        const no_glow            = 1 << 17;
        /// @nodoc
        const no_particles       = 1 << 18;
        /// @nodoc
        const scale_stick        = 1 << 19;
        /// @nodoc
        const no_audio_scale     = 1 << 20;
        /// @nodoc
        const single_ptouch      = 1 << 21;
        /// @nodoc
        const center_effect      = 1 << 22;
        /// @nodoc
        const reverse            = 1 << 23;
    }
}

impl GDObjAttributes {
    #[inline(always)]
    /// Makes a default instance of this object
    pub fn new() -> Self {
        Self::default()
    }

    /// Serialises this object to a string
    pub fn get_property_str(&self) -> String {
        let fields = [
            (DONT_FADE, Self::dont_fade),
            (DONT_ENTER, Self::dont_enter),
            (NO_OBJECT_EFFECTS, Self::no_effects),
            (IS_GROUP_PARENT, Self::is_group_parent),
            (IS_AREA_PARENT, Self::is_area_parent),
            (DONT_BOOST_X, Self::dont_boost_x),
            (DONT_BOOST_Y, Self::dont_boost_y),
            (IS_HIGH_DETAIL, Self::high_detail),
            (NO_TOUCH, Self::no_touch),
            (PASSABLE, Self::passable),
            (HIDDEN, Self::hidden),
            (NONSTICK_X, Self::non_stick_x),
            (NONSTICK_Y, Self::non_stick_y),
            (EXTRA_STICKY, Self::extra_sticky),
            (HAS_EXTENDED_COLLISION, Self::extended_collision),
            (IS_ICE_BLOCK, Self::is_ice_block),
            (GRIP_SLOPE, Self::grip_slope),
            (NO_GLOW, Self::no_glow),
            (NO_PARTICLES, Self::no_particles),
            (SCALE_STICK, Self::scale_stick),
            (NO_AUDIO_SCALE, Self::no_audio_scale),
            (SINGLE_PLAYER_TOUCH, Self::single_ptouch),
            (CENTER_EFFECT, Self::center_effect),
            (REVERSES_GAMEPLAY, Self::reverse),
        ];
        let mut properties_str = String::with_capacity(6 * fields.len());

        for (id, flag) in fields {
            if self.contains(flag) {
                let _ = write!(properties_str, ",{id},1");
            }
        }
        properties_str
    }
}

fn serialise_fields<T: PartialEq + Display>(fields: &[(&str, T, T)], buf: &mut String) {
    for (id, field, default) in fields {
        if field != default {
            let _ = write!(buf, ",{id},{field}");
        }
    }
}

/// Function is separate from [`serialise_fields`] to optimise boolean serialising
fn serialise_bools(fields: &[(&str, bool)], buf: &mut String) {
    for (id, field) in fields {
        if *field {
            let _ = write!(buf, ",{id},1");
        }
    }
}