MazeGraph.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace MazeGen
  4. {
  5. /// <summary>
  6. /// The full set of generated rooms so far, plus O(1)-ish id lookup, spatial queries and
  7. /// exit-usage bookkeeping. Everything else (agent tracking, visualization, collision/merge
  8. /// logic) reads from here instead of walking the scene hierarchy.
  9. ///
  10. /// Also tracks connected components (union-find over rooms, merged whenever two exits get
  11. /// connected) so "does an exit already exist" and "are there still unused exits" can be
  12. /// asked per-component instead of globally. That distinction matters once there are
  13. /// multiple start rooms: a global answer would let one isolated branch's safety valves get
  14. /// silently satisfied by an exit room that lives in a totally different, disconnected part
  15. /// of the maze - which is exactly how a branch can end up with no way out at all.
  16. /// </summary>
  17. public class MazeGraph
  18. {
  19. public readonly Dictionary<int, Room> Rooms = new Dictionary<int, Room>();
  20. public readonly List<Room> StartRooms = new List<Room>();
  21. public readonly List<Room> ExitRooms = new List<Room>();
  22. public readonly List<CorridorSegment> CorridorSegments = new List<CorridorSegment>();
  23. private readonly SpatialRoomIndex _spatialIndex;
  24. // Union-find over room ids, keyed by root id.
  25. private readonly Dictionary<int, int> _componentParent = new Dictionary<int, int>();
  26. private readonly Dictionary<int, bool> _componentHasExit = new Dictionary<int, bool>();
  27. private readonly Dictionary<int, int> _componentUnusedExitCount = new Dictionary<int, int>();
  28. private int _nextRoomId;
  29. private int _nextExitId;
  30. public int RoomCount => Rooms.Count;
  31. /// <summary>Total exits across the whole graph that are not yet used (informational only - generation decisions should use ComponentUnusedExitCount instead).</summary>
  32. public int UnusedExitCount { get; private set; }
  33. public MazeGraph(float spatialCellSize)
  34. {
  35. _spatialIndex = new SpatialRoomIndex(spatialCellSize);
  36. }
  37. public int AllocateRoomId() => _nextRoomId++;
  38. public int AllocateExitId() => _nextExitId++;
  39. public void Register(Room room)
  40. {
  41. Rooms[room.Id] = room;
  42. if (room.Kind == RoomKind.Start) StartRooms.Add(room);
  43. if (room.Kind == RoomKind.Exit)
  44. {
  45. ExitRooms.Add(room);
  46. _componentHasExit[Find(room.Id)] = true;
  47. }
  48. _spatialIndex.Add(room);
  49. // Register corridor segments if this is a hallway with waypoints (elbow connector)
  50. if (room.Kind == RoomKind.Hallway && room.CorridorWaypoints != null && room.CorridorWaypoints.Length >= 2)
  51. {
  52. for (int i = 0; i < room.CorridorWaypoints.Length - 1; i++)
  53. CorridorSegments.Add(new CorridorSegment(room.Id, room.CorridorWaypoints[i], room.CorridorWaypoints[i + 1], room.Radius));
  54. }
  55. }
  56. public Room Get(int id) => Rooms.TryGetValue(id, out var room) ? room : null;
  57. public IEnumerable<Room> QueryRoomsNear(Vector2 position, float radius) =>
  58. _spatialIndex.QueryNearby(position, radius);
  59. /// <summary>Finds corridor segments whose footprint may be near a position/radius (cheap AABB reject).</summary>
  60. public IEnumerable<CorridorSegment> QueryCorridorSegmentsNear(Vector2 position, float radius)
  61. {
  62. foreach (var seg in CorridorSegments)
  63. {
  64. // Cheap reject: expand seg bounds by radius, test point-in-rect
  65. if (position.x + radius < seg.Min.x || position.x - radius > seg.Max.x) continue;
  66. if (position.y + radius < seg.Min.y || position.y - radius > seg.Max.y) continue;
  67. yield return seg;
  68. }
  69. }
  70. /// <summary>Adds an exit to a room and keeps the unused-exit counters (global and per-component) in sync.</summary>
  71. public void AddExit(Room room, Exit exit)
  72. {
  73. room.Exits.Add(exit);
  74. if (!exit.IsUsed)
  75. {
  76. UnusedExitCount++;
  77. _componentUnusedExitCount[Find(room.Id)]++;
  78. }
  79. }
  80. /// <summary>Marks an exit as used (idempotent) and keeps the unused-exit counters in sync.</summary>
  81. public void MarkExitUsed(Exit exit)
  82. {
  83. if (exit.IsUsed) return;
  84. exit.IsUsed = true;
  85. UnusedExitCount--;
  86. _componentUnusedExitCount[Find(exit.OwnerRoomId)]--;
  87. }
  88. /// <summary>
  89. /// Undoes a speculative AddExit for an exit that turned out to be unusable (e.g. a
  90. /// door added on-the-fly to close a loop, where the path to it was later found to be
  91. /// blocked). Only valid for still-unused exits.
  92. /// </summary>
  93. public void RemoveUnusedExit(Room room, Exit exit)
  94. {
  95. if (exit.IsUsed) return;
  96. if (room.Exits.Remove(exit))
  97. {
  98. UnusedExitCount--;
  99. _componentUnusedExitCount[Find(room.Id)]--;
  100. }
  101. }
  102. /// <summary>Merges the connected components containing the two rooms - call whenever a connection is made between them.</summary>
  103. public void Union(int roomIdA, int roomIdB)
  104. {
  105. int a = Find(roomIdA);
  106. int b = Find(roomIdB);
  107. if (a == b) return;
  108. _componentParent[b] = a;
  109. _componentHasExit[a] = _componentHasExit[a] || _componentHasExit[b];
  110. _componentUnusedExitCount[a] += _componentUnusedExitCount[b];
  111. _componentHasExit.Remove(b);
  112. _componentUnusedExitCount.Remove(b);
  113. }
  114. public bool AreSameComponent(int roomIdA, int roomIdB) => Find(roomIdA) == Find(roomIdB);
  115. /// <summary>True if an Exit room already exists anywhere in the same connected component as this room.</summary>
  116. public bool ComponentHasExit(int roomId) => _componentHasExit[Find(roomId)];
  117. /// <summary>Unused exits remaining within this room's connected component only.</summary>
  118. public int ComponentUnusedExitCount(int roomId) => _componentUnusedExitCount[Find(roomId)];
  119. private int Find(int roomId)
  120. {
  121. if (!_componentParent.ContainsKey(roomId))
  122. {
  123. _componentParent[roomId] = roomId;
  124. _componentHasExit[roomId] = false;
  125. _componentUnusedExitCount[roomId] = 0;
  126. return roomId;
  127. }
  128. int parent = _componentParent[roomId];
  129. if (parent != roomId)
  130. {
  131. parent = Find(parent); // path compression
  132. _componentParent[roomId] = parent;
  133. }
  134. return parent;
  135. }
  136. }
  137. }