godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.17k stars 98 forks source link

Add warning when using an unassigned/uninitalized variable in shaders #10989

Open tetrapod00 opened 1 month ago

tetrapod00 commented 1 month ago

Describe the project you are working on

Shaders

Describe the problem or limitation you are having in your project

In shaders, unassigned local variables are not zero-initialized by default, and contain undefined values. This usually manifests as visual glitches.

Minimal example: Godot_v4 3-stable_win64_1boVkq23nA

shader_type spatial;

void fragment() {
    vec4 unset_color;
    ALBEDO = unset_color.rgb; 
}

See original issue https://github.com/godotengine/godot/issues/98223.

Describe the feature / enhancement and how it helps to overcome the problem or limitation

In the shader editor, warn if an unassigned variable is read from.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

Detect if an unassigned variable is used, and emit a warning. Note that some cases need more complex static analysis, such as the following (thanks @AThousandShips for the example):

vec4 color_variable;
if (foo) {
    color_variable = vec4(1, 0, 0, 1);
}
ALBEDO = color_variable.rgb;
ALPHA = color_variable.a;

If this enhancement will not be used often, can it be worked around with a few lines of script?

It can be worked around by documenting the behavior, and by assigning a value before using a variable.

Is there a reason why this should be core and not an add-on in the asset library?

The shader editor and compiler is core.

clayjohn commented 1 month ago

If this can be done in a very clean way and only when running in the editor, that would be great. But I don't think running static analysis on shaders at run time / load time is acceptable for a real time game engine.