editor_resource_preview.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*************************************************************************/
  2. /* editor_resource_preview.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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/object/message_queue.h"
  36. #include "editor_node.h"
  37. #include "editor_scale.h"
  38. #include "editor_settings.h"
  39. bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
  40. bool success;
  41. if (GDVIRTUAL_CALL(_handles, p_type, success)) {
  42. return success;
  43. }
  44. ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::_handles needs to be overridden.");
  45. }
  46. Ref<Texture2D> EditorResourcePreviewGenerator::generate(const RES &p_from, const Size2 &p_size) const {
  47. Ref<Texture2D> preview;
  48. if (GDVIRTUAL_CALL(_generate, p_from, p_size, preview)) {
  49. return preview;
  50. }
  51. ERR_FAIL_V_MSG(Ref<Texture2D>(), "EditorResourcePreviewGenerator::_generate needs to be overridden.");
  52. }
  53. Ref<Texture2D> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size) const {
  54. Ref<Texture2D> preview;
  55. if (GDVIRTUAL_CALL(_generate_from_path, p_path, p_size, preview)) {
  56. return preview;
  57. }
  58. RES res = ResourceLoader::load(p_path);
  59. if (!res.is_valid()) {
  60. return res;
  61. }
  62. return generate(res, p_size);
  63. }
  64. bool EditorResourcePreviewGenerator::generate_small_preview_automatically() const {
  65. bool success;
  66. if (GDVIRTUAL_CALL(_generate_small_preview_automatically, success)) {
  67. return success;
  68. }
  69. return false;
  70. }
  71. bool EditorResourcePreviewGenerator::can_generate_small_preview() const {
  72. bool success;
  73. if (GDVIRTUAL_CALL(_can_generate_small_preview, success)) {
  74. return success;
  75. }
  76. return false;
  77. }
  78. void EditorResourcePreviewGenerator::_bind_methods() {
  79. GDVIRTUAL_BIND(_handles, "type");
  80. GDVIRTUAL_BIND(_generate, "resource", "size");
  81. GDVIRTUAL_BIND(_generate_from_path, "path", "size");
  82. GDVIRTUAL_BIND(_generate_small_preview_automatically);
  83. GDVIRTUAL_BIND(_can_generate_small_preview);
  84. }
  85. EditorResourcePreviewGenerator::EditorResourcePreviewGenerator() {
  86. }
  87. EditorResourcePreview *EditorResourcePreview::singleton = nullptr;
  88. void EditorResourcePreview::_thread_func(void *ud) {
  89. EditorResourcePreview *erp = (EditorResourcePreview *)ud;
  90. erp->_thread();
  91. }
  92. void EditorResourcePreview::_preview_ready(const String &p_str, const Ref<Texture2D> &p_texture, const Ref<Texture2D> &p_small_texture, ObjectID id, const StringName &p_func, const Variant &p_ud) {
  93. String path = p_str;
  94. {
  95. MutexLock lock(preview_mutex);
  96. uint32_t hash = 0;
  97. uint64_t modified_time = 0;
  98. if (p_str.begins_with("ID:")) {
  99. hash = uint32_t(p_str.get_slicec(':', 2).to_int());
  100. path = "ID:" + p_str.get_slicec(':', 1);
  101. } else {
  102. modified_time = FileAccess::get_modified_time(path);
  103. }
  104. Item item;
  105. item.order = order++;
  106. item.preview = p_texture;
  107. item.small_preview = p_small_texture;
  108. item.last_hash = hash;
  109. item.modified_time = modified_time;
  110. cache[path] = item;
  111. }
  112. MessageQueue::get_singleton()->push_call(id, p_func, path, p_texture, p_small_texture, p_ud);
  113. }
  114. void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref<ImageTexture> &r_small_texture, const QueueItem &p_item, const String &cache_base) {
  115. String type;
  116. if (p_item.resource.is_valid()) {
  117. type = p_item.resource->get_class();
  118. } else {
  119. type = ResourceLoader::get_resource_type(p_item.path);
  120. }
  121. if (type == "") {
  122. r_texture = Ref<ImageTexture>();
  123. r_small_texture = Ref<ImageTexture>();
  124. return; //could not guess type
  125. }
  126. int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
  127. thumbnail_size *= EDSCALE;
  128. r_texture = Ref<ImageTexture>();
  129. r_small_texture = Ref<ImageTexture>();
  130. for (int i = 0; i < preview_generators.size(); i++) {
  131. if (!preview_generators[i]->handles(type)) {
  132. continue;
  133. }
  134. Ref<Texture2D> generated;
  135. if (p_item.resource.is_valid()) {
  136. generated = preview_generators[i]->generate(p_item.resource, Vector2(thumbnail_size, thumbnail_size));
  137. } else {
  138. generated = preview_generators[i]->generate_from_path(p_item.path, Vector2(thumbnail_size, thumbnail_size));
  139. }
  140. r_texture = generated;
  141. int small_thumbnail_size = EditorNode::get_singleton()->get_theme_base()->get_theme_icon(SNAME("Object"), SNAME("EditorIcons"))->get_width(); // Kind of a workaround to retrieve the default icon size
  142. if (preview_generators[i]->can_generate_small_preview()) {
  143. Ref<Texture2D> generated_small;
  144. if (p_item.resource.is_valid()) {
  145. generated_small = preview_generators[i]->generate(p_item.resource, Vector2(small_thumbnail_size, small_thumbnail_size));
  146. } else {
  147. generated_small = preview_generators[i]->generate_from_path(p_item.path, Vector2(small_thumbnail_size, small_thumbnail_size));
  148. }
  149. r_small_texture = generated_small;
  150. }
  151. if (!r_small_texture.is_valid() && r_texture.is_valid() && preview_generators[i]->generate_small_preview_automatically()) {
  152. Ref<Image> small_image = r_texture->get_image();
  153. small_image = small_image->duplicate();
  154. small_image->resize(small_thumbnail_size, small_thumbnail_size, Image::INTERPOLATE_CUBIC);
  155. r_small_texture.instantiate();
  156. r_small_texture->create_from_image(small_image);
  157. }
  158. break;
  159. }
  160. if (!p_item.resource.is_valid()) {
  161. // cache the preview in case it's a resource on disk
  162. if (r_texture.is_valid()) {
  163. //wow it generated a preview... save cache
  164. bool has_small_texture = r_small_texture.is_valid();
  165. ResourceSaver::save(cache_base + ".png", r_texture);
  166. if (has_small_texture) {
  167. ResourceSaver::save(cache_base + "_small.png", r_small_texture);
  168. }
  169. FileAccess *f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
  170. ERR_FAIL_COND_MSG(!f, "Cannot create file '" + cache_base + ".txt'. Check user write permissions.");
  171. f->store_line(itos(thumbnail_size));
  172. f->store_line(itos(has_small_texture));
  173. f->store_line(itos(FileAccess::get_modified_time(p_item.path)));
  174. f->store_line(FileAccess::get_md5(p_item.path));
  175. f->close();
  176. memdelete(f);
  177. }
  178. }
  179. }
  180. void EditorResourcePreview::_iterate() {
  181. preview_mutex.lock();
  182. if (queue.size()) {
  183. QueueItem item = queue.front()->get();
  184. queue.pop_front();
  185. if (cache.has(item.path)) {
  186. //already has it because someone loaded it, just let it know it's ready
  187. String path = item.path;
  188. if (item.resource.is_valid()) {
  189. path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below)
  190. }
  191. _preview_ready(path, cache[item.path].preview, cache[item.path].small_preview, item.id, item.function, item.userdata);
  192. preview_mutex.unlock();
  193. } else {
  194. preview_mutex.unlock();
  195. Ref<ImageTexture> texture;
  196. Ref<ImageTexture> small_texture;
  197. int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
  198. thumbnail_size *= EDSCALE;
  199. if (item.resource.is_valid()) {
  200. _generate_preview(texture, small_texture, item, String());
  201. //adding hash to the end of path (should be ID:<objid>:<hash>) because of 5 argument limit to call_deferred
  202. _preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, small_texture, item.id, item.function, item.userdata);
  203. } else {
  204. String temp_path = EditorPaths::get_singleton()->get_cache_dir();
  205. String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();
  206. cache_base = temp_path.plus_file("resthumb-" + cache_base);
  207. //does not have it, try to load a cached thumbnail
  208. String file = cache_base + ".txt";
  209. FileAccess *f = FileAccess::open(file, FileAccess::READ);
  210. if (!f) {
  211. // No cache found, generate
  212. _generate_preview(texture, small_texture, item, cache_base);
  213. } else {
  214. uint64_t modtime = FileAccess::get_modified_time(item.path);
  215. int tsize = f->get_line().to_int();
  216. bool has_small_texture = f->get_line().to_int();
  217. uint64_t last_modtime = f->get_line().to_int();
  218. bool cache_valid = true;
  219. if (tsize != thumbnail_size) {
  220. cache_valid = false;
  221. memdelete(f);
  222. } else if (last_modtime != modtime) {
  223. String last_md5 = f->get_line();
  224. String md5 = FileAccess::get_md5(item.path);
  225. memdelete(f);
  226. if (last_md5 != md5) {
  227. cache_valid = false;
  228. } else {
  229. //update modified time
  230. f = FileAccess::open(file, FileAccess::WRITE);
  231. if (!f) {
  232. // Not returning as this would leave the thread hanging and would require
  233. // some proper cleanup/disabling of resource preview generation.
  234. ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions.");
  235. } else {
  236. f->store_line(itos(thumbnail_size));
  237. f->store_line(itos(has_small_texture));
  238. f->store_line(itos(modtime));
  239. f->store_line(md5);
  240. memdelete(f);
  241. }
  242. }
  243. } else {
  244. memdelete(f);
  245. }
  246. if (cache_valid) {
  247. Ref<Image> img;
  248. img.instantiate();
  249. Ref<Image> small_img;
  250. small_img.instantiate();
  251. if (img->load(cache_base + ".png") != OK) {
  252. cache_valid = false;
  253. } else {
  254. texture.instantiate();
  255. texture->create_from_image(img);
  256. if (has_small_texture) {
  257. if (small_img->load(cache_base + "_small.png") != OK) {
  258. cache_valid = false;
  259. } else {
  260. small_texture.instantiate();
  261. small_texture->create_from_image(small_img);
  262. }
  263. }
  264. }
  265. }
  266. if (!cache_valid) {
  267. _generate_preview(texture, small_texture, item, cache_base);
  268. }
  269. }
  270. _preview_ready(item.path, texture, small_texture, item.id, item.function, item.userdata);
  271. }
  272. }
  273. } else {
  274. preview_mutex.unlock();
  275. }
  276. }
  277. void EditorResourcePreview::_thread() {
  278. exited.clear();
  279. while (!exit.is_set()) {
  280. preview_sem.wait();
  281. _iterate();
  282. }
  283. exited.set();
  284. }
  285. void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  286. ERR_FAIL_NULL(p_receiver);
  287. ERR_FAIL_COND(!p_res.is_valid());
  288. {
  289. MutexLock lock(preview_mutex);
  290. String path_id = "ID:" + itos(p_res->get_instance_id());
  291. if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version()) {
  292. cache[path_id].order = order++;
  293. p_receiver->call(p_receiver_func, path_id, cache[path_id].preview, cache[path_id].small_preview, p_userdata);
  294. return;
  295. }
  296. cache.erase(path_id); //erase if exists, since it will be regen
  297. QueueItem item;
  298. item.function = p_receiver_func;
  299. item.id = p_receiver->get_instance_id();
  300. item.resource = p_res;
  301. item.path = path_id;
  302. item.userdata = p_userdata;
  303. queue.push_back(item);
  304. }
  305. preview_sem.post();
  306. }
  307. void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  308. ERR_FAIL_NULL(p_receiver);
  309. {
  310. MutexLock lock(preview_mutex);
  311. if (cache.has(p_path)) {
  312. cache[p_path].order = order++;
  313. p_receiver->call(p_receiver_func, p_path, cache[p_path].preview, cache[p_path].small_preview, p_userdata);
  314. return;
  315. }
  316. QueueItem item;
  317. item.function = p_receiver_func;
  318. item.id = p_receiver->get_instance_id();
  319. item.path = p_path;
  320. item.userdata = p_userdata;
  321. queue.push_back(item);
  322. }
  323. preview_sem.post();
  324. }
  325. void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  326. preview_generators.push_back(p_generator);
  327. }
  328. void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  329. preview_generators.erase(p_generator);
  330. }
  331. EditorResourcePreview *EditorResourcePreview::get_singleton() {
  332. return singleton;
  333. }
  334. void EditorResourcePreview::_bind_methods() {
  335. ClassDB::bind_method("_preview_ready", &EditorResourcePreview::_preview_ready);
  336. ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_resource_preview);
  337. ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_edited_resource_preview);
  338. ClassDB::bind_method(D_METHOD("add_preview_generator", "generator"), &EditorResourcePreview::add_preview_generator);
  339. ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator"), &EditorResourcePreview::remove_preview_generator);
  340. ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);
  341. ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));
  342. }
  343. void EditorResourcePreview::check_for_invalidation(const String &p_path) {
  344. bool call_invalidated = false;
  345. {
  346. MutexLock lock(preview_mutex);
  347. if (cache.has(p_path)) {
  348. uint64_t modified_time = FileAccess::get_modified_time(p_path);
  349. if (modified_time != cache[p_path].modified_time) {
  350. cache.erase(p_path);
  351. call_invalidated = true;
  352. }
  353. }
  354. }
  355. if (call_invalidated) { //do outside mutex
  356. call_deferred(SNAME("emit_signal"), "preview_invalidated", p_path);
  357. }
  358. }
  359. void EditorResourcePreview::start() {
  360. if (OS::get_singleton()->get_render_main_thread_mode() == OS::RENDER_ANY_THREAD) {
  361. ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started.");
  362. thread.start(_thread_func, this);
  363. } else {
  364. _mainthread_only = true;
  365. }
  366. }
  367. void EditorResourcePreview::stop() {
  368. if (thread.is_started()) {
  369. exit.set();
  370. preview_sem.post();
  371. while (!exited.is_set()) {
  372. OS::get_singleton()->delay_usec(10000);
  373. RenderingServer::get_singleton()->sync(); //sync pending stuff, as thread may be blocked on rendering server
  374. }
  375. thread.wait_to_finish();
  376. }
  377. }
  378. EditorResourcePreview::EditorResourcePreview() {
  379. singleton = this;
  380. order = 0;
  381. }
  382. EditorResourcePreview::~EditorResourcePreview() {
  383. stop();
  384. }
  385. void EditorResourcePreview::update() {
  386. if (!_mainthread_only) {
  387. return;
  388. }
  389. if (!exit.is_set()) {
  390. // no need to even lock the mutex if the size is zero
  391. // there is no problem if queue.size() is wrong, even if
  392. // there was a race condition.
  393. if (queue.size()) {
  394. _iterate();
  395. }
  396. }
  397. }