darkomen 0.5.0

Warhammer: Dark Omen library and CLI in Rust
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
mod decoder;
mod encoder;

use core::f32::consts::*;

#[cfg(feature = "bevy_reflect")]
use bevy_reflect::prelude::*;
use bitflags::bitflags;
use glam::{IVec2, Vec2};
use serde::{Deserialize, Serialize};

pub use decoder::{DecodeError, Decoder};
pub use encoder::{EncodeError, Encoder};

/// The scale of the battle tabletop in the game world.
///
/// To get the world coordinates from the battle tabletop coordinates, divide
/// the battle tabletop coordinates by the scale.
pub const SCALE: f32 = 8.;

#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
    feature = "bevy_reflect",
    derive(Reflect),
    reflect(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct BattleTabletop {
    pub width: u32,
    pub height: u32,
    /// The name of the army 1 file, without the extension, e.g., `b101mrc`.
    ///
    /// This is used for the player army in singleplayer and player 1's army in
    /// multiplayer.
    pub army1_file_stem: String,
    /// The name of the army 2 file, without the extension, e.g., `b101nme`.
    ///
    /// This is used for the enemy army in singleplayer player 2's army in
    /// multiplayer.
    pub army2_file_stem: String,
    /// The name of the CTL file, without the extension, e.g., `B101`.
    pub ctl_file_stem: String,
    unknown1: String,
    unknown2: String,
    unknown3: Vec<i32>,
    /// A list of objectives relevant to the battle.
    pub objectives: Vec<Objective>,
    pub obstacles: Vec<Obstacle>,
    obstacles_unknown1: i32,
    pub regions: Vec<Region>,
    pub nodes: Vec<Node>,
}

/// Win condition: Eliminate all enemy regiments.
pub const ELIMINATE_ALL_ENEMIES_ID: i32 = 1;

/// Win condition: Kill specific enemy regiment (Dread King).
///
/// Used in B5_01 and B5_01B.
pub const KILL_DREAD_KING_ID: i32 = 2;

/// Lose condition: Critical regiment must not be captured/killed.
pub const CRITICAL_REGIMENT_LOSE_CONDITION_ID: i32 = 3;

/// Configuration: Spatial sound effects preset.
pub const SPATIAL_SOUND_EFFECT_PRESET_ID: i32 = 4;

/// Win condition: Kill specific enemy regiment (Mannfred von Carstein).
///
/// Used in B2_08.
pub const KILL_MANNFRED_VON_CARSTEIN_ID: i32 = 5;

/// Scripted event: Victory fireworks celebration.
///
/// Used in B1_05 for end-of-battle celebration.
pub const FIREWORKS_ID: i32 = 6;

/// Configuration: Initial regiment orientation/facing direction.
pub const INITIAL_REGIMENT_ORIENTATION_ID: i32 = 7;

/// Win condition: Kill specific enemy regiment (Hand of Nagash).
///
/// Used in B3_09.
pub const KILL_HAND_OF_NAGASH_ID: i32 = 8;

/// Win condition: Kill specific enemy regiment (Black Grail).
///
/// Used in B4_10.
pub const KILL_BLACK_GRAIL_ID: i32 = 9;

/// Post-battle metric: Gold collected by specified alignment.
///
/// Evaluates after battle completion, may affect victory rating or rewards.
///
/// Typically checks enemy alignment with threshold 0 (did enemies loot
/// anything?).
///
/// TODO: Confirm this objective, it's probably not right. Update docs below
/// too.
pub const GOLD_COLLECTION_METRIC_ID: i32 = 10;

/// Win condition: Inflict percentage casualties on enemy forces.
pub const ENEMY_CASUALTIES_ID: i32 = 11;

/// Lose condition: All player regiments eliminated.
pub const PLAYER_ELIMINATION_LOSE_CONDITION_ID: i32 = 26;

/// Battle objective/condition definition.
///
/// These represent various battle conditions, triggers, and configuration
/// parameters.
///
/// They can be:
///
/// - Win conditions (eliminate all enemies, collect treasure).
/// - Lose conditions (critical unit dies, all units eliminated).
/// - Configuration (initial facing, spatial sound effects).
/// - Scripted events (fireworks).
///
/// Each condition has an associated handler function that is called with
/// different trigger codes:
///
/// - 1: Initialize (called once at battle start).
/// - 2: Execute/trigger (called when condition should activate).
/// - 3: Evaluate (called periodically to check if condition is met).
/// - 4: Setup (called once for configuration conditions).
#[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 {
    /// The ID of the objective. This determines which handler function
    /// processes the objective and what the values mean.
    ///
    /// Used objective IDs:
    ///
    /// - 1: Eliminate all enemy regiments (win condition).
    ///   - `value1`: Unused.
    ///   - `value2`: Unused.
    ///
    /// - 2, 5, 8, 9: Kill specific enemy regiment (win condition).
    ///   - `value1`: Target regiment ID (e.g., 257 = "Hand of Nagash', 258 =
    ///     "Dread King", 260 = "Mannfred von Carstein").
    ///   - `value2`: Unused.
    ///   - Note: Different IDs used for different battles/regiments.
    ///
    /// - 3: Critical regiment lose condition.
    ///   - `value1`: Critical regiment ID (e.g., 1 = "Morgan Bernhardt").
    ///   - `value2`: Unused.
    ///   - If this regiment dies and is enemy-aligned: player wins.
    ///   - If this regiment dies and is player-aligned: player loses.
    ///
    /// - 4: Spatial sound effect configuration.
    ///   - `value1`: Indicates the preset of sound effect packets to load. The
    ///     battle can only spawn spatial sound effects from packets that are
    ///     part of this preset. Known presets:
    ///     - 1: "Forest River": Loads STREAM.H, TWITTER.H and WATAFALL.H.
    ///     - 2: "Grassland": Loads TWITTER.H.
    ///     - 3: "Evening Water": Loads NIGHT.H, STREAM.H and WATAFALL.H.
    ///     - 4: "Night": Loads NIGHT.H.
    ///     - 5: "Underground River": Loads CAVERN.H, STREAM.H and WATAFALL.H.
    ///     - 6: "Underground": Loads CAVERN.H.
    ///     - 7: "Mountain Stream": Loads MOUNTAIN.H, STREAM.H and WATAFALL.H.
    ///     - 8: "Mountain": Loads MOUNTAIN.H.
    ///   - `value2`: Unused.
    ///
    /// - 6: Victory fireworks.
    ///   - `value1`: Number of firework particle effects to spawn.
    ///   - `value2`: Starting node index for firework particle effect spawn
    ///     positions.
    ///   - Spawns particle effects at consecutive node positions.
    ///
    /// - 7: Initial regiment orientation.
    ///   - `value1`: Player regiment rotation (0-511, 0=north, 256=south).
    ///   - `value2`: Enemy regiment rotation (0-511, 0=north, 256=south).
    ///
    /// - 10: Gold collection metric (post-battle evaluation).
    ///   - `value1`: Alignment to check (0=Good, 64=Neutral, 128=Evil).
    ///   - `value2`: Gold threshold.
    ///   - Evaluates after battle: Checks if specified alignment collected more
    ///     gold than threshold.
    ///   - Includes both carried gold and uncollected ground items.
    ///   - Likely affects victory rating or determines if mission objectives
    ///     were "perfectly" completed.
    ///   - Example: Check if enemies looted any treasure (threshold=0) to
    ///     determine "flawless victory" status.
    ///
    /// - 11: Enemy casualties percentage (win condition).
    ///   - `value1`: Required casualty percentage (e.g., 75 = 75%).
    ///   - `value2`: Initial enemy count (calculated at battle start).
    ///
    /// - 12: Used in B5_01 and B5_01B but the handler does nothing so this was
    ///   likely unused/unfinished/cut content.
    ///
    /// - 26: Player elimination (lose condition).
    ///   - `value1`: Current alive player regiment count (updated during
    ///     battle).
    ///   - `value2`: Initial player regiment count.
    ///   - Always present in single-player battles.
    pub id: i32,

    /// First parameter value. Meaning depends on objective ID.
    pub value1: i32,

    /// Second parameter value. Meaning depends on objective ID.
    pub value2: i32,
}

