aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/boarding/bunker.rs
blob: a69a2d9376c36f9e4ed793c4b18c363deaf78414 (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
//! Manual operation of a fixed gun mount from the clan's command post.

use super::{has_working_pilot_control, start_player_control};
use crate::{
    hero_look::{turret_pitch, HeroLook},
    strategic_buildings::BuildingSection,
    strategic_view::command_post,
    Engine, MissionControlDeviceTableStatus, PlayerMotion, RemoteWarbotControl, StartingCockpit,
    TurretAim,
};
use fparkan_assets::{
    turret_elevation_row, MissionAssets, PreparedComponentControl, PreparedControlPoint,
    PreparedControlTypedRecord,
};
use fparkan_world::{identity_metadata, ObjectHandle};
use std::f32::consts::{PI, TAU};

/// The camera's projection record and its separate CPT origin and direction.
pub fn camera_binding(
    control: &PreparedComponentControl,
) -> Option<(&PreparedControlTypedRecord, [&PreparedControlPoint; 2])> {
    let record = control
        .typed_records
        .iter()
        .find(|record| record.tag == 4)?;
    let row = control
        .timeline_rows
        .get(*record.values.first()? as usize)?;
    let points = &control.point_list.as_ref()?.points;
    let origin = points.get(row.raw_parameters[0] as usize)?;
    let direction = points.get(row.raw_parameters[1] as usize)?;
    let usable = [origin, direction].into_iter().all(|point| {
        usize::try_from(point.raw_signed_field_04).is_ok_and(|node| node < control.model_node_count)
    });
    (usable && crate::has_turret_aim(control) && turret_elevation_row(control).is_some())
        .then_some((record, [origin, direction]))
}

fn camera_component(assets: &MissionAssets, object: usize) -> Option<usize> {
    assets
        .object_component_controls
        .get(object)?
        .iter()
        .position(|control| control.as_ref().and_then(camera_binding).is_some())
}

/// Prepare only the weapons mounted on the manually operated turret.
pub fn prepared_weapons(
    engine: &Engine,
) -> impl Iterator<Item = (usize, crate::PlayerWeapons)> + '_ {
    engine.loaded.iter().flat_map(|mission| {
        mission
            .object_drafts
            .iter()
            .enumerate()
            .filter_map(|(object, draft)| {
                if !BuildingSection::Bunkers.matches(draft.unit_dat_header_flags?) {
                    return None;
                }
                let turret = camera_component(&mission.mission_assets, object)?;
                let controls = mission
                    .mission_assets
                    .object_component_controls
                    .get(object)?;
                let tree = fparkan_prototype::unit_component_tree(&draft.unit_components).ok()?;
                let weapons = crate::player_weapon::prepare_component_weapons(
                    tree.iter().enumerate().filter_map(|(component, node)| {
                        (component == turret || node.parent_index == Some(turret))
                            .then(|| Some((component, controls.get(component)?.as_ref()?)))
                            .flatten()
                    }),
                );
                (!weapons.weapons().is_empty()).then_some((object, weapons))
            })
    })
}

/// Resolves the first active tag-4 device of an operated allied bunker.
pub fn cockpit(
    engine: &Engine,
    operator: StartingCockpit,
    target: ObjectHandle,
) -> Option<StartingCockpit> {
    let mission = engine.loaded.as_ref()?;
    if mission.boarding.is_some() || command_post(engine, operator).is_none() {
        return None;
    }
    let metadata = identity_metadata(&engine.world, target).ok()?;
    if metadata.owner_id?
        != identity_metadata(&engine.world, operator.handle)
            .ok()?
            .owner_id?
    {
        return None;
    }
    let object_index = metadata.original_id?.0 as usize;
    let draft = mission.object_drafts.get(object_index)?;
    if !BuildingSection::Bunkers.matches(draft.unit_dat_header_flags?) {
        return None;
    }
    let table = mission
        .control_device_tables
        .iter()
        .find(|table| table.handle == target)?;
    if table.node_provider_depletion_marked || !has_working_pilot_control(table) {
        return None;
    }
    let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
        return None;
    };
    let device = devices.iter().find(|device| device.descriptor.tag == 4)?;
    let component_index = device.factory_provenance.unit_component_index;
    let control = mission.mission_assets.object_component_controls[object_index]
        .get(component_index)?
        .as_ref()?;
    let (_, [origin, _]) = camera_binding(control)?;
    Some(StartingCockpit {
        handle: target,
        object_index,
        component_index,
        node_index: usize::try_from(origin.raw_signed_field_04).ok()?,
        node_point: origin.position,
    })
}

