From d2b1ab58f4631ca85b5433ae9a6c74befa551076 Mon Sep 17 00:00:00 2001 From: Danil Alexeev Date: Mon, 1 Sep 2025 12:09:52 +0300 Subject: [PATCH] [3.x] Shaders: Backport structs documentation --- .../shader_reference/shading_language.rst | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tutorials/shaders/shader_reference/shading_language.rst b/tutorials/shaders/shader_reference/shading_language.rst index f9c6607770d..083b0d3311b 100644 --- a/tutorials/shaders/shader_reference/shading_language.rst +++ b/tutorials/shaders/shader_reference/shading_language.rst @@ -293,6 +293,75 @@ Global constants are useful when you want to have access to a value throughout y const float PI = 3.14159265358979323846; +Structs +------- + +Structs are compound types which can be used for better abstraction of shader +code. You can declare them at the global scope like: + +.. code-block:: glsl + + struct PointLight { + vec3 position; + vec3 color; + float intensity; + }; + +After declaration, you can instantiate and initialize them like: + +.. code-block:: glsl + + void fragment() + { + PointLight light; + light.position = vec3(0.0); + light.color = vec3(1.0, 0.0, 0.0); + light.intensity = 0.5; + } + +Or use a struct constructor for the same purpose: + +.. code-block:: glsl + + PointLight light = PointLight(vec3(0.0), vec3(1.0, 0.0, 0.0), 0.5); + +Structs may contain other structs or arrays, you can also instance them as a global +constant: + +.. code-block:: glsl + + shader_type spatial; + + ... + + struct Scene { + PointLight lights[2]; + }; + + const Scene scene = Scene(PointLight[2](PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0))); + + void fragment() + { + ALBEDO = scene.lights[0].color; + } + +You can also pass them to functions: + +.. code-block:: glsl + + shader_type canvas_item; + + ... + + Scene construct_scene(PointLight light1, PointLight light2) { + return Scene({light1, light2}); + } + + void fragment() + { + COLOR.rgb = construct_scene(PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 1.0), 1.0)).lights[0].color; + } + Operators ---------