Re-organize all projects (#4166)

This commit is contained in:
DrSmugleaf
2021-06-09 22:19:39 +02:00
committed by GitHub
parent 9f50e4061b
commit ff1a2d97ea
1773 changed files with 5258 additions and 5508 deletions

View File

@@ -0,0 +1,71 @@
#nullable enable
using Content.Server.Ghost;
using Content.Server.Ghost.Components;
using Content.Server.Mind.Components;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Content.Shared.Movement.Components;
using Robust.Shared.GameObjects;
namespace Content.Server.Body.Behavior
{
public class BrainBehavior : MechanismBehavior
{
protected override void OnAddedToBody(IBody body)
{
base.OnAddedToBody(body);
HandleMind(body.Owner, Owner);
}
protected override void OnAddedToPart(IBodyPart part)
{
base.OnAddedToPart(part);
HandleMind(part.Owner, Owner);
}
protected override void OnAddedToPartInBody(IBody body, IBodyPart part)
{
base.OnAddedToPartInBody(body, part);
HandleMind(body.Owner, Owner);
}
protected override void OnRemovedFromBody(IBody old)
{
base.OnRemovedFromBody(old);
HandleMind(Part!.Owner, old.Owner);
}
protected override void OnRemovedFromPart(IBodyPart old)
{
base.OnRemovedFromPart(old);
HandleMind(Owner, old.Owner);
}
protected override void OnRemovedFromPartInBody(IBody oldBody, IBodyPart oldPart)
{
base.OnRemovedFromPartInBody(oldBody, oldPart);
HandleMind(oldBody.Owner, Owner);
}
private void HandleMind(IEntity newEntity, IEntity oldEntity)
{
newEntity.EnsureComponent<MindComponent>();
var oldMind = oldEntity.EnsureComponent<MindComponent>();
if (!newEntity.HasComponent<IGhostOnMove>())
newEntity.AddComponent<GhostOnMoveComponent>();
// TODO: This is an awful solution.
if (!newEntity.HasComponent<IMoverComponent>())
newEntity.AddComponent<SharedDummyInputMoverComponent>();
oldMind.Mind?.TransferTo(newEntity);
}
}
}

View File

@@ -0,0 +1,29 @@
using Content.Shared.Body.Networks;
namespace Content.Server.Body.Behavior
{
public class HeartBehavior : MechanismBehavior
{
private float _accumulatedFrameTime;
public override void Update(float frameTime)
{
// TODO BODY do between pre and metabolism
if (Parent.Body == null ||
!Parent.Body.Owner.HasComponent<SharedBloodstreamComponent>())
{
return;
}
// Update at most once per second
_accumulatedFrameTime += frameTime;
// TODO: Move/accept/process bloodstream reagents only when the heart is pumping
if (_accumulatedFrameTime >= 1)
{
// bloodstream.Update(_accumulatedFrameTime);
_accumulatedFrameTime -= 1;
}
}
}
}

View File

@@ -0,0 +1,109 @@
#nullable enable
using System.Linq;
using Content.Server.Body.Circulatory;
using Content.Shared.Body.Networks;
using Content.Shared.Chemistry.Metabolizable;
using Content.Shared.Chemistry.Reagent;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
namespace Content.Server.Body.Behavior
{
/// <summary>
/// Metabolizes reagents in <see cref="SharedBloodstreamComponent"/> after they are digested.
/// </summary>
public class LiverBehavior : MechanismBehavior
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
private float _accumulatedFrameTime;
/// <summary>
/// Whether the liver is functional.
/// </summary>
//[ViewVariables] private bool _liverFailing = false;
/// <summary>
/// Modifier for alcohol damage.
/// </summary>
//[DataField("alcoholLethality")]
//[ViewVariables] private float _alcoholLethality = 0.005f;
/// <summary>
/// Modifier for alcohol damage.
/// </summary>
//[DataField("alcoholExponent")]
//[ViewVariables] private float _alcoholExponent = 1.6f;
/// <summary>
/// Toxin volume that can be purged without damage.
/// </summary>
//[DataField("toxinTolerance")]
//[ViewVariables] private float _toxinTolerance = 3f;
/// <summary>
/// Toxin damage modifier.
/// </summary>
//[DataField("toxinLethality")]
//[ViewVariables] private float _toxinLethality = 0.01f;
/// <summary>
/// Loops through each reagent in _internalSolution,
/// and calls <see cref="IMetabolizable.Metabolize"/> for each of them.
/// Also handles toxins and alcohol.
/// </summary>
/// <param name="frameTime">
/// The time since the last update in seconds.
/// </param>
public override void Update(float frameTime)
{
if (Body == null)
{
return;
}
_accumulatedFrameTime += frameTime;
// Update at most once per second
if (_accumulatedFrameTime < 1)
{
return;
}
_accumulatedFrameTime -= 1;
if (!Body.Owner.TryGetComponent(out BloodstreamComponent? bloodstream))
{
return;
}
if (bloodstream.Solution.CurrentVolume <= ReagentUnit.Zero)
{
return;
}
// Run metabolism for each reagent, remove metabolized reagents
// Using ToList here lets us edit reagents while iterating
foreach (var reagent in bloodstream.Solution.ReagentList.ToList())
{
if (!_prototypeManager.TryIndex(reagent.ReagentId, out ReagentPrototype? prototype))
{
continue;
}
//TODO BODY Check if it's a Toxin. If volume < _toxinTolerance, just remove it. If greater, add damage = volume * _toxinLethality
//TODO BODY Check if it has BoozePower > 0. Affect drunkenness, apply damage. Proposed formula (SS13-derived): damage = sqrt(volume) * BoozePower^_alcoholExponent * _alcoholLethality / 10
//TODO BODY Liver failure.
//TODO Make sure reagent prototypes actually have the toxin and boozepower vars set.
// Run metabolism code for each reagent
foreach (var metabolizable in prototype.Metabolism)
{
var reagentDelta = metabolizable.Metabolize(Body.Owner, reagent.ReagentId, frameTime);
bloodstream.Solution.TryRemoveReagent(reagent.ReagentId, reagentDelta);
}
}
}
}
}

View File

