aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-14 06:19:53 +0300
committerValentin Popov <valentin@popov.link>2026-11-14 06:19:53 +0300
commit9591266ea01022c5fd6a98a6ebdca84f1961b2b5 (patch)
treeb4e44f6a232943a6b4485e205f79ff14cfb357be
parent640e0f69d9850e1c6863b48f8220930d51d068d4 (diff)
downloadfparkan-9591266ea01022c5fd6a98a6ebdca84f1961b2b5.tar.xz
fparkan-9591266ea01022c5fd6a98a6ebdca84f1961b2b5.zip
feat(game): play authored sounds on manual fire
-rw-r--r--README.md2
-rw-r--r--apps/fparkan-game/src/main.rs166
-rw-r--r--crates/fparkan-assets/src/lib.rs15
-rw-r--r--crates/fparkan-fx/src/ambient_sound.rs18
-rw-r--r--crates/fparkan-runtime/src/lib.rs26
-rw-r--r--crates/fparkan-runtime/src/player_weapon.rs196
-rw-r--r--docs/appendices/knowledge-boundaries.md4
-rw-r--r--docs/tomes/06-behavior.md23
8 files changed, 444 insertions, 6 deletions
diff --git a/README.md b/README.md
index e679a985..356b570c 100644
--- a/README.md
+++ b/README.md
@@ -48,6 +48,8 @@ cargo run --release -p fparkan-game -- `
открывается с видом из его кабины. Стрелки двигают героя вперёд, назад и
вбок. Мышь поворачивает корпус по горизонтали и наклоняет взгляд по
вертикали. `Esc` освобождает указатель, правая кнопка возвращает захват.
+Цифры выбирают орудие, `0` выбирает все. Левая кнопка запускает огонь
+с оригинальным звуком доступных орудий. Попадания ещё в работе.
Скорость шага, чувствительность и пределы угла пока приближённые.
Свободный обзор доступен через `--viewer` и служит запасной камерой для миссий
без однозначной кабины. В свободном обзоре `WASD` перемещают камеру
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 913668e8..0e4784d7 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -82,11 +82,11 @@ use fparkan_runtime::{
load_mission_static_preview, load_mission_static_preview_roots, load_mission_with_init_stubs,
loaded_mission_assets, loaded_mission_object_drafts, loaded_mission_script_bundles,
loaded_terrain, mission_object_handle, plan_player_motion, query_building_segment_world,
- simulate_mission_report, starting_cockpit, AutoDemoCamera, AutoDemoView, BasementPlacementMode,
- BuildingMeshNode, Engine, EngineError, EngineServices, FrameResult, LoadedMission,
- MissionAssets, MissionEventStop, MissionMode, MissionNotice, MissionObjectDraft,
- MissionRequest, MissionScriptInitExecution, MissionStartupInput, PlayerMotion, StartingCockpit,
- SIMULATION_COVERAGE,
+ simulate_mission_report, starting_cockpit, starting_player_weapons, AutoDemoCamera,
+ AutoDemoView, BasementPlacementMode, BuildingMeshNode, Engine, EngineError, EngineServices,
+ FrameResult, LoadedMission, MissionAssets, MissionEventStop, MissionMode, MissionNotice,
+ MissionObjectDraft, MissionRequest, MissionScriptInitExecution, MissionStartupInput,
+ PlayerMotion, PlayerWeapons, StartingCockpit, SIMULATION_COVERAGE,
};
#[cfg(test)]
use fparkan_terrain::BasementFoundationFragment;
@@ -271,6 +271,7 @@ fn run(args: &[String]) -> Result<String, String> {
preview,
environment,
audio,
+ &args.root,
(!args.viewer).then_some(engine),
demo_camera,
args.frames,
@@ -9656,6 +9657,7 @@ fn run_static_vulkan_mode(
preview: StaticPreviewScene,
environment: Option<DynamicEnvironment>,
audio: Option<audio::GameAudio>,
+ root: &Path,
mission_engine: Option<Engine>,
demo_camera: Option<AutoDemoCamera>,
target_frames: u64,
@@ -9750,6 +9752,35 @@ fn run_static_vulkan_mode(
if app.cockpit.is_some() {
app.camera_mode = "starting-cockpit";
}
+ if let Some(cockpit) = app.cockpit {
+ app.player_weapons = starting_player_weapons(engine, cockpit);
+ if app.player_weapons.weapons().is_empty() {
+ eprintln!("sim_coverage player_weapon_layout_stub=1");
+ }
+ app.player_weapon_sounds = app
+ .player_weapons
+ .weapons()
+ .iter()
+ .map(|weapon| {
+ let sound = weapon.effect.as_ref().and_then(|(archive, name)| {
+ let bytes =
+ load_resource_entry_bytes_from_root(root, archive, name).ok()?;
+ let effect = decode_fxid(bytes).ok()?;
+ effect
+ .commands()
+ .iter()
+ .find_map(Op2SoundCommand::from_command)
+ });
+ if sound.is_none() {
+ eprintln!(
+ "sim_coverage player_weapon_sound_stub=1 projectile={}",
+ weapon.projectile
+ );
+ }
+ sound
+ })
+ .collect();
+ }
eprintln!(
"{SIMULATION_COVERAGE} {}",
mission_camera_coverage(app.cockpit, app.demo_camera.is_some()),
@@ -9765,7 +9796,7 @@ fn mission_camera_coverage(cockpit: Option<StartingCockpit>, demo: bool) -> &'st
if demo {
"autodemo_camera_follow_approx=1 autodemo_camera_target_approx=1 cockpit_pose_approx=1"
} else if cockpit.is_some() {
- "player_motion_approx=1 cockpit_aim_approx=1 cockpit_pose_approx=1"
+ "player_motion_approx=1 cockpit_aim_approx=1 cockpit_pose_approx=1 player_weapon_cycle_approx=1 player_projectile_stub=1 player_weapon_fx_stub=1"
} else {
"mission_camera_stub=1"
}
@@ -9849,6 +9880,10 @@ struct StaticVulkanApp {
player_move_pressed: [bool; 4],
mouse_look: bool,
player_mouse: [f32; 2],
+ player_weapons: PlayerWeapons,
+ player_weapon_sounds: Vec<Option<Op2SoundCommand>>,
+ player_fire_held: bool,
+ player_fire_pressed: bool,
audio: Option<audio::GameAudio>,
camera_mode: &'static str,
mesh_components: usize,
@@ -9971,6 +10006,10 @@ impl StaticVulkanApp {
player_move_pressed: [false; 4],
mouse_look: false,
player_mouse: [0.0; 2],
+ player_weapons: PlayerWeapons::default(),
+ player_weapon_sounds: Vec::new(),
+ player_fire_held: false,
+ player_fire_pressed: false,
audio,
camera_mode: preview.camera_mode,
mesh_components: preview.mesh_components,
@@ -10331,6 +10370,90 @@ impl StaticVulkanApp {
)
}
+ fn update_player_fire(&mut self, clock_ms: u32) {
+ let trigger = self.player_fire_held || self.player_fire_pressed;
+ self.player_fire_pressed = false;
+ let (Some(cockpit), Some(frame)) = (self.cockpit, &self.mission_frame) else {
+ return;
+ };
+ if !trigger {
+ return;
+ }
+ let Some((_, state)) = frame
+ .snapshot
+ .transforms
+ .iter()
+ .find(|(handle, _)| *handle == cockpit.handle)
+ else {
+ return;
+ };
+ let Some(hierarchy) = self
+ .component_pose_buffers
+ .get(cockpit.object_index)
+ .and_then(|components| components.get(cockpit.component_index))
+ .and_then(Option::as_ref)
+ else {
+ return;
+ };
+ let mount = self
+ .component_mount_poses
+ .get(cockpit.object_index)
+ .and_then(|components| components.get(cockpit.component_index))
+ .copied()
+ .flatten();
+ let transform = LegacyIron3dEulerTransform {
+ translation: state.position.map(f32::from_bits),
+ orientation_radians: state.orientation.map(f32::from_bits),
+ };
+ let scale = state.scale.map(f32::from_bits);
+ for (slot, weapon) in self.player_weapons.fire(trigger, clock_ms) {
+ let pose = control_effect_owner_node_pose(
+ Some(hierarchy),
+ mount.is_some(),
+ weapon.muzzle.raw_signed_field_04 as usize,
+ );
+ let muzzle = pose.and_then(|pose| {
+ let pose = mount.map_or(pose, |mount| compose_unit_pose(mount, pose));
+ transform.try_transform_scaled_point(
+ add3(
+ pose.translation,
+ rotate_unit_vector(weapon.muzzle.position, pose.rotation),
+ ),
+ scale,
+ )
+ });
+ let Some(muzzle) = muzzle else {
+ eprintln!("sim_coverage player_weapon_pose_stub=1 slot={}", slot + 1);
+ continue;
+ };
+ eprintln!(
+ "player_shot slot={} projectile={}:{} queue_time_ms={clock_ms} muzzle={muzzle:?}",
+ slot + 1,
+ weapon.projectile_archive,
+ weapon.projectile
+ );
+ if let (Some(sound), Some(audio)) = (
+ self.player_weapon_sounds.get(slot).and_then(Option::as_ref),
+ self.audio.as_mut(),
+ ) {
+ if let Some(event) = sound.one_shot_at(muzzle) {
+ match audio.handle_sound_event(&event) {
+ Ok(()) => eprintln!(
+ "player_shot_sound slot={} resource={}:{} queue_time_ms={clock_ms}",
+ slot + 1,
+ event.archive,
+ event.name
+ ),
+ Err(error) => eprintln!(
+ "sim_coverage player_weapon_sound_stub=1 slot={} reason={error}",
+ slot + 1
+ ),
+ }
+ }
+ }
+ }
+ }
+
fn building_segment_blocked(&self, world_segment: [[f32; 3]; 2]) -> Result<bool, String> {
for binding in &self.building_collision_bindings {
if binding.selected_nodes.is_empty() {
@@ -10664,6 +10787,7 @@ impl StaticVulkanApp {
}
}
self.update_mission_camera(clock.delta_seconds, viewport)?;
+ self.update_player_fire(control_clock_ms);
refresh_dynamic_shadow_casters(
&mut self.shadow_casters,
&self.dynamic_shadow_casters,
@@ -11251,6 +11375,10 @@ impl StaticVulkanApp {
fn set_mouse_look(&mut self, active: bool) {
self.mouse_look = active;
+ if !active {
+ self.player_fire_held = false;
+ self.player_fire_pressed = false;
+ }
if let Some(window) = self.window.as_ref() {
if active {
// Relative device motion keeps the camera usable at the edge
@@ -11649,6 +11777,22 @@ impl ApplicationHandler for StaticVulkanApp {
} else if event.state == ElementState::Pressed {
self.pressed_keys.insert(code);
if self.cockpit.is_some() && !self.mission_paused && !event.repeat {
+ if let Some(slot) = [
+ KeyCode::Digit0,
+ KeyCode::Digit1,
+ KeyCode::Digit2,
+ KeyCode::Digit3,
+ KeyCode::Digit4,
+ KeyCode::Digit5,
+ KeyCode::Digit6,
+ KeyCode::Digit7,
+ KeyCode::Digit8,
+ ]
+ .iter()
+ .position(|&key| key == code)
+ {
+ self.player_weapons.select(slot);
+ }
if let Some(index) = [
KeyCode::ArrowRight,
KeyCode::ArrowLeft,
@@ -11667,6 +11811,15 @@ impl ApplicationHandler for StaticVulkanApp {
}
}
WindowEvent::MouseInput { state, button, .. } => {
+ if button == MouseButton::Left
+ && self.cockpit.is_some()
+ && self.demo_camera.is_none()
+ && self.mouse_look
+ && !self.mission_paused
+ {
+ self.player_fire_held = state == ElementState::Pressed;
+ self.player_fire_pressed |= self.player_fire_held;
+ }
if button == MouseButton::Right && self.demo_camera.is_none() {
if self.cockpit.is_none() {
self.set_mouse_look(state == ElementState::Pressed);
@@ -13260,6 +13413,7 @@ mod tests {
node_data: None,
effect_section: PreparedControlEffectSection::Absent,
initial_effect_group: None,
+ node_effect_links: Vec::new(),
point_list: None,
}
}
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs
index e8e892d8..615758bc 100644
--- a/crates/fparkan-assets/src/lib.rs
+++ b/crates/fparkan-assets/src/lib.rs
@@ -1104,6 +1104,8 @@ pub struct PreparedComponentControl {
/// Validated group selected by native Control's first effect-group
/// header word; `None` is the native no-group sentinel or an invalid index.
pub initial_effect_group: Option<usize>,
+ /// Node-to-effect links from Control opcode 14, resolved within each group.
+ pub node_effect_links: Vec<(usize, u32, u32)>,
/// Component-local points selected for parsed effect rows, when present.
pub point_list: Option<PreparedControlPointList>,
}
@@ -3950,6 +3952,7 @@ struct DecodedComponentEffectSection {
initial_effect_group: Option<usize>,
initial_group_opcodes: Option<Vec<u32>>,
typed_records: Vec<PreparedControlTypedRecord>,
+ node_effect_links: Vec<(usize, u32, u32)>,
}
fn decode_component_effect_section<F>(
@@ -3975,6 +3978,7 @@ where
initial_effect_group: None,
initial_group_opcodes: (cursor == payload.len()).then(Vec::new),
typed_records: Vec::new(),
+ node_effect_links: Vec::new(),
});
}
if typed_record_count > CONTROL_TYPED_RECORD_LIMIT {
@@ -3997,6 +4001,7 @@ where
initial_effect_group: None,
initial_group_opcodes: None,
typed_records,
+ node_effect_links: Vec::new(),
});
}
@@ -4098,6 +4103,7 @@ where
initial_effect_group: None,
initial_group_opcodes: complete.then(Vec::new),
typed_records,
+ node_effect_links: Vec::new(),
});
}
@@ -4117,6 +4123,7 @@ where
let mut initial_group_opcodes = Some(Vec::new());
let mut effect_rows = Vec::new();
+ let mut node_effect_links = Vec::new();
for table_index in 0..effect_group_count {
let row_count = usize::try_from(
control_u32_at(payload, cursor)
@@ -4143,6 +4150,11 @@ where
let row_start = rows_start + row_index * CONTROL_EFFECT_ROW_BYTES;
let row = &payload[row_start..row_start + CONTROL_EFFECT_ROW_BYTES];
let opcode = control_u32_at(row, 0x0C).expect("fixed effect row has opcode");
+ if opcode == 14 {
+ let selector = control_u32_at(row, 0x10).expect("fixed row has a selector");
+ let node = control_u32_at(row, 0x14).expect("fixed row has a node");
+ node_effect_links.push((table_index, node, selector));
+ }
if initial_effect_group == Some(table_index) {
initial_group_opcodes
.as_mut()
@@ -4190,6 +4202,7 @@ where
initial_effect_group: None,
initial_group_opcodes: None,
typed_records,
+ node_effect_links: Vec::new(),
});
}
Ok(DecodedComponentEffectSection {
@@ -4197,6 +4210,7 @@ where
initial_effect_group,
initial_group_opcodes,
typed_records,
+ node_effect_links,
})
}
@@ -4376,6 +4390,7 @@ fn decode_component_control_payload_with_opcodes(
node_data: None,
effect_section: decoded_effect.section,
initial_effect_group: decoded_effect.initial_effect_group,
+ node_effect_links: decoded_effect.node_effect_links,
point_list: None,
},
initial_group_opcodes,
diff --git a/crates/fparkan-fx/src/ambient_sound.rs b/crates/fparkan-fx/src/ambient_sound.rs
index bcc18149..c15e0637 100644
--- a/crates/fparkan-fx/src/ambient_sound.rs
+++ b/crates/fparkan-fx/src/ambient_sound.rs
@@ -89,6 +89,24 @@ impl Op2SoundCommand {
})
}
+ /// Starts a prepared one-shot at its initial authored parameters.
+ #[must_use]
+ pub fn one_shot_at(&self, position: [f32; 3]) -> Option<SoundEvent> {
+ if self.looping || !position.iter().all(|axis| axis.is_finite()) {
+ return None;
+ }
+ Some(SoundEvent {
+ archive: self.archive.clone(),
+ name: self.name.clone(),
+ position,
+ volume: 1.0,
+ min_distance: self.min_distance,
+ max_distance: self.max_distance,
+ frequency_ratio: self.frequency,
+ action: SoundAction::OneShot,
+ })
+ }
+
/// Evaluates Effect.dll's phase crossings and current source parameters.
/// `playing` comes from the audio owner, since a one-shot can finish between
/// updates. The matrix maps local command coordinates into world space.
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 883e5554..3dae4afa 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -45,6 +45,7 @@ mod autodemo;
mod mesh_collision;
mod mission_events;
mod player_motion;
+mod player_weapon;
pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoView};
pub use fparkan_assets::MissionAssets;
@@ -52,6 +53,7 @@ pub use mesh_collision::{query_building_segment_world, BuildingMeshHit, Building
use mission_events::MissionEvents;
pub use mission_events::{MissionEventStop, MissionEventTick, MissionNotice};
pub use player_motion::{plan_player_motion, PlayerMotion, PlayerMotionStep};
+pub use player_weapon::{starting_player_weapons, PlayerWeapons};
const MISSION_DECODED_PAYLOAD_CACHE_ENTRIES: usize = 256;
const MAX_MISSION_AI_RECORD_SLOTS: usize = 1_000_000;
@@ -8182,6 +8184,7 @@ mod tests {
node_data: None,
effect_section: PreparedControlEffectSection::Parsed(rows),
initial_effect_group,
+ node_effect_links: Vec::new(),
point_list: point_count.map(|count| PreparedControlPointList {
source: synthetic_resource_key(941),
points: (0..count)
@@ -8686,6 +8689,7 @@ mod tests {
node_data: None,
effect_section,
initial_effect_group: None,
+ node_effect_links: Vec::new(),
point_list: None,
}
}
@@ -17213,6 +17217,28 @@ mod tests {
},
)
.unwrap();
+ let cockpit = starting_cockpit(&engine).unwrap();
+ let weapons = starting_player_weapons(&engine, cockpit);
+ let projectiles = weapons
+ .weapons()
+ .iter()
+ .map(|weapon| weapon.projectile.as_str())
+ .collect::<Vec<_>>();
+ assert_eq!(projectiles, ["bb_h_01", "bp_h_01", "bl_h_01", "bm_h_01"]);
+ let effects = weapons
+ .weapons()
+ .iter()
+ .map(|weapon| weapon.effect.as_ref().map(|(_, name)| name.as_str()))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ effects,
+ [
+ Some("hero_cannon"),
+ Some("hero_prifle"),
+ Some("hero_redlaser"),
+ None
+ ]
+ );
let first = frame(&mut engine, 5).unwrap().mission_event.unwrap();
assert_eq!(
first.notices,
diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs
new file mode 100644
index 00000000..510cabb4
--- /dev/null
+++ b/crates/fparkan-runtime/src/player_weapon.rs
@@ -0,0 +1,196 @@
+use crate::{Engine, StartingCockpit};
+use fparkan_assets::{
+ PreparedComponentControl, PreparedControlEffectSection, PreparedControlPoint,
+};
+
+/// The starting hero's selectable weapon devices, in resource order.
+#[derive(Default)]
+pub struct PlayerWeapons {
+ weapons: Vec<PlayerWeapon>,
+ selected: Option<usize>,
+}
+
+/// A manual-fire device prepared from its CTLD record and effect rows.
+pub struct PlayerWeapon {
+ /// Name of the projectile prototype.
+ pub projectile: String,
+ /// Archive named by the weapon's projectile descriptor.
+ pub projectile_archive: String,
+ /// Point used by the weapon animation's first firing row.
+ pub muzzle: PreparedControlPoint,
+ /// Optional type-4 effect started by this weapon.
+ pub effect: Option<(String, String)>,
+ interval_ms: u32,
+ last_fire_ms: Option<u32>,
+}
+
+impl PlayerWeapons {
+ /// Returns the prepared devices in selection order.
+ pub fn weapons(&self) -> &[PlayerWeapon] {
+ &self.weapons
+ }
+
+ /// 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)> {
+ let selected = self.selected;
+ self.weapons
+ .iter_mut()
+ .enumerate()
+ .filter_map(move |(index, weapon)| {
+ if !trigger || selected.is_some_and(|selected| selected != index) {
+ return None;
+ }
+ if weapon
+ .last_fire_ms
+ .is_some_and(|last| clock_ms.wrapping_sub(last) < weapon.interval_ms)
+ {
+ return None;
+ }
+ weapon.last_fire_ms = Some(clock_ms);
+ Some((index, &*weapon))
+ })
+ }
+}
+
+/// 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, prepare_weapons),
+ ..PlayerWeapons::default()
+ }
+}
+
+fn prepare_weapons(control: &PreparedComponentControl) -> Vec<PlayerWeapon> {
+ let Some(points) = &control.point_list else {
+ return Vec::new();
+ };
+ control
+ .typed_records
+ .iter()
+ .filter(|record| record.tag == 2)
+ .filter_map(|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 row = control
+ .timeline_rows
+ .get(*record.values.first()? as usize)?;
+ if row.flags & 0x40 != 0 {
+ return None;
+ }
+ let muzzle = points.points.get(row.raw_parameters[1] as usize)?;
+ if muzzle.raw_signed_field_04 < 0
+ || muzzle.raw_signed_field_04 != muzzle.raw_signed_field_08
+ {
+ return None;
+ }
+ let interval_ms =
+ f32::from_bits(record.fixed_words[14]) + f32::from_bits(record.fixed_words[15]);
+ if !interval_ms.is_finite() || interval_ms < 0.0 {
+ return None;
+ }
+ let effect = match &control.effect_section {
+ PreparedControlEffectSection::Parsed(rows) => control
+ .node_effect_links
+ .iter()
+ .find(|&&(group, node, _)| {
+ Some(group) == control.initial_effect_group
+ && node as usize == row.node_index
+ })
+ .and_then(|&(group, _, selector)| {
+ rows.iter()
+ .find(|row| row.table_index == group && row.selector == selector)
+ })
+ .and_then(|row| {
+ Some((
+ crate::bounded_ascii_c_string(&row.resource.archive)?,
+ crate::bounded_ascii_c_string(&row.resource.name)?,
+ ))
+ }),
+ _ => None,
+ };
+ Some(PlayerWeapon {
+ projectile,
+ projectile_archive,
+ muzzle: muzzle.clone(),
+ effect,
+ // shortcut: begin the next cycle after the two configured
+ // waits and a 60 Hz step for each of the four native phases.
+ interval_ms: (interval_ms + 4.0 * (1000.0 / 60.0)).ceil() as u32,
+ last_fire_ms: None,
+ })
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn trigger_respects_selection_and_independent_weapon_waits() {
+ let mut weapons = PlayerWeapons {
+ selected: None,
+ weapons: [100, 250]
+ .map(|interval_ms| PlayerWeapon {
+ projectile: String::from("test"),
+ projectile_archive: String::from("test.rlb"),
+ 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],
+ },
+ effect: None,
+ interval_ms,
+ last_fire_ms: None,
+ })
+ .into(),
+ };
+ let mut fired = |trigger, t| {
+ weapons
+ .fire(trigger, t)
+ .map(|(slot, _)| slot)
+ .collect::<Vec<_>>()
+ };
+ assert!(fired(false, 0).is_empty());
+ assert_eq!(fired(true, 0), [0, 1]);
+ assert!(fired(true, 99).is_empty());
+ assert_eq!(fired(true, 100), [0]);
+ weapons.select(2);
+ assert!(weapons.fire(true, 249).next().is_none());
+ assert_eq!(weapons.fire(true, 250).next().unwrap().0, 1);
+ weapons.select(0);
+ assert_eq!(weapons.fire(true, 251).next().unwrap().0, 0);
+ }
+}
diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md
index 53cb090a..7d5b7b47 100644
--- a/docs/appendices/knowledge-boundaries.md
+++ b/docs/appendices/knowledge-boundaries.md
@@ -37,6 +37,10 @@ authoring API без динамического подтверждения.
Время доводки, поправки направления орудий и отдельный обзор со Shift открыты.
Выбор героя по владельцу и переход на внутренние этажи ещё открыты.
+`player_weapon_cycle_approx` отмечает приближённый такт огня, без нативных
+фаз, расхода боезапаса и поворота между стволами. `player_projectile_stub`
+и `player_weapon_fx_stub` отмечают отсутствие снаряда, попадания и вспышки.
+
`autodemo_camera_follow_approx` и `autodemo_camera_target_approx` отмечают
приближённое слежение и выбор размещённых юнитов с камерой через селектор AI.
Стратегический интерфейс и выбор вновь созданных юнитов ещё открыты.
diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md
index fe846a22..f6cbd59e 100644
--- a/docs/tomes/06-behavior.md
+++ b/docs/tomes/06-behavior.md
@@ -1796,6 +1796,29 @@ Simulation читает подготовленный input snapshot. Renderer н
самостоятельно опрашивать OS, иначе одно и то же нажатие будет зависеть от
частоты кадров.
+### Ручной огонь
+
+В `hero.tbl` кнопки от 1 до 8 выбирают орудие, а 0 выбирает все.
+Нажатие левой кнопки мыши включает непрерывный огонь выбранных
+орудий, отпускание его прекращает. В GOG `World3D.dll` по RVA
+`0xd7b0` имена `MCMD_STATE` и `MCMD_SELECT` превращаются в команды
+1 и 13. SHA-256 этой сборки указан в
+[перечне модулей](../reference/original-binaries.md).
+
+Герой получает орудия из записей Control типа 2. Запись указывает
+ресурс снаряда и строки CTL, которые выбирают точки выстрела в CPT.
+У пушки героя в «Огневом рубеже» строка указывает узел ствола, а
+связь эффекта этого узла ведёт к звуку `H_fire_cannon.wav`. В
+`Control.dll` с хешем из раздела выше RVA `0x29ca0` ведёт цикл
+орудия, `0x2a190` запускает эффект и создаёт снаряд на соседних
+фазах, а `0x2800` связывает строки эффектов с узлами командой 14.
+
+В FParkan каждое орудие имеет собственный срок следующего выстрела в
+игровом времени. Приложение ставит исходный звук в точку ствола из
+текущей позы. Пока интервал складывается из двух задержек CTL и
+приблизительного времени на четыре фазы. Выстрел регистрируется в
+журнале и даёт звук. Снаряд, визуальные эффекты и попадание ещё открыты.
+
### Joystick через DirectInput
`Joystick.dll` экспортирует: