resource_uid.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. // These constants are off by 1, causing the 'z' and '9' characters never to be used.
  37. // This cannot be fixed without breaking compatibility; see GH-83843.
  38. static constexpr uint32_t char_count = ('z' - 'a');
  39. static constexpr uint32_t base = char_count + ('9' - '0');
  40. String ResourceUID::get_cache_file() {
  41. return ProjectSettings::get_singleton()->get_project_data_path().path_join("uid_cache.bin");
  42. }
  43. 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' };
  44. static constexpr uint32_t uuid_characters_element_count = std::size(uuid_characters);
  45. static constexpr uint8_t max_uuid_number_length = 13; // Max 0x7FFFFFFFFFFFFFFF (uid://d4n4ub6itg400) size is 13 characters.
  46. String ResourceUID::id_to_text(ID p_id) const {
  47. if (p_id < 0) {
  48. return "uid://<invalid>";
  49. }
  50. char32_t tmp[max_uuid_number_length];
  51. uint32_t tmp_size = 0;
  52. do {
  53. uint32_t c = p_id % uuid_characters_element_count;
  54. tmp[tmp_size] = uuid_characters[c];
  55. p_id /= uuid_characters_element_count;
  56. ++tmp_size;
  57. } while (p_id);
  58. // tmp_size + uid:// (6) + 1 for null.
  59. String txt;
  60. txt.resize(tmp_size + 7);
  61. char32_t *p = txt.ptrw();
  62. p[0] = 'u';
  63. p[1] = 'i';
  64. p[2] = 'd';
  65. p[3] = ':';
  66. p[4] = '/';
  67. p[5] = '/';
  68. uint32_t size = 6;
  69. // The above loop give the number backward, recopy it in the string in the correct order.
  70. for (uint32_t i = 0; i < tmp_size; ++i) {
  71. p[size++] = tmp[tmp_size - i - 1];
  72. }
  73. p[size] = 0;
  74. return txt;
  75. }
  76. ResourceUID::ID ResourceUID::text_to_id(const String &p_text) const {
  77. if (!p_text.begins_with("uid://") || p_text == "uid://<invalid>") {
  78. return INVALID_ID;
  79. }
  80. uint32_t l = p_text.length();
  81. uint64_t uid = 0;
  82. for (uint32_t i = 6; i < l; i++) {
  83. uid *= base;
  84. uint32_t c = p_text[i];
  85. if (is_ascii_lower_case(c)) {
  86. uid += c - 'a';
  87. } else if (is_digit(c)) {
  88. uid += c - '0' + char_count;
  89. } else {
  90. return INVALID_ID;
  91. }
  92. }
  93. return ID(uid & 0x7FFFFFFFFFFFFFFF);
  94. }
  95. ResourceUID::ID ResourceUID::create_id() {
  96. while (true) {
  97. ID id = INVALID_ID;
  98. MutexLock lock(mutex);
  99. Error err = ((CryptoCore::RandomGenerator *)crypto)->get_random_bytes((uint8_t *)&id, sizeof(id));
  100. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  101. id &= 0x7FFFFFFFFFFFFFFF;
  102. bool exists = unique_ids.has(id);
  103. if (!exists) {
  104. return id;
  105. }
  106. }
  107. }
  108. bool ResourceUID::has_id(ID p_id) const {
  109. MutexLock l(mutex);
  110. return unique_ids.has(p_id);
  111. }
  112. void ResourceUID::add_id(ID p_id, const String &p_path) {
  113. MutexLock l(mutex);
  114. ERR_FAIL_COND(unique_ids.has(p_id));
  115. Cache c;
  116. c.cs = p_path.utf8();
  117. unique_ids[p_id] = c;
  118. changed = true;
  119. }
  120. void ResourceUID::set_id(ID p_id, const String &p_path) {
  121. MutexLock l(mutex);
  122. ERR_FAIL_COND(!unique_ids.has(p_id));
  123. CharString cs = p_path.utf8();
  124. const char *update_ptr = cs.ptr();
  125. const char *cached_ptr = unique_ids[p_id].cs.ptr();
  126. if (update_ptr == nullptr && cached_ptr == nullptr) {
  127. return; // Both are empty strings.
  128. }
  129. if ((update_ptr == nullptr) != (cached_ptr == nullptr) || strcmp(update_ptr, cached_ptr) != 0) {
  130. unique_ids[p_id].cs = cs;
  131. unique_ids[p_id].saved_to_cache = false; //changed
  132. changed = true;
  133. }
  134. }
  135. String ResourceUID::get_id_path(ID p_id) const {
  136. ERR_FAIL_COND_V_MSG(p_id == INVALID_ID, String(), "Invalid UID.");
  137. MutexLock l(mutex);
  138. const ResourceUID::Cache *cache = unique_ids.getptr(p_id);
  139. #if TOOLS_ENABLED
  140. // On startup, the scan_for_uid_on_startup callback should be set and will
  141. // execute EditorFileSystem::scan_for_uid, which scans all project files
  142. // to reload the UID cache before the first scan.
  143. // Note: EditorFileSystem::scan_for_uid sets scan_for_uid_on_startup to nullptr
  144. // once the first scan_for_uid is complete.
  145. if (!cache && scan_for_uid_on_startup) {
  146. scan_for_uid_on_startup();
  147. cache = unique_ids.getptr(p_id);
  148. }
  149. #endif
  150. ERR_FAIL_COND_V_MSG(!cache, String(), vformat("Unrecognized UID: \"%s\".", id_to_text(p_id)));
  151. const CharString &cs = cache->cs;
  152. return String::utf8(cs.ptr());
  153. }
  154. void ResourceUID::remove_id(ID p_id) {
  155. MutexLock l(mutex);
  156. ERR_FAIL_COND(!unique_ids.has(p_id));
  157. unique_ids.erase(p_id);
  158. }
  159. String ResourceUID::uid_to_path(const String &p_uid) {
  160. return singleton->get_id_path(singleton->text_to_id(p_uid));
  161. }
  162. String ResourceUID::path_to_uid(const String &p_path) {
  163. const ID id = ResourceLoader::get_resource_uid(p_path);
  164. if (id == INVALID_ID) {
  165. return p_path;
  166. } else {
  167. return singleton->id_to_text(id);
  168. }
  169. }
  170. String ResourceUID::ensure_path(const String &p_uid_or_path) {
  171. if (p_uid_or_path.begins_with("uid://")) {
  172. return uid_to_path(p_uid_or_path);
  173. }
  174. return p_uid_or_path;
  175. }
  176. Error ResourceUID::save_to_cache() {
  177. String cache_file = get_cache_file();
  178. if (!FileAccess::exists(cache_file)) {
  179. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  180. d->make_dir_recursive(String(cache_file).get_base_dir()); //ensure base dir exists
  181. }
  182. Ref<FileAccess> f = FileAccess::open(cache_file, FileAccess::WRITE);
  183. if (f.is_null()) {
  184. return ERR_CANT_OPEN;
  185. }
  186. MutexLock l(mutex);
  187. f->store_32(unique_ids.size());
  188. cache_entries = 0;
  189. for (KeyValue<ID, Cache> &E : unique_ids) {
  190. f->store_64(uint64_t(E.key));
  191. uint32_t s = E.value.cs.length();
  192. f->store_32(s);
  193. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  194. E.value.saved_to_cache = true;
  195. cache_entries++;
  196. }
  197. changed = false;
  198. return OK;
  199. }
  200. Error ResourceUID::load_from_cache(bool p_reset) {
  201. Ref<FileAccess> f = FileAccess::open(get_cache_file(), FileAccess::READ);
  202. if (f.is_null()) {
  203. return ERR_CANT_OPEN;
  204. }
  205. MutexLock l(mutex);
  206. if (p_reset) {
  207. unique_ids.clear();
  208. }
  209. uint32_t entry_count = f->get_32();
  210. for (uint32_t i = 0; i < entry_count; i++) {
  211. int64_t id = f->get_64();
  212. int32_t len = f->get_32();
  213. Cache c;
  214. c.cs.resize(len + 1);
  215. ERR_FAIL_COND_V(c.cs.size() != len + 1, ERR_FILE_CORRUPT); // Out of memory.
  216. c.cs[len] = 0;
  217. int32_t rl = f->get_buffer((uint8_t *)c.cs.ptrw(), len);
  218. ERR_FAIL_COND_V(rl != len, ERR_FILE_CORRUPT);
  219. c.saved_to_cache = true;
  220. unique_ids[id] = c;
  221. }
  222. cache_entries = entry_count;
  223. changed = false;
  224. return OK;
  225. }
  226. Error ResourceUID::update_cache() {
  227. if (!changed) {
  228. return OK;
  229. }
  230. if (cache_entries == 0) {
  231. return save_to_cache();
  232. }
  233. MutexLock l(mutex);
  234. Ref<FileAccess> f;
  235. for (KeyValue<ID, Cache> &E : unique_ids) {
  236. if (!E.value.saved_to_cache) {
  237. if (f.is_null()) {
  238. f = FileAccess::open(get_cache_file(), FileAccess::READ_WRITE); // Append.
  239. if (f.is_null()) {
  240. return ERR_CANT_OPEN;
  241. }
  242. f->seek_end();
  243. }
  244. f->store_64(uint64_t(E.key));
  245. uint32_t s = E.value.cs.length();
  246. f->store_32(s);
  247. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  248. E.value.saved_to_cache = true;
  249. cache_entries++;
  250. }
  251. }
  252. if (f.is_valid()) {
  253. f->seek(0);
  254. f->store_32(cache_entries); //update amount of entries
  255. }
  256. changed = false;
  257. return OK;
  258. }
  259. String ResourceUID::get_path_from_cache(Ref<FileAccess> &p_cache_file, const String &p_uid_string) {
  260. const uint32_t entry_count = p_cache_file->get_32();
  261. CharString cs;
  262. for (uint32_t i = 0; i < entry_count; i++) {
  263. int64_t id = p_cache_file->get_64();
  264. int32_t len = p_cache_file->get_32();
  265. cs.resize(len + 1);
  266. ERR_FAIL_COND_V(cs.size() != len + 1, String());
  267. cs[len] = 0;
  268. int32_t rl = p_cache_file->get_buffer((uint8_t *)cs.ptrw(), len);
  269. ERR_FAIL_COND_V(rl != len, String());
  270. if (singleton->id_to_text(id) == p_uid_string) {
  271. return String::utf8(cs.get_data());
  272. }
  273. }
  274. return String();
  275. }
  276. void ResourceUID::clear() {
  277. cache_entries = 0;
  278. unique_ids.clear();
  279. changed = false;
  280. }
  281. void ResourceUID::_bind_methods() {
  282. ClassDB::bind_method(D_METHOD("id_to_text", "id"), &ResourceUID::id_to_text);
  283. ClassDB::bind_method(D_METHOD("text_to_id", "text_id"), &ResourceUID::text_to_id);
  284. ClassDB::bind_method(D_METHOD("create_id"), &ResourceUID::create_id);
  285. ClassDB::bind_method(D_METHOD("has_id", "id"), &ResourceUID::has_id);
  286. ClassDB::bind_method(D_METHOD("add_id", "id", "path"), &ResourceUID::add_id);
  287. ClassDB::bind_method(D_METHOD("set_id", "id", "path"), &ResourceUID::set_id);
  288. ClassDB::bind_method(D_METHOD("get_id_path", "id"), &ResourceUID::get_id_path);
  289. ClassDB::bind_method(D_METHOD("remove_id", "id"), &ResourceUID::remove_id);
  290. BIND_CONSTANT(INVALID_ID)
  291. }
  292. ResourceUID *ResourceUID::singleton = nullptr;
  293. ResourceUID::ResourceUID() {
  294. ERR_FAIL_COND(singleton != nullptr);
  295. singleton = this;
  296. crypto = memnew(CryptoCore::RandomGenerator);
  297. ((CryptoCore::RandomGenerator *)crypto)->init();
  298. }
  299. ResourceUID::~ResourceUID() {
  300. memdelete((CryptoCore::RandomGenerator *)crypto);
  301. }