/**************************************************************************/
/*  object.h                                                              */
/**************************************************************************/
/*                         This file is part of:                          */
/*                             GODOT ENGINE                               */
/*                        https://godotengine.org                         */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.                  */
/*                                                                        */
/* Permission is hereby granted, free of charge, to any person obtaining  */
/* a copy of this software and associated documentation files (the        */
/* "Software"), to deal in the Software without restriction, including    */
/* without limitation the rights to use, copy, modify, merge, publish,    */
/* distribute, sublicense, and/or sell copies of the Software, and to     */
/* permit persons to whom the Software is furnished to do so, subject to  */
/* the following conditions:                                              */
/*                                                                        */
/* The above copyright notice and this permission notice shall be         */
/* included in all copies or substantial portions of the Software.        */
/*                                                                        */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,        */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF     */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY   */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,   */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE      */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                 */
/**************************************************************************/

#pragma once

#include "core/extension/gdextension_interface.gen.h"
#include "core/object/gdtype.h"
#include "core/object/method_info.h"
#include "core/object/object_id.h"
#include "core/object/property_info.h"
#include "core/os/mutex.h"
#include "core/os/spin_lock.h"
#include "core/templates/hash_map.h"
#include "core/templates/hash_set.h"
#include "core/templates/list.h"
#include "core/templates/safe_refcount.h"
#include "core/variant/variant.h"

#define ADD_SIGNAL(m_signal) get_gdtype_static_mutable().add_signal(m_signal)
#define ADD_PROPERTY(m_property, m_setter, m_getter) ::ClassDB::add_property(get_class_static(), m_property, StringName(m_setter), StringName(m_getter))
#define ADD_PROPERTYI(m_property, m_setter, m_getter, m_index) ::ClassDB::add_property(get_class_static(), m_property, StringName(m_setter), StringName(m_getter), m_index)
#define ADD_PROPERTY_DEFAULT(m_property, m_default) ::ClassDB::set_property_default_value(get_class_static(), m_property, m_default)
#define ADD_GROUP(m_name, m_prefix) ::ClassDB::add_property_group(get_class_static(), m_name, m_prefix)
#define ADD_GROUP_INDENT(m_name, m_prefix, m_depth) ::ClassDB::add_property_group(get_class_static(), m_name, m_prefix, m_depth)
#define ADD_SUBGROUP(m_name, m_prefix) ::ClassDB::add_property_subgroup(get_class_static(), m_name, m_prefix)
#define ADD_SUBGROUP_INDENT(m_name, m_prefix, m_depth) ::ClassDB::add_property_subgroup(get_class_static(), m_name, m_prefix, m_depth)
#define ADD_LINKED_PROPERTY(m_property, m_linked_property) ::ClassDB::add_linked_property(get_class_static(), m_property, m_linked_property)

#ifdef TOOLS_ENABLED
#define ADD_CLASS_DEPENDENCY(m_class) ::ClassDB::add_class_dependency(get_class_static(), m_class)
#else
#define ADD_CLASS_DEPENDENCY(m_class)
#endif

#define ADD_ARRAY_COUNT(m_label, m_count_property, m_count_property_setter, m_count_property_getter, m_prefix) ClassDB::add_property_array_count(get_class_static(), m_label, m_count_property, StringName(m_count_property_setter), StringName(m_count_property_getter), m_prefix)
#define ADD_ARRAY_COUNT_WITH_USAGE_FLAGS(m_label, m_count_property, m_count_property_setter, m_count_property_getter, m_prefix, m_property_usage_flags) ClassDB::add_property_array_count(get_class_static(), m_label, m_count_property, StringName(m_count_property_setter), StringName(m_count_property_getter), m_prefix, m_property_usage_flags)
#define ADD_ARRAY(m_array_path, m_prefix) ClassDB::add_property_array(get_class_static(), m_array_path, m_prefix)

// Helper macro to use with PROPERTY_HINT_ARRAY_TYPE for arrays of specific resources:
// PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font")
#define MAKE_RESOURCE_TYPE_HINT(m_type) vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, m_type)

// API used to extend in GDExtension and other C compatible compiled languages.
class MethodBind;
class GDExtension;

struct ObjectGDExtension {
	GDExtension *library = nullptr;
	ObjectGDExtension *parent = nullptr;
	List<ObjectGDExtension *> children;
	StringName parent_class_name;
	StringName class_name;
	bool editor_class = false;
	bool reloadable = false;
	bool is_virtual = false;
	bool is_abstract = false;
	bool is_exposed = true;
#ifdef TOOLS_ENABLED
	bool is_runtime = false;
	bool is_placeholder = false;
#endif
#ifndef DISABLE_DEPRECATED
	bool legacy_unexposed_class = false;
#endif // DISABLE_DEPRECATED
	GDExtensionClassSet set;
	GDExtensionClassGet get;
	GDExtensionClassGetPropertyList get_property_list;
	GDExtensionClassFreePropertyList2 free_property_list2;
	GDExtensionClassPropertyCanRevert property_can_revert;
	GDExtensionClassPropertyGetRevert property_get_revert;
	GDExtensionClassValidateProperty validate_property;
#ifndef DISABLE_DEPRECATED
	GDExtensionClassNotification notification;
	GDExtensionClassFreePropertyList free_property_list;
#endif // DISABLE_DEPRECATED
	GDExtensionClassNotification2 notification2;
	GDExtensionClassToString to_string;
	GDExtensionClassReference reference;
	GDExtensionClassReference unreference;
	GDExtensionClassGetRID get_rid;

