Add hunger and thirst (#363)

* Add hunger and thirst

Based on the SS13 systems.
Food (Nutriment) / Drink -> Stomach -> Hunger / Thirst

* Cleanup rebase

* Cleanup stuff that was prototyped

* Address feedback

Still need to add a statuseffects system in a separate branch

* More cleanup on nutrition

Fix Remie's feedback and also damage tick.

* Re-implement nutrition with master

* Updated to use the StatusEffectsUI update
* Removed all clientside components as they only receive the UI updates now
* Implemented PR feedback
* Had to make a slight adjustment to the chemistry SolutionComponent given it doesn't have an Owner, same with Solution

Still TODO:
* Metabolisation effects
* Change drink contents to alcohol / wine etc.
* Add items to the dispensers
* For transparent containers use RecalculateColor

Could probably genericise DrinkFoodContainer as well to be a temporary item dispenser

* Fix broken bottle parent
This commit is contained in:
metalgearsloth
2019-11-12 08:20:03 +11:00
committed by Pieter-Jan Briers
parent 6de5c01afb
commit de148fc98f
1026 changed files with 9617 additions and 8 deletions

View File

@@ -32,11 +32,21 @@ namespace Content.Server.GameObjects.Components.Chemistry
protected override void Startup()
{
base.Startup();
_reactions = _prototypeManager.EnumeratePrototypes<ReactionPrototype>();
_audioSystem = _entitySystemManager.GetEntitySystem<AudioSystem>();
}
/// <summary>
/// Initializes the SolutionComponent if it doesn't have an owner
/// </summary>
public void InitializeFromPrototype()
{
// Because Initialize needs an Owner, Startup isn't called, etc.
IoCManager.InjectDependencies(this);
_reactions = _prototypeManager.EnumeratePrototypes<ReactionPrototype>();
}
/// <summary>
/// Transfers solution from the held container to the target container.
/// </summary>
@@ -193,7 +203,7 @@ namespace Content.Server.GameObjects.Components.Chemistry
}
}
public bool TryAddReagent(string reagentId, int quantity, out int acceptedQuantity, bool skipReactionCheck = false)
public bool TryAddReagent(string reagentId, int quantity, out int acceptedQuantity, bool skipReactionCheck = false, bool skipColor = false)
{
if (quantity > _maxVolume - _containedSolution.TotalVolume)
{
@@ -206,20 +216,24 @@ namespace Content.Server.GameObjects.Components.Chemistry
}
_containedSolution.AddReagent(reagentId, acceptedQuantity);
RecalculateColor();
if (!skipColor) {
RecalculateColor();
}
if(!skipReactionCheck)
CheckForReaction();
OnSolutionChanged();
return true;
}
public bool TryAddSolution(Solution solution, bool skipReactionCheck = false)
public bool TryAddSolution(Solution solution, bool skipReactionCheck = false, bool skipColor = false)
{
if (solution.TotalVolume > (_maxVolume - _containedSolution.TotalVolume))
return false;
_containedSolution.AddSolution(solution);
RecalculateColor();
if (!skipColor) {
RecalculateColor();
}
if(!skipReactionCheck)
CheckForReaction();
OnSolutionChanged();

View File

@@ -0,0 +1,184 @@
using System;
using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Nutrition;
using Content.Shared.Interfaces;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public class DrinkComponent : Component, IAfterAttack, IUse
{
#pragma warning disable 649
[Dependency] private readonly ILocalizationManager _localizationManager;
#pragma warning restore 649
public override string Name => "Drink";
[ViewVariables]
private SolutionComponent _contents;
private AppearanceComponent _appearanceComponent;
[ViewVariables]
private string _useSound;
[ViewVariables]
private string _finishPrototype;
public int TransferAmount => _transferAmount;
[ViewVariables]
private int _transferAmount = 2;
public int MaxVolume
{
get => _contents.MaxVolume;
set => _contents.MaxVolume = value;
}
private Solution _initialContents; // This is just for loading from yaml
private bool _despawnOnFinish;
public int UsesLeft()
{
// In case transfer amount exceeds volume left
if (_contents.CurrentVolume == 0)
{
return 0;
}
return Math.Max(1, _contents.CurrentVolume / _transferAmount);
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _initialContents, "contents", null);
serializer.DataField(ref _useSound, "use_sound", "/Audio/items/drink.ogg");
// E.g. cola can when done or clear bottle, whatever
// Currently this will enforce it has the same volume but this may change.
serializer.DataField(ref _despawnOnFinish, "despawn_empty", true);
serializer.DataField(ref _finishPrototype, "spawn_on_finish", null);
}
public override void Initialize()
{
base.Initialize();
if (_contents == null)
{
if (Owner.TryGetComponent(out SolutionComponent solutionComponent))
{
_contents = solutionComponent;
}
else
{
_contents = Owner.AddComponent<SolutionComponent>();
_contents.Initialize();
}
}
_contents.MaxVolume = _initialContents.TotalVolume;
}
protected override void Startup()
{
base.Startup();
if (_initialContents != null)
{
_contents.TryAddSolution(_initialContents, true, true);
}
_initialContents = null;
Owner.TryGetComponent(out AppearanceComponent appearance);
_appearanceComponent = appearance;
_appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.MaxUses, MaxVolume);
_updateAppearance();
}
private void _updateAppearance()
{
_appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.Visual, UsesLeft());
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
UseDrink(eventArgs.User);
return true;
}
void IAfterAttack.AfterAttack(AfterAttackEventArgs eventArgs)
{
UseDrink(eventArgs.Attacked);
}
void UseDrink(IEntity user)
{
if (user == null)
{
return;
}
if (UsesLeft() == 0 && !_despawnOnFinish)
{
user.PopupMessage(user, _localizationManager.GetString("Empty"));
return;
}
if (user.TryGetComponent(out StomachComponent stomachComponent))
{
var transferAmount = Math.Min(_transferAmount, _contents.CurrentVolume);
var split = _contents.SplitSolution(transferAmount);
if (stomachComponent.TryTransferSolution(split))
{
if (_useSound != null)
{
Owner.GetComponent<SoundComponent>()?.Play(_useSound);
user.PopupMessage(user, _localizationManager.GetString("Slurp"));
}
}
else
{
// Add it back in
_contents.TryAddSolution(split);
user.PopupMessage(user, _localizationManager.GetString("Can't drink"));
}
}
// Drink containers are mostly transient.
if (!_despawnOnFinish || UsesLeft() > 0)
{
return;
}
Owner.Delete();
if (_finishPrototype != null)
{
var finisher = Owner.EntityManager.SpawnEntity(_finishPrototype);
if (user.TryGetComponent(out HandsComponent handsComponent) && finisher.TryGetComponent(out ItemComponent itemComponent))
{
if (handsComponent.CanPutInHand(itemComponent))
{
handsComponent.PutInHand(itemComponent);
return;
}
}
finisher.Transform.GridPosition = user.Transform.GridPosition;
if (finisher.TryGetComponent(out DrinkComponent drinkComponent))
{
drinkComponent.MaxVolume = MaxVolume;
}
return;
}
}
}
}

