Skip to content

Commit e05bb90

Browse files
committed
[3.x] Shaders: Backport structs documentation
1 parent 32a4041 commit e05bb90

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

tutorials/shaders/shader_reference/shading_language.rst

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,75 @@ Global constants are useful when you want to have access to a value throughout y
293293
294294
const float PI = 3.14159265358979323846;
295295
296+
Structs
297+
-------
298+
299+
Structs are compound types which can be used for better abstraction of shader
300+
code. You can declare them at the global scope like:
301+
302+
.. code-block:: glsl
303+
304+
struct PointLight {
305+
vec3 position;
306+
vec3 color;
307+
float intensity;
308+
};
309+
310+
After declaration, you can instantiate and initialize them like:
311+
312+
.. code-block:: glsl
313+
314+
void fragment()
315+
{
316+
PointLight light;
317+
light.position = vec3(0.0);
318+
light.color = vec3(1.0, 0.0, 0.0);
319+
light.intensity = 0.5;
320+
}
321+
322+
Or use struct constructor for same purpose:
323+
324+
.. code-block:: glsl
325+
326+
PointLight light = PointLight(vec3(0.0), vec3(1.0, 0.0, 0.0), 0.5);
327+
328+
Structs may contain other struct or array, you can also instance them as global
329+
constant:
330+
331+
.. code-block:: glsl
332+
333+
shader_type spatial;
334+
335+
...
336+
337+
struct Scene {
338+
PointLight lights[2];
339+
};
340+
341+
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)));
342+
343+
void fragment()
344+
{
345+
ALBEDO = scene.lights[0].color;
346+
}
347+
348+
You can also pass them to functions:
349+
350+
.. code-block:: glsl
351+
352+
shader_type canvas_item;
353+
354+
...
355+
356+
Scene construct_scene(PointLight light1, PointLight light2) {
357+
return Scene({light1, light2});
358+
}
359+
360+
void fragment()
361+
{
362+
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;
363+
}
364+
296365
Operators
297366
---------
298367

0 commit comments

Comments
 (0)