@@ -0,0 +1,202 @@
#nullable enable
using System;
using Content.Server.Atmos;
using Content.Server.Body.Circulatory;
using Content.Server.Body.Respiratory;
using Content.Server.GameObjects.Components.Atmos;
using Content.Server.Notification;
using Content.Shared.Atmos;
using Content.Shared.Body.Components;
using Content.Shared.MobState;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Behavior
{
[DataDefinition]
public class LungBehavior : MechanismBehavior
{
[Dependency] private readonly IGameTiming _gameTiming = default!;
private float _accumulatedFrameTime;
[ViewVariables] private TimeSpan _lastGaspPopupTime;
[DataField("air")]
[ViewVariables]
public GasMixture Air { get; set; } = new()
{
Volume = 6,
Temperature = Atmospherics.NormalBodyTemperature
};
[DataField("gaspPopupCooldown")]
[ViewVariables]
public TimeSpan GaspPopupCooldown { get; private set; } = TimeSpan.FromSeconds(8);
[ViewVariables] public LungStatus Status { get; set; }
[DataField("cycleDelay")]
[ViewVariables]
public float CycleDelay { get; set; } = 2;
public LungBehavior()
{
IoCManager.InjectDependencies(this);
}
protected override void OnAddedToBody(IBody body)
{
base.OnAddedToBody(body);
Inhale(CycleDelay);
}
public void Gasp()
{
if (_gameTiming.CurTime >= _lastGaspPopupTime + GaspPopupCooldown)
{
_lastGaspPopupTime = _gameTiming.CurTime;
Owner.PopupMessageEveryone(Loc.GetString("Gasp"));
}
Inhale(CycleDelay);
}
public void Transfer(GasMixture from, GasMixture to, float ratio)
{
to.Merge(from.RemoveRatio(ratio));
}
public void ToBloodstream(GasMixture mixture)
{
if (Body == null)
{
return;
}
if (!Body.Owner.TryGetComponent(out BloodstreamComponent? bloodstream))
{
return;
}
var to = bloodstream.Air;
to.Merge(mixture);
mixture.Clear();
}
public override void Update(float frameTime)
{
if (Body != null && Body.Owner.TryGetComponent(out IMobStateComponent? mobState) && mobState.IsCritical())
{
return;
}
if (Status == LungStatus.None)
{
Status = LungStatus.Inhaling;
}
_accumulatedFrameTime += Status switch
{
LungStatus.Inhaling => frameTime,
LungStatus.Exhaling => -frameTime,
_ => throw new ArgumentOutOfRangeException()
};
var absoluteTime = Math.Abs(_accumulatedFrameTime);
var delay = CycleDelay;
if (absoluteTime < delay)
{
return;
}
switch (Status)
{
case LungStatus.Inhaling:
Inhale(absoluteTime);
Status = LungStatus.Exhaling;
break;
case LungStatus.Exhaling:
Exhale(absoluteTime);
Status = LungStatus.Inhaling;
break;
default:
throw new ArgumentOutOfRangeException();
}
_accumulatedFrameTime = absoluteTime - delay;
}
public void Inhale(float frameTime)
{
if (Body != null &&
Body.Owner.TryGetComponent(out InternalsComponent? internals) &&
internals.BreathToolEntity != null &&
internals.GasTankEntity != null &&
internals.BreathToolEntity.TryGetComponent(out BreathToolComponent? breathTool) &&
breathTool.IsFunctional &&
internals.GasTankEntity.TryGetComponent(out GasTankComponent? gasTank) &&
gasTank.Air != null)
{
Inhale(frameTime, gasTank.RemoveAirVolume(Atmospherics.BreathVolume));
return;
}
if (!Owner.Transform.Coordinates.TryGetTileAir(out var tileAir))
{
return;
}
Inhale(frameTime, tileAir);
}
public void Inhale(float frameTime, GasMixture from)
{
var ratio = (Atmospherics.BreathVolume / from.Volume) * frameTime;
Transfer(from, Air, ratio);
ToBloodstream(Air);
}
public void Exhale(float frameTime)
{
if (!Owner.Transform.Coordinates.TryGetTileAir(out var tileAir))
{
return;
}
Exhale(frameTime, tileAir);
}
public void Exhale(float frameTime, GasMixture to)
{
// TODO: Make the bloodstream separately pump toxins into the lungs, making the lungs' only job to empty.
if (Body == null)
{
return;
}
if (!Body.Owner.TryGetComponent(out BloodstreamComponent? bloodstream))
{
return;
}
bloodstream.PumpToxins(Air);
var lungRemoved = Air.RemoveRatio(0.5f);
to.Merge(lungRemoved);
}
}
public enum LungStatus
{
None = 0,
Inhaling,
Exhaling
}
}

View File

@@ -0,0 +1,109 @@
#nullable enable
using Content.Shared.Body.Behavior;
using Content.Shared.Body.Components;
using Content.Shared.Body.Mechanism;
using Content.Shared.Body.Part;
using Robust.Shared.GameObjects;
using Robust.Shared.Utility;
namespace Content.Server.Body.Behavior
{
public abstract class MechanismBehavior : IMechanismBehavior
{
public IBody? Body => Part?.Body;
public IBodyPart? Part => Parent.Part;
public IMechanism Parent { get; private set; } = default!;
public IEntity Owner => Parent.Owner;
public virtual void Initialize(IMechanism parent)
{
Parent = parent;
}
public virtual void Startup()
{
if (Part == null)
{
return;
}
if (Body == null)
{
AddedToPart(Part);
}
else
{
AddedToPartInBody(Body, Part);
}
}
public void AddedToBody(IBody body)
{
DebugTools.AssertNotNull(Body);
DebugTools.AssertNotNull(body);
OnAddedToBody(body);
}
public void AddedToPart(IBodyPart part)
{
DebugTools.AssertNotNull(Part);
DebugTools.AssertNotNull(part);
OnAddedToPart(part);
}
public void AddedToPartInBody(IBody body, IBodyPart part)
{
DebugTools.AssertNotNull(Body);
DebugTools.AssertNotNull(body);
DebugTools.AssertNotNull(Part);
DebugTools.AssertNotNull(part);
OnAddedToPartInBody(body, part);
}
public void RemovedFromBody(IBody old)
{
DebugTools.AssertNull(Body);
DebugTools.AssertNotNull(old);
OnRemovedFromBody(old);
}
public void RemovedFromPart(IBodyPart old)
{
DebugTools.AssertNull(Part);
DebugTools.AssertNotNull(old);
OnRemovedFromPart(old);
}
public void RemovedFromPartInBody(IBody oldBody, IBodyPart oldPart)
{
DebugTools.AssertNull(Body);
DebugTools.AssertNull(Part);
DebugTools.AssertNotNull(oldBody);
DebugTools.AssertNotNull(oldPart);
OnRemovedFromPartInBody(oldBody, oldPart);
}
protected virtual void OnAddedToBody(IBody body) { }
protected virtual void OnAddedToPart(IBodyPart part) { }
protected virtual void OnAddedToPartInBody(IBody body, IBodyPart part) { }
protected virtual void OnRemovedFromBody(IBody old) { }
protected virtual void OnRemovedFromPart(IBodyPart old) { }
protected virtual void OnRemovedFromPartInBody(IBody oldBody, IBodyPart oldPart) { }
public virtual void Update(float frameTime) { }
}
}

View File

@@ -0,0 +1,74 @@
#nullable enable
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Shared.Body.Behavior;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
namespace Content.Server.Body.Behavior
{
public static class MechanismExtensions
{
public static bool HasMechanismBehavior<T>(this IBody body) where T : IMechanismBehavior
{
return body.Parts.Any(p => p.Key.HasMechanismBehavior<T>());
}
public static bool HasMechanismBehavior<T>(this IBodyPart part) where T : IMechanismBehavior
{
return part.Mechanisms.Any(m => m.HasBehavior<T>());
}
public static IEnumerable<IMechanismBehavior> GetMechanismBehaviors(this IBody body)
{
foreach (var (part, _) in body.Parts)
foreach (var mechanism in part.Mechanisms)
foreach (var behavior in mechanism.Behaviors.Values)
{
yield return behavior;
}
}
public static bool TryGetMechanismBehaviors(this IBody body,
[NotNullWhen(true)] out List<IMechanismBehavior>? behaviors)
{
behaviors = body.GetMechanismBehaviors().ToList();
if (behaviors.Count == 0)
{
behaviors = null;
return false;
}
return true;
}
public static IEnumerable<T> GetMechanismBehaviors<T>(this IBody body) where T : class, IMechanismBehavior
{
foreach (var (part, _) in body.Parts)
foreach (var mechanism in part.Mechanisms)
foreach (var behavior in mechanism.Behaviors.Values)
{
if (behavior is T tBehavior)
{
yield return tBehavior;
}
}
}
public static bool TryGetMechanismBehaviors<T>(this IBody entity, [NotNullWhen(true)] out List<T>? behaviors)
where T : class, IMechanismBehavior
{
behaviors = entity.GetMechanismBehaviors<T>().ToList();
if (behaviors.Count == 0)
{
behaviors = null;
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,175 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using Content.Server.Body.Circulatory;
using Content.Server.Chemistry.Components;
using Content.Shared.Body.Networks;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Chemistry.Solution;
using Content.Shared.Chemistry.Solution.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Behavior
{
/// <summary>
/// Where reagents go when ingested. Tracks ingested reagents over time, and
/// eventually transfers them to <see cref="SharedBloodstreamComponent"/> once digested.
/// </summary>
public class StomachBehavior : MechanismBehavior
{
private float _accumulatedFrameTime;
/// <summary>
/// Updates digestion status of ingested reagents.
/// Once reagents surpass _digestionDelay they are moved to the
/// bloodstream, where they are then metabolized.
/// </summary>
/// <param name="frameTime">
/// The time since the last update in seconds.
/// </param>
public override void Update(float frameTime)
{
if (Body == null)
{
return;
}
_accumulatedFrameTime += frameTime;
// Update at most once per second
if (_accumulatedFrameTime < 1)
{
return;
}
_accumulatedFrameTime -= 1;
if (!Body.Owner.TryGetComponent(out SolutionContainerComponent? solution) ||
!Body.Owner.TryGetComponent(out BloodstreamComponent? bloodstream))
{
return;
}
// Add reagents ready for transfer to bloodstream to transferSolution
var transferSolution = new Solution();
// Use ToList here to remove entries while iterating
foreach (var delta in _reagentDeltas.ToList())
{
//Increment lifetime of reagents
delta.Increment(1);
if (delta.Lifetime > _digestionDelay)
{
solution.TryRemoveReagent(delta.ReagentId, delta.Quantity);
transferSolution.AddReagent(delta.ReagentId, delta.Quantity);
_reagentDeltas.Remove(delta);
}
}
// Transfer digested reagents to bloodstream
bloodstream.TryTransferSolution(transferSolution);
}
/// <summary>
/// Max volume of internal solution storage
/// </summary>
public ReagentUnit MaxVolume
{
get => Owner.TryGetComponent(out SharedSolutionContainerComponent? solution) ? solution.MaxVolume : ReagentUnit.Zero;
set
{
if (Owner.TryGetComponent(out SharedSolutionContainerComponent? solution))
{
solution.MaxVolume = value;
}
}
}
/// <summary>
/// Initial internal solution storage volume
/// </summary>
[DataField("maxVolume")]
[ViewVariables]
protected ReagentUnit InitialMaxVolume { get; private set; } = ReagentUnit.New(100);
/// <summary>
/// Time in seconds between reagents being ingested and them being
/// transferred to <see cref="SharedBloodstreamComponent"/>
/// </summary>
[DataField("digestionDelay")] [ViewVariables]
private float _digestionDelay = 20;
/// <summary>
/// Used to track how long each reagent has been in the stomach
/// </summary>
[ViewVariables]
private readonly List<ReagentDelta> _reagentDeltas = new();
public override void Startup()
{
base.Startup();
Owner.EnsureComponentWarn(out SolutionContainerComponent solution);
solution.MaxVolume = InitialMaxVolume;
}
public bool CanTransferSolution(Solution solution)
{
if (!Owner.TryGetComponent(out SharedSolutionContainerComponent? solutionComponent))
{
return false;
}
// TODO: For now no partial transfers. Potentially change by design
if (!solutionComponent.CanAddSolution(solution))
{
return false;
}
return true;
}
public bool TryTransferSolution(Solution solution)
{
if (Body == null || !CanTransferSolution(solution))
return false;
if (!Body.Owner.TryGetComponent(out SolutionContainerComponent? solutionComponent))
{
return false;
}
// Add solution to _stomachContents
solutionComponent.TryAddSolution(solution);
// Add each reagent to _reagentDeltas. Used to track how long each reagent has been in the stomach
foreach (var reagent in solution.Contents)
{
_reagentDeltas.Add(new ReagentDelta(reagent.ReagentId, reagent.Quantity));
}
return true;
}
/// <summary>
/// Used to track quantity changes when ingesting & digesting reagents
/// </summary>
protected class ReagentDelta
{
public readonly string ReagentId;
public readonly ReagentUnit Quantity;
public float Lifetime { get; private set; }
public ReagentDelta(string reagentId, ReagentUnit quantity)
{
ReagentId = reagentId;
Quantity = quantity;
Lifetime = 0.0f;
}
public void Increment(float delta) => Lifetime += delta;
}
}
}

View File

@@ -0,0 +1,125 @@
#nullable enable
using Content.Server.GameTicking;
using Content.Server.Ghost;
using Content.Server.Mind.Components;
using Content.Shared.Audio;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Content.Shared.Body.Slot;
using Content.Shared.MobState;
using Content.Shared.Movement.Components;
using Content.Shared.Random.Helpers;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Player;
using Robust.Shared.Players;
namespace Content.Server.Body
{
[RegisterComponent]
[ComponentReference(typeof(SharedBodyComponent))]
[ComponentReference(typeof(IBody))]
[ComponentReference(typeof(IGhostOnMove))]
public class BodyComponent : SharedBodyComponent, IRelayMoveInput, IGhostOnMove
{
private Container _partContainer = default!;
[Dependency] private readonly IGameTicker _gameTicker = default!;
protected override bool CanAddPart(string slotId, IBodyPart part)
{
return base.CanAddPart(slotId, part) &&
_partContainer.CanInsert(part.Owner);
}
protected override void OnAddPart(BodyPartSlot slot, IBodyPart part)
{
base.OnAddPart(slot, part);
_partContainer.Insert(part.Owner);
}
protected override void OnRemovePart(BodyPartSlot slot, IBodyPart part)
{
base.OnRemovePart(slot, part);
_partContainer.ForceRemove(part.Owner);
part.Owner.RandomOffset(0.25f);
}
public override void Initialize()
{
base.Initialize();
_partContainer = Owner.EnsureContainer<Container>($"{Name}-{nameof(BodyComponent)}");
var preset = Preset;
if (preset != null)
{
foreach (var slot in Slots)
{
// Using MapPosition instead of Coordinates here prevents
// a crash within the character preview menu in the lobby
var entity = Owner.EntityManager.SpawnEntity(preset.PartIDs[slot.Id], Owner.Transform.MapPosition);
if (!entity.TryGetComponent(out IBodyPart? part))
{
Logger.Error($"Entity {slot.Id} does not have a {nameof(IBodyPart)} component.");
continue;
}
SetPart(slot.Id, part);
}
}
}
protected override void Startup()
{
base.Startup();
// This is ran in Startup as entities spawned in Initialize
// are not synced to the client since they are assumed to be
// identical on it
foreach (var (part, _) in Parts)
{
part.Dirty();
}
}
void IRelayMoveInput.MoveInputPressed(ICommonSession session)
{
if (Owner.TryGetComponent(out IMobStateComponent? mobState) &&
mobState.IsDead() &&
Owner.TryGetComponent(out MindComponent? mind) &&
mind.HasMind)
{
_gameTicker.OnGhostAttempt(mind.Mind!, true);
}
}
public override void Gib(bool gibParts = false)
{
base.Gib(gibParts);
SoundSystem.Play(Filter.Pvs(Owner), AudioHelpers.GetRandomFileFromSoundCollection("gib"), Owner.Transform.Coordinates,
AudioHelpers.WithVariation(0.025f));
if (Owner.TryGetComponent(out ContainerManagerComponent? container))
{
foreach (var cont in container.GetAllContainers())
{
foreach (var ent in cont.ContainedEntities)
{
cont.ForceRemove(ent);
ent.Transform.Coordinates = Owner.Transform.Coordinates;
ent.RandomOffset(0.25f);
}
}
}
Owner.QueueDelete();
}
}
}

View File

@@ -0,0 +1,20 @@
using Content.Shared.Body.Part;
using Content.Shared.Damage;
namespace Content.Server.Body
{
public interface IBodyHealthChangeParams
{
BodyPartType Part { get; }
}
public class BodyDamageChangeParams : DamageChangeParams, IBodyHealthChangeParams
{
public BodyDamageChangeParams(BodyPartType part)
{
Part = part;
}
public BodyPartType Part { get; }
}
}

View File

@@ -0,0 +1,96 @@
using System.Linq;
using Content.Server.Atmos;
using Content.Server.Chemistry.Components;
using Content.Server.Interfaces;
using Content.Server.Metabolism;
using Content.Shared.Atmos;
using Content.Shared.Body.Networks;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Chemistry.Solution;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Circulatory
{
[RegisterComponent]
[ComponentReference(typeof(SharedBloodstreamComponent))]
public class BloodstreamComponent : SharedBloodstreamComponent, IGasMixtureHolder
{
public override string Name => "Bloodstream";
/// <summary>
/// Max volume of internal solution storage
/// </summary>
[DataField("maxVolume")]
[ViewVariables] private ReagentUnit _initialMaxVolume = ReagentUnit.New(250);
/// <summary>
/// Internal solution for reagent storage
/// </summary>
[ViewVariables] private SolutionContainerComponent _internalSolution = default!;
/// <summary>
/// Empty volume of internal solution
/// </summary>
[ViewVariables] public ReagentUnit EmptyVolume => _internalSolution.EmptyVolume;
[ViewVariables]
public GasMixture Air { get; set; } = new(6)
{Temperature = Atmospherics.NormalBodyTemperature};
[ViewVariables] public SolutionContainerComponent Solution => _internalSolution;
public override void Initialize()
{
base.Initialize();
_internalSolution = Owner.EnsureComponent<SolutionContainerComponent>();
_internalSolution.MaxVolume = _initialMaxVolume;
}
/// <summary>
/// Attempt to transfer provided solution to internal solution.
/// Only supports complete transfers
/// </summary>
/// <param name="solution">Solution to be transferred</param>
/// <returns>Whether or not transfer was a success</returns>
public override bool TryTransferSolution(Solution solution)
{
// For now doesn't support partial transfers
if (solution.TotalVolume + _internalSolution.CurrentVolume > _internalSolution.MaxVolume)
{
return false;
}
_internalSolution.TryAddSolution(solution);
return true;
}
public void PumpToxins(GasMixture to)
{
if (!Owner.TryGetComponent(out MetabolismComponent? metabolism))
{
to.Merge(Air);
Air.Clear();
return;
}
var toxins = metabolism.Clean(this);
var toOld = to.Gases.ToArray();
to.Merge(toxins);
for (var i = 0; i < toOld.Length; i++)
{
var newAmount = to.GetMoles(i);
var oldAmount = toOld[i];
var delta = newAmount - oldAmount;
toxins.AdjustMoles(i, -delta);
}
Air.Merge(toxins);
}
}
}

View File

@@ -0,0 +1,146 @@
#nullable enable
using Content.Server.Administration;
using Content.Shared.Administration;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
namespace Content.Server.Body.Commands
{
[AdminCommand(AdminFlags.Fun)]
class AddHandCommand : IConsoleCommand
{
public const string DefaultHandPrototype = "LeftHandHuman";
public string Command => "addhand";
public string Description => "Adds a hand to your entity.";
public string Help => $"Usage: {Command} <entityUid> <handPrototypeId> / {Command} <entityUid> / {Command} <handPrototypeId> / {Command}";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
if (args.Length > 1)
{
shell.WriteLine(Help);
return;
}
var entityManager = IoCManager.Resolve<IEntityManager>();
var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
IEntity entity;
IEntity hand;
switch (args.Length)
{
case 0:
{
if (player == null)
{
shell.WriteLine("Only a player can run this command without arguments.");
return;
}
if (player.AttachedEntity == null)
{
shell.WriteLine("You don't have an entity to add a hand to.");
return;
}
entity = player.AttachedEntity;
hand = entityManager.SpawnEntity(DefaultHandPrototype, entity.Transform.Coordinates);
break;
}
case 1:
{
if (EntityUid.TryParse(args[0], out var uid))
{
if (!entityManager.TryGetEntity(uid, out var parsedEntity))
{
shell.WriteLine($"No entity found with uid {uid}");
return;
}
entity = parsedEntity;
hand = entityManager.SpawnEntity(DefaultHandPrototype, entity.Transform.Coordinates);
}
else
{
if (player == null)
{
shell.WriteLine("You must specify an entity to add a hand to when using this command from the server terminal.");
return;
}
if (player.AttachedEntity == null)
{
shell.WriteLine("You don't have an entity to add a hand to.");
return;
}
entity = player.AttachedEntity;
hand = entityManager.SpawnEntity(args[0], entity.Transform.Coordinates);
}
break;
}
case 2:
{
if (!EntityUid.TryParse(args[0], out var uid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
}
if (!entityManager.TryGetEntity(uid, out var parsedEntity))
{
shell.WriteLine($"No entity exists with uid {uid}.");
return;
}
entity = parsedEntity;
if (!prototypeManager.HasIndex<EntityPrototype>(args[1]))
{
shell.WriteLine($"No hand entity exists with id {args[1]}.");
return;
}
hand = entityManager.SpawnEntity(args[1], entity.Transform.Coordinates);
break;
}
default:
{
shell.WriteLine(Help);
return;
}
}
if (!entity.TryGetComponent(out IBody? body))
{
var random = IoCManager.Resolve<IRobustRandom>();
var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}";
shell.WriteLine(text);
return;
}
if (!hand.TryGetComponent(out IBodyPart? part))
{
shell.WriteLine($"Hand entity {hand} does not have a {nameof(IBodyPart)} component.");
return;
}
var slot = part.GetHashCode().ToString();
body.SetPart(slot, part);
shell.WriteLine($"Added hand to entity {entity.Name}");
}
}
}

View File

@@ -0,0 +1,106 @@
#nullable enable
using Content.Server.Administration;
using Content.Shared.Administration;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using static Content.Server.Body.Part.BodyPartComponent;
namespace Content.Server.Body.Commands
{
[AdminCommand(AdminFlags.Fun)]
public class AttachBodyPartCommand : IConsoleCommand
{
public string Command => "attachbodypart";
public string Description => "Attaches a body part to you or someone else.";
public string Help => $"{Command} <partEntityUid> / {Command} <entityUid> <partEntityUid>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
var entityManager = IoCManager.Resolve<IEntityManager>();
IEntity entity;
EntityUid partUid;
switch (args.Length)
{
case 1:
if (player == null)
{
shell.WriteLine($"You need to specify an entity to attach the part to if you aren't a player.\n{Help}");
return;
}
if (player.AttachedEntity == null)
{
shell.WriteLine($"You need to specify an entity to attach the part to if you aren't attached to an entity.\n{Help}");
return;
}
if (!EntityUid.TryParse(args[0], out partUid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
}
entity = player.AttachedEntity;
break;
case 2:
if (!EntityUid.TryParse(args[0], out var entityUid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
}
if (!EntityUid.TryParse(args[1], out partUid))
{
shell.WriteLine($"{args[1]} is not a valid entity uid.");
return;
}
if (!entityManager.TryGetEntity(entityUid, out var tempEntity))
{
shell.WriteLine($"{entityUid} is not a valid entity.");
return;
}
entity = tempEntity;
break;
default:
shell.WriteLine(Help);
return;
}
if (!entity.TryGetComponent(out IBody? body))
{
shell.WriteLine($"Entity {entity.Name} with uid {entity.Uid} does not have a {nameof(IBody)} component.");
return;
}
if (!entityManager.TryGetEntity(partUid, out var partEntity))
{
shell.WriteLine($"{partUid} is not a valid entity.");
return;
}
if (!partEntity.TryGetComponent(out IBodyPart? part))
{
shell.WriteLine($"Entity {partEntity.Name} with uid {args[0]} does not have a {nameof(IBodyPart)} component.");
return;
}
if (body.HasPart(part))
{
shell.WriteLine($"Body part {partEntity.Name} with uid {partEntity.Uid} is already attached to entity {entity.Name} with uid {entity.Uid}");
return;
}
body.SetPart($"{nameof(AttachBodyPartVerb)}-{partEntity.Uid}", part);
}
}
}

View File

@@ -0,0 +1,65 @@
#nullable enable
using Content.Server.Administration;
using Content.Shared.Administration;
using Content.Shared.Body.Components;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.IoC;
using Robust.Shared.Random;
namespace Content.Server.Body.Commands
{
[AdminCommand(AdminFlags.Fun)]
class DestroyMechanismCommand : IConsoleCommand
{
public string Command => "destroymechanism";
public string Description => "Destroys a mechanism from your entity";
public string Help => $"Usage: {Command} <mechanism>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
if (player == null)
{
shell.WriteLine("Only a player can run this command.");
return;
}
if (args.Length == 0)
{
shell.WriteLine(Help);
return;
}
if (player.AttachedEntity == null)
{
shell.WriteLine("You have no entity.");
return;
}
if (!player.AttachedEntity.TryGetComponent(out IBody? body))
{
var random = IoCManager.Resolve<IRobustRandom>();
var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}";
shell.WriteLine(text);
return;
}
var mechanismName = string.Join(" ", args).ToLowerInvariant();
foreach (var (part, _) in body.Parts)
foreach (var mechanism in part.Mechanisms)
{
if (mechanism.Name.ToLowerInvariant() == mechanismName)
{
part.DeleteMechanism(mechanism);
shell.WriteLine($"Mechanism with name {mechanismName} has been destroyed.");
return;
}
}
shell.WriteLine($"No mechanism was found with name {mechanismName}.");
}
}
}

View File

@@ -0,0 +1,57 @@
#nullable enable
using System.Linq;
using Content.Server.Administration;
using Content.Shared.Administration;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.IoC;
using Robust.Shared.Random;
namespace Content.Server.Body.Commands
{
[AdminCommand(AdminFlags.Fun)]
class RemoveHandCommand : IConsoleCommand
{
public string Command => "removehand";
public string Description => "Removes a hand from your entity.";
public string Help => $"Usage: {Command}";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
if (player == null)
{
shell.WriteLine("Only a player can run this command.");
return;
}
if (player.AttachedEntity == null)
{
shell.WriteLine("You have no entity.");
return;
}
if (!player.AttachedEntity.TryGetComponent(out IBody? body))
{
var random = IoCManager.Resolve<IRobustRandom>();
var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}";
shell.WriteLine(text);
return;
}
var hand = body.GetPartsOfType(BodyPartType.Hand).FirstOrDefault();
if (hand == null)
{
shell.WriteLine("You have no hands.");
}
else
{
body.RemovePart(hand);
}
}
}
}