View File

@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.GameObjects.Components.Nutrition;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.Components.Container;
using Robust.Server.Interfaces.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public sealed class DrinkFoodContainerComponent : SharedDrinkFoodContainerComponent, IMapInit, IUse
{
public override string Name => "DrinkFoodContainer";
private string _useSound;
private Container _foodContainer;
// Optimisation scabbed from BallisticMagazineComponent to avoid loading entities until needed
[ViewVariables] private readonly Stack<IEntity> _loadedFood = new Stack<IEntity>();
private AppearanceComponent _appearanceComponent;
[ViewVariables] public int Count => _availableSpawnCount + _loadedFood.Count;
private int _availableSpawnCount;
private Dictionary<string, int> _prototypes;
private string _finishPrototype;
public int Capacity => _capacity;
private int _capacity;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _useSound, "use_sound", null);
// Is a dictionary for stuff with probabilities (mainly donut box)
serializer.DataField(ref _prototypes, "prototypes", null);
// If you want the final item to be different e.g. trash
serializer.DataField(ref _finishPrototype, "spawn_on_finish", null);
serializer.DataField(ref _availableSpawnCount, "available_spawn_count", 0);
serializer.DataField(ref _capacity, "capacity", 5);
}
public override void Initialize()
{
base.Initialize();
Owner.TryGetComponent(out AppearanceComponent appearance);
_appearanceComponent = appearance;
if (_prototypes == null)
{
throw new NullReferenceException();
}
if (_prototypes.Sum(x => x.Value) != 100)
{
throw new ArgumentOutOfRangeException();
}
}
public void MapInit()
{
_availableSpawnCount = Capacity;
}
protected override void Startup()
{
base.Startup();
_foodContainer =
ContainerManagerComponent.Ensure<Container>("food_container", Owner, out var existed);
if (existed)
{
foreach (var entity in _foodContainer.ContainedEntities)
{
_loadedFood.Push(entity);
}
}
_updateAppearance();
_appearanceComponent?.SetData(DrinkFoodContainerVisuals.Capacity, Capacity);
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
// TODO: Potentially change this depending upon desired functionality
IEntity item = TakeItem(eventArgs.User);
if (item == null)
{
return false;
}
if (item.TryGetComponent(out ItemComponent itemComponent) &&
eventArgs.User.TryGetComponent(out HandsComponent handsComponent))
{
if (handsComponent.CanPutInHand(itemComponent))
{
handsComponent.PutInHand(itemComponent);
return true;
}
}
item.Transform.GridPosition = eventArgs.User.Transform.GridPosition;
return true;
}
// TODO: Somewhat shitcode
// Tried using .Prob() buuuuuttt trying that for each item wouldn't work.
private string _getProbItem(Dictionary<string, int> prototypes)
{
if (prototypes.Count == 1)
{
return prototypes.Keys.ToList()[0];
}
var prob = IoCManager.Resolve<IRobustRandom>();
var result = prob.Next(0, 100);
var runningTotal = 0;
foreach (var item in prototypes)
{
runningTotal += item.Value;
if (result < runningTotal)
{
return item.Key;
}
}
throw new Exception();
}
public IEntity TakeItem(IEntity user)
{
if (_useSound != null)
{
if (Owner.TryGetComponent(out SoundComponent soundComponent) && _useSound != null)
{
soundComponent.Play(_useSound);
}
}
IEntity item = null;
if (_loadedFood.Count > 0)
{
item = _loadedFood.Pop();
_foodContainer.Remove(item);
}
if (_availableSpawnCount > 0)
{
var prototypeName = _getProbItem(_prototypes);
item = Owner.EntityManager.SpawnEntity(prototypeName);
_availableSpawnCount -= 1;
}
_tryDelete(user);
_updateAppearance();
return item;
}
private void _tryDelete(IEntity user)
{
if (Count <= 0)
{
// Ideally this takes priority to be put into inventory rather than the desired item
if (_finishPrototype != null)
{
var item = Owner.EntityManager.SpawnEntity(_finishPrototype);
item.Transform.GridPosition = Owner.Transform.GridPosition;
Owner.Delete();
if (user.TryGetComponent(out HandsComponent handsComponent) &&
item.TryGetComponent(out ItemComponent itemComponent))
{
if (handsComponent.CanPutInHand(itemComponent))
{
handsComponent.PutInHand(itemComponent);
}
}
return;
}
Owner.Delete();
}
}
private void _updateAppearance()
{
_appearanceComponent?.SetData(DrinkFoodContainerVisuals.Current, Count);
}
}
}

