ShatterTool.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // Shatter Toolkit
  2. // Copyright 2015 Gustav Olsson
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. namespace ShatterToolkit
  6. {
  7. [RequireComponent(typeof(MeshFilter))]
  8. public class ShatterTool : MonoBehaviour
  9. {
  10. [SerializeField]
  11. protected int generation = 1;
  12. [SerializeField]
  13. protected int generationLimit = 3;
  14. [SerializeField]
  15. protected int cuts = 2;
  16. [SerializeField]
  17. protected bool fillCut = true;
  18. [SerializeField]
  19. protected bool sendPreSplitMessage = false;
  20. [SerializeField]
  21. protected bool sendPostSplitMessage = false;
  22. [SerializeField]
  23. protected HullType internalHullType = HullType.FastHull;
  24. protected bool isIntact = true;
  25. protected IHull hull;
  26. protected Vector3 center;
  27. /// <summary>
  28. /// Gets or sets the current generation of this ShatterTool instance.
  29. /// By default, a game object is of generation 1. When a game object
  30. /// is shattered using ShatterTool.Shatter() all new game objects
  31. /// will be considered of generation 2, and so on.
  32. /// For example, this value can be used to vary the color of a
  33. /// game object depending on how many times it has been shattered.
  34. /// </summary>
  35. public int Generation
  36. {
  37. get { return generation; }
  38. set { generation = Mathf.Max(value, 1); }
  39. }
  40. /// <summary>
  41. /// Gets or sets the generation limit of this ShatterTool instance.
  42. /// This value restricts how many times a game object may be shattered
  43. /// using ShatterTool.Shatter(). A game object will only be able to shatter
  44. /// if ShatterTool.Generation is less than ShatterTool.GenerationLimit.
  45. /// </summary>
  46. public int GenerationLimit
  47. {
  48. get { return generationLimit; }
  49. set { generationLimit = Mathf.Max(value, 1); }
  50. }
  51. /// <summary>
  52. /// Gets or sets the number of times the game object will be cut when ShatterTool.Shatter() occurs.
  53. /// </summary>
  54. public int Cuts
  55. {
  56. get { return cuts; }
  57. set { cuts = Mathf.Max(value, 1); }
  58. }
  59. /// <summary>
  60. /// Gets or sets whether the cut region should be triangulated.
  61. /// If true, the connected UvMapper component will control the vertex properties of the filled area.
  62. /// When the ShatterTool is used on double-sided meshes with zero thickness, such as planes, this value
  63. /// should be false.
  64. /// </summary>
  65. public bool FillCut
  66. {
  67. get { return fillCut; }
  68. set { fillCut = value; }
  69. }
  70. /// <summary>
  71. /// Gets or sets whether a PreSplit(Plane[] planes) message should be sent to the original game object prior to a split occurs.
  72. /// The supplied object will be the array of Planes that will be used to split the game object.
  73. /// </summary>
  74. public bool SendPreSplitMessage
  75. {
  76. get { return sendPreSplitMessage; }
  77. set { sendPreSplitMessage = value; }
  78. }
  79. /// <summary>
  80. /// Gets or sets whether a PostSplit(GameObject[] newGameObjects) message should be sent to the original game object
  81. /// after a split has occured. The message will be sent before destroying the original game object.
  82. /// The supplied object will be an array of all new GameObjects created during the split.
  83. /// </summary>
  84. public bool SendPostSplitMessage
  85. {
  86. get { return sendPostSplitMessage; }
  87. set { sendPostSplitMessage = value; }
  88. }
  89. /// <summary>
  90. /// Gets or sets the type of the internal hull used to shatter the mesh. The FastHull implementation is roughly 20-50% faster
  91. /// than the LegacyHull implementation and requires no time to startup. The LegacyHull implementation is more robust in extreme
  92. /// cases and is provided for backwards compatibility. This setting can't be changed during runtime.
  93. /// </summary>
  94. public HullType InternalHullType
  95. {
  96. get { return internalHullType; }
  97. set { internalHullType = value; }
  98. }
  99. /// <summary>
  100. /// Determines whether this game object is of the first generation. (Generation == 1)
  101. /// </summary>
  102. public bool IsFirstGeneration
  103. {
  104. get { return generation == 1; }
  105. }
  106. /// <summary>
  107. /// Determines whether this game object is of the last generation. (Generation >= GenerationLimit)
  108. /// </summary>
  109. public bool IsLastGeneration
  110. {
  111. get { return generation >= generationLimit; }
  112. }
  113. /// <summary>
  114. /// Gets the worldspace center of the game object. Only works during runtime.
  115. /// </summary>
  116. public Vector3 Center
  117. {
  118. get { return transform.TransformPoint(center); }
  119. }
  120. protected void CalculateCenter()
  121. {
  122. // Get the localspace center of the mesh bounds
  123. center = GetComponent<MeshFilter>().sharedMesh.bounds.center;
  124. }
  125. public void Start()
  126. {
  127. Mesh sharedMesh = GetComponent<MeshFilter>().sharedMesh;
  128. // Initialize the first generation hull
  129. if (hull == null)
  130. {
  131. if (internalHullType == HullType.FastHull)
  132. {
  133. hull = new FastHull(sharedMesh);
  134. }
  135. else if (internalHullType == HullType.LegacyHull)
  136. {
  137. hull = new LegacyHull(sharedMesh);
  138. }
  139. }
  140. // Update properties
  141. CalculateCenter();
  142. }
  143. /// <summary>
  144. /// Shatters the game object at a point, instantiating the pieces as new
  145. /// game objects (clones of the original) and destroying the original game object when finished.
  146. /// If the game object has reached the generation limit, nothing will happen.
  147. /// Apart from taking the generation into account, this is equivalent to calling
  148. /// ShatterTool.Split() using randomly generated planes passing through the point.
  149. /// </summary>
  150. /// <param name="point">
  151. /// The world-space point.
  152. /// </param>
  153. public void Shatter(Vector3 point)
  154. {
  155. if (!IsLastGeneration)
  156. {
  157. // Increase generation
  158. generation++;
  159. // Split the hull using randomly generated planes passing through the point
  160. Plane[] planes = new Plane[cuts];
  161. for (int i = 0; i < planes.Length; i++)
  162. {
  163. planes[i] = new Plane(Random.onUnitSphere, point);
  164. }
  165. Split(planes);
  166. }
  167. }
  168. /// <summary>
  169. /// Splits the game object using an array of planes, instantiating the pieces as new
  170. /// game objects (clones of the original) and destroying the original game object when finished.
  171. /// </summary>
  172. /// <param name="planes">
  173. /// An array of world-space planes with unit-length normals.
  174. /// </param>
  175. public void Split(Plane[] planes)
  176. {
  177. if (planes != null && planes.Length > 0 && isIntact && hull != null && !hull.IsEmpty)
  178. {
  179. UvMapper uvMapper = GetComponent<UvMapper>();
  180. ColorMapper colorMapper = GetComponent<ColorMapper>();
  181. if (sendPreSplitMessage)
  182. {
  183. SendMessage("PreSplit", planes, SendMessageOptions.DontRequireReceiver);
  184. }
  185. Vector3[] points, normals;
  186. ConvertPlanesToLocalspace(planes, out points, out normals);
  187. IList<IHull> newHulls;
  188. CreateNewHulls(uvMapper, colorMapper, points, normals, out newHulls);
  189. GameObject[] newGameObjects;
  190. CreateNewGameObjects(newHulls, out newGameObjects);
  191. if (sendPostSplitMessage)
  192. {
  193. SendMessage("PostSplit", newGameObjects, SendMessageOptions.DontRequireReceiver);
  194. }
  195. Destroy(gameObject);
  196. isIntact = false;
  197. }
  198. }
  199. protected void ConvertPlanesToLocalspace(Plane[] planes, out Vector3[] points, out Vector3[] normals)
  200. {
  201. points = new Vector3[planes.Length];
  202. normals = new Vector3[planes.Length];
  203. for (int i = 0; i < planes.Length; i++)
  204. {
  205. Plane plane = planes[i];
  206. Vector3 localPoint = transform.InverseTransformPoint(plane.normal * -plane.distance);
  207. Vector3 localNormal = transform.InverseTransformDirection(plane.normal);
  208. localNormal.Scale(transform.localScale);
  209. localNormal.Normalize();
  210. points[i] = localPoint;
  211. normals[i] = localNormal;
  212. }
  213. }
  214. protected void CreateNewHulls(UvMapper uvMapper, ColorMapper colorMapper, Vector3[] points, Vector3[] normals, out IList<IHull> newHulls)
  215. {
  216. newHulls = new List<IHull>();
  217. // Add the starting hull
  218. newHulls.Add(hull);
  219. for (int j = 0; j < points.Length; j++)
  220. {
  221. int previousHullCount = newHulls.Count;
  222. for (int i = 0; i < previousHullCount; i++)
  223. {
  224. IHull previousHull = newHulls[0];
  225. // Split the previous hull
  226. IHull a, b;
  227. previousHull.Split(points[j], normals[j], fillCut, uvMapper, colorMapper, out a, out b);
  228. // Update the list
  229. newHulls.Remove(previousHull);
  230. if (!a.IsEmpty)
  231. {
  232. newHulls.Add(a);
  233. }
  234. if (!b.IsEmpty)
  235. {
  236. newHulls.Add(b);
  237. }
  238. }
  239. }
  240. }
  241. protected void CreateNewGameObjects(IList<IHull> newHulls, out GameObject[] newGameObjects)
  242. {
  243. // Get new meshes
  244. Mesh[] newMeshes = new Mesh[newHulls.Count];
  245. float[] newVolumes = new float[newHulls.Count];
  246. float totalVolume = 0.0f;
  247. for (int i = 0; i < newHulls.Count; i++)
  248. {
  249. Mesh mesh = newHulls[i].GetMesh();
  250. Vector3 size = mesh.bounds.size;
  251. float volume = size.x * size.y * size.z;
  252. newMeshes[i] = mesh;
  253. newVolumes[i] = volume;
  254. totalVolume += volume;
  255. }
  256. MeshFilter meshFilter = GetComponent<MeshFilter>();
  257. MeshCollider meshCollider = GetComponent<MeshCollider>();
  258. Rigidbody rigidbody = GetComponent<Rigidbody>();
  259. // Remove mesh references to speed up instantiation
  260. meshFilter.sharedMesh = null;
  261. if (meshCollider != null)
  262. {
  263. meshCollider.sharedMesh = null;
  264. }
  265. // Create new game objects
  266. newGameObjects = new GameObject[newHulls.Count];
  267. for (int i = 0; i < newHulls.Count; i++)
  268. {
  269. IHull newHull = newHulls[i];
  270. Mesh newMesh = newMeshes[i];
  271. float volume = newVolumes[i];
  272. GameObject newGameObject = (GameObject)Instantiate(gameObject);
  273. // Set shatter tool
  274. ShatterTool newShatterTool = newGameObject.GetComponent<ShatterTool>();
  275. if (newShatterTool != null)
  276. {
  277. newShatterTool.hull = newHull;
  278. }
  279. // Set mesh filter
  280. MeshFilter newMeshFilter = newGameObject.GetComponent<MeshFilter>();
  281. if (newMeshFilter != null)
  282. {
  283. newMeshFilter.sharedMesh = newMesh;
  284. }
  285. // Set mesh collider
  286. MeshCollider newMeshCollider = newGameObject.GetComponent<MeshCollider>();
  287. if (newMeshCollider != null)
  288. {
  289. newMeshCollider.sharedMesh = newMesh;
  290. }
  291. // Set rigidbody
  292. Rigidbody newRigidbody = newGameObject.GetComponent<Rigidbody>();
  293. if (rigidbody != null && newRigidbody != null)
  294. {
  295. newRigidbody.mass = rigidbody.mass * (volume / totalVolume);
  296. if (!newRigidbody.isKinematic)
  297. {
  298. newRigidbody.velocity = rigidbody.GetPointVelocity(newRigidbody.worldCenterOfMass);
  299. newRigidbody.angularVelocity = rigidbody.angularVelocity;
  300. }
  301. }
  302. // Update properties
  303. newShatterTool.CalculateCenter();
  304. newGameObjects[i] = newGameObject;
  305. }
  306. }
  307. }
  308. }