Wireframe Shader (Godot 4.0)

Note: This only works in Godot 4.0 as you need the VERTEX_IDs in the shader to assign barycentric values.

 

Note: This only works consistently with flat-shaded models as the VERTED_IDs are not reliable for this when smoothshaded.

 

This was used as reference. https://catlikecoding.com/unity/tutorials/advanced-rendering/flat-and-wireframe-shading/

Shader code
shader_type spatial;

uniform vec4 albedo : source_color = vec4(1.0);
uniform vec4 wire_color : source_color = vec4(0.0, 0.0, 0.0, 1.0);
uniform float wire_width : hint_range(0.0, 40.0) = 5.0;
uniform float wire_smoothness : hint_range(0.0, 0.1) = 0.01;

varying vec3 barys;

void vertex() {
	int index = VERTEX_ID % 3;
	switch (index) {
		case 0:
			barys = vec3(1.0, 0.0, 0.0);
			break;
		case 1:
			barys = vec3(0.0, 1.0, 0.0);
			break;
		case 2:
			barys = vec3(0.0, 0.0, 1.0);
			break;
	}
}

void fragment() {
	vec3 deltas = fwidth(barys);
	vec3 barys_s = smoothstep(deltas * wire_width - wire_smoothness, deltas * wire_width + wire_smoothness, barys);
	float wires = min(barys_s.x, min(barys_s.y, barys_s.z));
	ALBEDO = mix(wire_color.rgb, albedo.rgb, wires);
}
Live Preview
Tags
wireframe
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from Arnklit

Related shaders

Comments 5

  1. This seems to work well for CSG shapes, but shapes imported from Blender seem to have entire faces shaded as the wire color. Any idea what could be causing this?

    1
  2. Awesome shader, but unfortunatly i have the same issue. Some faces arent shaded, as well as some lines being falsly drawn.

    0
  3. For people having issues with this shader, it's probably because your models use indexing for vertices (as they should), allowing you to reuse the same vertices for different triangles, rather than drawing duplicates in the same spots. This function seems to make the shader work as intended, but it does have the downside of probably not being all that fast + multiplying vertex count (working on godot 4.7.2) - I'm not sure what de-index fn looks like under the hood:

    # Gets rid of the index array so that triangles no longer reuse vertices
    # The barycentric shader relies on each triangle having its own unique set
    # of vertices... this does mean you end up with a bunch more vertices
    func deindex(mesh_instance: MeshInstance3D):
    var mesh = mesh_instance.mesh
    var new_mesh = ArrayMesh.new()
    for surface in mesh.get_surface_count():
    var surface_tool = SurfaceTool.new()
    surface_tool.create_from(mesh, surface)
    surface_tool.deindex()
    surface_tool.commit(new_mesh)
    new_mesh.surface_set_material(surface, mesh.surface_get_material((surface)))
    mesh_instance.mesh = new_mesh
    0