#Prevent stretching in corners in SDF rectangle

4 messages · Page 1 of 1 (latest)

thorn swift
#

Very beginner here... I have the following fragment shader which simply draws a red rounded rectangle filling all of the available space. However when the aspect ratio is different than 1:1, the corners as expected also stretch. How can I fill the canvas without stretching the corners?

varying vec2 tcoord;
varying vec4 color;

float sdRoundedBox(vec2 p, vec2 b, vec4 r ) {
    r.xy = (p.x>0.0)?r.xy : r.zw;
    r.x  = (p.y>0.0)?r.x  : r.y;
    vec2 q = abs(p)-b+r.x;
    return min(max(q.x,q.y),0.0) + length(max(q,0.0)) - r.x;
}

void main() {
    vec2 boxPos = vec2(.5);
    vec2 boxBnd = vec2(.5);
    float alpha = sdRoundedBox(tcoord - boxPos, boxBnd, vec4(0.1));

    if (alpha <= 0.0) {
        fragColor = vec4(1., 0., 0., 1.0);
    } else {
        fragColor = vec4(.0);
    }    
}
snow anchor
#

one way to fix this is to, rather than working with tcoord which is always a 0.0 to 1.0 square even if the canvas is not square, instead work with the pixel coordinates directly

#

e.g. sdRoundedBox(fragCoord - resolution*0.5, resolution*0.5, vec4(100.0))

#

or instead of vec4(100.0) you could make it vec4(resolution.y * 0.1) or something