De-hardcode chemical metabolism of StomachComponent (#437)

* Move chemical reaction effects into Chemistry/ReactionEffects/ subfolder

* Replace hardcoded StomachComponent metabolism with IMetabolizable

The benefits of this approach are that reagent metabolism effects are not hardcoded into StomachComponent, and metabolism effects can be more easily chained together in yaml prototypes, and reagents can have different metabolism rates. One problem with this approach is that getting metabolism rates slower than 1u / second is impossible. Implementing #377 should resolve that problem.

* Fix DefaultFood and DefaultDrink so they remove reagent regardless of Hunger/ThirstComponent presence

Previously if neither of those were present the reagents wouldn't be removed from the stomach. This fixes that.

* Additional comment on function

* Make metabolizer interface implementations explicit

Also removed some unused using statements

* Make StomachComponent._reagentDeltas readonly

* Fix misleading variable names and docs for metabolizables

Changes one of the arguments for `IMetabolizable.Metabolize()` to be called `tickTime` instead of `frameTime` to more accurately reflect it's purpose. It's not really the frametime, but the time since the last metabolism tick. Also updated and expanded the docs to reflect this and to be more clear.
This commit is contained in:
moneyl
2019-11-21 17:24:19 -05:00
committed by Pieter-Jan Briers
parent 1f177a044d
commit 3ab8036363
11 changed files with 213 additions and 85 deletions

View File

@@ -0,0 +1,41 @@
using System;
using Content.Server.GameObjects.Components.Nutrition;
using Content.Shared.Interfaces.Chemistry;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Serialization;
namespace Content.Server.Chemistry.Metabolism
{
/// <summary>
/// Default metabolism for drink reagents. Attempts to find a ThirstComponent on the target,
/// and to update it's thirst values.
/// </summary>
class DefaultDrink : IMetabolizable
{
//Rate of metabolism in units / second
private int _metabolismRate;
public int MetabolismRate => _metabolismRate;
//How much thirst is satiated when 1u of the reagent is metabolized
private float _hydrationFactor;
public float HydrationFactor => _hydrationFactor;
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _metabolismRate, "rate", 1);
serializer.DataField(ref _hydrationFactor, "nutrimentFactor", 30.0f);
}
//Remove reagent at set rate, satiate thirst if a ThirstComponent can be found
int IMetabolizable.Metabolize(IEntity solutionEntity, string reagentId, float tickTime)
{
int metabolismAmount = (int)Math.Round(MetabolismRate * tickTime);
if (solutionEntity.TryGetComponent(out ThirstComponent thirst))
thirst.UpdateThirst(metabolismAmount * HydrationFactor);
//Return amount of reagent to be removed, remove reagent regardless of ThirstComponent presence
return metabolismAmount;
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
using Content.Server.GameObjects.Components.Nutrition;
using Content.Shared.Interfaces.Chemistry;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Serialization;
namespace Content.Server.Chemistry.Metabolism
{
/// <summary>
/// Default metabolism for food reagents. Attempts to find a HungerComponent on the target,
/// and to update it's hunger values.
/// </summary>
class DefaultFood : IMetabolizable
{
//Rate of metabolism in units / second
private int _metabolismRate;
public int MetabolismRate => _metabolismRate;
//How much hunger is satiated when 1u of the reagent is metabolized
private float _nutritionFactor;
public float NutritionFactor => _nutritionFactor;
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _metabolismRate, "rate", 1);
serializer.DataField(ref _nutritionFactor, "nutrimentFactor", 30.0f);
}
//Remove reagent at set rate, satiate hunger if a HungerComponent can be found
int IMetabolizable.Metabolize(IEntity solutionEntity, string reagentId, float tickTime)
{
int metabolismAmount = (int)Math.Round(MetabolismRate * tickTime);
if (solutionEntity.TryGetComponent(out HungerComponent hunger))
hunger.UpdateFood(metabolismAmount * NutritionFactor);
//Return amount of reagent to be removed, remove reagent regardless of HungerComponent presence
return metabolismAmount;
}
}
}

View File

