use super::*;
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetModuleHandleW(module_name: *const u16) -> isize;
fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
fn GetSystemPowerStatus(status: *mut Win32SystemPowerStatus) -> i32;
fn LoadLibraryW(lib_file_name: *const u16) -> isize;
fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
fn CreateEventW(
event_attributes: *const c_void,
manual_reset: i32,
initial_state: i32,
name: *const u16,
) -> isize;
fn SetEvent(handle: isize) -> i32;
fn CloseHandle(handle: isize) -> i32;
fn CreateWaitableTimerExW(
timer_attributes: *const c_void,
timer_name: *const u16,
flags: u32,
desired_access: u32,
) -> isize;
fn SetWaitableTimer(
timer: isize,
due_time: *const i64,
period: i32,
completion_routine: *const c_void,
arg_to_completion_routine: *mut c_void,
resume: i32,
) -> i32;
fn WaitForSingleObject(handle: isize, milliseconds: u32) -> u32;
}
#[link(name = "winmm")]
unsafe extern "system" {
fn timeBeginPeriod(period: u32) -> u32;
}
#[link(name = "user32")]
unsafe extern "system" {
fn RegisterClassExW(wc: *const WndClassExW) -> u16;
fn AdjustWindowRectEx(rect: *mut Win32Rect, style: u32, menu: i32, ex_style: u32) -> i32;
fn GetClientRect(hwnd: isize, rect: *mut Win32Rect) -> i32;
fn GetWindowLongW(hwnd: isize, index: i32) -> i32;
fn SetWindowLongW(hwnd: isize, index: i32, new_long: i32) -> i32;
fn GetWindowPlacement(hwnd: isize, lpwndpl: *mut Win32WindowPlacement) -> i32;
fn SetWindowPlacement(hwnd: isize, lpwndpl: *const Win32WindowPlacement) -> i32;
fn MonitorFromWindow(hwnd: isize, dw_flags: u32) -> isize;
fn GetMonitorInfoW(h_monitor: isize, lpmi: *mut Win32MonitorInfoExW) -> i32;
fn EnumDisplaySettingsW(
lpsz_device_name: *const u16,
i_mode_num: u32,
lp_dev_mode: *mut Win32DevModeW,
) -> i32;
fn ValidateRect(hwnd: isize, rect: *const Win32Rect) -> i32;
fn GetKeyState(virtual_key: i32) -> i16;
fn CreateWindowExW(
ex_style: u32,
class_name: *const u16,
window_name: *const u16,
style: u32,
value_x: i32,
value_y: i32,
width: i32,
height: i32,
parent: isize,
menu: isize,
instance: isize,
param: *mut c_void,
) -> isize;
fn DefWindowProcW(hwnd: isize, msg: u32, w_param: usize, l_param: isize) -> isize;
fn ShowWindow(hwnd: isize, cmd_show: i32) -> i32;
fn SetWindowTextW(hwnd: isize, text: *const u16) -> i32;
fn SetWindowPos(
hwnd: isize,
insert_after: isize,
value_x: i32,
value_y: i32,
cx: i32,
cy: i32,
flags: u32,
) -> i32;
fn DestroyWindow(hwnd: isize) -> i32;
fn GetDC(hwnd: isize) -> isize;
fn ReleaseDC(hwnd: isize, hdc: isize) -> i32;
fn GetDpiForWindow(hwnd: isize) -> u32;
fn PeekMessageW(
msg: *mut Win32Msg,
hwnd: isize,
filter_min: u32,
filter_max: u32,
remove_msg: u32,
) -> i32;
fn TranslateMessage(msg: *const Win32Msg) -> i32;
fn DispatchMessageW(msg: *const Win32Msg) -> isize;
fn MsgWaitForMultipleObjects(
n_count: u32,
p_handles: *const isize,
f_wait_all: i32,
dw_milliseconds: u32,
dw_wake_mask: u32,
) -> u32;
}
#[link(name = "gdi32")]
unsafe extern "system" {
fn SetStretchBltMode(hdc: isize, mode: i32) -> i32;
fn GetDeviceCaps(hdc: isize, index: i32) -> i32;
fn SetDIBitsToDevice(
hdc: isize,
x_dest: i32,
y_dest: i32,
width: u32,
height: u32,
x_src: i32,
y_src: i32,
start_scan: u32,
scan_lines: u32,
bits: *const c_void,
lpbmi: *const BitmapInfo,
color_use: u32,
) -> i32;
fn StretchDIBits(
hdc: isize,
x_dest: i32,
y_dest: i32,
dest_width: i32,
dest_height: i32,
x_src: i32,
y_src: i32,
src_width: i32,
src_height: i32,
bits: *const c_void,
lpbmi: *const BitmapInfo,
usage: u32,
rop: u32,
) -> i32;
}
pub fn win32_enable_high_res_timer() -> bool {
*WIN32_HIGH_RES_TIMER_INIT.get_or_init(|| -> bool {
unsafe { timeBeginPeriod(1) == 0 }
})
}
pub fn win32_sleep_precise_us(duration_us: u64) {
if duration_us == 0 {
return;
}
let _: bool = win32_enable_high_res_timer();
let timer_handle: isize = WIN32_WAITABLE_TIMER
.try_with(|slot: &Cell<isize>| -> isize {
let existing: isize = slot.get();
if existing != 0 {
return existing;
}
let created: isize = unsafe {
let hi: isize = CreateWaitableTimerExW(
null(),
null(),
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
TIMER_ALL_ACCESS,
);
if hi != 0 {
hi
} else {
CreateWaitableTimerExW(null(), null(), 0, TIMER_ALL_ACCESS)
}
};
slot.set(created);
created
})
.unwrap_or(0);
if timer_handle == 0 {
return;
}
let due_time_100ns: i64 = -((duration_us.min(60_000_000) as i64).saturating_mul(10));
unsafe {
if SetWaitableTimer(timer_handle, &due_time_100ns, 0, null(), null_mut(), 0) != 0 {
let _: u32 = WaitForSingleObject(timer_handle, WIN32_WAIT_INFINITE);
}
}
}
#[must_use]
pub fn win32_probe_dxgi_swapchain_config() -> Win32DxgiSwapChainConfig {
*WIN32_DXGI_SWAPCHAIN_CONFIG.get_or_init(|| -> Win32DxgiSwapChainConfig {
let dxgi_wide: Vec<u16> = win32_wide(WIN32_DLL_DXGI);
let dxgi_ok: bool = unsafe {
let mut module: isize = GetModuleHandleW(dxgi_wide.as_ptr());
if module == 0 {
module = LoadLibraryW(dxgi_wide.as_ptr());
}
if module == 0 {
false
} else {
!GetProcAddress(
module as *mut c_void,
WIN32_SYM_CREATE_DXGI_FACTORY1.as_ptr(),
)
.is_null()
}
};
if dxgi_ok {
Win32DxgiSwapChainConfig {
dxgi_available: true,
allow_tearing: true,
swap_chain_flags: DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT
| DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING,
present_flags: DXGI_PRESENT_ALLOW_TEARING,
}
} else {
Win32DxgiSwapChainConfig::default()
}
})
}
#[must_use]
pub(crate) fn win32_display_refresh_rate_hz(hwnd: usize) -> f32 {
unsafe {
let mut dev_mode: Win32DevModeW = MaybeUninit::<Win32DevModeW>::zeroed().assume_init();
dev_mode.dm_size = size_of::<Win32DevModeW>() as u16;
let mut queried_per_monitor: bool = false;
if hwnd != 0 {
let monitor: isize = MonitorFromWindow(hwnd as isize, MONITOR_DEFAULTTONEAREST);
if monitor != 0 {
let mut mon_info: Win32MonitorInfoExW =
MaybeUninit::<Win32MonitorInfoExW>::zeroed().assume_init();
mon_info.cb_size = size_of::<Win32MonitorInfoExW>() as u32;
if GetMonitorInfoW(monitor, &mut mon_info) != 0
&& EnumDisplaySettingsW(
mon_info.sz_device.as_ptr(),
ENUM_CURRENT_SETTINGS,
&mut dev_mode,
) != 0
{
queried_per_monitor = true;
}
}
}
if !queried_per_monitor
&& EnumDisplaySettingsW(null(), ENUM_CURRENT_SETTINGS, &mut dev_mode) != 0
{
queried_per_monitor = true;
}
if queried_per_monitor && dev_mode.dm_display_frequency >= 24 {
return (dev_mode.dm_display_frequency as f32).max(MIN_REFRESH_RATE_HZ);
}
let hdc: isize = GetDC(hwnd as isize);
if hdc == 0 {
return FALLBACK_REFRESH_RATE_HZ;
}
let hz: i32 = GetDeviceCaps(hdc, GDI_VREFRESH);
let _: i32 = ReleaseDC(hwnd as isize, hdc);
if hz >= 24 {
(hz as f32).max(MIN_REFRESH_RATE_HZ)
} else {
FALLBACK_REFRESH_RATE_HZ
}
}
}
pub(crate) fn win32_wide(text: &str) -> Vec<u16> {
let mut wide: Vec<u16> = text.encode_utf16().collect();
wide.push(0);
wide
}
fn win32_enable_dpi_awareness() {
let user32_wide: Vec<u16> = win32_wide(WIN32_DLL_USER32);
unsafe {
let user32: isize = GetModuleHandleW(user32_wide.as_ptr());
if user32 != 0 {
let sym: *mut c_void =
GetProcAddress(user32 as *mut c_void, WIN32_SYM_SET_DPI_CONTEXT.as_ptr());
if !sym.is_null() {
let func: unsafe extern "system" fn(isize) -> i32 = transmute(sym);
let _: i32 = func(DPI_AWARENESS_CONTEXT_PER_MONITOR_V2);
}
}
}
}
#[must_use]
fn win32_modifiers() -> Modifiers {
unsafe {
let shift: bool = GetKeyState(VK_SHIFT) < 0;
let ctrl: bool = GetKeyState(VK_CONTROL) < 0;
let alt: bool = GetKeyState(VK_MENU) < 0;
let meta: bool = GetKeyState(VK_LWIN) < 0 || GetKeyState(VK_RWIN) < 0;
Modifiers::new(shift, ctrl, alt, meta)
}
}
#[must_use]
fn win32_vk_to_keycode(vk: u32) -> KeyCode {
match vk {
0x08 => KeyCode::Backspace,
0x09 => KeyCode::Tab,
0x0D => KeyCode::Enter,
0x1B => KeyCode::Escape,
0x20 => KeyCode::Space,
0x21 => KeyCode::PageUp,
0x22 => KeyCode::PageDown,
0x23 => KeyCode::End,
0x24 => KeyCode::Home,
0x25 => KeyCode::ArrowLeft,
0x26 => KeyCode::ArrowUp,
0x27 => KeyCode::ArrowRight,
0x28 => KeyCode::ArrowDown,
0x2E => KeyCode::Delete,
0x30..=0x39 => KeyCode::Character((vk as u8) as char),
0x41..=0x5A => KeyCode::Character(((vk as u8) + 32) as char),
_ => KeyCode::Unknown,
}
}
fn win32_push_event(hwnd: isize, payload: Win32EventPayload) {
let _: Result<(), _> =
WIN32_EVENT_QUEUE.try_with(|query_val: &RefCell<Vec<Win32QueuedEvent>>| {
if let Ok(mut guard) = query_val.try_borrow_mut() {
guard.push(Win32QueuedEvent {
hwnd: hwnd as usize,
payload,
});
}
});
}
pub(crate) unsafe extern "system" fn win32_wnd_proc(
hwnd: isize,
msg: u32,
w_param: usize,
l_param: isize,
) -> isize {
match msg {
WM_CLOSE => {
win32_push_event(hwnd, Win32EventPayload::Close);
return 0;
}
WM_DESTROY => {
win32_push_event(hwnd, Win32EventPayload::Destroyed);
}
WM_ACTIVATEAPP => {
win32_push_event(hwnd, Win32EventPayload::Activated(w_param != 0));
}
WM_SIZE => {
if w_param == SIZE_MINIMIZED {
win32_push_event(hwnd, Win32EventPayload::Minimized(true));
} else {
win32_push_event(hwnd, Win32EventPayload::Minimized(false));
let phys_w: u32 = ((l_param & 0xFFFF) as u32).max(1);
let phys_h: u32 = (((l_param >> 16) & 0xFFFF) as u32).max(1);
let dpi: u32 = unsafe { GetDpiForWindow(hwnd) };
let scale: f32 = if dpi > 0 {
(dpi as f32) / WIN32_DEFAULT_DPI
} else {
1.0
};
win32_push_event(hwnd, Win32EventPayload::Resized(phys_w, phys_h, scale));
}
}
WM_SETTINGCHANGE | WM_THEMECHANGED => {
win32_push_event(hwnd, Win32EventPayload::ThemeUpdated);
}
WM_CLIPBOARDUPDATE => {
win32_push_event(hwnd, Win32EventPayload::ClipboardUpdated);
}
WM_POWERBROADCAST if w_param == PBT_POWERSTATUSCHANGE => {
let mut node_style: Win32SystemPowerStatus = Win32SystemPowerStatus::default();
let ok: i32 = unsafe { GetSystemPowerStatus(&mut node_style) };
if ok != 0 {
let low_power: bool = (node_style.system_status_flag & 1) != 0;
win32_push_event(hwnd, Win32EventPayload::PowerStatusChanged(low_power));
}
}
WM_DPICHANGED => {
let dpi: u32 = (w_param & 0xFFFF) as u32;
let raw_scale: f32 = if dpi > 0 {
(dpi as f32) / WIN32_DEFAULT_DPI
} else {
1.0
};
let scale: f32 = clamp_viewport_scale(raw_scale);
if l_param != 0 {
let suggested: Win32Rect = unsafe { *(l_param as *const Win32Rect) };
let sug_w: i32 = (suggested.right - suggested.left).max(1);
let sug_h: i32 = (suggested.bottom - suggested.top).max(1);
let _: i32 = unsafe {
SetWindowPos(
hwnd,
0,
suggested.left,
suggested.top,
sug_w,
sug_h,
SWP_NOZORDER_NOACTIVATE,
)
};
}
let mut rect: Win32Rect = Win32Rect::default();
let _: i32 = unsafe { GetClientRect(hwnd, &mut rect) };
let phys_w: u32 = (rect.right - rect.left).max(1) as u32;
let phys_h: u32 = (rect.bottom - rect.top).max(1) as u32;
win32_push_event(hwnd, Win32EventPayload::Resized(phys_w, phys_h, scale));
}
WM_DISPLAYCHANGE => {
win32_push_event(hwnd, Win32EventPayload::DisplayChanged);
}
WM_PAINT => {
let _: i32 = unsafe { ValidateRect(hwnd, null()) };
win32_push_event(hwnd, Win32EventPayload::Redraw);
return 0;
}
WM_SETFOCUS => {
win32_push_event(hwnd, Win32EventPayload::Focused(true));
}
WM_KILLFOCUS => {
win32_push_event(hwnd, Win32EventPayload::Focused(false));
}
WM_CANCELMODE | WM_CAPTURECHANGED => {
win32_push_event(hwnd, Win32EventPayload::PointerCancel);
}
WM_MOUSEMOVE => {
let pos_x: i32 = (l_param & 0xFFFF) as i16 as i32;
let pos_y: i32 = ((l_param >> 16) & 0xFFFF) as i16 as i32;
win32_push_event(
hwnd,
Win32EventPayload::PointerMove(pos_x, pos_y, win32_modifiers()),
);
}
WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => {
let coord_x: i32 = (l_param & 0xFFFF) as i16 as i32;
let coord_y: i32 = ((l_param >> 16) & 0xFFFF) as i16 as i32;
let point_coords: PointerButton = match msg {
WM_RBUTTONDOWN => PointerButton::Secondary,
WM_MBUTTONDOWN => PointerButton::Auxiliary,
_ => PointerButton::Primary,
};
win32_push_event(
hwnd,
Win32EventPayload::PointerDown(coord_x, coord_y, point_coords, win32_modifiers()),
);
}
WM_LBUTTONUP | WM_RBUTTONUP | WM_MBUTTONUP => {
let sample_x: i32 = (l_param & 0xFFFF) as i16 as i32;
let sample_y: i32 = ((l_param >> 16) & 0xFFFF) as i16 as i32;
let cursor_point: PointerButton = match msg {
WM_RBUTTONUP => PointerButton::Secondary,
WM_MBUTTONUP => PointerButton::Auxiliary,
_ => PointerButton::Primary,
};
win32_push_event(
hwnd,
Win32EventPayload::PointerUp(sample_x, sample_y, cursor_point, win32_modifiers()),
);
}
WM_MOUSEWHEEL => {
let wheel_delta: i16 = ((w_param >> 16) & 0xFFFF) as i16;
let dy: f32 = -((wheel_delta as f32) / 120.0) * 40.0;
win32_push_event(hwnd, Win32EventPayload::Scroll(dy));
}
WM_KEYDOWN => {
let repeat: bool = (l_param & (1 << 30)) != 0;
let code: KeyCode = win32_vk_to_keycode(w_param as u32);
win32_push_event(
hwnd,
Win32EventPayload::KeyDown(code, win32_modifiers(), repeat),
);
}
WM_KEYUP => {
let code: KeyCode = win32_vk_to_keycode(w_param as u32);
win32_push_event(hwnd, Win32EventPayload::KeyUp(code, win32_modifiers()));
}
WM_CHAR => {
if let Some(ch) = char::from_u32(w_param as u32)
&& !ch.is_control()
{
win32_push_event(hwnd, Win32EventPayload::Text(ch));
}
}
_ => {}
}
unsafe { DefWindowProcW(hwnd, msg, w_param, l_param) }
}
pub(crate) fn win32_create_window(
config: &WindowConfig,
class_registered: &mut bool,
) -> Result<(usize, usize, f32), PlatformError> {
let _: bool = win32_enable_high_res_timer();
win32_enable_dpi_awareness();
let class_wide: Vec<u16> = win32_wide(WIN32_CLASS_NAME);
let title_wide: Vec<u16> = win32_wide(config.get_title());
unsafe {
let hinstance: isize = GetModuleHandleW(null());
if !*class_registered {
let wc: WndClassExW = WndClassExW {
cb_size: size_of::<WndClassExW>() as u32,
style: 0,
lpfn_wnd_proc: win32_wnd_proc,
cb_cls_extra: 0,
cb_wnd_extra: 0,
h_instance: hinstance,
h_icon: 0,
h_cursor: 0,
hbr_background: 0,
lpsz_menu_name: null(),
lpsz_class_name: class_wide.as_ptr(),
h_icon_sm: 0,
};
let _: u16 = RegisterClassExW(&wc);
*class_registered = true;
}
let style: u32 = if config.get_decorations() {
WS_OVERLAPPEDWINDOW
} else {
WS_POPUP
};
let mut rect: Win32Rect = Win32Rect {
left: 0,
top: 0,
right: config.get_width().max(1) as i32,
bottom: config.get_height().max(1) as i32,
};
let _: i32 = AdjustWindowRectEx(&mut rect, style, 0, 0);
let outer_w: i32 = (rect.right - rect.left).max(1);
let outer_h: i32 = (rect.bottom - rect.top).max(1);
let (pos_x, pos_y): (i32, i32) = config
.position_value()
.unwrap_or((CW_USEDEFAULT, CW_USEDEFAULT));
let hwnd: isize = CreateWindowExW(
0,
class_wide.as_ptr(),
title_wide.as_ptr(),
style,
pos_x,
pos_y,
outer_w,
outer_h,
0,
0,
hinstance,
null_mut(),
);
if hwnd == 0 {
return Err(PlatformError::InitializationFailed(
ERR_WIN32_CREATE_WINDOW.to_string(),
));
}
if config.get_always_on_top() {
let _: i32 = SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE_NOSIZE);
}
let dpi: u32 = GetDpiForWindow(hwnd);
let scale: f32 = if dpi > 0 {
(dpi as f32) / WIN32_DEFAULT_DPI
} else {
1.0
};
Ok((hwnd as usize, hinstance as usize, scale))
}
}
fn win32_pack_bgra_subrect(
framebuffer: &Framebuffer,
x0: u32,
y0: u32,
width: u32,
height: u32,
) -> Vec<u8> {
let fb_w: usize = framebuffer.get_width() as usize;
let src: &[u8] = framebuffer.get_pixels().as_slice();
let mut bgra: Vec<u8> = Vec::with_capacity((width as usize) * (height as usize) * 4);
for row in y0..(y0 + height) {
let row_start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
let row_end: usize = row_start + (width as usize) * 4;
if row_end <= src.len() {
for px in src[row_start..row_end].chunks_exact(4) {
bgra.push(px[2]);
bgra.push(px[1]);
bgra.push(px[0]);
bgra.push(px[3]);
}
}
}
bgra
}
pub(crate) fn win32_present_dib(
hwnd: usize,
framebuffer: &Framebuffer,
dirty_rect: Option<Rect>,
) -> Result<(), PlatformError> {
if hwnd == 0 {
return Ok(());
}
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
let src_w: i32 = fb_w as i32;
let src_h: i32 = fb_h as i32;
if src_w <= 0 || src_h <= 0 {
return Ok(());
}
unsafe {
let mut client: Win32Rect = Win32Rect::default();
let got_rect: i32 = GetClientRect(hwnd as isize, &mut client);
let dst_w: i32 = if got_rect != 0 && (client.right - client.left) > 0 {
client.right - client.left
} else {
src_w
};
let dst_h: i32 = if got_rect != 0 && (client.bottom - client.top) > 0 {
client.bottom - client.top
} else {
src_h
};
let hdc: isize = GetDC(hwnd as isize);
if hdc == 0 {
return Ok(());
}
if dst_w == src_w
&& dst_h == src_h
&& let Some(red_val) = dirty_rect
{
let x0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
let y0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
let x1: u32 =
((red_val.get_x() + red_val.get_width()).ceil().max(0.0) as u32).min(fb_w);
let y1: u32 =
((red_val.get_y() + red_val.get_height()).ceil().max(0.0) as u32).min(fb_h);
if x1 > x0 && y1 > y0 {
let rw: u32 = x1 - x0;
let rh: u32 = y1 - y0;
let bgra: Vec<u8> = win32_pack_bgra_subrect(framebuffer, x0, y0, rw, rh);
let info: BitmapInfo = BitmapInfo {
header: BitmapInfoHeader {
bi_size: size_of::<BitmapInfoHeader>() as u32,
bi_width: rw as i32,
bi_height: -(rh as i32),
bi_planes: 1,
bi_bit_count: 32,
bi_compression: BI_RGB,
bi_size_image: bgra.len() as u32,
bi_x_pels_per_meter: 0,
bi_y_pels_per_meter: 0,
bi_clr_used: 0,
bi_clr_important: 0,
},
colors: [0],
};
let _: i32 = SetDIBitsToDevice(
hdc,
x0 as i32,
y0 as i32,
rw,
rh,
0,
0,
0,
rh,
bgra.as_ptr().cast::<c_void>(),
&info,
DIB_RGB_COLORS,
);
let _: i32 = ReleaseDC(hwnd as isize, hdc);
return Ok(());
}
}
let bgra: Vec<u8> = framebuffer.to_bgra_bytes();
let info: BitmapInfo = BitmapInfo {
header: BitmapInfoHeader {
bi_size: size_of::<BitmapInfoHeader>() as u32,
bi_width: src_w,
bi_height: -src_h,
bi_planes: 1,
bi_bit_count: 32,
bi_compression: BI_RGB,
bi_size_image: bgra.len() as u32,
bi_x_pels_per_meter: 0,
bi_y_pels_per_meter: 0,
bi_clr_used: 0,
bi_clr_important: 0,
},
colors: [0],
};
if dst_w == src_w && dst_h == src_h {
let _: i32 = SetDIBitsToDevice(
hdc,
0,
0,
fb_w,
fb_h,
0,
0,
0,
fb_h,
bgra.as_ptr().cast::<c_void>(),
&info,
DIB_RGB_COLORS,
);
} else {
let _: i32 = SetStretchBltMode(hdc, STRETCH_HALFTONE);
let _: i32 = StretchDIBits(
hdc,
0,
0,
dst_w,
dst_h,
0,
0,
src_w,
src_h,
bgra.as_ptr().cast::<c_void>(),
&info,
DIB_RGB_COLORS,
SRCCOPY,
);
}
let _: i32 = ReleaseDC(hwnd as isize, hdc);
}
Ok(())
}
pub(crate) fn win32_create_wake_event() -> isize {
unsafe { CreateEventW(null(), 0, 0, null()) }
}
pub(crate) fn win32_signal_wake_event(handle: isize) -> bool {
if handle == 0 {
return false;
}
unsafe { SetEvent(handle) != 0 }
}
pub(crate) fn win32_close_handle(handle: isize) {
if handle == 0 {
return;
}
unsafe {
let _: i32 = CloseHandle(handle);
}
}
pub(crate) fn win32_wait_for_events(wait_handles: &[isize], timeout_ms: u32) -> u32 {
let count: u32 = wait_handles.len().min(63) as u32;
let ptr: *const isize = if count == 0 {
null()
} else {
wait_handles.as_ptr()
};
unsafe { MsgWaitForMultipleObjects(count, ptr, 0, timeout_ms, WIN32_QS_ALLINPUT) }
}
pub(crate) fn win32_d3d11_syms() -> &'static Win32D3d11Syms {
WIN32_D3D11_SYMS.get_or_init(|| -> Win32D3d11Syms {
unsafe {
let dxgi_mod: *mut c_void = LoadLibraryA(WIN32_DLL_DXGI_ASCII.as_ptr());
let d3d11_mod: *mut c_void = LoadLibraryA(WIN32_DLL_D3D11_ASCII.as_ptr());
let compiler_mod: *mut c_void = LoadLibraryA(WIN32_DLL_D3DCOMPILER_ASCII.as_ptr());
let create_dxgi_factory1: usize = if !dxgi_mod.is_null() {
GetProcAddress(dxgi_mod, WIN32_SYM_CREATE_DXGI_FACTORY1.as_ptr()) as usize
} else {
0
};
let d3d11_create_device: usize = if !d3d11_mod.is_null() {
GetProcAddress(d3d11_mod, WIN32_SYM_D3D11_CREATE_DEVICE.as_ptr()) as usize
} else {
0
};
let d3d_compile: usize = if !compiler_mod.is_null() {
GetProcAddress(compiler_mod, WIN32_SYM_D3D_COMPILE.as_ptr()) as usize
} else {
0
};
Win32D3d11Syms {
create_dxgi_factory1,
d3d11_create_device,
d3d_compile,
}
}
})
}
unsafe fn win32_com_vtable_slot(obj: *mut c_void, slot: usize) -> *const c_void {
let vtable: *const *const c_void = unsafe { *obj.cast::<*const *const c_void>() };
unsafe { *vtable.add(slot) }
}
pub(crate) fn win32_com_release(obj_addr: usize) {
if obj_addr == 0 {
return;
}
let obj: *mut c_void = obj_addr as *mut c_void;
unsafe {
let release_fn: Win32ComUnknownReleaseVtableFn = transmute(win32_com_vtable_slot(obj, 2));
let _: u32 = release_fn(obj);
}
}
unsafe fn win32_com_query_interface(obj: *mut c_void, iid: &[u8; 16]) -> Option<*mut c_void> {
if obj.is_null() {
return None;
}
let mut out: *mut c_void = null_mut();
let hr: i32 = unsafe {
let qi_fn: Win32ComQueryInterfaceVtableFn = transmute(win32_com_vtable_slot(obj, 0));
qi_fn(obj, iid, &mut out)
};
if hr >= 0 && !out.is_null() {
Some(out)
} else {
None
}
}
unsafe fn win32_compile_hlsl_source(
d3d_compile: usize,
source: &str,
entry: &str,
target: &str,
) -> Option<Vec<u8>> {
if d3d_compile == 0 || source.is_empty() {
return None;
}
let mut code_blob: *mut c_void = null_mut();
let mut err_blob: *mut c_void = null_mut();
let hr: i32 = unsafe {
let compile_fn: Win32D3dCompileEntryPointFn = transmute(d3d_compile as *const c_void);
compile_fn(
source.as_ptr().cast::<c_void>(),
source.len(),
null(),
null(),
null(),
entry.as_ptr(),
target.as_ptr(),
0,
0,
&mut code_blob,
&mut err_blob,
)
};
win32_com_release(err_blob as usize);
if hr < 0 || code_blob.is_null() {
win32_com_release(code_blob as usize);
return None;
}
let bytecode: Vec<u8> = unsafe {
let ptr_fn: Win32D3dBlobGetBufferPointerVtableFn =
transmute(win32_com_vtable_slot(code_blob, 3));
let len_fn: Win32D3dBlobGetBufferSizeVtableFn =
transmute(win32_com_vtable_slot(code_blob, 4));
let ptr: *const u8 = ptr_fn(code_blob).cast::<u8>();
let len: usize = len_fn(code_blob);
if ptr.is_null() || len == 0 {
Vec::new()
} else {
from_raw_parts(ptr, len).to_vec()
}
};
win32_com_release(code_blob as usize);
if bytecode.is_empty() {
None
} else {
Some(bytecode)
}
}
unsafe fn win32_compile_hlsl(d3d_compile: usize, entry: &str, target: &str) -> Option<Vec<u8>> {
unsafe { win32_compile_hlsl_source(d3d_compile, HLSL_UI_SHADER, entry, target) }
}
unsafe fn win32_d3d11_create_texture_with_srv(
device: *mut c_void,
width: u32,
height: u32,
format: u32,
pixels: &[u8],
row_pitch: u32,
) -> Option<(usize, usize)> {
let tex_desc: D3d11Texture2dDesc = D3d11Texture2dDesc {
width: width.max(1),
height: height.max(1),
mip_levels: 1,
array_size: 1,
format,
sample_desc: DxgiSampleDesc {
count: 1,
quality: 0,
},
usage: D3D11_USAGE_DEFAULT,
bind_flags: D3D11_BIND_SHADER_RESOURCE,
cpu_access_flags: 0,
misc_flags: 0,
};
let init_data: D3d11SubresourceData = D3d11SubresourceData {
sys_mem: pixels.as_ptr().cast::<c_void>(),
sys_mem_pitch: row_pitch,
sys_mem_slice_pitch: 0,
};
let mut tex: *mut c_void = null_mut();
let tex_hr: i32 = unsafe {
let create_tex: Win32D3d11CreateTexture2dVtableFn =
transmute(win32_com_vtable_slot(device, 5));
create_tex(device, &tex_desc, &init_data, &mut tex)
};
if tex_hr < 0 || tex.is_null() {
return None;
}
let srv_desc: D3d11SrvDesc = D3d11SrvDesc {
format,
view_dimension: D3D11_SRV_DIMENSION_TEXTURE2D,
union_first: 0,
union_second: 1,
union_pad: [0; 2],
};
let mut srv: *mut c_void = null_mut();
let srv_hr: i32 = unsafe {
let create_srv: Win32D3d11CreateSrvVtableFn = transmute(win32_com_vtable_slot(device, 7));
create_srv(device, tex, &srv_desc, &mut srv)
};
if srv_hr < 0 || srv.is_null() {
win32_com_release(tex as usize);
return None;
}
Some((tex as usize, srv as usize))
}
unsafe fn win32_d3d11_create_backbuffer_rtv(
device: *mut c_void,
swap_chain: *mut c_void,
) -> Option<usize> {
let mut backbuffer: *mut c_void = null_mut();
let buf_hr: i32 = unsafe {
let get_buf: Win32DxgiGetBufferVtableFn = transmute(win32_com_vtable_slot(swap_chain, 9));
get_buf(swap_chain, 0, &IID_ID3D11_TEXTURE2D, &mut backbuffer)
};
if buf_hr < 0 || backbuffer.is_null() {
return None;
}
let mut rtv: *mut c_void = null_mut();
let rtv_hr: i32 = unsafe {
let create_rtv: Win32D3d11CreateRtvVtableFn = transmute(win32_com_vtable_slot(device, 9));
create_rtv(device, backbuffer, null(), &mut rtv)
};
win32_com_release(backbuffer as usize);
if rtv_hr < 0 || rtv.is_null() {
None
} else {
Some(rtv as usize)
}
}
pub(crate) fn win32_d3d11_create_swapchain(
hwnd: usize,
width: u32,
height: u32,
dxgi_cfg: Win32DxgiSwapChainConfig,
) -> Option<Win32D3d11SwapChain> {
if cfg!(target_arch = "x86") || hwnd == 0 || !dxgi_cfg.get_dxgi_available() {
return None;
}
let syms: &Win32D3d11Syms = win32_d3d11_syms();
if syms.get_create_dxgi_factory1() == 0
|| syms.get_d3d11_create_device() == 0
|| syms.get_d3d_compile() == 0
{
return None;
}
let w: u32 = width.max(1);
let h: u32 = height.max(1);
unsafe {
let feature_levels: [u32; 1] = [D3D_FEATURE_LEVEL_11_0];
let mut device: *mut c_void = null_mut();
let mut context: *mut c_void = null_mut();
let mut chosen_level: u32 = 0;
let create_dev: Win32D3d11CreateDeviceEntryPointFn =
transmute(syms.get_d3d11_create_device() as *const c_void);
let dev_hr: i32 = create_dev(
null_mut(),
D3D_DRIVER_TYPE_HARDWARE,
0,
0,
feature_levels.as_ptr(),
1,
D3D11_SDK_VERSION,
&mut device,
&mut chosen_level,
&mut context,
);
if dev_hr < 0 || device.is_null() || context.is_null() {
win32_com_release(context as usize);
win32_com_release(device as usize);
return None;
}
let mut swapchain_state: Win32D3d11SwapChain = Win32D3d11SwapChain::default();
swapchain_state.set_device(device as usize);
swapchain_state.set_context(context as usize);
swapchain_state.set_width(w);
swapchain_state.set_height(h);
swapchain_state.set_swap_chain_flags(dxgi_cfg.get_swap_chain_flags());
swapchain_state.set_present_flags(dxgi_cfg.get_present_flags());
let mut factory2: *mut c_void = null_mut();
let create_factory: Win32CreateDxgiFactory1EntryPointFn =
transmute(syms.get_create_dxgi_factory1() as *const c_void);
let fac_hr: i32 = create_factory(&IID_IDXGI_FACTORY2, &mut factory2);
if fac_hr < 0 || factory2.is_null() {
return None;
}
let mut tearing_supported: bool =
(dxgi_cfg.get_swap_chain_flags() & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0;
if let Some(factory5) = win32_com_query_interface(factory2, &IID_IDXGI_FACTORY5) {
let mut allow_tearing: u32 = 0;
let check_feat: Win32DxgiFactory5CheckFeatureSupportVtableFn =
transmute(win32_com_vtable_slot(factory5, 28));
if check_feat(
factory5,
DXGI_FEATURE_PRESENT_ALLOW_TEARING,
(&mut allow_tearing as *mut u32).cast::<c_void>(),
size_of::<u32>() as u32,
) >= 0
{
tearing_supported = allow_tearing != 0;
}
win32_com_release(factory5 as usize);
}
let mut sc_flags: u32 = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT
| if tearing_supported {
DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING
} else {
0
};
let mut present_flags: u32 = if tearing_supported {
DXGI_PRESENT_ALLOW_TEARING
} else {
0
};
let mut desc: DxgiSwapChainDesc1 = DxgiSwapChainDesc1 {
width: w,
height: h,
format: DXGI_FORMAT_R8G8B8A8_UNORM,
stereo: 0,
sample_desc: DxgiSampleDesc {
count: 1,
quality: 0,
},
buffer_usage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
buffer_count: 3,
scaling: DXGI_SCALING_NONE,
swap_effect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
alpha_mode: DXGI_ALPHA_MODE_IGNORE,
flags: sc_flags,
};
let create_sc_for_hwnd: Win32DxgiCreateSwapChainForHwndVtableFn =
transmute(win32_com_vtable_slot(factory2, 15));
let mut swap_chain: *mut c_void = null_mut();
let mut sc_hr: i32 = create_sc_for_hwnd(
factory2,
device,
hwnd as isize,
&desc,
null(),
null_mut(),
&mut swap_chain,
);
if sc_hr < 0 {
sc_flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
present_flags = 0;
desc.flags = sc_flags;
sc_hr = create_sc_for_hwnd(
factory2,
device,
hwnd as isize,
&desc,
null(),
null_mut(),
&mut swap_chain,
);
}
win32_com_release(factory2 as usize);
if sc_hr < 0 || swap_chain.is_null() {
return None;
}
swapchain_state.set_swap_chain(swap_chain as usize);
swapchain_state.set_swap_chain_flags(sc_flags);
swapchain_state.set_present_flags(present_flags);
if let Some(sc2) = win32_com_query_interface(swap_chain, &IID_IDXGI_SWAP_CHAIN2) {
swapchain_state.set_swap_chain2(sc2 as usize);
let set_lat: Win32DxgiSetMaximumFrameLatencyVtableFn =
transmute(win32_com_vtable_slot(sc2, 31));
let _: i32 = set_lat(sc2, 2);
let get_waitable: Win32DxgiGetFrameLatencyWaitableVtableFn =
transmute(win32_com_vtable_slot(sc2, 33));
swapchain_state.set_waitable_handle(get_waitable(sc2));
}
let rtv: usize = win32_d3d11_create_backbuffer_rtv(device, swap_chain)?;
swapchain_state.set_rtv(rtv);
let vs_bytes: Vec<u8> = win32_compile_hlsl(
syms.get_d3d_compile(),
WIN32_HLSL_ENTRY_VS,
WIN32_HLSL_TARGET_VS,
)?;
let ps_bytes: Vec<u8> = win32_compile_hlsl(
syms.get_d3d_compile(),
WIN32_HLSL_ENTRY_PS,
WIN32_HLSL_TARGET_PS,
)?;
let mut vs: *mut c_void = null_mut();
let create_vs: Win32D3d11CreateShaderVtableFn =
transmute(win32_com_vtable_slot(device, 12));
if create_vs(
device,
vs_bytes.as_ptr().cast::<c_void>(),
vs_bytes.len(),
null_mut(),
&mut vs,
) < 0
|| vs.is_null()
{
return None;
}
swapchain_state.set_vertex_shader(vs as usize);
let mut ps: *mut c_void = null_mut();
let create_ps: Win32D3d11CreateShaderVtableFn =
transmute(win32_com_vtable_slot(device, 15));
if create_ps(
device,
ps_bytes.as_ptr().cast::<c_void>(),
ps_bytes.len(),
null_mut(),
&mut ps,
) < 0
|| ps.is_null()
{
return None;
}
swapchain_state.set_pixel_shader(ps as usize);
let cb_desc: D3d11BufferDesc = D3d11BufferDesc {
byte_width: size_of::<D3d11LayerUniforms>() as u32,
usage: D3D11_USAGE_DEFAULT,
bind_flags: D3D11_BIND_CONSTANT_BUFFER,
cpu_access_flags: 0,
misc_flags: 0,
structure_byte_stride: 0,
};
let mut cb: *mut c_void = null_mut();
let create_buf: Win32D3d11CreateBufferVtableFn =
transmute(win32_com_vtable_slot(device, 3));
if create_buf(device, &cb_desc, null(), &mut cb) < 0 || cb.is_null() {
return None;
}
swapchain_state.set_constant_buffer(cb as usize);
let mut blend_desc: D3d11BlendDesc = D3d11BlendDesc::default();
blend_desc.render_target[0] = D3d11RenderTargetBlendDesc {
blend_enable: 1,
src_blend: D3D11_BLEND_SRC_ALPHA,
dest_blend: D3D11_BLEND_INV_SRC_ALPHA,
blend_op: D3D11_BLEND_OP_ADD,
src_blend_alpha: D3D11_BLEND_ONE,
dest_blend_alpha: D3D11_BLEND_INV_SRC_ALPHA,
blend_op_alpha: D3D11_BLEND_OP_ADD,
render_target_write_mask: D3D11_COLOR_WRITE_ENABLE_ALL,
};
let mut blend_state: *mut c_void = null_mut();
let create_blend: Win32D3d11CreateBlendStateVtableFn =
transmute(win32_com_vtable_slot(device, 20));
if create_blend(device, &blend_desc, &mut blend_state) < 0 || blend_state.is_null() {
return None;
}
swapchain_state.set_blend_state(blend_state as usize);
let mut opaque_desc: D3d11BlendDesc = D3d11BlendDesc::default();
opaque_desc.render_target[0] = D3d11RenderTargetBlendDesc {
blend_enable: 0,
src_blend: D3D11_BLEND_ONE,
dest_blend: D3D11_BLEND_ONE,
blend_op: D3D11_BLEND_OP_ADD,
src_blend_alpha: D3D11_BLEND_ONE,
dest_blend_alpha: D3D11_BLEND_ONE,
blend_op_alpha: D3D11_BLEND_OP_ADD,
render_target_write_mask: D3D11_COLOR_WRITE_ENABLE_ALL,
};
let mut opaque_blend_state: *mut c_void = null_mut();
if create_blend(device, &opaque_desc, &mut opaque_blend_state) < 0
|| opaque_blend_state.is_null()
{
return None;
}
swapchain_state.set_opaque_blend_state(opaque_blend_state as usize);
let raster_desc: D3d11RasterizerDesc = D3d11RasterizerDesc {
fill_mode: D3D11_FILL_SOLID,
cull_mode: D3D11_CULL_NONE,
front_counter_clockwise: 0,
depth_bias: 0,
depth_bias_clamp: 0.0,
slope_scaled_depth_bias: 0.0,
depth_clip_enable: 1,
scissor_enable: 1,
multisample_enable: 0,
antialiased_line_enable: 0,
};
let mut raster_state: *mut c_void = null_mut();
let create_raster: Win32D3d11CreateRasterizerStateVtableFn =
transmute(win32_com_vtable_slot(device, 22));
if create_raster(device, &raster_desc, &mut raster_state) < 0 || raster_state.is_null() {
return None;
}
swapchain_state.set_rasterizer_state(raster_state as usize);
let sampler_desc: D3d11SamplerDesc = D3d11SamplerDesc {
filter: D3D11_FILTER_MIN_MAG_MIP_LINEAR,
address_u: D3D11_TEXTURE_ADDRESS_CLAMP,
address_v: D3D11_TEXTURE_ADDRESS_CLAMP,
address_w: D3D11_TEXTURE_ADDRESS_CLAMP,
mip_lod_bias: 0.0,
max_anisotropy: 1,
comparison_func: D3D11_COMPARISON_NEVER,
border_color: [0.0; 4],
min_lod: 0.0,
max_lod: 0.0,
};
let mut sampler_state: *mut c_void = null_mut();
let create_sampler: Win32D3d11CreateSamplerStateVtableFn =
transmute(win32_com_vtable_slot(device, 23));
if create_sampler(device, &sampler_desc, &mut sampler_state) < 0 || sampler_state.is_null()
{
return None;
}
swapchain_state.set_sampler_state(sampler_state as usize);
let one_r8: [u8; 1] = [255];
let one_rgba: [u8; 4] = [255, 255, 255, 255];
let (gr8_t, gr8_s): (usize, usize) =
win32_d3d11_create_texture_with_srv(device, 1, 1, DXGI_FORMAT_R8_UNORM, &one_r8, 1)?;
swapchain_state.set_glyph_r8_tex(gr8_t);
swapchain_state.set_glyph_r8_srv(gr8_s);
swapchain_state.set_glyph_r8_w(1);
swapchain_state.set_glyph_r8_h(1);
let (grgba_t, grgba_s): (usize, usize) = win32_d3d11_create_texture_with_srv(
device,
1,
1,
DXGI_FORMAT_R8G8B8A8_UNORM,
&one_rgba,
4,
)?;
swapchain_state.set_glyph_rgba8_tex(grgba_t);
swapchain_state.set_glyph_rgba8_srv(grgba_s);
let (img_t, img_s): (usize, usize) = win32_d3d11_create_texture_with_srv(
device,
1,
1,
DXGI_FORMAT_R8G8B8A8_UNORM,
&one_rgba,
4,
)?;
swapchain_state.set_image_tex(img_t);
swapchain_state.set_image_srv(img_s);
swapchain_state.set_image_w(1);
swapchain_state.set_image_h(1);
let (ext_t, ext_s): (usize, usize) = win32_d3d11_create_texture_with_srv(
device,
1,
1,
DXGI_FORMAT_R8G8B8A8_UNORM,
&one_rgba,
4,
)?;
swapchain_state.set_external_tex(ext_t);
swapchain_state.set_external_srv(ext_s);
Some(swapchain_state)
}
}
unsafe fn win32_d3d11_ensure_instance_buffer(
swapchain: &mut Win32D3d11SwapChain,
needed: usize,
) -> bool {
if needed <= swapchain.get_instance_capacity()
&& swapchain.get_instance_buffer() != 0
&& swapchain.get_instance_srv() != 0
{
return true;
}
let cap: usize = needed.max(256).next_power_of_two();
let device: *mut c_void = swapchain.get_device() as *mut c_void;
let desc: D3d11BufferDesc = D3d11BufferDesc {
byte_width: (cap.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)) as u32,
usage: D3D11_USAGE_DYNAMIC,
bind_flags: D3D11_BIND_SHADER_RESOURCE,
cpu_access_flags: D3D11_CPU_ACCESS_WRITE,
misc_flags: D3D11_RESOURCE_MISC_BUFFER_STRUCTURED,
structure_byte_stride: GPU_PRIMITIVE_INSTANCE_BYTES as u32,
};
let mut buf: *mut c_void = null_mut();
let buf_hr: i32 = unsafe {
let create_buf: Win32D3d11CreateBufferVtableFn =
transmute(win32_com_vtable_slot(device, 3));
create_buf(device, &desc, null(), &mut buf)
};
if buf_hr < 0 || buf.is_null() {
return false;
}
let srv_desc: D3d11SrvDesc = D3d11SrvDesc {
format: DXGI_FORMAT_UNKNOWN,
view_dimension: D3D11_SRV_DIMENSION_BUFFER,
union_first: 0,
union_second: cap as u32,
union_pad: [0; 2],
};
let mut srv: *mut c_void = null_mut();
let srv_hr: i32 = unsafe {
let create_srv: Win32D3d11CreateSrvVtableFn = transmute(win32_com_vtable_slot(device, 7));
create_srv(device, buf, &srv_desc, &mut srv)
};
if srv_hr < 0 || srv.is_null() {
win32_com_release(buf as usize);
return false;
}
win32_com_release(swapchain.get_instance_srv());
win32_com_release(swapchain.get_instance_buffer());
swapchain.set_instance_buffer(buf as usize);
swapchain.set_instance_srv(srv as usize);
swapchain.set_instance_capacity(cap);
true
}
pub(crate) fn win32_d3d11_present_batch(
swapchain: &mut Win32D3d11SwapChain,
batch: &DirectGpuFrameBatch,
) -> Result<(u64, u32), PlatformError> {
let device: *mut c_void = swapchain.get_device() as *mut c_void;
let context: *mut c_void = swapchain.get_context() as *mut c_void;
let sc: *mut c_void = swapchain.get_swap_chain() as *mut c_void;
if device.is_null() || context.is_null() || sc.is_null() {
return Err(PlatformError::SurfaceError(
ERR_WIN32_D3D11_PRESENT.to_string(),
));
}
let vw: u32 = batch.get_viewport_width().max(1);
let vh: u32 = batch.get_viewport_height().max(1);
unsafe {
if vw != swapchain.get_width() || vh != swapchain.get_height() {
let null_rtv: [*mut c_void; 1] = [null_mut()];
let om_set_rt: Win32D3d11OmSetRenderTargetsVtableFn =
transmute(win32_com_vtable_slot(context, 33));
om_set_rt(context, 1, null_rtv.as_ptr(), null_mut());
win32_com_release(swapchain.get_rtv());
swapchain.set_rtv(0);
let resize_fn: Win32DxgiResizeBuffersVtableFn =
transmute(win32_com_vtable_slot(sc, 13));
let rz_hr: i32 = resize_fn(
sc,
0,
vw,
vh,
DXGI_FORMAT_R8G8B8A8_UNORM,
swapchain.get_swap_chain_flags(),
);
if rz_hr < 0 {
return Err(PlatformError::SurfaceError(
ERR_WIN32_D3D11_PRESENT.to_string(),
));
}
let new_rtv: usize = win32_d3d11_create_backbuffer_rtv(device, sc)
.ok_or_else(|| PlatformError::SurfaceError(ERR_WIN32_D3D11_PRESENT.to_string()))?;
swapchain.set_rtv(new_rtv);
swapchain.set_width(vw);
swapchain.set_height(vh);
}
let update_subresource: Win32D3d11UpdateSubresourceVtableFn =
transmute(win32_com_vtable_slot(context, 48));
if let Some(glyph_atlas) = batch.glyph_r8_atlas_ref()
&& glyph_atlas.get_width() > 0
&& glyph_atlas.get_height() > 0
&& glyph_atlas.get_revision() != swapchain.get_glyph_r8_rev()
{
let gw: u32 = glyph_atlas.get_width();
let gh: u32 = glyph_atlas.get_height();
if gw == swapchain.get_glyph_r8_w() && gh == swapchain.get_glyph_r8_h() {
update_subresource(
context,
swapchain.get_glyph_r8_tex() as *mut c_void,
0,
null(),
glyph_atlas.get_pixels().as_ptr().cast::<c_void>(),
gw,
0,
);
} else if let Some((tex, srv)) = win32_d3d11_create_texture_with_srv(
device,
gw,
gh,
DXGI_FORMAT_R8_UNORM,
&glyph_atlas.get_pixels()[..],
gw,
) {
win32_com_release(swapchain.get_glyph_r8_srv());
win32_com_release(swapchain.get_glyph_r8_tex());
swapchain.set_glyph_r8_tex(tex);
swapchain.set_glyph_r8_srv(srv);
swapchain.set_glyph_r8_w(gw);
swapchain.set_glyph_r8_h(gh);
}
swapchain.set_glyph_r8_rev(glyph_atlas.get_revision());
}
if let Some(img_atlas) = batch.image_rgba8_atlas_ref()
&& img_atlas.get_width() > 0
&& img_atlas.get_height() > 0
&& img_atlas.get_revision() != swapchain.get_image_rev()
{
let iw: u32 = img_atlas.get_width();
let ih: u32 = img_atlas.get_height();
let pitch: u32 = iw.saturating_mul(4);
if iw == swapchain.get_image_w() && ih == swapchain.get_image_h() {
update_subresource(
context,
swapchain.get_image_tex() as *mut c_void,
0,
null(),
img_atlas.get_pixels().as_ptr().cast::<c_void>(),
pitch,
0,
);
} else if let Some((tex, srv)) = win32_d3d11_create_texture_with_srv(
device,
iw,
ih,
DXGI_FORMAT_R8G8B8A8_UNORM,
&img_atlas.get_pixels()[..],
pitch,
) {
win32_com_release(swapchain.get_image_srv());
win32_com_release(swapchain.get_image_tex());
swapchain.set_image_tex(tex);
swapchain.set_image_srv(srv);
swapchain.set_image_w(iw);
swapchain.set_image_h(ih);
}
swapchain.set_image_rev(img_atlas.get_revision());
}
let prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
let prim_count: usize = prims.len();
if prim_count > 0 && win32_d3d11_ensure_instance_buffer(swapchain, prim_count) {
let mut mapped: D3d11MappedSubresource = D3d11MappedSubresource {
data: null_mut(),
row_pitch: 0,
depth_pitch: 0,
};
let map_fn: Win32D3d11ContextMapVtableFn =
transmute(win32_com_vtable_slot(context, 14));
if map_fn(
context,
swapchain.get_instance_buffer() as *mut c_void,
0,
D3D11_MAP_WRITE_DISCARD,
0,
&mut mapped,
) >= 0
&& !mapped.data.is_null()
{
let byte_len: usize = prim_count.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
let src_bytes: &[u8] = from_raw_parts(prims.as_ptr().cast::<u8>(), byte_len);
let dst_bytes: &mut [u8] = from_raw_parts_mut(mapped.data.cast::<u8>(), byte_len);
dst_bytes.copy_from_slice(src_bytes);
let unmap_fn: Win32D3d11ContextUnmapResourceVtableFn =
transmute(win32_com_vtable_slot(context, 15));
unmap_fn(context, swapchain.get_instance_buffer() as *mut c_void, 0);
}
}
let rtv_ptr: *mut c_void = swapchain.get_rtv() as *mut c_void;
let rtvs: [*mut c_void; 1] = [rtv_ptr];
let om_set_rt: Win32D3d11OmSetRenderTargetsVtableFn =
transmute(win32_com_vtable_slot(context, 33));
om_set_rt(context, 1, rtvs.as_ptr(), null_mut());
let clear_color: [f32; 4] = batch.get_clear_rgba();
let clear_rtv: Win32D3d11ClearRenderTargetViewVtableFn =
transmute(win32_com_vtable_slot(context, 50));
clear_rtv(context, rtv_ptr, &clear_color);
if prim_count > 0 && swapchain.get_instance_srv() != 0 {
let vp: D3d11Viewport = D3d11Viewport {
top_left_x: 0.0,
top_left_y: 0.0,
width: vw as f32,
height: vh as f32,
min_depth: 0.0,
max_depth: 1.0,
};
let rs_set_vp: Win32D3d11RsSetViewportsVtableFn =
transmute(win32_com_vtable_slot(context, 44));
rs_set_vp(context, 1, &vp);
let rs_set_state: Win32D3d11RsSetRasterizerStateVtableFn =
transmute(win32_com_vtable_slot(context, 43));
rs_set_state(context, swapchain.get_rasterizer_state() as *mut c_void);
let blend_factor: [f32; 4] = [0.0; 4];
let om_set_blend: Win32D3d11OmSetBlendStateVtableFn =
transmute(win32_com_vtable_slot(context, 35));
om_set_blend(
context,
swapchain.get_blend_state() as *mut c_void,
&blend_factor,
u32::MAX,
);
let ia_set_topo: Win32D3d11IaSetPrimitiveTopologyVtableFn =
transmute(win32_com_vtable_slot(context, 24));
ia_set_topo(context, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
let vs_set_shader: Win32D3d11SetStageShaderVtableFn =
transmute(win32_com_vtable_slot(context, 11));
vs_set_shader(
context,
swapchain.get_vertex_shader() as *mut c_void,
null(),
0,
);
let ps_set_shader: Win32D3d11SetStageShaderVtableFn =
transmute(win32_com_vtable_slot(context, 9));
ps_set_shader(
context,
swapchain.get_pixel_shader() as *mut c_void,
null(),
0,
);
let cbs: [*mut c_void; 1] = [swapchain.get_constant_buffer() as *mut c_void];
let vs_set_cb: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 7));
vs_set_cb(context, 0, 1, cbs.as_ptr());
let vs_srvs: [*mut c_void; 1] = [swapchain.get_instance_srv() as *mut c_void];
let vs_set_srvs: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 25));
vs_set_srvs(context, 0, 1, vs_srvs.as_ptr());
let ps_srvs: [*mut c_void; 4] = [
swapchain.get_glyph_r8_srv() as *mut c_void,
swapchain.get_glyph_rgba8_srv() as *mut c_void,
swapchain.get_image_srv() as *mut c_void,
swapchain.get_external_srv() as *mut c_void,
];
let ps_set_srvs: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 8));
ps_set_srvs(context, 1, 4, ps_srvs.as_ptr());
let samplers: [*mut c_void; 1] = [swapchain.get_sampler_state() as *mut c_void];
let ps_set_samplers: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 10));
ps_set_samplers(context, 0, 1, samplers.as_ptr());
let rs_set_scissor: Win32D3d11RsSetScissorRectsVtableFn =
transmute(win32_com_vtable_slot(context, 45));
let draw_instanced: Win32D3d11ContextDrawInstancedVtableFn =
transmute(win32_com_vtable_slot(context, 21));
for range in batch.get_draw_ranges().iter() {
let base: u32 = range.get_base_instance();
let count: u32 = range.get_instance_count();
if count == 0 || (base as usize) >= prim_count {
continue;
}
let draw_count: u32 = count.min((prim_count as u32).saturating_sub(base));
let uniforms: D3d11LayerUniforms = D3d11LayerUniforms {
viewport_size: [vw as f32, vh as f32],
scroll_offset: [range.get_scroll_x(), range.get_scroll_y()],
};
update_subresource(
context,
swapchain.get_constant_buffer() as *mut c_void,
0,
null(),
(&uniforms as *const D3d11LayerUniforms).cast::<c_void>(),
0,
0,
);
let sx: i32 = range.get_scissor_x().min(vw) as i32;
let sy: i32 = range.get_scissor_y().min(vh) as i32;
let sr: i32 = range
.get_scissor_x()
.saturating_add(range.get_scissor_w())
.min(vw) as i32;
let sb: i32 = range
.get_scissor_y()
.saturating_add(range.get_scissor_h())
.min(vh) as i32;
let scissor: Win32Rect = Win32Rect {
left: sx,
top: sy,
right: sr.max(sx),
bottom: sb.max(sy),
};
rs_set_scissor(context, 1, &scissor);
draw_instanced(context, 6, draw_count, 0, base);
}
}
let present_fn: Win32DxgiSwapChainPresentVtableFn = transmute(win32_com_vtable_slot(sc, 8));
let pflags: u32 = swapchain.get_present_flags();
let mut pres_hr: i32 = present_fn(sc, 0, pflags);
if pres_hr < 0 && pflags != 0 {
pres_hr = present_fn(sc, 0, 0);
}
if pres_hr < 0 {
pres_hr = present_fn(sc, 1, 0);
}
if pres_hr < 0 {
return Err(PlatformError::SurfaceError(
ERR_WIN32_D3D11_PRESENT.to_string(),
));
}
let mut stats: DxgiFrameStatistics = DxgiFrameStatistics::default();
let get_stats: Win32DxgiGetFrameStatisticsVtableFn =
transmute(win32_com_vtable_slot(sc, 16));
if get_stats(sc, &mut stats) >= 0 {
Ok((stats.sync_qpc_time.max(0) as u64, stats.present_count))
} else {
Ok((0, 0))
}
}
}
pub(crate) fn win32_d3d11_release_scene_pipeline(scene: &Win32D3d11ScenePipeline) {
win32_com_release(scene.get_mesh3d_inst_srv());
win32_com_release(scene.get_mesh3d_inst_buf());
win32_com_release(scene.get_mesh3d_vert_srv());
win32_com_release(scene.get_mesh3d_vert_buf());
win32_com_release(scene.get_boat_srv());
win32_com_release(scene.get_boat_buf());
win32_com_release(scene.get_wake_srv());
win32_com_release(scene.get_wake_tex());
win32_com_release(scene.get_scene_depth_dsv());
win32_com_release(scene.get_scene_depth_tex());
win32_com_release(scene.get_scene_color_srv());
win32_com_release(scene.get_scene_color_rtv());
win32_com_release(scene.get_scene_color_tex());
win32_com_release(scene.get_depth_off_state());
win32_com_release(scene.get_depth_on_state());
win32_com_release(scene.get_world3d_cb());
win32_com_release(scene.get_ocean_cb());
win32_com_release(scene.get_mesh3d_ps());
win32_com_release(scene.get_mesh3d_vs());
win32_com_release(scene.get_sky3d_ps());
win32_com_release(scene.get_boat_ps());
win32_com_release(scene.get_boat_vs());
win32_com_release(scene.get_ocean_ps());
win32_com_release(scene.get_fs_vs());
}
unsafe fn win32_d3d11_create_structured_buffer(
device: *mut c_void,
cap: usize,
stride: usize,
) -> Option<(usize, usize)> {
let desc: D3d11BufferDesc = D3d11BufferDesc {
byte_width: (cap.saturating_mul(stride)) as u32,
usage: D3D11_USAGE_DYNAMIC,
bind_flags: D3D11_BIND_SHADER_RESOURCE,
cpu_access_flags: D3D11_CPU_ACCESS_WRITE,
misc_flags: D3D11_RESOURCE_MISC_BUFFER_STRUCTURED,
structure_byte_stride: stride as u32,
};
let mut buf: *mut c_void = null_mut();
let buf_hr: i32 = unsafe {
let create_buf: Win32D3d11CreateBufferVtableFn =
transmute(win32_com_vtable_slot(device, 3));
create_buf(device, &desc, null(), &mut buf)
};
if buf_hr < 0 || buf.is_null() {
return None;
}
let srv_desc: D3d11SrvDesc = D3d11SrvDesc {
format: DXGI_FORMAT_UNKNOWN,
view_dimension: D3D11_SRV_DIMENSION_BUFFER,
union_first: 0,
union_second: cap as u32,
union_pad: [0; 2],
};
let mut srv: *mut c_void = null_mut();
let srv_hr: i32 = unsafe {
let create_srv: Win32D3d11CreateSrvVtableFn = transmute(win32_com_vtable_slot(device, 7));
create_srv(device, buf, &srv_desc, &mut srv)
};
if srv_hr < 0 || srv.is_null() {
win32_com_release(buf as usize);
return None;
}
Some((buf as usize, srv as usize))
}
unsafe fn win32_d3d11_upload_dynamic_bytes(
context: *mut c_void,
buffer: usize,
src_ptr: *const u8,
byte_len: usize,
) -> bool {
if buffer == 0 || src_ptr.is_null() || byte_len == 0 {
return false;
}
let mut mapped: D3d11MappedSubresource = D3d11MappedSubresource {
data: null_mut(),
row_pitch: 0,
depth_pitch: 0,
};
unsafe {
let map_fn: Win32D3d11ContextMapVtableFn = transmute(win32_com_vtable_slot(context, 14));
if map_fn(
context,
buffer as *mut c_void,
0,
D3D11_MAP_WRITE_DISCARD,
0,
&mut mapped,
) < 0
|| mapped.data.is_null()
{
return false;
}
let src_bytes: &[u8] = from_raw_parts(src_ptr, byte_len);
let dst_bytes: &mut [u8] = from_raw_parts_mut(mapped.data.cast::<u8>(), byte_len);
dst_bytes.copy_from_slice(src_bytes);
let unmap_fn: Win32D3d11ContextUnmapResourceVtableFn =
transmute(win32_com_vtable_slot(context, 15));
unmap_fn(context, buffer as *mut c_void, 0);
true
}
}
unsafe fn win32_d3d11_init_scene_pipeline(
device: *mut c_void,
d3d_compile: usize,
) -> Option<Win32D3d11ScenePipeline> {
unsafe {
let mut pipe: Win32D3d11ScenePipeline = Win32D3d11ScenePipeline::default();
let create_vs: Win32D3d11CreateShaderVtableFn =
transmute(win32_com_vtable_slot(device, 12));
let create_ps: Win32D3d11CreateShaderVtableFn =
transmute(win32_com_vtable_slot(device, 15));
let create_buf: Win32D3d11CreateBufferVtableFn =
transmute(win32_com_vtable_slot(device, 3));
let create_ds: Win32D3d11CreateDepthStencilStateVtableFn =
transmute(win32_com_vtable_slot(device, 21));
let fs_vs_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_OCEAN_SHADER,
WIN32_HLSL_ENTRY_SCENE_FS_VS,
WIN32_HLSL_TARGET_VS,
)?;
let ocean_ps_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_OCEAN_SHADER,
WIN32_HLSL_ENTRY_OCEAN_PS,
WIN32_HLSL_TARGET_PS,
)?;
let boat_vs_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_BOAT_SHADER,
WIN32_HLSL_ENTRY_BOAT_VS,
WIN32_HLSL_TARGET_VS,
)?;
let boat_ps_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_BOAT_SHADER,
WIN32_HLSL_ENTRY_BOAT_PS,
WIN32_HLSL_TARGET_PS,
)?;
let sky3d_ps_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_3D_SHADER,
WIN32_HLSL_ENTRY_SKY3D_PS,
WIN32_HLSL_TARGET_PS,
)?;
let mesh3d_vs_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_3D_SHADER,
WIN32_HLSL_ENTRY_MESH3D_VS,
WIN32_HLSL_TARGET_VS,
)?;
let mesh3d_ps_bc: Vec<u8> = win32_compile_hlsl_source(
d3d_compile,
HLSL_SCENE_3D_SHADER,
WIN32_HLSL_ENTRY_MESH3D_PS,
WIN32_HLSL_TARGET_PS,
)?;
let mut obj: *mut c_void = null_mut();
if create_vs(
device,
fs_vs_bc.as_ptr().cast::<c_void>(),
fs_vs_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_fs_vs(obj as usize);
obj = null_mut();
if create_ps(
device,
ocean_ps_bc.as_ptr().cast::<c_void>(),
ocean_ps_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_ocean_ps(obj as usize);
obj = null_mut();
if create_vs(
device,
boat_vs_bc.as_ptr().cast::<c_void>(),
boat_vs_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_boat_vs(obj as usize);
obj = null_mut();
if create_ps(
device,
boat_ps_bc.as_ptr().cast::<c_void>(),
boat_ps_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_boat_ps(obj as usize);
obj = null_mut();
if create_ps(
device,
sky3d_ps_bc.as_ptr().cast::<c_void>(),
sky3d_ps_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_sky3d_ps(obj as usize);
obj = null_mut();
if create_vs(
device,
mesh3d_vs_bc.as_ptr().cast::<c_void>(),
mesh3d_vs_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_mesh3d_vs(obj as usize);
obj = null_mut();
if create_ps(
device,
mesh3d_ps_bc.as_ptr().cast::<c_void>(),
mesh3d_ps_bc.len(),
null_mut(),
&mut obj,
) < 0
|| obj.is_null()
{
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_mesh3d_ps(obj as usize);
let ocean_cb_desc: D3d11BufferDesc = D3d11BufferDesc {
byte_width: size_of::<D3d11OceanUniforms>() as u32,
usage: D3D11_USAGE_DEFAULT,
bind_flags: D3D11_BIND_CONSTANT_BUFFER,
cpu_access_flags: 0,
misc_flags: 0,
structure_byte_stride: 0,
};
obj = null_mut();
if create_buf(device, &ocean_cb_desc, null(), &mut obj) < 0 || obj.is_null() {
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_ocean_cb(obj as usize);
let world_cb_desc: D3d11BufferDesc = D3d11BufferDesc {
byte_width: size_of::<D3d11World3dUniforms>() as u32,
usage: D3D11_USAGE_DEFAULT,
bind_flags: D3D11_BIND_CONSTANT_BUFFER,
cpu_access_flags: 0,
misc_flags: 0,
structure_byte_stride: 0,
};
obj = null_mut();
if create_buf(device, &world_cb_desc, null(), &mut obj) < 0 || obj.is_null() {
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_world3d_cb(obj as usize);
let stencil_keep: D3d11DepthStencilOpDesc = D3d11DepthStencilOpDesc {
stencil_fail_op: D3D11_STENCIL_OP_KEEP,
stencil_depth_fail_op: D3D11_STENCIL_OP_KEEP,
stencil_pass_op: D3D11_STENCIL_OP_KEEP,
stencil_func: D3D11_COMPARISON_ALWAYS,
};
let ds_on_desc: D3d11DepthStencilDesc = D3d11DepthStencilDesc {
depth_enable: 1,
depth_write_mask: D3D11_DEPTH_WRITE_MASK_ALL,
depth_func: D3D11_COMPARISON_LESS,
stencil_enable: 0,
stencil_read_mask: 0xFF,
stencil_write_mask: 0xFF,
front_face: stencil_keep,
back_face: stencil_keep,
};
obj = null_mut();
if create_ds(device, &ds_on_desc, &mut obj) < 0 || obj.is_null() {
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_depth_on_state(obj as usize);
let ds_off_desc: D3d11DepthStencilDesc = D3d11DepthStencilDesc {
depth_enable: 0,
depth_write_mask: D3D11_DEPTH_WRITE_MASK_ZERO,
depth_func: D3D11_COMPARISON_ALWAYS,
stencil_enable: 0,
stencil_read_mask: 0xFF,
stencil_write_mask: 0xFF,
front_face: stencil_keep,
back_face: stencil_keep,
};
obj = null_mut();
if create_ds(device, &ds_off_desc, &mut obj) < 0 || obj.is_null() {
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
pipe.set_depth_off_state(obj as usize);
let one_wake: [u8; 4] = [128, 128, 0, 255];
if let Some((wt, ws)) = win32_d3d11_create_texture_with_srv(
device,
1,
1,
DXGI_FORMAT_R8G8B8A8_UNORM,
&one_wake,
4,
) {
pipe.set_wake_tex(wt);
pipe.set_wake_srv(ws);
pipe.set_wake_w(1);
pipe.set_wake_h(1);
} else {
win32_d3d11_release_scene_pipeline(&pipe);
return None;
}
Some(pipe)
}
}
unsafe fn win32_d3d11_ensure_scene_targets(
device: *mut c_void,
pipe: &mut Win32D3d11ScenePipeline,
req_w: u32,
req_h: u32,
) -> bool {
if pipe.get_scene_w() == req_w
&& pipe.get_scene_h() == req_h
&& pipe.get_scene_color_rtv() != 0
&& pipe.get_scene_color_srv() != 0
&& pipe.get_scene_depth_dsv() != 0
{
return true;
}
unsafe {
let create_tex: Win32D3d11CreateTexture2dVtableFn =
transmute(win32_com_vtable_slot(device, 5));
let create_srv: Win32D3d11CreateSrvVtableFn = transmute(win32_com_vtable_slot(device, 7));
let create_rtv: Win32D3d11CreateRtvVtableFn = transmute(win32_com_vtable_slot(device, 9));
let create_dsv: Win32D3d11CreateDsvVtableFn = transmute(win32_com_vtable_slot(device, 10));
let color_desc: D3d11Texture2dDesc = D3d11Texture2dDesc {
width: req_w,
height: req_h,
mip_levels: 1,
array_size: 1,
format: DXGI_FORMAT_R8G8B8A8_UNORM,
sample_desc: DxgiSampleDesc {
count: 1,
quality: 0,
},
usage: D3D11_USAGE_DEFAULT,
bind_flags: D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
cpu_access_flags: 0,
misc_flags: 0,
};
let mut color_tex: *mut c_void = null_mut();
if create_tex(device, &color_desc, null(), &mut color_tex) < 0 || color_tex.is_null() {
return false;
}
let mut color_rtv: *mut c_void = null_mut();
if create_rtv(device, color_tex, null(), &mut color_rtv) < 0 || color_rtv.is_null() {
win32_com_release(color_tex as usize);
return false;
}
let srv_desc: D3d11SrvDesc = D3d11SrvDesc {
format: DXGI_FORMAT_R8G8B8A8_UNORM,
view_dimension: D3D11_SRV_DIMENSION_TEXTURE2D,
union_first: 0,
union_second: 1,
union_pad: [0; 2],
};
let mut color_srv: *mut c_void = null_mut();
if create_srv(device, color_tex, &srv_desc, &mut color_srv) < 0 || color_srv.is_null() {
win32_com_release(color_rtv as usize);
win32_com_release(color_tex as usize);
return false;
}
let depth_desc: D3d11Texture2dDesc = D3d11Texture2dDesc {
width: req_w,
height: req_h,
mip_levels: 1,
array_size: 1,
format: DXGI_FORMAT_D24_UNORM_S8_UINT,
sample_desc: DxgiSampleDesc {
count: 1,
quality: 0,
},
usage: D3D11_USAGE_DEFAULT,
bind_flags: D3D11_BIND_DEPTH_STENCIL,
cpu_access_flags: 0,
misc_flags: 0,
};
let mut depth_tex: *mut c_void = null_mut();
if create_tex(device, &depth_desc, null(), &mut depth_tex) < 0 || depth_tex.is_null() {
win32_com_release(color_srv as usize);
win32_com_release(color_rtv as usize);
win32_com_release(color_tex as usize);
return false;
}
let mut depth_dsv: *mut c_void = null_mut();
if create_dsv(device, depth_tex, null(), &mut depth_dsv) < 0 || depth_dsv.is_null() {
win32_com_release(depth_tex as usize);
win32_com_release(color_srv as usize);
win32_com_release(color_rtv as usize);
win32_com_release(color_tex as usize);
return false;
}
win32_com_release(pipe.get_scene_depth_dsv());
win32_com_release(pipe.get_scene_depth_tex());
win32_com_release(pipe.get_scene_color_srv());
win32_com_release(pipe.get_scene_color_rtv());
win32_com_release(pipe.get_scene_color_tex());
pipe.set_scene_color_tex(color_tex as usize);
pipe.set_scene_color_rtv(color_rtv as usize);
pipe.set_scene_color_srv(color_srv as usize);
pipe.set_scene_depth_tex(depth_tex as usize);
pipe.set_scene_depth_dsv(depth_dsv as usize);
pipe.set_scene_w(req_w);
pipe.set_scene_h(req_h);
true
}
}
unsafe fn win32_d3d11_execute_scene_pass(
swapchain: &mut Win32D3d11SwapChain,
pass: &DirectGpuScenePass,
) -> usize {
let fallback_srv: usize = swapchain.get_external_srv();
let device: *mut c_void = swapchain.get_device() as *mut c_void;
let context: *mut c_void = swapchain.get_context() as *mut c_void;
let alpha_blend: *mut c_void = swapchain.get_blend_state() as *mut c_void;
let opaque_blend: *mut c_void = swapchain.get_opaque_blend_state() as *mut c_void;
let raster_state: *mut c_void = swapchain.get_rasterizer_state() as *mut c_void;
let sampler_state: *mut c_void = swapchain.get_sampler_state() as *mut c_void;
let d3d_compile: usize = win32_d3d11_syms().get_d3d_compile();
let Win32D3d11SwapChain { scene, .. } = swapchain;
unsafe {
if scene.is_none() {
*scene = win32_d3d11_init_scene_pipeline(device, d3d_compile);
}
let Some(pipe) = scene.as_mut() else {
return fallback_srv;
};
let (req_w, req_h): (u32, u32) = match pass {
DirectGpuScenePass::OceanFluid(ocean) => (
ocean.get_target_width().clamp(64, 4096),
ocean.get_target_height().clamp(64, 4096),
),
DirectGpuScenePass::World3d(world) => (
world.get_target_width().clamp(64, 4096),
world.get_target_height().clamp(64, 4096),
),
};
let ps_set_srvs: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 8));
let null_t4: [*mut c_void; 1] = [null_mut()];
ps_set_srvs(context, 4, 1, null_t4.as_ptr());
if !win32_d3d11_ensure_scene_targets(device, pipe, req_w, req_h) {
return fallback_srv;
}
let om_set_rt: Win32D3d11OmSetRenderTargetsVtableFn =
transmute(win32_com_vtable_slot(context, 33));
let om_set_blend: Win32D3d11OmSetBlendStateVtableFn =
transmute(win32_com_vtable_slot(context, 35));
let om_set_ds: Win32D3d11OmSetDepthStencilStateVtableFn =
transmute(win32_com_vtable_slot(context, 36));
let rs_set_state: Win32D3d11RsSetRasterizerStateVtableFn =
transmute(win32_com_vtable_slot(context, 43));
let rs_set_vp: Win32D3d11RsSetViewportsVtableFn =
transmute(win32_com_vtable_slot(context, 44));
let rs_set_scissor: Win32D3d11RsSetScissorRectsVtableFn =
transmute(win32_com_vtable_slot(context, 45));
let update_subresource: Win32D3d11UpdateSubresourceVtableFn =
transmute(win32_com_vtable_slot(context, 48));
let clear_rtv: Win32D3d11ClearRenderTargetViewVtableFn =
transmute(win32_com_vtable_slot(context, 50));
let clear_dsv: Win32D3d11ClearDepthStencilViewVtableFn =
transmute(win32_com_vtable_slot(context, 53));
let ia_set_topo: Win32D3d11IaSetPrimitiveTopologyVtableFn =
transmute(win32_com_vtable_slot(context, 24));
let vs_set_shader: Win32D3d11SetStageShaderVtableFn =
transmute(win32_com_vtable_slot(context, 11));
let ps_set_shader: Win32D3d11SetStageShaderVtableFn =
transmute(win32_com_vtable_slot(context, 9));
let vs_set_cb: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 7));
let ps_set_cb: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 16));
let vs_set_srvs: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 25));
let ps_set_samplers: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 10));
let draw_fn: Win32D3d11ContextDrawVtableFn = transmute(win32_com_vtable_slot(context, 13));
let draw_instanced: Win32D3d11ContextDrawInstancedVtableFn =
transmute(win32_com_vtable_slot(context, 21));
let rtv_ptr: *mut c_void = pipe.get_scene_color_rtv() as *mut c_void;
let dsv_ptr: *mut c_void = pipe.get_scene_depth_dsv() as *mut c_void;
let rtvs: [*mut c_void; 1] = [rtv_ptr];
let vp: D3d11Viewport = D3d11Viewport {
top_left_x: 0.0,
top_left_y: 0.0,
width: req_w as f32,
height: req_h as f32,
min_depth: 0.0,
max_depth: 1.0,
};
let full_scissor: Win32Rect = Win32Rect {
left: 0,
top: 0,
right: req_w as i32,
bottom: req_h as i32,
};
let blend_factor: [f32; 4] = [0.0; 4];
rs_set_state(context, raster_state);
rs_set_vp(context, 1, &vp);
rs_set_scissor(context, 1, &full_scissor);
ia_set_topo(context, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
match pass {
DirectGpuScenePass::OceanFluid(ocean) => {
let wake_w: u32 = ocean.get_wake_width().max(1);
let wake_h: u32 = ocean.get_wake_height().max(1);
let wake_bytes: &[u8] = ocean.get_wake_rgba8().as_slice();
let req_wake: usize = (wake_w as usize)
.saturating_mul(wake_h as usize)
.saturating_mul(4);
if wake_bytes.len() >= req_wake
&& (pipe.get_wake_w() != wake_w
|| pipe.get_wake_h() != wake_h
|| ocean.get_has_active_wake())
{
let pitch: u32 = wake_w.saturating_mul(4);
if pipe.get_wake_w() == wake_w && pipe.get_wake_h() == wake_h {
update_subresource(
context,
pipe.get_wake_tex() as *mut c_void,
0,
null(),
wake_bytes.as_ptr().cast::<c_void>(),
pitch,
0,
);
} else if let Some((wt, ws)) = win32_d3d11_create_texture_with_srv(
device,
wake_w,
wake_h,
DXGI_FORMAT_R8G8B8A8_UNORM,
wake_bytes,
pitch,
) {
win32_com_release(pipe.get_wake_srv());
win32_com_release(pipe.get_wake_tex());
pipe.set_wake_tex(wt);
pipe.set_wake_srv(ws);
pipe.set_wake_w(wake_w);
pipe.set_wake_h(wake_h);
}
}
om_set_rt(context, 1, rtvs.as_ptr(), null_mut());
om_set_ds(context, pipe.get_depth_off_state() as *mut c_void, 0);
om_set_blend(context, opaque_blend, &blend_factor, u32::MAX);
let boat_uv: [f32; 2] = ocean.get_boat_uv();
let sun: [f32; 3] = ocean.get_sun_dir();
let wf: f32 = req_w as f32;
let hf: f32 = req_h as f32;
let uniforms: D3d11OceanUniforms = D3d11OceanUniforms {
time_agit_hor_aspect: [
ocean.get_sim_time(),
ocean.get_agitation(),
ocean.get_horizon_v(),
ocean.get_aspect(),
],
roll_boat_uv: [
ocean.get_roll_cos(),
ocean.get_roll_sin(),
boat_uv[0],
boat_uv[1],
],
sun_dir_wake: [
sun[0],
sun[1],
sun[2],
if ocean.get_has_active_wake() {
1.0
} else {
0.0
},
],
pad0: [wf, hf, 1.0 / wf.max(1.0), 1.0 / hf.max(1.0)],
};
update_subresource(
context,
pipe.get_ocean_cb() as *mut c_void,
0,
null(),
(&uniforms as *const D3d11OceanUniforms).cast::<c_void>(),
0,
0,
);
let cbs: [*mut c_void; 1] = [pipe.get_ocean_cb() as *mut c_void];
ps_set_cb(context, 0, 1, cbs.as_ptr());
let wake_srvs: [*mut c_void; 1] = [pipe.get_wake_srv() as *mut c_void];
ps_set_srvs(context, 0, 1, wake_srvs.as_ptr());
let samplers: [*mut c_void; 1] = [sampler_state];
ps_set_samplers(context, 0, 1, samplers.as_ptr());
vs_set_shader(context, pipe.get_fs_vs() as *mut c_void, null(), 0);
ps_set_shader(context, pipe.get_ocean_ps() as *mut c_void, null(), 0);
draw_fn(context, 3, 0);
let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
if !boat_verts.is_empty() {
let needed: usize = boat_verts.len();
if needed > pipe.get_boat_cap() || pipe.get_boat_buf() == 0 {
let cap: usize = needed.max(64).next_power_of_two();
if let Some((buf, srv)) = win32_d3d11_create_structured_buffer(
device,
cap,
size_of::<GpuOceanBoatVertex>(),
) {
win32_com_release(pipe.get_boat_srv());
win32_com_release(pipe.get_boat_buf());
pipe.set_boat_buf(buf);
pipe.set_boat_srv(srv);
pipe.set_boat_cap(cap);
}
}
let byte_len: usize = needed.saturating_mul(size_of::<GpuOceanBoatVertex>());
if pipe.get_boat_srv() != 0
&& win32_d3d11_upload_dynamic_bytes(
context,
pipe.get_boat_buf(),
boat_verts.as_ptr().cast::<u8>(),
byte_len,
)
{
om_set_blend(context, alpha_blend, &blend_factor, u32::MAX);
let boat_srvs: [*mut c_void; 1] = [pipe.get_boat_srv() as *mut c_void];
vs_set_srvs(context, 0, 1, boat_srvs.as_ptr());
vs_set_shader(context, pipe.get_boat_vs() as *mut c_void, null(), 0);
ps_set_shader(context, pipe.get_boat_ps() as *mut c_void, null(), 0);
draw_fn(context, needed as u32, 0);
}
}
}
DirectGpuScenePass::World3d(world) => {
om_set_rt(context, 1, rtvs.as_ptr(), dsv_ptr);
let clear_col: [f32; 4] = [0.04, 0.05, 0.09, 1.0];
clear_rtv(context, rtv_ptr, &clear_col);
clear_dsv(context, dsv_ptr, D3D11_CLEAR_DEPTH, 1.0, 0);
let vp_mat: [f32; 16] = world.get_view_proj();
let mut uniforms: D3d11World3dUniforms = D3d11World3dUniforms {
vp_c0: [vp_mat[0], vp_mat[1], vp_mat[2], vp_mat[3]],
vp_c1: [vp_mat[4], vp_mat[5], vp_mat[6], vp_mat[7]],
vp_c2: [vp_mat[8], vp_mat[9], vp_mat[10], vp_mat[11]],
vp_c3: [vp_mat[12], vp_mat[13], vp_mat[14], vp_mat[15]],
camera_pos: world.get_camera_pos(),
sun_dir_fog: world.get_sun_dir_fog(),
sun_color_ambient: world.get_sun_color_ambient(),
sky_horizon_tod: world.get_sky_horizon_tod(),
sky_zenith_aspect: world.get_sky_zenith_aspect(),
draw_offsets: [0, 0, 0, 0],
};
update_subresource(
context,
pipe.get_world3d_cb() as *mut c_void,
0,
null(),
(&uniforms as *const D3d11World3dUniforms).cast::<c_void>(),
0,
0,
);
let cbs: [*mut c_void; 1] = [pipe.get_world3d_cb() as *mut c_void];
vs_set_cb(context, 0, 1, cbs.as_ptr());
ps_set_cb(context, 0, 1, cbs.as_ptr());
om_set_blend(context, opaque_blend, &blend_factor, u32::MAX);
om_set_ds(context, pipe.get_depth_off_state() as *mut c_void, 0);
vs_set_shader(context, pipe.get_fs_vs() as *mut c_void, null(), 0);
ps_set_shader(context, pipe.get_sky3d_ps() as *mut c_void, null(), 0);
draw_fn(context, 3, 0);
let verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
let insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
if !verts.is_empty() && !insts.is_empty() {
let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
if pipe.get_mesh3d_vert_rev() != mesh_rev || pipe.get_mesh3d_vert_buf() == 0 {
let vneed: usize = verts.len();
if vneed > pipe.get_mesh3d_vert_cap() || pipe.get_mesh3d_vert_buf() == 0 {
let cap: usize = vneed.max(256).next_power_of_two();
if let Some((buf, srv)) = win32_d3d11_create_structured_buffer(
device,
cap,
size_of::<GpuWorld3dVertex>(),
) {
win32_com_release(pipe.get_mesh3d_vert_srv());
win32_com_release(pipe.get_mesh3d_vert_buf());
pipe.set_mesh3d_vert_buf(buf);
pipe.set_mesh3d_vert_srv(srv);
pipe.set_mesh3d_vert_cap(cap);
}
}
let vbytes: usize = vneed.saturating_mul(size_of::<GpuWorld3dVertex>());
if win32_d3d11_upload_dynamic_bytes(
context,
pipe.get_mesh3d_vert_buf(),
verts.as_ptr().cast::<u8>(),
vbytes,
) {
pipe.set_mesh3d_vert_rev(mesh_rev);
}
}
let ineed: usize = insts.len();
if ineed > pipe.get_mesh3d_inst_cap() || pipe.get_mesh3d_inst_buf() == 0 {
let cap: usize = ineed.max(64).next_power_of_two();
if let Some((buf, srv)) = win32_d3d11_create_structured_buffer(
device,
cap,
size_of::<GpuWorld3dInstance>(),
) {
win32_com_release(pipe.get_mesh3d_inst_srv());
win32_com_release(pipe.get_mesh3d_inst_buf());
pipe.set_mesh3d_inst_buf(buf);
pipe.set_mesh3d_inst_srv(srv);
pipe.set_mesh3d_inst_cap(cap);
}
}
let ibytes: usize = ineed.saturating_mul(size_of::<GpuWorld3dInstance>());
if pipe.get_mesh3d_vert_srv() != 0
&& pipe.get_mesh3d_inst_srv() != 0
&& win32_d3d11_upload_dynamic_bytes(
context,
pipe.get_mesh3d_inst_buf(),
insts.as_ptr().cast::<u8>(),
ibytes,
)
{
om_set_ds(context, pipe.get_depth_on_state() as *mut c_void, 0);
vs_set_shader(context, pipe.get_mesh3d_vs() as *mut c_void, null(), 0);
ps_set_shader(context, pipe.get_mesh3d_ps() as *mut c_void, null(), 0);
let mesh_srvs: [*mut c_void; 2] = [
pipe.get_mesh3d_vert_srv() as *mut c_void,
pipe.get_mesh3d_inst_srv() as *mut c_void,
];
vs_set_srvs(context, 0, 2, mesh_srvs.as_ptr());
for batch in world.get_draw_batches().iter() {
if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
continue;
}
uniforms.draw_offsets =
[batch.get_vertex_start(), batch.get_instance_start(), 0, 0];
update_subresource(
context,
pipe.get_world3d_cb() as *mut c_void,
0,
null(),
(&uniforms as *const D3d11World3dUniforms).cast::<c_void>(),
0,
0,
);
draw_instanced(
context,
batch.get_vertex_count(),
batch.get_instance_count(),
0,
0,
);
}
}
}
}
}
let null_rtv: [*mut c_void; 1] = [null_mut()];
om_set_rt(context, 1, null_rtv.as_ptr(), null_mut());
om_set_ds(context, pipe.get_depth_off_state() as *mut c_void, 0);
let null_vs_srvs: [*mut c_void; 2] = [null_mut(), null_mut()];
vs_set_srvs(context, 0, 2, null_vs_srvs.as_ptr());
pipe.get_scene_color_srv()
}
}
unsafe fn win32_d3d11_upload_atlas_dirty_rects(
context: *mut c_void,
tex: *mut c_void,
bpp: u32,
atlas_w: u32,
atlas_h: u32,
pixels: &[u8],
dirty_rects: &[PixelDirtyRect],
) {
let row_pitch: u32 = atlas_w.saturating_mul(bpp);
unsafe {
let update_subresource: Win32D3d11UpdateSubresourceVtableFn =
transmute(win32_com_vtable_slot(context, 48));
if dirty_rects.is_empty() {
update_subresource(
context,
tex,
0,
null(),
pixels.as_ptr().cast::<c_void>(),
row_pitch,
0,
);
return;
}
for rect in dirty_rects.iter() {
let rx: u32 = rect.get_x().min(atlas_w);
let ry: u32 = rect.get_y().min(atlas_h);
let rw: u32 = rect.get_width().min(atlas_w.saturating_sub(rx));
let rh: u32 = rect.get_height().min(atlas_h.saturating_sub(ry));
if rw == 0 || rh == 0 {
continue;
}
let byte_off: usize = (ry as usize)
.saturating_mul(row_pitch as usize)
.saturating_add((rx as usize).saturating_mul(bpp as usize));
if byte_off >= pixels.len() {
continue;
}
let dst_box: D3d11Box = D3d11Box {
left: rx,
top: ry,
front: 0,
right: rx.saturating_add(rw),
bottom: ry.saturating_add(rh),
back: 1,
};
update_subresource(
context,
tex,
0,
(&dst_box as *const D3d11Box).cast::<c_void>(),
pixels.as_ptr().add(byte_off).cast::<c_void>(),
row_pitch,
0,
);
}
}
}
pub(crate) fn win32_d3d11_present_submission(
swapchain: &mut Win32D3d11SwapChain,
submission: &GpuFrameSubmission,
) -> Result<(u64, u32, usize, usize), PlatformError> {
let device: *mut c_void = swapchain.get_device() as *mut c_void;
let context: *mut c_void = swapchain.get_context() as *mut c_void;
let sc: *mut c_void = swapchain.get_swap_chain() as *mut c_void;
if device.is_null() || context.is_null() || sc.is_null() {
return Err(PlatformError::SurfaceError(
ERR_WIN32_D3D11_PRESENT.to_string(),
));
}
let vw: u32 = submission.get_width().max(1);
let vh: u32 = submission.get_height().max(1);
unsafe {
if vw != swapchain.get_width() || vh != swapchain.get_height() {
let null_rtv: [*mut c_void; 1] = [null_mut()];
let om_set_rt: Win32D3d11OmSetRenderTargetsVtableFn =
transmute(win32_com_vtable_slot(context, 33));
om_set_rt(context, 1, null_rtv.as_ptr(), null_mut());
win32_com_release(swapchain.get_rtv());
swapchain.set_rtv(0);
let resize_fn: Win32DxgiResizeBuffersVtableFn =
transmute(win32_com_vtable_slot(sc, 13));
let rz_hr: i32 = resize_fn(
sc,
0,
vw,
vh,
DXGI_FORMAT_R8G8B8A8_UNORM,
swapchain.get_swap_chain_flags(),
);
if rz_hr < 0 {
return Err(PlatformError::SurfaceError(
ERR_WIN32_D3D11_PRESENT.to_string(),
));
}
let new_rtv: usize = win32_d3d11_create_backbuffer_rtv(device, sc)
.ok_or_else(|| PlatformError::SurfaceError(ERR_WIN32_D3D11_PRESENT.to_string()))?;
swapchain.set_rtv(new_rtv);
swapchain.set_width(vw);
swapchain.set_height(vh);
}
if let Some(glyph_atlas) = submission.glyph_atlas_r8_ref()
&& glyph_atlas.get_width() > 0
&& glyph_atlas.get_height() > 0
{
let gw: u32 = glyph_atlas.get_width();
let gh: u32 = glyph_atlas.get_height();
let pixels: &[u8] = &glyph_atlas.get_pixels()[..];
if pixels.len() >= (gw as usize).saturating_mul(gh as usize) {
if gw == swapchain.get_glyph_r8_w() && gh == swapchain.get_glyph_r8_h() {
win32_d3d11_upload_atlas_dirty_rects(
context,
swapchain.get_glyph_r8_tex() as *mut c_void,
1,
gw,
gh,
pixels,
submission.get_glyph_dirty_rects().as_slice(),
);
} else if let Some((tex, srv)) = win32_d3d11_create_texture_with_srv(
device,
gw,
gh,
DXGI_FORMAT_R8_UNORM,
pixels,
gw,
) {
win32_com_release(swapchain.get_glyph_r8_srv());
win32_com_release(swapchain.get_glyph_r8_tex());
swapchain.set_glyph_r8_tex(tex);
swapchain.set_glyph_r8_srv(srv);
swapchain.set_glyph_r8_w(gw);
swapchain.set_glyph_r8_h(gh);
}
swapchain.set_glyph_r8_rev(glyph_atlas.get_revision());
}
}
if let Some(img_atlas) = submission.image_atlas_rgba8_ref()
&& img_atlas.get_width() > 0
&& img_atlas.get_height() > 0
{
let iw: u32 = img_atlas.get_width();
let ih: u32 = img_atlas.get_height();
let pitch: u32 = iw.saturating_mul(4);
let pixels: &[u8] = &img_atlas.get_pixels()[..];
if pixels.len() >= (iw as usize).saturating_mul(ih as usize).saturating_mul(4) {
if iw == swapchain.get_image_w() && ih == swapchain.get_image_h() {
win32_d3d11_upload_atlas_dirty_rects(
context,
swapchain.get_image_tex() as *mut c_void,
4,
iw,
ih,
pixels,
submission.get_image_dirty_rects().as_slice(),
);
} else if let Some((tex, srv)) = win32_d3d11_create_texture_with_srv(
device,
iw,
ih,
DXGI_FORMAT_R8G8B8A8_UNORM,
pixels,
pitch,
) {
win32_com_release(swapchain.get_image_srv());
win32_com_release(swapchain.get_image_tex());
swapchain.set_image_tex(tex);
swapchain.set_image_srv(srv);
swapchain.set_image_w(iw);
swapchain.set_image_h(ih);
}
swapchain.set_image_rev(img_atlas.get_revision());
}
}
let active_ext_srv: usize = if let Some(pass) = submission.gpu_scene_pass_ref() {
win32_d3d11_execute_scene_pass(swapchain, pass)
} else {
swapchain.get_external_srv()
};
let (prim_count, range_count): (usize, usize) = {
let Win32D3d11SwapChain {
scratch_prims,
scratch_ranges,
..
} = swapchain;
scratch_prims.clear();
scratch_ranges.clear();
for batch in submission.get_batches().iter() {
let prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
if prims.is_empty() {
continue;
}
let base: u32 = scratch_prims.len() as u32;
scratch_prims.extend_from_slice(prims);
scratch_ranges.push((
base,
prims.len() as u32,
batch.get_scissor(),
batch.get_scroll_offset(),
));
}
(scratch_prims.len(), scratch_ranges.len())
};
if prim_count > 0 && win32_d3d11_ensure_instance_buffer(swapchain, prim_count) {
let byte_len: usize = prim_count.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
let prims_ptr: *const u8 = {
let Win32D3d11SwapChain { scratch_prims, .. } = swapchain;
scratch_prims.as_ptr().cast::<u8>()
};
let _: bool = win32_d3d11_upload_dynamic_bytes(
context,
swapchain.get_instance_buffer(),
prims_ptr,
byte_len,
);
}
let rtv_ptr: *mut c_void = swapchain.get_rtv() as *mut c_void;
let rtvs: [*mut c_void; 1] = [rtv_ptr];
let om_set_rt: Win32D3d11OmSetRenderTargetsVtableFn =
transmute(win32_com_vtable_slot(context, 33));
om_set_rt(context, 1, rtvs.as_ptr(), null_mut());
let clear_color: [f32; 4] = submission.get_clear_color().to_f32_array();
let clear_rtv: Win32D3d11ClearRenderTargetViewVtableFn =
transmute(win32_com_vtable_slot(context, 50));
clear_rtv(context, rtv_ptr, &clear_color);
if prim_count > 0 && swapchain.get_instance_srv() != 0 {
let vp: D3d11Viewport = D3d11Viewport {
top_left_x: 0.0,
top_left_y: 0.0,
width: vw as f32,
height: vh as f32,
min_depth: 0.0,
max_depth: 1.0,
};
let rs_set_vp: Win32D3d11RsSetViewportsVtableFn =
transmute(win32_com_vtable_slot(context, 44));
rs_set_vp(context, 1, &vp);
let rs_set_state: Win32D3d11RsSetRasterizerStateVtableFn =
transmute(win32_com_vtable_slot(context, 43));
rs_set_state(context, swapchain.get_rasterizer_state() as *mut c_void);
let blend_factor: [f32; 4] = [0.0; 4];
let om_set_blend: Win32D3d11OmSetBlendStateVtableFn =
transmute(win32_com_vtable_slot(context, 35));
om_set_blend(
context,
swapchain.get_blend_state() as *mut c_void,
&blend_factor,
u32::MAX,
);
let ia_set_topo: Win32D3d11IaSetPrimitiveTopologyVtableFn =
transmute(win32_com_vtable_slot(context, 24));
ia_set_topo(context, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
let vs_set_shader: Win32D3d11SetStageShaderVtableFn =
transmute(win32_com_vtable_slot(context, 11));
vs_set_shader(
context,
swapchain.get_vertex_shader() as *mut c_void,
null(),
0,
);
let ps_set_shader: Win32D3d11SetStageShaderVtableFn =
transmute(win32_com_vtable_slot(context, 9));
ps_set_shader(
context,
swapchain.get_pixel_shader() as *mut c_void,
null(),
0,
);
let cbs: [*mut c_void; 1] = [swapchain.get_constant_buffer() as *mut c_void];
let vs_set_cb: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 7));
vs_set_cb(context, 0, 1, cbs.as_ptr());
let vs_srvs: [*mut c_void; 1] = [swapchain.get_instance_srv() as *mut c_void];
let vs_set_srvs: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 25));
vs_set_srvs(context, 0, 1, vs_srvs.as_ptr());
let ps_srvs: [*mut c_void; 4] = [
swapchain.get_glyph_r8_srv() as *mut c_void,
swapchain.get_glyph_rgba8_srv() as *mut c_void,
swapchain.get_image_srv() as *mut c_void,
active_ext_srv as *mut c_void,
];
let ps_set_srvs: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 8));
ps_set_srvs(context, 1, 4, ps_srvs.as_ptr());
let samplers: [*mut c_void; 1] = [swapchain.get_sampler_state() as *mut c_void];
let ps_set_samplers: Win32D3d11SetStageBindingsVtableFn =
transmute(win32_com_vtable_slot(context, 10));
ps_set_samplers(context, 0, 1, samplers.as_ptr());
let update_subresource: Win32D3d11UpdateSubresourceVtableFn =
transmute(win32_com_vtable_slot(context, 48));
let rs_set_scissor: Win32D3d11RsSetScissorRectsVtableFn =
transmute(win32_com_vtable_slot(context, 45));
let draw_instanced: Win32D3d11ContextDrawInstancedVtableFn =
transmute(win32_com_vtable_slot(context, 21));
let cb_ptr: *mut c_void = swapchain.get_constant_buffer() as *mut c_void;
let Win32D3d11SwapChain { scratch_ranges, .. } = swapchain;
for &(base, count, scissor_rect, scroll) in scratch_ranges.iter() {
if count == 0 || (base as usize) >= prim_count {
continue;
}
let draw_count: u32 = count.min((prim_count as u32).saturating_sub(base));
let uniforms: D3d11LayerUniforms = D3d11LayerUniforms {
viewport_size: [vw as f32, vh as f32],
scroll_offset: scroll,
};
update_subresource(
context,
cb_ptr,
0,
null(),
(&uniforms as *const D3d11LayerUniforms).cast::<c_void>(),
0,
0,
);
let sx_u: u32 = scissor_rect.get_x().max(0.0).floor() as u32;
let sy_u: u32 = scissor_rect.get_y().max(0.0).floor() as u32;
let sw_u: u32 = scissor_rect.get_width().max(1.0).ceil() as u32;
let sh_u: u32 = scissor_rect.get_height().max(1.0).ceil() as u32;
let sx: i32 = sx_u.min(vw) as i32;
let sy: i32 = sy_u.min(vh) as i32;
let sr: i32 = sx_u.saturating_add(sw_u).min(vw) as i32;
let sb: i32 = sy_u.saturating_add(sh_u).min(vh) as i32;
let scissor: Win32Rect = Win32Rect {
left: sx,
top: sy,
right: sr.max(sx),
bottom: sb.max(sy),
};
rs_set_scissor(context, 1, &scissor);
draw_instanced(context, 6, draw_count, 0, base);
}
let null_t4: [*mut c_void; 1] = [null_mut()];
ps_set_srvs(context, 4, 1, null_t4.as_ptr());
}
let present_fn: Win32DxgiSwapChainPresentVtableFn = transmute(win32_com_vtable_slot(sc, 8));
let pflags: u32 = swapchain.get_present_flags();
let mut pres_hr: i32 = present_fn(sc, 0, pflags);
if pres_hr < 0 && pflags != 0 {
pres_hr = present_fn(sc, 0, 0);
}
if pres_hr < 0 {
pres_hr = present_fn(sc, 1, 0);
}
if pres_hr < 0 {
return Err(PlatformError::SurfaceError(
ERR_WIN32_D3D11_PRESENT.to_string(),
));
}
let mut stats: DxgiFrameStatistics = DxgiFrameStatistics::default();
let get_stats: Win32DxgiGetFrameStatisticsVtableFn =
transmute(win32_com_vtable_slot(sc, 16));
if get_stats(sc, &mut stats) >= 0 {
Ok((
stats.sync_qpc_time.max(0) as u64,
stats.present_count,
range_count.max(1),
prim_count,
))
} else {
Ok((0, 0, range_count.max(1), prim_count))
}
}
}
pub(crate) fn win32_pump_messages(
windows: &mut HashMap<WindowId, WindowsWindowRecord>,
events: &mut Vec<WindowEvent>,
) {
let mut msg: Win32Msg = Win32Msg::default();
unsafe {
while PeekMessageW(&mut msg, 0, 0, 0, PM_REMOVE) != 0 {
let _: i32 = TranslateMessage(&msg);
let _: isize = DispatchMessageW(&msg);
}
}
let queued: Vec<Win32QueuedEvent> = WIN32_EVENT_QUEUE
.try_with(|query_val: &RefCell<Vec<Win32QueuedEvent>>| {
query_val
.try_borrow_mut()
.map(|mut green_val: RefMut<'_, Vec<Win32QueuedEvent>>| take(&mut *green_val))
.unwrap_or_default()
})
.unwrap_or_default();
for item in queued.into_iter() {
let mut target: Option<(WindowId, f32)> = None;
for (wid, rec) in windows.iter() {
if rec.get_hwnd() == item.hwnd {
target = Some((*wid, rec.get_state().get_scale_factor()));
break;
}
}
let Some((wid, scale)) = target else {
continue;
};
match item.payload {
Win32EventPayload::Close => {
events.push(WindowEvent::CloseRequested(wid));
}
Win32EventPayload::Resized(phys_w, phys_h, new_scale) => {
let source_val: f32 = clamp_viewport_scale(new_scale);
let exact_lw: f32 = ((phys_w as f32) / source_val).max(1.0);
let exact_lh: f32 = ((phys_h as f32) / source_val).max(1.0);
let log_w: u32 = exact_lw.round().max(1.0) as u32;
let log_h: u32 = exact_lh.round().max(1.0) as u32;
if let Some(rec) = windows.get_mut(&wid) {
rec.get_mut_config().set_width(log_w);
rec.get_mut_config().set_height(log_h);
rec.get_mut_state().set_scale_factor(source_val);
rec.get_mut_state().set_logical_width(exact_lw);
rec.get_mut_state().set_logical_height(exact_lh);
rec.get_mut_state().set_physical_width(phys_w);
rec.get_mut_state().set_physical_height(phys_h);
}
events.push(WindowEvent::Resized(wid, log_w, log_h, source_val));
}
Win32EventPayload::Redraw => {
events.push(WindowEvent::RedrawRequested(wid));
}
Win32EventPayload::Focused(focused) => {
if let Some(rec) = windows.get_mut(&wid) {
rec.get_mut_state().set_focused(focused);
}
if !focused {
events.push(WindowEvent::PointerCancel(wid, 0));
}
events.push(WindowEvent::Focused(wid, focused));
}
Win32EventPayload::PointerCancel => {
events.push(WindowEvent::PointerCancel(wid, 0));
}
Win32EventPayload::PointerMove(px, py, mods) => {
let pos: Point = Point::new((px as f32) / scale, (py as f32) / scale);
let point_coords: PointerEvent = PointerEvent::new(
1,
PointerDevice::Mouse,
pos,
PointerButton::Primary,
0.0,
mods,
);
events.push(WindowEvent::PointerMove(wid, point_coords));
}
Win32EventPayload::PointerDown(px, py, button_node, mods) => {
let pos: Point = Point::new((px as f32) / scale, (py as f32) / scale);
let cursor_point: PointerEvent =
PointerEvent::new(1, PointerDevice::Mouse, pos, button_node, 1.0, mods);
events.push(WindowEvent::PointerDown(wid, cursor_point));
}
Win32EventPayload::PointerUp(px, py, button_element, mods) => {
let pos: Point = Point::new((px as f32) / scale, (py as f32) / scale);
let sample_point: PointerEvent =
PointerEvent::new(1, PointerDevice::Mouse, pos, button_element, 0.0, mods);
events.push(WindowEvent::PointerUp(wid, sample_point));
}
Win32EventPayload::Scroll(dy) => {
events.push(WindowEvent::Scroll(wid, Point::new(0.0, dy)));
}
Win32EventPayload::KeyDown(code, mods, repeat) => {
events.push(WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat)));
}
Win32EventPayload::KeyUp(code, mods) => {
events.push(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
}
Win32EventPayload::Text(ch) => {
events.push(WindowEvent::TextInput(wid, ch.to_string()));
}
Win32EventPayload::Activated(active) => {
if !active {
events.push(WindowEvent::PointerCancel(wid, 0));
}
let system_event: SystemEvent = if active {
SystemEvent::Foreground
} else {
SystemEvent::Inactive
};
events.push(WindowEvent::System(system_event));
}
Win32EventPayload::Minimized(minimized) => {
if minimized {
events.push(WindowEvent::PointerCancel(wid, 0));
}
let lifecycle_event: SystemEvent = if minimized {
SystemEvent::Background
} else {
SystemEvent::Foreground
};
events.push(WindowEvent::System(lifecycle_event));
}
Win32EventPayload::ClipboardUpdated => {
events.push(WindowEvent::System(SystemEvent::ClipboardChanged));
}
Win32EventPayload::ThemeUpdated => {
events.push(WindowEvent::ThemeChanged(wid, ThemeMode::Light));
}
Win32EventPayload::PowerStatusChanged(low_power) => {
events.push(WindowEvent::System(SystemEvent::LowPowerModeChanged(
low_power,
)));
}
Win32EventPayload::DisplayChanged => {
if let Some(rec) = windows.get_mut(&wid) {
let hz: f32 = win32_display_refresh_rate_hz(rec.get_hwnd());
rec.get_mut_state()
.get_mut_display()
.set_refresh_rate_hz(hz.round() as u32);
}
}
Win32EventPayload::Destroyed => {
events.push(WindowEvent::System(SystemEvent::Terminate));
}
}
}
}
pub(crate) fn win32_set_title(hwnd: usize, title: &str) {
if hwnd == 0 {
return;
}
let wide: Vec<u16> = win32_wide(title);
unsafe {
let _: i32 = SetWindowTextW(hwnd as isize, wide.as_ptr());
}
}
pub(crate) fn win32_set_size(hwnd: usize, width: u32, height: u32) {
if hwnd == 0 {
return;
}
unsafe {
let style: u32 = GetWindowLongW(hwnd as isize, -16) as u32;
let mut rect: Win32Rect = Win32Rect {
left: 0,
top: 0,
right: width.max(1) as i32,
bottom: height.max(1) as i32,
};
let _: i32 = AdjustWindowRectEx(&mut rect, style, 0, 0);
let _: i32 = SetWindowPos(
hwnd as isize,
0,
0,
0,
(rect.right - rect.left).max(1),
(rect.bottom - rect.top).max(1),
SWP_NOMOVE_NOZORDER,
);
}
}
pub(crate) fn win32_set_topmost(hwnd: usize, on_top: bool) {
if hwnd == 0 {
return;
}
let pos_z: isize = if on_top { HWND_TOPMOST } else { HWND_NOTOPMOST };
unsafe {
let _: i32 = SetWindowPos(hwnd as isize, pos_z, 0, 0, 0, 0, SWP_NOMOVE_NOSIZE);
}
}
pub(crate) fn win32_set_fullscreen(
hwnd: usize,
fullscreen: bool,
saved_style: &mut i32,
saved_placement: &mut Win32WindowPlacement,
) {
if hwnd == 0 {
return;
}
unsafe {
let win: isize = hwnd as isize;
if fullscreen {
let current_style: i32 = GetWindowLongW(win, GWL_STYLE);
*saved_style = current_style;
saved_placement.length = size_of::<Win32WindowPlacement>() as u32;
let _: i32 = GetWindowPlacement(win, saved_placement);
let monitor: isize = MonitorFromWindow(win, MONITOR_DEFAULTTONEAREST);
let mut mon_info: Win32MonitorInfoExW =
MaybeUninit::<Win32MonitorInfoExW>::zeroed().assume_init();
mon_info.cb_size = size_of::<Win32MonitorInfoExW>() as u32;
if monitor != 0 && GetMonitorInfoW(monitor, &mut mon_info) != 0 {
let borderless_style: i32 = ((current_style as u32) & !WS_OVERLAPPEDWINDOW) as i32;
let _: i32 = SetWindowLongW(win, GWL_STYLE, borderless_style);
let bounds: Win32Rect = mon_info.rc_monitor;
let _: i32 = SetWindowPos(
win,
0,
bounds.left,
bounds.top,
(bounds.right - bounds.left).max(1),
(bounds.bottom - bounds.top).max(1),
SWP_FULLSCREEN_ENTER,
);
}
} else {
let restore_style: i32 = if *saved_style != 0 {
*saved_style
} else {
WS_OVERLAPPEDWINDOW as i32
};
let _: i32 = SetWindowLongW(win, GWL_STYLE, restore_style);
if saved_placement.length == size_of::<Win32WindowPlacement>() as u32 {
let _: i32 = SetWindowPlacement(win, saved_placement);
}
let _: i32 = SetWindowPos(win, 0, 0, 0, 0, 0, SWP_FULLSCREEN_EXIT);
}
}
}
pub(crate) fn win32_set_visible(hwnd: usize, visible: bool) {
if hwnd == 0 {
return;
}
unsafe {
let _: i32 = ShowWindow(hwnd as isize, if visible { SW_SHOW } else { SW_HIDE });
}
}
pub(crate) fn win32_destroy(hwnd: usize) {
if hwnd == 0 {
return;
}
unsafe {
let _: i32 = DestroyWindow(hwnd as isize);
}
}