Refactoring body system to use containers and general body cleanup (#20202)

Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
This commit is contained in:
Jezithyr
2023-09-21 00:23:02 -07:00
committed by GitHub
parent d888d9ad67
commit 31b2c9f830
38 changed files with 1298 additions and 1098 deletions

3
.github/CODEOWNERS vendored
View File

@@ -60,3 +60,6 @@
/Content.*/Atmos/ @Partmedia
/Content.*/Botany/ @Partmedia
#Jezi
/Content.*/Medical @Jezithyr
/Content.*/Body @Jezithyr

View File

@@ -38,6 +38,7 @@ namespace Content.IntegrationTests.Tests.Body
var entityManager = server.ResolveDependency<IEntityManager>();
var mapManager = server.ResolveDependency<IMapManager>();
var appearanceSystem = entityManager.System<SharedAppearanceSystem>();
var xformSystem = entityManager.System<SharedTransformSystem>();
await server.WaitAssertion(() =>
{
@@ -60,7 +61,7 @@ namespace Content.IntegrationTests.Tests.Body
foreach (var leg in legs)
{
bodySystem.DropPart(leg.Id, leg.Component);
xformSystem.DetachParentToNull(leg.Id, entityManager.GetComponent<TransformComponent>(leg.Id));
}
});

View File

@@ -3,6 +3,7 @@ using System.Linq;
using Content.Shared.Body.Components;
using Content.Shared.Body.Systems;
using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
@@ -31,6 +32,7 @@ public sealed class SaveLoadReparentTest
var maps = server.ResolveDependency<IMapManager>();
var mapLoader = entities.System<MapLoaderSystem>();
var bodySystem = entities.System<SharedBodySystem>();
var containerSystem = entities.System<SharedContainerSystem>();
await server.WaitAssertion(() =>
{
@@ -40,7 +42,7 @@ public sealed class SaveLoadReparentTest
Assert.That(entities.HasComponent<BodyComponent>(human), Is.True);
var parts = bodySystem.GetBodyChildren(human).ToArray();
var parts = bodySystem.GetBodyChildren(human).Skip(1).ToArray();
var organs = bodySystem.GetBodyOrgans(human).ToArray();
Assert.Multiple(() =>
@@ -54,9 +56,17 @@ public sealed class SaveLoadReparentTest
Assert.Multiple(() =>
{
Assert.That(component.Body, Is.EqualTo(human));
Assert.That(component.ParentSlot, Is.Not.Null);
Assert.That(component.ParentSlot.Parent, Is.Not.EqualTo(default(EntityUid)));
Assert.That(component.ParentSlot.Child, Is.EqualTo(id));
Assert.That(component.Body, Is.Not.Null);
var parent = bodySystem.GetParentPartOrNull(id);
Assert.That(parent, Is.Not.EqualTo(default(EntityUid)));
if (!bodySystem.IsPartRoot(component.Body.Value, id, null, component))
{
Assert.That(parent, Is.Not.Null);
}
else
{
Assert.That(parent, Is.Null);
}
});
foreach (var (slotId, slot) in component.Children)
@@ -64,19 +74,22 @@ public sealed class SaveLoadReparentTest
Assert.Multiple(() =>
{
Assert.That(slot.Id, Is.EqualTo(slotId));
Assert.That(slot.Parent, Is.Not.EqualTo(default(EntityUid)));
var container =
containerSystem.GetContainer(id, SharedBodySystem.GetPartSlotContainerId(slotId));
Assert.That(container.ContainedEntities, Is.Not.Empty);
});
}
}
foreach (var (id, component) in organs)
{
var parent = bodySystem.GetParentPartOrNull(id);
Assert.Multiple(() =>
{
Assert.That(component.Body, Is.EqualTo(human));
Assert.That(component.ParentSlot, Is.Not.Null);
Assert.That(component.ParentSlot.Parent, Is.Not.EqualTo(default(EntityUid)));
Assert.That(component.ParentSlot.Child, Is.EqualTo(id));
Assert.That(parent, Is.Not.Null);
Assert.That(parent.Value, Is.Not.EqualTo(default(EntityUid)));
});
}
@@ -115,7 +128,7 @@ public sealed class SaveLoadReparentTest
foreach (var (uid, body) in query)
{
human = uid;
parts = bodySystem.GetBodyChildren(human).ToArray();
parts = bodySystem.GetBodyChildren(human).Skip(1).ToArray();
organs = bodySystem.GetBodyOrgans(human).ToArray();
Assert.Multiple(() =>
@@ -126,12 +139,13 @@ public sealed class SaveLoadReparentTest
foreach (var (id, component) in parts)
{
var parent = bodySystem.GetParentPartOrNull(id);
Assert.Multiple(() =>
{
Assert.That(component.Body, Is.EqualTo(human));
Assert.That(component.ParentSlot, Is.Not.Null);
Assert.That(component.ParentSlot.Parent, Is.Not.EqualTo(default(EntityUid)));
Assert.That(component.ParentSlot.Child, Is.EqualTo(id));
Assert.That(parent, Is.Not.Null);
Assert.That(parent.Value, Is.Not.EqualTo(default(EntityUid)));
});
foreach (var (slotId, slot) in component.Children)
@@ -139,19 +153,22 @@ public sealed class SaveLoadReparentTest
Assert.Multiple(() =>
{
Assert.That(slot.Id, Is.EqualTo(slotId));
Assert.That(slot.Parent, Is.Not.EqualTo(default(EntityUid)));
var container =
containerSystem.GetContainer(id, SharedBodySystem.GetPartSlotContainerId(slotId));
Assert.That(container.ContainedEntities, Is.Not.Empty);
});
}
}
foreach (var (id, component) in organs)
{
var parent = bodySystem.GetParentPartOrNull(id);
Assert.Multiple(() =>
{
Assert.That(component.Body, Is.EqualTo(human));
Assert.That(component.ParentSlot, Is.Not.Null);
Assert.That(component.ParentSlot.Parent, Is.Not.EqualTo(default(EntityUid)));
Assert.That(component.ParentSlot.Child, Is.EqualTo(id));
Assert.That(parent, Is.Not.Null);
Assert.That(parent.Value, Is.Not.EqualTo(default(EntityUid)));
});
}

View File

@@ -258,6 +258,7 @@ namespace Content.IntegrationTests.Tests.Buckle
var entityManager = server.ResolveDependency<IEntityManager>();
var handsSys = entityManager.EntitySysManager.GetEntitySystem<SharedHandsSystem>();
var buckleSystem = entityManager.EntitySysManager.GetEntitySystem<SharedBuckleSystem>();
var xformSystem = entityManager.System<SharedTransformSystem>();
await server.WaitAssertion(() =>
{
@@ -309,7 +310,7 @@ namespace Content.IntegrationTests.Tests.Buckle
// Break our guy's kneecaps
foreach (var leg in legs)
{
bodySystem.DropPart(leg.Id, leg.Component);
xformSystem.DetachParentToNull(leg.Id, entityManager.GetComponent<TransformComponent>(leg.Id));
}
});

View File

@@ -30,7 +30,7 @@ public sealed class RemoveEncryptionKeys : InteractionTest
Assert.That(comp.Channels, Has.Count.EqualTo(0));
});
// Checkl that the key was ejected and not just deleted or something.
// Check that the key was ejected and not just deleted or something.
await AssertEntityLookup(("EncryptionKeyCommon", 1));
// Re-insert a key.

View File

@@ -218,12 +218,13 @@ public abstract partial class InteractionTest
// Ensure that the player only has one hand, so that they do not accidentally pick up deconstruction products
await Server.WaitPost(() =>
{
// I lost an hour of my life trying to track down how the hell interaction tests were breaking
// so greatz to this. Just make your own body prototype!
var bodySystem = SEntMan.System<BodySystem>();
var hands = bodySystem.GetBodyChildrenOfType(SEntMan.GetEntity(Player), BodyPartType.Hand).ToArray();
for (var i = 1; i < hands.Length; i++)
{
bodySystem.DropPart(hands[i].Id);
SEntMan.DeleteEntity(hands[i].Id);
}
});

View File

@@ -1,5 +1,6 @@
using Content.Server.Body.Systems;
using Content.Shared.Administration;
using Content.Shared.Body.Part;
using Robust.Shared.Console;
namespace Content.Server.Administration.Commands
@@ -11,7 +12,7 @@ namespace Content.Server.Administration.Commands
public string Command => "addbodypart";
public string Description => "Adds a given entity to a containing body.";
public string Help => "Usage: addbodypart <entity uid> <body uid> <part slot>";
public string Help => "Usage: addbodypart <entity uid> <body uid> <part slot> <part type>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
@@ -37,7 +38,10 @@ namespace Content.Server.Administration.Commands
var parentId = _entManager.GetEntity(parentNetId);
var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.TryCreatePartSlotAndAttach(parentId, args[2], childId))
if (Enum.TryParse<BodyPartType>(args[3], out var partType) &&
bodySystem.TryCreatePartSlotAndAttach(parentId, args[2], childId, partType))
{
shell.WriteLine($@"Added {childId} to {parentId}.");
}

