Rework Drink/Food/FoodContainer entirely (#1009)

Co-authored-by: FL-OZ <anotherscuffed@gmail.com>
Co-authored-by: Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
This commit is contained in:
FL-OZ
2020-05-29 15:50:23 -05:00
committed by GitHub
parent 7222b6d8e2
commit aa26bdfcae
107 changed files with 946 additions and 1099 deletions

View File

@@ -241,7 +241,13 @@ namespace Content.Server.GameObjects.Components.Kitchen
return true;
}
itemEntity.TryGetComponent(typeof(ItemComponent), out var food);
if (!itemEntity.TryGetComponent(typeof(ItemComponent), out var food))
{
_notifyManager.PopupMessage(Owner, eventArgs.User, "That won't work!");
return false;
}
var ent = food.Owner; //Get the entity of the ItemComponent.
_storage.Insert(ent);
_uiDirty = true;

View File

@@ -1,148 +1,163 @@
using System;
using System.Linq;
using System;
using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems;
using Content.Server.Utility;
using Content.Shared.Audio;
using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Nutrition;
using Content.Shared.Interfaces;
using Content.Shared.Maths;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public class DrinkComponent : Component, IAfterInteract, IUse
[ComponentReference(typeof(IAfterInteract))]
public class DrinkComponent : Component, IUse, IAfterInteract, ISolutionChange,IExamine
{
#pragma warning disable 649
[Dependency] private readonly ILocalizationManager _localizationManager;
[Dependency] private readonly IPrototypeManager _prototypeManager;
[Dependency] private readonly IRobustRandom _random;
[Dependency] private readonly IEntitySystemManager _entitySystem;
#pragma warning restore 649
private AudioSystem _audioSystem;
public override string Name => "Drink";
[ViewVariables]
private SolutionComponent _contents;
private AppearanceComponent _appearanceComponent;
[ViewVariables]
private string _useSound;
[ViewVariables]
private string _finishPrototype;
public ReagentUnit TransferAmount => _transferAmount;
private bool _defaultToOpened;
[ViewVariables]
private ReagentUnit _transferAmount = ReagentUnit.New(2);
public ReagentUnit TransferAmount { get; private set; } = ReagentUnit.New(2);
public ReagentUnit MaxVolume
{
get => _contents.MaxVolume;
set => _contents.MaxVolume = value;
}
[ViewVariables]
public bool Opened => _opened;
private bool _despawnOnFinish;
private bool _drinking;
public int UsesLeft()
{
// In case transfer amount exceeds volume left
if (_contents.CurrentVolume == 0)
{
return 0;
}
return Math.Max(1, (int)Math.Ceiling((_contents.CurrentVolume / _transferAmount).Float()));
}
[ViewVariables]
public bool Empty => _contents.CurrentVolume.Float() <= 0;
private AppearanceComponent _appearanceComponent;
private bool _opened = false;
private string _soundCollection;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
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. - TODO: this should be implemented in a separate component
serializer.DataField(ref _despawnOnFinish, "despawn_empty", false);
serializer.DataField(ref _finishPrototype, "spawn_on_finish", null);
serializer.DataField(ref _useSound, "useSound", "/Audio/items/drink.ogg");
serializer.DataField(ref _defaultToOpened, "isOpen", false); //For things like cups of coffee.
serializer.DataField(ref _soundCollection, "openSounds","canOpenSounds");
}
protected override void Startup()
public override void Initialize()
{
base.Startup();
_contents = Owner.GetComponent<SolutionComponent>();
base.Initialize();
Owner.TryGetComponent(out _appearanceComponent);
if(!Owner.TryGetComponent(out _contents))
{
_contents = Owner.AddComponent<SolutionComponent>();
}
_contents.Capabilities = SolutionCaps.PourIn
| SolutionCaps.PourOut
| SolutionCaps.Injectable;
_drinking = false;
Owner.TryGetComponent(out AppearanceComponent appearance);
_appearanceComponent = appearance;
_appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.MaxUses, MaxVolume.Float());
_updateAppearance();
_opened = _defaultToOpened;
UpdateAppearance();
}
private void _updateAppearance()
void ISolutionChange.SolutionChanged(SolutionChangeEventArgs eventArgs)
{
UpdateAppearance();
}
private void UpdateAppearance()
{
_appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.Visual, _contents.CurrentVolume.Float());
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
bool IUse.UseEntity(UseEntityEventArgs args)
{
UseDrink(eventArgs.User);
return true;
if (!_opened)
{
//Do the opening stuff like playing the sounds.
var soundCollection = _prototypeManager.Index<SoundCollectionPrototype>(_soundCollection);
var file = _random.Pick(soundCollection.PickFiles);
_audioSystem = _entitySystem.GetEntitySystem<AudioSystem>();
_audioSystem.Play(file, Owner, AudioParams.Default);
_opened = true;
return false;
}
return TryUseDrink(args.User);
}
//Force feeding a drink to someone.
void IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (!InteractionChecks.InRangeUnobstructed(eventArgs)) return;
UseDrink(eventArgs.Target);
TryUseDrink(eventArgs.Target);
}
private void UseDrink(IEntity targetEntity)
public void Examine(FormattedMessage message)
{
if (targetEntity == null)
if (!Opened)
{
return;
}
var color = Empty ? "gray" : "yellow";
var openedText = Loc.GetString(Empty ? "Empty" : "Opened");
message.AddMarkup(Loc.GetString("[color={0}]{1}[/color]", color, openedText));
if (UsesLeft() == 0 && !_despawnOnFinish)
}
private bool TryUseDrink(IEntity target)
{
if (target == null)
{
targetEntity.PopupMessage(targetEntity, _localizationManager.GetString("Empty"));
return;
return false;
}
if (targetEntity.TryGetComponent(out StomachComponent stomachComponent))
if (!_opened)
{
_drinking = true;
var transferAmount = ReagentUnit.Min(_transferAmount, _contents.CurrentVolume);
var split = _contents.SplitSolution(transferAmount);
if (stomachComponent.TryTransferSolution(split))
{
// When we split Finish gets called which may delete the can so need to use the entity system for sound
if (_useSound != null)
{
var audioSystem = EntitySystem.Get<AudioSystem>();
audioSystem.Play(_useSound, Owner, AudioParams.Default.WithVolume(-2f));
targetEntity.PopupMessage(targetEntity, _localizationManager.GetString("Slurp"));
}
}
else
{
// Add it back in
_contents.TryAddSolution(split);
targetEntity.PopupMessage(targetEntity, _localizationManager.GetString("Can't drink"));
}
_drinking = false;
target.PopupMessage(target, Loc.GetString("Open it first!"));
}
if (_contents.CurrentVolume.Float() <= 0)
{
target.PopupMessage(target, Loc.GetString("It's empty!"));
return false;
}
if (!target.TryGetComponent(out StomachComponent stomachComponent))
{
return false;
}
var transferAmount = ReagentUnit.Min(TransferAmount, _contents.CurrentVolume);
var split = _contents.SplitSolution(transferAmount);
if (stomachComponent.TryTransferSolution(split))
{
if (_useSound == null) return false;
_audioSystem.Play(_useSound, Owner, AudioParams.Default.WithVolume(-2f));
target.PopupMessage(target, Loc.GetString("Slurp"));
UpdateAppearance();
return true;
}
//Stomach was full or can't handle whatever solution we have.
_contents.TryAddSolution(split);
target.PopupMessage(target, Loc.GetString("You've had enough {0}!", Owner.Name));
return false;
}
}
}

