aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/boarding.rs
blob: c8f586b59fbb059001cd9a437f7ad83eb07f72b1 (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
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
use super::{
    component_cockpit, control_device_provider_value,
    projectile::{projectile_terrain_hit, projectile_unit_hit, unit_sphere},
    starting_cockpit, Engine, EngineError, MissionControlDeviceTableState,
    MissionControlDeviceTableStatus, StartingCockpit, SurfaceQuery, TransformState,
};
use crate::player_motion::FLOOR_CLEARANCE;
use fparkan_world::{
    handle_by_original_id, identity_metadata, set_transform, transform_state, ObjectHandle,
    OriginalObjectId,
};

pub(super) const WARBOT_CLASS: u32 = 0x0100_8000;
pub mod bunker;
mod remote_control;
pub use remote_control::{
    can_control_warbot_remotely, control_warbot_remotely, remote_automatic_weapons,
    remote_warbot_control, RemoteWarbotControl,
};

/// Ownership and cockpit changes from one Enter command.
pub struct VehicleEntry {
    /// Original ID of the neutral machine transferred to the player's clan.
    pub captured: Option<OriginalObjectId>,
    /// New player cockpit if the machine supports boarding.
    pub cockpit: Option<StartingCockpit>,
}

impl VehicleEntry {
    /// Captures that leave the player outside the machine receive a spoken acknowledgement.
    pub fn capture_notice(&self) -> Option<crate::MissionNotice> {
        (self.captured.is_some() && self.cockpit.is_none())
            .then_some(crate::MissionNotice::VehicleCaptured)
    }
}

#[derive(Clone, Copy)]
pub(super) struct Boarding {
    pub(super) cockpit: StartingCockpit,
    pub(super) hero: StartingCockpit,
    pub(super) remote: Option<RemoteWarbotControl>,
    pub(super) turret: Option<crate::TurretAim>,
    pub(super) can_fly: bool,
    pub(super) ground: Option<crate::ground_support::GroundSupport>,
    pub(super) on_building_floor: bool,
    pub(super) flight_velocity: [f32; 3],
}

impl Boarding {
    pub(super) fn controls_chassis(self) -> bool {
        self.turret.is_none() && self.remote != Some(RemoteWarbotControl::Autopilot)
    }

    pub(super) fn controls_weapons(self) -> bool {
        self.remote
            .is_none_or(|mode| mode == RemoteWarbotControl::Manual)
    }
}

/// The vehicle cockpit while the player is aboard.
#[must_use]
pub fn player_vehicle(engine: &Engine) -> Option<StartingCockpit> {
    Some(engine.loaded.as_ref()?.boarding.as_ref()?.cockpit)
}

/// Selects an allied vehicle for boarding or a mobile command link.
pub fn select_boarding_target(
    engine: &Engine,
    hero: StartingCockpit,
    segment: [[f32; 3]; 2],
) -> Option<ObjectHandle> {
    let target = projectile_unit_hit(engine, hero.handle, segment)?;
    let owner = identity_metadata(&engine.world, hero.handle)
        .ok()?
        .owner_id?;
    let mission = engine.loaded.as_ref()?;
    // shortcut: use the cockpit sight ray until the original selection ranking is recovered.
    if projectile_terrain_hit(&mission.terrain, segment)
        .ok()?
        .is_some_and(|ground| ground <= target.fraction)
    {
        return None;
    }
    let vehicle = mission.object_drafts.iter().any(|draft| {
        matches!(
            draft.unit_dat_header_flags,
            Some(WARBOT_CLASS | crate::mission_events::MOBILE_HQ_CLASS)
        ) && draft
            .original_id
            .and_then(|id| handle_by_original_id(&engine.world, id))
            == Some(target.handle)
    });
    (vehicle
        && identity_metadata(&engine.world, target.handle)
            .ok()?
            .owner_id
            == Some(owner))
    .then_some(target.handle)
}

/// Boards a selected ally or captures an available neutral machine.
///
/// Capturing a working warbot also boards it during the same command.
///
/// # Errors
///
/// Returns an error if the hero's world state or the ownership update fails.
pub fn enter_vehicle(
    engine: &mut Engine,
    hero: StartingCockpit,
    target: Option<ObjectHandle>,
) -> Result<VehicleEntry, EngineError> {
    if let Some(cockpit) = board_friendly_warbot(engine, target)? {
        return Ok(VehicleEntry {
            captured: None,
            cockpit: Some(cockpit),
        });
    }
    let captured = super::mission_events::capture_neutral_warbot(engine, hero)?;
    let new_ally = captured.and_then(|id| handle_by_original_id(&engine.world, id));
    let cockpit = board_friendly_warbot(engine, new_ally)?;
    Ok(VehicleEntry { captured, cockpit })
}

/// Boards the selected compatible allied warbot within 20 units in XY.
///
/// # Errors
///
/// Returns an error if the hero's world handle is stale.
pub fn board_friendly_warbot(
    engine: &mut Engine,
    target: Option<ObjectHandle>,
) -> Result<Option<StartingCockpit>, EngineError> {
    let Some(target) = target else {
        return Ok(None);
    };
    let Some(hero) = starting_cockpit(engine) else {
        return Ok(None);
    };
    let Some(mission) = &engine.loaded else {
        return Ok(None);
    };
    if mission.boarding.is_some() {
        return Ok(None);
    }
    let Some(owner) = identity_metadata(&engine.world, hero.handle)?.owner_id else {
        return Ok(None);
    };
    let hero_pose = transform_state(&engine.world, hero.handle)?;
    let hero_position = hero_pose.position.map(f32::from_bits);
    let candidate = mission
        .object_drafts
        .iter()
        .enumerate()
        .filter_map(|(index, draft)| {
            if draft.unit_dat_header_flags != Some(WARBOT_CLASS) {
                return None;
            }
            let handle = handle_by_original_id(&engine.world, draft.original_id?)?;
            if handle != target
                || identity_metadata(&engine.world, handle).ok()?.owner_id != Some(owner)
            {
                return None;
            }
            let table = mission
                .control_device_tables
                .iter()
                .find(|table| table.handle == handle)?;
            if !has_working_pilot_control(table) {
                return None;
            }
            let state = transform_state(&engine.world, handle).ok()?;
            vehicle_interaction_distance_sq(hero_position, state.position.map(f32::from_bits))?;
            Some((component_cockpit(mission, index, handle)?, state.position))
        })
        .next();
    let Some((cockpit, position)) = candidate else {
        return Ok(None);
    };
    set_transform(
        &mut engine.world,
        hero.handle,
        TransformState {
            position,
            ..hero_pose
        },
    )?;
    start_player_control(engine, hero, cockpit, None, None);
    Ok(Some(cockpit))
}

fn start_player_control(
    engine: &mut Engine,
    hero: StartingCockpit,
    cockpit: StartingCockpit,
    remote: Option<RemoteWarbotControl>,
    turret: Option<crate::TurretAim>,
) {
    let can_fly =
        turret.is_none() && crate::player_motion::warbot_can_fly(engine, cockpit.object_index);
    if let Some(mission) = &mut engine.loaded {
        mission.boarding = Some(Boarding {
            cockpit,
            hero,
            remote,
            turret,
            can_fly,
            ground: (turret.is_none() && !can_fly)
                .then(|| {
                    crate::ground_support::GroundSupport::prepare(
                        &mission.mission_assets,
                        cockpit.object_index,
                    )
                })
                .flatten(),
            on_building_floor: false,
            flight_velocity: [0.0; 3],
        });
        mission.player_pitch_bits = 0;
        mission.cockpit_speed = 0.0;
        mission.hero_walk_velocity = [0.0; 2];
        mission.hero_look.reset();
    }
}

pub(super) fn vehicle_interaction_distance_sq(
    [hero_x, hero_y, _]: [f32; 3],
    [x, y, _]: [f32; 3],
) -> Option<f64> {
    // iron3d+0x7240b narrows the X delta to f32 before comparing the
    // horizontal length without storing it back to f32.
    let dx = f64::from(x - hero_x);
    let dy = f64::from(y) - f64::from(hero_y);
    let distance_sq = dx * dx + dy * dy;
    (distance_sq < 20.0 * 20.0).then_some(distance_sq)
}

#[cfg(test)]
mod tests {
    #[test]
    fn vehicle_interaction_ignores_height_and_excludes_the_horizontal_boundary() {
        use super::vehicle_interaction_distance_sq;

        let hero = [0.0; 3];
        assert!(vehicle_interaction_distance_sq(hero, [12.0, 15.99, 1_000.0]).is_some());
        assert!(vehicle_interaction_distance_sq(hero, [19.0, 0.0, -1_000.0]).is_some());
        assert!(vehicle_interaction_distance_sq(hero, [12.0, 16.0, 0.0]).is_none());
        assert!(vehicle_interaction_distance_sq(hero, [20.0, 0.0, 0.0]).is_none());
        assert!(vehicle_interaction_distance_sq(hero, [f32::NAN, 0.0, 0.0]).is_none());
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn one_enter_captures_and_boards_the_neutral_warbot() {
        use super::{enter_vehicle, player_vehicle, starting_cockpit, OriginalObjectId};
        use crate::{
            create, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
            MissionStartupInput,
        };
        use fparkan_vfs::DirectoryVfs;
        use fparkan_world::{handle_by_original_id, set_transform, transform_state};
        use std::sync::Arc;

        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/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma".into(),
                mode: MissionMode::SingleMission,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let hero = starting_cockpit(&engine).unwrap();
        let id = OriginalObjectId(11);
        let target = handle_by_original_id(&engine.world, id).unwrap();
        let mut pose = transform_state(&engine.world, hero.handle).unwrap();
        let [x, y, z] = transform_state(&engine.world, target)
            .unwrap()
            .position
            .map(f32::from_bits);
        pose.position = [x - 15.0, y, z].map(f32::to_bits);
        set_transform(&mut engine.world, hero.handle, pose).unwrap();

        let entry = enter_vehicle(&mut engine, hero, None).unwrap();
        assert_eq!(entry.captured, Some(id));
        assert_eq!(entry.cockpit.unwrap().handle, target);
        assert_eq!(entry.capture_notice(), None);
        assert_eq!(player_vehicle(&engine), entry.cockpit);
    }
}

fn has_working_pilot_control(table: &MissionControlDeviceTableState) -> bool {
    let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
        return false;
    };
    devices
        .iter()
        .find(|device| device.descriptor.tag == 1)
        .is_some_and(|device| {
            control_device_provider_value(table, device).is_ok_and(|value| value > 0.0)
        })
}

/// Leaves the vehicle and restores the hero's cockpit.
///
/// # Errors
///
/// Returns an error when the hero pose or terrain query cannot be read.
pub fn disembark_warbot(engine: &mut Engine) -> Result<Option<StartingCockpit>, EngineError> {
    let Some(mission) = &mut engine.loaded else {
        return Ok(None);
    };
    let Some(Boarding {
        cockpit: vehicle,
        hero,
        remote,
        turret,
        can_fly,
        on_building_floor,
        ..
    }) = mission.boarding
    else {
        return Ok(None);
    };
    let mut pose = transform_state(&engine.world, hero.handle)?;
    let vehicle_pose = remote
        .is_none()
        .then(|| transform_state(&engine.world, vehicle.handle).ok())
        .flatten();
    if let Some(vehicle_pose) = vehicle_pose {
        let [x, y, _] = vehicle_pose.position.map(f32::from_bits);
        let yaw = f32::from_bits(vehicle_pose.orientation[2]);
        let (sin, cos) = yaw.sin_cos();
        let radius = unit_sphere(&mission.mission_assets, vehicle.object_index, vehicle_pose)
            .map_or(1.0, |(_, radius)| radius);
        // shortcut: use the sides and terrain surface until the exit
        // point and collision checks are recovered.
        let mut exit = None;
        for side in [1.0, -1.0] {
            let xy = [
                x + cos * (radius + 1.0) * side,
                y + sin * (radius + 1.0) * side,
            ];
            if let Some(ground) = mission
                .terrain
                .height_at(xy)
                .map_err(EngineError::Terrain)?
            {
                exit = Some([xy[0], xy[1], ground + FLOOR_CLEARANCE]);
                break;
            }
        }
        let Some(exit) = exit else {
            return Ok(None);
        };
        pose.position = exit.map(f32::to_bits);
        pose.orientation[2] = yaw.to_bits();
        set_transform(&mut engine.world, hero.handle, pose)?;
    } else if remote.is_none() && !can_fly && !on_building_floor {
        // The passenger still has the destroyed chassis's root height.
        let [x, y, _] = pose.position.map(f32::from_bits);
        if let Some(ground) = mission
            .terrain
            .height_at([x, y])
            .map_err(EngineError::Terrain)?
        {
            pose.position[2] = (ground + FLOOR_CLEARANCE).to_bits();
            set_transform(&mut engine.world, hero.handle, pose)?;
        }
    }
    mission.boarding = None;
    mission.player_pitch_bits = 0;
    mission.cockpit_speed = 0.0;
    mission.hero_walk_velocity = [0.0; 2];
    if turret.is_some() {
        if let Some(vfs) = &engine.services.vfs {
            mission.hero_look = crate::hero_look::HeroLook::load(vfs.as_ref());
        }
    }
    mission.hero_look.reset();
    Ok(Some(hero))
}

pub(super) fn move_passenger(
    engine: &mut Engine,
    cockpit: StartingCockpit,
    vehicle_pose: TransformState,
) -> Option<(ObjectHandle, TransformState)> {
    let boarding = engine.loaded.as_ref()?.boarding.as_ref()?;
    if boarding.remote.is_some() || boarding.cockpit.handle != cockpit.handle {
        return None;
    }
    let hero = boarding.hero;
    let previous = transform_state(&engine.world, hero.handle).ok()?;
    let pose = TransformState {
        position: vehicle_pose.position,
        ..previous
    };
    set_transform(&mut engine.world, hero.handle, pose).ok()?;
    Some((hero.handle, previous))
}