View File

@@ -35,7 +35,7 @@ namespace Content.Server.Administration.Commands
var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.AddOrganToFirstValidSlot(organId, partId))
if (bodySystem.AddOrganToFirstValidSlot(partId.Value, organId.Value))
{
shell.WriteLine($@"Added {organId} to {partId}.");
}

View File

@@ -27,16 +27,10 @@ namespace Content.Server.Administration.Commands
return;
}
var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.DropPart(entityUid))
{
shell.WriteLine($"Removed body part {_entManager.ToPrettyString(entityUid.Value)}.");
}
else
{
shell.WriteError("Was not a body part, or did not have a parent.");
}
// TODO: THIS IS JUST A MECHANISM COPYPASTE
var xformSystem = _entManager.System<SharedTransformSystem>();
xformSystem.AttachToGridOrMap(entityUid.Value);
shell.WriteLine($"Removed body part {_entManager.ToPrettyString(entityUid.Value)}");
}
}
}

View File

@@ -27,16 +27,9 @@ namespace Content.Server.Administration.Commands
return;
}
var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.DropOrgan(entityUid))
{
var xformSystem = _entManager.System<SharedTransformSystem>();
xformSystem.AttachToGridOrMap(entityUid.Value);
shell.WriteLine($"Removed organ {_entManager.ToPrettyString(entityUid.Value)}");
}
else
{
shell.WriteError("Was not a mechanism, or did not have a parent.");
}
}
}
}

View File

