oort_api 0.84.0

APIs for Oort, a space fleet programming game.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

use std::f64::consts::TAU;

#[doc(hidden)]
pub mod panic;
mod vec;

#[allow(missing_docs)]
#[derive(Copy, Clone)]
pub enum SystemState {
    Class,
    Seed,
    PositionX,
    PositionY,
    VelocityX,
    VelocityY,
    Heading,
    AngularVelocity,

    AccelerateX,
    AccelerateY,
    Torque,

    Aim0,
    Aim1,
    Aim2,
    Aim3,

    Fire0,
    Fire1,
    Fire2,
    Fire3,

    Explode,

    Radar0Heading,
    Radar0Width,
    Radar0MinDistance,
    Radar0MaxDistance,
    Radar0EcmMode,

    Radar0ContactFound,
    Radar0ContactClass,
    Radar0ContactPositionX,
    Radar0ContactPositionY,
    Radar0ContactVelocityX,
    Radar0ContactVelocityY,
    Radar0ContactRssi,
    Radar0ContactSnr,

    Radar1Heading,
    Radar1Width,
    Radar1MinDistance,
    Radar1MaxDistance,
    Radar1EcmMode,

    Radar1ContactFound,
    Radar1ContactClass,
    Radar1ContactPositionX,
    Radar1ContactPositionY,
    Radar1ContactVelocityX,
    Radar1ContactVelocityY,
    Radar1ContactRssi,
    Radar1ContactSnr,

    DebugTextPointer,
    DebugTextLength,

    MaxForwardAcceleration,
    MaxLateralAcceleration,
    MaxAngularAcceleration,

    DebugLinesPointer,
    DebugLinesLength,

    CurrentTick,
    MaxBackwardAcceleration,

    ActivateAbility,

    Radio0Channel, // TODO collapse into command word
    Radio0Send,
    Radio0Receive,
    Radio0Data0,
    Radio0Data1,
    Radio0Data2,
    Radio0Data3,

    Radio1Channel,
    Radio1Send,
    Radio1Receive,
    Radio1Data0,
    Radio1Data1,
    Radio1Data2,
    Radio1Data3,

    Radio2Channel,
    Radio2Send,
    Radio2Receive,
    Radio2Data0,
    Radio2Data1,
    Radio2Data2,
    Radio2Data3,

    Radio3Channel,
    Radio3Send,
    Radio3Receive,
    Radio3Data0,
    Radio3Data1,
    Radio3Data2,
    Radio3Data3,

    Radio4Channel,
    Radio4Send,
    Radio4Receive,
    Radio4Data0,
    Radio4Data1,
    Radio4Data2,
    Radio4Data3,

    Radio5Channel,
    Radio5Send,
    Radio5Receive,
    Radio5Data0,
    Radio5Data1,
    Radio5Data2,
    Radio5Data3,

    Radio6Channel,
    Radio6Send,
    Radio6Receive,
    Radio6Data0,
    Radio6Data1,
    Radio6Data2,
    Radio6Data3,

    Radio7Channel,
    Radio7Send,
    Radio7Receive,
    Radio7Data0,
    Radio7Data1,
    Radio7Data2,
    Radio7Data3,

    // TODO not part of interface
    SelectedRadio,
    SelectedRadar,

    DrawnTextPointer,
    DrawnTextLength,

    Health,
    Fuel,

    ReloadTicks0,
    ReloadTicks1,
    ReloadTicks2,
    ReloadTicks3,

    Id,

    Size,
    MaxSize = 128,
}

#[allow(missing_docs)]
pub const MAX_ENVIRONMENT_SIZE: usize = 1024;

/// Identifiers for each class of ship.
#[allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Class {
    Fighter,
    Frigate,
    Cruiser,
    Asteroid,
    Target,
    Missile,
    Torpedo,
    Unknown,
}

impl Class {
    #[allow(missing_docs)]
    pub fn from_f64(v: f64) -> Class {
        match v as u32 {
            0 => Class::Fighter,
            1 => Class::Frigate,
            2 => Class::Cruiser,
            3 => Class::Asteroid,
            4 => Class::Target,
            5 => Class::Missile,
            6 => Class::Torpedo,
            _ => Class::Unknown,
        }
    }