impl Objective {
    /// Returns the rotation in radians. 0 is north (up), π/2 is east (right), π
    /// is south (down), and 3Ï€/2 is west (left).
    #[inline]
    pub fn rotation_radians(value: i32) -> f32 {
        (value as f32 / 512.0) * TAU
    }
}

#[derive(Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
    feature = "bevy_reflect",
    derive(Reflect),
    reflect(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "bevy_reflect", feature = "debug"), reflect(Debug))]
pub struct Obstacle {
    /// Obstacle flags.
    ///
    /// When the regiment obstacle is spawned, this is assigned a value of 9
    /// which corresponds to [ObstacleFlags::ACTIVE] |
    /// [ObstacleFlags::UNKNOWN_FLAG_1].
    pub flags: ObstacleFlags,
    /// The position of the obstacle in the horizontal plane.
    pub position: IVec2,
    /// The height of the obstacle's collision volume in battle tabletop
    /// coordinates. Combined with `radius`, this defines a vertical collision
    /// volume (likely a cylinder) that blocks movement and projectiles (e.g.,
    /// cannonballs).
    ///
    /// This value is also reused by some particle effect scripts to determine
    /// the range of random vertical positions when spawning particle effects
    /// within the obstacle's volume. Particles spawn at heights between
    /// `-height/2` and `+height/2` relative to the obstacle's base position.
    ///
    /// For example, large trees/forests in B1_04 have a height value of 128 (16
    /// in world space after dividing by [SCALE]), which blocks projectiles at
    /// tree-top height.
    ///
    /// When the regiment obstacle is spawned, this is assigned a value of 16.
    pub height: i32,
    /// When the regiment obstacle is spawned, this is assigned a value of 12.
    pub radius: u32,
    pub unknown: i32,
}

impl Obstacle {
    /// Returns the position of the obstacle in the horizontal plane, in world
    /// coordinates.
    #[inline]
    pub fn world_position(&self) -> Vec2 {
        Vec2::new(
            self.position.x as f32 / SCALE,
            self.position.y as f32 / SCALE,
        )
    }

    /// Returns the height of the obstacle in world space.
    #[inline]
    pub fn world_height(&self) -> f32 {
        self.height as f32 / SCALE
    }

    /// Returns the radius of the obstacle in world space.
    #[inline]
    pub fn world_radius(&self) -> f32 {
        self.radius as f32 / SCALE
    }
}

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 ObstacleFlags: u32 {
        const NONE = 0;
        const ACTIVE = 1 << 0;
        const BLOCKS_MOVEMENT = 1 << 1;
        const BLOCKS_PROJECTILES = 1 << 2;
        const UNKNOWN_FLAG_1 = 1 << 3;
        const UNKNOWN_FLAG_2 = 1 << 4;
        const UNKNOWN_FLAG_3 = 1 << 5;
        const UNKNOWN_FLAG_4 = 1 << 6;
        const UNKNOWN_FLAG_5 = 1 << 7;
        const UNKNOWN_FLAG_6 = 1 << 8;
        const UNKNOWN_FLAG_7 = 1 << 9;
        const UNKNOWN_FLAG_8 = 1 << 10;
        const UNKNOWN_FLAG_9 = 1 << 11;
        const UNKNOWN_FLAG_10 = 1 << 12;
        const UNKNOWN_FLAG_11 = 1 << 13;
        const UNKNOWN_FLAG_12 = 1 << 14;
        const UNKNOWN_FLAG_13 = 1 << 15;
    }
}

#[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 LineSegment {
    /// The start position of the line segment in the horizontal plane.
    pub start: IVec2,
    /// The end position of the line segment in the horizontal plane.
    pub end: IVec2,
}

impl LineSegment {
    /// Returns the start position of the line segment in world coordinates.
    #[inline]
    pub fn world_start(&self) -> Vec2 {
        Vec2::new(self.start.x as f32 / SCALE, self.start.y as f32 / SCALE)
    }

    /// Returns the end position of the line segment in world coordinates.
    #[inline]
    pub fn world_end(&self) -> Vec2 {
        Vec2::new(self.end.x as f32 / SCALE, self.end.y as f32 / SCALE)
    }

    /// Returns `true` if a point is on a line segment.
    fn is_point_on_line_segment(&self, point: &IVec2) -> bool {
        let crossproduct = (point.y - self.start.y) * (self.end.x - self.start.x)
            - (point.x - self.start.x) * (self.end.y - self.start.y);
        if crossproduct != 0 {
            return false;
        }

        let dotproduct = (point.x - self.start.x) * (self.end.x - self.start.x)
            + (point.y - self.start.y) * (self.end.y - self.start.y);
        if dotproduct < 0 {
            return false;
        }

        let squared_length_line =
            (self.end.x - self.start.x).pow(2) + (self.end.y - self.start.y).pow(2);
        if dotproduct > squared_length_line {
            return false;
        }

        true
    }

