Generalized Store System (#10201)
This commit is contained in:
127
Content.Server/Store/Systems/StoreSystem.Listings.cs
Normal file
127
Content.Server/Store/Systems/StoreSystem.Listings.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
using Content.Server.Store.Components;
|
||||
using Content.Shared.Store;
|
||||
|
||||
namespace Content.Server.Store.Systems;
|
||||
|
||||
public sealed partial class StoreSystem : EntitySystem
|
||||
{
|
||||
/// <summary>
|
||||
/// Refreshes all listings on a store.
|
||||
/// Do not use if you don't know what you're doing.
|
||||
/// </summary>
|
||||
/// <param name="component">The store to refresh</param>
|
||||
public void RefreshAllListings(StoreComponent component)
|
||||
{
|
||||
component.Listings = GetAllListings();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all listings from a prototype.
|
||||
/// </summary>
|
||||
/// <returns>All the listings</returns>
|
||||
public HashSet<ListingData> GetAllListings()
|
||||
{
|
||||
var allListings = _proto.EnumeratePrototypes<ListingPrototype>();
|
||||
|
||||
var allData = new HashSet<ListingData>();
|
||||
|
||||
foreach (var listing in allListings)
|
||||
allData.Add(listing);
|
||||
|
||||
return allData;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a listing from an Id to a store
|
||||
/// </summary>
|
||||
/// <param name="component">The store to add the listing to</param>
|
||||
/// <param name="listingId">The id of the listing</param>
|
||||
/// <returns>Whetehr or not the listing was added successfully</returns>
|
||||
public bool TryAddListing(StoreComponent component, string listingId)
|
||||
{
|
||||
if (!_proto.TryIndex<ListingPrototype>(listingId, out var proto))
|
||||
{
|
||||
Logger.Error("Attempted to add invalid listing.");
|
||||
return false;
|
||||
}
|
||||
return TryAddListing(component, proto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a listing to a store
|
||||
/// </summary>
|
||||
/// <param name="component">The store to add the listing to</param>
|
||||
/// <param name="listing">The listing</param>
|
||||
/// <returns>Whether or not the listing was add successfully</returns>
|
||||
public bool TryAddListing(StoreComponent component, ListingData listing)
|
||||
{
|
||||
return component.Listings.Add(listing);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the available listings for a store
|
||||
/// </summary>
|
||||
/// <param name="user">The person getting the listings.</param>
|
||||
/// <param name="component">The store the listings are coming from.</param>
|
||||
/// <returns>The available listings.</returns>
|
||||
public IEnumerable<ListingData> GetAvailableListings(EntityUid user, StoreComponent component)
|
||||
{
|
||||
return GetAvailableListings(user, component.Listings, component.Categories, component.Owner);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the available listings for a user given an overall set of listings and categories to filter by.
|
||||
/// </summary>
|
||||
/// <param name="user">The person getting the listings.</param>
|
||||
/// <param name="listings">All of the listings that are available. If null, will just get all listings from the prototypes.</param>
|
||||
/// <param name="categories">What categories to filter by.</param>
|
||||
/// <param name="storeEntity">The physial entity of the store. Can be null.</param>
|
||||
/// <returns>The available listings.</returns>
|
||||
public IEnumerable<ListingData> GetAvailableListings(EntityUid user, HashSet<ListingData>? listings, HashSet<string> categories, EntityUid? storeEntity = null)
|
||||
{
|
||||
if (listings == null)
|
||||
listings = GetAllListings();
|
||||
|
||||
foreach (var listing in listings)
|
||||
{
|
||||
if (!ListingHasCategory(listing, categories))
|
||||
continue;
|
||||
|
||||
if (listing.Conditions != null)
|
||||
{
|
||||
var args = new ListingConditionArgs(user, storeEntity, listing, EntityManager);
|
||||
var conditionsMet = true;
|
||||
|
||||
foreach (var condition in listing.Conditions)
|
||||
{
|
||||
if (!condition.Condition(args))
|
||||
{
|
||||
conditionsMet = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!conditionsMet)
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return listing;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a listing appears in a list of given categories
|
||||
/// </summary>
|
||||
/// <param name="listing">The listing itself.</param>
|
||||
/// <param name="categories">The categories to check through.</param>
|
||||
/// <returns>If the listing was present in one of the categories.</returns>
|
||||
public bool ListingHasCategory(ListingData listing, HashSet<string> categories)
|
||||
{
|
||||
foreach (var cat in categories)
|
||||
{
|
||||
if (listing.Categories.Contains(cat))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
226
Content.Server/Store/Systems/StoreSystem.Ui.cs
Normal file
226
Content.Server/Store/Systems/StoreSystem.Ui.cs
Normal file
@@ -0,0 +1,226 @@
|
||||
using Content.Server.Actions;
|
||||
using Content.Server.Administration.Logs;
|
||||
using Content.Server.Mind.Components;
|
||||
using Content.Server.Store.Components;
|
||||
using Content.Server.UserInterface;
|
||||
using Content.Shared.Actions.ActionTypes;
|
||||
using Content.Shared.FixedPoint;
|
||||
using Content.Shared.Hands.EntitySystems;
|
||||
using Content.Shared.Store;
|
||||
using Content.Shared.Database;
|
||||
using Robust.Server.GameObjects;
|
||||
using System.Linq;
|
||||
using Content.Server.Stack;
|
||||
using Content.Shared.Prototypes;
|
||||
using Robust.Shared.Player;
|
||||
using Robust.Shared.Prototypes;
|
||||
|
||||
namespace Content.Server.Store.Systems;
|
||||
|
||||
public sealed partial class StoreSystem : EntitySystem
|
||||
{
|
||||
[Dependency] private readonly IAdminLogManager _admin = default!;
|
||||
[Dependency] private readonly SharedHandsSystem _hands = default!;
|
||||
[Dependency] private readonly ActionsSystem _actions = default!;
|
||||
[Dependency] private readonly SharedAudioSystem _audio = default!;
|
||||
[Dependency] private readonly StackSystem _stack = default!;
|
||||
|
||||
private void InitializeUi()
|
||||
{
|
||||
SubscribeLocalEvent<StoreComponent, StoreRequestUpdateInterfaceMessage>((_,c,r) => UpdateUserInterface(r.CurrentBuyer, c));
|
||||
SubscribeLocalEvent<StoreComponent, StoreBuyListingMessage>(OnBuyRequest);
|
||||
SubscribeLocalEvent<StoreComponent, StoreRequestWithdrawMessage>(OnRequestWithdraw);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Toggles the store Ui open and closed
|
||||
/// </summary>
|
||||
/// <param name="user">the person doing the toggling</param>
|
||||
/// <param name="component">the store being toggled</param>
|
||||
public void ToggleUi(EntityUid user, StoreComponent component)
|
||||
{
|
||||
if (!TryComp<ActorComponent>(user, out var actor))
|
||||
return;
|
||||
|
||||
var ui = component.Owner.GetUIOrNull(StoreUiKey.Key);
|
||||
ui?.Toggle(actor.PlayerSession);
|
||||
|
||||
UpdateUserInterface(user, component, ui);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the user interface for a store and refreshes the listings
|
||||
/// </summary>
|
||||
/// <param name="user">The person who if opening the store ui. Listings are filtered based on this.</param>
|
||||
/// <param name="component">The store component being refreshed.</param>
|
||||
/// <param name="ui"></param>
|
||||
public void UpdateUserInterface(EntityUid? user, StoreComponent component, BoundUserInterface? ui = null)
|
||||
{
|
||||
if (ui == null)
|
||||
{
|
||||
ui = component.Owner.GetUIOrNull(StoreUiKey.Key);
|
||||
if (ui == null)
|
||||
{
|
||||
Logger.Error("No Ui key.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//if we haven't opened it before, initialize the shit
|
||||
if (!component.Opened)
|
||||
{
|
||||
InitializeFromPreset(component.Preset, component);
|
||||
component.Opened = true;
|
||||
}
|
||||
|
||||
//this is the person who will be passed into logic for all listing filtering.
|
||||
var buyer = user;
|
||||
if (buyer != null) //if we have no "buyer" for this update, then don't update the listings
|
||||
{
|
||||
if (component.AccountOwner != null) //if we have one stored, then use that instead
|
||||
buyer = component.AccountOwner.Value;
|
||||
|
||||
component.LastAvailableListings = GetAvailableListings(buyer.Value, component).ToHashSet();
|
||||
}
|
||||
|
||||
//dictionary for all currencies, including 0 values for currencies on the whitelist
|
||||
Dictionary<string, FixedPoint2> allCurrency = new();
|
||||
foreach (var supported in component.CurrencyWhitelist)
|
||||
{
|
||||
allCurrency.Add(supported, FixedPoint2.Zero);
|
||||
|
||||
if (component.Balance.ContainsKey(supported))
|
||||
allCurrency[supported] = component.Balance[supported];
|
||||
}
|
||||
|
||||
var state = new StoreUpdateState(buyer, component.LastAvailableListings, allCurrency);
|
||||
ui.SetState(state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles whenever a purchase was made.
|
||||
/// </summary>
|
||||
private void OnBuyRequest(EntityUid uid, StoreComponent component, StoreBuyListingMessage msg)
|
||||
{
|
||||
ListingData? listing = component.Listings.FirstOrDefault(x => x.Equals(msg.Listing));
|
||||
if (listing == null) //make sure this listing actually exists
|
||||
{
|
||||
Logger.Debug("listing does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
//verify that we can actually buy this listing and it wasn't added
|
||||
if (!ListingHasCategory(listing, component.Categories))
|
||||
return;
|
||||
//condition checking because why not
|
||||
if (listing.Conditions != null)
|
||||
{
|
||||
var args = new ListingConditionArgs(msg.Buyer, component.Owner, listing, EntityManager);
|
||||
var conditionsMet = true;
|
||||
|
||||
foreach (var condition in listing.Conditions.Where(condition => !condition.Condition(args)))
|
||||
conditionsMet = false;
|
||||
|
||||
if (!conditionsMet)
|
||||
return;
|
||||
}
|
||||
|
||||
//check that we have enough money
|
||||
foreach (var currency in listing.Cost)
|
||||
{
|
||||
if (!component.Balance.TryGetValue(currency.Key, out var balance) || balance < currency.Value)
|
||||
{
|
||||
_audio.Play(component.InsufficientFundsSound, Filter.SinglePlayer(msg.Session), uid);
|
||||
return;
|
||||
}
|
||||
}
|
||||
//subtract the cash
|
||||
foreach (var currency in listing.Cost)
|
||||
component.Balance[currency.Key] -= currency.Value;
|
||||
|
||||
//spawn entity
|
||||
if (listing.ProductEntity != null)
|
||||
{
|
||||
var product = Spawn(listing.ProductEntity, Transform(msg.Buyer).Coordinates);
|
||||
_hands.TryPickupAnyHand(msg.Buyer, product);
|
||||
}
|
||||
|
||||
//give action
|
||||
if (listing.ProductAction != null)
|
||||
{
|
||||
var action = new InstantAction(_proto.Index<InstantActionPrototype>(listing.ProductAction));
|
||||
_actions.AddAction(msg.Buyer, action, null);
|
||||
}
|
||||
|
||||
//broadcast event
|
||||
if (listing.ProductEvent != null)
|
||||
{
|
||||
RaiseLocalEvent(listing.ProductEvent);
|
||||
}
|
||||
|
||||
//log dat shit.
|
||||
if (TryComp<MindComponent>(msg.Buyer, out var mind))
|
||||
{
|
||||
_admin.Add(LogType.StorePurchase, LogImpact.Low,
|
||||
$"{ToPrettyString(mind.Owner):player} purchased listing \"{listing.Name}\" from {ToPrettyString(uid)}");
|
||||
}
|
||||
|
||||
listing.PurchaseAmount++; //track how many times something has been purchased
|
||||
_audio.Play(component.BuySuccessSound, Filter.SinglePlayer(msg.Session), uid); //cha-ching!
|
||||
|
||||
UpdateUserInterface(msg.Buyer, component);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles dispensing the currency you requested to be withdrawn.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This would need to be done should a currency with decimal values need to use it.
|
||||
/// not quite sure how to handle that
|
||||
/// </remarks>
|
||||
private void OnRequestWithdraw(EntityUid uid, StoreComponent component, StoreRequestWithdrawMessage msg)
|
||||
{
|
||||
//make sure we have enough cash in the bank and we actually support this currency
|
||||
if (!component.Balance.TryGetValue(msg.Currency, out var currentAmount) || currentAmount < msg.Amount)
|
||||
return;
|
||||
|
||||
//make sure a malicious client didn't send us random shit
|
||||
if (!_proto.TryIndex<CurrencyPrototype>(msg.Currency, out var proto))
|
||||
return;
|
||||
|
||||
//we need an actually valid entity to spawn. This check has been done earlier, but just in case.
|
||||
if (proto.EntityId == null || !proto.CanWithdraw)
|
||||
return;
|
||||
|
||||
var entproto = _proto.Index<EntityPrototype>(proto.EntityId);
|
||||
|
||||
var amountRemaining = msg.Amount;
|
||||
var coordinates = Transform(msg.Buyer).Coordinates;
|
||||
if (entproto.HasComponent<StackComponent>())
|
||||
{
|
||||
while (amountRemaining > 0)
|
||||
{
|
||||
var ent = Spawn(proto.EntityId, coordinates);
|
||||
var stackComponent = Comp<StackComponent>(ent); //we already know it exists
|
||||
|
||||
var amountPerStack = Math.Min(stackComponent.MaxCount, amountRemaining);
|
||||
|
||||
_stack.SetCount(ent, amountPerStack, stackComponent);
|
||||
amountRemaining -= amountPerStack;
|
||||
_hands.TryPickupAnyHand(msg.Buyer, ent);
|
||||
}
|
||||
}
|
||||
else //please for the love of christ give your currency stack component
|
||||
{
|
||||
while (amountRemaining > 0)
|
||||
{
|
||||
var ent = Spawn(proto.EntityId, coordinates);
|
||||
_hands.TryPickupAnyHand(msg.Buyer, ent);
|
||||
amountRemaining--;
|
||||
}
|
||||
}
|
||||
|
||||
component.Balance[msg.Currency] -= msg.Amount;
|
||||
UpdateUserInterface(msg.Buyer, component);
|
||||
}
|
||||
}
|
||||
154
Content.Server/Store/Systems/StoreSystem.cs
Normal file
154
Content.Server/Store/Systems/StoreSystem.cs
Normal file
@@ -0,0 +1,154 @@
|
||||
using Content.Server.Stack;
|
||||
using Content.Server.Store.Components;
|
||||
using Content.Shared.FixedPoint;
|
||||
using Content.Shared.Interaction;
|
||||
using Content.Shared.Popups;
|
||||
using Content.Shared.Store;
|
||||
using Robust.Shared.Player;
|
||||
using Robust.Shared.Prototypes;
|
||||
using System.Linq;
|
||||
using Content.Server.UserInterface;
|
||||
|
||||
namespace Content.Server.Store.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Manages general interactions with a store and different entities,
|
||||
/// getting listings for stores, and interfacing with the store UI.
|
||||
/// </summary>
|
||||
public sealed partial class StoreSystem : EntitySystem
|
||||
{
|
||||
[Dependency] private readonly IPrototypeManager _proto = default!;
|
||||
[Dependency] private readonly SharedPopupSystem _popup = default!;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
|
||||
SubscribeLocalEvent<CurrencyComponent, AfterInteractEvent>(OnAfterInteract);
|
||||
SubscribeLocalEvent<StoreComponent, BeforeActivatableUIOpenEvent>((_,c,a) => UpdateUserInterface(a.User, c));
|
||||
|
||||
SubscribeLocalEvent<StoreComponent, ComponentStartup>(OnStartup);
|
||||
SubscribeLocalEvent<StoreComponent, ComponentShutdown>(OnShutdown);
|
||||
|
||||
InitializeUi();
|
||||
}
|
||||
|
||||
private void OnStartup(EntityUid uid, StoreComponent component, ComponentStartup args)
|
||||
{
|
||||
RaiseLocalEvent(uid, new StoreAddedEvent(), true);
|
||||
}
|
||||
|
||||
private void OnShutdown(EntityUid uid, StoreComponent component, ComponentShutdown args)
|
||||
{
|
||||
RaiseLocalEvent(uid, new StoreRemovedEvent(), true);
|
||||
}
|
||||
|
||||
private void OnAfterInteract(EntityUid uid, CurrencyComponent component, AfterInteractEvent args)
|
||||
{
|
||||
if (args.Handled || !args.CanReach)
|
||||
return;
|
||||
|
||||
if (args.Target == null || !TryComp<StoreComponent>(args.Target, out var store))
|
||||
return;
|
||||
|
||||
//if you somehow are inserting cash before the store initializes.
|
||||
if (!store.Opened)
|
||||
{
|
||||
InitializeFromPreset(store.Preset, store);
|
||||
store.Opened = true;
|
||||
}
|
||||
|
||||
args.Handled = TryAddCurrency(GetCurrencyValue(component), store);
|
||||
|
||||
if (args.Handled)
|
||||
{
|
||||
var msg = Loc.GetString("store-currency-inserted", ("used", args.Used), ("target", args.Target));
|
||||
_popup.PopupEntity(msg, args.Target.Value, Filter.Pvs(args.Target.Value));
|
||||
QueueDel(args.Used);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value from an entity's currency component.
|
||||
/// Scales with stacks.
|
||||
/// </summary>
|
||||
/// <param name="component"></param>
|
||||
/// <returns>The value of the currency</returns>
|
||||
public Dictionary<string, FixedPoint2> GetCurrencyValue(CurrencyComponent component)
|
||||
{
|
||||
TryComp<StackComponent>(component.Owner, out var stack);
|
||||
var amount = stack?.Count ?? 1;
|
||||
|
||||
return component.Price.ToDictionary(v => v.Key, p => p.Value * amount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to add a currency to a store's balance.
|
||||
/// </summary>
|
||||
/// <param name="component">The currency to add</param>
|
||||
/// <param name="store">The store to add it to</param>
|
||||
/// <returns>Whether or not the currency was succesfully added</returns>
|
||||
public bool TryAddCurrency(CurrencyComponent component, StoreComponent store)
|
||||
{
|
||||
return TryAddCurrency(GetCurrencyValue(component), store);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to add a currency to a store's balance
|
||||
/// </summary>
|
||||
/// <param name="currency">The value to add to the store</param>
|
||||
/// <param name="store">The store to add it to</param>
|
||||
/// <returns>Whether or not the currency was succesfully added</returns>
|
||||
public bool TryAddCurrency(Dictionary<string, FixedPoint2> currency, StoreComponent store)
|
||||
{
|
||||
//verify these before values are modified
|
||||
foreach (var type in currency)
|
||||
{
|
||||
if (!store.CurrencyWhitelist.Contains(type.Key))
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var type in currency)
|
||||
{
|
||||
if (!store.Balance.TryAdd(type.Key, type.Value))
|
||||
store.Balance[type.Key] += type.Value;
|
||||
}
|
||||
|
||||
UpdateUserInterface(null, store);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a store based on a preset ID
|
||||
/// </summary>
|
||||
/// <param name="preset">The ID of a store preset prototype</param>
|
||||
/// <param name="component">The store being initialized</param>
|
||||
public void InitializeFromPreset(string? preset, StoreComponent component)
|
||||
{
|
||||
if (preset == null)
|
||||
return;
|
||||
|
||||
if (!_proto.TryIndex<StorePresetPrototype>(preset, out var proto))
|
||||
return;
|
||||
|
||||
InitializeFromPreset(proto, component);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a store based on a given preset
|
||||
/// </summary>
|
||||
/// <param name="preset">The StorePresetPrototype</param>
|
||||
/// <param name="component">The store being initialized</param>
|
||||
public void InitializeFromPreset(StorePresetPrototype preset, StoreComponent component)
|
||||
{
|
||||
RefreshAllListings(component);
|
||||
component.Preset = preset.ID;
|
||||
component.CurrencyWhitelist.UnionWith(preset.CurrencyWhitelist);
|
||||
component.Categories.UnionWith(preset.Categories);
|
||||
if (component.Balance == new Dictionary<string, FixedPoint2>() && preset.InitialBalance != null) //if we don't have a value stored, use the preset
|
||||
TryAddCurrency(preset.InitialBalance, component);
|
||||
|
||||
var ui = component.Owner.GetUIOrNull(StoreUiKey.Key);
|
||||
ui?.SetState(new StoreInitializeState(preset.StoreName));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user