Use another color interpolation for vertices in shader

Hello fellow BabylonJS users,

I’d like to change the way my shader does color interpolation between vertices.

See this playground
image

On Quad 3, a custom shader rounds Vertex color values (0 or 1), creating a sharp transition between green and red in the triangle, which is the result I want to achieve.

Now, I need my custom shader to work with any color (Quad 3 version would only work with black, red, green, blue, cyan, yellow, magenta or white) :

Is there any way to make the fragment shader use “nearest color” instead of the interpolation ?

Thanks a lot for your help !

Hey @SvenFrankson ,

I think you code already works for other colors:

Custom shader with nearest color | Babylon.js Playground (babylonjs.com)

On trick that you can do is to multiply the values of r g b by a constant before the round and than divide by that same value after the round operation. That will allow you to have more colors allowed in you interpolation.

See example: Custom shader with nearest color | Babylon.js Playground (babylonjs.com)

Thanks srzerbetto !

Yes it does work with other colors (the 8 combinations of 0 and 1), but I would like to use more of them (around 100)

The issue with a multiply step is that some stripes will appear when fragment shader interpolates to an intermediary value.

I think you would have to add two additional color vertex buffers to the mesh so that each vertex knows the 3 colors used by the face. Then, in the fragment shader, you can compute the distance of the current interpolated color with each of the 3 colors and choose the right one. For this to work, you will have to “flatten” the mesh, that is each face should have 3 unique vertices (unlike the PG, where there are only 4 vertices and 2 of them are shared between the 2 triangles).

I did something like that in a first version (using UV canals : I don’t know how to add a color buffer), but it feeled strange to do distance computation in the fragment shader (because fragment shader does an interpolation based on distance computation, I’d like to re-use this)

Thank you both for the inputs ! (even if I was hoping for a simple VERTEX_COLOR_INTERPOLATION_MODE flag I had missed ^^)

Actually, you have a flat modifier that you can add to the declaration of vColor (flat varying vec4 vColor;), but this will tell the GPU not to interpolate vColor across the whole triangle, it won’t produce the result you expect.