nTerra

Mesh Optimization

Below is my custom version of a greedy mesh optimizer for voxel data in Unity3d translated from JavaScript to c# using the original awesome mind bending code of Mikola Lysenko.

meshopt

This is useful if you need to use mesh for collision data and it can drastically improve speed when building/rebuilding game objects. I’ve added a method of excluding some data from generating mesh which is great for blocks which the player should fall through.

Don’t forget to include the original copyright if you use it in your project or share it. Feel free to also credit this site if you wish.

It’s worth noting that there is a kind of “bug” in Mikola’s code which is possibly only apparent when used with Unity3d/c# which returns incorrect normals on 3/6 sides of the cube. This is corrected in the c# below.

If you have a more efficient mesh optimizer you’d like to share. please do! dev@nuzly.com

c#

JavaScript

5 comments

  1. Do you have a github page or something, where I can view the code together with your Chunk class and Mesh class? Thanks.

    1. Not currently. The Mesh class is a part of UnityEngine. I will post a copy of a Chunk class for reference but it’s really just a place to store all the related data; vertices, triangles, uvs, colour & sub-material data for the final mesh.

  2. Are you try to paste this code to Unity? Where Type of List in function AddFace? Where declaration of du and dv in C# example?

    1. The WordPress code format plugin broke the formatting. You can scroll to the right and see it. Or below;

      for (h = 1; j + h < size; ++h) { for (k = 0; k < w; ++k) { if (c != mask[n + k + h * size]) { done = true; break; } } if (done) break; } bool flip = false; x[u] = i; x[v] = j; int[] du = new int[3]; int[] dv = new int[3]; if (c > -1)
      {
      du[u] = w;
      dv[v] = h;
      }
      else
      {
      flip = true;
      c = -c;
      du[u] = w;
      dv[v] = h;
      }

      AddFace is using vector3 list for vertices and integer list (elements) for triangles. Each chunk stores these lists prior to rendering.

Leave a Reply

Your email address will not be published. Required fields are marked *