3

I tried to translate this shadertoy scene into Metal Kernel. In shadertoy code:

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec3 dir = rayDirection(45.0, iResolution.xy, fragCoord);
    ...
}

in OpenGL case, we need to send iResolution from the glfw window. And fragCoord will be gl_FragCoord from Fragment Shader.

I have this in metal file:

kernel void compute(texture2d<float, access::write> output [[texture(0)]],
                    uint2 gid [[thread_position_in_grid]]) {
    int width = output.get_width();
    int height = output.get_height();
    ....
}

So I can get my iResolution from the width and height. But I am not sure how to get gl_FragCoord.

Do Metal_stdlib have something equivalent to gl_FragCoord? Or if I have to calculate, How can I get obtain the same value?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
sooon
  • 4,718
  • 8
  • 63
  • 116
  • Provided you're dispatching a single grid that's exactly the same size as the output texture, one equivalent to `gl_FragCoord` is `float2(gid) / float2(width, height)`. – warrenm Apr 18 '17 at 18:21
  • 3
    Also, this seems like it's maybe a better match for an actual fragment function in a render pass, rather than a compute function. In that case, the fragment coordinate would be an input variable or `stage_in` struct field marked with `[[position]]`. – Ken Thomases Apr 19 '17 at 02:33
  • @warrenm Any example code how to do that? Let say my screen resolution is float(800/600), How do I divide the 'thread groups' or 'thread groups count'? – sooon Apr 19 '17 at 02:46
  • I may have misunderstood. If you're looking for the "fragment" position in window coordinates (as `gl_FragCoord` is), that's just `float2(gid)`, which ranges from (0, 0) to (width, height) (again, provided your grid dimensions (the product of your threadgroup size and threadgroup count) exactly match the destination texture. – warrenm Apr 19 '17 at 16:59
  • @warrenm Can you give example by what do you mean by grid dimension exactly match the destination texture? I vaguely get the idea. With example I think I can see it clearer. – sooon Apr 20 '17 at 00:39
  • Ok it works. I just replace it with `float2(gid)` and I get what I want. @warrenm can you make it into answer so that I can accept it? – sooon Apr 20 '17 at 00:41

1 Answers1

2

If you're looking for the "fragment" position in window coordinates (as gl_FragCoord is), you can use float2(gid), which ranges from (0, 0) to (width, height). This is only the case if your grid dimensions (the product of your threadgroup size and threadgroup count) exactly match the dimensions of the destination texture.

warrenm
  • 31,094
  • 6
  • 92
  • 116