Predict dumping (#32394)

* Predict dumping

- This got soaped really fucking hard.
- Dumping is predicted, this required disposals to be predicte.d
- Disposals required mailing (because it's tightly coupled), and a smidge of other content systems.
- I also had to fix a compnetworkgenerator issue at the same time so it wouldn't mispredict.

* Fix a bunch of stuff

* nasty merge

* Some reviews

* Some more reviews while I stash

* Fix merge

* Fix merge

* Half of review

* Review

* re(h)f

* lizards

* feexes

* feex
This commit is contained in:
metalgearsloth
2025-04-19 16:20:40 +10:00
committed by GitHub
parent f1f431e720
commit 63dfd21b14
140 changed files with 1655 additions and 1858 deletions

View File

@@ -13,7 +13,13 @@ namespace Content.Shared.Climbing.Components
/// <summary>
/// The range from which this entity can be climbed.
/// </summary>
[DataField("range")] public float Range = SharedInteractionSystem.InteractionRange / 1.4f;
[DataField] public float Range = SharedInteractionSystem.InteractionRange;
/// <summary>
/// Can drag-drop / verb vaulting be done? Set to false if climbing is being handled manually.
/// </summary>
[DataField]
public bool Vaultable = true;
/// <summary>
/// The time it takes to climb onto the entity.

View File

@@ -149,7 +149,7 @@ public sealed partial class ClimbSystem : VirtualController
private void OnCanDragDropOn(EntityUid uid, ClimbableComponent component, ref CanDropTargetEvent args)
{
if (args.Handled)
if (args.Handled || !component.Vaultable)
return;
// If already climbing then don't show outlines.
@@ -261,7 +261,7 @@ public sealed partial class ClimbSystem : VirtualController
args.Handled = true;
}
private void Climb(EntityUid uid, EntityUid user, EntityUid climbable, bool silent = false, ClimbingComponent? climbing = null,
public void Climb(EntityUid uid, EntityUid user, EntityUid climbable, bool silent = false, ClimbingComponent? climbing = null,
PhysicsComponent? physics = null, FixturesComponent? fixtures = null, ClimbableComponent? comp = null)
{
if (!Resolve(uid, ref climbing, ref physics, ref fixtures, false))
@@ -456,6 +456,12 @@ public sealed partial class ClimbSystem : VirtualController
/// <param name="reason">The reason why it cant be dropped</param>
public bool CanVault(ClimbableComponent component, EntityUid user, EntityUid target, out string reason)
{
if (!component.Vaultable)
{
reason = string.Empty;
return false;
}
if (!_actionBlockerSystem.CanInteract(user, target))
{
reason = Loc.GetString("comp-climbable-cant-interact");

View File

@@ -2,34 +2,38 @@ using System.Text.RegularExpressions;
using Content.Shared.Tools;
using Content.Shared.Tools.Systems;
using Robust.Shared.GameStates;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Shared.Configurable
{
[RegisterComponent, NetworkedComponent]
/// <summary>
/// Configuration for mailing units.
/// </summary>
/// <remarks>
/// If you want a more detailed description ask the original coder.
/// </remarks>
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
public sealed partial class ConfigurationComponent : Component
{
[DataField("config")]
/// <summary>
/// Tags for mail unit routing.
/// </summary>
[DataField, AutoNetworkedField]
public Dictionary<string, string?> Config = new();
[DataField("qualityNeeded", customTypeSerializer: typeof(PrototypeIdSerializer<ToolQualityPrototype>))]
public string QualityNeeded = SharedToolSystem.PulseQuality;
/// <summary>
/// Quality to open up the configuration UI.
/// </summary>
[DataField]
public ProtoId<ToolQualityPrototype> QualityNeeded = SharedToolSystem.PulseQuality;
[DataField("validation")]
/// <summary>
/// Validate tags in <see cref="Config"/>.
/// </summary>
[DataField]
public Regex Validation = new("^[a-zA-Z0-9 ]*$", RegexOptions.Compiled);
[Serializable, NetSerializable]
public sealed class ConfigurationBoundUserInterfaceState : BoundUserInterfaceState
{
public Dictionary<string, string?> Config { get; }
public ConfigurationBoundUserInterfaceState(Dictionary<string, string?> config)
{
Config = config;
}
}
/// <summary>
/// Message data sent from client to server when the device configuration is updated.
/// </summary>

View File

@@ -0,0 +1,77 @@
using Content.Shared.Interaction;
using Content.Shared.Tools.Systems;
using Robust.Shared.Containers;
using static Content.Shared.Configurable.ConfigurationComponent;
namespace Content.Shared.Configurable;
/// <summary>
/// <see cref="ConfigurationComponent"/>
/// </summary>
public abstract class SharedConfigurationSystem : EntitySystem
{
[Dependency] private readonly SharedUserInterfaceSystem _uiSystem = default!;
[Dependency] private readonly SharedToolSystem _toolSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ConfigurationComponent, ConfigurationUpdatedMessage>(OnUpdate);
SubscribeLocalEvent<ConfigurationComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<ConfigurationComponent, ContainerIsInsertingAttemptEvent>(OnInsert);
}
private void OnInteractUsing(EntityUid uid, ConfigurationComponent component, InteractUsingEvent args)
{
// TODO use activatable ui system
if (args.Handled)
return;
if (!_toolSystem.HasQuality(args.Used, component.QualityNeeded))
return;
args.Handled = _uiSystem.TryOpenUi(uid, ConfigurationUiKey.Key, args.User);
}
private void OnUpdate(EntityUid uid, ConfigurationComponent component, ConfigurationUpdatedMessage args)
{
foreach (var key in component.Config.Keys)
{
var value = args.Config.GetValueOrDefault(key);
if (string.IsNullOrWhiteSpace(value) || component.Validation != null && !component.Validation.IsMatch(value))
continue;
component.Config[key] = value;
}
Dirty(uid, component);
var updatedEvent = new ConfigurationUpdatedEvent(component);
RaiseLocalEvent(uid, updatedEvent);
// TODO support float (spinbox) and enum (drop-down) configurations
// TODO support verbs.
}
private void OnInsert(EntityUid uid, ConfigurationComponent component, ContainerIsInsertingAttemptEvent args)
{
if (!_toolSystem.HasQuality(args.EntityUid, component.QualityNeeded))
return;
args.Cancel();
}
}
/// <summary>
/// Sent when configuration values got changes
/// </summary>
public sealed class ConfigurationUpdatedEvent : EntityEventArgs
{
public ConfigurationComponent Configuration;
public ConfigurationUpdatedEvent(ConfigurationComponent configuration)
{
Configuration = configuration;
}
}

View File

@@ -0,0 +1,8 @@
namespace Content.Shared.Containers;
/// <summary>
/// Sent before the insertion is made.
/// Allows preventing the insertion if any system on the entity should need to.
/// </summary>
[ByRefEvent]
public record struct BeforeThrowInsertEvent(EntityUid ThrownEntity, bool Cancelled = false);

View File

@@ -0,0 +1,125 @@
using Content.Shared.DeviceNetwork.Systems;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Shared.DeviceNetwork.Components
{
[RegisterComponent]
[Access(typeof(SharedDeviceNetworkSystem), typeof(DeviceNet))]
public sealed partial class DeviceNetworkComponent : Component
{
public enum DeviceNetIdDefaults
{
Private,
Wired,
Wireless,
Apc,
AtmosDevices,
Reserved = 100,
// Ids outside this enum may exist
// This exists to let yml use nice names instead of numbers
}
[DataField("deviceNetId")]
public DeviceNetIdDefaults NetIdEnum { get; set; }
public int DeviceNetId => (int) NetIdEnum;
/// <summary>
/// The frequency that this device is listening on.
/// </summary>
[DataField("receiveFrequency")]
public uint? ReceiveFrequency;
/// <summary>
/// frequency prototype. Used to select a default frequency to listen to on. Used when the map is
/// initialized.
/// </summary>
[DataField("receiveFrequencyId", customTypeSerializer: typeof(PrototypeIdSerializer<DeviceFrequencyPrototype>))]
public string? ReceiveFrequencyId;
/// <summary>
/// The frequency that this device going to try transmit on.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("transmitFrequency")]
public uint? TransmitFrequency;
/// <summary>
/// frequency prototype. Used to select a default frequency to transmit on. Used when the map is
/// initialized.
/// </summary>
[DataField("transmitFrequencyId", customTypeSerializer: typeof(PrototypeIdSerializer<DeviceFrequencyPrototype>))]
public string? TransmitFrequencyId;
/// <summary>
/// The address of the device, either on the network it is currently connected to or whatever address it
/// most recently used.
/// </summary>
[DataField("address")]
public string Address = string.Empty;
/// <summary>
/// If true, the address was customized and should be preserved across networks. If false, a randomly
/// generated address will be created whenever this device connects to a network.
/// </summary>
[DataField("customAddress")]
public bool CustomAddress = false;
/// <summary>
/// Prefix to prepend to any automatically generated addresses. Helps players to identify devices. This gets
/// localized.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("prefix")]
public string? Prefix;
/// <summary>
/// Whether the device should listen for all device messages, regardless of the intended recipient.
/// </summary>
[DataField("receiveAll")]
public bool ReceiveAll;
/// <summary>
/// If the device should show its address upon an examine. Useful for devices
/// that do not have a visible UI.
/// </summary>
[DataField("examinableAddress")]
public bool ExaminableAddress;
/// <summary>
/// Whether the device should attempt to join the network on map init.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("autoConnect")]
public bool AutoConnect = true;
/// <summary>
/// Whether to send the broadcast recipients list to the sender so it can be filtered.
/// <see cref="DeviceListSystem"/>
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("sendBroadcastAttemptEvent")]
public bool SendBroadcastAttemptEvent = false;
/// <summary>
/// Whether this device's address can be saved to device-lists
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("savableAddress")]
public bool SavableAddress = true;
/// <summary>
/// A list of device-lists that this device is on.
/// </summary>
[DataField]
[Access(typeof(SharedDeviceListSystem))]
public HashSet<EntityUid> DeviceLists = new();
/// <summary>
/// A list of configurators that this device is on.
/// </summary>
[DataField]
[Access(typeof(SharedNetworkConfiguratorSystem))]
public HashSet<EntityUid> Configurators = new();
}
}

View File

@@ -0,0 +1,238 @@
using Robust.Shared.Random;
using Content.Shared.DeviceNetwork.Components;
namespace Content.Shared.DeviceNetwork;
/// <summary>
/// Data class for storing and retrieving information about devices connected to a device network.
/// </summary>
/// <remarks>
/// This basically just makes <see cref="DeviceNetworkComponent"/> accessible via their addresses and frequencies on
/// some network.
/// </remarks>
public sealed class DeviceNet
{
/// <summary>
/// Devices, mapped by their "Address", which is just an int that gets converted to Hex for displaying to users.
/// This dictionary contains all devices connected to this network, though they may not be listening to any
/// specific frequency.
/// </summary>
public readonly Dictionary<string, DeviceNetworkComponent> Devices = new();
/// <summary>
/// Devices listening on a given frequency.
/// </summary>
public readonly Dictionary<uint, HashSet<DeviceNetworkComponent>> ListeningDevices = new();
/// <summary>
/// Devices listening to all packets on a given frequency, regardless of the intended recipient.
/// </summary>
public readonly Dictionary<uint, HashSet<DeviceNetworkComponent>> ReceiveAllDevices = new();
private readonly IRobustRandom _random;
public readonly int NetId;
public DeviceNet(int netId, IRobustRandom random)
{
_random = random;
NetId = netId;
}
/// <summary>
/// Add a device to the network.
/// </summary>
public bool Add(DeviceNetworkComponent device)
{
if (device.CustomAddress)
{
// Only add if the device's existing address is available.
if (!Devices.TryAdd(device.Address, device))
return false;
}
else
{
// Randomly generate a new address if the existing random one is invalid. Otherwise, keep the existing address
if (string.IsNullOrWhiteSpace(device.Address) || Devices.ContainsKey(device.Address))
device.Address = GenerateValidAddress(device.Prefix);
Devices[device.Address] = device;
}
if (device.ReceiveFrequency is not uint freq)
return true;
if (!ListeningDevices.TryGetValue(freq, out var devices))
ListeningDevices[freq] = devices = new();
devices.Add(device);
if (!device.ReceiveAll)
return true;
if (!ReceiveAllDevices.TryGetValue(freq, out var receiveAlldevices))
ReceiveAllDevices[freq] = receiveAlldevices = new();
receiveAlldevices.Add(device);
return true;
}
/// <summary>
/// Remove a device from the network.
/// </summary>
public bool Remove(DeviceNetworkComponent device)
{
if (device.Address == null || !Devices.Remove(device.Address))
return false;
if (device.ReceiveFrequency is not uint freq)
return true;
if (ListeningDevices.TryGetValue(freq, out var listening))
{
listening.Remove(device);
if (listening.Count == 0)
ListeningDevices.Remove(freq);
}
if (device.ReceiveAll && ReceiveAllDevices.TryGetValue(freq, out var receiveAll))
{
receiveAll.Remove(device);
if (receiveAll.Count == 0)
ListeningDevices.Remove(freq);
}
return true;
}
/// <summary>
/// Give an existing device a new randomly generated address. Useful if the device's address prefix was updated
/// and they want a new address to reflect that, or something like that.
/// </summary>
public bool RandomizeAddress(string oldAddress, string? prefix = null)
{
if (!Devices.Remove(oldAddress, out var device))
return false;
device.Address = GenerateValidAddress(prefix ?? device.Prefix);
device.CustomAddress = false;
Devices[device.Address] = device;
return true;
}
/// <summary>
/// Update the address of an existing device.
/// </summary>
public bool UpdateAddress(string oldAddress, string newAddress)
{
if (Devices.ContainsKey(newAddress))
return false;
if (!Devices.Remove(oldAddress, out var device))
return false;
device.Address = newAddress;
device.CustomAddress = true;
Devices[newAddress] = device;
return true;
}
/// <summary>
/// Make an existing network device listen to a new frequency.
/// </summary>
public bool UpdateReceiveFrequency(string address, uint? newFrequency)
{
if (!Devices.TryGetValue(address, out var device))
return false;
if (device.ReceiveFrequency == newFrequency)
return true;
if (device.ReceiveFrequency is uint freq)
{
if (ListeningDevices.TryGetValue(freq, out var listening))
{
listening.Remove(device);
if (listening.Count == 0)
ListeningDevices.Remove(freq);
}
if (device.ReceiveAll && ReceiveAllDevices.TryGetValue(freq, out var receiveAll))
{
receiveAll.Remove(device);
if (receiveAll.Count == 0)
ListeningDevices.Remove(freq);
}
}
device.ReceiveFrequency = newFrequency;
if (newFrequency == null)
return true;
if (!ListeningDevices.TryGetValue(newFrequency.Value, out var devices))
ListeningDevices[newFrequency.Value] = devices = new();
devices.Add(device);
if (!device.ReceiveAll)
return true;
if (!ReceiveAllDevices.TryGetValue(newFrequency.Value, out var receiveAlldevices))
ReceiveAllDevices[newFrequency.Value] = receiveAlldevices = new();
receiveAlldevices.Add(device);
return true;
}
/// <summary>
/// Make an existing network device listen to a new frequency.
/// </summary>
public bool UpdateReceiveAll(string address, bool receiveAll)
{
if (!Devices.TryGetValue(address, out var device))
return false;
if (device.ReceiveAll == receiveAll)
return true;
device.ReceiveAll = receiveAll;
if (device.ReceiveFrequency is not uint freq)
return true;
// remove or add to set of listening devices
HashSet<DeviceNetworkComponent>? devices;
if (receiveAll)
{
if (!ReceiveAllDevices.TryGetValue(freq, out devices))
ReceiveAllDevices[freq] = devices = new();
devices.Add(device);
}
else if (ReceiveAllDevices.TryGetValue(freq, out devices))
{
devices.Remove(device);
if (devices.Count == 0)
ReceiveAllDevices.Remove(freq);
}
return true;
}
/// <summary>
/// Generates a valid address by randomly generating one and checking if it already exists on the network.
/// </summary>
private string GenerateValidAddress(string? prefix)
{
prefix = string.IsNullOrWhiteSpace(prefix) ? null : Loc.GetString(prefix);
string address;
do
{
var num = _random.Next();
address = $"{prefix}{num >> 16:X4}-{num & 0xFFFF:X4}";
}
while (Devices.ContainsKey(address));
return address;
}
}

View File

@@ -0,0 +1,79 @@
using Robust.Shared.Utility;
using Content.Shared.DeviceNetwork.Components;
namespace Content.Shared.DeviceNetwork
{
/// <summary>
/// A collection of constants to help with using device networks
/// </summary>
public static class DeviceNetworkConstants
{
/// <summary>
/// Used by logic gates to transmit the state of their ports
/// </summary>
public const string LogicState = "logic_state";
#region Commands
/// <summary>
/// The key for command names
/// E.g. [DeviceNetworkConstants.Command] = "ping"
/// </summary>
public const string Command = "command";
/// <summary>
/// The command for setting a devices state
/// E.g. to turn a light on or off
/// </summary>
public const string CmdSetState = "set_state";
/// <summary>
/// The command for a device that just updated its state
/// E.g. suit sensors broadcasting owners vitals state
/// </summary>
public const string CmdUpdatedState = "updated_state";
#endregion
#region SetState
/// <summary>
/// Used with the <see cref="CmdSetState"/> command to turn a device on or off
/// </summary>
public const string StateEnabled = "state_enabled";
#endregion
#region DisplayHelpers
/// <summary>
/// Converts the unsigned int to string and inserts a number before the last digit
/// </summary>
public static string FrequencyToString(this uint frequency)
{
var result = frequency.ToString();
if (result.Length <= 2)
return result + ".0";
return result.Insert(result.Length - 1, ".");
}
/// <summary>
/// Either returns the localized name representation of the corresponding <see cref="DeviceNetworkComponent.DeviceNetIdDefaults"/>
/// or converts the id to string
/// </summary>
public static string DeviceNetIdToLocalizedName(this int id)
{
if (!Enum.IsDefined(typeof(DeviceNetworkComponent.DeviceNetIdDefaults), id))
return id.ToString();
var result = ((DeviceNetworkComponent.DeviceNetIdDefaults) id).ToString();
var resultKebab = "device-net-id-" + CaseConversion.PascalToKebab(result);
return !Loc.TryGetString(resultKebab, out var name) ? result : name;
}
#endregion
}
}

View File

@@ -0,0 +1,17 @@
using Content.Shared.DeviceNetwork.Components;
namespace Content.Shared.DeviceNetwork.Events;
/// <summary>
/// Sent to the sending entity before broadcasting network packets to recipients
/// </summary>
public sealed class BeforeBroadcastAttemptEvent : CancellableEntityEventArgs
{
public readonly IReadOnlySet<DeviceNetworkComponent> Recipients;
public HashSet<DeviceNetworkComponent>? ModifiedRecipients;
public BeforeBroadcastAttemptEvent(IReadOnlySet<DeviceNetworkComponent> recipients)
{
Recipients = recipients;
}
}

View File

@@ -0,0 +1,35 @@
using System.Numerics;
namespace Content.Shared.DeviceNetwork.Events;
/// <summary>
/// Event raised before a device network packet is send.
/// Subscribed to by other systems to prevent the packet from being sent.
/// </summary>
public sealed class BeforePacketSentEvent : CancellableEntityEventArgs
{
/// <summary>
/// The EntityUid of the entity the packet was sent from.
/// </summary>
public readonly EntityUid Sender;
public readonly TransformComponent SenderTransform;
/// <summary>
/// The senders current position in world coordinates.
/// </summary>
public readonly Vector2 SenderPosition;
/// <summary>
/// The network the packet will be sent to.
/// </summary>
public readonly string NetworkId;
public BeforePacketSentEvent(EntityUid sender, TransformComponent xform, Vector2 senderPosition, string networkId)
{
Sender = sender;
SenderTransform = xform;
SenderPosition = senderPosition;
NetworkId = networkId;
}
}

View File

@@ -0,0 +1,47 @@
namespace Content.Shared.DeviceNetwork.Events;
/// <summary>
/// Event raised when a device network packet gets sent.
/// </summary>
public sealed class DeviceNetworkPacketEvent : EntityEventArgs
{
/// <summary>
/// The id of the network that this packet is being sent on.
/// </summary>
public int NetId;
/// <summary>
/// The frequency the packet is sent on.
/// </summary>
public readonly uint Frequency;
/// <summary>
/// Address of the intended recipient. Null if the message was broadcast.
/// </summary>
public string? Address;
/// <summary>
/// The device network address of the sending entity.
/// </summary>
public readonly string SenderAddress;
/// <summary>
/// The entity that sent the packet.
/// </summary>
public EntityUid Sender;
/// <summary>
/// The data that is being sent.
/// </summary>
public readonly NetworkPayload Data;
public DeviceNetworkPacketEvent(int netId, string? address, uint frequency, string senderAddress, EntityUid sender, NetworkPayload data)
{
NetId = netId;
Address = address;
Frequency = frequency;
SenderAddress = senderAddress;
Sender = sender;
Data = data;
}
}

View File

@@ -0,0 +1,25 @@
using Content.Shared.DeviceNetwork.Components;
namespace Content.Shared.DeviceNetwork.Systems;
public abstract class SharedDeviceNetworkSystem : EntitySystem
{
/// <summary>
/// Sends the given payload as a device network packet to the entity with the given address and frequency.
/// Addresses are given to the DeviceNetworkComponent of an entity when connecting.
/// </summary>
/// <param name="uid">The EntityUid of the sending entity</param>
/// <param name="address">The address of the entity that the packet gets sent to. If null, the message is broadcast to all devices on that frequency (except the sender)</param>
/// <param name="frequency">The frequency to send on</param>
/// <param name="data">The data to be sent</param>
/// <returns>Returns true when the packet was successfully enqueued.</returns>
public virtual bool QueuePacket(EntityUid uid,
string? address,
NetworkPayload data,
uint? frequency = null,
int? network = null,
DeviceNetworkComponent? device = null)
{
return false;
}
}

View File

@@ -0,0 +1,28 @@
using Content.Shared.Disposal.Mailing;
using Robust.Shared.GameStates;
namespace Content.Shared.Disposal.Components;
[Access(typeof(SharedMailingUnitSystem))]
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState(true)]
public sealed partial class MailingUnitComponent : Component
{
/// <summary>
/// List of targets the mailing unit can send to.
/// Each target is just a disposal routing tag
/// </summary>
[DataField, AutoNetworkedField]
public List<string> TargetList = new();
/// <summary>
/// The target that gets attached to the disposal holders tag list on flush
/// </summary>
[DataField, AutoNetworkedField]
public string? Target;
/// <summary>
/// The tag for this mailing unit
/// </summary>
[DataField, AutoNetworkedField]
public string? Tag;
}

View File

@@ -0,0 +1,174 @@
using Content.Shared.Configurable;
using Content.Shared.DeviceNetwork;
using Content.Shared.DeviceNetwork.Components;
using Content.Shared.DeviceNetwork.Events;
using Content.Shared.DeviceNetwork.Systems;
using Content.Shared.Disposal.Components;
using Content.Shared.Disposal.Unit;
using Content.Shared.Disposal.Unit.Events;
using Content.Shared.Interaction;
using Content.Shared.Power.EntitySystems;
using Robust.Shared.Player;
namespace Content.Shared.Disposal.Mailing;
public abstract class SharedMailingUnitSystem : EntitySystem
{
[Dependency] private readonly SharedDeviceNetworkSystem _deviceNetworkSystem = default!;
[Dependency] private readonly SharedPowerReceiverSystem _power = default!;
[Dependency] protected readonly SharedUserInterfaceSystem UserInterfaceSystem = default!;
private const string MailTag = "mail";
private const string TagConfigurationKey = "tag";
private const string NetTag = "tag";
private const string NetSrc = "src";
private const string NetTarget = "target";
private const string NetCmdSent = "mail_sent";
private const string NetCmdRequest = "get_mailer_tag";
private const string NetCmdResponse = "mailer_tag";
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<MailingUnitComponent, ComponentInit>(OnComponentInit);
SubscribeLocalEvent<MailingUnitComponent, DeviceNetworkPacketEvent>(OnPacketReceived);
SubscribeLocalEvent<MailingUnitComponent, BeforeDisposalFlushEvent>(OnBeforeFlush);
SubscribeLocalEvent<MailingUnitComponent, ConfigurationUpdatedEvent>(OnConfigurationUpdated);
SubscribeLocalEvent<MailingUnitComponent, ActivateInWorldEvent>(HandleActivate, before: new[] { typeof(SharedDisposalUnitSystem) });
SubscribeLocalEvent<MailingUnitComponent, TargetSelectedMessage>(OnTargetSelected);
}
private void OnComponentInit(EntityUid uid, MailingUnitComponent component, ComponentInit args)
{
UpdateTargetList(uid, component);
}
private void OnPacketReceived(EntityUid uid, MailingUnitComponent component, DeviceNetworkPacketEvent args)
{
if (!args.Data.TryGetValue(DeviceNetworkConstants.Command, out string? command) || !_power.IsPowered(uid))
return;
switch (command)
{
case NetCmdRequest:
SendTagRequestResponse(uid, args, component.Tag);
break;
case NetCmdResponse when args.Data.TryGetValue(NetTag, out string? tag):
//Add the received tag request response to the list of targets
component.TargetList.Add(tag);
Dirty(uid, component);
break;
}
}
/// <summary>
/// Sends the given tag as a response to a <see cref="NetCmdRequest"/> if it's not null
/// </summary>
private void SendTagRequestResponse(EntityUid uid, DeviceNetworkPacketEvent args, string? tag)
{
if (tag == null)
return;
var payload = new NetworkPayload
{
[DeviceNetworkConstants.Command] = NetCmdResponse,
[NetTag] = tag
};
_deviceNetworkSystem.QueuePacket(uid, args.Address, payload, args.Frequency);
}
/// <summary>
/// Prevents the unit from flushing if no target is selected
/// </summary>
private void OnBeforeFlush(EntityUid uid, MailingUnitComponent component, BeforeDisposalFlushEvent args)
{
if (string.IsNullOrEmpty(component.Target))
{
args.Cancel();
return;
}
Dirty(uid, component);
args.Tags.Add(MailTag);
args.Tags.Add(component.Target);
BroadcastSentMessage(uid, component);
}
/// <summary>
/// Broadcast that a mail was sent including the src and target tags
/// </summary>
private void BroadcastSentMessage(EntityUid uid, MailingUnitComponent component, DeviceNetworkComponent? device = null)
{
if (string.IsNullOrEmpty(component.Tag) || string.IsNullOrEmpty(component.Target) || !Resolve(uid, ref device))
return;
var payload = new NetworkPayload
{
[DeviceNetworkConstants.Command] = NetCmdSent,
[NetSrc] = component.Tag,
[NetTarget] = component.Target
};
_deviceNetworkSystem.QueuePacket(uid, null, payload, null, null, device);
}
/// <summary>
/// Clears the units target list and broadcasts a <see cref="NetCmdRequest"/>.
/// The target list will then get populated with <see cref="NetCmdResponse"/> responses from all active mailing units on the same grid
/// </summary>
private void UpdateTargetList(EntityUid uid, MailingUnitComponent component, DeviceNetworkComponent? device = null)
{
if (!Resolve(uid, ref device, false))
return;
var payload = new NetworkPayload
{
[DeviceNetworkConstants.Command] = NetCmdRequest
};
component.TargetList.Clear();
_deviceNetworkSystem.QueuePacket(uid, null, payload, null, null, device);
}
/// <summary>
/// Gets called when the units tag got updated
/// </summary>
private void OnConfigurationUpdated(EntityUid uid, MailingUnitComponent component, ConfigurationUpdatedEvent args)
{
var configuration = args.Configuration.Config;
if (!configuration.ContainsKey(TagConfigurationKey) || configuration[TagConfigurationKey] == string.Empty)
{
component.Tag = null;
return;
}
component.Tag = configuration[TagConfigurationKey];
Dirty(uid, component);
}
private void HandleActivate(EntityUid uid, MailingUnitComponent component, ActivateInWorldEvent args)
{
if (args.Handled || !args.Complex)
return;
if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor))
{
return;
}
args.Handled = true;
UpdateTargetList(uid, component);
UserInterfaceSystem.OpenUi(uid, MailingUnitUiKey.Key, actor.PlayerSession);
}
private void OnTargetSelected(EntityUid uid, MailingUnitComponent component, TargetSelectedMessage args)
{
component.Target = args.Target;
Dirty(uid, component);
}
}

View File

@@ -1,45 +0,0 @@
using Content.Shared.Disposal.Components;
using Robust.Shared.Serialization;
namespace Content.Shared.Disposal;
[Serializable, NetSerializable]
public sealed class MailingUnitBoundUserInterfaceState : BoundUserInterfaceState, IEquatable<MailingUnitBoundUserInterfaceState>
{
public string? Target;
public List<string> TargetList;
public string? Tag;
public SharedDisposalUnitComponent.DisposalUnitBoundUserInterfaceState DisposalState;
public MailingUnitBoundUserInterfaceState(SharedDisposalUnitComponent.DisposalUnitBoundUserInterfaceState disposalState, string? target, List<string> targetList, string? tag)
{
DisposalState = disposalState;
Target = target;
TargetList = targetList;
Tag = tag;
}
public bool Equals(MailingUnitBoundUserInterfaceState? other)
{
if (other is null)
return false;
if (ReferenceEquals(this, other))
return true;
return DisposalState.Equals(other.DisposalState)
&& Target == other.Target
&& TargetList.Equals(other.TargetList)
&& Tag == other.Tag;
}
public override bool Equals(object? other)
{
if (other is MailingUnitBoundUserInterfaceState otherState)
return Equals(otherState);
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}

View File

@@ -1,162 +0,0 @@
using System.Diagnostics.CodeAnalysis;
using Content.Shared.Body.Components;
using Content.Shared.Disposal.Components;
using Content.Shared.DoAfter;
using Content.Shared.DragDrop;
using Content.Shared.Emag.Systems;
using Content.Shared.Item;
using Content.Shared.Throwing;
using Content.Shared.Whitelist;
using Robust.Shared.Audio;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
namespace Content.Shared.Disposal;
[Serializable, NetSerializable]
public sealed partial class DisposalDoAfterEvent : SimpleDoAfterEvent
{
}
public abstract class SharedDisposalUnitSystem : EntitySystem
{
[Dependency] protected readonly IGameTiming GameTiming = default!;
[Dependency] protected readonly EmagSystem _emag = default!;
[Dependency] protected readonly MetaDataSystem Metadata = default!;
[Dependency] protected readonly SharedJointSystem Joints = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
protected static TimeSpan ExitAttemptDelay = TimeSpan.FromSeconds(0.5);
// Percentage
public const float PressurePerSecond = 0.05f;
public abstract bool HasDisposals([NotNullWhen(true)] EntityUid? uid);
public abstract bool ResolveDisposals(EntityUid uid, [NotNullWhen(true)] ref SharedDisposalUnitComponent? component);
/// <summary>
/// Gets the current pressure state of a disposals unit.
/// </summary>
/// <param name="uid"></param>
/// <param name="component"></param>
/// <param name="metadata"></param>
/// <returns></returns>
public DisposalsPressureState GetState(EntityUid uid, SharedDisposalUnitComponent component, MetaDataComponent? metadata = null)
{
var nextPressure = Metadata.GetPauseTime(uid, metadata) + component.NextPressurized - GameTiming.CurTime;
var pressurizeTime = 1f / PressurePerSecond;
var pressurizeDuration = pressurizeTime - component.FlushDelay.TotalSeconds;
if (nextPressure.TotalSeconds > pressurizeDuration)
{
return DisposalsPressureState.Flushed;
}
if (nextPressure > TimeSpan.Zero)
{
return DisposalsPressureState.Pressurizing;
}
return DisposalsPressureState.Ready;
}
public float GetPressure(EntityUid uid, SharedDisposalUnitComponent component, MetaDataComponent? metadata = null)
{
if (!Resolve(uid, ref metadata))
return 0f;
var pauseTime = Metadata.GetPauseTime(uid, metadata);
return MathF.Min(1f,
(float) (GameTiming.CurTime - pauseTime - component.NextPressurized).TotalSeconds / PressurePerSecond);
}
protected void OnPreventCollide(EntityUid uid, SharedDisposalUnitComponent component,
ref PreventCollideEvent args)
{
var otherBody = args.OtherEntity;
// Items dropped shouldn't collide but items thrown should
if (HasComp<ItemComponent>(otherBody) && !HasComp<ThrownItemComponent>(otherBody))
{
args.Cancelled = true;
return;
}
if (component.RecentlyEjected.Contains(otherBody))
{
args.Cancelled = true;
}
}
protected void OnCanDragDropOn(EntityUid uid, SharedDisposalUnitComponent component, ref CanDropTargetEvent args)
{
if (args.Handled)
return;
args.CanDrop = CanInsert(uid, component, args.Dragged);
args.Handled = true;
}
protected void OnEmagged(EntityUid uid, SharedDisposalUnitComponent component, ref GotEmaggedEvent args)
{
if (!_emag.CompareFlag(args.Type, EmagType.Interaction))
return;
if (component.DisablePressure == true)
return;
component.DisablePressure = true;
args.Handled = true;
}
public virtual bool CanInsert(EntityUid uid, SharedDisposalUnitComponent component, EntityUid entity)
{
if (!Transform(uid).Anchored)
return false;
var storable = HasComp<ItemComponent>(entity);
if (!storable && !HasComp<BodyComponent>(entity))
return false;
if (_whitelistSystem.IsBlacklistPass(component.Blacklist, entity) ||
_whitelistSystem.IsWhitelistFail(component.Whitelist, entity))
return false;
if (TryComp<PhysicsComponent>(entity, out var physics) && (physics.CanCollide) || storable)
return true;
else
return false;
}
public abstract void DoInsertDisposalUnit(EntityUid uid, EntityUid toInsert, EntityUid user, SharedDisposalUnitComponent? disposal = null);
[Serializable, NetSerializable]
protected sealed class DisposalUnitComponentState : ComponentState
{
public SoundSpecifier? FlushSound;
public DisposalsPressureState State;
public TimeSpan NextPressurized;
public TimeSpan AutomaticEngageTime;
public TimeSpan? NextFlush;
public bool Powered;
public bool Engaged;
public List<NetEntity> RecentlyEjected;
public DisposalUnitComponentState(SoundSpecifier? flushSound, DisposalsPressureState state, TimeSpan nextPressurized, TimeSpan automaticEngageTime, TimeSpan? nextFlush, bool powered, bool engaged, List<NetEntity> recentlyEjected)
{
FlushSound = flushSound;
State = state;
NextPressurized = nextPressurized;
AutomaticEngageTime = automaticEngageTime;
NextFlush = nextFlush;
Powered = powered;
Engaged = engaged;
RecentlyEjected = recentlyEjected;
}
}
}

View File

@@ -0,0 +1,12 @@
using Content.Shared.Disposal.Unit;
using Robust.Shared.Prototypes;
namespace Content.Shared.Disposal.Tube;
[RegisterComponent]
[Access(typeof(SharedDisposalTubeSystem), typeof(SharedDisposalUnitSystem))]
public sealed partial class DisposalEntryComponent : Component
{
[DataField]
public EntProtoId HolderPrototypeId = "DisposalHolder";
}

View File

@@ -0,0 +1,10 @@
namespace Content.Shared.Disposal.Unit.Events;
/// <summary>
/// Sent before the disposal unit flushes it's contents.
/// Allows adding tags for sorting and preventing the disposal unit from flushing.
/// </summary>
public sealed class BeforeDisposalFlushEvent : CancellableEntityEventArgs
{
public readonly List<string> Tags = new();
}

View File

@@ -1,3 +1,4 @@
using Content.Shared.Atmos;
using Robust.Shared.Audio;
using Content.Shared.Whitelist;
using Robust.Shared.Containers;
@@ -7,15 +8,24 @@ using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom;
namespace Content.Shared.Disposal.Components;
[NetworkedComponent]
public abstract partial class SharedDisposalUnitComponent : Component
/// <summary>
/// Takes in entities and flushes them out to attached disposals tubes after a timer.
/// </summary>
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState(true)]
public sealed partial class DisposalUnitComponent : Component
{
public const string ContainerId = "disposals";
/// <summary>
/// Air contained in the disposal unit.
/// </summary>
[DataField]
public GasMixture Air = new(Atmospherics.CellVolume);
/// <summary>
/// Sounds played upon the unit flushing.
/// </summary>
[ViewVariables(VVAccess.ReadWrite), DataField("soundFlush")]
[DataField("soundFlush"), AutoNetworkedField]
public SoundSpecifier? FlushSound = new SoundPathSpecifier("/Audio/Machines/disposalflush.ogg");
/// <summary>
@@ -39,20 +49,13 @@ public abstract partial class SharedDisposalUnitComponent : Component
/// <summary>
/// State for this disposals unit.
/// </summary>
[DataField]
[DataField, AutoNetworkedField]
public DisposalsPressureState State;
// TODO: Just make this use vaulting.
/// <summary>
/// We'll track whatever just left disposals so we know what collision we need to ignore until they stop intersecting our BB.
/// </summary>
[ViewVariables, DataField]
public List<EntityUid> RecentlyEjected = new();
/// <summary>
/// Next time the disposal unit will be pressurized.
/// </summary>
[DataField(customTypeSerializer:typeof(TimeOffsetSerializer))]
[DataField(customTypeSerializer: typeof(TimeOffsetSerializer)), AutoNetworkedField]
public TimeSpan NextPressurized = TimeSpan.Zero;
/// <summary>
@@ -70,26 +73,24 @@ public abstract partial class SharedDisposalUnitComponent : Component
/// <summary>
/// Removes the pressure requirement for flushing.
/// </summary>
[DataField, ViewVariables(VVAccess.ReadWrite)]
[DataField]
public bool DisablePressure;
/// <summary>
/// Last time that an entity tried to exit this disposal unit.
/// </summary>
[ViewVariables]
[DataField, AutoNetworkedField]
public TimeSpan LastExitAttempt;
[DataField]
public bool AutomaticEngage = true;
[ViewVariables(VVAccess.ReadWrite)]
[DataField]
[DataField, AutoNetworkedField]
public TimeSpan AutomaticEngageTime = TimeSpan.FromSeconds(30);
/// <summary>
/// Delay from trying to enter disposals ourselves.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField]
public float EntryDelay = 0.5f;
@@ -104,20 +105,16 @@ public abstract partial class SharedDisposalUnitComponent : Component
/// </summary>
[ViewVariables] public Container Container = default!;
// TODO: Network power shit instead fam.
[ViewVariables, DataField]
public bool Powered;
/// <summary>
/// Was the disposals unit engaged for a manual flush.
/// </summary>
[ViewVariables(VVAccess.ReadWrite), DataField]
[DataField, AutoNetworkedField]
public bool Engaged;
/// <summary>
/// Next time this unit will flush. Is the lesser of <see cref="FlushDelay"/> and <see cref="AutomaticEngageTime"/>
/// </summary>
[ViewVariables, DataField(customTypeSerializer:typeof(TimeOffsetSerializer))]
[DataField(customTypeSerializer: typeof(TimeOffsetSerializer)), AutoNetworkedField]
public TimeSpan? NextFlush;
[Serializable, NetSerializable]
@@ -162,37 +159,6 @@ public abstract partial class SharedDisposalUnitComponent : Component
Power
}
[Serializable, NetSerializable]
public sealed class DisposalUnitBoundUserInterfaceState : BoundUserInterfaceState, IEquatable<DisposalUnitBoundUserInterfaceState>
{
public readonly string UnitName;
public readonly string UnitState;
public readonly TimeSpan FullPressureTime;
public readonly bool Powered;
public readonly bool Engaged;
public DisposalUnitBoundUserInterfaceState(string unitName, string unitState, TimeSpan fullPressureTime, bool powered,
bool engaged)
{
UnitName = unitName;
UnitState = unitState;
FullPressureTime = fullPressureTime;
Powered = powered;
Engaged = engaged;
}
public bool Equals(DisposalUnitBoundUserInterfaceState? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return UnitName == other.UnitName &&
UnitState == other.UnitState &&
Powered == other.Powered &&
Engaged == other.Engaged &&
FullPressureTime.Equals(other.FullPressureTime);
}
}
/// <summary>
/// Message data sent from client to server when a disposal unit ui button is pressed.
/// </summary>

View File

@@ -0,0 +1,14 @@
using Content.Shared.Disposal.Components;
namespace Content.Shared.Disposal.Unit;
public abstract class SharedDisposalTubeSystem : EntitySystem
{
public virtual bool TryInsert(EntityUid uid,
DisposalUnitComponent from,
IEnumerable<string>? tags = default,
Tube.DisposalEntryComponent? entry = null)
{
return false;
}
}

View File

@@ -0,0 +1,788 @@
using System.Linq;
using Content.Shared.ActionBlocker;
using Content.Shared.Administration.Logs;
using Content.Shared.Body.Components;
using Content.Shared.Climbing.Systems;
using Content.Shared.Containers;
using Content.Shared.Database;
using Content.Shared.Disposal.Components;
using Content.Shared.Disposal.Unit.Events;
using Content.Shared.DoAfter;
using Content.Shared.DragDrop;
using Content.Shared.Emag.Systems;
using Content.Shared.Hands.Components;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.IdentityManagement;
using Content.Shared.Interaction;
using Content.Shared.Item;
using Content.Shared.Movement.Events;
using Content.Shared.Popups;
using Content.Shared.Power;
using Content.Shared.Power.EntitySystems;
using Content.Shared.Throwing;
using Content.Shared.Verbs;
using Content.Shared.Whitelist;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Containers;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
namespace Content.Shared.Disposal.Unit;
[Serializable, NetSerializable]
public sealed partial class DisposalDoAfterEvent : SimpleDoAfterEvent
{
}
public abstract class SharedDisposalUnitSystem : EntitySystem
{
[Dependency] protected readonly ActionBlockerSystem ActionBlockerSystem = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
[Dependency] protected readonly MetaDataSystem Metadata = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] protected readonly SharedAudioSystem Audio = default!;
[Dependency] protected readonly IGameTiming GameTiming = default!;
[Dependency] private readonly ISharedAdminLogManager _adminLog = default!;
[Dependency] private readonly ClimbSystem _climb = default!;
[Dependency] protected readonly SharedContainerSystem Containers = default!;
[Dependency] protected readonly SharedJointSystem Joints = default!;
[Dependency] private readonly SharedPowerReceiverSystem _power = default!;
[Dependency] private readonly SharedDisposalTubeSystem _disposalTubeSystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfterSystem = default!;
[Dependency] private readonly SharedHandsSystem _handsSystem = default!;
[Dependency] protected readonly SharedTransformSystem TransformSystem = default!;
[Dependency] private readonly SharedUserInterfaceSystem _ui = default!;
[Dependency] private readonly SharedMapSystem _map = default!;
protected static TimeSpan ExitAttemptDelay = TimeSpan.FromSeconds(0.5);
// Percentage
public const float PressurePerSecond = 0.05f;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<DisposalUnitComponent, PreventCollideEvent>(OnPreventCollide);
SubscribeLocalEvent<DisposalUnitComponent, CanDropTargetEvent>(OnCanDragDropOn);
SubscribeLocalEvent<DisposalUnitComponent, GetVerbsEvent<InteractionVerb>>(AddInsertVerb);
SubscribeLocalEvent<DisposalUnitComponent, GetVerbsEvent<AlternativeVerb>>(AddDisposalAltVerbs);
SubscribeLocalEvent<DisposalUnitComponent, GetVerbsEvent<Verb>>(AddClimbInsideVerb);
SubscribeLocalEvent<DisposalUnitComponent, DisposalDoAfterEvent>(OnDoAfter);
SubscribeLocalEvent<DisposalUnitComponent, BeforeThrowInsertEvent>(OnThrowInsert);
SubscribeLocalEvent<DisposalUnitComponent, DisposalUnitComponent.UiButtonPressedMessage>(OnUiButtonPressed);
SubscribeLocalEvent<DisposalUnitComponent, GotEmaggedEvent>(OnEmagged);
SubscribeLocalEvent<DisposalUnitComponent, AnchorStateChangedEvent>(OnAnchorChanged);
SubscribeLocalEvent<DisposalUnitComponent, PowerChangedEvent>(OnPowerChange);
SubscribeLocalEvent<DisposalUnitComponent, ComponentInit>(OnDisposalInit);
SubscribeLocalEvent<DisposalUnitComponent, ActivateInWorldEvent>(OnActivate);
SubscribeLocalEvent<DisposalUnitComponent, AfterInteractUsingEvent>(OnAfterInteractUsing);
SubscribeLocalEvent<DisposalUnitComponent, DragDropTargetEvent>(OnDragDropOn);
SubscribeLocalEvent<DisposalUnitComponent, ContainerRelayMovementEntityEvent>(OnMovement);
}
private void AddDisposalAltVerbs(Entity<DisposalUnitComponent> ent, ref GetVerbsEvent<AlternativeVerb> args)
{
if (!args.CanAccess || !args.CanInteract)
return;
var uid = ent.Owner;
var component = ent.Comp;
// Behavior for if the disposals bin has items in it
if (component.Container.ContainedEntities.Count > 0)
{
// Verbs to flush the unit
AlternativeVerb flushVerb = new()
{
Act = () => ManualEngage(uid, component),
Text = Loc.GetString("disposal-flush-verb-get-data-text"),
Icon = new SpriteSpecifier.Texture(new("/Textures/Interface/VerbIcons/delete_transparent.svg.192dpi.png")),
Priority = 1,
};
args.Verbs.Add(flushVerb);
// Verb to eject the contents
AlternativeVerb ejectVerb = new()
{
Act = () => TryEjectContents(uid, component),
Category = VerbCategory.Eject,
Text = Loc.GetString("disposal-eject-verb-get-data-text")
};
args.Verbs.Add(ejectVerb);
}
}
private void AddInsertVerb(EntityUid uid, DisposalUnitComponent component, GetVerbsEvent<InteractionVerb> args)
{
if (!args.CanAccess || !args.CanInteract || args.Hands == null || args.Using == null)
return;
if (!ActionBlockerSystem.CanDrop(args.User))
return;
if (!CanInsert(uid, component, args.Using.Value))
return;
InteractionVerb insertVerb = new()
{
Text = Name(args.Using.Value),
Category = VerbCategory.Insert,
Act = () =>
{
_handsSystem.TryDropIntoContainer(args.User, args.Using.Value, component.Container, checkActionBlocker: false, args.Hands);
_adminLog.Add(LogType.Action, LogImpact.Medium, $"{ToPrettyString(args.User):player} inserted {ToPrettyString(args.Using.Value)} into {ToPrettyString(uid)}");
AfterInsert(uid, component, args.Using.Value, args.User);
}
};
args.Verbs.Add(insertVerb);
}
private void OnDoAfter(EntityUid uid, DisposalUnitComponent component, DoAfterEvent args)
{
if (args.Handled || args.Cancelled || args.Args.Target == null || args.Args.Used == null)
return;
AfterInsert(uid, component, args.Args.Target.Value, args.Args.User, doInsert: true);
args.Handled = true;
}
private void OnThrowInsert(Entity<DisposalUnitComponent> ent, ref BeforeThrowInsertEvent args)
{
if (!CanInsert(ent, ent, args.ThrownEntity))
args.Cancelled = true;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<DisposalUnitComponent, MetaDataComponent>();
while (query.MoveNext(out var uid, out var unit, out var metadata))
{
Update(uid, unit, metadata);
}
}
// TODO: This should just use the same thing as entity storage?
private void OnMovement(EntityUid uid, DisposalUnitComponent component, ref ContainerRelayMovementEntityEvent args)
{
var currentTime = GameTiming.CurTime;
if (!ActionBlockerSystem.CanMove(args.Entity))
return;
if (!TryComp(args.Entity, out HandsComponent? hands) ||
hands.Count == 0 ||
currentTime < component.LastExitAttempt + ExitAttemptDelay)
return;
Dirty(uid, component);
component.LastExitAttempt = currentTime;
Remove(uid, component, args.Entity);
UpdateUI((uid, component));
}
private void OnActivate(EntityUid uid, DisposalUnitComponent component, ActivateInWorldEvent args)
{
if (args.Handled || !args.Complex)
return;
args.Handled = true;
_ui.TryToggleUi(uid, DisposalUnitComponent.DisposalUnitUiKey.Key, args.User);
}
private void OnAfterInteractUsing(EntityUid uid, DisposalUnitComponent component, AfterInteractUsingEvent args)
{
if (args.Handled || !args.CanReach)
return;
if (!HasComp<HandsComponent>(args.User))
{
return;
}
if (!CanInsert(uid, component, args.Used) || !_handsSystem.TryDropIntoContainer(args.User, args.Used, component.Container))
{
return;
}
_adminLog.Add(LogType.Action, LogImpact.Medium, $"{ToPrettyString(args.User):player} inserted {ToPrettyString(args.Used)} into {ToPrettyString(uid)}");
AfterInsert(uid, component, args.Used, args.User);
args.Handled = true;
}
protected virtual void OnDisposalInit(Entity<DisposalUnitComponent> ent, ref ComponentInit args)
{
ent.Comp.Container = Containers.EnsureContainer<Container>(ent, DisposalUnitComponent.ContainerId);
}
private void OnPowerChange(EntityUid uid, DisposalUnitComponent component, ref PowerChangedEvent args)
{
if (!component.Running)
return;
UpdateUI((uid, component));
UpdateVisualState(uid, component);
if (!args.Powered)
{
component.NextFlush = null;
Dirty(uid, component);
return;
}
if (component.Engaged)
{
// Run ManualEngage to recalculate a new flush time
ManualEngage(uid, component);
}
}
private void OnAnchorChanged(EntityUid uid, DisposalUnitComponent component, ref AnchorStateChangedEvent args)
{
if (Terminating(uid))
return;
UpdateVisualState(uid, component);
if (!args.Anchored)
TryEjectContents(uid, component);
}
private void OnDragDropOn(EntityUid uid, DisposalUnitComponent component, ref DragDropTargetEvent args)
{
args.Handled = TryInsert(uid, args.Dragged, args.User);
}
protected virtual void UpdateUI(Entity<DisposalUnitComponent> entity)
{
}
/// <summary>
/// Returns the estimated time when the disposal unit will be back to full pressure.
/// </summary>
public TimeSpan EstimatedFullPressure(EntityUid uid, DisposalUnitComponent component)
{
if (component.NextPressurized < GameTiming.CurTime)
return TimeSpan.Zero;
return component.NextPressurized;
}
public bool CanFlush(EntityUid unit, DisposalUnitComponent component)
{
return GetState(unit, component) == DisposalsPressureState.Ready
&& _power.IsPowered(unit)
&& Comp<TransformComponent>(unit).Anchored;
}
public void Remove(EntityUid uid, DisposalUnitComponent component, EntityUid toRemove)
{
if (GameTiming.ApplyingState)
return;
if (!Containers.Remove(toRemove, component.Container))
return;
if (component.Container.ContainedEntities.Count == 0)
{
// If not manually engaged then reset the flushing entirely.
if (!component.Engaged)
{
component.NextFlush = null;
Dirty(uid, component);
UpdateUI((uid, component));
}
}
_climb.Climb(toRemove, toRemove, uid, silent: true);
UpdateVisualState(uid, component);
}
public void UpdateVisualState(EntityUid uid, DisposalUnitComponent component, bool flush = false)
{
if (!TryComp(uid, out AppearanceComponent? appearance))
{
return;
}
if (!Transform(uid).Anchored)
{
_appearance.SetData(uid, DisposalUnitComponent.Visuals.VisualState, DisposalUnitComponent.VisualState.UnAnchored, appearance);
_appearance.SetData(uid, DisposalUnitComponent.Visuals.Handle, DisposalUnitComponent.HandleState.Normal, appearance);
_appearance.SetData(uid, DisposalUnitComponent.Visuals.Light, DisposalUnitComponent.LightStates.Off, appearance);
return;
}
var state = GetState(uid, component);
switch (state)
{
case DisposalsPressureState.Flushed:
_appearance.SetData(uid, DisposalUnitComponent.Visuals.VisualState, DisposalUnitComponent.VisualState.OverlayFlushing, appearance);
break;
case DisposalsPressureState.Pressurizing:
_appearance.SetData(uid, DisposalUnitComponent.Visuals.VisualState, DisposalUnitComponent.VisualState.OverlayCharging, appearance);
break;
case DisposalsPressureState.Ready:
_appearance.SetData(uid, DisposalUnitComponent.Visuals.VisualState, DisposalUnitComponent.VisualState.Anchored, appearance);
break;
}
_appearance.SetData(uid, DisposalUnitComponent.Visuals.Handle, component.Engaged
? DisposalUnitComponent.HandleState.Engaged
: DisposalUnitComponent.HandleState.Normal, appearance);
if (!_power.IsPowered(uid))
{
_appearance.SetData(uid, DisposalUnitComponent.Visuals.Light, DisposalUnitComponent.LightStates.Off, appearance);
return;
}
var lightState = DisposalUnitComponent.LightStates.Off;
if (component.Container.ContainedEntities.Count > 0)
{
lightState |= DisposalUnitComponent.LightStates.Full;
}
if (state is DisposalsPressureState.Pressurizing or DisposalsPressureState.Flushed)
{
lightState |= DisposalUnitComponent.LightStates.Charging;
}
else
{
lightState |= DisposalUnitComponent.LightStates.Ready;
}
_appearance.SetData(uid, DisposalUnitComponent.Visuals.Light, lightState, appearance);
}
/// <summary>
/// Gets the current pressure state of a disposals unit.
/// </summary>
/// <param name="uid"></param>
/// <param name="component"></param>
/// <param name="metadata"></param>
/// <returns></returns>
public DisposalsPressureState GetState(EntityUid uid, DisposalUnitComponent component, MetaDataComponent? metadata = null)
{
var nextPressure = Metadata.GetPauseTime(uid, metadata) + component.NextPressurized - GameTiming.CurTime;
var pressurizeTime = 1f / PressurePerSecond;
var pressurizeDuration = pressurizeTime - component.FlushDelay.TotalSeconds;
if (nextPressure.TotalSeconds > pressurizeDuration)
{
return DisposalsPressureState.Flushed;
}
if (nextPressure > TimeSpan.Zero)
{
return DisposalsPressureState.Pressurizing;
}
return DisposalsPressureState.Ready;
}
public float GetPressure(EntityUid uid, DisposalUnitComponent component, MetaDataComponent? metadata = null)
{
if (!Resolve(uid, ref metadata))
return 0f;
var pauseTime = Metadata.GetPauseTime(uid, metadata);
return MathF.Min(1f,
(float)(GameTiming.CurTime - pauseTime - component.NextPressurized).TotalSeconds / PressurePerSecond);
}
protected void OnPreventCollide(EntityUid uid, DisposalUnitComponent component,
ref PreventCollideEvent args)
{
var otherBody = args.OtherEntity;
// Items dropped shouldn't collide but items thrown should
if (HasComp<ItemComponent>(otherBody) && !HasComp<ThrownItemComponent>(otherBody))
{
args.Cancelled = true;
}
}
protected void OnCanDragDropOn(EntityUid uid, DisposalUnitComponent component, ref CanDropTargetEvent args)
{
if (args.Handled)
return;
args.CanDrop = CanInsert(uid, component, args.Dragged);
args.Handled = true;
}
protected void OnEmagged(EntityUid uid, DisposalUnitComponent component, ref GotEmaggedEvent args)
{
component.DisablePressure = true;
args.Handled = true;
}
public virtual bool CanInsert(EntityUid uid, DisposalUnitComponent component, EntityUid entity)
{
// TODO: All of the below should be using the EXISTING EVENT
if (!Containers.CanInsert(entity, component.Container))
return false;
if (!Transform(uid).Anchored)
return false;
var storable = HasComp<ItemComponent>(entity);
if (!storable && !HasComp<BodyComponent>(entity))
return false;
if (_whitelistSystem.IsBlacklistPass(component.Blacklist, entity) ||
_whitelistSystem.IsWhitelistFail(component.Whitelist, entity))
return false;
if (TryComp<PhysicsComponent>(entity, out var physics) && (physics.CanCollide) || storable)
return true;
else
return false;
}
public void DoInsertDisposalUnit(EntityUid uid,
EntityUid toInsert,
EntityUid user,
DisposalUnitComponent? disposal = null)
{
if (!Resolve(uid, ref disposal))
return;
if (!Containers.Insert(toInsert, disposal.Container))
return;
_adminLog.Add(LogType.Action, LogImpact.Medium, $"{ToPrettyString(user):player} inserted {ToPrettyString(toInsert)} into {ToPrettyString(uid)}");
AfterInsert(uid, disposal, toInsert, user);
}
public virtual void AfterInsert(EntityUid uid,
DisposalUnitComponent component,
EntityUid inserted,
EntityUid? user = null,
bool doInsert = false)
{
Audio.PlayPredicted(component.InsertSound, uid, user: user);
if (doInsert && !Containers.Insert(inserted, component.Container))
return;
if (user != inserted && user != null)
_adminLog.Add(LogType.Action, LogImpact.Medium, $"{ToPrettyString(user.Value):player} inserted {ToPrettyString(inserted)} into {ToPrettyString(uid)}");
QueueAutomaticEngage(uid, component);
_ui.CloseUi(uid, DisposalUnitComponent.DisposalUnitUiKey.Key, inserted);
// Maybe do pullable instead? Eh still fine.
Joints.RecursiveClearJoints(inserted);
UpdateVisualState(uid, component);
}
public bool TryInsert(EntityUid unitId, EntityUid toInsertId, EntityUid? userId, DisposalUnitComponent? unit = null)
{
if (!Resolve(unitId, ref unit))
return false;
if (userId.HasValue && !HasComp<HandsComponent>(userId) && toInsertId != userId) // Mobs like mouse can Jump inside even with no hands
{
_popupSystem.PopupEntity(Loc.GetString("disposal-unit-no-hands"), userId.Value, userId.Value, PopupType.SmallCaution);
return false;
}
if (!CanInsert(unitId, unit, toInsertId))
return false;
bool insertingSelf = userId == toInsertId;
var delay = insertingSelf ? unit.EntryDelay : unit.DraggedEntryDelay;
if (userId != null && !insertingSelf)
_popupSystem.PopupEntity(Loc.GetString("disposal-unit-being-inserted", ("user", Identity.Entity((EntityUid)userId, EntityManager))), toInsertId, toInsertId, PopupType.Large);
if (delay <= 0 || userId == null)
{
AfterInsert(unitId, unit, toInsertId, userId, doInsert: true);
return true;
}
// Can't check if our target AND disposals moves currently so we'll just check target.
// if you really want to check if disposals moves then add a predicate.
var doAfterArgs = new DoAfterArgs(EntityManager, userId.Value, delay, new DisposalDoAfterEvent(), unitId, target: toInsertId, used: unitId)
{
BreakOnDamage = true,
BreakOnMove = true,
NeedHand = false,
};
_doAfterSystem.TryStartDoAfter(doAfterArgs);
return true;
}
private void UpdateState(EntityUid uid, DisposalsPressureState state, DisposalUnitComponent component, MetaDataComponent metadata)
{
if (component.State == state)
return;
component.State = state;
UpdateVisualState(uid, component);
Dirty(uid, component, metadata);
if (state == DisposalsPressureState.Ready)
{
component.NextPressurized = TimeSpan.Zero;
// Manually engaged
if (component.Engaged)
{
component.NextFlush = GameTiming.CurTime + component.ManualFlushTime;
}
else if (component.Container.ContainedEntities.Count > 0)
{
component.NextFlush = GameTiming.CurTime + component.AutomaticEngageTime;
}
else
{
component.NextFlush = null;
}
}
}
/// <summary>
/// Work out if we can stop updating this disposals component i.e. full pressure and nothing colliding.
/// </summary>
private void Update(EntityUid uid, DisposalUnitComponent component, MetaDataComponent metadata)
{
var state = GetState(uid, component, metadata);
// Pressurizing, just check if we need a state update.
if (component.NextPressurized > GameTiming.CurTime)
{
UpdateState(uid, state, component, metadata);
return;
}
if (component.NextFlush != null)
{
if (component.NextFlush.Value < GameTiming.CurTime)
{
TryFlush(uid, component);
}
}
UpdateState(uid, state, component, metadata);
}
public bool TryFlush(EntityUid uid, DisposalUnitComponent component)
{
if (!CanFlush(uid, component))
{
return false;
}
if (component.NextFlush != null)
component.NextFlush = component.NextFlush.Value + component.AutomaticEngageTime;
var beforeFlushArgs = new BeforeDisposalFlushEvent();
RaiseLocalEvent(uid, beforeFlushArgs);
if (beforeFlushArgs.Cancelled)
{
Disengage(uid, component);
return false;
}
var xform = Transform(uid);
if (!TryComp(xform.GridUid, out MapGridComponent? grid))
return false;
var coords = xform.Coordinates;
var entry = _map.GetLocal(xform.GridUid.Value, grid, coords)
.FirstOrDefault(HasComp<Tube.DisposalEntryComponent>);
if (entry == default || component is not DisposalUnitComponent sDisposals)
{
component.Engaged = false;
UpdateUI((uid, component));
Dirty(uid, component);
return false;
}
HandleAir(uid, sDisposals, xform);
_disposalTubeSystem.TryInsert(entry, sDisposals, beforeFlushArgs.Tags);
component.NextPressurized = GameTiming.CurTime;
if (!component.DisablePressure)
component.NextPressurized += TimeSpan.FromSeconds(1f / PressurePerSecond);
component.Engaged = false;
// stop queuing NOW
component.NextFlush = null;
UpdateVisualState(uid, component, true);
Dirty(uid, component);
UpdateUI((uid, component));
return true;
}
protected virtual void HandleAir(EntityUid uid, DisposalUnitComponent component, TransformComponent xform)
{
}
public void ManualEngage(EntityUid uid, DisposalUnitComponent component, MetaDataComponent? metadata = null)
{
component.Engaged = true;
UpdateVisualState(uid, component);
Dirty(uid, component);
UpdateUI((uid, component));
if (!CanFlush(uid, component))
return;
if (!Resolve(uid, ref metadata))
return;
var pauseTime = Metadata.GetPauseTime(uid, metadata);
var nextEngage = GameTiming.CurTime - pauseTime + component.ManualFlushTime;
component.NextFlush = TimeSpan.FromSeconds(Math.Min((component.NextFlush ?? TimeSpan.MaxValue).TotalSeconds, nextEngage.TotalSeconds));
}
public void Disengage(EntityUid uid, DisposalUnitComponent component)
{
component.Engaged = false;
if (component.Container.ContainedEntities.Count == 0)
{
component.NextFlush = null;
}
UpdateVisualState(uid, component);
Dirty(uid, component);
UpdateUI((uid, component));
}
/// <summary>
/// Remove all entities currently in the disposal unit.
/// </summary>
public void TryEjectContents(EntityUid uid, DisposalUnitComponent component)
{
foreach (var entity in component.Container.ContainedEntities.ToArray())
{
Remove(uid, component, entity);
}
if (!component.Engaged)
{
component.NextFlush = null;
Dirty(uid, component);
UpdateUI((uid, component));
}
}
/// <summary>
/// If something is inserted (or the likes) then we'll queue up an automatic flush in the future.
/// </summary>
public void QueueAutomaticEngage(EntityUid uid, DisposalUnitComponent component, MetaDataComponent? metadata = null)
{
if (component.Deleted || !component.AutomaticEngage || !_power.IsPowered(uid) && component.Container.ContainedEntities.Count == 0)
{
return;
}
var pauseTime = Metadata.GetPauseTime(uid, metadata);
var automaticTime = GameTiming.CurTime + component.AutomaticEngageTime - pauseTime;
var flushTime = TimeSpan.FromSeconds(Math.Min((component.NextFlush ?? TimeSpan.MaxValue).TotalSeconds, automaticTime.TotalSeconds));
component.NextFlush = flushTime;
Dirty(uid, component);
UpdateUI((uid, component));
}
private void OnUiButtonPressed(EntityUid uid, DisposalUnitComponent component, DisposalUnitComponent.UiButtonPressedMessage args)
{
if (args.Actor is not { Valid: true } player)
{
return;
}
switch (args.Button)
{
case DisposalUnitComponent.UiButton.Eject:
TryEjectContents(uid, component);
_adminLog.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(player):player} hit eject button on {ToPrettyString(uid)}");
break;
case DisposalUnitComponent.UiButton.Engage:
ToggleEngage(uid, component);
_adminLog.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(player):player} hit flush button on {ToPrettyString(uid)}, it's now {(component.Engaged ? "on" : "off")}");
break;
case DisposalUnitComponent.UiButton.Power:
_power.TogglePower(uid, user: args.Actor);
break;
default:
throw new ArgumentOutOfRangeException($"{ToPrettyString(player):player} attempted to hit a nonexistant button on {ToPrettyString(uid)}");
}
}
public void ToggleEngage(EntityUid uid, DisposalUnitComponent component)
{
component.Engaged ^= true;
if (component.Engaged)
{
ManualEngage(uid, component);
}
else
{
Disengage(uid, component);
}
}
private void AddClimbInsideVerb(EntityUid uid, DisposalUnitComponent component, GetVerbsEvent<Verb> args)
{
// This is not an interaction, activation, or alternative verb type because unfortunately most users are
// unwilling to accept that this is where they belong and don't want to accidentally climb inside.
if (!args.CanAccess ||
!args.CanInteract ||
component.Container.ContainedEntities.Contains(args.User) ||
!ActionBlockerSystem.CanMove(args.User))
{
return;
}
if (!CanInsert(uid, component, args.User))
return;
// Add verb to climb inside of the unit,
Verb verb = new()
{
Act = () => TryInsert(uid, args.User, args.User),
DoContactInteraction = true,
Text = Loc.GetString("disposal-self-insert-verb-get-data-text")
};
// TODO VERB ICON
// TODO VERB CATEGORY
// create a verb category for "enter"?
// See also, medical scanner. Also maybe add verbs for entering lockers/body bags?
args.Verbs.Add(verb);
}
}

View File

@@ -8,9 +8,15 @@ public abstract partial class SharedApcPowerReceiverComponent : Component
[ViewVariables]
public bool Powered;
[ViewVariables]
public virtual bool NeedsPower { get; set; }
/// <summary>
/// When false, causes this to appear powered even if not receiving power from an Apc.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public virtual bool NeedsPower { get; set;}
[ViewVariables]
/// <summary>
/// When true, causes this to never appear powered.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public virtual bool PowerDisabled { get; set; }
}

View File

@@ -62,8 +62,13 @@ public abstract class SharedPowerReceiverSystem : EntitySystem
return !receiver.PowerDisabled; // i.e. PowerEnabled
}
/// <summary>
/// Checks if entity is APC-powered device, and if it have power.
protected virtual void RaisePower(Entity<SharedApcPowerReceiverComponent> entity)
{
// NOOP on server because client has 0 idea of load so we can't raise it properly in shared.
}
/// <summary>
/// Checks if entity is APC-powered device, and if it have power.
/// </summary>
public bool IsPowered(Entity<SharedApcPowerReceiverComponent?> entity)
{

View File

@@ -1,5 +1,7 @@
using System.Linq;
using Content.Shared.Disposal;
using Content.Shared.Disposal.Components;
using Content.Shared.Disposal.Unit;
using Content.Shared.DoAfter;
using Content.Shared.Interaction;
using Content.Shared.Item;
@@ -40,7 +42,7 @@ public sealed class DumpableSystem : EntitySystem
if (!args.CanReach || args.Handled)
return;
if (!_disposalUnitSystem.HasDisposals(args.Target) && !HasComp<PlaceableSurfaceComponent>(args.Target))
if (!HasComp<DisposalUnitComponent>(args.Target) && !HasComp<PlaceableSurfaceComponent>(args.Target))
return;
if (!TryComp<StorageComponent>(uid, out var storage))
@@ -81,7 +83,7 @@ public sealed class DumpableSystem : EntitySystem
if (!TryComp<StorageComponent>(uid, out var storage) || !storage.Container.ContainedEntities.Any())
return;
if (_disposalUnitSystem.HasDisposals(args.Target))
if (HasComp<DisposalUnitComponent>(args.Target))
{
UtilityVerb verb = new()
{
@@ -146,7 +148,7 @@ public sealed class DumpableSystem : EntitySystem
var dumped = false;
if (_disposalUnitSystem.HasDisposals(args.Args.Target))
if (HasComp<DisposalUnitComponent>(args.Args.Target))
{
dumped = true;