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
|
use crate::{Engine, StartingCockpit};
use fparkan_assets::{
PreparedComponentControl, PreparedControlEffectRow, PreparedControlEffectSection,
PreparedControlPoint, PreparedControlTimelineRow,
};
/// A unit's selectable weapon devices, in resource order.
#[derive(Clone, Default)]
pub struct PlayerWeapons {
weapons: Vec<PlayerWeapon>,
selected: Option<usize>,
last_sample_ms: Option<u32>,
clock_ms: f64,
}
/// A manual-fire device prepared from its CTLD record and effect rows.
#[derive(Clone)]
pub struct PlayerWeapon {
/// Component containing the barrel's CPT point.
pub component_index: usize,
pub(super) control_record_index: usize,
pub(super) charge: Option<crate::mobile_budget::Charge>,
pub(super) energy_waits: u64,
pub(super) autonomous_fire_distance: f32,
/// Name of the projectile prototype.
pub projectile: String,
/// Archive named by the weapon's projectile descriptor.
pub projectile_archive: String,
/// Optional type-4 effect started by this weapon.
pub effect: Option<(String, String)>,
pub(super) effect_row: Option<(usize, usize)>,
barrels: Vec<Barrel>,
barrel_index: usize,
rounds_remaining: Option<u32>,
shot_hold_ms: f64,
reload_ms: f64,
phase: FirePhase,
phase_start_ms: f64,
phase_end_ms: f64,
}
#[derive(Clone)]
struct Barrel {
muzzle: PreparedControlPoint,
row: PreparedControlTimelineRow,
rate: f64,
blend: f64,
from_blend: f64,
}
#[derive(Clone, PartialEq)]
enum FirePhase {
Idle,
Shot,
Recover,
Finish,
Reload,
}
impl PlayerWeapons {
/// Reads the authoritative Control charge before sampling this weapon bank.
pub fn read_control_energy(&mut self, engine: &Engine, handle: crate::ObjectHandle) {
if let Some(mission) = &engine.loaded {
crate::mobile_budget::read(mission, handle, &mut self.weapons);
}
}
/// Publishes completed shots to Control before its next resource budget.
pub fn publish_control_energy(&mut self, engine: &mut Engine, handle: crate::ObjectHandle) {
if let Some(mission) = &mut engine.loaded {
crate::mobile_budget::publish(mission, handle, &mut self.weapons);
}
}
/// Returns the prepared devices in selection order.
pub fn weapons(&self) -> &[PlayerWeapon] {
&self.weapons
}
/// Samples the barrel tracks after advancing the weapon bank on this frame.
pub fn apply_firing_pose(&self, component: usize, node_times: &mut [Option<f32>]) {
for weapon in self
.weapons
.iter()
.filter(|weapon| weapon.component_index == component)
{
for (index, barrel) in weapon.barrels.iter().enumerate() {
if barrel.row.flags & 4 != 0 {
continue;
}
let Some(time) = node_times.get_mut(barrel.row.node_index) else {
continue;
};
let mut blend = barrel.blend;
if index == weapon.barrel_index
&& matches!(weapon.phase, FirePhase::Shot | FirePhase::Finish)
{
let duration = weapon.phase_end_ms - weapon.phase_start_ms;
if duration > 0.0 {
let progress =
((self.clock_ms - weapon.phase_start_ms) / duration).clamp(0.0, 1.0);
blend = barrel.from_blend + progress * (blend - barrel.from_blend);
}
}
let mut blend = blend as f32;
if barrel.row.flags & 2 != 0 {
blend = 1.0 - blend;
}
*time = Some((1.0 - blend) * barrel.row.frame_a + blend * barrel.row.frame_b);
}
}
}
/// Selects all weapons with zero, or one weapon by its one-based slot.
pub fn select(&mut self, slot: usize) {
match slot {
0 => self.selected = None,
n if n <= self.weapons.len() => self.selected = Some(n - 1),
_ => {}
}
}
/// Samples the active trigger on the queue clock and emits due shots.
/// At most one shot per weapon is produced by a single simulation sample.
pub fn fire(
&mut self,
trigger: bool,
clock_ms: u32,
) -> impl Iterator<Item = (usize, &PlayerWeapon, &PreparedControlPoint)> {
self.fire_where(clock_ms, move |_, _, _| trigger)
}
pub(super) fn fire_where(
&mut self,
clock_ms: u32,
mut trigger: impl FnMut(usize, &PlayerWeapon, &PreparedControlPoint) -> bool,
) -> impl Iterator<Item = (usize, &PlayerWeapon, &PreparedControlPoint)> {
if let Some(last) = self.last_sample_ms.replace(clock_ms) {
self.clock_ms += f64::from(clock_ms.wrapping_sub(last));
}
let now = self.clock_ms;
let selected = self.selected;
self.weapons
.iter_mut()
.enumerate()
.filter_map(move |(index, weapon)| {
let start = selected.is_none_or(|selected| selected == index)
&& trigger(index, weapon, &weapon.barrels[weapon.barrel_index].muzzle);
let barrel = weapon.sample_fire(start, now)?;
Some((index, &*weapon, &weapon.barrels[barrel].muzzle))
})
}
}
impl PlayerWeapon {
fn sample_fire(&mut self, trigger: bool, now: f64) -> Option<usize> {
let mut shot = None;
while now > self.phase_end_ms || self.phase == FirePhase::Idle {
// shortcut: leave a second overdue shot pending until the next simulation sample.
if self.phase == FirePhase::Shot && shot.is_some() {
break;
}
// Control rebases a zero-length phase to the current sample.
let start = if self.phase_start_ms == self.phase_end_ms {
now
} else {
self.phase_end_ms
};
self.phase_start_ms = start;
let barrel = &mut self.barrels[self.barrel_index];
let delay = match self.phase {
FirePhase::Idle | FirePhase::Reload => {
if !trigger || self.rounds_remaining == Some(0) {
self.phase = FirePhase::Idle;
break;
}
if self
.charge
.as_ref()
.is_some_and(|charge| !charge.can_start())
{
self.energy_waits += 1;
self.phase = FirePhase::Idle;
self.phase_start_ms = now;
self.phase_end_ms = now;
break;
}
self.phase = FirePhase::Shot;
barrel.travel_to(0.5)
}
FirePhase::Shot => {
shot = Some(self.barrel_index);
self.phase = FirePhase::Recover;
self.shot_hold_ms.max(barrel.travel_to(0.5))
}
FirePhase::Recover => {
self.phase = FirePhase::Finish;
barrel.travel_to(1.0)
}
FirePhase::Finish => {
barrel.blend = 0.0;
self.phase = FirePhase::Reload;
self.barrel_index = (self.barrel_index + 1) % self.barrels.len();
if let Some(rounds) = &mut self.rounds_remaining {
*rounds -= 1;
}
if let Some(charge) = &mut self.charge {
charge.finish_shot();
}
self.reload_ms
}
};
self.phase_end_ms = start + delay;
}
shot
}
/// Remaining shots, or `None` for an unlimited weapon.
pub fn rounds_remaining(&self) -> Option<u32> {
self.rounds_remaining
}
/// Conservative lower bound used to size the projectile draw pool.
pub fn interval_ms(&self) -> u32 {
let fastest = self
.barrels
.iter()
.map(|barrel| 500.0 / barrel.rate)
.fold(f64::INFINITY, f64::min);
((2.0 * fastest + self.shot_hold_ms + self.reload_ms) as u32).max(1)
}
}
impl Barrel {
fn travel_to(&mut self, blend: f64) -> f64 {
let duration = (blend - self.blend).abs() * 1000.0 / self.rate;
self.from_blend = self.blend;
self.blend = blend;
duration
}
}
/// Resolves starting weapons from the hero's mounted CTLD and CPT resources.
pub fn starting_player_weapons(engine: &Engine, cockpit: StartingCockpit) -> PlayerWeapons {
let control = engine
.loaded
.as_ref()
.and_then(|mission| {
mission
.mission_assets
.object_component_controls
.get(cockpit.object_index)
})
.and_then(|controls| controls.get(cockpit.component_index))
.and_then(Option::as_ref);
PlayerWeapons {
weapons: control.map_or_else(Vec::new, |control| {
prepare_weapons(cockpit.component_index, control)
}),
..PlayerWeapons::default()
}
}
/// Resolves weapon devices for placed and prepared production warbots.
pub fn prepared_warbot_weapons(
engine: &Engine,
) -> impl Iterator<Item = (usize, PlayerWeapons)> + '_ {
engine.loaded.iter().flat_map(|mission| {
mission
.object_drafts
.iter()
.zip(&mission.mission_assets.object_component_controls)
.enumerate()
.filter(|(_, (draft, _))| {
draft.unit_dat_header_flags == Some(crate::boarding::WARBOT_CLASS)
})
.map(|(index, (_, controls))| (index, prepare_unit_weapons(controls)))
})
}
fn prepare_weapons(
component_index: usize,
control: &PreparedComponentControl,
) -> Vec<PlayerWeapon> {
let Some(points) = &control.point_list else {
return Vec::new();
};
control
.typed_records
.iter()
.enumerate()
.filter(|(_, record)| record.tag == 2)
.filter_map(|(control_record_index, record)| {
let projectile_archive =
crate::fixed_words_ascii_c_string(&record.fixed_words[27..35])?;
let projectile = crate::fixed_words_ascii_c_string(&record.fixed_words[35..43])?;
if projectile_archive.is_empty() || projectile.is_empty() {
return None;
}
let mut firing_rows = record
.values
.iter()
.filter_map(|&index| control.timeline_rows.get(index as usize))
.filter(|row| row.flags & 0x40 == 0);
let row = firing_rows.next()?;
let barrels = std::iter::once(row)
.chain(firing_rows)
.map(|row| {
let muzzle = points.points.get(row.raw_parameters[1] as usize)?;
let rate = f32::from_bits(row.raw_parameters[2]);
if muzzle.raw_signed_field_04 < 0
|| (muzzle.raw_signed_field_08 != -1
&& muzzle.raw_signed_field_04 != muzzle.raw_signed_field_08)
|| !rate.is_finite()
|| rate <= 0.0
|| row.flags & 1 != 0
|| !(0.0..=1.0).contains(&row.initial_blend)
{
return None;
}
Some(Barrel {
muzzle: muzzle.clone(),
row: *row,
rate: f64::from(rate),
blend: f64::from(row.initial_blend),
from_blend: f64::from(row.initial_blend),
})
})
.collect::<Option<Vec<_>>>()?;
let reload_ms = f64::from(f32::from_bits(record.fixed_words[14]));
let shot_hold_ms = f64::from(f32::from_bits(record.fixed_words[15]));
if ![reload_ms, shot_hold_ms]
.into_iter()
.all(|ms| ms.is_finite() && ms >= 0.0)
{
return None;
}
let rounds = f32::from_bits(record.fixed_words[11]).round_ties_even();
let rounds_remaining = if rounds == -1.0 {
None
} else if (0.0..2_147_483_648.0).contains(&rounds) {
Some(rounds as u32)
} else {
return None;
};
let effect_row = firing_effect_row(control, row);
let effect = effect_row.and_then(|row| {
Some((
crate::bounded_ascii_c_string(&row.resource.archive)?,
crate::bounded_ascii_c_string(&row.resource.name)?,
))
});
Some(PlayerWeapon {
component_index,
control_record_index,
charge: None,
energy_waits: 0,
autonomous_fire_distance: f32::from_bits(record.fixed_words[19]),
projectile,
projectile_archive,
effect,
effect_row: effect_row.map(|row| (row.table_index, row.row_index)),
barrels,
barrel_index: 0,
rounds_remaining,
shot_hold_ms,
reload_ms,
phase: FirePhase::Idle,
phase_start_ms: 0.0,
phase_end_ms: 0.0,
})
})
.collect()
}
fn firing_effect_row<'a>(
control: &'a PreparedComponentControl,
muzzle: &PreparedControlTimelineRow,
) -> Option<&'a PreparedControlEffectRow> {
let PreparedControlEffectSection::Parsed(rows) = &control.effect_section else {
return None;
};
let group = control.initial_effect_group?;
if let Some(&(_, _, selector)) = control
.node_effect_links
.iter()
.find(|&&(table, node, _)| table == group && node as usize == muzzle.node_index)
{
rows.iter()
.find(|row| row.opcode == 4 && row.table_index == group && row.selector == selector)
} else {
// Separate gun meshes can have one firing record and an effect whose
// first control point is the same muzzle. Ambiguous rows stay unresolved.
if control
.typed_records
.iter()
.filter(|record| record.tag == 2)
.nth(1)
.is_some()
{
return None;
}
let mut candidates = rows.iter().filter(|row| {
row.opcode == 4
&& row.table_index == group
&& row.raw_condition == [0; 3]
&& row.point_offsets[0] == muzzle.raw_parameters[1]
});
let row = candidates.next()?;
if candidates.next().is_some() {
return None;
}
Some(row)
}
}
pub(super) fn prepare_unit_weapons(controls: &[Option<PreparedComponentControl>]) -> PlayerWeapons {
PlayerWeapons {
weapons: controls
.iter()
.enumerate()
.filter_map(|(index, control)| Some((index, control.as_ref()?)))
.flat_map(|(index, control)| prepare_weapons(index, control))
.collect(),
..PlayerWeapons::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shot_finishes_after_trigger_release_and_spends_ammo_and_charge() {
let mut weapons = PlayerWeapons {
weapons: vec![PlayerWeapon {
component_index: 0,
control_record_index: 0,
charge: None,
energy_waits: 0,
autonomous_fire_distance: 0.0,
projectile: String::from("test"),
projectile_archive: String::from("test.rlb"),
effect: None,
effect_row: None,
barrels: vec![Barrel {
muzzle: PreparedControlPoint {
raw_flags: 0,
raw_signed_field_04: 0,
raw_signed_field_08: 0,
position: [0.0; 3],
direction: [0.0, 1.0, 0.0],
name: [0; 32],
},
row: PreparedControlTimelineRow {
row_index: 0,
node_index: 0,
frame_a: 4.0,
frame_b: 8.0,
initial_blend: 0.0,
raw_parameters: [0; 4],
flags: 0,
},
rate: 50.0,
blend: 0.0,
from_blend: 0.0,
}],
barrel_index: 0,
rounds_remaining: Some(1),
shot_hold_ms: 0.0,
reload_ms: 30.0,
phase: FirePhase::Idle,
phase_start_ms: 0.0,
phase_end_ms: 0.0,
}],
..PlayerWeapons::default()
};
weapons.weapons[0].charge = Some(crate::mobile_budget::Charge {
capacity: 10.0,
cost: 4.0,
amount: 8.0,
});
let mut node_times = [None];
assert!(weapons.fire(true, 0).next().is_none());
assert!(weapons.fire(false, 5).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(5.0)]);
assert!(weapons.fire(false, 10).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(6.0)]);
assert_eq!(weapons.fire(false, 11).next().unwrap().0, 0);
assert!(weapons.fire(false, 16).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(7.0)]);
assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(1));
assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 8.0);
assert!(weapons.fire(false, 22).next().is_none());
weapons.apply_firing_pose(0, &mut node_times);
assert_eq!(node_times, [Some(4.0)]);
assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(0));
assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 4.0);
assert!(weapons.fire(true, 100).next().is_none());
weapons.weapons[0].rounds_remaining = None;
weapons.weapons[0].charge.as_mut().unwrap().amount = 0.0;
assert!(weapons.fire(true, 150).next().is_none());
assert!(weapons.weapons[0].energy_waits > 0);
weapons.weapons[0].charge.as_mut().unwrap().amount = 4.0;
assert!(weapons.fire(true, 10_000).next().is_none());
assert!(weapons.fire(true, 10_011).next().is_some());
}
}
|