View File

@@ -0,0 +1,181 @@
using System;
using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Nutrition;
using Content.Shared.Interfaces;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public class FoodComponent : Component, IAfterAttack, IUse
{
#pragma warning disable 649
[Dependency] private readonly ILocalizationManager _localizationManager;
#pragma warning restore 649
// Currently the design is similar to drinkcomponent but it's susceptible to change so left as is for now.
public override string Name => "Food";
private AppearanceComponent _appearanceComponent;
[ViewVariables]
private string _useSound;
[ViewVariables]
private string _finishPrototype;
[ViewVariables]
private SolutionComponent _contents;
[ViewVariables]
private int _transferAmount;
private Solution _initialContents; // This is just for loading from yaml
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
// Default is 1 use restoring 30
serializer.DataField(ref _initialContents, "contents", null);
serializer.DataField(ref _useSound, "use_sound", "/Audio/items/eatfood.ogg");
// Default is transfer 30 units
serializer.DataField(ref _transferAmount,
"transfer_amount",
30 / StomachComponent.NutrimentFactor);
// E.g. empty chip packet when done
serializer.DataField(ref _finishPrototype, "spawn_on_finish", null);
}
public override void Initialize()
{
base.Initialize();
if (_contents == null)
{
if (Owner.TryGetComponent(out SolutionComponent solutionComponent))
{
_contents = solutionComponent;
}
else
{
_contents = Owner.AddComponent<SolutionComponent>();
_contents.Initialize();
}
}
_contents.MaxVolume = _initialContents.TotalVolume;
}
protected override void Startup()
{
base.Startup();
if (_initialContents != null)
{
_contents.TryAddSolution(_initialContents, true, true);
}
_initialContents = null;
if (_contents.CurrentVolume == 0)
{
_contents.TryAddReagent("chem.Nutriment", 30 / StomachComponent.NutrimentFactor,
out _);
}
Owner.TryGetComponent(out AppearanceComponent appearance);
_appearanceComponent = appearance;
// UsesLeft() at the start should match the max, at least currently.
_appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.MaxUses, UsesLeft());
_updateAppearance();
}
private void _updateAppearance()
{
_appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.Visual, UsesLeft());
}
public int UsesLeft()
{
// In case transfer amount exceeds volume left
if (_contents.CurrentVolume == 0)
{
return 0;
}
return Math.Max(1, _contents.CurrentVolume / _transferAmount);
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
UseFood(eventArgs.User);
return true;
}
void IAfterAttack.AfterAttack(AfterAttackEventArgs eventArgs)
{
UseFood(eventArgs.Attacked);
}
void UseFood(IEntity user)
{
if (user == null)
{
return;
}
if (UsesLeft() == 0)
{
user.PopupMessage(user, _localizationManager.GetString("Empty"));
}
else
{
// TODO: Add putting food back in boxes here?
if (user.TryGetComponent(out StomachComponent stomachComponent))
{
var transferAmount = Math.Min(_transferAmount, _contents.CurrentVolume);
var split = _contents.SplitSolution(transferAmount);
if (stomachComponent.TryTransferSolution(split))
{
if (_useSound != null)
{
Owner.GetComponent<SoundComponent>()?.Play(_useSound);
user.PopupMessage(user, _localizationManager.GetString("Nom"));
}
}
else
{
// Add it back in
_contents.TryAddSolution(split);
user.PopupMessage(user, _localizationManager.GetString("Can't eat"));
}
}
}
if (UsesLeft() > 0)
{
return;
}
Owner.Delete();
if (_finishPrototype != null)
{
var finisher = Owner.EntityManager.SpawnEntity(_finishPrototype);
if (user.TryGetComponent(out HandsComponent handsComponent) && finisher.TryGetComponent(out ItemComponent itemComponent))
{
if (handsComponent.CanPutInHand(itemComponent))
{
handsComponent.PutInHand(itemComponent);
return;
}
}
finisher.Transform.GridPosition = user.Transform.GridPosition;
return;
}
}
}
}