    /// Returns `true` if the ray from the point is intersecting with the line
    /// segment.
    fn is_ray_intersecting_segment(&self, point: &IVec2) -> bool {
        // Ensure the point is between the y-coordinates of the line segment's
        // endpoints.
        if point.y < self.start.y.min(self.end.y) || point.y > self.start.y.max(self.end.y) {
            return false;
        }

        // Avoid division by zero for horizontal line segments.
        if self.end.y == self.start.y {
            return false;
        }

        // Calculate the x-coordinate of the intersection.
        let intersection_x = self.start.x
            + (point.y - self.start.y) * (self.end.x - self.start.x) / (self.end.y - self.start.y);

        // The ray intersects if the intersection is to the right of the point.
        intersection_x >= point.x
    }
}

#[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 Region {
    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>>,
    pub flags: RegionFlags,
    /// The position of the region in the horizontal plane.
    pub position: IVec2,
    pub line_segments: Vec<LineSegment>,
}

impl Region {
    /// Returns `true` if the region is a deployment zone.
    pub fn is_deployment_zone(&self) -> bool {
        self.flags.contains(RegionFlags::ARMY1_DEPLOYMENT_ZONE)
            || self.flags.contains(RegionFlags::ARMY2_DEPLOYMENT_ZONE)
    }

    /// Returns `true` if the region is an army 1 deployment zone.
    pub fn is_army1_deployment_zone(&self) -> bool {
        self.flags.contains(RegionFlags::ARMY1_DEPLOYMENT_ZONE)
    }

    /// Returns `true` if the region is an army 2 deployment zone.
    pub fn is_army2_deployment_zone(&self) -> bool {
        self.flags.contains(RegionFlags::ARMY2_DEPLOYMENT_ZONE)
    }

    /// Returns `true` if the given point is contained within the region.
    pub fn is_point_contained(&self, point: IVec2) -> bool {
        let mut intersections = 0;
        for line in &self.line_segments {
            // Check if point is exactly on the line segment.
            if line.is_point_on_line_segment(&point) {
                return true;
            }

            // Check for intersections with the ray.
            if line.is_ray_intersecting_segment(&point) {
                intersections += 1;
            }
        }

        // Odd number of intersections means the point is inside.
        intersections % 2 == 1
    }

    /// Returns the position of the region in the horizontal plane, in world
    /// coordinates.
    #[inline]
    pub fn world_position(&self) -> Vec2 {
        Vec2::new(
            self.position.x as f32 / SCALE,
            self.position.y as f32 / SCALE,
        )
    }
}

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 RegionFlags: u32 {
        const NONE = 0;
        const ACTIVE = 1 << 0;
        const CLOSED = 1 << 1;
        const OPEN = 1 << 2;
        const UNKNOWN_FLAG_2 = 1 << 3;
        /// The region is used for holes in the battle's navmesh.
        const BOUNDARY_REVERSED = 1 << 4;
        /// The region is used for the outer geometry of the battle's navmesh.
        const BATTLE_BOUNDARY = 1 << 5;
        const UNKNOWN_FLAG_3 = 1 << 6;
        const BOUNDARY = 1 << 7;
        /// The region is a deployment zone for army 1. This is the player
        /// deployment zone in singleplayer and player 1's deployment zone in
        /// multiplayer.
        const ARMY1_DEPLOYMENT_ZONE = 1 << 8;
        /// The region is a deployment zone for army 2. This is player 2's
        /// deployment zone in multiplayer.
        const ARMY2_DEPLOYMENT_ZONE = 1 << 9;
        const VISIBLE_AREA = 1 << 10;
        const UNKNOWN_FLAG_4 = 1 << 11;
        const UNKNOWN_FLAG_5 = 1 << 12;
        const UNKNOWN_FLAG_6 = 1 << 13;
        const UNKNOWN_FLAG_7 = 1 << 14;
        const UNKNOWN_FLAG_8 = 1 << 15;
    }
}

