ggez_egui/
lib.rs

1mod input;
2mod painter;
3pub use input::Input;
4use painter::Painter;
5use std::{cell::RefCell, ops::Deref, rc::Rc};
6use ggez::{graphics::{self, Drawable, Canvas, DrawParam, GraphicsContext}, context::Has};
7
8pub use egui;
9
10/// Contains a copy of [`egui::Context`] and a mutable reference for the paint_jobs vector from [`Painter`].
11///
12/// When is droped automatically will call [`egui::Context::end_frame`] function and update the paint_jobs
13pub struct EguiContext {
14	context  : egui::Context,
15	painter  : Rc<RefCell<Painter>>,
16	clipboard: Rc<RefCell<String >>,
17}
18
19impl Deref for EguiContext {
20	type Target = egui::Context;
21	fn deref(&self) -> &Self::Target {
22		&self.context
23	}
24}
25
26impl Drop for EguiContext {
27	fn drop(&mut self) {
28		let egui::FullOutput {
29			platform_output,
30			textures_delta,
31			shapes,
32			repaint_after: _,
33		} = self.context.end_frame();
34
35		if !platform_output.copied_text.is_empty() {
36			*self.clipboard.borrow_mut() = platform_output.copied_text;
37		}
38		self.painter.borrow_mut().shapes = self.context.tessellate(shapes);
39		self.painter.borrow_mut().textures_delta.push_front(textures_delta);
40	}
41}
42
43/// Contains and handles everything related to [`egui`]
44#[derive(Default)]
45pub struct EguiBackend {
46	context: egui::Context,
47	pub input: Input,
48	painter: Rc<RefCell<Painter>>,
49}
50
51impl EguiBackend {
52	/// Create a [`EguiBackend`] with extra information for use the [`Input::set_scale_factor`]
53	pub fn new(ctx: &ggez::Context) -> Self {
54		let mut input = Input::default();
55		let (w, h) = ctx.gfx.size();
56		input.set_scale_factor(1.0, (w, h));
57		Self {
58			input,
59			..Default::default()
60		}
61	}
62
63	pub fn update(&mut self, ctx: &mut ggez::Context) {
64		self.input.update(ctx);
65		self.painter.borrow_mut().update(ctx);
66	}
67
68	/// Return an [`EguiContext`] for update the gui
69	pub fn ctx(&mut self) -> EguiContext {
70		self.context.begin_frame(self.input.take());
71		EguiContext {
72			context: self.context.clone(),
73			painter: self.painter.clone(),
74			clipboard: self.input.clipboard.clone(),
75		}
76	}
77}
78
79impl Drawable for EguiBackend {
80	/// this funtion comes from [`Drawable`] trait that allow the struct use the function [`ggez::graphics::draw`]
81	/// * Example
82	/// ```
83	/// struct State {
84	/// 	egui_backend: EguiBackend
85	/// }
86	/// 
87	/// impl EventHandler<ggez::GameError> for State {
88	/// 	fn draw(&mut self, ctx: &mut ggez::Context) -> {
89	/// 		ggez::graphics::draw(ctx, &self.egui_backend, ([0.0, 0.0],))?;
90	/// 		...
91	/// 	} 
92	/// 	...
93	/// }
94	/// ```
95	fn draw(&self, canvas: &mut Canvas, _param: impl Into<DrawParam>) {
96		self.painter.borrow_mut().draw(canvas, self.input.scale_factor);
97	}
98
99	fn dimensions(&self, _gfx: &impl Has<GraphicsContext>) -> Option<graphics::Rect> {
100		None
101	}
102}