    /// Returns base stats for a class of ship
    pub fn default_stats(&self) -> ClassStats {
        match self {
            Class::Fighter => ClassStats {
                max_health: 100.0,
                mass: 15000.0,
                max_forward_acceleration: 60.0,
                max_backward_acceleration: 30.0,
                max_lateral_acceleration: 30.0,
                max_angular_acceleration: TAU,
            },
            Class::Frigate => ClassStats {
                max_health: 10000.0,
                mass: 4e6,
                max_forward_acceleration: 10.0,
                max_backward_acceleration: 5.0,
                max_lateral_acceleration: 5.0,
                max_angular_acceleration: TAU / 8.0,
            },
            Class::Cruiser => ClassStats {
                max_health: 20000.0,
                mass: 9e6,
                max_forward_acceleration: 5.0,
                max_backward_acceleration: 2.5,
                max_lateral_acceleration: 2.5,
                max_angular_acceleration: TAU / 16.0,
            },
            Class::Asteroid => ClassStats {
                max_health: 200.0,
                mass: 20e6,
                max_forward_acceleration: 0.0,
                max_backward_acceleration: 0.0,
                max_lateral_acceleration: 0.0,
                max_angular_acceleration: 0.0,
            },
            Class::Target => ClassStats {
                max_health: 1.0,
                mass: 10.0,
                max_forward_acceleration: 0.0,
                max_backward_acceleration: 0.0,
                max_lateral_acceleration: 0.0,
                max_angular_acceleration: 0.0,
            },
            Class::Missile => ClassStats {
                max_health: 20.0,
                mass: 150.0,
                max_forward_acceleration: 300.0,
                max_backward_acceleration: 0.0,
                max_lateral_acceleration: 100.0,
                max_angular_acceleration: 4.0 * TAU,
            },
            Class::Torpedo => ClassStats {
                max_health: 100.0,
                mass: 500.0,
                max_forward_acceleration: 70.0,
                max_backward_acceleration: 0.0,
                max_lateral_acceleration: 20.0,
                max_angular_acceleration: 2.0 * TAU,
            },
            Class::Unknown => ClassStats {
                max_health: 100.0,
                mass: 1000.0,
                max_forward_acceleration: 0.0,
                max_backward_acceleration: 0.0,
                max_lateral_acceleration: 0.0,
                max_angular_acceleration: 0.0,
            },
        }
    }
}

/// Stats for a class of ship
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct ClassStats {
    pub max_health: f64,
    pub mass: f64,
    pub max_forward_acceleration: f64,
    pub max_backward_acceleration: f64,
    pub max_lateral_acceleration: f64,
    pub max_angular_acceleration: f64,
}

/// List of active abilities for an entity.
#[repr(transparent)]
pub struct ActiveAbilities(pub u64);

impl ActiveAbilities {
    /// Activate an ability.
    pub fn set_ability(&mut self, ability: Ability) {
        let mut mask = 0u64;
        mask ^= 1u64 << (ability as u64);
        self.0 |= mask;
    }
    /// Deactivate an ability.
    pub fn unset_ability(&mut self, ability: Ability) {
        let mut mask = 0u64;
        mask ^= 1u64 << (ability as u64);
        self.0 &= !mask;
    }
    /// Get whether an ability is active.
    pub fn get_ability(&self, ability: Ability) -> bool {
        (self.0 & 1 << (ability as u64)) >> (ability as u64) != 0
    }
    /// Unset all abilities
    pub fn clear(&mut self) {
        self.0 = 0
    }
    /// Invert set and unset abilities.
    pub fn invert(&mut self) {
        self.0 = !self.0
    }
    /// Iterator over active abilities
    pub fn active_iter(&self) -> impl Iterator<Item = Ability> + core::fmt::Debug + Clone + '_ {
        ABILITIES
            .iter()
            .flat_map(|&ability| self.get_ability(ability).then_some(ability))
    }
}

/// Special abilities available to different ship classes.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Ability {
    /// No-op.
    #[doc(hidden)]
    None,
    /// Fighter and missile only. Applies a 100 m/s² forward acceleration for 2s. Reloads in 10s.
    Boost,
    /// Deprecated
    #[doc(hidden)]
    ShapedCharge,
    /// Torpedo only. Mimics the radar signature of a Cruiser for 0.5s. Reloads in 10s.
    Decoy,
    /// Cruiser only. Deflects projectiles for 1s. Reloads in 5s.
    Shield,
}

/// Array of all ability types.
pub const ABILITIES: &[Ability] = &[Ability::Boost, Ability::Decoy, Ability::Shield];

/// Electronic Counter Measures (ECM) modes.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EcmMode {
    /// No ECM, radar will work normally.
    None,
    /// Affected enemy radars will have a lower signal-to-noise ratio, making
    /// it harder to detect and track targets.
    Noise,
}

impl From<f64> for EcmMode {
    fn from(x: f64) -> Self {
        match x as u32 {
            0 => EcmMode::None,
            1 => EcmMode::Noise,
            _ => EcmMode::None,
        }
    }
}

#[doc(hidden)]
#[derive(Default, Clone)]
pub struct Line {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
    pub color: u32,
}

#[doc(hidden)]
#[derive(Default, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Text {
    pub x: f64,
    pub y: f64,
    pub color: u32,
    pub length: u8,
    pub text: [u8; 11],
}

/// Message sent and received on the radio.
pub type Message = [f64; 4];

// Public for fuzzer.
#[doc(hidden)]
pub mod sys {
    use super::SystemState;
    use crate::MAX_ENVIRONMENT_SIZE;
    use std::ptr;

    // TODO crashes rust-analyzer
    #[no_mangle]
    pub static mut SYSTEM_STATE: [u64; SystemState::MaxSize as usize] =
        [0; SystemState::MaxSize as usize];

    pub fn read_system_state_u64(index: SystemState) -> u64 {
        let system_state = unsafe { ptr::addr_of!(SYSTEM_STATE) };
        unsafe { (*system_state)[index as usize] }
    }

    pub fn write_system_state_u64(index: SystemState, value: u64) {
        let system_state = unsafe { ptr::addr_of_mut!(SYSTEM_STATE) };
        unsafe { (*system_state)[index as usize] = value };
    }

    pub fn read_system_state(index: SystemState) -> f64 {
        f64::from_bits(read_system_state_u64(index))
    }

    pub fn write_system_state(index: SystemState, value: f64) {
        write_system_state_u64(index, value.to_bits())
    }

    #[no_mangle]
    pub static mut ENVIRONMENT: [u8; MAX_ENVIRONMENT_SIZE] = [0; MAX_ENVIRONMENT_SIZE];

    pub fn read_environment() -> &'static str {
        // Format is key=value\nkey=value\n... ending with a null byte.
        unsafe {
            let environment = ptr::addr_of!(ENVIRONMENT);
            let n = (*environment)
                .iter()
                .position(|&c| c == 0)
                .unwrap_or((*environment).len());
            std::str::from_utf8(&(*environment)[..n])
                .expect("Failed to convert environment to string")
        }
    }

    pub fn getenv(key: &str) -> Option<&'static str> {
        let environment = read_environment();
        for line in environment.lines() {
            let mut parts = line.splitn(2, '=');
            if let Some(k) = parts.next() {
                if k == key {
                    return parts.next();
                }
            }
        }
        None
    }
}

mod math {
    pub use std::f64::consts::{PI, TAU};

    /// Returns the smallest rotation between angles `a` and `b`.
    ///
    /// A positive result is a counter-clockwise rotation and negative is clockwise.
    pub fn angle_diff(a: f64, b: f64) -> f64 {
        let c = (b - a).rem_euclid(TAU);
        if c > PI {
            c - TAU
        } else {
            c
        }
    }
}

mod rng {
    fn rng() -> &'static mut oorandom::Rand64 {
        let rng_state = unsafe { super::rng_state::get() };
        &mut rng_state.rng
    }

    /// Returns a random number between `low` and `high`.
    pub fn rand(low: f64, high: f64) -> f64 {
        rng().rand_float() * (high - low) + low
    }
}

#[doc(hidden)]
pub mod rng_state {
    #[derive(Clone)]
    pub struct RngState {
        pub rng: oorandom::Rand64,
    }

    static mut RNG_STATE: Option<RngState> = None;

    impl RngState {
        #[allow(clippy::new_without_default)]
        pub fn new() -> Self {
            Self {
                rng: oorandom::Rand64::new(super::api::seed()),
            }
        }
    }

    pub unsafe fn get() -> &'static mut RngState {
        RNG_STATE.as_mut().unwrap()
    }

    pub unsafe fn set(s: RngState) {
        RNG_STATE = Some(s)
    }
}

mod api {
    use super::sys::{read_system_state, write_system_state};
    use super::{Ability, Class, EcmMode, SystemState};
    use crate::sys::{read_system_state_u64, write_system_state_u64};
    use crate::{vec::*, ActiveAbilities, Message};

    /// The time between each simulation tick.
    pub const TICK_LENGTH: f64 = 1.0 / 60.0;

    /// Returns a per-ship ID that is unique within a team.
    pub fn id() -> u32 {
        read_system_state(SystemState::Id) as u32
    }

    /// Returns the ship [`Class`] (Fighter, Cruiser, etc).
    pub fn class() -> Class {
        Class::from_f64(read_system_state(SystemState::Class))
    }

    /// Returns a random number useful for initializing a random number generator.
    pub fn seed() -> u128 {
        read_system_state(super::SystemState::Seed) as u128
    }

    /// Returns the scenario name.
    pub fn scenario_name() -> &'static str {
        super::sys::getenv("SCENARIO_NAME").unwrap_or("unknown")
    }

    /// Returns the world size in meters.
    pub fn world_size() -> f64 {
        super::sys::getenv("WORLD_SIZE")
            .unwrap_or("0.0")
            .parse()
            .unwrap_or(0.0)
    }

    /// Returns the current position (in meters).
    pub fn position() -> Vec2 {
        vec2(
            read_system_state(SystemState::PositionX),
            read_system_state(SystemState::PositionY),
        )
    }

    /// Returns the current velocity (in m/s).
    pub fn velocity() -> Vec2 {
        vec2(
            read_system_state(SystemState::VelocityX),
            read_system_state(SystemState::VelocityY),
        )
    }

    /// Returns the current heading (in radians).
    pub fn heading() -> f64 {
        read_system_state(SystemState::Heading)
    }

    /// Returns the current angular velocity (in radians/s).
    pub fn angular_velocity() -> f64 {
        read_system_state(SystemState::AngularVelocity)
    }

    /// Sets the linear acceleration for the next tick (in m/s²).
    pub fn accelerate(mut acceleration: Vec2) {
        acceleration = acceleration.rotate(-heading());
        if acceleration.x > max_forward_acceleration() {
            acceleration *= max_forward_acceleration() / acceleration.x;
        }
        if acceleration.x < -max_backward_acceleration() {
            acceleration *= max_backward_acceleration() / -acceleration.x;
        }
        if acceleration.y.abs() > max_lateral_acceleration() {
            acceleration *= max_lateral_acceleration() / acceleration.y.abs();
        }
        write_system_state(SystemState::AccelerateX, acceleration.x);
        write_system_state(SystemState::AccelerateY, acceleration.y);
    }

    /// Rotates the ship at the given speed (in radians/s).
    ///
    /// Internally this uses `torque()`. Reaching the commanded speed takes time.
    pub fn turn(speed: f64) {
        let max = max_angular_acceleration() * 0.2;
        let dv = speed.clamp(-max, max) - angular_velocity();
        if dv.abs() < max_angular_acceleration() * TICK_LENGTH {
            torque(dv / TICK_LENGTH);
        } else {
            torque(dv.signum() * max_angular_acceleration());
        }
    }

    /// Sets the angular acceleration for the next tick (in radians/s²).
    ///
    /// This is lower-level than turn() and can be used to turn faster.
    pub fn torque(angular_acceleration: f64) {
        write_system_state(SystemState::Torque, angular_acceleration);
    }

    /// Aims a turreted weapon.
    ///
    /// `index` selects the weapon.
    /// `heading` is in radians.
    pub fn aim(index: usize, heading: f64) {
        let state_index = match index {
            0 => SystemState::Aim0,
            1 => SystemState::Aim1,
            2 => SystemState::Aim2,
            3 => SystemState::Aim3,
            _ => return,
        };
        write_system_state(state_index, heading);
    }

    /// Fires a weapon.
    ///
    /// `index` selects the weapon.
    pub fn fire(index: usize) {
        let state_index = match index {
            0 => SystemState::Fire0,
            1 => SystemState::Fire1,
            2 => SystemState::Fire2,
            3 => SystemState::Fire3,
            _ => return,
        };
        write_system_state(state_index, 1.0);
    }

    /// Returns the number of ticks until a weapon is ready to fire.
    ///
    /// `index` selects the weapon. Returns 0 if the weapon is ready.
    pub fn reload_ticks(index: usize) -> u32 {
        let state_index = match index {
            0 => SystemState::ReloadTicks0,
            1 => SystemState::ReloadTicks1,
            2 => SystemState::ReloadTicks2,
            3 => SystemState::ReloadTicks3,
            _ => return 0,
        };
        read_system_state(state_index) as u32
    }

    /// Self-destructs, producing a damaging explosion.
    ///
    /// This is commonly used by missiles.
    pub fn explode() {
        write_system_state(SystemState::Explode, 1.0);
    }

    /// Returns the current health.
    pub fn health() -> f64 {
        read_system_state(SystemState::Health)
    }

    /// Returns the current fuel (delta-v).
    pub fn fuel() -> f64 {
        read_system_state(SystemState::Fuel)
    }

    #[doc(hidden)]
    pub mod radar_internal {
        use super::SystemState;

        pub const MAX_RADARS: usize = 2;

        pub struct RadarControlIndices {
            pub heading: SystemState,
            pub width: SystemState,
            pub min_distance: SystemState,
            pub max_distance: SystemState,
            pub ecm_mode: SystemState,
        }

        pub fn radar_control_indices(sel: usize) -> RadarControlIndices {
            assert!(sel < MAX_RADARS);
            let stride = 13;
            let offset = stride * sel;
            let add_offset =
                |x| unsafe { ::std::mem::transmute::<u8, SystemState>((x as u8) + offset as u8) };
            RadarControlIndices {
                heading: add_offset(SystemState::Radar0Heading),
                width: add_offset(SystemState::Radar0Width),
                min_distance: add_offset(SystemState::Radar0MinDistance),
                max_distance: add_offset(SystemState::Radar0MaxDistance),
                ecm_mode: add_offset(SystemState::Radar0EcmMode),
            }
        }

        pub fn current_radar_control_indices() -> RadarControlIndices {
            let sel = super::read_system_state(SystemState::SelectedRadar) as usize;
            radar_control_indices(sel)
        }

        pub struct RadarContactIndices {
            pub found: SystemState,
            pub class: SystemState,
            pub position: [SystemState; 2],
            pub velocity: [SystemState; 2],
            pub rssi: SystemState,
            pub snr: SystemState,
        }

        pub fn radar_contact_indices(sel: usize) -> RadarContactIndices {
            assert!(sel < MAX_RADARS);
            let stride = 13;
            let offset = stride * sel;
            let add_offset =
                |x| unsafe { ::std::mem::transmute::<u8, SystemState>((x as u8) + offset as u8) };
            RadarContactIndices {
                found: add_offset(SystemState::Radar0ContactFound),
                class: add_offset(SystemState::Radar0ContactClass),
                position: [
                    add_offset(SystemState::Radar0ContactPositionX),
                    add_offset(SystemState::Radar0ContactPositionY),
                ],
                velocity: [
                    add_offset(SystemState::Radar0ContactVelocityX),
                    add_offset(SystemState::Radar0ContactVelocityY),
                ],
                rssi: add_offset(SystemState::Radar0ContactRssi),
                snr: add_offset(SystemState::Radar0ContactSnr),
            }
        }

        pub fn current_radar_contact_indices() -> RadarContactIndices {
            let sel = super::read_system_state(SystemState::SelectedRadar) as usize;
            radar_contact_indices(sel)
        }
    }

    /// Select the radar to control with subsequent API calls.
    pub fn select_radar(index: usize) {
        let index = index.clamp(0, radar_internal::MAX_RADARS - 1);
        write_system_state(SystemState::SelectedRadar, index as f64);
    }

    /// Returns the heading the radar is pointed at.
    pub fn radar_heading() -> f64 {
        read_system_state(radar_internal::current_radar_control_indices().heading)
    }

    /// Sets the heading to point the radar at.
    ///
    /// It takes effect next tick.
    pub fn set_radar_heading(heading: f64) {
        write_system_state(
            radar_internal::current_radar_control_indices().heading,
            heading,
        );
    }

    /// Returns the current radar width (in radians).
    ///
    /// This is the field of view of the radar.
    pub fn radar_width() -> f64 {
        read_system_state(radar_internal::current_radar_control_indices().width)
    }

    /// Sets the radar width (in radians).
    ///
    /// This is the field of view of the radar.
    /// It takes effect next tick.
    pub fn set_radar_width(width: f64) {
        write_system_state(radar_internal::current_radar_control_indices().width, width);
    }

    /// Gets the current minimum distance filter of the radar (in meters).
    pub fn radar_min_distance() -> f64 {
        read_system_state(radar_internal::current_radar_control_indices().min_distance)
    }

    /// Sets the minimum distance filter of the radar (in meters).
    ///
    /// It takes effect next tick.
    pub fn set_radar_min_distance(dist: f64) {
        write_system_state(
            radar_internal::current_radar_control_indices().min_distance,
            dist,
        );
    }

    /// Gets the current maximum distance filter of the radar (in meters).
    pub fn radar_max_distance() -> f64 {
        read_system_state(radar_internal::current_radar_control_indices().max_distance)
    }

    /// Sets the maximum distance filter of the radar (in meters).
    ///
    /// It takes effect next tick.
    pub fn set_radar_max_distance(dist: f64) {
        write_system_state(
            radar_internal::current_radar_control_indices().max_distance,
            dist,
        );
    }

    /// Gets the Electronic Counter Measures (ECM) mode.
    pub fn radar_ecm_mode() -> EcmMode {
        read_system_state(radar_internal::current_radar_control_indices().ecm_mode).into()
    }

    /// Sets the Electronic Counter Measures (ECM) mode.
    pub fn set_radar_ecm_mode(mode: EcmMode) {
        write_system_state(
            radar_internal::current_radar_control_indices().ecm_mode,
            mode as u32 as f64,
        );
    }

    /// A radar contact.
    #[derive(Clone, Debug)]
    pub struct ScanResult {
        /// The contact's class.
        pub class: Class,
        /// The contact's approximate position.
        pub position: Vec2,
        /// The contact's approximate velocity.
        pub velocity: Vec2,
        /// The received signal strength measured in dBm.
        pub rssi: f64,
        /// The signal-to-noise ratio measured in dB.
        pub snr: f64,
    }

    /// Returns the radar contact with the highest signal strength.
    pub fn scan() -> Option<ScanResult> {
        let indices = radar_internal::current_radar_contact_indices();
        if read_system_state(indices.found) == 0.0 {
            return None;
        }
        Some(ScanResult {
            class: Class::from_f64(read_system_state(indices.class)),
            position: vec2(
                read_system_state(indices.position[0]),
                read_system_state(indices.position[1]),
            ),
            velocity: vec2(
                read_system_state(indices.velocity[0]),
                read_system_state(indices.velocity[1]),
            ),
            rssi: read_system_state(indices.rssi),
            snr: read_system_state(indices.snr),
        })
    }

    #[doc(hidden)]
    pub mod radio_internal {
        use super::SystemState;

        pub const MAX_RADIOS: usize = 8;

        pub struct RadioIndices {
            pub channel: SystemState,
            pub send: SystemState,
            pub receive: SystemState,
            pub data: [SystemState; 4],
        }

        pub fn radio_indices(sel: usize) -> RadioIndices {
            assert!(sel < MAX_RADIOS);
            let stride = 7;
            let offset = stride * sel;
            let add_offset =
                |x| unsafe { ::std::mem::transmute::<u8, SystemState>((x as u8) + offset as u8) };
            RadioIndices {
                channel: add_offset(SystemState::Radio0Channel),
                send: add_offset(SystemState::Radio0Send),
                receive: add_offset(SystemState::Radio0Receive),
                data: [
                    add_offset(SystemState::Radio0Data0),
                    add_offset(SystemState::Radio0Data1),
                    add_offset(SystemState::Radio0Data2),
                    add_offset(SystemState::Radio0Data3),
                ],
            }
        }
    }

    /// Select the radio to control with subsequent API calls.
    pub fn select_radio(index: usize) {
        let index = index.clamp(0, radio_internal::MAX_RADIOS - 1);
        write_system_state(SystemState::SelectedRadio, index as f64);
    }

    /// Sets the channel to send and receive radio transmissions on.
    ///
    /// Takes effect next tick.
    pub fn set_radio_channel(channel: usize) {
        write_system_state(
            radio_internal::radio_indices(read_system_state(SystemState::SelectedRadio) as usize)
                .channel,
            channel as f64,
        );
    }

    /// Gets the current radio channel.
    pub fn get_radio_channel() -> usize {
        read_system_state(
            radio_internal::radio_indices(read_system_state(SystemState::SelectedRadio) as usize)
                .channel,
        ) as usize
    }

    /// Sends a radio message.
    ///
    /// The message will be received on the next tick.
    ///
    /// If you want to send arbitrary data, consider using [`send_bytes`] instead.
    pub fn send(msg: Message) {
        let idxs =
            radio_internal::radio_indices(read_system_state(SystemState::SelectedRadio) as usize);
        write_system_state(idxs.send, 1.0);
        write_system_state(idxs.data[0], msg[0]);
        write_system_state(idxs.data[1], msg[1]);
        write_system_state(idxs.data[2], msg[2]);
        write_system_state(idxs.data[3], msg[3]);
    }

    /// Returns the received radio message.
    pub fn receive() -> Option<Message> {
        let idxs =
            radio_internal::radio_indices(read_system_state(SystemState::SelectedRadio) as usize);
        if read_system_state(idxs.receive) != 0.0 {
            Some([
                read_system_state(idxs.data[0]),
                read_system_state(idxs.data[1]),
                read_system_state(idxs.data[2]),
                read_system_state(idxs.data[3]),
            ])
        } else {
            None
        }
    }

    /// Sends a radio message.
    /// The message will be zero-filled or truncated to be 32 bytes long.
    ///
    /// The message will be received on the next tick.
    ///
    /// If you only want to send [`f64`]s consider using [`send`] instead.
    pub fn send_bytes(msg: &[u8]) {
        let mut bytes = [[0; 8]; 4];
        bytes
            .iter_mut()
            .flatten()
            .zip(msg)
            .for_each(|(b, m)| *b = *m);

        let idxs =
            radio_internal::radio_indices(read_system_state(SystemState::SelectedRadio) as usize);
        write_system_state(idxs.send, 1.0);
        write_system_state_u64(idxs.data[0], u64::from_ne_bytes(bytes[0]));
        write_system_state_u64(idxs.data[1], u64::from_ne_bytes(bytes[1]));
        write_system_state_u64(idxs.data[2], u64::from_ne_bytes(bytes[2]));
        write_system_state_u64(idxs.data[3], u64::from_ne_bytes(bytes[3]));
    }

    /// Returns the received radio message.
    pub fn receive_bytes() -> Option<[u8; 32]> {
        let idxs =
            radio_internal::radio_indices(read_system_state(SystemState::SelectedRadio) as usize);
        if read_system_state(idxs.receive) != 0.0 {
            let mut bytes = [0; 32];
            bytes[0..8].copy_from_slice(&read_system_state_u64(idxs.data[0]).to_ne_bytes());
            bytes[8..16].copy_from_slice(&read_system_state_u64(idxs.data[1]).to_ne_bytes());
            bytes[16..24].copy_from_slice(&read_system_state_u64(idxs.data[2]).to_ne_bytes());
            bytes[24..32].copy_from_slice(&read_system_state_u64(idxs.data[3]).to_ne_bytes());
            Some(bytes)
        } else {
            None
        }
    }

    /// Returns the maximum linear acceleration (in m/s²).
    #[deprecated]
    pub fn max_acceleration() -> Vec2 {
        vec2(
            read_system_state(SystemState::MaxForwardAcceleration),
            read_system_state(SystemState::MaxBackwardAcceleration),
        )
    }

    /// Returns the maximum forward acceleration (in m/s²).
    pub fn max_forward_acceleration() -> f64 {
        read_system_state(SystemState::MaxForwardAcceleration)
    }

    /// Returns the maximum backward acceleration (in m/s²).
    pub fn max_backward_acceleration() -> f64 {
        read_system_state(SystemState::MaxBackwardAcceleration)
    }

    /// Returns the maximum lateral acceleration (in m/s²).
    pub fn max_lateral_acceleration() -> f64 {
        read_system_state(SystemState::MaxLateralAcceleration)
    }

    /// Returns the maximum angular acceleration (in radians/s²).
    pub fn max_angular_acceleration() -> f64 {
        read_system_state(SystemState::MaxAngularAcceleration)
    }

    /// Returns the number of ticks elapsed since the simulation began.
    pub fn current_tick() -> u32 {
        read_system_state(SystemState::CurrentTick) as u32
    }

    /// Returns the number of seconds elapsed since the simulation began.
    pub fn current_time() -> f64 {
        read_system_state(SystemState::CurrentTick) * TICK_LENGTH
    }

    /// Activates a special ability.
    pub fn activate_ability(ability: Ability) {
        let mut active_abilities =
            ActiveAbilities(read_system_state_u64(SystemState::ActivateAbility));
        active_abilities.set_ability(ability);
        write_system_state_u64(SystemState::ActivateAbility, active_abilities.0);
    }

    /// Deactivates a special ability.
    pub fn deactivate_ability(ability: Ability) {
        let mut active_abilities =
            ActiveAbilities(read_system_state_u64(SystemState::ActivateAbility));
        active_abilities.unset_ability(ability);
        write_system_state_u64(SystemState::ActivateAbility, active_abilities.0);
    }

    /// Get a copy of the active abilities. Useful for querying which abilities are currently active.
    pub fn active_abilities() -> ActiveAbilities {
        ActiveAbilities(read_system_state_u64(SystemState::ActivateAbility))
    }

    /// Returns the position of the target set by the scenario.
    /// Only used in tutorials.
    pub fn target() -> Vec2 {
        vec2(
            read_system_state(radar_internal::current_radar_contact_indices().position[0]),
            read_system_state(radar_internal::current_radar_contact_indices().position[1]),
        )
    }

    /// Returns the velocity of the target set by the scenario.
    /// Only used in tutorials.
    pub fn target_velocity() -> Vec2 {
        vec2(
            read_system_state(radar_internal::current_radar_contact_indices().velocity[0]),
            read_system_state(radar_internal::current_radar_contact_indices().velocity[1]),
        )
    }
}

