1#[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 pub type Com = *mut c_void;
35
36 pub unsafe fn function<F: Copy>(object: Com, at: usize) -> F {
41 unsafe { std::mem::transmute_copy(&*(*(object as *const *const usize)).add(at)) }
43 }
44
45 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 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 pub struct Device {
107 pub device: Com,
109 pub context: Com,
111 pub swap: Com,
113 target: Com,
114 size: [u32; 2],
116 }
117
118 impl Device {
119 pub fn new(window: isize) -> Device {
120 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 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 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 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 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 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 pub fn show(&self) {
182 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 unsafe { [self.target, self.swap, self.context, self.device].into_iter().for_each(|object| release(object)) };
191 }
192 }
193
194 #[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 static HEARD: RefCell<Vec<(u32, usize, isize)>> = const { RefCell::new(Vec::new()) };
252 }
253
254 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 let mut leave = TRACKMOUSEEVENT { size: size_of::<TRACKMOUSEEVENT>() as u32, flags: 2, hwnd, hover_time: 0 };
259 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 fn pump() -> bool {
270 let mut message = MSG::default();
271 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 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 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 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 unsafe { messages.events(msg, w, l, scale, |event| waiting |= ui.event(event)) };
329 }
330 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}