View File

@@ -1,191 +0,0 @@
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, Owner.Transform.GridPosition);
_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, Owner.Transform.GridPosition);
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

@@ -1,12 +1,11 @@
using System;
using System;
using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems;
using Content.Server.Utility;
using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Nutrition;
using Content.Shared.Interfaces;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
@@ -17,165 +16,105 @@ using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Nutrition
{
[RegisterComponent]
public class FoodComponent : Component, IAfterInteract, IUse
[ComponentReference(typeof(IAfterInteract))]
public class FoodComponent : Component, IUse, IAfterInteract
{
#pragma warning disable 649
[Dependency] private readonly ILocalizationManager _localizationManager;
[Dependency] private readonly IEntitySystemManager _entitySystem;
#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;
private string _trashPrototype;
[ViewVariables]
private SolutionComponent _contents;
[ViewVariables]
private ReagentUnit _transferAmount;
private Solution _initialContents; // This is just for loading from yaml
public int UsesRemaining => _contents.CurrentVolume == 0
?
0 : Math.Max(1, (int)Math.Ceiling((_contents.CurrentVolume / _transferAmount).Float()));
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", ReagentUnit.New(5));
// E.g. empty chip packet when done
serializer.DataField(ref _finishPrototype, "spawn_on_finish", null);
serializer.DataField(ref _useSound, "useSound", "/Audio/items/eatfood.ogg");
serializer.DataField(ref _transferAmount, "transferAmount", ReagentUnit.New(5));
serializer.DataField(ref _trashPrototype, "trash", "TrashPlate");
}
public override void Initialize()
{
base.Initialize();
if (_contents == null)
{
if (Owner.TryGetComponent(out SolutionComponent solutionComponent))
{
_contents = solutionComponent;
}
else
{
_contents = Owner.AddComponent<SolutionComponent>();
}
}
_contents = Owner.GetComponent<SolutionComponent>();
_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", ReagentUnit.New(5), 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, (int)Math.Ceiling((_contents.CurrentVolume / _transferAmount).Float()));
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
UseFood(eventArgs.User);
return true;
return TryUseFood(eventArgs.User, null);
}
void IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (!InteractionChecks.InRangeUnobstructed(eventArgs)) return;
UseFood(eventArgs.Target);
TryUseFood(eventArgs.User, eventArgs.Target);
}
void UseFood(IEntity user)
private bool TryUseFood(IEntity user, IEntity target)
{
if (user == null)
{
return;
return false;
}
if (UsesLeft() == 0)
if (UsesRemaining <= 0)
{
user.PopupMessage(user, _localizationManager.GetString("Empty"));
user.PopupMessage(user, Loc.GetString($"The {Owner.Name} is empty!"));
return false;
}
else
var trueTarget = target ?? user;
if (trueTarget.TryGetComponent(out StomachComponent stomachComponent))
{
// TODO: Add putting food back in boxes here?
if (user.TryGetComponent(out StomachComponent stomachComponent))
var transferAmount = ReagentUnit.Min(_transferAmount, _contents.CurrentVolume);
var split = _contents.SplitSolution(transferAmount);
if (stomachComponent.TryTransferSolution(split))
{
var transferAmount = ReagentUnit.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"));
}
_entitySystem.GetEntitySystem<AudioSystem>()
.Play(_useSound, trueTarget, AudioParams.Default.WithVolume(-1f));
trueTarget.PopupMessage(user, Loc.GetString("Nom"));
}
else
{
_contents.TryAddSolution(split);
trueTarget.PopupMessage(user, Loc.GetString("You can't eat any more!"));
}
}
if (UsesLeft() > 0)
if (UsesRemaining > 0)
{
return;
return true;
}
//We're empty. Become trash.
var position = Owner.Transform.GridPosition;
Owner.Delete();
if (_finishPrototype != null)
var finisher = Owner.EntityManager.SpawnEntity(_trashPrototype, position);
if (user.TryGetComponent(out HandsComponent handsComponent) && finisher.TryGetComponent(out ItemComponent itemComponent))
{
var finisher = Owner.EntityManager.SpawnEntity(_finishPrototype, position);
if (user.TryGetComponent(out HandsComponent handsComponent) && finisher.TryGetComponent(out ItemComponent itemComponent))
if (handsComponent.CanPutInHand(itemComponent))
{
if (handsComponent.CanPutInHand(itemComponent))
{
handsComponent.PutInHand(itemComponent);
return;
}
handsComponent.PutInHand(itemComponent);
return true;
}
finisher.Transform.GridPosition = user.Transform.GridPosition;
return;
}
finisher.Transform.GridPosition = user.Transform.GridPosition;
return true;
}
}
}