View File

@@ -0,0 +1,162 @@
#nullable enable
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.UserInterface;
using Content.Shared.Body.Components;
using Content.Shared.Body.Mechanism;
using Content.Shared.Body.Part;
using Content.Shared.Body.Surgery;
using Content.Shared.Interaction;
using Content.Shared.Notification;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Mechanism
{
[RegisterComponent]
[ComponentReference(typeof(SharedMechanismComponent))]
[ComponentReference(typeof(IMechanism))]
public class MechanismComponent : SharedMechanismComponent, IAfterInteract
{
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(SurgeryUIKey.Key);
public override void Initialize()
{
base.Initialize();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += OnUIMessage;
}
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (eventArgs.Target == null)
{
return false;
}
CloseAllSurgeryUIs();
OptionsCache.Clear();
PerformerCache = null;
BodyCache = null;
if (eventArgs.Target.TryGetComponent(out IBody? body))
{
SendBodyPartListToUser(eventArgs, body);
}
else if (eventArgs.Target.TryGetComponent<IBodyPart>(out var part))
{
DebugTools.AssertNotNull(part);
if (!part.TryAddMechanism(this))
{
eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("You can't fit it in!"));
}
}
return true;
}
private void SendBodyPartListToUser(AfterInteractEventArgs eventArgs, IBody body)
{
// Create dictionary to send to client (text to be shown : data sent back if selected)
var toSend = new Dictionary<string, int>();
foreach (var (part, slot) in body.Parts)
{
// For each limb in the target, add it to our cache if it is a valid option.
if (part.CanAddMechanism(this))
{
OptionsCache.Add(IdHash, slot);
toSend.Add(part + ": " + part.Name, IdHash++);
}
}
if (OptionsCache.Count > 0 &&
eventArgs.User.TryGetComponent(out ActorComponent? actor))
{
OpenSurgeryUI(actor.PlayerSession);
UpdateSurgeryUIBodyPartRequest(actor.PlayerSession, toSend);
PerformerCache = eventArgs.User;
BodyCache = body;
}
else // If surgery cannot be performed, show message saying so.
{
eventArgs.Target?.PopupMessage(eventArgs.User,
Loc.GetString("You see no way to install the {0}.", Owner.Name));
}
}
/// <summary>
/// Called after the client chooses from a list of possible BodyParts that can be operated on.
/// </summary>
private void HandleReceiveBodyPart(int key)
{
if (PerformerCache == null ||
!PerformerCache.TryGetComponent(out ActorComponent? actor))
{
return;
}
CloseSurgeryUI(actor.PlayerSession);
if (BodyCache == null)
{
return;
}
// TODO: sanity checks to see whether user is in range, user is still able-bodied, target is still the same, etc etc
if (!OptionsCache.TryGetValue(key, out var targetObject))
{
BodyCache.Owner.PopupMessage(PerformerCache,
Loc.GetString("You see no useful way to use the {0} anymore.", Owner.Name));
return;
}
var target = (IBodyPart) targetObject;
var message = target.TryAddMechanism(this)
? Loc.GetString("You jam {0:theName} inside {1:them}.", Owner, PerformerCache)
: Loc.GetString("You can't fit it in!");
BodyCache.Owner.PopupMessage(PerformerCache, message);
// TODO: {1:theName}
}
private void OpenSurgeryUI(IPlayerSession session)
{
UserInterface?.Open(session);
}
private void UpdateSurgeryUIBodyPartRequest(IPlayerSession session, Dictionary<string, int> options)
{
UserInterface?.SendMessage(new RequestBodyPartSurgeryUIMessage(options), session);
}
private void CloseSurgeryUI(IPlayerSession session)
{
UserInterface?.Close(session);
}
private void CloseAllSurgeryUIs()
{
UserInterface?.CloseAll();
}
private void OnUIMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case ReceiveBodyPartSurgeryUIMessage msg:
HandleReceiveBodyPart(msg.SelectedOptionId);
break;
}
}
}
}