@@ -76,6 +76,7 @@ public sealed partial class AdminVerbSystem
[Dependency] private readonly VomitSystem _vomitSystem = default!;
[Dependency] private readonly WeldableSystem _weldableSystem = default!;
[Dependency] private readonly SharedContentEyeSystem _eyeSystem = default!;
[Dependency] private readonly SharedTransformSystem _transformSystem = default!;
// All smite verbs have names so invokeverb works.
private void AddSmiteVerbs(GetVerbsEvent<Verb> args)
@@ -293,8 +294,7 @@ public sealed partial class AdminVerbSystem
if (HasComp<BrainComponent>(xform.Owner) || HasComp<EyeComponent>(xform.Owner))
continue;
var coordinates = baseXform.Coordinates.Offset(_random.NextVector2(0.5f, 0.75f));
_bodySystem.DropOrganAt(organ.Owner, coordinates, organ);
_transformSystem.AttachToGridOrMap(organ.Owner);
}
_popupSystem.PopupEntity(Loc.GetString("admin-smite-vomit-organs-self"), args.Target,
@@ -317,7 +317,7 @@ public sealed partial class AdminVerbSystem
var baseXform = Transform(args.Target);
foreach (var part in _bodySystem.GetBodyChildrenOfType(args.Target, BodyPartType.Hand))
{
_bodySystem.DropPartAt(part.Id, baseXform.Coordinates, part.Component);
_transformSystem.AttachToGridOrMap(part.Id);
}
_popupSystem.PopupEntity(Loc.GetString("admin-smite-remove-hands-self"), args.Target,
args.Target, PopupType.LargeCaution);
@@ -339,7 +339,7 @@ public sealed partial class AdminVerbSystem
var baseXform = Transform(args.Target);
foreach (var part in _bodySystem.GetBodyChildrenOfType(body.Owner, BodyPartType.Hand, body))
{
_bodySystem.DropPartAt(part.Id, baseXform.Coordinates, part.Component);
_transformSystem.AttachToGridOrMap(part.Id);
break;
}
_popupSystem.PopupEntity(Loc.GetString("admin-smite-remove-hands-self"), args.Target,

View File

@@ -118,7 +118,7 @@ namespace Content.Server.Body.Commands
}
}
if (!_entManager.TryGetComponent(entity, out BodyComponent? body) || body.Root == null)
if (!_entManager.TryGetComponent(entity, out BodyComponent? body) || body.RootContainer.ContainedEntity == null)
{
var text = $"You have no body{(_random.Prob(0.2f) ? " and you must scream." : ".")}";
@@ -140,7 +140,7 @@ namespace Content.Server.Body.Commands
var slotId = part.GetHashCode().ToString();
if (!bodySystem.TryCreatePartSlotAndAttach(attachAt.Id, slotId, hand, attachAt.Component, part))
if (!bodySystem.TryCreatePartSlotAndAttach(attachAt.Id, slotId, hand, BodyPartType.Hand,attachAt.Component, part))
{
shell.WriteError($"Couldn't create a slot with id {slotId} on entity {_entManager.ToPrettyString(entity)}");
return;

View File

@@ -94,7 +94,7 @@ namespace Content.Server.Body.Commands
}
var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.BodyHasChild(bodyId, partUid, body, part))
if (bodySystem.BodyHasChild(bodyId, partUid.Value, body, part))
{
shell.WriteLine($"Body part {_entManager.GetComponent<MetaDataComponent>(partUid.Value).EntityName} with uid {partUid} is already attached to entity {_entManager.GetComponent<MetaDataComponent>(bodyId).EntityName} with uid {bodyId}");
return;
@@ -103,16 +103,14 @@ namespace Content.Server.Body.Commands
var slotId = $"AttachBodyPartVerb-{partUid}";
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (bodySystem.TryCreateBodyRootSlot(bodyId, slotId, out var rootSlot, body))
if (body.RootContainer.ContainedEntity != null)
{
bodySystem.DropPart(partUid, part);
bodySystem.AttachPart(partUid, rootSlot, part);
bodySystem.AttachPartToRoot(bodyId,partUid.Value, body ,part);
}
else
{
var attachAt = bodySystem.GetBodyChildren(bodyId, body).First();
if (!bodySystem.TryCreatePartSlotAndAttach(attachAt.Id, slotId, partUid, attachAt.Component, part))
var (rootPartId,rootPart) = bodySystem.GetRootPartOrNull(bodyId, body)!.Value;
if (!bodySystem.TryCreatePartSlotAndAttach(rootPartId, slotId, partUid.Value, part.PartType, rootPart, part))
{
shell.WriteError($"Could not create slot {slotId} on entity {_entManager.ToPrettyString(bodyId)}");
return;

View File

@@ -55,7 +55,7 @@ namespace Content.Server.Body.Commands
{
if (fac.GetComponentName(organ.Component.GetType()).ToLowerInvariant() == mechanismName)
{
bodySystem.DeleteOrgan(organ.Id, organ.Component);
entityManager.QueueDeleteEntity(organ.Id);
shell.WriteLine($"Mechanism with name {mechanismName} has been destroyed.");
return;
}

View File

@@ -11,8 +11,11 @@ using Robust.Shared.Random;
namespace Content.Server.Body.Commands
{
[AdminCommand(AdminFlags.Fun)]
sealed class RemoveHandCommand : IConsoleCommand
public sealed class RemoveHandCommand : IConsoleCommand
{
[Dependency] private readonly IEntityManager _entManager = default!;
[Dependency] private readonly IRobustRandom _random = default!;
public string Command => "removehand";
public string Description => "Removes a hand from your entity.";
public string Help => $"Usage: {Command}";
@@ -32,18 +35,16 @@ namespace Content.Server.Body.Commands
return;
}
var entityManager = IoCManager.Resolve<IEntityManager>();
if (!entityManager.TryGetComponent(player.AttachedEntity, out BodyComponent? body))
if (!_entManager.TryGetComponent(player.AttachedEntity, out BodyComponent? body))
{
var random = IoCManager.Resolve<IRobustRandom>();
var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}";
var text = $"You have no body{(_random.Prob(0.2f) ? " and you must scream." : ".")}";
shell.WriteLine(text);
return;
}
var bodySystem = entityManager.System<BodySystem>();
var hand = bodySystem.GetBodyChildrenOfType(player.AttachedEntity, BodyPartType.Hand, body).FirstOrDefault();
var bodySystem = _entManager.System<BodySystem>();
var hand = bodySystem.GetBodyChildrenOfType(player.AttachedEntity.Value, BodyPartType.Hand, body).FirstOrDefault();
if (hand == default)
{
@@ -51,7 +52,7 @@ namespace Content.Server.Body.Commands
}
else
{
bodySystem.DropPart(hand.Id, hand.Component);
_entManager.System<SharedTransformSystem>().AttachToGridOrMap(hand.Id);
}
}
}

View File

@@ -17,6 +17,7 @@ using Content.Shared.Movement.Events;
using Content.Shared.Random.Helpers;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.Map;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
@@ -32,80 +33,16 @@ public sealed class BodySystem : SharedBodySystem
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] private readonly SharedMindSystem _mindSystem = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<BodyPartComponent, ComponentStartup>(OnPartStartup);
SubscribeLocalEvent<BodyComponent, ComponentStartup>(OnBodyStartup);
SubscribeLocalEvent<BodyComponent, MoveInputEvent>(OnRelayMoveInput);
SubscribeLocalEvent<BodyComponent, ApplyMetabolicMultiplierEvent>(OnApplyMetabolicMultiplier);
SubscribeLocalEvent<BodyComponent, BeingMicrowavedEvent>(OnBeingMicrowaved);
}
private void OnPartStartup(EntityUid uid, BodyPartComponent component, ComponentStartup args)
{
// This inter-entity relationship makes be deeply uncomfortable because its probably going to re-encounter
// all of the networking & startup ordering issues that containers and joints have.
// TODO just use containers. Please.
foreach (var slot in component.Children.Values)
{
DebugTools.Assert(slot.Parent == uid);
if (slot.Child == null)
continue;
if (TryComp(slot.Child, out BodyPartComponent? child))
{
child.ParentSlot = slot;
Dirty(slot.Child.Value, child);
continue;
}
Log.Error($"Body part encountered missing limbs: {ToPrettyString(uid)}. Slot: {slot.Id}");
slot.Child = null;
}
foreach (var slot in component.Organs.Values)
{
DebugTools.Assert(slot.Parent == uid);
if (slot.Child == null)
continue;
if (TryComp(slot.Child, out OrganComponent? child))
{
child.ParentSlot = slot;
Dirty(slot.Child.Value, child);
continue;
}
Log.Error($"Body part encountered missing organ: {ToPrettyString(uid)}. Slot: {slot.Id}");
slot.Child = null;
}
}
private void OnBodyStartup(EntityUid uid, BodyComponent component, ComponentStartup args)
{
if (component.Root is not { } slot)
return;
DebugTools.Assert(slot.Parent == uid);
if (slot.Child == null)
return;
if (!TryComp(slot.Child, out BodyPartComponent? child))
{
Log.Error($"Body part encountered missing limbs: {ToPrettyString(uid)}. Slot: {slot.Id}");
slot.Child = null;
return;
}
child.ParentSlot = slot;
Dirty(slot.Child.Value, child);
}
private void OnRelayMoveInput(EntityUid uid, BodyComponent component, ref MoveInputEvent args)
{
if (_mobState.IsDead(uid) && _mindSystem.TryGetMind(uid, out var mindId, out var mind))
@@ -130,98 +67,95 @@ public sealed class BodySystem : SharedBodySystem
return;
// Don't microwave animals, kids
_transform.AttachToGridOrMap(uid);
SharedTransform.AttachToGridOrMap(uid);
_appearance.SetData(args.Microwave, MicrowaveVisualState.Bloody, true);
GibBody(uid, false, component);
args.Handled = true;
}
public override bool AttachPart(
EntityUid? partId,
BodyPartSlot slot,
[NotNullWhen(true)] BodyPartComponent? part = null)
protected override void AddPart(
EntityUid bodyUid,
EntityUid partUid,
string slotId,
BodyPartComponent component,
BodyComponent? bodyComp = null)
{
if (!base.AttachPart(partId, slot, part))
return false;
// TODO: Predict this probably.
base.AddPart(bodyUid, partUid, slotId, component, bodyComp);
if (part.Body is { } body &&
TryComp<HumanoidAppearanceComponent>(body, out var humanoid))
if (TryComp<HumanoidAppearanceComponent>(bodyUid, out var humanoid))
{
var layer = part.ToHumanoidLayers();
var layer = component.ToHumanoidLayers();
if (layer != null)
{
var layers = HumanoidVisualLayersExtension.Sublayers(layer.Value);
_humanoidSystem.SetLayersVisibility(body, layers, true, true, humanoid);
_humanoidSystem.SetLayersVisibility(bodyUid, layers, true, true, humanoid);
}
}
}
return true;
}
public override bool DropPart(EntityUid? partId, BodyPartComponent? part = null)
protected override void RemovePart(
EntityUid bodyUid,
EntityUid partUid,
string slotId,
BodyPartComponent component,
BodyComponent? bodyComp = null)
{
if (partId == null || !Resolve(partId.Value, ref part))
return false;
base.RemovePart(bodyUid, partUid, slotId, component, bodyComp);
if (!base.DropPart(partId, part))
return false;
if (!TryComp<HumanoidAppearanceComponent>(bodyUid, out var humanoid))
return;
var oldBody = part.Body;
if (oldBody == null || !TryComp<HumanoidAppearanceComponent>(oldBody, out var humanoid))
return true;
var layer = component.ToHumanoidLayers();
var layer = part.ToHumanoidLayers();
if (layer == null)
return true;
return;
var layers = HumanoidVisualLayersExtension.Sublayers(layer.Value);
_humanoidSystem.SetLayersVisibility(oldBody.Value, layers, false, true, humanoid);
return true;
_humanoidSystem.SetLayersVisibility(bodyUid, layers, false, true, humanoid);
}
public override HashSet<EntityUid> GibBody(EntityUid? bodyId, bool gibOrgans = false, BodyComponent? body = null, bool deleteItems = false)
public override HashSet<EntityUid> GibBody(EntityUid bodyId, bool gibOrgans = false, BodyComponent? body = null, bool deleteItems = false)
{
if (bodyId == null || !Resolve(bodyId.Value, ref body, false))
if (!Resolve(bodyId, ref body, false))
return new HashSet<EntityUid>();
if (LifeStage(bodyId.Value) >= EntityLifeStage.Terminating || EntityManager.IsQueuedForDeletion(bodyId.Value))
if (LifeStage(bodyId) >= EntityLifeStage.Terminating || EntityManager.IsQueuedForDeletion(bodyId))
return new HashSet<EntityUid>();
var xform = Transform(bodyId.Value);
var xform = Transform(bodyId);
if (xform.MapUid == null)
return new HashSet<EntityUid>();
var gibs = base.GibBody(bodyId, gibOrgans, body, deleteItems);
var coordinates = xform.Coordinates;
var filter = Filter.Pvs(bodyId.Value, entityManager: EntityManager);
var filter = Filter.Pvs(bodyId, entityManager: EntityManager);
var audio = AudioParams.Default.WithVariation(0.025f);
_audio.Play(body.GibSound, filter, coordinates, true, audio);
if (TryComp(bodyId, out ContainerManagerComponent? container))
var containers = GetBodyContainers(bodyId, body: body).ToList();
foreach (var container in containers)
{
foreach (var cont in container.GetAllContainers().ToArray())
{
foreach (var ent in cont.ContainedEntities.ToArray())
foreach (var entity in container.ContainedEntities)
{
if (deleteItems)
{
QueueDel(ent);
QueueDel(entity);
}
else
{
cont.Remove(ent, EntityManager, force: true);
Transform(ent).Coordinates = coordinates;
ent.RandomOffset(0.25f);
container.Remove(entity, EntityManager, force: true);
SharedTransform.SetCoordinates(entity,coordinates);
entity.RandomOffset(0.25f);
}
}
}
}
RaiseLocalEvent(bodyId.Value, new BeingGibbedEvent(gibs));
QueueDel(bodyId.Value);
RaiseLocalEvent(bodyId, new BeingGibbedEvent(gibs));
QueueDel(bodyId);
return gibs;
}

View File

@@ -30,17 +30,18 @@ namespace Content.Server.Body.Systems
private void OnRemovedFromBody(EntityUid uid, BrainComponent component, RemovedFromBodyEvent args)
{
// This one needs to be special, okay?
if (!EntityManager.TryGetComponent(uid, out OrganComponent? organ) ||
organ.ParentSlot is not {Parent: var parent})
if (!EntityManager.TryGetComponent(uid, out OrganComponent? organ))
{
return;
}
HandleMind(parent, args.Old);
HandleMind(uid, args.Old);
}
private void HandleMind(EntityUid newEntity, EntityUid oldEntity)
{
EnsureComp<MindContainerComponent>(newEntity);
var oldMind = EnsureComp<MindContainerComponent>(oldEntity);
EnsureComp<MindContainerComponent>(oldEntity);
var ghostOnMove = EnsureComp<GhostOnMoveComponent>(newEntity);
if (HasComp<BodyComponent>(newEntity))

View File

@@ -94,8 +94,9 @@ public sealed class PricingSystem : EntitySystem
return;
}
var partList = _bodySystem.GetBodyAllSlots(uid, body).ToList();
var totalPartsPresent = partList.Sum(x => x.Child != null ? 1 : 0);
// TODO: Better handling of missing.
var partList = _bodySystem.GetBodyChildren(uid, body).ToList();
var totalPartsPresent = partList.Sum(_ => 1);
var totalParts = partList.Count;
var partRatio = totalPartsPresent / (double) totalParts;

