hUI/hui-examples/boilerplate.rs

85 lines
2.4 KiB
Rust
Raw Normal View History

2024-02-29 09:02:05 -06:00
use glam::{UVec2, Vec2};
2024-03-21 13:40:48 -05:00
use glium::{Surface, backend::glutin::SimpleWindowBuilder};
2024-02-29 09:02:05 -06:00
use winit::{
event::{Event, WindowEvent},
event_loop::{EventLoopBuilder, ControlFlow}
};
use hui::UiInstance;
use hui_glium::GliumUiRenderer;
/// Generates a `main` function that initializes glium renderer, `UiInstance`, and runs the event loop.
macro_rules! ui_main {
2024-03-06 17:41:26 -06:00
($name:literal, init: $closure0:expr, run: $closure1:expr) => {
fn main() {
2024-03-06 17:41:26 -06:00
$crate::boilerplate::ui($closure0, $closure1, $name);
}
};
(init: $closure0:expr, run: $closure1:expr) => {
fn main() {
$crate::boilerplate::ui($closure0, $closure1, "hUI example");
}
};
2024-02-29 09:02:05 -06:00
($closure: expr) => {
fn main() {
2024-03-06 17:41:26 -06:00
$crate::boilerplate::ui(|_|(), $closure, "hUI example");
2024-02-29 09:02:05 -06:00
}
};
}
/// Initializes glium renderer, `UiInstance`, and runs the event loop.
2024-03-06 17:41:26 -06:00
pub fn ui<T>(
mut init: impl FnMut(&mut UiInstance) -> T,
2024-03-11 14:52:25 -05:00
mut draw: impl FnMut(&mut UiInstance, Vec2, &mut T),
2024-03-06 17:41:26 -06:00
name: &'static str
) {
2024-02-29 09:02:05 -06:00
kubi_logging::init();
let event_loop = EventLoopBuilder::new().build().unwrap();
2024-03-21 13:40:48 -05:00
let (window, display) = SimpleWindowBuilder::new()
.with_title(name)
.build(&event_loop);
2024-03-06 17:42:01 -06:00
2024-02-29 09:02:05 -06:00
let mut hui = UiInstance::new();
let mut backend = GliumUiRenderer::new(&display);
2024-03-11 14:48:39 -05:00
let mut result = init(&mut hui);
2024-02-29 09:02:05 -06:00
event_loop.run(|event, window_target| {
window.request_redraw();
2024-02-29 09:02:05 -06:00
window_target.set_control_flow(ControlFlow::Poll);
2024-02-29 09:11:29 -06:00
hui_winit::handle_winit_event(&mut hui, &event);
2024-02-29 09:02:05 -06:00
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => {
window_target.exit();
},
2024-09-08 05:13:44 -05:00
WindowEvent::Resized(size) => {
display.resize((size.width, size.height));
},
WindowEvent::RedrawRequested => {
let mut frame = display.draw();
2024-03-01 13:49:41 -06:00
frame.clear_color_srgb(0.5, 0.5, 0.5, 1.);
2024-02-29 09:02:05 -06:00
hui.begin();
2024-02-29 09:02:05 -06:00
let size = UVec2::from(display.get_framebuffer_dimensions()).as_vec2();
2024-03-11 14:48:39 -05:00
draw(&mut hui, size, &mut result);
2024-02-29 09:02:05 -06:00
hui.end();
2024-02-29 09:02:05 -06:00
backend.update(&hui);
backend.draw(&mut frame, size);
2024-02-29 09:02:05 -06:00
frame.finish().unwrap();
},
_ => (),
},
Event::Suspended => {
#[cfg(target_os = "android")]
window_target.exit();
},
2024-02-29 09:02:05 -06:00
_ => (),
}
}).unwrap();
}