diff --git a/core/io/image.cpp b/core/io/image.cpp index 6350271a83..37cf7c278d 100644 --- a/core/io/image.cpp +++ b/core/io/image.cpp @@ -4268,7 +4268,7 @@ Image::Image(const uint8_t *p_mem_png_jpg, int p_len) { } } -Ref Image::duplicate(bool p_subresources) const { +Ref Image::_duplicate(const DuplicateParams &p_params) const { Ref copy; copy.instantiate(); copy->_copy_internals_from(*this); diff --git a/core/io/image.h b/core/io/image.h index 5ea5147174..9b2a1ff07f 100644 --- a/core/io/image.h +++ b/core/io/image.h @@ -244,6 +244,8 @@ public: static Ref (*basis_universal_unpacker_ptr)(const uint8_t *p_data, int p_size); protected: + virtual Ref _duplicate(const DuplicateParams &p_params) const override; + static void _bind_methods(); private: @@ -425,8 +427,6 @@ public: void convert_ra_rgba8_to_rg(); void convert_rgba8_to_bgra8(); - virtual Ref duplicate(bool p_subresources = false) const override; - UsedChannels detect_used_channels(CompressSource p_source = COMPRESS_SOURCE_GENERIC) const; void optimize_channels(); diff --git a/core/io/resource.cpp b/core/io/resource.cpp index 5b76b6a544..770bed3353 100644 --- a/core/io/resource.cpp +++ b/core/io/resource.cpp @@ -34,6 +34,7 @@ #include "core/math/math_funcs.h" #include "core/math/random_pcg.h" #include "core/os/os.h" +#include "core/variant/container_type_validate.h" #include "scene/main/node.h" //only so casting works void Resource::emit_changed() { @@ -265,76 +266,178 @@ void Resource::reload_from_file() { copy_from(s); } -void Resource::_dupe_sub_resources(Variant &r_variant, Node *p_for_scene, HashMap, Ref> &p_remap_cache) { - switch (r_variant.get_type()) { - case Variant::ARRAY: { - Array a = r_variant; - for (int i = 0; i < a.size(); i++) { - _dupe_sub_resources(a[i], p_for_scene, p_remap_cache); - } - } break; - case Variant::DICTIONARY: { - Dictionary d = r_variant; - for (Variant &k : d.get_key_list()) { - if (k.get_type() == Variant::OBJECT) { - // Replace in dictionary key. - Ref sr = k; - if (sr.is_valid() && sr->is_local_to_scene()) { - if (p_remap_cache.has(sr)) { - d[p_remap_cache[sr]] = d[k]; - d.erase(k); - } else { - Ref dupe = sr->duplicate_for_local_scene(p_for_scene, p_remap_cache); - d[dupe] = d[k]; - d.erase(k); - p_remap_cache[sr] = dupe; +Variant Resource::_duplicate_recursive(const Variant &p_variant, const DuplicateParams &p_params, uint32_t p_usage) const { + // Anything other than object can be simply skipped in case of a shallow copy. + if (!p_params.deep && p_variant.get_type() != Variant::OBJECT) { + return p_variant; + } + + switch (p_variant.get_type()) { + case Variant::OBJECT: { + const Ref &sr = p_variant; + bool should_duplicate = false; + if (sr.is_valid()) { + if ((p_usage & PROPERTY_USAGE_ALWAYS_DUPLICATE)) { + should_duplicate = true; + } else if ((p_usage & PROPERTY_USAGE_NEVER_DUPLICATE)) { + should_duplicate = false; + } else if (p_params.local_scene) { + should_duplicate = sr->is_local_to_scene(); + } else { + switch (p_params.subres_mode) { + case RESOURCE_DEEP_DUPLICATE_NONE: { + should_duplicate = false; + } break; + case RESOURCE_DEEP_DUPLICATE_INTERNAL: { + should_duplicate = p_params.deep && sr->is_built_in(); + } break; + case RESOURCE_DEEP_DUPLICATE_ALL: { + should_duplicate = p_params.deep; + } break; + default: { + DEV_ASSERT(false); } } - } else { - _dupe_sub_resources(k, p_for_scene, p_remap_cache); } - - _dupe_sub_resources(d[k], p_for_scene, p_remap_cache); + } + if (should_duplicate) { + if (thread_duplicate_remap_cache->has(sr)) { + return thread_duplicate_remap_cache->get(sr); + } else { + const Ref &dupe = p_params.local_scene + ? sr->duplicate_for_local_scene(p_params.local_scene, *thread_duplicate_remap_cache) + : sr->_duplicate(p_params); + thread_duplicate_remap_cache->insert(sr, dupe); + return dupe; + } + } else { + return p_variant; } } break; - case Variant::OBJECT: { - Ref sr = r_variant; - if (sr.is_valid() && sr->is_local_to_scene()) { - if (p_remap_cache.has(sr)) { - r_variant = p_remap_cache[sr]; - } else { - Ref dupe = sr->duplicate_for_local_scene(p_for_scene, p_remap_cache); - r_variant = dupe; - p_remap_cache[sr] = dupe; - } + case Variant::ARRAY: { + const Array &src = p_variant; + Array dst; + if (src.is_typed()) { + dst.set_typed(src.get_element_type()); } + dst.resize(src.size()); + for (int i = 0; i < src.size(); i++) { + dst[i] = _duplicate_recursive(src[i], p_params); + } + return dst; + } break; + case Variant::DICTIONARY: { + const Dictionary &src = p_variant; + Dictionary dst; + if (src.is_typed()) { + dst.set_typed(src.get_key_type(), src.get_value_type()); + } + for (const Variant &k : src.get_key_list()) { + const Variant &v = src[k]; + dst.set( + _duplicate_recursive(k, p_params), + _duplicate_recursive(v, p_params)); + } + return dst; + } break; + case Variant::PACKED_BYTE_ARRAY: + case Variant::PACKED_INT32_ARRAY: + case Variant::PACKED_INT64_ARRAY: + case Variant::PACKED_FLOAT32_ARRAY: + case Variant::PACKED_FLOAT64_ARRAY: + case Variant::PACKED_STRING_ARRAY: + case Variant::PACKED_VECTOR2_ARRAY: + case Variant::PACKED_VECTOR3_ARRAY: + case Variant::PACKED_COLOR_ARRAY: + case Variant::PACKED_VECTOR4_ARRAY: { + return p_variant.duplicate(); } break; default: { + return p_variant; } } } -Ref Resource::duplicate_for_local_scene(Node *p_for_scene, HashMap, Ref> &p_remap_cache) { +Ref Resource::_duplicate(const DuplicateParams &p_params) const { + ERR_FAIL_COND_V_MSG(p_params.local_scene && p_params.subres_mode != RESOURCE_DEEP_DUPLICATE_MAX, Ref(), "Duplication for local-to-scene can't specify a deep duplicate mode."); + + DuplicateRemapCacheT *remap_cache_backup = thread_duplicate_remap_cache; + +// These are for avoiding potential duplicates that can happen in custom code +// from participating in the same duplication session (remap cache). +#define BEFORE_USER_CODE thread_duplicate_remap_cache = nullptr; +#define AFTER_USER_CODE thread_duplicate_remap_cache = remap_cache_backup; + List plist; get_property_list(&plist); + BEFORE_USER_CODE Ref r = Object::cast_to(ClassDB::instantiate(get_class())); + AFTER_USER_CODE ERR_FAIL_COND_V(r.is_null(), Ref()); - r->local_scene = p_for_scene; + thread_duplicate_remap_cache->insert(Ref(this), r); + + if (p_params.local_scene) { + r->local_scene = p_params.local_scene; + } + + // Duplicate script first, so the scripted properties are considered. + BEFORE_USER_CODE + r->set_script(get_script()); + AFTER_USER_CODE for (const PropertyInfo &E : plist) { if (!(E.usage & PROPERTY_USAGE_STORAGE)) { continue; } - Variant p = get(E.name).duplicate(true); + if (E.name == "script") { + continue; + } - _dupe_sub_resources(p, p_for_scene, p_remap_cache); + BEFORE_USER_CODE + Variant p = get(E.name); + AFTER_USER_CODE + p = _duplicate_recursive(p, p_params, E.usage); + + BEFORE_USER_CODE r->set(E.name, p); + AFTER_USER_CODE } return r; + +#undef BEFORE_USER_CODE +#undef AFTER_USER_CODE +} + +Ref Resource::duplicate_for_local_scene(Node *p_for_scene, DuplicateRemapCacheT &p_remap_cache) const { +#ifdef DEBUG_ENABLED + // The only possibilities for the remap cache passed being valid are these: + // a) It's the same already used as the one of the thread. That happens when this function + // is called within some recursion level within a duplication. + // b) There's no current thread remap cache, which means this function is acting as an entry point. + // This check failing means that this function is being called as an entry point during an ongoing + // duplication, likely due to custom instantiation or setter code. It would be an engine bug because + // code starting or joining a duplicate session must ensure to exit it temporarily when making calls + // that may in turn invoke such custom code. + if (thread_duplicate_remap_cache && &p_remap_cache != thread_duplicate_remap_cache) { + ERR_PRINT("Resource::duplicate_for_local_scene() called during an ongoing duplication session. This is an engine bug."); + } +#endif + + DuplicateRemapCacheT *remap_cache_backup = thread_duplicate_remap_cache; + thread_duplicate_remap_cache = &p_remap_cache; + + DuplicateParams params; + params.deep = true; + params.local_scene = p_for_scene; + const Ref &dupe = _duplicate(params); + + thread_duplicate_remap_cache = remap_cache_backup; + + return dupe; } void Resource::_find_sub_resources(const Variant &p_variant, HashSet> &p_resources_found) { @@ -363,7 +466,7 @@ void Resource::_find_sub_resources(const Variant &p_variant, HashSet, Ref> &p_remap_cache) { +void Resource::configure_for_local_scene(Node *p_for_scene, DuplicateRemapCacheT &p_remap_cache) { List plist; get_property_list(&plist); @@ -390,53 +493,90 @@ void Resource::configure_for_local_scene(Node *p_for_scene, HashMap Resource::duplicate(bool p_subresources) const { - List plist; - get_property_list(&plist); +Ref Resource::duplicate(bool p_deep) const { + DuplicateRemapCacheT remap_cache; + bool started_session = false; + if (!thread_duplicate_remap_cache) { + thread_duplicate_remap_cache = &remap_cache; + started_session = true; + } - Ref r = static_cast(ClassDB::instantiate(get_class())); - ERR_FAIL_COND_V(r.is_null(), Ref()); + DuplicateParams params; + params.deep = p_deep; + params.subres_mode = RESOURCE_DEEP_DUPLICATE_INTERNAL; + const Ref &dupe = _duplicate(params); - for (const PropertyInfo &E : plist) { - if (!(E.usage & PROPERTY_USAGE_STORAGE)) { - continue; - } - Variant p = get(E.name); + if (started_session) { + thread_duplicate_remap_cache = nullptr; + } - switch (p.get_type()) { - case Variant::Type::DICTIONARY: - case Variant::Type::ARRAY: - case Variant::Type::PACKED_BYTE_ARRAY: - case Variant::Type::PACKED_COLOR_ARRAY: - case Variant::Type::PACKED_INT32_ARRAY: - case Variant::Type::PACKED_INT64_ARRAY: - case Variant::Type::PACKED_FLOAT32_ARRAY: - case Variant::Type::PACKED_FLOAT64_ARRAY: - case Variant::Type::PACKED_STRING_ARRAY: - case Variant::Type::PACKED_VECTOR2_ARRAY: - case Variant::Type::PACKED_VECTOR3_ARRAY: - case Variant::Type::PACKED_VECTOR4_ARRAY: { - r->set(E.name, p.duplicate(p_subresources)); - } break; + return dupe; +} - case Variant::Type::OBJECT: { - if (!(E.usage & PROPERTY_USAGE_NEVER_DUPLICATE) && (p_subresources || (E.usage & PROPERTY_USAGE_ALWAYS_DUPLICATE))) { - Ref sr = p; - if (sr.is_valid()) { - r->set(E.name, sr->duplicate(p_subresources)); - } - } else { - r->set(E.name, p); - } - } break; +Ref Resource::duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode) const { + ERR_FAIL_INDEX_V(p_deep_subresources_mode, RESOURCE_DEEP_DUPLICATE_MAX, Ref()); - default: { - r->set(E.name, p); - } + DuplicateRemapCacheT remap_cache; + bool started_session = false; + if (!thread_duplicate_remap_cache) { + thread_duplicate_remap_cache = &remap_cache; + started_session = true; + } + + DuplicateParams params; + params.deep = true; + params.subres_mode = p_deep_subresources_mode; + const Ref &dupe = _duplicate(params); + + if (started_session) { + thread_duplicate_remap_cache = nullptr; + } + + return dupe; +} + +Ref Resource::_duplicate_from_variant(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int p_recursion_count) const { + // A call without deep duplication would have been early-rejected at Variant::duplicate() unless it's the root call. + DEV_ASSERT(!(p_recursion_count > 0 && p_deep_subresources_mode == RESOURCE_DEEP_DUPLICATE_NONE)); + + // When duplicating from Variant, this function may be called multiple times from + // different parts of the data structure being copied. Therefore, we need to create + // a remap cache instance in a way that can be shared among all of the calls. + // Whatever Variant, Array or Dictionary that initiated the call chain will eventually + // claim it, when the stack unwinds up to the root call. + // One exception is that this is the root call. + + if (p_recursion_count == 0) { + if (p_deep) { + return duplicate_deep(p_deep_subresources_mode); + } else { + return duplicate(false); } } - return r; + if (thread_duplicate_remap_cache) { + Resource::DuplicateRemapCacheT::Iterator E = thread_duplicate_remap_cache->find(Ref(this)); + if (E) { + return E->value; + } + } else { + thread_duplicate_remap_cache = memnew(DuplicateRemapCacheT); + } + + DuplicateParams params; + params.deep = p_deep; + params.subres_mode = p_deep_subresources_mode; + + const Ref dupe = _duplicate(params); + + return dupe; +} + +void Resource::_teardown_duplicate_from_variant() { + if (thread_duplicate_remap_cache) { + memdelete(thread_duplicate_remap_cache); + thread_duplicate_remap_cache = nullptr; + } } void Resource::_set_path(const String &p_path) { @@ -583,7 +723,14 @@ void Resource::_bind_methods() { ClassDB::bind_method(D_METHOD("emit_changed"), &Resource::emit_changed); - ClassDB::bind_method(D_METHOD("duplicate", "subresources"), &Resource::duplicate, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("duplicate", "deep"), &Resource::duplicate, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("duplicate_deep", "deep_subresources_mode"), &Resource::duplicate_deep, DEFVAL(RESOURCE_DEEP_DUPLICATE_INTERNAL)); + + // For the bindings, it's much more natural to expose this enum from the Variant realm via Resource. + ClassDB::bind_integer_constant(get_class_static(), StringName("ResourceDeepDuplicateMode"), "RESOURCE_DEEP_DUPLICATE_NONE", RESOURCE_DEEP_DUPLICATE_NONE); + ClassDB::bind_integer_constant(get_class_static(), StringName("ResourceDeepDuplicateMode"), "RESOURCE_DEEP_DUPLICATE_INTERNAL", RESOURCE_DEEP_DUPLICATE_INTERNAL); + ClassDB::bind_integer_constant(get_class_static(), StringName("ResourceDeepDuplicateMode"), "RESOURCE_DEEP_DUPLICATE_ALL", RESOURCE_DEEP_DUPLICATE_ALL); + ADD_SIGNAL(MethodInfo("changed")); ADD_SIGNAL(MethodInfo("setup_local_to_scene_requested")); diff --git a/core/io/resource.h b/core/io/resource.h index 14c08629d9..7d9b19c83a 100644 --- a/core/io/resource.h +++ b/core/io/resource.h @@ -57,6 +57,13 @@ public: static void register_custom_data_to_otdb() { ClassDB::add_resource_base_extension("res", get_class_static()); } virtual String get_base_extension() const { return "res"; } +protected: + struct DuplicateParams { + bool deep = false; + ResourceDeepDuplicateMode subres_mode = RESOURCE_DEEP_DUPLICATE_MAX; + Node *local_scene = nullptr; + }; + private: friend class ResBase; friend class ResourceCache; @@ -83,7 +90,10 @@ private: SelfList remapped_list; - void _dupe_sub_resources(Variant &r_variant, Node *p_for_scene, HashMap, Ref> &p_remap_cache); + using DuplicateRemapCacheT = HashMap, Ref>; + static thread_local inline DuplicateRemapCacheT *thread_duplicate_remap_cache = nullptr; + + Variant _duplicate_recursive(const Variant &p_variant, const DuplicateParams &p_params, uint32_t p_usage = 0) const; void _find_sub_resources(const Variant &p_variant, HashSet> &p_resources_found); protected: @@ -104,6 +114,8 @@ protected: GDVIRTUAL1C(_set_path_cache, String); GDVIRTUAL0(_reset_state); + virtual Ref _duplicate(const DuplicateParams &p_params) const; + public: static Node *(*_get_local_scene_func)(); //used by editor static void (*_update_configuration_warning)(); //used by editor @@ -131,8 +143,11 @@ public: void set_scene_unique_id(const String &p_id); String get_scene_unique_id() const; - virtual Ref duplicate(bool p_subresources = false) const; - Ref duplicate_for_local_scene(Node *p_for_scene, HashMap, Ref> &p_remap_cache); + Ref duplicate(bool p_deep = false) const; + Ref duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode = RESOURCE_DEEP_DUPLICATE_INTERNAL) const; + Ref _duplicate_from_variant(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int p_recursion_count) const; + static void _teardown_duplicate_from_variant(); + Ref duplicate_for_local_scene(Node *p_for_scene, HashMap, Ref> &p_remap_cache) const; void configure_for_local_scene(Node *p_for_scene, HashMap, Ref> &p_remap_cache); void set_local_to_scene(bool p_enable); @@ -168,6 +183,8 @@ public: ~Resource(); }; +VARIANT_ENUM_CAST(ResourceDeepDuplicateMode); + class ResourceCache { friend class Resource; friend class ResourceLoader; //need the lock diff --git a/core/variant/array.cpp b/core/variant/array.cpp index 8e3a0f7040..eb94ae97f0 100644 --- a/core/variant/array.cpp +++ b/core/variant/array.cpp @@ -37,7 +37,6 @@ #include "core/templates/vector.h" #include "core/variant/callable.h" #include "core/variant/dictionary.h" -#include "core/variant/variant.h" struct ArrayPrivate { SafeRefCount refcount; @@ -518,10 +517,14 @@ const Variant &Array::get(int p_idx) const { } Array Array::duplicate(bool p_deep) const { - return recursive_duplicate(p_deep, 0); + return recursive_duplicate(p_deep, RESOURCE_DEEP_DUPLICATE_NONE, 0); } -Array Array::recursive_duplicate(bool p_deep, int recursion_count) const { +Array Array::duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode) const { + return recursive_duplicate(true, p_deep_subresources_mode, 0); +} + +Array Array::recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const { Array new_arr; new_arr._p->typed = _p->typed; @@ -531,12 +534,19 @@ Array Array::recursive_duplicate(bool p_deep, int recursion_count) const { } if (p_deep) { + bool is_call_chain_end = recursion_count == 0; + recursion_count++; int element_count = size(); new_arr.resize(element_count); Variant *write = new_arr._p->array.ptrw(); for (int i = 0; i < element_count; i++) { - write[i] = get(i).recursive_duplicate(true, recursion_count); + write[i] = get(i).recursive_duplicate(true, p_deep_subresources_mode, recursion_count); + } + + // Variant::recursive_duplicate() may have created a remap cache by now. + if (is_call_chain_end) { + Resource::_teardown_duplicate_from_variant(); } } else { new_arr._p->array = _p->array; diff --git a/core/variant/array.h b/core/variant/array.h index 38c988ba7f..539c24df67 100644 --- a/core/variant/array.h +++ b/core/variant/array.h @@ -31,6 +31,7 @@ #pragma once #include "core/typedefs.h" +#include "core/variant/variant_deep_duplicate.h" #include #include @@ -164,7 +165,8 @@ public: Variant pop_at(int p_pos); Array duplicate(bool p_deep = false) const; - Array recursive_duplicate(bool p_deep, int recursion_count) const; + Array duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode = RESOURCE_DEEP_DUPLICATE_INTERNAL) const; + Array recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const; Array slice(int p_begin, int p_end = INT_MAX, int p_step = 1, bool p_deep = false) const; Array filter(const Callable &p_callable) const; diff --git a/core/variant/dictionary.cpp b/core/variant/dictionary.cpp index 1a425e3cf9..ed6693daa3 100644 --- a/core/variant/dictionary.cpp +++ b/core/variant/dictionary.cpp @@ -569,7 +569,11 @@ const Variant *Dictionary::next(const Variant *p_key) const { } Dictionary Dictionary::duplicate(bool p_deep) const { - return recursive_duplicate(p_deep, 0); + return recursive_duplicate(p_deep, RESOURCE_DEEP_DUPLICATE_NONE, 0); +} + +Dictionary Dictionary::duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode) const { + return recursive_duplicate(true, p_deep_subresources_mode, 0); } void Dictionary::make_read_only() { @@ -581,7 +585,7 @@ bool Dictionary::is_read_only() const { return _p->read_only != nullptr; } -Dictionary Dictionary::recursive_duplicate(bool p_deep, int recursion_count) const { +Dictionary Dictionary::recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const { Dictionary n; n._p->typed_key = _p->typed_key; n._p->typed_value = _p->typed_value; @@ -592,9 +596,16 @@ Dictionary Dictionary::recursive_duplicate(bool p_deep, int recursion_count) con } if (p_deep) { + bool is_call_chain_end = recursion_count == 0; + recursion_count++; for (const KeyValue &E : _p->variant_map) { - n[E.key.recursive_duplicate(true, recursion_count)] = E.value.recursive_duplicate(true, recursion_count); + n[E.key.recursive_duplicate(true, p_deep_subresources_mode, recursion_count)] = E.value.recursive_duplicate(true, p_deep_subresources_mode, recursion_count); + } + + // Variant::recursive_duplicate() may have created a remap cache by now. + if (is_call_chain_end) { + Resource::_teardown_duplicate_from_variant(); } } else { for (const KeyValue &E : _p->variant_map) { @@ -643,6 +654,10 @@ bool Dictionary::is_typed_value() const { return _p->typed_value.type != Variant::NIL; } +bool Dictionary::is_same_instance(const Dictionary &p_other) const { + return _p == p_other._p; +} + bool Dictionary::is_same_typed(const Dictionary &p_other) const { return is_same_typed_key(p_other) && is_same_typed_value(p_other); } diff --git a/core/variant/dictionary.h b/core/variant/dictionary.h index d170a5d394..86c50b1c03 100644 --- a/core/variant/dictionary.h +++ b/core/variant/dictionary.h @@ -35,6 +35,7 @@ #include "core/templates/local_vector.h" #include "core/templates/pair.h" #include "core/variant/array.h" +#include "core/variant/variant_deep_duplicate.h" class Variant; @@ -98,7 +99,8 @@ public: Array values() const; Dictionary duplicate(bool p_deep = false) const; - Dictionary recursive_duplicate(bool p_deep, int recursion_count) const; + Dictionary duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode = RESOURCE_DEEP_DUPLICATE_INTERNAL) const; + Dictionary recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const; void set_typed(const ContainerType &p_key_type, const ContainerType &p_value_type); void set_typed(uint32_t p_key_type, const StringName &p_key_class_name, const Variant &p_key_script, uint32_t p_value_type, const StringName &p_value_class_name, const Variant &p_value_script); @@ -106,6 +108,7 @@ public: bool is_typed() const; bool is_typed_key() const; bool is_typed_value() const; + bool is_same_instance(const Dictionary &p_other) const; bool is_same_typed(const Dictionary &p_other) const; bool is_same_typed_key(const Dictionary &p_other) const; bool is_same_typed_value(const Dictionary &p_other) const; diff --git a/core/variant/variant.h b/core/variant/variant.h index 9e1963bb26..cf77a3d8a3 100644 --- a/core/variant/variant.h +++ b/core/variant/variant.h @@ -61,6 +61,7 @@ #include "core/variant/array.h" #include "core/variant/callable.h" #include "core/variant/dictionary.h" +#include "core/variant/variant_deep_duplicate.h" class Object; class RefCounted; @@ -612,7 +613,8 @@ public: void zero(); Variant duplicate(bool p_deep = false) const; - Variant recursive_duplicate(bool p_deep, int recursion_count) const; + Variant duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode = RESOURCE_DEEP_DUPLICATE_INTERNAL) const; + Variant recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const; /* Built-In Methods */ diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp index 279b742669..2894b38875 100644 --- a/core/variant/variant_call.cpp +++ b/core/variant/variant_call.cpp @@ -2408,6 +2408,7 @@ static void _register_variant_builtin_methods_misc() { bind_method(Dictionary, keys, sarray(), varray()); bind_method(Dictionary, values, sarray(), varray()); bind_method(Dictionary, duplicate, sarray("deep"), varray(false)); + bind_method(Dictionary, duplicate_deep, sarray("deep_subresources_mode"), varray(RESOURCE_DEEP_DUPLICATE_INTERNAL)); bind_method(Dictionary, get, sarray("key", "default"), varray(Variant())); bind_method(Dictionary, get_or_add, sarray("key", "default"), varray(Variant())); bind_method(Dictionary, set, sarray("key", "value"), varray()); @@ -2466,6 +2467,7 @@ static void _register_variant_builtin_methods_array() { bind_method(Array, bsearch_custom, sarray("value", "func", "before"), varray(true)); bind_method(Array, reverse, sarray(), varray()); bind_method(Array, duplicate, sarray("deep"), varray(false)); + bind_method(Array, duplicate_deep, sarray("deep_subresources_mode"), varray(RESOURCE_DEEP_DUPLICATE_INTERNAL)); bind_method(Array, slice, sarray("begin", "end", "step", "deep"), varray(INT_MAX, 1, false)); bind_method(Array, filter, sarray("method"), varray()); bind_method(Array, map, sarray("method"), varray()); diff --git a/core/variant/variant_deep_duplicate.h b/core/variant/variant_deep_duplicate.h new file mode 100644 index 0000000000..f99952248f --- /dev/null +++ b/core/variant/variant_deep_duplicate.h @@ -0,0 +1,41 @@ +/**************************************************************************/ +/* variant_deep_duplicate.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 + +// This would be ideally declared nested in Variant, but that would cause circular +// includes with Array and Dictionary, for instance. +// Also, this enum is be exposed via Resource. +enum ResourceDeepDuplicateMode { + RESOURCE_DEEP_DUPLICATE_NONE, + RESOURCE_DEEP_DUPLICATE_INTERNAL, + RESOURCE_DEEP_DUPLICATE_ALL, + RESOURCE_DEEP_DUPLICATE_MAX +}; diff --git a/core/variant/variant_setget.cpp b/core/variant/variant_setget.cpp index 3553ea5988..b6e0dbe6d0 100644 --- a/core/variant/variant_setget.cpp +++ b/core/variant/variant_setget.cpp @@ -29,9 +29,10 @@ /**************************************************************************/ #include "variant_setget.h" - #include "variant_callable.h" +#include "core/io/resource.h" + struct VariantSetterGetterInfo { void (*setter)(Variant *base, const Variant *value, bool &valid); void (*getter)(const Variant *base, Variant *value); @@ -1969,26 +1970,33 @@ Variant Variant::iter_get(const Variant &r_iter, bool &r_valid) const { } Variant Variant::duplicate(bool p_deep) const { - return recursive_duplicate(p_deep, 0); + return recursive_duplicate(p_deep, RESOURCE_DEEP_DUPLICATE_NONE, 0); } -Variant Variant::recursive_duplicate(bool p_deep, int recursion_count) const { +Variant Variant::duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode) const { + ERR_FAIL_INDEX_V(p_deep_subresources_mode, RESOURCE_DEEP_DUPLICATE_MAX, Variant()); + return recursive_duplicate(true, p_deep_subresources_mode, 0); +} + +Variant Variant::recursive_duplicate(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int recursion_count) const { switch (type) { case OBJECT: { - /* breaks stuff :( - if (p_deep && !_get_obj().ref.is_null()) { - Ref resource = _get_obj().ref; - if (resource.is_valid()) { - return resource->duplicate(true); - } + // If the root target of duplicate() is a Resource, we can't early-reject because that + // resource itself must be duplicated, much as if Resource::duplicate() had been called. + if (p_deep_subresources_mode == RESOURCE_DEEP_DUPLICATE_NONE && recursion_count > 0) { + return *this; + } + Resource *res = Object::cast_to(_get_obj().obj); + if (res) { + return res->_duplicate_from_variant(p_deep, p_deep_subresources_mode, recursion_count); + } else { + return *this; } - */ - return *this; } break; case DICTIONARY: - return operator Dictionary().recursive_duplicate(p_deep, recursion_count); + return operator Dictionary().recursive_duplicate(p_deep, p_deep_subresources_mode, recursion_count); case ARRAY: - return operator Array().recursive_duplicate(p_deep, recursion_count); + return operator Array().recursive_duplicate(p_deep, p_deep_subresources_mode, recursion_count); case PACKED_BYTE_ARRAY: return operator Vector().duplicate(); case PACKED_INT32_ARRAY: diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml index 3dbf34f5a5..35415b3b3a 100644 --- a/doc/classes/Array.xml +++ b/doc/classes/Array.xml @@ -332,7 +332,16 @@ Returns a new copy of the array. - By default, a [b]shallow[/b] copy is returned: all nested [Array] and [Dictionary] elements are shared with the original array. Modifying them in one array will also affect them in the other.[br]If [param deep] is [code]true[/code], a [b]deep[/b] copy is returned: all nested arrays and dictionaries are also duplicated (recursively). + By default, a [b]shallow[/b] copy is returned: all nested [Array], [Dictionary], and [Resource] elements are shared with the original array. Modifying any of those in one array will also affect them in the other. + If [param deep] is [code]true[/code], a [b]deep[/b] copy is returned: all nested arrays and dictionaries are also duplicated (recursively). Any [Resource] is still shared with the original array, though. + + + + + + + Duplicates this array, deeply, like [method duplicate][code](true)[/code], with extra control over how subresources are handled. + [param deep_subresources_mode] must be one of the values from [enum Resource.ResourceDeepDuplicateMode]. By default, only internal resources will be duplicated (recursively). diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml index f80114d5c8..efaeefd151 100644 --- a/doc/classes/Dictionary.xml +++ b/doc/classes/Dictionary.xml @@ -187,7 +187,17 @@ - Creates and returns a new copy of the dictionary. If [param deep] is [code]true[/code], inner [Dictionary] and [Array] keys and values are also copied, recursively. + Returns a new copy of the dictionary. + By default, a [b]shallow[/b] copy is returned: all nested [Array], [Dictionary], and [Resource] keys and values are shared with the original dictionary. Modifying any of those in one dictionary will also affect them in the other. + If [param deep] is [code]true[/code], a [b]deep[/b] copy is returned: all nested arrays and dictionaries are also duplicated (recursively). Any [Resource] is still shared with the original dictionary, though. + + + + + + + Duplicates this dictionary, deeply, like [method duplicate][code](true)[/code], with extra control over how subresources are handled. + [param deep_subresources_mode] must be one of the values from [enum Resource.ResourceDeepDuplicateMode]. By default, only internal resources will be duplicated (recursively). diff --git a/doc/classes/Resource.xml b/doc/classes/Resource.xml index 0f3a231cb7..f52e45b1ff 100644 --- a/doc/classes/Resource.xml +++ b/doc/classes/Resource.xml @@ -50,15 +50,24 @@ - + Duplicates this resource, returning a new resource with its [code]export[/code]ed or [constant PROPERTY_USAGE_STORAGE] properties copied from the original. - If [param subresources] is [code]false[/code], a shallow copy is returned; nested resources within subresources are not duplicated and are shared with the original resource (with one exception; see below). If [param subresources] is [code]true[/code], a deep copy is returned; nested subresources will be duplicated and are not shared (with two exceptions; see below). - [param subresources] is usually respected, with the following exceptions: - - Subresource properties with the [constant PROPERTY_USAGE_ALWAYS_DUPLICATE] flag are always duplicated. + If [param deep] is [code]false[/code], a [b]shallow[/b] copy is returned: nested [Array], [Dictionary], and [Resource] properties are not duplicated and are shared with the original resource. + If [param deep] is [code]true[/code], a [b]deep[/b] copy is returned: all nested arrays, dictionaries, and packed arrays are also duplicated (recursively). Any [Resource] found inside will only be duplicated if it's local, like [constant RESOURCE_DEEP_DUPLICATE_INTERNAL] used with [method duplicate_deep]. + The following exceptions apply: + - Subresource properties with the [constant PROPERTY_USAGE_ALWAYS_DUPLICATE] flag are always duplicated (recursively or not, depending on [param deep]). - Subresource properties with the [constant PROPERTY_USAGE_NEVER_DUPLICATE] flag are never duplicated. - - Subresources inside [Array] and [Dictionary] properties are never duplicated. [b]Note:[/b] For custom resources, this method will fail if [method Object._init] has been defined with required parameters. + [b]Note:[/b] When duplicating with [param deep] set to [code]true[/code], each resource found, including the one on which this method is called, will be only duplicated once and referenced as many times as needed in the duplicate. For instance, if you are duplicating resource A that happens to have resource B referenced twice, you'll get a new resource A' referencing a new resource B' twice. + + + + + + + Duplicates this resource, deeply, like [method duplicate][code](true)[/code], with extra control over how subresources are handled. + [param deep_subresources_mode] must be one of the values from [enum ResourceDeepDuplicateMode]. @@ -176,4 +185,15 @@ + + + No subresorces at all are duplicated. This is useful even in a deep duplication to have all the arrays and dictionaries duplicated but still pointing to the original resources. + + + Only subresources without a path or with a scene-local path will be duplicated. + + + Every subresource found will be duplicated, even if it has a non-local path. In other words, even potentially big resources stored separately will be duplicated. + + diff --git a/modules/gdscript/tests/scripts/runtime/features/duplicate_resource.gd b/modules/gdscript/tests/scripts/runtime/features/duplicate_resource.gd new file mode 100644 index 0000000000..507797d6cd --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/duplicate_resource.gd @@ -0,0 +1,40 @@ +# We could use @export_custom to really test every property usage, but we know for good +# that duplicating scripted properties flows through the same code already thoroughly tested +# in the [Resource] test cases. The same goes for all the potential deep duplicate modes. +# Therefore, it's enough to ensure the exported scriped properties are copied when invoking +# duplication by each entry point. +class TestResource: + extends Resource + @export var text: String = "holaaa" + @export var arr: Array = [1, 2, 3] + @export var dict: Dictionary = { "a": 1, "b": 2 } + +func test(): + # Via Resource type. + var res := TestResource.new() + var dupe: TestResource + + dupe = res.duplicate() + print(dupe.text) + print(dupe.arr) + print(dupe.dict) + + dupe = res.duplicate_deep() + print(dupe.text) + print(dupe.arr) + print(dupe.dict) + + # Via Variant type. + + var res_var = TestResource.new() + var dupe_var + + dupe_var = res_var.duplicate() + print(dupe_var.text) + print(dupe_var.arr) + print(dupe_var.dict) + + dupe_var = res_var.duplicate_deep() + print(dupe_var.text) + print(dupe_var.arr) + print(dupe_var.dict) diff --git a/modules/gdscript/tests/scripts/runtime/features/duplicate_resource.out b/modules/gdscript/tests/scripts/runtime/features/duplicate_resource.out new file mode 100644 index 0000000000..a8e8dc2f9d --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/features/duplicate_resource.out @@ -0,0 +1,13 @@ +GDTEST_OK +holaaa +[1, 2, 3] +{ "a": 1, "b": 2 } +holaaa +[1, 2, 3] +{ "a": 1, "b": 2 } +holaaa +[1, 2, 3] +{ "a": 1, "b": 2 } +holaaa +[1, 2, 3] +{ "a": 1, "b": 2 } diff --git a/scene/main/node.cpp b/scene/main/node.cpp index 8ea3849227..cb7d4cfc44 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -3155,7 +3155,11 @@ void Node::_duplicate_properties(const Node *p_root, const Node *p_original, Nod continue; } - Variant value = p_original->get(name).duplicate(true); + Variant value = p_original->get(name); + // To keep classic behavior, because, in contrast, nowadays a resource would be duplicated. + if (value.get_type() != Variant::OBJECT) { + value = value.duplicate(true); + } if (E.usage & PROPERTY_USAGE_ALWAYS_DUPLICATE) { Resource *res = Object::cast_to(value); diff --git a/tests/core/io/test_resource.h b/tests/core/io/test_resource.h index ef98a8c013..83b21762ce 100644 --- a/tests/core/io/test_resource.h +++ b/tests/core/io/test_resource.h @@ -34,37 +34,505 @@ #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/os/os.h" +#include "scene/main/node.h" #include "thirdparty/doctest/doctest.h" #include "tests/test_macros.h" +#include + namespace TestResource { +enum TestDuplicateMode { + TEST_MODE_RESOURCE_DUPLICATE_SHALLOW, + TEST_MODE_RESOURCE_DUPLICATE_DEEP, + TEST_MODE_RESOURCE_DUPLICATE_DEEP_WITH_MODE, + TEST_MODE_RESOURCE_DUPLICATE_FOR_LOCAL_SCENE, + TEST_MODE_VARIANT_DUPLICATE_SHALLOW, + TEST_MODE_VARIANT_DUPLICATE_DEEP, + TEST_MODE_VARIANT_DUPLICATE_DEEP_WITH_MODE, +}; + +class DuplicateGuineaPigData : public Object { + GDSOFTCLASS(DuplicateGuineaPigData, Object) + +public: + const Variant SENTINEL_1 = "A"; + const Variant SENTINEL_2 = 645; + const Variant SENTINEL_3 = StringName("X"); + const Variant SENTINEL_4 = true; + + Ref SUBRES_1 = memnew(Resource); + Ref SUBRES_2 = memnew(Resource); + Ref SUBRES_3 = memnew(Resource); + Ref SUBRES_SL_1 = memnew(Resource); + Ref SUBRES_SL_2 = memnew(Resource); + Ref SUBRES_SL_3 = memnew(Resource); + + Variant obj; // Variant helps with lifetime so duplicates pointing to the same don't try to double-free it. + Array arr; + Dictionary dict; + Variant packed; // A PackedByteArray, but using Variant to be able to tell if the array is shared or not. + Ref subres; + Ref subres_sl; + + void set_defaults() { + SUBRES_1->set_name("juan"); + SUBRES_2->set_name("you"); + SUBRES_3->set_name("tree"); + SUBRES_SL_1->set_name("maybe_scene_local"); + SUBRES_SL_2->set_name("perhaps_local_to_scene"); + SUBRES_SL_3->set_name("sometimes_locality_scenial"); + + // To try some cases of internal and external. + SUBRES_1->set_path_cache(""); + SUBRES_2->set_path_cache("local://hehe"); + SUBRES_3->set_path_cache("res://some.tscn::1"); + DEV_ASSERT(SUBRES_1->is_built_in()); + DEV_ASSERT(SUBRES_2->is_built_in()); + DEV_ASSERT(SUBRES_3->is_built_in()); + SUBRES_SL_1->set_path_cache("res://thing.scn"); + SUBRES_SL_2->set_path_cache("C:/not/really/possible/but/still/external"); + SUBRES_SL_3->set_path_cache("/this/neither"); + DEV_ASSERT(!SUBRES_SL_1->is_built_in()); + DEV_ASSERT(!SUBRES_SL_2->is_built_in()); + DEV_ASSERT(!SUBRES_SL_3->is_built_in()); + + obj = memnew(Object); + + // Construct enough cases to test deep recursion involving resources; + // we mix some primitive values with recurses nested in different ways, + // acting as array values and dictionary keys and values, some of those + // being marked as scene-local when for subcases where scene-local is relevant. + + arr.push_back(SENTINEL_1); + arr.push_back(SUBRES_1); + arr.push_back(SUBRES_SL_1); + { + Dictionary d; + d[SENTINEL_2] = SENTINEL_3; + d[SENTINEL_4] = SUBRES_2; + d[SUBRES_3] = SUBRES_SL_2; + d[SUBRES_SL_3] = SUBRES_1; + arr.push_back(d); + } + + dict[SENTINEL_4] = SENTINEL_1; + dict[SENTINEL_2] = SUBRES_2; + dict[SUBRES_3] = SUBRES_SL_1; + dict[SUBRES_SL_2] = SUBRES_1; + { + Array a; + a.push_back(SENTINEL_3); + a.push_back(SUBRES_2); + a.push_back(SUBRES_SL_3); + dict[SENTINEL_4] = a; + } + + packed = PackedByteArray{ 0xaa, 0xbb, 0xcc }; + + subres = SUBRES_1; + subres_sl = SUBRES_SL_1; + } + + void verify_empty() const { + CHECK(obj.get_type() == Variant::NIL); + CHECK(arr.size() == 0); + CHECK(dict.size() == 0); + CHECK(packed.get_type() == Variant::NIL); + CHECK(subres.is_null()); + } + + void verify_duplication(const DuplicateGuineaPigData *p_orig, uint32_t p_property_usage, TestDuplicateMode p_test_mode, ResourceDeepDuplicateMode p_deep_mode) const { + if (!(p_property_usage & PROPERTY_USAGE_STORAGE)) { + verify_empty(); + return; + } + + // To see if each resource involved is copied once at most, + // and then the reference to the duplicate reused. + HashMap duplicates; + + auto _verify_resource = [&](const Ref &p_dupe_res, const Ref &p_orig_res, bool p_is_property = false) { + bool expect_true_copy = (p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_DEEP && p_orig_res->is_built_in()) || + (p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_DEEP_WITH_MODE && p_deep_mode == RESOURCE_DEEP_DUPLICATE_INTERNAL && p_orig_res->is_built_in()) || + (p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_DEEP_WITH_MODE && p_deep_mode == RESOURCE_DEEP_DUPLICATE_ALL) || + (p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_FOR_LOCAL_SCENE && p_orig_res->is_local_to_scene()) || + (p_test_mode == TEST_MODE_VARIANT_DUPLICATE_DEEP_WITH_MODE && p_deep_mode == RESOURCE_DEEP_DUPLICATE_INTERNAL && p_orig_res->is_built_in()) || + (p_test_mode == TEST_MODE_VARIANT_DUPLICATE_DEEP_WITH_MODE && p_deep_mode == RESOURCE_DEEP_DUPLICATE_ALL); + + if (expect_true_copy) { + if (p_deep_mode == RESOURCE_DEEP_DUPLICATE_NONE) { + expect_true_copy = false; + } else if (p_deep_mode == RESOURCE_DEEP_DUPLICATE_INTERNAL) { + expect_true_copy = p_orig_res->is_built_in(); + } + } + + if (p_is_property) { + if ((p_property_usage & PROPERTY_USAGE_ALWAYS_DUPLICATE)) { + expect_true_copy = true; + } else if ((p_property_usage & PROPERTY_USAGE_NEVER_DUPLICATE)) { + expect_true_copy = false; + } + } + + if (expect_true_copy) { + CHECK(p_dupe_res != p_orig_res); + CHECK(p_dupe_res->get_name() == p_orig_res->get_name()); + if (duplicates.has(p_orig_res.ptr())) { + CHECK(duplicates[p_orig_res.ptr()] == p_dupe_res.ptr()); + } else { + duplicates[p_orig_res.ptr()] = p_dupe_res.ptr(); + } + } else { + CHECK(p_dupe_res == p_orig_res); + } + }; + + std::function _verify_deep_copied_variants = [&](const Variant &p_a, const Variant &p_b) { + CHECK(p_a.get_type() == p_b.get_type()); + const Ref &res_a = p_a; + const Ref &res_b = p_b; + if (res_a.is_valid()) { + _verify_resource(res_a, res_b); + } else if (p_a.get_type() == Variant::ARRAY) { + const Array &arr_a = p_a; + const Array &arr_b = p_b; + CHECK(!arr_a.is_same_instance(arr_b)); + CHECK(arr_a.size() == arr_b.size()); + for (int i = 0; i < arr_a.size(); i++) { + _verify_deep_copied_variants(arr_a[i], arr_b[i]); + } + } else if (p_a.get_type() == Variant::DICTIONARY) { + const Dictionary &dict_a = p_a; + const Dictionary &dict_b = p_b; + CHECK(!dict_a.is_same_instance(dict_b)); + CHECK(dict_a.size() == dict_b.size()); + for (int i = 0; i < dict_a.size(); i++) { + _verify_deep_copied_variants(dict_a.get_key_at_index(i), dict_b.get_key_at_index(i)); + _verify_deep_copied_variants(dict_a.get_value_at_index(i), dict_b.get_value_at_index(i)); + } + } else { + CHECK(p_a == p_b); + } + }; + + CHECK(this != p_orig); + + CHECK((Object *)obj == (Object *)p_orig->obj); + + bool expect_true_copy = p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_DEEP || + p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_DEEP_WITH_MODE || + p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_FOR_LOCAL_SCENE || + p_test_mode == TEST_MODE_VARIANT_DUPLICATE_DEEP || + p_test_mode == TEST_MODE_VARIANT_DUPLICATE_DEEP_WITH_MODE; + if (expect_true_copy) { + _verify_deep_copied_variants(arr, p_orig->arr); + _verify_deep_copied_variants(dict, p_orig->dict); + CHECK(!packed.identity_compare(p_orig->packed)); + } else { + CHECK(arr.is_same_instance(p_orig->arr)); + CHECK(dict.is_same_instance(p_orig->dict)); + CHECK(packed.identity_compare(p_orig->packed)); + } + + _verify_resource(subres, p_orig->subres, true); + _verify_resource(subres_sl, p_orig->subres_sl, true); + } + + void enable_scene_local_subresources() { + SUBRES_SL_1->set_local_to_scene(true); + SUBRES_SL_2->set_local_to_scene(true); + SUBRES_SL_3->set_local_to_scene(true); + } + + virtual ~DuplicateGuineaPigData() { + Object *obj_ptr = obj.get_validated_object(); + if (obj_ptr) { + memdelete(obj_ptr); + } + } +}; + +#define DEFINE_DUPLICATE_GUINEA_PIG(m_class_name, m_property_usage) \ + class m_class_name : public Resource { \ + GDCLASS(m_class_name, Resource) \ + \ + DuplicateGuineaPigData data; \ + \ + public: \ + void set_obj(Object *p_obj) { \ + data.obj = p_obj; \ + } \ + Object *get_obj() const { \ + return data.obj; \ + } \ + \ + void set_arr(const Array &p_arr) { \ + data.arr = p_arr; \ + } \ + Array get_arr() const { \ + return data.arr; \ + } \ + \ + void set_dict(const Dictionary &p_dict) { \ + data.dict = p_dict; \ + } \ + Dictionary get_dict() const { \ + return data.dict; \ + } \ + \ + void set_packed(const Variant &p_packed) { \ + data.packed = p_packed; \ + } \ + Variant get_packed() const { \ + return data.packed; \ + } \ + \ + void set_subres(const Ref &p_subres) { \ + data.subres = p_subres; \ + } \ + Ref get_subres() const { \ + return data.subres; \ + } \ + \ + void set_subres_sl(const Ref &p_subres) { \ + data.subres_sl = p_subres; \ + } \ + Ref get_subres_sl() const { \ + return data.subres_sl; \ + } \ + \ + void set_defaults() { \ + data.set_defaults(); \ + } \ + \ + Object *get_data() { \ + return &data; \ + } \ + \ + void verify_duplication(const Ref &p_orig, int p_test_mode, int p_deep_mode) const { \ + const DuplicateGuineaPigData *orig_data = Object::cast_to(p_orig->call("get_data")); \ + data.verify_duplication(orig_data, m_property_usage, (TestDuplicateMode)p_test_mode, (ResourceDeepDuplicateMode)p_deep_mode); \ + } \ + \ + protected: \ + static void _bind_methods() { \ + ClassDB::bind_method(D_METHOD("set_obj", "obj"), &m_class_name::set_obj); \ + ClassDB::bind_method(D_METHOD("get_obj"), &m_class_name::get_obj); \ + \ + ClassDB::bind_method(D_METHOD("set_arr", "arr"), &m_class_name::set_arr); \ + ClassDB::bind_method(D_METHOD("get_arr"), &m_class_name::get_arr); \ + \ + ClassDB::bind_method(D_METHOD("set_dict", "dict"), &m_class_name::set_dict); \ + ClassDB::bind_method(D_METHOD("get_dict"), &m_class_name::get_dict); \ + \ + ClassDB::bind_method(D_METHOD("set_packed", "packed"), &m_class_name::set_packed); \ + ClassDB::bind_method(D_METHOD("get_packed"), &m_class_name::get_packed); \ + \ + ClassDB::bind_method(D_METHOD("set_subres", "subres"), &m_class_name::set_subres); \ + ClassDB::bind_method(D_METHOD("get_subres"), &m_class_name::get_subres); \ + \ + ClassDB::bind_method(D_METHOD("set_subres_sl", "subres"), &m_class_name::set_subres_sl); \ + ClassDB::bind_method(D_METHOD("get_subres_sl"), &m_class_name::get_subres_sl); \ + \ + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "obj", PROPERTY_HINT_NONE, "", m_property_usage), "set_obj", "get_obj"); \ + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "arr", PROPERTY_HINT_NONE, "", m_property_usage), "set_arr", "get_arr"); \ + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "dict", PROPERTY_HINT_NONE, "", m_property_usage), "set_dict", "get_dict"); \ + ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packed", PROPERTY_HINT_NONE, "", m_property_usage), "set_packed", "get_packed"); \ + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "subres", PROPERTY_HINT_NONE, "", m_property_usage), "set_subres", "get_subres"); \ + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "subres_sl", PROPERTY_HINT_NONE, "", m_property_usage), "set_subres_sl", "get_subres_sl"); \ + \ + ClassDB::bind_method(D_METHOD("set_defaults"), &m_class_name::set_defaults); \ + ClassDB::bind_method(D_METHOD("get_data"), &m_class_name::get_data); \ + ClassDB::bind_method(D_METHOD("verify_duplication", "orig", "test_mode", "deep_mode"), &m_class_name::verify_duplication); \ + } \ + \ + public: \ + static m_class_name *register_and_instantiate() { \ + static bool registered = false; \ + if (!registered) { \ + GDREGISTER_CLASS(m_class_name); \ + registered = true; \ + } \ + return memnew(m_class_name); \ + } \ + }; + +DEFINE_DUPLICATE_GUINEA_PIG(DuplicateGuineaPig_None, PROPERTY_USAGE_NONE) +DEFINE_DUPLICATE_GUINEA_PIG(DuplicateGuineaPig_Always, PROPERTY_USAGE_ALWAYS_DUPLICATE) +DEFINE_DUPLICATE_GUINEA_PIG(DuplicateGuineaPig_Storage, PROPERTY_USAGE_STORAGE) +DEFINE_DUPLICATE_GUINEA_PIG(DuplicateGuineaPig_Storage_Always, (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_ALWAYS_DUPLICATE)) +DEFINE_DUPLICATE_GUINEA_PIG(DuplicateGuineaPig_Storage_Never, (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_NEVER_DUPLICATE)) + TEST_CASE("[Resource] Duplication") { - Ref resource = memnew(Resource); - resource->set_name("Hello world"); - Ref child_resource = memnew(Resource); - child_resource->set_name("I'm a child resource"); - resource->set_meta("other_resource", child_resource); + auto _run_test = []( + TestDuplicateMode p_test_mode, + ResourceDeepDuplicateMode p_deep_mode, + Ref (*p_duplicate_fn)(const Ref &)) -> void { + LocalVector> resources = { + DuplicateGuineaPig_None::register_and_instantiate(), + DuplicateGuineaPig_Always::register_and_instantiate(), + DuplicateGuineaPig_Storage::register_and_instantiate(), + DuplicateGuineaPig_Storage_Always::register_and_instantiate(), + DuplicateGuineaPig_Storage_Never::register_and_instantiate(), + }; - Ref resource_dupe = resource->duplicate(); - const Ref &resource_dupe_reference = resource_dupe; - resource_dupe->set_name("Changed name"); - child_resource->set_name("My name was changed too"); + for (const Ref &orig : resources) { + INFO(std::string(String(orig->get_class_name()).utf8().get_data())); - CHECK_MESSAGE( - resource_dupe->get_name() == "Changed name", - "Duplicated resource should have the new name."); - CHECK_MESSAGE( - resource_dupe_reference->get_name() == "Changed name", - "Reference to the duplicated resource should have the new name."); - CHECK_MESSAGE( - resource->get_name() == "Hello world", - "Original resource name should not be affected after editing the duplicate's name."); - CHECK_MESSAGE( - Ref(resource_dupe->get_meta("other_resource"))->get_name() == "My name was changed too", - "Duplicated resource should share its child resource with the original."); + orig->call("set_defaults"); + + const Ref &dupe = p_duplicate_fn(orig); + if ((p_test_mode == TEST_MODE_RESOURCE_DUPLICATE_DEEP_WITH_MODE || p_test_mode == TEST_MODE_VARIANT_DUPLICATE_DEEP_WITH_MODE) && p_deep_mode == RESOURCE_DEEP_DUPLICATE_MAX) { + CHECK(dupe.is_null()); + } else { + dupe->call("verify_duplication", orig, p_test_mode, p_deep_mode); + } + } + }; + + SUBCASE("Resource::duplicate(), shallow") { + _run_test( + TEST_MODE_RESOURCE_DUPLICATE_SHALLOW, + RESOURCE_DEEP_DUPLICATE_MAX, + [](const Ref &p_res) -> Ref { + return p_res->duplicate(false); + }); + } + + SUBCASE("Resource::duplicate(), deep") { + _run_test( + TEST_MODE_RESOURCE_DUPLICATE_DEEP, + RESOURCE_DEEP_DUPLICATE_MAX, + [](const Ref &p_res) -> Ref { + return p_res->duplicate(true); + }); + } + + SUBCASE("Resource::duplicate_deep()") { + static int deep_mode = 0; + for (deep_mode = 0; deep_mode <= RESOURCE_DEEP_DUPLICATE_MAX; deep_mode++) { + _run_test( + TEST_MODE_RESOURCE_DUPLICATE_DEEP_WITH_MODE, + (ResourceDeepDuplicateMode)deep_mode, + [](const Ref &p_res) -> Ref { + return p_res->duplicate_deep((ResourceDeepDuplicateMode)deep_mode); + }); + } + } + + SUBCASE("Resource::duplicate_for_local_scene()") { + static int mark_main_as_local = 0; + static int mark_some_subs_as_local = 0; + for (mark_main_as_local = 0; mark_main_as_local < 2; ++mark_main_as_local) { // Whether main is local-to-scene shouldn't matter. + for (mark_some_subs_as_local = 0; mark_some_subs_as_local < 2; ++mark_some_subs_as_local) { + _run_test( + TEST_MODE_RESOURCE_DUPLICATE_FOR_LOCAL_SCENE, + RESOURCE_DEEP_DUPLICATE_MAX, + [](const Ref &p_res) -> Ref { + if (mark_main_as_local) { + p_res->set_local_to_scene(true); + } + if (mark_some_subs_as_local) { + Object::cast_to(p_res->call("get_data"))->enable_scene_local_subresources(); + } + HashMap, Ref> remap_cache; + Node fake_scene; + return p_res->duplicate_for_local_scene(&fake_scene, remap_cache); + }); + } + } + } + + SUBCASE("Variant::duplicate(), shallow") { + _run_test( + TEST_MODE_VARIANT_DUPLICATE_SHALLOW, + RESOURCE_DEEP_DUPLICATE_MAX, + [](const Ref &p_res) -> Ref { + return Variant(p_res).duplicate(false); + }); + } + + SUBCASE("Variant::duplicate(), deep") { + _run_test( + TEST_MODE_VARIANT_DUPLICATE_DEEP, + RESOURCE_DEEP_DUPLICATE_MAX, + [](const Ref &p_res) -> Ref { + return Variant(p_res).duplicate(true); + }); + } + + SUBCASE("Variant::duplicate_deep()") { + static int deep_mode = 0; + for (deep_mode = 0; deep_mode <= RESOURCE_DEEP_DUPLICATE_MAX; deep_mode++) { + _run_test( + TEST_MODE_VARIANT_DUPLICATE_DEEP_WITH_MODE, + (ResourceDeepDuplicateMode)deep_mode, + [](const Ref &p_res) -> Ref { + return Variant(p_res).duplicate_deep((ResourceDeepDuplicateMode)deep_mode); + }); + } + } + + SUBCASE("Via Variant, resource not being the root") { + // Variant controls the deep copy, recursing until resources are found, and then + // it's Resource who controls the deep copy from it onwards. + // Therefore, we have to test if Variant is able to track unique duplicates across + // multiple times Resource takes over. + // Since the other test cases already prove Resource's mechanism to have at most + // one duplicate per resource involved, the test for Variant is simple. + + Ref res; + res.instantiate(); + res->set_name("risi"); + Array a; + a.push_back(res); + { + Dictionary d; + d[res] = res; + a.push_back(d); + } + + Array dupe_a; + Ref dupe_res; + + SUBCASE("Variant::duplicate(), shallow") { + dupe_a = Variant(a).duplicate(false); + // Ensure it's referencing the original. + dupe_res = dupe_a[0]; + CHECK(dupe_res == res); + } + SUBCASE("Variant::duplicate(), deep") { + dupe_a = Variant(a).duplicate(true); + // Ensure it's referencing the original. + dupe_res = dupe_a[0]; + CHECK(dupe_res == res); + } + SUBCASE("Variant::duplicate_deep(), no resources") { + dupe_a = Variant(a).duplicate_deep(RESOURCE_DEEP_DUPLICATE_NONE); + // Ensure it's referencing the original. + dupe_res = dupe_a[0]; + CHECK(dupe_res == res); + } + SUBCASE("Variant::duplicate_deep(), with resources") { + dupe_a = Variant(a).duplicate_deep(RESOURCE_DEEP_DUPLICATE_ALL); + // Ensure it's a copy. + dupe_res = dupe_a[0]; + CHECK(dupe_res != res); + CHECK(dupe_res->get_name() == "risi"); + + // Ensure the map is already gone so we get new instances. + Array dupe_a_2 = Variant(a).duplicate_deep(RESOURCE_DEEP_DUPLICATE_ALL); + CHECK(dupe_a_2[0] != dupe_a[0]); + } + + // Ensure all the usages are of the same resource. + CHECK(((Dictionary)dupe_a[1]).get_key_at_index(0) == dupe_res); + CHECK(((Dictionary)dupe_a[1]).get_value_at_index(0) == dupe_res); + } } TEST_CASE("[Resource] Saving and loading") {