# How to optimise mesh data

So i have some procedurally generated mesh data and i want to reduce it down to its minimum number of verts. In case it matters this is a unity project.

Working on the basis of a simple example, lets assume a typical flat surface of points 2 by 3.

The point / vertex at [1,1] is used in many triangles.

I've generated mesh for a voxel type engine that adds verts to a list based on face visiblility and now I want to remove all the duplicates.

Can anyone come up with an efficient way of doing this because what i have is sooo bad its not even funny (and i don't even think it's logically correct) ...

``````private void Optimize()
{
Vector3 v;
Vector3 v2;
for (int i = 0; i < Vertices.Count; i++)
{
v = Vertices[i];
for (int j = i+1; j < Vertices.Count; j++)
{
v2 = Vertices[j];
if (v.x == v2.x && v.y == v2.y && v.z == v2.z)
{
for (int ind = 0; ind < Indices.Count; ind++)
{
if (Indices[ind] == j)
{
Indices[ind] = i;
}
else if (Indices[ind] > j && Indices[ind] > 0)
Indices[ind]--;
}

Vertices.RemoveAt(j);
Uvs.RemoveAt(j);
Normals.RemoveAt(j);
}
}
}
}
``````

EDIT: Ok i managed to get this (code sample above updated) to render an "optimised" set of verts but the UV data is all wrong now, which would make sense because i'm basically just removing any UV Vector that represents a UV coord for a removed vert and not actually considering what I need to do to "fix the tri" so to speak.

The code now seemingly does work but its quite time consuming, still looking to further optimise.

-
Since it's C# could you use a Dictionary's dislike of duplicates to remove duplicate vertices? – Dialock Apr 3 '13 at 16:13
i hadn't considered that ... mainly because at the moment im simply "removing from the target data" and using a dictionary like this would basically involve me allocating another chunk of ram. My logic was something like "for each vert, grab each vert after it and if its a dupe (by location), remove the dupe, remove any other data that points to the dupe (except indices), re-point those to the original". But for some reason this isn't working quite right. – War Apr 3 '13 at 17:35
when i say "isn't working quite right" i mean "results in 0 verts actually being rendered for some reason" – War Apr 3 '13 at 17:38
Maybe create a vertex object that contains a position, normal, and texture coordinate. Then remove duplicates of those. – Dialock Apr 3 '13 at 18:41
having thought about it ... you might be on to something there ... I was thinking about raw vertex info in terms of points but a vertex is more than just a point ... that may mean that my mesh is about as optimized as i can get it as the uv coordinates for each point will be different for each adjoined tri. – War Apr 3 '13 at 22:17

Unity's `Mesh` class has an `Optimize` method which should give you what you want.