#[doc(hidden)]
#[macro_use]
pub mod dbg {
    use super::{Line, Text};
    use crate::sys::write_system_state;
    use crate::vec::*;
    use std::f64::consts::TAU;
    use std::ptr;

    static mut TEXT_BUFFER: String = String::new();
    static mut LINE_BUFFER: Vec<Line> = Vec::new();
    static mut DRAWN_TEXT_BUFFER: Vec<Text> = Vec::new();

    /// Adds text to be displayed when the ship is selected by clicking on it.
    ///
    /// Works just like [println!].
    #[macro_export]
    macro_rules! debug {
        ($($arg:tt)*) => {
            $crate::dbg::write(std::format_args!($($arg)*))
        };
    }

    #[allow(unused)]
    #[doc(hidden)]
    pub fn write(args: std::fmt::Arguments) {
        use std::fmt::Write;
        unsafe {
            let buf = ptr::addr_of_mut!(TEXT_BUFFER);
            let _ = std::fmt::write(&mut *buf, args);
            (*buf).push('\n');
        }
    }

    /// Creates a 24-bit RGB color from the arguments.
    pub fn rgb(r: u8, g: u8, b: u8) -> u32 {
        let r = r as u32;
        let g = g as u32;
        let b = b as u32;
        r << 16 | g << 8 | b
    }

