summaryrefslogtreecommitdiff
path: root/scene/resources/shader.cpp
blob: fd2be9ba22d09ab2ae0913393d9dc143f1199334 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**************************************************************************/
/*  shader.cpp                                                            */
/**************************************************************************/
/*                         This file is part of:                          */
/*                             GODOT ENGINE                               */
/*                        https://godotengine.org                         */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.                  */
/*                                                                        */
/* Permission is hereby granted, free of charge, to any person obtaining  */
/* a copy of this software and associated documentation files (the        */
/* "Software"), to deal in the Software without restriction, including    */
/* without limitation the rights to use, copy, modify, merge, publish,    */
/* distribute, sublicense, and/or sell copies of the Software, and to     */
/* permit persons to whom the Software is furnished to do so, subject to  */
/* the following conditions:                                              */
/*                                                                        */
/* The above copyright notice and this permission notice shall be         */
/* included in all copies or substantial portions of the Software.        */
/*                                                                        */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,        */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF     */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY   */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,   */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE      */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                 */
/**************************************************************************/

#include "shader.h"

#include "core/io/file_access.h"
#include "scene/scene_string_names.h"
#include "servers/rendering/shader_language.h"
#include "servers/rendering/shader_preprocessor.h"
#include "servers/rendering_server.h"
#include "texture.h"

Shader::Mode Shader::get_mode() const {
	return mode;
}

void Shader::_dependency_changed() {
	// Preprocess and compile the code again because a dependency has changed. It also calls emit_changed() for us.
	_recompile();
}

void Shader::_recompile() {
	set_code(get_code());
}

void Shader::set_path(const String &p_path, bool p_take_over) {
	Resource::set_path(p_path, p_take_over);
	RS::get_singleton()->shader_set_path_hint(shader, p_path);
}

void Shader::set_include_path(const String &p_path) {
	// Used only if the shader does not have a resource path set,
	// for example during loading stage or when created by code.
	include_path = p_path;
}

void Shader::set_code(const String &p_code) {
	for (Ref<ShaderInclude> E : include_dependencies) {
		E->disconnect(SNAME("changed"), callable_mp(this, &Shader::_dependency_changed));
	}

	String type = ShaderLanguage::get_shader_type(p_code);

	if (type == "canvas_item") {
		mode = MODE_CANVAS_ITEM;
	} else if (type == "particles") {
		mode = MODE_PARTICLES;
	} else if (type == "sky") {
		mode = MODE_SKY;
	} else if (type == "fog") {
		mode = MODE_FOG;
	} else {
		mode = MODE_SPATIAL;
	}

	code = p_code;
	String pp_code = p_code;

	HashSet<Ref<ShaderInclude>> new_include_dependencies;

	{
		String path = get_path();
		if (path.is_empty()) {
			path = include_path;
		}
		// Preprocessor must run here and not in the server because:
		// 1) Need to keep track of include dependencies at resource level
		// 2) Server does not do interaction with Resource filetypes, this is a scene level feature.
		ShaderPreprocessor preprocessor;
		preprocessor.preprocess(p_code, path, pp_code, nullptr, nullptr, nullptr, &new_include_dependencies);
	}

	// This ensures previous include resources are not freed and then re-loaded during parse (which would make compiling slower)
	include_dependencies = new_include_dependencies;

	for (Ref<ShaderInclude> E : include_dependencies) {
		E->connect(SNAME("changed"), callable_mp(this, &Shader::_dependency_changed));
	}

	RenderingServer::get_singleton()->shader_set_code(shader, pp_code);

	emit_changed();
}

String Shader::get_code() const {
	_update_shader();
	return code;
}

void Shader::get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_groups) const {
	_update_shader();

	List<PropertyInfo> local;
	RenderingServer::get_singleton()->get_shader_parameter_list(shader, &local);

	for (PropertyInfo &pi : local) {
		bool is_group = pi.usage == PROPERTY_USAGE_GROUP || pi.usage == PROPERTY_USAGE_SUBGROUP;
		if (!p_get_groups && is_group) {
			continue;
		}
		if (!is_group) {
			if (default_textures.has(pi.name)) { //do not show default textures
				continue;
			}
		}
		if (p_params) {
			//small little hack
			if (pi.type == Variant::RID) {
				pi.type = Variant::OBJECT;
			}
			p_params->push_back(pi);
		}
	}
}

RID Shader::get_rid() const {
	_update_shader();

	return shader;
}

void Shader::set_default_texture_parameter(const StringName &p_name, const Ref<Texture2D> &p_texture, int p_index) {
	if (p_texture.is_valid()) {
		if (!default_textures.has(p_name)) {
			default_textures[p_name] = HashMap<int, Ref<Texture2D>>();
		}
		default_textures[p_name][p_index] = p_texture;
		RS::get_singleton()->shader_set_default_texture_parameter(shader, p_name, p_texture->get_rid(), p_index);
	} else {
		if (default_textures.has(p_name) && default_textures[p_name].has(p_index)) {
			default_textures[p_name].erase(p_index);

			if (default_textures[p_name].is_empty()) {
				default_textures.erase(p_name);
			}
		}
		RS::get_singleton()->shader_set_default_texture_parameter(shader, p_name, RID(), p_index);
	}

	emit_changed();
}

Ref<Texture2D> Shader::get_default_texture_parameter(const StringName &p_name, int p_index) const {
	if (default_textures.has(p_name) && default_textures[p_name].has(p_index)) {
		return default_textures[p_name][p_index];
	}
	return Ref<Texture2D>();
}

void Shader::get_default_texture_parameter_list(List<StringName> *r_textures) const {
	for (const KeyValue<StringName, HashMap<int, Ref<Texture2D>>> &E : default_textures) {
		r_textures->push_back(E.key);
	}
}

bool Shader::is_text_shader() const {
	return true;
}

void Shader::_update_shader() const {
}

Array Shader::_get_shader_uniform_list(bool p_get_groups) {
	List<PropertyInfo> uniform_list;
	get_shader_uniform_list(&uniform_list, p_get_groups);
	Array ret;
	for (const PropertyInfo &pi : uniform_list) {
		ret.push_back(pi.operator Dictionary());
	}
	return ret;
}

void Shader::_bind_methods() {
	ClassDB::bind_method(D_METHOD("get_mode"), &Shader::get_mode);

	ClassDB::bind_method(D_METHOD("set_code", "code"), &Shader::set_code);
	ClassDB::bind_method(D_METHOD("get_code"), &Shader::get_code);

	ClassDB::bind_method(D_METHOD("set_default_texture_parameter", "name", "texture", "index"), &Shader::set_default_texture_parameter, DEFVAL(0));
	ClassDB::bind_method(D_METHOD("get_default_texture_parameter", "name", "index"), &Shader::get_default_texture_parameter, DEFVAL(0));

	ClassDB::bind_method(D_METHOD("get_shader_uniform_list", "get_groups"), &Shader::_get_shader_uniform_list, DEFVAL(false));

	ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_code", "get_code");

	BIND_ENUM_CONSTANT(MODE_SPATIAL);
	BIND_ENUM_CONSTANT(MODE_CANVAS_ITEM);
	BIND_ENUM_CONSTANT(MODE_PARTICLES);
	BIND_ENUM_CONSTANT(MODE_SKY);
	BIND_ENUM_CONSTANT(MODE_FOG);
}

Shader::Shader() {
	shader = RenderingServer::get_singleton()->shader_create();
}

Shader::~Shader() {
	ERR_FAIL_NULL(RenderingServer::get_singleton());
	RenderingServer::get_singleton()->free(shader);
}

////////////

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) {
	if (r_error) {
		*r_error = ERR_FILE_CANT_OPEN;
	}

	Ref<Shader> shader;
	shader.instantiate();

	Vector<uint8_t> buffer = FileAccess::get_file_as_bytes(p_path);

	String str;
	str.parse_utf8((const char *)buffer.ptr(), buffer.size());

	shader->set_include_path(p_path);
	shader->set_code(str);

	if (r_error) {
		*r_error = OK;
	}

	return shader;
}

void ResourceFormatLoaderShader::get_recognized_extensions(List<String> *p_extensions) const {
	p_extensions->push_back("gdshader");
}

bool ResourceFormatLoaderShader::handles_type(const String &p_type) const {
	return (p_type == "Shader");
}

String ResourceFormatLoaderShader::get_resource_type(const String &p_path) const {
	String el = p_path.get_extension().to_lower();
	if (el == "gdshader") {
		return "Shader";
	}
	return "";
}

Error ResourceFormatSaverShader::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
	Ref<Shader> shader = p_resource;
	ERR_FAIL_COND_V(shader.is_null(), ERR_INVALID_PARAMETER);

	String source = shader->get_code();

	Error err;
	Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);

	ERR_FAIL_COND_V_MSG(err, err, "Cannot save shader '" + p_path + "'.");

	file->store_string(source);
	if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
		return ERR_CANT_CREATE;
	}

	return OK;
}

void ResourceFormatSaverShader::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
	if (const Shader *shader = Object::cast_to<Shader>(*p_resource)) {
		if (shader->is_text_shader()) {
			p_extensions->push_back("gdshader");
		}
	}
}

bool ResourceFormatSaverShader::recognize(const Ref<Resource> &p_resource) const {
	return p_resource->get_class_name() == "Shader"; //only shader, not inherited
}