1use glutin::dpi::PhysicalPosition;
2use glutin::event_loop::EventLoop;
3use glutin::window::WindowBuilder;
4use glutin::ContextBuilder;
5use glutin::dpi::PhysicalSize;
6use glutin::PossiblyCurrent;
7use glutin::WindowedContext;
8
9pub struct Window {
10 context: WindowedContext<PossiblyCurrent>,
11 size: PhysicalSize<u32>,
12 previous_size: PhysicalSize<u32>, cursor_position: Option<PhysicalPosition<f64>>, }
15
16impl Window {
17 pub fn new(title: &str, width: u32, height: u32) -> (Self, EventLoop<()>) {
18 let size = PhysicalSize::new(width, height);
19 let event_loop = EventLoop::new();
20 let wb = WindowBuilder::new().with_title(title).with_inner_size(size);
21
22 let windowed_context = ContextBuilder::new()
23 .with_vsync(true)
24 .build_windowed(wb, &event_loop)
25 .unwrap();
26
27 let windowed_context = unsafe { windowed_context.make_current().unwrap() };
28
29 (
30 Self {
31 context: windowed_context,
32 size,
33 previous_size: size, cursor_position: None,
35 },
36 event_loop,
37 )
38 }
39
40 pub fn size(&self) -> (f32, f32) {
41 (self.size.width as f32, self.size.height as f32)
42 }
43
44 pub fn swap_buffers(&self) {
45 self.context.swap_buffers().unwrap();
46 }
47
48 pub fn get_proc_address(&self, s: &str) -> *const std::ffi::c_void {
49 self.context.get_proc_address(s) as *const _
50 }
51
52 pub fn resize(&mut self, new_size: PhysicalSize<u32>) -> (f32, f32) {
53 let scale_x = (new_size.width as f32) / (self.size.width as f32);
54 let scale_y = (new_size.height as f32) / (self.size.height as f32);
55
56 self.previous_size = self.size;
57 self.size = new_size;
58 self.context.resize(new_size);
59
60 unsafe {
61 gl::Viewport(0, 0, new_size.width as i32, new_size.height as i32);
62 }
63
64 (scale_x, scale_y)
65 }
66
67 pub fn set_size(&mut self, width: u32, height: u32) {
68 self.resize(PhysicalSize::new(width, height));
69 }
70
71 pub fn set_cursor_position(&mut self, position: PhysicalPosition<f64>) {
72 self.cursor_position = Some(position);
73 }
74
75 pub fn get_cursor_position(&self) -> Option<(f64, f64)> {
77 self.cursor_position.map(|pos| (pos.x, pos.y))
78 }
79}