Files
wwdpublic/Content.Server/Atmos/EntitySystems/AtmosphereSystem.LINDA.cs
SimpleStation14 6e0ffe81bc Mirror: Partial atmos refactor (#312)
## Mirror of PR #22521: [Partial atmos
refactor](https://github.com/space-wizards/space-station-14/pull/22521)
from <img src="https://avatars.githubusercontent.com/u/10567778?v=4"
alt="space-wizards" width="22"/>
[space-wizards](https://github.com/space-wizards)/[space-station-14](https://github.com/space-wizards/space-station-14)

###### `18a35e7e83b2b71ee84b054d44d9ed5e595dd618`

PR opened by <img
src="https://avatars.githubusercontent.com/u/60421075?v=4"
width="16"/><a href="https://github.com/ElectroJr"> ElectroJr</a> at
2023-12-15 03:45:42 UTC

---

PR changed 43 files with 891 additions and 635 deletions.

The PR had the following labels:
- Status: Needs Review


---

<details open="true"><summary><h1>Original Body</h1></summary>

> This PR reworks how some parts of atmos code work. Originally it was
just meant to be a performance and bugfix PR, but it has ballooned in
scope. I'm not sure about some of my changes largely because I'm not
sure if some things were an oversight or an intentional decision for
some reason.
> 
> List of changes:
> - The `MolesArchived float[]` field is now read-only
> - It simply gets zeroed whenever the `GasMixture` is set to null
instead of constantly reallocating
> - Airtight query information is now cached in `TileAtmosphere`
> - This means that it should only iterate over anchored entities once
per update.
> - Previously an invalidated atmos tile would cause
`ProcessRevalidate()` to query airtight entities on the same tile six
times by calling a combination of `GridIsTileAirBlocked()`,
`NeedsVacuumFixing()`, and `GridIsTileAirBlocked()`. So this should help
significantly reduce component lookups & entity enumeration.
> - This does change some behaviour. In particular blocked directions
are now only updated if the tile was invalidated prior to the current
atmos-update, and will only ever be updated once per atmos-update.
> - AFAIK this only has an effect if the invalid tile processing is
deferred over multiple ticks, and I don't think it should cause any
issues?
> - Fixes a potential bug, where tiles might not dispose of their
excited group if their direction flags changed.
> - `MapAtmosphereComponent.Mixture` is now always immutable and no
longer nullable
> - I'm not sure why the mixture was nullable before? AFAICT the
component is meaningless if its null?
> - Space "gas" was always immutable, but there was nothing that
required planet atmospheres to be immutable. Requiring that it be
immutable gets rid of the constant gas mixture cloning.
> - I don't know if there was a reason for why they weren't immutable to
begin with.
> - Fixes lungs removing too much air from a gas mixture, resulting in
negative moles.
> - `GasMixture.Moles` is now `[Access]` restricted to the atmosphere
system.
> - This is to prevent people from improperly modifying the gas mixtures
(e.g., lungs), or accidentally modifying immutable mixtures.
> - Fixes an issue where non-grid atmosphere tiles would fail to update
their adjacent tiles, resulting in null reference exception spam
>   - Fixes #21732
>   - Fixes #21210 (probably) 
> - Disconnected atmosphere tiles, i.e., tiles that aren't on or
adjacent to a grid tile, will now get removed from the tile set.
Previously the tile set would just always increase, with tiles never
getting removed.
> - Removes various redundant component and tile-definition queries.
> - Removes some method events in favour of just using methods.
> - Map-exposded tiles now get updated when a map's atmosphere changes
(or the grid moves across maps).
> - Adds a `setmapatmos` command for adding map-wide atmospheres.
> - Fixed (non-planet) map atmospheres rendering over grids.
> 
> ## Media
> 
> This PR also includes changes to the atmos debug overlay, though I've
also split that off into a separate PR to make reviewing easier
(#22520).
> 
> Below is a video showing that atmos still seems to work, and that
trimming of disconnected tiles works:
> 
>
https://github.com/space-wizards/space-station-14/assets/60421075/4da46992-19e6-4354-8ecd-3cd67be4d0ed
> 
> For comparison, here is a video showing how current master works
(disconnected tiles never get removed):
> 
>
https://github.com/space-wizards/space-station-14/assets/60421075/54590777-e11c-41dc-b49d-fd7e53bfeed7
> 
> 🆑
> - fix: Fixed a bug where partially airtight entities (e.g., thin
windows or doors) could let air leak out into space.
> 


</details>

Co-authored-by: SimpleStation14 <Unknown>
2024-05-20 02:33:00 -04:00

336 lines
14 KiB
C#

using Content.Server.Atmos.Components;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Components;
using Robust.Shared.Utility;
namespace Content.Server.Atmos.EntitySystems
{
public sealed partial class AtmosphereSystem
{
private void ProcessCell(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, int fireCount, GasTileOverlayComponent visuals)
{
// Can't process a tile without air
if (tile.Air == null)
{
RemoveActiveTile(gridAtmosphere, tile);
return;
}
if (tile.ArchivedCycle < fireCount)
Archive(tile, fireCount);
tile.CurrentCycle = fireCount;
var adjacentTileLength = 0;
for (var i = 0; i < Atmospherics.Directions; i++)
{
var direction = (AtmosDirection) (1 << i);
if(tile.AdjacentBits.IsFlagSet(direction))
adjacentTileLength++;
}
for(var i = 0; i < Atmospherics.Directions; i++)
{
var direction = (AtmosDirection) (1 << i);
if (!tile.AdjacentBits.IsFlagSet(direction)) continue;
var enemyTile = tile.AdjacentTiles[i];
// If the tile is null or has no air, we don't do anything for it.
if(enemyTile?.Air == null) continue;
if (fireCount <= enemyTile.CurrentCycle) continue;
Archive(enemyTile, fireCount);
var shouldShareAir = false;
if (ExcitedGroups && tile.ExcitedGroup != null && enemyTile.ExcitedGroup != null)
{
if (tile.ExcitedGroup != enemyTile.ExcitedGroup)
{
ExcitedGroupMerge(gridAtmosphere, tile.ExcitedGroup, enemyTile.ExcitedGroup);
}
shouldShareAir = true;
} else if (CompareExchange(tile.Air, enemyTile.Air) != GasCompareResult.NoExchange)
{
if (!enemyTile.Excited)
{
AddActiveTile(gridAtmosphere, enemyTile);
}
if (ExcitedGroups)
{
var excitedGroup = tile.ExcitedGroup;
excitedGroup ??= enemyTile.ExcitedGroup;
if (excitedGroup == null)
{
excitedGroup = new ExcitedGroup();
gridAtmosphere.ExcitedGroups.Add(excitedGroup);
}
if (tile.ExcitedGroup == null)
ExcitedGroupAddTile(excitedGroup, tile);
if(enemyTile.ExcitedGroup == null)
ExcitedGroupAddTile(excitedGroup, enemyTile);
}
shouldShareAir = true;
}
if (shouldShareAir)
{
var difference = Share(tile, enemyTile, adjacentTileLength);
// Monstermos already handles this, so let's not handle it ourselves.
if (!MonstermosEqualization)
{
if (difference >= 0)
{
ConsiderPressureDifference(gridAtmosphere, tile, direction, difference);
}
else
{
ConsiderPressureDifference(gridAtmosphere, enemyTile, direction.GetOpposite(), -difference);
}
}
LastShareCheck(tile);
}
}
if(tile.Air != null)
React(tile.Air, tile);
InvalidateVisuals(tile.GridIndex, tile.GridIndices, visuals);
var remove = true;
if(tile.Air!.Temperature > Atmospherics.MinimumTemperatureStartSuperConduction)
if (ConsiderSuperconductivity(gridAtmosphere, tile, true))
remove = false;
if(ExcitedGroups && tile.ExcitedGroup == null && remove)
RemoveActiveTile(gridAtmosphere, tile);
}
private void Archive(TileAtmosphere tile, int fireCount)
{
if (tile.Air != null)
tile.Air.Moles.AsSpan().CopyTo(tile.MolesArchived.AsSpan());
tile.TemperatureArchived = tile.Temperature;
tile.ArchivedCycle = fireCount;
}
private void LastShareCheck(TileAtmosphere tile)
{
if (tile.Air == null || tile.ExcitedGroup == null)
return;
switch (tile.LastShare)
{
case > Atmospherics.MinimumAirToSuspend:
ExcitedGroupResetCooldowns(tile.ExcitedGroup);
break;
case > Atmospherics.MinimumMolesDeltaToMove:
tile.ExcitedGroup.DismantleCooldown = 0;
break;
}
}
/// <summary>
/// Makes a tile become active and start processing. Does NOT check if the tile belongs to the grid atmos.
/// </summary>
/// <param name="gridAtmosphere">Grid Atmosphere where to get the tile.</param>
/// <param name="tile">Tile Atmosphere to be activated.</param>
private void AddActiveTile(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile)
{
if (tile.Air == null)
return;
tile.Excited = true;
gridAtmosphere.ActiveTiles.Add(tile);
}
/// <summary>
/// Makes a tile become inactive and stop processing.
/// </summary>
/// <param name="gridAtmosphere">Grid Atmosphere where to get the tile.</param>
/// <param name="tile">Tile Atmosphere to be deactivated.</param>
/// <param name="disposeExcitedGroup">Whether to dispose of the tile's <see cref="ExcitedGroup"/></param>
private void RemoveActiveTile(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, bool disposeExcitedGroup = true)
{
DebugTools.Assert(tile.Excited == gridAtmosphere.ActiveTiles.Contains(tile));
DebugTools.Assert(tile.Excited || tile.ExcitedGroup == null);
if (!tile.Excited)
return;
tile.Excited = false;
gridAtmosphere.ActiveTiles.Remove(tile);
if (tile.ExcitedGroup == null)
return;
if (disposeExcitedGroup)
ExcitedGroupDispose(gridAtmosphere, tile.ExcitedGroup);
else
ExcitedGroupRemoveTile(tile.ExcitedGroup, tile);
}
/// <summary>
/// Calculates the heat capacity for a gas mixture, using the archived values.
/// </summary>
public float GetHeatCapacityArchived(TileAtmosphere tile)
{
if (tile.Air == null)
return tile.HeatCapacity;
return GetHeatCapacityCalculation(tile.MolesArchived!, tile.Space);
}
/// <summary>
/// Shares gas between two tiles. Part of LINDA.
/// </summary>
public float Share(TileAtmosphere tileReceiver, TileAtmosphere tileSharer, int atmosAdjacentTurfs)
{
if (tileReceiver.Air is not {} receiver || tileSharer.Air is not {} sharer)
return 0f;
var temperatureDelta = tileReceiver.TemperatureArchived - tileSharer.TemperatureArchived;
var absTemperatureDelta = Math.Abs(temperatureDelta);
var oldHeatCapacity = 0f;
var oldSharerHeatCapacity = 0f;
if (absTemperatureDelta > Atmospherics.MinimumTemperatureDeltaToConsider)
{
oldHeatCapacity = GetHeatCapacity(receiver);
oldSharerHeatCapacity = GetHeatCapacity(sharer);
}
var heatCapacityToSharer = 0f;
var heatCapacitySharerToThis = 0f;
var movedMoles = 0f;
var absMovedMoles = 0f;
for(var i = 0; i < Atmospherics.TotalNumberOfGases; i++)
{
var thisValue = receiver.Moles[i];
var sharerValue = sharer.Moles[i];
var delta = (thisValue - sharerValue) / (atmosAdjacentTurfs + 1);
if (!(MathF.Abs(delta) >= Atmospherics.GasMinMoles)) continue;
if (absTemperatureDelta > Atmospherics.MinimumTemperatureDeltaToConsider)
{
var gasHeatCapacity = delta * GasSpecificHeats[i];
if (delta > 0)
{
heatCapacityToSharer += gasHeatCapacity;
}
else
{
heatCapacitySharerToThis -= gasHeatCapacity;
}
}
if (!receiver.Immutable) receiver.Moles[i] -= delta;
if (!sharer.Immutable) sharer.Moles[i] += delta;
movedMoles += delta;
absMovedMoles += MathF.Abs(delta);
}
tileReceiver.LastShare = absMovedMoles;
if (absTemperatureDelta > Atmospherics.MinimumTemperatureDeltaToConsider)
{
var newHeatCapacity = oldHeatCapacity + heatCapacitySharerToThis - heatCapacityToSharer;
var newSharerHeatCapacity = oldSharerHeatCapacity + heatCapacityToSharer - heatCapacitySharerToThis;
// Transfer of thermal energy (via changed heat capacity) between self and sharer.
if (!receiver.Immutable && newHeatCapacity > Atmospherics.MinimumHeatCapacity)
{
receiver.Temperature = ((oldHeatCapacity * receiver.Temperature) - (heatCapacityToSharer * tileReceiver.TemperatureArchived) + (heatCapacitySharerToThis * tileSharer.TemperatureArchived)) / newHeatCapacity;
}
if (!sharer.Immutable && newSharerHeatCapacity > Atmospherics.MinimumHeatCapacity)
{
sharer.Temperature = ((oldSharerHeatCapacity * sharer.Temperature) - (heatCapacitySharerToThis * tileSharer.TemperatureArchived) + (heatCapacityToSharer * tileReceiver.TemperatureArchived)) / newSharerHeatCapacity;
}
// Thermal energy of the system (self and sharer) is unchanged.
if (MathF.Abs(oldSharerHeatCapacity) > Atmospherics.MinimumHeatCapacity)
{
if (MathF.Abs(newSharerHeatCapacity / oldSharerHeatCapacity - 1) < 0.1)
{
TemperatureShare(tileReceiver, tileSharer, Atmospherics.OpenHeatTransferCoefficient);
}
}
}
if (!(temperatureDelta > Atmospherics.MinimumTemperatureToMove) &&
!(MathF.Abs(movedMoles) > Atmospherics.MinimumMolesDeltaToMove)) return 0f;
var moles = receiver.TotalMoles;
var theirMoles = sharer.TotalMoles;
return (tileReceiver.TemperatureArchived * (moles + movedMoles)) - (tileSharer.TemperatureArchived * (theirMoles - movedMoles)) * Atmospherics.R / receiver.Volume;
}
/// <summary>
/// Shares temperature between two mixtures, taking a conduction coefficient into account.
/// </summary>
public float TemperatureShare(TileAtmosphere tileReceiver, TileAtmosphere tileSharer, float conductionCoefficient)
{
if (tileReceiver.Air is not { } receiver || tileSharer.Air is not { } sharer)
return 0f;
var temperatureDelta = tileReceiver.TemperatureArchived - tileSharer.TemperatureArchived;
if (MathF.Abs(temperatureDelta) > Atmospherics.MinimumTemperatureDeltaToConsider)
{
var heatCapacity = GetHeatCapacityArchived(tileReceiver);
var sharerHeatCapacity = GetHeatCapacityArchived(tileSharer);
if (sharerHeatCapacity > Atmospherics.MinimumHeatCapacity && heatCapacity > Atmospherics.MinimumHeatCapacity)
{
var heat = conductionCoefficient * temperatureDelta * (heatCapacity * sharerHeatCapacity / (heatCapacity + sharerHeatCapacity));
if (!receiver.Immutable)
receiver.Temperature = MathF.Abs(MathF.Max(receiver.Temperature - heat / heatCapacity, Atmospherics.TCMB));
if (!sharer.Immutable)
sharer.Temperature = MathF.Abs(MathF.Max(sharer.Temperature + heat / sharerHeatCapacity, Atmospherics.TCMB));
}
}
return sharer.Temperature;
}
/// <summary>
/// Shares temperature between a gas mixture and an abstract sharer, taking a conduction coefficient into account.
/// </summary>
public float TemperatureShare(TileAtmosphere tileReceiver, float conductionCoefficient, float sharerTemperature, float sharerHeatCapacity)
{
if (tileReceiver.Air is not {} receiver)
return 0;
var temperatureDelta = tileReceiver.TemperatureArchived - sharerTemperature;
if (MathF.Abs(temperatureDelta) > Atmospherics.MinimumTemperatureDeltaToConsider)
{
var heatCapacity = GetHeatCapacityArchived(tileReceiver);
if (sharerHeatCapacity > Atmospherics.MinimumHeatCapacity && heatCapacity > Atmospherics.MinimumHeatCapacity)
{
var heat = conductionCoefficient * temperatureDelta * (heatCapacity * sharerHeatCapacity / (heatCapacity + sharerHeatCapacity));
if (!receiver.Immutable)
receiver.Temperature = MathF.Abs(MathF.Max(receiver.Temperature - heat / heatCapacity, Atmospherics.TCMB));
sharerTemperature = MathF.Abs(MathF.Max(sharerTemperature + heat / sharerHeatCapacity, Atmospherics.TCMB));
}
}
return sharerTemperature;
}
}
}