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