Performance of sharing vs not sharing vertex in arraymesh

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jujumumu

For a large mesh is it more performant to render a mesh that shares vertices with indices or does it not matter?

Not Sharing verticies:

var arr = []
arr.resize(Mesh.ARRAY_MAX)
var verts = PoolVector3Array([Vector3(0,0,0),Vector3(1,0,0),Vector3(0,0,1),Vector3(1,0,1),Vector3(0,0,1),Vector3(1,0,0)])
var normals = PoolVector3Array([Vector3(0,1,0),Vector3(0,1,0),Vector3(0,1,0),Vector3(0,1,0),Vector3(0,1,0),Vector3(0,1,0)])

arr[Mesh.ARRAY_VERTEX] = verts
arr[Mesh.ARRAY_NORMAL] = normals
#arr[Mesh.ARRAY_INDEX] = indices

var mesh = ArrayMesh.new()
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arr)

Sharing verticies:

var arr = []
arr.resize(Mesh.ARRAY_MAX)
var verts = PoolVector3Array([Vector3(0,0,0),Vector3(1,0,0),Vector3(0,0,1),Vector3(1,0,1)])
var normals = PoolVector3Array([Vector3(0,1,0),Vector3(0,1,0),Vector3(0,1,0),Vector3(0,1,0)])
var indices = PoolIntArray([0,1,2,3,2,1])

arr[Mesh.ARRAY_VERTEX] = verts
arr[Mesh.ARRAY_NORMAL] = normals
arr[Mesh.ARRAY_INDEX] = indices

var mesh = ArrayMesh.new()
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arr)

I ask this since I want to have flat shading which cannot share any verticies. Is there a performance difference in Godot for much larger meshes? The only thing I can think of is if there were any vertex shaders.

:bust_in_silhouette: Reply From: Zylann

Sharing vertices means less data to upload to the graphics card, so there is some performance gain. To know how much, you’d have to measure it.

If you need flat shading you could still use shared vertices, if you add this in your fragment shader:

NORMAL = normalize(cross(dFdx(VERTEX), dFdy(VERTEX)));

Although I would opt for the non-shared vertices for the convenience and it’s more standard. If performance is a concern you need to measure it, because apart from the time it takes to upload the data, it’s harder to guess how fast it will render.

I did some testing just in gdscript and shared vertex meshes definitely render faster. The vertex count displayed in the monitors are also somehow the same for both. However for some reason godot has the vertex counts doubled. In just a scene with a cube mesh instance, there are 72 vertices. Not really sure why this happens any ideas?

jujumumu | 2022-02-24 00:54

Godot also includes the grid and gizmos in editor stats.

Also if you have shadows enabled, that will render the cube a few more times so numbers will be multiplied.

Zylann | 2022-02-24 19:15