	void *class_userdata = nullptr;

#ifndef DISABLE_DEPRECATED
	GDExtensionClassCreateInstance create_instance;
	GDExtensionClassCreateInstance2 create_instance2; // Without refcount.
#endif // DISABLE_DEPRECATED
	GDExtensionClassCreateInstance3 create_instance3;
	GDExtensionClassFreeInstance free_instance;
#ifndef DISABLE_DEPRECATED
	GDExtensionClassGetVirtual get_virtual;
	GDExtensionClassGetVirtualCallData get_virtual_call_data;
#endif // DISABLE_DEPRECATED
	GDExtensionClassGetVirtual2 get_virtual2;
	GDExtensionClassGetVirtualCallData2 get_virtual_call_data2;
	GDExtensionClassCallVirtualWithData call_virtual_with_data;
	GDExtensionClassRecreateInstance recreate_instance;

#ifdef TOOLS_ENABLED
	void *tracking_userdata = nullptr;
	void (*track_instance)(void *p_userdata, void *p_instance) = nullptr;
	void (*untrack_instance)(void *p_userdata, void *p_instance) = nullptr;
#endif

	/// A type for this Object extension.
	/// This is not exposed through the GDExtension API (yet) so it is inferred from above parameters.
	GDType *gdtype;
	void create_gdtype();
	void destroy_gdtype();

	~ObjectGDExtension();
};

#define GDVIRTUAL_CALL(m_name, ...) _gdvirtual_##m_name##_call(__VA_ARGS__)
#define GDVIRTUAL_CALL_PTR(m_obj, m_name, ...) m_obj->_gdvirtual_##m_name##_call(__VA_ARGS__)

#ifdef DEBUG_ENABLED
#define GDVIRTUAL_BIND(m_name, ...) ::ClassDB::add_virtual_method(get_class_static(), _gdvirtual_##m_name##_get_method_info(), true, sarray(__VA_ARGS__));
#else
#define GDVIRTUAL_BIND(m_name, ...)
#endif // DEBUG_ENABLED
#define GDVIRTUAL_BIND_COMPAT(m_alias, ...) ::ClassDB::add_virtual_compatibility_method(get_class_static(), _gdvirtual_##m_alias##_get_method_info(), true, sarray(__VA_ARGS__));
#define GDVIRTUAL_IS_OVERRIDDEN(m_name) _gdvirtual_##m_name##_overridden()
#define GDVIRTUAL_IS_OVERRIDDEN_PTR(m_obj, m_name) m_obj->_gdvirtual_##m_name##_overridden()

/*
 * The following is an incomprehensible blob of hacks and workarounds to
 * compensate for many of the fallacies in C++. As a plus, this macro pretty
 * much alone defines the object model.
 */

/// Provides `Object` functionality, such as being able to use `Object::cast_to()`.
/// Use this for `Object` subclasses that are not registered in `ClassDB` (use `GDCLASS` otherwise).
#define GDSOFTCLASS(m_class, m_inherits) \
public: \
	using self_type = m_class; \
	using super_type = m_inherits; \
	static _FORCE_INLINE_ void *get_class_ptr_static() { \
		static int ptr; \
		return &ptr; \
	} \
	virtual bool is_class_ptr(void *p_ptr) const override { \
		return (p_ptr == get_class_ptr_static()) || m_inherits::is_class_ptr(p_ptr); \
	} \
\
protected: \
	_FORCE_INLINE_ bool (Object::*_get_get() const)(const StringName &p_name, Variant &) const { \
		return (bool (Object::*)(const StringName &, Variant &) const) & m_class::_get; \
	} \
	virtual bool _getv(const StringName &p_name, Variant &r_ret) const override { \
		if (m_class::_get_get() != m_inherits::_get_get()) { \
			if (_get(p_name, r_ret)) { \
				return true; \
			} \
		} \
		return m_inherits::_getv(p_name, r_ret); \
	} \
	_FORCE_INLINE_ bool (Object::*_get_set() const)(const StringName &p_name, const Variant &p_property) { \
		return (bool (Object::*)(const StringName &, const Variant &)) & m_class::_set; \
	} \
	virtual bool _setv(const StringName &p_name, const Variant &p_property) override { \
		if (m_inherits::_setv(p_name, p_property)) { \
			return true; \
		} \
		if (m_class::_get_set() != m_inherits::_get_set()) { \
			return _set(p_name, p_property); \
		} \
		return false; \
	} \
	_FORCE_INLINE_ void (Object::*_get_validate_property() const)(PropertyInfo & p_property) const { \
		return (void (Object::*)(PropertyInfo &) const) & m_class::_validate_property; \
	} \
	virtual void _validate_propertyv(PropertyInfo &p_property) const override { \
		m_inherits::_validate_propertyv(p_property); \
		if (m_class::_get_validate_property() != m_inherits::_get_validate_property()) { \
			_validate_property(p_property); \
		} \
	} \
	_FORCE_INLINE_ bool (Object::*_get_property_can_revert() const)(const StringName &p_name) const { \
		return (bool (Object::*)(const StringName &) const) & m_class::_property_can_revert; \
	} \
	virtual bool _property_can_revertv(const StringName &p_name) const override { \
		if (m_class::_get_property_can_revert() != m_inherits::_get_property_can_revert()) { \
			if (_property_can_revert(p_name)) { \
				return true; \
			} \
		} \
		return m_inherits::_property_can_revertv(p_name); \
	} \
	_FORCE_INLINE_ bool (Object::*_get_property_get_revert() const)(const StringName &p_name, Variant &) const { \
		return (bool (Object::*)(const StringName &, Variant &) const) & m_class::_property_get_revert; \
	} \
	virtual bool _property_get_revertv(const StringName &p_name, Variant &r_ret) const override { \
		if (m_class::_get_property_get_revert() != m_inherits::_get_property_get_revert()) { \
			if (_property_get_revert(p_name, r_ret)) { \
				return true; \
			} \
		} \
		return m_inherits::_property_get_revertv(p_name, r_ret); \
	} \
	_FORCE_INLINE_ void (Object::*_get_notification() const)(int) { \
		return (void (Object::*)(int)) & m_class::_notification; \
	} \
	virtual void _notification_forwardv(int p_notification) override { \
		m_inherits::_notification_forwardv(p_notification); \
		if (m_class::_get_notification() != m_inherits::_get_notification()) { \
			_notification(p_notification); \
		} \
	} \
	virtual void _notification_backwardv(int p_notification) override { \
		if (m_class::_get_notification() != m_inherits::_get_notification()) { \
			_notification(p_notification); \
		} \
		m_inherits::_notification_backwardv(p_notification); \
	} \
