aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/cockpit_instruments.rs
blob: 9911d52e853b3f7d9bad6a86e6c7b55f54866c4c (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
//! Live Control values used by the cockpit's unit instruments.

use crate::{
    control_device_provider_value, control_device_selector_zero,
    projectile::unit_sphere,
    projectile_parts::warbot_node_is_depleted,
    projectile_shield::{enclosing_sphere, world_sphere},
    query_control_device_table_selector,
    strategic_map_readout::{contact_readout, ContactReadout},
    weapon_pose::WeaponPoses,
    Engine, MissionControlDeviceTableStatus, MissionControlNodeProviderTableStatus,
    StartingCockpit, HERO_UNIT_CLASS,
};
use fparkan_world::{identity_metadata, transform_state, ObjectHandle};

/// Data shared by the controlled object and the selected target instruments.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InstrumentReadout {
    pub object_index: usize,
    pub object: Option<ContactReadout>,
    pub status: Option<InstrumentStatus>,
    pub energy_percent: u8,
    pub shield: Option<[u8; 6]>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstrumentStatus {
    Order(u32),
    Dangerous,
}

pub fn instrument_readout(
    engine: &Engine,
    cockpit: StartingCockpit,
    subject: ObjectHandle,
) -> Option<InstrumentReadout> {
    let identity = identity_metadata(&engine.world, subject).ok()?;
    let object = contact_readout(engine, cockpit, subject);
    let operator = identity_metadata(&engine.world, cockpit.handle).ok()?;
    let table = engine
        .loaded
        .as_ref()?
        .control_device_tables
        .iter()
        .find(|table| table.handle == subject)?;
    let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
        return None;
    };
    let status = object
        .filter(|object| object.class != HERO_UNIT_CLASS && object.class & 0x8000_0000 == 0)
        .and_then(|object| {
            if identity.owner_id == operator.owner_id {
                return object.order_label.map(InstrumentStatus::Order);
            }
            // iron3d+0x76b40 checks the operational provider and selector 6.
            let dangerous = devices.iter().enumerate().any(|(index, device)| {
                device.descriptor.tag == 2
                    && control_device_provider_value(table, device)
                        .is_ok_and(|provider| provider > 0.0)
                    && query_control_device_table_selector(table, index, 6)
                        .is_ok_and(|value| value.is_some_and(|value| value > 10_000.0))
            });
            dangerous.then_some(InstrumentStatus::Dangerous)
        });
    let batteries = devices
        .iter()
        .filter(|device| device.descriptor.tag == 19)
        .map(control_device_selector_zero);
    let ratio = battery_reading(batteries).ok()?;
    let energy_percent = (f64::from(ratio) * 100.0)
        .round_ties_even()
        .clamp(0.0, 100.0) as u8;
    let shield = (|| {
        let field = devices.iter().rfind(|device| device.factory_tag == 9)?;
        let provider = devices.iter().rfind(|device| device.factory_tag == 21)?;
        let multiplier = f32::from_bits(provider.multiplier_bits?);
        let integrity = control_device_provider_value(table, provider).ok()?;
        Some(field.class9_values_bits?.map(|bits| {
            let ratio = f32::from_bits(bits) * multiplier * integrity;
            (f64::from(ratio) * 255.0)
                .round_ties_even()
                .clamp(0.0, 255.0) as u8
        }))
    })();
    Some(InstrumentReadout {
        object_index: identity.original_id?.0 as usize,
        object,
        status,
        energy_percent,
        shield,
    })
}

/// Local sphere used by AniMesh selector 2 with the targeter's node filter.
pub fn instrument_bounds(engine: &Engine, object_index: usize) -> Option<([f32; 3], f32)> {
    let mission = engine.loaded.as_ref()?;
    let draft = mission.object_drafts.get(object_index)?;
    let poses = WeaponPoses::new(draft, &mission.mission_assets, object_index);
    enclosing_sphere(&poses.instrument_node_spheres(&mission.mission_assets, object_index))
}

