4 using System.Collections.Immutable;
8 using Microsoft.Xna.Framework;
12 internal partial class CircuitBoxComponent : CircuitBoxNode, ICircuitBoxIdentifiable
15 public ushort ID {
get; }
17 public readonly ItemPrefab UsedResource;
19 public CircuitBoxComponent(ushort
id,
Item item, Vector2 position, CircuitBox circuitBox, ItemPrefab usedResource): base(circuitBox)
21 if (item.Connections is
null)
23 throw new ArgumentNullException(nameof(item.Connections), $
"Tried to load a CircuitBoxNode with an item \"{item.Prefab.Name}\" that has no connections.");
26 var conns = item.Connections.Select(connection =>
new CircuitBoxNodeConnection(Vector2.Zero,
this, connection, circuitBox)).ToList();
28 Vector2 size = CalculateSize(conns);
33 Connectors = conns.Cast<CircuitBoxConnection>().ToImmutableArray();
35 UsedResource = usedResource;
39 public static Option<CircuitBoxComponent> TryLoadFromXML(ContentXElement element, CircuitBox circuitBox)
41 ushort
id = element.GetAttributeUInt16(
"id", ICircuitBoxIdentifiable.NullComponentID);
42 Vector2 position = element.GetAttributeVector2(
"position", Vector2.Zero);
43 var itemIdOption = ItemSlotIndexPair.TryDeserializeFromXML(element,
"backingitemid");
44 Identifier usedResourceIdentifier = element.GetAttributeIdentifier(
"usedresource", Identifier.Empty);
46 if (!itemIdOption.TryUnwrap(out var itemId) || itemId.FindItemInContainer(circuitBox.ComponentContainer) is not { } backingItem)
48 DebugConsole.ThrowErrorAndLogToGA(
"CircuitBoxComponent.TryLoadFromXML:IdNotFound",
49 $
"Failed to find item with ID {itemId} for CircuitBoxNode with ID {id}");
53 if (!ItemPrefab.Prefabs.TryGet(usedResourceIdentifier, out var usedResource))
55 DebugConsole.ThrowErrorAndLogToGA(
"CircuitBoxComponent.TryLoadXML:UsedResourceNotFound",
56 $
"Failed to find item prefab with identifier {usedResourceIdentifier} for CircuitBoxNode with ID {id}");
60 return Option.Some(
new CircuitBoxComponent(
id, backingItem, position, circuitBox, usedResource));
63 public XElement Save()
65 return new XElement(
"Component",
66 new XAttribute(
"id", ID),
67 new XAttribute(
"position", XMLExtensions.Vector2ToString(Position)),
68 new XAttribute(
"backingitemid", ItemSlotIndexPair.Serialize(
Item)),
69 new XAttribute(
"usedresource", UsedResource.Identifier));
74 if (Entity.Spawner is { } spawner && Screen.Selected is not { IsEditor: true })
76 spawner.AddEntityToRemoveQueue(
Item);