\
private:

/// Provides `Object` functionality, such as being able to use `Object::cast_to()`, and `ClassDB` integration.
/// Use this for `Object` subclasses that are registered in `ClassDB` (use `GDSOFTCLASS` otherwise).
#define GDCLASS(m_class, m_inherits) \
	GDSOFTCLASS(m_class, m_inherits) \
private: \
	void operator=(const m_class &p_rval) {} \
	friend class ::ClassDB; \
\
	static GDType &get_gdtype_static_mutable() { \
		static GDType *gdtype = nullptr; \
		static bool initialized = false; \
		if (likely(initialized)) { \
			return *gdtype; \
		} \
\
		static BinaryMutex __init_mutex; \
		MutexLock lock(__init_mutex); \
		if (initialized) { \
			return *gdtype; \
		} \
		gdtype = memnew(GDType(&super_type::get_gdtype_static(), StringName(#m_class))); \
		m_class::autorelease_gdtype(&gdtype); \
		initialized = true; \
		return *gdtype; \
	} \
\
public: \
	virtual const GDType &_get_typev() const override { \
		return get_gdtype_static(); \
	} \
	static const GDType &get_gdtype_static() { \
		return get_gdtype_static_mutable(); \
	} \
	static const StringName &get_class_static() { \
		return get_gdtype_static().get_name(); \
	} \
\
protected: \
	_FORCE_INLINE_ static void (*_get_bind_methods())() { \
		return &m_class::_bind_methods; \
	} \
	_FORCE_INLINE_ static void (*_get_bind_compatibility_methods())() { \
		return &m_class::_bind_compatibility_methods; \
	} \
\
public: \
	static void initialize_class() { \
		static bool initialized = false; \
		if (likely(initialized)) { \
			return; \
		} \
\
		static BinaryMutex __init_mutex; \
		MutexLock lock(__init_mutex); \
		if (initialized) { \
			return; \
		} \
		m_inherits::initialize_class(); \
		_add_class_to_classdb(get_gdtype_static_mutable(), &super_type::get_gdtype_static()); \
		get_gdtype_static_mutable().initialize(); \
		if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods()) { \
			_bind_methods(); \
		} \
		if (m_class::_get_bind_compatibility_methods() != m_inherits::_get_bind_compatibility_methods()) { \
			_bind_compatibility_methods(); \
		} \
		initialized = true; \
	} \
\
protected: \
	virtual void _initialize_classv() override { \
		initialize_class(); \
	} \
	_FORCE_INLINE_ void (Object::*_get_get_property_list() const)(List<PropertyInfo> * p_list) const { \
		return (void (Object::*)(List<PropertyInfo> *) const) & m_class::_get_property_list; \
	} \
	virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const override { \
		if (!p_reversed) { \
			m_inherits::_get_property_listv(p_list, p_reversed); \
		} \
		p_list->push_back(PropertyInfo(Variant::NIL, get_class_static(), PROPERTY_HINT_NONE, get_class_static(), PROPERTY_USAGE_CATEGORY)); \
		_get_property_list_from_classdb(#m_class, p_list, true, this); \
		if (m_class::_get_get_property_list() != m_inherits::_get_get_property_list()) { \
			_get_property_list(p_list); \
		} \
		if (p_reversed) { \
			m_inherits::_get_property_listv(p_list, p_reversed); \
		} \
	} \
\
private:

#define OBJ_SAVE_TYPE(m_class) \
public: \
	virtual String get_save_class() const override { \
		return #m_class; \
	} \
\
private:

class ClassDB;
class ScriptInstance;

class Object {
public:
	typedef Object self_type;

	enum ConnectFlags {
		CONNECT_DEFERRED = 1,
		CONNECT_PERSIST = 2, // Hint for scene to save this connection.
		CONNECT_ONE_SHOT = 4,
		CONNECT_REFERENCE_COUNTED = 8,
		CONNECT_APPEND_SOURCE_OBJECT = 16,
		CONNECT_INHERITED = 32, // Used in editor builds.
	};

	// Store on each object a bitfield to quickly test whether it is derived from some "key" classes
	// that are commonly tested in performance sensitive code.
	// Ensure unsigned to bitpack.
	enum class AncestralClass : unsigned int {
		REF_COUNTED = 1 << 0,
		NODE = 1 << 1,
		RESOURCE = 1 << 2,
		SCRIPT = 1 << 3,

		CANVAS_ITEM = 1 << 4,
		CONTROL = 1 << 5,
		NODE_2D = 1 << 6,
		COLLISION_OBJECT_2D = 1 << 7,
		AREA_2D = 1 << 8,

		NODE_3D = 1 << 9,
		VISUAL_INSTANCE_3D = 1 << 10,
		GEOMETRY_INSTANCE_3D = 1 << 11,
		COLLISION_OBJECT_3D = 1 << 12,
		PHYSICS_BODY_3D = 1 << 13,
		MESH_INSTANCE_3D = 1 << 14,
	};

	static constexpr AncestralClass static_ancestral_class = (AncestralClass)0;

	struct Connection {
		::Signal signal;
		Callable callable;

		uint32_t flags = 0;
		bool operator<(const Connection &p_conn) const;

		operator Variant() const;

		Connection() {}
		Connection(const Variant &p_variant);
	};

private:
#ifdef DEBUG_ENABLED
	friend struct _ObjectDebugLock;
#endif // DEBUG_ENABLED
	friend struct ObjectSignalLock;
	friend bool predelete_handler(Object *);
	friend void postinitialize_handler(Object *);

	ObjectGDExtension *_extension = nullptr;
	GDExtensionClassInstancePtr _extension_instance = nullptr;

	struct SignalData {
		struct Slot {
			int reference_count = 0;
			Connection conn;
			List<Connection>::Element *cE = nullptr;
		};

		MethodInfo user;
		HashMap<Callable, Slot> slot_map;
		bool removable = false;
	};
	mutable Mutex *signal_mutex = nullptr;
	HashMap<StringName, SignalData> signal_map;
	List<Connection> connections;
#ifdef DEBUG_ENABLED
	SafeRefCount _lock_index;
#endif // DEBUG_ENABLED
	ObjectID _instance_id;
	bool _predelete();
	void _initialize();
	void _postinitialize();

	uint32_t _ancestry : 15;

	bool _block_signals : 1;
	bool _can_translate : 1;
	bool _emitting : 1;
	bool _predelete_ok : 1;

public:
	bool _is_queued_for_deletion : 1; // Set to true by SceneTree::queue_delete().

private:
#ifdef TOOLS_ENABLED
	bool _edited : 1;
	uint32_t _edited_version = 0;
	HashSet<String> editor_section_folding;
#endif
	ScriptInstance *script_instance = nullptr;
	HashMap<StringName, Variant> metadata;
	HashMap<StringName, Variant *> metadata_properties;
	mutable const GDType *_gdtype_ptr = nullptr;
	void _reset_gdtype() const;

	static GDType &get_gdtype_static_mutable() {
		static GDType *gdtype = nullptr;
		static bool initialized = false;
		if (likely(initialized)) {
			return *gdtype;
		}

		static BinaryMutex __init_mutex;
		MutexLock lock(__init_mutex);
		if (initialized) {
			return *gdtype;
		}
		gdtype = memnew(GDType(nullptr, StringName("Object")));
		autorelease_gdtype(&gdtype);
		initialized = true;
		return *gdtype;
	}

	void _add_user_signal(const String &p_name, const Array &p_args = Array());
	bool _has_user_signal(const StringName &p_name) const;
	void _remove_user_signal(const StringName &p_name);
	Error _emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
	TypedArray<Dictionary> _get_signal_list() const;
	TypedArray<Dictionary> _get_signal_connection_list(const StringName &p_signal) const;
	TypedArray<Dictionary> _get_incoming_connections() const;
	void _set_bind(const StringName &p_set, const Variant &p_value);
	Variant _get_bind(const StringName &p_name) const;
	void _set_indexed_bind(const NodePath &p_name, const Variant &p_value);
	Variant _get_indexed_bind(const NodePath &p_name) const;
	int _get_method_argument_count_bind(const StringName &p_name) const;

	_FORCE_INLINE_ void _construct_object(bool p_reference);

	friend class RefCounted;

	BinaryMutex _instance_binding_mutex;
	struct InstanceBinding {
		void *binding = nullptr;
		void *token = nullptr;
		GDExtensionInstanceBindingFreeCallback free_callback = nullptr;
		GDExtensionInstanceBindingReferenceCallback reference_callback = nullptr;
	};
	InstanceBinding *_instance_bindings = nullptr;
	uint32_t _instance_binding_count = 0;

	Object(bool p_reference);

protected:
	StringName _translation_domain;

	_FORCE_INLINE_ bool _instance_binding_reference(bool p_reference) {
		bool can_die = true;
		if (_instance_bindings) {
			MutexLock instance_binding_lock(_instance_binding_mutex);
			for (uint32_t i = 0; i < _instance_binding_count; i++) {
				if (_instance_bindings[i].reference_callback) {
					if (!_instance_bindings[i].reference_callback(_instance_bindings[i].token, _instance_bindings[i].binding, p_reference)) {
						can_die = false;
					}
				}
			}
		}
		return can_die;
	}

	// Used in gdvirtual.gen.h
	void _gdvirtual_init_method_ptr(uint32_t p_compat_hash, void *&r_fn_ptr, const StringName &p_fn_name, bool p_compat) const;

	friend class GDExtensionMethodBind;
	_ALWAYS_INLINE_ const ObjectGDExtension *_get_extension() const { return _extension; }
	_ALWAYS_INLINE_ GDExtensionClassInstancePtr _get_extension_instance() const { return _extension_instance; }
	virtual void _initialize_classv() { initialize_class(); }
	virtual bool _setv(const StringName &p_name, const Variant &p_property) { return false; }
	virtual bool _getv(const StringName &p_name, Variant &r_property) const { return false; }
	virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const {}
	virtual void _validate_propertyv(PropertyInfo &p_property) const {}
	virtual bool _property_can_revertv(const StringName &p_name) const { return false; }
	virtual bool _property_get_revertv(const StringName &p_name, Variant &r_property) const { return false; }

	void _notification_forward(int p_notification);
	void _notification_backward(int p_notification);
	virtual void _notification_forwardv(int p_notification) {}
	virtual void _notification_backwardv(int p_notification) {}
	virtual String _to_string();

	static void _bind_methods();
	static void _bind_compatibility_methods();
	bool _set(const StringName &p_name, const Variant &p_property) { return false; }
	bool _get(const StringName &p_name, Variant &r_property) const { return false; }
	void _get_property_list(List<PropertyInfo> *p_list) const {}
	void _validate_property(PropertyInfo &p_property) const {}
	bool _property_can_revert(const StringName &p_name) const { return false; }
	bool _property_get_revert(const StringName &p_name, Variant &r_property) const { return false; }
	void _notification(int p_notification) {}

	_FORCE_INLINE_ static void (*_get_bind_methods())() {
		return &Object::_bind_methods;
	}
	_FORCE_INLINE_ static void (*_get_bind_compatibility_methods())() {
		return &Object::_bind_compatibility_methods;
	}
	_FORCE_INLINE_ bool (Object::*_get_get() const)(const StringName &p_name, Variant &r_ret) const {
		return &Object::_get;
	}
	_FORCE_INLINE_ bool (Object::*_get_set() const)(const StringName &p_name, const Variant &p_property) {
		return &Object::_set;
	}
	_FORCE_INLINE_ void (Object::*_get_get_property_list() const)(List<PropertyInfo> *p_list) const {
		return &Object::_get_property_list;
	}
	_FORCE_INLINE_ void (Object::*_get_validate_property() const)(PropertyInfo &p_property) const {
		return &Object::_validate_property;
	}
	_FORCE_INLINE_ bool (Object::*_get_property_can_revert() const)(const StringName &p_name) const {
		return &Object::_property_can_revert;
	}
	_FORCE_INLINE_ bool (Object::*_get_property_get_revert() const)(const StringName &p_name, Variant &) const {
		return &Object::_property_get_revert;
	}
	_FORCE_INLINE_ void (Object::*_get_notification() const)(int) {
		return &Object::_notification;
	}

	Variant _call_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
	Variant _call_deferred_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);

	static void autorelease_gdtype(GDType **r_type);

	virtual const GDType &_get_typev() const { return get_gdtype_static(); }

	TypedArray<StringName> _get_meta_list_bind() const;
	TypedArray<Dictionary> _get_property_list_bind() const;
	TypedArray<Dictionary> _get_method_list_bind() const;

	void _clear_internal_resource_paths(const Variant &p_var);

	friend class ::ClassDB;
	friend class PlaceholderExtensionInstance;

	static void _add_class_to_classdb(GDType &p_class, const GDType *p_inherits);
	static void _get_property_list_from_classdb(const StringName &p_class, List<PropertyInfo> *p_list, bool p_no_inheritance, const Object *p_validator);

	bool _disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force = false);
	void _define_ancestry(AncestralClass p_class) { _ancestry |= (uint32_t)p_class; }
	// Prefer using derives_from.
	bool _has_ancestry(AncestralClass p_class) const { return _ancestry & (uint32_t)p_class; }

	virtual bool _uses_signal_mutex() const;

	// Internal helper to get the current locale, taking into account the translation domain.
	String _get_locale() const;

#ifdef TOOLS_ENABLED
	struct VirtualMethodTracker {
		void **method;
		VirtualMethodTracker *next;
	};

	mutable VirtualMethodTracker *virtual_method_list = nullptr;
#endif

#ifndef DISABLE_DEPRECATED
	bool _is_class_bind_compat_118582(const String &p_name) const;
#endif

public: // Should be protected, but bug in clang++.
	static void initialize_class();
	_FORCE_INLINE_ static void register_custom_data_to_otdb() {}

public:
	void notify_property_list_changed();

	static void *get_class_ptr_static() {
		static int ptr;
		return &ptr;
	}

	void detach_from_objectdb();
	_FORCE_INLINE_ ObjectID get_instance_id() const { return _instance_id; }

	template <typename T, typename O>
	static T *cast_to(O *p_object) {
		// This is like dynamic_cast, but faster.
		// The reason is that we can assume no virtual and multiple inheritance.
		return p_object && p_object->template derives_from<T, O>() ? static_cast<T *>(p_object) : nullptr;
	}

	template <typename T, typename O>
	static const T *cast_to(const O *p_object) {
		return p_object && p_object->template derives_from<T, O>() ? static_cast<const T *>(p_object) : nullptr;
	}

	// cast_to versions for types that implicitly convert to Object.
	template <typename T>
	static T *cast_to(Object *p_object) {
		return p_object && p_object->template derives_from<T, Object>() ? static_cast<T *>(p_object) : nullptr;
	}

	template <typename T>
	static const T *cast_to(const Object *p_object) {
		return p_object && p_object->template derives_from<T, Object>() ? static_cast<const T *>(p_object) : nullptr;
	}

	enum {
		NOTIFICATION_POSTINITIALIZE = 0,
		NOTIFICATION_PREDELETE = 1,
		NOTIFICATION_EXTENSION_RELOADED = 2,
		// Internal notification to send after NOTIFICATION_PREDELETE, not bound to scripting.
		NOTIFICATION_PREDELETE_CLEANUP = 3,
	};

	/* TYPE API */
	static const GDType &get_gdtype_static() { return get_gdtype_static_mutable(); }

	const GDType &get_gdtype() const;

	static const StringName &get_class_static() { return get_gdtype_static().get_name(); }

	_FORCE_INLINE_ String get_class() const { return get_class_name(); }

	virtual String get_save_class() const { return get_class(); } //class stored when saving

	bool is_class(const StringName &p_class) const;
	virtual bool is_class_ptr(void *p_ptr) const { return get_class_ptr_static() == p_ptr; }

	template <typename T, typename O>
	bool derives_from() const;

	const StringName &get_class_name() const;

	StringName get_class_name_for_extension(const GDExtension *p_library) const;

	/* IAPI */

	void set(const StringName &p_name, const Variant &p_value, bool *r_valid = nullptr);
	Variant get(const StringName &p_name, bool *r_valid = nullptr) const;
	void set_indexed(const Vector<StringName> &p_names, const Variant &p_value, bool *r_valid = nullptr);
	Variant get_indexed(const Vector<StringName> &p_names, bool *r_valid = nullptr) const;

	void get_property_list(List<PropertyInfo> *p_list, bool p_reversed = false) const;
	void validate_property(PropertyInfo &p_property) const;
	bool property_can_revert(const StringName &p_name) const;
	Variant property_get_revert(const StringName &p_name) const;

	bool has_method(const StringName &p_method) const;
	int get_method_argument_count(const StringName &p_method, bool *r_is_valid = nullptr) const;
	void get_method_list(List<MethodInfo> *p_list) const;
	Variant callv(const StringName &p_method, const Array &p_args);
	virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
	virtual Variant call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);

	template <typename... VarArgs>
	Variant call(const StringName &p_method, VarArgs... p_args) {
		Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
		const Variant *argptrs[sizeof...(p_args) + 1];
		for (uint32_t i = 0; i < sizeof...(p_args); i++) {
			argptrs[i] = &args[i];
		}
		Callable::CallError cerr;
		const Variant ret = callp(p_method, sizeof...(p_args) == 0 ? nullptr : (const Variant **)argptrs, sizeof...(p_args), cerr);
		return (cerr.error == Callable::CallError::CALL_OK) ? ret : Variant();
	}

	// Depending on the boolean, we call either the virtual function _notification_backward or _notification_forward.
	// - Forward calls subclasses in descending order (e.g. Object -> Node -> Node3D -> extension -> script).
	//   Backward calls subclasses in descending order (e.g. script -> extension -> Node3D -> Node -> Object).
	_FORCE_INLINE_ void notification(int p_notification, bool p_reversed = false) {
		if (p_reversed) {
			_notification_backward(p_notification);
		} else {
			_notification_forward(p_notification);
		}
	}

	String to_string();

	// Used mainly by script, get and set all INCLUDING string.
	virtual Variant getvar(const Variant &p_key, bool *r_valid = nullptr) const;
	virtual void setvar(const Variant &p_key, const Variant &p_value, bool *r_valid = nullptr);

	/* SCRIPT */

// When in debug, some non-virtual functions can be overridden.
#ifdef DEBUG_ENABLED
#define DEBUG_VIRTUAL virtual
#else
#define DEBUG_VIRTUAL
#endif // DEBUG_ENABLED

	DEBUG_VIRTUAL void set_script(const Variant &p_script);
	DEBUG_VIRTUAL Variant get_script() const;

	DEBUG_VIRTUAL bool has_meta(const StringName &p_name) const;
	DEBUG_VIRTUAL void set_meta(const StringName &p_name, const Variant &p_value);
	DEBUG_VIRTUAL void remove_meta(const StringName &p_name);
	DEBUG_VIRTUAL Variant get_meta(const StringName &p_name, const Variant &p_default = Variant()) const;
	DEBUG_VIRTUAL void get_meta_list(List<StringName> *p_list) const;
	DEBUG_VIRTUAL void merge_meta_from(const Object *p_src);

#ifdef TOOLS_ENABLED
	void set_edited(bool p_edited);
	bool is_edited() const;
	// This function is used to check when something changed beyond a point, it's used mainly for generating previews.
	uint32_t get_edited_version() const;
#endif

	void set_script_instance(ScriptInstance *p_instance);
	_FORCE_INLINE_ ScriptInstance *get_script_instance() const { return script_instance; }

	void add_user_signal(const MethodInfo &p_signal);

	template <typename... VarArgs>
	Error emit_signal(const StringName &p_name, VarArgs... p_args) {
		Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
		const Variant *argptrs[sizeof...(p_args) + 1];
		for (uint32_t i = 0; i < sizeof...(p_args); i++) {
			argptrs[i] = &args[i];
		}
		return emit_signalp(p_name, sizeof...(p_args) == 0 ? nullptr : (const Variant **)argptrs, sizeof...(p_args));
	}

	DEBUG_VIRTUAL Error emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount);
	DEBUG_VIRTUAL bool has_signal(const StringName &p_name) const;
	DEBUG_VIRTUAL void get_signal_list(List<MethodInfo> *p_signals) const;
	DEBUG_VIRTUAL void get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const;
	DEBUG_VIRTUAL void get_all_signal_connections(List<Connection> *p_connections) const;
	DEBUG_VIRTUAL int get_persistent_signal_connection_count() const;
	DEBUG_VIRTUAL uint32_t get_signal_connection_flags(const StringName &p_name, const Callable &p_callable) const;
	DEBUG_VIRTUAL void get_signals_connected_to_this(List<Connection> *p_connections) const;

	DEBUG_VIRTUAL Error connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags = 0);
	DEBUG_VIRTUAL void disconnect(const StringName &p_signal, const Callable &p_callable);
	DEBUG_VIRTUAL bool is_connected(const StringName &p_signal, const Callable &p_callable) const;
	DEBUG_VIRTUAL bool has_connections(const StringName &p_signal) const;

	void call_deferredp(const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error = false);
	template <typename... VarArgs>
	void call_deferred(const StringName &p_name, VarArgs... p_args) {
		Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
		const Variant *argptrs[sizeof...(p_args) + 1];
		for (uint32_t i = 0; i < sizeof...(p_args); i++) {
			argptrs[i] = &args[i];
		}
		return call_deferredp(p_name, sizeof...(p_args) == 0 ? nullptr : (const Variant **)argptrs, sizeof...(p_args));
	}

	void set_deferred(const StringName &p_property, const Variant &p_value);

	void set_block_signals(bool p_block);
	bool is_blocking_signals() const;

	Variant::Type get_static_property_type(const StringName &p_property, bool *r_valid = nullptr) const;
	Variant::Type get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid = nullptr) const;

	// Translate message (internationalization).
	String tr(const StringName &p_message, const StringName &p_context = "") const;
	String tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context = "") const;

	bool is_queued_for_deletion() const;

	_FORCE_INLINE_ void set_message_translation(bool p_enable) { _can_translate = p_enable; }
	_FORCE_INLINE_ bool can_translate_messages() const { return _can_translate; }

	virtual StringName get_translation_domain() const;
	virtual void set_translation_domain(const StringName &p_domain);