/// Current MSH state by component and local node. A detached warbot part has
/// no visible state. A node with no Control provider uses its initial slot.
pub fn instrument_node_states(
    engine: &Engine,
    subject: ObjectHandle,
) -> impl Iterator<Item = ((usize, usize), Option<u32>)> + '_ {
    engine
        .loaded
        .iter()
        .filter_map(move |mission| {
            let table = mission
                .control_device_tables
                .iter()
                .find(|table| table.handle == subject)?;
            let MissionControlNodeProviderTableStatus::Available(rows) =
                &table.node_provider_status
            else {
                return None;
            };
            let draft = mission.object_drafts.get(table.original_id?.0 as usize)?;
            let warbot = draft.unit_dat_header_flags == Some(crate::boarding::WARBOT_CLASS);
            Some((rows.as_slice(), warbot))
        })
        .flat_map(|(rows, warbot)| {
            rows.iter().enumerate().map(move |(index, row)| {
                let state = if warbot && index != 0 && warbot_node_is_depleted(row) {
                    None
                } else {
                    Some(row.mesh_state.map_or(0, |state| state.visible_stage))
                };
                ((row.unit_component_index, row.source_row_index), state)
            })
        })
}

/// Places the sphere in the object's current world pose.
pub fn instrument_sphere(
    engine: &Engine,
    subject: ObjectHandle,
    object_index: usize,
    bounds: Option<([f32; 3], f32)>,
) -> Option<([f32; 3], f32)> {
    let mission = engine.loaded.as_ref()?;
    let pose = transform_state(&engine.world, subject).ok()?;
    bounds.map_or_else(
        || unit_sphere(&mission.mission_assets, object_index, pose),
        |bounds| world_sphere(bounds, pose),
    )
}

/// Targeter distance is the 3D separation of the two centers in world units.
pub fn instrument_distance(origin: [f32; 3], target: [f32; 3]) -> Option<u32> {
    let distance = origin
        .into_iter()
        .zip(target)
        .map(|(a, b)| (f64::from(a) - f64::from(b)).powi(2))
        .sum::<f64>()
        .sqrt() as f32;
    (distance.is_finite() && distance > 0.0).then(|| distance.round_ties_even() as u32)
}

fn battery_reading<E>(batteries: impl Iterator<Item = Result<f32, E>>) -> Result<f32, E> {
    let mut total = 0.0;
    // Control+0x2b410 (selector 1) returns the first negative descriptor as-is.
    for battery in batteries {
        let charge = battery?;
        if charge < 0.0 {
            return Ok(charge);
        }
        total += charge;
    }
    Ok(total)
}

#[cfg(test)]
#[test]
fn battery_reading_uses_the_native_sentinel_and_sum() {
    let reading = |values: &[f32]| battery_reading(values.iter().copied().map(Ok::<_, ()>));
    assert_eq!(reading(&[]), Ok(0.0));
    assert_eq!(reading(&[0.25, 0.5]), Ok(0.75));
    assert_eq!(reading(&[0.25, -1.0, 1.0]), Ok(-1.0));
}

#[cfg(test)]
#[test]
fn targeter_distance_includes_height_and_rounds_to_even() {
    assert_eq!(instrument_distance([0.0; 3], [3.0, 0.0, 4.0]), Some(5));
    assert_eq!(instrument_distance([0.0; 3], [0.0, 0.0, 4.5]), Some(4));
    assert_eq!(instrument_distance([0.0; 3], [0.0; 3]), None);
}

#[cfg(test)]
#[test]
#[ignore = "requires licensed corpus"]
fn licensed_targeter_bounds_match_the_original_hero_and_bunker() {
    use crate::{
        create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode,
        MissionRequest, MissionStartupInput,
    };
    use fparkan_vfs::DirectoryVfs;
    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/Single.01/data.tma".into(),
            mode: MissionMode::SingleMission,
        },
        MissionStartupInput {
            queue_time_ms: 0,
            research_creation_gate: false,
        },
        None,
    )
    .unwrap();

    // Local bounds observed on the stock start, AniMesh+0xf3b0.
    let hero = starting_cockpit(&engine).unwrap();
    for (index, expected_center, expected_radius) in [
        (
            hero.object_index,
            [-0.001875045, -0.17754595, 0.0161541],
            1.5871644,
        ),
        (0, [-0.00038418506, -0.036218945, 5.9308352], 54.111202),
    ] {
        let (center, radius) = instrument_bounds(&engine, index).unwrap();
        for (actual, expected) in center.into_iter().zip(expected_center) {
            assert!((actual - expected).abs() < 0.0001, "{center:?}");
        }
        assert!((radius - expected_radius).abs() < 0.0001, "{radius}");
    }
}