BiomeSystem.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. using System.Linq;
  2. using System.Numerics;
  3. using System.Threading.Tasks;
  4. using Content.Server.Atmos;
  5. using Content.Server.Atmos.Components;
  6. using Content.Server.Atmos.EntitySystems;
  7. using Content.Server.Decals;
  8. using Content.Server.Ghost.Roles.Components;
  9. using Content.Server.Shuttles.Events;
  10. using Content.Server.Shuttles.Systems;
  11. using Content.Shared.Atmos;
  12. using Content.Shared.Decals;
  13. using Content.Shared.Ghost;
  14. using Content.Shared.Gravity;
  15. using Content.Shared.Light.Components;
  16. using Content.Shared.Parallax.Biomes;
  17. using Content.Shared.Parallax.Biomes.Layers;
  18. using Content.Shared.Parallax.Biomes.Markers;
  19. using Microsoft.Extensions.ObjectPool;
  20. using Robust.Server.Player;
  21. using Robust.Shared;
  22. using Robust.Shared.Collections;
  23. using Robust.Shared.Configuration;
  24. using Robust.Shared.Console;
  25. using Robust.Shared.Map;
  26. using Robust.Shared.Map.Components;
  27. using Robust.Shared.Physics;
  28. using Robust.Shared.Physics.Systems;
  29. using Robust.Shared.Player;
  30. using Robust.Shared.Prototypes;
  31. using Robust.Shared.Random;
  32. using Robust.Shared.Threading;
  33. using Robust.Shared.Utility;
  34. using ChunkIndicesEnumerator = Robust.Shared.Map.Enumerators.ChunkIndicesEnumerator;
  35. namespace Content.Server.Parallax;
  36. public sealed partial class BiomeSystem : SharedBiomeSystem
  37. {
  38. [Dependency] private readonly IConfigurationManager _configManager = default!;
  39. [Dependency] private readonly IConsoleHost _console = default!;
  40. [Dependency] private readonly IMapManager _mapManager = default!;
  41. [Dependency] private readonly IParallelManager _parallel = default!;
  42. [Dependency] private readonly IPrototypeManager _proto = default!;
  43. [Dependency] private readonly IPlayerManager _playerManager = default!;
  44. [Dependency] private readonly IRobustRandom _random = default!;
  45. [Dependency] private readonly AtmosphereSystem _atmos = default!;
  46. [Dependency] private readonly DecalSystem _decals = default!;
  47. [Dependency] private readonly SharedMapSystem _mapSystem = default!;
  48. [Dependency] private readonly SharedPhysicsSystem _physics = default!;
  49. [Dependency] private readonly SharedTransformSystem _transform = default!;
  50. [Dependency] private readonly ShuttleSystem _shuttles = default!;
  51. private EntityQuery<BiomeComponent> _biomeQuery;
  52. private EntityQuery<FixturesComponent> _fixturesQuery;
  53. private EntityQuery<GhostComponent> _ghostQuery;
  54. private EntityQuery<TransformComponent> _xformQuery;
  55. private readonly HashSet<EntityUid> _handledEntities = new();
  56. private const float DefaultLoadRange = 16f;
  57. private float _loadRange = DefaultLoadRange;
  58. private List<(Vector2i, Tile)> _tiles = new();
  59. private ObjectPool<HashSet<Vector2i>> _tilePool =
  60. new DefaultObjectPool<HashSet<Vector2i>>(new SetPolicy<Vector2i>(), 256);
  61. /// <summary>
  62. /// Load area for chunks containing tiles, decals etc.
  63. /// </summary>
  64. private Box2 _loadArea = new(-DefaultLoadRange, -DefaultLoadRange, DefaultLoadRange, DefaultLoadRange);
  65. /// <summary>
  66. /// Stores the chunks active for this tick temporarily.
  67. /// </summary>
  68. private readonly Dictionary<BiomeComponent, HashSet<Vector2i>> _activeChunks = new();
  69. private readonly Dictionary<BiomeComponent,
  70. Dictionary<string, HashSet<Vector2i>>> _markerChunks = new();
  71. public override void Initialize()
  72. {
  73. base.Initialize();
  74. Log.Level = LogLevel.Debug;
  75. _biomeQuery = GetEntityQuery<BiomeComponent>();
  76. _fixturesQuery = GetEntityQuery<FixturesComponent>();
  77. _ghostQuery = GetEntityQuery<GhostComponent>();
  78. _xformQuery = GetEntityQuery<TransformComponent>();
  79. SubscribeLocalEvent<BiomeComponent, MapInitEvent>(OnBiomeMapInit);
  80. SubscribeLocalEvent<FTLStartedEvent>(OnFTLStarted);
  81. SubscribeLocalEvent<ShuttleFlattenEvent>(OnShuttleFlatten);
  82. Subs.CVar(_configManager, CVars.NetMaxUpdateRange, SetLoadRange, true);
  83. InitializeCommands();
  84. SubscribeLocalEvent<PrototypesReloadedEventArgs>(ProtoReload);
  85. }
  86. private void ProtoReload(PrototypesReloadedEventArgs obj)
  87. {
  88. if (!obj.ByType.TryGetValue(typeof(BiomeTemplatePrototype), out var reloads))
  89. return;
  90. var query = AllEntityQuery<BiomeComponent>();
  91. while (query.MoveNext(out var uid, out var biome))
  92. {
  93. if (biome.Template == null || !reloads.Modified.TryGetValue(biome.Template, out var proto))
  94. continue;
  95. SetTemplate(uid, biome, (BiomeTemplatePrototype) proto);
  96. }
  97. }
  98. private void SetLoadRange(float obj)
  99. {
  100. // Round it up
  101. _loadRange = MathF.Ceiling(obj / ChunkSize) * ChunkSize;
  102. _loadArea = new Box2(-_loadRange, -_loadRange, _loadRange, _loadRange);
  103. }
  104. private void OnBiomeMapInit(EntityUid uid, BiomeComponent component, MapInitEvent args)
  105. {
  106. if (component.Seed == -1)
  107. {
  108. SetSeed(uid, component, _random.Next());
  109. }
  110. if (_proto.TryIndex(component.Template, out var biome))
  111. SetTemplate(uid, component, biome);
  112. var xform = Transform(uid);
  113. var mapId = xform.MapID;
  114. if (mapId != MapId.Nullspace && HasComp<MapGridComponent>(uid))
  115. {
  116. var setTiles = new List<(Vector2i Index, Tile tile)>();
  117. foreach (var grid in _mapManager.GetAllGrids(mapId))
  118. {
  119. if (!_fixturesQuery.TryGetComponent(grid.Owner, out var fixtures))
  120. continue;
  121. // Don't want shuttles flying around now do we.
  122. _shuttles.Disable(grid.Owner);
  123. var pTransform = _physics.GetPhysicsTransform(grid.Owner);
  124. foreach (var fixture in fixtures.Fixtures.Values)
  125. {
  126. for (var i = 0; i < fixture.Shape.ChildCount; i++)
  127. {
  128. var aabb = fixture.Shape.ComputeAABB(pTransform, i);
  129. setTiles.Clear();
  130. ReserveTiles(uid, aabb, setTiles);
  131. }
  132. }
  133. }
  134. }
  135. }
  136. public void SetEnabled(Entity<BiomeComponent?> ent, bool enabled = true)
  137. {
  138. if (!Resolve(ent, ref ent.Comp) || ent.Comp.Enabled == enabled)
  139. return;
  140. ent.Comp.Enabled = enabled;
  141. Dirty(ent, ent.Comp);
  142. }
  143. public void SetSeed(EntityUid uid, BiomeComponent component, int seed, bool dirty = true)
  144. {
  145. component.Seed = seed;
  146. if (dirty)
  147. Dirty(uid, component);
  148. }
  149. public void ClearTemplate(EntityUid uid, BiomeComponent component, bool dirty = true)
  150. {
  151. component.Layers.Clear();
  152. component.Template = null;
  153. if (dirty)
  154. Dirty(uid, component);
  155. }
  156. /// <summary>
  157. /// Sets the <see cref="BiomeComponent.Template"/> and refreshes layers.
  158. /// </summary>
  159. public void SetTemplate(EntityUid uid, BiomeComponent component, BiomeTemplatePrototype template, bool dirty = true)
  160. {
  161. component.Layers.Clear();
  162. component.Template = template.ID;
  163. foreach (var layer in template.Layers)
  164. {
  165. component.Layers.Add(layer);
  166. }
  167. if (dirty)
  168. Dirty(uid, component);
  169. }
  170. /// <summary>
  171. /// Adds the specified layer at the specified marker if it exists.
  172. /// </summary>
  173. public void AddLayer(EntityUid uid, BiomeComponent component, string id, IBiomeLayer addedLayer, int seedOffset = 0)
  174. {
  175. for (var i = 0; i < component.Layers.Count; i++)
  176. {
  177. var layer = component.Layers[i];
  178. if (layer is not BiomeDummyLayer dummy || dummy.ID != id)
  179. continue;
  180. addedLayer.Noise.SetSeed(addedLayer.Noise.GetSeed() + seedOffset);
  181. component.Layers.Insert(i, addedLayer);
  182. break;
  183. }
  184. Dirty(uid, component);
  185. }
  186. public void AddMarkerLayer(EntityUid uid, BiomeComponent component, string marker)
  187. {
  188. component.MarkerLayers.Add(marker);
  189. Dirty(uid, component);
  190. }
  191. /// <summary>
  192. /// Adds the specified template at the specified marker if it exists, withour overriding every layer.
  193. /// </summary>
  194. public void AddTemplate(EntityUid uid, BiomeComponent component, string id, BiomeTemplatePrototype template, int seedOffset = 0)
  195. {
  196. for (var i = 0; i < component.Layers.Count; i++)
  197. {
  198. var layer = component.Layers[i];
  199. if (layer is not BiomeDummyLayer dummy || dummy.ID != id)
  200. continue;
  201. for (var j = template.Layers.Count - 1; j >= 0; j--)
  202. {
  203. var addedLayer = template.Layers[j];
  204. addedLayer.Noise.SetSeed(addedLayer.Noise.GetSeed() + seedOffset);
  205. component.Layers.Insert(i, addedLayer);
  206. }
  207. break;
  208. }
  209. Dirty(uid, component);
  210. }
  211. private void OnFTLStarted(ref FTLStartedEvent ev)
  212. {
  213. var targetMap = ev.TargetCoordinates.ToMap(EntityManager, _transform);
  214. var targetMapUid = _mapManager.GetMapEntityId(targetMap.MapId);
  215. if (!TryComp<BiomeComponent>(targetMapUid, out var biome))
  216. return;
  217. var preloadArea = new Vector2(32f, 32f);
  218. var targetArea = new Box2(targetMap.Position - preloadArea, targetMap.Position + preloadArea);
  219. Preload(targetMapUid, biome, targetArea);
  220. }
  221. private void OnShuttleFlatten(ref ShuttleFlattenEvent ev)
  222. {
  223. if (!TryComp<BiomeComponent>(ev.MapUid, out var biome) ||
  224. !TryComp<MapGridComponent>(ev.MapUid, out var grid))
  225. {
  226. return;
  227. }
  228. var tiles = new List<(Vector2i Index, Tile Tile)>();
  229. foreach (var aabb in ev.AABBs)
  230. {
  231. for (var x = Math.Floor(aabb.Left); x <= Math.Ceiling(aabb.Right); x++)
  232. {
  233. for (var y = Math.Floor(aabb.Bottom); y <= Math.Ceiling(aabb.Top); y++)
  234. {
  235. var index = new Vector2i((int) x, (int) y);
  236. var chunk = SharedMapSystem.GetChunkIndices(index, ChunkSize);
  237. var mod = biome.ModifiedTiles.GetOrNew(chunk * ChunkSize);
  238. if (!mod.Add(index) || !TryGetBiomeTile(index, biome.Layers, biome.Seed, grid, out var tile))
  239. continue;
  240. // If we flag it as modified then the tile is never set so need to do it ourselves.
  241. tiles.Add((index, tile.Value));
  242. }
  243. }
  244. }
  245. _mapSystem.SetTiles(ev.MapUid, grid, tiles);
  246. }
  247. /// <summary>
  248. /// Preloads biome for the specified area.
  249. /// </summary>
  250. public void Preload(EntityUid uid, BiomeComponent component, Box2 area)
  251. {
  252. var markers = component.MarkerLayers;
  253. var goobers = _markerChunks.GetOrNew(component);
  254. foreach (var layer in markers)
  255. {
  256. var proto = ProtoManager.Index(layer);
  257. var enumerator = new ChunkIndicesEnumerator(area, proto.Size);
  258. while (enumerator.MoveNext(out var chunk))
  259. {
  260. var chunkOrigin = chunk * proto.Size;
  261. var layerChunks = goobers.GetOrNew(proto.ID);
  262. layerChunks.Add(chunkOrigin.Value);
  263. }
  264. }
  265. }
  266. private bool CanLoad(EntityUid uid)
  267. {
  268. return !_ghostQuery.HasComp(uid);
  269. }
  270. public override void Update(float frameTime)
  271. {
  272. base.Update(frameTime);
  273. var biomes = AllEntityQuery<BiomeComponent>();
  274. while (biomes.MoveNext(out var biome))
  275. {
  276. if (biome.LifeStage < ComponentLifeStage.Running)
  277. continue;
  278. _activeChunks.Add(biome, _tilePool.Get());
  279. _markerChunks.GetOrNew(biome);
  280. }
  281. // Get chunks in range
  282. foreach (var pSession in Filter.GetAllPlayers(_playerManager))
  283. {
  284. if (_xformQuery.TryGetComponent(pSession.AttachedEntity, out var xform) &&
  285. _handledEntities.Add(pSession.AttachedEntity.Value) &&
  286. _biomeQuery.TryGetComponent(xform.MapUid, out var biome) &&
  287. biome.Enabled &&
  288. CanLoad(pSession.AttachedEntity.Value))
  289. {
  290. var worldPos = _transform.GetWorldPosition(xform);
  291. AddChunksInRange(biome, worldPos);
  292. foreach (var layer in biome.MarkerLayers)
  293. {
  294. var layerProto = ProtoManager.Index(layer);
  295. AddMarkerChunksInRange(biome, worldPos, layerProto);
  296. }
  297. }
  298. foreach (var viewer in pSession.ViewSubscriptions)
  299. {
  300. if (!_handledEntities.Add(viewer) ||
  301. !_xformQuery.TryGetComponent(viewer, out xform) ||
  302. !_biomeQuery.TryGetComponent(xform.MapUid, out biome) ||
  303. !biome.Enabled ||
  304. !CanLoad(viewer))
  305. {
  306. continue;
  307. }
  308. var worldPos = _transform.GetWorldPosition(xform);
  309. AddChunksInRange(biome, worldPos);
  310. foreach (var layer in biome.MarkerLayers)
  311. {
  312. var layerProto = ProtoManager.Index(layer);
  313. AddMarkerChunksInRange(biome, worldPos, layerProto);
  314. }
  315. }
  316. }
  317. var loadBiomes = AllEntityQuery<BiomeComponent, MapGridComponent>();
  318. while (loadBiomes.MoveNext(out var gridUid, out var biome, out var grid))
  319. {
  320. // If not MapInit don't run it.
  321. if (biome.LifeStage < ComponentLifeStage.Running)
  322. continue;
  323. if (!biome.Enabled)
  324. continue;
  325. // Load new chunks
  326. LoadChunks(biome, gridUid, grid, biome.Seed);
  327. // Unload old chunks
  328. UnloadChunks(biome, gridUid, grid, biome.Seed);
  329. }
  330. _handledEntities.Clear();
  331. foreach (var tiles in _activeChunks.Values)
  332. {
  333. _tilePool.Return(tiles);
  334. }
  335. _activeChunks.Clear();
  336. _markerChunks.Clear();
  337. }
  338. private void AddChunksInRange(BiomeComponent biome, Vector2 worldPos)
  339. {
  340. var enumerator = new ChunkIndicesEnumerator(_loadArea.Translated(worldPos), ChunkSize);
  341. while (enumerator.MoveNext(out var chunkOrigin))
  342. {
  343. _activeChunks[biome].Add(chunkOrigin.Value * ChunkSize);
  344. }
  345. }
  346. private void AddMarkerChunksInRange(BiomeComponent biome, Vector2 worldPos, IBiomeMarkerLayer layer)
  347. {
  348. // Offset the load area so it's centralised.
  349. var loadArea = new Box2(0, 0, layer.Size, layer.Size);
  350. var halfLayer = new Vector2(layer.Size / 2f);
  351. var enumerator = new ChunkIndicesEnumerator(loadArea.Translated(worldPos - halfLayer), layer.Size);
  352. while (enumerator.MoveNext(out var chunkOrigin))
  353. {
  354. var lay = _markerChunks[biome].GetOrNew(layer.ID);
  355. lay.Add(chunkOrigin.Value * layer.Size);
  356. }
  357. }
  358. #region Load
  359. /// <summary>
  360. /// Loads all of the chunks for a particular biome, as well as handle any marker chunks.
  361. /// </summary>
  362. private void LoadChunks(
  363. BiomeComponent component,
  364. EntityUid gridUid,
  365. MapGridComponent grid,
  366. int seed)
  367. {
  368. BuildMarkerChunks(component, gridUid, grid, seed);
  369. var active = _activeChunks[component];
  370. foreach (var chunk in active)
  371. {
  372. LoadChunkMarkers(component, gridUid, grid, chunk, seed);
  373. if (!component.LoadedChunks.Add(chunk))
  374. continue;
  375. // Load NOW!
  376. LoadChunk(component, gridUid, grid, chunk, seed);
  377. }
  378. }
  379. /// <summary>
  380. /// Goes through all marker chunks that haven't been calculated, then calculates what spawns there are and
  381. /// allocates them to the relevant actual chunks in the biome (marker chunks may be many times larger than biome chunks).
  382. /// </summary>
  383. private void BuildMarkerChunks(BiomeComponent component, EntityUid gridUid, MapGridComponent grid, int seed)
  384. {
  385. var markers = _markerChunks[component];
  386. var loadedMarkers = component.LoadedMarkers;
  387. var idx = 0;
  388. foreach (var (layer, chunks) in markers)
  389. {
  390. // I know dictionary ordering isn't guaranteed but I just need something to differentiate seeds.
  391. idx++;
  392. var localIdx = idx;
  393. Parallel.ForEach(chunks, new ParallelOptions() { MaxDegreeOfParallelism = _parallel.ParallelProcessCount }, chunk =>
  394. {
  395. if (loadedMarkers.TryGetValue(layer, out var mobChunks) && mobChunks.Contains(chunk))
  396. return;
  397. var forced = component.ForcedMarkerLayers.Contains(layer);
  398. // Make a temporary version and copy back in later.
  399. var pending = new Dictionary<Vector2i, Dictionary<string, List<Vector2i>>>();
  400. // Essentially get the seed + work out a buffer to adjacent chunks so we don't
  401. // inadvertantly spawn too many near the edges.
  402. var layerProto = ProtoManager.Index<BiomeMarkerLayerPrototype>(layer);
  403. var markerSeed = seed + chunk.X * ChunkSize + chunk.Y + localIdx;
  404. var rand = new Random(markerSeed);
  405. var buffer = (int) (layerProto.Radius / 2f);
  406. var bounds = new Box2i(chunk + buffer, chunk + layerProto.Size - buffer);
  407. var count = (int) (bounds.Area / (layerProto.Radius * layerProto.Radius));
  408. count = Math.Min(count, layerProto.MaxCount);
  409. GetMarkerNodes(gridUid, component, grid, layerProto, forced, bounds, count, rand,
  410. out var spawnSet, out var existing);
  411. // Forcing markers to spawn so delete any that were found to be in the way.
  412. if (forced && existing.Count > 0)
  413. {
  414. // Lock something so we can delete these safely.
  415. lock (component.PendingMarkers)
  416. {
  417. foreach (var ent in existing)
  418. {
  419. Del(ent);
  420. }
  421. }
  422. }
  423. foreach (var node in spawnSet.Keys)
  424. {
  425. var chunkOrigin = SharedMapSystem.GetChunkIndices(node, ChunkSize) * ChunkSize;
  426. if (!pending.TryGetValue(chunkOrigin, out var pendingMarkers))
  427. {
  428. pendingMarkers = new Dictionary<string, List<Vector2i>>();
  429. pending[chunkOrigin] = pendingMarkers;
  430. }
  431. if (!pendingMarkers.TryGetValue(layer, out var layerMarkers))
  432. {
  433. layerMarkers = new List<Vector2i>();
  434. pendingMarkers[layer] = layerMarkers;
  435. }
  436. layerMarkers.Add(node);
  437. }
  438. lock (loadedMarkers)
  439. {
  440. if (!loadedMarkers.TryGetValue(layer, out var lockMobChunks))
  441. {
  442. lockMobChunks = new HashSet<Vector2i>();
  443. loadedMarkers[layer] = lockMobChunks;
  444. }
  445. lockMobChunks.Add(chunk);
  446. foreach (var (chunkOrigin, layers) in pending)
  447. {
  448. if (!component.PendingMarkers.TryGetValue(chunkOrigin, out var lockMarkers))
  449. {
  450. lockMarkers = new Dictionary<string, List<Vector2i>>();
  451. component.PendingMarkers[chunkOrigin] = lockMarkers;
  452. }
  453. foreach (var (lockLayer, nodes) in layers)
  454. {
  455. lockMarkers[lockLayer] = nodes;
  456. }
  457. }
  458. }
  459. });
  460. }
  461. component.ForcedMarkerLayers.Clear();
  462. }
  463. /// <summary>
  464. /// Gets the marker nodes for the specified area.
  465. /// </summary>
  466. /// <param name="emptyTiles">Should we include empty tiles when determine markers (e.g. if they are yet to be loaded)</param>
  467. public void GetMarkerNodes(
  468. EntityUid gridUid,
  469. BiomeComponent biome,
  470. MapGridComponent grid,
  471. BiomeMarkerLayerPrototype layerProto,
  472. bool forced,
  473. Box2i bounds,
  474. int count,
  475. Random rand,
  476. out Dictionary<Vector2i, string?> spawnSet,
  477. out HashSet<EntityUid> existingEnts,
  478. bool emptyTiles = true)
  479. {
  480. DebugTools.Assert(count > 0);
  481. var remainingTiles = _tilePool.Get();
  482. var nodeEntities = new Dictionary<Vector2i, EntityUid?>();
  483. var nodeMask = new Dictionary<Vector2i, string?>();
  484. // Okay so originally we picked a random tile and BFS outwards
  485. // the problem is if you somehow get a cooked frontier then it might drop entire veins
  486. // hence we'll grab all valid tiles up front and use that as possible seeds.
  487. // It's hella more expensive but stops issues.
  488. for (var x = bounds.Left; x < bounds.Right; x++)
  489. {
  490. for (var y = bounds.Bottom; y < bounds.Top; y++)
  491. {
  492. var node = new Vector2i(x, y);
  493. // Empty tile, skip if relevant.
  494. if (!emptyTiles && (!_mapSystem.TryGetTile(grid, node, out var tile) || tile.IsEmpty))
  495. continue;
  496. // Check if it's a valid spawn, if so then use it.
  497. var enumerator = _mapSystem.GetAnchoredEntitiesEnumerator(gridUid, grid, node);
  498. enumerator.MoveNext(out var existing);
  499. if (!forced && existing != null)
  500. continue;
  501. // Check if mask matches // anything blocking.
  502. TryGetEntity(node, biome, grid, out var proto);
  503. // If there's an existing entity and it doesn't match the mask then skip.
  504. if (layerProto.EntityMask.Count > 0 &&
  505. (proto == null ||
  506. !layerProto.EntityMask.ContainsKey(proto)))
  507. {
  508. continue;
  509. }
  510. // If it's just a flat spawn then just check for anything blocking.
  511. if (proto != null && layerProto.Prototype != null)
  512. {
  513. continue;
  514. }
  515. DebugTools.Assert(layerProto.EntityMask.Count == 0 || !string.IsNullOrEmpty(proto));
  516. remainingTiles.Add(node);
  517. nodeEntities.Add(node, existing);
  518. nodeMask.Add(node, proto);
  519. }
  520. }
  521. var frontier = new ValueList<Vector2i>(32);
  522. // TODO: Need poisson but crashes whenever I use moony's due to inputs or smth idk
  523. // Get the total amount of groups to spawn across the entire chunk.
  524. // We treat a null entity mask as requiring nothing else on the tile
  525. spawnSet = new Dictionary<Vector2i, string?>();
  526. existingEnts = new HashSet<EntityUid>();
  527. // Iterate the group counts and pathfind out each group.
  528. for (var i = 0; i < count; i++)
  529. {
  530. var groupSize = rand.Next(layerProto.MinGroupSize, layerProto.MaxGroupSize + 1);
  531. // While we have remaining tiles keep iterating
  532. while (groupSize > 0 && remainingTiles.Count > 0)
  533. {
  534. var startNode = rand.PickAndTake(remainingTiles);
  535. frontier.Clear();
  536. frontier.Add(startNode);
  537. // This essentially may lead to a vein being split in multiple areas but the count matters more than position.
  538. while (frontier.Count > 0 && groupSize > 0)
  539. {
  540. // Need to pick a random index so we don't just get straight lines of ores.
  541. var frontierIndex = rand.Next(frontier.Count);
  542. var node = frontier[frontierIndex];
  543. frontier.RemoveSwap(frontierIndex);
  544. remainingTiles.Remove(node);
  545. // Add neighbors if they're valid, worst case we add no more and pick another random seed tile.
  546. for (var x = -1; x <= 1; x++)
  547. {
  548. for (var y = -1; y <= 1; y++)
  549. {
  550. var neighbor = new Vector2i(node.X + x, node.Y + y);
  551. if (frontier.Contains(neighbor) || !remainingTiles.Contains(neighbor))
  552. continue;
  553. frontier.Add(neighbor);
  554. }
  555. }
  556. // Tile valid salad so add it.
  557. var mask = nodeMask[node];
  558. spawnSet.Add(node, mask);
  559. groupSize--;
  560. if (nodeEntities.TryGetValue(node, out var existing))
  561. {
  562. Del(existing);
  563. }
  564. }
  565. }
  566. if (groupSize > 0)
  567. {
  568. Log.Warning($"Found remaining group size for ore veins!");
  569. }
  570. }
  571. _tilePool.Return(remainingTiles);
  572. }
  573. /// <summary>
  574. /// Loads the pre-deteremined marker nodes for a particular chunk.
  575. /// This is calculated in <see cref="BuildMarkerChunks"/>
  576. /// </summary>
  577. /// <remarks>
  578. /// Note that the marker chunks do not correspond to this chunk.
  579. /// </remarks>
  580. private void LoadChunkMarkers(
  581. BiomeComponent component,
  582. EntityUid gridUid,
  583. MapGridComponent grid,
  584. Vector2i chunk,
  585. int seed)
  586. {
  587. // Load any pending marker tiles first.
  588. if (!component.PendingMarkers.TryGetValue(chunk, out var layers))
  589. return;
  590. // This needs to be done separately in case we try to add a marker layer and want to force it on existing
  591. // loaded chunks.
  592. component.ModifiedTiles.TryGetValue(chunk, out var modified);
  593. modified ??= _tilePool.Get();
  594. foreach (var (layer, nodes) in layers)
  595. {
  596. var layerProto = ProtoManager.Index<BiomeMarkerLayerPrototype>(layer);
  597. foreach (var node in nodes)
  598. {
  599. if (modified.Contains(node))
  600. continue;
  601. // Need to ensure the tile under it has loaded for anchoring.
  602. if (TryGetBiomeTile(node, component.Layers, seed, grid, out var tile))
  603. {
  604. _mapSystem.SetTile(gridUid, grid, node, tile.Value);
  605. }
  606. string? prototype;
  607. if (TryGetEntity(node, component, grid, out var proto) &&
  608. layerProto.EntityMask.TryGetValue(proto, out var maskedProto))
  609. {
  610. prototype = maskedProto;
  611. }
  612. else
  613. {
  614. prototype = layerProto.Prototype;
  615. }
  616. // If it is a ghost role then purge it
  617. // TODO: This is *kind* of a bandaid but natural mobs spawns needs a lot more work.
  618. // Ideally we'd just have ghost role and non-ghost role variants for some stuff.
  619. var uid = EntityManager.CreateEntityUninitialized(prototype, _mapSystem.GridTileToLocal(gridUid, grid, node));
  620. RemComp<GhostTakeoverAvailableComponent>(uid);
  621. RemComp<GhostRoleComponent>(uid);
  622. EntityManager.InitializeAndStartEntity(uid);
  623. modified.Add(node);
  624. }
  625. }
  626. if (modified.Count == 0)
  627. {
  628. component.ModifiedTiles.Remove(chunk);
  629. _tilePool.Return(modified);
  630. }
  631. component.PendingMarkers.Remove(chunk);
  632. }
  633. /// <summary>
  634. /// Loads a particular queued chunk for a biome.
  635. /// </summary>
  636. private void LoadChunk(
  637. BiomeComponent component,
  638. EntityUid gridUid,
  639. MapGridComponent grid,
  640. Vector2i chunk,
  641. int seed)
  642. {
  643. component.ModifiedTiles.TryGetValue(chunk, out var modified);
  644. modified ??= _tilePool.Get();
  645. _tiles.Clear();
  646. // Set tiles first
  647. for (var x = 0; x < ChunkSize; x++)
  648. {
  649. for (var y = 0; y < ChunkSize; y++)
  650. {
  651. var indices = new Vector2i(x + chunk.X, y + chunk.Y);
  652. // Pass in null so we don't try to get the tileref.
  653. if (modified.Contains(indices))
  654. continue;
  655. // If there's existing data then don't overwrite it.
  656. if (_mapSystem.TryGetTileRef(gridUid, grid, indices, out var tileRef) && !tileRef.Tile.IsEmpty)
  657. continue;
  658. if (!TryGetBiomeTile(indices, component.Layers, seed, grid, out var biomeTile))
  659. continue;
  660. _tiles.Add((indices, biomeTile.Value));
  661. }
  662. }
  663. _mapSystem.SetTiles(gridUid, grid, _tiles);
  664. _tiles.Clear();
  665. // Now do entities
  666. var loadedEntities = new Dictionary<EntityUid, Vector2i>();
  667. component.LoadedEntities.Add(chunk, loadedEntities);
  668. for (var x = 0; x < ChunkSize; x++)
  669. {
  670. for (var y = 0; y < ChunkSize; y++)
  671. {
  672. var indices = new Vector2i(x + chunk.X, y + chunk.Y);
  673. if (modified.Contains(indices))
  674. continue;
  675. // Don't mess with anything that's potentially anchored.
  676. var anchored = _mapSystem.GetAnchoredEntitiesEnumerator(gridUid, grid, indices);
  677. if (anchored.MoveNext(out _) || !TryGetEntity(indices, component, grid, out var entPrototype))
  678. continue;
  679. // TODO: Fix non-anchored ents spawning.
  680. // Just track loaded chunks for now.
  681. var ent = Spawn(entPrototype, _mapSystem.GridTileToLocal(gridUid, grid, indices));
  682. // At least for now unless we do lookups or smth, only work with anchoring.
  683. if (_xformQuery.TryGetComponent(ent, out var xform) && !xform.Anchored)
  684. {
  685. _transform.AnchorEntity((ent, xform), (gridUid, grid), indices);
  686. }
  687. loadedEntities.Add(ent, indices);
  688. }
  689. }
  690. // Decals
  691. var loadedDecals = new Dictionary<uint, Vector2i>();
  692. component.LoadedDecals.Add(chunk, loadedDecals);
  693. for (var x = 0; x < ChunkSize; x++)
  694. {
  695. for (var y = 0; y < ChunkSize; y++)
  696. {
  697. var indices = new Vector2i(x + chunk.X, y + chunk.Y);
  698. if (modified.Contains(indices))
  699. continue;
  700. // Don't mess with anything that's potentially anchored.
  701. var anchored = _mapSystem.GetAnchoredEntitiesEnumerator(gridUid, grid, indices);
  702. if (anchored.MoveNext(out _) || !TryGetDecals(indices, component.Layers, seed, grid, out var decals))
  703. continue;
  704. foreach (var decal in decals)
  705. {
  706. if (!_decals.TryAddDecal(decal.ID, new EntityCoordinates(gridUid, decal.Position), out var dec))
  707. continue;
  708. loadedDecals.Add(dec, indices);
  709. }
  710. }
  711. }
  712. if (modified.Count == 0)
  713. {
  714. _tilePool.Return(modified);
  715. component.ModifiedTiles.Remove(chunk);
  716. }
  717. else
  718. {
  719. component.ModifiedTiles[chunk] = modified;
  720. }
  721. }
  722. #endregion
  723. #region Unload
  724. /// <summary>
  725. /// Handles all of the queued chunk unloads for a particular biome.
  726. /// </summary>
  727. private void UnloadChunks(BiomeComponent component, EntityUid gridUid, MapGridComponent grid, int seed)
  728. {
  729. var active = _activeChunks[component];
  730. List<(Vector2i, Tile)>? tiles = null;
  731. foreach (var chunk in component.LoadedChunks)
  732. {
  733. if (active.Contains(chunk) || !component.LoadedChunks.Remove(chunk))
  734. continue;
  735. // Unload NOW!
  736. tiles ??= new List<(Vector2i, Tile)>(ChunkSize * ChunkSize);
  737. UnloadChunk(component, gridUid, grid, chunk, seed, tiles);
  738. }
  739. }
  740. /// <summary>
  741. /// Unloads a specific biome chunk.
  742. /// </summary>
  743. private void UnloadChunk(BiomeComponent component, EntityUid gridUid, MapGridComponent grid, Vector2i chunk, int seed, List<(Vector2i, Tile)> tiles)
  744. {
  745. // Reverse order to loading
  746. component.ModifiedTiles.TryGetValue(chunk, out var modified);
  747. modified ??= new HashSet<Vector2i>();
  748. // Delete decals
  749. foreach (var (dec, indices) in component.LoadedDecals[chunk])
  750. {
  751. // If we couldn't remove it then flag the tile to never be touched.
  752. if (!_decals.RemoveDecal(gridUid, dec))
  753. {
  754. modified.Add(indices);
  755. }
  756. }
  757. component.LoadedDecals.Remove(chunk);
  758. // Delete entities
  759. // Ideally any entities that aren't modified just get deleted and re-generated later
  760. // This is because if we want to save the map (e.g. persistent server) it makes the file much smaller
  761. // and also if the map is enormous will make stuff like physics broadphase much faster
  762. var xformQuery = GetEntityQuery<TransformComponent>();
  763. foreach (var (ent, tile) in component.LoadedEntities[chunk])
  764. {
  765. if (Deleted(ent) || !xformQuery.TryGetComponent(ent, out var xform))
  766. {
  767. modified.Add(tile);
  768. continue;
  769. }
  770. // It's moved
  771. var entTile = _mapSystem.LocalToTile(gridUid, grid, xform.Coordinates);
  772. if (!xform.Anchored || entTile != tile)
  773. {
  774. modified.Add(tile);
  775. continue;
  776. }
  777. if (!EntityManager.IsDefault(ent))
  778. {
  779. modified.Add(tile);
  780. continue;
  781. }
  782. Del(ent);
  783. }
  784. component.LoadedEntities.Remove(chunk);
  785. // Unset tiles (if the data is custom)
  786. for (var x = 0; x < ChunkSize; x++)
  787. {
  788. for (var y = 0; y < ChunkSize; y++)
  789. {
  790. var indices = new Vector2i(x + chunk.X, y + chunk.Y);
  791. if (modified.Contains(indices))
  792. continue;
  793. // Don't mess with anything that's potentially anchored.
  794. var anchored = grid.GetAnchoredEntitiesEnumerator(indices);
  795. if (anchored.MoveNext(out _))
  796. {
  797. modified.Add(indices);
  798. continue;
  799. }
  800. // If it's default data unload the tile.
  801. if (!TryGetBiomeTile(indices, component.Layers, seed, null, out var biomeTile) ||
  802. _mapSystem.TryGetTileRef(gridUid, grid, indices, out var tileRef) && tileRef.Tile != biomeTile.Value)
  803. {
  804. modified.Add(indices);
  805. continue;
  806. }
  807. tiles.Add((indices, Tile.Empty));
  808. }
  809. }
  810. _mapSystem.SetTiles(gridUid, grid, tiles);
  811. tiles.Clear();
  812. component.LoadedChunks.Remove(chunk);
  813. if (modified.Count == 0)
  814. {
  815. component.ModifiedTiles.Remove(chunk);
  816. }
  817. else
  818. {
  819. component.ModifiedTiles[chunk] = modified;
  820. }
  821. }
  822. #endregion
  823. /// <summary>
  824. /// Creates a simple planet setup for a map.
  825. /// </summary>
  826. public void EnsurePlanet(EntityUid mapUid, BiomeTemplatePrototype biomeTemplate, int? seed = null, MetaDataComponent? metadata = null, Color? mapLight = null)
  827. {
  828. if (!Resolve(mapUid, ref metadata))
  829. return;
  830. EnsureComp<MapGridComponent>(mapUid);
  831. var biome = (BiomeComponent) EntityManager.ComponentFactory.GetComponent(typeof(BiomeComponent));
  832. seed ??= _random.Next();
  833. SetSeed(mapUid, biome, seed.Value, false);
  834. SetTemplate(mapUid, biome, biomeTemplate, false);
  835. AddComp(mapUid, biome, true);
  836. Dirty(mapUid, biome, metadata);
  837. var gravity = EnsureComp<GravityComponent>(mapUid);
  838. gravity.Enabled = true;
  839. gravity.Inherent = true;
  840. Dirty(mapUid, gravity, metadata);
  841. // Day lighting
  842. // Daylight: #D8B059
  843. // Midday: #E6CB8B
  844. // Moonlight: #2b3143
  845. // Lava: #A34931
  846. var light = EnsureComp<MapLightComponent>(mapUid);
  847. light.AmbientLightColor = mapLight ?? Color.FromHex("#D8B059");
  848. Dirty(mapUid, light, metadata);
  849. EnsureComp<RoofComponent>(mapUid);
  850. EnsureComp<LightCycleComponent>(mapUid);
  851. EnsureComp<SunShadowComponent>(mapUid);
  852. EnsureComp<SunShadowCycleComponent>(mapUid);
  853. var moles = new float[Atmospherics.AdjustedNumberOfGases];
  854. moles[(int) Gas.Oxygen] = 21.824779f;
  855. moles[(int) Gas.Nitrogen] = 82.10312f;
  856. var mixture = new GasMixture(moles, Atmospherics.T20C);
  857. _atmos.SetMapAtmosphere(mapUid, false, mixture);
  858. }
  859. /// <summary>
  860. /// Sets the specified tiles as relevant and marks them as modified.
  861. /// </summary>
  862. public void ReserveTiles(EntityUid mapUid, Box2 bounds, List<(Vector2i Index, Tile Tile)> tiles, BiomeComponent? biome = null, MapGridComponent? mapGrid = null)
  863. {
  864. if (!Resolve(mapUid, ref biome, ref mapGrid, false))
  865. return;
  866. foreach (var tileSet in _mapSystem.GetLocalTilesIntersecting(mapUid, mapGrid, bounds, false))
  867. {
  868. Vector2i chunkOrigin;
  869. HashSet<Vector2i> modified;
  870. // Existing, ignore
  871. if (_mapSystem.TryGetTileRef(mapUid, mapGrid, tileSet.GridIndices, out var existingRef) && !existingRef.Tile.IsEmpty)
  872. {
  873. chunkOrigin = SharedMapSystem.GetChunkIndices(tileSet.GridIndices, ChunkSize) * ChunkSize;
  874. modified = biome.ModifiedTiles.GetOrNew(chunkOrigin);
  875. modified.Add(tileSet.GridIndices);
  876. continue;
  877. }
  878. if (!TryGetBiomeTile(tileSet.GridIndices, biome.Layers, biome.Seed, mapGrid, out var tile))
  879. {
  880. continue;
  881. }
  882. chunkOrigin = SharedMapSystem.GetChunkIndices(tileSet.GridIndices, ChunkSize) * ChunkSize;
  883. modified = biome.ModifiedTiles.GetOrNew(chunkOrigin);
  884. modified.Add(tileSet.GridIndices);
  885. tiles.Add((tileSet.GridIndices, tile.Value));
  886. }
  887. _mapSystem.SetTiles(mapUid, mapGrid, tiles);
  888. }
  889. }