hao-il2cpp-unity 0.0.8

Typed Unity wrappers for mods of Unity Il2Cpp games
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Draw an [`egui`] UI over the game from the render hook. Enable with the
//! `egui` feature.
//!
//! egui is rendered with Unity's immediate-mode [`gl`](crate::gl): its font atlas
//! is uploaded to a [`Texture2D`] (point-sampled, so solid fills stay opaque),
//! bound through a `Material`, and each tessellated triangle is emitted (with its
//! colours converted from gamma to linear) into an [`OverlaySurface`], which draws
//! it on top of the game's own UI. See [`on_egui`].

use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use hao_il2cpp_runtime::{GcHandle, Object, Result};

use crate::{gl, input, screen, Color, Material, OverlaySurface, Shader, Texture2D, TextureFormat};

static UI_SCALE: AtomicU32 = AtomicU32::new(0);
static NEXT_USER_TEX: AtomicU64 = AtomicU64::new(1);
static USER_TEXTURES: std::sync::LazyLock<Mutex<HashMap<u64, GcHandle>>> =
    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));

/// Scales the egui overlay UI. A value of 0.5 makes the UI half-size; 2.0 makes
/// it double-size. Font rasterization quality is preserved — only the coordinate
/// space is scaled. Pass 0.0 to reset to the default (1.0).
pub fn set_ui_scale(scale: f32) {
    if scale <= 0.0 {
        UI_SCALE.store(0, Ordering::Relaxed);
    } else {
        UI_SCALE.store(scale.to_bits(), Ordering::Relaxed);
    }
}

fn ui_scale() -> f32 {
    let bits = UI_SCALE.load(Ordering::Relaxed);
    if bits == 0 {
        1.0
    } else {
        f32::from_bits(bits)
    }
}

/// Registers a Unity texture object for use in egui as a user texture.
///
/// Returns a [`egui::TextureId::User`] id that can be passed to egui's
/// `Image` widget via `SizedTexture`. The texture object is GC-pinned so it
/// won't be collected while registered.
pub fn register_user_texture(object: Object) -> Result<egui::TextureId> {
    let id = NEXT_USER_TEX.fetch_add(1, Ordering::Relaxed);
    let handle = GcHandle::new(crate::il2cpp()?, object);
    USER_TEXTURES.lock().unwrap().insert(id, handle);
    Ok(egui::TextureId::User(id))
}

/// Removes a previously registered user texture.
pub fn unregister_user_texture(id: egui::TextureId) {
    if let egui::TextureId::User(n) = id {
        USER_TEXTURES.lock().unwrap().remove(&n);
    }
}

/// Runs `ui` every frame to build and draw an egui interface over the game.
///
/// Call it once (e.g. from `on_init`). The egui context, font texture and
/// material are created on the render thread on the first frame. Mouse input is
/// fed from `UnityEngine.Input`.
pub fn on_egui(ui: impl Fn(&egui::Context) + Send + Sync + 'static) -> Result<()> {
    let ui = Arc::new(ui);
    let state: Mutex<Option<EguiState>> = Mutex::new(None);
    // The render hook fires once per camera, so several times per frame. Run egui
    // (input + layout) only on the first callback of each frame: otherwise a click
    // edge is read in whichever camera's pass happened to catch it, so presses get
    // dropped. The render target persists, so one draw per frame is enough.
    let last_frame = std::sync::atomic::AtomicI32::new(-1);
    crate::on_render(move |_camera| {
        match crate::time::frame_count() {
            Ok(frame) if last_frame.swap(frame, std::sync::atomic::Ordering::Relaxed) == frame => {
                return
            }
            _ => {}
        }
        let mut guard = state.lock().unwrap_or_else(|e| e.into_inner());
        let state = match guard.as_mut() {
            Some(state) => state,
            None => match EguiState::new() {
                Ok(state) => guard.insert(state),
                Err(e) => {
                    tracing::error!("egui init failed: {}", e);
                    return;
                }
            },
        };
        if let Err(e) = state.frame(&*ui) {
            tracing::error!("egui frame failed: {}", e);
        }
    })
}

struct EguiState {
    ctx: egui::Context,
    /// Kept alive across frames: the GC doesn't scan Rust memory.
    material: GcHandle,
    texture: Option<(GcHandle, [usize; 2])>,
    /// A CPU copy of the font atlas (RGBA), patched from egui's texture deltas.
    atlas: Vec<u8>,
    /// Previous state of the left/right mouse buttons, so a press or release is
    /// sent to egui only on the edge (egui is event-based, not level-based).
    pointer_down: [bool; 2],
    /// Previous held state of each key in [`KEYS`], for the same edge detection
    /// (read from the held state, as GetKeyDown is unreliable off the main thread).
    keys_down: [bool; KEYS.len()],
    /// Previous held state of typeable keys for the fallback text input path.
    text_keys_down: [bool; TEXT_KEYS.len()],
    /// Whether `Input.inputString` has ever returned a non-empty string. Once
    /// it does, the fallback key-to-char path is disabled.
    input_string_works: bool,
    /// The top-most render target egui draws into and is composited from.
    surface: OverlaySurface,
}

/// Non-text keys forwarded to egui for editing and navigation. Typed characters
/// go through `Input.inputString` instead (see [`EguiState::raw_input`]).
const KEYS: &[(crate::KeyCode, egui::Key)] = {
    use crate::KeyCode as K;
    use egui::Key;
    &[
        (K::BACKSPACE, Key::Backspace),
        (K::DELETE, Key::Delete),
        (K::RETURN, Key::Enter),
        (K::TAB, Key::Tab),
        (K::ESCAPE, Key::Escape),
        (K::LEFT, Key::ArrowLeft),
        (K::RIGHT, Key::ArrowRight),
        (K::UP, Key::ArrowUp),
        (K::DOWN, Key::ArrowDown),
        (K::HOME, Key::Home),
        (K::END, Key::End),
        (K::PAGE_UP, Key::PageUp),
        (K::PAGE_DOWN, Key::PageDown),
        (K::SPACE, Key::Space),
        // With a held ctrl/cmd these drive select-all/copy/paste/cut/undo.
        (K::A, Key::A),
        (K::C, Key::C),
        (K::V, Key::V),
        (K::X, Key::X),
        (K::Z, Key::Z),
    ]
};

/// Typeable keys for the fallback text input path. Each entry is a key code, the
/// lowercase char, and the shifted char. Used only when `Input.inputString` is
/// unavailable — it doesn't handle non-US layouts, but covers the common case.
const TEXT_KEYS: &[(crate::KeyCode, char, char)] = {
    use crate::KeyCode as K;
    &[
        (K::A, 'a', 'A'),
        (K::B, 'b', 'B'),
        (K::C, 'c', 'C'),
        (K::D, 'd', 'D'),
        (K::E, 'e', 'E'),
        (K::F, 'f', 'F'),
        (K::G, 'g', 'G'),
        (K::H, 'h', 'H'),
        (K::I, 'i', 'I'),
        (K::J, 'j', 'J'),
        (K::K, 'k', 'K'),
        (K::L, 'l', 'L'),
        (K::M, 'm', 'M'),
        (K::N, 'n', 'N'),
        (K::O, 'o', 'O'),
        (K::P, 'p', 'P'),
        (K::Q, 'q', 'Q'),
        (K::R, 'r', 'R'),
        (K::S, 's', 'S'),
        (K::T, 't', 'T'),
        (K::U, 'u', 'U'),
        (K::V, 'v', 'V'),
        (K::W, 'w', 'W'),
        (K::X, 'x', 'X'),
        (K::Y, 'y', 'Y'),
        (K::Z, 'z', 'Z'),
        (K::ALPHA0, '0', ')'),
        (K::ALPHA1, '1', '!'),
        (K::ALPHA2, '2', '@'),
        (K::ALPHA3, '3', '#'),
        (K(52), '4', '$'),
        (K(53), '5', '%'),
        (K(54), '6', '^'),
        (K(55), '7', '&'),
        (K(56), '8', '*'),
        (K(57), '9', '('),
        (K::SPACE, ' ', ' '),
    ]
};

