Microwave ECS (#10766)

* microwave ECS

* allcomponentdelete etset

ack

* container purge
This commit is contained in:
Nemanja
2022-08-27 19:40:29 -04:00
committed by GitHub
parent f442fb044e
commit 32abdf5f00
23 changed files with 535 additions and 922 deletions

View File

@@ -0,0 +1,19 @@
using Content.Shared.Kitchen;
namespace Content.Server.Kitchen.Components;
/// <summary>
/// Attached to a microwave that is currently in the process of cooking
/// </summary>
[RegisterComponent]
public sealed class ActiveMicrowaveComponent : Component
{
[ViewVariables(VVAccess.ReadWrite)]
public float CookTimeRemaining;
[ViewVariables(VVAccess.ReadWrite)]
public float TotalTime;
[ViewVariables]
public (FoodRecipePrototype?, int) PortionedRecipe;
}

View File

@@ -1,49 +1,34 @@
using System.Linq;
using Content.Server.Chemistry.Components.SolutionManager;
using Content.Server.Chemistry.EntitySystems;
using Content.Server.Power.Components;
using Content.Server.Temperature.Components;
using Content.Server.Temperature.Systems;
using Content.Server.UserInterface;
using Content.Shared.FixedPoint;
using Content.Shared.Kitchen;
using Content.Shared.Kitchen.Components;
using Content.Shared.Power;
using Content.Shared.Tag;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Server.Kitchen.Components
{
[RegisterComponent]
public sealed class MicrowaveComponent : SharedMicrowaveComponent
public sealed class MicrowaveComponent : Component
{
[Dependency] private readonly IEntityManager _entities = default!;
[Dependency] private readonly RecipeManager _recipeManager = default!;
#region YAMLSERIALIZE
[DataField("cookTime")] private uint _cookTimeDefault = 5;
[DataField("cookTimeMultiplier")] private int _cookTimeMultiplier = 1000; //For upgrades and stuff I guess?
[DataField("failureResult")] private string _badRecipeName = "FoodBadRecipe";
[DataField("beginCookingSound")] private SoundSpecifier _startCookingSound =
new SoundPathSpecifier("/Audio/Machines/microwave_start_beep.ogg");
[DataField("foodDoneSound")] private SoundSpecifier _cookingCompleteSound =
new SoundPathSpecifier("/Audio/Machines/microwave_done_beep.ogg");
[DataField("cookTimeMultiplier")]
public int CookTimeMultiplier = 1; //For upgrades and stuff I guess? don't ask me.
[DataField("failureResult", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))]
public string BadRecipeEntityId = "FoodBadRecipe";
#region audio
[DataField("beginCookingSound")]
public SoundSpecifier StartCookingSound = new SoundPathSpecifier("/Audio/Machines/microwave_start_beep.ogg");
[DataField("foodDoneSound")]
public SoundSpecifier FoodDoneSound = new SoundPathSpecifier("/Audio/Machines/microwave_done_beep.ogg");
[DataField("clickSound")]
private SoundSpecifier _clickSound = new SoundPathSpecifier("/Audio/Machines/machine_switch.ogg");
public SoundSpecifier ClickSound = new SoundPathSpecifier("/Audio/Machines/machine_switch.ogg");
[DataField("ItemBreakSound")]
public SoundSpecifier ItemBreakSound = new SoundPathSpecifier("/Audio/Effects/clang.ogg");
#endregion YAMLSERIALIZE
public IPlayingAudioStream? PlayingStream { get; set; }
[DataField("loopingSound")]
public SoundSpecifier LoopingSound = new SoundPathSpecifier("/Audio/Machines/microwave_loop.ogg");
#endregion
[ViewVariables] private bool _busy = false;
[ViewVariables]
public bool Broken;
/// <summary>
@@ -51,7 +36,8 @@ namespace Content.Server.Kitchen.Components
/// The cook times for all recipes should be divisible by 5,with a minimum of 1 second.
/// For right now, I don't think any recipe cook time should be greater than 60 seconds.
/// </summary>
[ViewVariables] private uint _currentCookTimerTime = 1;
[DataField("currentCookTimerTime"), ViewVariables(VVAccess.ReadWrite)]
public uint CurrentCookTimerTime = 5;
/// <summary>
/// The max temperature that this microwave can heat objects to.
@@ -59,403 +45,9 @@ namespace Content.Server.Kitchen.Components
[DataField("temperatureUpperThreshold")]
public float TemperatureUpperThreshold = 373.15f;
public bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered;
private bool HasContents => Storage.ContainedEntities.Count > 0;
public bool UIDirty = true;
private bool _lostPower;
private int _currentCookTimeButtonIndex;
public void DirtyUi()
{
UIDirty = true;
}
public int CurrentCookTimeButtonIndex;
public Container Storage = default!;
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(MicrowaveUiKey.Key);
protected override void Initialize()
{
base.Initialize();
_currentCookTimerTime = _cookTimeDefault;
Storage = ContainerHelpers.EnsureContainer<Container>(Owner, "microwave_entity_container",
out _);
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += UserInterfaceOnReceiveMessage;
}
}
public void SetCookTime(uint cookTime)
{
_currentCookTimerTime = cookTime;
UIDirty = true;
}
private void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage message)
{
if (!Powered || _busy)
{
return;
}
switch (message.Message)
{
case MicrowaveStartCookMessage:
Wzhzhzh();
break;
case MicrowaveEjectMessage:
if (HasContents)
{
EjectSolids();
ClickSound();
UIDirty = true;
}
break;
case MicrowaveEjectSolidIndexedMessage msg:
if (HasContents)
{
EjectSolid(msg.EntityID);
ClickSound();
UIDirty = true;
}
break;
case MicrowaveSelectCookTimeMessage msg:
_currentCookTimeButtonIndex = msg.ButtonIndex;
_currentCookTimerTime = msg.NewCookTime;
ClickSound();
UIDirty = true;
break;
}
}
public void OnUpdate()
{
if (!Powered)
{
//TODO:If someone cuts power currently, microwave magically keeps going. FIX IT!
SetAppearance(MicrowaveVisualState.Idle);
}
if (_busy && !Powered)
{
//we lost power while we were cooking/busy!
_lostPower = true;
EjectSolids();
_busy = false;
UIDirty = true;
}
if (_busy && Broken)
{
SetAppearance(MicrowaveVisualState.Broken);
//we broke while we were cooking/busy!
_lostPower = true;
EjectSolids();
_busy = false;
UIDirty = true;
}
if (UIDirty)
{
UserInterface?.SetState(new MicrowaveUpdateUserInterfaceState
(
Storage.ContainedEntities.Select(item => item).ToArray(),
_busy,
_currentCookTimeButtonIndex,
_currentCookTimerTime
));
UIDirty = false;
}
}
public void SetAppearance(MicrowaveVisualState state)
{
var finalState = state;
if (Broken)
{
finalState = MicrowaveVisualState.Broken;
}
if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearance))
{
appearance.SetData(PowerDeviceVisuals.VisualState, finalState);
}
}
// ReSharper disable once InconsistentNaming
// ReSharper disable once IdentifierTypo
public void Wzhzhzh()
{
if (!HasContents)
{
return;
}
_busy = true;
// Convert storage into Dictionary of ingredients
var solidsDict = new Dictionary<string, int>();
var reagentDict = new Dictionary<string, FixedPoint2>();
foreach (var item in Storage.ContainedEntities)
{
// special behavior when being microwaved ;)
var ev = new BeingMicrowavedEvent(Owner);
_entities.EventBus.RaiseLocalEvent(item, ev, false);
if (ev.Handled)
{
_busy = false;
UIDirty = true;
return;
}
var tagSys = EntitySystem.Get<TagSystem>();
if (tagSys.HasTag(item, "MicrowaveMachineUnsafe")
|| tagSys.HasTag(item, "Metal"))
{
// destroy microwave
Broken = true;
SetAppearance(MicrowaveVisualState.Broken);
SoundSystem.Play(ItemBreakSound.GetSound(), Filter.Pvs(Owner), Owner);
return;
}
if (tagSys.HasTag(item, "MicrowaveSelfUnsafe")
|| tagSys.HasTag(item, "Plastic"))
{
_entities.SpawnEntity(_badRecipeName,
_entities.GetComponent<TransformComponent>(Owner).Coordinates);
_entities.QueueDeleteEntity(item);
}
var metaData = _entities.GetComponent<MetaDataComponent>(item);
if (metaData.EntityPrototype == null)
{
continue;
}
if (solidsDict.ContainsKey(metaData.EntityPrototype.ID))
{
solidsDict[metaData.EntityPrototype.ID]++;
}
else
{
solidsDict.Add(metaData.EntityPrototype.ID, 1);
}
if (!_entities.TryGetComponent<SolutionContainerManagerComponent>(item, out var solMan))
continue;
foreach (var (_, solution) in solMan.Solutions)
{
foreach (var reagent in solution.Contents)
{
if (reagentDict.ContainsKey(reagent.ReagentId))
reagentDict[reagent.ReagentId] += reagent.Quantity;
else
reagentDict.Add(reagent.ReagentId, reagent.Quantity);
}
}
}
// Check recipes
(FoodRecipePrototype, int) portionedRecipe = _recipeManager.Recipes.Select(
r => CanSatisfyRecipe(r, solidsDict, reagentDict)).Where(r => r.Item2 > 0).FirstOrDefault();
FoodRecipePrototype? recipeToCook = portionedRecipe.Item1;
SetAppearance(MicrowaveVisualState.Cooking);
var time = _currentCookTimerTime * _cookTimeMultiplier;
SoundSystem.Play(_startCookingSound.GetSound(), Filter.Pvs(Owner), Owner, AudioParams.Default);
Owner.SpawnTimer((int) (_currentCookTimerTime * _cookTimeMultiplier), () =>
{
if (_lostPower)
{
return;
}
AddTemperature(time);
if (recipeToCook != null)
{
for (int i = 0; i < portionedRecipe.Item2; i++)
{
SubtractContents(recipeToCook);
_entities.SpawnEntity(recipeToCook.Result,
_entities.GetComponent<TransformComponent>(Owner).Coordinates);
}
}
EjectSolids();
SoundSystem.Play(_cookingCompleteSound.GetSound(), Filter.Pvs(Owner),
Owner, AudioParams.Default.WithVolume(-1f));
SetAppearance(MicrowaveVisualState.Idle);
_busy = false;
UIDirty = true;
});
_lostPower = false;
UIDirty = true;
}
/// <summary>
/// Adds temperature to every item in the microwave,
/// based on the time it took to microwave.
/// </summary>
/// <param name="time">The time on the microwave, in seconds.</param>
public void AddTemperature(float time)
{
var solutionContainerSystem = EntitySystem.Get<SolutionContainerSystem>();
foreach (var entity in Storage.ContainedEntities)
{
if (_entities.TryGetComponent(entity, out TemperatureComponent? temp))
{
EntitySystem.Get<TemperatureSystem>().ChangeHeat(entity, time / 10, false, temp);
}
if (_entities.TryGetComponent(entity, out SolutionContainerManagerComponent? solutions))
{
foreach (var (_, solution) in solutions.Solutions)
{
if (solution.Temperature > TemperatureUpperThreshold)
continue;
solutionContainerSystem.AddThermalEnergy(entity, solution, time / 10);
}
}
}
}
private void EjectSolids()
{
for (var i = Storage.ContainedEntities.Count - 1; i >= 0; i--)
{
Storage.Remove(Storage.ContainedEntities.ElementAt(i));
}
}
private void EjectSolid(EntityUid entityId)
{
if (_entities.EntityExists(entityId))
{
Storage.Remove(entityId);
}
}
private void SubtractContents(FoodRecipePrototype recipe)
{
var totalReagentsToRemove = new Dictionary<string, FixedPoint2>(recipe.IngredientsReagents);
var solutionContainerSystem = EntitySystem.Get<SolutionContainerSystem>();
// this is spaghetti ngl
foreach (var item in Storage.ContainedEntities)
{
if (!_entities.TryGetComponent<SolutionContainerManagerComponent>(item, out var solMan))
continue;
// go over every solution
foreach (var (_, solution) in solMan.Solutions)
{
foreach (var (reagent, _) in recipe.IngredientsReagents)
{
// removed everything
if (!totalReagentsToRemove.ContainsKey(reagent))
continue;
if (!solution.ContainsReagent(reagent))
continue;
var quant = solution.GetReagentQuantity(reagent);
if (quant >= totalReagentsToRemove[reagent])
{
quant = totalReagentsToRemove[reagent];
totalReagentsToRemove.Remove(reagent);
}
else
{
totalReagentsToRemove[reagent] -= quant;
}
solutionContainerSystem.TryRemoveReagent(item, solution, reagent, quant);
}
}
}
foreach (var recipeSolid in recipe.IngredientsSolids)
{
for (var i = 0; i < recipeSolid.Value; i++)
{
foreach (var item in Storage.ContainedEntities)
{
var metaData = _entities.GetComponent<MetaDataComponent>(item);
if (metaData.EntityPrototype == null)
{
continue;
}
if (metaData.EntityPrototype.ID == recipeSolid.Key)
{
Storage.Remove(item);
_entities.DeleteEntity(item);
break;
}
}
}
}
}
private (FoodRecipePrototype, int) CanSatisfyRecipe(FoodRecipePrototype recipe, Dictionary<string, int> solids, Dictionary<string, FixedPoint2> reagents)
{
int portions = 0;
if(_currentCookTimerTime % recipe.CookTime != 0)
{
//can't be a multiple of this recipe
return (recipe, 0);
}
foreach (var solid in recipe.IngredientsSolids)
{
if (!solids.ContainsKey(solid.Key))
return (recipe, 0);
if (solids[solid.Key] < solid.Value)
return (recipe, 0);
else
portions = portions == 0 ? solids[solid.Key] / solid.Value.Int()
: Math.Min(portions, solids[solid.Key] / solid.Value.Int());
}
foreach (var reagent in recipe.IngredientsReagents)
{
if (!reagents.ContainsKey(reagent.Key))
return (recipe, 0);
if (reagents[reagent.Key] < reagent.Value)
return (recipe, 0);
else
portions = portions == 0 ? reagents[reagent.Key].Int() / reagent.Value.Int()
: Math.Min(portions, reagents[reagent.Key].Int() / reagent.Value.Int());
}
//cook only as many of those portions as time allows
return (recipe, (int)Math.Min(portions, _currentCookTimerTime / recipe.CookTime));
}
public void ClickSound()
{
SoundSystem.Play(_clickSound.GetSound(), Filter.Pvs(Owner), Owner, AudioParams.Default.WithVolume(-2f));
}
}
public sealed class BeingMicrowavedEvent : HandledEntityEventArgs

