Skip to main content

hao_il2cpp_unity/
lib.rs

1//! Typed Unity wrappers for mods of Unity Il2Cpp games, on top of
2//! [`hao_il2cpp_runtime`].
3//!
4//! The runtime crate finds and hooks methods by name. This crate wraps common
5//! Unity functionality the same way for any Unity game: game objects and
6//! components, UI, scenes, logging and time. Each Unity method is looked up the
7//! first time it's used and checked against the game's real signature, so a
8//! game whose Unity version differs gives an error rather than a crash.
9//!
10//! ```no_run
11//! use std::sync::OnceLock;
12//!
13//! use hao_il2cpp_unity::{on_scene_loaded, TextOverlay};
14//!
15//! static OVERLAY: OnceLock<TextOverlay> = OnceLock::new();
16//!
17//! hao_il2cpp_unity::on_init(|_| {
18//!     on_scene_loaded(|scene, _| {
19//!         let overlay = OVERLAY.get_or_init(|| TextOverlay::new("my mod").unwrap());
20//!         overlay.set_text(&format!("scene: {}", scene.name().unwrap())).unwrap();
21//!     })
22//! });
23//! ```
24//!
25//! Unity's API may only be used from its main thread: inside hooks of methods
26//! the game calls on it, such as [`on_scene_loaded`]'s callbacks.
27
28mod binding;
29mod bindings;
30#[cfg(feature = "egui")]
31pub mod egui {
32    //! egui integration (requires the `egui` feature). See [`on_egui`].
33    pub use crate::egui_backend::on_egui;
34    pub use ::egui::*;
35}
36#[cfg(feature = "egui")]
37mod egui_backend;
38pub mod gl;
39mod lifecycle;
40mod objects;
41mod overlay;
42mod scene;
43#[cfg(feature = "reflect")]
44pub mod reflect;
45mod values;
46
47pub use hao_il2cpp_runtime as runtime;
48#[cfg(unix)]
49pub use hao_il2cpp_runtime::on_init;
50use hao_il2cpp_runtime::{Error, Il2Cpp, Result};
51pub use lifecycle::{on_render, on_update};
52pub use objects::{
53    find_object_of_type, find_objects_of_type, Camera, Canvas, Component, ComponentType,
54    GameObject, Material, RawImage, RectTransform, RenderTexture, Shader, TextMeshPro, Texture2D,
55    Transform, UnityObject,
56};
57pub use overlay::{OverlayCanvas, OverlaySurface, TextOverlay};
58pub use scene::{on_scene_loaded, Scene};
59pub use values::{
60    Color, FilterMode, HideFlags, KeyCode, LoadSceneMode, Quaternion, RenderMode, TextureFormat,
61    Vector2, Vector3,
62};
63
64impl Quaternion {
65    /// A rotation from Euler angles in degrees (`Quaternion.Euler`).
66    pub fn euler(x: f32, y: f32, z: f32) -> Result<Self> {
67        bindings::QUATERNION_EULER.call((x, y, z))
68    }
69}
70
71use bindings::*;
72
73fn il2cpp() -> Result<&'static Il2Cpp> {
74    Il2Cpp::get().ok_or_else(|| Error::NotFound("the Il2Cpp runtime".into()))
75}
76
77/// `Debug.Log`: writes to the game's log (`Player.log`).
78pub fn log(message: &str) -> Result<()> {
79    DEBUG_LOG.call((il2cpp()?.string(message)?.0,))
80}
81
82/// `Debug.LogWarning`.
83pub fn log_warning(message: &str) -> Result<()> {
84    DEBUG_LOG_WARNING.call((il2cpp()?.string(message)?.0,))
85}
86
87/// `Debug.LogError`.
88pub fn log_error(message: &str) -> Result<()> {
89    DEBUG_LOG_ERROR.call((il2cpp()?.string(message)?.0,))
90}
91
92/// `Time`.
93pub mod time {
94    use super::*;
95
96    /// Seconds since the last frame.
97    pub fn delta() -> Result<f32> {
98        TIME_DELTA.call(())
99    }
100
101    /// The total number of frames rendered since startup.
102    pub fn frame_count() -> Result<i32> {
103        TIME_FRAME_COUNT.call(())
104    }
105
106    /// How fast game time passes; 0 pauses most games.
107    pub fn scale() -> Result<f32> {
108        TIME_GET_SCALE.call(())
109    }
110
111    pub fn set_scale(scale: f32) -> Result<()> {
112        TIME_SET_SCALE.call((scale,))
113    }
114
115    /// Seconds since the game started (scaled by [`scale`]).
116    pub fn time() -> Result<f32> {
117        TIME_GET_TIME.call(())
118    }
119
120    /// Real seconds since startup, unaffected by [`scale`].
121    pub fn realtime_since_startup() -> Result<f32> {
122        TIME_REALTIME.call(())
123    }
124}
125
126/// `UnityEngine.Screen`.
127pub mod screen {
128    use super::*;
129
130    pub fn width() -> Result<i32> {
131        SCREEN_WIDTH.call(())
132    }
133
134    pub fn height() -> Result<i32> {
135        SCREEN_HEIGHT.call(())
136    }
137
138    /// `(width, height)` in pixels.
139    pub fn size() -> Result<(i32, i32)> {
140        Ok((width()?, height()?))
141    }
142}
143
144/// `UnityEngine.Input` (the legacy input manager).
145pub mod input {
146    use super::*;
147
148    /// Whether `key` is held this frame.
149    pub fn key(key: KeyCode) -> Result<bool> {
150        INPUT_GET_KEY.call((key,))
151    }
152
153    /// Whether `key` was pressed this frame.
154    pub fn key_down(key: KeyCode) -> Result<bool> {
155        INPUT_GET_KEY_DOWN.call((key,))
156    }
157
158    /// Whether `key` was released this frame.
159    pub fn key_up(key: KeyCode) -> Result<bool> {
160        INPUT_GET_KEY_UP.call((key,))
161    }
162
163    /// Whether mouse `button` (0 left, 1 right, 2 middle) is held.
164    pub fn mouse_button(button: i32) -> Result<bool> {
165        INPUT_GET_MOUSE_BUTTON.call((button,))
166    }
167
168    /// The cursor position in pixels, origin at the bottom left.
169    pub fn mouse_position() -> Result<Vector3> {
170        INPUT_MOUSE_POSITION.call(())
171    }
172
173    /// The scroll wheel movement this frame (`x` horizontal, `y` vertical).
174    pub fn scroll_delta() -> Result<Vector2> {
175        INPUT_SCROLL_DELTA.call(())
176    }
177
178    /// The characters typed this frame (including `\b` for backspace and `\r`
179    /// for return), for driving a text field.
180    pub fn input_string() -> Result<String> {
181        Ok(INPUT_STRING.call(())?.to_rust().unwrap_or_default())
182    }
183}
184
185/// `UnityEngine.Application`.
186pub mod application {
187    use super::*;
188
189    pub fn is_playing() -> Result<bool> {
190        APPLICATION_IS_PLAYING.call(())
191    }
192
193    /// Quits the game with an exit code.
194    pub fn quit(exit_code: i32) -> Result<()> {
195        APPLICATION_QUIT.call((exit_code,))
196    }
197}
198
199/// Resolves every wrapped Unity method against the running game, returning
200/// the ones that are missing or have a different signature.
201pub fn check_bindings() -> Vec<(String, Error)> {
202    bindings::all()
203        .into_iter()
204        .filter_map(|b| b.check().err().map(|e| (b.describe(), e)))
205        .collect()
206}