shader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /**************************************************************************/
  2. /* shader.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 "shader.h"
  31. #include "shader.compat.inc"
  32. #include "core/io/file_access.h"
  33. #include "scene/main/scene_tree.h"
  34. #include "servers/rendering/rendering_server.h"
  35. #include "servers/rendering/shader_language.h"
  36. #include "servers/rendering/shader_preprocessor.h"
  37. #include "texture.h"
  38. #ifdef TOOLS_ENABLED
  39. #include "editor/doc/editor_help.h"
  40. #include "modules/modules_enabled.gen.h" // For regex.
  41. #ifdef MODULE_REGEX_ENABLED
  42. #include "modules/regex/regex.h"
  43. #endif
  44. #endif
  45. Shader::Mode Shader::get_mode() const {
  46. return mode;
  47. }
  48. void Shader::_check_shader_rid() const {
  49. MutexLock lock(shader_rid_mutex);
  50. if (shader_rid.is_null() && !preprocessed_code.is_empty()) {
  51. shader_rid = RenderingServer::get_singleton()->shader_create_from_code(preprocessed_code, get_path());
  52. preprocessed_code = String();
  53. }
  54. }
  55. void Shader::_dependency_changed() {
  56. // Preprocess and compile the code again because a dependency has changed. It also calls emit_changed() for us.
  57. _recompile();
  58. }
  59. void Shader::_recompile() {
  60. set_code(get_code());
  61. }
  62. void Shader::set_path(const String &p_path, bool p_take_over) {
  63. Resource::set_path(p_path, p_take_over);
  64. if (shader_rid.is_valid()) {
  65. RS::get_singleton()->shader_set_path_hint(shader_rid, p_path);
  66. }
  67. }
  68. void Shader::set_include_path(const String &p_path) {
  69. // Used only if the shader does not have a resource path set,
  70. // for example during loading stage or when created by code.
  71. include_path = p_path;
  72. }
  73. void Shader::set_code(const String &p_code) {
  74. for (const Ref<ShaderInclude> &E : include_dependencies) {
  75. E->disconnect_changed(callable_mp(this, &Shader::_dependency_changed));
  76. }
  77. code = p_code;
  78. preprocessed_code = p_code;
  79. {
  80. String path = get_path();
  81. if (path.is_empty()) {
  82. path = include_path;
  83. }
  84. // Preprocessor must run here and not in the server because:
  85. // 1) Need to keep track of include dependencies at resource level
  86. // 2) Server does not do interaction with Resource filetypes, this is a scene level feature.
  87. HashSet<Ref<ShaderInclude>> new_include_dependencies;
  88. ShaderPreprocessor preprocessor;
  89. Error result = preprocessor.preprocess(p_code, path, preprocessed_code, nullptr, nullptr, nullptr, &new_include_dependencies);
  90. if (result == OK) {
  91. // This ensures previous include resources are not freed and then re-loaded during parse (which would make compiling slower)
  92. include_dependencies = new_include_dependencies;
  93. }
  94. }
  95. // Try to get the shader type from the final, fully preprocessed shader code.
  96. String type = ShaderLanguage::get_shader_type(preprocessed_code);
  97. if (type == "canvas_item") {
  98. mode = MODE_CANVAS_ITEM;
  99. } else if (type == "particles") {
  100. mode = MODE_PARTICLES;
  101. } else if (type == "sky") {
  102. mode = MODE_SKY;
  103. } else if (type == "fog") {
  104. mode = MODE_FOG;
  105. } else {
  106. mode = MODE_SPATIAL;
  107. }
  108. for (const Ref<ShaderInclude> &E : include_dependencies) {
  109. E->connect_changed(callable_mp(this, &Shader::_dependency_changed));
  110. }
  111. if (shader_rid.is_valid()) {
  112. RenderingServer::get_singleton()->shader_set_code(shader_rid, preprocessed_code);
  113. preprocessed_code = String();
  114. }
  115. emit_changed();
  116. }
  117. String Shader::get_code() const {
  118. _update_shader();
  119. return code;
  120. }
  121. void Shader::inspect_native_shader_code() {
  122. SceneTree *st = SceneTree::get_singleton();
  123. RID _shader = get_rid();
  124. if (st && _shader.is_valid()) {
  125. st->call_group_flags(SceneTree::GROUP_CALL_DEFERRED, "_native_shader_source_visualizer", "_inspect_shader", _shader);
  126. }
  127. }
  128. void Shader::get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_groups) const {
  129. _update_shader();
  130. _check_shader_rid();
  131. List<PropertyInfo> local;
  132. RenderingServer::get_singleton()->get_shader_parameter_list(shader_rid, &local);
  133. #ifdef TOOLS_ENABLED
  134. DocData::ClassDoc class_doc;
  135. bool generate_doc = Engine::get_singleton()->is_editor_hint() && !get_path().is_empty();
  136. if (generate_doc) {
  137. class_doc.name = get_path().trim_prefix("res://").quote();
  138. class_doc.is_script_doc = true;
  139. class_doc.inherits = "Shader";
  140. }
  141. #endif
  142. for (PropertyInfo &pi : local) {
  143. bool is_group = pi.usage == PROPERTY_USAGE_GROUP || pi.usage == PROPERTY_USAGE_SUBGROUP;
  144. if (!p_get_groups && is_group) {
  145. continue;
  146. }
  147. if (!is_group) {
  148. if (default_textures.has(pi.name)) { //do not show default textures
  149. continue;
  150. }
  151. }
  152. if (p_params) {
  153. //small little hack
  154. if (pi.type == Variant::RID) {
  155. pi.type = Variant::OBJECT;
  156. }
  157. #ifdef TOOLS_ENABLED
  158. if (generate_doc) {
  159. DocData::PropertyDoc prop_doc;
  160. prop_doc.name = "shader_parameter/" + pi.name;
  161. const RegEx pattern("/\\*\\*\\s([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/\\s*uniform\\s+\\w+\\s+" + pi.name + "(?=[\\s:;=])");
  162. Ref<RegExMatch> pattern_ref = pattern.search(code);
  163. if (pattern_ref.is_valid()) {
  164. RegExMatch *match = pattern_ref.ptr();
  165. const RegEx pattern_tip("\\/\\*\\*([\\s\\S]*?)\\*/");
  166. Ref<RegExMatch> pattern_tip_ref = pattern_tip.search(match->get_string(0));
  167. RegExMatch *match_tip = pattern_tip_ref.ptr();
  168. const RegEx pattern_stripped("\\n\\s*\\*\\s*");
  169. prop_doc.description = pattern_stripped.sub(match_tip->get_string(1), "\n", true);
  170. pi.class_name = class_doc.name;
  171. class_doc.properties.push_back(prop_doc);
  172. }
  173. }
  174. #endif
  175. p_params->push_back(pi);
  176. }
  177. }
  178. #ifdef TOOLS_ENABLED
  179. if (generate_doc && class_doc.properties.size() > 0) {
  180. EditorHelp::add_doc(class_doc);
  181. }
  182. #endif
  183. }
  184. RID Shader::get_rid() const {
  185. _update_shader();
  186. _check_shader_rid();
  187. return shader_rid;
  188. }
  189. void Shader::set_default_texture_parameter(const StringName &p_name, const Ref<Texture> &p_texture, int p_index) {
  190. _check_shader_rid();
  191. if (p_texture.is_valid()) {
  192. if (!default_textures.has(p_name)) {
  193. default_textures[p_name] = HashMap<int, Ref<Texture>>();
  194. }
  195. default_textures[p_name][p_index] = p_texture;
  196. RS::get_singleton()->shader_set_default_texture_parameter(shader_rid, p_name, p_texture->get_rid(), p_index);
  197. } else {
  198. if (default_textures.has(p_name) && default_textures[p_name].has(p_index)) {
  199. default_textures[p_name].erase(p_index);
  200. if (default_textures[p_name].is_empty()) {
  201. default_textures.erase(p_name);
  202. }
  203. }
  204. RS::get_singleton()->shader_set_default_texture_parameter(shader_rid, p_name, RID(), p_index);
  205. }
  206. emit_changed();
  207. }
  208. Ref<Texture> Shader::get_default_texture_parameter(const StringName &p_name, int p_index) const {
  209. if (default_textures.has(p_name) && default_textures[p_name].has(p_index)) {
  210. return default_textures[p_name][p_index];
  211. }
  212. return Ref<Texture2D>();
  213. }
  214. void Shader::get_default_texture_parameter_list(List<StringName> *r_textures) const {
  215. for (const KeyValue<StringName, HashMap<int, Ref<Texture>>> &E : default_textures) {
  216. r_textures->push_back(E.key);
  217. }
  218. }
  219. bool Shader::is_text_shader() const {
  220. return true;
  221. }
  222. void Shader::_update_shader() const {
  223. // Base implementation does nothing.
  224. }
  225. Array Shader::_get_shader_uniform_list(bool p_get_groups) {
  226. List<PropertyInfo> uniform_list;
  227. get_shader_uniform_list(&uniform_list, p_get_groups);
  228. Array ret;
  229. for (const PropertyInfo &pi : uniform_list) {
  230. ret.push_back(pi.operator Dictionary());
  231. }
  232. return ret;
  233. }
  234. void Shader::_bind_methods() {
  235. ClassDB::bind_method(D_METHOD("get_mode"), &Shader::get_mode);
  236. ClassDB::bind_method(D_METHOD("set_code", "code"), &Shader::set_code);
  237. ClassDB::bind_method(D_METHOD("get_code"), &Shader::get_code);
  238. ClassDB::bind_method(D_METHOD("set_default_texture_parameter", "name", "texture", "index"), &Shader::set_default_texture_parameter, DEFVAL(0));
  239. ClassDB::bind_method(D_METHOD("get_default_texture_parameter", "name", "index"), &Shader::get_default_texture_parameter, DEFVAL(0));
  240. ClassDB::bind_method(D_METHOD("get_shader_uniform_list", "get_groups"), &Shader::_get_shader_uniform_list, DEFVAL(false));
  241. ClassDB::bind_method(D_METHOD("inspect_native_shader_code"), &Shader::inspect_native_shader_code);
  242. ClassDB::set_method_flags(get_class_static(), StringName("inspect_native_shader_code"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  243. ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_code", "get_code");
  244. BIND_ENUM_CONSTANT(MODE_SPATIAL);
  245. BIND_ENUM_CONSTANT(MODE_CANVAS_ITEM);
  246. BIND_ENUM_CONSTANT(MODE_PARTICLES);
  247. BIND_ENUM_CONSTANT(MODE_SKY);
  248. BIND_ENUM_CONSTANT(MODE_FOG);
  249. }
  250. Shader::Shader() {
  251. // Shader RID will be empty until it is required.
  252. }
  253. Shader::~Shader() {
  254. if (shader_rid.is_valid()) {
  255. ERR_FAIL_NULL(RenderingServer::get_singleton());
  256. RenderingServer::get_singleton()->free_rid(shader_rid);
  257. }
  258. }
  259. ////////////
  260. Ref<Resource> ResourceFormatLoaderShader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  261. if (r_error) {
  262. *r_error = ERR_FILE_CANT_OPEN;
  263. }
  264. Error error = OK;
  265. Vector<uint8_t> buffer = FileAccess::get_file_as_bytes(p_path, &error);
  266. ERR_FAIL_COND_V_MSG(error, nullptr, "Cannot load shader: " + p_path);
  267. String str;
  268. if (buffer.size() > 0) {
  269. error = str.append_utf8((const char *)buffer.ptr(), buffer.size());
  270. ERR_FAIL_COND_V_MSG(error, nullptr, "Cannot parse shader: " + p_path);
  271. }
  272. Ref<Shader> shader;
  273. shader.instantiate();
  274. shader->set_include_path(p_path);
  275. shader->set_code(str);
  276. if (r_error) {
  277. *r_error = OK;
  278. }
  279. return shader;
  280. }
  281. void ResourceFormatLoaderShader::get_recognized_extensions(List<String> *p_extensions) const {
  282. p_extensions->push_back("gdshader");
  283. }
  284. bool ResourceFormatLoaderShader::handles_type(const String &p_type) const {
  285. return (p_type == "Shader");
  286. }
  287. String ResourceFormatLoaderShader::get_resource_type(const String &p_path) const {
  288. if (p_path.has_extension("gdshader")) {
  289. return "Shader";
  290. }
  291. return "";
  292. }
  293. Error ResourceFormatSaverShader::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  294. Ref<Shader> shader = p_resource;
  295. ERR_FAIL_COND_V(shader.is_null(), ERR_INVALID_PARAMETER);
  296. String source = shader->get_code();
  297. Error err;
  298. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  299. ERR_FAIL_COND_V_MSG(err, err, "Cannot save shader '" + p_path + "'.");
  300. file->store_string(source);
  301. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  302. return ERR_CANT_CREATE;
  303. }
  304. return OK;
  305. }
  306. void ResourceFormatSaverShader::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  307. if (const Shader *shader = Object::cast_to<Shader>(*p_resource)) {
  308. if (shader->is_text_shader()) {
  309. p_extensions->push_back("gdshader");
  310. }
  311. }
  312. }
  313. bool ResourceFormatSaverShader::recognize(const Ref<Resource> &p_resource) const {
  314. return p_resource->get_class_name() == "Shader"; //only shader, not inherited
  315. }