aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/projectile_shield.rs
blob: 91715cc15c6a68c9d5ffc6cd96bd265cd233e12e (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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Apply the directional Control field before hull resistance.

use crate::{
    control_device_budget_coefficient, control_device_selector_zero, fixed_words_ascii_c_string,
    projectile::{segment_point, segment_sphere_entrance, unit_sphere},
    turret_aim::hull_local_point,
    weapon_pose::WeaponPoses,
    Engine, LoadedMissionState, MissionAssets, MissionControlDeviceTableStatus, MissionObjectDraft,
    ProjectileContact,
};
use fparkan_render::LegacyIron3dEulerTransform;
use fparkan_world::{transform_state, TransformState};

/// One shield pulse triggered on the side that intercepted a projectile.
pub struct ShieldImpact {
    /// The owning object draft, which determines the effect instance pool.
    pub object_index: usize,
    /// Authored archive and resource name of the protection device.
    pub source: (String, String),
    /// World matrix centered on the shield and directed toward the contact.
    pub world_from_effect: [[f32; 4]; 4],
}

/// Sphere entrances before the first physical collision, in travel order.
pub(super) fn shield_crossings(
    engine: &Engine,
    shooter: crate::ObjectHandle,
    segment: [[f32; 3]; 2],
    stop: Option<f32>,
) -> Vec<ProjectileContact> {
    let Some(mission) = &engine.loaded else {
        return Vec::new();
    };
    let passenger = mission.boarding.map(|boarding| boarding.hero.handle);
    let mut crossings: Vec<_> = mission
        .control_device_tables
        .iter()
        .filter_map(|table| {
            if table.handle == shooter || passenger == Some(table.handle) {
                return None;
            }
            let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
                return None;
            };
            if !devices.iter().any(|device| device.factory_tag == 9) {
                return None;
            }
            let pose = transform_state(&engine.world, table.handle).ok()?;
            let index = table.original_id?.0 as usize;
            let (center, radius) = contact_sphere(mission, index, pose)?;
            let fraction = segment_sphere_entrance(segment, center, radius)?;
            stop.is_none_or(|limit| fraction < limit)
                .then(|| ProjectileContact {
                    handle: table.handle,
                    fraction,
                    position: segment_point(segment, fraction),
                    node: None,
                })
        })
        .collect();
    crossings.sort_by(|a, b| a.fraction.total_cmp(&b.fraction));
    crossings
}

fn contact_sphere(
    mission: &LoadedMissionState,
    index: usize,
    pose: TransformState,
) -> Option<([f32; 3], f32)> {
    mission
        .shield_spheres
        .get(index)
        .copied()
        .flatten()
        .and_then(|sphere| world_sphere(sphere, pose))
        .or_else(|| unit_sphere(&mission.mission_assets, index, pose))
}

pub(super) fn prepare_shield_spheres(
    assets: &MissionAssets,
    drafts: &[MissionObjectDraft],
) -> Vec<Option<([f32; 3], f32)>> {
    drafts
        .iter()
        .enumerate()
        .map(|(index, draft)| {
            let controls = assets.object_component_controls.get(index)?;
            if draft.unit_dat_header_flags != Some(crate::boarding::WARBOT_CLASS)
                || !controls
                    .iter()
                    .flatten()
                    .flat_map(|control| &control.typed_records)
                    .any(|record| record.tag == 9)
            {
                return None;
            }
            let poses = WeaponPoses::new(draft, assets, index);
            enclosing_sphere(&poses.initial_model_spheres(assets, index))
        })
        .collect()
}

/// Enables collection of transient shield pulses for the presentation layer.
pub fn collect_shield_impacts(engine: &mut Engine) {
    engine.shield_impacts = Some(Vec::new());
}

/// Drains shield pulses accumulated since the last presentation update.
pub fn take_shield_impacts(engine: &mut Engine) -> Vec<ShieldImpact> {
    engine
        .shield_impacts
        .as_mut()
        .map_or_else(Vec::new, std::mem::take)
}