View File

@@ -300,8 +300,8 @@ public sealed class ClimbSystem : SharedClimbSystem
if (!HasComp<ClimbingComponent>(user)
|| !TryComp(user, out BodyComponent? body)
|| !_bodySystem.BodyHasChildOfType(user, BodyPartType.Leg, body)
|| !_bodySystem.BodyHasChildOfType(user, BodyPartType.Foot, body))
|| !_bodySystem.BodyHasPartType(user, BodyPartType.Leg, body)
|| !_bodySystem.BodyHasPartType(user, BodyPartType.Foot, body))
{
reason = Loc.GetString("comp-climbable-cant-climb");
return false;

View File

@@ -192,11 +192,6 @@ namespace Content.Server.Kitchen.EntitySystems
foreach (var part in headSlots)
{
if (!_bodySystem.OrphanPart(part.Id, part.Component))
{
continue;
}
component.Storage.Insert(part.Id);
headCount++;
}

View File

@@ -53,7 +53,7 @@ namespace Content.Server.Toilet
// Check that victim has a head
// FIXME: since suiciding turns you into a ghost immediately, both messages are seen, not sure how this can be fixed
if (TryComp<BodyComponent>(args.Victim, out var body) &&
_body.BodyHasChildOfType(args.Victim, BodyPartType.Head, body))
_body.BodyHasPartType(args.Victim, BodyPartType.Head, body))
{
var othersMessage = Loc.GetString("toilet-component-suicide-head-message-others",
("victim", Identity.Entity(args.Victim, EntityManager)), ("owner", uid));

View File

@@ -1,9 +1,10 @@
using Content.Shared.Body.Part;
using Content.Shared.Body.Prototypes;
using Content.Shared.Body.Systems;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Components;
@@ -11,19 +12,52 @@ namespace Content.Shared.Body.Components;
[Access(typeof(SharedBodySystem))]
public sealed partial class BodyComponent : Component
{
[DataField("prototype", customTypeSerializer: typeof(PrototypeIdSerializer<BodyPrototype>))]
public string? Prototype;
/// <summary>
/// Relevant template to spawn for this body.
/// </summary>
[DataField]
public ProtoId<BodyPrototype>? Prototype;
[DataField("root")]
public BodyPartSlot? Root;
/// <summary>
/// Container that holds the root body part.
/// </summary>
/// <remarks>
/// Typically is the torso.
/// </remarks>
[ViewVariables] public ContainerSlot RootContainer = default!;
[DataField("gibSound")]
public SoundSpecifier GibSound = new SoundCollectionSpecifier("gib");
[ViewVariables]
public string RootPartSlot => RootContainer.ID;
[DataField] public SoundSpecifier GibSound = new SoundCollectionSpecifier("gib");
/// <summary>
/// The amount of legs required to move at full speed.
/// If 0, then legs do not impact speed.
/// </summary>
[DataField("requiredLegs")]
public int RequiredLegs;
[DataField] public int RequiredLegs;
[ViewVariables]
[DataField]
public HashSet<EntityUid> LegEntities = new();
}
[Serializable, NetSerializable]
public sealed class BodyComponentState : ComponentState
{
public string? Prototype;
public string? RootPartSlot;
public SoundSpecifier GibSound;
public int RequiredLegs;
public HashSet<NetEntity> LegNetEntities;
public BodyComponentState(string? prototype, string? rootPartSlot, SoundSpecifier gibSound,
int requiredLegs, HashSet<NetEntity> legNetEntities)
{
Prototype = prototype;
RootPartSlot = rootPartSlot;
GibSound = gibSound;
RequiredLegs = requiredLegs;
LegNetEntities = legNetEntities;
}
}

View File

@@ -1,18 +0,0 @@
using Content.Shared.Body.Part;
using Robust.Shared.Audio;
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Components;
[Serializable, NetSerializable]
public sealed class BodyComponentState : ComponentState
{
public readonly BodyPartSlot? Root;
public readonly SoundSpecifier GibSound;
public BodyComponentState(BodyPartSlot? root, SoundSpecifier gibSound)
{
Root = root;
GibSound = gibSound;
}
}

View File

@@ -1,16 +1,16 @@
using Content.Shared.Body.Systems;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
namespace Content.Shared.Body.Organ;
[RegisterComponent, NetworkedComponent]
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
[Access(typeof(SharedBodySystem))]
public sealed partial class OrganComponent : Component
{
[DataField("body")]
/// <summary>
/// Relevant body this organ is attached to.
/// </summary>
[DataField("body"), AutoNetworkedField]
public EntityUid? Body;
// TODO use containers. See comments in BodyPartComponent.
// Do not rely on this in client-side code.
public OrganSlot? ParentSlot;
}

View File

@@ -1,16 +0,0 @@
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Organ;
[Serializable, NetSerializable]
public sealed class OrganComponentState : ComponentState
{
public readonly NetEntity? Body;
public readonly OrganSlot? Parent;
public OrganComponentState(NetEntity? body, OrganSlot? parent)
{
Body = body;
Parent = parent;
}
}

View File

@@ -1,33 +0,0 @@
using Content.Shared.Body.Systems;
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Organ;
[Serializable, NetSerializable]
[Access(typeof(SharedBodySystem))]
[DataDefinition]
public sealed partial record OrganSlot
{
[DataField("id")]
public string Id = string.Empty;
[NonSerialized]
[DataField("parent")]
public EntityUid Parent;
public NetEntity NetParent;
[NonSerialized]
[DataField("child")]
public EntityUid? Child;
public NetEntity? NetChild;
// Rider doesn't suggest explicit properties during deconstruction without this
public void Deconstruct(out EntityUid? child, out string id, out EntityUid parent)
{
child = Child;
id = Id;
parent = Parent;
}
}

View File

@@ -1,32 +1,23 @@
using Content.Shared.Body.Components;
using Content.Shared.Body.Organ;
using Content.Shared.Body.Systems;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Part;
[RegisterComponent, NetworkedComponent]
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
[Access(typeof(SharedBodySystem))]
public sealed partial class BodyPartComponent : Component
{
[DataField("body")]
// Need to set this on container changes as it may be several transform parents up the hierarchy.
/// <summary>
/// Parent body for this part.
/// </summary>
[DataField, AutoNetworkedField]
public EntityUid? Body;
// This inter-entity relationship makes be deeply uncomfortable because its probably going to re-encounter all of the
// networking issues that containers and joints have.
// TODO just use containers. Please.
// Do not use set or get data from this in client-side code.
public BodyPartSlot? ParentSlot;
// Do not use set or get data from this in client-side code.
[DataField("children")]
public Dictionary<string, BodyPartSlot> Children = new();
// See all the above ccomments.
[DataField("organs")]
public Dictionary<string, OrganSlot> Organs = new();
[DataField("partType")]
[DataField, AutoNetworkedField]
public BodyPartType PartType = BodyPartType.Other;
// TODO BODY Replace with a simulation of organs
@@ -34,9 +25,90 @@ public sealed partial class BodyPartComponent : Component
/// Whether or not the owning <see cref="Body"/> will die if all
/// <see cref="BodyComponent"/>s of this type are removed from it.
/// </summary>
[DataField("vital")]
[DataField("vital"), AutoNetworkedField]
public bool IsVital;
[DataField("symmetry")]
[DataField, AutoNetworkedField]
public BodyPartSymmetry Symmetry = BodyPartSymmetry.None;
/// <summary>
/// Child body parts attached to this body part.
/// </summary>
[DataField, AutoNetworkedField(CloneData = true)]
public Dictionary<string, BodyPartSlot> Children = new();
/// <summary>
/// Organs attached to this body part.
/// </summary>
[DataField, AutoNetworkedField(CloneData = true)]
public Dictionary<string, OrganSlot> Organs = new();
/// <summary>
/// These are only for VV/Debug do not use these for gameplay/systems
/// </summary>
[ViewVariables]
private List<ContainerSlot> BodyPartSlotsVV
{
get
{
List<ContainerSlot> temp = new();
var containerSystem = IoCManager.Resolve<IEntityManager>().System<SharedContainerSystem>();
foreach (var slotId in Children.Keys)
{
temp.Add((ContainerSlot) containerSystem.GetContainer(Owner, slotId));
}
return temp;
}
}
[ViewVariables]
private List<ContainerSlot> OrganSlotsVV
{
get
{
List<ContainerSlot> temp = new();
var containerSystem = IoCManager.Resolve<IEntityManager>().System<SharedContainerSystem>();
foreach (var slotId in Organs.Keys)
{
temp.Add((ContainerSlot) containerSystem.GetContainer(Owner, slotId));
}
return temp;
}
}
}
/// <summary>
/// Contains metadata about a body part in relation to its slot.
/// </summary>
[NetSerializable, Serializable]
[DataRecord]
public partial struct BodyPartSlot
{
public string Id;
public BodyPartType Type;
public BodyPartSlot(string id, BodyPartType type)
{
Id = id;
Type = type;
}
};
/// <summary>
/// Contains metadata about an organ part in relation to its slot.
/// </summary>
[NetSerializable, Serializable]
[DataRecord]
public partial struct OrganSlot
{
public string Id;
public OrganSlot(string id)
{
Id = id;
}
};

View File

@@ -1,34 +0,0 @@
using Content.Shared.Body.Organ;
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Part;
[Serializable, NetSerializable]
public sealed class BodyPartComponentState : ComponentState
{
public readonly NetEntity? Body;
public readonly BodyPartSlot? ParentSlot;
public readonly Dictionary<string, BodyPartSlot> Children;
public readonly Dictionary<string, OrganSlot> Organs;
public readonly BodyPartType PartType;
public readonly bool IsVital;
public readonly BodyPartSymmetry Symmetry;
public BodyPartComponentState(
NetEntity? body,
BodyPartSlot? parentSlot,
Dictionary<string, BodyPartSlot> children,
Dictionary<string, OrganSlot> organs,
BodyPartType partType,
bool isVital,
BodyPartSymmetry symmetry)
{
ParentSlot = parentSlot;
Children = children;
Organs = organs;
PartType = partType;
IsVital = isVital;
Symmetry = symmetry;
Body = body;
}
}

View File

@@ -1,43 +0,0 @@
using Content.Shared.Body.Systems;
using Robust.Shared.Serialization;
namespace Content.Shared.Body.Part;
[Serializable, NetSerializable]
[Access(typeof(SharedBodySystem))]
[DataDefinition]
public sealed partial record BodyPartSlot
{
[DataField("id")]
public string Id = string.Empty;
[DataField("type")]
public BodyPartType? Type;
[NonSerialized]
[DataField("parent")]
public EntityUid Parent;
public NetEntity NetParent;
[NonSerialized]
[DataField("child")]
public EntityUid? Child;
public NetEntity? NetChild;
public void SetChild(EntityUid? child, NetEntity? netChild)
{
Child = child;
NetChild = netChild;
}
// Rider doesn't suggest explicit properties during deconstruction without this
public void Deconstruct(out EntityUid? child, out string id, out EntityUid parent, out BodyPartType? type)
{
child = Child;
id = Id;
parent = Parent;
type = Type;
}
}

View File

@@ -27,28 +27,4 @@ public sealed class BodyPrototype : IPrototype
}
[DataRecord]
public sealed record BodyPrototypeSlot
{
[DataField("part", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))]
public string? Part;
public readonly HashSet<string> Connections = new();
public readonly Dictionary<string, string> Organs = new();
public BodyPrototypeSlot() : this(null, null, null)
{
}
public BodyPrototypeSlot(string? part, HashSet<string>? connections, Dictionary<string, string>? organs)
{
Part = part;
Connections = connections ?? new HashSet<string>();
Organs = organs ?? new Dictionary<string, string>();
}
public void Deconstruct(out string? part, out HashSet<string> connections, out Dictionary<string, string> organs)
{
part = Part;
connections = Connections;
organs = Organs;
}
}
public sealed record BodyPrototypeSlot(EntProtoId? Part, HashSet<string> Connections, Dictionary<string, string> Organs);

