editor_resource_preview.cpp 16 KB

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