#[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 Node {
    pub flags: NodeFlags,
    /// The position of the node in the horizontal plane.
    pub position: IVec2,
    pub radius: u32,
    /// The rotation of the node as a value between 0 (inclusive) and 512
    /// (exclusive). The rotation is in the range [0, 512) and corresponds to
    /// the angle in degrees. When looking at an aerial view of the map, 0 is
    /// north (up), 128 is east (right), 256 is south (down), and 384 is west
    /// (left).
    ///
    /// The rotation represents a 2D rotation around the horizontal plane.
    ///
    /// Note: This rotation value is used for enemy regiments to determine their
    /// initial facing direction. For player regiments, the initial facing
    /// direction is instead determined by the
    /// [`INITIAL_REGIMENT_ORIENTATION_ID`] battle condition. Use
    /// [`Node::rotation_radians`] or [`Node::rotation_degrees`] to convert the
    /// raw objective rotation values to radians or degrees.
    pub rotation: i32,
    pub node_id: u32,
    /// The ID of the regiment the node belongs to. Corresponds to the ID field
    /// of the regiment.
    pub regiment_id: u32,
    pub script_id: u32,
}

impl Node {
    /// Returns `true` if the node is a waypoint.
    #[inline]
    pub fn is_waypoint(&self) -> bool {
        self.flags.contains(NodeFlags::WAYPOINT)
    }

    /// Returns the position of the node in the horizontal plane in world
    /// coordinates.
    #[inline]
    pub fn world_position(&self) -> Vec2 {
        Vec2::new(
            self.position.x as f32 / SCALE,
            self.position.y as f32 / SCALE,
        )
    }

    /// Returns the radius of the node in world space.
    #[inline]
    pub fn world_radius(&self) -> f32 {
        self.radius as f32 / SCALE
    }

    /// Returns the rotation of the node in radians. 0 is north (up), π/2 is
    /// east (right), π is south (down), and 3π/2 is west (left).
    #[inline]
    pub fn rotation_radians(&self) -> f32 {
        (self.rotation as f32 / 512.0) * std::f32::consts::TAU
    }

    /// Returns the rotation of the node in degrees. 0 is north (up), 90 is east
    /// (right), 180 is south (down), and 270 is west (left).
    #[inline]
    pub fn rotation_degrees(&self) -> f32 {
        self.rotation_radians().to_degrees()
    }
}

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 NodeFlags: u32 {
        const NONE = 0;
        const ACTIVE = 1 << 0;
        const REGIMENT = 1 << 1;
        const WAYPOINT = 1 << 2;
        const UNKNOWN_FLAG_1 = 1 << 3;
        const UNKNOWN_FLAG_2 = 1 << 4;
        const UNKNOWN_FLAG_3 = 1 << 5;
        const UNKNOWN_FLAG_4 = 1 << 6;
        const UNKNOWN_FLAG_5 = 1 << 7;
        const UNKNOWN_FLAG_6 = 1 << 8;
        const UNKNOWN_FLAG_7 = 1 << 9;
        const UNKNOWN_FLAG_8 = 1 << 10;
        const UNKNOWN_FLAG_9 = 1 << 11;
        const UNKNOWN_FLAG_10 = 1 << 12;
        const UNKNOWN_FLAG_11 = 1 << 13;
        const UNKNOWN_FLAG_12 = 1 << 14;
        const UNKNOWN_FLAG_13 = 1 << 15;
    }
}

#[cfg(test)]
mod tests {
    use std::{
        ffi::{OsStr, OsString},
        fs::File,
        path::{Path, PathBuf},
    };

    use image::{DynamicImage, Rgba};
    use imageproc::{drawing::draw_hollow_rect_mut, rect::Rect};
    use pretty_assertions::assert_eq;

    use crate::project::{self, Project};

    use super::*;

    #[test]
    fn test_region_is_point_contained() {
        let region = Region {
            line_segments: vec![
                LineSegment {
                    start: IVec2::new(0, 0),
                    end: IVec2::new(10, 0),
                },
                LineSegment {
                    start: IVec2::new(10, 0),
                    end: IVec2::new(10, 10),
                },
                LineSegment {
                    start: IVec2::new(10, 10),
                    end: IVec2::new(0, 10),
                },
                LineSegment {
                    start: IVec2::new(0, 10),
                    end: IVec2::new(0, 0),
                },
            ],
            ..Default::default()
        };

        assert!(region.is_point_contained(IVec2::new(5, 5)));
        assert!(region.is_point_contained(IVec2::new(0, 0)));
        assert!(region.is_point_contained(IVec2::new(10, 0)));
        assert!(region.is_point_contained(IVec2::new(10, 10)));
        assert!(region.is_point_contained(IVec2::new(0, 10)));
        assert!(!region.is_point_contained(IVec2::new(11, 0)));
        assert!(!region.is_point_contained(IVec2::new(0, 11)));
        assert!(!region.is_point_contained(IVec2::new(11, 11)));
    }