/// Takes over a fixed turret, leaving the operator at the command post.
pub fn enter(
    engine: &mut Engine,
    operator: StartingCockpit,
    target: ObjectHandle,
) -> Option<StartingCockpit> {
    let camera = cockpit(engine, operator, target)?;
    let look = HeroLook::load_fixed_turret(engine.services.vfs.as_ref()?.as_ref());
    let row = turret_elevation_row(component_control(engine, camera)?)?;
    // The manual elevation starts at the input channel's center.
    let aim = TurretAim {
        azimuth: 0.0,
        elevation: turret_pitch(row, 0.0, 0.5 - row.initial_blend)?,
    };
    start_player_control(
        engine,
        operator,
        camera,
        Some(RemoteWarbotControl::Manual),
        Some(aim),
    );
    let mission = engine.loaded.as_mut()?;
    mission.player_pitch_bits = aim.elevation.to_bits();
    mission.hero_look = look;
    Some(camera)
}

/// Current manual aim of a fixed turret, shared by the camera, mesh and muzzles.
pub fn aim(engine: &Engine, camera: StartingCockpit) -> Option<TurretAim> {
    let boarding = engine.loaded.as_ref()?.boarding?;
    (boarding.cockpit == camera)
        .then_some(boarding.turret)
        .flatten()
}

fn component_control(
    engine: &Engine,
    camera: StartingCockpit,
) -> Option<&PreparedComponentControl> {
    engine
        .loaded
        .as_ref()?
        .mission_assets
        .object_component_controls
        .get(camera.object_index)?
        .get(camera.component_index)?
        .as_ref()
}

pub(crate) fn advance(
    engine: &Engine,
    camera: StartingCockpit,
    input: PlayerMotion,
    mut look: HeroLook,
    aim: TurretAim,
) -> (HeroLook, TurretAim) {
    let [delta, blend] = look.advance(
        [input.mouse_x, input.mouse_y],
        f32::INFINITY,
        input.look_around,
        input.center_view,
    );
    let row = component_control(engine, camera).and_then(turret_elevation_row);
    let elevation = row
        .and_then(|row| turret_pitch(row, aim.elevation, blend))
        .unwrap_or(aim.elevation);
    (
        look,
        TurretAim {
            azimuth: (aim.azimuth + delta + PI).rem_euclid(TAU) - PI,
            elevation,
        },
    )
}

#[cfg(test)]
#[test]
#[ignore = "requires licensed corpus"]
fn stock_bunker_aims_its_mounted_weapons_without_moving_the_operator() {
    use crate::{
        disembark_warbot, frame, frame_with_player_motion, plan_player_motion, starting_cockpit,
    };
    use fparkan_world::transform_state;

    let mut engine = super::remote_control::tests::stock_fortresses();
    frame(&mut engine, 1).unwrap();
    let hero = starting_cockpit(&engine).unwrap();
    let target = match command_post(&engine, hero).unwrap() {
        crate::strategic_view::CommandPost::Bunker(handle) => handle,
        _ => panic!("the hero starts at the bunker"),
    };
    let initial_hero = transform_state(&engine.world, hero.handle).unwrap();
    let initial_bunker = transform_state(&engine.world, target).unwrap();
    let camera = enter(&mut engine, hero, target).unwrap();
    assert_eq!(camera.object_index, 0);
    assert_eq!(camera.component_index, 3);
    assert_eq!(camera.node_index, 5);
    let (_, weapons) = prepared_weapons(&engine)
        .find(|(object, _)| *object == camera.object_index)
        .unwrap();
    assert_eq!(
        weapons
            .weapons()
            .iter()
            .map(|weapon| weapon.component_index)
            .collect::<Vec<_>>(),
        [4, 5]
    );

    let initial_aim = aim(&engine, camera).unwrap();
    let step = plan_player_motion(
        &engine,
        camera,
        PlayerMotion {
            movement: [1.0, 1.0],
            mouse_x: 35.0,
            mouse_y: -35.0,
            delta_seconds: 0.02,
            ..PlayerMotion::default()
        },
    )
    .unwrap()
    .unwrap();
    frame_with_player_motion(&mut engine, 21, camera, step, false).unwrap();
    let aim = aim(&engine, camera).unwrap();
    assert!(aim.azimuth.abs() > 0.05 && (aim.elevation - initial_aim.elevation).abs() > 0.05);
    assert_eq!(
        transform_state(&engine.world, hero.handle).unwrap(),
        initial_hero
    );
    assert_eq!(
        transform_state(&engine.world, target).unwrap(),
        initial_bunker
    );
    assert_eq!(disembark_warbot(&mut engine).unwrap(), Some(hero));
    assert_eq!(
        transform_state(&engine.world, hero.handle).unwrap(),
        initial_hero
    );
}