#ifdef TOOLS_ENABLED
	virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
	void editor_set_section_unfold(const String &p_section, bool p_unfolded, bool p_initializing = false);
	bool editor_is_section_unfolded(const String &p_section);
	const HashSet<String> &editor_get_section_folding() const { return editor_section_folding; }
	void editor_clear_section_folding() { editor_section_folding.clear(); }
#endif

	// Used by script languages to store binding data.
	void *get_instance_binding(void *p_token, const GDExtensionInstanceBindingCallbacks *p_callbacks);
	// Used on creation by binding only.
	void set_instance_binding(void *p_token, void *p_binding, const GDExtensionInstanceBindingCallbacks *p_callbacks);
	bool has_instance_binding(void *p_token);
	void free_instance_binding(void *p_token);

#ifdef TOOLS_ENABLED
	void clear_internal_extension();
	void reset_internal_extension(ObjectGDExtension *p_extension);
	bool is_extension_placeholder() const { return _extension && _extension->is_placeholder; }
#endif

	void clear_internal_resource_paths();

	_ALWAYS_INLINE_ bool is_ref_counted() const { return _has_ancestry(AncestralClass::REF_COUNTED); }

	void cancel_free();

	Object();
	virtual ~Object();
};

bool predelete_handler(Object *p_object);
void postinitialize_handler(Object *p_object);

