Skip to content

Instantly share code, notes, and snippets.

@hiepnd
Last active January 22, 2016 08:50
Show Gist options
  • Save hiepnd/88fde33894d85ac9358d to your computer and use it in GitHub Desktop.
Save hiepnd/88fde33894d85ac9358d to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class MeshCombine : MonoBehaviour {
const float EPSILON = 0.01f;
public void FindPoint (List<int> includes, Vector3[] vs, Vector3[] ns, Color[] cs) {
List<int> ps = new List<int>();
var p = vs[includes[0]];
foreach (var i in includes) {
if (Vector3.SqrMagnitude(p - vs[i]) < EPSILON * EPSILON) {
ps.Add(i);
}
}
Vector3 n = Vector3.zero;
foreach (var i in ps) {
n += ns[i];
// Debug.Log(string.Format("{0}, p = ({1}, {2}, {3}), n = ({4}, {5}, {6})",
// i, vs[i].x, vs[i].y, vs[i].z, ns[i].x, ns[i].y, ns[i].z));
}
n.Normalize();
// Debug.Log(string.Format("Average normal: ({0}, {1}, {2})", n.x, n.y, n.z));
var c = new Color(n.x, n.y, n.z);
foreach (var i in ps) {
cs[i] = c;
includes.Remove(i);
}
}
public void ModNormals () {
List<int> includes = new List<int>();
Mesh m = GetComponent<MeshFilter>().sharedMesh;
var vs = m.vertices;
var ns = m.normals;
var cs = m.colors;
if (cs == null || cs.Length == 0) {
cs = new Color[vs.Length];
}
for (int i = 0; i < vs.Length; i++) {
includes.Add(i);
}
while (includes.Count > 0) {
FindPoint(includes, vs, ns, cs);
}
m.colors = cs;
}
public void LogMesh () {
var m = GetComponent<MeshFilter>().sharedMesh;
Debug.Log(string.Format("Vertices {0}, Triangles {1}, Colors {2}", m.vertices.Length, m.triangles.Length/3,
m.colors != null ? m.colors.Length : 0));
}
public void Combile() {
MeshFilter[] meshFilters = new MeshFilter[transform.childCount];
int i = 0;
foreach (Transform t in transform) {
meshFilters[i++] = t.GetComponent<MeshFilter>();
}
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
i = 0;
Debug.Log("xxx = " + combine.Length);
while (i < meshFilters.Length) {
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = transform.worldToLocalMatrix * meshFilters[i].transform.localToWorldMatrix;
meshFilters[i].gameObject.active = false;
i++;
}
var mesh = new Mesh();
mesh.CombineMeshes(combine);
mesh.name = transform.gameObject.name;
transform.GetComponent<MeshFilter>().sharedMesh = mesh;
transform.gameObject.active = true;
ModNormals();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment