editor_resource_preview.cpp 16 KB

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