aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime/src/mobile_budget.rs
blob: 6f7787259ae8065fc47f6da1213f90ff33826444 (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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Mobile Control device budgets and weapon charge snapshots.

use crate::{
    checked_control_float, checked_control_product, checked_control_ratio, checked_control_sum,
    control_budget_device, control_device_budget_active_provider_value,
    control_device_budget_coefficient, control_device_budget_descriptor_float,
    ControlResourceAccessError, EffectiveControlDevice, MissionAssets,
    MissionControlDeviceTableState, MissionControlDeviceTableStatus, TransformState,
};
use fparkan_assets::{ControlDriveStates, PreparedControlDrive};
use std::collections::BTreeMap;

#[derive(Clone, Debug)]
pub(super) struct Charge {
    pub(super) capacity: f32,
    pub(super) cost: f32,
    pub(super) amount: f32,
}

impl Charge {
    pub(super) fn can_start(&self) -> bool {
        self.capacity <= 0.0 || self.cost <= self.amount
    }

    pub(super) fn finish_shot(&mut self) {
        if self.capacity > 0.0 && self.cost <= self.amount {
            self.amount -= self.cost;
        }
    }
}

/// Mobile budget steps, omitted motion inputs and energy waits, by original ID.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MobileBudgetReport {
    pub ticks: BTreeMap<u32, u64>,
    pub stubs: BTreeMap<(u32, String), u64>,
    pub weapon_waits: BTreeMap<u32, u64>,
}

impl MobileBudgetReport {
    pub(super) fn stub(&mut self, object: u32, reason: String) {
        let count = self.stubs.entry((object, reason.clone())).or_default();
        *count += 1;
        if *count == 1 {
            eprintln!("control_mobile_budget_stub object={object} reason={reason}");
        }
    }
}

fn charge_rate(
    amount: f32,
    capacity: f32,
    dt: f32,
    upkeep: f32,
    active: bool,
) -> Result<f32, ControlResourceAccessError> {
    let deficit = checked_control_sum(2, "weapon charge deficit", amount, -capacity)?;
    if active {
        checked_control_sum(
            2,
            "weapon charge and upkeep",
            deficit,
            -checked_control_product(2, "weapon upkeep interval", dt, upkeep)?,
        )
    } else {
        Ok(deficit)
    }
}

fn charge_update(
    amount: f32,
    capacity: f32,
    dt: f32,
    upkeep: f32,
    active: bool,
    allocation: f32,
) -> Result<(f32, Option<f32>), ControlResourceAccessError> {
    let rate = charge_rate(amount, capacity, dt, upkeep, active)?;
    let mut received = -checked_control_product(2, "weapon allocated charge", rate, allocation)?;
    if active {
        received = checked_control_sum(
            2,
            "weapon received minus upkeep",
            received,
            -checked_control_product(2, "weapon upkeep interval", dt, upkeep)?,
        )?;
    }
    if capacity <= 0.0 {
        return Ok((amount, None));
    }
    let amount = checked_control_sum(2, "weapon updated charge", received, amount)?;
    Ok((
        amount,
        Some(checked_control_ratio(
            "weapon charge ratio",
            amount,
            capacity,
        )?),
    ))
}

fn weapon_amount(device: &EffectiveControlDevice) -> Result<f32, ControlResourceAccessError> {
    let bits = device
        .weapon_charge_bits
        .ok_or(ControlResourceAccessError::UnsupportedField {
            factory_tag: 2,
            field: "weapon charge +0x120",
        })?;
    checked_control_float(2, "weapon charge", f32::from_bits(bits))
}

pub(super) fn weapon_rate(
    table: &MissionControlDeviceTableState,
    device: &EffectiveControlDevice,
    dt: f32,
) -> Result<f32, ControlResourceAccessError> {
    let active = control_device_budget_active_provider_value(table, device)?.is_some();
    charge_rate(
        weapon_amount(device)?,
        control_device_budget_coefficient(device, 1)?,
        dt,
        control_device_budget_descriptor_float(device, 8, "weapon upkeep")?,
        active,
    )
}

pub(super) fn weapon_update(
    table: &mut MissionControlDeviceTableState,
    index: usize,
    dt: f32,
    allocation: f32,
) -> Result<(), ControlResourceAccessError> {
    let device = control_budget_device(table, index)?;
    let active = control_device_budget_active_provider_value(table, device)?.is_some();
    let (amount, ratio) = charge_update(
        weapon_amount(device)?,
        control_device_budget_coefficient(device, 1)?,
        dt,
        control_device_budget_descriptor_float(device, 8, "weapon upkeep")?,
        active,
        allocation,
    )?;
    let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else {
        unreachable!("checked table")
    };
    devices[index].weapon_charge_bits = Some(amount.to_bits());
    if let Some(ratio) = ratio {
        devices[index].multiplier_bits = Some(ratio.to_bits());
    }
    Ok(())
}

pub(super) fn unmodeled_motion_rate() -> f32 {
    // shortcut: omit demand where the live CTL state has not been recovered.
    0.0
}

#[derive(Default)]
pub(super) struct DriveStateSelection {
    current: usize,
    destination: Option<usize>,
}

impl DriveStateSelection {
    fn advance(&mut self, states: &ControlDriveStates, velocity: [f32; 6]) -> Option<f32> {
        if let Some(destination) = states.destination(self.current, velocity) {
            self.destination = Some(destination);
        }
        if let Some(destination) = self.destination {
            let next = states.next_state(self.current, destination);
            self.destination = next
                .filter(|&next| next != destination)
                .map(|_| destination);
            if let Some(next) = next {
                self.current = next;
            }
        }
        states.factor(self.current)
    }
}

#[derive(Clone, Copy)]
pub(super) struct DriveMotion {
    local_speed: f32,
    profile_limit: f32,
    state_factor: f32,
}

impl DriveMotion {
    pub(super) fn sample(
        table: &MissionControlDeviceTableState,
        assets: &MissionAssets,
        [previous, current]: [TransformState; 2],
        frame_seconds: f32,
        can_fly: bool,
        selection: &mut DriveStateSelection,
    ) -> Option<Self> {
        let object = table.original_id?.0 as usize;
        let profile = table.owner_profile.as_ref()?;
        let control = assets
            .object_component_controls
            .get(object)?
            .get(profile.unit_component_index)?
            .as_ref()?;
        let limits = profile.original_words[6..9]
            .iter()
            .map(|&word| f32::from_bits(word));
        let profile_limit = largest_component(limits)?;
        let [dx, dy, dz] = std::array::from_fn(|axis| {
            f32::from_bits(current.position[axis]) - f32::from_bits(previous.position[axis])
        });
        let (sin, cos) = f32::from_bits(current.orientation[2]).sin_cos();
        // shortcut: use the frame's realized displacement until native motion publishes its local vector.
        let local_velocity = [
            (cos * dx + sin * dy) / frame_seconds,
            (-sin * dx + cos * dy) / frame_seconds,
            if can_fly { dz / frame_seconds } else { 0.0 },
        ];
        let local_speed = largest_component(local_velocity)?;
        let state_factor = match &control.drive {
            PreparedControlDrive::Uniform(bits) => f32::from_bits(*bits),
            PreparedControlDrive::Automatic(states) => {
                let [x, y, z] = local_velocity;
                let [roll, pitch, yaw] = std::array::from_fn(|axis| {
                    let delta = f32::from_bits(current.orientation[axis])
                        - f32::from_bits(previous.orientation[axis]);
                    use std::f32::consts::{PI, TAU};
                    ((delta + PI).rem_euclid(TAU) - PI) / frame_seconds
                });
                selection.advance(states, [x, y, z, roll, pitch, yaw])?
            }
            PreparedControlDrive::Unavailable => return None,
        };
        (profile_limit > 0.0 && state_factor.is_finite() && !state_factor.is_subnormal()).then_some(
            Self {
                local_speed,
                profile_limit,
                state_factor,
            },
        )
    }

    pub(super) fn rate(
        self,
        table: &MissionControlDeviceTableState,
        device: &EffectiveControlDevice,
        seconds: f32,
    ) -> Result<f32, ControlResourceAccessError> {
        if control_device_budget_active_provider_value(table, device)?.is_none() {
            return Ok(0.0);
        }
        self.demand(
            control_device_budget_descriptor_float(device, 8, "drive rate")?,
            seconds,
        )
    }

    fn demand(self, descriptor_rate: f32, seconds: f32) -> Result<f32, ControlResourceAccessError> {
        let fraction =
            checked_control_ratio("drive speed fraction", self.local_speed, self.profile_limit)?;
        let rate = checked_control_product(5, "drive nominal demand", fraction, descriptor_rate)?;
        let rate = checked_control_product(5, "drive state demand", rate, self.state_factor)?;
        Ok(-checked_control_product(
            5,
            "drive interval demand",
            rate,
            seconds,
        )?)
    }
}

fn largest_component(values: impl IntoIterator<Item = f32>) -> Option<f32> {
    values.into_iter().try_fold(0.0_f32, |largest, value| {
        (value.is_finite() && !value.is_subnormal()).then(|| largest.max(value.abs()))
    })
}

pub(super) fn read(
    mission: &crate::LoadedMissionState,
    handle: crate::ObjectHandle,
    weapons: &mut [crate::player_weapon::PlayerWeapon],
) {
    let table = mission
        .control_device_tables
        .iter()
        .find(|table| table.handle == handle);
    let devices = table.and_then(|table| match &table.status {
        MissionControlDeviceTableStatus::Available(devices) => Some(devices),
        _ => None,
    });
    for weapon in weapons {
        let device = devices
            .and_then(|devices| devices.iter().find(|device| matches_weapon(device, weapon)));
        if let Some(device) = device {
            weapon.rounds_remaining = device.weapon_rounds;
        }
        weapon.destroyed = device
            .and_then(|device| crate::control_node_provider_row(table?, device.key).ok())
            .is_some_and(|row| row.current_flags.is_some_and(|flags| flags & 0x10 != 0));
        weapon.charge = if !weapon.destroyed && mission.control_resources.energy_available(handle) {
            device.and_then(|device| {
                let coefficients = device.coefficient_bits?;
                let charge = Charge {
                    capacity: f32::from_bits(coefficients[1]),
                    cost: f32::from_bits(coefficients[2]),
                    amount: f32::from_bits(device.weapon_charge_bits?),
                };
                [charge.capacity, charge.cost, charge.amount]
                    .into_iter()
                    .all(|value| value.is_finite() && !value.is_subnormal())
                    .then_some(charge)
            })
        } else {
            None
        };
    }
}

fn matches_weapon(
    device: &EffectiveControlDevice,
    weapon: &crate::player_weapon::PlayerWeapon,
) -> bool {
    device.factory_tag == 2
        && device.factory_provenance.unit_component_index == weapon.component_index
        && device.factory_provenance.typed_record_index == weapon.control_record_index
}

