Roest
Roest

Reputation: 818

GLSL custom/no interpolation of triangles with vertex colors

The effect I want to achieve is vertex color with sharp contours. So inside the triangle the fragment shader should use the color of whatever vertex is closest to that fragment.

Now when thinking about it, the only solution I can come up with is assigning tex coords 1,0,0 0,1,0 and 0,0,1 to the three vertices and have 2 (reoordered) duplicates of the vertex color array and then choose from the color aray of which the corresponding tex coord is highest. This method would at least add 9 more floats to each vertex. Which will slow down the application as my meshes are changing quit often and increase the memory footprint significantly.

Is there a better/easier way to achieve this?

Upvotes: 1

Views: 7592

Answers (1)

jozxyqk
jozxyqk

Reputation: 17416

[replaced incorrect original]

This should actually work...

//vert
out vec3 colour;
...

//geom
//simple passthrough but dupe colours to separate and include barycentric coord
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
in vec3 colour[];
flat out vec3 colours[3];
out vec3 coord;
...
for (int i = 0; i < 3; ++i)
    colours[i] = colour[i];
for (int i = 0; i < 3; ++i)
{
    coord = vec3(0.0);
    coord[i] = 1.0;
    gl_Position = gl_in[i].gl_Position;
    EmitVertex();
}

//frag
flat in vec3 colours[3]; //triangle's 3 vertex colours
in vec3 coord; //barycentric weights as a result of interp
...
//get index of biggest coord
int i = (coord.x > cood.y && coord.x > coord.z) ? 0 :
    ((coord.y > coord.z) ? 1 : 2);
//choose that colour
vec3 fragColour = colours[i];

Upvotes: 1

Related Questions