-
Notifications
You must be signed in to change notification settings - Fork 86
/
hello-world.rs
341 lines (299 loc) · 11 KB
/
hello-world.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use imgui::*;
use imgui_wgpu::{Renderer, RendererConfig};
use imgui_winit_support::WinitPlatform;
use pollster::block_on;
use std::{sync::Arc, time::Instant};
use winit::{
application::ApplicationHandler,
dpi::LogicalSize,
event::{Event, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
keyboard::{Key, NamedKey},
window::Window,
};
struct ImguiState {
context: imgui::Context,
platform: WinitPlatform,
renderer: Renderer,
clear_color: wgpu::Color,
demo_open: bool,
last_frame: Instant,
last_cursor: Option<MouseCursor>,
}
struct AppWindow {
device: wgpu::Device,
queue: wgpu::Queue,
window: Arc<Window>,
surface_desc: wgpu::SurfaceConfiguration,
surface: wgpu::Surface<'static>,
hidpi_factor: f64,
imgui: Option<ImguiState>,
}
#[derive(Default)]
struct App {
window: Option<AppWindow>,
}
impl AppWindow {
fn setup_gpu(event_loop: &ActiveEventLoop) -> Self {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
});
let window = {
let version = env!("CARGO_PKG_VERSION");
let size = LogicalSize::new(1280.0, 720.0);
let attributes = Window::default_attributes()
.with_inner_size(size)
.with_title(&format!("imgui-wgpu {version}"));
Arc::new(event_loop.create_window(attributes).unwrap())
};
let size = window.inner_size();
let hidpi_factor = window.scale_factor();
let surface = instance.create_surface(window.clone()).unwrap();
let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}))
.unwrap();
let (device, queue) =
block_on(adapter.request_device(&wgpu::DeviceDescriptor::default(), None)).unwrap();
// Set up swap chain
let surface_desc = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
desired_maximum_frame_latency: 2,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![wgpu::TextureFormat::Bgra8Unorm],
};
surface.configure(&device, &surface_desc);
let imgui = None;
Self {
device,
queue,
window,
surface_desc,
surface,
hidpi_factor,
imgui,
}
}
fn setup_imgui(&mut self) {
let mut context = imgui::Context::create();
let mut platform = imgui_winit_support::WinitPlatform::new(&mut context);
platform.attach_window(
context.io_mut(),
&self.window,
imgui_winit_support::HiDpiMode::Default,
);
context.set_ini_filename(None);
let font_size = (13.0 * self.hidpi_factor) as f32;
context.io_mut().font_global_scale = (1.0 / self.hidpi_factor) as f32;
context.fonts().add_font(&[FontSource::DefaultFontData {
config: Some(imgui::FontConfig {
oversample_h: 1,
pixel_snap_h: true,
size_pixels: font_size,
..Default::default()
}),
}]);
//
// Set up dear imgui wgpu renderer
//
let clear_color = wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
};
let renderer_config = RendererConfig {
texture_format: self.surface_desc.format,
..Default::default()
};
let renderer = Renderer::new(&mut context, &self.device, &self.queue, renderer_config);
let last_frame = Instant::now();
let last_cursor = None;
let demo_open = true;
self.imgui = Some(ImguiState {
context,
platform,
renderer,
clear_color,
demo_open,
last_frame,
last_cursor,
})
}
fn new(event_loop: &ActiveEventLoop) -> Self {
let mut window = Self::setup_gpu(event_loop);
window.setup_imgui();
window
}
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
self.window = Some(AppWindow::new(event_loop));
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
window_id: winit::window::WindowId,
event: WindowEvent,
) {
let window = self.window.as_mut().unwrap();
let imgui = window.imgui.as_mut().unwrap();
match &event {
WindowEvent::Resized(size) => {
window.surface_desc = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
desired_maximum_frame_latency: 2,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![wgpu::TextureFormat::Bgra8Unorm],
};
window
.surface
.configure(&window.device, &window.surface_desc);
}
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::KeyboardInput { event, .. } => {
if let Key::Named(NamedKey::Escape) = event.logical_key {
if event.state.is_pressed() {
event_loop.exit();
}
}
}
WindowEvent::RedrawRequested => {
let delta_s = imgui.last_frame.elapsed();
let now = Instant::now();
imgui
.context
.io_mut()
.update_delta_time(now - imgui.last_frame);
imgui.last_frame = now;
let frame = match window.surface.get_current_texture() {
Ok(frame) => frame,
Err(e) => {
eprintln!("dropped frame: {e:?}");
return;
}
};
imgui
.platform
.prepare_frame(imgui.context.io_mut(), &window.window)
.expect("Failed to prepare frame");
let ui = imgui.context.frame();
{
let window = ui.window("Hello world");
window
.size([300.0, 100.0], Condition::FirstUseEver)
.build(|| {
ui.text("Hello world!");
ui.text("This...is...imgui-rs on WGPU!");
ui.separator();
let mouse_pos = ui.io().mouse_pos;
ui.text(format!(
"Mouse Position: ({:.1},{:.1})",
mouse_pos[0], mouse_pos[1]
));
});
let window = ui.window("Hello too");
window
.size([400.0, 200.0], Condition::FirstUseEver)
.position([400.0, 200.0], Condition::FirstUseEver)
.build(|| {
ui.text(format!("Frametime: {delta_s:?}"));
});
ui.show_demo_window(&mut imgui.demo_open);
}
let mut encoder: wgpu::CommandEncoder = window
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
if imgui.last_cursor != ui.mouse_cursor() {
imgui.last_cursor = ui.mouse_cursor();
imgui.platform.prepare_render(ui, &window.window);
}
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(imgui.clear_color),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
imgui
.renderer
.render(
imgui.context.render(),
&window.queue,
&window.device,
&mut rpass,
)
.expect("Rendering failed");
drop(rpass);
window.queue.submit(Some(encoder.finish()));
frame.present();
}
_ => (),
}
imgui.platform.handle_event::<()>(
imgui.context.io_mut(),
&window.window,
&Event::WindowEvent { window_id, event },
);
}
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: ()) {
let window = self.window.as_mut().unwrap();
let imgui = window.imgui.as_mut().unwrap();
imgui.platform.handle_event::<()>(
imgui.context.io_mut(),
&window.window,
&Event::UserEvent(event),
);
}
fn device_event(
&mut self,
_event_loop: &ActiveEventLoop,
device_id: winit::event::DeviceId,
event: winit::event::DeviceEvent,
) {
let window = self.window.as_mut().unwrap();
let imgui = window.imgui.as_mut().unwrap();
imgui.platform.handle_event::<()>(
imgui.context.io_mut(),
&window.window,
&Event::DeviceEvent { device_id, event },
);
}
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
let window = self.window.as_mut().unwrap();
let imgui = window.imgui.as_mut().unwrap();
window.window.request_redraw();
imgui.platform.handle_event::<()>(
imgui.context.io_mut(),
&window.window,
&Event::AboutToWait,
);
}
}
fn main() {
env_logger::init();
let event_loop = EventLoop::new().unwrap();
event_loop.set_control_flow(ControlFlow::Poll);
event_loop.run_app(&mut App::default()).unwrap();
}