diff options
Diffstat (limited to 'adapters/fparkan-platform-winit/src/startup_window.rs')
| -rw-r--r-- | adapters/fparkan-platform-winit/src/startup_window.rs | 286 |
1 files changed, 68 insertions, 218 deletions
diff --git a/adapters/fparkan-platform-winit/src/startup_window.rs b/adapters/fparkan-platform-winit/src/startup_window.rs index 0b49ca6d..b3935bea 100644 --- a/adapters/fparkan-platform-winit/src/startup_window.rs +++ b/adapters/fparkan-platform-winit/src/startup_window.rs @@ -1,231 +1,81 @@ -//! A responsive Windows startup window that does not depend on the game renderer. +//! Paints the loading frame into the window that will host the Vulkan surface. -use std::{ - io, mem, ptr, - sync::{mpsc, Arc, Mutex}, - thread, -}; +use raw_window_handle::{HasWindowHandle, RawWindowHandle}; +use std::{io, mem}; use windows_sys::Win32::{ - Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM}, - Graphics::Gdi::*, - System::LibraryLoader::GetModuleHandleW, - UI::WindowsAndMessaging::*, + Foundation::{HWND, RECT}, + Graphics::Gdi::{ + GetDC, ReleaseDC, StretchDIBits, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, + GDI_ERROR, SRCCOPY, + }, + UI::WindowsAndMessaging::GetClientRect, }; +use winit::window::Window; -const SET_FRAME: u32 = WM_APP + 1; - -/// Keeps a startup bitmap visible until the game renderer can present. -pub struct StartupWindow { - handle: usize, - thread: Option<thread::JoinHandle<()>>, - state: Arc<State>, -} - -impl StartupWindow { - /// Opens a window with the supplied top-down 0x00RRGGBB bitmap. - pub fn open(extent: [u32; 2], pixels: Vec<u32>) -> io::Result<Self> { - let [width, height] = extent; - if width == 0 - || height == 0 - || width > i32::MAX as u32 - || height > i32::MAX as u32 - || (width as usize).checked_mul(height as usize) != Some(pixels.len()) - { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "invalid startup bitmap dimensions", - )); - } - let state = Arc::new(State { - extent: [width as i32, height as i32], - pixels: Mutex::new(pixels), - }); - let window_state = Arc::clone(&state); - let (ready, receiver) = mpsc::sync_channel(0); - let thread = thread::Builder::new() - .name("startup-window".into()) - .spawn(move || show(&window_state, ready))?; - match receiver.recv() { - Ok(Ok(handle)) => Ok(Self { - handle, - thread: Some(thread), - state, - }), - result => { - let _ = thread.join(); - Err(result - .ok() - .and_then(Result::err) - .unwrap_or_else(|| io::Error::other("startup window did not initialize"))) - } - } +/// Paints a top-down 0x00RRGGBB bitmap into the current client area. +/// +/// Call from the window thread before starting Vulkan presentation. +pub fn paint(window: &Window, extent: [u32; 2], pixels: &[u32]) -> io::Result<()> { + let [width, height] = extent; + if width == 0 + || height == 0 + || width > i32::MAX as u32 + || height > i32::MAX as u32 + || (width as usize).checked_mul(height as usize) != Some(pixels.len()) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid startup bitmap dimensions", + )); } - - /// Replaces the current bitmap and schedules a repaint. - pub fn set_frame(&self, pixels: Vec<u32>) { - if let Ok(mut frame) = self.state.pixels.lock() { - if frame.len() != pixels.len() { - return; - } - *frame = pixels; + let handle = window.window_handle().map_err(io::Error::other)?; + let RawWindowHandle::Win32(raw) = handle.as_raw() else { + return Err(io::Error::other("startup drawing requires a Win32 window")); + }; + let hwnd = raw.hwnd.get() as HWND; + // SAFETY: The borrowed window owns the HWND. The DC is acquired and released + // on this thread, and the validated bitmap stays alive while GDI reads it. + unsafe { + let mut rect = RECT::default(); + if GetClientRect(hwnd, &mut rect) == 0 { + return Err(io::Error::last_os_error()); } - // SAFETY: The message carries no references and is ignored if the window closed. - unsafe { PostMessageW(self.handle as HWND, SET_FRAME, 0, 0) }; - } -} - -impl Drop for StartupWindow { - fn drop(&mut self) { - // SAFETY: WM_CLOSE destroys the window on its owning thread. - unsafe { PostMessageW(self.handle as HWND, WM_CLOSE, 0, 0) }; - if let Some(thread) = self.thread.take() { - let _ = thread.join(); + if rect.right == 0 || rect.bottom == 0 { + return Ok(()); } - } -} - -struct State { - extent: [i32; 2], - pixels: Mutex<Vec<u32>>, -} - -fn show(state: &State, ready: mpsc::SyncSender<io::Result<usize>>) { - let class_name: Vec<_> = "FParkanStartup\0".encode_utf16().collect(); - let title: Vec<_> = "FParkan\0".encode_utf16().collect(); - // SAFETY: The class and window belong to this thread. The creation strings - // stay alive through their calls, and state outlives all window messages. - unsafe { - let instance = GetModuleHandleW(ptr::null()); - let class = WNDCLASSW { - lpfnWndProc: Some(window_proc), - hInstance: instance, - hCursor: LoadCursorW(ptr::null_mut(), IDC_ARROW), - lpszClassName: class_name.as_ptr(), - ..mem::zeroed() - }; - if RegisterClassW(&class) == 0 { - let _ = ready.send(Err(io::Error::last_os_error())); - return; + let dc = GetDC(hwnd); + if dc.is_null() { + return Err(io::Error::last_os_error()); } - let style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; - let [width, height] = state.extent; - let mut outer = RECT { - left: 0, - top: 0, - right: width, - bottom: height, + let mut info: BITMAPINFO = mem::zeroed(); + info.bmiHeader = BITMAPINFOHEADER { + biSize: mem::size_of::<BITMAPINFOHEADER>() as u32, + biWidth: width as i32, + biHeight: -(height as i32), + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB, + ..mem::zeroed() }; - AdjustWindowRectEx(&mut outer, style, 0, WS_EX_APPWINDOW); - let width = outer.right - outer.left; - let height = outer.bottom - outer.top; - let window = CreateWindowExW( - WS_EX_APPWINDOW, - class_name.as_ptr(), - title.as_ptr(), - style, - (GetSystemMetrics(SM_CXSCREEN) - width) / 2, - (GetSystemMetrics(SM_CYSCREEN) - height) / 2, - width, - height, - ptr::null_mut(), - ptr::null_mut(), - instance, - (state as *const State).cast(), + let result = StretchDIBits( + dc, + 0, + 0, + rect.right, + rect.bottom, + 0, + 0, + width as i32, + height as i32, + pixels.as_ptr().cast(), + &info, + DIB_RGB_COLORS, + SRCCOPY, ); - if window.is_null() { - let _ = ready.send(Err(io::Error::last_os_error())); - } else { - ShowWindow(window, SW_SHOW); - UpdateWindow(window); - if ready.send(Ok(window as usize)).is_ok() { - let mut message: MSG = mem::zeroed(); - while GetMessageW(&mut message, ptr::null_mut(), 0, 0) > 0 { - TranslateMessage(&message); - DispatchMessageW(&message); - } - } - if IsWindow(window) != 0 { - DestroyWindow(window); - } - } - UnregisterClassW(class_name.as_ptr(), instance); - } -} - -unsafe extern "system" fn window_proc( - window: HWND, - message: u32, - wparam: WPARAM, - data: LPARAM, -) -> LRESULT { - // SAFETY: Win32 supplies CREATESTRUCTW for WM_NCCREATE. The userdata points - // to the State kept alive by show until destruction. - unsafe { - match message { - WM_NCCREATE => { - let create = &*(data as *const CREATESTRUCTW); - SetWindowLongPtrW(window, GWLP_USERDATA, create.lpCreateParams as isize); - } - SET_FRAME => { - InvalidateRect(window, ptr::null(), 0); - UpdateWindow(window); - return 0; - } - WM_PAINT => { - let state = GetWindowLongPtrW(window, GWLP_USERDATA) as *const State; - if let Some(state) = state.as_ref() { - draw(window, state); - return 0; - } - } - WM_DESTROY => { - PostQuitMessage(0); - return 0; - } - _ => {} - } - DefWindowProcW(window, message, wparam, data) - } -} - -fn draw(window: HWND, state: &State) { - // SAFETY: The paint context is borrowed until EndPaint. The bitmap is - // locked while GDI reads its validated width × height 32-bit pixels. - unsafe { - let mut paint: PAINTSTRUCT = mem::zeroed(); - let dc = BeginPaint(window, &mut paint); - if !dc.is_null() { - if let Ok(frame) = state.pixels.lock() { - let [width, height] = state.extent; - let mut info: BITMAPINFO = mem::zeroed(); - info.bmiHeader = BITMAPINFOHEADER { - biSize: mem::size_of::<BITMAPINFOHEADER>() as u32, - biWidth: width, - biHeight: -height, - biPlanes: 1, - biBitCount: 32, - biCompression: BI_RGB, - ..mem::zeroed() - }; - let mut area: RECT = mem::zeroed(); - GetClientRect(window, &mut area); - StretchDIBits( - dc, - 0, - 0, - area.right, - area.bottom, - 0, - 0, - width, - height, - frame.as_ptr().cast(), - &info, - DIB_RGB_COLORS, - SRCCOPY, - ); - } + ReleaseDC(hwnd, dc); + if result == GDI_ERROR { + return Err(io::Error::other("GDI could not present the startup bitmap")); } - EndPaint(window, &paint); } + Ok(()) } |