@@ -5,7 +5,7 @@ using Content.Shared.Interfaces;
using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Serialization; using Robust.Shared.Serialization;
namespace Content.Server.Chemistry namespace Content.Server.Chemistry.ReactionEffects
{ {
class ExplosionReactionEffect : IReactionEffect class ExplosionReactionEffect : IReactionEffect
{ {

View File

@@ -1,4 +1,4 @@
using System; using System;
using Content.Server.GameObjects.Components.Chemistry; using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.Components.Sound; using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems; using Content.Server.GameObjects.EntitySystems;
@@ -44,9 +44,7 @@ namespace Content.Server.GameObjects.Components.Nutrition
serializer.DataField(ref _initialContents, "contents", null); serializer.DataField(ref _initialContents, "contents", null);
serializer.DataField(ref _useSound, "use_sound", "/Audio/items/eatfood.ogg"); serializer.DataField(ref _useSound, "use_sound", "/Audio/items/eatfood.ogg");
// Default is transfer 30 units // Default is transfer 30 units
serializer.DataField(ref _transferAmount, serializer.DataField(ref _transferAmount, "transfer_amount", 5);
"transfer_amount",
30 / StomachComponent.NutrimentFactor);
// E.g. empty chip packet when done // E.g. empty chip packet when done
serializer.DataField(ref _finishPrototype, "spawn_on_finish", null); serializer.DataField(ref _finishPrototype, "spawn_on_finish", null);
} }
@@ -81,8 +79,7 @@ namespace Content.Server.GameObjects.Components.Nutrition
_initialContents = null; _initialContents = null;
if (_contents.CurrentVolume == 0) if (_contents.CurrentVolume == 0)
{ {
_contents.TryAddReagent("chem.Nutriment", 30 / StomachComponent.NutrimentFactor, _contents.TryAddReagent("chem.Nutriment", 5, out _);
out _);
} }
Owner.TryGetComponent(out AppearanceComponent appearance); Owner.TryGetComponent(out AppearanceComponent appearance);
_appearanceComponent = appearance; _appearanceComponent = appearance;

View File

@@ -1,7 +1,11 @@
using System.Collections.Generic;
using Content.Server.GameObjects.Components.Chemistry; using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.Chemistry; using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Nutrition; using Content.Shared.GameObjects.Components.Nutrition;
using Robust.Shared.GameObjects; using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization; using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables; using Robust.Shared.ViewVariables;
@@ -10,43 +14,35 @@ namespace Content.Server.GameObjects.Components.Nutrition
[RegisterComponent] [RegisterComponent]
public class StomachComponent : SharedStomachComponent public class StomachComponent : SharedStomachComponent
{ {
// Essentially every time it ticks it'll pull out the MetabolisationAmount of reagents and process them. #pragma warning disable 649
// Generic food goes under "nutriment" like SS13 [Dependency] private readonly IPrototypeManager _prototypeManager;
// There's also separate hunger and thirst components which means you can have a stomach #pragma warning restore 649
// but not require food / water.
public static readonly int NutrimentFactor = 30;
public static readonly int HydrationFactor = 30;
public static readonly int MetabolisationAmount = 5;
[ViewVariables(VVAccess.ReadOnly)]
private SolutionComponent _stomachContents; private SolutionComponent _stomachContents;
public float MetaboliseDelay => _metaboliseDelay;
[ViewVariables]
private float _metaboliseDelay; // How long between metabolisation for 5 units
public int MaxVolume public int MaxVolume
{ {
get => _stomachContents.MaxVolume; get => _stomachContents.MaxVolume;
set => _stomachContents.MaxVolume = value; set => _stomachContents.MaxVolume = value;
} }
private float _metabolisationCounter = 0.0f;
private int _initialMaxVolume; private int _initialMaxVolume;
//Used to track changes to reagent amounts during metabolism
private readonly Dictionary<string, int> _reagentDeltas = new Dictionary<string, int>();
public override void ExposeData(ObjectSerializer serializer) public override void ExposeData(ObjectSerializer serializer)
{ {
base.ExposeData(serializer); base.ExposeData(serializer);
serializer.DataField(ref _metaboliseDelay, "metabolise_delay", 6.0f);
serializer.DataField(ref _initialMaxVolume, "max_volume", 20); serializer.DataField(ref _initialMaxVolume, "max_volume", 20);
} }
public override void Initialize() public override void Initialize()
{ {
base.Initialize(); base.Initialize();
// Shouldn't add to Owner to avoid cross-contamination (e.g. with blood or whatever they made hold other solutions) //Doesn't use Owner.AddComponent<>() to avoid cross-contamination (e.g. with blood or whatever they holds other solutions)
_stomachContents = new SolutionComponent(); _stomachContents = new SolutionComponent();
_stomachContents.InitializeFromPrototype(); _stomachContents.InitializeFromPrototype();
_stomachContents.MaxVolume = _initialMaxVolume; _stomachContents.MaxVolume = _initialMaxVolume;
_stomachContents.Owner = Owner; //Manually set owner to avoid crash when VV'ing this
} }
public bool TryTransferSolution(Solution solution) public bool TryTransferSolution(Solution solution)
@@ -61,69 +57,42 @@ namespace Content.Server.GameObjects.Components.Nutrition
} }
/// <summary> /// <summary>
/// This is where the magic happens. Make people throw up, increase nutrition, whatever /// Loops through each reagent in _stomachContents, and calls the IMetabolizable for each of them./>
/// </summary> /// </summary>
/// <param name="solution"></param> /// <param name="tickTime">The time since the last metabolism tick in seconds.</param>
public void React(Solution solution) public void Metabolize(float tickTime)
{
// TODO: Implement metabolism post from here
// https://github.com/space-wizards/space-station-14/issues/170#issuecomment-481835623 as raised by moneyl
var hungerUpdate = 0;
var thirstUpdate = 0;
foreach (var reagent in solution.Contents)
{
switch (reagent.ReagentId)
{
case "chem.Nutriment":
hungerUpdate++;
break;
case "chem.H2O":
thirstUpdate++;
break;
case "chem.Alcohol":
thirstUpdate++;
break;
default:
continue;
}
}
// Quantity x restore amount per unit
if (hungerUpdate > 0 && Owner.TryGetComponent(out HungerComponent hungerComponent))
{
hungerComponent.UpdateFood(hungerUpdate * NutrimentFactor);
}
if (thirstUpdate > 0 && Owner.TryGetComponent(out ThirstComponent thirstComponent))
{
thirstComponent.UpdateThirst(thirstUpdate * HydrationFactor);
}
// TODO: Dispose solution?
}
public void Metabolise()
{ {
if (_stomachContents.CurrentVolume == 0) if (_stomachContents.CurrentVolume == 0)
{
return; return;
}
var metabolisation = _stomachContents.SplitSolution(MetabolisationAmount); //Run metabolism for each reagent, track quantity changes
_reagentDeltas.Clear();
React(metabolisation); foreach (var reagent in _stomachContents.ReagentList)
}
public void OnUpdate(float frameTime)
{ {
_metabolisationCounter += frameTime; if(!_prototypeManager.TryIndex(reagent.ReagentId, out ReagentPrototype proto))
if (_metabolisationCounter >= MetaboliseDelay) continue;
foreach (var metabolizable in proto.Metabolism)
{ {
// Going to be rounding issues with frametime but no easy way to avoid it with int reagents. _reagentDeltas[reagent.ReagentId] = metabolizable.Metabolize(Owner, reagent.ReagentId, tickTime);
// It is a long-term mechanic so shouldn't be a big deal. }
Metabolise(); }
_metabolisationCounter -= MetaboliseDelay;
} //Apply changes to quantity afterwards. Can't change the reagent quantities while the iterating the
//list of reagents, because that would invalidate the iterator and throw an exception.
foreach (var reagentDelta in _reagentDeltas)
{
_stomachContents.TryRemoveReagent(reagentDelta.Key, reagentDelta.Value);
}
}
/// <summary>
/// Triggers metabolism of the reagents inside _stomachContents. Called by <see cref="StomachSystem"/>
/// </summary>
/// <param name="tickTime">The time since the last metabolism tick in seconds.</param>
public void OnUpdate(float tickTime)
{
Metabolize(tickTime);
} }
} }
} }

