global vertex snapping with 3dresolution scaling

This shader converts all the vertex coordinates to global space using the object’s transform, then snaps every vertex to the nearest global position based on the “res” value which is a 3d scale of the implied resolution in global space. This was made in Godot 4.0.3.

Shader code
// created by zodiepupper and xlinka (https://github.com/xlinka)
shader_type spatial;
uniform float res;
uniform vec4 albedo;

void vertex() {
    vec3 scale = vec3(length(MODEL_MATRIX[0]), length(MODEL_MATRIX[1]), length(MODEL_MATRIX[2]));
    mat4 rot_matrix = mat4(normalize(MODEL_MATRIX[0]), normalize(MODEL_MATRIX[1]), normalize(MODEL_MATRIX[2]), vec4(0.0, 0.0, 0.0, 1.0));
    mat4 scale_matrix = mat4(vec4(scale.x, 0.0, 0.0, 0.0),
                             vec4(0.0, scale.y, 0.0, 0.0),
                             vec4(0.0, 0.0, scale.z, 0.0),
                             vec4(0.0, 0.0, 0.0, 1.0));
    vec4 world_pos = MODEL_MATRIX * vec4(VERTEX, 1.0);
    world_pos.xyz = round(world_pos.xyz * res) / res;
    vec4 local_pos = inverse(MODEL_MATRIX) * world_pos;

    VERTEX = (rot_matrix * scale_matrix * local_pos).xyz;
}

void fragment() {
    ALBEDO = albedo.rgb;
}
Tags
snap, vertex
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

Camera Distance UV Scaling

Global Scale

Updated: Faux Vertex Lighting

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
xLinka
xLinka
1 year ago

👍