    /// Draws a line visible in debug mode.
    ///
    /// `a` and `b` are positions in world coordinates.
    /// `color` is 24-bit RGB.
    ///
    /// Up to 1024 lines can be drawn per ship, per tick. This quota is also consumed
    /// by the various shape drawing functions.
    pub fn draw_line(a: Vec2, b: Vec2, color: u32) {
        unsafe {
            let buf = ptr::addr_of_mut!(LINE_BUFFER);
            (*buf).push(Line {
                x0: a.x,
                y0: a.y,
                x1: b.x,
                y1: b.y,
                color,
            });
        }
    }

    #[deprecated]
    #[doc(hidden)]
    pub fn debug_line(a: Vec2, b: Vec2, color: u32) {
        draw_line(a, b, color)
    }

    /// Draws a regular polygon visible in debug mode.
    ///
    /// `center` is a position in world coordinates.
    /// `color` is 24-bit RGB.
    pub fn draw_polygon(center: Vec2, radius: f64, sides: i32, angle: f64, color: u32) {
        let delta_angle = TAU / sides as f64;
        let sin = delta_angle.sin();
        let cos = delta_angle.cos();
        let rotation: maths_rs::Mat2d = maths_rs::prelude::MatNew2::new(cos, -sin, sin, cos);
        let mut p = vec2(radius, 0.0).rotate(angle);
        for _ in 0..sides {
            let p2 = rotation * p;
            draw_line(center + p, center + p2, color);
            p = p2;
        }
    }

