Skip to main content

hao_il2cpp_unity/
lifecycle.rs

1//! Running mod code every frame.
2
3use std::sync::{
4    atomic::{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
22/// Runs `callback` once per frame on Unity's main thread, a good place to update
23/// an overlay. Panics are caught and printed.
24///
25/// It works by hooking `UnityEngine.Time.frameCount`, which the engine reads
26/// every frame, and firing when the frame number changes. A frame where nothing
27/// reads `Time.frameCount` is skipped, which in an active game does not happen.
28pub fn on_update(callback: impl Fn() + Send + Sync + 'static) -> Result<()> {
29    CALLBACKS
30        .lock()
31        .unwrap_or_else(|e| e.into_inner())
32        .push(Arc::new(callback));
33    let mut hooked = HOOKED.lock().unwrap_or_else(|e| e.into_inner());
34    if !*hooked {
35        let frame_count = crate::il2cpp()?
36            .class("UnityEngine.CoreModule", "UnityEngine", "Time")?
37            .method("get_frameCount", 0)?;
38        frame_count.hook(|original: Original<_, i32>| {
39            let frame = original.call(());
40            // Fire once per frame. The callback calls the original code, not the
41            // hook, so this never recurses.
42            if LAST_FRAME.swap(frame, Ordering::Relaxed) != frame {
43                let callbacks = CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
44                // A managed exception thrown by a Unity call inside a callback must
45                // flow back to Unity (which logs it); catching it here would abort,
46                // as Rust can't catch foreign exceptions.
47                for callback in callbacks {
48                    callback();
49                }
50            }
51            frame
52        })?;
53        *hooked = true;
54        tracing::debug!("watching for frame updates");
55    }
56    Ok(())
57}
58
59/// Runs `callback` on the render thread after each camera finishes rendering,
60/// passing the [`Camera`]. This is where to draw an overlay on top of the game
61/// with [`gl`](crate::gl), or to drive an immediate-mode UI such as egui.
62///
63/// It hooks `Camera.FireOnPostRender`, which Unity invokes from native code per
64/// camera render, so the callback runs in the render pipeline whether or not
65/// anything subscribed to `Camera.onPostRender`. Games with several cameras call
66/// it more than once per frame; compare the passed camera's `name()` if you only
67/// want one. Panics are caught and printed.
68pub fn on_render(callback: impl Fn(Camera) + Send + Sync + 'static) -> Result<()> {
69    RENDER_CALLBACKS
70        .lock()
71        .unwrap_or_else(|e| e.into_inner())
72        .push(Arc::new(callback));
73    let mut hooked = RENDER_HOOKED.lock().unwrap_or_else(|e| e.into_inner());
74    if !*hooked {
75        CAMERA_FIRE_ON_POST_RENDER.method()?.hook(
76            |camera: Camera, original: Original<_, ()>| {
77                original.call((camera,));
78                let callbacks = RENDER_CALLBACKS
79                    .lock()
80                    .unwrap_or_else(|e| e.into_inner())
81                    .clone();
82                // See on_update: managed exceptions must flow back to Unity, not be caught.
83                for callback in callbacks {
84                    callback(camera);
85                }
86            },
87        )?;
88        *hooked = true;
89        tracing::debug!("watching for camera renders");
90    }
91    Ok(())
92}