Skip to main content

hao_il2cpp_unity/
egui_backend.rs

1//! Draw an [`egui`] UI over the game from the render hook. Enable with the
2//! `egui` feature.
3//!
4//! egui is rendered with Unity's immediate-mode [`gl`](crate::gl): its font atlas
5//! is uploaded to a [`Texture2D`] (point-sampled, so solid fills stay opaque),
6//! bound through a `Material`, and each tessellated triangle is emitted (with its
7//! colours converted from gamma to linear) into an [`OverlaySurface`], which draws
8//! it on top of the game's own UI. See [`on_egui`].
9
10use std::collections::HashMap;
11use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
12use std::sync::{Arc, Mutex};
13
14use hao_il2cpp_runtime::{GcHandle, Object, Result};
15
16use crate::{gl, input, screen, Color, Material, OverlaySurface, Shader, Texture2D, TextureFormat};
17
18static UI_SCALE: AtomicU32 = AtomicU32::new(0);
19static NEXT_USER_TEX: AtomicU64 = AtomicU64::new(1);
20static USER_TEXTURES: std::sync::LazyLock<Mutex<HashMap<u64, GcHandle>>> =
21    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
22
23/// Scales the egui overlay UI. A value of 0.5 makes the UI half-size; 2.0 makes
24/// it double-size. Font rasterization quality is preserved — only the coordinate
25/// space is scaled. Pass 0.0 to reset to the default (1.0).
26pub fn set_ui_scale(scale: f32) {
27    if scale <= 0.0 {
28        UI_SCALE.store(0, Ordering::Relaxed);
29    } else {
30        UI_SCALE.store(scale.to_bits(), Ordering::Relaxed);
31    }
32}
33
34fn ui_scale() -> f32 {
35    let bits = UI_SCALE.load(Ordering::Relaxed);
36    if bits == 0 { 1.0 } else { f32::from_bits(bits) }
37}
38
39/// Registers a Unity texture object for use in egui as a user texture.
40///
41/// Returns a [`egui::TextureId::User`] id that can be passed to egui's
42/// `Image` widget via `SizedTexture`. The texture object is GC-pinned so it
43/// won't be collected while registered.
44pub fn register_user_texture(object: Object) -> Result<egui::TextureId> {
45    let id = NEXT_USER_TEX.fetch_add(1, Ordering::Relaxed);
46    let handle = GcHandle::new(crate::il2cpp()?, object);
47    USER_TEXTURES.lock().unwrap().insert(id, handle);
48    Ok(egui::TextureId::User(id))
49}
50
51/// Removes a previously registered user texture.
52pub fn unregister_user_texture(id: egui::TextureId) {
53    if let egui::TextureId::User(n) = id {
54        USER_TEXTURES.lock().unwrap().remove(&n);
55    }
56}
57
58/// Runs `ui` every frame to build and draw an egui interface over the game.
59///
60/// Call it once (e.g. from `on_init`). The egui context, font texture and
61/// material are created on the render thread on the first frame. Mouse input is
62/// fed from `UnityEngine.Input`.
63pub fn on_egui(ui: impl Fn(&egui::Context) + Send + Sync + 'static) -> Result<()> {
64    let ui = Arc::new(ui);
65    let state: Mutex<Option<EguiState>> = Mutex::new(None);
66    // The render hook fires once per camera, so several times per frame. Run egui
67    // (input + layout) only on the first callback of each frame: otherwise a click
68    // edge is read in whichever camera's pass happened to catch it, so presses get
69    // dropped. The render target persists, so one draw per frame is enough.
70    let last_frame = std::sync::atomic::AtomicI32::new(-1);
71    crate::on_render(move |_camera| {
72        match crate::time::frame_count() {
73            Ok(frame) if last_frame.swap(frame, std::sync::atomic::Ordering::Relaxed) == frame => {
74                return
75            }
76            _ => {}
77        }
78        let mut guard = state.lock().unwrap_or_else(|e| e.into_inner());
79        let state = match guard.as_mut() {
80            Some(state) => state,
81            None => match EguiState::new() {
82                Ok(state) => guard.insert(state),
83                Err(e) => {
84                    tracing::error!("egui init failed: {}", e);
85                    return;
86                }
87            },
88        };
89        if let Err(e) = state.frame(&*ui) {
90            tracing::error!("egui frame failed: {}", e);
91        }
92    })
93}
94
95struct EguiState {
96    ctx: egui::Context,
97    /// Kept alive across frames: the GC doesn't scan Rust memory.
98    material: GcHandle,
99    texture: Option<(GcHandle, [usize; 2])>,
100    /// A CPU copy of the font atlas (RGBA), patched from egui's texture deltas.
101    atlas: Vec<u8>,
102    /// Previous state of the left/right mouse buttons, so a press or release is
103    /// sent to egui only on the edge (egui is event-based, not level-based).
104    pointer_down: [bool; 2],
105    /// Previous held state of each key in [`KEYS`], for the same edge detection
106    /// (read from the held state, as GetKeyDown is unreliable off the main thread).
107    keys_down: [bool; KEYS.len()],
108    /// Previous held state of typeable keys for the fallback text input path.
109    text_keys_down: [bool; TEXT_KEYS.len()],
110    /// Whether `Input.inputString` has ever returned a non-empty string. Once
111    /// it does, the fallback key-to-char path is disabled.
112    input_string_works: bool,
113    /// The top-most render target egui draws into and is composited from.
114    surface: OverlaySurface,
115}
116
117/// Non-text keys forwarded to egui for editing and navigation. Typed characters
118/// go through `Input.inputString` instead (see [`EguiState::raw_input`]).
119const KEYS: &[(crate::KeyCode, egui::Key)] = {
120    use crate::KeyCode as K;
121    use egui::Key;
122    &[
123        (K::BACKSPACE, Key::Backspace),
124        (K::DELETE, Key::Delete),
125        (K::RETURN, Key::Enter),
126        (K::TAB, Key::Tab),
127        (K::ESCAPE, Key::Escape),
128        (K::LEFT, Key::ArrowLeft),
129        (K::RIGHT, Key::ArrowRight),
130        (K::UP, Key::ArrowUp),
131        (K::DOWN, Key::ArrowDown),
132        (K::HOME, Key::Home),
133        (K::END, Key::End),
134        (K::PAGE_UP, Key::PageUp),
135        (K::PAGE_DOWN, Key::PageDown),
136        (K::SPACE, Key::Space),
137        // With a held ctrl/cmd these drive select-all/copy/paste/cut/undo.
138        (K::A, Key::A),
139        (K::C, Key::C),
140        (K::V, Key::V),
141        (K::X, Key::X),
142        (K::Z, Key::Z),
143    ]
144};
145
146/// Typeable keys for the fallback text input path. Each entry is a key code, the
147/// lowercase char, and the shifted char. Used only when `Input.inputString` is
148/// unavailable — it doesn't handle non-US layouts, but covers the common case.
149const TEXT_KEYS: &[(crate::KeyCode, char, char)] = {
150    use crate::KeyCode as K;
151    &[
152        (K::A, 'a', 'A'), (K::B, 'b', 'B'), (K::C, 'c', 'C'), (K::D, 'd', 'D'),
153        (K::E, 'e', 'E'), (K::F, 'f', 'F'), (K::G, 'g', 'G'), (K::H, 'h', 'H'),
154        (K::I, 'i', 'I'), (K::J, 'j', 'J'), (K::K, 'k', 'K'), (K::L, 'l', 'L'),
155        (K::M, 'm', 'M'), (K::N, 'n', 'N'), (K::O, 'o', 'O'), (K::P, 'p', 'P'),
156        (K::Q, 'q', 'Q'), (K::R, 'r', 'R'), (K::S, 's', 'S'), (K::T, 't', 'T'),
157        (K::U, 'u', 'U'), (K::V, 'v', 'V'), (K::W, 'w', 'W'), (K::X, 'x', 'X'),
158        (K::Y, 'y', 'Y'), (K::Z, 'z', 'Z'),
159        (K::ALPHA0, '0', ')'), (K::ALPHA1, '1', '!'), (K::ALPHA2, '2', '@'),
160        (K::ALPHA3, '3', '#'), (K(52), '4', '$'), (K(53), '5', '%'),
161        (K(54), '6', '^'), (K(55), '7', '&'), (K(56), '8', '*'),
162        (K(57), '9', '('),
163        (K::SPACE, ' ', ' '),
164    ]
165};
166
167/// Builds the egui material: a textured, vertex-coloured, alpha-blended shader.
168/// `HideAndDontSave` keeps Unity from destroying it (and throwing NRE on later
169/// use) when a scene loads, which `DontDestroyOnLoad` does not do for assets.
170fn make_material() -> Result<Material> {
171    let (name, shader) = match Shader::find("Sprites/Default")? {
172        Some(shader) => ("Sprites/Default", shader),
173        None => (
174            "UI/Default",
175            Shader::find("UI/Default")?.ok_or_else(|| {
176                hao_il2cpp_runtime::Error::NotFound("a sprite/UI shader for egui".into())
177            })?,
178        ),
179    };
180    tracing::debug!(shader = name, "egui material shader");
181    let material = Material::new(shader)?;
182    material.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
183    Ok(material)
184}
185
186impl EguiState {
187    fn new() -> Result<Self> {
188        let ctx = egui::Context::default();
189        if let Ok((w, h)) = screen::size() {
190            tracing::info!(w, h, scale = ui_scale(), "egui overlay: screen size");
191        }
192        let material = make_material()?;
193        Ok(Self {
194            ctx,
195            material: GcHandle::new(crate::il2cpp()?, material.object()),
196            texture: None,
197            atlas: Vec::new(),
198            pointer_down: [false; 2],
199            keys_down: [false; KEYS.len()],
200            text_keys_down: [false; TEXT_KEYS.len()],
201            input_string_works: false,
202            surface: OverlaySurface::new("hao-egui-overlay"),
203        })
204    }
205
206    fn material(&self) -> Material {
207        Material(self.material.target())
208    }
209
210    /// Rebuilds the material and font texture if a scene load destroyed them
211    /// despite `HideAndDontSave`. The GC handles keep the C# wrappers alive, so
212    /// their sizes survive; only the underlying Unity objects are remade.
213    fn ensure_alive(&mut self) -> Result<()> {
214        if self.material().is_alive()? {
215            return Ok(());
216        }
217        tracing::debug!("egui: resources were destroyed, recreating");
218        self.material = GcHandle::new(crate::il2cpp()?, make_material()?.object());
219        if let Some((_, size)) = self.texture.take() {
220            self.ensure_texture(size)?;
221            if !self.atlas.is_empty() {
222                Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)?;
223            }
224        }
225        Ok(())
226    }
227
228    fn frame(&mut self, ui: &(impl Fn(&egui::Context) + ?Sized)) -> Result<()> {
229        self.ensure_alive()?;
230        let (sw, sh) = screen::size()?;
231        let (iw, ih) = (sw.max(1), sh.max(1));
232        let scale = ui_scale();
233        let inv = 1.0 / scale;
234        // Point space is larger than screen when scale < 1 → smaller UI.
235        let (pw, ph) = (iw as f32 * inv, ih as f32 * inv);
236        // Render texture matches point space so 1 point = 1 pixel → crisp text.
237        // The Canvas bilinearly downscales the larger texture to screen size.
238        let tex_w = (iw as f32 * inv) as i32;
239        let tex_h = (ih as f32 * inv) as i32;
240
241        let input = self.raw_input(pw, ph, inv)?;
242        let output = self.ctx.run_pass(input, |ctx| ui(ctx));
243        for (id, deltas) in &output.textures_delta.set {
244            if matches!(id, egui::TextureId::Managed(_)) {
245                for delta in deltas {
246                    self.update_texture(delta)?;
247                }
248            }
249        }
250        let primitives = self.ctx.tessellate(output.shapes, 1.0);
251        self.render(pw, ph, (tex_w, tex_h), &primitives)
252    }
253
254    fn raw_input(&mut self, pw: f32, ph: f32, inv: f32) -> Result<egui::RawInput> {
255        use crate::KeyCode as K;
256        let held = |k| input::key(k).unwrap_or(false);
257        let ctrl = held(K::LEFT_CONTROL) || held(K::RIGHT_CONTROL);
258        let modifiers = egui::Modifiers {
259            alt: held(K::LEFT_ALT) || held(K::RIGHT_ALT),
260            ctrl,
261            shift: held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT),
262            mac_cmd: false,
263            command: ctrl,
264        };
265
266        let mouse = input::mouse_position()?;
267        // Unity mouse is in pixel coords (bottom-left origin). Scale to point
268        // space (top-left origin): x_pt = x_px * inv, y_pt = ph - y_px * inv.
269        let pos = egui::pos2(mouse.x * inv, ph - mouse.y * inv);
270        let mut events = vec![egui::Event::PointerMoved(pos)];
271        for (i, (button, egui_button)) in [
272            (0, egui::PointerButton::Primary),
273            (1, egui::PointerButton::Secondary),
274        ]
275        .into_iter()
276        .enumerate()
277        {
278            // Send an event only when the button changes state, so egui gets one
279            // press and one release per click rather than a press every frame
280            // (which left drags stuck to the cursor).
281            let down = input::mouse_button(button)?;
282            if down != self.pointer_down[i] {
283                self.pointer_down[i] = down;
284                events.push(egui::Event::PointerButton {
285                    pos,
286                    button: egui_button,
287                    pressed: down,
288                    modifiers,
289                });
290            }
291        }
292
293        let scroll = input::scroll_delta()?;
294        if scroll.x != 0.0 || scroll.y != 0.0 {
295            events.push(egui::Event::MouseWheel {
296                unit: egui::MouseWheelUnit::Line,
297                delta: egui::vec2(scroll.x, scroll.y),
298                phase: egui::TouchPhase::Move,
299                source: egui::MouseWheelSource::Unknown,
300                modifiers,
301            });
302        }
303
304        // Non-text keys, edge-detected from the held state (see KEYS).
305        for (i, &(key_code, key)) in KEYS.iter().enumerate() {
306            let down = held(key_code);
307            if down != self.keys_down[i] {
308                self.keys_down[i] = down;
309                events.push(egui::Event::Key {
310                    key,
311                    physical_key: None,
312                    pressed: down,
313                    repeat: false,
314                    modifiers,
315                });
316            }
317        }
318
319        // Typed characters. Prefer Unity's `Input.inputString` (handles
320        // layout, shift, IME), falling back to manual key-to-char conversion
321        // when it's unavailable or consistently empty.
322        if let Ok(typed) = input::input_string() {
323            if !typed.is_empty() {
324                self.input_string_works = true;
325            }
326            for c in typed.chars().filter(|c| !c.is_control()) {
327                events.push(egui::Event::Text(c.to_string()));
328            }
329        }
330
331        // Fallback: generate text events from individual key edges when
332        // inputString isn't delivering characters. Doesn't handle non-US
333        // layouts, but covers the common case.
334        if !self.input_string_works {
335            let shift = held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT);
336            for (i, &(key_code, lower, upper)) in TEXT_KEYS.iter().enumerate() {
337                let down = held(key_code);
338                if down && !self.text_keys_down[i] {
339                    let ch = if shift { upper } else { lower };
340                    events.push(egui::Event::Text(ch.to_string()));
341                }
342                self.text_keys_down[i] = down;
343            }
344        }
345
346        Ok(egui::RawInput {
347            screen_rect: Some(egui::Rect::from_min_size(
348                egui::pos2(0.0, 0.0),
349                egui::vec2(pw, ph),
350            )),
351            events,
352            ..Default::default()
353        })
354    }
355
356    /// Patches the CPU atlas with a texture delta and re-uploads it.
357    fn update_texture(&mut self, delta: &egui::epaint::ImageDelta) -> Result<()> {
358        let [dw, dh] = delta.image.size();
359        let pixels: Vec<u8> = match &delta.image {
360            egui::epaint::ImageData::Color(image) => {
361                image.pixels.iter().flat_map(|p| p.to_array()).collect()
362            }
363        };
364
365        match delta.pos {
366            None => {
367                self.atlas = pixels;
368                self.ensure_texture([dw, dh])?;
369            }
370            Some([x, y]) => {
371                let full = self.texture.as_ref().map(|(_, s)| *s).unwrap_or([dw, dh]);
372                for row in 0..dh {
373                    let dst = ((y + row) * full[0] + x) * 4;
374                    let src = row * dw * 4;
375                    if dst + dw * 4 <= self.atlas.len() {
376                        self.atlas[dst..dst + dw * 4].copy_from_slice(&pixels[src..src + dw * 4]);
377                    }
378                }
379            }
380        }
381        Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)
382    }
383
384    fn ensure_texture(&mut self, size: [usize; 2]) -> Result<()> {
385        if self.texture.as_ref().map(|(_, s)| *s) != Some(size) {
386            let texture = Texture2D::new(size[0] as i32, size[1] as i32, TextureFormat::RGBA32)?;
387            // Survive scene loads, as for the material.
388            texture.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
389            // Point sampling: egui's solid fills sample the atlas's white texel, and
390            // bilinear filtering blends it with transparent neighbours, which capped
391            // every fill's alpha below 1 and made the whole UI look see-through.
392            texture.set_filter_mode(crate::FilterMode::POINT)?;
393            let handle = GcHandle::new(crate::il2cpp()?, texture.object());
394            self.texture = Some((handle, size));
395        }
396        Ok(())
397    }
398
399    fn render(
400        &mut self,
401        w: f32,
402        h: f32,
403        size: (i32, i32),
404        primitives: &[egui::ClippedPrimitive],
405    ) -> Result<()> {
406        let Some((atlas_handle, _)) = &self.texture else {
407            return Ok(());
408        };
409        let atlas_obj = atlas_handle.target();
410        let material = self.material();
411        material.set_main_texture(Texture2D(atlas_obj))?;
412
413        let user_textures = USER_TEXTURES.lock().unwrap();
414
415        // Draw the tessellated UI into the overlay surface (cleared transparent so
416        // last frame's UI doesn't linger), which composites it on top of the game.
417        self.surface.draw(size, Color::CLEAR, || {
418            gl::push_matrix()?;
419            // Flip Y so egui's top-left origin maps to Unity's bottom-left.
420            gl::load_pixel_matrix(0.0, w, h, 0.0)?;
421            let mut active_texture = atlas_obj;
422            for primitive in primitives {
423                let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive else {
424                    continue;
425                };
426                let wanted = match mesh.texture_id {
427                    egui::TextureId::Managed(_) => atlas_obj,
428                    egui::TextureId::User(id) => {
429                        match user_textures.get(&id) {
430                            Some(handle) => handle.target(),
431                            None => atlas_obj,
432                        }
433                    }
434                };
435                if wanted != active_texture {
436                    material.set_main_texture(Texture2D(wanted))?;
437                    active_texture = wanted;
438                }
439                material.set_pass(0)?;
440                gl::begin(gl::Mode::Triangles)?;
441                for &index in &mesh.indices {
442                    let v = mesh.vertices[index as usize];
443                    // egui's Color32 is gamma (sRGB); Unity's linear colour space
444                    // wants linear values from GL.Color, so convert (otherwise the
445                    // dark UI is brightened into grey). Both are premultiplied.
446                    let c = egui::Rgba::from(v.color);
447                    gl::color(Color::rgba(c.r(), c.g(), c.b(), c.a()))?;
448                    gl::tex_coord(v.uv.x, v.uv.y)?;
449                    gl::vertex(v.pos.x, v.pos.y)?;
450                }
451                gl::end()?;
452            }
453            gl::pop_matrix()
454        })
455    }
456}