/// Builds the egui material: a textured, vertex-coloured, alpha-blended shader.
/// `HideAndDontSave` keeps Unity from destroying it (and throwing NRE on later
/// use) when a scene loads, which `DontDestroyOnLoad` does not do for assets.
fn make_material() -> Result<Material> {
    let (name, shader) = match Shader::find("Sprites/Default")? {
        Some(shader) => ("Sprites/Default", shader),
        None => (
            "UI/Default",
            Shader::find("UI/Default")?.ok_or_else(|| {
                hao_il2cpp_runtime::Error::NotFound("a sprite/UI shader for egui".into())
            })?,
        ),
    };
    tracing::debug!(shader = name, "egui material shader");
    let material = Material::new(shader)?;
    material.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
    Ok(material)
}

impl EguiState {
    fn new() -> Result<Self> {
        let ctx = egui::Context::default();
        if let Ok((w, h)) = screen::size() {
            tracing::info!(w, h, scale = ui_scale(), "egui overlay: screen size");
        }
        let material = make_material()?;
        Ok(Self {
            ctx,
            material: GcHandle::new(crate::il2cpp()?, material.object()),
            texture: None,
            atlas: Vec::new(),
            pointer_down: [false; 2],
            keys_down: [false; KEYS.len()],
            text_keys_down: [false; TEXT_KEYS.len()],
            input_string_works: false,
            surface: OverlaySurface::new("hao-egui-overlay"),
        })
    }

    fn material(&self) -> Material {
        Material(self.material.target())
    }

