aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/boarding/remote_control.rs
blob: 1a881a5d1bd07460823753484927243b8bcdbc81 (plain) (blame)
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
//! The command-post link to a friendly warbot's cockpit.

use super::{has_working_pilot_control, start_player_control};
use crate::{
    component_cockpit,
    strategic_roster::warbot_rows,
    strategic_view::{command_post, CommandPost},
    Engine, PlayerWeapons, StartingCockpit,
};
use fparkan_world::{identity_metadata, ObjectHandle};

/// Which systems the player operates from the command post.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RemoteWarbotControl {
    /// The player pilots the chassis and fires the weapons.
    Manual,
    /// The player drives while the automatic gunner aims and fires.
    AutoGunner,
    /// The player watches while the autonomous controller drives and fires.
    Autopilot,
}

fn remote_cockpit(
    engine: &Engine,
    hero: StartingCockpit,
    target: ObjectHandle,
) -> Option<StartingCockpit> {
    let mission = engine.loaded.as_ref()?;
    if mission.boarding.is_some()
        || !matches!(command_post(engine, hero), Some(CommandPost::Bunker(_)))
        || !warbot_rows(engine, hero)
            .iter()
            .any(|row| row.handle == target && row.selectable)
        || mission
            .unit_patrol
            .as_ref()
            .is_some_and(|patrol| patrol.is_leaving_factory(target))
    {
        return None;
    }
    let table = mission
        .control_device_tables
        .iter()
        .find(|table| table.handle == target)?;
    if !has_working_pilot_control(table) {
        return None;
    }
    let id = identity_metadata(&engine.world, target).ok()?.original_id?;
    component_cockpit(mission, id.0 as usize, target)
}

/// Whether the selected friendly warbot has a usable manual-control cockpit.
#[must_use]
pub fn can_control_warbot_remotely(
    engine: &Engine,
    hero: StartingCockpit,
    target: ObjectHandle,
) -> bool {
    remote_cockpit(engine, hero, target).is_some()
}

/// Opens a warbot cockpit from the bunker in the chosen control mode.
pub fn control_warbot_remotely(
    engine: &mut Engine,
    hero: StartingCockpit,
    target: ObjectHandle,
    mode: RemoteWarbotControl,
) -> Option<StartingCockpit> {
    let cockpit = remote_cockpit(engine, hero, target)?;
    if let Some(patrol) = engine
        .loaded
        .as_mut()?
        .unit_patrol
        .as_mut()
        .filter(|_| mode == RemoteWarbotControl::Manual)
    {
        patrol.release_orders_for_manual_control(target);
    }
    start_player_control(engine, hero, cockpit, Some(mode), None);
    Some(cockpit)
}

/// The active control mode of a warbot linked to the command post.
#[must_use]
pub fn remote_warbot_control(engine: &Engine) -> Option<RemoteWarbotControl> {
    let boarding = engine.loaded.as_ref()?.boarding?;
    boarding
        .turret
        .is_none()
        .then_some(boarding.remote)
        .flatten()
}

/// The active autonomous weapons' ammunition, charge and firing phases.
#[must_use]
pub fn remote_automatic_weapons(engine: &Engine) -> Option<&PlayerWeapons> {
    let boarding = engine.loaded.as_ref()?.boarding?;
    if boarding.controls_weapons() {
        return None;
    }
    engine
        .autodemo_combat
        .as_ref()?
        .weapons(boarding.cockpit.handle)
}

#[cfg(test)]
pub(super) mod tests {
    use super::*;
    use crate::{
        create, disembark_warbot, frame, frame_with_player_motion, load_gameplay_mission,
        plan_player_motion, starting_cockpit, strategic_orders, AutoDemoCombatEvent,
        EngineServices, MissionMode, MissionRequest, MissionStartupInput, PlayerMotion,
    };
    use fparkan_vfs::DirectoryVfs;
    use fparkan_world::transform_state;
    use std::sync::Arc;

    pub(in crate::boarding) fn stock_fortresses() -> Engine {
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
        let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap();
        load_gameplay_mission(
            &mut engine,
            MissionRequest {
                key: "MISSIONS/Single.01/data.tma".into(),
                mode: MissionMode::SingleMission,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        engine
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_fortresses_drives_the_warbot_without_moving_the_hero() {
        let mut engine = stock_fortresses();
        let hero = starting_cockpit(&engine).unwrap();
        let actor = warbot_rows(&engine, hero)[0].handle;
        let hero_pose = transform_state(&engine.world, hero.handle).unwrap();
        let vehicle_pose = transform_state(&engine.world, actor).unwrap();
        assert!(crate::boarding::vehicle_interaction_distance_sq(
            hero_pose.position.map(f32::from_bits),
            vehicle_pose.position.map(f32::from_bits)
        )
        .is_none());
        assert!(strategic_orders::stand(&mut engine, hero, actor));
        let vehicle =
            control_warbot_remotely(&mut engine, hero, actor, RemoteWarbotControl::Manual).unwrap();
        assert_eq!(vehicle.handle, actor);
        assert_eq!(warbot_rows(&engine, hero)[0].order_label, 0x1824);
        for time in [100, 200, 300, 400, 500] {
            let motion = plan_player_motion(
                &engine,
                vehicle,
                PlayerMotion {
                    movement: [0.0, 1.0],
                    delta_seconds: 0.1,
                    ..PlayerMotion::default()
                },
            )
            .unwrap()
            .unwrap();
            frame_with_player_motion(&mut engine, time, vehicle, motion, false).unwrap();
        }
        assert_ne!(
            transform_state(&engine.world, actor).unwrap().position,
            vehicle_pose.position
        );
        assert_eq!(
            transform_state(&engine.world, hero.handle).unwrap(),
            hero_pose
        );
        assert_eq!(disembark_warbot(&mut engine).unwrap(), Some(hero));
        assert_eq!(
            transform_state(&engine.world, hero.handle).unwrap(),
            hero_pose
        );
        assert!(crate::player_vehicle(&engine).is_none());
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_fortresses_auto_gunner_uses_live_ammunition_and_retains_the_order() {
        let mut engine = stock_fortresses();
        let hero = starting_cockpit(&engine).unwrap();
        let actor = warbot_rows(&engine, hero)[0].handle;
        let initial = transform_state(&engine.world, actor).unwrap();
        assert!(strategic_orders::stand(&mut engine, hero, actor));
        assert!(
            control_warbot_remotely(&mut engine, hero, actor, RemoteWarbotControl::AutoGunner)
                .is_some()
        );
        let rounds = |engine: &Engine| -> u32 {
            remote_automatic_weapons(engine)
                .unwrap()
                .indicators()
                .filter_map(|indicator| indicator.rounds)
                .sum()
        };
        let before = rounds(&engine);
        for tick in 0..=60 * 210 {
            let result = frame(&mut engine, tick * 1000 / 60).unwrap();
            if result.autodemo_combat_events.iter().any(|event| {
                matches!(event, AutoDemoCombatEvent::Shot { shooter, .. } if *shooter == actor)
            }) {
                assert!(rounds(&engine) < before);
                assert_eq!(warbot_rows(&engine, hero)[0].order_label, 0x1827);
                assert_eq!(transform_state(&engine.world, actor).unwrap(), initial);
                assert_eq!(disembark_warbot(&mut engine).unwrap(), Some(hero));
                assert!(remote_automatic_weapons(&engine).is_none());
                return;
            }
        }
        panic!("the stock defenders never opened fire with the auto gunner active");
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_fortresses_autopilot_keeps_the_route_and_ignores_manual_drive() {
        let mut engine = stock_fortresses();
        let hero = starting_cockpit(&engine).unwrap();
        let actor = warbot_rows(&engine, hero)[0].handle;
        let hero_start = transform_state(&engine.world, hero.handle).unwrap();
        let start = transform_state(&engine.world, actor).unwrap();
        let extent = crate::satellite_contacts::landscape_extent(&engine).unwrap();
        // The left valley waypoint on the stock satellite map.
        let waypoint = [34.0, 62.0].map(|axis| axis * extent / 256.0);
        assert!(strategic_orders::follow_route(
            &mut engine,
            hero,
            actor,
            &[waypoint]
        ));
        let cockpit =
            control_warbot_remotely(&mut engine, hero, actor, RemoteWarbotControl::Autopilot)
                .unwrap();
        assert_eq!(warbot_rows(&engine, hero)[0].order_label, 0x1828);
        assert!(remote_automatic_weapons(&engine).is_some());
        for time in (0..=12_000).step_by(100) {
            assert!(plan_player_motion(
                &engine,
                cockpit,
                PlayerMotion {
                    movement: [-1.0, -1.0],
                    climb: 1.0,
                    mouse_x: 100.0,
                    mouse_y: 100.0,
                    delta_seconds: 0.1,
                    ..PlayerMotion::default()
                },
            )
            .unwrap()
            .is_none());
            frame(&mut engine, time).unwrap();
        }
        let from_waypoint = |position: [u32; 3]| {
            let [x, y, _] = position.map(f32::from_bits);
            (x - waypoint[0]).hypot(y - waypoint[1])
        };
        let current = transform_state(&engine.world, actor).unwrap();
        assert!(from_waypoint(current.position) < from_waypoint(start.position));
        assert_eq!(disembark_warbot(&mut engine).unwrap(), Some(hero));
        assert_eq!(
            transform_state(&engine.world, hero.handle).unwrap(),
            hero_start
        );
        assert_eq!(warbot_rows(&engine, hero)[0].order_label, 0x1828);
    }
}