template <typename T, typename O>
bool Object::derives_from() const {
	if constexpr (std::is_base_of_v<T, O>) {
		// We derive statically from T (or are the same class), so casting to it is trivial.
		return true;
	} else {
		static_assert(std::is_base_of_v<Object, O>, "derives_from can only be used with Object subclasses.");
		static_assert(std::is_base_of_v<O, T>, "Cannot cast argument to T because T does not derive from the argument's known class.");
		static_assert(std::is_same_v<std::decay_t<T>, typename T::self_type>, "T must use GDCLASS or GDSOFTCLASS.");

		// If there is an explicitly set ancestral class on the type, we can use that.
		if constexpr (T::static_ancestral_class != T::super_type::static_ancestral_class) {
			return _has_ancestry(T::static_ancestral_class);
		} else {
			return is_class_ptr(T::get_class_ptr_static());
		}
	}
}

class ObjectDB {
// This needs to add up to 63, 1 bit is for reference.
#define OBJECTDB_VALIDATOR_BITS 39
#define OBJECTDB_VALIDATOR_MASK ((uint64_t(1) << OBJECTDB_VALIDATOR_BITS) - 1)
#define OBJECTDB_SLOT_MAX_COUNT_BITS 24
#define OBJECTDB_SLOT_MAX_COUNT_MASK ((uint64_t(1) << OBJECTDB_SLOT_MAX_COUNT_BITS) - 1)
#define OBJECTDB_REFERENCE_BIT (uint64_t(1) << (OBJECTDB_SLOT_MAX_COUNT_BITS + OBJECTDB_VALIDATOR_BITS))