    /// Rebuilds the material and font texture if a scene load destroyed them
    /// despite `HideAndDontSave`. The GC handles keep the C# wrappers alive, so
    /// their sizes survive; only the underlying Unity objects are remade.
    fn ensure_alive(&mut self) -> Result<()> {
        if self.material().is_alive()? {
            return Ok(());
        }
        tracing::debug!("egui: resources were destroyed, recreating");
        self.material = GcHandle::new(crate::il2cpp()?, make_material()?.object());
        if let Some((_, size)) = self.texture.take() {
            self.ensure_texture(size)?;
            if !self.atlas.is_empty() {
                Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)?;
            }
        }
        Ok(())
    }

    fn frame(&mut self, ui: &(impl Fn(&egui::Context) + ?Sized)) -> Result<()> {
        self.ensure_alive()?;
        let (sw, sh) = screen::size()?;
        let (iw, ih) = (sw.max(1), sh.max(1));
        let scale = ui_scale();
        let inv = 1.0 / scale;
        // Point space is larger than screen when scale < 1 → smaller UI.
        let (pw, ph) = (iw as f32 * inv, ih as f32 * inv);
        // Render texture matches point space so 1 point = 1 pixel → crisp text.
        // The Canvas bilinearly downscales the larger texture to screen size.
        let tex_w = (iw as f32 * inv) as i32;
        let tex_h = (ih as f32 * inv) as i32;

        let input = self.raw_input(pw, ph, inv)?;
        let mut output = self.ctx.run_pass(input, |ctx| ui(ctx));
        for (id, deltas) in &output.textures_delta.set {
            if matches!(id, egui::TextureId::Managed(_)) {
                for delta in deltas {
                    self.update_texture(delta)?;
                }
            }
        }
        // The `.set` deltas are uploaded above; mark the whole delta consumed so
        // epaint's `TexturesDelta::drop` debug_assert passes (a debug build would
        // otherwise panic here). `.free` ids aren't reclaimed in Unity yet.
        output.textures_delta.clear();
        let primitives = self.ctx.tessellate(output.shapes, 1.0);
        self.render(pw, ph, (tex_w, tex_h), &primitives)
    }

    fn raw_input(&mut self, pw: f32, ph: f32, inv: f32) -> Result<egui::RawInput> {
        use crate::KeyCode as K;
        let held = |k| input::key(k).unwrap_or(false);
        let ctrl = held(K::LEFT_CONTROL) || held(K::RIGHT_CONTROL);
        let modifiers = egui::Modifiers {
            alt: held(K::LEFT_ALT) || held(K::RIGHT_ALT),
            ctrl,
            shift: held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT),
            mac_cmd: false,
            command: ctrl,
        };

        let mouse = input::mouse_position()?;
        // Unity mouse is in pixel coords (bottom-left origin). Scale to point
        // space (top-left origin): x_pt = x_px * inv, y_pt = ph - y_px * inv.
        let pos = egui::pos2(mouse.x * inv, ph - mouse.y * inv);
        let mut events = vec![egui::Event::PointerMoved(pos)];
        for (i, (button, egui_button)) in [
            (0, egui::PointerButton::Primary),
            (1, egui::PointerButton::Secondary),
        ]
        .into_iter()
        .enumerate()
        {
            // Send an event only when the button changes state, so egui gets one
            // press and one release per click rather than a press every frame
            // (which left drags stuck to the cursor).
            let down = input::mouse_button(button)?;
            if down != self.pointer_down[i] {
                self.pointer_down[i] = down;
                events.push(egui::Event::PointerButton {
                    pos,
                    button: egui_button,
                    pressed: down,
                    modifiers,
                });
            }
        }

        let scroll = input::scroll_delta()?;
        if scroll.x != 0.0 || scroll.y != 0.0 {
            events.push(egui::Event::MouseWheel {
                unit: egui::MouseWheelUnit::Line,
                delta: egui::vec2(scroll.x, scroll.y),
                phase: egui::TouchPhase::Move,
                source: egui::MouseWheelSource::Unknown,
                modifiers,
            });
        }

        // Non-text keys, edge-detected from the held state (see KEYS).
        for (i, &(key_code, key)) in KEYS.iter().enumerate() {
            let down = held(key_code);
            if down != self.keys_down[i] {
                self.keys_down[i] = down;
                events.push(egui::Event::Key {
                    key,
                    physical_key: None,
                    pressed: down,
                    repeat: false,
                    modifiers,
                });
            }
        }

        // Typed characters. Prefer Unity's `Input.inputString` (handles
        // layout, shift, IME), falling back to manual key-to-char conversion
        // when it's unavailable or consistently empty.
        if let Ok(typed) = input::input_string() {
            if !typed.is_empty() {
                self.input_string_works = true;
            }
            for c in typed.chars().filter(|c| !c.is_control()) {
                events.push(egui::Event::Text(c.to_string()));
            }
        }

        // Fallback: generate text events from individual key edges when
        // inputString isn't delivering characters. Doesn't handle non-US
        // layouts, but covers the common case.
        if !self.input_string_works {
            let shift = held(K::LEFT_SHIFT) || held(K::RIGHT_SHIFT);
            for (i, &(key_code, lower, upper)) in TEXT_KEYS.iter().enumerate() {
                let down = held(key_code);
                if down && !self.text_keys_down[i] {
                    let ch = if shift { upper } else { lower };
                    events.push(egui::Event::Text(ch.to_string()));
                }
                self.text_keys_down[i] = down;
            }
        }

        Ok(egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(pw, ph),
            )),
            events,
            ..Default::default()
        })
    }

    /// Patches the CPU atlas with a texture delta and re-uploads it.
    fn update_texture(&mut self, delta: &egui::epaint::ImageDelta) -> Result<()> {
        let [dw, dh] = delta.image.size();
        let pixels: Vec<u8> = match &delta.image {
            egui::epaint::ImageData::Color(image) => {
                image.pixels.iter().flat_map(|p| p.to_array()).collect()
            }
        };

        match delta.pos {
            None => {
                self.atlas = pixels;
                self.ensure_texture([dw, dh])?;
            }
            Some([x, y]) => {
                let full = self.texture.as_ref().map(|(_, s)| *s).unwrap_or([dw, dh]);
                for row in 0..dh {
                    let dst = ((y + row) * full[0] + x) * 4;
                    let src = row * dw * 4;
                    if dst + dw * 4 <= self.atlas.len() {
                        self.atlas[dst..dst + dw * 4].copy_from_slice(&pixels[src..src + dw * 4]);
                    }
                }
            }
        }
        Texture2D(self.texture.as_ref().unwrap().0.target()).load_raw(&self.atlas)
    }

    fn ensure_texture(&mut self, size: [usize; 2]) -> Result<()> {
        if self.texture.as_ref().map(|(_, s)| *s) != Some(size) {
            let texture = Texture2D::new(size[0] as i32, size[1] as i32, TextureFormat::RGBA32)?;
            // Survive scene loads, as for the material.
            texture.set_hide_flags(crate::HideFlags::HIDE_AND_DONT_SAVE)?;
            // Point sampling: egui's solid fills sample the atlas's white texel, and
            // bilinear filtering blends it with transparent neighbours, which capped
            // every fill's alpha below 1 and made the whole UI look see-through.
            texture.set_filter_mode(crate::FilterMode::POINT)?;
            let handle = GcHandle::new(crate::il2cpp()?, texture.object());
            self.texture = Some((handle, size));
        }
        Ok(())
    }

    fn render(
        &mut self,
        w: f32,
        h: f32,
        size: (i32, i32),
        primitives: &[egui::ClippedPrimitive],
    ) -> Result<()> {
        let Some((atlas_handle, _)) = &self.texture else {
            return Ok(());
        };
        let atlas_obj = atlas_handle.target();
        let material = self.material();
        material.set_main_texture(Texture2D(atlas_obj))?;

        let user_textures = USER_TEXTURES.lock().unwrap();

        // Draw the tessellated UI into the overlay surface (cleared transparent so
        // last frame's UI doesn't linger), which composites it on top of the game.
        self.surface.draw(size, Color::CLEAR, || {
            gl::push_matrix()?;
            // Flip Y so egui's top-left origin maps to Unity's bottom-left.
            gl::load_pixel_matrix(0.0, w, h, 0.0)?;
            let mut active_texture = atlas_obj;
            for primitive in primitives {
                let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive else {
                    continue;
                };
                let wanted = match mesh.texture_id {
                    egui::TextureId::Managed(_) => atlas_obj,
                    egui::TextureId::User(id) => match user_textures.get(&id) {
                        Some(handle) => handle.target(),
                        None => atlas_obj,
                    },
                };
                if wanted != active_texture {
                    material.set_main_texture(Texture2D(wanted))?;
                    active_texture = wanted;
                }
                material.set_pass(0)?;
                gl::begin(gl::Mode::Triangles)?;
                for &index in &mesh.indices {
                    let v = mesh.vertices[index as usize];
                    // egui's Color32 is gamma (sRGB); Unity's linear colour space
                    // wants linear values from GL.Color, so convert (otherwise the
                    // dark UI is brightened into grey). Both are premultiplied.
                    let c = egui::Rgba::from(v.color);
                    gl::color(Color::rgba(c.r(), c.g(), c.b(), c.a()))?;
                    gl::tex_coord(v.uv.x, v.uv.y)?;
                    gl::vertex(v.pos.x, v.pos.y)?;
                }
                gl::end()?;
            }
            gl::pop_matrix()
        })
    }
}