LYGIA Shader Library

rectSDF (lygia/sdf/rectSDF)

Returns a rectangular SDF

Use:

rectSDF(<vec2> st [, <vec2|float> size])
rectSDF(<vec2> st [, <vec2|float> size, float radius])

Check it on Github


#ifndef FNC_RECTSDF
#define FNC_RECTSDF

float rectSDF(vec2 p, vec2 b, float r) {
    vec2 d = abs(p - 0.5) * 4.2 - b + vec2(r);
    return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)) - r;   
}

float rectSDF(vec2 p, float b, float r) {
    return rectSDF(p, vec2(b), r);
}

float rectSDF(in vec2 st, in vec2 s) {
    #ifdef CENTER_2D
        st -= CENTER_2D;
        st *= 2.0;
    #else
        st = st * 2.0 - 1.0;
    #endif
    return max( abs(st.x / s.x),
                abs(st.y / s.y) );
}

float rectSDF(in vec2 st, in float s) {
    return rectSDF(st, vec2(s) );
}

float rectSDF(in vec2 st) {
    return rectSDF(st, vec2(1.0));
}

#endif

Use:

rectSDF(<float2> st, <float2> size)

Check it on Github


#ifndef FNC_RECTSDF
#define FNC_RECTSDF
float rectSDF(float2 p, float2 b, float r) {
    float2 d = abs(p - 0.5) * 4.2 - b + float2(r, r);
    return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)) - r;   
}

float rectSDF(float2 p, float b, float r) {
    return rectSDF(p, float2(b, b), r);
}

float rectSDF(in float2 st, in float2 s) {
    #ifdef CENTER_2D
        st -= CENTER_2D;
        st *= 2.0;
    #else
        st = st * 2.0 - 1.0;
    #endif
    return max( abs(st.x / s.x),
                abs(st.y / s.y) );
}

float rectSDF(in float2 st, in float s) {
    return rectSDF(st, float2(s, s) );
}

float rectSDF(in float2 st) {
    return rectSDF(st, float2(1.0, 1.0));
}
#endif

Check it on Github

fn rectSDF_round(p: vec2f , b: vec2f, r: f32) -> f32 {
    let d = abs(p - 0.5) * 4.2 - b + r;
    return min(max(d.x, d.y), 0.0) + length(vec2f( max(d.x, 0.0), max(d.y, 0.0) )) - r;   
}

fn rectSDF(st: vec2f, s: vec2f) -> f32 {
    let uv = st * 2.0 - 1.0;
    return max( abs(uv.x / s.x),
                abs(uv.y / s.y) );
}

Examples

License

LYGIA is dual-licensed under the Prosperity License and the Patron License for sponsors and contributors.

Sponsors and contributors are automatically added to the Patron License and they can ignore the any non-commercial rule of the Prosperity Licensed software (please take a look to the exception).

It's also possible to get a permanent comercial license hook to a single and specific version of LYGIA.

Get the latest news and releases

Sign up for the news letter bellow, joing the LYGIA's channel on Discord or follow the Github repository