I tried various ways of getting the interpolation work and generate a perspective correct image, but none of the suggested ways works.

My current code is:

struct VertexStruct
  float4 normalizedPosition [[ position ]];
  float4 texCoord;

vertex VertexStruct testVertex(device float4 *vertices [[ buffer(0) ]],
                                     uint vid [[ vertex_id ]])
  VertexStruct outVertices;

  outVertices.normalizedPosition = ...;

  outVertices.texCoord = float4(vertices[vid].x, vertices[vid].y, 0.0, 127.0);

  return outVertices;

fragment half4 testFragment(VertexStruct inFrag [[ stage_in ]],
                            texture2d<half, access::sample> volume [[ texture(0) ]])
  float2 texCoord = float2(inFrag.texCoord.xy * (1.0 / inFrag.texCoord.w));
  constexpr sampler s(coord::normalized, filter::linear, address::clamp_to_zero);
  return volume.sample(s, texCoord);

Texture is 128x128 and vertices are:

  • 0,0
  • 0,127
  • 127,0
  • 127,127

In theory, the 4th parameter, w, should help with perspective correct interpolation. This trick has been reported to work in OpenGL ES, but in my case if I have it or not, nothing changes.

What I get is:

enter image description here

Blue is the clear color, while anything inside the black trapezoid is the content of the texture. The red trapezoid should be centered in the black trapezoid. If you open it with Photoshop and trace the diagonal of the black trapezoid, it will pass exactly true the diagonal of the red trapezoid.

enter image description here

It means that the two triangles that are rendered don't read the texture with perspective correct sampling. It is the classic problem of texture mapping, but I can't get my head around it.

Can anyone see the error?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.