6 using System.Collections.Generic;
17 [Tooltip(
"The amount, if any, to expand each bounding volume by.")]
18 public float BoundsExpansion = 0.0f;
25 public delegate
void EventHandler(
object source, EventArgs args);
35 private bool removingVerts =
false;
41 private Queue<Bounds> boundingObjectsQueue;
43 #if UNITY_EDITOR || UNITY_STANDALONE 44 private static readonly
float FrameTime = .016f;
49 private static readonly
float FrameTime = .008f;
58 boundingObjectsQueue =
new Queue<Bounds>();
59 removingVerts =
false;
68 if (boundingObjects == null)
76 AddBoundingObjectsToQueue(boundingObjects);
79 StartCoroutine(RemoveSurfaceVerticesWithinBoundsRoutine());
84 AddBoundingObjectsToQueue(boundingObjects);
92 private void AddBoundingObjectsToQueue(IEnumerable<GameObject> boundingObjects)
94 foreach (GameObject item
in boundingObjects)
96 Collider boundingCollider = item.GetComponent<Collider>();
97 if (boundingCollider != null)
99 Bounds bounds = boundingCollider.bounds;
102 if (BoundsExpansion > 0.0f)
104 bounds.Expand(BoundsExpansion);
107 boundingObjectsQueue.Enqueue(bounds);
116 private IEnumerator RemoveSurfaceVerticesWithinBoundsRoutine()
119 float start = Time.realtimeSinceStartup;
121 while (boundingObjectsQueue.Count > 0)
124 Bounds bounds = boundingObjectsQueue.Dequeue();
126 foreach (MeshFilter filter
in meshFilters)
135 Mesh mesh = filter.sharedMesh;
136 MeshRenderer meshRenderer = filter.GetComponent<MeshRenderer>();
144 if (mesh == null || meshRenderer == null || !meshRenderer.bounds.Intersects(bounds))
151 Vector3[] verts = mesh.vertices;
152 HashSet<int> vertsToRemove =
new HashSet<int>();
155 for (
int i = 0; i < verts.Length; ++i)
157 if (bounds.Contains(filter.transform.TransformPoint(verts[i])))
160 vertsToRemove.Add(i);
164 if ((Time.realtimeSinceStartup - start) > FrameTime)
168 start = Time.realtimeSinceStartup;
172 if (vertsToRemove.Count == 0)
179 int[] indices = mesh.GetTriangles(0);
180 List<int> updatedIndices =
new List<int>();
182 for (
int index = 0; index < indices.Length; index += 3)
186 if (vertsToRemove.Contains(indices[index]) ||
187 vertsToRemove.Contains(indices[index + 1]) ||
188 vertsToRemove.Contains(indices[index + 2]))
195 updatedIndices.Add(indices[index]);
196 updatedIndices.Add(indices[index + 1]);
197 updatedIndices.Add(indices[index + 2]);
201 if ((Time.realtimeSinceStartup - start) > FrameTime)
205 start = Time.realtimeSinceStartup;
209 if (indices.Length == updatedIndices.Count)
216 mesh.SetTriangles(updatedIndices.ToArray(), 0);
217 mesh.RecalculateBounds();
219 start = Time.realtimeSinceStartup;
222 MeshCollider meshCollider = filter.gameObject.GetComponent<MeshCollider>();
223 if (meshCollider != null)
225 meshCollider.sharedMesh = null;
226 meshCollider.sharedMesh = mesh;
231 Debug.Log(
"Finished removing vertices.");
234 EventHandler handler = RemoveVerticesComplete;
237 handler(
this, EventArgs.Empty);
240 removingVerts =
false;