resource.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. /**************************************************************************/
  2. /* resource.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource.h"
  31. #include "core/io/resource_loader.h"
  32. #include "core/math/math_funcs.h"
  33. #include "core/math/random_pcg.h"
  34. #include "core/os/os.h"
  35. #include "core/variant/container_type_validate.h"
  36. #include "scene/main/node.h" //only so casting works
  37. void Resource::emit_changed() {
  38. if (emit_changed_state != EMIT_CHANGED_UNBLOCKED) {
  39. emit_changed_state = EMIT_CHANGED_BLOCKED_PENDING_EMIT;
  40. return;
  41. }
  42. if (ResourceLoader::is_within_load() && !Thread::is_main_thread()) {
  43. ResourceLoader::resource_changed_emit(this);
  44. return;
  45. }
  46. emit_signal(CoreStringName(changed));
  47. }
  48. void Resource::_block_emit_changed() {
  49. if (emit_changed_state == EMIT_CHANGED_UNBLOCKED) {
  50. emit_changed_state = EMIT_CHANGED_BLOCKED;
  51. }
  52. }
  53. void Resource::_unblock_emit_changed() {
  54. bool emit = (emit_changed_state == EMIT_CHANGED_BLOCKED_PENDING_EMIT);
  55. emit_changed_state = EMIT_CHANGED_UNBLOCKED;
  56. if (emit) {
  57. emit_changed();
  58. }
  59. }
  60. void Resource::_resource_path_changed() {
  61. }
  62. void Resource::set_path(const String &p_path, bool p_take_over) {
  63. if (path_cache == p_path) {
  64. return;
  65. }
  66. if (p_path.is_empty()) {
  67. p_take_over = false; // Can't take over an empty path
  68. }
  69. {
  70. MutexLock lock(ResourceCache::lock);
  71. if (!path_cache.is_empty()) {
  72. ResourceCache::resources.erase(path_cache);
  73. }
  74. path_cache = "";
  75. Ref<Resource> existing = ResourceCache::get_ref(p_path);
  76. if (existing.is_valid()) {
  77. if (p_take_over) {
  78. existing->path_cache = String();
  79. ResourceCache::resources.erase(p_path);
  80. } else {
  81. ERR_FAIL_MSG(vformat("Another resource is loaded from path '%s' (possible cyclic resource inclusion).", p_path));
  82. }
  83. }
  84. path_cache = p_path;
  85. if (!path_cache.is_empty()) {
  86. ResourceCache::resources[path_cache] = this;
  87. }
  88. }
  89. _resource_path_changed();
  90. }
  91. String Resource::get_path() const {
  92. return path_cache;
  93. }
  94. void Resource::set_path_cache(const String &p_path) {
  95. path_cache = p_path;
  96. GDVIRTUAL_CALL(_set_path_cache, p_path);
  97. }
  98. static thread_local RandomPCG unique_id_gen = RandomPCG(0);
  99. void Resource::seed_scene_unique_id(uint32_t p_seed) {
  100. unique_id_gen.seed(p_seed);
  101. }
  102. String Resource::generate_scene_unique_id() {
  103. // Generate a unique enough hash, but still user-readable.
  104. // If it's not unique it does not matter because the saver will try again.
  105. if (unique_id_gen.get_seed() == 0) {
  106. OS::DateTime dt = OS::get_singleton()->get_datetime();
  107. uint32_t hash = hash_murmur3_one_32(OS::get_singleton()->get_ticks_usec());
  108. hash = hash_murmur3_one_32(dt.year, hash);
  109. hash = hash_murmur3_one_32(dt.month, hash);
  110. hash = hash_murmur3_one_32(dt.day, hash);
  111. hash = hash_murmur3_one_32(dt.hour, hash);
  112. hash = hash_murmur3_one_32(dt.minute, hash);
  113. hash = hash_murmur3_one_32(dt.second, hash);
  114. hash = hash_murmur3_one_32(Math::rand(), hash);
  115. unique_id_gen.seed(hash);
  116. }
  117. uint32_t random_num = unique_id_gen.rand();
  118. static constexpr uint32_t characters = 5;
  119. static constexpr uint32_t char_count = ('z' - 'a');
  120. static constexpr uint32_t base = char_count + ('9' - '0');
  121. String id;
  122. id.resize_uninitialized(characters + 1);
  123. char32_t *ptr = id.ptrw();
  124. for (uint32_t i = 0; i < characters; i++) {
  125. uint32_t c = random_num % base;
  126. if (c < char_count) {
  127. ptr[i] = ('a' + c);
  128. } else {
  129. ptr[i] = ('0' + (c - char_count));
  130. }
  131. random_num /= base;
  132. }
  133. ptr[characters] = '\0';
  134. return id;
  135. }
  136. void Resource::set_scene_unique_id(const String &p_id) {
  137. bool is_valid = true;
  138. for (int i = 0; i < p_id.length(); i++) {
  139. if (!is_ascii_identifier_char(p_id[i])) {
  140. is_valid = false;
  141. scene_unique_id = Resource::generate_scene_unique_id();
  142. break;
  143. }
  144. }
  145. ERR_FAIL_COND_MSG(!is_valid, "The scene unique ID must contain only letters, numbers, and underscores.");
  146. scene_unique_id = p_id;
  147. }
  148. String Resource::get_scene_unique_id() const {
  149. return scene_unique_id;
  150. }
  151. void Resource::set_name(const String &p_name) {
  152. name = p_name;
  153. emit_changed();
  154. }
  155. String Resource::get_name() const {
  156. return name;
  157. }
  158. void Resource::update_configuration_warning() {
  159. if (_update_configuration_warning) {
  160. _update_configuration_warning();
  161. }
  162. }
  163. bool Resource::editor_can_reload_from_file() {
  164. return true; //by default yes
  165. }
  166. void Resource::connect_changed(const Callable &p_callable, uint32_t p_flags) {
  167. if (ResourceLoader::is_within_load() && !Thread::is_main_thread()) {
  168. ResourceLoader::resource_changed_connect(this, p_callable, p_flags);
  169. return;
  170. }
  171. if (!is_connected(CoreStringName(changed), p_callable) || p_flags & CONNECT_REFERENCE_COUNTED) {
  172. connect(CoreStringName(changed), p_callable, p_flags);
  173. }
  174. }
  175. void Resource::disconnect_changed(const Callable &p_callable) {
  176. if (ResourceLoader::is_within_load() && !Thread::is_main_thread()) {
  177. ResourceLoader::resource_changed_disconnect(this, p_callable);
  178. return;
  179. }
  180. if (is_connected(CoreStringName(changed), p_callable)) {
  181. disconnect(CoreStringName(changed), p_callable);
  182. }
  183. }
  184. void Resource::reset_state() {
  185. GDVIRTUAL_CALL(_reset_state);
  186. }
  187. Error Resource::copy_from(const Ref<Resource> &p_resource) {
  188. ERR_FAIL_COND_V(p_resource.is_null(), ERR_INVALID_PARAMETER);
  189. if (get_class() != p_resource->get_class()) {
  190. return ERR_INVALID_PARAMETER;
  191. }
  192. _block_emit_changed();
  193. reset_state(); // May want to reset state.
  194. List<PropertyInfo> pi;
  195. p_resource->get_property_list(&pi);
  196. for (const PropertyInfo &E : pi) {
  197. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  198. continue;
  199. }
  200. if (E.name == "resource_path") {
  201. continue; //do not change path
  202. }
  203. set(E.name, p_resource->get(E.name));
  204. }
  205. _unblock_emit_changed();
  206. return OK;
  207. }
  208. void Resource::reload_from_file() {
  209. String path = get_path();
  210. if (!path.is_resource_file()) {
  211. return;
  212. }
  213. Ref<Resource> s = ResourceLoader::load(ResourceLoader::path_remap(path), get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
  214. if (s.is_null()) {
  215. return;
  216. }
  217. copy_from(s);
  218. }
  219. Variant Resource::_duplicate_recursive(const Variant &p_variant, const DuplicateParams &p_params, uint32_t p_usage) const {
  220. // Anything other than object can be simply skipped in case of a shallow copy.
  221. if (!p_params.deep && p_variant.get_type() != Variant::OBJECT) {
  222. return p_variant;
  223. }
  224. switch (p_variant.get_type()) {
  225. case Variant::OBJECT: {
  226. const Ref<Resource> &sr = p_variant;
  227. bool should_duplicate = false;
  228. if (sr.is_valid()) {
  229. if ((p_usage & PROPERTY_USAGE_ALWAYS_DUPLICATE)) {
  230. should_duplicate = true;
  231. } else if ((p_usage & PROPERTY_USAGE_NEVER_DUPLICATE)) {
  232. should_duplicate = false;
  233. } else if (p_params.local_scene) {
  234. should_duplicate = sr->is_local_to_scene();
  235. } else {
  236. switch (p_params.subres_mode) {
  237. case RESOURCE_DEEP_DUPLICATE_NONE: {
  238. should_duplicate = false;
  239. } break;
  240. case RESOURCE_DEEP_DUPLICATE_INTERNAL: {
  241. should_duplicate = p_params.deep && sr->is_built_in();
  242. } break;
  243. case RESOURCE_DEEP_DUPLICATE_ALL: {
  244. should_duplicate = p_params.deep;
  245. } break;
  246. default: {
  247. DEV_ASSERT(false);
  248. }
  249. }
  250. }
  251. }
  252. if (should_duplicate) {
  253. if (thread_duplicate_remap_cache->has(sr)) {
  254. return thread_duplicate_remap_cache->get(sr);
  255. } else {
  256. const Ref<Resource> &dupe = p_params.local_scene
  257. ? sr->duplicate_for_local_scene(p_params.local_scene, *thread_duplicate_remap_cache)
  258. : sr->_duplicate(p_params);
  259. thread_duplicate_remap_cache->insert(sr, dupe);
  260. return dupe;
  261. }
  262. } else {
  263. return p_variant;
  264. }
  265. } break;
  266. case Variant::ARRAY: {
  267. const Array &src = p_variant;
  268. Array dst;
  269. if (src.is_typed()) {
  270. dst.set_typed(src.get_element_type());
  271. }
  272. dst.resize(src.size());
  273. for (int i = 0; i < src.size(); i++) {
  274. dst[i] = _duplicate_recursive(src[i], p_params);
  275. }
  276. return dst;
  277. } break;
  278. case Variant::DICTIONARY: {
  279. const Dictionary &src = p_variant;
  280. Dictionary dst;
  281. if (src.is_typed()) {
  282. dst.set_typed(src.get_key_type(), src.get_value_type());
  283. }
  284. for (const Variant &k : src.get_key_list()) {
  285. const Variant &v = src[k];
  286. dst.set(
  287. _duplicate_recursive(k, p_params),
  288. _duplicate_recursive(v, p_params));
  289. }
  290. return dst;
  291. } break;
  292. case Variant::PACKED_BYTE_ARRAY:
  293. case Variant::PACKED_INT32_ARRAY:
  294. case Variant::PACKED_INT64_ARRAY:
  295. case Variant::PACKED_FLOAT32_ARRAY:
  296. case Variant::PACKED_FLOAT64_ARRAY:
  297. case Variant::PACKED_STRING_ARRAY:
  298. case Variant::PACKED_VECTOR2_ARRAY:
  299. case Variant::PACKED_VECTOR3_ARRAY:
  300. case Variant::PACKED_COLOR_ARRAY:
  301. case Variant::PACKED_VECTOR4_ARRAY: {
  302. return p_variant.duplicate();
  303. } break;
  304. default: {
  305. return p_variant;
  306. }
  307. }
  308. }
  309. Ref<Resource> Resource::_duplicate(const DuplicateParams &p_params) const {
  310. ERR_FAIL_COND_V_MSG(p_params.local_scene && p_params.subres_mode != RESOURCE_DEEP_DUPLICATE_MAX, Ref<Resource>(), "Duplication for local-to-scene can't specify a deep duplicate mode.");
  311. DuplicateRemapCacheT *remap_cache_backup = thread_duplicate_remap_cache;
  312. // These are for avoiding potential duplicates that can happen in custom code
  313. // from participating in the same duplication session (remap cache).
  314. #define BEFORE_USER_CODE thread_duplicate_remap_cache = nullptr;
  315. #define AFTER_USER_CODE thread_duplicate_remap_cache = remap_cache_backup;
  316. List<PropertyInfo> plist;
  317. get_property_list(&plist);
  318. BEFORE_USER_CODE
  319. Ref<Resource> r = Object::cast_to<Resource>(ClassDB::instantiate(get_class()));
  320. AFTER_USER_CODE
  321. ERR_FAIL_COND_V(r.is_null(), Ref<Resource>());
  322. thread_duplicate_remap_cache->insert(Ref<Resource>(this), r);
  323. if (p_params.local_scene) {
  324. r->local_scene = p_params.local_scene;
  325. }
  326. // Duplicate script first, so the scripted properties are considered.
  327. BEFORE_USER_CODE
  328. r->set_script(get_script());
  329. AFTER_USER_CODE
  330. for (const PropertyInfo &E : plist) {
  331. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  332. continue;
  333. }
  334. if (E.name == "script") {
  335. continue;
  336. }
  337. BEFORE_USER_CODE
  338. Variant p = get(E.name);
  339. AFTER_USER_CODE
  340. p = _duplicate_recursive(p, p_params, E.usage);
  341. BEFORE_USER_CODE
  342. r->set(E.name, p);
  343. AFTER_USER_CODE
  344. }
  345. return r;
  346. #undef BEFORE_USER_CODE
  347. #undef AFTER_USER_CODE
  348. }
  349. Ref<Resource> Resource::duplicate_for_local_scene(Node *p_for_scene, DuplicateRemapCacheT &p_remap_cache) const {
  350. #ifdef DEBUG_ENABLED
  351. // The only possibilities for the remap cache passed being valid are these:
  352. // a) It's the same already used as the one of the thread. That happens when this function
  353. // is called within some recursion level within a duplication.
  354. // b) There's no current thread remap cache, which means this function is acting as an entry point.
  355. // This check failing means that this function is being called as an entry point during an ongoing
  356. // duplication, likely due to custom instantiation or setter code. It would be an engine bug because
  357. // code starting or joining a duplicate session must ensure to exit it temporarily when making calls
  358. // that may in turn invoke such custom code.
  359. if (thread_duplicate_remap_cache && &p_remap_cache != thread_duplicate_remap_cache) {
  360. ERR_PRINT("Resource::duplicate_for_local_scene() called during an ongoing duplication session. This is an engine bug.");
  361. }
  362. #endif
  363. DuplicateRemapCacheT *remap_cache_backup = thread_duplicate_remap_cache;
  364. thread_duplicate_remap_cache = &p_remap_cache;
  365. DuplicateParams params;
  366. params.deep = true;
  367. params.local_scene = p_for_scene;
  368. const Ref<Resource> &dupe = _duplicate(params);
  369. thread_duplicate_remap_cache = remap_cache_backup;
  370. return dupe;
  371. }
  372. void Resource::_find_sub_resources(const Variant &p_variant, HashSet<Ref<Resource>> &p_resources_found) {
  373. switch (p_variant.get_type()) {
  374. case Variant::ARRAY: {
  375. Array a = p_variant;
  376. for (int i = 0; i < a.size(); i++) {
  377. _find_sub_resources(a[i], p_resources_found);
  378. }
  379. } break;
  380. case Variant::DICTIONARY: {
  381. Dictionary d = p_variant;
  382. for (const KeyValue<Variant, Variant> &kv : d) {
  383. _find_sub_resources(kv.key, p_resources_found);
  384. _find_sub_resources(kv.value, p_resources_found);
  385. }
  386. } break;
  387. case Variant::OBJECT: {
  388. Ref<Resource> r = p_variant;
  389. if (r.is_valid()) {
  390. p_resources_found.insert(r);
  391. }
  392. } break;
  393. default: {
  394. }
  395. }
  396. }
  397. void Resource::configure_for_local_scene(Node *p_for_scene, DuplicateRemapCacheT &p_remap_cache) {
  398. List<PropertyInfo> plist;
  399. get_property_list(&plist);
  400. reset_local_to_scene();
  401. local_scene = p_for_scene;
  402. for (const PropertyInfo &E : plist) {
  403. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  404. continue;
  405. }
  406. Variant p = get(E.name);
  407. HashSet<Ref<Resource>> sub_resources;
  408. _find_sub_resources(p, sub_resources);
  409. for (Ref<Resource> sr : sub_resources) {
  410. if (sr->is_local_to_scene()) {
  411. if (!p_remap_cache.has(sr)) {
  412. sr->configure_for_local_scene(p_for_scene, p_remap_cache);
  413. p_remap_cache[sr] = sr;
  414. }
  415. }
  416. }
  417. }
  418. }
  419. Ref<Resource> Resource::duplicate(bool p_deep) const {
  420. DuplicateRemapCacheT remap_cache;
  421. bool started_session = false;
  422. if (!thread_duplicate_remap_cache) {
  423. thread_duplicate_remap_cache = &remap_cache;
  424. started_session = true;
  425. }
  426. DuplicateParams params;
  427. params.deep = p_deep;
  428. params.subres_mode = RESOURCE_DEEP_DUPLICATE_INTERNAL;
  429. const Ref<Resource> &dupe = _duplicate(params);
  430. if (started_session) {
  431. thread_duplicate_remap_cache = nullptr;
  432. }
  433. return dupe;
  434. }
  435. Ref<Resource> Resource::duplicate_deep(ResourceDeepDuplicateMode p_deep_subresources_mode) const {
  436. ERR_FAIL_INDEX_V(p_deep_subresources_mode, RESOURCE_DEEP_DUPLICATE_MAX, Ref<Resource>());
  437. DuplicateRemapCacheT remap_cache;
  438. bool started_session = false;
  439. if (!thread_duplicate_remap_cache) {
  440. thread_duplicate_remap_cache = &remap_cache;
  441. started_session = true;
  442. }
  443. DuplicateParams params;
  444. params.deep = true;
  445. params.subres_mode = p_deep_subresources_mode;
  446. const Ref<Resource> &dupe = _duplicate(params);
  447. if (started_session) {
  448. thread_duplicate_remap_cache = nullptr;
  449. }
  450. return dupe;
  451. }
  452. Ref<Resource> Resource::_duplicate_deep_bind(DeepDuplicateMode p_deep_subresources_mode) const {
  453. return _duplicate_from_variant(true, (ResourceDeepDuplicateMode)p_deep_subresources_mode, 0);
  454. }
  455. Ref<Resource> Resource::_duplicate_from_variant(bool p_deep, ResourceDeepDuplicateMode p_deep_subresources_mode, int p_recursion_count) const {
  456. // A call without deep duplication would have been early-rejected at Variant::duplicate() unless it's the root call.
  457. DEV_ASSERT(!(p_recursion_count > 0 && p_deep_subresources_mode == RESOURCE_DEEP_DUPLICATE_NONE));
  458. // When duplicating from Variant, this function may be called multiple times from
  459. // different parts of the data structure being copied. Therefore, we need to create
  460. // a remap cache instance in a way that can be shared among all of the calls.
  461. // Whatever Variant, Array or Dictionary that initiated the call chain will eventually
  462. // claim it, when the stack unwinds up to the root call.
  463. // One exception is that this is the root call.
  464. if (p_recursion_count == 0) {
  465. if (p_deep) {
  466. return duplicate_deep(p_deep_subresources_mode);
  467. } else {
  468. return duplicate(false);
  469. }
  470. }
  471. if (thread_duplicate_remap_cache) {
  472. Resource::DuplicateRemapCacheT::Iterator E = thread_duplicate_remap_cache->find(Ref<Resource>(this));
  473. if (E) {
  474. return E->value;
  475. }
  476. } else {
  477. thread_duplicate_remap_cache = memnew(DuplicateRemapCacheT);
  478. }
  479. DuplicateParams params;
  480. params.deep = p_deep;
  481. params.subres_mode = p_deep_subresources_mode;
  482. const Ref<Resource> dupe = _duplicate(params);
  483. return dupe;
  484. }
  485. void Resource::_teardown_duplicate_from_variant() {
  486. if (thread_duplicate_remap_cache) {
  487. memdelete(thread_duplicate_remap_cache);
  488. thread_duplicate_remap_cache = nullptr;
  489. }
  490. }
  491. void Resource::_set_path(const String &p_path) {
  492. set_path(p_path, false);
  493. }
  494. void Resource::_take_over_path(const String &p_path) {
  495. set_path(p_path, true);
  496. }
  497. RID Resource::get_rid() const {
  498. RID ret;
  499. if (!GDVIRTUAL_CALL(_get_rid, ret)) {
  500. #ifndef DISABLE_DEPRECATED
  501. if (_get_extension() && _get_extension()->get_rid) {
  502. ret = RID::from_uint64(_get_extension()->get_rid(_get_extension_instance()));
  503. }
  504. #endif
  505. }
  506. return ret;
  507. }
  508. #ifdef TOOLS_ENABLED
  509. uint32_t Resource::hash_edited_version_for_preview() const {
  510. uint32_t hash = hash_murmur3_one_32(get_edited_version());
  511. List<PropertyInfo> plist;
  512. get_property_list(&plist);
  513. for (const PropertyInfo &E : plist) {
  514. if (E.usage & PROPERTY_USAGE_STORAGE && E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  515. Ref<Resource> res = get(E.name);
  516. if (res.is_valid()) {
  517. hash = hash_murmur3_one_32(res->hash_edited_version_for_preview(), hash);
  518. }
  519. }
  520. }
  521. return hash;
  522. }
  523. #endif
  524. void Resource::set_local_to_scene(bool p_enable) {
  525. local_to_scene = p_enable;
  526. }
  527. bool Resource::is_local_to_scene() const {
  528. return local_to_scene;
  529. }
  530. Node *Resource::get_local_scene() const {
  531. if (local_scene) {
  532. return local_scene;
  533. }
  534. if (_get_local_scene_func) {
  535. return _get_local_scene_func();
  536. }
  537. return nullptr;
  538. }
  539. void Resource::setup_local_to_scene() {
  540. emit_signal(SNAME("setup_local_to_scene_requested"));
  541. GDVIRTUAL_CALL(_setup_local_to_scene);
  542. }
  543. void Resource::reset_local_to_scene() {
  544. // Restores the state as if setup_local_to_scene() hadn't been called.
  545. }
  546. Node *(*Resource::_get_local_scene_func)() = nullptr;
  547. void (*Resource::_update_configuration_warning)() = nullptr;
  548. void Resource::set_as_translation_remapped(bool p_remapped) {
  549. if (remapped_list.in_list() == p_remapped) {
  550. return;
  551. }
  552. MutexLock lock(ResourceCache::lock);
  553. if (p_remapped) {
  554. ResourceLoader::remapped_list.add(&remapped_list);
  555. } else {
  556. ResourceLoader::remapped_list.remove(&remapped_list);
  557. }
  558. }
  559. // Helps keep IDs the same when loading/saving scenes. An empty ID clears the entry, and an empty ID is returned when not found.
  560. void Resource::set_id_for_path(const String &p_path, const String &p_id) {
  561. #ifdef TOOLS_ENABLED
  562. if (p_id.is_empty()) {
  563. ResourceCache::path_cache_lock.write_lock();
  564. ResourceCache::resource_path_cache[p_path].erase(get_path());
  565. ResourceCache::path_cache_lock.write_unlock();
  566. } else {
  567. ResourceCache::path_cache_lock.write_lock();
  568. ResourceCache::resource_path_cache[p_path][get_path()] = p_id;
  569. ResourceCache::path_cache_lock.write_unlock();
  570. }
  571. #endif
  572. }
  573. String Resource::get_id_for_path(const String &p_path) const {
  574. #ifdef TOOLS_ENABLED
  575. ResourceCache::path_cache_lock.read_lock();
  576. if (ResourceCache::resource_path_cache[p_path].has(get_path())) {
  577. String result = ResourceCache::resource_path_cache[p_path][get_path()];
  578. ResourceCache::path_cache_lock.read_unlock();
  579. return result;
  580. } else {
  581. ResourceCache::path_cache_lock.read_unlock();
  582. return "";
  583. }
  584. #else
  585. return "";
  586. #endif
  587. }
  588. void Resource::_bind_methods() {
  589. ClassDB::bind_method(D_METHOD("set_path", "path"), &Resource::_set_path);
  590. ClassDB::bind_method(D_METHOD("take_over_path", "path"), &Resource::_take_over_path);
  591. ClassDB::bind_method(D_METHOD("get_path"), &Resource::get_path);
  592. ClassDB::bind_method(D_METHOD("set_path_cache", "path"), &Resource::set_path_cache);
  593. ClassDB::bind_method(D_METHOD("set_name", "name"), &Resource::set_name);
  594. ClassDB::bind_method(D_METHOD("get_name"), &Resource::get_name);
  595. ClassDB::bind_method(D_METHOD("get_rid"), &Resource::get_rid);
  596. ClassDB::bind_method(D_METHOD("set_local_to_scene", "enable"), &Resource::set_local_to_scene);
  597. ClassDB::bind_method(D_METHOD("is_local_to_scene"), &Resource::is_local_to_scene);
  598. ClassDB::bind_method(D_METHOD("get_local_scene"), &Resource::get_local_scene);
  599. ClassDB::bind_method(D_METHOD("setup_local_to_scene"), &Resource::setup_local_to_scene);
  600. ClassDB::bind_method(D_METHOD("reset_state"), &Resource::reset_state);
  601. ClassDB::bind_method(D_METHOD("set_id_for_path", "path", "id"), &Resource::set_id_for_path);
  602. ClassDB::bind_method(D_METHOD("get_id_for_path", "path"), &Resource::get_id_for_path);
  603. ClassDB::bind_method(D_METHOD("is_built_in"), &Resource::is_built_in);
  604. ClassDB::bind_static_method("Resource", D_METHOD("generate_scene_unique_id"), &Resource::generate_scene_unique_id);
  605. ClassDB::bind_method(D_METHOD("set_scene_unique_id", "id"), &Resource::set_scene_unique_id);
  606. ClassDB::bind_method(D_METHOD("get_scene_unique_id"), &Resource::get_scene_unique_id);
  607. ClassDB::bind_method(D_METHOD("emit_changed"), &Resource::emit_changed);
  608. ClassDB::bind_method(D_METHOD("duplicate", "deep"), &Resource::duplicate, DEFVAL(false));
  609. ClassDB::bind_method(D_METHOD("duplicate_deep", "deep_subresources_mode"), &Resource::_duplicate_deep_bind, DEFVAL(RESOURCE_DEEP_DUPLICATE_INTERNAL));
  610. // For the bindings, it's much more natural to expose this enum from the Variant realm via Resource.
  611. // Therefore, we can't use BIND_ENUM_CONSTANT here because we need some customization.
  612. ClassDB::bind_integer_constant(get_class_static(), StringName("DeepDuplicateMode"), "DEEP_DUPLICATE_NONE", RESOURCE_DEEP_DUPLICATE_NONE);
  613. ClassDB::bind_integer_constant(get_class_static(), StringName("DeepDuplicateMode"), "DEEP_DUPLICATE_INTERNAL", RESOURCE_DEEP_DUPLICATE_INTERNAL);
  614. ClassDB::bind_integer_constant(get_class_static(), StringName("DeepDuplicateMode"), "DEEP_DUPLICATE_ALL", RESOURCE_DEEP_DUPLICATE_ALL);
  615. ADD_SIGNAL(MethodInfo("changed"));
  616. ADD_SIGNAL(MethodInfo("setup_local_to_scene_requested"));
  617. ADD_GROUP("Resource", "resource_");
  618. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "resource_local_to_scene"), "set_local_to_scene", "is_local_to_scene");
  619. ADD_PROPERTY(PropertyInfo(Variant::STRING, "resource_path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_path", "get_path");
  620. ADD_PROPERTY(PropertyInfo(Variant::STRING, "resource_name"), "set_name", "get_name");
  621. ADD_PROPERTY(PropertyInfo(Variant::STRING, "resource_scene_unique_id", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_scene_unique_id", "get_scene_unique_id");
  622. GDVIRTUAL_BIND(_setup_local_to_scene);
  623. GDVIRTUAL_BIND(_get_rid);
  624. GDVIRTUAL_BIND(_reset_state);
  625. GDVIRTUAL_BIND(_set_path_cache, "path");
  626. }
  627. Resource::Resource() :
  628. remapped_list(this) {}
  629. Resource::~Resource() {
  630. if (unlikely(path_cache.is_empty())) {
  631. return;
  632. }
  633. MutexLock lock(ResourceCache::lock);
  634. // Only unregister from the cache if this is the actual resource listed there.
  635. // (Other resources can have the same value in `path_cache` if loaded with `CACHE_IGNORE`.)
  636. HashMap<String, Resource *>::Iterator E = ResourceCache::resources.find(path_cache);
  637. if (likely(E && E->value == this)) {
  638. ResourceCache::resources.remove(E);
  639. }
  640. }
  641. HashMap<String, Resource *> ResourceCache::resources;
  642. #ifdef TOOLS_ENABLED
  643. HashMap<String, HashMap<String, String>> ResourceCache::resource_path_cache;
  644. #endif
  645. Mutex ResourceCache::lock;
  646. #ifdef TOOLS_ENABLED
  647. RWLock ResourceCache::path_cache_lock;
  648. #endif
  649. void ResourceCache::clear() {
  650. if (!resources.is_empty()) {
  651. if (OS::get_singleton()->is_stdout_verbose()) {
  652. ERR_PRINT(vformat("%d resources still in use at exit.", resources.size()));
  653. for (const KeyValue<String, Resource *> &E : resources) {
  654. print_line(vformat("Resource still in use: %s (%s)", E.key, E.value->get_class()));
  655. }
  656. } else {
  657. ERR_PRINT(vformat("%d resources still in use at exit (run with --verbose for details).", resources.size()));
  658. }
  659. }
  660. resources.clear();
  661. }
  662. bool ResourceCache::has(const String &p_path) {
  663. Resource **res = nullptr;
  664. {
  665. MutexLock mutex_lock(lock);
  666. res = resources.getptr(p_path);
  667. if (res && (*res)->get_reference_count() == 0) {
  668. // This resource is in the process of being deleted, ignore its existence.
  669. (*res)->path_cache = String();
  670. resources.erase(p_path);
  671. res = nullptr;
  672. }
  673. }
  674. if (!res) {
  675. return false;
  676. }
  677. return true;
  678. }
  679. Ref<Resource> ResourceCache::get_ref(const String &p_path) {
  680. Ref<Resource> ref;
  681. {
  682. MutexLock mutex_lock(lock);
  683. Resource **res = resources.getptr(p_path);
  684. if (res) {
  685. ref = Ref<Resource>(*res);
  686. }
  687. if (res && ref.is_null()) {
  688. // This resource is in the process of being deleted, ignore its existence
  689. (*res)->path_cache = String();
  690. resources.erase(p_path);
  691. res = nullptr;
  692. }
  693. }
  694. return ref;
  695. }
  696. void ResourceCache::get_cached_resources(List<Ref<Resource>> *p_resources) {
  697. MutexLock mutex_lock(lock);
  698. LocalVector<String> to_remove;
  699. for (KeyValue<String, Resource *> &E : resources) {
  700. Ref<Resource> ref = Ref<Resource>(E.value);
  701. if (ref.is_null()) {
  702. // This resource is in the process of being deleted, ignore its existence
  703. E.value->path_cache = String();
  704. to_remove.push_back(E.key);
  705. continue;
  706. }
  707. p_resources->push_back(ref);
  708. }
  709. for (const String &E : to_remove) {
  710. resources.erase(E);
  711. }
  712. }
  713. int ResourceCache::get_cached_resource_count() {
  714. MutexLock mutex_lock(lock);
  715. return resources.size();
  716. }