resource_uid.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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(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. rng.seed(project_name.hash64() * p_path.hash64() * FileAccess::get_md5(p_path).hash64());
  120. while (true) {
  121. int64_t num1 = rng.rand();
  122. int64_t num2 = ((int64_t)rng.rand()) << 32;
  123. id = (num1 | num2) & 0x7FFFFFFFFFFFFFFF;
  124. MutexLock lock(mutex);
  125. if (!unique_ids.has(id)) {
  126. break;
  127. }
  128. }
  129. return id;
  130. }
  131. bool ResourceUID::has_id(ID p_id) const {
  132. MutexLock l(mutex);
  133. return unique_ids.has(p_id);
  134. }
  135. void ResourceUID::add_id(ID p_id, const String &p_path) {
  136. MutexLock l(mutex);
  137. ERR_FAIL_COND(unique_ids.has(p_id));
  138. Cache c;
  139. c.cs = p_path.utf8();
  140. unique_ids[p_id] = c;
  141. changed = true;
  142. }
  143. void ResourceUID::set_id(ID p_id, const String &p_path) {
  144. MutexLock l(mutex);
  145. ERR_FAIL_COND(!unique_ids.has(p_id));
  146. CharString cs = p_path.utf8();
  147. const char *update_ptr = cs.ptr();
  148. const char *cached_ptr = unique_ids[p_id].cs.ptr();
  149. if (update_ptr == nullptr && cached_ptr == nullptr) {
  150. return; // Both are empty strings.
  151. }
  152. if ((update_ptr == nullptr) != (cached_ptr == nullptr) || strcmp(update_ptr, cached_ptr) != 0) {
  153. unique_ids[p_id].cs = cs;
  154. unique_ids[p_id].saved_to_cache = false; //changed
  155. changed = true;
  156. }
  157. }
  158. String ResourceUID::get_id_path(ID p_id) const {
  159. ERR_FAIL_COND_V_MSG(p_id == INVALID_ID, String(), "Invalid UID.");
  160. MutexLock l(mutex);
  161. const ResourceUID::Cache *cache = unique_ids.getptr(p_id);
  162. #if TOOLS_ENABLED
  163. // On startup, the scan_for_uid_on_startup callback should be set and will
  164. // execute EditorFileSystem::scan_for_uid, which scans all project files
  165. // to reload the UID cache before the first scan.
  166. // Note: EditorFileSystem::scan_for_uid sets scan_for_uid_on_startup to nullptr
  167. // once the first scan_for_uid is complete.
  168. if (!cache && scan_for_uid_on_startup) {
  169. scan_for_uid_on_startup();
  170. cache = unique_ids.getptr(p_id);
  171. }
  172. #endif
  173. ERR_FAIL_COND_V_MSG(!cache, String(), vformat("Unrecognized UID: \"%s\".", id_to_text(p_id)));
  174. const CharString &cs = cache->cs;
  175. return String::utf8(cs.ptr());
  176. }
  177. void ResourceUID::remove_id(ID p_id) {
  178. MutexLock l(mutex);
  179. ERR_FAIL_COND(!unique_ids.has(p_id));
  180. unique_ids.erase(p_id);
  181. }
  182. String ResourceUID::uid_to_path(const String &p_uid) {
  183. return singleton->get_id_path(singleton->text_to_id(p_uid));
  184. }
  185. String ResourceUID::path_to_uid(const String &p_path) {
  186. const ID id = ResourceLoader::get_resource_uid(p_path);
  187. if (id == INVALID_ID) {
  188. return p_path;
  189. } else {
  190. return singleton->id_to_text(id);
  191. }
  192. }
  193. String ResourceUID::ensure_path(const String &p_uid_or_path) {
  194. if (p_uid_or_path.begins_with("uid://")) {
  195. return uid_to_path(p_uid_or_path);
  196. }
  197. return p_uid_or_path;
  198. }
  199. Error ResourceUID::save_to_cache() {
  200. String cache_file = get_cache_file();
  201. if (!FileAccess::exists(cache_file)) {
  202. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  203. d->make_dir_recursive(String(cache_file).get_base_dir()); //ensure base dir exists
  204. }
  205. Ref<FileAccess> f = FileAccess::open(cache_file, FileAccess::WRITE);
  206. if (f.is_null()) {
  207. return ERR_CANT_OPEN;
  208. }
  209. MutexLock l(mutex);
  210. f->store_32(unique_ids.size());
  211. cache_entries = 0;
  212. for (KeyValue<ID, Cache> &E : unique_ids) {
  213. f->store_64(uint64_t(E.key));
  214. uint32_t s = E.value.cs.length();
  215. f->store_32(s);
  216. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  217. E.value.saved_to_cache = true;
  218. cache_entries++;
  219. }
  220. changed = false;
  221. return OK;
  222. }
  223. Error ResourceUID::load_from_cache(bool p_reset) {
  224. Ref<FileAccess> f = FileAccess::open(get_cache_file(), FileAccess::READ);
  225. if (f.is_null()) {
  226. return ERR_CANT_OPEN;
  227. }
  228. MutexLock l(mutex);
  229. if (p_reset) {
  230. unique_ids.clear();
  231. }
  232. uint32_t entry_count = f->get_32();
  233. for (uint32_t i = 0; i < entry_count; i++) {
  234. int64_t id = f->get_64();
  235. int32_t len = f->get_32();
  236. Cache c;
  237. c.cs.resize(len + 1);
  238. ERR_FAIL_COND_V(c.cs.size() != len + 1, ERR_FILE_CORRUPT); // Out of memory.
  239. c.cs[len] = 0;
  240. int32_t rl = f->get_buffer((uint8_t *)c.cs.ptrw(), len);
  241. ERR_FAIL_COND_V(rl != len, ERR_FILE_CORRUPT);
  242. c.saved_to_cache = true;
  243. unique_ids[id] = c;
  244. }
  245. cache_entries = entry_count;
  246. changed = false;
  247. return OK;
  248. }
  249. Error ResourceUID::update_cache() {
  250. if (!changed) {
  251. return OK;
  252. }
  253. if (cache_entries == 0) {
  254. return save_to_cache();
  255. }
  256. MutexLock l(mutex);
  257. Ref<FileAccess> f;
  258. for (KeyValue<ID, Cache> &E : unique_ids) {
  259. if (!E.value.saved_to_cache) {
  260. if (f.is_null()) {
  261. f = FileAccess::open(get_cache_file(), FileAccess::READ_WRITE); // Append.
  262. if (f.is_null()) {
  263. return ERR_CANT_OPEN;
  264. }
  265. f->seek_end();
  266. }
  267. f->store_64(uint64_t(E.key));
  268. uint32_t s = E.value.cs.length();
  269. f->store_32(s);
  270. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  271. E.value.saved_to_cache = true;
  272. cache_entries++;
  273. }
  274. }
  275. if (f.is_valid()) {
  276. f->seek(0);
  277. f->store_32(cache_entries); //update amount of entries
  278. }
  279. changed = false;
  280. return OK;
  281. }
  282. String ResourceUID::get_path_from_cache(Ref<FileAccess> &p_cache_file, const String &p_uid_string) {
  283. const uint32_t entry_count = p_cache_file->get_32();
  284. CharString cs;
  285. for (uint32_t i = 0; i < entry_count; i++) {
  286. int64_t id = p_cache_file->get_64();
  287. int32_t len = p_cache_file->get_32();
  288. cs.resize(len + 1);
  289. ERR_FAIL_COND_V(cs.size() != len + 1, String());
  290. cs[len] = 0;
  291. int32_t rl = p_cache_file->get_buffer((uint8_t *)cs.ptrw(), len);
  292. ERR_FAIL_COND_V(rl != len, String());
  293. if (singleton->id_to_text(id) == p_uid_string) {
  294. return String::utf8(cs.get_data());
  295. }
  296. }
  297. return String();
  298. }
  299. void ResourceUID::clear() {
  300. cache_entries = 0;
  301. unique_ids.clear();
  302. changed = false;
  303. }
  304. void ResourceUID::_bind_methods() {
  305. ClassDB::bind_method(D_METHOD("id_to_text", "id"), &ResourceUID::id_to_text);
  306. ClassDB::bind_method(D_METHOD("text_to_id", "text_id"), &ResourceUID::text_to_id);
  307. ClassDB::bind_method(D_METHOD("create_id"), &ResourceUID::create_id);
  308. ClassDB::bind_method(D_METHOD("create_id_for_path", "path"), &ResourceUID::create_id_for_path);
  309. ClassDB::bind_method(D_METHOD("has_id", "id"), &ResourceUID::has_id);
  310. ClassDB::bind_method(D_METHOD("add_id", "id", "path"), &ResourceUID::add_id);
  311. ClassDB::bind_method(D_METHOD("set_id", "id", "path"), &ResourceUID::set_id);
  312. ClassDB::bind_method(D_METHOD("get_id_path", "id"), &ResourceUID::get_id_path);
  313. ClassDB::bind_method(D_METHOD("remove_id", "id"), &ResourceUID::remove_id);
  314. BIND_CONSTANT(INVALID_ID)
  315. }
  316. ResourceUID *ResourceUID::singleton = nullptr;
  317. ResourceUID::ResourceUID() {
  318. ERR_FAIL_COND(singleton != nullptr);
  319. singleton = this;
  320. }
  321. ResourceUID::~ResourceUID() {
  322. if (crypto != nullptr) {
  323. memdelete((CryptoCore::RandomGenerator *)crypto);
  324. }
  325. }