View File

@@ -0,0 +1,27 @@
using System;
using Content.Shared.Interfaces.Chemistry;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Serialization;
namespace Content.Shared.Chemistry
{
//Default metabolism for reagents. Metabolizes the reagent with no effects
class DefaultMetabolizable : IMetabolizable
{
//Rate of metabolism in units / second
private int _metabolismRate = 1;
public int MetabolismRate => _metabolismRate;
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _metabolismRate, "rate", 1);
}
int IMetabolizable.Metabolize(IEntity solutionEntity, string reagentId, float tickTime)
{
int metabolismAmount = (int)Math.Round(MetabolismRate * tickTime);
return metabolismAmount;
}
}
}

View File

@@ -1,5 +1,9 @@
using Robust.Shared.Maths; using System;
using System.Collections.Generic;
using Content.Shared.Interfaces.Chemistry;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes; using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Utility; using Robust.Shared.Utility;
using YamlDotNet.RepresentationModel; using YamlDotNet.RepresentationModel;
@@ -8,18 +12,28 @@ namespace Content.Shared.Chemistry
[Prototype("reagent")] [Prototype("reagent")]
public class ReagentPrototype : IPrototype, IIndexedPrototype public class ReagentPrototype : IPrototype, IIndexedPrototype
{ {
public string ID { get; private set; } private string _id;
public string Name { get; private set; } private string _name;
public string Description { get; private set; } private string _description;
public Color SubstanceColor { get; private set; } private Color _substanceColor;
private List<IMetabolizable> _metabolism;
public string ID => _id;
public string Name => _name;
public string Description => _description;
public Color SubstanceColor => _substanceColor;
//List of metabolism effects this reagent has, should really only be used server-side.
public List<IMetabolizable> Metabolism => _metabolism;
public void LoadFrom(YamlMappingNode mapping) public void LoadFrom(YamlMappingNode mapping)
{ {
ID = mapping.GetNode("id").AsString(); var serializer = YamlObjectSerializer.NewReader(mapping);
Name = mapping.GetNode("name").ToString();
Description = mapping.GetNode("desc").ToString();
SubstanceColor = mapping.TryGetNode("color", out var colorNode) ? colorNode.AsHexColor(Color.White) : Color.White; serializer.DataField(ref _id, "id", string.Empty);
serializer.DataField(ref _name, "name", string.Empty);
serializer.DataField(ref _description, "desc", string.Empty);
serializer.DataField(ref _substanceColor, "color", Color.White);
serializer.DataField(ref _metabolism, "metabolism", new List<IMetabolizable>{new DefaultMetabolizable()});
} }
} }
} }