View File

@@ -0,0 +1,273 @@
#nullable enable
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.UserInterface;
using Content.Shared.Body.Components;
using Content.Shared.Body.Mechanism;
using Content.Shared.Body.Part;
using Content.Shared.Body.Surgery;
using Content.Shared.Interaction;
using Content.Shared.Notification;
using Content.Shared.Random.Helpers;
using Content.Shared.Verbs;
using Robust.Server.Console;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Part
{
[RegisterComponent]
[ComponentReference(typeof(SharedBodyPartComponent))]
[ComponentReference(typeof(IBodyPart))]
public class BodyPartComponent : SharedBodyPartComponent, IAfterInteract
{
private readonly Dictionary<int, object> _optionsCache = new();
private IBody? _owningBodyCache;
private int _idHash;
private IEntity? _surgeonCache;
private Container _mechanismContainer = default!;
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(SurgeryUIKey.Key);
public override bool CanAddMechanism(IMechanism mechanism)
{
return base.CanAddMechanism(mechanism) &&
_mechanismContainer.CanInsert(mechanism.Owner);
}
protected override void OnAddMechanism(IMechanism mechanism)
{
base.OnAddMechanism(mechanism);
_mechanismContainer.Insert(mechanism.Owner);
}
protected override void OnRemoveMechanism(IMechanism mechanism)
{
base.OnRemoveMechanism(mechanism);
_mechanismContainer.Remove(mechanism.Owner);
mechanism.Owner.RandomOffset(0.25f);
}
public override void Initialize()
{
base.Initialize();
_mechanismContainer = Owner.EnsureContainer<Container>($"{Name}-{nameof(BodyPartComponent)}");
// This is ran in Startup as entities spawned in Initialize
// are not synced to the client since they are assumed to be
// identical on it
foreach (var mechanismId in MechanismIds)
{
var entity = Owner.EntityManager.SpawnEntity(mechanismId, Owner.Transform.MapPosition);
if (!entity.TryGetComponent(out IMechanism? mechanism))
{
Logger.Error($"Entity {mechanismId} does not have a {nameof(IMechanism)} component.");
continue;
}
TryAddMechanism(mechanism, true);
}
}
protected override void Startup()
{
base.Startup();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += OnUIMessage;
}
foreach (var mechanism in Mechanisms)
{
mechanism.Dirty();
}
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
// TODO BODY
if (eventArgs.Target == null)
{
return false;
}
CloseAllSurgeryUIs();
_optionsCache.Clear();
_surgeonCache = null;
_owningBodyCache = null;
if (eventArgs.Target.TryGetComponent(out IBody? body))
{
SendSlots(eventArgs, body);
}
return true;
}
private void SendSlots(AfterInteractEventArgs eventArgs, IBody body)
{
// Create dictionary to send to client (text to be shown : data sent back if selected)
var toSend = new Dictionary<string, int>();
// Here we are trying to grab a list of all empty BodySlots adjacent to an existing BodyPart that can be
// attached to. i.e. an empty left hand slot, connected to an occupied left arm slot would be valid.
foreach (var slot in body.EmptySlots)
{
if (slot.PartType != PartType)
{
continue;
}
foreach (var connection in slot.Connections)
{
if (connection.Part == null ||
!connection.Part.CanAttachPart(this))
{
continue;
}
_optionsCache.Add(_idHash, slot);
toSend.Add(slot.Id, _idHash++);
}
}
if (_optionsCache.Count > 0)
{
OpenSurgeryUI(eventArgs.User.GetComponent<ActorComponent>().PlayerSession);
BodyPartSlotRequest(eventArgs.User.GetComponent<ActorComponent>().PlayerSession,
toSend);
_surgeonCache = eventArgs.User;
_owningBodyCache = body;
}
else // If surgery cannot be performed, show message saying so.
{
eventArgs.Target?.PopupMessage(eventArgs.User,
Loc.GetString("You see no way to install {0:theName}.", Owner));
}
}
/// <summary>
/// Called after the client chooses from a list of possible
/// BodyPartSlots to install the limb on.
/// </summary>
private void ReceiveBodyPartSlot(int key)
{
if (_surgeonCache == null ||
!_surgeonCache.TryGetComponent(out ActorComponent? actor))
{
return;
}
CloseSurgeryUI(actor.PlayerSession);
if (_owningBodyCache == null)
{
return;
}
// TODO: sanity checks to see whether user is in range, user is still able-bodied, target is still the same, etc etc
if (!_optionsCache.TryGetValue(key, out var targetObject))
{
_owningBodyCache.Owner.PopupMessage(_surgeonCache,
Loc.GetString("You see no useful way to attach {0:theName} anymore.", Owner));
}
var target = (string) targetObject!;
var message = _owningBodyCache.TryAddPart(target, this)
? Loc.GetString("You attach {0:theName}.", Owner)
: Loc.GetString("You can't attach {0:theName}!", Owner);
_owningBodyCache.Owner.PopupMessage(_surgeonCache, message);
}
private void OpenSurgeryUI(IPlayerSession session)
{
UserInterface?.Open(session);
}
private void BodyPartSlotRequest(IPlayerSession session, Dictionary<string, int> options)
{
UserInterface?.SendMessage(new RequestBodyPartSlotSurgeryUIMessage(options), session);
}
private void CloseSurgeryUI(IPlayerSession session)
{
UserInterface?.Close(session);
}
private void CloseAllSurgeryUIs()
{
UserInterface?.CloseAll();
}
private void OnUIMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case ReceiveBodyPartSlotSurgeryUIMessage msg:
ReceiveBodyPartSlot(msg.SelectedOptionId);
break;
}
}
[Verb]
public class AttachBodyPartVerb : Verb<BodyPartComponent>
{
protected override void GetData(IEntity user, BodyPartComponent component, VerbData data)
{
data.Visibility = VerbVisibility.Invisible;
if (user == component.Owner)
{
return;
}
if (!user.TryGetComponent(out ActorComponent? actor))
{
return;
}
var groupController = IoCManager.Resolve<IConGroupController>();
if (!groupController.CanCommand(actor.PlayerSession, "attachbodypart"))
{
return;
}
if (!user.TryGetComponent(out IBody? body))
{
return;
}
if (body.HasPart(component))
{
return;
}
data.Visibility = VerbVisibility.Visible;
data.Text = Loc.GetString("Attach Body Part");
}
protected override void Activate(IEntity user, BodyPartComponent component)
{
if (!user.TryGetComponent(out IBody? body))
{
return;
}
body.SetPart($"{nameof(AttachBodyPartVerb)}-{component.Owner.Uid}", component);
}
}
}
}

