Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metal Fragment shader concept: interpolated colours vs texture

Tags:

metal

I need help understanding a fundamental concept in Apple's Metal pipeline.

Let's assume I have a single triangle I am going to render, made of three points R, G and B. Let's also assume that each point has a colour associated with it - corresponding to its name. We set up the vertex shader to simply pass the vertex position and colour without modification.

The pipeline now rasterises the triangle - let say that it covers 10 pixels on screen. Now here's where my confusion lies - the fragment shader...

If my fragment shader just returns the vertex's colour then Metal will interpolate between the colours of each corner. My naive assumption was that Metal would call the fragment shader once for each vertex, and then use the resulting colours to interpolate the values for each pixel.

However, if I sample a texture in my fragment shader then it would need to be passed the position of each pixel in uv space, not the original vertices' data, so I can look up / sample the correct colour from in the texture in the shader.

I suppose a daft way to ask the same question is: How often is the fragment shader called 3, 10, 30 or some other number of times? Or even more daft - what is a fragment: an individual pixel, or a structure that comprises the 3 vertices and pixels that need to be coloured?

like image 420
Philip Pegden Avatar asked Dec 30 '25 09:12

Philip Pegden


1 Answers

From that article it is the comment on the RasterizerData code snippet that answers my question:

Since this member does not have a special attribute, the rasterizer interpolates its value with the values of the other triangle vertices and then passes the interpolated value to the fragment shader for each fragment in the triangle.

Now the pipeline makes sense to me. The rasteriser has no idea of which field is a colour on the records passed from the vertex shader - it just interpolates them all, and forwards this to the fragment shader, along with the pixel position. The fragment shader can use any of these interpolated values in its calculations, or do something different - such as return a colour looked up in a texture.

Thus, going back to my original question / example - the fragment shader would be called 10 times - once for each pixel in the rasterised triangle. Each input would be the location of a pixel, plus all the other non-position values, interpolated from the value of the three original vertices.

like image 193
Philip Pegden Avatar answered Jan 04 '26 23:01

Philip Pegden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!