Refactor body component to use slots instead of an army of dictionaries (#3749)

* Refactor body component to use slots instead of an army of dictionaries

* Update vox

* Replace static method call with extension

* Add setpart method, replace dispose with shutdown

* Fix tests, fix not listening to slot events when setting a part
This commit is contained in:
DrSmugleaf
2021-04-05 14:54:51 +02:00
committed by GitHub
parent 5387f87608
commit 677706b117
30 changed files with 602 additions and 466 deletions

View File

@@ -8,7 +8,6 @@ using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using static Robust.Client.UserInterface.Controls.ItemList;
namespace Content.Client.GameObjects.Components.Body.Scanner
@@ -114,9 +113,9 @@ namespace Content.Client.GameObjects.Components.Body.Scanner
return;
}
foreach (var slotName in body.Parts.Keys)
foreach (var (part, _) in body.Parts)
{
BodyPartList.AddItem(Loc.GetString(slotName));
BodyPartList.AddItem(Loc.GetString(part.Name));
}
}
@@ -129,12 +128,12 @@ namespace Content.Client.GameObjects.Components.Body.Scanner
return;
}
var slot = body.SlotAt(args.ItemIndex).Key;
_currentBodyPart = body.PartAt(args.ItemIndex).Value;
var slot = body.SlotAt(args.ItemIndex);
_currentBodyPart = body.PartAt(args.ItemIndex).Key;
if (body.Parts.TryGetValue(slot, out var part))
if (slot.Part != null)
{
UpdateBodyPartBox(part, slot);
UpdateBodyPartBox(slot.Part, slot.Id);
}
}

View File

@@ -55,7 +55,7 @@ namespace Content.Client.GameObjects.Components.Mobs
if (Owner.TryGetComponent(out IBody? body))
{
foreach (var part in body.Parts.Values)
foreach (var (part, _) in body.Parts)
{
if (!part.Owner.TryGetComponent(out SpriteComponent? partSprite))
{

View File

@@ -131,7 +131,7 @@ namespace Content.IntegrationTests.Tests.Body
Assert.That(human.TryGetComponent(out IBody? body));
Assert.NotNull(body);
var centerPart = body!.CenterPart();
var centerPart = body!.CenterPart;
Assert.NotNull(centerPart);
Assert.That(body.TryGetSlot(centerPart!, out var centerSlot));
@@ -196,7 +196,7 @@ namespace Content.IntegrationTests.Tests.Body
behavior.ResetAll();
body.TryAddPart(centerSlot!, centerPart, true);
body.SetPart(centerSlot!.Id, centerPart);
Assert.That(behavior.WasAddedToBody);
Assert.False(behavior.WasAddedToPart);

View File

@@ -78,7 +78,8 @@ namespace Content.IntegrationTests.Tests.GameObjects.Components.ActionBlocking
// Test to ensure a player with 4 hands will still only have 2 hands cuffed
AddHand(cuffed.Owner);
AddHand(cuffed.Owner);
Assert.True(cuffed.CuffedHandCount == 2 && hands.Hands.Count() == 4, "Player doesn't have correct amount of hands cuffed");
Assert.That(cuffed.CuffedHandCount, Is.EqualTo(2));
Assert.That(hands.Hands.Count(), Is.EqualTo(4));
// Test to give a player with 4 hands 2 sets of cuffs
cuffed.TryAddNewCuffs(human, secondCuffs);

View File

@@ -1,6 +1,5 @@
#nullable enable
using Content.Server.Administration;
using Content.Server.GameObjects.Components.Body.Part;
using Content.Shared.Administration;
using Content.Shared.GameObjects.Components.Body;
using Content.Shared.GameObjects.Components.Body.Part;
@@ -8,6 +7,7 @@ using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using static Content.Server.GameObjects.Components.Body.Part.BodyPartComponent;
namespace Content.Server.Commands
{
@@ -100,7 +100,7 @@ namespace Content.Server.Commands
return;
}
body.TryAddPart($"{nameof(BodyPartComponent.AttachBodyPartVerb)}-{partEntity.Uid}", part, true);
body.SetPart($"{nameof(AttachBodyPartVerb)}-{partEntity.Uid}", part);
}
}
}

View File

@@ -138,11 +138,9 @@ namespace Content.Server.Commands.Body
}
var slot = part.GetHashCode().ToString();
var response = body.TryAddPart(slot, part, true)
? $"Added hand to entity {entity.Name}"
: $"Error occurred trying to add a hand to entity {entity.Name}";
body.SetPart(slot, part);
shell.WriteLine(response);
shell.WriteLine($"Added hand to entity {entity.Name}");
}
}
}

View File

