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