1
votes

Say I have a simple OpenGL triangle like this:

//1
glColor3f(1, 0, 0);
glVertex3f(0.5, 0, 0);
//2
glColor3f(0, 1, 0);
glVertex3f(0, 1, 0);
//3
glColor3f(0, 0, 1);
glVertex3f(1, 1, 0);

enter image description here

In a glsl fragment shader I can use the interpolated fragment color to determine my distance from each vertex. In this example the red component of the color determines distance from the first vertex, green determines the distance from the second, and blue from the third.

Is there a way I can determine these distances in the shader without passing vertex data such as texture coordinates or colors?

1
No. If you want to compute a distance then you have to know 2 points. There is not built in fragment shader input, which contains the coordinates relative to a primitive. - Rabbid76

1 Answers

1
votes

Not in standard OpenGL. There are two vendor-specific extensions:

  1. AMD_shader_explicit_vertex_parameter
  2. NV_fragment_shader_barycentric

which will give you access to the barycentric coordinates within the primitive. But without such extensions, there are only very clumsy ways to get this data to the FS, and each will have significant drawbacks. Here are some ideas:

  • You could use per-vertex attributes as you already suggested, but in real meshes, it will require a lot of additional vertex splitting to get the values right.

  • You could use geometry shaders to generate those attribute values on the fly, but that will come with a huge performance hit as geometry shaders really don't perform well.

  • You could make your vertex data available to the FS (for example via an SSBO) and basically calculate the barycentric coordinates based on gl_FragCoord and the relevant endpoints. But this requires you to get information on which vertices were used to the FS, which might require extra data structures (i.e. some triangle- and/or vertex-indices lookup table based on gl_PrimitiveID).