/// Finds authored shield effects for placed units and prepared spawn slots.
pub fn shield_effect_sources(
    engine: &Engine,
) -> impl Iterator<Item = (usize, (String, String))> + '_ {
    engine.loaded.iter().flat_map(|mission| {
        mission
            .mission_assets
            .object_component_controls
            .iter()
            .enumerate()
            .flat_map(|(object, controls)| {
                controls.iter().flatten().flat_map(move |control| {
                    control
                        .typed_records
                        .iter()
                        .filter(|record| record.tag == 9)
                        .filter_map(move |record| {
                            Some((object, shield_effect_source(&record.fixed_words)?))
                        })
                })
            })
    })
}

fn shield_effect_source(words: &[u32; 44]) -> Option<(String, String)> {
    let archive = fixed_words_ascii_c_string(&words[27..35])?;
    let name = fixed_words_ascii_c_string(&words[35..43])?;
    (!archive.is_empty() && !name.is_empty()).then_some((archive, name))
}

pub(super) fn absorb(engine: &mut Engine, hit: ProjectileContact, volume: f32) -> f32 {
    if !volume.is_finite() || volume <= 0.0 {
        return volume;
    }
    let Some(mission) = engine.loaded.as_mut() else {
        return volume;
    };
    let Some(table_index) = mission
        .control_device_tables
        .iter()
        .position(|table| table.handle == hit.handle)
    else {
        return volume;
    };
    let Some(index) = mission.control_device_tables[table_index]
        .original_id
        .map(|id| id.0 as usize)
    else {
        return volume;
    };
    let Ok(pose) = transform_state(&engine.world, hit.handle) else {
        return volume;
    };
    let Some((center, radius)) = contact_sphere(mission, index, pose) else {
        return volume;
    };
    let shield_pose = TransformState {
        position: center.map(f32::to_bits),
        scale: [1.0_f32.to_bits(); 3],
        ..pose
    };
    let Some(sector) = hull_local_point(shield_pose, hit.position).and_then(contact_sector) else {
        return volume;
    };
    let MissionControlDeviceTableStatus::Available(devices) =
        &mut mission.control_device_tables[table_index].status
    else {
        return volume;
    };
    let Some(strength) = devices.iter().rfind(|device| device.factory_tag == 21) else {
        return volume;
    };
    let Ok(multiplier) = control_device_budget_coefficient(strength, sector) else {
        return volume;
    };
    let Some(shield) = devices.iter_mut().rfind(|device| device.factory_tag == 9) else {
        return volume;
    };
    let Ok(base) = control_device_selector_zero(shield) else {
        return volume;
    };
    let (Some(values), Some(deltas)) = (
        &mut shield.class9_values_bits,
        &mut shield.class9_deltas_bits,
    ) else {
        return volume;
    };
    let fraction = f32::from_bits(values[sector]);
    let capacity = base * fraction * multiplier;
    if !capacity.is_finite() || capacity <= 0.0 {
        return volume;
    }
    let (remaining, strength_left) = intercept(volume, capacity);
    // The projectile callback writes the remaining power through Control+0x2ca80.
    let delta = (strength_left / multiplier - base * fraction) / base;
    let updated = (fraction + delta).clamp(0.0, 1.0);
    values[sector] = updated.to_bits();
    deltas[sector] = (f32::from_bits(deltas[sector]) + (updated - fraction)).to_bits();
    if let Some(impacts) = engine.shield_impacts.as_mut() {
        if let Some(source) = shield_effect_source(&shield.descriptor.fixed_words) {
            let offset = std::array::from_fn(|axis| hit.position[axis] - center[axis]);
            impacts.push(ShieldImpact {
                object_index: index,
                source,
                world_from_effect: effect_transform(center, offset, radius),
            });
        }
    }
    remaining
}

fn world_sphere(
    (center, radius): ([f32; 3], f32),
    pose: TransformState,
) -> Option<([f32; 3], f32)> {
    let scale = pose.scale.map(f32::from_bits);
    let transform = LegacyIron3dEulerTransform {
        translation: pose.position.map(f32::from_bits),
        orientation_radians: pose.orientation.map(f32::from_bits),
    };
    Some((
        transform.try_transform_scaled_point(center, scale)?,
        radius * scale.into_iter().map(f32::abs).fold(0.0, f32::max),
    ))
}

