resource_uid.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /**************************************************************************/
  2. /* resource_uid.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_uid.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/crypto/crypto_core.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_loader.h"
  36. #include "core/math/random_pcg.h"
  37. // These constants are off by 1, causing the 'z' and '9' characters never to be used.
  38. // This cannot be fixed without breaking compatibility; see GH-83843.
  39. static constexpr uint32_t char_count = ('z' - 'a');
  40. static constexpr uint32_t base = char_count + ('9' - '0');
  41. String ResourceUID::get_cache_file() {
  42. return ProjectSettings::get_singleton()->get_project_data_path().path_join("uid_cache.bin");
  43. }
  44. static constexpr uint8_t uuid_characters[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', '0', '1', '2', '3', '4', '5', '6', '7', '8' };
  45. static constexpr uint32_t uuid_characters_element_count = std_size(uuid_characters);
  46. static constexpr uint8_t max_uuid_number_length = 13; // Max 0x7FFFFFFFFFFFFFFF (uid://d4n4ub6itg400) size is 13 characters.
  47. String ResourceUID::id_to_text(ID p_id) const {
  48. if (p_id < 0) {
  49. return "uid://<invalid>";
  50. }
  51. char32_t tmp[max_uuid_number_length];
  52. uint32_t tmp_size = 0;
  53. do {
  54. uint32_t c = p_id % uuid_characters_element_count;
  55. tmp[tmp_size] = uuid_characters[c];
  56. p_id /= uuid_characters_element_count;
  57. ++tmp_size;
  58. } while (p_id);
  59. // tmp_size + uid:// (6) + 1 for null.
  60. String txt;
  61. txt.resize_uninitialized(tmp_size + 7);
  62. char32_t *p = txt.ptrw();
  63. p[0] = 'u';
  64. p[1] = 'i';
  65. p[2] = 'd';
  66. p[3] = ':';
  67. p[4] = '/';
  68. p[5] = '/';
  69. uint32_t size = 6;
  70. // The above loop give the number backward, recopy it in the string in the correct order.
  71. for (uint32_t i = 0; i < tmp_size; ++i) {
  72. p[size++] = tmp[tmp_size - i - 1];
  73. }
  74. p[size] = 0;
  75. return txt;
  76. }
  77. ResourceUID::ID ResourceUID::text_to_id(const String &p_text) const {
  78. if (!p_text.begins_with("uid://") || p_text == "uid://<invalid>") {
  79. return INVALID_ID;
  80. }
  81. uint32_t l = p_text.length();
  82. uint64_t uid = 0;
  83. for (uint32_t i = 6; i < l; i++) {
  84. uid *= base;
  85. uint32_t c = p_text[i];
  86. if (is_ascii_lower_case(c)) {
  87. uid += c - 'a';
  88. } else if (is_digit(c)) {
  89. uid += c - '0' + char_count;
  90. } else {
  91. return INVALID_ID;
  92. }
  93. }
  94. return ID(uid & 0x7FFFFFFFFFFFFFFF);
  95. }
  96. ResourceUID::ID ResourceUID::create_id() {
  97. // mbedTLS may not be fully initialized when the ResourceUID is created, so we
  98. // need to lazily instantiate the random number generator.
  99. if (crypto == nullptr) {
  100. crypto = memnew(CryptoCore::RandomGenerator);
  101. ((CryptoCore::RandomGenerator *)crypto)->init();
  102. }
  103. while (true) {
  104. ID id = INVALID_ID;
  105. MutexLock lock(mutex);
  106. Error err = ((CryptoCore::RandomGenerator *)crypto)->get_random_bytes((uint8_t *)&id, sizeof(id));
  107. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  108. id &= 0x7FFFFFFFFFFFFFFF;
  109. bool exists = unique_ids.has(id);
  110. if (!exists) {
  111. return id;
  112. }
  113. }
  114. }
  115. ResourceUID::ID ResourceUID::create_id_for_path(const String &p_path) {
  116. ID id = INVALID_ID;
  117. RandomPCG rng;
  118. const String project_name = GLOBAL_GET("application/config/name");
  119. // Use lowercase file name as random seed.
  120. // This ensures that case differences don't cause UIDs to shift on case-insensitive filesystems. The downside is that identical files with different case
  121. // (but otherwise identical name) will run into a hash collision, but this is a very rare scenario.
  122. rng.seed(project_name.hash64() * p_path.to_lower().hash64() * FileAccess::get_md5(p_path).hash64());
  123. while (true) {
  124. int64_t num1 = rng.rand();
  125. int64_t num2 = ((int64_t)rng.rand()) << 32;
  126. id = (num1 | num2) & 0x7FFFFFFFFFFFFFFF;
  127. MutexLock lock(mutex);
  128. if (!unique_ids.has(id)) {
  129. break;
  130. }
  131. }
  132. return id;
  133. }
  134. bool ResourceUID::has_id(ID p_id) const {
  135. MutexLock l(mutex);
  136. return unique_ids.has(p_id);
  137. }
  138. void ResourceUID::add_id(ID p_id, const String &p_path) {
  139. MutexLock l(mutex);
  140. ERR_FAIL_COND(unique_ids.has(p_id));
  141. Cache c;
  142. c.cs = p_path.utf8();
  143. unique_ids[p_id] = c;
  144. if (use_reverse_cache) {
  145. reverse_cache[c.cs] = p_id;
  146. }
  147. changed = true;
  148. }
  149. void ResourceUID::set_id(ID p_id, const String &p_path) {
  150. MutexLock l(mutex);
  151. ERR_FAIL_COND(!unique_ids.has(p_id));
  152. CharString cs = p_path.utf8();
  153. const char *update_ptr = cs.ptr();
  154. const char *cached_ptr = unique_ids[p_id].cs.ptr();
  155. if (update_ptr == nullptr && cached_ptr == nullptr) {
  156. return; // Both are empty strings.
  157. }
  158. if ((update_ptr == nullptr) != (cached_ptr == nullptr) || strcmp(update_ptr, cached_ptr) != 0) {
  159. unique_ids[p_id].cs = cs;
  160. unique_ids[p_id].saved_to_cache = false; //changed
  161. if (use_reverse_cache) {
  162. reverse_cache[cs] = p_id;
  163. }
  164. changed = true;
  165. }
  166. }
  167. String ResourceUID::get_id_path(ID p_id) const {
  168. ERR_FAIL_COND_V_MSG(p_id == INVALID_ID, String(), "Invalid UID.");
  169. MutexLock l(mutex);
  170. const ResourceUID::Cache *cache = unique_ids.getptr(p_id);
  171. #if TOOLS_ENABLED
  172. // On startup, the scan_for_uid_on_startup callback should be set and will
  173. // execute EditorFileSystem::scan_for_uid, which scans all project files
  174. // to reload the UID cache before the first scan.
  175. // Note: EditorFileSystem::scan_for_uid sets scan_for_uid_on_startup to nullptr
  176. // once the first scan_for_uid is complete.
  177. if (!cache && scan_for_uid_on_startup) {
  178. scan_for_uid_on_startup();
  179. cache = unique_ids.getptr(p_id);
  180. }
  181. #endif
  182. ERR_FAIL_COND_V_MSG(!cache, String(), vformat("Unrecognized UID: \"%s\".", id_to_text(p_id)));
  183. const CharString &cs = cache->cs;
  184. return String::utf8(cs.ptr());
  185. }
  186. ResourceUID::ID ResourceUID::get_path_id(const String &p_path) const {
  187. const ID *id = reverse_cache.getptr(p_path.utf8());
  188. if (id) {
  189. return *id;
  190. }
  191. return INVALID_ID;
  192. }
  193. void ResourceUID::remove_id(ID p_id) {
  194. MutexLock l(mutex);
  195. ERR_FAIL_COND(!unique_ids.has(p_id));
  196. if (use_reverse_cache) {
  197. reverse_cache.erase(unique_ids[p_id].cs);
  198. }
  199. unique_ids.erase(p_id);
  200. }
  201. String ResourceUID::uid_to_path(const String &p_uid) {
  202. return singleton->get_id_path(singleton->text_to_id(p_uid));
  203. }
  204. String ResourceUID::path_to_uid(const String &p_path) {
  205. const ID id = ResourceLoader::get_resource_uid(p_path);
  206. if (id == INVALID_ID) {
  207. return p_path;
  208. } else {
  209. return singleton->id_to_text(id);
  210. }
  211. }
  212. String ResourceUID::ensure_path(const String &p_uid_or_path) {
  213. if (p_uid_or_path.begins_with("uid://")) {
  214. return uid_to_path(p_uid_or_path);
  215. }
  216. return p_uid_or_path;
  217. }
  218. Error ResourceUID::save_to_cache() {
  219. String cache_file = get_cache_file();
  220. if (!FileAccess::exists(cache_file)) {
  221. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  222. d->make_dir_recursive(String(cache_file).get_base_dir()); //ensure base dir exists
  223. }
  224. Ref<FileAccess> f = FileAccess::open(cache_file, FileAccess::WRITE);
  225. if (f.is_null()) {
  226. return ERR_CANT_OPEN;
  227. }
  228. MutexLock l(mutex);
  229. f->store_32(unique_ids.size());
  230. cache_entries = 0;
  231. for (KeyValue<ID, Cache> &E : unique_ids) {
  232. f->store_64(uint64_t(E.key));
  233. uint32_t s = E.value.cs.length();
  234. f->store_32(s);
  235. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  236. E.value.saved_to_cache = true;
  237. cache_entries++;
  238. }
  239. changed = false;
  240. return OK;
  241. }
  242. Error ResourceUID::load_from_cache(bool p_reset) {
  243. Ref<FileAccess> f = FileAccess::open(get_cache_file(), FileAccess::READ);
  244. if (f.is_null()) {
  245. return ERR_CANT_OPEN;
  246. }
  247. MutexLock l(mutex);
  248. if (p_reset) {
  249. if (use_reverse_cache) {
  250. reverse_cache.clear();
  251. }
  252. unique_ids.clear();
  253. }
  254. uint32_t entry_count = f->get_32();
  255. for (uint32_t i = 0; i < entry_count; i++) {
  256. int64_t id = f->get_64();
  257. int32_t len = f->get_32();
  258. Cache c;
  259. c.cs.resize_uninitialized(len + 1);
  260. ERR_FAIL_COND_V(c.cs.size() != len + 1, ERR_FILE_CORRUPT); // Out of memory.
  261. c.cs[len] = 0;
  262. int32_t rl = f->get_buffer((uint8_t *)c.cs.ptrw(), len);
  263. ERR_FAIL_COND_V(rl != len, ERR_FILE_CORRUPT);
  264. c.saved_to_cache = true;
  265. unique_ids[id] = c;
  266. if (use_reverse_cache) {
  267. reverse_cache[c.cs] = id;
  268. }
  269. }
  270. cache_entries = entry_count;
  271. changed = false;
  272. return OK;
  273. }
  274. Error ResourceUID::update_cache() {
  275. if (!changed) {
  276. return OK;
  277. }
  278. if (cache_entries == 0) {
  279. return save_to_cache();
  280. }
  281. MutexLock l(mutex);
  282. Ref<FileAccess> f;
  283. for (KeyValue<ID, Cache> &E : unique_ids) {
  284. if (!E.value.saved_to_cache) {
  285. if (f.is_null()) {
  286. f = FileAccess::open(get_cache_file(), FileAccess::READ_WRITE); // Append.
  287. if (f.is_null()) {
  288. return ERR_CANT_OPEN;
  289. }
  290. f->seek_end();
  291. }
  292. f->store_64(uint64_t(E.key));
  293. uint32_t s = E.value.cs.length();
  294. f->store_32(s);
  295. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  296. E.value.saved_to_cache = true;
  297. cache_entries++;
  298. }
  299. }
  300. if (f.is_valid()) {
  301. f->seek(0);
  302. f->store_32(cache_entries); //update amount of entries
  303. }
  304. changed = false;
  305. return OK;
  306. }
  307. String ResourceUID::get_path_from_cache(Ref<FileAccess> &p_cache_file, const String &p_uid_string) {
  308. const int64_t uid_from_string = singleton->text_to_id(p_uid_string);
  309. if (uid_from_string != INVALID_ID) {
  310. const uint32_t entry_count = p_cache_file->get_32();
  311. CharString cs;
  312. for (uint32_t i = 0; i < entry_count; i++) {
  313. int64_t id = p_cache_file->get_64();
  314. int32_t len = p_cache_file->get_32();
  315. cs.resize_uninitialized(len + 1);
  316. ERR_FAIL_COND_V(cs.size() != len + 1, String());
  317. cs[len] = 0;
  318. int32_t rl = p_cache_file->get_buffer((uint8_t *)cs.ptrw(), len);
  319. ERR_FAIL_COND_V(rl != len, String());
  320. if (id == uid_from_string) {
  321. return String::utf8(cs.get_data());
  322. }
  323. }
  324. }
  325. return String();
  326. }
  327. void ResourceUID::clear() {
  328. cache_entries = 0;
  329. if (use_reverse_cache) {
  330. reverse_cache.clear();
  331. }
  332. unique_ids.clear();
  333. changed = false;
  334. }
  335. void ResourceUID::_bind_methods() {
  336. ClassDB::bind_method(D_METHOD("id_to_text", "id"), &ResourceUID::id_to_text);
  337. ClassDB::bind_method(D_METHOD("text_to_id", "text_id"), &ResourceUID::text_to_id);
  338. ClassDB::bind_method(D_METHOD("create_id"), &ResourceUID::create_id);
  339. ClassDB::bind_method(D_METHOD("create_id_for_path", "path"), &ResourceUID::create_id_for_path);
  340. ClassDB::bind_method(D_METHOD("has_id", "id"), &ResourceUID::has_id);
  341. ClassDB::bind_method(D_METHOD("add_id", "id", "path"), &ResourceUID::add_id);
  342. ClassDB::bind_method(D_METHOD("set_id", "id", "path"), &ResourceUID::set_id);
  343. ClassDB::bind_method(D_METHOD("get_id_path", "id"), &ResourceUID::get_id_path);
  344. ClassDB::bind_method(D_METHOD("remove_id", "id"), &ResourceUID::remove_id);
  345. ClassDB::bind_static_method("ResourceUID", D_METHOD("uid_to_path", "uid"), &ResourceUID::uid_to_path);
  346. ClassDB::bind_static_method("ResourceUID", D_METHOD("path_to_uid", "path"), &ResourceUID::path_to_uid);
  347. ClassDB::bind_static_method("ResourceUID", D_METHOD("ensure_path", "path_or_uid"), &ResourceUID::ensure_path);
  348. BIND_CONSTANT(INVALID_ID)
  349. }
  350. ResourceUID *ResourceUID::singleton = nullptr;
  351. ResourceUID::ResourceUID() {
  352. ERR_FAIL_COND(singleton != nullptr);
  353. singleton = this;
  354. }
  355. ResourceUID::~ResourceUID() {
  356. if (crypto != nullptr) {
  357. memdelete((CryptoCore::RandomGenerator *)crypto);
  358. }
  359. }