shader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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/shader_language.h"
  35. #include "servers/rendering/shader_preprocessor.h"
  36. #include "servers/rendering_server.h"
  37. #include "texture.h"
  38. #ifdef TOOLS_ENABLED
  39. #include "editor/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. class_doc.name = get_path();
  136. class_doc.is_script_doc = true;
  137. #endif
  138. for (PropertyInfo &pi : local) {
  139. bool is_group = pi.usage == PROPERTY_USAGE_GROUP || pi.usage == PROPERTY_USAGE_SUBGROUP;
  140. if (!p_get_groups && is_group) {
  141. continue;
  142. }
  143. if (!is_group) {
  144. if (default_textures.has(pi.name)) { //do not show default textures
  145. continue;
  146. }
  147. }
  148. if (p_params) {
  149. //small little hack
  150. if (pi.type == Variant::RID) {
  151. pi.type = Variant::OBJECT;
  152. }
  153. #ifdef TOOLS_ENABLED
  154. if (Engine::get_singleton()->is_editor_hint()) {
  155. DocData::PropertyDoc prop_doc;
  156. prop_doc.name = "shader_parameter/" + pi.name;
  157. #ifdef MODULE_REGEX_ENABLED
  158. const RegEx pattern("/\\*\\*\\s([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/\\s*uniform\\s+\\w+\\s+" + pi.name + "(?=[\\s:;=])");
  159. Ref<RegExMatch> pattern_ref = pattern.search(code);
  160. if (pattern_ref.is_valid()) {
  161. RegExMatch *match = pattern_ref.ptr();
  162. const RegEx pattern_tip("\\/\\*\\*([\\s\\S]*?)\\*/");
  163. Ref<RegExMatch> pattern_tip_ref = pattern_tip.search(match->get_string(0));
  164. RegExMatch *match_tip = pattern_tip_ref.ptr();
  165. const RegEx pattern_stripped("\\n\\s*\\*\\s*");
  166. prop_doc.description = pattern_stripped.sub(match_tip->get_string(1), "\n", true);
  167. }
  168. #endif
  169. class_doc.properties.push_back(prop_doc);
  170. }
  171. #endif
  172. p_params->push_back(pi);
  173. }
  174. }
  175. #ifdef TOOLS_ENABLED
  176. if (EditorHelp::get_doc_data() != nullptr && Engine::get_singleton()->is_editor_hint() && !class_doc.name.is_empty() && p_params) {
  177. EditorHelp::get_doc_data()->add_doc(class_doc);
  178. }
  179. #endif
  180. }
  181. RID Shader::get_rid() const {
  182. _update_shader();
  183. _check_shader_rid();
  184. return shader_rid;
  185. }
  186. void Shader::set_default_texture_parameter(const StringName &p_name, const Ref<Texture> &p_texture, int p_index) {
  187. _check_shader_rid();
  188. if (p_texture.is_valid()) {
  189. if (!default_textures.has(p_name)) {
  190. default_textures[p_name] = HashMap<int, Ref<Texture>>();
  191. }
  192. default_textures[p_name][p_index] = p_texture;
  193. RS::get_singleton()->shader_set_default_texture_parameter(shader_rid, p_name, p_texture->get_rid(), p_index);
  194. } else {
  195. if (default_textures.has(p_name) && default_textures[p_name].has(p_index)) {
  196. default_textures[p_name].erase(p_index);
  197. if (default_textures[p_name].is_empty()) {
  198. default_textures.erase(p_name);
  199. }
  200. }
  201. RS::get_singleton()->shader_set_default_texture_parameter(shader_rid, p_name, RID(), p_index);
  202. }
  203. emit_changed();
  204. }
  205. Ref<Texture> Shader::get_default_texture_parameter(const StringName &p_name, int p_index) const {
  206. if (default_textures.has(p_name) && default_textures[p_name].has(p_index)) {
  207. return default_textures[p_name][p_index];
  208. }
  209. return Ref<Texture2D>();
  210. }
  211. void Shader::get_default_texture_parameter_list(List<StringName> *r_textures) const {
  212. for (const KeyValue<StringName, HashMap<int, Ref<Texture>>> &E : default_textures) {
  213. r_textures->push_back(E.key);
  214. }
  215. }
  216. bool Shader::is_text_shader() const {
  217. return true;
  218. }
  219. void Shader::_update_shader() const {
  220. // Base implementation does nothing.
  221. }
  222. Array Shader::_get_shader_uniform_list(bool p_get_groups) {
  223. List<PropertyInfo> uniform_list;
  224. get_shader_uniform_list(&uniform_list, p_get_groups);
  225. Array ret;
  226. for (const PropertyInfo &pi : uniform_list) {
  227. ret.push_back(pi.operator Dictionary());
  228. }
  229. return ret;
  230. }
  231. void Shader::_bind_methods() {
  232. ClassDB::bind_method(D_METHOD("get_mode"), &Shader::get_mode);
  233. ClassDB::bind_method(D_METHOD("set_code", "code"), &Shader::set_code);
  234. ClassDB::bind_method(D_METHOD("get_code"), &Shader::get_code);
  235. ClassDB::bind_method(D_METHOD("set_default_texture_parameter", "name", "texture", "index"), &Shader::set_default_texture_parameter, DEFVAL(0));
  236. ClassDB::bind_method(D_METHOD("get_default_texture_parameter", "name", "index"), &Shader::get_default_texture_parameter, DEFVAL(0));
  237. ClassDB::bind_method(D_METHOD("get_shader_uniform_list", "get_groups"), &Shader::_get_shader_uniform_list, DEFVAL(false));
  238. ClassDB::bind_method(D_METHOD("inspect_native_shader_code"), &Shader::inspect_native_shader_code);
  239. ClassDB::set_method_flags(get_class_static(), _scs_create("inspect_native_shader_code"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  240. ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_code", "get_code");
  241. BIND_ENUM_CONSTANT(MODE_SPATIAL);
  242. BIND_ENUM_CONSTANT(MODE_CANVAS_ITEM);
  243. BIND_ENUM_CONSTANT(MODE_PARTICLES);
  244. BIND_ENUM_CONSTANT(MODE_SKY);
  245. BIND_ENUM_CONSTANT(MODE_FOG);
  246. }
  247. Shader::Shader() {
  248. // Shader RID will be empty until it is required.
  249. }
  250. Shader::~Shader() {
  251. if (shader_rid.is_valid()) {
  252. ERR_FAIL_NULL(RenderingServer::get_singleton());
  253. RenderingServer::get_singleton()->free(shader_rid);
  254. }
  255. }
  256. ////////////
  257. 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) {
  258. if (r_error) {
  259. *r_error = ERR_FILE_CANT_OPEN;
  260. }
  261. Error error = OK;
  262. Vector<uint8_t> buffer = FileAccess::get_file_as_bytes(p_path, &error);
  263. ERR_FAIL_COND_V_MSG(error, nullptr, "Cannot load shader: " + p_path);
  264. String str;
  265. if (buffer.size() > 0) {
  266. error = str.parse_utf8((const char *)buffer.ptr(), buffer.size());
  267. ERR_FAIL_COND_V_MSG(error, nullptr, "Cannot parse shader: " + p_path);
  268. }
  269. Ref<Shader> shader;
  270. shader.instantiate();
  271. shader->set_include_path(p_path);
  272. shader->set_code(str);
  273. if (r_error) {
  274. *r_error = OK;
  275. }
  276. return shader;
  277. }
  278. void ResourceFormatLoaderShader::get_recognized_extensions(List<String> *p_extensions) const {
  279. p_extensions->push_back("gdshader");
  280. }
  281. bool ResourceFormatLoaderShader::handles_type(const String &p_type) const {
  282. return (p_type == "Shader");
  283. }
  284. String ResourceFormatLoaderShader::get_resource_type(const String &p_path) const {
  285. String el = p_path.get_extension().to_lower();
  286. if (el == "gdshader") {
  287. return "Shader";
  288. }
  289. return "";
  290. }
  291. Error ResourceFormatSaverShader::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  292. Ref<Shader> shader = p_resource;
  293. ERR_FAIL_COND_V(shader.is_null(), ERR_INVALID_PARAMETER);
  294. String source = shader->get_code();
  295. Error err;
  296. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  297. ERR_FAIL_COND_V_MSG(err, err, "Cannot save shader '" + p_path + "'.");
  298. file->store_string(source);
  299. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  300. return ERR_CANT_CREATE;
  301. }
  302. return OK;
  303. }
  304. void ResourceFormatSaverShader::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  305. if (const Shader *shader = Object::cast_to<Shader>(*p_resource)) {
  306. if (shader->is_text_shader()) {
  307. p_extensions->push_back("gdshader");
  308. }
  309. }
  310. }
  311. bool ResourceFormatSaverShader::recognize(const Ref<Resource> &p_resource) const {
  312. return p_resource->get_class_name() == "Shader"; //only shader, not inherited
  313. }