pub(super) fn publish(
    mission: &mut crate::LoadedMissionState,
    handle: crate::ObjectHandle,
    weapons: &mut [crate::player_weapon::PlayerWeapon],
) {
    if weapons.is_empty() {
        return;
    }
    let available = mission.control_resources.energy_available(handle);
    let Some(table) = mission
        .control_device_tables
        .iter_mut()
        .find(|table| table.handle == handle)
    else {
        mission
            .control_resources
            .mobile
            .stub(handle.slot, "weapon_owner_table".into());
        return;
    };
    let object = table.original_id.map_or(handle.slot, |id| id.0);
    let waits: u64 = weapons.iter().map(|weapon| weapon.energy_waits).sum();
    let total = mission
        .control_resources
        .mobile
        .weapon_waits
        .entry(object)
        .or_default();
    let previous = *total;
    *total += waits;
    if previous == 0 && waits > 0 {
        eprintln!("weapon_energy_wait object={object} samples={waits}");
    }
    for weapon in weapons {
        weapon.energy_waits = 0;
        if weapon.destroyed {
            continue;
        }
        let device = match &mut table.status {
            MissionControlDeviceTableStatus::Available(devices) => devices
                .iter_mut()
                .find(|device| matches_weapon(device, weapon)),
            _ => None,
        };
        if let Some(device) = device {
            device.weapon_rounds = weapon.rounds_remaining;
            if let Some(charge) = &weapon.charge {
                device.weapon_charge_bits = Some(charge.amount.to_bits());
                if charge.capacity > 0.0 {
                    device.multiplier_bits = Some((charge.amount / charge.capacity).to_bits());
                }
                continue;
            }
        }
        if available {
            mission.control_resources.mobile.stub(
                object,
                format!(
                    "weapon_link_{}_{}",
                    weapon.component_index, weapon.control_record_index
                ),
            );
        }
    }
}

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

    #[test]
    fn drive_demand_uses_largest_local_axis_and_the_ctl_factor() {
        let profile_limit = largest_component([5.0, 14.0, 7.0]).unwrap();
        for (velocity, state_factor, seconds, expected) in [
            ([0.0, -7.0, 2.0], 0.8, 0.25, 0xbe80_0000),
            ([-14.0, 1.0, 2.0], 1.0, 0.5, 0xbfa0_0000),
            ([1.0, 2.0, -7.0], 1.0, 1.0, 0xbfa0_0000),
            ([0.0, -7.0, 2.0], 0.0, 0.25, 0x8000_0000),
        ] {
            let motion = DriveMotion {
                local_speed: largest_component(velocity).unwrap(),
                profile_limit,
                state_factor,
            };
            assert_eq!(motion.demand(2.5, seconds).unwrap().to_bits(), expected);
        }
    }

    #[test]
    fn native_weapon_budget_refills_disabled_devices_and_can_go_negative() {
        // GOG Control.dll +0x29a40 / +0x29a90, x87 CW 0x007f.
        for (capacity, amount, dt, upkeep, allocation, active, rate, charge, multiplier) in [
            (
                10.0, 3.0, 0.25, 4.0, 0.5, true, 0xc1000000, 0x40c00000, 0x3f19999a,
            ),
            (
                10.0, 10.0, 0.25, 4.0, 0.5, true, 0xbf800000, 0x41180000, 0x3f733333,
            ),
            (
                10.0, 3.0, 0.25, 4.0, 0.5, false, 0xc0e00000, 0x40d00000, 0x3f266666,
            ),
            (
                10.0, 3.0, 0.25, 4.0, 0.0, true, 0xc1000000, 0x40000000, 0x3e4ccccd,
            ),
            (0.0, 0.0, 0.25, 4.0, 1.0, true, 0xbf800000, 0, 0x3e800000),
            (
                10.0, 0.5, 0.25, 4.0, 0.0, true, 0xc1280000, 0xbf000000, 0xbd4ccccd,
            ),
            (
                19.81, 0.23, 0.375491, 17.258, 0.234267, true, 0xc1d07b56, 0xbe14a841, 0xbbf02203,
            ),
        ] {
            let rate_value = charge_rate(amount, capacity, dt, upkeep, active).unwrap();
            assert_eq!(rate_value.to_bits(), rate);
            let (amount, ratio) =
                charge_update(amount, capacity, dt, upkeep, active, allocation).unwrap();
            assert_eq!(amount.to_bits(), charge);
            assert_eq!(ratio.unwrap_or(0.25).to_bits(), multiplier);
        }
    }

    #[test]
    fn charge_allows_equality_and_is_spent_after_a_completed_shot() {
        let mut charge = Charge {
            capacity: 10.0,
            cost: 4.0,
            amount: 8.0,
        };
        assert!(charge.can_start());
        charge.finish_shot();
        assert!(charge.can_start());
        charge.finish_shot();
        assert!(!charge.can_start());
        let unlimited = Charge {
            capacity: 0.0,
            cost: 4.0,
            amount: 0.0,
        };
        assert!(unlimited.can_start());
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_spider_drive_uses_the_authored_gait_and_resource_budget() {
        use crate::{
            create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
            MissionStartupInput,
        };
        use fparkan_vfs::DirectoryVfs;
        use fparkan_world::OriginalObjectId;
        use std::sync::Arc;

        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
        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();
        let mission = engine.loaded.as_ref().unwrap();
        let control = mission.mission_assets.object_component_controls[58][0]
            .as_ref()
            .expect("stock 12spd1 chassis CTL");
        let PreparedControlDrive::Automatic(states) = &control.drive else {
            panic!("stock spider selects its drive state using velocity");
        };
        let mut selection = DriveStateSelection::default();
        // Consecutive 0x51c0 calls on the GOG profile, applying the first
        // queued state after each call as in 0xc317–0xc37a.
        for (forward, yaw, expected) in [
            (0.0, 0.0, &[0, 0][..]),
            (0.5, 0.0, &[0, 0]),
            (6.0, 0.0, &[15, 16, 15, 16, 15]),
            (6.0, 0.25, &[16, 15, 16, 15, 16]),
            (13.0, 0.0, &[19, 20, 21, 22, 19]),
            (0.0, 0.0, &[20, 21, 22, 0, 0, 0]),
            (-6.0, 0.0, &[17, 18, 17, 18, 17]),
            (0.0, 0.0, &[18, 0, 0, 0, 0, 0]),
            (0.0, 0.25, &[8, 9, 10, 11, 12]),
            (0.0, 0.0, &[13, 14, 0, 0, 0, 0]),
        ] {
            let velocity = [0.0, forward, 0.0, 0.0, 0.0, yaw];
            for &state in expected {
                let factor = selection.advance(states, velocity).unwrap();
                assert_eq!(selection.current, state, "{velocity:?}");
                assert_eq!(factor, if state == 0 { 0.0 } else { 1.0 });
            }
        }

        let mut first_position = None;
        let mut moving_budget = false;
        for now in (0..=40_000).step_by(100) {
            frame(&mut engine, now).unwrap();
            let mission = engine.loaded.as_ref().unwrap();
            if let Some(table) = mission.control_device_tables.iter().find(|table| {
                table.original_id == Some(OriginalObjectId(58))
                    && fparkan_world::transform_state(&engine.world, table.handle).is_ok()
            }) {
                let position = fparkan_world::transform_state(&engine.world, table.handle)
                    .unwrap()
                    .position;
                let initial = first_position.get_or_insert(position);
                let horizontal_move = position[..2] != initial[..2];
                moving_budget |=
                    horizontal_move && f32::from_bits(table.current_output_rate_5e0_bits) > 0.0;
            }
        }
        let report = &engine.loaded.as_ref().unwrap().control_resources.mobile;
        assert!(!report.stubs.contains_key(&(58, "motion_factory_5".into())));
        assert!(
            moving_budget,
            "the first released spider must spend power while walking"
        );
    }

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

        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
        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();
        engine.autodemo_combat = None;
        let mission = engine.loaded.as_ref().unwrap();
        let flyer = mission
            .control_device_tables
            .iter()
            .position(|table| table.original_id == Some(fparkan_world::OriginalObjectId(2)))
            .unwrap();
        let handle = mission.control_device_tables[flyer].handle;
        let start = fparkan_world::transform_state(&engine.world, handle)
            .unwrap()
            .position;
        let mut drive_spent = false;
        for now in (0..=6_000).step_by(100) {
            frame(&mut engine, now).unwrap();
            let mission = engine.loaded.as_ref().unwrap();
            drive_spent |=
                f32::from_bits(mission.control_device_tables[flyer].current_output_rate_5e0_bits)
                    > 0.0;
        }
        let end = fparkan_world::transform_state(&engine.world, handle)
            .unwrap()
            .position;
        assert_ne!(start, end);
        let stubs = &engine
            .loaded
            .as_ref()
            .unwrap()
            .control_resources
            .mobile
            .stubs;
        assert!(!stubs.contains_key(&(2, "motion_factory_5".into())));
        assert!(drive_spent, "motion must draw from the budget");

        let mut at_rest = engine.loaded.as_ref().unwrap().control_device_tables[flyer].clone();
        let MissionControlDeviceTableStatus::Available(devices) = &mut at_rest.status else {
            panic!("stock flyer has a complete Control table");
        };
        for device in devices.iter_mut().filter(|device| device.factory_tag == 2) {
            device.weapon_charge_bits = Some(0);
        }
        let mut in_motion = at_rest.clone();
        crate::control_resource_budget_pass(&mut at_rest, 0.5).unwrap();
        crate::control_resource_budget_pass_with_motion(
            &mut in_motion,
            0.5,
            Some(DriveMotion {
                local_speed: 10.0,
                profile_limit: 10.0,
                state_factor: 1.0,
            }),
        )
        .unwrap();
        let charge = |table: &MissionControlDeviceTableState| {
            let MissionControlDeviceTableStatus::Available(devices) = &table.status else {
                panic!("stock flyer has a complete Control table");
            };
            let weapon = devices
                .iter()
                .find(|device| device.factory_tag == 2)
                .unwrap();
            f32::from_bits(weapon.weapon_charge_bits.unwrap())
        };
        assert!(charge(&in_motion) < charge(&at_rest));
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_stock_lasers_wait_for_charge_and_recover_from_the_unit_budget() {
        use crate::{
            create, frame, load_gameplay_mission, EngineServices, MissionMode, MissionRequest,
            MissionStartupInput,
        };
        use fparkan_vfs::DirectoryVfs;
        use std::sync::Arc;
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap();
        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();
        // Isolate a held trigger on an unchanged stock unit; this is not mission acceptance.
        engine.autodemo_combat = None;
        let mission = engine.loaded.as_ref().unwrap();
        let handle = mission.control_device_tables[1].handle;
        let mut weapons = crate::player_weapon::prepare_unit_weapons(
            &mission.mission_assets.object_component_controls[1],
        );
        let mut idle_bank = weapons.clone();
        assert_eq!(weapons.weapons().len(), 2);
        assert!(weapons
            .weapons()
            .iter()
            .all(|weapon| weapon.rounds_remaining().is_none()));
        let mut shots = 0;
        frame(&mut engine, 0).unwrap();
        for now in (50..=120_000).step_by(50) {
            frame(&mut engine, now).unwrap();
            weapons.read_control_energy(&engine, handle);
            shots += weapons.fire(true, now).count();
            weapons.publish_control_energy(&mut engine, handle);
            idle_bank.read_control_energy(&engine, handle);
            idle_bank.publish_control_energy(&mut engine, handle);
        }
        let report = &engine.loaded.as_ref().unwrap().control_resources.mobile;
        assert!(shots > 0);
        assert!(
            report.weapon_waits[&1] > 0,
            "expected depleted laser charge"
        );
        assert!(
            !report.stubs.keys().any(|(object, reason)| *object == 1
                && (reason.starts_with("budget_") || reason.starts_with("weapon_link"))),
            "{:?}",
            report.stubs
        );
        for now in (120_050..=140_000).step_by(50) {
            frame(&mut engine, now).unwrap();
            weapons.read_control_energy(&engine, handle);
            weapons.fire(false, now).count();
            weapons.publish_control_energy(&mut engine, handle);
        }
        let mut resumed = 0;
        for now in (140_050..=142_000).step_by(50) {
            frame(&mut engine, now).unwrap();
            weapons.read_control_energy(&engine, handle);
            resumed += weapons.fire(true, now).count();
            weapons.publish_control_energy(&mut engine, handle);
        }
        assert!(resumed > 0, "laser must resume after regeneration");
    }
}