fn enclosing_sphere(parts: &[([f32; 3], f32)]) -> Option<([f32; 3], f32)> {
    // AniMesh+0x9510 weights model centers by the authored radii. A second
    // pass then puts even the most distant model sphere inside the result.
    let weight: f32 = parts.iter().map(|(_, radius)| radius).sum();
    if weight <= 0.0 {
        return None;
    }
    let center = std::array::from_fn(|axis| {
        parts
            .iter()
            .map(|(point, radius)| point[axis] * radius)
            .sum::<f32>()
            / weight
    });
    let radius = parts
        .iter()
        .map(|(point, radius)| {
            let distance_sq: f32 = (0..3)
                .map(|axis| (center[axis] - point[axis]).powi(2))
                .sum();
            distance_sq.sqrt() + radius
        })
        .fold(0.0, f32::max);
    Some((center, radius))
}

fn effect_transform(center: [f32; 3], [x, y, z]: [f32; 3], radius: f32) -> [[f32; 4]; 4] {
    // Control+0x2c844 builds X from the incident side of the sphere, Y in the
    // horizontal plane, and Z as their cross product.
    let horizontal = x.hypot(y);
    let length = horizontal.hypot(z);
    let [nx, ny, nz] = [x / length, y / length, z / length];
    let [tx, ty] = if horizontal > 0.0 {
        [-y / horizontal, x / horizontal]
    } else {
        [1.0, 0.0]
    };
    [
        [radius * nx, radius * tx, -radius * nz * ty, center[0]],
        [radius * ny, radius * ty, radius * nz * tx, center[1]],
        [radius * nz, 0.0, radius * (nx * ty - ny * tx), center[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]
}

fn contact_sector([x, y, z]: [f32; 3]) -> Option<usize> {
    if ![x, y, z].into_iter().all(f32::is_finite) || [x, y, z] == [0.0; 3] {
        return None;
    }
    Some(if y.abs() >= x.abs().max(z.abs()) {
        usize::from(y < 0.0)
    } else if x.abs() >= z.abs() {
        2 + usize::from(x < 0.0)
    } else {
        4 + usize::from(z < 0.0)
    })
}

fn intercept(volume: f32, capacity: f32) -> (f32, f32) {
    ((volume - capacity).max(0.0), (capacity - volume).max(0.0))
}

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

    #[test]
    fn enclosing_sphere_uses_radii_to_weight_the_center() {
        let parts = [([0.0; 3], 2.0), ([6.0, 0.0, 0.0], 1.0)];
        assert_eq!(enclosing_sphere(&parts), Some(([2.0, 0.0, 0.0], 5.0)));
        assert_eq!(enclosing_sphere(&[]), None);
    }

    #[test]
    fn shield_spends_strength_before_dealing_hull_damage() {
        assert_eq!(intercept(899.0, 3040.0), (0.0, 2141.0));
        assert_eq!(intercept(220.0, 235.0), (0.0, 15.0));
        assert_eq!(intercept(235.0, 235.0), (0.0, 0.0));
        assert_eq!(intercept(260.0, 235.0), (25.0, 0.0));
        assert_eq!(intercept(260.0, 0.0), (260.0, 0.0));
        assert_eq!(contact_sector([1.0, 1.0, 1.0]), Some(0));
        assert_eq!(contact_sector([1.0, -2.0, 1.0]), Some(1));
        assert_eq!(contact_sector([-2.0, 0.2, 1.0]), Some(3));
        assert_eq!(contact_sector([-1.0, 0.2, -2.0]), Some(5));
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_autodemo_grazing_shot_can_pierce_a_field_and_miss_the_body() {
        use crate::{
            create, load_gameplay_mission, projectile::segment_sphere_fraction,
            projectile_terrain_hit, projectile_unit_hit, EngineServices, MissionMode,
            MissionRequest, MissionStartupInput, PlayerProjectile, ProjectileFlightHit,
        };
        use fparkan_vfs::DirectoryVfs;
        use fparkan_world::{handle_by_original_id, OriginalObjectId};
        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/Autodemo.00/data.tma".into(),
                mode: MissionMode::AutoDemo,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let target = handle_by_original_id(&engine.world, OriginalObjectId(0)).unwrap();
        let shooter = handle_by_original_id(&engine.world, OriginalObjectId(1)).unwrap();
        let pose = transform_state(&engine.world, target).unwrap();
        let mission = engine.loaded.as_ref().unwrap();
        let table = mission
            .control_device_tables
            .iter()
            .find(|table| table.handle == target)
            .unwrap();
        let health_before = table.node_provider_amount_bits;
        let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
            panic!("stock shield and resistance devices");
        };
        let shield = devices
            .iter()
            .rfind(|device| device.factory_tag == 9)
            .unwrap();
        let resistance = devices
            .iter()
            .rfind(|device| device.factory_tag == 21)
            .unwrap();
        let (center, radius) = contact_sphere(mission, 0, pose).unwrap();
        let (hull_center, hull_radius) = unit_sphere(&mission.mission_assets, 0, pose).unwrap();
        let (segment, crossing) = (0..2)
            .flat_map(|axis| (-10..=10).flat_map(move |a| (-10..=10).map(move |b| (axis, a, b))))
            .find_map(|(axis, a, b)| {
                let mut line = center;
                line[1 - axis] += a as f32 * radius / 10.0;
                line[2] += b as f32 * radius / 10.0;
                let mut segment = [line; 2];
                segment[0][axis] -= radius * 2.0;
                segment[1][axis] += radius * 2.0;
                segment_sphere_fraction(segment, hull_center, hull_radius)?;
                let crossings = shield_crossings(&engine, shooter, segment, None);
                let [crossing] = crossings.as_slice() else {
                    return None;
                };
                (crossing.handle == target
                    && crossing.fraction < 0.5
                    && projectile_unit_hit(&engine, shooter, segment).is_none()
                    && projectile_terrain_hit(&mission.terrain, segment)
                        .ok()?
                        .is_none())
                .then_some((segment, *crossing))
            })
            .expect(
                "a stock shot crosses the field and chassis sphere while missing all triangles",
            );
        let shield_pose = TransformState {
            position: center.map(f32::to_bits),
            scale: [1.0_f32.to_bits(); 3],
            ..pose
        };
        let sector =
            contact_sector(hull_local_point(shield_pose, crossing.position).unwrap()).unwrap();
        let capacity = control_device_selector_zero(shield).unwrap()
            * control_device_budget_coefficient(resistance, sector).unwrap();
        assert!(capacity > 0.0);
        let direction = std::array::from_fn(|i| segment[1][i] - segment[0][i]);
        let speed = direction
            .into_iter()
            .map(|axis| axis * axis)
            .sum::<f32>()
            .sqrt();
        let launch = |volume| {
            PlayerProjectile::new(segment[0], direction, speed, 2_000, 0)
                .unwrap()
                .with_volume(Some(volume))
        };
        collect_shield_impacts(&mut engine);

        let stopped = launch(capacity * 0.5)
            .advance_in_world(&mut engine, shooter, 500)
            .unwrap();
        assert!(matches!(stopped.hit, Some(ProjectileFlightHit::Shield)));
        assert!(!stopped.flying);
        assert!(stopped.segment.unwrap()[1]
            .into_iter()
            .zip(crossing.position)
            .all(|(actual, expected)| (actual - expected).abs() < 0.001));
        assert_eq!(take_shield_impacts(&mut engine).len(), 1);

        let mut flight = launch(capacity * 0.5 + 20.0);
        let pierced = flight.advance_in_world(&mut engine, shooter, 500).unwrap();
        assert!(pierced.flying && pierced.hit.is_none());
        assert!((pierced.volume.unwrap() - 20.0).abs() < 0.001);
        assert_eq!(take_shield_impacts(&mut engine).len(), 1);
        let tail = flight
            .advance_in_world(&mut engine, shooter, 1_000)
            .unwrap();
        assert!(tail.flying && tail.hit.is_none());
        assert_eq!(tail.volume, pierced.volume);
        assert!(take_shield_impacts(&mut engine).is_empty());
        let table = engine
            .loaded
            .as_ref()
            .unwrap()
            .control_device_tables
            .iter()
            .find(|table| table.handle == target)
            .unwrap();
        assert_eq!(table.node_provider_amount_bits, health_before);
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_autodemo_shield_blocks_and_then_exposes_one_sector() {
        use crate::{
            apply_projectile_impact, create, load_gameplay_mission, EngineServices, MissionMode,
            MissionRequest, MissionStartupInput, ProjectileImpact,
        };
        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/Autodemo.00/data.tma".into(),
                mode: MissionMode::AutoDemo,
            },
            MissionStartupInput {
                queue_time_ms: 0,
                research_creation_gate: false,
            },
            None,
        )
        .unwrap();
        let mission = engine.loaded.as_ref().unwrap();
        let (contact, sector, capacity, health) = mission
            .control_device_tables
            .iter()
            .find_map(|table| {
                let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
                    return None;
                };
                let shield = devices.iter().rfind(|device| device.factory_tag == 9)?;
                let strength = devices.iter().rfind(|device| device.factory_tag == 21)?;
                let pose = transform_state(&engine.world, table.handle).ok()?;
                let index = table.original_id?.0 as usize;
                let (center, _) = world_sphere(mission.shield_spheres[index]?, pose)?;
                let (hull_center, _) = unit_sphere(&mission.mission_assets, index, pose)?;
                let position = std::array::from_fn(|axis| (center[axis] + hull_center[axis]) * 0.5);
                let at = |origin: [f32; 3]| TransformState {
                    position: origin.map(f32::to_bits),
                    scale: [1.0_f32.to_bits(); 3],
                    ..pose
                };
                let sector = hull_local_point(at(center), position).and_then(contact_sector)?;
                let hull_sector =
                    hull_local_point(at(hull_center), position).and_then(contact_sector)?;
                if sector == hull_sector {
                    return None;
                }
                let capacity = control_device_selector_zero(shield).ok()?
                    * f32::from_bits(shield.class9_values_bits?[sector])
                    * control_device_budget_coefficient(strength, sector).ok()?;
                if capacity <= 0.0 {
                    return None;
                }
                let hit = ProjectileContact {
                    handle: table.handle,
                    fraction: 0.5,
                    position,
                    node: None,
                };
                Some((hit, sector, capacity, table.node_provider_amount_bits?))
            })
            .expect("stock shield whose assembled center changes the selected sector");
        // Headless combat and rendering must spend charge from the same side.
        assert_eq!(
            apply_projectile_impact(&mut engine, contact, capacity * 0.25).unwrap(),
            ProjectileImpact::ShieldAbsorbed
        );
        collect_shield_impacts(&mut engine);
        let (center, radius) = engine.loaded.as_ref().unwrap().shield_spheres[0]
            .expect("stock AutoDemo warbot enclosure");
        assert!(center[2] > 0.0 && radius > 6.0);
        assert_eq!(
            apply_projectile_impact(&mut engine, contact, capacity * 0.25).unwrap(),
            ProjectileImpact::ShieldAbsorbed
        );
        let impacts = take_shield_impacts(&mut engine);
        let [impact] = impacts.as_slice() else {
            panic!("charged sector starts one shield effect");
        };
        assert!(shield_effect_sources(&engine)
            .any(|(object, source)| object == impact.object_index && source == impact.source));
        assert!(impact
            .world_from_effect
            .into_iter()
            .flatten()
            .all(f32::is_finite));
        let table = engine
            .loaded
            .as_ref()
            .unwrap()
            .control_device_tables
            .iter()
            .find(|table| table.handle == contact.handle)
            .unwrap();
        assert_eq!(table.node_provider_amount_bits, Some(health));
        let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
            panic!("missing shield devices");
        };
        let shield = devices
            .iter()
            .rfind(|device| device.factory_tag == 9)
            .unwrap();
        let charges = shield.class9_values_bits.unwrap().map(f32::from_bits);
        let mut expected = [1.0; 6];
        expected[sector] = 0.5;
        assert!(charges
            .iter()
            .zip(expected)
            .all(|(a, b)| (a - b).abs() < 1e-6));
        assert!((absorb(&mut engine, contact, capacity * 0.5 + 20.0) - 20.0).abs() < 0.001);
        assert_eq!(take_shield_impacts(&mut engine).len(), 1);
        assert_eq!(absorb(&mut engine, contact, capacity * 0.5), capacity * 0.5);
        assert!(take_shield_impacts(&mut engine).is_empty());
    }
}