View File

@@ -179,9 +179,10 @@ public sealed class BodyPrototypeSerializer : ITypeReader<BodyPrototype, Mapping
}
var slots = new Dictionary<string, BodyPrototypeSlot>();
foreach (var (slotId, (part, connections, organs)) in allConnections)
{
var slot = new BodyPrototypeSlot(part, connections, organs);
var slot = new BodyPrototypeSlot(part != null ? new EntProtoId(part) : null!, connections ?? new HashSet<string>(), organs ?? new Dictionary<string, string>());
slots.Add(slotId, slot);
}

View File

@@ -1,28 +1,141 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq;
using System.Numerics;
using Content.Shared.Body.Components;
using Content.Shared.Body.Organ;
using Content.Shared.Body.Part;
using Content.Shared.Body.Prototypes;
using Content.Shared.Coordinates;
using Content.Shared.DragDrop;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Network;
using Robust.Shared.Map;
using MapInitEvent = Robust.Shared.GameObjects.MapInitEvent;
namespace Content.Shared.Body.Systems;
public partial class SharedBodySystem
{
[Dependency] private readonly INetManager _netManager = default!;
/*
* tl;dr of how bobby works
* - BodyComponent uses a BodyPrototype as a template.
* - On MapInit we spawn the root entity in the prototype and spawn all connections outwards from here
* - Each "connection" is a body part (e.g. arm, hand, etc.) and each part can also contain organs.
*/
public void InitializeBody()
private void InitializeBody()
{
SubscribeLocalEvent<BodyComponent, ComponentInit>(OnBodyInit);
// Body here to handle root body parts.
SubscribeLocalEvent<BodyComponent, EntInsertedIntoContainerMessage>(OnBodyInserted);
SubscribeLocalEvent<BodyComponent, EntRemovedFromContainerMessage>(OnBodyRemoved);
SubscribeLocalEvent<BodyComponent, ComponentInit>(OnBodyInit);
SubscribeLocalEvent<BodyComponent, MapInitEvent>(OnBodyMapInit);
SubscribeLocalEvent<BodyComponent, CanDragEvent>(OnBodyCanDrag);
SubscribeLocalEvent<BodyComponent, ComponentGetState>(OnBodyGetState);
SubscribeLocalEvent<BodyComponent, ComponentHandleState>(OnBodyHandleState);
SubscribeLocalEvent<BodyComponent, CanDragEvent>(OnBodyCanDrag);
}
private void OnBodyInserted(EntityUid uid, BodyComponent component, EntInsertedIntoContainerMessage args)
{
// Root body part?
var slotId = args.Container.ID;
if (slotId != BodyRootContainerId)
return;
var entity = args.Entity;
if (TryComp(entity, out BodyPartComponent? childPart))
{
AddPart(uid, entity, slotId, childPart);
RecursiveBodyUpdate(entity, uid, childPart);
}
if (TryComp(entity, out OrganComponent? organ))
{
AddOrgan(entity, uid, uid, organ);
}
}
private void OnBodyRemoved(EntityUid uid, BodyComponent component, EntRemovedFromContainerMessage args)
{
// TODO: lifestage shenanigans
if (LifeStage(uid) >= EntityLifeStage.Terminating)
return;
// Root body part?
var slotId = args.Container.ID;
if (slotId != BodyRootContainerId)
return;
var entity = args.Entity;
if (TryComp(entity, out BodyPartComponent? childPart))
{
RemovePart(uid, entity, slotId, childPart);
RecursiveBodyUpdate(entity, null, childPart);
}
if (TryComp(entity, out OrganComponent? organ))
{
RemoveOrgan(entity, uid, uid, organ);
}
}
private void OnBodyHandleState(EntityUid uid, BodyComponent component, ref ComponentHandleState args)
{
if (args.Current is not BodyComponentState state)
return;
component.Prototype = state.Prototype != null ? state.Prototype : null!;
component.GibSound = state.GibSound;
component.RequiredLegs = state.RequiredLegs;
component.LegEntities = EntityManager.EnsureEntitySet<BodyComponent>(state.LegNetEntities, uid);
}
private void OnBodyGetState(EntityUid uid, BodyComponent component, ref ComponentGetState args)
{
args.State = new BodyComponentState(
component.Prototype,
component.RootPartSlot,
component.GibSound,
component.RequiredLegs,
EntityManager.GetNetEntitySet(component.LegEntities)
);
}
private void OnBodyInit(EntityUid bodyId, BodyComponent body, ComponentInit args)
{
// Setup the initial container.
body.RootContainer = Containers.EnsureContainer<ContainerSlot>(bodyId, BodyRootContainerId);
}
private void OnBodyMapInit(EntityUid bodyId, BodyComponent body, MapInitEvent args)
{
if (body.Prototype == null)
return;
// One-time setup
// Obviously can't run in Init to avoid double-spawns on save / load.
var prototype = Prototypes.Index(body.Prototype.Value);
MapInitBody(bodyId, prototype);
}
private void MapInitBody(EntityUid bodyEntity, BodyPrototype prototype)
{
var protoRoot = prototype.Slots[prototype.Root];
if (protoRoot.Part == null)
return;
// This should already handle adding the entity to the root.
var rootPartEntity = SpawnInContainerOrDrop(protoRoot.Part, bodyEntity, BodyRootContainerId);
var rootPart = Comp<BodyPartComponent>(rootPartEntity);
rootPart.Body = bodyEntity;
Dirty(rootPartEntity, rootPart);
// Setup the rest of the body entities.
SetupOrgans(rootPartEntity, rootPart, protoRoot.Organs);
MapInitParts(rootPartEntity, prototype);
}
private void OnBodyCanDrag(EntityUid uid, BodyComponent component, ref CanDragEvent args)
@@ -30,148 +143,114 @@ public partial class SharedBodySystem
args.Handled = true;
}
private void OnBodyInit(EntityUid bodyId, BodyComponent body, ComponentInit args)
/// <summary>
/// Sets up all of the relevant body parts for a particular body entity and root part.
/// </summary>
private void MapInitParts(EntityUid rootPartId, BodyPrototype prototype)
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (body.Prototype == null || body.Root != null)
return;
// Start at the root part and traverse the body graph, setting up parts as we go.
// Basic BFS pathfind.
var rootSlot = prototype.Root;
var frontier = new Queue<string>();
frontier.Enqueue(rootSlot);
var prototype = Prototypes.Index<BodyPrototype>(body.Prototype);
// Child -> Parent connection.
var cameFrom = new Dictionary<string, string>();
// Maps slot to its relevant entity.
var cameFromEntities = new Dictionary<string, EntityUid>();
cameFromEntities[rootSlot] = rootPartId;
if (!_netManager.IsClient || IsClientSide(bodyId))
InitBody(body, prototype);
Dirty(body); // Client doesn't actually spawn the body, need to sync it
}
private void OnBodyGetState(EntityUid uid, BodyComponent body, ref ComponentGetState args)
while (frontier.TryDequeue(out var currentSlotId))
{
args.State = new BodyComponentState(body.Root, body.GibSound);
}
var currentSlot = prototype.Slots[currentSlotId];
private void OnBodyHandleState(EntityUid uid, BodyComponent body, ref ComponentHandleState args)
foreach (var connection in currentSlot.Connections)
{
if (args.Current is not BodyComponentState state)
return;
body.Root = state.Root; // TODO use containers. This is broken and does not work.
body.GibSound = state.GibSound;
}
public bool TryCreateBodyRootSlot(
EntityUid? bodyId,
string slotId,
[NotNullWhen(true)] out BodyPartSlot? slot,
BodyComponent? body = null)
{
slot = null;
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (bodyId == null ||
!Resolve(bodyId.Value, ref body, false) ||
body.Root != null)
return false;
slot = new BodyPartSlot
{
Id = slotId,
Parent = bodyId.Value,
NetParent = GetNetEntity(bodyId.Value),
};
body.Root = slot;
return true;
}
protected void InitBody(BodyComponent body, BodyPrototype prototype)
{
var root = prototype.Slots[prototype.Root];
Containers.EnsureContainer<Container>(body.Owner, BodyContainerId);
if (root.Part == null)
return;
var bodyId = Spawn(root.Part, body.Owner.ToCoordinates());
var partComponent = Comp<BodyPartComponent>(bodyId);
var slot = new BodyPartSlot
{
Id = root.Part,
Type = partComponent.PartType,
Parent = body.Owner,
NetParent = GetNetEntity(body.Owner),
};
body.Root = slot;
partComponent.Body = bodyId;
AttachPart(bodyId, slot, partComponent);
InitPart(partComponent, prototype, prototype.Root);
}
protected void InitPart(BodyPartComponent parent, BodyPrototype prototype, string slotId, HashSet<string>? initialized = null)
{
initialized ??= new HashSet<string>();
if (initialized.Contains(slotId))
return;
initialized.Add(slotId);
var (_, connections, organs) = prototype.Slots[slotId];
connections = new HashSet<string>(connections);
connections.ExceptWith(initialized);
var coordinates = parent.Owner.ToCoordinates();
var subConnections = new List<(BodyPartComponent child, string slotId)>();
Containers.EnsureContainer<Container>(parent.Owner, BodyContainerId);
foreach (var connection in connections)
{
var childSlot = prototype.Slots[connection];
if (childSlot.Part == null)
// Already been handled
if (!cameFrom.TryAdd(connection, currentSlotId))
continue;
var childPart = Spawn(childSlot.Part, coordinates);
// Setup part
var connectionSlot = prototype.Slots[connection];
var parentEntity = cameFromEntities[currentSlotId];
var parentPartComponent = Comp<BodyPartComponent>(parentEntity);
// Spawn the entity on the target
// then get the body part type, create the slot, and finally
// we can insert it into the container.
var childPart = Spawn(connectionSlot.Part, new EntityCoordinates(parentEntity, Vector2.Zero));
cameFromEntities[connection] = childPart;
var childPartComponent = Comp<BodyPartComponent>(childPart);
var slot = CreatePartSlot(connection, parent.Owner, childPartComponent.PartType, parent);
if (slot == null)
var partSlot = CreatePartSlot(parentEntity, connection, childPartComponent.PartType, parentPartComponent);
var cont = Containers.GetContainer(parentEntity, GetPartSlotContainerId(connection));
if (partSlot == null || !cont.Insert(childPart))
{
Logger.Error($"Could not create slot for connection {connection} in body {prototype.ID}");
Log.Error($"Could not create slot for connection {connection} in body {prototype.ID}");
QueueDel(childPart);
continue;
}
AttachPart(childPart, slot, childPartComponent);
subConnections.Add((childPartComponent, connection));
// Add organs
SetupOrgans(childPart, childPartComponent, connectionSlot.Organs);
// Enqueue it so we can also get its neighbors.
frontier.Enqueue(connection);
}
}
}
foreach (var (organSlotId, organId) in organs)
private void SetupOrgans(EntityUid partId, BodyPartComponent partComponent, Dictionary<string, string> organs)
{
var organ = Spawn(organId, coordinates);
var organComponent = Comp<OrganComponent>(organ);
foreach (var (organSlotId, organProto) in organs)
{
var slot = CreateOrganSlot(organSlotId, partId, partComponent);
SpawnInContainerOrDrop(organProto, partId, GetOrganContainerId(organSlotId));
var slot = CreateOrganSlot(organSlotId, parent.Owner, parent);
if (slot == null)
{
Logger.Error($"Could not create slot for connection {organSlotId} in body {prototype.ID}");
continue;
Log.Error($"Could not create organ for slot {organSlotId} in {ToPrettyString(partId)}");
}
}
}
InsertOrgan(organ, slot, organComponent);
}
foreach (var connection in subConnections)
/// <summary>
/// Gets all body containers on this entity including the root one.
/// </summary>
public IEnumerable<BaseContainer> GetBodyContainers(EntityUid id, BodyComponent? body = null,
BodyPartComponent? rootPart = null)
{
InitPart(connection.child, prototype, connection.slotId, initialized);
if (!Resolve(id, ref body, false) ||
body.RootContainer.ContainedEntity == null ||
!Resolve(body.RootContainer.ContainedEntity.Value, ref rootPart))
{
yield break;
}
yield return body.RootContainer;
foreach (var childContainer in GetPartContainers(body.RootContainer.ContainedEntity.Value, rootPart))
{
yield return childContainer;
}
}
public IEnumerable<(EntityUid Id, BodyPartComponent Component)> GetBodyChildren(EntityUid? id, BodyComponent? body = null)
/// <summary>
/// Gets all child body parts of this entity, including the root entity.
/// </summary>
public IEnumerable<(EntityUid Id, BodyPartComponent Component)> GetBodyChildren(EntityUid? id, BodyComponent? body = null,
BodyPartComponent? rootPart = null)
{
if (id == null ||
!Resolve(id.Value, ref body, false) ||
!TryComp(body.Root?.Child, out BodyPartComponent? part))
body.RootContainer.ContainedEntity == null ||
!Resolve(body.RootContainer.ContainedEntity.Value, ref rootPart))
{
yield break;
}
yield return (body.Root.Child.Value, part);
foreach (var child in GetPartChildren(body.Root.Child))
foreach (var child in GetBodyPartChildren(body.RootContainer.ContainedEntity.Value, rootPart))
{
yield return child;
}
@@ -191,55 +270,37 @@ public partial class SharedBodySystem
}
}
public IEnumerable<BodyPartSlot> GetBodyAllSlots(EntityUid? bodyId, BodyComponent? body = null)
{
if (bodyId == null || !Resolve(bodyId.Value, ref body, false))
yield break;
foreach (var slot in GetPartAllSlots(body.Root?.Child))
{
yield return slot;
}
}
/// <summary>
/// Returns all body part slots in the graph, including ones connected by
/// body parts which are null.
/// Returns all body part slots for this entity.
/// </summary>
/// <param name="partId"></param>
/// <param name="part"></param>
/// <param name="bodyId"></param>
/// <param name="body"></param>
/// <returns></returns>
public IEnumerable<BodyPartSlot> GetAllBodyPartSlots(EntityUid partId, BodyPartComponent? part = null)
public IEnumerable<BodyPartSlot> GetBodyAllSlots(EntityUid bodyId, BodyComponent? body = null)
{
if (!Resolve(partId, ref part, false))
if (!Resolve(bodyId, ref body, false) || body.RootContainer.ContainedEntity == null)
yield break;
foreach (var slot in part.Children.Values)
foreach (var slot in GetAllBodyPartSlots(body.RootContainer.ContainedEntity.Value))
{
if (!TryComp<BodyPartComponent>(slot.Child, out var childPart))
continue;
yield return slot;
foreach (var child in GetAllBodyPartSlots(slot.Child.Value, childPart))
{
yield return child;
}
}
}
public virtual HashSet<EntityUid> GibBody(EntityUid? partId, bool gibOrgans = false,
public virtual HashSet<EntityUid> GibBody(EntityUid bodyId, bool gibOrgans = false,
BodyComponent? body = null, bool deleteItems = false)
{
if (partId == null || !Resolve(partId.Value, ref body, false))
return new HashSet<EntityUid>();
var gibs = new HashSet<EntityUid>();
var parts = GetBodyChildren(partId, body).ToArray();
var gibs = new HashSet<EntityUid>(parts.Length);
if (!Resolve(bodyId, ref body, false))
return gibs;
var parts = GetBodyChildren(bodyId, body).ToArray();
gibs.EnsureCapacity(parts.Length);
foreach (var part in parts)
{
DropPart(part.Id, part.Component);
SharedTransform.AttachToGridOrMap(part.Id);
gibs.Add(part.Id);
if (!gibOrgans)
@@ -247,7 +308,7 @@ public partial class SharedBodySystem
foreach (var organ in GetPartOrgans(part.Id, part.Component))
{
DropOrgan(organ.Id, organ.Component);
SharedTransform.AttachToGridOrMap(organ.Id);
gibs.Add(organ.Id);
}
}

View File

@@ -3,194 +3,142 @@ using Content.Shared.Body.Components;
using Content.Shared.Body.Events;
using Content.Shared.Body.Organ;
using Content.Shared.Body.Part;
using Content.Shared.Random.Helpers;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
namespace Content.Shared.Body.Systems;
public partial class SharedBodySystem
{
[Dependency] private readonly SharedContainerSystem _container = default!;
private void InitializeOrgans()
private void AddOrgan(EntityUid uid, EntityUid bodyUid, EntityUid parentPartUid, OrganComponent component)
{
SubscribeLocalEvent<OrganComponent, ComponentGetState>(OnOrganGetState);
SubscribeLocalEvent<OrganComponent, ComponentHandleState>(OnOrganHandleState);
component.Body = bodyUid;
RaiseLocalEvent(uid, new AddedToPartEvent(bodyUid));
if (component.Body != null)
RaiseLocalEvent(uid, new AddedToPartInBodyEvent(component.Body.Value, parentPartUid));
Dirty(uid, component);
}
private void RemoveOrgan(EntityUid uid, EntityUid bodyUid, EntityUid parentPartUid, OrganComponent component)
{
RaiseLocalEvent(uid, new RemovedFromPartEvent(bodyUid));
if (component.Body != null)
RaiseLocalEvent(uid, new RemovedFromPartInBodyEvent(component.Body.Value, parentPartUid));
component.Body = null;
Dirty(uid, component);
}
/// <summary>
/// Creates the specified organ slot on the parent entity.
/// </summary>
private OrganSlot? CreateOrganSlot(string slotId, EntityUid parent, BodyPartComponent? part = null)
{
if (!Resolve(parent, ref part, false))
return null;
var slot = new OrganSlot()
{
Id = slotId,
Parent = parent,
NetParent = GetNetEntity(parent),
};
Containers.EnsureContainer<ContainerSlot>(parent, GetOrganContainerId(slotId));
var slot = new OrganSlot(slotId);
part.Organs.Add(slotId, slot);
return slot;
}
private bool CanInsertOrgan(EntityUid? organId, OrganSlot slot, OrganComponent? organ = null)
/// <summary>
/// Attempts to create the specified organ slot on the specified parent if it exists.
/// </summary>
public bool TryCreateOrganSlot(
EntityUid? parent,
string slotId,
[NotNullWhen(true)] out OrganSlot? slot,
BodyPartComponent? part = null)
{
return organId != null &&
slot.Child == null &&
Resolve(organId.Value, ref organ, false) &&
Containers.TryGetContainer(slot.Parent, BodyContainerId, out var container) &&
_container.CanInsert(organId.Value, container);
slot = null;
if (parent == null || !Resolve(parent.Value, ref part, false))
{
return false;
}
private void OnOrganGetState(EntityUid uid, OrganComponent organ, ref ComponentGetState args)
{
args.State = new OrganComponentState(GetNetEntity(organ.Body), organ.ParentSlot);
Containers.EnsureContainer<ContainerSlot>(parent.Value, GetOrganContainerId(slotId));
slot = new OrganSlot(slotId);
return part.Organs.TryAdd(slotId,slot.Value);
}
private void OnOrganHandleState(EntityUid uid, OrganComponent organ, ref ComponentHandleState args)
/// <summary>
/// Returns whether the slotId exists on the partId.
/// </summary>
public bool CanInsertOrgan(EntityUid partId, string slotId, BodyPartComponent? part = null)
{
if (args.Current is not OrganComponentState state)
return;
organ.Body = EnsureEntity<OrganComponent>(state.Body, uid);
organ.ParentSlot = state.Parent;
return Resolve(partId, ref part) && part.Organs.ContainsKey(slotId);
}
public bool InsertOrgan(EntityUid? organId, OrganSlot slot, OrganComponent? organ = null)
/// <summary>
/// Returns whether the specified organ slot exists on the partId.
/// </summary>
public bool CanInsertOrgan(EntityUid partId, OrganSlot slot, BodyPartComponent? part = null)
{
if (organId == null ||
!Resolve(organId.Value, ref organ, false) ||
!CanInsertOrgan(organId, slot, organ))
return CanInsertOrgan(partId, slot.Id, part);
}
public bool InsertOrgan(EntityUid partId, EntityUid organId, string slotId, BodyPartComponent? part = null, OrganComponent? organ = null)
{
if (!Resolve(organId, ref organ, false) ||
!Resolve(partId, ref part, false) ||
!CanInsertOrgan(partId, slotId, part))
{
return false;
}
var containerId = GetOrganContainerId(slotId);
if (!Containers.TryGetContainer(partId, containerId, out var container))
return false;
DropOrgan(slot.Child);
DropOrgan(organId, organ);
return container.Insert(organId);
}
var container = Containers.EnsureContainer<Container>(slot.Parent, BodyContainerId);
if (!container.Insert(organId.Value))
/// <summary>
/// Removes the organ if it is inside of a body part.
/// </summary>
public bool RemoveOrgan(EntityUid organId, OrganComponent? organ = null)
{
if (!Containers.TryGetContainingContainer(organId, out var container))
return false;
slot.Child = organId;
organ.ParentSlot = slot;
organ.Body = CompOrNull<BodyPartComponent>(slot.Parent)?.Body;
var parent = container.Owner;
DirtyAllComponents(slot.Parent);
Dirty(organId.Value, organ);
if (!HasComp<BodyPartComponent>(parent))
return false;
if (organ.Body == null)
{
RaiseLocalEvent(organId.Value, new AddedToPartEvent(slot.Parent));
}
else
{
RaiseLocalEvent(organId.Value, new AddedToPartInBodyEvent(organ.Body.Value, slot.Parent));
return container.Remove(organId);
}
return true;
}
public void DirtyAllComponents(EntityUid uid)
{
// TODO just use containers. Please
if (TryComp(uid, out BodyPartComponent? part))
Dirty(uid, part);
if (TryComp(uid, out OrganComponent? organ))
Dirty(uid, organ);
if (TryComp(uid, out BodyComponent? body))
Dirty(uid, body);
}
/// <summary>
/// Tries to add this organ to any matching slot on this body part.
/// </summary>
public bool AddOrganToFirstValidSlot(
EntityUid? childId,
EntityUid? parentId,
OrganComponent? child = null,
BodyPartComponent? parent = null)
EntityUid partId,
EntityUid organId,
BodyPartComponent? part = null,
OrganComponent? organ = null)
{
if (!Resolve(partId, ref part, false) ||
!Resolve(organId, ref organ, false))
{
if (childId == null ||
!Resolve(childId.Value, ref child, false) ||
parentId == null ||
!Resolve(parentId.Value, ref parent, false))
return false;
}
foreach (var slot in parent.Organs.Values)
foreach (var slotId in part.Organs.Keys)
{
if (slot.Child == null)
continue;
InsertOrgan(childId, slot, child);
InsertOrgan(partId, organId, slotId, part, organ);
return true;
}
return false;
}
public bool DropOrgan(EntityUid? organId, OrganComponent? organ = null)
{
if (organId == null ||
!Resolve(organId.Value, ref organ, false) ||
organ.ParentSlot is not { } slot)
return false;
var oldParent = CompOrNull<BodyPartComponent>(organ.ParentSlot.Parent);
slot.Child = null;
organ.ParentSlot = null;
organ.Body = null;
if (Containers.TryGetContainer(slot.Parent, BodyContainerId, out var container))
container.Remove(organId.Value);
if (TryComp(organId, out TransformComponent? transform))
transform.AttachToGridOrMap();
organ.Owner.RandomOffset(0.25f);
if (oldParent == null)
return true;
if (oldParent.Body != null)
{
RaiseLocalEvent(organId.Value, new RemovedFromPartInBodyEvent(oldParent.Body.Value, oldParent.Owner));
}
else
{
RaiseLocalEvent(organId.Value, new RemovedFromPartEvent(oldParent.Owner));
}
return true;
}
public bool DropOrganAt(EntityUid? organId, EntityCoordinates dropAt, OrganComponent? organ = null)
{
if (organId == null || !DropOrgan(organId, organ))
return false;
if (TryComp(organId.Value, out TransformComponent? transform))
transform.Coordinates = dropAt;
return true;
}
public bool DeleteOrgan(EntityUid? id, OrganComponent? part = null)
{
if (id == null || !Resolve(id.Value, ref part, false))
return false;
DropOrgan(id, part);
if (Deleted(id.Value))
return false;
Del(id.Value);
return true;
}
/// <summary>
/// Returns a list of ValueTuples of <see cref="T"/> and OrganComponent on each organ
/// in the given body.

File diff suppressed because it is too large Load Diff

View File

@@ -8,14 +8,31 @@ namespace Content.Shared.Body.Systems;
public abstract partial class SharedBodySystem : EntitySystem
{
protected const string BodyContainerId = "BodyContainer";
/*
* See the body partial for how this works.
*/
/// <summary>
/// Container ID prefix for any body parts.
/// </summary>
protected const string PartSlotContainerIdPrefix = "body_part_slot_";
/// <summary>
/// Container ID for the ContainerSlot on the body entity itself.
/// </summary>
protected const string BodyRootContainerId = "body_root_part";
/// <summary>
/// Container ID prefix for any body organs.
/// </summary>
protected const string OrganSlotContainerIdPrefix = "body_organ_slot_";
[Dependency] protected readonly IPrototypeManager Prototypes = default!;
[Dependency] protected readonly SharedContainerSystem Containers = default!;
[Dependency] protected readonly DamageableSystem Damageable = default!;
[Dependency] protected readonly StandingStateSystem Standing = default!;
[Dependency] protected readonly MovementSpeedModifierSystem Movement = default!;
[Dependency] protected readonly SharedContainerSystem Containers = default!;
[Dependency] protected readonly SharedTransformSystem SharedTransform = default!;
[Dependency] protected readonly StandingStateSystem Standing = default!;
public override void Initialize()
{
@@ -23,6 +40,36 @@ public abstract partial class SharedBodySystem : EntitySystem
InitializeBody();
InitializeParts();
InitializeOrgans();
}
/// <summary>
/// Inverse of <see cref="GetPartSlotContainerId"/>
/// </summary>
protected static string? GetPartSlotContainerIdFromContainer(string containerSlotId)
{
// This is blursed
var slotIndex = containerSlotId.IndexOf(PartSlotContainerIdPrefix, StringComparison.Ordinal);
if (slotIndex < -1)
return null;
var slotId = containerSlotId.Remove(slotIndex, PartSlotContainerIdPrefix.Length);
return slotId;
}
/// <summary>
/// Gets the container Id for the specified slotId.
/// </summary>
public static string GetPartSlotContainerId(string slotId)
{
return PartSlotContainerIdPrefix + slotId;
}
/// <summary>
/// Gets the container Id for the specified slotId.
/// </summary>
public static string GetOrganContainerId(string slotId)
{
return OrganSlotContainerIdPrefix + slotId;
}
}

View File

@@ -6,17 +6,17 @@
torso:
part: TorsoHuman
connections:
- left arm
- right arm
right arm:
- left_arm
- right_arm
right_arm:
part: RightArmHuman
connections:
- right hand
left arm:
- right_hand
left_arm:
part: LeftArmHuman
connections:
- left hand
right hand:
- left_hand
right_hand:
part: RightHandHuman
left hand:
left_hand:
part: LeftHandHuman

View File

@@ -13,37 +13,37 @@
torso:
part: TorsoHuman
connections:
- left arm
- right arm
- left leg
- right leg
- left_arm
- right_arm
- left_leg
- right_leg
organs:
heart: OrganHumanHeart
lungs: OrganHumanLungs
stomach: OrganHumanStomach
liver: OrganHumanLiver
kidneys: OrganHumanKidneys
right arm:
right_arm:
part: RightArmHuman
connections:
- right hand
left arm:
- right_hand
left_arm:
part: LeftArmHuman
connections:
- left hand
right hand:
- left_hand
right_hand:
part: RightHandHuman
left hand:
left_hand:
part: LeftHandHuman
right leg:
right_leg:
part: RightLegHuman
connections:
- right foot
left leg:
- right_foot
left_leg:
part: LeftLegHuman
connections:
- left foot
right foot:
- left_foot
right_foot:
part: RightFootHuman
left foot:
left_foot:
part: LeftFootHuman

View File

@@ -4,7 +4,7 @@
sprite: Mobs/Animals/bee.rsi
state: 0
product: CrateNPCBee
cost: 4200
cost: 7000
category: Livestock
group: market
@@ -14,7 +14,7 @@
sprite: Mobs/Animals/butterfly.rsi
state: butterfly
product: CrateNPCButterflies
cost: 2700
cost: 4400
category: Livestock
group: market
@@ -24,7 +24,7 @@
sprite: Mobs/Pets/cat.rsi
state: cat
product: CrateNPCCat
cost: 1000
cost: 1200
category: Livestock
group: market
@@ -34,7 +34,7 @@
sprite: Mobs/Animals/chicken.rsi
state: icon-1
product: CrateNPCChicken
cost: 2600
cost: 4000
category: Livestock
group: market
@@ -44,7 +44,7 @@
sprite: Mobs/Animals/crab.rsi
state: crab
product: CrateNPCCrab
cost: 2000
cost: 3000
category: Livestock
group: market
@@ -54,7 +54,7 @@
sprite: Mobs/Animals/duck.rsi
state: icon-0
product: CrateNPCDuck
cost: 3800
cost: 6000
category: Livestock
group: market
@@ -64,7 +64,7 @@
sprite: Mobs/Pets/corgi.rsi
state: corgi
product: CrateNPCCorgi
cost: 1000
cost: 1200
category: Livestock
group: market
@@ -84,7 +84,7 @@
sprite: Mobs/Animals/goat.rsi
state: goat
product: CrateNPCGoat
cost: 1000
cost: 1200
category: Livestock
group: market
@@ -94,7 +94,7 @@
sprite: Mobs/Animals/goose.rsi
state: goose
product: CrateNPCGoose
cost: 1500
cost: 2100
category: Livestock
group: market
@@ -104,7 +104,7 @@
sprite: Mobs/Animals/gorilla.rsi
state: icon
product: CrateNPCGorilla
cost: 1000
cost: 1100
category: Livestock
group: market
@@ -124,7 +124,7 @@
sprite: Mobs/Animals/mouse.rsi
state: icon-0
product: CrateNPCMouse
cost: 2700
cost: 4400
category: Livestock
group: market
@@ -134,7 +134,7 @@
sprite: Mobs/Animals/parrot.rsi
state: parrot
product: CrateNPCParrot
cost: 2000
cost: 3000
category: Livestock
group: market
@@ -144,7 +144,7 @@
sprite: Mobs/Animals/penguin.rsi
state: penguin
product: CrateNPCPenguin
cost: 1500
cost: 2100
category: Livestock
group: market
@@ -154,7 +154,7 @@
sprite: Mobs/Animals/pig.rsi
state: pig
product: CrateNPCPig
cost: 1000
cost: 1100
category: Livestock
group: market
@@ -164,7 +164,7 @@
sprite: Mobs/Animals/snake.rsi
state: snake
product: CrateNPCSnake
cost: 2000
cost: 3000
category: Livestock
group: market
@@ -184,7 +184,7 @@
sprite: Mobs/Animals/lizard.rsi
state: lizard
product: CrateNPCLizard
cost: 1000
cost: 1100
category: Livestock
group: market