View File

@@ -0,0 +1,24 @@
using System.Collections.Generic;
using Content.Shared.Chemistry;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Serialization;
namespace Content.Shared.Interfaces.Chemistry
{
/// <summary>
/// Metabolism behavior for a reagent.
/// </summary>
public interface IMetabolizable : IExposeData
{
/// <summary>
/// Metabolize the attached reagent. Return the amount of reagent to be removed from the solution.
/// You shouldn't remove the reagent yourself to avoid invalidating the iterator of the metabolism
/// organ that is processing it's reagents.
/// </summary>
/// <param name="solutionEntity">The entity containing the solution.</param>
/// <param name="reagentId">The reagent id</param>
/// <param name="tickTime">The time since the last metabolism tick in seconds.</param>
/// <returns>The amount of reagent to be removed. The metabolizing organ should handle removing the reagent.</returns>
int Metabolize(IEntity solutionEntity, string reagentId, float tickTime);
}
}

View File

@@ -2,6 +2,9 @@
id: chem.Nutriment id: chem.Nutriment
name: Nutriment name: Nutriment
desc: Generic nutrition desc: Generic nutrition
metabolism:
- !type:DefaultFood
rate: 1
- type: reagent - type: reagent
id: chem.H2SO4 id: chem.H2SO4
@@ -12,6 +15,9 @@
id: chem.H2O id: chem.H2O
name: Water name: Water
desc: A tasty colorless liquid. desc: A tasty colorless liquid.
metabolism:
- !type:DefaultDrink
rate: 1
- type: reagent - type: reagent
id: chem.Ice id: chem.Ice

View File

@@ -17,13 +17,22 @@
id: chem.Cola id: chem.Cola
name: Cola name: Cola
desc: A sweet, carbonated soft drink. Caffeine free. desc: A sweet, carbonated soft drink. Caffeine free.
metabolism:
- !type:DefaultDrink
rate: 1
- type: reagent - type: reagent
id: chem.Coffee id: chem.Coffee
name: Coffee name: Coffee
desc: A drink made from brewed coffee beans. Contains a moderate amount of caffeine. desc: A drink made from brewed coffee beans. Contains a moderate amount of caffeine.
metabolism:
- !type:DefaultDrink
rate: 1
- type: reagent - type: reagent
id: chem.Tea id: chem.Tea
name: Tea name: Tea
desc: A made by boiling leaves of the tea tree, Camellia sinensis. desc: A made by boiling leaves of the tea tree, Camellia sinensis.
metabolism:
- !type:DefaultDrink
rate: 1