Skip to main content

godot_core/obj/
gd.rs

1/*
2 * Copyright (c) godot-rust; Bromeon and contributors.
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 */
7
8use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
9use std::ops::{Deref, DerefMut};
10
11use godot_ffi as sys;
12use godot_ffi::is_main_thread;
13use sys::{SysPtr as _, static_assert_eq_size_align};
14
15use crate::builtin::{Callable, NodePath, StringName, Variant};
16use crate::meta::error::{ConvertError, FromFfiError};
17use crate::meta::shape::GodotShape;
18use crate::meta::{
19    AsArg, ClassId, Element, FromGodot, GodotConvert, GodotNullableType, GodotType, RefArg, ToGodot,
20};
21use crate::obj::{
22    Bounds, DynGd, GdDerefTarget, GdMut, GdRef, GodotClass, Inherits, InstanceId, OnEditor, RawGd,
23    WithBaseField, WithSignals, bounds, cap,
24};
25use crate::private::{PanicPayload, callbacks};
26use crate::registry::class::try_dynify_object;
27use crate::registry::info::PropertyHintInfo;
28use crate::registry::property::{Export, SimpleVar, Var};
29use crate::{classes, meta, out};
30
31/// Smart pointer to objects owned by the Godot engine.
32///
33/// See also [chapter about objects][book] in the book.
34///
35/// This smart pointer can only hold _objects_ in the Godot sense: instances of Godot classes (`Node`, `RefCounted`, etc.)
36/// or user-declared structs (declared with `#[derive(GodotClass)]`). It does **not** hold built-in types (`Vector3`, `Color`, `i32`).
37///
38/// `Gd<T>` never holds null objects. If you need nullability, use `Option<Gd<T>>`. To pass null objects to engine APIs, you can
39/// additionally use [`Gd::null_arg()`] as a shorthand.
40///
41/// # Memory management
42///
43/// This smart pointer behaves differently depending on `T`'s associated types, see [`GodotClass`] for their documentation.
44/// In particular, the memory management strategy is fully dependent on `T`:
45///
46/// - **Reference-counted**<br>
47///   Objects of type [`RefCounted`] or inherited from it are **reference-counted**. This means that every time a smart pointer is
48///   shared using [`Clone::clone()`], the reference counter is incremented, and every time one is dropped, it is decremented.
49///   This ensures that the last reference (either in Rust or Godot) will deallocate the object and call `T`'s destructor.<br><br>
50///
51/// - **Manual**<br>
52///   Objects inheriting from [`Object`] which are not `RefCounted` (or inherited) are **manually-managed**.
53///   Their destructor is not automatically called (unless they are part of the scene tree). Creating a `Gd<T>` means that
54///   you are responsible for explicitly deallocating such objects using [`free()`][Self::free].<br><br>
55///
56/// - **Dynamic**<br>
57///   For `T=Object`, the memory strategy is determined **dynamically**. Due to polymorphism, a `Gd<Object>` can point to either
58///   reference-counted or manually-managed types at runtime. The behavior corresponds to one of the two previous points.
59///   Note that if the dynamic type is also `Object`, the memory is manually-managed.
60///
61/// # Construction
62///
63/// To construct default instances of various `Gd<T>` types, there are extension methods on the type `T` itself:
64///
65/// - Manually managed: [`NewAlloc::new_alloc()`][crate::obj::NewAlloc::new_alloc]
66/// - Reference-counted: [`NewGd::new_gd()`][crate::obj::NewGd::new_gd]
67/// - Singletons: `T::singleton()` (inherent)
68///
69/// In addition, the smart pointer can be constructed in multiple ways:
70///
71/// * [`Gd::default()`] for reference-counted types that are constructible. For user types, this means they must expose an `init` function
72///   or have a generated one. `Gd::<T>::default()` is equivalent to the shorter `T::new_gd()` and primarily useful for derives or generics.
73/// * [`Gd::from_init_fn(function)`][Gd::from_init_fn] for Rust objects with `Base<T>` field, which are constructed inside the smart pointer.
74///   This is a very handy function if you want to pass extra parameters to your object upon construction.
75/// * [`Gd::from_object(rust_obj)`][Gd::from_object] for existing Rust objects without a `Base<T>` field that are moved _into_ the smart pointer.
76/// * [`Gd::from_instance_id(id)`][Gd::from_instance_id] and [`Gd::try_from_instance_id(id)`][Gd::try_from_instance_id]
77///   to obtain a pointer to an object which is already alive in the engine.
78///
79/// # Bind guards
80///
81/// The [`bind()`][Self::bind] and [`bind_mut()`][Self::bind_mut] methods allow you to obtain a shared or exclusive guard to the user instance.
82/// These provide interior mutability similar to [`RefCell`][std::cell::RefCell], with the addition that `Gd` simultaneously handles reference
83/// counting (for some types `T`).
84///
85/// Holding a bind guard will prevent other code paths from obtaining their own shared/mutable bind. As such, you should drop the guard
86/// as soon as you don't need it anymore, by closing a `{ }` block or calling `std::mem::drop()`.
87///
88/// When you declare a `#[func]` method on your own class, and it accepts `&self` or `&mut self`, an implicit `bind()` or `bind_mut()` call
89/// on the owning `Gd<T>` is performed. This is important to keep in mind, as you can get into situations that violate dynamic borrow rules; for
90/// example if you are inside a `&mut self` method, make a call to GDScript and indirectly call another method on the same object (re-entrancy).
91///
92/// # Conversions
93///
94/// For type conversions, please read the [`godot::meta` module docs](../meta/index.html).
95///
96/// # Exporting
97///
98/// The [`Export`][crate::registry::property::Export] trait is not directly implemented for `Gd<T>`, because the editor expects object-based
99/// properties to be nullable, while `Gd<T>` can't be null. Instead, `Export` is implemented for [`OnEditor<Gd<T>>`][crate::obj::OnEditor],
100/// which validates that objects have been set by the editor. For the most flexible but least ergonomic option, you can also export
101/// `Option<Gd<T>>` fields.
102///
103/// Objects can only be exported if `T: Inherits<Node>` or `T: Inherits<Resource>`, just like GDScript.
104/// This means you cannot use `#[export]` with `OnEditor<Gd<RefCounted>>`, for example.
105///
106/// [book]: https://godot-rust.github.io/book/godot-api/objects.html
107/// [`Object`]: classes::Object
108/// [`RefCounted`]: classes::RefCounted
109#[repr(C)] // must be layout compatible with engine classes
110pub struct Gd<T: GodotClass> {
111    // Note: `opaque` has the same layout as GDExtensionObjectPtr == Object* in C++, i.e. the bytes represent a pointer
112    // To receive a GDExtensionTypePtr == GDExtensionObjectPtr* == Object**, we need to get the address of this
113    // Hence separate sys() for GDExtensionTypePtr, and obj_sys() for GDExtensionObjectPtr.
114    // The former is the standard FFI type, while the latter is used in object-specific GDExtension engines.
115    // pub(crate) because accessed in obj::dom
116    pub(crate) raw: RawGd<T>,
117}
118
119// Size equality check (should additionally be covered by mem::transmute())
120static_assert_eq_size_align!(
121    sys::GDExtensionObjectPtr,
122    sys::types::OpaqueObject,
123    "Godot FFI: pointer type `Object*` should have size advertised in JSON extension file"
124);
125
126/// _The methods in this impl block are only available for user-declared `T`, that is,
127/// structs with `#[derive(GodotClass)]` but not Godot classes like `Node` or `RefCounted`._ <br><br>
128impl<T> Gd<T>
129where
130    T: GodotClass + Bounds<Declarer = bounds::DeclUser>,
131{
132    /// Creates a `Gd<T>` using a function that constructs a `T` from a provided base.
133    ///
134    /// Imagine you have a type `T`, which has a base field that you cannot default-initialize.
135    /// The `init` function provides you with a `Base<T::Base>` object that you can use inside your `T`, which
136    /// is then wrapped in a `Gd<T>`.
137    ///
138    /// # Example
139    /// ```no_run
140    /// # use godot::prelude::*;
141    /// #[derive(GodotClass)]
142    /// #[class(init, base=Node2D)]
143    /// struct MyClass {
144    ///     my_base: Base<Node2D>,
145    ///     other_field: i32,
146    /// }
147    ///
148    /// let obj = Gd::from_init_fn(|my_base| {
149    ///     // accepts the base and returns a constructed object containing it
150    ///     MyClass { my_base, other_field: 732 }
151    /// });
152    /// ```
153    ///
154    /// # Panics
155    /// Panics occurring in the `init` function are propagated to the caller.
156    pub fn from_init_fn<F>(init: F) -> Self
157    where
158        F: FnOnce(crate::obj::Base<T::Base>) -> T,
159    {
160        let object_ptr = callbacks::create_custom(init, true) // or propagate panic.
161            .unwrap_or_else(|payload| PanicPayload::repanic(payload));
162
163        unsafe { Gd::from_obj_sys(object_ptr) }
164    }
165
166    /// Moves a user-created object into this smart pointer, submitting ownership to the Godot engine.
167    ///
168    /// This is only useful for types `T` which do not store their base objects (if they have a base,
169    /// you cannot construct them standalone).
170    pub fn from_object(user_object: T) -> Self {
171        Self::from_init_fn(move |_base| user_object)
172    }
173
174    /// Hands out a guard for a shared borrow, through which the user instance can be read.
175    ///
176    /// The pattern is very similar to interior mutability with standard [`RefCell`][std::cell::RefCell].
177    /// You can either have multiple `GdRef` shared guards, or a single `GdMut` exclusive guard to a Rust
178    /// `GodotClass` instance, independently of how many `Gd` smart pointers point to it. There are runtime
179    /// checks to ensure that Rust safety rules (e.g. no `&` and `&mut` coexistence) are upheld.
180    ///
181    /// Drop the guard as soon as you don't need it anymore. See also [Bind guards](#bind-guards).
182    ///
183    /// # Panics
184    /// * If another `Gd` smart pointer pointing to the same Rust instance has a live `GdMut` guard bound.
185    /// * If there is an ongoing function call from GDScript to Rust, which currently holds a `&mut T`
186    ///   reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
187    // Note: possible names: write/read, hold/hold_mut, r/w, r/rw, ...
188    pub fn bind(&self) -> GdRef<'_, T> {
189        self.raw.bind()
190    }
191
192    /// Hands out a guard for an exclusive borrow, through which the user instance can be read and written.
193    ///
194    /// The pattern is very similar to interior mutability with standard [`RefCell`][std::cell::RefCell].
195    /// You can either have multiple `GdRef` shared guards, or a single `GdMut` exclusive guard to a Rust
196    /// `GodotClass` instance, independently of how many `Gd` smart pointers point to it. There are runtime
197    /// checks to ensure that Rust safety rules (e.g. no `&mut` aliasing) are upheld.
198    ///
199    /// Drop the guard as soon as you don't need it anymore. See also [Bind guards](#bind-guards).
200    ///
201    /// # Panics
202    /// * If another `Gd` smart pointer pointing to the same Rust instance has a live `GdRef` or `GdMut` guard bound.
203    /// * If there is an ongoing function call from GDScript to Rust, which currently holds a `&T` or `&mut T`
204    ///   reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
205    pub fn bind_mut(&mut self) -> GdMut<'_, T> {
206        self.raw.bind_mut()
207    }
208}
209
210/// _The methods in this impl block are available for any `T`._ <br><br>
211impl<T: GodotClass> Gd<T> {
212    /// Looks up the given instance ID and returns the associated object, if possible.
213    ///
214    /// If no such instance ID is registered, or if the dynamic type of the object behind that instance ID
215    /// is not compatible with `T`, then `None` is returned.
216    pub fn try_from_instance_id(instance_id: InstanceId) -> Result<Self, ConvertError> {
217        let ptr = classes::object_ptr_from_id(instance_id);
218
219        // SAFETY: assumes that the returned GDExtensionObjectPtr is convertible to Object* (i.e. C++ upcast doesn't modify the pointer)
220        let untyped = unsafe { Gd::<classes::Object>::from_obj_sys_or_none(ptr)? };
221        untyped
222            .owned_cast::<T>()
223            .map_err(|obj| FromFfiError::WrongObjectType.into_error(obj))
224    }
225
226    /// ⚠️ Looks up the given instance ID and returns the associated object.
227    ///
228    /// Corresponds to Godot's global function `instance_from_id()`.
229    ///
230    /// # Panics
231    /// If no such instance ID is registered, or if the dynamic type of the object behind that instance ID
232    /// is not compatible with `T`.
233    #[doc(alias = "instance_from_id")]
234    pub fn from_instance_id(instance_id: InstanceId) -> Self {
235        Self::try_from_instance_id(instance_id).unwrap_or_else(|err| {
236            panic!(
237                "Instance ID {} does not belong to a valid object of class '{}': {}",
238                instance_id,
239                T::class_id(),
240                err
241            )
242        })
243    }
244
245    /// Returns the instance ID of this object, or `None` if the object is dead or null.
246    pub(crate) fn instance_id_or_none(&self) -> Option<InstanceId> {
247        let known_id = self.instance_id_unchecked();
248
249        // Refreshes the internal cached ID on every call, as we cannot be sure that the object has not been
250        // destroyed since last time. The only reliable way to find out is to call is_instance_id_valid().
251        if self.raw.is_instance_valid() {
252            Some(known_id)
253        } else {
254            None
255        }
256    }
257
258    /// ⚠️ Returns the instance ID of this object (panics when dead).
259    ///
260    /// # Panics
261    /// If this object is no longer alive (registered in Godot's object database).
262    pub fn instance_id(&self) -> InstanceId {
263        self.instance_id_or_none().unwrap_or_else(|| {
264            panic!(
265                "failed to call instance_id() on destroyed object; \
266                use instance_id_or_none() or keep your objects alive"
267            )
268        })
269    }
270
271    /// Returns the last known, possibly invalid instance ID of this object.
272    ///
273    /// This function does not check that the returned instance ID points to a valid instance!
274    /// Unless performance is a problem, use [`instance_id()`][Self::instance_id] instead.
275    ///
276    /// This method is safe and never panics.
277    pub fn instance_id_unchecked(&self) -> InstanceId {
278        let instance_id = self.raw.instance_id_unchecked();
279
280        // SAFETY: a `Gd` can only be created from a non-null `RawGd`, meaning `raw.instance_id_unchecked()` will
281        // always return `Some`.
282        unsafe { instance_id.unwrap_unchecked() }
283    }
284
285    /// Checks if this smart pointer points to a live object (read description!).
286    ///
287    /// Using this method is often indicative of bad design -- you should dispose of your pointers once an object is
288    /// destroyed. However, this method exists because GDScript offers it and there may be **rare** use cases.
289    ///
290    /// Do not use this method to check if you can safely access an object. Accessing dead objects is generally safe
291    /// and will panic in a defined manner. Encountering such panics is almost always a bug you should fix, and not a
292    /// runtime condition to check against.
293    pub fn is_instance_valid(&self) -> bool {
294        self.raw.is_instance_valid()
295    }
296
297    /// Returns the dynamic class name of the object as `StringName`.
298    ///
299    /// This method retrieves the class name of the object at runtime, which can be different from [`T::class_id()`][GodotClass::class_id]
300    /// if derived classes are involved.
301    ///
302    /// Unlike [`Object::get_class()`][crate::classes::Object::get_class], this returns `StringName` instead of `GString` and needs no
303    /// `Inherits<Object>` bound.
304    pub(crate) fn dynamic_class_string(&self) -> StringName {
305        unsafe {
306            StringName::new_with_string_uninit(|ptr| {
307                let success = sys::interface_fn!(object_get_class_name)(
308                    self.obj_sys().as_const(),
309                    sys::get_library(),
310                    ptr,
311                );
312
313                let success = sys::conv::bool_from_sys(success);
314                assert!(success, "failed to get class name for object {self:?}");
315            })
316        }
317    }
318
319    /// Returns the reference count, if the dynamic object inherits `RefCounted`; and `None` otherwise.
320    ///
321    /// Returns `Err(())` if obtaining reference count failed, due to being called during init/drop.
322    pub(crate) fn maybe_refcount(&self) -> Option<Result<usize, ()>> {
323        // May become infallible if implemented via call() on Object, if ref-count bit of instance ID is set.
324        // This would likely be more efficient, too.
325
326        // Fast check if ref-counted without downcast.
327        if !self.instance_id().is_ref_counted() {
328            return None;
329        }
330
331        // Optimization: call `get_reference_count()` directly. Might also increase reliability and obviate the need for Result.
332
333        let rc = self
334            .raw
335            .try_with_ref_counted(|refc| refc.get_reference_count());
336
337        Some(rc.map(|i| i as usize))
338    }
339
340    /// Create a non-owning pointer from this.
341    ///
342    /// # Safety
343    /// Must be destroyed with [`drop_weak()`][Self::drop_weak]; regular `Drop` will cause use-after-free.
344    pub(crate) unsafe fn clone_weak(&self) -> Self {
345        // SAFETY: delegated to caller.
346        unsafe { Gd::from_obj_sys_weak(self.obj_sys()) }
347    }
348
349    /// Drop without decrementing ref-counter.
350    ///
351    /// Needed in situations where the instance should effectively be forgotten, but without leaking other associated data.
352    pub(crate) fn drop_weak(self) {
353        // As soon as fields need custom Drop, this won't be enough anymore.
354        std::mem::forget(self);
355    }
356
357    #[cfg(feature = "trace")] // itest only.
358    #[doc(hidden)]
359    pub fn test_refcount(&self) -> Option<usize> {
360        self.maybe_refcount()
361            .transpose()
362            .expect("failed to obtain refcount")
363    }
364
365    /// **Upcast:** convert into a smart pointer to a base class. Always succeeds.
366    ///
367    /// Moves out of this value. If you want to create _another_ smart pointer instance,
368    /// use this idiom:
369    /// ```no_run
370    /// # use godot::prelude::*;
371    /// #[derive(GodotClass)]
372    /// #[class(init, base=Node2D)]
373    /// struct MyClass {}
374    ///
375    /// let obj: Gd<MyClass> = MyClass::new_alloc();
376    /// let base = obj.clone().upcast::<Node>();
377    /// ```
378    pub fn upcast<Base>(self) -> Gd<Base>
379    where
380        Base: GodotClass,
381        T: Inherits<Base>,
382    {
383        self.owned_cast()
384            .expect("Upcast failed. This is a bug; please report it.")
385    }
386
387    /// Equivalent to [`upcast::<Object>()`][Self::upcast], but without bounds.
388    // Not yet public because it might need _mut/_ref overloads, and 6 upcast methods are a bit much...
389    #[doc(hidden)] // no public API, but used by #[signal].
390    pub fn upcast_object(self) -> Gd<classes::Object> {
391        self.owned_cast()
392            .expect("Upcast to Object failed. This is a bug; please report it.")
393    }
394
395    // /// Equivalent to [`upcast_mut::<Object>()`][Self::upcast_mut], but without bounds.
396    // pub(crate) fn upcast_object_ref(&self) -> &classes::Object {
397    //     self.raw.as_object_ref()
398    // }
399
400    /// Equivalent to [`upcast_mut::<Object>()`][Self::upcast_mut], but without bounds.
401    pub(crate) fn upcast_object_mut(&mut self) -> &mut classes::Object {
402        self.raw.as_object_mut()
403    }
404
405    // pub(crate) fn upcast_object_mut_from_ref(&self) -> &mut classes::Object {
406    //     self.raw.as_object_mut()
407    // }
408
409    /// **Upcast shared-ref:** access this object as a shared reference to a base class.
410    ///
411    /// This is semantically equivalent to multiple applications of [`Self::deref()`]. Not really useful on its own, but combined with
412    /// generic programming:
413    /// ```no_run
414    /// # use godot::prelude::*;
415    /// fn print_node_name<T>(node: &Gd<T>)
416    /// where
417    ///     T: Inherits<Node>,
418    /// {
419    ///     println!("Node name: {}", node.upcast_ref().get_name());
420    /// }
421    /// ```
422    ///
423    /// Note that this cannot be used to get a reference to Rust classes, for that you should use [`Gd::bind()`]. For instance this
424    /// will fail:
425    /// ```compile_fail
426    /// # use godot::prelude::*;
427    /// #[derive(GodotClass)]
428    /// #[class(init, base = Node)]
429    /// struct SomeClass {}
430    ///
431    /// #[godot_api]
432    /// impl INode for SomeClass {
433    ///     fn ready(&mut self) {
434    ///         let other = SomeClass::new_alloc();
435    ///         let _ = other.upcast_ref::<SomeClass>();
436    ///     }
437    /// }
438    /// ```
439    pub fn upcast_ref<Base>(&self) -> &Base
440    where
441        Base: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
442        T: Inherits<Base>,
443    {
444        // SAFETY: `Base` is guaranteed to be an engine base class of `T` because of the generic bounds.
445        unsafe { self.raw.as_upcast_ref::<Base>() }
446    }
447
448    /// **Upcast exclusive-ref:** access this object as an exclusive reference to a base class.
449    ///
450    /// This is semantically equivalent to multiple applications of [`Self::deref_mut()`]. Not really useful on its own, but combined with
451    /// generic programming:
452    /// ```no_run
453    /// # use godot::prelude::*;
454    /// fn set_node_name<T>(node: &mut Gd<T>, name: &str)
455    /// where
456    ///     T: Inherits<Node>,
457    /// {
458    ///     node.upcast_mut().set_name(name);
459    /// }
460    /// ```
461    ///
462    /// Note that this cannot be used to get a mutable reference to Rust classes, for that you should use [`Gd::bind_mut()`]. For instance this
463    /// will fail:
464    /// ```compile_fail
465    /// # use godot::prelude::*;
466    /// #[derive(GodotClass)]
467    /// #[class(init, base = Node)]
468    /// struct SomeClass {}
469    ///
470    /// #[godot_api]
471    /// impl INode for SomeClass {
472    ///     fn ready(&mut self) {
473    ///         let mut other = SomeClass::new_alloc();
474    ///         let _ = other.upcast_mut::<SomeClass>();
475    ///     }
476    /// }
477    /// ```
478    pub fn upcast_mut<Base>(&mut self) -> &mut Base
479    where
480        Base: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
481        T: Inherits<Base>,
482    {
483        // SAFETY: `Base` is guaranteed to be an engine base class of `T` because of the generic bounds.
484        unsafe { self.raw.as_upcast_mut::<Base>() }
485    }
486
487    /// **Downcast:** try to convert into a smart pointer to a derived class.
488    ///
489    /// If `T`'s dynamic type is not `Derived` or one of its subclasses, `Err(self)` is returned, meaning you can reuse the original
490    /// object for further casts.
491    pub fn try_cast<Derived>(self) -> Result<Gd<Derived>, Self>
492    where
493        Derived: Inherits<T>,
494    {
495        // Separate method due to more restrictive bounds.
496        self.owned_cast()
497    }
498
499    /// ⚠️ **Downcast:** convert into a smart pointer to a derived class. Panics on error.
500    ///
501    /// # Panics
502    /// If the class' dynamic type is not `Derived` or one of its subclasses. Use [`Self::try_cast()`] if you want to check the result.
503    pub fn cast<Derived>(self) -> Gd<Derived>
504    where
505        Derived: Inherits<T>,
506    {
507        self.owned_cast().unwrap_or_else(|from_obj| {
508            panic!(
509                "downcast from {from} to {to} failed; instance {from_obj:?}",
510                from = T::class_id(),
511                to = Derived::class_id(),
512            )
513        })
514    }
515
516    /// Returns `Ok(cast_obj)` on success, `Err(self)` on error.
517    // Visibility: used by DynGd.
518    pub(crate) fn owned_cast<U>(self) -> Result<Gd<U>, Self>
519    where
520        U: GodotClass,
521    {
522        self.raw
523            .owned_cast()
524            .map(Gd::from_ffi)
525            .map_err(Self::from_ffi)
526    }
527
528    /// Create default instance for all types that have `GodotDefault`.
529    ///
530    /// Deliberately more loose than `Gd::default()`, does not require ref-counted memory strategy for user types.
531    pub(crate) fn default_instance() -> Self
532    where
533        T: cap::GodotDefault,
534    {
535        unsafe {
536            // Default value (and compat one) for `p_notify_postinitialize` is true in Godot.
537            #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
538            let object_ptr = callbacks::create::<T>(std::ptr::null_mut(), sys::conv::SYS_TRUE);
539            #[cfg(before_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.4")))]
540            let object_ptr = callbacks::create::<T>(std::ptr::null_mut());
541
542            Gd::from_obj_sys(object_ptr)
543        }
544    }
545
546    /// Upgrades to a `DynGd<T, D>` pointer, enabling the `D` abstraction.
547    ///
548    /// The `D` parameter can typically be inferred when there is a single `AsDyn<...>` implementation for `T`.  \
549    /// Otherwise, use it as `gd.into_dyn::<dyn MyTrait>()`.
550    #[must_use]
551    pub fn into_dyn<D>(self) -> DynGd<T, D>
552    where
553        T: crate::obj::AsDyn<D> + Bounds<Declarer = bounds::DeclUser>,
554        D: ?Sized + 'static,
555    {
556        DynGd::<T, D>::from_gd(self)
557    }
558
559    /// Tries to upgrade to a `DynGd<T, D>` pointer, enabling the `D` abstraction.
560    ///
561    /// If `T`'s dynamic class doesn't implement `AsDyn<D>`, `Err(self)` is returned, meaning you can reuse the original
562    /// object for further casts.
563    pub fn try_dynify<D>(self) -> Result<DynGd<T, D>, Self>
564    where
565        T: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
566        D: ?Sized + 'static,
567    {
568        match try_dynify_object(self) {
569            Ok(dyn_gd) => Ok(dyn_gd),
570            Err((_convert_err, obj)) => Err(obj),
571        }
572    }
573
574    /// Returns a callable referencing a method from this object named `method_name`.
575    ///
576    /// This is shorter syntax for [`Callable::from_object_method(self, method_name)`][Callable::from_object_method].
577    pub fn callable(&self, method_name: impl AsArg<StringName>) -> Callable {
578        Callable::from_object_method(self, method_name)
579    }
580
581    /// Creates a new callable linked to the given object from **single-threaded** Rust function or closure.
582    /// This is shorter syntax for [`Callable::from_linked_fn()`].
583    ///
584    /// `name` is used for the string representation of the closure, which helps with debugging.
585    ///
586    /// Such a callable will be automatically invalidated by Godot when a linked Object is freed.
587    /// If you need a Callable which can live indefinitely, use [`Callable::from_fn()`].
588    pub fn linked_callable<R, F>(
589        &self,
590        method_name: impl Into<crate::builtin::CowStr>,
591        rust_function: F,
592    ) -> Callable
593    where
594        R: ToGodot,
595        F: 'static + FnMut(&[&Variant]) -> R,
596    {
597        Callable::from_linked_fn(method_name, self, rust_function)
598    }
599
600    pub(crate) unsafe fn from_obj_sys_or_none(
601        ptr: sys::GDExtensionObjectPtr,
602    ) -> Result<Self, ConvertError> {
603        unsafe {
604            // Used to have a flag to select RawGd::from_obj_sys_weak(ptr) for Base::to_init_gd(), but solved differently in the end.
605            let obj = RawGd::from_obj_sys(ptr);
606
607            Self::try_from_ffi(obj)
608        }
609    }
610
611    /// Initializes this `Gd<T>` from the object pointer as a **strong ref**, meaning it initializes/increments the reference counter and keeps
612    /// the object alive.
613    ///
614    /// This is the default for most initializations from FFI. In cases where the reference counter should explicitly **not** be updated,
615    /// [`Self::from_obj_sys_weak`] is available.
616    ///
617    /// # Safety
618    /// `ptr` must point to a valid object of this type.
619    pub(crate) unsafe fn from_obj_sys(ptr: sys::GDExtensionObjectPtr) -> Self {
620        sys::strict_assert!(
621            !ptr.is_null(),
622            "Gd::from_obj_sys() called with null pointer"
623        );
624
625        unsafe { Self::from_obj_sys_or_none(ptr) }.unwrap()
626    }
627
628    /// # Safety
629    /// `ptr` must point to a valid object of this type, or null.
630    pub(crate) unsafe fn from_obj_sys_weak_or_none(
631        ptr: sys::GDExtensionObjectPtr,
632    ) -> Result<Self, ConvertError> {
633        unsafe { Self::try_from_ffi(RawGd::from_obj_sys_weak(ptr)) }
634    }
635
636    /// # Safety
637    /// `ptr` must point to a valid object of this type.
638    pub(crate) unsafe fn from_obj_sys_weak(ptr: sys::GDExtensionObjectPtr) -> Self {
639        unsafe { Self::from_obj_sys_weak_or_none(ptr).unwrap() }
640    }
641
642    #[cfg(feature = "trace")] // itest only.
643    #[doc(hidden)]
644    pub unsafe fn __from_obj_sys_weak(ptr: sys::GDExtensionObjectPtr) -> Self {
645        unsafe { Self::from_obj_sys_weak(ptr) }
646    }
647
648    #[doc(hidden)]
649    pub fn obj_sys(&self) -> sys::GDExtensionObjectPtr {
650        self.raw.obj_sys()
651    }
652
653    #[doc(hidden)]
654    pub fn script_sys(&self) -> sys::GDExtensionScriptLanguagePtr
655    where
656        T: Inherits<classes::ScriptLanguage>,
657    {
658        self.raw.script_sys()
659    }
660
661    /// Runs `init_fn` on the address of a pointer (initialized to null). If that pointer is still null after the `init_fn` call,
662    /// then `None` will be returned; otherwise `Gd::from_obj_sys(ptr)`.
663    ///
664    /// This method will **NOT** increment the reference-count of the object, as it assumes the input to come from a Godot API
665    /// return value.
666    ///
667    /// # Safety
668    /// `init_fn` must be a function that correctly handles a _type pointer_ pointing to an _object pointer_.
669    #[doc(hidden)]
670    pub unsafe fn from_sys_init_opt(init_fn: impl FnOnce(sys::GDExtensionTypePtr)) -> Option<Self> {
671        // TODO(uninit) - should we use GDExtensionUninitializedTypePtr instead? Then update all the builtin codegen...
672        let init_fn = |ptr| {
673            init_fn(sys::SysPtr::force_init(ptr));
674        };
675
676        // Note: see _call_native_mb_ret_obj() in godot-cpp, which does things quite different (e.g. querying the instance binding).
677
678        // Initialize pointer with given function. Return Some(ptr) on success, and None otherwise.
679        // SAFETY: init_fn takes a type-ptr pointing to an object-ptr.
680        let object_ptr = unsafe { super::raw_object_init(init_fn) };
681
682        // Do not increment ref-count; assumed to be return value from FFI.
683        sys::ptr_then(object_ptr, |ptr| unsafe { Gd::from_obj_sys_weak(ptr) })
684    }
685
686    /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
687    ///
688    /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred]. The closure receives
689    /// `&mut Self` allowing direct access to Rust fields and methods.
690    ///
691    /// This method is only available for user-defined classes with a `Base<T>` field.
692    /// For engine classes, use [`run_deferred_gd()`][Self::run_deferred_gd] instead.
693    ///
694    /// See also [`WithBaseField::run_deferred()`] if you are within an `impl` block and have access to `self`.
695    ///
696    /// # Panics
697    /// If called outside the main thread.
698    pub fn run_deferred<F>(&mut self, mut_self_method: F)
699    where
700        T: WithBaseField,
701        F: FnOnce(&mut T) + 'static,
702    {
703        self.run_deferred_gd(move |mut gd| {
704            let mut guard = gd.bind_mut();
705            mut_self_method(&mut *guard);
706        });
707    }
708
709    /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
710    ///
711    /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred]. The closure receives
712    /// `Gd<T>`, which can be used to call engine methods or [`bind()`][Gd::bind]/[`bind_mut()`][Gd::bind_mut] to access the Rust object.
713    ///
714    /// See also [`WithBaseField::run_deferred_gd()`] if you are within an `impl` block and have access to `self`.
715    ///
716    /// # Panics
717    /// If called outside the main thread.
718    pub fn run_deferred_gd<F>(&mut self, gd_function: F)
719    where
720        F: FnOnce(Gd<T>) + 'static,
721    {
722        let obj = self.clone();
723        assert!(
724            is_main_thread(),
725            "`run_deferred` must be called on the main thread"
726        );
727
728        let callable = Callable::from_once_fn("run_deferred", move |_| {
729            gd_function(obj);
730        });
731        callable.call_deferred(&[]);
732    }
733}
734
735/// _The methods in this impl block are only available for objects `T` that are manually managed,
736/// i.e. anything that is not `RefCounted` or inherited from it._ <br><br>
737impl<T> Gd<T>
738where
739    T: GodotClass + Bounds<Memory = bounds::MemManual>,
740{
741    /// Destroy the manually-managed Godot object.
742    ///
743    /// Consumes this smart pointer and renders all other `Gd` smart pointers (as well as any GDScript references) to the same object
744    /// immediately invalid. Using those `Gd` instances will lead to panics, but not undefined behavior.
745    ///
746    /// This operation is **safe** and effectively prevents double-free.
747    ///
748    /// Not calling `free()` on manually-managed instances causes memory leaks, unless their ownership is delegated, for
749    /// example to the node tree in case of nodes.
750    ///
751    /// # Panics
752    /// - When the referred-to object has already been destroyed.
753    /// - When this is invoked on an upcast `Gd<Object>` that dynamically points to a reference-counted type (i.e. operation not supported).
754    /// - When the object is bound by an ongoing `bind()` or `bind_mut()` call (through a separate `Gd` pointer).
755    pub fn free(self) {
756        // Note: this method is NOT invoked when the free() call happens dynamically (e.g. through GDScript or reflection).
757        // As such, do not use it for operations and validations to perform upon destruction.
758
759        // free() is likely to be invoked in destructors during panic unwind. In this case, we cannot panic again.
760        // Instead, we print an error and exit free() immediately. The closure is supposed to be used in a unit return statement.
761        let is_panic_unwind = std::thread::panicking();
762        let error_or_panic = |msg: String| {
763            if is_panic_unwind {
764                if crate::private::has_error_print_level(1) {
765                    crate::godot_error!(
766                        "Encountered 2nd panic in free() during panic unwind; will skip destruction:\n{msg}"
767                    );
768                }
769            } else {
770                panic!("{}", msg);
771            }
772        };
773
774        // TODO disallow for singletons, either only at runtime or both at compile time (new memory policy) and runtime
775        use bounds::Declarer;
776
777        // Runtime check in case of T=Object, no-op otherwise
778        let ref_counted =
779            <<T as Bounds>::DynMemory as bounds::DynMemory>::is_ref_counted(&self.raw);
780        if ref_counted == Some(true) {
781            return error_or_panic(format!(
782                "Called free() on Gd<Object> which points to a RefCounted dynamic type; free() only supported for manually managed types\n\
783                Object: {self:?}"
784            ));
785        }
786
787        // If ref_counted returned None, that means the instance was destroyed
788        if ref_counted != Some(false) || (cfg!(safeguards_balanced) && !self.is_instance_valid()) {
789            return error_or_panic("called free() on already destroyed object".to_string());
790        }
791
792        // If the object is still alive, make sure the dynamic type matches. Necessary because subsequent checks may rely on the
793        // static type information to be correct. This is a no-op in Release mode.
794        // Skip check during panic unwind; would need to rewrite whole thing to use Result instead. Having BOTH panic-in-panic and bad type is
795        // a very unlikely corner case.
796        #[cfg(safeguards_strict)] #[cfg_attr(published_docs, doc(cfg(safeguards_strict)))]
797        if !is_panic_unwind {
798            self.raw
799                .check_dynamic_type(&crate::meta::CallContext::gd::<T>("free"));
800        }
801
802        // SAFETY: object must be alive, which was just checked above. No multithreading here.
803        // Also checked in the C free_instance_func callback, however error message can be more precise here, and we don't need to instruct
804        // the engine about object destruction. Both paths are tested.
805        let bound = unsafe { T::Declarer::is_currently_bound(&self.raw) };
806        if bound {
807            return error_or_panic(
808                "called free() while a bind() or bind_mut() call is active".to_string(),
809            );
810        }
811
812        // SAFETY: object alive as checked.
813        // This destroys the Storage instance, no need to run destructor again.
814        unsafe {
815            sys::interface_fn!(object_destroy)(self.raw.obj_sys());
816        }
817
818        // Deallocate associated data in Gd, without destroying the object pointer itself (already done above).
819        self.drop_weak()
820    }
821}
822
823/// _The methods in this impl block are only available for objects `T` that are reference-counted,
824/// i.e. anything that inherits `RefCounted`._ <br><br>
825impl<T> Gd<T>
826where
827    T: GodotClass + Bounds<Memory = bounds::MemRefCounted>,
828{
829    /// Makes sure that `self` does not share references with other `Gd` instances.
830    ///
831    /// Succeeds if the reference count is 1.
832    /// Otherwise, returns the shared object and its reference count.
833    ///
834    /// ## Example
835    ///
836    /// ```no_run
837    /// use godot::prelude::*;
838    ///
839    /// let obj = RefCounted::new_gd();
840    /// match obj.try_to_unique() {
841    ///    Ok(unique_obj) => {
842    ///        // No other Gd<T> shares a reference with `unique_obj`.
843    ///    },
844    ///    Err((shared_obj, ref_count)) => {
845    ///        // `shared_obj` is the original object `obj`.
846    ///        // `ref_count` is the total number of references (including one held by `shared_obj`).
847    ///    }
848    /// }
849    /// ```
850    pub fn try_to_unique(self) -> Result<Self, (Self, usize)> {
851        use crate::obj::bounds::DynMemory as _;
852
853        match <T as Bounds>::DynMemory::get_ref_count(&self.raw) {
854            Some(1) => Ok(self),
855            Some(ref_count) => Err((self, ref_count)),
856            None => unreachable!(),
857        }
858    }
859}
860
861impl<T> Gd<T>
862where
863    T: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
864{
865    /// Represents `null` when passing an object argument to Godot.
866    ///
867    /// This expression is only intended for function argument lists. It can be used whenever a Godot signature accepts
868    /// [`AsArg<Option<Gd<T>>>`][crate::meta::AsArg]. `Gd::null_arg()` as an argument is equivalent to `Option::<Gd<T>>::None`, but less wordy.
869    ///
870    /// To work with objects that can be null, use `Option<Gd<T>>` instead. For APIs that accept `Variant`, you can pass [`Variant::nil()`].
871    ///
872    /// # Nullability
873    /// <div class="warning">
874    /// The GDExtension API does not inform about nullability of its function parameters. It is up to you to verify that the arguments you pass
875    /// are only null when this is allowed. Doing this wrong should be safe, but can lead to the function call failing.
876    /// </div>
877    ///
878    /// # Example
879    /// ```no_run
880    /// # fn some_node() -> Gd<Node> { unimplemented!() }
881    /// use godot::prelude::*;
882    ///
883    /// let mut shape: Gd<Node> = some_node();
884    /// shape.set_owner(Gd::null_arg());
885    pub fn null_arg() -> impl AsArg<Option<Gd<T>>> {
886        meta::NullArg(std::marker::PhantomData)
887    }
888}
889
890impl<T> Gd<T>
891where
892    T: WithSignals,
893{
894    /// Access user-defined signals of this object.
895    ///
896    /// For classes that have at least one `#[signal]` defined, returns a collection of signal names. Each returned signal has a specialized
897    /// API for connecting and emitting signals in a type-safe way. This method is the equivalent of [`WithUserSignals::signals()`], but when
898    /// called externally (not from `self`). Furthermore, this is also available for engine classes, not just user-defined ones.
899    ///
900    /// When you are within the `impl` of a class, use `self.signals()` directly instead.
901    ///
902    /// If you haven't already, read the [book chapter about signals](https://godot-rust.github.io/book/register/signals.html) for a
903    /// walkthrough.
904    ///
905    /// [`WithUserSignals::signals()`]: crate::obj::WithUserSignals::signals()
906    pub fn signals(&self) -> T::SignalCollection<'_, T> {
907        T::__signals_from_external(self)
908    }
909}
910
911// ----------------------------------------------------------------------------------------------------------------------------------------------
912// Trait impls
913
914/// Dereferences to the nearest engine class, enabling direct calls to its `&self` methods.
915///
916/// For engine classes, returns `T` itself. For user classes, returns `T::Base` (the direct engine base class).
917/// The bound ensures that the target is always an engine-provided class.
918impl<T: GodotClass> Deref for Gd<T>
919where
920    GdDerefTarget<T>: Bounds<Declarer = bounds::DeclEngine>,
921{
922    // Target is always an engine class:
923    // * if T is an engine class => T
924    // * if T is a user class => T::Base
925    type Target = GdDerefTarget<T>;
926
927    fn deref(&self) -> &Self::Target {
928        self.raw.as_target()
929    }
930}
931
932/// Mutably dereferences to the nearest engine class, enabling direct calls to its `&mut self` methods.
933///
934/// For engine classes, returns `T` itself. For user classes, returns `T::Base` (the direct engine base class).
935/// The bound ensures that the target is always an engine-provided class.
936impl<T: GodotClass> DerefMut for Gd<T>
937where
938    GdDerefTarget<T>: Bounds<Declarer = bounds::DeclEngine>,
939{
940    fn deref_mut(&mut self) -> &mut Self::Target {
941        self.raw.as_target_mut()
942    }
943}
944
945impl<T: GodotClass> GodotConvert for Gd<T> {
946    type Via = Gd<T>;
947
948    fn godot_shape() -> GodotShape {
949        use crate::meta::shape::ClassHeritage;
950
951        let heritage = if T::inherits::<classes::Resource>() {
952            ClassHeritage::Resource
953        } else if T::inherits::<classes::Node>() {
954            ClassHeritage::Node
955        } else {
956            ClassHeritage::Other
957        };
958
959        let class_id = T::class_id();
960        GodotShape::Class {
961            class_id,
962            heritage,
963            is_nullable: false,
964        }
965    }
966}
967
968impl<T: GodotClass> ToGodot for Gd<T> {
969    type Pass = meta::ByObject;
970
971    fn to_godot(&self) -> &Self {
972        // Note: Gd<T> never null, so no need to check raw.is_null().
973        self.raw.check_rtti("to_godot");
974        self
975    }
976}
977
978impl<T: GodotClass> FromGodot for Gd<T> {
979    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
980        Ok(via)
981    }
982}
983
984// Keep in sync with DynGd.
985impl<T: GodotClass> GodotType for Gd<T> {
986    // Some #[doc(hidden)] are repeated despite already declared in trait; some IDEs suggest in auto-complete otherwise.
987    type Ffi = RawGd<T>;
988
989    type ToFfi<'f>
990        = RefArg<'f, RawGd<T>>
991    where
992        Self: 'f;
993
994    #[doc(hidden)]
995    fn to_ffi(&self) -> Self::ToFfi<'_> {
996        RefArg::new(&self.raw)
997    }
998
999    #[doc(hidden)]
1000    fn into_ffi(self) -> Self::Ffi {
1001        self.raw
1002    }
1003
1004    fn try_from_ffi(raw: Self::Ffi) -> Result<Self, ConvertError> {
1005        if raw.is_null() {
1006            Err(FromFfiError::NullRawGd.into_error(raw))
1007        } else {
1008            Ok(Self { raw })
1009        }
1010    }
1011
1012    fn qualifies_as_special_none(from_variant: &Variant) -> bool {
1013        // Behavior in Godot 4.2 when unsetting an #[export]'ed property:
1014        // 🔁 reset button: passes null object pointer inside Variant (as expected).
1015        // 🧹 clear button: sends a NodePath with an empty string (!?).
1016
1017        // We recognize the latter case and return a Gd::null() instead of failing to convert the NodePath.
1018        if let Ok(node_path) = from_variant.try_to::<NodePath>()
1019            && node_path.is_empty()
1020        {
1021            return true;
1022        }
1023
1024        false
1025    }
1026
1027    fn as_object_arg(&self) -> meta::ObjectArg<'_> {
1028        meta::ObjectArg::from_gd(self)
1029    }
1030}
1031
1032impl<T: GodotClass> Element for Gd<T> {}
1033
1034impl<T: GodotClass> GodotNullableType for Gd<T> {
1035    fn ffi_null() -> RawGd<T> {
1036        RawGd::null()
1037    }
1038
1039    fn ffi_null_ref<'f>() -> RefArg<'f, RawGd<T>>
1040    where
1041        Self: 'f,
1042    {
1043        RefArg::null_ref()
1044    }
1045
1046    fn ffi_is_null(ffi: &RawGd<T>) -> bool {
1047        ffi.is_null()
1048    }
1049}
1050
1051impl<T: GodotClass> Element for Option<Gd<T>> {}
1052
1053impl<T> Default for Gd<T>
1054where
1055    T: cap::GodotDefault + Bounds<Memory = bounds::MemRefCounted>,
1056{
1057    /// Creates a default-constructed `T` inside a smart pointer.
1058    ///
1059    /// This is equivalent to the GDScript expression `T.new()`, and to the shorter Rust expression `T::new_gd()`.
1060    ///
1061    /// This trait is only implemented for reference-counted classes. Classes with manually-managed memory (e.g. `Node`) are not covered,
1062    /// because they need explicit memory management, and deriving `Default` has a high chance of the user forgetting to call `free()` on those.
1063    /// `T::new_alloc()` should be used for those instead.
1064    fn default() -> Self {
1065        T::__godot_default()
1066    }
1067}
1068
1069impl<T: GodotClass> Clone for Gd<T> {
1070    fn clone(&self) -> Self {
1071        out!("Gd::clone");
1072        Self {
1073            raw: self.raw.clone(),
1074        }
1075    }
1076}
1077
1078impl<T: GodotClass> SimpleVar for Gd<T> {}
1079
1080/// See [`Gd` Exporting](struct.Gd.html#exporting) section.
1081impl<T> Export for Option<Gd<T>>
1082where
1083    T: GodotClass + Bounds<Exportable = bounds::Yes>,
1084    Option<Gd<T>>: Var,
1085{
1086    #[doc(hidden)]
1087    fn as_node_class() -> Option<ClassId> {
1088        PropertyHintInfo::object_as_node_class::<T>()
1089    }
1090}
1091
1092impl<T: GodotClass> Default for OnEditor<Gd<T>> {
1093    fn default() -> Self {
1094        OnEditor::gd_invalid()
1095    }
1096}
1097
1098impl<T> GodotConvert for OnEditor<Gd<T>>
1099where
1100    T: GodotClass,
1101    Option<<Gd<T> as GodotConvert>::Via>: GodotType,
1102{
1103    type Via = Option<<Gd<T> as GodotConvert>::Via>;
1104
1105    fn godot_shape() -> GodotShape {
1106        Gd::<T>::godot_shape()
1107    }
1108}
1109
1110impl<T> Var for OnEditor<Gd<T>>
1111where
1112    T: GodotClass,
1113{
1114    // Not Option<...> -- accessing from Rust through Var trait should not expose larger API than OnEditor itself.
1115    type PubType = <Gd<T> as GodotConvert>::Via;
1116
1117    fn var_get(field: &Self) -> Self::Via {
1118        Self::get_property_inner(field)
1119    }
1120
1121    fn var_set(field: &mut Self, value: Self::Via) {
1122        Self::set_property_inner(field, value);
1123    }
1124
1125    fn var_pub_get(field: &Self) -> Self::PubType {
1126        Self::var_get(field).expect("generated #[var(pub)] getter: uninitialized OnEditor<Gd<T>>")
1127    }
1128
1129    fn var_pub_set(field: &mut Self, value: Self::PubType) {
1130        Self::var_set(field, Some(value))
1131    }
1132}
1133
1134/// See [`Gd` Exporting](struct.Gd.html#exporting) section.
1135impl<T> Export for OnEditor<Gd<T>>
1136where
1137    Self: Var,
1138    T: GodotClass + Bounds<Exportable = bounds::Yes>,
1139{
1140    #[doc(hidden)]
1141    fn as_node_class() -> Option<ClassId> {
1142        PropertyHintInfo::object_as_node_class::<T>()
1143    }
1144}
1145
1146impl<T: GodotClass> PartialEq for Gd<T> {
1147    /// ⚠️ Returns whether two `Gd` pointers point to the same object.
1148    ///
1149    /// # Panics
1150    /// When `self` or `other` is dead.
1151    fn eq(&self, other: &Self) -> bool {
1152        // Panics when one is dead
1153        self.instance_id() == other.instance_id()
1154    }
1155}
1156
1157impl<T: GodotClass> Eq for Gd<T> {}
1158
1159impl<T: GodotClass> Display for Gd<T> {
1160    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1161        classes::display_string(self, f)
1162    }
1163}
1164
1165impl<T: GodotClass> Debug for Gd<T> {
1166    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1167        classes::debug_string(self, f, "Gd")
1168    }
1169}
1170
1171impl<T: GodotClass> std::hash::Hash for Gd<T> {
1172    /// ⚠️ Hashes this object based on its instance ID.
1173    ///
1174    /// # Panics
1175    /// When `self` is dead.
1176    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1177        self.instance_id().hash(state);
1178    }
1179}
1180
1181// Gd unwinding across panics does not invalidate any invariants;
1182// its mutability is anyway present, in the Godot engine.
1183impl<T: GodotClass> std::panic::UnwindSafe for Gd<T> {}
1184impl<T: GodotClass> std::panic::RefUnwindSafe for Gd<T> {}