Search Unity

"Lines of fixed width" shader glitch

Discussion in 'General Graphics' started by dotsquid, Nov 11, 2021.

  1. dotsquid

    dotsquid

    Joined:
    Aug 11, 2016
    Posts:
    224
    Greetings!

    I need to draw the lines on the UI Canvas that have the same width in pixels on any resolution. Specifically, I need lines of 1-pixel width.
    I wrote a shader which uses derivatives and is pretty straightforward. Here is an abstract of the fragment shader:

    Code (CSharp):
    1. float gradient = IN.texcoord.y - _Midline;
    2. float distance = abs(gradient / fwidth(IN.texcoord.y));
    3. float weight = 1.0 - step(_Thickness * 0.5, distance);
    4. half4 color = half4((1.0).xxx, weight);
    It mainly does its jobs. But it also produces an unallowable artifact: the lines that match the vertical or horizontal center of the screen can either partially disappear or become 1 pixel wider than intended. My first thought was that it happens when the underlying mesh becomes too narrow (less than the screen pixel), but it turned out to be not the case.

    pc_better_lines_glitch.gif

    Each line is represented as a quad. The line is drawn by the V-component of the UV depending on the '_Midline' parameter (which is 0.5 in the example above)

    Any clues?
     
    Last edited: Dec 29, 2021
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,445
  3. dotsquid

    dotsquid

    Joined:
    Aug 11, 2016
    Posts:
    224
  4. beatdesign

    beatdesign

    Joined:
    Apr 3, 2015
    Posts:
    137
    Can you share your updated shader, please?
     
  5. dotsquid

    dotsquid

    Joined:
    Aug 11, 2016
    Posts:
    224
    Code (CSharp):
    1. float gradient = IN.texcoord.y - _Midline;
    2. float distance = abs(gradient / fwidth(IN.texcoord.y) + 0.5);
    3. float thickness = _Thickness * IN.thickness;
    4. float weight = 1.0 - step(thickness * 0.5, distance);