ExplosionSystem.GridMap.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. using System.Numerics;
  2. using Content.Shared.Atmos;
  3. using Content.Shared.Explosion;
  4. using Content.Shared.Explosion.Components;
  5. using Content.Shared.Explosion.EntitySystems;
  6. using Robust.Shared.Map;
  7. using Robust.Shared.Map.Components;
  8. namespace Content.Server.Explosion.EntitySystems;
  9. // This partial part of the explosion system has all of the functions used to facilitate explosions moving across grids.
  10. // A good portion of it is focused around keeping track of what tile-indices on a grid correspond to tiles that border
  11. // space. AFAIK no other system currently needs to track these "edge-tiles". If they do, this should probably be a
  12. // property of the grid itself?
  13. public sealed partial class ExplosionSystem
  14. {
  15. /// <summary>
  16. /// Set of tiles of each grid that are directly adjacent to space, along with the directions that face space.
  17. /// </summary>
  18. private Dictionary<EntityUid, Dictionary<Vector2i, NeighborFlag>> _gridEdges = new();
  19. /// <summary>
  20. /// On grid startup, prepare a map of grid edges.
  21. /// </summary>
  22. private void OnGridStartup(GridStartupEvent ev)
  23. {
  24. var grid = Comp<MapGridComponent>(ev.EntityUid);
  25. Dictionary<Vector2i, NeighborFlag> edges = new();
  26. _gridEdges[ev.EntityUid] = edges;
  27. foreach (var tileRef in _map.GetAllTiles(ev.EntityUid, grid))
  28. {
  29. if (IsEdge(grid, tileRef.GridIndices, out var dir))
  30. edges.Add(tileRef.GridIndices, dir);
  31. }
  32. }
  33. private void OnGridRemoved(GridRemovalEvent ev)
  34. {
  35. _airtightMap.Remove(ev.EntityUid);
  36. _gridEdges.Remove(ev.EntityUid);
  37. // this should be a small enough set that iterating all of them is fine
  38. var query = EntityQueryEnumerator<ExplosionVisualsComponent>();
  39. while (query.MoveNext(out var visuals))
  40. {
  41. visuals.Tiles.Remove(ev.EntityUid);
  42. }
  43. }
  44. /// <summary>
  45. /// Take our map of grid edges, where each is defined in their own grid's reference frame, and map those
  46. /// edges all onto one grids reference frame.
  47. /// </summary>
  48. public (Dictionary<Vector2i, BlockedSpaceTile>, ushort) TransformGridEdges(
  49. MapCoordinates epicentre,
  50. EntityUid? referenceGrid,
  51. List<EntityUid> localGrids,
  52. float maxDistance)
  53. {
  54. Dictionary<Vector2i, BlockedSpaceTile> transformedEdges = new();
  55. var targetMatrix = Matrix3x2.Identity;
  56. Angle targetAngle = new();
  57. var tileSize = DefaultTileSize;
  58. var maxDistanceSq = (int) (maxDistance * maxDistance);
  59. // if the explosion is centered on some grid (and not just space), get the transforms.
  60. if (referenceGrid != null)
  61. {
  62. var targetGrid = Comp<MapGridComponent>(referenceGrid.Value);
  63. var xform = Transform(referenceGrid.Value);
  64. (_, targetAngle, targetMatrix) = _transformSystem.GetWorldPositionRotationInvMatrix(xform);
  65. tileSize = targetGrid.TileSize;
  66. }
  67. var offsetMatrix = Matrix3x2.Identity;
  68. offsetMatrix.M31 = tileSize / 2f;
  69. offsetMatrix.M32 = tileSize / 2f;
  70. // Here we can end up with a triple nested for loop:
  71. // foreach other grid
  72. // foreach edge tile in that grid
  73. // foreach tile in our grid that touches that tile (vast majority of the time: 1 tile, but could be up to 4)
  74. foreach (var gridToTransform in localGrids)
  75. {
  76. // we treat the target grid separately
  77. if (gridToTransform == referenceGrid)
  78. continue;
  79. if (!_gridEdges.TryGetValue(gridToTransform, out var edges))
  80. continue;
  81. if (!TryComp(gridToTransform, out MapGridComponent? grid))
  82. continue;
  83. if (grid.TileSize != tileSize)
  84. {
  85. Log.Error($"Explosions do not support grids with different grid sizes. GridIds: {gridToTransform} and {referenceGrid}");
  86. continue;
  87. }
  88. var xforms = EntityManager.GetEntityQuery<TransformComponent>();
  89. var xform = xforms.GetComponent(gridToTransform);
  90. var (_, gridWorldRotation, gridWorldMatrix, invGridWorldMatrid) = _transformSystem.GetWorldPositionRotationMatrixWithInv(xform, xforms);
  91. var localEpicentre = (Vector2i) Vector2.Transform(epicentre.Position, invGridWorldMatrid);
  92. var matrix = offsetMatrix * gridWorldMatrix * targetMatrix;
  93. var angle = gridWorldRotation - targetAngle;
  94. var (x, y) = angle.RotateVec(new Vector2(tileSize / 4f, tileSize / 4f));
  95. foreach (var (tile, dir) in edges)
  96. {
  97. // if a tile is further than max distance from the epicentre, we just ignore it.
  98. var delta = tile - localEpicentre;
  99. if (delta.X * delta.X + delta.Y * delta.Y > maxDistanceSq) // no Vector2.Length???
  100. continue;
  101. var center = Vector2.Transform(tile, matrix);
  102. if ((dir & NeighborFlag.Cardinal) == 0)
  103. {
  104. // this is purely a diagonal edge tile
  105. var newIndex = new Vector2i((int) MathF.Floor(center.X), (int) MathF.Floor(center.Y));
  106. if (!transformedEdges.TryGetValue(newIndex, out var data))
  107. {
  108. data = new();
  109. transformedEdges[newIndex] = data;
  110. }
  111. data.BlockingGridEdges.Add(new(default, null, center, angle, tileSize));
  112. continue;
  113. }
  114. // Instead of just mapping the center of the tile, we map for points on that tile. This is basically a
  115. // shitty approximation to doing a proper check to get all space-tiles that intersect this grid tile.
  116. // Not perfect, but works well enough.
  117. HashSet<Vector2i> transformedTiles = new()
  118. {
  119. new((int) MathF.Floor(center.X + x), (int) MathF.Floor(center.Y + x)), // center of tile, offset by (0.25, 0.25) in tile coordinates
  120. new((int) MathF.Floor(center.X - y), (int) MathF.Floor(center.Y - y)), // center offset by (-0.25, 0.25)
  121. new((int) MathF.Floor(center.X - x), (int) MathF.Floor(center.Y + y)), // offset by (-0.25, -0.25)
  122. new((int) MathF.Floor(center.X + y), (int) MathF.Floor(center.Y - x)), // offset by (0.25, -0.25)
  123. };
  124. foreach (var newIndices in transformedTiles)
  125. {
  126. if (!transformedEdges.TryGetValue(newIndices, out var data))
  127. {
  128. data = new();
  129. transformedEdges[newIndices] = data;
  130. }
  131. data.BlockingGridEdges.Add(new(tile, gridToTransform, center, angle, tileSize));
  132. }
  133. }
  134. }
  135. if (referenceGrid == null)
  136. return (transformedEdges, tileSize);
  137. // finally, we also include the blocking tiles from the reference grid.
  138. if (_gridEdges.TryGetValue(referenceGrid.Value, out var localEdges))
  139. {
  140. foreach (var (tile, dir) in localEdges)
  141. {
  142. // grids cannot overlap, so tile should never be an existing entry.
  143. // if this ever changes, this needs to do a try-get.
  144. var data = new BlockedSpaceTile();
  145. transformedEdges[tile] = data;
  146. data.UnblockedDirections = AtmosDirection.Invalid; // all directions are blocked automatically.
  147. if ((dir & NeighborFlag.Cardinal) == 0)
  148. data.BlockingGridEdges.Add(new(default, null, (tile + Vector2Helpers.Half) * tileSize, 0, tileSize));
  149. else
  150. data.BlockingGridEdges.Add(new(tile, referenceGrid.Value, (tile + Vector2Helpers.Half) * tileSize, 0, tileSize));
  151. }
  152. }
  153. return (transformedEdges, tileSize);
  154. }
  155. /// <summary>
  156. /// Given an grid-edge blocking map, check if the blockers are allowed to propagate to each other through gaps in grids.
  157. /// </summary>
  158. /// <remarks>
  159. /// After grid edges were transformed into the reference frame of some other grid, this function figures out
  160. /// which of those edges are actually blocking explosion propagation.
  161. /// </remarks>
  162. public void GetUnblockedDirections(Dictionary<Vector2i, BlockedSpaceTile> transformedEdges, float tileSize)
  163. {
  164. foreach (var (tile, data) in transformedEdges)
  165. {
  166. if (data.UnblockedDirections == AtmosDirection.Invalid)
  167. continue; // already all blocked.
  168. var tileCenter = (tile + new Vector2(0.5f, 0.5f)) * tileSize;
  169. foreach (var edge in data.BlockingGridEdges)
  170. {
  171. // if a blocking edge contains the center of the tile, block all directions
  172. if (edge.Box.Contains(tileCenter))
  173. {
  174. data.UnblockedDirections = AtmosDirection.Invalid;
  175. break;
  176. }
  177. // check north
  178. if (edge.Box.Contains(tileCenter + new Vector2(0, tileSize / 2f)))
  179. data.UnblockedDirections &= ~AtmosDirection.North;
  180. // check south
  181. if (edge.Box.Contains(tileCenter + new Vector2(0, -tileSize / 2f)))
  182. data.UnblockedDirections &= ~AtmosDirection.South;
  183. // check east
  184. if (edge.Box.Contains(tileCenter + new Vector2(tileSize / 2f, 0)))
  185. data.UnblockedDirections &= ~AtmosDirection.East;
  186. // check west
  187. if (edge.Box.Contains(tileCenter + new Vector2(-tileSize / 2f, 0)))
  188. data.UnblockedDirections &= ~AtmosDirection.West;
  189. }
  190. }
  191. }
  192. /// <summary>
  193. /// When a tile is updated, we might need to update the grid edge maps.
  194. /// </summary>
  195. private void OnTileChanged(ref TileChangedEvent ev)
  196. {
  197. // only need to update the grid-edge map if a tile was added or removed from the grid.
  198. if (!ev.NewTile.Tile.IsEmpty && !ev.OldTile.IsEmpty)
  199. return;
  200. if (!TryComp(ev.Entity, out MapGridComponent? grid))
  201. return;
  202. var tileRef = ev.NewTile;
  203. if (!_gridEdges.TryGetValue(tileRef.GridUid, out var edges))
  204. {
  205. edges = new();
  206. _gridEdges[tileRef.GridUid] = edges;
  207. }
  208. if (tileRef.Tile.IsEmpty)
  209. {
  210. // if the tile is empty, it cannot itself be an edge tile.
  211. edges.Remove(tileRef.GridIndices);
  212. // add any valid neighbours to the list of edge-tiles
  213. for (var i = 0; i < NeighbourVectors.Length; i++)
  214. {
  215. var neighbourIndex = tileRef.GridIndices + NeighbourVectors[i];
  216. if (grid.TryGetTileRef(neighbourIndex, out var neighbourTile) && !neighbourTile.Tile.IsEmpty)
  217. {
  218. var oppositeDirection = (NeighborFlag) (1 << ((i + 4) % 8));
  219. edges[neighbourIndex] = edges.GetValueOrDefault(neighbourIndex) | oppositeDirection;
  220. }
  221. }
  222. return;
  223. }
  224. // the tile is not empty space, but was previously. So update directly adjacent neighbours, which may no longer
  225. // be edge tiles.
  226. for (var i = 0; i < NeighbourVectors.Length; i++)
  227. {
  228. var neighbourIndex = tileRef.GridIndices + NeighbourVectors[i];
  229. if (edges.TryGetValue(neighbourIndex, out var neighborSpaceDir))
  230. {
  231. var oppositeDirection = (NeighborFlag) (1 << ((i + 4) % 8));
  232. neighborSpaceDir &= ~oppositeDirection;
  233. if (neighborSpaceDir == NeighborFlag.Invalid)
  234. {
  235. // no longer an edge tile
  236. edges.Remove(neighbourIndex);
  237. continue;
  238. }
  239. edges[neighbourIndex] = neighborSpaceDir;
  240. }
  241. }
  242. // finally check if the new tile is itself an edge tile
  243. if (IsEdge(grid, tileRef.GridIndices, out var spaceDir))
  244. edges.Add(tileRef.GridIndices, spaceDir);
  245. }
  246. /// <summary>
  247. /// Check whether a tile is on the edge of a grid (i.e., whether it borders space).
  248. /// </summary>
  249. /// <remarks>
  250. /// Optionally ignore a specific Vector2i. Used by <see cref="OnTileChanged"/> when we already know that a
  251. /// given tile is not space. This avoids unnecessary TryGetTileRef calls.
  252. /// </remarks>
  253. private bool IsEdge(MapGridComponent grid, Vector2i index, out NeighborFlag spaceDirections)
  254. {
  255. spaceDirections = NeighborFlag.Invalid;
  256. for (var i = 0; i < NeighbourVectors.Length; i++)
  257. {
  258. if (!grid.TryGetTileRef(index + NeighbourVectors[i], out var neighborTile) || neighborTile.Tile.IsEmpty)
  259. spaceDirections |= (NeighborFlag) (1 << i);
  260. }
  261. return spaceDirections != NeighborFlag.Invalid;
  262. }
  263. // yeah this is now the third direction flag enum, and the 5th (afaik) direction enum overall.....
  264. /// <summary>
  265. /// Directional bitflags used to denote the neighbouring tiles of some tile on a grid.. Differ from atmos and
  266. /// normal directional flags as NorthEast != North | East
  267. /// </summary>
  268. [Flags]
  269. public enum NeighborFlag : byte
  270. {
  271. Invalid = 0,
  272. North = 1 << 0,
  273. NorthEast = 1 << 1,
  274. East = 1 << 2,
  275. SouthEast = 1 << 3,
  276. South = 1 << 4,
  277. SouthWest = 1 << 5,
  278. West = 1 << 6,
  279. NorthWest = 1 << 7,
  280. Cardinal = North | East | South | West,
  281. Diagonal = NorthEast | SouthEast | SouthWest | NorthWest,
  282. Any = Cardinal | Diagonal
  283. }
  284. public static bool AnyNeighborBlocked(NeighborFlag neighbors, AtmosDirection blockedDirs)
  285. {
  286. if ((neighbors & NeighborFlag.North) == NeighborFlag.North && (blockedDirs & AtmosDirection.North) == AtmosDirection.North)
  287. return true;
  288. if ((neighbors & NeighborFlag.South) == NeighborFlag.South && (blockedDirs & AtmosDirection.South) == AtmosDirection.South)
  289. return true;
  290. if ((neighbors & NeighborFlag.East) == NeighborFlag.East && (blockedDirs & AtmosDirection.East) == AtmosDirection.East)
  291. return true;
  292. if ((neighbors & NeighborFlag.West) == NeighborFlag.West && (blockedDirs & AtmosDirection.West) == AtmosDirection.West)
  293. return true;
  294. return false;
  295. }
  296. // array indices match NeighborFlags shifts.
  297. public static readonly Vector2i[] NeighbourVectors =
  298. {
  299. new (0, 1),
  300. new (1, 1),
  301. new (1, 0),
  302. new (1, -1),
  303. new (0, -1),
  304. new (-1, -1),
  305. new (-1, 0),
  306. new (-1, 1)
  307. };
  308. }
  309. /// <summary>
  310. /// This class has information about the space equivalent of an airtight entity blocking explosions: the edges of grids.
  311. /// </summary>
  312. public sealed class BlockedSpaceTile
  313. {
  314. /// <summary>
  315. /// What directions of this tile are not blocked?
  316. /// </summary>
  317. public AtmosDirection UnblockedDirections = AtmosDirection.All;
  318. /// <summary>
  319. /// The set of grid edge-tiles that are blocking this space tile.
  320. /// </summary>
  321. public List<GridEdgeData> BlockingGridEdges = new();
  322. public sealed class GridEdgeData
  323. {
  324. public Vector2i Tile;
  325. public EntityUid? Grid;
  326. public Box2Rotated Box;
  327. public GridEdgeData(Vector2i tile, EntityUid? grid, Vector2 center, Angle angle, float size)
  328. {
  329. Tile = tile;
  330. Grid = grid;
  331. Box = new(Box2.CenteredAround(center, new Vector2(size, size)), angle, center);
  332. }
  333. }
  334. }