-
-
Notifications
You must be signed in to change notification settings - Fork 21.1k
/
material.cpp
3152 lines (2627 loc) · 127 KB
/
material.cpp
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/* material.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 "material.h"
#include "core/config/engine.h"
#include "core/config/project_settings.h"
#include "core/error/error_macros.h"
#include "core/version.h"
#include "scene/main/scene_tree.h"
#include "scene/scene_string_names.h"
void Material::set_next_pass(const Ref<Material> &p_pass) {
for (Ref<Material> pass_child = p_pass; pass_child != nullptr; pass_child = pass_child->get_next_pass()) {
ERR_FAIL_COND_MSG(pass_child == this, "Can't set as next_pass one of its parents to prevent crashes due to recursive loop.");
}
if (next_pass == p_pass) {
return;
}
next_pass = p_pass;
RID next_pass_rid;
if (next_pass.is_valid()) {
next_pass_rid = next_pass->get_rid();
}
RS::get_singleton()->material_set_next_pass(material, next_pass_rid);
}
Ref<Material> Material::get_next_pass() const {
return next_pass;
}
void Material::set_render_priority(int p_priority) {
ERR_FAIL_COND(p_priority < RENDER_PRIORITY_MIN);
ERR_FAIL_COND(p_priority > RENDER_PRIORITY_MAX);
render_priority = p_priority;
RS::get_singleton()->material_set_render_priority(material, p_priority);
}
int Material::get_render_priority() const {
return render_priority;
}
RID Material::get_rid() const {
return material;
}
void Material::_validate_property(PropertyInfo &p_property) const {
if (!_can_do_next_pass() && p_property.name == "next_pass") {
p_property.usage = PROPERTY_USAGE_NONE;
}
if (!_can_use_render_priority() && p_property.name == "render_priority") {
p_property.usage = PROPERTY_USAGE_NONE;
}
}
void Material::inspect_native_shader_code() {
SceneTree *st = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
RID shader = get_shader_rid();
if (st && shader.is_valid()) {
st->call_group_flags(SceneTree::GROUP_CALL_DEFERRED, "_native_shader_source_visualizer", "_inspect_shader", shader);
}
}
RID Material::get_shader_rid() const {
RID ret;
GDVIRTUAL_REQUIRED_CALL(_get_shader_rid, ret);
return ret;
}
Shader::Mode Material::get_shader_mode() const {
Shader::Mode ret = Shader::MODE_MAX;
GDVIRTUAL_REQUIRED_CALL(_get_shader_mode, ret);
return ret;
}
bool Material::_can_do_next_pass() const {
bool ret = false;
GDVIRTUAL_CALL(_can_do_next_pass, ret);
return ret;
}
bool Material::_can_use_render_priority() const {
bool ret = false;
GDVIRTUAL_CALL(_can_use_render_priority, ret);
return ret;
}
Ref<Resource> Material::create_placeholder() const {
Ref<PlaceholderMaterial> placeholder;
placeholder.instantiate();
return placeholder;
}
void Material::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_next_pass", "next_pass"), &Material::set_next_pass);
ClassDB::bind_method(D_METHOD("get_next_pass"), &Material::get_next_pass);
ClassDB::bind_method(D_METHOD("set_render_priority", "priority"), &Material::set_render_priority);
ClassDB::bind_method(D_METHOD("get_render_priority"), &Material::get_render_priority);
ClassDB::bind_method(D_METHOD("inspect_native_shader_code"), &Material::inspect_native_shader_code);
ClassDB::set_method_flags(get_class_static(), _scs_create("inspect_native_shader_code"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
ClassDB::bind_method(D_METHOD("create_placeholder"), &Material::create_placeholder);
ADD_PROPERTY(PropertyInfo(Variant::INT, "render_priority", PROPERTY_HINT_RANGE, itos(RENDER_PRIORITY_MIN) + "," + itos(RENDER_PRIORITY_MAX) + ",1"), "set_render_priority", "get_render_priority");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "next_pass", PROPERTY_HINT_RESOURCE_TYPE, "Material"), "set_next_pass", "get_next_pass");
BIND_CONSTANT(RENDER_PRIORITY_MAX);
BIND_CONSTANT(RENDER_PRIORITY_MIN);
GDVIRTUAL_BIND(_get_shader_rid)
GDVIRTUAL_BIND(_get_shader_mode)
GDVIRTUAL_BIND(_can_do_next_pass)
GDVIRTUAL_BIND(_can_use_render_priority)
}
Material::Material() {
material = RenderingServer::get_singleton()->material_create();
render_priority = 0;
}
Material::~Material() {
ERR_FAIL_NULL(RenderingServer::get_singleton());
RenderingServer::get_singleton()->free(material);
}
///////////////////////////////////
bool ShaderMaterial::_set(const StringName &p_name, const Variant &p_value) {
if (shader.is_valid()) {
const StringName *sn = remap_cache.getptr(p_name);
if (sn) {
set_shader_parameter(*sn, p_value);
return true;
}
String s = p_name;
if (s.begins_with("shader_parameter/")) {
String param = s.replace_first("shader_parameter/", "");
remap_cache[s] = param;
set_shader_parameter(param, p_value);
return true;
}
#ifndef DISABLE_DEPRECATED
// Compatibility remaps are only needed here.
if (s.begins_with("param/")) {
s = s.replace_first("param/", "shader_parameter/");
} else if (s.begins_with("shader_param/")) {
s = s.replace_first("shader_param/", "shader_parameter/");
} else if (s.begins_with("shader_uniform/")) {
s = s.replace_first("shader_uniform/", "shader_parameter/");
} else {
return false; // Not a shader parameter.
}
WARN_PRINT("This material (containing shader with path: '" + shader->get_path() + "') uses an old deprecated parameter names. Consider re-saving this resource (or scene which contains it) in order for it to continue working in future versions.");
String param = s.replace_first("shader_parameter/", "");
remap_cache[s] = param;
set_shader_parameter(param, p_value);
return true;
#endif
}
return false;
}
bool ShaderMaterial::_get(const StringName &p_name, Variant &r_ret) const {
if (shader.is_valid()) {
const StringName *sn = remap_cache.getptr(p_name);
if (sn) {
// Only return a parameter if it was previously set.
r_ret = get_shader_parameter(*sn);
return true;
}
}
return false;
}
void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const {
if (!shader.is_null()) {
List<PropertyInfo> list;
shader->get_shader_uniform_list(&list, true);
HashMap<String, HashMap<String, List<PropertyInfo>>> groups;
{
HashMap<String, List<PropertyInfo>> none_subgroup;
none_subgroup.insert("<None>", List<PropertyInfo>());
groups.insert("<None>", none_subgroup);
}
String last_group = "<None>";
String last_subgroup = "<None>";
bool is_none_group_undefined = true;
bool is_none_group = true;
for (List<PropertyInfo>::Element *E = list.front(); E; E = E->next()) {
if (E->get().usage == PROPERTY_USAGE_GROUP) {
if (!E->get().name.is_empty()) {
Vector<String> vgroup = E->get().name.split("::");
last_group = vgroup[0];
if (vgroup.size() > 1) {
last_subgroup = vgroup[1];
} else {
last_subgroup = "<None>";
}
is_none_group = false;
if (!groups.has(last_group)) {
PropertyInfo info;
info.usage = PROPERTY_USAGE_GROUP;
info.name = last_group.capitalize();
info.hint_string = "shader_parameter/";
List<PropertyInfo> none_subgroup;
none_subgroup.push_back(info);
HashMap<String, List<PropertyInfo>> subgroup_map;
subgroup_map.insert("<None>", none_subgroup);
groups.insert(last_group, subgroup_map);
}
if (!groups[last_group].has(last_subgroup)) {
PropertyInfo info;
info.usage = PROPERTY_USAGE_SUBGROUP;
info.name = last_subgroup.capitalize();
info.hint_string = "shader_parameter/";
List<PropertyInfo> subgroup;
subgroup.push_back(info);
groups[last_group].insert(last_subgroup, subgroup);
}
} else {
last_group = "<None>";
last_subgroup = "<None>";
is_none_group = true;
}
continue; // Pass group.
}
if (is_none_group_undefined && is_none_group) {
is_none_group_undefined = false;
PropertyInfo info;
info.usage = PROPERTY_USAGE_GROUP;
info.name = "Shader Parameters";
info.hint_string = "shader_parameter/";
groups["<None>"]["<None>"].push_back(info);
}
PropertyInfo info = E->get();
info.name = "shader_parameter/" + info.name;
if (!param_cache.has(E->get().name)) {
// Property has never been edited, retrieve with default value.
Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), E->get().name);
param_cache.insert(E->get().name, default_value);
remap_cache.insert(info.name, E->get().name);
}
groups[last_group][last_subgroup].push_back(info);
}
List<String> group_names;
for (HashMap<String, HashMap<String, List<PropertyInfo>>>::Iterator group = groups.begin(); group; ++group) {
group_names.push_back(group->key);
}
group_names.sort();
for (const String &group_name : group_names) {
List<String> subgroup_names;
HashMap<String, List<PropertyInfo>> &subgroups = groups[group_name];
for (HashMap<String, List<PropertyInfo>>::Iterator subgroup = subgroups.begin(); subgroup; ++subgroup) {
subgroup_names.push_back(subgroup->key);
}
subgroup_names.sort();
for (const String &subgroup_name : subgroup_names) {
List<PropertyInfo> &prop_infos = subgroups[subgroup_name];
for (List<PropertyInfo>::Element *item = prop_infos.front(); item; item = item->next()) {
p_list->push_back(item->get());
}
}
}
}
}
bool ShaderMaterial::_property_can_revert(const StringName &p_name) const {
if (shader.is_valid()) {
const StringName *pr = remap_cache.getptr(p_name);
if (pr) {
Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), *pr);
Variant current_value = get_shader_parameter(*pr);
return default_value.get_type() != Variant::NIL && default_value != current_value;
}
}
return false;
}
bool ShaderMaterial::_property_get_revert(const StringName &p_name, Variant &r_property) const {
if (shader.is_valid()) {
const StringName *pr = remap_cache.getptr(p_name);
if (*pr) {
r_property = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), *pr);
return true;
}
}
return false;
}
void ShaderMaterial::set_shader(const Ref<Shader> &p_shader) {
// Only connect/disconnect the signal when running in the editor.
// This can be a slow operation, and `notify_property_list_changed()` (which is called by `_shader_changed()`)
// does nothing in non-editor builds anyway. See GH-34741 for details.
if (shader.is_valid() && Engine::get_singleton()->is_editor_hint()) {
shader->disconnect("changed", callable_mp(this, &ShaderMaterial::_shader_changed));
}
shader = p_shader;
RID rid;
if (shader.is_valid()) {
rid = shader->get_rid();
if (Engine::get_singleton()->is_editor_hint()) {
shader->connect("changed", callable_mp(this, &ShaderMaterial::_shader_changed));
}
}
RS::get_singleton()->material_set_shader(_get_material(), rid);
notify_property_list_changed(); //properties for shader exposed
emit_changed();
}
Ref<Shader> ShaderMaterial::get_shader() const {
return shader;
}
void ShaderMaterial::set_shader_parameter(const StringName &p_param, const Variant &p_value) {
if (p_value.get_type() == Variant::NIL) {
param_cache.erase(p_param);
RS::get_singleton()->material_set_param(_get_material(), p_param, Variant());
} else {
param_cache[p_param] = p_value;
if (p_value.get_type() == Variant::OBJECT) {
RID tex_rid = p_value;
if (tex_rid == RID()) {
param_cache.erase(p_param);
RS::get_singleton()->material_set_param(_get_material(), p_param, Variant());
} else {
RS::get_singleton()->material_set_param(_get_material(), p_param, tex_rid);
}
} else {
RS::get_singleton()->material_set_param(_get_material(), p_param, p_value);
}
}
}
Variant ShaderMaterial::get_shader_parameter(const StringName &p_param) const {
if (param_cache.has(p_param)) {
return param_cache[p_param];
} else {
return Variant();
}
}
void ShaderMaterial::_shader_changed() {
notify_property_list_changed(); //update all properties
}
void ShaderMaterial::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_shader", "shader"), &ShaderMaterial::set_shader);
ClassDB::bind_method(D_METHOD("get_shader"), &ShaderMaterial::get_shader);
ClassDB::bind_method(D_METHOD("set_shader_parameter", "param", "value"), &ShaderMaterial::set_shader_parameter);
ClassDB::bind_method(D_METHOD("get_shader_parameter", "param"), &ShaderMaterial::get_shader_parameter);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, "Shader"), "set_shader", "get_shader");
}
void ShaderMaterial::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
String f = p_function.operator String();
if ((f == "get_shader_parameter" || f == "set_shader_parameter") && p_idx == 0) {
if (shader.is_valid()) {
List<PropertyInfo> pl;
shader->get_shader_uniform_list(&pl);
for (const PropertyInfo &E : pl) {
r_options->push_back(E.name.replace_first("shader_parameter/", "").quote());
}
}
}
Resource::get_argument_options(p_function, p_idx, r_options);
}
bool ShaderMaterial::_can_do_next_pass() const {
return shader.is_valid() && shader->get_mode() == Shader::MODE_SPATIAL;
}
bool ShaderMaterial::_can_use_render_priority() const {
return shader.is_valid() && shader->get_mode() == Shader::MODE_SPATIAL;
}
Shader::Mode ShaderMaterial::get_shader_mode() const {
if (shader.is_valid()) {
return shader->get_mode();
} else {
return Shader::MODE_SPATIAL;
}
}
RID ShaderMaterial::get_shader_rid() const {
if (shader.is_valid()) {
return shader->get_rid();
} else {
return RID();
}
}
ShaderMaterial::ShaderMaterial() {
}
ShaderMaterial::~ShaderMaterial() {
}
/////////////////////////////////
Mutex BaseMaterial3D::material_mutex;
SelfList<BaseMaterial3D>::List *BaseMaterial3D::dirty_materials = nullptr;
HashMap<BaseMaterial3D::MaterialKey, BaseMaterial3D::ShaderData, BaseMaterial3D::MaterialKey> BaseMaterial3D::shader_map;
BaseMaterial3D::ShaderNames *BaseMaterial3D::shader_names = nullptr;
void BaseMaterial3D::init_shaders() {
dirty_materials = memnew(SelfList<BaseMaterial3D>::List);
shader_names = memnew(ShaderNames);
shader_names->albedo = "albedo";
shader_names->specular = "specular";
shader_names->roughness = "roughness";
shader_names->metallic = "metallic";
shader_names->emission = "emission";
shader_names->emission_energy = "emission_energy";
shader_names->normal_scale = "normal_scale";
shader_names->rim = "rim";
shader_names->rim_tint = "rim_tint";
shader_names->clearcoat = "clearcoat";
shader_names->clearcoat_roughness = "clearcoat_roughness";
shader_names->anisotropy = "anisotropy_ratio";
shader_names->heightmap_scale = "heightmap_scale";
shader_names->subsurface_scattering_strength = "subsurface_scattering_strength";
shader_names->backlight = "backlight";
shader_names->refraction = "refraction";
shader_names->point_size = "point_size";
shader_names->uv1_scale = "uv1_scale";
shader_names->uv1_offset = "uv1_offset";
shader_names->uv2_scale = "uv2_scale";
shader_names->uv2_offset = "uv2_offset";
shader_names->uv1_blend_sharpness = "uv1_blend_sharpness";
shader_names->uv2_blend_sharpness = "uv2_blend_sharpness";
shader_names->particles_anim_h_frames = "particles_anim_h_frames";
shader_names->particles_anim_v_frames = "particles_anim_v_frames";
shader_names->particles_anim_loop = "particles_anim_loop";
shader_names->heightmap_min_layers = "heightmap_min_layers";
shader_names->heightmap_max_layers = "heightmap_max_layers";
shader_names->heightmap_flip = "heightmap_flip";
shader_names->grow = "grow";
shader_names->ao_light_affect = "ao_light_affect";
shader_names->proximity_fade_distance = "proximity_fade_distance";
shader_names->distance_fade_min = "distance_fade_min";
shader_names->distance_fade_max = "distance_fade_max";
shader_names->msdf_pixel_range = "msdf_pixel_range";
shader_names->msdf_outline_size = "msdf_outline_size";
shader_names->metallic_texture_channel = "metallic_texture_channel";
shader_names->ao_texture_channel = "ao_texture_channel";
shader_names->clearcoat_texture_channel = "clearcoat_texture_channel";
shader_names->rim_texture_channel = "rim_texture_channel";
shader_names->heightmap_texture_channel = "heightmap_texture_channel";
shader_names->refraction_texture_channel = "refraction_texture_channel";
shader_names->transmittance_color = "transmittance_color";
shader_names->transmittance_depth = "transmittance_depth";
shader_names->transmittance_boost = "transmittance_boost";
shader_names->texture_names[TEXTURE_ALBEDO] = "texture_albedo";
shader_names->texture_names[TEXTURE_METALLIC] = "texture_metallic";
shader_names->texture_names[TEXTURE_ROUGHNESS] = "texture_roughness";
shader_names->texture_names[TEXTURE_EMISSION] = "texture_emission";
shader_names->texture_names[TEXTURE_NORMAL] = "texture_normal";
shader_names->texture_names[TEXTURE_RIM] = "texture_rim";
shader_names->texture_names[TEXTURE_CLEARCOAT] = "texture_clearcoat";
shader_names->texture_names[TEXTURE_FLOWMAP] = "texture_flowmap";
shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION] = "texture_ambient_occlusion";
shader_names->texture_names[TEXTURE_HEIGHTMAP] = "texture_heightmap";
shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING] = "texture_subsurface_scattering";
shader_names->texture_names[TEXTURE_SUBSURFACE_TRANSMITTANCE] = "texture_subsurface_transmittance";
shader_names->texture_names[TEXTURE_BACKLIGHT] = "texture_backlight";
shader_names->texture_names[TEXTURE_REFRACTION] = "texture_refraction";
shader_names->texture_names[TEXTURE_DETAIL_MASK] = "texture_detail_mask";
shader_names->texture_names[TEXTURE_DETAIL_ALBEDO] = "texture_detail_albedo";
shader_names->texture_names[TEXTURE_DETAIL_NORMAL] = "texture_detail_normal";
shader_names->texture_names[TEXTURE_ORM] = "texture_orm";
shader_names->alpha_scissor_threshold = "alpha_scissor_threshold";
shader_names->alpha_hash_scale = "alpha_hash_scale";
shader_names->alpha_antialiasing_edge = "alpha_antialiasing_edge";
shader_names->albedo_texture_size = "albedo_texture_size";
}
HashMap<uint64_t, Ref<StandardMaterial3D>> BaseMaterial3D::materials_for_2d;
void BaseMaterial3D::finish_shaders() {
materials_for_2d.clear();
memdelete(dirty_materials);
dirty_materials = nullptr;
memdelete(shader_names);
}
void BaseMaterial3D::_update_shader() {
dirty_materials->remove(&element);
MaterialKey mk = _compute_key();
if (mk == current_key) {
return; //no update required in the end
}
if (shader_map.has(current_key)) {
shader_map[current_key].users--;
if (shader_map[current_key].users == 0) {
//deallocate shader, as it's no longer in use
RS::get_singleton()->free(shader_map[current_key].shader);
shader_map.erase(current_key);
}
}
current_key = mk;
if (shader_map.has(mk)) {
RS::get_singleton()->material_set_shader(_get_material(), shader_map[mk].shader);
shader_map[mk].users++;
return;
}
String texfilter_str;
// Force linear filtering for the heightmap texture, as the heightmap effect
// looks broken with nearest-neighbor filtering (with and without Deep Parallax).
String texfilter_height_str;
switch (texture_filter) {
case TEXTURE_FILTER_NEAREST:
texfilter_str = "filter_nearest";
texfilter_height_str = "filter_linear";
break;
case TEXTURE_FILTER_LINEAR:
texfilter_str = "filter_linear";
texfilter_height_str = "filter_linear";
break;
case TEXTURE_FILTER_NEAREST_WITH_MIPMAPS:
texfilter_str = "filter_nearest_mipmap";
texfilter_height_str = "filter_linear_mipmap";
break;
case TEXTURE_FILTER_LINEAR_WITH_MIPMAPS:
texfilter_str = "filter_linear_mipmap";
texfilter_height_str = "filter_linear_mipmap";
break;
case TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC:
texfilter_str = "filter_nearest_mipmap_anisotropic";
texfilter_height_str = "filter_linear_mipmap_anisotropic";
break;
case TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC:
texfilter_str = "filter_linear_mipmap_anisotropic";
texfilter_height_str = "filter_linear_mipmap_anisotropic";
break;
case TEXTURE_FILTER_MAX:
break; // Internal value, skip.
}
if (flags[FLAG_USE_TEXTURE_REPEAT]) {
texfilter_str += ",repeat_enable";
texfilter_height_str += ",repeat_enable";
} else {
texfilter_str += ",repeat_disable";
texfilter_height_str += ",repeat_disable";
}
//must create a shader!
// Add a comment to describe the shader origin (useful when converting to ShaderMaterial).
String code = vformat(
"// NOTE: Shader automatically converted from " VERSION_NAME " " VERSION_FULL_CONFIG "'s %s.\n\n",
orm ? "ORMMaterial3D" : "StandardMaterial3D");
code += "shader_type spatial;\nrender_mode ";
switch (blend_mode) {
case BLEND_MODE_MIX:
code += "blend_mix";
break;
case BLEND_MODE_ADD:
code += "blend_add";
break;
case BLEND_MODE_SUB:
code += "blend_sub";
break;
case BLEND_MODE_MUL:
code += "blend_mul";
break;
case BLEND_MODE_MAX:
break; // Internal value, skip.
}
DepthDrawMode ddm = depth_draw_mode;
if (features[FEATURE_REFRACTION]) {
ddm = DEPTH_DRAW_ALWAYS;
}
switch (ddm) {
case DEPTH_DRAW_OPAQUE_ONLY:
code += ",depth_draw_opaque";
break;
case DEPTH_DRAW_ALWAYS:
code += ",depth_draw_always";
break;
case DEPTH_DRAW_DISABLED:
code += ",depth_draw_never";
break;
case DEPTH_DRAW_MAX:
break; // Internal value, skip.
}
switch (cull_mode) {
case CULL_BACK:
code += ",cull_back";
break;
case CULL_FRONT:
code += ",cull_front";
break;
case CULL_DISABLED:
code += ",cull_disabled";
break;
case CULL_MAX:
break; // Internal value, skip.
}
switch (diffuse_mode) {
case DIFFUSE_BURLEY:
code += ",diffuse_burley";
break;
case DIFFUSE_LAMBERT:
code += ",diffuse_lambert";
break;
case DIFFUSE_LAMBERT_WRAP:
code += ",diffuse_lambert_wrap";
break;
case DIFFUSE_TOON:
code += ",diffuse_toon";
break;
case DIFFUSE_MAX:
break; // Internal value, skip.
}
switch (specular_mode) {
case SPECULAR_SCHLICK_GGX:
code += ",specular_schlick_ggx";
break;
case SPECULAR_TOON:
code += ",specular_toon";
break;
case SPECULAR_DISABLED:
code += ",specular_disabled";
break;
case SPECULAR_MAX:
break; // Internal value, skip.
}
if (features[FEATURE_SUBSURFACE_SCATTERING] && flags[FLAG_SUBSURFACE_MODE_SKIN]) {
code += ",sss_mode_skin";
}
if (shading_mode == SHADING_MODE_UNSHADED) {
code += ",unshaded";
}
if (flags[FLAG_DISABLE_DEPTH_TEST]) {
code += ",depth_test_disabled";
}
if (flags[FLAG_PARTICLE_TRAILS_MODE]) {
code += ",particle_trails";
}
if (shading_mode == SHADING_MODE_PER_VERTEX) {
code += ",vertex_lighting";
}
if (flags[FLAG_DONT_RECEIVE_SHADOWS]) {
code += ",shadows_disabled";
}
if (flags[FLAG_DISABLE_AMBIENT_LIGHT]) {
code += ",ambient_light_disabled";
}
if (flags[FLAG_USE_SHADOW_TO_OPACITY]) {
code += ",shadow_to_opacity";
}
if (transparency == TRANSPARENCY_ALPHA_DEPTH_PRE_PASS) {
code += ",depth_prepass_alpha";
}
// Although its technically possible to do alpha antialiasing without using alpha hash or alpha scissor,
// it is restricted in the base material because it has no use, and abusing it with regular Alpha blending can
// saturate the MSAA mask
if (transparency == TRANSPARENCY_ALPHA_HASH || transparency == TRANSPARENCY_ALPHA_SCISSOR) {
// alpha antialiasing is only useful in ALPHA_HASH or ALPHA_SCISSOR
if (alpha_antialiasing_mode == ALPHA_ANTIALIASING_ALPHA_TO_COVERAGE) {
code += ",alpha_to_coverage";
} else if (alpha_antialiasing_mode == ALPHA_ANTIALIASING_ALPHA_TO_COVERAGE_AND_TO_ONE) {
code += ",alpha_to_coverage_and_one";
}
}
code += ";\n";
code += "uniform vec4 albedo : source_color;\n";
code += "uniform sampler2D texture_albedo : source_color," + texfilter_str + ";\n";
if (grow_enabled) {
code += "uniform float grow;\n";
}
if (proximity_fade_enabled) {
code += "uniform float proximity_fade_distance;\n";
}
if (distance_fade != DISTANCE_FADE_DISABLED) {
code += "uniform float distance_fade_min;\n";
code += "uniform float distance_fade_max;\n";
}
if (flags[FLAG_ALBEDO_TEXTURE_MSDF]) {
code += "uniform float msdf_pixel_range;\n";
code += "uniform float msdf_outline_size;\n";
}
// alpha scissor is only valid if there is not antialiasing edge
// alpha hash is valid whenever, but not with alpha scissor
if (transparency == TRANSPARENCY_ALPHA_SCISSOR) {
code += "uniform float alpha_scissor_threshold;\n";
} else if (transparency == TRANSPARENCY_ALPHA_HASH) {
code += "uniform float alpha_hash_scale;\n";
}
// if alpha antialiasing isn't off, add in the edge variable
if (alpha_antialiasing_mode != ALPHA_ANTIALIASING_OFF &&
(transparency == TRANSPARENCY_ALPHA_SCISSOR || transparency == TRANSPARENCY_ALPHA_HASH)) {
code += "uniform float alpha_antialiasing_edge;\n";
code += "uniform ivec2 albedo_texture_size;\n";
}
code += "uniform float point_size : hint_range(0,128);\n";
//TODO ALL HINTS
if (!orm) {
code += "uniform float roughness : hint_range(0,1);\n";
code += "uniform sampler2D texture_metallic : hint_default_white," + texfilter_str + ";\n";
code += "uniform vec4 metallic_texture_channel;\n";
switch (roughness_texture_channel) {
case TEXTURE_CHANNEL_RED: {
code += "uniform sampler2D texture_roughness : hint_roughness_r," + texfilter_str + ";\n";
} break;
case TEXTURE_CHANNEL_GREEN: {
code += "uniform sampler2D texture_roughness : hint_roughness_g," + texfilter_str + ";\n";
} break;
case TEXTURE_CHANNEL_BLUE: {
code += "uniform sampler2D texture_roughness : hint_roughness_b," + texfilter_str + ";\n";
} break;
case TEXTURE_CHANNEL_ALPHA: {
code += "uniform sampler2D texture_roughness : hint_roughness_a," + texfilter_str + ";\n";
} break;
case TEXTURE_CHANNEL_GRAYSCALE: {
code += "uniform sampler2D texture_roughness : hint_roughness_gray," + texfilter_str + ";\n";
} break;
case TEXTURE_CHANNEL_MAX:
break; // Internal value, skip.
}
code += "uniform float specular;\n";
code += "uniform float metallic;\n";
} else {
code += "uniform sampler2D texture_orm : hint_roughness_g," + texfilter_str + ";\n";
}
if (billboard_mode == BILLBOARD_PARTICLES) {
code += "uniform int particles_anim_h_frames;\n";
code += "uniform int particles_anim_v_frames;\n";
code += "uniform bool particles_anim_loop;\n";
}
if (features[FEATURE_EMISSION]) {
code += "uniform sampler2D texture_emission : source_color, hint_default_black," + texfilter_str + ";\n";
code += "uniform vec4 emission : source_color;\n";
code += "uniform float emission_energy;\n";
}
if (features[FEATURE_REFRACTION]) {
code += "uniform sampler2D texture_refraction : " + texfilter_str + ";\n";
code += "uniform float refraction : hint_range(-16,16);\n";
code += "uniform vec4 refraction_texture_channel;\n";
}
if (features[FEATURE_REFRACTION]) {
code += "uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_linear_mipmap;";
}
if (proximity_fade_enabled) {
code += "uniform sampler2D depth_texture : hint_depth_texture, repeat_disable, filter_nearest;";
}
if (features[FEATURE_NORMAL_MAPPING]) {
code += "uniform sampler2D texture_normal : hint_roughness_normal," + texfilter_str + ";\n";
code += "uniform float normal_scale : hint_range(-16,16);\n";
}
if (features[FEATURE_RIM]) {
code += "uniform float rim : hint_range(0,1);\n";
code += "uniform float rim_tint : hint_range(0,1);\n";
code += "uniform sampler2D texture_rim : hint_default_white," + texfilter_str + ";\n";
}
if (features[FEATURE_CLEARCOAT]) {
code += "uniform float clearcoat : hint_range(0,1);\n";
code += "uniform float clearcoat_roughness : hint_range(0,1);\n";
code += "uniform sampler2D texture_clearcoat : hint_default_white," + texfilter_str + ";\n";
}
if (features[FEATURE_ANISOTROPY]) {
code += "uniform float anisotropy_ratio : hint_range(0,256);\n";
code += "uniform sampler2D texture_flowmap : hint_anisotropy," + texfilter_str + ";\n";
}
if (features[FEATURE_AMBIENT_OCCLUSION]) {
code += "uniform sampler2D texture_ambient_occlusion : hint_default_white, " + texfilter_str + ";\n";
code += "uniform vec4 ao_texture_channel;\n";
code += "uniform float ao_light_affect;\n";
}
if (features[FEATURE_DETAIL]) {
code += "uniform sampler2D texture_detail_albedo : source_color," + texfilter_str + ";\n";
code += "uniform sampler2D texture_detail_normal : hint_normal," + texfilter_str + ";\n";
code += "uniform sampler2D texture_detail_mask : hint_default_white," + texfilter_str + ";\n";
}
if (features[FEATURE_SUBSURFACE_SCATTERING]) {
code += "uniform float subsurface_scattering_strength : hint_range(0,1);\n";
code += "uniform sampler2D texture_subsurface_scattering : hint_default_white," + texfilter_str + ";\n";
}
if (features[FEATURE_SUBSURFACE_TRANSMITTANCE]) {
code += "uniform vec4 transmittance_color : source_color;\n";
code += "uniform float transmittance_depth;\n";
code += "uniform sampler2D texture_subsurface_transmittance : hint_default_white," + texfilter_str + ";\n";
code += "uniform float transmittance_boost;\n";
}
if (features[FEATURE_BACKLIGHT]) {
code += "uniform vec4 backlight : source_color;\n";
code += "uniform sampler2D texture_backlight : hint_default_black," + texfilter_str + ";\n";
}
if (features[FEATURE_HEIGHT_MAPPING]) {
code += "uniform sampler2D texture_heightmap : hint_default_black," + texfilter_height_str + ";\n";
code += "uniform float heightmap_scale;\n";
code += "uniform int heightmap_min_layers;\n";
code += "uniform int heightmap_max_layers;\n";
code += "uniform vec2 heightmap_flip;\n";
}
if (flags[FLAG_UV1_USE_TRIPLANAR]) {
code += "varying vec3 uv1_triplanar_pos;\n";
}
if (flags[FLAG_UV2_USE_TRIPLANAR]) {
code += "varying vec3 uv2_triplanar_pos;\n";
}
if (flags[FLAG_UV1_USE_TRIPLANAR]) {
code += "uniform float uv1_blend_sharpness;\n";
code += "varying vec3 uv1_power_normal;\n";
}
if (flags[FLAG_UV2_USE_TRIPLANAR]) {
code += "uniform float uv2_blend_sharpness;\n";
code += "varying vec3 uv2_power_normal;\n";
}
code += "uniform vec3 uv1_scale;\n";
code += "uniform vec3 uv1_offset;\n";
code += "uniform vec3 uv2_scale;\n";
code += "uniform vec3 uv2_offset;\n";
code += "\n\n";
code += "void vertex() {\n";
if (flags[FLAG_SRGB_VERTEX_COLOR]) {
code += " if (!OUTPUT_IS_SRGB) {\n";
code += " COLOR.rgb = mix(pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb * (1.0 / 12.92), lessThan(COLOR.rgb, vec3(0.04045)));\n";
code += " }\n";
}
if (flags[FLAG_USE_POINT_SIZE]) {
code += " POINT_SIZE=point_size;\n";
}
if (shading_mode == SHADING_MODE_PER_VERTEX) {
code += " ROUGHNESS=roughness;\n";
}
if (!flags[FLAG_UV1_USE_TRIPLANAR]) {
code += " UV=UV*uv1_scale.xy+uv1_offset.xy;\n";
}
switch (billboard_mode) {
case BILLBOARD_DISABLED: {
} break;
case BILLBOARD_ENABLED: {
code += " MODELVIEW_MATRIX = VIEW_MATRIX * mat4(INV_VIEW_MATRIX[0], INV_VIEW_MATRIX[1], INV_VIEW_MATRIX[2], MODEL_MATRIX[3]);\n";
if (flags[FLAG_BILLBOARD_KEEP_SCALE]) {
code += " MODELVIEW_MATRIX = MODELVIEW_MATRIX * mat4(vec4(length(MODEL_MATRIX[0].xyz), 0.0, 0.0, 0.0), vec4(0.0, length(MODEL_MATRIX[1].xyz), 0.0, 0.0), vec4(0.0, 0.0, length(MODEL_MATRIX[2].xyz), 0.0), vec4(0.0, 0.0, 0.0, 1.0));\n";
}
code += " MODELVIEW_NORMAL_MATRIX = mat3(MODELVIEW_MATRIX);\n";
} break;
case BILLBOARD_FIXED_Y: {
code += " MODELVIEW_MATRIX = VIEW_MATRIX * mat4(vec4(normalize(cross(vec3(0.0, 1.0, 0.0), INV_VIEW_MATRIX[2].xyz)), 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(normalize(cross(INV_VIEW_MATRIX[0].xyz, vec3(0.0, 1.0, 0.0))), 0.0), MODEL_MATRIX[3]);\n";
if (flags[FLAG_BILLBOARD_KEEP_SCALE]) {
code += " MODELVIEW_MATRIX = MODELVIEW_MATRIX * mat4(vec4(length(MODEL_MATRIX[0].xyz), 0.0, 0.0, 0.0),vec4(0.0, length(MODEL_MATRIX[1].xyz), 0.0, 0.0), vec4(0.0, 0.0, length(MODEL_MATRIX[2].xyz), 0.0), vec4(0.0, 0.0, 0.0, 1.0));\n";
}
code += " MODELVIEW_NORMAL_MATRIX = mat3(MODELVIEW_MATRIX);\n";
} break;
case BILLBOARD_PARTICLES: {
//make billboard
code += " mat4 mat_world = mat4(normalize(INV_VIEW_MATRIX[0]) * length(MODEL_MATRIX[0]), normalize(INV_VIEW_MATRIX[1]) * length(MODEL_MATRIX[0]),normalize(INV_VIEW_MATRIX[2]) * length(MODEL_MATRIX[2]), MODEL_MATRIX[3]);\n";
//rotate by rotation
code += " mat_world = mat_world * mat4(vec4(cos(INSTANCE_CUSTOM.x), -sin(INSTANCE_CUSTOM.x), 0.0, 0.0), vec4(sin(INSTANCE_CUSTOM.x), cos(INSTANCE_CUSTOM.x), 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0));\n";
//set modelview
code += " MODELVIEW_MATRIX = VIEW_MATRIX * mat_world;\n";
//set modelview normal
code += " MODELVIEW_NORMAL_MATRIX = mat3(MODELVIEW_MATRIX);\n";
//handle animation
code += " float h_frames = float(particles_anim_h_frames);\n";
code += " float v_frames = float(particles_anim_v_frames);\n";
code += " float particle_total_frames = float(particles_anim_h_frames * particles_anim_v_frames);\n";
code += " float particle_frame = floor(INSTANCE_CUSTOM.z * float(particle_total_frames));\n";
code += " if (!particles_anim_loop) {\n";
code += " particle_frame = clamp(particle_frame, 0.0, particle_total_frames - 1.0);\n";
code += " } else {\n";
code += " particle_frame = mod(particle_frame, particle_total_frames);\n";
code += " }\n";
code += " UV /= vec2(h_frames, v_frames);\n";
code += " UV += vec2(mod(particle_frame, h_frames) / h_frames, floor((particle_frame + 0.5) / h_frames) / v_frames);\n";
} break;
case BILLBOARD_MAX:
break; // Internal value, skip.
}
if (flags[FLAG_FIXED_SIZE]) {
code += " if (PROJECTION_MATRIX[3][3] != 0.0) {\n";
//orthogonal matrix, try to do about the same
//with viewport size
code += " float h = abs(1.0 / (2.0 * PROJECTION_MATRIX[1][1]));\n";
code += " float sc = (h * 2.0); //consistent with Y-fov\n";
code += " MODELVIEW_MATRIX[0]*=sc;\n";
code += " MODELVIEW_MATRIX[1]*=sc;\n";
code += " MODELVIEW_MATRIX[2]*=sc;\n";
code += " } else {\n";
//just scale by depth
code += " float sc = -(MODELVIEW_MATRIX)[3].z;\n";
code += " MODELVIEW_MATRIX[0]*=sc;\n";
code += " MODELVIEW_MATRIX[1]*=sc;\n";
code += " MODELVIEW_MATRIX[2]*=sc;\n";
code += " }\n";
}