Skip to main content

d3d11/
d3d11.rs

1//! taut under Direct3D 11. The program renders with Direct3D as usual, and the interface lies
2//! over it: `taut::layer_d3d11::Layer`, created once from the program's device and context,
3//! draws it with one call per frame. Around it is the plainest possible program: a window, a
4//! device, a swap chain, and the window's messages forwarded to the interface.
5//!   cargo run -p taut --example d3d11
6//!
7//! The Direct3D API used is declared here by hand, as the Windows SDK's d3d11.h and dxgi.h
8//! declare it: COM methods are called by vtable index, noted beside each call. (A program using
9//! a Windows bindings crate calls them by name, and passes the layer its device's and context's
10//! raw pointers.)
11#[cfg(not(windows))]
12fn main() {
13    println!("Direct3D is Windows' own: there is nothing for this example to show here.");
14}
15
16#[cfg(windows)]
17fn main() {
18    direct3d::run();
19}
20
21#[cfg(windows)]
22#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
23pub mod direct3d {
24    use std::cell::RefCell;
25    use std::ffi::c_void;
26    use std::ptr::{null, null_mut};
27    use std::time::{Duration, Instant};
28    use taut::geom::Size;
29    use taut::layer_d3d11::Layer;
30    use taut::platform::{Messages, SystemClipboard};
31    use taut::{Color, Length, Ui};
32
33    /// An object of Direct3D's: a pointer to a pointer to its table of functions.
34    pub type Com = *mut c_void;
35
36    /// Function number `at` of a COM object's table, as a function of the kind `F`.
37    ///
38    /// # Safety
39    /// The object is alive, and its function of that number is of that kind.
40    pub unsafe fn function<F: Copy>(object: Com, at: usize) -> F {
41        // SAFETY: as the caller promises; a function is known by where it is, one number.
42        unsafe { std::mem::transmute_copy(&*(*(object as *const *const usize)).add(at)) }
43    }
44
45    /// Lets go of a COM object (function 2, of every one), if there is one.
46    ///
47    /// # Safety
48    /// The object is held once here, and not used after this.
49    pub unsafe fn release(object: Com) {
50        if !object.is_null() {
51            unsafe { function::<unsafe extern "system" fn(Com) -> u32>(object, 2)(object) };
52        }
53    }
54
55    /// Stops the program with what Direct3D said, where it said something went wrong.
56    pub fn check(result: i32, what: &str) {
57        assert!(result >= 0, "{what} failed: {:#010x}", result as u32);
58    }
59
60    #[repr(C)]
61    struct DXGI_SWAP_CHAIN_DESC {
62        width: u32,
63        height: u32,
64        refresh_rate: [u32; 2],
65        format: u32,
66        scanline_ordering: u32,
67        scaling: u32,
68        sample_count: u32,
69        sample_quality: u32,
70        buffer_usage: u32,
71        buffer_count: u32,
72        window: isize,
73        windowed: i32,
74        swap_effect: u32,
75        flags: u32,
76    }
77    #[repr(C)]
78    pub struct D3D11_VIEWPORT {
79        pub x: f32,
80        pub y: f32,
81        pub width: f32,
82        pub height: f32,
83        pub min_depth: f32,
84        pub max_depth: f32,
85    }
86    #[link(name = "d3d11")]
87    unsafe extern "system" {
88        fn D3D11CreateDeviceAndSwapChain(
89            adapter: Com,
90            driver: u32,
91            software: isize,
92            flags: u32,
93            levels: *const u32,
94            count: u32,
95            version: u32,
96            desc: *const DXGI_SWAP_CHAIN_DESC,
97            swap: *mut Com,
98            device: *mut Com,
99            level: *mut u32,
100            context: *mut Com,
101        ) -> i32;
102    }
103
104    /// A device and a swap chain on the window: on the graphics card, or on Windows' own
105    /// software renderer where there is none. And the swap chain's buffer as a render target.
106    pub struct Device {
107        /// The device (`ID3D11Device`), which makes things.
108        pub device: Com,
109        /// Its context (`ID3D11DeviceContext`), which draws and copies.
110        pub context: Com,
111        /// The swap chain (`IDXGISwapChain`).
112        pub swap: Com,
113        target: Com,
114        /// The buffers' size, in pixels.
115        size: [u32; 2],
116    }
117
118    impl Device {
119        pub fn new(window: isize) -> Device {
120            // Pixels of B8G8R8A8_UNORM (87), drawn into (0x20), two buffers, flipped (4).
121            let desc = DXGI_SWAP_CHAIN_DESC {
122                width: 0,
123                height: 0,
124                refresh_rate: [0, 0],
125                format: 87,
126                scanline_ordering: 0,
127                scaling: 0,
128                sample_count: 1,
129                sample_quality: 0,
130                buffer_usage: 0x20,
131                buffer_count: 2,
132                window,
133                windowed: 1,
134                swap_effect: 4,
135                flags: 0,
136            };
137            let mut made = Device { device: null_mut(), context: null_mut(), swap: null_mut(), target: null_mut(), size: [0; 2] };
138            // The graphics card (1), or else Windows' software renderer (5); for B8G8R8A8 (0x20).
139            // SAFETY: the description is whole, and the rest is room for what is made.
140            let result = [1, 5]
141                .into_iter()
142                .map(|driver| unsafe { D3D11CreateDeviceAndSwapChain(null_mut(), driver, 0, 0x20, null(), 0, 7, &desc, &mut made.swap, &mut made.device, null_mut(), &mut made.context) })
143                .find(|result| *result >= 0);
144            check(result.unwrap_or(-1), "making a Direct3D 11 device");
145            made.resize(0, 0);
146            made
147        }
148
149        /// The swap chain's buffers at the window's new size (0 by 0: the size it has), and a
150        /// render target for them.
151        pub fn resize(&mut self, width: u32, height: u32) {
152            const TEXTURE_2D: [u32; 4] = [0x6f15_aaf2, 0x4e89_d208, 0x9548_b49a, 0x9c4f_d335];
153            let (mut buffer, mut desc) = (null_mut(), [0u32; 11]);
154            // SAFETY: the target is let go of before the buffers are made again (swap chain 13
155            // resizes, 9 hands out a buffer; device 9 makes the render target; texture 10 says
156            // how large it is).
157            unsafe {
158                release(std::mem::replace(&mut self.target, null_mut()));
159                check(function::<unsafe extern "system" fn(Com, u32, u32, u32, u32, u32) -> i32>(self.swap, 13)(self.swap, 0, width, height, 0, 0), "resizing the swap chain");
160                check(function::<unsafe extern "system" fn(Com, u32, *const [u32; 4], *mut Com) -> i32>(self.swap, 9)(self.swap, 0, &TEXTURE_2D, &mut buffer), "finding the swap chain's buffer");
161                check(function::<unsafe extern "system" fn(Com, Com, *const c_void, *mut Com) -> i32>(self.device, 9)(self.device, buffer, null(), &mut self.target), "making the render target");
162                function::<unsafe extern "system" fn(Com, *mut [u32; 11])>(buffer, 10)(buffer, &mut desc);
163                release(buffer);
164            }
165            self.size = [desc[0], desc[1]];
166        }
167
168        /// The program's own picture, which is here a colour, in the whole window: the target
169        /// bound, its viewport set, and filled.
170        pub fn clear(&self, colour: [f32; 4]) {
171            let viewport = D3D11_VIEWPORT { x: 0.0, y: 0.0, width: self.size[0] as f32, height: self.size[1] as f32, min_depth: 0.0, max_depth: 1.0 };
172            // SAFETY: the context is alive (33 binds the target, 44 sets the viewport, 50 fills).
173            unsafe {
174                function::<unsafe extern "system" fn(Com, u32, *const Com, Com)>(self.context, 33)(self.context, 1, &self.target, null_mut());
175                function::<unsafe extern "system" fn(Com, u32, *const D3D11_VIEWPORT)>(self.context, 44)(self.context, 1, &viewport);
176                function::<unsafe extern "system" fn(Com, Com, *const [f32; 4])>(self.context, 50)(self.context, self.target, &colour);
177            }
178        }
179
180        /// Shows the frame, once the screen is ready for it (swap chain function 8).
181        pub fn show(&self) {
182            // SAFETY: the swap chain is alive.
183            unsafe { function::<unsafe extern "system" fn(Com, u32, u32) -> i32>(self.swap, 8)(self.swap, 1, 0) };
184        }
185    }
186
187    impl Drop for Device {
188        fn drop(&mut self) {
189            // SAFETY: each is held once, by this.
190            unsafe { [self.target, self.swap, self.context, self.device].into_iter().for_each(|object| release(object)) };
191        }
192    }
193
194    // Everything from here on is the program's own: its window, what it shows, its loop.
195
196    #[repr(C)]
197    struct WNDCLASSW {
198        style: u32,
199        proc: unsafe extern "system" fn(isize, u32, usize, isize) -> isize,
200        class_extra: i32,
201        window_extra: i32,
202        instance: isize,
203        icon: isize,
204        cursor: isize,
205        background: isize,
206        menu: *const u16,
207        name: *const u16,
208    }
209    #[repr(C)]
210    #[derive(Default)]
211    struct MSG {
212        hwnd: isize,
213        message: u32,
214        wparam: usize,
215        lparam: isize,
216        time: u32,
217        pt: [i32; 2],
218    }
219    #[repr(C)]
220    struct TRACKMOUSEEVENT {
221        size: u32,
222        flags: u32,
223        hwnd: isize,
224        hover_time: u32,
225    }
226    #[link(name = "user32")]
227    unsafe extern "system" {
228        fn RegisterClassW(class: *const WNDCLASSW) -> u16;
229        fn CreateWindowExW(ex: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: isize, menu: isize, instance: isize, param: *const c_void) -> isize;
230        fn DefWindowProcW(hwnd: isize, msg: u32, w: usize, l: isize) -> isize;
231        fn PeekMessageW(msg: *mut MSG, hwnd: isize, first: u32, last: u32, remove: u32) -> i32;
232        fn TranslateMessage(msg: *const MSG) -> i32;
233        fn DispatchMessageW(msg: *const MSG) -> isize;
234        fn PostQuitMessage(code: i32);
235        fn LoadCursorW(instance: isize, name: *const u16) -> isize;
236        fn TrackMouseEvent(track: *mut TRACKMOUSEEVENT) -> i32;
237        fn SetProcessDpiAwarenessContext(context: isize) -> i32;
238        fn GetDpiForWindow(hwnd: isize) -> u32;
239    }
240    #[link(name = "kernel32")]
241    unsafe extern "system" {
242        fn GetModuleHandleW(name: *const u16) -> isize;
243    }
244    const WM_DESTROY: u32 = 0x0002;
245    const WM_SIZE: u32 = 0x0005;
246    const WM_QUIT: u32 = 0x0012;
247    const WM_MOUSEMOVE: u32 = 0x0200;
248
249    thread_local! {
250        /// The messages the window got since they were last looked at.
251        static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
252    }
253
254    /// What Windows calls with each message for the window: it is kept, for the loop below.
255    unsafe extern "system" fn keep(hwnd: isize, msg: u32, w: usize, l: isize) -> isize {
256        HEARD.with_borrow_mut(|heard| heard.push((msg, w, l)));
257        // (Windows says when the pointer leaves the window only to a window that asks.)
258        let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
259        // SAFETY: the window is this one; the record is filled in as Windows wants it.
260        match msg {
261            WM_DESTROY => unsafe { PostQuitMessage(0) },
262            WM_MOUSEMOVE => _ = unsafe { TrackMouseEvent(&mut leave) },
263            _ => {}
264        }
265        unsafe { DefWindowProcW(hwnd, msg, w, l) }
266    }
267
268    /// Hands the window every message that is waiting for it; false once the program is to end.
269    fn pump() -> bool {
270        let mut message = MSG::default();
271        // SAFETY: messages of this thread's window, handed back to Windows to be sent on.
272        while unsafe { PeekMessageW(&mut message, 0, 0, 0, 1) } != 0 {
273            if message.message == WM_QUIT {
274                return false;
275            }
276            unsafe { (TranslateMessage(&message), DispatchMessageW(&message)) };
277        }
278        true
279    }
280
281    /// What the program's own parts are set to.
282    struct App {
283        still: bool,
284        speed: f32,
285        name: String,
286    }
287
288    fn describe(app: &mut App, ui: &mut Ui) {
289        let t = ui.theme;
290        ui.column().w(Length::Px(260.0)).offset(16.0, 16.0).pad(14.0).gap(10.0).fill(t.panel.with_alpha(0.9)).border(t.line_strong, 1.0).radius(10.0).shadow(12.0).open();
291        ui.text("Over Direct3D 11", t.font.bold(), t.text);
292        ui.switch(&mut app.still, "Hold the colour still");
293        ui.slider(&mut app.speed, 0.0..=4.0);
294        ui.text_box(&mut app.name, "Type here");
295        ui.note(&format!("{} letters typed", app.name.chars().count()));
296        ui.close();
297    }
298
299    pub fn run() {
300        let (class, title): (Vec<u16>, Vec<u16>) = ("taut-d3d11\0".encode_utf16().collect(), "taut over Direct3D 11\0".encode_utf16().collect());
301        // SAFETY: the class and the window are made once, with names that end in a zero; the
302        // pixels of this program are the screen's own (-4: per monitor, the second way).
303        let window = unsafe {
304            SetProcessDpiAwarenessContext(-4);
305            let instance = GetModuleHandleW(null());
306            let arrow = LoadCursorW(0, 32512 as *const u16);
307            RegisterClassW(&WNDCLASSW { style: 0, proc: keep, class_extra: 0, window_extra: 0, instance, icon: 0, cursor: arrow, background: 0, menu: null(), name: class.as_ptr() });
308            CreateWindowExW(0, class.as_ptr(), title.as_ptr(), 0x10CF_0000, i32::MIN, i32::MIN, 900, 600, 0, 0, instance, null())
309        };
310        let mut device = Device::new(window);
311        // SAFETY: the device and its context are the program's own, and alive.
312        let mut layer = unsafe { Layer::new(device.device, device.context) }.unwrap_or_else(|failed| panic!("{failed}"));
313        let mut ui = Ui::new(taut::platform::system_text(), Box::new(SystemClipboard));
314        ui.theme.bg = Color::NONE;
315        let mut app = App { still: false, speed: 1.0, name: String::new() };
316        let (mut messages, scale) = (Messages::of(window), unsafe { GetDpiForWindow(window) } as f32 / 96.0);
317        let (mut waiting, started, mut hue) = (true, Instant::now(), 0.0f32);
318        while pump() {
319            for (msg, w, l) in HEARD.take() {
320                let (width, height) = (l as u32 & 0xffff, l as u32 >> 16 & 0xffff);
321                if msg == WM_SIZE && width > 0 && height > 0 {
322                    device.resize(width, height);
323                    ui.resize(Size { w: width as f32 / scale, h: height as f32 / scale }, scale);
324                    waiting = true;
325                }
326                // SAFETY: the message comes straight from the window procedure, with what
327                // Windows sent along with it.
328                unsafe { messages.events(msg, w, l, scale, |event| waiting |= ui.event(event)) };
329            }
330            // The interface runs when something happened, or something in it moves.
331            ui.set_time(started.elapsed());
332            if std::mem::take(&mut waiting) || ui.wake_in() == Some(Duration::ZERO) {
333                ui.run(&mut |ui| describe(&mut app, ui));
334            }
335            hue += if app.still { 0.0 } else { app.speed / 120.0 };
336            device.clear([0.3 + 0.25 * hue.sin(), 0.3 + 0.25 * (hue + 2.1).sin(), 0.3 + 0.25 * (hue + 4.2).sin(), 1.0]);
337            layer.draw(&mut ui).unwrap_or_else(|failed| panic!("{failed}"));
338            device.show();
339        }
340    }
341}