editor_resource_preview.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /**************************************************************************/
  2. /* editor_resource_preview.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 "editor_resource_preview.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/io/resource_saver.h"
  35. #include "core/variant/variant_utility.h"
  36. #include "editor/editor_node.h"
  37. #include "editor/editor_paths.h"
  38. #include "editor/editor_settings.h"
  39. #include "editor/editor_string_names.h"
  40. #include "editor/themes/editor_scale.h"
  41. #include "scene/resources/image_texture.h"
  42. #include "servers/rendering/rendering_server_default.h"
  43. bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
  44. bool success = false;
  45. if (GDVIRTUAL_CALL(_handles, p_type, success)) {
  46. return success;
  47. }
  48. ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::_handles needs to be overridden.");
  49. }
  50. Ref<Texture2D> EditorResourcePreviewGenerator::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  51. Ref<Texture2D> preview;
  52. if (GDVIRTUAL_CALL(_generate, p_from, p_size, p_metadata, preview)) {
  53. return preview;
  54. }
  55. ERR_FAIL_V_MSG(Ref<Texture2D>(), "EditorResourcePreviewGenerator::_generate needs to be overridden.");
  56. }
  57. Ref<Texture2D> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {
  58. Ref<Texture2D> preview;
  59. if (GDVIRTUAL_CALL(_generate_from_path, p_path, p_size, p_metadata, preview)) {
  60. return preview;
  61. }
  62. Ref<Resource> res = ResourceLoader::load(p_path);
  63. if (!res.is_valid()) {
  64. return res;
  65. }
  66. return generate(res, p_size, p_metadata);
  67. }
  68. bool EditorResourcePreviewGenerator::generate_small_preview_automatically() const {
  69. bool success = false;
  70. GDVIRTUAL_CALL(_generate_small_preview_automatically, success);
  71. return success;
  72. }
  73. bool EditorResourcePreviewGenerator::can_generate_small_preview() const {
  74. bool success = false;
  75. GDVIRTUAL_CALL(_can_generate_small_preview, success);
  76. return success;
  77. }
  78. void EditorResourcePreviewGenerator::_bind_methods() {
  79. GDVIRTUAL_BIND(_handles, "type");
  80. GDVIRTUAL_BIND(_generate, "resource", "size", "metadata");
  81. GDVIRTUAL_BIND(_generate_from_path, "path", "size", "metadata");
  82. GDVIRTUAL_BIND(_generate_small_preview_automatically);
  83. GDVIRTUAL_BIND(_can_generate_small_preview);
  84. }
  85. EditorResourcePreviewGenerator::EditorResourcePreviewGenerator() {
  86. }
  87. void EditorResourcePreviewGenerator::DrawRequester::request_and_wait(RID p_viewport) const {
  88. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  89. Callable request_vp_update_once = callable_mp(RS::get_singleton(), &RS::viewport_set_update_mode).bind(p_viewport, RS::VIEWPORT_UPDATE_ONCE);
  90. RS::get_singleton()->connect(SNAME("frame_pre_draw"), request_vp_update_once, Object::CONNECT_ONE_SHOT);
  91. RS::get_singleton()->request_frame_drawn_callback(callable_mp(const_cast<EditorResourcePreviewGenerator::DrawRequester *>(this), &EditorResourcePreviewGenerator::DrawRequester::_post_semaphore));
  92. semaphore.wait();
  93. } else {
  94. RS::get_singleton()->draw(false);
  95. }
  96. }
  97. void EditorResourcePreviewGenerator::DrawRequester::abort() const {
  98. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  99. semaphore.post();
  100. }
  101. }
  102. Variant EditorResourcePreviewGenerator::DrawRequester::_post_semaphore() const {
  103. semaphore.post();
  104. return Variant(); // Needed because of how the callback is used.
  105. }
  106. bool EditorResourcePreview::is_threaded() const {
  107. return RSG::texture_storage->can_create_resources_async();
  108. }
  109. void EditorResourcePreview::_thread_func(void *ud) {
  110. EditorResourcePreview *erp = (EditorResourcePreview *)ud;
  111. erp->_thread();
  112. }
  113. void EditorResourcePreview::_preview_ready(const String &p_path, int p_hash, const Ref<Texture2D> &p_texture, const Ref<Texture2D> &p_small_texture, ObjectID id, const StringName &p_func, const Variant &p_ud, const Dictionary &p_metadata) {
  114. {
  115. MutexLock lock(preview_mutex);
  116. uint64_t modified_time = 0;
  117. if (!p_path.begins_with("ID:")) {
  118. modified_time = FileAccess::get_modified_time(p_path);
  119. }
  120. Item item;
  121. item.order = order++;
  122. item.preview = p_texture;
  123. item.small_preview = p_small_texture;
  124. item.last_hash = p_hash;
  125. item.modified_time = modified_time;
  126. item.preview_metadata = p_metadata;
  127. cache[p_path] = item;
  128. }
  129. Callable(id, p_func).call_deferred(p_path, p_texture, p_small_texture, p_ud);
  130. }
  131. void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref<ImageTexture> &r_small_texture, const QueueItem &p_item, const String &cache_base, Dictionary &p_metadata) {
  132. String type;
  133. uint64_t started_at = OS::get_singleton()->get_ticks_usec();
  134. if (p_item.resource.is_valid()) {
  135. type = p_item.resource->get_class();
  136. } else {
  137. type = ResourceLoader::get_resource_type(p_item.path);
  138. }
  139. if (type.is_empty()) {
  140. r_texture = Ref<ImageTexture>();
  141. r_small_texture = Ref<ImageTexture>();
  142. if (is_print_verbose_enabled()) {
  143. print_line(vformat("Generated '%s' preview in %d usec", p_item.path, OS::get_singleton()->get_ticks_usec() - started_at));
  144. }
  145. return; //could not guess type
  146. }
  147. int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  148. thumbnail_size *= EDSCALE;
  149. r_texture = Ref<ImageTexture>();
  150. r_small_texture = Ref<ImageTexture>();
  151. for (int i = 0; i < preview_generators.size(); i++) {
  152. if (!preview_generators[i]->handles(type)) {
  153. continue;
  154. }
  155. Ref<Texture2D> generated;
  156. if (p_item.resource.is_valid()) {
  157. generated = preview_generators.write[i]->generate(p_item.resource, Vector2(thumbnail_size, thumbnail_size), p_metadata);
  158. } else {
  159. generated = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(thumbnail_size, thumbnail_size), p_metadata);
  160. }
  161. r_texture = generated;
  162. if (preview_generators[i]->can_generate_small_preview()) {
  163. Ref<Texture2D> generated_small;
  164. Dictionary d;
  165. if (p_item.resource.is_valid()) {
  166. generated_small = preview_generators.write[i]->generate(p_item.resource, Vector2(small_thumbnail_size, small_thumbnail_size), d);
  167. } else {
  168. generated_small = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(small_thumbnail_size, small_thumbnail_size), d);
  169. }
  170. r_small_texture = generated_small;
  171. }
  172. if (!r_small_texture.is_valid() && r_texture.is_valid() && preview_generators[i]->generate_small_preview_automatically()) {
  173. Ref<Image> small_image = r_texture->get_image();
  174. small_image = small_image->duplicate();
  175. small_image->resize(small_thumbnail_size, small_thumbnail_size, Image::INTERPOLATE_CUBIC);
  176. r_small_texture.instantiate();
  177. r_small_texture->set_image(small_image);
  178. }
  179. break;
  180. }
  181. if (!p_item.resource.is_valid()) {
  182. // Cache the preview in case it's a resource on disk.
  183. if (r_texture.is_valid()) {
  184. // Wow it generated a preview... save cache.
  185. bool has_small_texture = r_small_texture.is_valid();
  186. ResourceSaver::save(r_texture, cache_base + ".png");
  187. if (has_small_texture) {
  188. ResourceSaver::save(r_small_texture, cache_base + "_small.png");
  189. }
  190. Ref<FileAccess> f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
  191. ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + cache_base + ".txt'. Check user write permissions.");
  192. _write_preview_cache(f, thumbnail_size, has_small_texture, FileAccess::get_modified_time(p_item.path), FileAccess::get_md5(p_item.path), p_metadata);
  193. }
  194. }
  195. if (is_print_verbose_enabled()) {
  196. print_line(vformat("Generated '%s' preview in %d usec", p_item.path, OS::get_singleton()->get_ticks_usec() - started_at));
  197. }
  198. }
  199. const Dictionary EditorResourcePreview::get_preview_metadata(const String &p_path) const {
  200. ERR_FAIL_COND_V(!cache.has(p_path), Dictionary());
  201. return cache[p_path].preview_metadata;
  202. }
  203. void EditorResourcePreview::_iterate() {
  204. preview_mutex.lock();
  205. if (queue.size() == 0) {
  206. preview_mutex.unlock();
  207. return;
  208. }
  209. QueueItem item = queue.front()->get();
  210. queue.pop_front();
  211. if (cache.has(item.path)) {
  212. Item cached_item = cache[item.path];
  213. // Already has it because someone loaded it, just let it know it's ready.
  214. _preview_ready(item.path, cached_item.last_hash, cached_item.preview, cached_item.small_preview, item.id, item.function, item.userdata, cached_item.preview_metadata);
  215. preview_mutex.unlock();
  216. return;
  217. }
  218. preview_mutex.unlock();
  219. Ref<ImageTexture> texture;
  220. Ref<ImageTexture> small_texture;
  221. int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  222. thumbnail_size *= EDSCALE;
  223. if (item.resource.is_valid()) {
  224. Dictionary preview_metadata;
  225. _generate_preview(texture, small_texture, item, String(), preview_metadata);
  226. _preview_ready(item.path, item.resource->hash_edited_version_for_preview(), texture, small_texture, item.id, item.function, item.userdata, preview_metadata);
  227. return;
  228. }
  229. Dictionary preview_metadata;
  230. String temp_path = EditorPaths::get_singleton()->get_cache_dir();
  231. String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();
  232. cache_base = temp_path.path_join("resthumb-" + cache_base);
  233. // Does not have it, try to load a cached thumbnail.
  234. String file = cache_base + ".txt";
  235. Ref<FileAccess> f = FileAccess::open(file, FileAccess::READ);
  236. if (f.is_null()) {
  237. // No cache found, generate.
  238. _generate_preview(texture, small_texture, item, cache_base, preview_metadata);
  239. } else {
  240. uint64_t modtime = FileAccess::get_modified_time(item.path);
  241. int tsize;
  242. bool has_small_texture;
  243. uint64_t last_modtime;
  244. String hash;
  245. bool outdated;
  246. _read_preview_cache(f, &tsize, &has_small_texture, &last_modtime, &hash, &preview_metadata, &outdated);
  247. bool cache_valid = true;
  248. if (tsize != thumbnail_size) {
  249. cache_valid = false;
  250. f.unref();
  251. } else if (outdated) {
  252. cache_valid = false;
  253. f.unref();
  254. } else if (last_modtime != modtime) {
  255. String last_md5 = f->get_line();
  256. String md5 = FileAccess::get_md5(item.path);
  257. f.unref();
  258. if (last_md5 != md5) {
  259. cache_valid = false;
  260. } else {
  261. // Update modified time.
  262. Ref<FileAccess> f2 = FileAccess::open(file, FileAccess::WRITE);
  263. if (f2.is_null()) {
  264. // Not returning as this would leave the thread hanging and would require
  265. // some proper cleanup/disabling of resource preview generation.
  266. ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions.");
  267. } else {
  268. _write_preview_cache(f2, thumbnail_size, has_small_texture, modtime, md5, preview_metadata);
  269. }
  270. }
  271. } else {
  272. f.unref();
  273. }
  274. if (cache_valid) {
  275. Ref<Image> img;
  276. img.instantiate();
  277. Ref<Image> small_img;
  278. small_img.instantiate();
  279. if (img->load(cache_base + ".png") != OK) {
  280. cache_valid = false;
  281. } else {
  282. texture.instantiate();
  283. texture->set_image(img);
  284. if (has_small_texture) {
  285. if (small_img->load(cache_base + "_small.png") != OK) {
  286. cache_valid = false;
  287. } else {
  288. small_texture.instantiate();
  289. small_texture->set_image(small_img);
  290. }
  291. }
  292. }
  293. }
  294. if (!cache_valid) {
  295. _generate_preview(texture, small_texture, item, cache_base, preview_metadata);
  296. }
  297. }
  298. _preview_ready(item.path, 0, texture, small_texture, item.id, item.function, item.userdata, preview_metadata);
  299. }
  300. void EditorResourcePreview::_write_preview_cache(Ref<FileAccess> p_file, int p_thumbnail_size, bool p_has_small_texture, uint64_t p_modified_time, const String &p_hash, const Dictionary &p_metadata) {
  301. p_file->store_line(itos(p_thumbnail_size));
  302. p_file->store_line(itos(p_has_small_texture));
  303. p_file->store_line(itos(p_modified_time));
  304. p_file->store_line(p_hash);
  305. p_file->store_line(VariantUtilityFunctions::var_to_str(p_metadata).replace("\n", " "));
  306. p_file->store_line(itos(CURRENT_METADATA_VERSION));
  307. }
  308. void EditorResourcePreview::_read_preview_cache(Ref<FileAccess> p_file, int *r_thumbnail_size, bool *r_has_small_texture, uint64_t *r_modified_time, String *r_hash, Dictionary *r_metadata, bool *r_outdated) {
  309. *r_thumbnail_size = p_file->get_line().to_int();
  310. *r_has_small_texture = p_file->get_line().to_int();
  311. *r_modified_time = p_file->get_line().to_int();
  312. *r_hash = p_file->get_line();
  313. *r_metadata = VariantUtilityFunctions::str_to_var(p_file->get_line());
  314. *r_outdated = p_file->get_line().to_int() < CURRENT_METADATA_VERSION;
  315. }
  316. void EditorResourcePreview::_thread() {
  317. exited.clear();
  318. while (!exiting.is_set()) {
  319. preview_sem.wait();
  320. _iterate();
  321. }
  322. exited.set();
  323. }
  324. void EditorResourcePreview::_idle_callback() {
  325. if (!singleton) {
  326. // Just in case the shutdown of the editor involves the deletion of the singleton
  327. // happening while additional idle callbacks can happen.
  328. return;
  329. }
  330. // Process preview tasks, trying to leave a little bit of responsiveness worst case.
  331. uint64_t start = OS::get_singleton()->get_ticks_msec();
  332. while (!singleton->queue.is_empty() && OS::get_singleton()->get_ticks_msec() - start < 100) {
  333. singleton->_iterate();
  334. }
  335. }
  336. void EditorResourcePreview::_update_thumbnail_sizes() {
  337. if (small_thumbnail_size == -1) {
  338. // Kind of a workaround to retrieve the default icon size.
  339. small_thumbnail_size = EditorNode::get_singleton()->get_editor_theme()->get_icon(SNAME("Object"), EditorStringName(EditorIcons))->get_width();
  340. }
  341. }
  342. void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  343. ERR_FAIL_NULL(p_receiver);
  344. ERR_FAIL_COND(!p_res.is_valid());
  345. _update_thumbnail_sizes();
  346. {
  347. MutexLock lock(preview_mutex);
  348. String path_id = "ID:" + itos(p_res->get_instance_id());
  349. if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version_for_preview()) {
  350. cache[path_id].order = order++;
  351. p_receiver->call(p_receiver_func, path_id, cache[path_id].preview, cache[path_id].small_preview, p_userdata);
  352. return;
  353. }
  354. cache.erase(path_id); //erase if exists, since it will be regen
  355. QueueItem item;
  356. item.function = p_receiver_func;
  357. item.id = p_receiver->get_instance_id();
  358. item.resource = p_res;
  359. item.path = path_id;
  360. item.userdata = p_userdata;
  361. queue.push_back(item);
  362. }
  363. preview_sem.post();
  364. }
  365. void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  366. ERR_FAIL_NULL(p_receiver);
  367. _update_thumbnail_sizes();
  368. {
  369. MutexLock lock(preview_mutex);
  370. if (cache.has(p_path)) {
  371. cache[p_path].order = order++;
  372. p_receiver->call(p_receiver_func, p_path, cache[p_path].preview, cache[p_path].small_preview, p_userdata);
  373. return;
  374. }
  375. QueueItem item;
  376. item.function = p_receiver_func;
  377. item.id = p_receiver->get_instance_id();
  378. item.path = p_path;
  379. item.userdata = p_userdata;
  380. queue.push_back(item);
  381. }
  382. preview_sem.post();
  383. }
  384. void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  385. preview_generators.push_back(p_generator);
  386. }
  387. void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  388. preview_generators.erase(p_generator);
  389. }
  390. EditorResourcePreview *EditorResourcePreview::get_singleton() {
  391. return singleton;
  392. }
  393. void EditorResourcePreview::_bind_methods() {
  394. ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_resource_preview);
  395. ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_edited_resource_preview);
  396. ClassDB::bind_method(D_METHOD("add_preview_generator", "generator"), &EditorResourcePreview::add_preview_generator);
  397. ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator"), &EditorResourcePreview::remove_preview_generator);
  398. ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);
  399. ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));
  400. }
  401. void EditorResourcePreview::check_for_invalidation(const String &p_path) {
  402. bool call_invalidated = false;
  403. {
  404. MutexLock lock(preview_mutex);
  405. if (cache.has(p_path)) {
  406. uint64_t modified_time = FileAccess::get_modified_time(p_path);
  407. if (modified_time != cache[p_path].modified_time) {
  408. cache.erase(p_path);
  409. call_invalidated = true;
  410. }
  411. }
  412. }
  413. if (call_invalidated) { //do outside mutex
  414. call_deferred(SNAME("emit_signal"), "preview_invalidated", p_path);
  415. }
  416. }
  417. void EditorResourcePreview::start() {
  418. if (DisplayServer::get_singleton()->get_name() == "headless") {
  419. return;
  420. }
  421. if (is_threaded()) {
  422. ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started.");
  423. thread.start(_thread_func, this);
  424. } else {
  425. SceneTree *st = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
  426. ERR_FAIL_NULL_MSG(st, "Editor's MainLoop is not a SceneTree. This is a bug.");
  427. st->add_idle_callback(&_idle_callback);
  428. }
  429. }
  430. void EditorResourcePreview::stop() {
  431. if (is_threaded()) {
  432. if (thread.is_started()) {
  433. exiting.set();
  434. preview_sem.post();
  435. for (int i = 0; i < preview_generators.size(); i++) {
  436. preview_generators.write[i]->abort();
  437. }
  438. while (!exited.is_set()) {
  439. OS::get_singleton()->delay_usec(10000);
  440. RenderingServer::get_singleton()->sync(); //sync pending stuff, as thread may be blocked on rendering server
  441. }
  442. thread.wait_to_finish();
  443. }
  444. }
  445. }
  446. EditorResourcePreview::EditorResourcePreview() {
  447. singleton = this;
  448. order = 0;
  449. }
  450. EditorResourcePreview::~EditorResourcePreview() {
  451. stop();
  452. }