View File

@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using Content.Server.GameObjects.Components.Mobs;
using Content.Server.GameObjects.Components.Movement;
using Content.Shared.GameObjects;
using Content.Shared.GameObjects.Components.Mobs;
using Content.Shared.GameObjects.Components.Nutrition;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public sealed class HungerComponent : Component
{
#pragma warning disable 649
[Dependency] private readonly IRobustRandom _random;
#pragma warning restore 649
public override string Name => "Hunger";
// Base stuff
public float BaseDecayRate => _baseDecayRate;
[ViewVariables] private float _baseDecayRate;
public float ActualDecayRate => _actualDecayRate;
[ViewVariables] private float _actualDecayRate;
// Hunger
public HungerThreshold CurrentHungerThreshold => _currentHungerThreshold;
private HungerThreshold _currentHungerThreshold;
private HungerThreshold _lastHungerThreshold;
public float CurrentHunger => _currentHunger;
[ViewVariables] private float _currentHunger;
public Dictionary<HungerThreshold, float> HungerThresholds => _hungerThresholds;
private Dictionary<HungerThreshold, float> _hungerThresholds = new Dictionary<HungerThreshold, float>
{
{HungerThreshold.Overfed, 600.0f},
{HungerThreshold.Okay, 450.0f},
{HungerThreshold.Peckish, 300.0f},
{HungerThreshold.Starving, 150.0f},
{HungerThreshold.Dead, 0.0f},
};
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _baseDecayRate, "base_decay_rate", 0.5f);
}
public void HungerThresholdEffect(bool force = false)
{
if (_currentHungerThreshold != _lastHungerThreshold || force) {
Logger.InfoS("hunger", $"Updating hunger state for {Owner.Name}");
// Revert slow speed if required
if (_lastHungerThreshold == HungerThreshold.Starving && _currentHungerThreshold != HungerThreshold.Dead &&
Owner.TryGetComponent(out PlayerInputMoverComponent playerSpeedupComponent))
{
// TODO shitcode: Come up something better
playerSpeedupComponent.WalkMoveSpeed = playerSpeedupComponent.WalkMoveSpeed * 2;
playerSpeedupComponent.SprintMoveSpeed = playerSpeedupComponent.SprintMoveSpeed * 4;
}
// Update UI
Owner.TryGetComponent(out ServerStatusEffectsComponent statusEffectsComponent);
statusEffectsComponent?.ChangeStatus(StatusEffect.Hunger, "/Textures/Mob/UI/Hunger/" +
_currentHungerThreshold + ".png");
switch (_currentHungerThreshold)
{
case HungerThreshold.Overfed:
_lastHungerThreshold = _currentHungerThreshold;
_actualDecayRate = _baseDecayRate * 1.2f;
return;
case HungerThreshold.Okay:
_lastHungerThreshold = _currentHungerThreshold;
_actualDecayRate = _baseDecayRate;
return;
case HungerThreshold.Peckish:
// Same as okay except with UI icon saying eat soon.
_lastHungerThreshold = _currentHungerThreshold;
_actualDecayRate = _baseDecayRate * 0.8f;
return;
case HungerThreshold.Starving:
// TODO: If something else bumps this could cause mega-speed.
// If some form of speed update system if multiple things are touching it use that.
if (Owner.TryGetComponent(out PlayerInputMoverComponent playerInputMoverComponent)) {
playerInputMoverComponent.WalkMoveSpeed = playerInputMoverComponent.WalkMoveSpeed / 2;
playerInputMoverComponent.SprintMoveSpeed = playerInputMoverComponent.SprintMoveSpeed / 4;
}
_lastHungerThreshold = _currentHungerThreshold;
_actualDecayRate = _baseDecayRate * 0.6f;
return;
case HungerThreshold.Dead:
return;
default:
Logger.ErrorS("hunger", $"No hunger threshold found for {_currentHungerThreshold}");
throw new ArgumentOutOfRangeException($"No hunger threshold found for {_currentHungerThreshold}");
}
}
}
protected override void Startup()
{
base.Startup();
// Similar functionality to SS13. Should also stagger people going to the chef.
_currentHunger = _random.Next(
(int)_hungerThresholds[HungerThreshold.Peckish] + 10,
(int)_hungerThresholds[HungerThreshold.Okay] - 1);
_currentHungerThreshold = GetHungerThreshold(_currentHunger);
_lastHungerThreshold = HungerThreshold.Okay; // TODO: Potentially change this -> Used Okay because no effects.
HungerThresholdEffect(true);
}
public HungerThreshold GetHungerThreshold(float food)
{
HungerThreshold result = HungerThreshold.Dead;
var value = HungerThresholds[HungerThreshold.Overfed];
foreach (var threshold in _hungerThresholds)
{
if (threshold.Value <= value && threshold.Value >= food)
{
result = threshold.Key;
value = threshold.Value;
}
}
return result;
}
public void UpdateFood(float amount)
{
_currentHunger = Math.Min(_currentHunger + amount, HungerThresholds[HungerThreshold.Overfed]);
}
// TODO: If mob is moving increase rate of consumption?
// Should use a multiplier as something like a disease would overwrite decay rate.
public void OnUpdate(float frametime)
{
_currentHunger -= frametime * ActualDecayRate;
var calculatedHungerThreshold = GetHungerThreshold(_currentHunger);
// _trySound(calculatedThreshold);
if (calculatedHungerThreshold != _currentHungerThreshold)
{
_currentHungerThreshold = calculatedHungerThreshold;
HungerThresholdEffect();
}
if (_currentHungerThreshold == HungerThreshold.Dead)
{
// TODO: Remove from dead people
if (Owner.TryGetComponent(out DamageableComponent damage))
{
damage.TakeDamage(DamageType.Brute, 2);
return;
}
return;
}
}
}
public enum HungerThreshold
{
Overfed,
Okay,
Peckish,
Starving,
Dead,
}
}

