Skip to main content

hao_il2cpp_unity/
lifecycle.rs

1//! Running mod code every frame.
2
3use std::sync::{
4    atomic::{AtomicBool, AtomicI32, Ordering},
5    Arc, Mutex,
6};
7
8use hao_il2cpp_runtime::{Original, Result};
9
10use crate::{bindings::CAMERA_FIRE_ON_POST_RENDER, Camera};
11
12type Callback = Arc<dyn Fn() + Send + Sync>;
13type RenderCallback = Arc<dyn Fn(Camera) + Send + Sync>;
14
15static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
16static HOOKED: Mutex<bool> = Mutex::new(false);
17static LAST_FRAME: AtomicI32 = AtomicI32::new(-1);
18
19static RENDER_CALLBACKS: Mutex<Vec<RenderCallback>> = Mutex::new(Vec::new());
20static RENDER_HOOKED: Mutex<bool> = Mutex::new(false);
21
22static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);
23
24/// Returns `true` after [`shutdown`] has been called.
25pub fn is_shutting_down() -> bool {
26    SHUTTING_DOWN.load(Ordering::Relaxed)
27}
28
29/// Signals all lifecycle hooks to stop firing. Call from an
30/// `Application.quitting` handler or a `dtor` to prevent crashes
31/// during engine teardown.
32pub fn shutdown() {
33    SHUTTING_DOWN.store(true, Ordering::Relaxed);
34}
35
36/// Runs `callback` once per frame on Unity's main thread, a good place to update
37/// an overlay. Panics are caught and printed.
38///
39/// It works by hooking `UnityEngine.Time.frameCount`, which the engine reads
40/// every frame, and firing when the frame number changes. A frame where nothing
41/// reads `Time.frameCount` is skipped, which in an active game does not happen.
42pub fn on_update(callback: impl Fn() + Send + Sync + 'static) -> Result<()> {
43    CALLBACKS
44        .lock()
45        .unwrap_or_else(|e| e.into_inner())
46        .push(Arc::new(callback));
47    let mut hooked = HOOKED.lock().unwrap_or_else(|e| e.into_inner());
48    if !*hooked {
49        let frame_count = crate::il2cpp()?
50            .class("UnityEngine.CoreModule", "UnityEngine", "Time")?
51            .method("get_frameCount", 0)?;
52        frame_count.hook(|original: Original<_, i32>| {
53            let frame = original.call(());
54            if SHUTTING_DOWN.load(Ordering::Relaxed) {
55                return frame;
56            }
57            if LAST_FRAME.swap(frame, Ordering::Relaxed) != frame {
58                let callbacks = CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
59                for callback in callbacks {
60                    callback();
61                }
62            }
63            frame
64        })?;
65        *hooked = true;
66        tracing::debug!("watching for frame updates");
67    }
68    Ok(())
69}
70
71/// Runs `callback` on the render thread after each camera finishes rendering,
72/// passing the [`Camera`]. This is where to draw an overlay on top of the game
73/// with [`gl`](crate::gl), or to drive an immediate-mode UI such as egui.
74///
75/// It hooks `Camera.FireOnPostRender`, which Unity invokes from native code per
76/// camera render, so the callback runs in the render pipeline whether or not
77/// anything subscribed to `Camera.onPostRender`. Games with several cameras call
78/// it more than once per frame; compare the passed camera's `name()` if you only
79/// want one. Panics are caught and printed.
80pub fn on_render(callback: impl Fn(Camera) + Send + Sync + 'static) -> Result<()> {
81    RENDER_CALLBACKS
82        .lock()
83        .unwrap_or_else(|e| e.into_inner())
84        .push(Arc::new(callback));
85    let mut hooked = RENDER_HOOKED.lock().unwrap_or_else(|e| e.into_inner());
86    if !*hooked {
87        CAMERA_FIRE_ON_POST_RENDER.method()?.hook(
88            |camera: Camera, original: Original<_, ()>| {
89                original.call((camera,));
90                if SHUTTING_DOWN.load(Ordering::Relaxed) {
91                    return;
92                }
93                let callbacks = RENDER_CALLBACKS
94                    .lock()
95                    .unwrap_or_else(|e| e.into_inner())
96                    .clone();
97                for callback in callbacks {
98                    callback(camera);
99                }
100            },
101        )?;
102        *hooked = true;
103        tracing::debug!("watching for camera renders");
104    }
105    Ok(())
106}