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;
43mod values;
44
45pub use hao_il2cpp_runtime as runtime;
46#[cfg(unix)]
47pub use hao_il2cpp_runtime::on_init;
48use hao_il2cpp_runtime::{Error, Il2Cpp, Result};
49pub use lifecycle::{on_render, on_update};
50pub use objects::{
51    find_object_of_type, find_objects_of_type, Camera, Canvas, Component, ComponentType,
52    GameObject, Material, RawImage, RectTransform, RenderTexture, Shader, TextMeshPro, Texture2D,
53    Transform, UnityObject,
54};
55pub use overlay::{OverlayCanvas, OverlaySurface, TextOverlay};
56pub use scene::{on_scene_loaded, Scene};
57pub use values::{
58    Color, FilterMode, HideFlags, KeyCode, LoadSceneMode, Quaternion, RenderMode, TextureFormat,
59    Vector2, Vector3,
60};
61
62impl Quaternion {
63    /// A rotation from Euler angles in degrees (`Quaternion.Euler`).
64    pub fn euler(x: f32, y: f32, z: f32) -> Result<Self> {
65        bindings::QUATERNION_EULER.call((x, y, z))
66    }
67}
68
69use bindings::*;
70
71fn il2cpp() -> Result<&'static Il2Cpp> {
72    Il2Cpp::get().ok_or_else(|| Error::NotFound("the Il2Cpp runtime".into()))
73}
74
75/// `Debug.Log`: writes to the game's log (`Player.log`).
76pub fn log(message: &str) -> Result<()> {
77    DEBUG_LOG.call((il2cpp()?.string(message)?.0,))
78}
79
80/// `Debug.LogWarning`.
81pub fn log_warning(message: &str) -> Result<()> {
82    DEBUG_LOG_WARNING.call((il2cpp()?.string(message)?.0,))
83}
84
85/// `Debug.LogError`.
86pub fn log_error(message: &str) -> Result<()> {
87    DEBUG_LOG_ERROR.call((il2cpp()?.string(message)?.0,))
88}
89
90/// `Time`.
91pub mod time {
92    use super::*;
93
94    /// Seconds since the last frame.
95    pub fn delta() -> Result<f32> {
96        TIME_DELTA.call(())
97    }
98
99    /// The total number of frames rendered since startup.
100    pub fn frame_count() -> Result<i32> {
101        TIME_FRAME_COUNT.call(())
102    }
103
104    /// How fast game time passes; 0 pauses most games.
105    pub fn scale() -> Result<f32> {
106        TIME_GET_SCALE.call(())
107    }
108
109    pub fn set_scale(scale: f32) -> Result<()> {
110        TIME_SET_SCALE.call((scale,))
111    }
112
113    /// Seconds since the game started (scaled by [`scale`]).
114    pub fn time() -> Result<f32> {
115        TIME_GET_TIME.call(())
116    }
117
118    /// Real seconds since startup, unaffected by [`scale`].
119    pub fn realtime_since_startup() -> Result<f32> {
120        TIME_REALTIME.call(())
121    }
122}
123
124/// `UnityEngine.Screen`.
125pub mod screen {
126    use super::*;
127
128    pub fn width() -> Result<i32> {
129        SCREEN_WIDTH.call(())
130    }
131
132    pub fn height() -> Result<i32> {
133        SCREEN_HEIGHT.call(())
134    }
135
136    /// `(width, height)` in pixels.
137    pub fn size() -> Result<(i32, i32)> {
138        Ok((width()?, height()?))
139    }
140}
141
142/// `UnityEngine.Input` (the legacy input manager).
143pub mod input {
144    use super::*;
145
146    /// Whether `key` is held this frame.
147    pub fn key(key: KeyCode) -> Result<bool> {
148        INPUT_GET_KEY.call((key,))
149    }
150
151    /// Whether `key` was pressed this frame.
152    pub fn key_down(key: KeyCode) -> Result<bool> {
153        INPUT_GET_KEY_DOWN.call((key,))
154    }
155
156    /// Whether `key` was released this frame.
157    pub fn key_up(key: KeyCode) -> Result<bool> {
158        INPUT_GET_KEY_UP.call((key,))
159    }
160
161    /// Whether mouse `button` (0 left, 1 right, 2 middle) is held.
162    pub fn mouse_button(button: i32) -> Result<bool> {
163        INPUT_GET_MOUSE_BUTTON.call((button,))
164    }
165
166    /// The cursor position in pixels, origin at the bottom left.
167    pub fn mouse_position() -> Result<Vector3> {
168        INPUT_MOUSE_POSITION.call(())
169    }
170
171    /// The scroll wheel movement this frame (`x` horizontal, `y` vertical).
172    pub fn scroll_delta() -> Result<Vector2> {
173        INPUT_SCROLL_DELTA.call(())
174    }
175
176    /// The characters typed this frame (including `\b` for backspace and `\r`
177    /// for return), for driving a text field.
178    pub fn input_string() -> Result<String> {
179        Ok(INPUT_STRING.call(())?.to_rust().unwrap_or_default())
180    }
181}
182
183/// `UnityEngine.Application`.
184pub mod application {
185    use super::*;
186
187    pub fn is_playing() -> Result<bool> {
188        APPLICATION_IS_PLAYING.call(())
189    }
190
191    /// Quits the game with an exit code.
192    pub fn quit(exit_code: i32) -> Result<()> {
193        APPLICATION_QUIT.call((exit_code,))
194    }
195}
196
197/// Resolves every wrapped Unity method against the running game, returning
198/// the ones that are missing or have a different signature.
199pub fn check_bindings() -> Vec<(String, Error)> {
200    bindings::all()
201        .into_iter()
202        .filter_map(|b| b.check().err().map(|e| (b.describe(), e)))
203        .collect()
204}