@@ -48,7 +48,7 @@ namespace Content.Server.Commands.Body
var mechanismName = string.Join(" ", args).ToLowerInvariant();
foreach (var part in body.Parts.Values)
foreach (var (part, _) in body.Parts)
foreach (var mechanism in part.Mechanisms)
{
if (mechanism.Name.ToLowerInvariant() == mechanismName)

View File

@@ -42,7 +42,8 @@ namespace Content.Server.Commands.Body
return;
}
var (_, hand) = body.Parts.FirstOrDefault(x => x.Value.PartType == BodyPartType.Hand);
var hand = body.GetPartsOfType(BodyPartType.Hand).FirstOrDefault();
if (hand == null)
{
shell.WriteLine("You have no hands.");

View File

@@ -12,7 +12,7 @@ namespace Content.Server.GameObjects.Components.Body.Behavior
{
public static bool HasMechanismBehavior<T>(this IBody body) where T : IMechanismBehavior
{
return body.Parts.Values.Any(p => p.HasMechanismBehavior<T>());
return body.Parts.Any(p => p.Key.HasMechanismBehavior<T>());
}
public static bool HasMechanismBehavior<T>(this IBodyPart part) where T : IMechanismBehavior
@@ -22,7 +22,7 @@ namespace Content.Server.GameObjects.Components.Body.Behavior
public static IEnumerable<IMechanismBehavior> GetMechanismBehaviors(this IBody body)
{
foreach (var part in body.Parts.Values)
foreach (var (part, _) in body.Parts)
foreach (var mechanism in part.Mechanisms)
foreach (var behavior in mechanism.Behaviors.Values)
{
@@ -46,7 +46,7 @@ namespace Content.Server.GameObjects.Components.Body.Behavior
public static IEnumerable<T> GetMechanismBehaviors<T>(this IBody body) where T : class, IMechanismBehavior
{
foreach (var part in body.Parts.Values)
foreach (var (part, _) in body.Parts)
foreach (var mechanism in part.Mechanisms)
foreach (var behavior in mechanism.Behaviors.Values)
{

View File

@@ -5,11 +5,11 @@ using Content.Server.GameObjects.Components.Observer;
using Content.Shared.Audio;
using Content.Shared.GameObjects.Components.Body;
using Content.Shared.GameObjects.Components.Body.Part;
using Content.Shared.GameObjects.Components.Body.Slot;
using Content.Shared.GameObjects.Components.Mobs.State;
using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.Utility;
using Robust.Server.Console;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Console;
using Robust.Shared.Containers;
@@ -29,20 +29,20 @@ namespace Content.Server.GameObjects.Components.Body
{
private Container _partContainer = default!;
protected override bool CanAddPart(string slot, IBodyPart part)
protected override bool CanAddPart(string slotId, IBodyPart part)
{
return base.CanAddPart(slot, part) &&
return base.CanAddPart(slotId, part) &&
_partContainer.CanInsert(part.Owner);
}
protected override void OnAddPart(string slot, IBodyPart part)
protected override void OnAddPart(BodyPartSlot slot, IBodyPart part)
{
base.OnAddPart(slot, part);
_partContainer.Insert(part.Owner);
}
protected override void OnRemovePart(string slot, IBodyPart part)
protected override void OnRemovePart(BodyPartSlot slot, IBodyPart part)
{
base.OnRemovePart(slot, part);
@@ -54,21 +54,25 @@ namespace Content.Server.GameObjects.Components.Body
{
base.Initialize();
_partContainer = ContainerHelpers.EnsureContainer<Container>(Owner, $"{Name}-{nameof(BodyComponent)}");
_partContainer = Owner.EnsureContainer<Container>($"{Name}-{nameof(BodyComponent)}");
var preset = Preset;
foreach (var (slot, partId) in PartIds)
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(partId, Owner.Transform.MapPosition);
var entity = Owner.EntityManager.SpawnEntity(preset.PartIDs[slot.Id], Owner.Transform.MapPosition);
if (!entity.TryGetComponent(out IBodyPart? part))
{
Logger.Error($"Entity {partId} does not have a {nameof(IBodyPart)} component.");
Logger.Error($"Entity {slot.Id} does not have a {nameof(IBodyPart)} component.");
continue;
}
TryAddPart(slot, part, true);
SetPart(slot.Id, part);
}
}
}
@@ -79,7 +83,7 @@ namespace Content.Server.GameObjects.Components.Body
// 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.Values)
foreach (var (part, _) in Parts)
{
part.Dirty();
}

View File

@@ -68,13 +68,13 @@ namespace Content.Server.GameObjects.Components.Body
// Create dictionary to send to client (text to be shown : data sent back if selected)
var toSend = new Dictionary<string, int>();
foreach (var (key, value) in body.Parts)
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 (value.CanAddMechanism(this))
if (part.CanAddMechanism(this))
{
OptionsCache.Add(IdHash, value);
toSend.Add(key + ": " + value.Name, IdHash++);
OptionsCache.Add(IdHash, slot);
toSend.Add(part + ": " + part.Name, IdHash++);
}
}

View File

@@ -1,6 +1,5 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Content.Server.Utility;
using Content.Shared.GameObjects.Components.Body;
@@ -61,7 +60,7 @@ namespace Content.Server.GameObjects.Components.Body.Part
{
base.Initialize();
_mechanismContainer = ContainerHelpers.EnsureContainer<Container>(Owner, $"{Name}-{nameof(BodyPartComponent)}");
_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
@@ -123,25 +122,23 @@ namespace Content.Server.GameObjects.Components.Body.Part
// 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.
var unoccupiedSlots = body.Slots.Keys.ToList().Except(body.Parts.Keys.ToList()).ToList();
foreach (var slot in unoccupiedSlots)
foreach (var slot in body.EmptySlots)
{
if (!body.TryGetSlotType(slot, out var typeResult) ||
typeResult != PartType ||
!body.TryGetPartConnections(slot, out var parts))
if (slot.PartType != PartType)
{
continue;
}
foreach (var connectedPart in parts)
foreach (var connection in slot.Connections)
{
if (!connectedPart.CanAttachPart(this))
if (connection.Part == null ||
!connection.Part.CanAttachPart(this))
{
continue;
}
_optionsCache.Add(_idHash, slot);
toSend.Add(slot, _idHash++);
toSend.Add(slot.Id, _idHash++);
}
}
@@ -269,7 +266,7 @@ namespace Content.Server.GameObjects.Components.Body.Part
return;
}
body.TryAddPart($"{nameof(AttachBodyPartVerb)}-{component.Owner.Uid}", component, true);
body.SetPart($"{nameof(AttachBodyPartVerb)}-{component.Owner.Uid}", component);
}
}
}

View File

@@ -69,13 +69,13 @@ namespace Content.Server.GameObjects.Components.Body.Surgery
// Create dictionary to send to client (text to be shown : data sent back if selected)
var toSend = new Dictionary<string, int>();
foreach (var (key, value) in body.Parts)
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 (value.SurgeryCheck(_surgeryType))
if (part.SurgeryCheck(_surgeryType))
{
_optionsCache.Add(_idHash, value);
toSend.Add(key + ": " + value.Name, _idHash++);
_optionsCache.Add(_idHash, part);
toSend.Add(slot.Id + ": " + part.Name, _idHash++);
}
}

View File

@@ -469,19 +469,26 @@ namespace Content.Server.GameObjects.Components.Kitchen
if (victim.TryGetComponent<IBody>(out var body))
{
var heads = body.GetPartsOfType(BodyPartType.Head);
foreach (var head in heads)
var headSlots = body.GetSlotsOfType(BodyPartType.Head);
foreach (var slot in headSlots)
{
if (!body.TryDropPart(head, out var dropped))
var part = slot.Part;
if (part == null ||
!body.TryDropPart(slot, out var dropped))
{
continue;
}
var droppedHeads = dropped.Where(p => p.PartType == BodyPartType.Head);
foreach (var droppedHead in droppedHeads)
foreach (var droppedPart in dropped.Values)
{
_storage.Insert(droppedHead.Owner);
if (droppedPart.PartType != BodyPartType.Head)
{
continue;
}
_storage.Insert(droppedPart.Owner);
headCount++;
}
}

View File

@@ -18,7 +18,7 @@ namespace Content.Server.GameObjects.Components.Mobs
if (Owner.TryGetComponent(out IBody? body))
{
foreach (var part in body.Parts.Values)
foreach (var (part, _) in body.Parts)
{
if (!part.Owner.TryGetComponent(out SpriteComponent? sprite))
{
@@ -37,7 +37,7 @@ namespace Content.Server.GameObjects.Components.Mobs
if (Appearance != null! && Owner.TryGetComponent(out IBody? body))
{
foreach (var part in body.Parts.Values)
foreach (var (part, _) in body.Parts)
{
if (!part.Owner.TryGetComponent(out SpriteComponent? sprite))
{

View File

@@ -80,8 +80,8 @@ namespace Content.Server.GameObjects.Components.Movement
return false;
}
if (body.GetPartsOfType(BodyPartType.Leg).Count == 0 ||
body.GetPartsOfType(BodyPartType.Foot).Count == 0)
if (!body.HasPartOfType(BodyPartType.Leg) ||
!body.HasPartOfType(BodyPartType.Foot))
{
reason = Loc.GetString("comp-climbable-cant-climb");
return false;

View File

@@ -1,4 +1,5 @@
#nullable enable
using System.Threading.Tasks;
using Content.Server.GameObjects.Components.Interactable;
using Content.Server.GameObjects.Components.Items.Storage;
using Content.Server.GameObjects.Components.Strap;
@@ -14,15 +15,14 @@ using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.Interfaces;
using Content.Shared.Interfaces.GameObjects.Components;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using Robust.Shared.Random;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
using System.Threading.Tasks;
using Robust.Shared.Audio;
using Robust.Shared.Player;
namespace Content.Server.GameObjects.Components.Watercloset
{
@@ -144,7 +144,7 @@ namespace Content.Server.GameObjects.Components.Watercloset
{
// check that victim even have head
if (victim.TryGetComponent<IBody>(out var body) &&
body.GetPartsOfType(BodyPartType.Head).Count != 0)
body.HasPartOfType(BodyPartType.Head))
{
var othersMessage = Loc.GetString("{0:theName} sticks their head into {1:theName} and flushes it!", victim, Owner);
victim.PopupMessageOtherClients(othersMessage);

View File

@@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis;
using Content.Shared.GameObjects.Components.Body.Part;
using Content.Shared.GameObjects.Components.Body.Part.Property;
using Content.Shared.GameObjects.Components.Body.Preset;
using Content.Shared.GameObjects.Components.Body.Slot;
using Content.Shared.GameObjects.Components.Body.Template;
using Robust.Shared.GameObjects;
@@ -17,70 +18,81 @@ namespace Content.Shared.GameObjects.Components.Body
public interface IBody : IComponent, IBodyPartContainer
{
/// <summary>
/// The name of the <see cref="BodyTemplatePrototype"/> used by this
/// The <see cref="BodyTemplatePrototype"/> used to create this
/// <see cref="IBody"/>.
/// </summary>
public string? TemplateName { get; }
public BodyTemplatePrototype? Template { get; }
/// <summary>
/// The name of the <see cref="BodyPresetPrototype"/> used by this
/// The <see cref="BodyPresetPrototype"/> used to create this
/// <see cref="IBody"/>.
/// </summary>
public string? PresetName { get; }
public BodyPresetPrototype? Preset { get; }
/// <summary>
/// An enumeration of the slots that make up this body, regardless
/// of if they contain a part or not.
/// </summary>
IEnumerable<BodyPartSlot> Slots { get; }
/// <summary>
/// An enumeration of the parts on this body paired with the slots
/// that they are in.
/// </summary>
IEnumerable<KeyValuePair<IBodyPart, BodyPartSlot>> Parts { get; }
/// <summary>
/// An enumeration of the slots on this body without a part in them.
/// </summary>
IEnumerable<BodyPartSlot> EmptySlots { get; }
/// <summary>
/// Finds the central <see cref="BodyPartSlot"/>, if any,
/// of this body.
/// </summary>
/// <returns>
/// The central <see cref="BodyPartSlot"/> if one exists,
/// null otherwise.
/// </returns>
BodyPartSlot? CenterSlot { get; }
/// <summary>
/// Finds the central <see cref="IBodyPart"/>, if any,
/// of this body.
/// </summary>
/// <returns>
/// The central <see cref="IBodyPart"/> if one exists,
/// null otherwise.
/// </returns>
IBodyPart? CenterPart { get; }
// TODO BODY Part slots
// TODO BODY Sensible templates
/// <summary>
/// Mapping of <see cref="IBodyPart"/> slots in this body to their
/// <see cref="BodyPartType"/>.
/// </summary>
public Dictionary<string, BodyPartType> Slots { get; }
/// <summary>
/// Mapping of slots to the <see cref="IBodyPart"/> filling each one.
/// </summary>
public IReadOnlyDictionary<string, IBodyPart> Parts { get; }
/// <summary>
/// Mapping of slots to which other slots they connect to.
/// For example, the torso could be mapped to a list containing
/// "right arm", "left arm", "left leg", and "right leg".
/// This is mapped both ways during runtime, but in the prototype
/// it only has to be defined one-way, "torso": "left arm" will automatically
/// map "left arm" to "torso" as well.
/// </summary>
public Dictionary<string, List<string>> Connections { get; }
/// <summary>
/// Mapping of template slots to the ID of the <see cref="IBodyPart"/>
/// that should fill it. E.g. "right arm" : "BodyPart.arm.basic_human".
/// </summary>
public IReadOnlyDictionary<string, string> PartIds { get; }
/// <summary>
/// Attempts to add a part to the given slot.
/// </summary>
/// <param name="slot">The slot to add this part to.</param>
/// <param name="slotId">The slot to add this part to.</param>
/// <param name="part">The part to add.</param>
/// <param name="force">
/// Whether or not to check for the validity of the given <see cref="part"/>.
/// Passing true does not guarantee it to be added, for example if it
/// had already been added before.
/// <param name="checkSlotExists">
/// Whether to check if the slot exists, or create one otherwise.
/// </param>
/// <returns>
/// true if the part was added, false otherwise even if it was already added.
/// true if the part was added, false otherwise even if it was
/// already added.
/// </returns>
bool TryAddPart(string slot, IBodyPart part, bool force = false);
bool TryAddPart(string slotId, IBodyPart part);
void SetPart(string slotId, IBodyPart part);
/// <summary>
/// Checks if there is a <see cref="IBodyPart"/> in the given slot.
/// </summary>
/// <param name="slot">The slot to look in.</param>
/// <param name="slotId">The slot to look in.</param>
/// <returns>
/// true if there is a part in the given <see cref="slot"/>,
/// true if there is a part in the given <see cref="slotId"/>,
/// false otherwise.
/// </returns>
bool HasPart(string slot);
bool HasPart(string slotId);
/// <summary>
/// Checks if this <see cref="IBody"/> contains the given <see cref="part"/>.
@@ -93,145 +105,130 @@ namespace Content.Shared.GameObjects.Components.Body
bool HasPart(IBodyPart part);
/// <summary>
/// Removes the given <see cref="IBodyPart"/> reference, potentially
/// dropping other <see cref="IBodyPart">BodyParts</see> if they
/// were hanging off of it.
/// Removes the given <see cref="IBodyPart"/> from this body,
/// dropping other <see cref="IBodyPart"/> if they were hanging
/// off of it.
/// <param name="part">The part to remove.</param>
/// <returns>
/// true if the part was removed, false otherwise
/// even if the part was already removed previously.
/// </returns>
/// </summary>
void RemovePart(IBodyPart part);
bool RemovePart(IBodyPart part);
/// <summary>
/// Removes the body part in slot <see cref="slot"/> from this body,
/// Removes the body part in slot <see cref="slotId"/> from this body,
/// if one exists.
/// </summary>
/// <param name="slot">The slot to remove it from.</param>
/// <returns>True if the part was removed, false otherwise.</returns>
bool RemovePart(string slot);
/// <param name="slotId">The slot to remove it from.</param>
/// <returns>true if the part was removed, false otherwise.</returns>
bool RemovePart(string slotId);
/// <summary>
/// Removes the body part from this body, if one exists.
/// </summary>
/// <param name="part">The part to remove from this body.</param>
/// <param name="slotName">The slot that the part was in, if any.</param>
/// <returns>True if <see cref="part"/> was removed, false otherwise.</returns>
bool RemovePart(IBodyPart part, [NotNullWhen(true)] out string? slotName);
/// <param name="slotId">The slot that the part was in, if any.</param>
/// <returns>
/// true if <see cref="part"/> was removed, false otherwise.
/// </returns>
bool RemovePart(IBodyPart part, [NotNullWhen(true)] out BodyPartSlot? slotId);
/// <summary>
/// Disconnects the given <see cref="IBodyPart"/> reference, potentially
/// dropping other <see cref="IBodyPart">BodyParts</see> if they
/// were hanging off of it.
/// </summary>
/// <param name="part">The part to drop.</param>
/// <param name="slot">The part to drop.</param>
/// <param name="dropped">
/// All of the parts that were dropped, including <see cref="part"/>.
/// All of the parts that were dropped, including the one in
/// <see cref="slot"/>.
/// </param>
/// <returns>
/// True if the part was dropped, false otherwise.
/// true if the part was dropped, false otherwise.
/// </returns>
bool TryDropPart(IBodyPart part, [NotNullWhen(true)] out List<IBodyPart>? dropped);
bool TryDropPart(BodyPartSlot slot, [NotNullWhen(true)] out Dictionary<BodyPartSlot, IBodyPart>? dropped);
/// <summary>
/// Recursively searches for if <see cref="part"/> is connected to
/// the center.
/// </summary>
/// <param name="part">The body part to find the center for.</param>
/// <returns>True if it is connected to the center, false otherwise.</returns>
/// <returns>
/// true if it is connected to the center, false otherwise.
/// </returns>
bool ConnectedToCenter(IBodyPart part);
/// <summary>
/// Finds the central <see cref="IBodyPart"/>, if any, of this body based on
/// the <see cref="BodyTemplate"/>. For humans, this is the torso.
/// </summary>
/// <returns>The <see cref="BodyPart"/> if one exists, null otherwise.</returns>
IBodyPart? CenterPart();
/// <summary>
/// Returns whether the given part slot name exists within the current
/// <see cref="BodyTemplate"/>.
/// Returns whether the given part slot exists in this body.
/// </summary>
/// <param name="slot">The slot to check for.</param>
/// <returns>True if the slot exists in this body, false otherwise.</returns>
/// <returns>true if the slot exists in this body, false otherwise.</returns>
bool HasSlot(string slot);
/// <summary>
/// Finds the <see cref="IBodyPart"/> in the given <see cref="slot"/> if
/// one exists.
/// </summary>
/// <param name="slot">The part slot to search in.</param>
/// <param name="result">The body part in that slot, if any.</param>
/// <returns>True if found, false otherwise.</returns>
bool TryGetPart(string slot, [NotNullWhen(true)] out IBodyPart? result);
BodyPartSlot? GetSlot(IBodyPart part);
/// <summary>
/// Finds the slotName that the given <see cref="IBodyPart"/> resides in.
/// Finds the slot that the given <see cref="IBodyPart"/> resides in.
/// </summary>
/// <param name="part">
/// The <see cref="IBodyPart"/> to find the slot for.
/// </param>
/// <param name="slot">The slot found, if any.</param>
/// <returns>True if a slot was found, false otherwise</returns>
bool TryGetSlot(IBodyPart part, [NotNullWhen(true)] out string? slot);
/// <returns>true if a slot was found, false otherwise</returns>
bool TryGetSlot(IBodyPart part, [NotNullWhen(true)] out BodyPartSlot? slot);
/// <summary>
/// Finds the <see cref="BodyPartType"/> in the given
/// <see cref="slot"/> if one exists.
/// Finds the <see cref="IBodyPart"/> in the given
/// <see cref="slotId"/> if one exists.
/// </summary>
/// <param name="slot">The slot to search in.</param>
/// <param name="result">
/// The <see cref="BodyPartType"/> of that slot, if any.
/// </param>
/// <returns>True if found, false otherwise.</returns>
bool TryGetSlotType(string slot, out BodyPartType result);
/// <param name="slotId">The part slot to search in.</param>
/// <param name="result">The body part in that slot, if any.</param>
/// <returns>true if found, false otherwise.</returns>
bool TryGetPart(string slotId, [NotNullWhen(true)] out IBodyPart? result);
/// <summary>
/// Finds the names of all slots connected to the given
/// <see cref="slot"/> for the template.
/// Checks if a slot of the specified type exists on this body.
/// </summary>
/// <param name="slot">The slot to search in.</param>
/// <param name="connections">The connections found, if any.</param>
/// <returns>True if the connections are found, false otherwise.</returns>
bool TryGetSlotConnections(string slot, [NotNullWhen(true)] out List<string>? connections);
/// <param name="type">The type to check for.</param>
/// <returns>true if present, false otherwise.</returns>
bool HasSlotOfType(BodyPartType type);
/// <summary>
/// Grabs all occupied slots connected to the given slot,
/// regardless of whether the given <see cref="slot"/> is occupied.
/// Gets all slots of the specified type on this body.
/// </summary>
/// <param name="slot">The slot name to find connections from.</param>
/// <param name="connections">The connected body parts, if any.</param>
/// <returns>
/// True if successful, false if the slot couldn't be found on this body.
/// </returns>
bool TryGetPartConnections(string slot, [NotNullWhen(true)] out List<IBodyPart>? connections);
/// <param name="type">The type to check for.</param>
/// <returns>An enumerable of the found slots.</returns>
IEnumerable<BodyPartSlot> GetSlotsOfType(BodyPartType type);
/// <summary>
/// Grabs all parts connected to the given <see cref="part"/>, regardless
/// of whether the given <see cref="part"/> is occupied.
/// Checks if a part of the specified type exists on this body.
/// </summary>
/// <param name="part">The part to find connections from.</param>
/// <param name="connections">The connected body parts, if any.</param>
/// <returns>
/// True if successful, false if the part couldn't be found on this body.
/// </returns>
bool TryGetPartConnections(IBodyPart part, [NotNullWhen(true)] out List<IBodyPart>? connections);
/// <param name="type">The type to check for.</param>
/// <returns>true if present, false otherwise.</returns>
bool HasPartOfType(BodyPartType type);
/// <summary>
/// Finds all <see cref="IBodyPart"/>s of the given type in this body.
/// Gets all slots of the specified type on this body.
/// </summary>
/// <returns>A list of parts of that type.</returns>
List<IBodyPart> GetPartsOfType(BodyPartType type);
/// <param name="type">The type to check for.</param>
/// <returns>An enumerable of the found slots.</returns>
IEnumerable<IBodyPart> GetPartsOfType(BodyPartType type);
/// <summary>
/// Finds all <see cref="IBodyPart"/>s with the given property in this body.
/// Finds all <see cref="IBodyPart"/>s with the given property in
/// this body.
/// </summary>
/// <type name="type">The property type to look for.</type>
/// <returns>A list of parts with that property.</returns>
List<(IBodyPart part, IBodyPartProperty property)> GetPartsWithProperty(Type type);
IEnumerable<(IBodyPart part, IBodyPartProperty property)> GetPartsWithProperty(Type type);
/// <summary>
/// Finds all <see cref="IBodyPart"/>s with the given property in this body.
/// </summary>
/// <typeparam name="T">The property type to look for.</typeparam>
/// <returns>A list of parts with that property.</returns>
List<(IBodyPart part, T property)> GetPartsWithProperty<T>() where T : class, IBodyPartProperty;
IEnumerable<(IBodyPart part, T property)> GetPartsWithProperty<T>() where T : class, IBodyPartProperty;
// TODO BODY Make a slot object that makes sense to the human mind, and make it serializable. Imagine the possibilities!
/// <summary>
@@ -239,18 +236,21 @@ namespace Content.Shared.GameObjects.Components.Body
/// </summary>
/// <param name="index">The index to look in.</param>
/// <returns>A pair of the slot name and part type occupying it.</returns>
KeyValuePair<string, BodyPartType> SlotAt(int index);
BodyPartSlot SlotAt(int index);
/// <summary>
/// Retrieves the part at the given index.
/// </summary>
/// <param name="index">The index to look in.</param>
/// <returns>A pair of the part name and body part occupying it.</returns>
KeyValuePair<string, IBodyPart> PartAt(int index);
KeyValuePair<IBodyPart, BodyPartSlot> PartAt(int index);
/// <summary>
/// Gibs this body.
/// </summary>
/// <param name="gibParts">
/// Whether or not to also gib this body's parts.
/// </param>
void Gib(bool gibParts = false);
}
}

View File

@@ -15,6 +15,11 @@ namespace Content.Shared.GameObjects.Components.Body.Part
/// </summary>
IBody? Body { get; set; }
/// <summary>
/// The string to show when displaying this part's name to players.
/// </summary>
string DisplayName { get; }
/// <summary>
/// <see cref="BodyPartType"/> that this <see cref="IBodyPart"/> is considered
/// to be.

View File

@@ -20,20 +20,20 @@ namespace Content.Shared.GameObjects.Components.Body.Part
public class BodyPartAddedEventArgs : EventArgs
{
public BodyPartAddedEventArgs(IBodyPart part, string slot)
public BodyPartAddedEventArgs(string slot, IBodyPart part)
{
Part = part;
Slot = slot;
Part = part;
}
/// <summary>
/// The part that was added.
/// </summary>
public IBodyPart Part { get; }
/// <summary>
/// The slot that <see cref="Part"/> was added to.
/// </summary>
public string Slot { get; }
/// <summary>
/// The part that was added.
/// </summary>
public IBodyPart Part { get; }
}
}

View File

@@ -19,20 +19,20 @@ namespace Content.Shared.GameObjects.Components.Body.Part
public class BodyPartRemovedEventArgs : EventArgs
{
public BodyPartRemovedEventArgs(IBodyPart part, string slot)
public BodyPartRemovedEventArgs(string slot, IBodyPart part)
{
Part = part;
Slot = slot;
Part = part;
}
/// <summary>
/// The part that was removed.
/// </summary>
public IBodyPart Part { get; }
/// <summary>
/// The slot that <see cref="Part"/> was removed from.
/// </summary>
public string Slot { get; }
/// <summary>
/// The part that was removed.
/// </summary>
public IBodyPart Part { get; }
}
}

View File

@@ -57,6 +57,9 @@ namespace Content.Shared.GameObjects.Components.Body.Part
}
}
[ViewVariables]
public string DisplayName => Name;
[ViewVariables]
[DataField("partType")]
public BodyPartType PartType { get; private set; } = BodyPartType.Other;

View File

@@ -20,13 +20,14 @@ namespace Content.Shared.GameObjects.Components.Body.Preset
[field: DataField("id", required: true)]
public string ID { get; } = default!;
[DataField("partIDs")]
[field: DataField("partIDs")]
private Dictionary<string, string> _partIDs = new();
[ViewVariables]
[field: DataField("name")]
public string Name { get; } = string.Empty;
[ViewVariables] public Dictionary<string, string> PartIDs => new(_partIDs);
[ViewVariables]
public Dictionary<string, string> PartIDs => new(_partIDs);
}
}

View File

@@ -7,15 +7,13 @@ using Content.Shared.Damage;
using Content.Shared.GameObjects.Components.Body.Part;
using Content.Shared.GameObjects.Components.Body.Part.Property;
using Content.Shared.GameObjects.Components.Body.Preset;
using Content.Shared.GameObjects.Components.Body.Slot;
using Content.Shared.GameObjects.Components.Body.Template;
using Content.Shared.GameObjects.Components.Damage;
using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.GameObjects.EntitySystems;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Collision;
using Robust.Shared.Players;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
@@ -34,35 +32,45 @@ namespace Content.Shared.GameObjects.Components.Body
public override uint? NetID => ContentNetIDs.BODY;
[DataField("centerSlot", required: true)]
private string? _centerSlot;
private Dictionary<string, string> _partIds = new();
private readonly Dictionary<string, IBodyPart> _parts = new();
[ViewVariables]
[field: DataField("template", required: true)]
private string? TemplateId { get; } = default;
[ViewVariables]
[DataField("template", required: true)]
public string? TemplateName { get; private set; }
[field: DataField("preset", required: true)]
private string? PresetId { get; } = default;
[ViewVariables]
[DataField("preset", required: true)]
public string? PresetName { get; private set; }
public BodyTemplatePrototype? Template => TemplateId == null
? null
: _prototypeManager.Index<BodyTemplatePrototype>(TemplateId);
[ViewVariables]
public Dictionary<string, BodyPartType> Slots { get; private set; } = new();
public BodyPresetPrototype? Preset => PresetId == null
? null
: _prototypeManager.Index<BodyPresetPrototype>(PresetId);
[ViewVariables]
public Dictionary<string, List<string>> Connections { get; private set; } = new();
/// <summary>
/// Maps slots to the part filling each one.
/// </summary>
[ViewVariables]
public IReadOnlyDictionary<string, IBodyPart> Parts => _parts;
private Dictionary<string, BodyPartSlot> SlotIds { get; } = new();
[ViewVariables]
public IReadOnlyDictionary<string, string> PartIds => _partIds;
private Dictionary<IBodyPart, BodyPartSlot> SlotParts { get; } = new();
[ViewVariables]
public IEnumerable<BodyPartSlot> Slots => SlotIds.Values;
[ViewVariables]
public IEnumerable<KeyValuePair<IBodyPart, BodyPartSlot>> Parts => SlotParts;
[ViewVariables]
public IEnumerable<BodyPartSlot> EmptySlots => Slots.Where(slot => slot.Part == null);
public BodyPartSlot? CenterSlot =>
Template?.CenterSlot is { } centerSlot
? SlotIds.GetValueOrDefault(centerSlot)
: null;
public IBodyPart? CenterPart => CenterSlot?.Part;
public override void Initialize()
{
@@ -70,60 +78,66 @@ namespace Content.Shared.GameObjects.Components.Body
// TODO BODY BeforeDeserialization
// TODO BODY Move to template or somewhere else
if (TemplateName != null)
if (TemplateId != null)
{
var template = _prototypeManager.Index<BodyTemplatePrototype>(TemplateName);
var template = _prototypeManager.Index<BodyTemplatePrototype>(TemplateId);
Connections = template.Connections;
Slots = template.Slots;
_centerSlot = template.CenterSlot;
foreach (var (id, partType) in template.Slots)
{
SetSlot(id, partType);
}
if (PresetName != null)
foreach (var (slotId, connectionIds) in template.Connections)
{
var preset = _prototypeManager.Index<BodyPresetPrototype>(PresetName);
_partIds = preset.PartIDs;
}
// Our prototypes don't force the user to define a BodyPart connection twice. E.g. Head: Torso v.s. Torso: Head.
// The user only has to do one. We want it to be that way in the code, though, so this cleans that up.
var cleanedConnections = new Dictionary<string, List<string>>();
foreach (var targetSlotName in Slots.Keys)
{
var tempConnections = new List<string>();
foreach (var (slotName, slotConnections) in Connections)
{
if (slotName == targetSlotName)
{
foreach (var connection in slotConnections)
{
if (!tempConnections.Contains(connection))
{
tempConnections.Add(connection);
}
}
}
else if (slotConnections.Contains(targetSlotName))
{
tempConnections.Add(slotName);
var connections = connectionIds.Select(id => SlotIds[id]);
SlotIds[slotId].SetConnectionsInternal(connections);
}
}
if (tempConnections.Count > 0)
{
cleanedConnections.Add(targetSlotName, tempConnections);
}
}
Connections = cleanedConnections;
CalculateSpeed();
}
protected virtual bool CanAddPart(string slot, IBodyPart part)
public override void OnRemove()
{
if (!HasSlot(slot) || !_parts.TryAdd(slot, part))
foreach (var slot in SlotIds.Values)
{
slot.Shutdown();
}
base.OnRemove();
}
private BodyPartSlot SetSlot(string id, BodyPartType type)
{
var slot = new BodyPartSlot(id, type);
SlotIds[id] = slot;
slot.PartAdded += part => OnAddPart(slot, part);
slot.PartRemoved += part => OnRemovePart(slot, part);
return slot;
}
private Dictionary<BodyPartSlot, IBodyPart> GetHangingParts(BodyPartSlot from)
{
var hanging = new Dictionary<BodyPartSlot, IBodyPart>();
foreach (var connection in from.Connections)
{
if (connection.Part != null &&
!ConnectedToCenter(connection.Part))
{
hanging.Add(connection, connection.Part);
}
}
return hanging;
}
protected virtual bool CanAddPart(string slotId, IBodyPart part)
{
if (!SlotIds.TryGetValue(slotId, out var slot) ||
slot.CanAddPart(part))
{
return false;
}
@@ -131,11 +145,12 @@ namespace Content.Shared.GameObjects.Components.Body
return true;
}
protected virtual void OnAddPart(string slot, IBodyPart part)
protected virtual void OnAddPart(BodyPartSlot slot, IBodyPart part)
{
SlotParts[part] = slot;
part.Body = this;
var argsAdded = new BodyPartAddedEventArgs(part, slot);
var argsAdded = new BodyPartAddedEventArgs(slot.Id, part);
foreach (var component in Owner.GetAllComponents<IBodyPartAdded>().ToArray())
{
@@ -146,11 +161,22 @@ namespace Content.Shared.GameObjects.Components.Body
OnBodyChanged();
}
protected virtual void OnRemovePart(string slot, IBodyPart part)
protected virtual void OnRemovePart(BodyPartSlot slot, IBodyPart part)
{
SlotParts.Remove(part);
foreach (var connectedSlot in slot.Connections)
{
if (connectedSlot.Part != null &&
!ConnectedToCenter(connectedSlot.Part))
{
RemovePart(connectedSlot.Part);
}
}
part.Body = null;
var args = new BodyPartRemovedEventArgs(part, slot);
var args = new BodyPartRemovedEventArgs(slot.Id, part);
foreach (var component in Owner.GetAllComponents<IBodyPartRemoved>())
{
@@ -158,7 +184,8 @@ namespace Content.Shared.GameObjects.Components.Body
}
// creadth: fall down if no legs
if (part.PartType == BodyPartType.Leg && Parts.Count(x => x.Value.PartType == BodyPartType.Leg) == 0)
if (part.PartType == BodyPartType.Leg &&
GetPartsOfType(BodyPartType.Leg).ToArray().Length == 0)
{
EntitySystem.Get<SharedStandingStateSystem>().Down(Owner);
}
@@ -166,7 +193,7 @@ namespace Content.Shared.GameObjects.Components.Body
// creadth: immediately kill entity if last vital part removed
if (Owner.TryGetComponent(out IDamageableComponent? damageable))
{
if (part.IsVital && Parts.Count(x => x.Value.PartType == part.PartType) == 0)
if (part.IsVital && SlotParts.Count(x => x.Value.PartType == part.PartType) == 0)
{
damageable.ChangeDamage(DamageType.Bloodloss, 300, true); // TODO BODY KILL
}
@@ -175,174 +202,133 @@ namespace Content.Shared.GameObjects.Components.Body
OnBodyChanged();
}
public bool TryAddPart(string slot, IBodyPart part, bool force = false)
public bool TryAddPart(string slotId, IBodyPart part)
{
DebugTools.AssertNotNull(part);
DebugTools.AssertNotNull(slot);
DebugTools.AssertNotNull(slotId);
if (force)
{
if (!HasSlot(slot))
{
Slots[slot] = part.PartType;
}
_parts[slot] = part;
}
else
{
if (!CanAddPart(slot, part))
if (!CanAddPart(slotId, part))
{
return false;
}
return SlotIds.TryGetValue(slotId, out var slot) &&
slot.TryAddPart(part);
}
OnAddPart(slot, part);
return true;
}
public bool HasPart(string slot)
public void SetPart(string slotId, IBodyPart part)
{
DebugTools.AssertNotNull(slot);
if (!SlotIds.TryGetValue(slotId, out var slot))
{
slot = SetSlot(slotId, part.PartType);
SlotIds[slotId] = slot;
}
return _parts.ContainsKey(slot);
slot.SetPart(part);
}
public bool HasPart(string slotId)
{
DebugTools.AssertNotNull(slotId);
return SlotIds.TryGetValue(slotId, out var slot) &&
slot.Part != null;
}
public bool HasPart(IBodyPart part)
{
DebugTools.AssertNotNull(part);
return _parts.ContainsValue(part);
return SlotParts.ContainsKey(part);
}
public void RemovePart(IBodyPart part)
public bool RemovePart(IBodyPart part)
{
DebugTools.AssertNotNull(part);
var slotName = _parts.FirstOrDefault(x => x.Value == part).Key;
return SlotParts.TryGetValue(part, out var slot) &&
slot.RemovePart();
}
if (string.IsNullOrEmpty(slotName))
public bool RemovePart(string slotId)
{
return;
DebugTools.AssertNotNull(slotId);
return SlotIds.TryGetValue(slotId, out var slot) &&
slot.RemovePart();
}
RemovePart(slotName);
public bool RemovePart(IBodyPart part, [NotNullWhen(true)] out BodyPartSlot? slotId)
{
DebugTools.AssertNotNull(part);
if (!SlotParts.TryGetValue(part, out var slot))
{
slotId = null;
return false;
}
// TODO BODY invert this behavior with the one above
public bool RemovePart(string slot)
if (!slot.RemovePart())
{
slotId = null;
return false;
}
slotId = slot;
return true;
}
public bool TryDropPart(BodyPartSlot slot, [NotNullWhen(true)] out Dictionary<BodyPartSlot, IBodyPart>? dropped)
{
DebugTools.AssertNotNull(slot);
if (!_parts.Remove(slot, out var part))
{
return false;
}
OnRemovePart(slot, part);
if (TryGetSlotConnections(slot, out var connections))
{
foreach (var connectionName in connections)
{
if (TryGetPart(connectionName, out var result) && !ConnectedToCenter(result))
{
RemovePart(connectionName);
}
}
}
return true;
}
public bool RemovePart(IBodyPart part, [NotNullWhen(true)] out string? slotName)
{
DebugTools.AssertNotNull(part);
(slotName, _) = _parts.FirstOrDefault(kvPair => kvPair.Value == part);
if (slotName == null)
{
return false;
}
if (RemovePart(slotName))
{
return true;
}
slotName = null;
return false;
}
public bool TryDropPart(IBodyPart part, [NotNullWhen(true)] out List<IBodyPart>? dropped)
{
DebugTools.AssertNotNull(part);
if (!_parts.ContainsValue(part))
if (!SlotIds.TryGetValue(slot.Id, out var ownedSlot) ||
ownedSlot != slot ||
slot.Part == null)
{
dropped = null;
return false;
}
if (!RemovePart(part, out var slotName))
var oldPart = slot.Part;
dropped = GetHangingParts(slot);
if (!slot.RemovePart())
{
dropped = null;
return false;
}
dropped = new List<IBodyPart> {part};
// Call disconnect on all limbs that were hanging off this limb.
if (TryGetSlotConnections(slotName, out var connections))
{
// TODO BODY optimize
foreach (var connectionName in connections)
{
if (TryGetPart(connectionName, out var result) &&
!ConnectedToCenter(result) &&
RemovePart(connectionName))
{
dropped.Add(result);
}
}
}
OnBodyChanged();
dropped[slot] = oldPart;
return true;
}
public bool ConnectedToCenter(IBodyPart part)
{
var searchedSlots = new List<string>();
return TryGetSlot(part, out var result) &&
ConnectedToCenterPartRecursion(searchedSlots, result);
ConnectedToCenterPartRecursion(result);
}
private bool ConnectedToCenterPartRecursion(ICollection<string> searchedSlots, string slotName)
private bool ConnectedToCenterPartRecursion(BodyPartSlot slot, HashSet<BodyPartSlot>? searched = null)
{
if (!TryGetPart(slotName, out var part))
searched ??= new HashSet<BodyPartSlot>();
if (Template?.CenterSlot == null)
{
return false;
}
if (part == CenterPart())
if (slot.Part == CenterPart)
{
return true;
}
searchedSlots.Add(slotName);
searched.Add(slot);
if (!TryGetSlotConnections(slotName, out var connections))
foreach (var connection in slot.Connections)
{
return false;
}
foreach (var connection in connections)
{
if (!searchedSlots.Contains(connection) &&
ConnectedToCenterPartRecursion(searchedSlots, connection))
if (!searched.Contains(connection) &&
ConnectedToCenterPartRecursion(connection, searched))
{
return true;
}
@@ -351,56 +337,64 @@ namespace Content.Shared.GameObjects.Components.Body
return false;
}
public IBodyPart? CenterPart()
{
if (_centerSlot == null) return null;
return Parts.GetValueOrDefault(_centerSlot);
}
public bool HasSlot(string slot)
{
return Slots.ContainsKey(slot);
return SlotIds.ContainsKey(slot);
}
public bool TryGetPart(string slot, [NotNullWhen(true)] out IBodyPart? result)
public IEnumerable<IBodyPart> GetParts()
{
return Parts.TryGetValue(slot, out result);
foreach (var slot in SlotIds.Values)
{
if (slot.Part != null)
{
yield return slot.Part;
}
}
}
public bool TryGetSlot(IBodyPart part, [NotNullWhen(true)] out string? slot)
public bool TryGetPart(string slotId, [NotNullWhen(true)] out IBodyPart? result)
{
// We enforce that there is only one of each value in the dictionary,
// so we can iterate through the dictionary values to get the key from there.
(slot, _) = Parts.FirstOrDefault(x => x.Value == part);
result = null;
return slot != null;
return SlotIds.TryGetValue(slotId, out var slot) &&
(result = slot.Part) != null;
}
public bool TryGetSlotType(string slot, out BodyPartType result)
public BodyPartSlot? GetSlot(string id)
{
return Slots.TryGetValue(slot, out result);
return SlotIds.GetValueOrDefault(id);
}
public bool TryGetSlotConnections(string slot, [NotNullWhen(true)] out List<string>? connections)
public BodyPartSlot? GetSlot(IBodyPart part)
{
return Connections.TryGetValue(slot, out connections);
return SlotParts.GetValueOrDefault(part);
}
public bool TryGetPartConnections(string slot, [NotNullWhen(true)] out List<IBodyPart>? connections)
public bool TryGetSlot(string slotId, [NotNullWhen(true)] out BodyPartSlot? slot)
{
if (!Connections.TryGetValue(slot, out var slotConnections))
return (slot = GetSlot(slotId)) != null;
}
public bool TryGetSlot(IBodyPart part, [NotNullWhen(true)] out BodyPartSlot? slot)
{
return (slot = GetSlot(part)) != null;
}
public bool TryGetPartConnections(string slotId, [NotNullWhen(true)] out List<IBodyPart>? connections)
{
if (!SlotIds.TryGetValue(slotId, out var slot))
{
connections = null;
return false;
}
connections = new List<IBodyPart>();
foreach (var connection in slotConnections)
foreach (var connection in slot.Connections)
{
if (TryGetPart(connection, out var part))
if (connection.Part != null)
{
connections.Add(part);
connections.Add(connection.Part);
}
}
@@ -413,57 +407,68 @@ namespace Content.Shared.GameObjects.Components.Body
return true;
}
public bool TryGetPartConnections(IBodyPart part, [NotNullWhen(true)] out List<IBodyPart>? connections)
public bool HasSlotOfType(BodyPartType type)
{
connections = null;
return TryGetSlot(part, out var slotName) &&
TryGetPartConnections(slotName, out connections);
foreach (var _ in GetSlotsOfType(type))
{
return true;
}
public List<IBodyPart> GetPartsOfType(BodyPartType type)
{
var parts = new List<IBodyPart>();
return false;
}
foreach (var part in Parts.Values)
public IEnumerable<BodyPartSlot> GetSlotsOfType(BodyPartType type)
{
if (part.PartType == type)
foreach (var slot in SlotIds.Values)
{
parts.Add(part);
if (slot.PartType == type)
{
yield return slot;
}
}
}
return parts;
public bool HasPartOfType(BodyPartType type)
{
foreach (var _ in GetPartsOfType(type))
{
return true;
}
public List<(IBodyPart part, IBodyPartProperty property)> GetPartsWithProperty(Type type)
{
var parts = new List<(IBodyPart, IBodyPartProperty)>();
return false;
}
foreach (var part in Parts.Values)
public IEnumerable<IBodyPart> GetPartsOfType(BodyPartType type)
{
if (part.TryGetProperty(type, out var property))
foreach (var slot in GetSlotsOfType(type))
{
parts.Add((part, property));
if (slot.Part != null)
{
yield return slot.Part;
}
}
}
return parts;
public IEnumerable<(IBodyPart part, IBodyPartProperty property)> GetPartsWithProperty(Type type)
{
foreach (var slot in SlotIds.Values)
{
if (slot.Part != null && slot.Part.TryGetProperty(type, out var property))
{
yield return (slot.Part, property);
}
}
}
public List<(IBodyPart part, T property)> GetPartsWithProperty<T>() where T : class, IBodyPartProperty
public IEnumerable<(IBodyPart part, T property)> GetPartsWithProperty<T>() where T : class, IBodyPartProperty
{
var parts = new List<(IBodyPart, T)>();
foreach (var part in Parts.Values)
foreach (var part in SlotParts.Keys)
{
if (part.TryGetProperty<T>(out var property))
{
parts.Add((part, property));
yield return (part, property);
}
}
return parts;
}
private void CalculateSpeed()
@@ -473,7 +478,7 @@ namespace Content.Shared.GameObjects.Components.Body
return;
}
var legs = GetPartsWithProperty<LegComponent>();
var legs = GetPartsWithProperty<LegComponent>().ToArray();
float speedSum = 0;
foreach (var leg in legs)
@@ -497,7 +502,7 @@ namespace Content.Shared.GameObjects.Components.Body
{
// Extra legs stack diminishingly.
playerMover.BaseWalkSpeed =
speedSum / (legs.Count - (float) Math.Log(legs.Count, 4.0));
speedSum / (legs.Length - (float) Math.Log(legs.Length, 4.0));
playerMover.BaseSprintSpeed = playerMover.BaseWalkSpeed * 1.75f;
}
@@ -537,27 +542,29 @@ namespace Content.Shared.GameObjects.Components.Body
return extension.Distance;
}
return LookForFootRecursion(source, new List<IBodyPart>());
return LookForFootRecursion(source);
}
private float LookForFootRecursion(IBodyPart current, ICollection<IBodyPart> searchedParts)
private float LookForFootRecursion(IBodyPart current, HashSet<BodyPartSlot>? searched = null)
{
searched ??= new HashSet<BodyPartSlot>();
if (!current.TryGetProperty<ExtensionComponent>(out var extProperty))
{
return float.MinValue;
}
// Get all connected parts if the current part has an extension property
if (!TryGetPartConnections(current, out var connections))
if (!TryGetSlot(current, out var slot))
{
return float.MinValue;
}
// If a connected BodyPart is a foot, return this BodyPart's length.
foreach (var connection in connections)
foreach (var connection in slot.Connections)
{
if (connection.PartType == BodyPartType.Foot &&
!searchedParts.Contains(connection))
!searched.Contains(connection))
{
return extProperty.Distance;
}
@@ -566,14 +573,14 @@ namespace Content.Shared.GameObjects.Components.Body
// Otherwise, get the recursion values of all connected BodyParts and
// store them in a list.
var distances = new List<float>();
foreach (var connection in connections)
foreach (var connection in slot.Connections)
{
if (!searchedParts.Contains(connection))
if (connection.Part == null || !searched.Contains(connection))
{
continue;
}
var result = LookForFootRecursion(connection, searchedParts);
var result = LookForFootRecursion(connection.Part, searched);
if (Math.Abs(result - float.MinValue) > 0.001f)
{
@@ -592,24 +599,24 @@ namespace Content.Shared.GameObjects.Components.Body
}
// TODO BODY optimize this
public KeyValuePair<string, BodyPartType> SlotAt(int index)
public BodyPartSlot SlotAt(int index)
{
return Slots.ElementAt(index);
return SlotIds.Values.ElementAt(index);
}
public KeyValuePair<string, IBodyPart> PartAt(int index)
public KeyValuePair<IBodyPart, BodyPartSlot> PartAt(int index)
{
return Parts.ElementAt(index);
return SlotParts.ElementAt(index);
}
public override ComponentState GetComponentState(ICommonSession player)
{
var parts = new (string slot, EntityUid partId)[_parts.Count];
var parts = new (string slot, EntityUid partId)[SlotParts.Count];
var i = 0;
foreach (var (slot, part) in _parts)
foreach (var (part, slot) in SlotParts)
{
parts[i] = (slot, part.Owner.Uid);
parts[i] = (slot.Id, part.Owner.Uid);
i++;
}
@@ -627,28 +634,28 @@ namespace Content.Shared.GameObjects.Components.Body
var newParts = state.Parts();
foreach (var (slot, oldPart) in _parts)
foreach (var (oldPart, slot) in SlotParts)
{
if (!newParts.TryGetValue(slot, out var newPart) ||
if (!newParts.TryGetValue(slot.Id, out var newPart) ||
newPart != oldPart)
{
RemovePart(oldPart);
}
}
foreach (var (slot, newPart) in newParts)
foreach (var (slotId, newPart) in newParts)
{
if (!_parts.TryGetValue(slot, out var oldPart) ||
oldPart != newPart)
if (!SlotIds.TryGetValue(slotId, out var slot) ||
slot.Part != newPart)
{
TryAddPart(slot, newPart, true);
SetPart(slotId, newPart);
}
}
}
public virtual void Gib(bool gibParts = false)
{
foreach (var (_, part) in Parts)
foreach (var part in SlotParts.Keys)
{
RemovePart(part);

View File

@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using Content.Shared.GameObjects.Components.Body.Part;
using Robust.Shared.ViewVariables;
namespace Content.Shared.GameObjects.Components.Body.Slot
{
public class BodyPartSlot
{
public BodyPartSlot(string id, BodyPartType partType, IEnumerable<BodyPartSlot> connections)
{
Id = id;
PartType = partType;
Connections = new HashSet<BodyPartSlot>(connections);
}
public BodyPartSlot(string id, BodyPartType partType)
{
Id = id;
PartType = partType;
Connections = new HashSet<BodyPartSlot>();
}
/// <summary>
/// The ID of this slot.
/// </summary>
[ViewVariables]
public string Id { get; }
/// <summary>
/// The part type that this slot accepts.
/// </summary>
[ViewVariables]
public BodyPartType PartType { get; }
/// <summary>
/// The part currently in this slot, if any.
/// </summary>
[ViewVariables]
public IBodyPart? Part { get; private set; }
/// <summary>
/// List of slots that this slot connects to.
/// </summary>
[ViewVariables]
public HashSet<BodyPartSlot> Connections { get; private set; }
public event Action<IBodyPart>? PartAdded;
public event Action<IBodyPart>? PartRemoved;
internal void SetConnectionsInternal(IEnumerable<BodyPartSlot> connections)
{
Connections = new HashSet<BodyPartSlot>(connections);
}
public bool CanAddPart(IBodyPart part)
{
return Part == null && part.PartType == PartType;
}
public bool TryAddPart(IBodyPart part)
{
if (!CanAddPart(part))
{
return false;
}
SetPart(part);
return true;
}
public void SetPart(IBodyPart part)
{
if (Part != null)
{
RemovePart();
}
Part = part;
PartAdded?.Invoke(part);
}
public bool RemovePart()
{
if (Part == null)
{
return false;
}
var old = Part;
Part = null;
PartRemoved?.Invoke(old);
return true;
}
public void Shutdown()
{
Part = null;
Connections.Clear();
PartAdded = null;
PartRemoved = null;
}
}
}

View File

@@ -16,16 +16,16 @@ namespace Content.Shared.GameObjects.Components.Body.Template
[Serializable, NetSerializable]
public class BodyTemplatePrototype : IPrototype, ISerializationHooks
{
[DataField("slots")]
[field: DataField("slots")]
private Dictionary<string, BodyPartType> _slots = new();
[DataField("connections")]
[field: DataField("connections")]
private Dictionary<string, List<string>> _rawConnections = new();
[DataField("layers")]
[field: DataField("layers")]
private Dictionary<string, string> _layers = new();
[DataField("mechanismLayers")]
[field: DataField("mechanismLayers")]
private Dictionary<string, string> _mechanismLayers = new();
[ViewVariables]
@@ -44,7 +44,7 @@ namespace Content.Shared.GameObjects.Components.Body.Template
public Dictionary<string, BodyPartType> Slots => new(_slots);
[ViewVariables]
public Dictionary<string, List<string>> Connections { get; set; } = new();
public Dictionary<string, HashSet<string>> Connections { get; set; } = new();
[ViewVariables]
public Dictionary<string, string> Layers => new(_layers);
@@ -56,11 +56,11 @@ namespace Content.Shared.GameObjects.Components.Body.Template
{
//Our prototypes don't force the user to define a BodyPart connection twice. E.g. Head: Torso v.s. Torso: Head.
//The user only has to do one. We want it to be that way in the code, though, so this cleans that up.
var cleanedConnections = new Dictionary<string, List<string>>();
var cleanedConnections = new Dictionary<string, HashSet<string>>();
foreach (var targetSlotName in _slots.Keys)
{
var tempConnections = new List<string>();
var tempConnections = new HashSet<string>();
foreach (var (slotName, slotConnections) in _rawConnections)
{
if (slotName == targetSlotName)

View File

@@ -163,7 +163,6 @@
- type: Body
template: HumanoidTemplate
preset: HumanPreset
centerSlot: torso
- type: Damageable
damageContainer: biologicalDamageContainer
- type: Metabolism
@@ -336,7 +335,6 @@
- type: Body
template: HumanoidTemplate
preset: HumanPreset
centerSlot: torso
- type: Damageable
damageContainer: biologicalDamageContainer
- type: MobState

View File

@@ -141,7 +141,6 @@
- type: Body
template: HumanoidTemplate
preset: SlimePreset
centerSlot: torso
- type: Damageable
damageContainer: biologicalDamageContainer
- type: Metabolism

View File

@@ -82,7 +82,6 @@
- type: Body
template: HumanoidTemplate
preset: VoxPreset
centerSlot: torso
- type: Metabolism
needsGases:
Nitrogen: 0.00060763888

View File

@@ -0,0 +1,10 @@
- type: entityList
id: CowTools
entities:
- Haycutters
- Moodriver
- Wronch
- Cowbar
- Mooltitool
- Cowelder
- Milkalyzer