1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
mod decoder;
mod encoder;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use bitflags::bitflags;
use derive_more::derive::{Display, Error, From};
use glam::UVec2;
use num_enum::{IntoPrimitive, TryFromPrimitive, TryFromPrimitiveError};
use serde::{Deserialize, Serialize};
pub use decoder::{DecodeError, Decoder};
pub use encoder::{EncodeError, Encoder};
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct ScriptState {
pub program_counter: u32,
/// - 0x13 (19u32) is saved after a cutscene (which could also be just
/// before a battle would start).
/// - 0x3A (58u32) is saved at the victory screen.
pub unknown0: u32,
/// The base address in the script where the campaign should start executing
/// from. In the English version of the game, this is `0x4C3C48`. In the
/// German version of the game, this is `0x4C3D90`. Combine with
/// `execution_offset_index
/// * 4` to get the address to start executing from.
pub base_execution_address: u32,
/// In the English version of the game, this is `0x4CCD28`. In the German
/// version of the game, this is `0x4CCE70`.
pub unknown_address: u32,
/// Initialized to 0 on init.
pub local_variable: u32,
/// Initialized to 1 on init.
pub unknown1: u32,
/// Initialized to 20 on init.
pub stack_pointer: u32,
unknown2: Vec<u8>,
unknown2_hex: Vec<String>, // TODO: Remove, debug only.
unknown2_as_u32s: Vec<u32>, // TODO: Remove, debug only.
/// The offset index to add to the base execution address to get the address
/// to start executing from. To account for alignment, multiply this value
/// by 4 before adding it to the base address.
pub execution_offset_index: u32,
pub unknown3: u32,
/// Initialized to 0 on init.
pub nest_if: u32,
/// Initialized to 0 on init.
pub nest_gosub: u32,
/// Initialized to 0 on init.
pub nest_loop: u32,
pub unknown4: u32,
/// Initialized to the current tick count on init, which is the number of
/// milliseconds since the operating system started. The purpose of this is
/// not yet known.
pub elapsed_millis: u32,
/// Initialized to 0 on init.
pub unknown5: u32,
/// Initialized to 0 on init.
pub unknown6: u32,
unknown7: Vec<u8>,
unknown7_hex: Vec<String>, // TODO: Remove, debug only.
unknown7_as_u32s: Vec<u32>, // TODO: Remove, debug only.
}
impl ScriptState {
/// Returns the address to start executing from.
pub fn execution_address(&self) -> u32 {
self.base_execution_address + self.execution_offset_index * 4
}
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct ScriptVariables {
/// Bogenhafen mission completed. This does not mean the mission was won or
/// lost, just that it was completed.
///
/// This is variable 0 in the WHMTG script.
pub bogenhafen_mission_completed: bool,
/// Attacked either the mission to attack the Goblin camp or the mission to
/// help Ragnar fight the trolls.
///
/// This is variable 1 in the WHMTG script.
pub goblin_camp_or_ragnar_troll_mission_accepted: bool,
/// Accepted the mission to attack the Goblin camp together with Munz.
///
/// This is variable 2 in the WHMTG script.
pub goblin_camp_mission_accepted: bool,
/// Accepted the mission to help Ragnar fight the trolls.
///
/// This is variable 3 in the WHMTG script.
pub ragnar_troll_mission_accepted: bool,
/// Accepted either the mission to attack the Greenskins near Vingtienne or
/// the mission to help Treeman in Loren Lake.
///
/// This is variable 4 in the WHMTG script.
pub vingtienne_or_treeman_mission_accepted: bool,
/// Accepted the mission to attack the Greenskins near Vingtienne.
///
/// This is variable 5 in the WHMTG script.
pub vingtienne_mission_accepted: bool,
/// Accepted the mission to help Treeman in Loren Lake.
///
/// This is variable 6 in the WHMTG script.
pub treeman_mission_accepted: bool,
/// Manfred von Carstein defeated.
///
/// This is variable 7 in the WHMTG script.
pub count_carstein_destroyed: bool,
/// Hand of Nagash defeated.
///
/// This is variable 8 in the WHMTG script.
pub hand_of_nagash_destroyed: bool,
/// Black Grail defeated.
///
/// This is variable 9 in the WHMTG script.
pub black_grail_destroyed: bool,
/// Set to true if the enemy was victorious in the Bogenhafen mission.
///
/// This is variable 10 in the WHMTG script.
pub bogenhafen_mission_failed: bool,
/// Helmgart mission played.
///
/// This is variable 11 in the WHMTG script.
pub helmgart_mission_victorious: bool,
/// Helped Ragnar defeat the trolls.
///
/// This is variable 12 in the WHMTG script.
pub troll_country_mission_victorious: bool,
/// Talked with King Orion (Woodelf King).
///
/// This is variable 13 in the WHMTG script.
pub loren_king_met: bool,
/// Helped Azkuz move through the Axebite Pass. This does not mean the
/// mission was won or lost, just that it was completed.
///
/// This is variable 14 in the WHMTG script.
pub axebite_mission_completed: bool,
/// The Wood Elf Glade Guards are destroyed.
///
/// This is variable 15 in the WHMTG script.
pub wood_elf_glade_guards_destroyed: bool,
/// The Imperial Steam Tank is destroyed.
///
/// This is variable 16 in the WHMTG script.
pub imperial_steam_tank_destroyed: bool,
/// This is variable 17 in the WHMTG script.
pub unknown1: u32,
/// This is variable 18 in the WHMTG script.
pub unknown2: u32,
/// This is variable 19 in the WHMTG script.
pub unknown3: u32,
/// This is variable 20 in the WHMTG script.
pub unknown4: u32,
/// Debrief or meet action selected by the player.
///
/// When the player saves the game while on the debrief screen, this is set
/// to 1 which corresponds to the "Save or Load" action from the debrief
/// screen.
///
/// When the player saves the game while on the meet screen, this is set to
/// 0 which corresponds to the "Save or Load" action from the meet screen.
///
/// This is variable 21 in the WHMTG script.
pub debrief_or_meet_action: u32,
/// Indicates if the player selected to either continue campaign or replay
/// meet. Set to true when player selects either "Continue Campaign" or
/// "Replay Meet" in a meeting.
///
/// This is variable 22 in the WHMTG script.
pub meet_continue_or_replay_selected: bool,
/// Indicates the player's decision at choice points in meets.
///
/// - `true` = Player chose the "positive/heroic" option (first choice).
/// - `false` = Player chose the "cautious/pragmatic" option (second
/// choice).
///
/// Note: The value is inverted from the choice index. For example, for the
/// "Stay and fight" and "Continue to Helmgart" choices, the value is `true`
/// for the first choice and `false` for the second choice.
///
/// This is variable 23 in the WHMTG script.
pub heroic_choice_made: bool,
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct SaveGameHeader {
/// The name displayed when loading the save game.
pub display_name: String,
/// The original game writes over the existing value with the new value but
/// the old bytes are not cleared first. This field is used to store the
/// residual bytes, if there are any. If it's `None` then there are no
/// residual bytes / all bytes are zero after the null-terminated string. If
/// it's `Some`, then it contains the residual bytes, up to, but not
/// including, the last nul-terminated string.
display_name_residual_bytes: Option<Vec<u8>>,
/// The name suggested when saving the game.
pub suggested_display_name: String,
/// The original game writes over the existing value with the new value but
/// the old bytes are not cleared first. This field is used to store the
/// residual bytes, if there are any. If it's `None` then there are no
/// residual bytes / all bytes are zero after the null-terminated string. If
/// it's `Some`, then it contains the residual bytes, up to, but not
/// including, the last nul-terminated string.
suggested_display_name_residual_bytes: Option<Vec<u8>>,
pub unknown_bool1: bool,
pub unknown_bool2: bool,
script_state_hex: Vec<String>, // TODO: Remove, debug only.
script_state_as_u32s: Vec<u32>, // TODO: Remove, debug only.
/// The script state of the save game. Used by the WHMTG scripting engine to
/// run the next part of the campaign.
pub script_state: ScriptState,
/// The script variables set throughout the campaign. Useful for making
/// decisions in the campaign.
pub script_variables: ScriptVariables,
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct MeetAnimatedSprite {
/// Whether the animated sprite is enabled.
pub enabled: bool,
unknown1: u32,
/// The position the top-left corner of the animated sprite should be placed
/// on the screen.
pub position: UVec2,
/// The path to the sprite sheet file, e.g., "[SPRITES]\m_empbi1.spr".
pub path: String,
unknown2: u32,
unknown3: u32,
/// The number of sprites in the sprite sheet / the number of frames in the
/// animated sprite.
pub sprite_count: u32,
/// The duration, in milliseconds, to display each frame of the animated
/// sprite.
pub frame_duration_millis: u32,
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct Objective {
pub unknown1: i32,
/// The ID of the objective.
///
/// Interesting IDs:
///
/// - 1: Indicates if the enemy was victorious. When `result` is 1, the
/// enemy won the battle. When `result` is 0, the player won the battle.
pub id: i32,
pub unknown2: i32,
/// The result of the objective.
pub result: i32,
pub unknown4: i32,
pub unknown5: i32,
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct SaveGameFooter {
unknown1: Vec<u8>,
unknown1_as_u16s: Vec<u16>, // TODO: Remove, debug only.
unknown1_as_u32s: Vec<u32>, // TODO: Remove, debug only.
pub objectives: Vec<Objective>,
/// A history of path indices the player has traveled, accumulated across
/// travel map screens to display the full journey, e.g., from Altdorf, over
/// the Black Mountains, through Teufelbad and to the current location.
/// Reset by game scripts on events like map changes or new chapters.
pub travel_path_history: Vec<i32>,
/// The path to the background image file, e.g., "[PICTURES]\m_empn.bmp".
pub background_image_path: Option<String>,
/// The original game writes over the existing value with the new value but
/// the old bytes are not cleared first. This field is used to store the
/// residual bytes, if there are any. If it's `None` then there are no
/// residual bytes / all bytes are zero after the null-terminated string. If
/// it's `Some`, then it contains the residual bytes, up to, but not
/// including, the last nul-terminated string.
background_image_path_residual_bytes: Option<Vec<u8>>,
/// Always 0.
unknown2: u32,
/// The index into the list of battle debrief messages found in ENGREL.EXE
/// for the case where the player wins the battle.
///
/// This is used to display a message to the player after winning a battle.
pub victory_message_index: u32,
/// The index into the list of battle debrief messages found in ENGREL.EXE
/// for the case where the player loses the battle.
///
/// This is used to display a message to the player after losing a battle.
pub defeat_message_index: u32,
/// The seed value for the random number generator used by the save game.
///
/// The seed is persisted in save games to ensure deterministic behavior
/// when loading and replaying from a saved state.
pub rng_seed: u32,
/// A list of aniamted sprites used on the meet screens shown in between
/// battles.
pub meet_animated_sprites: Vec<MeetAnimatedSprite>,
unknown3: Vec<u8>,
unknown3_as_u16s: Vec<u16>, // TODO: Remove, debug only.
unknown3_as_u32s: Vec<u32>, // TODO: Remove, debug only.
hex: Vec<String>, // TODO: Remove, debug only.
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct Army {
/// An optional save game header if the army is a save game.
pub save_game_header: Option<SaveGameHeader>,
/// An optional save game footer if the army is a save game.
pub save_game_footer: Option<SaveGameFooter>,
/// The army's race.
///
/// This is used in multiplayer mode to group armies by race.
pub race: ArmyRace,
unknown1: [u8; 3], // always seems to be 0, could be padding
/// The index of the name to use when army name is empty.
///
/// This is used to display the army name in multiplayer mode when no army
/// name is set.
pub default_name_index: u16,
/// The name of the army. Displayed in multiplayer mode.
pub name: String,
/// There are some bytes after the null-terminated string. Not sure what
/// they are for.
name_remainder: Vec<u8>,
pub small_banners_path: String,
/// There are some bytes after the null-terminated string. Not sure what
/// they are for.
small_banners_path_remainder: Vec<u8>,
pub disabled_small_banners_path: String,
/// There are some bytes after the null-terminated string. Not sure what
/// they are for.
disabled_small_banners_path_remainder: Vec<u8>,
disabled_small_banners_path_remainder_as_u16s: Vec<u16>, // TODO: Remove, debug only.
disabled_small_banners_path_remainder_as_u32s: Vec<u32>, // TODO: Remove, debug only.
pub large_banners_path: String,
/// There are some bytes after the null-terminated string. Not sure what
/// they are for.
large_banners_path_remainder: Vec<u8>,
large_banners_path_remainder_as_u16s: Vec<u16>, // TODO: Remove, debug only.
large_banners_path_remainder_as_u32s: Vec<u32>, // TODO: Remove, debug only.
/// The amount of gold captured from treasures and earned in the last
/// battle.
pub last_battle_captured_gold: u16,
/// The total amount of gold available to the army for buying new units and
/// armor.
pub total_gold: u16,
/// A list of magic items in the army's inventory.
///
/// Each magic item is an index into the list of magic items. A value of 1
/// means the Grudgebringer Sword is equipped in that slot. A value of 0
/// means the army does not have anything in that slot.
pub magic_items: Vec<u8>,
unknown3: Vec<u8>,
pub regiments: Vec<Regiment>,
}
impl Army {
/// Returns the total amount of gold earned by the army in the last battle.
///
/// The amount of gold earned is calculated by summing the experience of
/// each regiment in the army and multiplying it by 1.5.
///
/// The total amount is rounded down to the nearest integer.
pub fn last_battle_earned_gold(&self) -> u32 {
self.regiments
.iter()
.map(|regiment| regiment.last_battle_stats.experience as f32 * 1.5)
.sum::<f32>() as u32
}
/// Returns the total amount of gold captured by the army in the last
/// battle.
pub fn last_battle_captured_gold(&self) -> u32 {
self.regiments
.iter()
.map(|regiment| regiment.last_battle_captured_gold)
.sum::<u16>() as u32
}
/// Returns true if the army has any magic items in its inventory.
pub fn any_magic_items(&self) -> bool {
self.magic_items.iter().any(|&item| item != 0)
}
/// Returns a list of all magic items in the army's inventory.
pub fn all_magic_items(&self) -> Vec<u8> {
self.magic_items
.iter()
.filter(|&&item| item != 0)
.copied()
.collect()
}
}
bitflags! {
#[repr(transparent)]
#[derive(Clone, Copy, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(opaque), reflect(Default, Deserialize, Hash, PartialEq, Serialize))]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct ArmyRace: u8 {
/// Empire army.
const EMPIRE = 0;
/// Multiplayer army.
const MULTIPLAYER = 1 << 0;
/// Greenskins army.
const GREENSKINS = 1 << 1;
/// Undead army.
const UNDEAD = 1 << 2;
}
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct Regiment {
pub flags: RegimentFlags,
unknown1: [u8; 2],
pub id: u32,
pub mage_class: MageClass,
/// The regiment's maximum level of armor.
pub max_armor: u8,
pub cost: u16,
/// The index into the list of sprite sheet file names found in ENGREL.EXE
/// for the regiment's banner.
pub banner_sprite_sheet_index: u16,
unknown3: [u8; 2],
pub attributes: RegimentAttributes,
/// The profile of the regiment's rank and file units.
pub unit_profile: UnitProfile,
unknown4: u8,
/// The profile of the regiment's leader unit.
///
/// Some of the fields are not used for leader units.
pub leader_profile: UnitProfile,
/// The leader's 3D head ID.
pub leader_head_id: i16,
/// The stats of the regiment's last battle.
pub last_battle_stats: LastBattleStats,
/// A number that represents the regiment's total experience.
///
/// It is a number between 0 and 6000. If experience is <1000 then the
/// regiment has a threat level of 1. If experience >=1000 and <3000 then
/// the regiment has a threat level of 2. If experience >= 3000 and <6000
/// then the regiment has a threat level of 3. If experience >= 6000 then
/// the regiment has a threat level of 4.
pub total_experience: u16,
pub duplicate_id: u8,
/// The regiment's minimum or base level of armor.
///
/// This is displayed as the gold shields in the troop roster.
pub min_armor: u8,
/// The spell book that is equipped to the regiment. A spell book is one of
/// the magic items.
///
/// This is an index into the list of magic items. In the original game, the
/// value is either 22, 23, 24, 25 or 65535.
///
/// A value of 22 means the Bright Book is equipped. A value of 23 means the
/// Ice Book is equipped. A value of 65535 means the regiment does not have
/// a spell book slot. Only mages can equip spell books.
pub spell_book: SpellBook,
/// A list of magic items that are equipped to the regiment.
///
/// Each magic item is an index into the list of magic items. A value of 1
/// means the Grudgebringer Sword is equipped in that slot. A value of 65535
/// means the regiment does not have anything equipped in that slot.
pub magic_items: [u16; 3],
/// A list of spells that the regiment can cast.
///
/// Each spell is an index into the list of magic items unless the value is
/// 0 or 65535. From testing changes to `SPARE9MR.ARM` in the original game,
/// it doesn't seem like this can be changed to a specific set of spells.
/// The changes seem to be ignored. It's possible that a CTL file overrides
/// this value, or for player regiments, the threat level determines the
/// number of spells to provision.
///
/// See `GAMEDATA/1PBAT/B1_04/B104NME.ARM` for an example of all 0s in the
/// spells field.
///
/// See `GAMEDATA/1PBAT/B3_08/B308MRC.ARM` and
/// `GAMEDATA/1PBAT/B3_08/B308NME.ARM` for an example with non-zero values.
pub spells: [u16; 5],
/// The amount of gold captured by the regiment in the last battle. The
/// total amount of gold captured by the army can be calculated by summing
/// the gold captured by each regiment.
pub last_battle_captured_gold: u16,
pub purchased_armor: u8,
pub max_purchasable_armor: u8,
pub repurchased_unit_count: u8,
pub max_purchasable_unit_count: u8,
pub book_profile_index: u32,
}
impl Regiment {
/// Returns the display name of the regiment.
///
/// May be empty. The display name index is the preferred way to get the
/// display name. This is so that the display name can be localized.
#[inline(always)]
pub fn display_name(&self) -> &str {
self.unit_profile.display_name.as_str()
}
/// Returns the display name index of the regiment.
///
/// The display name index is used to look up the display name string in the
/// list of display names found in ENGREL.EXE. This allows the display name
/// to be localized.
///
/// This is an index into the list of display names found in ENGREL.EXE.
#[inline(always)]
pub fn display_name_index(&self) -> u16 {
self.unit_profile.display_name_index
}
/// Marks the regiment as active.
pub fn mark_active(&mut self) {
self.flags.insert(RegimentFlags::ACTIVE);
}
/// Forces the regiment to be deployed.
pub fn mark_must_deploy(&mut self) {
self.flags.insert(RegimentFlags::MUST_DEPLOY);
}
/// Marks the regiment as temporary.
pub fn mark_temporary(&mut self) {
self.flags.insert(RegimentFlags::TEMPORARY);
}
/// Returns `true` if the regiment must be deployed.
pub fn must_deploy(&self) -> bool {
self.flags.contains(RegimentFlags::MUST_DEPLOY)
}
/// Returns `true` if the regiment is active.
pub fn is_active(&self) -> bool {
self.flags.contains(RegimentFlags::ACTIVE)
}
/// Returns `true` if the regiment is temporary.
pub fn is_temporary(&self) -> bool {
self.flags.contains(RegimentFlags::TEMPORARY)
}
/// Returns `true` if the regiment is deployable.
pub fn is_deployable(&self) -> bool {
self.flags.contains(RegimentFlags::ACTIVE)
&& !self.flags.contains(RegimentFlags::NON_DEPLOYABLE)
}
/// Returns the number of units in the regiment that are alive.
#[inline(always)]
pub fn alive_unit_count(&self) -> u8 {
self.unit_profile.alive_unit_count
}
/// Returns the maximum number of units allowed in the regiment.
#[inline(always)]
pub fn max_unit_count(&self) -> u8 {
self.unit_profile.max_unit_count
}
/// Returns the rank count.
#[inline(always)]
pub fn rank_count(&self) -> u8 {
self.unit_profile.rank_count
}
/// Returns `true` if the regiment is a mage.
#[inline(always)]
pub fn is_mage(&self) -> bool {
self.mage_class != MageClass::None
}
/// Returns `true` if the regiment has any magic items equipped.
pub fn any_magic_items(&self) -> bool {
self.magic_items.iter().any(|&item| item != 65535)
}
/// Returns a list of all magic items equipped to the regiment.
pub fn all_magic_items(&self) -> Vec<u16> {
self.magic_items
.iter()
.filter(|&&item| item != 65535)
.copied()
.collect()
}
/// Returns the projectile class of the regiment.
#[inline(always)]
pub fn projectile_class(&self) -> ProjectileClass {
self.leader_profile.projectile_class
}
}
bitflags! {
#[repr(transparent)]
#[derive(Clone, Copy, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(opaque), reflect(Default, Deserialize, Hash, PartialEq, Serialize))]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct RegimentFlags: u16 {
/// No flags are set. This is the default state.
const NONE = 0;
/// Set if the regiment is active. Active regiments can be deployed to
/// the battlefield. This is used when deciding if the regiment should
/// be shown in the troop roster, or if the regiment is available in the
/// army reserve. Also known as "available for hire".
const ACTIVE = 1 << 0;
/// Set if the regiment is deployed or was deployed in the last battle.
///
/// This flag's meaning is context-dependent.
///
/// During a battle, it indicates that the regiment is currently
/// deployed to the battlefield. If a regiment is not deployed, then it
/// remains in the army's reserve.
///
/// Outside of a battle, it indicates that the regiment was deployed in
/// the last battle. Among other things, this is used when deciding if
/// the regiment should be shown on the debrief screen battle roster.
const DEPLOYED = 1 << 1;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_2 = 1 << 2;
/// Set if the regiment must be deployed to the battlefield. Regiments
/// that must be deployed cannot be taken off the battlefield. The
/// player is not allowed to put them in the army reserve.
const MUST_DEPLOY = 1 << 3;
/// TODO: Not sure what this flag is yet. This is used by almost every
/// regiment across .ARM and save games. Removed this from a regiment
/// and they battled fine and then the flag stayed off after the battle
/// was finished (i.e., it wasn't reinstated after the battle).
const UNKNOWN_REGIMENT_FLAG_4 = 1 << 4;
/// Set if the regiment is heavily damaged. Heavily damaged regiments
/// result in the leader's portrait being shown in the campaign with
/// blood on their face.
///
/// This flag is cleared when entering the travel map, likely to
/// represent that time has passed during the journey and the regiment
/// is no longer visibly heavily damaged, even if it may still be
/// under-strength.
const HEAVILY_DAMAGED = 1 << 5;
/// Set if the regiment is non-deployable. Non-deployable regiments
/// cannot be deployed to the battlefield and do not appear in the army
/// reserve. This overrides the [`RegimentFlags::ACTIVE`] flag when
/// deciding if the regiment can be deployed. This is used for cases
/// such as underground battles where artillery regiments like cannons
/// and mortars are not available (you can imagine they stay above
/// ground back at base). Regiments with the [`RegimentFlags::ACTIVE`]
/// flag as well as the [`RegimentFlags::NON_DEPLOYABLE`] flag are shown
/// in the troop roster but cannot be deployed to the battlefield.
const NON_DEPLOYABLE = 1 << 6;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_7 = 1 << 7;
/// Set if the regiment is temporarily in the army. In the troop roster,
/// temporary regiments are shown with a green arrow next to the banner.
const TEMPORARY = 1 << 8;
/// Set if the regiment has departed.
const DEPARTED = 1 << 9;
/// Set when the regiment is purchased during multiplayer army editing.
///
/// Displays a red frame around the regiment's banner to highlight the
/// new purchase. Cleared when the army is saved. Never used in campaign.
const NEWLY_PURCHASED = 1 << 10;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_11 = 1 << 11;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_12 = 1 << 12;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_13 = 1 << 13;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_14 = 1 << 14;
/// The flag seems to be unused in any .ARM or save games. It's possible
/// it's only set during battle.
const UNKNOWN_REGIMENT_FLAG_15 = 1 << 15;
}
}
#[repr(u8)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum MageClass {
#[default]
None = 0,
BaseMage = 2,
OrcAdept = 3,
AdeptMage = 4,
MasterMage = 5,
}
#[repr(u8)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum RegimentAlignment {
#[default]
Good = 0,
Neutral = 64,
Evil = 128,
}
#[repr(u8)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum RegimentClass {
#[default]
None = 0,
HumanInfantry = 8,
WoodElfInfantry = 9,
DwarfInfantry = 10,
NightGoblinInfantry = 11,
OrcInfantry = 12,
UndeadInfantry = 13,
Townsfolk = 14,
Ogre1 = 15,
HumanCavalry = 16,
OrcCavalry = 20,
UndeadCavalry = 21,
HumanArcher = 24,
WoodElfArcher = 25,
NightGoblinArcher = 27,
OrcArcher = 28,
SkeletonArcher = 29,
HumanArtillery = 32,
OrcArtillery = 36,
UndeadArtillery = 37,
HumanMage = 40,
NightGoblinShaman = 43,
OrcShaman = 44,
EvilMage = 45,
DreadKing = 53,
Monster = 55,
UndeadChariot = 61,
Fanatic = 67,
Ogre2 = 71,
}
impl RegimentClass {
/// The mask used to extract regiment kind (removes race bits).
const KIND_MASK: u8 = 0xF8;
/// Get the regiment kind (removes race information from the class).
pub fn kind(&self) -> RegimentKind {
RegimentKind::try_from(Into::<u8>::into(*self) & Self::KIND_MASK)
.unwrap_or(RegimentKind::Unknown)
}
pub fn is_human(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::Human)
}
pub fn is_wood_elf(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::WoodElf)
}
pub fn is_dwarf(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::Dwarf)
}
pub fn is_night_goblin(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::NightGoblin)
}
pub fn is_orc(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::Orc)
}
pub fn is_undead(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::Undead)
}
pub fn is_townsfolk(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::Townsfolk)
}
pub fn is_ogre(&self) -> bool {
Into::<u8>::into(*self) & 0x07 == Into::<u8>::into(RegimentRace::Ogre)
}
}
#[repr(u8)]
#[derive(
Clone,
Copy,
Default,
Deserialize,
Eq,
Hash,
IntoPrimitive,
PartialEq,
Serialize,
TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Hash, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum RegimentKind {
#[default]
Unknown = 0,
Infantry = 8,
Cavalry = 16,
Archer = 24,
Artillery = 32,
Mage = 40,
/// Covers [`RegimentClass::DreadKing`], [`RegimentClass::Monster`].
Monster = 48,
Chariot = 56,
/// Covers [`RegimentClass::Fanatic`], [`RegimentClass::Ogre2`].
FanaticOgre2 = 64,
}
#[repr(u8)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum RegimentRace {
#[default]
Human,
WoodElf,
Dwarf,
NightGoblin,
Orc,
Undead,
Townsfolk,
Ogre,
}
#[repr(u8)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum MountClass {
#[default]
None,
Horse,
Boar,
}
bitflags! {
#[repr(transparent)]
#[derive(Clone, Copy, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(opaque), reflect(Default, Deserialize, Hash, PartialEq, Serialize))]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct RegimentAttributes: u32 {
const NONE = 0;
/// The regiment never retreats from a fight and the retreat button is
/// disabled.
const NEVER_ROUTS = 1 << 0;
const UNKNOWN_FLAG_2 = 1 << 1;
/// Fear increases the chance that the enemy retreats during combat.
const CAUSES_FEAR = 1 << 2;
/// Stronger version of CAUSES_FEAR.
const CAUSES_TERROR = 1 << 3;
/// Used by elves (unknown use).
const ELF_RACE = 1 << 4;
/// Used by goblins (unknown use).
const GOBLIN_RACE = 1 << 5;
const HATES_GREENSKINS = 1 << 6;
/// Regiment has the same movement speed on every terrain.
const NOT_SLOWED_BY_DIFFICULT_TERRAIN = 1 << 7;
/// Immune against any fear but can still rout.
const IMMUNE_TO_FEAR_CAN_BE_ROUTED = 1 << 8;
/// Slowly heals damage.
const REGENERATES_WOUNDS = 1 << 9;
/// Regiment never regroups when it is retreating.
const NEVER_RALLIES_OR_REGROUPS = 1 << 10;
/// Permanently follows retreating units.
const ALWAYS_PURSUES = 1 << 11;
/// Steam Tank flag. Can't enter close combat anymore.
const ENGINE_OF_WAR_RULE = 1 << 12;
/// Regiment becomes invulnerable.
const INDESTRUCTIBLE = 1 << 13;
const UNKNOWN_FLAG_15 = 1 << 14;
/// Regiment gets lots of additional damage in close combat (used by
/// skeletons).
const SUFFERS_ADDITIONAL_WOUNDS = 1 << 15;
/// If the regiment attacks an enemy using close or ranged combat, the
/// enemy receives additional fear.
const INFLICTING_CASUALTY_CAUSES_FEAR = 1 << 16;
/// Regiment is less resistant against fear.
const COWARDLY = 1 << 17;
/// Regiment dies during retreat.
const DESTROYED_IF_ROUTED = 1 << 18;
/// Suffers additional damage when attacked by fire.
const FLAMMABLE = 1 << 19;
/// Regiment can see everything that isn't blocked by mountains or other
/// obstacles.
const THREE_SIXTY_DEGREE_VISION = 1 << 20;
/// Regiment spawns fanatics if an enemy is near enough.
const SPAWNS_FANATICS = 1 << 21;
/// Used by wraiths (unknown use).
const WRAITH_RACE = 1 << 22;
/// Used by Treeman.
const GIANT = 1 << 23;
/// The goblins on the Trading Post map have this flag set (unknown
/// use).
const GOBLIN_FLAG_TRADING_POST_MAP_ONLY = 1 << 24;
/// Regiment is completely immune against magic attacks.
const IMPERVIOUS_TO_MAGIC = 1 << 25;
/// Same as NEVER_ROUTS but the retreat button is enabled (and ignored).
const NEVER_RETREATS = 1 << 26;
/// Regiment has no magic item slots. Magic items can still be assigned.
const NO_MAGIC_ITEM_SLOTS = 1 << 27;
/// Fanatics have this flag.
const FANATICS_FLAG = 1 << 28;
/// Penalty when fighting elves.
const FEARS_ELVES = 1 << 29;
}
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct LastBattleStats {
/// The number of units in the regiment that were killed in the last battle.
pub unit_killed_count: u16,
unknown1: u16,
/// The number of units the regiment killed in the last battle.
pub kill_count: u16,
/// The regiment's experience gained in the last battle.
pub experience: u16,
}
#[repr(u16)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum SpellBook {
#[default]
None = 65535,
BrightBook = 22,
IceBook = 23,
WaaaghBook = 24,
DarkBook = 25,
}
#[repr(u8)]
#[derive(
Clone, Copy, Default, Deserialize, IntoPrimitive, PartialEq, Serialize, TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum WeaponClass {
#[default]
None,
BasicHandWeapon,
TwoHandedWeapon,
Polearm,
Flail,
WightBlade,
}
#[repr(u8)]
#[derive(
Clone,
Copy,
Default,
Deserialize,
IntoPrimitive,
PartialEq,
PartialOrd,
Serialize,
TryFromPrimitive,
)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, PartialEq, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub enum ProjectileClass {
#[default]
None,
ShortBow = 7,
NormalBow = 8,
ElvenBow = 9,
Crossbow = 10,
Pistol = 11,
Cannon = 12,
Mortar = 13,
SteamTankCannon = 14,
RockLobber = 15,
Ballista = 16,
ScreamingSkullCatapult = 17,
}
#[derive(Debug, Display, Error, From)]
pub enum DecodeClassError {
#[error(ignore)]
InvalidKind(TryFromPrimitiveError<RegimentKind>),
#[error(ignore)]
InvalidRace(TryFromPrimitiveError<RegimentRace>),
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct UnitProfile {
/// The index into the list of sprite sheet file names found in ENGREL.EXE
/// for the unit's sprite sheet.
pub sprite_sheet_index: u16,
/// The display name of the regiment, e.g., "Grudgebringer Cavalry",
/// "Zombies #1", "Imperial Steam Tank".
///
/// May be empty. The display name index is the preferred way to get the
/// display name. This is so that the display name can be localized.
pub display_name: String,
/// The index into the list of display names found in ENGREL.EXE. This
/// allows the display name to be localized.
pub display_name_index: u16,
/// The regiment's alignment to good or evil.
///
/// - 0x00 (decimal 0) is good.
/// - 0x40 (decimal 64) is neutral.
/// - 0x80 (decimal 128) is evil.
pub alignment: RegimentAlignment,
/// The maximum number of units allowed in the regiment.
pub max_unit_count: u8,
/// The number of units currently alive in the regiment.
pub alive_unit_count: u8,
pub rank_count: u8,
unknown1: Vec<u8>,
pub stats: UnitStats,
pub mount_class: MountClass,
/// When you purchase armor, this goes up by 1 for each armor shield
/// purchased.
///
/// When you sell armor, this goes down by 1 for each armor shield sold.
///
/// If you have not purchased any armor, this is the same as `min_armor`.
///
/// This is displayed as the silver shields in the troop roster.
pub armor: u8,
pub weapon_class: WeaponClass,
pub class: RegimentClass,
/// A value from 0 to 31, inclusive, that indicates the regiment's threat
/// rating.
///
/// - 0-7: Threat rating 1
/// - 8-15: Threat rating 2
/// - 16-23: Threat rating 3
/// - 24-31: Threat rating 4
///
/// For example, the Dread King has the maximum value of 31 and a threat
/// rating of 4.
///
/// This is set in the `unit_profile`, but 0 in the `leader_profile`.
pub point_value: u8,
pub projectile_class: ProjectileClass,
unknown2: [u8; 4],
unknown2_a: u16, // TODO: Remove, debug only.
unknown2_b: u16, // TODO: Remove, debug only.
unknown2_as_u32: u32, // TODO: Remove, debug only.
}
#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Default, Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct UnitStats {
pub movement: u8,
pub weapon_skill: u8,
pub ballistic_skill: u8,
pub strength: u8,
pub toughness: u8,
pub wounds: u8,
pub initiative: u8,
pub attacks: u8,
pub leadership: u8,
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::{
ffi::{OsStr, OsString},
fs::File,
path::{Path, PathBuf},
};
#[test]
fn test_regiment_class_infantry() {
assert!(RegimentClass::HumanInfantry.kind() == RegimentKind::Infantry);
assert!(RegimentClass::HumanCavalry.kind() != RegimentKind::Infantry);
assert!(RegimentClass::HumanArcher.kind() != RegimentKind::Infantry);
assert!(RegimentClass::HumanArtillery.kind() != RegimentKind::Infantry);
assert!(RegimentClass::HumanMage.kind() != RegimentKind::Infantry);
assert!(RegimentClass::Monster.kind() != RegimentKind::Infantry);
assert!(RegimentClass::Fanatic.kind() != RegimentKind::Infantry);
}
#[test]
fn test_regiment_class_cavalry() {
assert!(RegimentClass::HumanInfantry.kind() != RegimentKind::Cavalry);
assert!(RegimentClass::HumanCavalry.kind() == RegimentKind::Cavalry);
assert!(RegimentClass::HumanArcher.kind() != RegimentKind::Cavalry);
assert!(RegimentClass::HumanArtillery.kind() != RegimentKind::Cavalry);
assert!(RegimentClass::HumanMage.kind() != RegimentKind::Cavalry);
assert!(RegimentClass::Monster.kind() != RegimentKind::Cavalry);
assert!(RegimentClass::Fanatic.kind() != RegimentKind::Cavalry);
}
#[test]
fn test_regiment_class_archer() {
assert!(RegimentClass::HumanInfantry.kind() != RegimentKind::Archer);
assert!(RegimentClass::HumanCavalry.kind() != RegimentKind::Archer);
assert!(RegimentClass::HumanArcher.kind() == RegimentKind::Archer);
assert!(RegimentClass::HumanArtillery.kind() != RegimentKind::Archer);
assert!(RegimentClass::HumanMage.kind() != RegimentKind::Archer);
assert!(RegimentClass::Monster.kind() != RegimentKind::Archer);
assert!(RegimentClass::Fanatic.kind() != RegimentKind::Archer);
}
#[test]
fn test_regiment_class_artillery() {
assert!(RegimentClass::HumanInfantry.kind() != RegimentKind::Artillery);
assert!(RegimentClass::HumanCavalry.kind() != RegimentKind::Artillery);
assert!(RegimentClass::HumanArcher.kind() != RegimentKind::Artillery);
assert!(RegimentClass::HumanArtillery.kind() == RegimentKind::Artillery);
assert!(RegimentClass::HumanMage.kind() != RegimentKind::Artillery);
assert!(RegimentClass::Monster.kind() != RegimentKind::Artillery);
assert!(RegimentClass::Fanatic.kind() != RegimentKind::Artillery);
}
#[test]
fn test_regiment_class_mage() {
assert!(RegimentClass::HumanInfantry.kind() != RegimentKind::Mage);
assert!(RegimentClass::HumanCavalry.kind() != RegimentKind::Mage);
assert!(RegimentClass::HumanArcher.kind() != RegimentKind::Mage);
assert!(RegimentClass::HumanArtillery.kind() != RegimentKind::Mage);
assert!(RegimentClass::HumanMage.kind() == RegimentKind::Mage);
assert!(RegimentClass::Monster.kind() != RegimentKind::Mage);
assert!(RegimentClass::Fanatic.kind() != RegimentKind::Mage);
}
#[test]
fn test_regiment_class_is_human() {
assert!(RegimentClass::HumanInfantry.is_human());
assert!(RegimentClass::HumanCavalry.is_human());
assert!(!RegimentClass::WoodElfInfantry.is_human());
}
#[test]
fn test_regiment_class_is_wood_elf() {
assert!(!RegimentClass::HumanInfantry.is_wood_elf());
assert!(!RegimentClass::HumanCavalry.is_wood_elf());
assert!(RegimentClass::WoodElfInfantry.is_wood_elf());
}
#[test]
fn test_regiment_class_is_dwarf() {
assert!(!RegimentClass::HumanInfantry.is_dwarf());
assert!(!RegimentClass::HumanCavalry.is_dwarf());
assert!(RegimentClass::DwarfInfantry.is_dwarf());
}
#[test]
fn test_regiment_class_is_night_goblin() {
assert!(!RegimentClass::HumanInfantry.is_night_goblin());
assert!(!RegimentClass::HumanCavalry.is_night_goblin());
assert!(RegimentClass::NightGoblinInfantry.is_night_goblin());
}
#[test]
fn test_regiment_class_is_orc() {
assert!(!RegimentClass::HumanInfantry.is_orc());
assert!(!RegimentClass::HumanCavalry.is_orc());
assert!(RegimentClass::OrcInfantry.is_orc());
}
#[test]
fn test_regiment_class_is_undead() {
assert!(!RegimentClass::HumanInfantry.is_undead());
assert!(!RegimentClass::HumanCavalry.is_undead());
assert!(RegimentClass::UndeadInfantry.is_undead());
}
#[test]
fn test_regiment_class_is_townsfolk() {
assert!(!RegimentClass::HumanInfantry.is_townsfolk());
assert!(!RegimentClass::HumanCavalry.is_townsfolk());
assert!(RegimentClass::Townsfolk.is_townsfolk());
}
fn roundtrip_test(original_bytes: &[u8], army: &Army) {
let mut encoded_bytes = Vec::new();
Encoder::new(&mut encoded_bytes).encode(army).unwrap();
let original_bytes = original_bytes
.chunks(16)
.map(|chunk| {
chunk
.iter()
.map(|b| format!("{b:02X}"))
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>()
.join("\n");
let encoded_bytes = encoded_bytes
.chunks(16)
.map(|chunk| {
chunk
.iter()
.map(|b| format!("{b:02X}"))
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>()
.join("\n");
assert_eq!(original_bytes, encoded_bytes);
}
#[test]
fn test_decode_plyr_alg() {
let d: PathBuf = [
std::env::var("DARKOMEN_PATH").unwrap().as_str(),
"DARKOMEN",
"GAMEDATA",
"1PARM",
"PLYR_ALG.ARM",
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
assert_eq!(a.regiments[0].unit_profile.display_name, ""); // not set
assert_eq!(a.regiments[0].unit_profile.display_name_index, 4);
assert_eq!(a.regiments[0].book_profile_index, 4);
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_b101mrc() {
let d: PathBuf = [
std::env::var("DARKOMEN_PATH").unwrap().as_str(),
"DARKOMEN",
"GAMEDATA",
"1PBAT",
"B1_01",
"B101MRC.ARM",
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
assert!(a.race.contains(ArmyRace::EMPIRE));
assert_eq!(a.small_banners_path, "[BOOKS]\\hshield.spr");
assert_eq!(a.disabled_small_banners_path, "[BOOKS]\\hgban.spr");
assert_eq!(a.large_banners_path, "[BOOKS]\\hlban.spr");
assert_eq!(a.regiments.len(), 4);
assert!(a.regiments[0].flags.contains(RegimentFlags::ACTIVE));
assert_eq!(a.regiments[0].id, 1);
assert_eq!(
a.regiments[0].unit_profile.display_name,
"Grudgebringer Cavalry"
);
assert_eq!(
a.regiments[0].unit_profile.class,
RegimentClass::HumanCavalry
);
assert_eq!(a.regiments[0].unit_profile.mount_class, MountClass::Horse);
assert_eq!(
a.regiments[0].leader_profile.display_name,
"Morgan Bernhardt"
);
assert_eq!(a.regiments[1].id, 2);
assert_eq!(
a.regiments[1].unit_profile.display_name,
"Grudgebringer Infantry"
);
assert_eq!(
a.regiments[1].unit_profile.class,
RegimentClass::HumanInfantry
);
assert_eq!(a.regiments[2].id, 3);
assert_eq!(
a.regiments[2].unit_profile.display_name,
"Grudgebringer Crossbows"
);
assert_eq!(
a.regiments[2].unit_profile.class,
RegimentClass::HumanArcher
);
assert_eq!(a.regiments[3].id, 4);
assert_eq!(
a.regiments[3].unit_profile.display_name,
"Grudgebringer Cannon"
);
assert_eq!(
a.regiments[3].unit_profile.class,
RegimentClass::HumanArtillery
);
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_b103mrc() {
let d: PathBuf = [
std::env::var("DARKOMEN_PATH").unwrap().as_str(),
"DARKOMEN",
"GAMEDATA",
"1PBAT",
"B1_03",
"B103MRC.ARM",
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
assert_eq!(a.regiments[4].unit_profile.display_name, "Bright Wizard");
assert_eq!(a.regiments[4].mage_class, MageClass::BaseMage);
assert_eq!(a.regiments[4].spell_book, SpellBook::BrightBook);
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_save_game_000() {
let d: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"src",
"army",
"testdata",
"save-games",
"darkomen.000", // http://en.dark-omen.org/downloads/view-details/4.-savegames/1.-original-campaigns/save-game-1-1-trading-post.html
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
let save_game_header = a.save_game_header.as_ref().unwrap();
assert_eq!(save_game_header.display_name, "Grenzgrafschaften - 1026gc");
assert_eq!(save_game_header.suggested_display_name, "Handelsposten 1");
assert_eq!(
save_game_header.script_state.base_execution_address,
0x4C3D90
);
let save_game_footer = a.save_game_footer.as_ref().unwrap();
assert_eq!(save_game_footer.travel_path_history, vec![]);
assert_eq!(save_game_footer.victory_message_index, 0);
assert_eq!(save_game_footer.defeat_message_index, 1);
assert_eq!(save_game_footer.rng_seed, 3011451320);
assert!(a.regiments[0].flags.contains(RegimentFlags::MUST_DEPLOY));
assert_eq!(a.regiments[0].last_battle_stats.kill_count, 10);
assert_eq!(a.regiments[0].last_battle_stats.experience, 46);
assert_eq!(a.regiments[0].total_experience, 46);
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_save_game_001() {
let d: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"src",
"army",
"testdata",
"save-games",
"darkomen.001", // http://en.dark-omen.org/downloads/view-details/4.-savegames/1.-original-campaigns/save-game-1-2-border-counties.html
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
let save_game_header = a.save_game_header.as_ref().unwrap();
assert_eq!(save_game_header.display_name, "Stadt Grissburg - 1410gc");
assert_eq!(
save_game_header.suggested_display_name,
"Prinzen der Grenze 2"
);
assert_eq!(
save_game_header.script_state.base_execution_address,
0x4C3D90
);
let save_game_footer = a.save_game_footer.as_ref().unwrap();
assert_eq!(save_game_footer.objectives.len(), 27);
assert_eq!(save_game_footer.objectives.first().unwrap().id, 26);
assert_eq!(save_game_footer.travel_path_history, vec![0, 1]);
assert_eq!(a.regiments[0].last_battle_stats.unit_killed_count, 3);
assert_eq!(a.regiments[0].last_battle_stats.kill_count, 19);
assert_eq!(a.regiments[0].last_battle_stats.experience, 175);
assert_eq!(a.regiments[0].total_experience, 221); // 46 from the first battle plus 175 from the battle prior to this save equals 221
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_save_game_en_000() {
let d: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"src",
"army",
"testdata",
"save-games",
"en",
"darkomen.000",
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
let save_game_header = a.save_game_header.as_ref().unwrap();
assert_eq!(save_game_header.display_name, "Trading Post 1 - 56gc");
assert_eq!(save_game_header.display_name_residual_bytes, None);
assert_eq!(save_game_header.suggested_display_name, "Trading Post 1");
assert_eq!(save_game_header.suggested_display_name_residual_bytes, None);
assert_eq!(
save_game_header.script_state.base_execution_address,
0x4C3C48
);
assert_eq!(save_game_header.script_state.execution_offset_index, 370);
assert_eq!(a.last_battle_earned_gold(), 316); // (48 + 89 + 74) * 1.5 = 316.5 = 316 (rounded down)
assert_eq!(a.last_battle_captured_gold(), 150);
assert!(a.regiments[0].flags.contains(RegimentFlags::MUST_DEPLOY));
assert_eq!(a.regiments[0].last_battle_stats.kill_count, 10);
assert_eq!(a.regiments[0].last_battle_stats.experience, 48);
assert_eq!(a.regiments[0].total_experience, 48);
assert_eq!(a.regiments[0].last_battle_captured_gold, 150);
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_save_game_en_003() {
let d: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"src",
"army",
"testdata",
"save-games",
"en",
"darkomen.003",
]
.iter()
.collect();
let original_bytes = std::fs::read(d.clone()).unwrap();
let file = File::open(d).unwrap();
let a = Decoder::new(file).decode().unwrap();
let save_game_header = a.save_game_header.as_ref().unwrap();
assert_eq!(save_game_header.display_name, "Grissburg 1 - 883gc");
assert_eq!(
String::from_utf8(
save_game_header
.display_name_residual_bytes
.as_ref()
.unwrap()
.to_vec()
)
.unwrap(),
"83gc" // residual from "Border Princes 2 - 883gc" in the previous save game
);
assert_eq!(save_game_header.suggested_display_name, "Grissburg 1");
assert_eq!(
String::from_utf8(
save_game_header
.suggested_display_name_residual_bytes
.as_ref()
.unwrap()
.to_vec()
)
.unwrap(),
"es 2" // residual from "Border Princes 2" in the previous save game
);
assert_eq!(
save_game_header.script_state.base_execution_address,
0x4C3C48
);
assert_eq!(save_game_header.script_state.execution_offset_index, 489);
roundtrip_test(&original_bytes, &a);
}
#[test]
fn test_decode_all() {
let d: PathBuf = [
std::env::var("DARKOMEN_PATH").unwrap().as_str(),
"DARKOMEN",
"GAMEDATA",
]
.iter()
.collect();
let root_output_dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "decoded", "armies"]
.iter()
.collect();
std::fs::create_dir_all(&root_output_dir).unwrap();
fn visit_dirs(dir: &Path, cb: &mut dyn FnMut(&Path)) {
println!("Reading dir {:?}", dir.display());
let mut paths = std::fs::read_dir(dir)
.unwrap()
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, std::io::Error>>()
.unwrap();
paths.sort();
for path in paths {
if path.is_dir() {
visit_dirs(&path, cb);
} else {
cb(&path);
}
}
}
visit_dirs(&d, &mut |path| {
let Some(ext) = path.extension() else {
return;
};
if !(ext.to_string_lossy().to_uppercase() == "ARM"
|| ext.to_string_lossy().to_uppercase() == "AUD"
|| ext.to_string_lossy().to_uppercase() == "ARE")
{
return;
}
println!("Decoding {:?}", path.file_name().unwrap());
let original_bytes = std::fs::read(path).unwrap();
let file = File::open(path).unwrap();
let army = Decoder::new(file).decode().unwrap();
roundtrip_test(&original_bytes, &army);
let parent_dir = path
.components()
.collect::<Vec<_>>()
.iter()
.rev()
.skip(1) // skip the file name
.take_while(|c| c.as_os_str() != "DARKOMEN")
.collect::<Vec<_>>()
.iter()
.rev()
.collect::<PathBuf>();
let output_dir = root_output_dir.join(parent_dir);
std::fs::create_dir_all(&output_dir).unwrap();
let output_path = append_ext("ron", output_dir.join(path.file_name().unwrap()));
let mut buffer = String::new();
ron::ser::to_writer_pretty(&mut buffer, &army, Default::default()).unwrap();
std::fs::write(output_path, buffer).unwrap();
});
}
#[test]
fn test_decode_all_save_games() {
let d: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"src",
"army",
"testdata",
"save-games",
]
.iter()
.collect();
let root_output_dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "decoded"].iter().collect();
std::fs::create_dir_all(&root_output_dir).unwrap();
fn visit_dirs(dir: &Path, cb: &mut dyn FnMut(&Path)) {
println!("Reading dir {:?}", dir.display());
let mut paths = std::fs::read_dir(dir)
.unwrap()
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, std::io::Error>>()
.unwrap();
paths.sort();
for path in paths {
if path.is_dir() {
visit_dirs(&path, cb);
} else {
cb(&path);
}
}
}
visit_dirs(&d, &mut |path| {
let Some(ext) = path.extension() else {
return;
};
// Skip unless the extension matches \d{3}.
let ext = ext.to_string_lossy();
if !(ext.len() == 3 && ext.chars().all(|c| c.is_ascii_digit())) {
println!("Skipping {:?}", path.file_name().unwrap());
return;
}
println!("Decoding {:?}", path.file_name().unwrap());
let original_bytes = std::fs::read(path).unwrap();
let file = File::open(path).unwrap();
let army = Decoder::new(file).decode().unwrap();
// Every same game should at least have the following objectives.
let save_game_footer = army.save_game_footer.as_ref().unwrap();
let required_objective_ids = [1, 3, 4, 7, 26];
for id in required_objective_ids {
assert!(
save_game_footer.objectives.iter().any(|obj| obj.id == id),
"Save game {:?} is missing required objective ID: {}",
path.file_name().unwrap(),
id
);
}
let parent_dir = path
.components()
.collect::<Vec<_>>()
.iter()
.rev()
.skip(1) // skip the file name
.take_while(|c| c.as_os_str() != "testdata")
.collect::<Vec<_>>()
.iter()
.rev()
.collect::<PathBuf>();
let output_dir = root_output_dir.join(parent_dir);
std::fs::create_dir_all(&output_dir).unwrap();
let output_path = append_ext("ron", output_dir.join(path.file_name().unwrap()));
let mut buffer = String::new();
ron::ser::to_writer_pretty(&mut buffer, &army, Default::default()).unwrap();
std::fs::write(output_path, buffer).unwrap();
roundtrip_test(&original_bytes, &army);
});
}
fn append_ext(ext: impl AsRef<OsStr>, path: PathBuf) -> PathBuf {
let mut os_string: OsString = path.into();
os_string.push(".");
os_string.push(ext.as_ref());
os_string.into()
}
}