Skip to content

Instantly share code, notes, and snippets.

@hiepnd
Last active January 13, 2016 03:52
Show Gist options
  • Save hiepnd/4c57e15341570b84ce0b to your computer and use it in GitHub Desktop.
Save hiepnd/4c57e15341570b84ce0b to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshModifier : 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);
}
// Debug.Log("Vertices left = " + includes.Count);
}
public void ModNormals () {
List<int> includes = new List<int>();
Mesh m = GetComponent<MeshFilter>().mesh;
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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment