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    /// How the texture is sampled (inherited from `Texture`).
307    pub fn set_filter_mode(&self, mode: crate::FilterMode) -> Result<()> {
308        TEXTURE_SET_FILTER_MODE.call((Texture2D(self.0), mode))
309    }
310}
311
312component_type!(
313    /// `UnityEngine.UI.RawImage`, a UI element that draws a raw [`Texture2D`] or
314    /// [`RenderTexture`].
315    RawImage = "UnityEngine.UI" "UnityEngine.UI" "RawImage"
316);
317
318impl RawImage {
319    /// The texture the image displays.
320    pub fn set_texture(&self, texture: Object) -> Result<()> {
321        RAW_IMAGE_SET_TEXTURE.call((*self, texture))
322    }
323}
324
325impl GameObject {
326    /// `new GameObject(name)`.
327    pub fn new(name: &str) -> Result<Self> {
328        let il2cpp = il2cpp()?;
329        let object = GameObject(
330            il2cpp
331                .class(Self::ASSEMBLY, Self::NAMESPACE, Self::NAME)?
332                .new_object(),
333        );
334        GAME_OBJECT_CTOR.call((object, il2cpp.string(name)?))?;
335        Ok(object)
336    }
337
338    /// `GameObject.Find(name)`: an active object by name or path, such as `Canvas/Menu`.
339    pub fn find(name: &str) -> Result<Option<Self>> {
340        let found = GAME_OBJECT_FIND.call((il2cpp()?.string(name)?,))?;
341        Ok((!found.is_null()).then_some(found))
342    }
343
344    /// `AddComponent(typeof(T))`.
345    pub fn add_component<T: ComponentType>(&self) -> Result<T> {
346        let class = il2cpp()?.class(T::ASSEMBLY, T::NAMESPACE, T::NAME)?;
347        let component = GAME_OBJECT_ADD_COMPONENT.call((*self, class.type_object()))?;
348        Ok(T::from_object(component.0))
349    }
350
351    /// `GetComponent<T>()`, or `None` if the object has no such component.
352    pub fn get_component<T: ComponentType>(&self) -> Result<Option<T>> {
353        let found = GAME_OBJECT_GET_COMPONENT.call((*self, component_type::<T>()?))?;
354        Ok((!found.is_null()).then(|| T::from_object(found.0)))
355    }
356
357    pub fn transform(&self) -> Result<Transform> {
358        GAME_OBJECT_TRANSFORM.call((*self,))
359    }
360
361    /// The transform as a [`RectTransform`], which objects with UI components have.
362    pub fn rect_transform(&self) -> Result<Option<RectTransform>> {
363        let transform = self.transform()?;
364        let class = unsafe { il2cpp()?.class_of(transform.0) };
365        Ok((class.name() == RectTransform::NAME).then_some(RectTransform(transform.0)))
366    }
367
368    pub fn set_active(&self, active: bool) -> Result<()> {
369        GAME_OBJECT_SET_ACTIVE.call((*self, active))
370    }
371
372    /// Whether the object itself is active (its own flag, ignoring parents).
373    pub fn is_active(&self) -> Result<bool> {
374        GAME_OBJECT_ACTIVE_SELF.call((*self,))
375    }
376
377    /// Whether the object is active, taking its parents into account.
378    pub fn is_active_in_hierarchy(&self) -> Result<bool> {
379        GAME_OBJECT_ACTIVE_IN_HIERARCHY.call((*self,))
380    }
381
382    pub fn tag(&self) -> Result<String> {
383        Ok(GAME_OBJECT_GET_TAG
384            .call((*self,))?
385            .to_rust()
386            .unwrap_or_default())
387    }
388
389    pub fn set_tag(&self, tag: &str) -> Result<()> {
390        GAME_OBJECT_SET_TAG.call((*self, il2cpp()?.string(tag)?))
391    }
392
393    pub fn compare_tag(&self, tag: &str) -> Result<bool> {
394        GAME_OBJECT_COMPARE_TAG.call((*self, il2cpp()?.string(tag)?))
395    }
396
397    pub fn layer(&self) -> Result<i32> {
398        GAME_OBJECT_GET_LAYER.call((*self,))
399    }
400
401    pub fn set_layer(&self, layer: i32) -> Result<()> {
402        GAME_OBJECT_SET_LAYER.call((*self, layer))
403    }
404}
405
406impl Transform {
407    pub fn set_parent(&self, parent: Transform, world_position_stays: bool) -> Result<()> {
408        TRANSFORM_SET_PARENT.call((*self, parent, world_position_stays))
409    }
410
411    pub fn set_local_scale(&self, scale: Vector3) -> Result<()> {
412        TRANSFORM_SET_LOCAL_SCALE.call((*self, scale))
413    }
414
415    /// World-space position.
416    pub fn position(&self) -> Result<Vector3> {
417        TRANSFORM_GET_POSITION.call((*self,))
418    }
419
420    pub fn set_position(&self, position: Vector3) -> Result<()> {
421        TRANSFORM_SET_POSITION.call((*self, position))
422    }
423
424    /// Position relative to the parent.
425    pub fn local_position(&self) -> Result<Vector3> {
426        TRANSFORM_GET_LOCAL_POSITION.call((*self,))
427    }
428
429    pub fn set_local_position(&self, position: Vector3) -> Result<()> {
430        TRANSFORM_SET_LOCAL_POSITION.call((*self, position))
431    }
432
433    /// World-space rotation as Euler angles in degrees.
434    pub fn euler_angles(&self) -> Result<Vector3> {
435        TRANSFORM_GET_EULER_ANGLES.call((*self,))
436    }
437
438    pub fn rotation(&self) -> Result<Quaternion> {
439        TRANSFORM_GET_ROTATION.call((*self,))
440    }
441
442    pub fn set_rotation(&self, rotation: Quaternion) -> Result<()> {
443        TRANSFORM_SET_ROTATION.call((*self, rotation))
444    }
445
446    /// The parent transform, or `None` at the scene root.
447    pub fn parent(&self) -> Result<Option<Transform>> {
448        let parent = TRANSFORM_GET_PARENT.call((*self,))?;
449        Ok((!parent.is_null()).then_some(parent))
450    }
451
452    pub fn child_count(&self) -> Result<i32> {
453        TRANSFORM_GET_CHILD_COUNT.call((*self,))
454    }
455
456    pub fn child(&self, index: i32) -> Result<Transform> {
457        TRANSFORM_GET_CHILD.call((*self, index))
458    }
459
460    /// A descendant by name or path (e.g. `"HUD/Health"`), or `None`.
461    pub fn find(&self, path: &str) -> Result<Option<Transform>> {
462        let found = TRANSFORM_FIND.call((*self, il2cpp()?.string(path)?))?;
463        Ok((!found.is_null()).then_some(found))
464    }
465}
466
467impl RectTransform {
468    pub fn as_transform(&self) -> Transform {
469        Transform(self.0)
470    }
471
472    /// Anchors and pivot, each from (0, 0) at the bottom left of the parent to (1, 1) at the top right.
473    pub fn set_anchors(&self, min: Vector2, max: Vector2, pivot: Vector2) -> Result<()> {
474        RECT_SET_ANCHOR_MIN.call((*self, min))?;
475        RECT_SET_ANCHOR_MAX.call((*self, max))?;
476        RECT_SET_PIVOT.call((*self, pivot))
477    }
478
479    /// The pivot's position relative to the anchors, in pixels with y up.
480    pub fn set_anchored_position(&self, position: Vector2) -> Result<()> {
481        RECT_SET_ANCHORED_POSITION.call((*self, position))
482    }
483
484    pub fn set_size(&self, size: Vector2) -> Result<()> {
485        RECT_SET_SIZE_DELTA.call((*self, size))
486    }
487}
488
489impl Canvas {
490    pub fn set_render_mode(&self, mode: RenderMode) -> Result<()> {
491        CANVAS_SET_RENDER_MODE.call((*self, mode))
492    }
493
494    /// Canvases with a higher order draw on top.
495    pub fn set_sorting_order(&self, order: i32) -> Result<()> {
496        CANVAS_SET_SORTING_ORDER.call((*self, order))
497    }
498}
499
500impl TextMeshPro {
501    pub fn set_text(&self, text: &str) -> Result<()> {
502        TMP_SET_TEXT.call((*self, il2cpp()?.string(text)?))
503    }
504
505    pub fn set_font_size(&self, size: f32) -> Result<()> {
506        TMP_SET_FONT_SIZE.call((*self, size))
507    }
508
509    pub fn set_color(&self, color: Color) -> Result<()> {
510        TMP_SET_COLOR.call((*self, color))
511    }
512}