	struct ObjectSlot { // 128 bits per slot.
		uint64_t validator : OBJECTDB_VALIDATOR_BITS;
		uint64_t next_free : OBJECTDB_SLOT_MAX_COUNT_BITS;
		uint64_t is_ref_counted : 1;
		Object *object = nullptr;
	};

	static SpinLock spin_lock;
	static uint32_t slot_count;
	static uint32_t slot_max;
	static ObjectSlot *object_slots;
	static uint64_t validator_counter;

	friend class Object;
	friend void unregister_core_types();
	static void cleanup();

	static ObjectID add_instance(Object *p_object);
	static void remove_instance(Object *p_object);

	friend void register_core_types();
	static void setup();

public:
	typedef void (*DebugFunc)(Object *p_obj, void *p_user_data);

	_ALWAYS_INLINE_ static Object *get_instance(ObjectID p_instance_id) {
		uint64_t id = p_instance_id;
		uint32_t slot = id & OBJECTDB_SLOT_MAX_COUNT_MASK;

		ERR_FAIL_COND_V(slot >= slot_max, nullptr); // This should never happen unless RID is corrupted.

		spin_lock.lock();

		uint64_t validator = (id >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;

		if (unlikely(object_slots[slot].validator != validator)) {
			spin_lock.unlock();
			return nullptr;
		}

		Object *object = object_slots[slot].object;

		spin_lock.unlock();

		return object;
	}

	template <typename T>
	_ALWAYS_INLINE_ static T *get_instance(ObjectID p_instance_id) {
		return Object::cast_to<T>(get_instance(p_instance_id));
	}

	template <typename T>
	_ALWAYS_INLINE_ static Ref<T> get_ref(ObjectID p_instance_id); // Defined in ref_counted.h

	static void debug_objects(DebugFunc p_func, void *p_user_data);
	static int get_object_count();
};

// Using `RequiredResult<T>` as the return type indicates that null will only be returned in the case of an error.
// This allows GDExtension language bindings to use the appropriate error handling mechanism for that language
// when null is returned (for example, throwing an exception), rather than simply returning the value.
template <typename T>
class RequiredResult {
	static_assert(!is_fully_defined_v<T> || std::is_base_of_v<Object, T>, "T must be an Object subtype");

public:
	using element_type = T;
	using ptr_type = std::conditional_t<std::is_base_of_v<RefCounted, T>, Ref<T>, T *>;

private:
	ptr_type _value = ptr_type();

public:
	_FORCE_INLINE_ RequiredResult() = default;

	RequiredResult(const RequiredResult &p_other) = default;
	RequiredResult(RequiredResult &&p_other) = default;
	RequiredResult &operator=(const RequiredResult &p_other) = default;
	RequiredResult &operator=(RequiredResult &&p_other) = default;

	_FORCE_INLINE_ RequiredResult(std::nullptr_t) :
			RequiredResult() {}
	_FORCE_INLINE_ RequiredResult &operator=(std::nullptr_t) { _value = nullptr; }

	// These functions should not be called directly, they are only for internal use.
	_FORCE_INLINE_ ptr_type _internal_ptr_dont_use() const { return _value; }
	_FORCE_INLINE_ static RequiredResult<T> _err_return_dont_use() { return RequiredResult<T>(); }

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult(const RequiredResult<T_Other> &p_other) :
			_value(p_other._value) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult &operator=(const RequiredResult<T_Other> &p_other) {
		_value = p_other._value;
		return *this;
	}

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult(T_Other *p_ptr) :
			_value(p_ptr) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult &operator=(T_Other *p_ptr) {
		_value = p_ptr;
		return *this;
	}

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult(const Ref<T_Other> &p_ref) :
			_value(p_ref) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult &operator=(const Ref<T_Other> &p_ref) {
		_value = p_ref;
		return *this;
	}

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult(Ref<T_Other> &&p_ref) :
			_value(std::move(p_ref)) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredResult &operator=(Ref<T_Other> &&p_ref) {
		_value = std::move(p_ref);
		return &this;
	}

	template <typename U = T, std::enable_if_t<std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredResult(const Variant &p_variant) :
			_value(Object::cast_to<T>(p_variant.get_validated_object())) {}
	template <typename U = T, std::enable_if_t<std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredResult &operator=(const Variant &p_variant) {
		_value = Object::cast_to<T>(p_variant.get_validated_object());
		return *this;
	}

	template <typename U = T, std::enable_if_t<!std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredResult(const Variant &p_variant) :
			_value(Object::cast_to<T>(p_variant.operator Object *())) {}
	template <typename U = T, std::enable_if_t<!std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredResult &operator=(const Variant &p_variant) {
		_value = Object::cast_to<T>(p_variant.operator Object *());
		return *this;
	}

