Tile.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using DunGen.Pooling;
  2. using DunGen.Tags;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using UnityEngine;
  7. using UnityEngine.Serialization;
  8. namespace DunGen
  9. {
  10. [AddComponentMenu("DunGen/Tile")]
  11. public class Tile : MonoBehaviour, ISerializationCallbackReceiver
  12. {
  13. public const int CurrentFileVersion = 3;
  14. #region Legacy Properties
  15. // Legacy properties only exist to avoid breaking existing projects
  16. // Converting old data structures over to the new ones
  17. [SerializeField]
  18. [FormerlySerializedAs("AllowImmediateRepeats")]
  19. private bool allowImmediateRepeats = true;
  20. [SerializeField]
  21. [Obsolete("'Entrance' is no longer used. Please use the 'Entrances' list instead", false)]
  22. public Doorway Entrance;
  23. [SerializeField]
  24. [Obsolete("'Exit' is no longer used. Please use the 'Exits' list instead", false)]
  25. public Doorway Exit;
  26. #endregion
  27. /// <summary>
  28. /// Should this tile be allowed to rotate to fit in place?
  29. /// </summary>
  30. public bool AllowRotation = true;
  31. /// <summary>
  32. /// Should this tile be allowed to be placed next to another instance of itself?
  33. /// </summary>
  34. public TileRepeatMode RepeatMode = TileRepeatMode.Allow;
  35. /// <summary>
  36. /// Should the automatically generated tile bounds be overridden with a user-defined value?
  37. /// </summary>
  38. public bool OverrideAutomaticTileBounds = false;
  39. /// <summary>
  40. /// Optional tile bounds to override the automatically calculated tile bounds
  41. /// </summary>
  42. public Bounds TileBoundsOverride = new Bounds(Vector3.zero, Vector3.one);
  43. /// <summary>
  44. /// An optional collection of entrance doorways. DunGen will try to use one of these doorways as the entrance to the tile if possible
  45. /// </summary>
  46. public List<Doorway> Entrances = new List<Doorway>();
  47. /// <summary>
  48. /// An optional collection of exit doorways. DunGen will try to use one of these doorways as the exit to the tile if possible
  49. /// </summary>
  50. public List<Doorway> Exits = new List<Doorway>();
  51. /// <summary>
  52. /// Should this tile override the connection chance globally defined in the DungeonFlow?
  53. /// </summary>
  54. public bool OverrideConnectionChance = false;
  55. /// <summary>
  56. /// The overridden connection chance value. Only used if <see cref="OverrideConnectionChance"/> is true.
  57. /// If both tiles have overridden the connection chance, the lowest value is used
  58. /// </summary>
  59. public float ConnectionChance = 0f;
  60. /// <summary>
  61. /// A collection of tags for this tile. Can be used with the dungeon flow asset to restrict which
  62. /// tiles can be attached
  63. /// </summary>
  64. public TagContainer Tags = new TagContainer();
  65. /// <summary>
  66. /// The calculated world-space bounds of this Tile
  67. /// </summary>
  68. [HideInInspector]
  69. public Bounds Bounds { get { return transform.TransformBounds(Placement.LocalBounds); } }
  70. /// <summary>
  71. /// Information about the tile's position in the generated dungeon
  72. /// </summary>
  73. public TilePlacementData Placement
  74. {
  75. get { return placement; }
  76. internal set { placement = value; }
  77. }
  78. /// <summary>
  79. /// The dungeon that this tile belongs to
  80. /// </summary>
  81. public Dungeon Dungeon { get; internal set; }
  82. public List<Doorway> AllDoorways = new List<Doorway>();
  83. public List<Doorway> UsedDoorways = new List<Doorway>();
  84. public List<Doorway> UnusedDoorways = new List<Doorway>();
  85. public GameObject Prefab { get; internal set; }
  86. public bool HasValidBounds => Placement != null && Placement.LocalBounds.extents.sqrMagnitude > 0f;
  87. [SerializeField]
  88. private TilePlacementData placement;
  89. [SerializeField]
  90. private int fileVersion;
  91. private BoxCollider triggerVolume;
  92. private BoxCollider2D triggerVolume2D;
  93. private readonly List<ITileSpawnEventReceiver> spawnEventReceivers = new List<ITileSpawnEventReceiver>();
  94. public void RefreshTileEventReceivers()
  95. {
  96. spawnEventReceivers.Clear();
  97. GetComponentsInChildren(true, spawnEventReceivers);
  98. }
  99. internal void TileSpawned()
  100. {
  101. foreach (var receiver in spawnEventReceivers)
  102. receiver.OnTileSpawned(this);
  103. }
  104. internal void TileDespawned()
  105. {
  106. Dungeon = null;
  107. foreach (var doorway in AllDoorways)
  108. doorway.ResetInstanceData();
  109. placement.SetPositionAndRotation(Vector2.zero, Quaternion.identity);
  110. UsedDoorways.Clear();
  111. UnusedDoorways.Clear();
  112. foreach(var receiver in spawnEventReceivers)
  113. receiver.OnTileDespawned(this);
  114. }
  115. internal void AddTriggerVolume(bool use2dCollider)
  116. {
  117. if (use2dCollider)
  118. {
  119. if (triggerVolume2D == null)
  120. triggerVolume2D = gameObject.AddComponent<BoxCollider2D>();
  121. triggerVolume2D.offset = Placement.LocalBounds.center;
  122. triggerVolume2D.size = Placement.LocalBounds.size;
  123. triggerVolume2D.isTrigger = true;
  124. }
  125. else
  126. {
  127. if(triggerVolume == null)
  128. triggerVolume = gameObject.AddComponent<BoxCollider>();
  129. triggerVolume.center = Placement.LocalBounds.center;
  130. triggerVolume.size = Placement.LocalBounds.size;
  131. triggerVolume.isTrigger = true;
  132. }
  133. }
  134. private void OnTriggerEnter(Collider other)
  135. {
  136. if (other == null)
  137. return;
  138. if (other.gameObject.TryGetComponent<DungenCharacter>(out var character))
  139. character.OnTileEntered(this);
  140. }
  141. private void OnTriggerEnter2D(Collider2D other)
  142. {
  143. if (other == null)
  144. return;
  145. if (other.gameObject.TryGetComponent<DungenCharacter>(out var character))
  146. character.OnTileEntered(this);
  147. }
  148. private void OnTriggerExit(Collider other)
  149. {
  150. if (other == null)
  151. return;
  152. if (other.gameObject.TryGetComponent<DungenCharacter>(out var character))
  153. character.OnTileExited(this);
  154. }
  155. private void OnTriggerExit2D(Collider2D other)
  156. {
  157. if (other == null)
  158. return;
  159. if (other.gameObject.TryGetComponent<DungenCharacter>(out var character))
  160. character.OnTileExited(this);
  161. }
  162. private void OnDrawGizmos()
  163. {
  164. Gizmos.color = Color.red;
  165. Bounds? bounds = null;
  166. if (OverrideAutomaticTileBounds)
  167. bounds = transform.TransformBounds(TileBoundsOverride);
  168. else if (placement != null)
  169. bounds = Bounds;
  170. if (bounds.HasValue)
  171. Gizmos.DrawWireCube(bounds.Value.center, bounds.Value.size);
  172. }
  173. public IEnumerable<Tile> GetAdjacentTiles()
  174. {
  175. return UsedDoorways.Select(x => x.ConnectedDoorway.Tile).Distinct();
  176. }
  177. public bool IsAdjacentTo(Tile other)
  178. {
  179. foreach (var door in UsedDoorways)
  180. if (door.ConnectedDoorway.Tile == other)
  181. return true;
  182. return false;
  183. }
  184. public Doorway GetEntranceDoorway()
  185. {
  186. foreach (var doorway in UsedDoorways)
  187. {
  188. var connectedTile = doorway.ConnectedDoorway.Tile;
  189. if (Placement.IsOnMainPath)
  190. {
  191. if (connectedTile.Placement.IsOnMainPath && Placement.PathDepth > connectedTile.Placement.PathDepth)
  192. return doorway;
  193. }
  194. else
  195. {
  196. if (connectedTile.Placement.IsOnMainPath || Placement.Depth > connectedTile.Placement.Depth)
  197. return doorway;
  198. }
  199. }
  200. return null;
  201. }
  202. public Doorway GetExitDoorway()
  203. {
  204. foreach (var doorway in UsedDoorways)
  205. {
  206. var connectedTile = doorway.ConnectedDoorway.Tile;
  207. if (Placement.IsOnMainPath)
  208. {
  209. if (connectedTile.Placement.IsOnMainPath && Placement.PathDepth < connectedTile.Placement.PathDepth)
  210. return doorway;
  211. }
  212. else
  213. {
  214. if (!connectedTile.Placement.IsOnMainPath && Placement.Depth < connectedTile.Placement.Depth)
  215. return doorway;
  216. }
  217. }
  218. return null;
  219. }
  220. /// <summary>
  221. /// Recalculates the Tile's bounds based on the geometry inside the prefab
  222. /// </summary>
  223. /// <returns>True if the bounds changed when recalculated</returns>
  224. public bool RecalculateBounds()
  225. {
  226. if (Placement == null)
  227. Placement = new TilePlacementData();
  228. var oldBounds = Placement.LocalBounds;
  229. if (OverrideAutomaticTileBounds)
  230. Placement.LocalBounds = TileBoundsOverride;
  231. else
  232. {
  233. var tileBounds = UnityUtil.CalculateObjectBounds(gameObject,
  234. false,
  235. DunGenSettings.Instance.BoundsCalculationsIgnoreSprites,
  236. true);
  237. tileBounds = UnityUtil.CondenseBounds(tileBounds, GetComponentsInChildren<Doorway>(true));
  238. // Convert tileBounds to local space
  239. tileBounds = transform.InverseTransformBounds(tileBounds);
  240. Placement.LocalBounds = tileBounds;
  241. }
  242. var bounds = Placement.LocalBounds;
  243. bool haveBoundsChanged = bounds != oldBounds;
  244. // Let the user know that the tile's bounds are invalid
  245. if (bounds.size.x <= 0f || bounds.size.y <= 0f || bounds.size.z <= 0f)
  246. Debug.LogError(string.Format("Tile prefab '{0}' has automatic bounds that are zero or negative in size. The bounding volume for this tile will need to be manually defined.", gameObject), gameObject);
  247. //if (haveBoundsChanged)
  248. // Debug.Log($"Updated bounds for '{gameObject.name}'");
  249. //else
  250. // Debug.Log($"RecalculateBounds(): Bounds were already up-to-date for '{gameObject.name}'");
  251. return haveBoundsChanged;
  252. }
  253. public void CopyBoundsFrom(Tile otherTile)
  254. {
  255. if (otherTile == null)
  256. return;
  257. if(Placement == null)
  258. Placement = new TilePlacementData();
  259. Placement.LocalBounds = otherTile.Placement.LocalBounds;
  260. }
  261. #region ISerializationCallbackReceiver Implementation
  262. public void OnBeforeSerialize()
  263. {
  264. fileVersion = CurrentFileVersion;
  265. }
  266. public void OnAfterDeserialize()
  267. {
  268. #pragma warning disable 618
  269. // AllowImmediateRepeats (bool) -> TileRepeatMode (enum)
  270. if (fileVersion < 1)
  271. RepeatMode = (allowImmediateRepeats) ? TileRepeatMode.Allow : TileRepeatMode.DisallowImmediate;
  272. // Converted individual Entrance and Exit doorways to collections
  273. if (fileVersion < 2)
  274. {
  275. if (Entrances == null)
  276. Entrances = new List<Doorway>();
  277. if (Exits == null)
  278. Exits = new List<Doorway>();
  279. if (Entrance != null)
  280. Entrances.Add(Entrance);
  281. if(Exit != null)
  282. Exits.Add(Exit);
  283. Entrance = null;
  284. Exit = null;
  285. }
  286. #pragma warning restore 618
  287. }
  288. #endregion
  289. }
  290. }