View File

@@ -0,0 +1,129 @@
using Content.Server.GameObjects.Components.Chemistry;
using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Nutrition;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public class StomachComponent : SharedStomachComponent
{
// Essentially every time it ticks it'll pull out the MetabolisationAmount of reagents and process them.
// Generic food goes under "nutriment" like SS13
// There's also separate hunger and thirst components which means you can have a stomach
// but not require food / water.
public static readonly int NutrimentFactor = 30;
public static readonly int HydrationFactor = 30;
public static readonly int MetabolisationAmount = 5;
private SolutionComponent _stomachContents;
public float MetaboliseDelay => _metaboliseDelay;
[ViewVariables]
private float _metaboliseDelay; // How long between metabolisation for 5 units
public int MaxVolume
{
get => _stomachContents.MaxVolume;
set => _stomachContents.MaxVolume = value;
}
private float _metabolisationCounter = 0.0f;
private int _initialMaxVolume;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _metaboliseDelay, "metabolise_delay", 6.0f);
serializer.DataField(ref _initialMaxVolume, "max_volume", 20);
}
public override void Initialize()
{
base.Initialize();
// Shouldn't add to Owner to avoid cross-contamination (e.g. with blood or whatever they made hold other solutions)
_stomachContents = new SolutionComponent();
_stomachContents.InitializeFromPrototype();
_stomachContents.MaxVolume = _initialMaxVolume;
}
public bool TryTransferSolution(Solution solution)
{
// TODO: For now no partial transfers. Potentially change by design
if (solution.TotalVolume + _stomachContents.CurrentVolume > _stomachContents.MaxVolume)
{
return false;
}
_stomachContents.TryAddSolution(solution, false, true);
return true;
}
/// <summary>
/// This is where the magic happens. Make people throw up, increase nutrition, whatever
/// </summary>
/// <param name="solution"></param>
public void React(Solution solution)
{
// 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)
{
return;
}
var metabolisation = _stomachContents.SplitSolution(MetabolisationAmount);
React(metabolisation);
}
public void OnUpdate(float frameTime)
{
_metabolisationCounter += frameTime;
if (_metabolisationCounter >= MetaboliseDelay)
{
// Going to be rounding issues with frametime but no easy way to avoid it with int reagents.
// It is a long-term mechanic so shouldn't be a big deal.
Metabolise();
_metabolisationCounter -= MetaboliseDelay;
}
}
}
}

