Rust rendering library built on top of Raylib
0

Configure Feed

Select the types of activity you want to include in your feed.

ren / crates / ren-graphics / src / _lib / window.rs
3.2 kB 133 lines
1use ren_core::{math::Vec2, time::Delta}; 2use std::{ffi::CString, path::PathBuf}; 3 4use raylib_ffi::{ 5 self as rl, 6 enums::{ConfigFlags, KeyboardKey, TraceLogLevel}, 7}; 8 9use crate::Drawer; 10 11#[derive(Clone, Copy)] 12pub struct Resolution { 13 pub width: u32, 14 pub height: u32, 15} 16 17pub struct Window { 18 pub open: bool, 19 pub seconds_open: f64, 20 pub frame: u64, 21 icon: Option<rl::Image>, 22} 23 24impl Window { 25 pub fn new(width: i32, height: i32, title: String) -> Self { 26 unsafe { 27 rl::SetTraceLogLevel(TraceLogLevel::Warning as i32); 28 rl::SetConfigFlags(ConfigFlags::WindowResizable as u32); 29 rl::InitWindow(width, height, CString::new(title).unwrap().as_ptr()); 30 rl::SetExitKey(KeyboardKey::Null as i32); 31 rl::SetTargetFPS(60); 32 } 33 Self { 34 open: true, 35 seconds_open: 0.0, 36 frame: 0, 37 icon: None, 38 } 39 } 40 41 pub fn should_close(&self) -> bool { 42 unsafe { rl::WindowShouldClose() } 43 } 44 45 pub fn close(&mut self) { 46 self.open = false; 47 unsafe { 48 if let Some(icon) = self.icon { 49 rl::UnloadImage(icon); 50 self.icon = None; 51 } 52 rl::CloseWindow(); 53 } 54 } 55 56 pub fn get_window_size(&self) -> Vec2<i32> { 57 Vec2 { 58 x: unsafe { rl::GetScreenWidth() }, 59 y: unsafe { rl::GetScreenHeight() }, 60 } 61 } 62 63 pub fn get_fps(&self) -> i32 { 64 unsafe { rl::GetFPS() } 65 } 66 67 /* get delta time in seconds */ 68 pub fn get_delta_time(&self) -> Delta { 69 unsafe { rl::GetFrameTime() as f64 } 70 } 71 72 pub fn get_mouse_pos(&self) -> Vec2<f32> { 73 let v = unsafe { rl::GetMousePosition() }; 74 Vec2::new(v.x, v.y) 75 } 76 77 pub fn get_mouse_delta(&self) -> Vec2<f32> { 78 let v = unsafe { rl::GetMouseDelta() }; 79 Vec2::new(v.x, v.y) 80 } 81 82 pub fn set_cursor_shown(&mut self, shown: bool) { 83 if shown { 84 unsafe { 85 rl::ShowCursor(); 86 } 87 } else { 88 unsafe { 89 rl::HideCursor(); 90 } 91 } 92 } 93 94 pub fn set_icon(&mut self, icon_path: PathBuf) { 95 if let Some(icon) = self.icon { 96 unsafe { 97 rl::UnloadImage(icon); 98 } 99 } 100 self.icon = Some(unsafe { 101 rl::LoadImage(CString::new(icon_path.to_str().unwrap()).unwrap().as_ptr()) 102 }); 103 unsafe { 104 rl::SetWindowIcon(self.icon.unwrap()); 105 } 106 } 107 108 pub fn set_title(&mut self, title: String) { 109 unsafe { 110 rl::SetWindowTitle(CString::new(title).unwrap().as_ptr()); 111 } 112 } 113 114 pub fn draw<T: Fn(&mut Drawer)>(&self, f: T) { 115 unsafe { 116 rl::BeginDrawing(); 117 } 118 f(&mut Drawer::Window); 119 unsafe { 120 rl::EndDrawing(); 121 } 122 } 123 124 pub fn draw_mut<T: FnMut(&mut Drawer)>(&self, f: &mut T) { 125 unsafe { 126 rl::BeginDrawing(); 127 } 128 f(&mut Drawer::Window); 129 unsafe { 130 rl::EndDrawing(); 131 } 132 } 133}