Skip to main content

hao_il2cpp_unity/
objects.rs

1//! Typed handles to Unity objects.
2
3use hao_il2cpp_runtime::{Il2CppValue, Object, Result, TypeInfo};
4
5use crate::{
6    bindings::*,
7    il2cpp,
8    values::{Color, Quaternion, RenderMode, Vector2, Vector3},
9};
10
11macro_rules! object_type {
12    ($(#[$doc:meta])* $name:ident = $assembly:literal $namespace:literal $class:literal) => {
13        $(#[$doc])*
14        #[repr(transparent)]
15        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16        pub struct $name(pub Object);
17
18        unsafe impl Il2CppValue for $name {
19            fn is_reference() -> bool {
20                true
21            }
22
23            fn matches(ty: TypeInfo) -> bool {
24                <Object as Il2CppValue>::matches(ty) && ty.namespace == $namespace && ty.name == $class
25            }
26        }
27
28        impl $name {
29            pub const ASSEMBLY: &'static str = $assembly;
30            pub const NAMESPACE: &'static str = $namespace;
31            pub const NAME: &'static str = $class;
32
33            pub fn object(&self) -> Object {
34                self.0
35            }
36
37            pub fn is_null(&self) -> bool {
38                self.0.is_null()
39            }
40
41            pub fn name(&self) -> Result<String> {
42                let name = OBJECT_GET_NAME.call((UnityObject(self.0),))?;
43                Ok(name.to_rust().unwrap_or_default())
44            }
45
46            pub fn set_name(&self, name: &str) -> Result<()> {
47                OBJECT_SET_NAME.call((UnityObject(self.0), il2cpp()?.string(name)?))
48            }
49
50            /// Keeps the object when a new scene loads. Only works for GameObjects;
51            /// for assets (`Material`, `Texture2D`) use [`set_hide_flags`](Self::set_hide_flags).
52            pub fn dont_destroy_on_load(&self) -> Result<()> {
53                OBJECT_DONT_DESTROY_ON_LOAD.call((UnityObject(self.0),))
54            }
55
56            /// Sets the object's `HideFlags`. `HideFlags::HIDE_AND_DONT_SAVE` keeps a
57            /// runtime-created asset from being unloaded on scene load.
58            pub fn set_hide_flags(&self, flags: crate::HideFlags) -> Result<()> {
59                OBJECT_SET_HIDE_FLAGS.call((UnityObject(self.0), flags))
60            }
61
62            /// Whether the object is still alive (Unity's `(bool)obj`): `false` once
63            /// it has been destroyed, even though the managed wrapper still exists.
64            pub fn is_alive(&self) -> Result<bool> {
65                OBJECT_IS_ALIVE.call((UnityObject(self.0),))
66            }
67
68            /// Destroys the object at the end of the frame.
69            pub fn destroy(&self) -> Result<()> {
70                OBJECT_DESTROY.call((UnityObject(self.0),))
71            }
72        }
73    };
74}
75
76/// A component type, for [`GameObject::add_component`].
77pub trait ComponentType: Il2CppValue {
78    const ASSEMBLY: &'static str;
79    const NAMESPACE: &'static str;
80    const NAME: &'static str;
81
82    fn from_object(object: Object) -> Self;
83    fn object(&self) -> Object;
84
85    fn game_object(&self) -> Result<GameObject> {
86        COMPONENT_GAME_OBJECT.call((Component(self.object()),))
87    }
88
89    fn transform(&self) -> Result<Transform> {
90        COMPONENT_TRANSFORM.call((Component(self.object()),))
91    }
92
93    /// `GetComponent<U>()` on this component's game object, or `None` if absent.
94    fn get_component<U: ComponentType>(&self) -> Result<Option<U>> {
95        let found =
96            COMPONENT_GET_COMPONENT.call((Component(self.object()), component_type::<U>()?))?;
97        Ok((!found.is_null()).then(|| U::from_object(found.0)))
98    }
99
100    /// Whether the component is enabled. For `Behaviour`-derived components
101    /// (`MonoBehaviour`, `Canvas`, …); meaningless on a plain `Transform`.
102    fn is_enabled(&self) -> Result<bool> {
103        BEHAVIOUR_GET_ENABLED.call((Component(self.object()),))
104    }
105
106    fn set_enabled(&self, enabled: bool) -> Result<()> {
107        BEHAVIOUR_SET_ENABLED.call((Component(self.object()), enabled))
108    }
109}
110
111/// The `System.Type` of a component type `T`, for the Unity query methods.
112fn component_type<T: ComponentType>() -> Result<Object> {
113    Ok(il2cpp()?
114        .class(T::ASSEMBLY, T::NAMESPACE, T::NAME)?
115        .type_object())
116}
117
118/// Collects the elements of a managed `T[]` whose object is `array`.
119fn read_object_array<T: ComponentType>(array: Object) -> Vec<T> {
120    if array.is_null() {
121        return Vec::new();
122    }
123    let Some(il2cpp) = il2cpp().ok() else {
124        return Vec::new();
125    };
126    let length = unsafe { (il2cpp.api().il2cpp_array_length)(array.as_ptr()) };
127    // Elements follow the array header (object header, bounds, length): 4 pointers.
128    let base = 4 * std::mem::size_of::<usize>();
129    (0..length)
130        .map(|i| {
131            T::from_object(unsafe {
132                hao_il2cpp_runtime::read_field(array, base + i * std::mem::size_of::<usize>())
133            })
134        })
135        .collect()
136}
137
138/// Every active object of type `T` in the loaded scenes (`Object.FindObjectsOfType`).
139///
140/// Call this on Unity's main thread (e.g. in [`on_update`](crate::on_update) or
141/// [`on_scene_loaded`](crate::on_scene_loaded)).
142pub fn find_objects_of_type<T: ComponentType>() -> Result<Vec<T>> {
143    let array = OBJECT_FIND_OBJECTS_OF_TYPE.call((component_type::<T>()?,))?;
144    Ok(read_object_array(array))
145}
146
147/// The first active object of type `T`, or `None` (`Object.FindObjectOfType`).
148pub fn find_object_of_type<T: ComponentType>() -> Result<Option<T>> {
149    Ok(find_objects_of_type::<T>()?.into_iter().next())
150}
151
152macro_rules! component_type {
153    ($(#[$doc:meta])* $name:ident = $assembly:literal $namespace:literal $class:literal) => {
154        object_type!($(#[$doc])* $name = $assembly $namespace $class);
155
156        impl ComponentType for $name {
157            const ASSEMBLY: &'static str = $assembly;
158            const NAMESPACE: &'static str = $namespace;
159            const NAME: &'static str = $class;
160
161            fn from_object(object: Object) -> Self {
162                Self(object)
163            }
164
165            fn object(&self) -> Object {
166                self.0
167            }
168        }
169    };
170}
171
172object_type!(
173    /// `UnityEngine.Object`, the base of everything Unity manages.
174    UnityObject = "UnityEngine.CoreModule" "UnityEngine" "Object"
175);
176object_type!(
177    /// `UnityEngine.GameObject`.
178    GameObject = "UnityEngine.CoreModule" "UnityEngine" "GameObject"
179);
180component_type!(
181    /// `UnityEngine.Component`.
182    Component = "UnityEngine.CoreModule" "UnityEngine" "Component"
183);
184component_type!(
185    /// `UnityEngine.Transform`: position in the scene and the parent/child hierarchy.
186    Transform = "UnityEngine.CoreModule" "UnityEngine" "Transform"
187);
188component_type!(
189    /// `UnityEngine.RectTransform`, the transform of UI elements.
190    RectTransform = "UnityEngine.CoreModule" "UnityEngine" "RectTransform"
191);
192component_type!(
193    /// `UnityEngine.Canvas`, the root of a UI.
194    Canvas = "UnityEngine.UIModule" "UnityEngine" "Canvas"
195);
196component_type!(
197    /// `TMPro.TextMeshProUGUI`, TextMeshPro text in a UI.
198    TextMeshPro = "Unity.TextMeshPro" "TMPro" "TextMeshProUGUI"
199);
200component_type!(
201    /// `UnityEngine.Camera`, passed to [`on_render`](crate::on_render) callbacks.
202    Camera = "UnityEngine.CoreModule" "UnityEngine" "Camera"
203);
204object_type!(
205    /// `UnityEngine.Shader`.
206    Shader = "UnityEngine.CoreModule" "UnityEngine" "Shader"
207);
208object_type!(
209    /// `UnityEngine.Material`, e.g. for a [`gl`](crate::gl) drawing pass.
210    Material = "UnityEngine.CoreModule" "UnityEngine" "Material"
211);
212
213impl Shader {
214    /// `Shader.Find(name)`, or `None` if the shader isn't present.
215    pub fn find(name: &str) -> Result<Option<Shader>> {
216        let shader = SHADER_FIND.call((il2cpp()?.string(name)?,))?;
217        Ok((!shader.is_null()).then_some(shader))
218    }
219}
220
221impl Material {
222    /// `new Material(shader)`.
223    pub fn new(shader: Shader) -> Result<Material> {
224        let object = Material(
225            il2cpp()?
226                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
227                .new_object(),
228        );
229        MATERIAL_CTOR.call((object, shader))?;
230        Ok(object)
231    }
232
233    /// Activates pass `pass` for drawing (returns whether it can be rendered).
234    /// Call this before a [`gl`](crate::gl) primitive so it has a material.
235    pub fn set_pass(&self, pass: i32) -> Result<bool> {
236        MATERIAL_SET_PASS.call((*self, pass))
237    }
238
239    pub fn set_color(&self, color: Color) -> Result<()> {
240        MATERIAL_SET_COLOR.call((*self, color))
241    }
242
243    pub fn set_main_texture(&self, texture: Texture2D) -> Result<()> {
244        MATERIAL_SET_MAIN_TEXTURE.call((*self, texture.0))
245    }
246}
247
248object_type!(
249    /// `UnityEngine.Texture2D`.
250    Texture2D = "UnityEngine.CoreModule" "UnityEngine" "Texture2D"
251);
252
253impl Texture2D {
254    /// `new Texture2D(width, height, format, mipChain: false)`.
255    pub fn new(width: i32, height: i32, format: crate::TextureFormat) -> Result<Texture2D> {
256        let object = Texture2D(
257            il2cpp()?
258                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
259                .new_object(),
260        );
261        TEXTURE2D_CTOR.call((object, width, height, format, false))?;
262        Ok(object)
263    }
264
265    /// Uploads raw pixel bytes (matching the texture's format), then applies them.
266    pub fn load_raw(&self, bytes: &[u8]) -> Result<()> {
267        TEXTURE2D_LOAD_RAW.call((*self, il2cpp()?.byte_array(bytes)?))?;
268        TEXTURE2D_APPLY.call((*self,))
269    }
270
271    /// How the texture is sampled (`Point` avoids blending neighbouring texels).
272    pub fn set_filter_mode(&self, mode: crate::FilterMode) -> Result<()> {
273        TEXTURE_SET_FILTER_MODE.call((*self, mode))
274    }
275}
276
277object_type!(
278    /// `UnityEngine.RenderTexture`, an off-screen render target.
279    RenderTexture = "UnityEngine.CoreModule" "UnityEngine" "RenderTexture"
280);
281
282impl RenderTexture {
283    /// `new RenderTexture(width, height, depth)` (depth is the depth-buffer bits,
284    /// e.g. 0 for a colour-only target).
285    pub fn new(width: i32, height: i32, depth: i32) -> Result<RenderTexture> {
286        let object = RenderTexture(
287            il2cpp()?
288                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
289                .new_object(),
290        );
291        RENDER_TEXTURE_CTOR.call((object, width, height, depth))?;
292        Ok(object)
293    }
294
295    /// `RenderTexture.active`, the target GL and camera drawing goes to.
296    pub fn active() -> Result<Option<RenderTexture>> {
297        let rt = RENDER_TEXTURE_GET_ACTIVE.call(())?;
298        Ok((!rt.is_null()).then_some(rt))
299    }
300
301    /// Sets `RenderTexture.active`. Pass `None` to restore the back buffer.
302    pub fn set_active(target: Option<RenderTexture>) -> Result<()> {
303        RENDER_TEXTURE_SET_ACTIVE.call((target.unwrap_or(RenderTexture(Object::NULL)),))
304    }
305}
306
307component_type!(
308    /// `UnityEngine.UI.RawImage`, a UI element that draws a raw [`Texture2D`] or
309    /// [`RenderTexture`].
310    RawImage = "UnityEngine.UI" "UnityEngine.UI" "RawImage"
311);
312
313impl RawImage {
314    /// The texture the image displays.
315    pub fn set_texture(&self, texture: Object) -> Result<()> {
316        RAW_IMAGE_SET_TEXTURE.call((*self, texture))
317    }
318}
319
320impl GameObject {
321    /// `new GameObject(name)`.
322    pub fn new(name: &str) -> Result<Self> {
323        let il2cpp = il2cpp()?;
324        let object = GameObject(
325            il2cpp
326                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
327                .new_object(),
328        );
329        GAME_OBJECT_CTOR.call((object, il2cpp.string(name)?))?;
330        Ok(object)
331    }
332
333    /// `GameObject.Find(name)`: an active object by name or path, such as `Canvas/Menu`.
334    pub fn find(name: &str) -> Result<Option<Self>> {
335        let found = GAME_OBJECT_FIND.call((il2cpp()?.string(name)?,))?;
336        Ok((!found.is_null()).then_some(found))
337    }
338
339    /// `AddComponent(typeof(T))`.
340    pub fn add_component<T: ComponentType>(&self) -> Result<T> {
341        let class = il2cpp()?.class(T::ASSEMBLY, T::NAMESPACE, T::NAME)?;
342        let component = GAME_OBJECT_ADD_COMPONENT.call((*self, class.type_object()))?;
343        Ok(T::from_object(component.0))
344    }
345
346    /// `GetComponent<T>()`, or `None` if the object has no such component.
347    pub fn get_component<T: ComponentType>(&self) -> Result<Option<T>> {
348        let found = GAME_OBJECT_GET_COMPONENT.call((*self, component_type::<T>()?))?;
349        Ok((!found.is_null()).then(|| T::from_object(found.0)))
350    }
351
352    pub fn transform(&self) -> Result<Transform> {
353        GAME_OBJECT_TRANSFORM.call((*self,))
354    }
355
356    /// The transform as a [`RectTransform`], which objects with UI components have.
357    pub fn rect_transform(&self) -> Result<Option<RectTransform>> {
358        let transform = self.transform()?;
359        let class = unsafe { il2cpp()?.class_of(transform.0) };
360        Ok((class.name() == RectTransform::NAME).then_some(RectTransform(transform.0)))
361    }
362
363    pub fn set_active(&self, active: bool) -> Result<()> {
364        GAME_OBJECT_SET_ACTIVE.call((*self, active))
365    }
366
367    /// Whether the object itself is active (its own flag, ignoring parents).
368    pub fn is_active(&self) -> Result<bool> {
369        GAME_OBJECT_ACTIVE_SELF.call((*self,))
370    }
371
372    /// Whether the object is active, taking its parents into account.
373    pub fn is_active_in_hierarchy(&self) -> Result<bool> {
374        GAME_OBJECT_ACTIVE_IN_HIERARCHY.call((*self,))
375    }
376
377    pub fn tag(&self) -> Result<String> {
378        Ok(GAME_OBJECT_GET_TAG
379            .call((*self,))?
380            .to_rust()
381            .unwrap_or_default())
382    }
383
384    pub fn set_tag(&self, tag: &str) -> Result<()> {
385        GAME_OBJECT_SET_TAG.call((*self, il2cpp()?.string(tag)?))
386    }
387
388    pub fn compare_tag(&self, tag: &str) -> Result<bool> {
389        GAME_OBJECT_COMPARE_TAG.call((*self, il2cpp()?.string(tag)?))
390    }
391
392    pub fn layer(&self) -> Result<i32> {
393        GAME_OBJECT_GET_LAYER.call((*self,))
394    }
395
396    pub fn set_layer(&self, layer: i32) -> Result<()> {
397        GAME_OBJECT_SET_LAYER.call((*self, layer))
398    }
399}
400
401impl Transform {
402    pub fn set_parent(&self, parent: Transform, world_position_stays: bool) -> Result<()> {
403        TRANSFORM_SET_PARENT.call((*self, parent, world_position_stays))
404    }
405
406    pub fn set_local_scale(&self, scale: Vector3) -> Result<()> {
407        TRANSFORM_SET_LOCAL_SCALE.call((*self, scale))
408    }
409
410    /// World-space position.
411    pub fn position(&self) -> Result<Vector3> {
412        TRANSFORM_GET_POSITION.call((*self,))
413    }
414
415    pub fn set_position(&self, position: Vector3) -> Result<()> {
416        TRANSFORM_SET_POSITION.call((*self, position))
417    }
418
419    /// Position relative to the parent.
420    pub fn local_position(&self) -> Result<Vector3> {
421        TRANSFORM_GET_LOCAL_POSITION.call((*self,))
422    }
423
424    pub fn set_local_position(&self, position: Vector3) -> Result<()> {
425        TRANSFORM_SET_LOCAL_POSITION.call((*self, position))
426    }
427
428    /// World-space rotation as Euler angles in degrees.
429    pub fn euler_angles(&self) -> Result<Vector3> {
430        TRANSFORM_GET_EULER_ANGLES.call((*self,))
431    }
432
433    pub fn rotation(&self) -> Result<Quaternion> {
434        TRANSFORM_GET_ROTATION.call((*self,))
435    }
436
437    pub fn set_rotation(&self, rotation: Quaternion) -> Result<()> {
438        TRANSFORM_SET_ROTATION.call((*self, rotation))
439    }
440
441    /// The parent transform, or `None` at the scene root.
442    pub fn parent(&self) -> Result<Option<Transform>> {
443        let parent = TRANSFORM_GET_PARENT.call((*self,))?;
444        Ok((!parent.is_null()).then_some(parent))
445    }
446
447    pub fn child_count(&self) -> Result<i32> {
448        TRANSFORM_GET_CHILD_COUNT.call((*self,))
449    }
450
451    pub fn child(&self, index: i32) -> Result<Transform> {
452        TRANSFORM_GET_CHILD.call((*self, index))
453    }
454
455    /// A descendant by name or path (e.g. `"HUD/Health"`), or `None`.
456    pub fn find(&self, path: &str) -> Result<Option<Transform>> {
457        let found = TRANSFORM_FIND.call((*self, il2cpp()?.string(path)?))?;
458        Ok((!found.is_null()).then_some(found))
459    }
460}
461
462impl RectTransform {
463    pub fn as_transform(&self) -> Transform {
464        Transform(self.0)
465    }
466
467    /// Anchors and pivot, each from (0, 0) at the bottom left of the parent to (1, 1) at the top right.
468    pub fn set_anchors(&self, min: Vector2, max: Vector2, pivot: Vector2) -> Result<()> {
469        RECT_SET_ANCHOR_MIN.call((*self, min))?;
470        RECT_SET_ANCHOR_MAX.call((*self, max))?;
471        RECT_SET_PIVOT.call((*self, pivot))
472    }
473
474    /// The pivot's position relative to the anchors, in pixels with y up.
475    pub fn set_anchored_position(&self, position: Vector2) -> Result<()> {
476        RECT_SET_ANCHORED_POSITION.call((*self, position))
477    }
478
479    pub fn set_size(&self, size: Vector2) -> Result<()> {
480        RECT_SET_SIZE_DELTA.call((*self, size))
481    }
482}
483
484impl Canvas {
485    pub fn set_render_mode(&self, mode: RenderMode) -> Result<()> {
486        CANVAS_SET_RENDER_MODE.call((*self, mode))
487    }
488
489    /// Canvases with a higher order draw on top.
490    pub fn set_sorting_order(&self, order: i32) -> Result<()> {
491        CANVAS_SET_SORTING_ORDER.call((*self, order))
492    }
493}
494
495impl TextMeshPro {
496    pub fn set_text(&self, text: &str) -> Result<()> {
497        TMP_SET_TEXT.call((*self, il2cpp()?.string(text)?))
498    }
499
500    pub fn set_font_size(&self, size: f32) -> Result<()> {
501        TMP_SET_FONT_SIZE.call((*self, size))
502    }
503
504    pub fn set_color(&self, color: Color) -> Result<()> {
505        TMP_SET_COLOR.call((*self, color))
506    }
507}