View File

@@ -1,45 +1,187 @@
using System.Linq;
using Content.Server.Chemistry.Components.SolutionManager;
using Content.Server.Chemistry.EntitySystems;
using Content.Server.Construction;
using Content.Server.Kitchen.Components;
using Content.Server.Popups;
using Content.Shared.Destructible;
using Content.Shared.Interaction;
using Content.Shared.Item;
using Content.Shared.Kitchen.Components;
using Robust.Shared.Player;
using JetBrains.Annotations;
using Content.Shared.Interaction.Events;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Content.Shared.Popups;
using Content.Server.Hands.Systems;
using Content.Server.Power.Components;
using Content.Server.Temperature.Components;
using Content.Server.Temperature.Systems;
using Content.Shared.FixedPoint;
using Content.Shared.Kitchen;
using Content.Shared.Popups;
using Content.Shared.Power;
using Content.Shared.Tag;
using Robust.Server.Containers;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
namespace Content.Server.Kitchen.EntitySystems
{
[UsedImplicitly]
internal sealed class MicrowaveSystem : EntitySystem
public sealed class MicrowaveSystem : EntitySystem
{
[Dependency] private readonly PopupSystem _popupSystem = default!;
[Dependency] private readonly ContainerSystem _container = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly RecipeManager _recipeManager = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedContainerSystem _sharedContainer = default!;
[Dependency] private readonly SolutionContainerSystem _solutionContainer = default!;
[Dependency] private readonly TagSystem _tag = default!;
[Dependency] private readonly TemperatureSystem _temperature = default!;
[Dependency] private readonly UserInterfaceSystem _userInterface = default!;
[Dependency] private readonly HandsSystem _handsSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<MicrowaveComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<MicrowaveComponent, SolutionChangedEvent>(OnSolutionChange);
SubscribeLocalEvent<MicrowaveComponent, InteractUsingEvent>(OnInteractUsing, after: new[]{typeof(AnchorableSystem)});
SubscribeLocalEvent<MicrowaveComponent, BreakageEventArgs>(OnBreak);
SubscribeLocalEvent<MicrowaveComponent, PowerChangedEvent>(OnPowerChanged);
SubscribeLocalEvent<MicrowaveComponent, SuicideEvent>(OnSuicide);
SubscribeLocalEvent<MicrowaveComponent, MicrowaveStartCookMessage>((u,c,_) => Wzhzhzh(u,c));
SubscribeLocalEvent<MicrowaveComponent, MicrowaveEjectMessage>(OnEjectMessage);
SubscribeLocalEvent<MicrowaveComponent, MicrowaveEjectSolidIndexedMessage>(OnEjectIndex);
SubscribeLocalEvent<MicrowaveComponent, MicrowaveSelectCookTimeMessage>(OnSelectTime);
SubscribeLocalEvent<ActiveMicrowaveComponent, ComponentStartup>(OnCookStart);
SubscribeLocalEvent<ActiveMicrowaveComponent, ComponentShutdown>(OnCookStop);
}
private void OnCookStart(EntityUid uid, ActiveMicrowaveComponent component, ComponentStartup args)
{
if (!TryComp<MicrowaveComponent>(uid, out var microwaveComponent))
return;
SetAppearance(microwaveComponent, MicrowaveVisualState.Cooking);
microwaveComponent.PlayingStream =
_audio.Play(microwaveComponent.LoopingSound, Filter.Pvs(uid), uid, AudioParams.Default.WithLoop(true).WithMaxDistance(5));
}
private void OnCookStop(EntityUid uid, ActiveMicrowaveComponent component, ComponentShutdown args)
{
if (!TryComp<MicrowaveComponent>(uid, out var microwaveComponent))
return;
SetAppearance(microwaveComponent, MicrowaveVisualState.Idle);
microwaveComponent.PlayingStream?.Stop();
}
/// <summary>
/// Adds temperature to every item in the microwave,
/// based on the time it took to microwave.
/// </summary>
/// <param name="component">The microwave that is heating up.</param>
/// <param name="time">The time on the microwave, in seconds.</param>
private void AddTemperature(MicrowaveComponent component, float time)
{
foreach (var entity in component.Storage.ContainedEntities)
{
if (TryComp<TemperatureComponent>(entity, out var tempComp))
_temperature.ChangeHeat(entity, time / 10, false, tempComp);
if (!TryComp<SolutionContainerManagerComponent>(entity, out var solutions))
continue;
foreach (var (_, solution) in solutions.Solutions)
{
if (solution.Temperature > component.TemperatureUpperThreshold)
continue;
_solutionContainer.AddThermalEnergy(entity, solution, time / 10);
}
}
}
private void SubtractContents(MicrowaveComponent component, FoodRecipePrototype recipe)
{
var totalReagentsToRemove = new Dictionary<string, FixedPoint2>(recipe.IngredientsReagents);
// this is spaghetti ngl
foreach (var item in component.Storage.ContainedEntities)
{
if (!TryComp<SolutionContainerManagerComponent>(item, out var solMan))
continue;
// go over every solution
foreach (var (_, solution) in solMan.Solutions)
{
foreach (var (reagent, _) in recipe.IngredientsReagents)
{
// removed everything
if (!totalReagentsToRemove.ContainsKey(reagent))
continue;
if (!solution.ContainsReagent(reagent))
continue;
var quant = solution.GetReagentQuantity(reagent);
if (quant >= totalReagentsToRemove[reagent])
{
quant = totalReagentsToRemove[reagent];
totalReagentsToRemove.Remove(reagent);
}
else
{
totalReagentsToRemove[reagent] -= quant;
}
_solutionContainer.TryRemoveReagent(item, solution, reagent, quant);
}
}
}
foreach (var recipeSolid in recipe.IngredientsSolids)
{
for (var i = 0; i < recipeSolid.Value; i++)
{
foreach (var item in component.Storage.ContainedEntities)
{
var metaData = MetaData(item);
if (metaData.EntityPrototype == null)
{
continue;
}
if (metaData.EntityPrototype.ID == recipeSolid.Key)
{
component.Storage.Remove(item);
EntityManager.DeleteEntity(item);
break;
}
}
}
}
}
private void OnInit(EntityUid uid, MicrowaveComponent component, ComponentInit ags)
{
component.Storage = _container.EnsureContainer<Container>(uid,"microwave_entity_container");
}
private void OnSuicide(EntityUid uid, MicrowaveComponent component, SuicideEvent args)
{
if (args.Handled) return;
if (args.Handled)
return;
args.SetHandled(SuicideKind.Heat);
var victim = args.Victim;
var headCount = 0;
if (TryComp<SharedBodyComponent?>(victim, out var body))
if (TryComp<SharedBodyComponent>(victim, out var body))
{
var headSlots = body.GetSlotsOfType(BodyPartType.Head);
@@ -69,36 +211,29 @@ namespace Content.Server.Kitchen.EntitySystems
? Loc.GetString("microwave-component-suicide-multi-head-others-message", ("victim", victim))
: Loc.GetString("microwave-component-suicide-others-message", ("victim", victim));
victim.PopupMessageOtherClients(othersMessage);
var selfMessage = headCount > 1
? Loc.GetString("microwave-component-suicide-multi-head-message")
: Loc.GetString("microwave-component-suicide-message");
victim.PopupMessage(selfMessage);
component.ClickSound();
component.SetCookTime(10);
component.Wzhzhzh();
_popupSystem.PopupEntity(othersMessage, victim, Filter.PvsExcept(victim));
_popupSystem.PopupEntity(selfMessage, victim, Filter.Entities(victim));
_audio.PlayPvs(component.ClickSound, uid, AudioParams.Default.WithVolume(-2));
component.CurrentCookTimerTime = 10;
Wzhzhzh(uid, component);
UpdateUserInterfaceState(uid, component);
}
private void OnSolutionChange(EntityUid uid, MicrowaveComponent component, SolutionChangedEvent args)
{
component.DirtyUi();
}
public override void Update(float frameTime)
{
base.Update(frameTime);
foreach (var comp in EntityManager.EntityQuery<MicrowaveComponent>())
{
comp.OnUpdate();
}
UpdateUserInterfaceState(uid, component);
}
private void OnInteractUsing(EntityUid uid, MicrowaveComponent component, InteractUsingEvent args)
{
if(args.Handled) return;
if (!component.Powered)
if(args.Handled)
return;
if (!(TryComp<ApcPowerReceiverComponent>(uid, out var apc) && apc.Powered))
{
_popupSystem.PopupEntity(Loc.GetString("microwave-component-interact-using-no-power"), uid, Filter.Entities(args.User));
return;
@@ -118,13 +253,236 @@ namespace Content.Server.Kitchen.EntitySystems
args.Handled = true;
_handsSystem.TryDropIntoContainer(args.User, args.Used, component.Storage);
component.DirtyUi();
UpdateUserInterfaceState(uid, component);
}
private void OnBreak(EntityUid uid, MicrowaveComponent component, BreakageEventArgs args)
{
component.Broken = true;
component.SetAppearance(MicrowaveVisualState.Broken);
SetAppearance(component, MicrowaveVisualState.Broken);
RemComp<ActiveMicrowaveComponent>(uid);
_sharedContainer.EmptyContainer(component.Storage);
UpdateUserInterfaceState(uid, component);
}
private void OnPowerChanged(EntityUid uid, MicrowaveComponent component, PowerChangedEvent args)
{
if (!args.Powered)
{
SetAppearance(component, MicrowaveVisualState.Idle);
RemComp<ActiveMicrowaveComponent>(uid);
_sharedContainer.EmptyContainer(component.Storage);
}
UpdateUserInterfaceState(uid, component);
}
public void UpdateUserInterfaceState(EntityUid uid, MicrowaveComponent component)
{
var ui = _userInterface.GetUiOrNull(uid, MicrowaveUiKey.Key);
if (ui == null)
return;
var state = new MicrowaveUpdateUserInterfaceState(
component.Storage.ContainedEntities.ToArray(),
HasComp<ActiveMicrowaveComponent>(uid),
component.CurrentCookTimeButtonIndex,
component.CurrentCookTimerTime
);
_userInterface.SetUiState(ui, state);
}
public void SetAppearance(MicrowaveComponent component, MicrowaveVisualState state)
{
var display = component.Broken ? MicrowaveVisualState.Broken : state;
_appearance.SetData(component.Owner, PowerDeviceVisuals.VisualState, display);
}
public bool HasContents(MicrowaveComponent component)
{
return component.Storage.ContainedEntities.Any();
}
/// <summary>
/// Starts Cooking
/// </summary>
/// <remarks>
/// It does not make a "wzhzhzh" sound, it makes a "mmmmmmmm" sound!
/// -emo
/// </remarks>
public void Wzhzhzh(EntityUid uid, MicrowaveComponent component)
{
if (!HasContents(component) || HasComp<ActiveMicrowaveComponent>(uid))
return;
var solidsDict = new Dictionary<string, int>();
var reagentDict = new Dictionary<string, FixedPoint2>();
foreach (var item in component.Storage.ContainedEntities)
{
// special behavior when being microwaved ;)
var ev = new BeingMicrowavedEvent(uid);
RaiseLocalEvent(item, ev);
if (ev.Handled)
{
UpdateUserInterfaceState(uid, component);
return;
}
// destroy microwave
if (_tag.HasTag(item, "MicrowaveMachineUnsafe") || _tag.HasTag(item, "Metal"))
{
component.Broken = true;
SetAppearance(component, MicrowaveVisualState.Broken);
_audio.PlayPvs(component.ItemBreakSound, uid);
return;
}
if (_tag.HasTag(item, "MicrowaveSelfUnsafe") || _tag.HasTag(item, "Plastic"))
{
var junk = Spawn(component.BadRecipeEntityId, Transform(uid).Coordinates);
component.Storage.Insert(junk);
QueueDel(item);
}
var metaData = MetaData(item); //this simply begs for cooking refactor
if (metaData.EntityPrototype == null)
continue;
if (solidsDict.ContainsKey(metaData.EntityPrototype.ID))
{
solidsDict[metaData.EntityPrototype.ID]++;
}
else
{
solidsDict.Add(metaData.EntityPrototype.ID, 1);
}
if (!TryComp<SolutionContainerManagerComponent>(item, out var solMan))
continue;
foreach (var (_, solution) in solMan.Solutions)
{
foreach (var reagent in solution.Contents)
{
if (reagentDict.ContainsKey(reagent.ReagentId))
reagentDict[reagent.ReagentId] += reagent.Quantity;
else
reagentDict.Add(reagent.ReagentId, reagent.Quantity);
}
}
}
// Check recipes
var portionedRecipe = _recipeManager.Recipes.Select(r =>
CanSatisfyRecipe(component, r, solidsDict, reagentDict)).FirstOrDefault(r => r.Item2 > 0);
_audio.PlayPvs(component.StartCookingSound, uid);
var activeComp = AddComp<ActiveMicrowaveComponent>(uid); //microwave is now cooking
activeComp.CookTimeRemaining = component.CurrentCookTimerTime * component.CookTimeMultiplier;
activeComp.TotalTime = component.CurrentCookTimerTime * component.CookTimeMultiplier;
activeComp.PortionedRecipe = portionedRecipe;
UpdateUserInterfaceState(uid, component);
}
public (FoodRecipePrototype, int) CanSatisfyRecipe(MicrowaveComponent component, FoodRecipePrototype recipe, Dictionary<string, int> solids, Dictionary<string, FixedPoint2> reagents)
{
var portions = 0;
if(component.CurrentCookTimerTime % recipe.CookTime != 0)
{
//can't be a multiple of this recipe
return (recipe, 0);
}
foreach (var solid in recipe.IngredientsSolids)
{
if (!solids.ContainsKey(solid.Key))
return (recipe, 0);
if (solids[solid.Key] < solid.Value)
return (recipe, 0);
portions = portions == 0
? solids[solid.Key] / solid.Value.Int()
: Math.Min(portions, solids[solid.Key] / solid.Value.Int());
}
foreach (var reagent in recipe.IngredientsReagents)
{
if (!reagents.ContainsKey(reagent.Key))
return (recipe, 0);
if (reagents[reagent.Key] < reagent.Value)
return (recipe, 0);
portions = portions == 0
? reagents[reagent.Key].Int() / reagent.Value.Int()
: Math.Min(portions, reagents[reagent.Key].Int() / reagent.Value.Int());
}
//cook only as many of those portions as time allows
return (recipe, (int)Math.Min(portions, component.CurrentCookTimerTime / recipe.CookTime));
}
public override void Update(float frameTime)
{
base.Update(frameTime);
foreach (var (active, microwave) in EntityManager.EntityQuery<ActiveMicrowaveComponent, MicrowaveComponent>())
{
//check if there's still cook time left
active.CookTimeRemaining -= frameTime;
if (active.CookTimeRemaining > 0)
continue;
//this means the microwave has finished cooking.
AddTemperature(microwave, active.TotalTime);
if (active.PortionedRecipe.Item1 != null)
{
var coords = Transform(microwave.Owner).Coordinates;
for (var i = 0; i < active.PortionedRecipe.Item2; i++)
{
SubtractContents(microwave, active.PortionedRecipe.Item1);
Spawn(active.PortionedRecipe.Item1.Result, coords);
}
}
_sharedContainer.EmptyContainer(microwave.Storage);
UpdateUserInterfaceState(microwave.Owner, microwave);
EntityManager.RemoveComponentDeferred<ActiveMicrowaveComponent>(active.Owner);
_audio.PlayPvs(microwave.FoodDoneSound, microwave.Owner, AudioParams.Default.WithVolume(-1));
}
}
#region ui
private void OnEjectMessage(EntityUid uid, MicrowaveComponent component, MicrowaveEjectMessage args)
{
if (!HasContents(component) || HasComp<ActiveMicrowaveComponent>(uid))
return;
_sharedContainer.EmptyContainer(component.Storage);
_audio.PlayPvs(component.ClickSound, uid, AudioParams.Default.WithVolume(-2));
UpdateUserInterfaceState(uid, component);
}
private void OnEjectIndex(EntityUid uid, MicrowaveComponent component, MicrowaveEjectSolidIndexedMessage args)
{
if (!HasContents(component) || HasComp<ActiveMicrowaveComponent>(uid))
return;
component.Storage.Remove(args.EntityID);
UpdateUserInterfaceState(uid, component);
}
private void OnSelectTime(EntityUid uid, MicrowaveComponent component, MicrowaveSelectCookTimeMessage args)
{
if (!HasContents(component) || HasComp<ActiveMicrowaveComponent>(uid) || !(TryComp<ApcPowerReceiverComponent>(uid, out var apc) && apc.Powered))
return;
component.CurrentCookTimeButtonIndex = args.ButtonIndex;
component.CurrentCookTimerTime = args.NewCookTime;
_audio.PlayPvs(component.ClickSound, uid, AudioParams.Default.WithVolume(-2));
UpdateUserInterfaceState(uid, component);
}
#endregion
}
}