    #[deprecated]
    #[doc(hidden)]
    pub fn debug_polygon(center: Vec2, radius: f64, sides: i32, angle: f64, color: u32) {
        draw_polygon(center, radius, sides, angle, color)
    }

    /// Draws a triangle visible in debug mode.
    ///
    /// `center` is a position in world coordinates.
    /// `color` is 24-bit RGB.
    pub fn draw_triangle(center: Vec2, radius: f64, color: u32) {
        let x = f64::sqrt(3.0) * radius / 2.0;
        let y = radius / 2.0;
        let points = [
            center + vec2(0.0, radius),
            center + vec2(-x, -y),
            center + vec2(x, -y),
        ];
        for i in 0..3 {
            draw_line(points[i], points[(i + 1) % 3], color);
        }
    }

    #[deprecated]
    #[doc(hidden)]
    pub fn debug_triangle(center: Vec2, radius: f64, color: u32) {
        draw_triangle(center, radius, color)
    }

    /// Draws a square visible in debug mode.
    ///
    /// `center` is a position in world coordinates.
    /// `color` is 24-bit RGB.
    pub fn draw_square(center: Vec2, radius: f64, color: u32) {
        let offset = radius / f64::sqrt(2.0);
        let mut p = vec2(offset, offset);
        for _ in 0..4 {
            let p2 = vec2(-p.y, p.x);
            draw_line(center + p, center + p2, color);
            p = p2;
        }
    }

    #[deprecated]
    #[doc(hidden)]
    pub fn debug_square(center: Vec2, radius: f64, color: u32) {
        draw_square(center, radius, color)
    }

    /// Draws a diamond visible in debug mode.
    ///
    /// `center` is a position in world coordinates.
    /// `color` is 24-bit RGB.
    pub fn draw_diamond(center: Vec2, radius: f64, color: u32) {
        let mut p = vec2(radius, 0.0);
        for _ in 0..4 {
            let p2 = vec2(-p.y, p.x);
            draw_line(center + p, center + p2, color);
            p = p2;
        }
    }

    #[deprecated]
    #[doc(hidden)]
    pub fn debug_diamond(center: Vec2, radius: f64, color: u32) {
        draw_diamond(center, radius, color)
    }

    /// Adds text to be drawn in the world, visible in debug mode.
    ///
    /// Works like [println!]. Up to 128 strings can be drawn per ship, per tick.
    #[macro_export]
    macro_rules! draw_text {
        ($topleft:expr, $color:expr, $($arg:tt)*) => {
            $crate::dbg::draw_text_internal($topleft, $color, std::format_args!($($arg)*))
        };
    }

    #[allow(unused)]
    #[doc(hidden)]
    pub fn draw_text_internal(topleft: Vec2, color: u32, args: std::fmt::Arguments) {
        use std::fmt::Write;
        let mut text = String::new();
        let _ = std::fmt::write(&mut text, args);
        let buf = unsafe { &mut *ptr::addr_of_mut!(DRAWN_TEXT_BUFFER) };
        // TODO handle longer text
        let mut text_buf = [0u8; 11];
        text_buf
            .iter_mut()
            .zip(text.bytes())
            .for_each(|(d, s)| *d = s);
        buf.push(Text {
            x: topleft.x,
            y: topleft.y,
            color,
            length: text.len().min(text_buf.len()) as u8,
            text: text_buf,
        });
    }

    #[doc(hidden)]
    pub fn update() {
        {
            let slice = unsafe { &mut *ptr::addr_of_mut!(TEXT_BUFFER) }.as_bytes();
            write_system_state(
                super::SystemState::DebugTextPointer,
                slice.as_ptr() as u32 as f64,
            );
            write_system_state(
                super::SystemState::DebugTextLength,
                slice.len() as u32 as f64,
            );
        }
        {
            let slice = unsafe { &mut *ptr::addr_of_mut!(LINE_BUFFER) }.as_slice();
            write_system_state(
                super::SystemState::DebugLinesPointer,
                slice.as_ptr() as u32 as f64,
            );
            write_system_state(
                super::SystemState::DebugLinesLength,
                slice.len() as u32 as f64,
            );
        }
        {
            let slice = unsafe { &mut *ptr::addr_of_mut!(DRAWN_TEXT_BUFFER) }.as_slice();
            write_system_state(
                super::SystemState::DrawnTextPointer,
                slice.as_ptr() as u32 as f64,
            );
            write_system_state(
                super::SystemState::DrawnTextLength,
                slice.len() as u32 as f64,
            );
        }
    }

    #[doc(hidden)]
    pub fn reset() {
        unsafe {
            TEXT_BUFFER.clear();
            LINE_BUFFER.clear();
            DRAWN_TEXT_BUFFER.clear();
        }
    }
}

mod deprecated {
    use super::api::*;
    use super::sys::write_system_state;
    use super::SystemState;

    /// TODO Remove this.
    #[deprecated]
    pub fn aim_gun(index: usize, heading: f64) {
        aim(index, heading);
    }

    /// TODO Remove this.
    #[deprecated]
    pub fn fire_gun(index: usize) {
        fire(index);
    }

    /// TODO Remove this.
    #[deprecated]
    pub fn launch_missile(index: usize, _unused: f64) {
        use super::Class::*;
        let state_index = match (class(), index) {
            (Fighter, 0) => SystemState::Fire1,

            (Frigate, 0) => SystemState::Fire3,

            (Cruiser, 0) => SystemState::Fire1,
            (Cruiser, 1) => SystemState::Fire2,
            (Cruiser, 2) => SystemState::Fire3,

            _ => return,
        };
        write_system_state(state_index, 1.0);
    }

    /// TODO Remove this.
    #[deprecated]
    pub fn orders() -> f64 {
        0.0
    }
}

/// All APIs.
pub mod prelude {
    #[doc(inline)]
    pub use super::api::*;
    #[doc(inline)]
    pub use super::dbg::*;
    #[doc(hidden)]
    pub use super::deprecated::*;
    #[doc(inline)]
    pub use super::math::*;
    #[doc(inline)]
    pub use super::rng::*;
    #[doc(inline)]
    pub use super::vec::*;
    #[doc(inline)]
    pub use super::{Ability, Class, EcmMode, Message};
    #[doc(inline)]
    pub use crate::{debug, draw_text};

    pub use byteorder;
    pub use maths_rs;
    pub use oorandom;
}