Starfield-style Shader Mechanics

I’m new to shaders.

In a classic starfield effect each star has a struct which represents its state: position, status, etc. I saw shaders which draw various starfields and I don’t understand how they do it. In a shader I can’t store any data per star. Reading code is hard. What is the trick?

The issue is that shaders seem to have no explicit STATE, like in most normal programs.

Depends on the use case. If you just want a bunch of stars in the sky all you need is a mesh with some arbitrary data stored on the vertices in the UV and color channels. For a star shader I wrote I have a mesh with 3000 quads with their brightness and positions stored in the UV channel. The quads are rotated towards the camera and flickered with a noise function completely in the shader. If I was to write this again I would probably do this by just having a vertex point cloud mesh I expand out to quads with a geometry shader.

I mean doing starfield using pixel shader only. I mean stuff you can see on Shadertoy.com. I look at their code and don’t understand anything.

You have a noise function (or several noise functions), time, and position on screen. From that you calculate everything every frame, every pixel. There’s no real “tricks”, just brute force processing and optimizing the math.

I think that’s an example of “functional”/state-less programming, like Haskell or something. I hate this.

Shaders aren’t quite the same as function programming, but they are stateless. Modern GPUs are massively parallel SIMD architectures (an Nvidia GTX 1080 has 2560 “shader processors”, and an AMD RX 480 has 2304 “unified shader cores”). Functional and stateless programming languages are often also trying to solve the same issue of massive parallelization but for far more general programming.

Shaders are about doing as much math on as much data as possible.