View File

@@ -0,0 +1,72 @@
#nullable enable
using Content.Server.GameObjects.Components.Atmos;
using Robust.Shared.GameObjects;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Respiratory
{
[RegisterComponent]
public class InternalsComponent : Component
{
public override string Name => "Internals";
[ViewVariables] public IEntity? GasTankEntity { get; set; }
[ViewVariables] public IEntity? BreathToolEntity { get; set; }
public void DisconnectBreathTool()
{
var old = BreathToolEntity;
BreathToolEntity = null;
if (old != null && old.TryGetComponent(out BreathToolComponent? breathTool) )
{
breathTool.DisconnectInternals();
DisconnectTank();
}
}
public void ConnectBreathTool(IEntity toolEntity)
{
if (BreathToolEntity != null && BreathToolEntity.TryGetComponent(out BreathToolComponent? tool))
{
tool.DisconnectInternals();
}
BreathToolEntity = toolEntity;
}
public void DisconnectTank()
{
if (GasTankEntity != null && GasTankEntity.TryGetComponent(out GasTankComponent? tank))
{
tank.DisconnectFromInternals(Owner);
}
GasTankEntity = null;
}
public bool TryConnectTank(IEntity tankEntity)
{
if (BreathToolEntity == null)
return false;
if (GasTankEntity != null && GasTankEntity.TryGetComponent(out GasTankComponent? tank))
{
tank.DisconnectFromInternals(Owner);
}
GasTankEntity = tankEntity;
return true;
}
public bool AreInternalsWorking()
{
return BreathToolEntity != null &&
GasTankEntity != null &&
BreathToolEntity.TryGetComponent(out BreathToolComponent? breathTool) &&
breathTool.IsFunctional &&
GasTankEntity.TryGetComponent(out GasTankComponent? gasTank) &&
gasTank.Air != null;
}
}
}

View File

@@ -0,0 +1,64 @@
#nullable enable
using Content.Server.UserInterface;
using Content.Shared.Body.Components;
using Content.Shared.Body.Scanner;
using Content.Shared.Interaction;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Scanner
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(SharedBodyScannerComponent))]
public class BodyScannerComponent : SharedBodyScannerComponent, IActivate
{
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(BodyScannerUiKey.Key);
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out ActorComponent? actor))
{
return;
}
var session = actor.PlayerSession;
if (session.AttachedEntity == null)
{
return;
}
if (session.AttachedEntity.TryGetComponent(out IBody? body))
{
var state = InterfaceState(body);
UserInterface?.SetState(state);
}
UserInterface?.Open(session);
}
public override void Initialize()
{
base.Initialize();
Owner.EnsureComponentWarn<ServerUserInterfaceComponent>();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage;
}
}
private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg) { }
/// <summary>
/// Copy BodyTemplate and BodyPart data into a common data class that the client can read.
/// </summary>
private BodyScannerUIState InterfaceState(IBody body)
{
return new(body.Owner.Uid);
}
}
}

View File

@@ -0,0 +1,371 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Content.Server.DoAfter;
using Content.Shared.Body.Components;
using Content.Shared.Body.Mechanism;
using Content.Shared.Body.Part;
using Content.Shared.Body.Surgery;
using Content.Shared.Notification;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using static Content.Shared.Body.Surgery.ISurgeryData;
namespace Content.Server.Body.Surgery
{
/// <summary>
/// Data class representing the surgery state of a biological entity.
/// </summary>
[RegisterComponent]
[ComponentReference(typeof(ISurgeryData))]
public class BiologicalSurgeryDataComponent : Component, ISurgeryData
{
public override string Name => "BiologicalSurgeryData";
private readonly HashSet<IMechanism> _disconnectedOrgans = new();
private bool SkinOpened { get; set; }
private bool SkinRetracted { get; set; }
private bool VesselsClamped { get; set; }
public IBodyPart? Parent => Owner.GetComponentOrNull<IBodyPart>();
public BodyPartType? ParentType => Parent?.PartType;
private void AddDisconnectedOrgan(IMechanism mechanism)
{
if (_disconnectedOrgans.Add(mechanism))
{
Dirty();
}
}
private void RemoveDisconnectedOrgan(IMechanism mechanism)
{
if (_disconnectedOrgans.Remove(mechanism))
{
Dirty();
}
}
private async Task<bool> SurgeryDoAfter(IEntity performer)
{
if (!performer.HasComponent<DoAfterComponent>())
{
return true;
}
var doAfterSystem = EntitySystem.Get<DoAfterSystem>();
var target = Parent?.Body?.Owner ?? Owner;
var args = new DoAfterEventArgs(performer, 3, target: target)
{
BreakOnUserMove = true,
BreakOnTargetMove = true
};
return await doAfterSystem.DoAfter(args) == DoAfterStatus.Finished;
}
private bool HasIncisionNotClamped()
{
return SkinOpened && !VesselsClamped;
}
private bool HasClampedIncisionNotRetracted()
{
return SkinOpened && VesselsClamped && !SkinRetracted;
}
private bool HasFullyOpenIncision()
{
return SkinOpened && VesselsClamped && SkinRetracted;
}
public string GetDescription()
{
if (Parent == null)
{
return string.Empty;
}
var toReturn = new StringBuilder();
if (HasIncisionNotClamped())
{
toReturn.Append(Loc.GetString("The skin on {0:their} {1} has an incision, but it is prone to bleeding.",
Owner, Parent.Name));
}
else if (HasClampedIncisionNotRetracted())
{
toReturn.AppendLine(Loc.GetString("The skin on {0:their} {1} has an incision, but it is not retracted.",
Owner, Parent.Name));
}
else if (HasFullyOpenIncision())
{
toReturn.AppendLine(Loc.GetString("There is an incision on {0:their} {1}.\n", Owner, Parent.Name));
foreach (var mechanism in _disconnectedOrgans)
{
toReturn.AppendLine(Loc.GetString("{0:their} {1} is loose.", Owner, mechanism.Name));
}
}
return toReturn.ToString();
}
public bool CanAddMechanism(IMechanism mechanism)
{
return Parent != null &&
SkinOpened &&
VesselsClamped &&
SkinRetracted;
}
public bool CanAttachBodyPart(IBodyPart part)
{
return Parent != null;
// TODO BODY if a part is disconnected, you should have to do some surgery to allow another body part to be attached.
}
public SurgeryAction? GetSurgeryStep(SurgeryType toolType)
{
if (Parent == null)
{
return null;
}
if (toolType == SurgeryType.Amputation)
{
return RemoveBodyPartSurgery;
}
if (!SkinOpened)
{
// Case: skin is normal.
if (toolType == SurgeryType.Incision)
{
return OpenSkinSurgery;
}
}
else if (!VesselsClamped)
{
// Case: skin is opened, but not clamped.
switch (toolType)
{
case SurgeryType.VesselCompression:
return ClampVesselsSurgery;
case SurgeryType.Cauterization:
return CauterizeIncisionSurgery;
}
}
else if (!SkinRetracted)
{
// Case: skin is opened and clamped, but not retracted.
switch (toolType)
{
case SurgeryType.Retraction:
return RetractSkinSurgery;
case SurgeryType.Cauterization:
return CauterizeIncisionSurgery;
}
}
else
{
// Case: skin is fully open.
if (Parent.Mechanisms.Count > 0 &&
toolType == SurgeryType.VesselCompression)
{
if (_disconnectedOrgans.Except(Parent.Mechanisms).Count() != 0 ||
Parent.Mechanisms.Except(_disconnectedOrgans).Count() != 0)
{
return LoosenOrganSurgery;
}
}
if (_disconnectedOrgans.Count > 0 && toolType == SurgeryType.Incision)
{
return RemoveOrganSurgery;
}
if (toolType == SurgeryType.Cauterization)
{
return CauterizeIncisionSurgery;
}
}
return null;
}
public bool CheckSurgery(SurgeryType toolType)
{
return GetSurgeryStep(toolType) != null;
}
public bool PerformSurgery(SurgeryType surgeryType, IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
var step = GetSurgeryStep(surgeryType);
if (step == null)
{
return false;
}
step(container, surgeon, performer);
return true;
}
private async void OpenSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null)
{
return;
}
performer.PopupMessage(Loc.GetString("Cut open the skin..."));
if (await SurgeryDoAfter(performer))
{
SkinOpened = true;
}
}
private async void ClampVesselsSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null) return;
performer.PopupMessage(Loc.GetString("Clamp the vessels..."));
if (await SurgeryDoAfter(performer))
{
VesselsClamped = true;
}
}
private async void RetractSkinSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null) return;
performer.PopupMessage(Loc.GetString("Retracting the skin..."));
if (await SurgeryDoAfter(performer))
{
SkinRetracted = true;
}
}
private async void CauterizeIncisionSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null) return;
performer.PopupMessage(Loc.GetString("Cauterizing the incision..."));
if (await SurgeryDoAfter(performer))
{
SkinOpened = false;
VesselsClamped = false;
SkinRetracted = false;
}
}
private void LoosenOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null) return;
if (Parent.Mechanisms.Count <= 0) return;
var toSend = new List<IMechanism>();
foreach (var mechanism in Parent.Mechanisms)
{
if (!_disconnectedOrgans.Contains(mechanism))
{
toSend.Add(mechanism);
}
}
if (toSend.Count > 0)
{
surgeon.RequestMechanism(toSend, LoosenOrganSurgeryCallback);
}
}
private async void LoosenOrganSurgeryCallback(IMechanism? target, IBodyPartContainer container, ISurgeon surgeon,
IEntity performer)
{
if (Parent == null || target == null || !Parent.Mechanisms.Contains(target))
{
return;
}
performer.PopupMessage(Loc.GetString("Loosening the organ..."));
if (!performer.HasComponent<DoAfterComponent>())
{
AddDisconnectedOrgan(target);
return;
}
if (await SurgeryDoAfter(performer))
{
AddDisconnectedOrgan(target);
}
}
private void RemoveOrganSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null) return;
if (_disconnectedOrgans.Count <= 0)
{
return;
}
if (_disconnectedOrgans.Count == 1)
{
RemoveOrganSurgeryCallback(_disconnectedOrgans.First(), container, surgeon, performer);
}
else
{
surgeon.RequestMechanism(_disconnectedOrgans, RemoveOrganSurgeryCallback);
}
}
private async void RemoveOrganSurgeryCallback(IMechanism? target, IBodyPartContainer container, ISurgeon surgeon,
IEntity performer)
{
if (Parent == null || target == null || !Parent.Mechanisms.Contains(target))
{
return;
}
performer.PopupMessage(Loc.GetString("Removing the organ..."));
if (!performer.HasComponent<DoAfterComponent>())
{
Parent.RemoveMechanism(target, performer.Transform.Coordinates);
RemoveDisconnectedOrgan(target);
return;
}
if (await SurgeryDoAfter(performer))
{
Parent.RemoveMechanism(target, performer.Transform.Coordinates);
RemoveDisconnectedOrgan(target);
}
}
private async void RemoveBodyPartSurgery(IBodyPartContainer container, ISurgeon surgeon, IEntity performer)
{
if (Parent == null) return;
if (container is not IBody body) return;
performer.PopupMessage(Loc.GetString("Sawing off the limb!"));
if (await SurgeryDoAfter(performer))
{
body.RemovePart(Parent);
}
}
}
}

View File