View File

@@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using Content.Server.GameObjects.Components.Mobs;
using Content.Server.GameObjects.Components.Movement;
using Content.Shared.GameObjects;
using Content.Shared.GameObjects.Components.Mobs;
using Content.Shared.GameObjects.Components.Nutrition;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public sealed class ThirstComponent : Component
{
#pragma warning disable 649
[Dependency] private readonly IRobustRandom _random;
#pragma warning restore 649
public override string Name => "Thirst";
// Base stuff
public float BaseDecayRate => _baseDecayRate;
[ViewVariables] private float _baseDecayRate;
public float ActualDecayRate => _actualDecayRate;
[ViewVariables] private float _actualDecayRate;
// Thirst
public ThirstThreshold CurrentThirstThreshold => _currentThirstThreshold;
private ThirstThreshold _currentThirstThreshold;
private ThirstThreshold _lastThirstThreshold;
public float CurrentThirst => _currentThirst;
[ViewVariables] private float _currentThirst;
public Dictionary<ThirstThreshold, float> ThirstThresholds => _thirstThresholds;
private Dictionary<ThirstThreshold, float> _thirstThresholds = new Dictionary<ThirstThreshold, float>
{
{ThirstThreshold.OverHydrated, 400.0f},
{ThirstThreshold.Okay, 300.0f},
{ThirstThreshold.Thirsty, 200.0f},
{ThirstThreshold.Parched, 100.0f},
{ThirstThreshold.Dead, 0.0f},
};
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _baseDecayRate, "base_decay_rate", 0.5f);
}
public void ThirstThresholdEffect(bool force = false)
{
if (_currentThirstThreshold != _lastThirstThreshold || force) {
Logger.InfoS("thirst", $"Updating Thirst state for {Owner.Name}");
// Revert slow speed if required
if (_lastThirstThreshold == ThirstThreshold.Parched && _currentThirstThreshold != ThirstThreshold.Dead &&
Owner.TryGetComponent(out PlayerInputMoverComponent playerSpeedupComponent))
{
// TODO shitcode: Come up something better
playerSpeedupComponent.WalkMoveSpeed = playerSpeedupComponent.WalkMoveSpeed * 2;
playerSpeedupComponent.SprintMoveSpeed = playerSpeedupComponent.SprintMoveSpeed * 4;
}
// Update UI
Owner.TryGetComponent(out ServerStatusEffectsComponent statusEffectsComponent);
statusEffectsComponent?.ChangeStatus(StatusEffect.Thirst, "/Textures/Mob/UI/Thirst/" +
_currentThirstThreshold + ".png");
switch (_currentThirstThreshold)
{
case ThirstThreshold.OverHydrated:
_lastThirstThreshold = _currentThirstThreshold;
_actualDecayRate = _baseDecayRate * 1.2f;
return;
case ThirstThreshold.Okay:
_lastThirstThreshold = _currentThirstThreshold;
_actualDecayRate = _baseDecayRate;
return;
case ThirstThreshold.Thirsty:
// Same as okay except with UI icon saying drink soon.
_lastThirstThreshold = _currentThirstThreshold;
_actualDecayRate = _baseDecayRate * 0.8f;
return;
case ThirstThreshold.Parched:
// TODO: If something else bumps this could cause mega-speed.
// If some form of speed update system if multiple things are touching it use that.
if (Owner.TryGetComponent(out PlayerInputMoverComponent playerInputMoverComponent)) {
playerInputMoverComponent.WalkMoveSpeed = playerInputMoverComponent.WalkMoveSpeed / 2;
playerInputMoverComponent.SprintMoveSpeed = playerInputMoverComponent.SprintMoveSpeed / 4;
}
_lastThirstThreshold = _currentThirstThreshold;
_actualDecayRate = _baseDecayRate * 0.6f;
return;
case ThirstThreshold.Dead:
return;
default:
Logger.ErrorS("thirst", $"No thirst threshold found for {_currentThirstThreshold}");
throw new ArgumentOutOfRangeException($"No thirst threshold found for {_currentThirstThreshold}");
}
}
}
protected override void Startup()
{
base.Startup();
_currentThirst = _random.Next(
(int)_thirstThresholds[ThirstThreshold.Thirsty] + 10,
(int)_thirstThresholds[ThirstThreshold.Okay] - 1);
_currentThirstThreshold = GetThirstThreshold(_currentThirst);
_lastThirstThreshold = ThirstThreshold.Okay; // TODO: Potentially change this -> Used Okay because no effects.
// TODO: Check all thresholds make sense and throw if they don't.
ThirstThresholdEffect(true);
}
public ThirstThreshold GetThirstThreshold(float drink)
{
ThirstThreshold result = ThirstThreshold.Dead;
var value = ThirstThresholds[ThirstThreshold.OverHydrated];
foreach (var threshold in _thirstThresholds)
{
if (threshold.Value <= value && threshold.Value >= drink)
{
result = threshold.Key;
value = threshold.Value;
}
}
return result;
}
public void UpdateThirst(float amount)
{
_currentThirst = Math.Min(_currentThirst + amount, ThirstThresholds[ThirstThreshold.OverHydrated]);
}
// TODO: If mob is moving increase rate of consumption.
// Should use a multiplier as something like a disease would overwrite decay rate.
public void OnUpdate(float frametime)
{
_currentThirst -= frametime * ActualDecayRate;
var calculatedThirstThreshold = GetThirstThreshold(_currentThirst);
// _trySound(calculatedThreshold);
if (calculatedThirstThreshold != _currentThirstThreshold)
{
_currentThirstThreshold = calculatedThirstThreshold;
ThirstThresholdEffect();
}
if (_currentThirstThreshold == ThirstThreshold.Dead)
{
// TODO: Remove from dead people
if (Owner.TryGetComponent(out DamageableComponent damage))
{
damage.TakeDamage(DamageType.Brute, 2);
return;
}
return;
}
}
}
public enum ThirstThreshold
{
// Hydrohomies
OverHydrated,
Okay,
Thirsty,
Parched,
Dead,
}
}