    #[test]
    fn test_node_rotation() {
        let node = Node {
            rotation: 0, // north (up)
            ..Default::default()
        };
        assert_eq!(node.rotation_radians(), 0.);
        assert_eq!(node.rotation_degrees(), 0.);

        let node = Node {
            rotation: 256, // south (down)
            ..Default::default()
        };
        assert_eq!(node.rotation_radians(), std::f32::consts::PI);
        assert_eq!(node.rotation_degrees(), 180.);

        let node = Node {
            rotation: 128, // east (right)
            ..Default::default()
        };
        assert_eq!(node.rotation_radians(), std::f32::consts::PI / 2.);
        assert_eq!(node.rotation_degrees(), 90.);

        let node = Node {
            rotation: 384, // west (left)
            ..Default::default()
        };
        assert_eq!(node.rotation_radians(), std::f32::consts::PI * 1.5);
        assert_eq!(node.rotation_degrees(), 270.);
    }

    fn roundtrip_test(original_bytes: &[u8], b: &BattleTabletop) {
        let mut encoded_bytes = Vec::new();
        Encoder::new(&mut encoded_bytes).encode(b).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_b1_01() {
        let d: PathBuf = [
            std::env::var("DARKOMEN_PATH").unwrap().as_str(),
            "DARKOMEN",
            "GAMEDATA",
            "1PBAT",
            "B1_01",
            "B1_01.BTB",
        ]
        .iter()
        .collect();

        let original_bytes = std::fs::read(d.clone()).unwrap();
        let file = File::open(d).unwrap();
        let b = Decoder::new(file).decode().unwrap();

        assert_eq!(b.width, 1440);
        assert_eq!(b.height, 1600);
        assert_eq!(b.army1_file_stem, "B101mrc");
        assert_eq!(b.army2_file_stem, "B101nme");
        assert_eq!(b.ctl_file_stem, "B101");

        const EPSILON: f32 = 0.0001;

        assert!(b.obstacles[0]
            .world_position()
            .abs_diff_eq(Vec2::new(138.625, 47.5), EPSILON));
        assert!((b.obstacles[0].world_radius() - 7.875).abs() < EPSILON);
        assert!(b.obstacles[5]
            .world_position()
            .abs_diff_eq(Vec2::new(-0.75, 161.0), EPSILON));

        // Night Goblins#1
        assert!(b.nodes[0]
            .world_position()
            .abs_diff_eq(Vec2::new(151.25, 119.625), EPSILON));
        assert!((b.nodes[0].world_radius() - 6.0).abs() < EPSILON);
        assert!((b.nodes[0].rotation_degrees() - 182.10938).abs() < EPSILON);
        assert_eq!(b.nodes[0].regiment_id, 131);

        roundtrip_test(&original_bytes, &b);
    }

    #[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", "btbs"]
            .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() != "BTB" {
                return;
            }

            println!("Decoding {:?}", path.file_name().unwrap());

            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 original_bytes = std::fs::read(path).unwrap();
            let file = File::open(path).unwrap();
            let b = Decoder::new(file).decode().unwrap();

            // The width and height should be multiples of 8.
            assert_eq!(b.width % 8, 0);
            assert_eq!(b.height % 8, 0);

            roundtrip_test(&original_bytes, &b);

            let project_file = File::open(path.with_extension("PRJ"));
            if let Ok(project_file) = project_file {
                let p = project::Decoder::new(project_file).decode().unwrap();

                // The scaled down dimensions should always be smaller than the
                // project dimensions.
                assert!(b.width / 8 <= p.attributes.width);
                assert!(b.height / 8 <= p.attributes.height);

                // Overlay the battle tabletop on the heightmap image.
                let img = overlay_battle_tabletop_on_terrain(&p, &b);
                img.save(
                    output_dir
                        .join(path.file_stem().unwrap())
                        .with_extension("overlay.png"),
                )
                .unwrap();
            }

            // Every 1-player battle tabletop should at least have the following
            // objectives.
            for id in [
                ELIMINATE_ALL_ENEMIES_ID,
                CRITICAL_REGIMENT_LOSE_CONDITION_ID,
                SPATIAL_SOUND_EFFECT_PRESET_ID,
                INITIAL_REGIMENT_ORIENTATION_ID,
                PLAYER_ELIMINATION_LOSE_CONDITION_ID,
            ] {
                // Skip if file name is TMPBAT.BTB.
                if path.file_name().unwrap() == "TMPBAT.BTB" {
                    continue;
                }
                // Skip the multiplayer files.
                if path.file_name().unwrap().to_str().unwrap().starts_with('M') {
                    continue;
                }
                // Skip the tutorial file.
                if path.file_name().unwrap() == "SPARE9.BTB" {
                    continue;
                }

                assert!(
                    b.objectives.iter().any(|obj| obj.id == id),
                    "Battle tabletop {:?} is missing required objective ID: {}",
                    path.file_name().unwrap(),
                    id
                );
            }

            // Every multiplayer battle tabletop should have the following
            // objectives.
            for id in [
                ELIMINATE_ALL_ENEMIES_ID,
                SPATIAL_SOUND_EFFECT_PRESET_ID,
                INITIAL_REGIMENT_ORIENTATION_ID,
                PLAYER_ELIMINATION_LOSE_CONDITION_ID,
            ] {
                // Skip non-multiplayer files.
                if !path.file_name().unwrap().to_str().unwrap().starts_with('M') {
                    continue;
                }

                assert!(
                    b.objectives.iter().any(|obj| obj.id == id),
                    "Battle tabletop {:?} is missing required objective ID: {}",
                    path.file_name().unwrap(),
                    id
                );
            }

            for o in &b.obstacles {
                // Should either block movement or projectiles.
                assert!(
                    o.flags.contains(ObstacleFlags::BLOCKS_MOVEMENT)
                        || o.flags.contains(ObstacleFlags::BLOCKS_PROJECTILES)
                );
                // All obstacles should be active.
                assert!(o.flags.contains(ObstacleFlags::ACTIVE));
            }

            for region in &b.regions {
                // All regions should be active.
                assert!(region.flags.contains(RegionFlags::ACTIVE));
            }

            for node in &b.nodes {
                // All nodes should be active.
                assert!(node.flags.contains(NodeFlags::ACTIVE));

                // All regiment nodes should have a regiment ID except for
                // "TMPBAT.BTB". "TMPBAT.BTB" is the only file that has a
                // regiment node with a regiment ID of 0. It was probably a
                // temporary file.
                if node.flags.contains(NodeFlags::REGIMENT)
                    && path.file_name().unwrap() != "TMPBAT.BTB"
                {
                    assert!(node.regiment_id > 0);
                }

                // All waypoint nodes should have a route ID.
                if node.flags.contains(NodeFlags::WAYPOINT) {
                    assert!(node.node_id > 0);
                }
            }

            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, &b, Default::default()).unwrap();
            std::fs::write(output_path, buffer).unwrap();
        });
    }

    #[test]
    fn test_summarize_objectives() {
        use std::collections::{BTreeMap, BTreeSet};

        let d: PathBuf = [
            std::env::var("DARKOMEN_PATH").unwrap().as_str(),
            "DARKOMEN",
            "GAMEDATA",
        ]
        .iter()
        .collect();

        // Map of objective_id -> file -> set of (value1, value2) pairs.
        let mut objective_data: BTreeMap<i32, BTreeMap<String, BTreeSet<(i32, i32)>>> =
            BTreeMap::new();

        fn visit_dirs(dir: &Path, cb: &mut dyn FnMut(&Path)) {
            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() != "BTB" {
                return;
            }

            let file = File::open(path).unwrap();
            let b = Decoder::new(file).decode().unwrap();
            let file_name = path.file_name().unwrap().to_string_lossy().to_string();

            for obj in &b.objectives {
                objective_data
                    .entry(obj.id)
                    .or_default()
                    .entry(file_name.clone())
                    .or_default()
                    .insert((obj.value1, obj.value2));
            }
        });

        // Print summary table.
        println!("\n=== OBJECTIVE SUMMARY ===\n");

        for (obj_id, files) in &objective_data {
            let obj_name = match *obj_id {
                ELIMINATE_ALL_ENEMIES_ID => "Eliminate all enemies",
                KILL_DREAD_KING_ID => "Kill Dread King",
                CRITICAL_REGIMENT_LOSE_CONDITION_ID => "Critical regiment lose condition",
                SPATIAL_SOUND_EFFECT_PRESET_ID => "Spatial sound effect preset",
                KILL_MANNFRED_VON_CARSTEIN_ID => "Kill Mannfred von Carstein",
                FIREWORKS_ID => "Fireworks",
                INITIAL_REGIMENT_ORIENTATION_ID => "Initial regiment orientation",
                KILL_HAND_OF_NAGASH_ID => "Kill Hand of Nagash",
                KILL_BLACK_GRAIL_ID => "Kill Black Grail",
                GOLD_COLLECTION_METRIC_ID => "Gold collection metric",
                ENEMY_CASUALTIES_ID => "Enemy casualties",
                PLAYER_ELIMINATION_LOSE_CONDITION_ID => "Player elimination lose condition",
                _ => "Unknown",
            };

            println!(
                "Objective ID {}: {} (used in {} files)",
                obj_id,
                obj_name,
                files.len()
            );

            // Group files by their value pairs.
            let mut value_to_files: BTreeMap<BTreeSet<(i32, i32)>, Vec<String>> = BTreeMap::new();
            for (file, values) in files {
                value_to_files
                    .entry(values.clone())
                    .or_default()
                    .push(file.clone());
            }

            for (values, file_list) in &value_to_files {
                let values_str = values
                    .iter()
                    .map(|(v1, v2)| format!("({}, {})", v1, v2))
                    .collect::<Vec<_>>()
                    .join(", ");

                println!("  Values: {} - Files: {}", values_str, file_list.join(", "));
            }
            println!();
        }

        // Print a simple frequency table.
        println!("\n=== OBJECTIVE FREQUENCY ===\n");
        println!("{:<5} {:<45} {:<10}", "ID", "Name", "Count");
        println!("{}", "-".repeat(60));

        for (obj_id, files) in &objective_data {
            let obj_name = match *obj_id {
                ELIMINATE_ALL_ENEMIES_ID => "Eliminate all enemies",
                KILL_DREAD_KING_ID => "Kill Dread King",
                CRITICAL_REGIMENT_LOSE_CONDITION_ID => "Critical regiment lose condition",
                SPATIAL_SOUND_EFFECT_PRESET_ID => "Spatial sound effect preset",
                KILL_MANNFRED_VON_CARSTEIN_ID => "Kill Mannfred von Carstein",
                FIREWORKS_ID => "Fireworks",
                INITIAL_REGIMENT_ORIENTATION_ID => "Initial regiment orientation",
                KILL_HAND_OF_NAGASH_ID => "Kill Hand of Nagash",
                KILL_BLACK_GRAIL_ID => "Kill Black Grail",
                GOLD_COLLECTION_METRIC_ID => "Gold collection metric",
                ENEMY_CASUALTIES_ID => "Enemy casualties",
                PLAYER_ELIMINATION_LOSE_CONDITION_ID => "Player elimination lose condition",
                _ => "Unknown",
            };

            println!("{:<5} {:<45} {:<10}", obj_id, obj_name, files.len());
        }
    }

    /// Note: We know the battle tabletop always fits within the project
    /// dimensions so we don't need to expand the base image.
    fn overlay_battle_tabletop_on_terrain(p: &Project, b: &BattleTabletop) -> DynamicImage {
        // Doesn't matter which heightmap we use, they all have the same
        // dimensions, but the furniture one has the most detail.
        let img = p.terrain.furniture_heightmap_image();
        let mut img_buffer = img.to_rgba8();

        // The image is quite dark, so invert colors just for ease of viewing.
        for pixel in img_buffer.pixels_mut() {
            let (r, g, b, a) = (255 - pixel[0], 255 - pixel[1], 255 - pixel[2], pixel[3]); // invert RGB, keep alpha the same
            *pixel = Rgba([r, g, b, a]);
        }

        // Pin the rectangle to the top right which is the terrain origin.
        let start_x = img_buffer.width() as i32 - (b.width / 8) as i32;
        let start_y = 0; // top edge, so y is 0

        // Draw a hollow rectangle on the base image to show the battle tabletop
        // dimensions.
        let rect = Rect::at(start_x, start_y).of_size(b.width / 8, b.height / 8);
        draw_hollow_rect_mut(&mut img_buffer, rect, Rgba([255, 0, 0, 255]));

        // Now rotate the image 180 degrees to make the origin at the bottom
        // left which matches the in-game aeiral map view.
        let img_buffer = image::imageops::rotate180(&img_buffer);

        DynamicImage::ImageRgba8(img_buffer)
    }

    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()
    }
}