diff options
| -rw-r--r-- | Cargo.lock | 1 | ||||
| -rw-r--r-- | README.md | 4 | ||||
| -rw-r--r-- | adapters/fparkan-platform-winit/Cargo.toml | 1 | ||||
| -rw-r--r-- | adapters/fparkan-platform-winit/src/intro_video.rs | 194 | ||||
| -rw-r--r-- | adapters/fparkan-platform-winit/src/lib.rs | 4 | ||||
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 2 | ||||
| -rw-r--r-- | apps/fparkan-game/src/mission_loading.rs | 48 | ||||
| -rw-r--r-- | apps/fparkan-game/src/startup_intro.rs | 67 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/lib.rs | 1 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/startup_movies.rs | 42 | ||||
| -rw-r--r-- | docs/appendices/ui-shell.md | 14 |
11 files changed, 377 insertions, 1 deletions
@@ -585,6 +585,7 @@ version = "0.1.0" dependencies = [ "fparkan-platform", "raw-window-handle", + "windows", "windows-sys 0.101.0", "winit", ] @@ -32,7 +32,9 @@ cargo run --release -p fparkan-game -- ` --mission 'MISSIONS\Autodemo.00\data.tma' ``` -При запуске без `--mission` в Windows открывается меню выбора миссии. +При запуске без `--mission` в Windows проигрываются вступительные ролики, +затем открывается меню выбора миссии. Пропустить вступление можно клавишей +или щелчком левой кнопки мыши. Оно показывает кампании, одиночные миссии и демо из установленной игры. При запуске из каталога игры `--root` можно опустить. `--list-missions` выводит пути к миссиям и их номера. Для `--mission` diff --git a/adapters/fparkan-platform-winit/Cargo.toml b/adapters/fparkan-platform-winit/Cargo.toml index 6523dd5a..e7a2c171 100644 --- a/adapters/fparkan-platform-winit/Cargo.toml +++ b/adapters/fparkan-platform-winit/Cargo.toml @@ -11,4 +11,5 @@ raw-window-handle = "0.6" winit = { version = "0.30", default-features = false, features = ["rwh_06"] } [target.'cfg(windows)'.dependencies] +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Media_DirectShow", "Win32_System_Com", "Win32_UI_WindowsAndMessaging"] } windows-sys = { version = "0.101", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_Input", "Win32_UI_WindowsAndMessaging"] } diff --git a/adapters/fparkan-platform-winit/src/intro_video.rs b/adapters/fparkan-platform-winit/src/intro_video.rs new file mode 100644 index 00000000..37c9d19f --- /dev/null +++ b/adapters/fparkan-platform-winit/src/intro_video.rs @@ -0,0 +1,194 @@ +//! DirectShow AVI playback inside the existing game window. + +use raw_window_handle::{HasWindowHandle, RawWindowHandle}; +use std::{io, marker::PhantomData, os::windows::ffi::OsStrExt, path::Path, rc::Rc}; +use windows::{ + core::{Interface, PCWSTR}, + Win32::{ + Foundation::E_ABORT, + Media::DirectShow::{ + FilgraphManager, IBasicVideo, IGraphBuilder, IMediaControl, IMediaEventEx, + IVideoWindow, EC_COMPLETE, EC_ERRORABORT, EC_USERABORT, + }, + System::Com::{ + CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_HANDLER, + CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, + }, + UI::WindowsAndMessaging::WS_CHILD, + }, +}; +use winit::window::Window; + +/// A clip whose DirectShow renderer is a child of the game window. +pub struct IntroVideo { + control: IMediaControl, + events: IMediaEventEx, + video: IVideoWindow, + frame: [i32; 2], + // Drop the graph interfaces before leaving their COM apartment. + _apartment: Apartment, +} + +impl IntroVideo { + /// Renders the original AVI's video and audio streams in the game window. + /// The player is opened, polled and dropped on the window thread. + pub fn play(window: &Window, path: &Path) -> Result<Self, Box<dyn std::error::Error>> { + let handle = window.window_handle()?; + let RawWindowHandle::Win32(owner) = handle.as_raw() else { + return Err(io::Error::other("intro playback requires a Win32 window").into()); + }; + let owner = owner.hwnd.get(); + let mut filename: Vec<u16> = path.as_os_str().encode_wide().collect(); + if filename.contains(&0) { + return Err( + io::Error::new(io::ErrorKind::InvalidInput, "AVI path contains a NUL").into(), + ); + } + filename.push(0); + let apartment = Apartment::enter()?; + + // SAFETY: This is the window thread's initialized STA. The path stays + // valid through RenderFile, and DirectShow owns the graph and renderer. + let movie = unsafe { + let graph: IGraphBuilder = CoCreateInstance( + &FilgraphManager, + None, + CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, + )?; + graph.RenderFile(PCWSTR(filename.as_ptr()), PCWSTR::null())?; + let control = graph.cast::<IMediaControl>()?; + let events = graph.cast::<IMediaEventEx>()?; + let video = graph.cast::<IVideoWindow>()?; + let dimensions = graph.cast::<IBasicVideo>()?; + let frame = [dimensions.SourceWidth()?, dimensions.SourceHeight()?]; + Self { + control, + events, + video, + frame, + _apartment: apartment, + } + }; + // SAFETY: The parent HWND is borrowed from the live Window above. The + // child is detached when playback ends, before the game window drops. + unsafe { + movie.video.SetOwner(owner)?; + movie.video.SetMessageDrain(owner)?; + movie.video.SetWindowStyle(WS_CHILD.0 as i32)?; + } + movie.resize(window)?; + // SAFETY: All graph interfaces are used on their creating STA. + unsafe { movie.control.Run()? }; + Ok(movie) + } + + /// Updates the child rectangle using the original movie fitting rule. + pub fn resize(&self, window: &Window) -> Result<(), Box<dyn std::error::Error>> { + let size = window.inner_size(); + if size.width == 0 || size.height == 0 { + return Ok(()); + } + let client = [i32::try_from(size.width)?, i32::try_from(size.height)?]; + let [left, top, width, height] = content_rect(client, self.frame)?; + // SAFETY: The renderer belongs to the STA calling this method. + unsafe { self.video.SetWindowPosition(left, top, width, height)? }; + Ok(()) + } + + /// Drains pending graph events without blocking the window thread. + pub fn finished(&self) -> Result<bool, Box<dyn std::error::Error>> { + // SAFETY: The event parameters are writable for the duration of the + // call and every successfully retrieved event is freed on this STA. + unsafe { + loop { + let (mut code, mut first, mut second) = (0, 0, 0); + match self.events.GetEvent(&mut code, &mut first, &mut second, 0) { + Ok(()) => self.events.FreeEventParams(code, first, second)?, + Err(error) if error.code() == E_ABORT => return Ok(false), + Err(error) => return Err(error.into()), + } + match code as u32 { + EC_COMPLETE | EC_USERABORT => return Ok(true), + EC_ERRORABORT => { + return Err(windows::core::Error::from_hresult(windows::core::HRESULT( + first as i32, + )) + .into()); + } + _ => {} + } + } + } + } +} + +impl Drop for IntroVideo { + fn drop(&mut self) { + // SAFETY: Playback shuts down on the creating STA while its owner + // window still exists. The interfaces then release before COM exits. + unsafe { + let _ = self.control.Stop(); + let _ = self.video.SetVisible(0); + let _ = self.video.SetMessageDrain(0); + let _ = self.video.SetOwner(0); + } + } +} + +struct Apartment(PhantomData<Rc<()>>); + +impl Apartment { + fn enter() -> windows::core::Result<Self> { + // SAFETY: The reserved parameter is null. Each successful call, + // including S_FALSE, is balanced by Drop on the same thread. + unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()? }; + Ok(Self(PhantomData)) + } +} + +impl Drop for Apartment { + fn drop(&mut self) { + // SAFETY: enter acquired this thread's COM initialization count. + unsafe { CoUninitialize() }; + } +} + +fn content_rect(client: [i32; 2], video: [i32; 2]) -> io::Result<[i32; 4]> { + let [frame_width, frame_height] = video.map(i64::from); + if frame_width <= 0 || frame_height <= 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid AVI dimensions", + )); + } + let [client_width, client_height] = client.map(i64::from); + let (width, height) = if frame_height < frame_width { + (client_width, frame_height * client_width / frame_width) + } else { + (frame_width * client_height / frame_height, client_height) + }; + let coordinate = |value| i32::try_from(value).map_err(io::Error::other); + Ok([ + coordinate((client_width - width) / 2)?, + coordinate((client_height - height) / 2)?, + coordinate(width)?, + coordinate(height)?, + ]) +} + +#[cfg(test)] +#[test] +fn positions_movie_using_the_original_orientation_rule() { + assert_eq!( + content_rect([800, 600], [640, 480]).unwrap(), + [0, 0, 800, 600] + ); + assert_eq!( + content_rect([1280, 720], [640, 480]).unwrap(), + [0, -120, 1280, 960] + ); + assert_eq!( + content_rect([800, 600], [480, 640]).unwrap(), + [175, 0, 450, 600] + ); +} diff --git a/adapters/fparkan-platform-winit/src/lib.rs b/adapters/fparkan-platform-winit/src/lib.rs index 57ca827f..28738f70 100644 --- a/adapters/fparkan-platform-winit/src/lib.rs +++ b/adapters/fparkan-platform-winit/src/lib.rs @@ -7,6 +7,10 @@ pub mod text; #[cfg(windows)] #[allow(unsafe_code)] +pub mod intro_video; + +#[cfg(windows)] +#[allow(unsafe_code)] pub mod startup_window; #[cfg(windows)] diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index ef5ae722..c324139f 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -47,6 +47,8 @@ mod satellite_map; #[cfg(windows)] mod satellite_map_chrome; #[cfg(windows)] +mod startup_intro; +#[cfg(windows)] mod strategic_balance_hud; #[cfg(windows)] mod strategic_buildings_hud; diff --git a/apps/fparkan-game/src/mission_loading.rs b/apps/fparkan-game/src/mission_loading.rs index 7410aec4..823c6b35 100644 --- a/apps/fparkan-game/src/mission_loading.rs +++ b/apps/fparkan-game/src/mission_loading.rs @@ -22,9 +22,12 @@ use winit::{ #[cfg(windows)] use { + super::startup_intro::StartupIntro, fparkan_assets::mission_loader::MissionLoader, fparkan_platform_winit::{startup_window, text::StringResources}, fparkan_vfs::DirectoryVfs, + std::time::{Duration, Instant}, + winit::event::{ElementState, MouseButton}, }; #[derive(Clone, Copy)] @@ -58,6 +61,8 @@ pub(super) fn run( let event_loop = new_game_event_loop().map_err(|error| format!("winit event loop: {error}"))?; event_loop.set_control_flow(ControlFlow::Wait); let mut startup = WindowedMission { + #[cfg(windows)] + intro: menu.as_ref().and_then(|_| StartupIntro::open(&args.root)), args, extent, resizable: capture.is_none(), @@ -107,6 +112,9 @@ struct WindowedMission { extent: [u32; 2], resizable: bool, menu: Option<LaunchMenu>, + // The DirectShow child and its graph must release before the window. + #[cfg(windows)] + intro: Option<StartupIntro>, loading: MissionLoading, load_request: Option<Box<LoadRequest>>, receive: Option<mpsc::Receiver<LoadEvent>>, @@ -229,6 +237,28 @@ impl ApplicationHandler for WindowedMission { event_loop.exit(); return; } + #[cfg(windows)] + if let Some(intro) = &self.intro { + match event { + WindowEvent::KeyboardInput { event, .. } + if event.state == ElementState::Pressed && !event.repeat => + { + self.intro = None; + window.request_redraw(); + } + WindowEvent::MouseInput { + state: ElementState::Pressed, + button: MouseButton::Left, + .. + } => { + self.intro = None; + window.request_redraw(); + } + WindowEvent::Resized(_) => intro.resize(window), + _ => {} + } + return; + } if let Some(menu) = &mut self.menu { if matches!(event, WindowEvent::RedrawRequested) { if let Err(error) = menu.paint(window) { @@ -279,8 +309,26 @@ impl ApplicationHandler for WindowedMission { } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if event_loop.exiting() { + return; + } if let Some(game) = &mut self.game { game.about_to_wait(event_loop); + return; + } + #[cfg(windows)] + if let Some((intro, window)) = self.intro.as_mut().zip(self.window.as_ref()) { + if intro.update(window) { + event_loop.set_control_flow(ControlFlow::WaitUntil( + Instant::now() + Duration::from_millis(50), + )); + } else { + self.intro = None; + event_loop.set_control_flow(ControlFlow::Wait); + window.request_redraw(); + } + } else if self.menu.is_some() { + event_loop.set_control_flow(ControlFlow::Wait); } } } diff --git a/apps/fparkan-game/src/startup_intro.rs b/apps/fparkan-game/src/startup_intro.rs new file mode 100644 index 00000000..d5fa80ef --- /dev/null +++ b/apps/fparkan-game/src/startup_intro.rs @@ -0,0 +1,67 @@ +//! Startup movie sequence shown before the mission menu. + +use fparkan_assets::startup_movies::movie_paths; +use fparkan_platform_winit::{intro_video::IntroVideo, startup_window}; +use fparkan_vfs::DirectoryVfs; +use std::{ + collections::VecDeque, + path::{Path, PathBuf}, +}; +use winit::window::Window; + +pub(super) struct StartupIntro { + waiting: VecDeque<PathBuf>, + playing: Option<IntroVideo>, +} + +impl StartupIntro { + pub(super) fn open(root: &Path) -> Option<Self> { + let paths = match movie_paths(&DirectoryVfs::new(root)) { + Ok(paths) => paths, + Err(error) => { + eprintln!("startup movies: {error}"); + return None; + } + }; + if paths.is_empty() { + return None; + } + Some(Self { + waiting: paths.iter().map(|path| root.join(path.as_str())).collect(), + playing: None, + }) + } + + /// Returns whether a movie is still playing. + pub(super) fn update(&mut self, window: &Window) -> bool { + if let Some(movie) = &self.playing { + match movie.finished() { + Ok(false) => return true, + Ok(true) => {} + Err(error) => eprintln!("startup playback: {error}"), + } + } + self.playing = None; + while let Some(path) = self.waiting.pop_front() { + if let Err(error) = startup_window::paint(window, [1, 1], &[0]) { + eprintln!("startup movie background: {error}"); + } + match IntroVideo::play(window, &path) { + Ok(movie) => { + self.playing = Some(movie); + return true; + } + Err(error) => eprintln!("startup movie {}: {error}", path.display()), + } + } + false + } + + pub(super) fn resize(&self, window: &Window) { + if let Some(movie) = &self.playing { + if let Err(error) = movie.resize(window) { + eprintln!("startup movie resize: {error}"); + } + } + } +} diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index 981534f9..a0b207d9 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -50,6 +50,7 @@ pub mod mission_pager; pub mod object_descriptions; pub mod satellite_map; pub mod satellite_map_chrome; +pub mod startup_movies; pub mod strategic_balance; pub mod strategic_buildings; pub mod strategic_factory; diff --git a/crates/fparkan-assets/src/startup_movies.rs b/crates/fparkan-assets/src/startup_movies.rs new file mode 100644 index 00000000..d2a590fe --- /dev/null +++ b/crates/fparkan-assets/src/startup_movies.rs @@ -0,0 +1,42 @@ +//! Intro movie paths declared in the installed shell configuration. + +use crate::ui_configuration::{field, object, read}; +use fparkan_path::{normalize_relative, NormalizedPath, PathPolicy}; +use fparkan_vfs::Vfs; + +/// Resolves the shell's logo and splash entries in playback order. +pub fn movie_paths(vfs: &dyn Vfs) -> Result<Vec<NormalizedPath>, String> { + parse_movies(&read(vfs, "ui/shell_ctrls.cfg")?) +} + +fn parse_movies(bytes: &[u8]) -> Result<Vec<NormalizedPath>, String> { + let text = String::from_utf8_lossy(bytes); + let common = object(&text, "common").ok_or("missing shell common configuration")?; + let mut paths = Vec::new(); + for slot in ["LOGO1_PARAM", "LOGO2_PARAM", "SPLASH_PARAM"] { + if !common.contains_key(slot) { + continue; + } + let path = field(&common, slot)?; + if !path.is_empty() { + paths.push( + normalize_relative(path.as_bytes(), PathPolicy::StrictLegacy) + .map_err(|error| format!("{slot}: {error}"))?, + ); + } + } + Ok(paths) +} + +#[cfg(test)] +#[test] +fn keeps_logo_order_and_skips_empty_slots() { + let paths = parse_movies( + b"object common\nsplash_param = \"data\\end.avi\"\nlogo2_param = \"DATA\\begin.avi\"\nlogo1_param = \"\"\nend", + ).unwrap(); + assert_eq!( + paths.iter().map(NormalizedPath::as_str).collect::<Vec<_>>(), + ["DATA/begin.avi", "data/end.avi"] + ); + assert!(parse_movies(b"object common\nlogo1_param = \"..\\video.avi\"\nend").is_err()); +} diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md index 06f444d8..1cbab73e 100644 --- a/docs/appendices/ui-shell.md +++ b/docs/appendices/ui-shell.md @@ -679,6 +679,20 @@ RVA `0x96190` строит строку из нескольких частей Ð проверку и для указателя, и для записи черновика. [Хеши GOG-сборок](../reference/original-binaries.md) +## Вступление + +Имена роликов берутся из `common` в `ui/shell_ctrls.cfg`. В GOG-сборке +`logo1_param` пуст, за ним идут `logo2_param` и `splash_param`. +В `iron3d.dll` RVA `0x23650` открывает AVI через DirectShow, привязывает +окно видео к игровому окну и передаёт ему сообщения ввода. Размер кадра +берётся из исходного прямоугольника. Альбомный кадр подгоняется по ширине, +книжный по высоте, затем видео центрируется. [Хеши GOG-сборок](../reference/original-binaries.md). + +FParkan передаёт DirectShow AVI из установленной игры вместе со звуковой +дорожкой. После показа или пропуска вступления в том же окне появляется +меню. Запуск конкретной миссии из командной строки сразу переходит к +загрузке мира. + ## Выбор миссии `iron3d.dll` по RVA `0x3430` открывает список кампаний, а по RVA |