	template <typename U = T, std::enable_if_t<std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ T *ptr() const {
		return *_value;
	}

	template <typename U = T, std::enable_if_t<!std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ T *ptr() const {
		return _value;
	}

	_FORCE_INLINE_ operator ptr_type() const {
		return _value;
	}

	template <typename U = T, typename T_Other, std::enable_if_t<std::is_base_of_v<RefCounted, U> && std::is_base_of_v<U, T_Other>, int> = 0>
	_FORCE_INLINE_ operator Ref<T_Other>() const {
		return Ref<T_Other>(_value);
	}

	_FORCE_INLINE_ T *operator*() const {
		return ptr();
	}

	_FORCE_INLINE_ T *operator->() const {
		return ptr();
	}
};

// Using `RequiredParam<T>` as an argument type indicates that passing null as that parameter is an error,
// that will prevent the method from doing its intended function.
// This allows GDExtension bindings to use language-specific mechanisms to prevent users from passing null,
// because it is never valid to do so.
template <typename T>
class RequiredParam {
	static_assert(!is_fully_defined_v<T> || std::is_base_of_v<Object, T>, "T must be an Object subtype");

public:
	static constexpr bool is_ref = std::is_base_of_v<RefCounted, T>;

	using element_type = T;
	using extracted_type = std::conditional_t<is_ref, const Ref<T> &, T *>;
	using persistent_type = std::conditional_t<is_ref, Ref<T>, T *>;

private:
	T *_value = nullptr;

	_FORCE_INLINE_ RequiredParam() = default;

public:
	// These functions should not be called directly, they are only for internal use.
	_FORCE_INLINE_ extracted_type _internal_ptr_dont_use() const {
		if constexpr (is_ref) {
			// Pretend _value is a Ref, for ease of use with existing `const Ref &` accepting APIs.
			// This only works as long as Ref is internally T *.
			// The double indirection should be optimized away by the compiler.
			static_assert(sizeof(Ref<T>) == sizeof(T *));
			return *((const Ref<T> *)&_value);
		} else {
			return _value;
		}
	}
	_FORCE_INLINE_ bool _is_null_dont_use() const { return _value == nullptr; }
	_FORCE_INLINE_ static RequiredParam<T> _err_return_dont_use() { return RequiredParam<T>(); }

	// Prevent erroneously assigning null values by explicitly removing nullptr constructor/assignment.
	RequiredParam(std::nullptr_t) = delete;
	RequiredParam &operator=(std::nullptr_t) = delete;

	RequiredParam(const RequiredParam &p_other) = default;
	RequiredParam(RequiredParam &&p_other) = default;
	RequiredParam &operator=(const RequiredParam &p_other) = default;
	RequiredParam &operator=(RequiredParam &&p_other) = default;

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam(const RequiredParam<T_Other> &p_other) :
			_value(p_other._internal_ptr_dont_use()) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam &operator=(const RequiredParam<T_Other> &p_other) {
		_value = p_other._internal_ptr_dont_use();
		return *this;
	}

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam(const RequiredResult<T_Other> &p_other) :
			_value(p_other.ptr()) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam &operator=(const RequiredResult<T_Other> &p_other) {
		_value = p_other.ptr();
		return *this;
	}

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam(T_Other *p_ptr) :
			_value(p_ptr) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam &operator=(T_Other *p_ptr) {
		_value = p_ptr;
		return *this;
	}

	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam(const Ref<T_Other> &p_ref) :
			_value(*p_ref) {}
	template <typename T_Other, std::enable_if_t<std::is_base_of_v<T, T_Other>, int> = 0>
	_FORCE_INLINE_ RequiredParam &operator=(const Ref<T_Other> &p_ref) {
		_value = *p_ref;
		return *this;
	}

	template <typename U = T, std::enable_if_t<std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredParam(const Variant &p_variant) :
			_value(Object::cast_to<T>(p_variant.get_validated_object())) {}
	template <typename U = T, std::enable_if_t<std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredParam &operator=(const Variant &p_variant) {
		_value = Object::cast_to<T>(p_variant.get_validated_object());
		return *this;
	}

	template <typename U = T, std::enable_if_t<!std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredParam(const Variant &p_variant) :
			_value(Object::cast_to<T>(p_variant.operator Object *())) {}
	template <typename U = T, std::enable_if_t<!std::is_base_of_v<RefCounted, U>, int> = 0>
	_FORCE_INLINE_ RequiredParam &operator=(const Variant &p_variant) {
		_value = Object::cast_to<T>(p_variant.operator Object *());
		return *this;
	}
};

#define TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, m_retval, m_msg, m_editor) \
	if (unlikely(m_param._is_null_dont_use())) { \
		_err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Required object \"" _STR(m_param) "\" is null.", m_msg, m_editor); \
		return m_retval; \
	} \
	typename std::decay_t<decltype(m_param)>::extracted_type m_name = m_param._internal_ptr_dont_use(); \
	static_assert(true)

// These macros are equivalent to the ERR_FAIL_NULL*() family of macros, only for RequiredParam<T> instead of raw pointers.
#define EXTRACT_PARAM_OR_FAIL(m_name, m_param) TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, void(), "", false)
#define EXTRACT_PARAM_OR_FAIL_MSG(m_name, m_param, m_msg) TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, void(), m_msg, false)
#define EXTRACT_PARAM_OR_FAIL_EDMSG(m_name, m_param, m_msg) TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, void(), m_msg, true)
#define EXTRACT_PARAM_OR_FAIL_V(m_name, m_param, m_retval) TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, m_retval, "", false)
#define EXTRACT_PARAM_OR_FAIL_V_MSG(m_name, m_param, m_retval, m_msg) TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, m_retval, m_msg, false)
#define EXTRACT_PARAM_OR_FAIL_V_EDMSG(m_name, m_param, m_retval, m_msg) TMPL_EXTRACT_PARAM_OR_FAIL(m_name, m_param, m_retval, m_msg, true)
