aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/projectile.rs
blob: e2203fe2104eb047e4e2ed755539586b49343ea2 (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
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
use crate::{
    apply_loaded_mission_control_node_delta, ControlResourceAccessError, Engine, MissionAssets,
    MissionControlNodeProviderTableStatus, TerrainWorld, CONTROL_CLASS_SOURCE_BULL,
    UNIT_DAT_CONTROL_CLASS_HIGH_BIT,
};
use fparkan_assets::{AssetManager, PreparedModel};
use fparkan_msh::{
    node38_fallback_hierarchy, query_slot_segment, selected_slot, Group, Lod, NodeId,
    SegmentQueryMasks,
};
use fparkan_prototype::{resolve_prototype_all, PrototypeSource};
use fparkan_render::LegacyIron3dEulerTransform;
use fparkan_resource::{resource_name, CachedResourceRepository};
use fparkan_terrain::{FullSurfaceMask, SurfaceQuery, TerrainError};
use fparkan_vfs::Vfs;
use fparkan_world::{handle_by_original_id, request_delete, transform_state, ObjectHandle};
use std::sync::Arc;

const ANIMAL_UNIT_CLASS: u32 = 0x2000_0000;

/// Prepared visuals and travel parameters for one projectile prototype.
pub struct ProjectileAssets {
    /// Visual, materials and control profile for the single projectile mesh.
    pub assets: MissionAssets,
    /// Forward speed in world units per second.
    pub speed: f32,
    /// Maximum age on the mission clock, in milliseconds.
    pub lifetime_ms: u32,
    /// Initial provider volume of the projectile.
    pub volume: Option<f32>,
}

/// Prepares the BULL prototype referenced by a manual weapon.
pub fn load_player_projectile(
    engine: &Engine,
    archive: &str,
    name: &str,
) -> Result<ProjectileAssets, String> {
    let vfs = engine.services.vfs.as_ref().ok_or("missing resource VFS")?;
    load_projectile(vfs, archive, name)
}

pub(super) fn load_projectile(
    vfs: &Arc<dyn Vfs>,
    archive: &str,
    name: &str,
) -> Result<ProjectileAssets, String> {
    if !archive.eq_ignore_ascii_case("objects.rlb")
        || name.is_empty()
        || name.bytes().any(|byte| matches!(byte, b'/' | b'\\' | b'.'))
    {
        return Err(format!("unsupported projectile key {archive}:{name}"));
    }
    let asset_manager = AssetManager::new(CachedResourceRepository::new(vfs.clone()));
    let prototypes = resolve_prototype_all(
        asset_manager.repository(),
        vfs.as_ref(),
        &resource_name(name.as_bytes()),
    )
    .map_err(|error| error.to_string())?;
    let [prototype] = prototypes.as_slice() else {
        return Err("expected a single projectile prototype".into());
    };
    if prototype.source != PrototypeSource::ObjectsRegistry
        || prototype.source_type != Some(CONTROL_CLASS_SOURCE_BULL)
    {
        return Err("expected an objects.rlb BULL prototype".into());
    }
    let assets = asset_manager
        .prepare_mission_assets(&[0..1], &prototypes)
        .map_err(|error| error.to_string())?;
    let [controls] = assets.object_component_controls.as_slice() else {
        return Err("missing projectile component".into());
    };
    let [Some(control)] = controls.as_slice() else {
        return Err("missing projectile Control profile".into());
    };
    let speed = f32::from_bits(control.native_profile_words[7]);
    let lifetime_ms = control.native_profile_words[18];
    let volume = control.node_data.as_ref().and_then(|data| {
        let amount = data.rows.first()?.max_volume;
        (amount.is_finite() && amount > 0.0).then_some(amount)
    });
    if !speed.is_finite() || speed <= 0.0 || lifetime_ms == 0 || lifetime_ms >= 0x8000_0000 {
        return Err("invalid projectile speed or lifetime".into());
    }
    Ok(ProjectileAssets {
        assets,
        speed,
        lifetime_ms,
        volume,
    })
}

/// One in-flight projectile with a pose sampled on the mission queue clock.
#[derive(Clone, Copy)]
pub struct PlayerProjectile {
    /// World-space center of the projectile.
    pub position: [f32; 3],
    /// Unit world-space heading along local +Y.
    pub direction: [f32; 3],
    speed: f32,
    lifetime_ms: u32,
    born_ms: u32,
    updated_ms: u32,
}

impl PlayerProjectile {
    /// Starts a straight-flight projectile at a validated world point.
    pub fn new(
        position: [f32; 3],
        direction: [f32; 3],
        speed: f32,
        lifetime_ms: u32,
        clock_ms: u32,
    ) -> Option<Self> {
        let length = direction.iter().map(|axis| axis * axis).sum::<f32>().sqrt();
        if !position.iter().all(|axis| axis.is_finite())
            || !length.is_finite()
            || length <= 0.0
            || !speed.is_finite()
            || speed <= 0.0
            || lifetime_ms == 0
        {
            return None;
        }
        Some(Self {
            position,
            direction: direction.map(|axis| axis / length),
            speed,
            lifetime_ms,
            born_ms: clock_ms,
            updated_ms: clock_ms,
        })
    }

    /// Advances this projectile and returns whether it remains in flight.
    /// The callback identifies contacts with the world along the traveled segment.
    pub fn advance(
        &mut self,
        clock_ms: u32,
        mut collides: impl FnMut([[f32; 3]; 2]) -> Result<bool, TerrainError>,
    ) -> Result<bool, TerrainError> {
        let age = clock_ms.wrapping_sub(self.born_ms);
        let last_age = self.updated_ms.wrapping_sub(self.born_ms);
        let elapsed_ms = age.min(self.lifetime_ms).saturating_sub(last_age);
        if elapsed_ms != 0 {
            let distance = self.speed * (elapsed_ms as f32 * 0.001);
            let end =
                std::array::from_fn(|axis| self.position[axis] + self.direction[axis] * distance);
            if !end.iter().all(|axis| axis.is_finite()) || collides([self.position, end])? {
                return Ok(false);
            }
            self.position = end;
            self.updated_ms = clock_ms;
        }
        Ok(age < self.lifetime_ms)
    }
}

/// Tests the projectile segment against the mission terrain triangles.
pub fn projectile_terrain_hit(
    terrain: &TerrainWorld,
    [start, end]: [[f32; 3]; 2],
) -> Result<Option<f32>, TerrainError> {
    let direction = std::array::from_fn(|axis| end[axis] - start[axis]);
    // The terrain query reports the ray parameter, so this segment ends at 1.
    Ok(terrain
        .raycast(start, direction, FullSurfaceMask(0))?
        .filter(|hit| hit.distance <= 1.0)
        .map(|hit| hit.distance))
}

/// A live unit reached by a projectile, with the fraction of its travel used.
#[derive(Clone, Copy, Debug)]
pub struct ProjectileContact {
    pub handle: ObjectHandle,
    pub fraction: f32,
    /// Provider row identified by a building triangle hit.
    pub building_node: Option<u32>,
}

/// Finds the first unit or building intersected by this flight segment.
pub fn projectile_unit_hit(
    engine: &Engine,
    shooter: ObjectHandle,
    segment: [[f32; 3]; 2],
) -> Option<ProjectileContact> {
    let mission = engine.loaded.as_ref()?;
    let passenger = mission.boarding.map(|boarding| boarding.hero.handle);
    // shortcut: root MSH sphere until combat uses the per-node hull query.
    mission
        .object_drafts
        .iter()
        .enumerate()
        .filter_map(|(index, draft)| {
            let class = draft.unit_dat_header_flags?;
            let building = class & UNIT_DAT_CONTROL_CLASS_HIGH_BIT != 0;
            let animal = class == ANIMAL_UNIT_CLASS;
            if !building && !animal && class & super::autodemo::MOBILE_UNIT == 0 {
                return None;
            }
            let handle = handle_by_original_id(&engine.world, draft.original_id?)?;
            if handle == shooter || passenger == Some(handle) {
                return None;
            }
            let state = transform_state(&engine.world, handle).ok()?;
            let (center, radius) = unit_sphere(&mission.mission_assets, index, state)?;
            let sphere_fraction = segment_sphere_fraction(segment, center, radius)?;
            let (fraction, building_node) = if building {
                let (fraction, node) =
                    building_triangle_hit(&mission.mission_assets, index, state, segment)?;
                (fraction, Some(node))
            } else {
                (sphere_fraction, None)
            };
            Some(ProjectileContact {
                handle,
                fraction,
                building_node,
            })
        })
        .min_by(|a, b| a.fraction.total_cmp(&b.fraction))
}

pub(super) fn unit_sphere(
    assets: &MissionAssets,
    index: usize,
    state: fparkan_world::TransformState,
) -> Option<([f32; 3], f32)> {
    let model = &root_model(assets, index)?.validated;
    let scale = state.scale.map(f32::from_bits);
    let transform = LegacyIron3dEulerTransform {
        translation: state.position.map(f32::from_bits),
        orientation_radians: state.orientation.map(f32::from_bits),
    };
    let center = transform.try_transform_scaled_point(model.bounding_sphere_center, scale)?;
    let radius = model.bounding_sphere_radius * scale.into_iter().map(f32::abs).fold(0.0, f32::max);
    Some((center, radius))
}

fn root_model(assets: &MissionAssets, index: usize) -> Option<&PreparedModel> {
    let visual = assets.visual_by_id(*assets.visuals_for_object(index).first()?)?;
    assets.model_by_id(visual.model_id?)
}

fn building_triangle_hit(
    assets: &MissionAssets,
    index: usize,
    state: fparkan_world::TransformState,
    segment: [[f32; 3]; 2],
) -> Option<(f32, u32)> {
    let model = &root_model(assets, index)?.validated;
    let root = LegacyIron3dEulerTransform {
        translation: state.position.map(f32::from_bits),
        orientation_radians: state.orientation.map(f32::from_bits),
    }
    .try_row_major()?;
    let scale = state.scale.map(f32::from_bits);
    let mut body_segment = segment;
    for (local, point) in body_segment.iter_mut().zip(segment) {
        let [x, y, z] = [point[0] - root[3], point[1] - root[7], point[2] - root[11]];
        for i in 0..3 {
            local[i] = (root[i] * x + root[i + 4] * y + root[i + 8] * z) / scale[i];
        }
    }
    // shortcut: use root MSH fallback poses until combat shares live component transforms.
    let poses = node38_fallback_hierarchy(model)?;
    let squared_length: f32 = (0..3)
        .map(|i| (segment[1][i] - segment[0][i]).powi(2))
        .sum();
    if squared_length == 0.0 {
        return None;
    }
    poses
        .poses
        .into_iter()
        .enumerate()
        .filter_map(|(i, pose)| {
            let node = NodeId(u32::try_from(i).ok()?);
            let slot = selected_slot(model, node, Lod(0), Group(0))?;
            let mut inverse = pose;
            inverse.translation = [0.0; 3];
            for component in &mut inverse.rotation[..3] {
                *component = -*component;
            }
            let endpoints = body_segment.map(|point| {
                inverse.transform_point(std::array::from_fn(|axis| {
                    point[axis] - pose.translation[axis]
                }))
            });
            let hit =
                query_slot_segment(model, node, slot, endpoints, SegmentQueryMasks::default())
                    .ok()??;
            let body_hit = pose.transform_point(hit.position);
            let distance: f32 = (0..3)
                .map(|axis| ((body_hit[axis] - body_segment[0][axis]) * scale[axis]).powi(2))
                .sum();
            Some(((distance / squared_length).sqrt(), node.0))
        })
        .min_by(|a, b| a.0.total_cmp(&b.0))
}

/// Applies projectile damage to the contacted part of a building or unit.
pub fn apply_projectile_contact(
    engine: &mut Engine,
    contact: ProjectileContact,
    volume: f32,
) -> Result<Option<(f32, bool)>, ControlResourceAccessError> {
    let Some(key) = contact.building_node else {
        return apply_projectile_hit(engine, contact.handle, volume);
    };
    let row = engine.loaded.as_ref().and_then(|mission| {
        let table = mission
            .control_device_tables
            .iter()
            .find(|table| table.handle == contact.handle)?;
        super::control_node_provider_row(table, key).ok()
    });
    let Some(row) = row else {
        return Ok(None);
    };
    let remaining = f32::from_bits(row.current_amount_bits);
    if !volume.is_finite()
        || volume <= 0.0
        || !remaining.is_finite()
        || remaining <= 0.0
        || row.current_flags.is_some_and(|flags| flags & 0x10 != 0)
    {
        return Ok(None);
    }
    // shortcut: keep per-node damage using the projectile NDP volume while armor and splash are open.
    let updated = apply_loaded_mission_control_node_delta(engine, contact.handle, key, -volume)?;
    Ok(updated.map(|_| ((remaining - volume).max(0.0), false)))
}

pub(super) fn segment_sphere_fraction(
    [start, end]: [[f32; 3]; 2],
    center: [f32; 3],
    radius: f32,
) -> Option<f32> {
    if !radius.is_finite() || radius <= 0.0 {
        return None;
    }
    let dir: [f32; 3] = std::array::from_fn(|i| end[i] - start[i]);
    let rel: [f32; 3] = std::array::from_fn(|i| start[i] - center[i]);
    let dot = |a: [f32; 3], b: [f32; 3]| a.into_iter().zip(b).map(|(a, b)| a * b).sum::<f32>();
    let c = dot(rel, rel) - radius * radius;
    if c <= 0.0 {
        return Some(0.0);
    }
    let a = dot(dir, dir);
    let b = dot(rel, dir);
    let d = b * b - a * c;
    let fraction = (-b - d.sqrt()) / a;
    (0.0..=1.0).contains(&fraction).then_some(fraction)
}

/// Applies the first pass of combat damage to the root Control provider.
/// Returns the remaining volume and whether the world removed the unit.
pub fn apply_projectile_hit(
    engine: &mut Engine,
    handle: ObjectHandle,
    volume: f32,
) -> Result<Option<(f32, bool)>, ControlResourceAccessError> {
    let Some(remaining) = engine.loaded.as_ref().and_then(|mission| {
        let table = mission
            .control_device_tables
            .iter()
            .find(|table| table.handle == handle)?;
        let MissionControlNodeProviderTableStatus::Available(rows) = &table.node_provider_status
        else {
            return None;
        };
        Some(f32::from_bits(rows.first()?.current_amount_bits))
    }) else {
        return Ok(None);
    };
    if !volume.is_finite() || volume <= 0.0 || !remaining.is_finite() || remaining <= 0.0 {
        return Ok(None);
    }
    // shortcut: use the projectile provider volume directly, with immediate
    // removal on root depletion until native damage and death timing are wired.
    if volume >= remaining {
        let effect = super::destruction::pending_effect(engine, handle);
        request_delete(&mut engine.world, handle).map_err(ControlResourceAccessError::World)?;
        if let (Some(effect), Some(events)) = (effect, engine.destruction_effects.as_mut()) {
            events.push(effect);
        }
        return Ok(Some((0.0, true)));
    }
    apply_loaded_mission_control_node_delta(engine, handle, 0, -volume)?;
    Ok(Some((remaining - volume, false)))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_constructor_animal_takes_projectile_damage() {
        use crate::{
            create, load_gameplay_mission, starting_cockpit, EngineServices, MissionMode,
            MissionRequest, MissionStartupInput,
        };
        use fparkan_vfs::DirectoryVfs;

        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.02/data.tma".into(),
                mode: MissionMode::SingleMission,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let shooter = starting_cockpit(&engine).unwrap().handle;
        let mission = engine.loaded.as_ref().unwrap();
        let (index, draft) = mission
            .object_drafts
            .iter()
            .enumerate()
            .find(|(_, draft)| draft.unit_dat_header_flags == Some(ANIMAL_UNIT_CLASS))
            .unwrap();
        let creature = handle_by_original_id(&engine.world, draft.original_id.unwrap()).unwrap();
        let pose = transform_state(&engine.world, creature).unwrap();
        let ([x, y, z], radius) = unit_sphere(&mission.mission_assets, index, pose).unwrap();
        let shot = [[x, y, z + 2.0 * radius], [x, y, z]];
        let contact = projectile_unit_hit(&engine, shooter, shot).expect("animal contact");
        assert_eq!(contact.handle, creature);
        let table = mission
            .control_device_tables
            .iter()
            .find(|table| table.handle == creature)
            .unwrap();
        let hp = f32::from_bits(
            crate::control_node_provider_row(table, 0)
                .unwrap()
                .current_amount_bits,
        );
        assert!(hp.is_finite() && hp > 0.0);
        let remaining = hp * 0.5;
        assert_eq!(
            apply_projectile_contact(&mut engine, contact, remaining).unwrap(),
            Some((remaining, false))
        );
        assert_eq!(
            apply_projectile_contact(&mut engine, contact, remaining).unwrap(),
            Some((0.0, true))
        );
        assert!(transform_state(&engine.world, creature).is_err());
    }

    #[test]
    fn projectile_uses_queue_age_and_tests_only_the_traveled_segment() {
        let mut shot =
            PlayerProjectile::new([0.0; 3], [0.0, 2.0, 0.0], 100.0, 80, u32::MAX - 39).unwrap();
        assert!(shot
            .advance(0, |[from, to]| {
                assert_eq!(from, [0.0; 3]);
                assert!((to[1] - 4.0).abs() < 1e-6);
                Ok(false)
            })
            .unwrap());
        assert!(shot.advance(0, |_| panic!("replayed sample")).unwrap());
        assert!(!shot
            .advance(90, |[from, to]| {
                assert!((from[1] - 4.0).abs() < 1e-6);
                assert!((to[1] - 8.0).abs() < 1e-6);
                Ok(true)
            })
            .unwrap());
    }
}