• Godot Help2D
  • Game window resize results in loss of texture precision

I have a shader that draws grid

shader_type canvas_item;

uniform float cell_size : hint_range(1.0, 100.0); // Cell size of the grid
uniform float border_thickness_px : hint_range(1.0, 10.0); // Border thickness in pixels
uniform vec4 border_color : source_color; // Color of the grid border
uniform vec2 node_size; // Size of the node on which the grid is drawn

void fragment() {
    // Scale UV to get the number of cells based on the node size and cell size
    vec2 corrected_uv = UV * node_size / cell_size;

    // Calculate the fractional part to create repeating grid pattern
    vec2 uv_grid = fract(corrected_uv);

    // Convert border thickness from pixels to UV coordinates fraction
    float border_thickness_uv = border_thickness_px / cell_size;

    // Calculate borders by checking the distance to the nearest edge
    float grid_line_x = step(border_thickness_uv, uv_grid.x) + step(1.0 - border_thickness_uv, uv_grid.x);
    float grid_line_y = step(border_thickness_uv, uv_grid.y) + step(1.0 - border_thickness_uv, uv_grid.y);

    // To handle the double border effect, reduce the intensity where both conditions meet
    float grid_line = min(grid_line_x, grid_line_y);

    // Set fragment color based on grid line presence (transparent background)
    COLOR = mix(border_color, vec4(0.0, 0.0, 0.0, 0.0), grid_line);
}

Since the game supports multiple resolutions I would like to support scaling of the viewport. However, currently the texture gradually looses quality if scaled (especially downscaled). I think the issue is the sampling method which is Nearest by default. I have confirmed the same behavior in a photo editing software. The solution I have came up with was to use the Bilinear method. However, I could not find anything similar in godot! It looks like the sampling options are very limited. Is there a way to make my shader/textures look nicer when scaled?

video

before scaling

after

godot available options

  • xyz replied to this.

    dearme Use linear. It is in fact bilinear filtering as textures are 2 dimensional. Also enabling mipmaps may help.

      xyz that's the thing.. the Linear does not do anything good. See that on the second screenshot I already have it set as Linear globally. Tried other options to no avail.

      • xyz replied to this.

        dearme Umm, your shader does not use any textures, it draws a procedural grid, so texture filtering is irrelevant here. You have several options:

        • increase grid line thickness
        • use smoothstep instead of step
        • let the shader calculate line thickness in pixel space instead of object space to produce lines of same pixel width regardless of resolution
        • enable one of full scene anti aliasing options in project settings.