Client LuaCsForBarotrauma
ItemSlotIndexPair.cs
1 #nullable enable
2 
3 using System;
4 using System.Linq;
6 using Microsoft.Xna.Framework;
7 
8 namespace Barotrauma
9 {
10  internal readonly record struct ItemSlotIndexPair(int Slot, int StackIndex)
11  {
12  public static Option<ItemSlotIndexPair> TryDeserializeFromXML(ContentXElement element, string elementName)
13  {
14  string? elementStr = element.GetAttributeString(elementName, string.Empty);
15  if (string.IsNullOrEmpty(elementStr)) { return Option.None; }
16 
17  var point = XMLExtensions.ParsePoint(elementStr);
18  return Option.Some(new ItemSlotIndexPair(point.X, point.Y));
19  }
20 
21  public static string Serialize(Item item)
22  {
23  Inventory parent = item.ParentInventory;
24  if (item.ParentInventory is null)
25  {
26  throw new Exception($"Item \"{item.Name}\" is not in an inventory.");
27  }
28 
29  int slotIndex = parent.FindIndex(item);
30 
31  int stackIndex = parent.GetItemStackSlotIndex(item, slotIndex);
32 
33  if (slotIndex < 0 || stackIndex < 0)
34  {
35  throw new Exception($"Unable to find item \"{item.Name}\" in its parent inventory.");
36  }
37 
38  return XMLExtensions.PointToString(new Point(slotIndex, stackIndex));
39  }
40 
41  public Item? FindItemInContainer(ItemContainer? container)
42  {
43  var items = container?.Inventory.GetItemsAt(Slot);
44  if (items != null && StackIndex >= 0 && StackIndex < items.Count())
45  {
46  return items.ElementAt(StackIndex);
47  }
48  else
49  {
50  string errorMsg =
51  $"Circuit box error: failed to find an item in the container {container?.Item.Name ?? "null"}.";
52  DebugConsole.ThrowError(
53  errorMsg +
54  $" Items: {items?.Count().ToString() ?? "null"}, " +
55  $" Slot: {Slot}, StackIndex: {StackIndex}");
56  GameAnalyticsManager.AddErrorEventOnce("ItemSlotIndexPair.FindItemInContainer", GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
57  return null;
58  }
59  }
60  }
61 }
IEnumerable< Item > GetItemsAt(int index)
Get all the item stored in the specified inventory slot. Can return more than one item if the slot co...