diff options
| author | Valentin Popov <valentin@popov.link> | 2026-11-14 05:40:01 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-11-14 05:40:01 +0300 |
| commit | 8065381152e2d4f89279fd662e7376013ad13e82 (patch) | |
| tree | 27bcf4b04ddb71fc8df23a53514f87a3dc509ef7 | |
| parent | 520273dbe04fc1c9ea40127fb198d2bb5f0813f9 (diff) | |
| download | fparkan-8065381152e2d4f89279fd662e7376013ad13e82.tar.xz fparkan-8065381152e2d4f89279fd662e7376013ad13e82.zip | |
feat(game): tilt the cockpit view from vertical mouse input
| -rw-r--r-- | README.md | 6 | ||||
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 40 | ||||
| -rw-r--r-- | crates/fparkan-render/src/lib.rs | 39 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 30 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/player_motion.rs | 31 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 5 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 7 |
7 files changed, 134 insertions, 24 deletions
@@ -46,9 +46,9 @@ cargo run --release -p fparkan-game -- ` фиксированной позы или фазы материала тоже включают этот режим. Если в одиночной миссии найден один герой с точкой `CameraCenter`, окно открывается с видом из его кабины. Стрелки двигают героя вперёд, назад и -вбок, горизонтальное движение мыши поворачивает корпус. `Esc` освобождает -указатель, правая кнопка возвращает захват. Скорость шага и чувствительность -мыши пока приближённые. Вертикальное прицеливание ещё открыто. +вбок. Мышь поворачивает корпус по горизонтали и наклоняет взгляд по +вертикали. `Esc` освобождает указатель, правая кнопка возвращает захват. +Скорость шага, чувствительность и пределы угла пока приближённые. Свободный обзор доступен через `--viewer` и служит запасной камерой для миссий без однозначной кабины. В свободном обзоре `WASD` перемещают камеру относительно её направления, `E/Q` поднимают и diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 8c78a44a..4fde797c 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -9751,7 +9751,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_stub=1 cockpit_pose_approx=1" + "player_motion_approx=1 cockpit_aim_approx=1 cockpit_pose_approx=1" } else { "mission_camera_stub=1" } @@ -9834,7 +9834,7 @@ struct StaticVulkanApp { pressed_keys: HashSet<KeyCode>, player_move_pressed: [bool; 4], mouse_look: bool, - player_mouse_x: f32, + player_mouse: [f32; 2], audio: Option<audio::GameAudio>, camera_mode: &'static str, mesh_components: usize, @@ -9956,7 +9956,7 @@ impl StaticVulkanApp { pressed_keys: HashSet::new(), player_move_pressed: [false; 4], mouse_look: false, - player_mouse_x: 0.0, + player_mouse: [0.0; 2], audio, camera_mode: preview.camera_mode, mesh_components: preview.mesh_components, @@ -10272,9 +10272,8 @@ impl StaticVulkanApp { cockpit: StartingCockpit, viewport: [f32; 2], ) -> Option<PreviewCameraFrame> { - let (_, state) = self - .mission_frame - .as_ref()? + let frame = self.mission_frame.as_ref()?; + let (_, state) = frame .snapshot .transforms .iter() @@ -10305,7 +10304,8 @@ impl StaticVulkanApp { }, state.scale.map(f32::from_bits), point, - )?; + )? + .with_cockpit_pitch(f32::from_bits(frame.player_pitch_bits))?; PreviewCameraFrame::from_legacy_d3d7( camera, LegacyD3d7Projection { @@ -10402,7 +10402,7 @@ impl StaticVulkanApp { fn set_mission_paused_at(&mut self, paused: bool, now: Instant) { self.mission_paused = paused; - self.player_mouse_x = 0.0; + self.player_mouse = [0.0; 2]; self.player_move_pressed = [false; 4]; if self.cockpit.is_some() && self.demo_camera.is_none() { self.set_mouse_look(self.window_focused && !paused); @@ -10526,7 +10526,7 @@ impl StaticVulkanApp { let control_clock_ms = clock.time_ms; let mut player_step = None; // A held key and accumulated device motion belong to this simulation sample. - let mouse_x = std::mem::take(&mut self.player_mouse_x); + let [mouse_x, mouse_y] = std::mem::take(&mut self.player_mouse); if let (Some(engine), Some(cockpit), None) = (&self.mission_engine, self.cockpit, &self.demo_camera) { @@ -10547,6 +10547,7 @@ impl StaticVulkanApp { f32::from(forward || pressed[2]) - f32::from(back || pressed[3]), ], mouse_x, + mouse_y, delta_seconds: clock.delta_seconds, }, ) @@ -11414,7 +11415,8 @@ impl ApplicationHandler for StaticVulkanApp { if self.mouse_look { if let DeviceEvent::MouseMotion { delta } = event { if self.cockpit.is_some() && self.demo_camera.is_none() && !self.mission_paused { - self.player_mouse_x += delta.0 as f32; + self.player_mouse[0] += delta.0 as f32; + self.player_mouse[1] += delta.1 as f32; } else if self.cockpit.is_none() { if let Some(camera) = self.free_camera.as_mut() { camera.look_delta(delta.0, delta.1); @@ -11585,7 +11587,7 @@ impl ApplicationHandler for StaticVulkanApp { if !focused { self.pressed_keys.clear(); self.player_move_pressed = [false; 4]; - self.player_mouse_x = 0.0; + self.player_mouse = [0.0; 2]; self.set_mouse_look(false); } else if self.cockpit.is_some() && self.demo_camera.is_none() @@ -14660,6 +14662,22 @@ mod tests { app.update_mission_camera(0.016, [800.0, 600.0]).unwrap(); assert!((app.view_camera.position[0] - before[0] - 1.0).abs() < 1e-4); assert_eq!(app.view_camera.position[1], before[1]); + let moved = app.view_camera.position; + let aimed = plan_player_motion( + &engine, + cockpit, + PlayerMotion { + mouse_y: -100.0, + ..PlayerMotion::default() + }, + ) + .unwrap() + .unwrap(); + app.mission_frame = + Some(frame_with_player_motion(&mut engine, 32, cockpit, aimed, false).unwrap()); + app.update_mission_camera(0.016, [800.0, 600.0]).unwrap(); + assert_eq!(app.view_camera.position, moved); + assert!((app.view_camera.forward[2] - 0.5_f32.sin()).abs() < 1e-6); } #[test] diff --git a/crates/fparkan-render/src/lib.rs b/crates/fparkan-render/src/lib.rs index f34138e1..c8c94e09 100644 --- a/crates/fparkan-render/src/lib.rs +++ b/crates/fparkan-render/src/lib.rs @@ -25,6 +25,25 @@ impl RawCameraTransform { Self::TRANSLATION_WORD_INDICES.map(|index| f32::from_bits(self.words[index])) } + /// Rotates a cockpit's forward and up axes about its lateral axis, + /// preserving the camera point. + #[must_use] + pub fn with_cockpit_pitch(mut self, radians: f32) -> Option<Self> { + if !radians.is_finite() { + return None; + } + if radians != 0.0 { + let (sin, cos) = radians.sin_cos(); + for row in self.words[..12].chunks_exact_mut(4) { + let forward = f32::from_bits(row[0]); + let up = f32::from_bits(row[2]); + row[0] = (forward * cos + up * sin).to_bits(); + row[2] = (up * cos - forward * sin).to_bits(); + } + } + Some(self) + } + /// Inverts a finite row-major affine transform without assigning it a /// camera-space meaning. /// @@ -609,6 +628,26 @@ mod tests { } #[test] + fn pitching_the_cockpit_preserves_its_origin_and_lateral_axis() { + let unit = LegacyIron3dEulerTransform { + translation: [12.0, 3.0, 4.0], + orientation_radians: [0.0, 0.0, 0.0], + }; + let camera = forward_cockpit_camera(unit, [1.0; 3], [0.0; 3]).unwrap(); + assert_eq!(camera.with_cockpit_pitch(0.0), Some(camera)); + let tilted = camera + .with_cockpit_pitch(std::f32::consts::FRAC_PI_2) + .unwrap(); + assert_eq!(camera.translation(), tilted.translation()); + for axis in [1, 5, 9] { + assert_eq!(camera.words[axis], tilted.words[axis]); + } + let tilted = tilted.words.map(f32::from_bits); + assert_eq!(tilted[8], 1.0); + assert!((tilted[6] + 1.0).abs() < 1e-6); + } + + #[test] fn water_reflection_preserves_the_plane_and_reverses_height_before_projection() { let matrix = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 32a4d8d1..883e5554 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -1261,6 +1261,8 @@ pub struct FrameResult { pub snapshot: WorldSnapshot, /// Periodic script event attempted on this step, if due. pub mission_event: Option<MissionEventTick>, + /// Vertical aim of the controlled hero as an IEEE-754 radian value. + pub player_pitch_bits: u32, } /// Engine. @@ -1293,6 +1295,7 @@ struct LoadedMissionState { script_init_states: Vec<MissionScriptInitState>, script_varset_states: Vec<MissionScriptVarSetState>, mission_events: MissionEvents, + player_pitch_bits: u32, script_host_mode: MissionMode, script_host_status: u32, script_outcome: MissionScriptOutcome, @@ -2232,6 +2235,7 @@ fn load_mission_with_options( script_init_states: loaded_scripts.init_states, script_varset_states: loaded_scripts.varset_states, mission_events, + player_pitch_bits: 0, script_host_mode: request.mode, // Fresh IGame construction seeds this field with 5; this is not the // later status-4 transition performed after native game initialization. @@ -2283,6 +2287,10 @@ pub fn step_headless( Ok(FrameResult { snapshot, mission_event, + player_pitch_bits: engine + .loaded + .as_ref() + .map_or(0, |mission| mission.player_pitch_bits), }) } @@ -2314,11 +2322,19 @@ pub fn frame_with_player_motion( pose.position = previous.position; } set_transform(&mut engine.world, cockpit.handle, pose)?; - let result = frame(engine, queue_time_ms); - if result.is_err() { - set_transform(&mut engine.world, cockpit.handle, previous)?; + match frame(engine, queue_time_ms) { + Ok(mut frame) => { + if let Some(mission) = &mut engine.loaded { + mission.player_pitch_bits = motion.pitch_bits; + frame.player_pitch_bits = motion.pitch_bits; + } + Ok(frame) + } + Err(error) => { + set_transform(&mut engine.world, cockpit.handle, previous)?; + Err(error) + } } - result } /// Coverage entries for the subsystems still absent from the mission loop. @@ -17133,6 +17149,7 @@ mod tests { let input = PlayerMotion { movement: [0.0, 1.0], mouse_x: 100.0, + mouse_y: -500.0, delta_seconds: 0.1, }; let proposed = plan_player_motion(&engine, cockpit, input) @@ -17152,8 +17169,11 @@ mod tests { let turned = pose(&blocked); assert_eq!(turned.position, original.position); assert_ne!(turned.orientation[2], original.orientation[2]); + assert_eq!(turned.orientation[..2], original.orientation[..2]); + assert_eq!(f32::from_bits(blocked.player_pitch_bits), 1.0); let movement = PlayerMotion { mouse_x: 0.0, + mouse_y: 0.0, ..input }; let proposed = plan_player_motion(&engine, cockpit, movement) @@ -17172,6 +17192,8 @@ mod tests { .unwrap() }; assert!(((z1 - ground([x1, y1])) - (z0 - ground([x0, y0]))).abs() < 1e-5); + let idle = frame(&mut engine, 300).unwrap(); + assert_eq!(idle.player_pitch_bits, blocked.player_pitch_bits); } #[test] diff --git a/crates/fparkan-runtime/src/player_motion.rs b/crates/fparkan-runtime/src/player_motion.rs index 291b0451..439429cd 100644 --- a/crates/fparkan-runtime/src/player_motion.rs +++ b/crates/fparkan-runtime/src/player_motion.rs @@ -8,6 +8,8 @@ pub struct PlayerMotion { pub movement: [f32; 2], /// Relative horizontal mouse motion for this step. pub mouse_x: f32, + /// Relative vertical mouse motion for this step, positive down. + pub mouse_y: f32, /// Time spent on this simulation step, excluding time spent paused. pub delta_seconds: f32, } @@ -16,6 +18,7 @@ pub struct PlayerMotion { #[derive(Clone, Copy, Debug)] pub struct PlayerMotionStep { pub(super) pose: TransformState, + pub(super) pitch_bits: u32, /// Sweep segment when the step translates the hero. pub sweep: Option<[[f32; 3]; 2]>, } @@ -30,7 +33,7 @@ pub fn plan_player_motion( cockpit: StartingCockpit, input: PlayerMotion, ) -> Result<Option<PlayerMotionStep>, EngineError> { - if input.movement == [0.0; 2] && input.mouse_x == 0.0 { + if input.movement == [0.0; 2] && input.mouse_x == 0.0 && input.mouse_y == 0.0 { return Ok(None); } let (Some(mission), Ok(pose)) = ( @@ -39,12 +42,19 @@ pub fn plan_player_motion( ) else { return Ok(None); }; - plan_motion(&mission.terrain, pose, input).map(Some) + plan_motion( + &mission.terrain, + pose, + f32::from_bits(mission.player_pitch_bits), + input, + ) + .map(Some) } fn plan_motion( terrain: &TerrainWorld, mut pose: TransformState, + pitch: f32, input: PlayerMotion, ) -> Result<PlayerMotionStep, EngineError> { let from = pose.position.map(f32::from_bits); @@ -52,7 +62,13 @@ fn plan_motion( if !input .movement .into_iter() - .chain([input.mouse_x, input.delta_seconds, yaw]) + .chain([ + input.mouse_x, + input.mouse_y, + input.delta_seconds, + yaw, + pitch, + ]) .chain(from) .all(f32::is_finite) || input.delta_seconds < 0.0 @@ -96,5 +112,12 @@ fn plan_motion( ]); } } - Ok(PlayerMotionStep { pose, sweep }) + // shortcut: use a bounded camera aim until the native turret travel and + // sensitivity are recovered. The body remains aligned to the terrain. + let pitch = (pitch - input.mouse_y * 0.005).clamp(-1.0, 1.0); + Ok(PlayerMotionStep { + pose, + pitch_bits: pitch.to_bits(), + sweep, + }) } diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index a0b0c216..5f155d0c 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -32,8 +32,9 @@ authoring API без динамического подтверждения. `cockpit_pose_approx` отмечает расчёт кабины по ресурсной позе. `player_motion_approx` отмечает постоянную скорость, приближённую -чувствительность и проверку строений одним отрезком. `cockpit_aim_stub` -отмечает открытое вертикальное прицеливание и независимый обзор. +чувствительность и проверку строений одним отрезком. `cockpit_aim_approx` +отмечает приближённый вертикальный угол камеры. Поворот модели башни, +наведение оружия, инверсия мыши и отдельный обзор со Shift открыты. Выбор героя по владельцу и переход на внутренние этажи ещё открыты. `autodemo_camera_follow_approx` и `autodemo_camera_target_approx` отмечают diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 23e852fa..d939226e 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -1771,6 +1771,13 @@ zone/threshold и временной характеристикой. СтрокÐ команды `MCMD_STATE`, `MCMD_ANGLE_X`, `MCMD_ANGLE_Y`, режимы `MAN_WRAP` и `MAN_NOTWRAP`, а также параметры ускорения в миллисекундах. +В `hero.tbl` вертикальное движение мыши без Shift отправляет +`MCMD_ANGLE_Y` башне. С Shift эта же ось направлена камере. На этом +этапе FParkan сохраняет вертикальный угол в состоянии игрока и наклоняет +две оси камеры вокруг её поперечной оси. Например, подъём взгляда сохраняет +точку кабины и положение героя на земле. Угол сохраняется между тиками +и ограничен диапазоном от −1 до 1 радиана до сверки настройки башни. + Simulation читает подготовленный input snapshot. Renderer не должен самостоятельно опрашивать OS, иначе одно и то же нажатие будет зависеть от частоты кадров. |
