Search Unity

Get average of vertex colours instead of interpolation

Discussion in 'Shaders' started by MCrafterzz, Jun 21, 2019.

  1. MCrafterzz

    MCrafterzz

    Joined:
    Jun 3, 2017
    Posts:
    354
    I have set up a vertex colouring system but ofcourse that creates a big blur as it interpolates between the three vertices colours. Yes the vertices are split so triangles don't share any vertices. So I wonder if it's possible to get an average, this way all vertices can have their own colour as well as the triangle being a flat colour. It feels like storing a colour per triangle would be much harder as the mesh is dynamicly created with the marching cubes algoritmen. Currently every point in the grid has a colour and the vertices of the mesh should get their colours from that. Atm every vertex takes it from the nearest point. Thanks.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,342
    Using only a vertex fragment shader, no, there's no way to get an average. Your options are the interpolated value, or to use something like a nointerpolation modifier on the value to get only the value on the first vertex of the triangle. If you move to adding a geometry shader stage, you can get all 3 vertices of a triangle and average the color value, then re-assign them.

    But it seems odd to me that if your vertices are already split you don't have someplace in your code where you're dealing with a single triangle and it's 3 vertices where you could average the color, or perhaps get the color from the average of the 3 vertex positions (ie: the triangle center)?
     
  3. MCrafterzz

    MCrafterzz

    Joined:
    Jun 3, 2017
    Posts:
    354
    Getting the average beforehand is defently a good way to go and then take in those values for all vertices or is it better to take it in once per triangle?
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,342
    Presumably it'd cost less to only do one sample per triangle rather than 3 and interpolate?
     
  5. MCrafterzz

    MCrafterzz

    Joined:
    Jun 3, 2017
    Posts:
    354
    Wonder how to give it to the shader tho. Mesh.setcolors results in vertex colours so how would I have one per triangle?
     
  6. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,342
    By setting it on all of the vertices of that triangle. Maybe additionally using nointerpolation as a minor optimization so the GPU doesn't try to interpolate between the same color.

    Alternatively if you want to get fancy you could use the primitive id (SV_PrimitiveID) and an array or structured buffer with the color data.