View File

@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.GameObjects.Components.Nutrition;
using Robust.Server.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
{
/// <summary>
/// This container acts as a master object for things like Pizza, which holds slices.
/// </summary>
/// TODO: Perhaps implement putting food back (pizza boxes) but that really isn't mandatory.
/// This doesn't even need to have an actual Container for right now.
[RegisterComponent]
public sealed class FoodContainer : SharedFoodContainerComponent, IUse
{
#pragma warning disable 649
[Dependency] private readonly IRobustRandom _random;
[Dependency] private readonly IEntityManager _entityManager;
#pragma warning restore 649
public override string Name => "FoodContainer";
private AppearanceComponent _appearance;
private Dictionary<string, int> _prototypes;
private uint _capacity;
public int Capacity => (int)_capacity;
[ViewVariables]
public int Count => _count;
private int _count = 0;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _prototypes, "prototypes", null);
serializer.DataField<uint>(ref _capacity, "capacity", 5);
}
public override void Initialize()
{
base.Initialize();
Owner.TryGetComponent(out _appearance);
_count = Capacity;
UpdateAppearance();
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
var hands = eventArgs.User.TryGetComponent(out HandsComponent handsComponent);
var itemToSpawn = _entityManager.SpawnEntity(GetRandomPrototype(), Owner.Transform.GridPosition);
handsComponent.PutInHandOrDrop(itemToSpawn.GetComponent<ItemComponent>());
_count--;
if (_count < 1)
{
Owner.Delete();
return false;
}
return true;
}
private string GetRandomPrototype()
{
var defaultProto = _prototypes.Keys.FirstOrDefault();
if (_prototypes.Count == 1)
{
return defaultProto;
}
var probResult = _random.Next(0, 100);
var total = 0;
foreach (var item in _prototypes)
{
total += item.Value;
if (probResult < total)
{
return item.Key;
}
}
return defaultProto;
}
private void UpdateAppearance()
{
_appearance?.SetData(FoodContainerVisuals.Current, Count);
}
}
}