@@ -0,0 +1,278 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.Body.Mechanism;
using Content.Server.Body.Surgery.Messages;
using Content.Server.UserInterface;
using Content.Shared.Body.Components;
using Content.Shared.Body.Mechanism;
using Content.Shared.Body.Part;
using Content.Shared.Body.Surgery;
using Content.Shared.Interaction;
using Content.Shared.NetIDs;
using Content.Shared.Notification;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Body.Surgery.Components
{
/// <summary>
/// Server-side component representing a generic tool capable of performing surgery.
/// For instance, the scalpel.
/// </summary>
[RegisterComponent]
public class SurgeryToolComponent : Component, ISurgeon, IAfterInteract
{
public override string Name => "SurgeryTool";
public override uint? NetID => ContentNetIDs.SURGERY;
private readonly Dictionary<int, object> _optionsCache = new();
[DataField("baseOperateTime")]
private float _baseOperateTime = 5;
private ISurgeon.MechanismRequestCallback? _callbackCache;
private int _idHash;
[DataField("surgeryType")]
private SurgeryType _surgeryType = SurgeryType.Incision;
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(SurgeryUIKey.Key);
public IBody? BodyCache { get; private set; }
public IEntity? PerformerCache { get; private set; }
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (eventArgs.Target == null)
{
return false;
}
if (!eventArgs.User.TryGetComponent(out ActorComponent? actor))
{
return false;
}
CloseAllSurgeryUIs();
// Attempt surgery on a body by sending a list of operable parts for the client to choose from
if (eventArgs.Target.TryGetComponent(out IBody? body))
{
// Create dictionary to send to client (text to be shown : data sent back if selected)
var toSend = new Dictionary<string, int>();
foreach (var (part, slot) in body.Parts)
{
// For each limb in the target, add it to our cache if it is a valid option.
if (part.SurgeryCheck(_surgeryType))
{
_optionsCache.Add(_idHash, part);
toSend.Add(slot.Id + ": " + part.Name, _idHash++);
}
}
if (_optionsCache.Count > 0)
{
OpenSurgeryUI(actor.PlayerSession);
UpdateSurgeryUIBodyPartRequest(actor.PlayerSession, toSend);
PerformerCache = eventArgs.User; // Also, cache the data.
BodyCache = body;
}
else // If surgery cannot be performed, show message saying so.
{
NotUsefulPopup();
}
}
else if (eventArgs.Target.TryGetComponent<IBodyPart>(out var part))
{
// Attempt surgery on a DroppedBodyPart - there's only one possible target so no need for selection UI
PerformerCache = eventArgs.User;
// If surgery can be performed...
if (!part.SurgeryCheck(_surgeryType))
{
NotUsefulPopup();
return true;
}
// ...do the surgery.
if (part.AttemptSurgery(_surgeryType, part, this,
eventArgs.User))
{
return true;
}
// Log error if the surgery fails somehow.
Logger.Debug($"Error when trying to perform surgery on ${nameof(IBodyPart)} {eventArgs.User.Name}");
throw new InvalidOperationException();
}
return true;
}
public float BaseOperationTime { get => _baseOperateTime; set => _baseOperateTime = value; }
public void RequestMechanism(IEnumerable<IMechanism> options, ISurgeon.MechanismRequestCallback callback)
{
var toSend = new Dictionary<string, int>();
foreach (var mechanism in options)
{
_optionsCache.Add(_idHash, mechanism);
toSend.Add(mechanism.Name, _idHash++);
}
if (_optionsCache.Count > 0 && PerformerCache != null)
{
OpenSurgeryUI(PerformerCache.GetComponent<ActorComponent>().PlayerSession);
UpdateSurgeryUIMechanismRequest(PerformerCache.GetComponent<ActorComponent>().PlayerSession,
toSend);
_callbackCache = callback;
}
else
{
Logger.Debug("Error on callback from mechanisms: there were no viable options to choose from!");
throw new InvalidOperationException();
}
}
public override void Initialize()
{
base.Initialize();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage;
}
}
private void OpenSurgeryUI(IPlayerSession session)
{
UserInterface?.Open(session);
var message = new SurgeryWindowOpenMessage(this);
SendMessage(message);
Owner.EntityManager.EventBus.RaiseEvent(EventSource.Local, message);
}
private void UpdateSurgeryUIBodyPartRequest(IPlayerSession session, Dictionary<string, int> options)
{
UserInterface?.SendMessage(new RequestBodyPartSurgeryUIMessage(options), session);
}
private void UpdateSurgeryUIMechanismRequest(IPlayerSession session, Dictionary<string, int> options)
{
UserInterface?.SendMessage(new RequestMechanismSurgeryUIMessage(options), session);
}
private void ClearUIData()
{
_optionsCache.Clear();
PerformerCache = null;
BodyCache = null;
_callbackCache = null;
}
private void CloseSurgeryUI(IPlayerSession session)
{
UserInterface?.Close(session);
ClearUIData();
}
public void CloseAllSurgeryUIs()
{
UserInterface?.CloseAll();
ClearUIData();
}
private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case ReceiveBodyPartSurgeryUIMessage msg:
HandleReceiveBodyPart(msg.SelectedOptionId);
break;
case ReceiveMechanismSurgeryUIMessage msg:
HandleReceiveMechanism(msg.SelectedOptionId);
break;
}
}
/// <summary>
/// Called after the client chooses from a list of possible
/// <see cref="IBodyPart"/> that can be operated on.
/// </summary>
private void HandleReceiveBodyPart(int key)
{
if (PerformerCache == null ||
!PerformerCache.TryGetComponent(out ActorComponent? actor))
{
return;
}
CloseSurgeryUI(actor.PlayerSession);
// TODO: sanity checks to see whether user is in range, user is still able-bodied, target is still the same, etc etc
if (!_optionsCache.TryGetValue(key, out var targetObject) ||
BodyCache == null)
{
NotUsefulAnymorePopup();
return;
}
var target = (IBodyPart) targetObject!;
// TODO BODY Reconsider
if (!target.AttemptSurgery(_surgeryType, BodyCache, this, PerformerCache))
{
NotUsefulAnymorePopup();
}
}
/// <summary>
/// Called after the client chooses from a list of possible
/// <see cref="IMechanism"/> to choose from.
/// </summary>
private void HandleReceiveMechanism(int key)
{
// TODO: sanity checks to see whether user is in range, user is still able-bodied, target is still the same, etc etc
if (BodyCache == null ||
!_optionsCache.TryGetValue(key, out var targetObject) ||
targetObject is not MechanismComponent target ||
PerformerCache == null ||
!PerformerCache.TryGetComponent(out ActorComponent? actor))
{
NotUsefulAnymorePopup();
return;
}
CloseSurgeryUI(actor.PlayerSession);
_callbackCache?.Invoke(target, BodyCache, this, PerformerCache);
}
private void NotUsefulPopup()
{
if (PerformerCache == null) return;
BodyCache?.Owner.PopupMessage(PerformerCache,
Loc.GetString("You see no useful way to use {0:theName}.", Owner));
}
private void NotUsefulAnymorePopup()
{
if (PerformerCache == null) return;
BodyCache?.Owner.PopupMessage(PerformerCache,
Loc.GetString("You see no useful way to use {0:theName} anymore.", Owner));
}
}
}

View File

@@ -0,0 +1,71 @@
using System.Collections.Generic;
using Content.Server.Body.Surgery.Messages;
using Content.Shared.ActionBlocker;
using Content.Shared.GameTicking;
using Content.Shared.Interaction.Helpers;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
namespace Content.Server.Body.Surgery.Components
{
[UsedImplicitly]
public class SurgeryToolSystem : EntitySystem, IResettingEntitySystem
{
private readonly HashSet<SurgeryToolComponent> _openSurgeryUIs = new();
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SurgeryWindowOpenMessage>(OnSurgeryWindowOpen);
SubscribeLocalEvent<SurgeryWindowCloseMessage>(OnSurgeryWindowClose);
}
public override void Shutdown()
{
base.Shutdown();
UnsubscribeLocalEvent<SurgeryWindowOpenMessage>();
UnsubscribeLocalEvent<SurgeryWindowCloseMessage>();
}
public void Reset()
{
_openSurgeryUIs.Clear();
}
private void OnSurgeryWindowOpen(SurgeryWindowOpenMessage ev)
{
_openSurgeryUIs.Add(ev.Tool);
}
private void OnSurgeryWindowClose(SurgeryWindowCloseMessage ev)
{
_openSurgeryUIs.Remove(ev.Tool);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
foreach (var tool in _openSurgeryUIs)
{
if (tool.PerformerCache == null)
{
continue;
}
if (tool.BodyCache == null)
{
continue;
}
if (!ActionBlockerSystem.CanInteract(tool.PerformerCache) ||
!tool.PerformerCache.InRangeUnobstructed(tool.BodyCache))
{
tool.CloseAllSurgeryUIs();
}
}
}
}
}

View File

@@ -0,0 +1,14 @@
using Content.Server.Body.Surgery.Components;
namespace Content.Server.Body.Surgery.Messages
{
public class SurgeryWindowCloseMessage
{
public SurgeryWindowCloseMessage(SurgeryToolComponent tool)
{
Tool = tool;
}
public SurgeryToolComponent Tool { get; }
}
}

View File

@@ -0,0 +1,15 @@
using Content.Server.Body.Surgery.Components;
using Robust.Shared.GameObjects;
namespace Content.Server.Body.Surgery.Messages
{
public class SurgeryWindowOpenMessage : ComponentMessage
{
public SurgeryWindowOpenMessage(SurgeryToolComponent tool)
{
Tool = tool;
}
public SurgeryToolComponent Tool { get; }
}
}