From 43f33546a38474c216776db172578b3f47858536 Mon Sep 17 00:00:00 2001 From: hyperion51 Date: Fri, 5 Jun 2020 04:16:33 +0100 Subject: [PATCH] Inventory Refactoring Massively refactored everything related to entity inventory management We are no longer recalculating mass by iterating over the entire inventory any time anything changes, for example Gear is explicitly associated with hardpoints in the entity code This did introduce some bugs, will clean those up tomorrow --- Assets/Prefabs/Property Label.prefab | 12 +- Assets/Scripts/ServerShared/Agents/Aim.cs | 12 +- .../Scripts/ServerShared/Agents/Locomotion.cs | 16 +- .../ServerShared/Agents/VelocityMatch.cs | 12 +- .../ServerShared/Behaviors/Behaviors.cs | 2 +- .../ServerShared/Behaviors/FactoryBehavior.cs | 48 +- .../Behaviors/MiningController.cs | 23 +- .../ServerShared/Behaviors/StatModifier.cs | 10 +- .../Behaviors/SurveyController.cs | 4 +- .../ServerShared/Behaviors/Thruster.cs | 11 +- .../Scripts/ServerShared/Behaviors/Turning.cs | 11 +- Assets/Scripts/ServerShared/BlueprintData.cs | 27 +- Assets/Scripts/ServerShared/Entity.cs | 611 ++++++++++-------- Assets/Scripts/ServerShared/GameContext.cs | 217 +++---- Assets/Scripts/ServerShared/ItemInstance.cs | 15 +- Assets/Scripts/ServerShared/OrbitalEntity.cs | 2 +- Assets/Scripts/ServerShared/Ship.cs | 4 +- Assets/Scripts/StrategyGameManager.cs | 21 +- Assets/Scripts/TechTreeMsagl.cs | 2 +- Assets/Scripts/UI/ColonyTab.cs | 282 ++++---- Assets/Scripts/UI/PropertiesPanel.cs | 39 +- Assets/Scripts/UI/PropertyLabel.cs | 4 +- 22 files changed, 702 insertions(+), 683 deletions(-) diff --git a/Assets/Prefabs/Property Label.prefab b/Assets/Prefabs/Property Label.prefab index ec4f195b7..ad8e5a5ed 100644 --- a/Assets/Prefabs/Property Label.prefab +++ b/Assets/Prefabs/Property Label.prefab @@ -111,7 +111,7 @@ MonoBehaviour: m_enableWordWrapping: 1 m_wordWrappingRatios: 0.4 m_overflowMode: 0 - m_firstOverflowCharacterIndex: -1 + m_firstOverflowCharacterIndex: 0 m_linkedTextComponent: {fileID: 0} m_isLinkedTextComponent: 0 m_isTextTruncated: 0 @@ -140,7 +140,7 @@ MonoBehaviour: spaceCount: 14 wordCount: 15 linkCount: 0 - lineCount: 3 + lineCount: 64 pageCount: 1 materialCount: 1 m_isUsingLegacyAnimationComponent: 0 @@ -232,9 +232,9 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: b403db1d8980f544099fedf5735cf364, type: 3} m_Name: m_EditorClassIdentifier: - Name: {fileID: 2677123916028371620} - Value: {fileID: 1120484356114752953} + Label: {fileID: 2677123916028371620} Button: {fileID: 5626264982920981796} + Value: {fileID: 1120484356114752953} --- !u!222 &7959015954088891046 CanvasRenderer: m_ObjectHideFlags: 0 @@ -397,7 +397,7 @@ MonoBehaviour: m_enableWordWrapping: 1 m_wordWrappingRatios: 0.4 m_overflowMode: 0 - m_firstOverflowCharacterIndex: -1 + m_firstOverflowCharacterIndex: 0 m_linkedTextComponent: {fileID: 0} m_isLinkedTextComponent: 0 m_isTextTruncated: 0 @@ -426,7 +426,7 @@ MonoBehaviour: spaceCount: 0 wordCount: 1 linkCount: 0 - lineCount: 1 + lineCount: 9 pageCount: 1 materialCount: 1 m_isUsingLegacyAnimationComponent: 0 diff --git a/Assets/Scripts/ServerShared/Agents/Aim.cs b/Assets/Scripts/ServerShared/Agents/Aim.cs index 644f8dd36..f3c7e177b 100644 --- a/Assets/Scripts/ServerShared/Agents/Aim.cs +++ b/Assets/Scripts/ServerShared/Agents/Aim.cs @@ -11,24 +11,20 @@ public class Aim : AgentBehavior private Thruster _thrust; private Turning _turning; private VelocityLimit _velocityLimit; - private int _thrustAxis; - private int _turningAxis; public Aim(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData) { _velocityLimit = Entity.GetBehaviors().FirstOrDefault(); - _thrust = Entity.GetBehaviors().FirstOrDefault(); - _turning = Entity.GetBehaviors().FirstOrDefault(); - _thrustAxis = Entity.GetAxis(); - _turningAxis = Entity.GetAxis(); + _thrust = Entity.GetBehavior(); + _turning = Entity.GetBehavior(); } public override void Update(float delta) { if (_thrust != null && _turning != null) { float2 diff = Objective - Entity.Position; - Entity.Axes[_turningAxis].Value = TurningInput(diff); - Entity.Axes[_thrustAxis].Value = 0; + _turning.Axis = TurningInput(diff); + _thrust.Axis = 0; } } } diff --git a/Assets/Scripts/ServerShared/Agents/Locomotion.cs b/Assets/Scripts/ServerShared/Agents/Locomotion.cs index 7e6d3e9ec..ff388e2bd 100644 --- a/Assets/Scripts/ServerShared/Agents/Locomotion.cs +++ b/Assets/Scripts/ServerShared/Agents/Locomotion.cs @@ -13,16 +13,12 @@ public class Locomotion : AgentBehavior private Thruster _thrust; private Turning _turning; private VelocityLimit _velocityLimit; - private int _thrustAxis; - private int _turningAxis; public Locomotion(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData) { _velocityLimit = Entity.GetBehaviors().FirstOrDefault(); - _thrust = Entity.GetBehaviors().FirstOrDefault(); - _turning = Entity.GetBehaviors().FirstOrDefault(); - _thrustAxis = Entity.GetAxis(); - _turningAxis = Entity.GetAxis(); + _thrust = Entity.GetBehavior(); + _turning = Entity.GetBehavior(); } public override void Update(float delta) @@ -43,15 +39,15 @@ public class Locomotion : AgentBehavior { float2 tangential = Entity.Velocity - dot(normalize(diff), normalize(Entity.Velocity)) * Entity.Velocity; float2 adjustedDirection = normalize(diff) - tangential * TangentSensitivity; - Entity.Axes[_turningAxis].Value = TurningInput(adjustedDirection); - Entity.Axes[_thrustAxis].Value = 1; + _turning.Axis = TurningInput(adjustedDirection); + _thrust.Axis = 1; } // We have plenty of space, use exact maneuvering else { var deltaV = desiredVelocity - Entity.Velocity; - Entity.Axes[_turningAxis].Value = TurningInput(deltaV); - Entity.Axes[_thrustAxis].Value = ThrustInput(deltaV); + _turning.Axis = TurningInput(deltaV); + _thrust.Axis = ThrustInput(deltaV); } } } diff --git a/Assets/Scripts/ServerShared/Agents/VelocityMatch.cs b/Assets/Scripts/ServerShared/Agents/VelocityMatch.cs index 28508d7c7..b61c673c3 100644 --- a/Assets/Scripts/ServerShared/Agents/VelocityMatch.cs +++ b/Assets/Scripts/ServerShared/Agents/VelocityMatch.cs @@ -12,18 +12,14 @@ public class VelocityMatch : AgentBehavior private Thruster _thrust; private Turning _turning; private const float TargetThreshold = .1f; - private int _thrustAxis; - private int _turningAxis; private GameContext _context; public VelocityMatch(GameContext context, Entity entity, ControllerData controllerData) : base(context, entity, controllerData) { _context = context; - _thrust = Entity.GetBehaviors().FirstOrDefault(); - _turning = Entity.GetBehaviors().FirstOrDefault(); - _thrustAxis = Entity.GetAxis(); - _turningAxis = Entity.GetAxis(); + _thrust = Entity.GetBehavior(); + _turning = Entity.GetBehavior(); } public void Clear() @@ -38,8 +34,8 @@ public class VelocityMatch : AgentBehavior var deltaV = TargetVelocity - Entity.Velocity; if(length(deltaV) < TargetThreshold) OnMatch?.Invoke(); - Entity.Axes[_turningAxis].Value = TurningInput(deltaV); - Entity.Axes[_thrustAxis].Value = ThrustInput(deltaV); + _turning.Axis = TurningInput(deltaV); + _thrust.Axis = ThrustInput(deltaV); } } diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 4ab66df32..e8b6e7425 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -23,7 +23,7 @@ public interface IBehavior public interface IAnalogBehavior : IBehavior { - void SetAxis(float value); + float Axis { get; set; } } public interface IDisposableBehavior diff --git a/Assets/Scripts/ServerShared/Behaviors/FactoryBehavior.cs b/Assets/Scripts/ServerShared/Behaviors/FactoryBehavior.cs index 84855a45d..7ac9f32cf 100644 --- a/Assets/Scripts/ServerShared/Behaviors/FactoryBehavior.cs +++ b/Assets/Scripts/ServerShared/Behaviors/FactoryBehavior.cs @@ -27,7 +27,7 @@ public class Factory : IBehavior, IPersistentBehavior public float ProductionQuality; public double RetoolingTime; public string ItemName; - public List ItemsUnderConstruction = new List(); + public Guid ItemUnderConstruction; public Entity Entity { get; } public Gear Item { get; } @@ -47,20 +47,21 @@ public class Factory : IBehavior, IPersistentBehavior _blueprint = value; RetoolingTime = ToolingTime; _retooling = true; - OnToolingUpdate?.Invoke(); - OnToolingUpdate = null; + OnProductionUpdate?.Invoke(); + OnProductionUpdate = null; ItemName = Context.Cache.Get(value).Name; } } } - public event Action OnToolingUpdate; + public event Action OnProductionUpdate; private FactoryData _data; private Guid _blueprint; private int _assignedPopulation; private bool _retooling = false; + private float _currentProductionQuality; public Factory(GameContext context, FactoryData data, Entity entity, Gear item) { @@ -86,40 +87,37 @@ public class Factory : IBehavior, IPersistentBehavior if (_retooling) { _retooling = false; - OnToolingUpdate?.Invoke(); - OnToolingUpdate = null; + OnProductionUpdate?.Invoke(); } - if (ItemsUnderConstruction.Any()) + if (ItemUnderConstruction != Guid.Empty) { - var finishedConstruction = false; - foreach (var item in ItemsUnderConstruction.ToArray()) + Entity.IncompleteCargo[ItemUnderConstruction] = + Entity.IncompleteCargo[ItemUnderConstruction] - delta * (_assignedPopulation + _data.AutomationPoints) / + pow(lerp(blueprint.QualityFloor, 1, saturate(_currentProductionQuality)), + blueprint.ProductionExponent); + + if(Entity.IncompleteCargo[ItemUnderConstruction] < 0) { - Entity.IncompleteCargo[item] = - Entity.IncompleteCargo[item] - delta * (_assignedPopulation + _data.AutomationPoints) / - pow(lerp(blueprint.QualityFloor, 1, saturate(ProductionQuality)), - blueprint.ProductionExponent); - if(Entity.IncompleteCargo[item] < 0) - { - Entity.Cargo.Add(item); - Entity.IncompleteCargo.Remove(item); - ItemsUnderConstruction.Remove(item); - finishedConstruction = true; - } + var item = Context.Cache.Get(ItemUnderConstruction); + if (item is SimpleCommodity simpleCommodity) + Entity.AddCargo(simpleCommodity); + else if (item is CraftedItemInstance craftedItemInstance) + Entity.AddCargo(craftedItemInstance); + Entity.IncompleteCargo.Remove(ItemUnderConstruction); + ItemUnderConstruction = Guid.Empty; } - if(finishedConstruction) - Entity.RecalculateMass(); return true; } // Applying exponents to two random numbers and adding them produces a range of interesting probability distributions for quality - ItemsUnderConstruction = Entity.Build(blueprint, blueprint.Quality * + ItemUnderConstruction = Entity.Build(blueprint, blueprint.Quality * pow(ProductionQuality, blueprint.QualityExponent) * (pow(Context.Random.NextFloat(), blueprint.RandomExponent) + pow(Context.Random.NextFloat(), blueprint.RandomExponent)) / 2, ItemName); - if(ItemsUnderConstruction.Any()) - Entity.RecalculateMass(); // TODO: FIX THIS UGLY HACK, needed to update UI + + OnProductionUpdate?.Invoke(); return false; } diff --git a/Assets/Scripts/ServerShared/Behaviors/MiningController.cs b/Assets/Scripts/ServerShared/Behaviors/MiningController.cs index 897f6ac15..f3e4785a4 100644 --- a/Assets/Scripts/ServerShared/Behaviors/MiningController.cs +++ b/Assets/Scripts/ServerShared/Behaviors/MiningController.cs @@ -40,8 +40,8 @@ public class MiningController : ControllerBase, IBehavior, IPersistentBehavior, public new void Initialize() { - _miningTool = _entity.GetBehaviors().First(); - _toolSwitch = _entity.GetSwitch(_miningTool); + _miningTool = _entity.GetBehavior(); + _toolSwitch = _entity.GetSwitch(); base.Initialize(); } @@ -96,11 +96,22 @@ public class MiningController : ControllerBase, IBehavior, IPersistentBehavior, private void OnArriveHome() { var homeEntity = _context.Cache.Get(HomeEntity); - if (!_entity.Cargo.ToArray().All(ii => _context.MoveCargo(_entity, homeEntity, _context.Cache.Get(ii)))) + foreach (var item in _entity.Cargo + .Select(id => _context.Cache.Get(id)) + .Where(item => item is SimpleCommodity) + .Cast()) { - homeEntity.SetMessage("Colony is out of cargo space. Closing Mining Task."); - FinishTask(); - _taskStarted = false; + int supportedQuantity = (int) ((homeEntity.Capacity - homeEntity.OccupiedCapacity) / item.ItemData.Size); + var newItem = _entity.RemoveCargo(item, supportedQuantity); + homeEntity.AddCargo(newItem); + + if (supportedQuantity < item.Quantity) + { + homeEntity.SetMessage("Colony is out of cargo space. Closing Mining Task."); + FinishTask(); + _taskStarted = false; + return; + } } } diff --git a/Assets/Scripts/ServerShared/Behaviors/StatModifier.cs b/Assets/Scripts/ServerShared/Behaviors/StatModifier.cs index 351f0bb3f..8ea7e9f8f 100644 --- a/Assets/Scripts/ServerShared/Behaviors/StatModifier.cs +++ b/Assets/Scripts/ServerShared/Behaviors/StatModifier.cs @@ -54,15 +54,17 @@ public class StatModifier : IBehavior, IInitializableBehavior, IDisposableBehavi if (statField != null) { if (typeof(EquippableItemData).IsAssignableFrom(targetType)) - _stats = Entity.EquippedItems.Append(Entity.Hull) - .Select(id => Context.Cache.Get(id)) + _stats = Entity.Hardpoints + .Select(hp => hp.Gear) + .Where(gear => gear != null) .Where(gear => _data.RequireBehavior == null || gear.ItemData.Behaviors.Any(behavior => behavior.GetType() == _data.RequireBehavior)) .Where(gear => gear.ItemData.GetType() == targetType) .Select(gear => statField.GetValue(gear.ItemData) as PerformanceStat) .ToArray(); else - _stats = Entity.EquippedItems.Append(Entity.Hull) - .Select(id => Context.Cache.Get(id)) + _stats = Entity.Hardpoints + .Select(hp => hp.Gear) + .Where(gear => gear != null) .Where(gear => _data.RequireBehavior == null || gear.ItemData.Behaviors.Any(behavior => behavior.GetType() == _data.RequireBehavior)) .SelectMany(gear => gear.ItemData.Behaviors) .Where(behaviorData => behaviorData.GetType() == targetType) diff --git a/Assets/Scripts/ServerShared/Behaviors/SurveyController.cs b/Assets/Scripts/ServerShared/Behaviors/SurveyController.cs index f6e11516e..6df6c3709 100644 --- a/Assets/Scripts/ServerShared/Behaviors/SurveyController.cs +++ b/Assets/Scripts/ServerShared/Behaviors/SurveyController.cs @@ -42,8 +42,8 @@ public class SurveyController : ControllerBase, IBehavior, IPersistentBehavior, public new void Initialize() { - _scanningTool = _entity.GetBehaviors().First(); - _toolSwitch = _entity.GetSwitch(_scanningTool); + _scanningTool = _entity.GetBehavior(); + _toolSwitch = _entity.GetSwitch(); base.Initialize(); } diff --git a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs index 0b54de876..608e6e431 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs @@ -29,6 +29,12 @@ public class Thruster : IAnalogBehavior public float Thrust { get; private set; } + public float Axis + { + get => _input; + set => _input = saturate(value); + } + public BehaviorData Data => _data; private ThrusterData _data; @@ -42,11 +48,6 @@ public class Thruster : IAnalogBehavior Entity = entity; Item = item; } - - public void SetAxis(float value) - { - _input = saturate(value); - } public bool Update(float delta) { diff --git a/Assets/Scripts/ServerShared/Behaviors/Turning.cs b/Assets/Scripts/ServerShared/Behaviors/Turning.cs index d377ecff3..113e9d2bf 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Turning.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Turning.cs @@ -29,6 +29,12 @@ public class Turning : IAnalogBehavior public float Torque { get; private set; } + public float Axis + { + get => _input; + set => _input = clamp(value, -1, 1); + } + public BehaviorData Data => _data; private TurningData _data; @@ -42,11 +48,6 @@ public class Turning : IAnalogBehavior Entity = entity; Item = item; } - - public void SetAxis(float value) - { - _input = clamp(value, -1, 1); - } public void Initialize() { diff --git a/Assets/Scripts/ServerShared/BlueprintData.cs b/Assets/Scripts/ServerShared/BlueprintData.cs index d005213d0..4eb7d7184 100644 --- a/Assets/Scripts/ServerShared/BlueprintData.cs +++ b/Assets/Scripts/ServerShared/BlueprintData.cs @@ -18,43 +18,40 @@ public class BlueprintData : DatabaseEntry, INamedEntry [JsonProperty("item"), Key(3)] public Guid Item; - [InspectableField, JsonProperty("quantity"), Key(4)] - public int Quantity; - - [InspectableField, JsonProperty("productionTime"), Key(5)] + [InspectableField, JsonProperty("productionTime"), Key(4)] public float ProductionTime; - [InspectableField, JsonProperty("quality"), Key(6)] + [InspectableField, JsonProperty("quality"), Key(5)] public float Quality; - [InspectableField, JsonProperty("qualityExponent"), Key(7)] + [InspectableField, JsonProperty("qualityExponent"), Key(6)] public float QualityExponent = 1; - [InspectableField, JsonProperty("productionExponent"), Key(8)] + [InspectableField, JsonProperty("productionExponent"), Key(7)] public float ProductionExponent = 1; - [InspectableField, JsonProperty("randomExponent"), Key(9)] + [InspectableField, JsonProperty("randomExponent"), Key(8)] public float RandomExponent = 1; - [InspectableField, JsonProperty("qualityFloor"), Key(10)] + [InspectableField, JsonProperty("qualityFloor"), Key(9)] public float QualityFloor = .25f; - [InspectableField, JsonProperty("statEffects"), Key(11)] + [InspectableField, JsonProperty("statEffects"), Key(10)] public List StatEffects = new List(); - [InspectableField, JsonProperty("researchTime"), Key(12)] + [InspectableField, JsonProperty("researchTime"), Key(11)] public float ResearchTime; - [InspectableDatabaseLink(typeof(BlueprintData)), JsonProperty("researchDependencies"), Key(13)] + [InspectableDatabaseLink(typeof(BlueprintData)), JsonProperty("researchDependencies"), Key(12)] public List Dependencies = new List(); - [InspectableDatabaseLink(typeof(CraftedItemData)), JsonProperty("factoryItem"), Key(14)] + [InspectableDatabaseLink(typeof(CraftedItemData)), JsonProperty("factoryItem"), Key(13)] public Guid FactoryItem; - [InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("resourceRequirements"), Key(15)] + [InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("resourceRequirements"), Key(14)] public Dictionary ResourceRequirements = new Dictionary(); - [InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("productionProfile"), Key(16)] + [InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("productionProfile"), Key(15)] public Dictionary ProductionProfile = new Dictionary(); [IgnoreMember] public string EntryName diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index c27f266b9..2d87f58ca 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -31,10 +31,10 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR public float2 Velocity; [JsonProperty("cargo"), Key(6)] - public readonly List Cargo; // Type: ItemInstance - - [JsonProperty("equipment"), Key(7)] - public readonly List EquippedItems; // Type: Gear + public readonly HashSet Cargo; // Type: ItemInstance + + [JsonProperty("gear"), Key(7)] + public readonly List Gear; [JsonProperty("parent"), Key(8)] public Guid Parent; // Type: Entity @@ -64,25 +64,22 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR public Dictionary IncompleteGear = new Dictionary(); //public List IncompleteGear = new List(); - [JsonProperty("incompleteGear"), Key(17)] + [JsonProperty("incompleteCargo"), Key(17)] public Dictionary IncompleteCargo = new Dictionary(); //public List IncompleteCargo = new List(); - // [IgnoreMember] protected List Behaviors; [IgnoreMember] public Guid Zone; - [IgnoreMember] public Dictionary> Behaviors; - [IgnoreMember] public Dictionary Switches; - [IgnoreMember] public Dictionary Triggers; - [IgnoreMember] public Dictionary Axes; - [IgnoreMember] public Dictionary AxisOverrides = new Dictionary(); + [IgnoreMember] public List Hardpoints; [IgnoreMember] public readonly Dictionary VisibilitySources = new Dictionary(); [IgnoreMember] public readonly Dictionary Messages = new Dictionary(); - [IgnoreMember] public Dictionary GearData; - [IgnoreMember] public Dictionary> ItemBehaviors; + // [IgnoreMember] public Dictionary GearData; + // [IgnoreMember] public Dictionary> ItemBehaviors; + + private bool _inventoryChanged; [IgnoreMember] public float Mass { get; private set; } [IgnoreMember] public float OccupiedCapacity { get; private set; } - [IgnoreMember] public float SpecificHeat { get; private set; } + [IgnoreMember] public float ThermalMass { get; private set; } [IgnoreMember] public float Visibility => VisibilitySources.Values.Sum(); public event Action OnInventoryUpdate; @@ -104,102 +101,220 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR } - public Entity(GameContext context, Guid hull, IEnumerable items, IEnumerable cargo, Guid zone, Guid corporation) + public Entity(GameContext context, Guid hull, IEnumerable gear, IEnumerable cargo, Guid zone, Guid corporation) { Context = context; Zone = zone; Corporation = corporation; - EquippedItems = items.ToList(); - Cargo = cargo.ToList(); + Gear = gear.ToList(); + Cargo = new HashSet(cargo); Hull = hull; + Hydrate(); + } + + public void Hydrate() + { + //var gearIDs = EquippedItems.Append(Hull); + //var gear = gearIDs.ToDictionary(id => id, id => Context.Cache.Get(id)); + //GearData = gear.Values.ToDictionary(g => g, g => g.ItemData); + + Hardpoints = new List(); + Hardpoints.Add(new Hardpoint + { + HardpointData = new HardpointData{ Type = HardpointType.Hull } + }); + var hull = Context.Cache.Get(Hull); + Equip(hull, Hardpoints[0]); + + var hullData = Context.Cache.Get(hull.Data); + Hardpoints.AddRange(hullData.Hardpoints.Select(hd => new Hardpoint {HardpointData = hd})); + + // Create a copy of the gear list and remove every item actually equipped + var remainingGear = new List(Gear); + foreach (var gearID in Gear) + if (Equip(gearID)) + remainingGear.Remove(gearID); + + foreach (var remaining in remainingGear) + { + Context.Log($"Item {Context.Cache.Get(remaining).Name} equipped on entity {Name} has no compatible hardpoint, moved to cargo."); + Gear.Remove(remaining); + Cargo.Add(remaining); + } + + foreach (var hardpoint in Hardpoints) + if(hardpoint.Gear!=null) + foreach (var behavior in hardpoint.Behaviors + .Where(behavior => behavior is IInitializableBehavior)) + ((IInitializableBehavior) behavior).Initialize(); + RecalculateMass(); - - AddItemBehaviors(); } - public void AddItemBehaviors() + public void HydrateHardpoint(Hardpoint hardpoint) { - var gearIDs = EquippedItems.Append(Hull); - var gear = gearIDs.ToDictionary(id => id, id => Context.Cache.Get(id)); - GearData = gear.Values.ToDictionary(g => g, g => g.ItemData); - - // Associate items with behavior list, used for persistence and convenience - ItemBehaviors = gearIDs - .Where(i=> gear[i].ItemData.Behaviors?.Any()??false) - .ToDictionary(i=> gear[i], i => gear[i].ItemData.Behaviors - .OrderBy(bd => bd.GetType().GetCustomAttribute()?.Order ?? 0) - .Select(bd => bd.CreateInstance(Context, this, gear[i])) - .ToList()); + if (hardpoint.Gear == null) + { + Context.Log("Attempted to hydrate hardpoint with no gear on it!"); + return; + } - var behaviorGroups = ItemBehaviors - .SelectMany(x => x.Value - .Select(b => new {item = x.Key, behavior = b})) - .GroupBy(ib => new {ib.item, ib.behavior.Data.Group}); + hardpoint.Behaviors = hardpoint.Gear.ItemData.Behaviors + .Select(bd => bd.CreateInstance(Context, this, hardpoint.Gear)) + .ToArray(); - Behaviors = behaviorGroups - .Select((grouping, i) => new {index = i, group = grouping}) - .ToDictionary(ig => ig.index, ig => ig.group.Select(x => x.behavior).ToList()); - - Switches = Behaviors - .Where(x => x.Value.Any(g => g is Switch)) - .Select((x, i) => new {index = i, s = x.Value.First(g => g is Switch) as Switch}) - .ToDictionary(x => x.index, x => x.s); - - Triggers = Behaviors - .Where(x => x.Value.Any(g => g is Trigger)) - .Select((x, i) => new {index = i, s = x.Value.First(g => g is Trigger) as Trigger}) - .ToDictionary(x => x.index, x => x.s); - - Axes = Behaviors - .Where(x => x.Value.Any(g => g is IAnalogBehavior)) - .Select((x, i) => new {index = i, behaviors = x.Value - .Where(g => g is IAnalogBehavior) - .Cast().ToList()}) - .ToDictionary(x => x.index, x => new AxisSetting{Behaviors = x.behaviors, Value = 0f}); - - // Axes = Behaviors.Values - // .SelectMany(behaviors=>behaviors) - // .Where(b => b is IAnalogBehavior) - // .ToDictionary(b => b as IAnalogBehavior, b => 0f); - - foreach (var behavior in Behaviors.Values - .SelectMany(behaviors=>behaviors) - .Where(behavior => behavior is IInitializableBehavior) - .Cast()) behavior.Initialize(); + hardpoint.BehaviorGroups = hardpoint.Behaviors + .GroupBy(b => b.Data.Group) + .OrderBy(g=>g.Key) + .Select(g=>new BehaviorGroup { + Behaviors = g.ToArray(), + //Axis = (IAnalogBehavior) g.FirstOrDefault(b=>b is IAnalogBehavior), + Switch = (Switch) g.FirstOrDefault(b=>b is Switch), + Trigger = (Trigger) g.FirstOrDefault(b=>b is Trigger) + }) + .ToArray(); } - public void Equip(Gear gear) + public void Equip(Gear gear, Hardpoint hardpoint) { - if (Cargo.Contains(gear.ID)) Cargo.Remove(gear.ID); - else if (IncompleteGear.Any(ig => ig.Key == gear.ID)) - IncompleteGear.Remove(IncompleteGear.First(ig => ig.Key == gear.ID).Key); - else + // Hardpoint is occupied, remove existing item from gear list + if (hardpoint.Gear != null) + { + Gear.Remove(hardpoint.Gear.ID); + Cargo.Add(hardpoint.Gear.ID); + } + + hardpoint.Gear = gear; + HydrateHardpoint(hardpoint); + _inventoryChanged = true; + } + + public bool Equip(Guid gearID, bool force = false) + { + // Check all portions of inventory for a matching item + if (Cargo.Contains(gearID)) Cargo.Remove(gearID); + else if (IncompleteGear.ContainsKey(gearID)) + IncompleteGear.Remove(gearID); + else if(!Gear.Contains(gearID)) throw new ArgumentException("Attempted to equip gear which is not present in inventory!"); + + var gear = Context.Cache.Get(gearID); + var gearData = Context.Cache.Get(gear.Data); + + // Find an empty hardpoint of the correct type + var hardpoint = Hardpoints + .FirstOrDefault(hp => hp.Gear == null && hp.HardpointData.Type == gearData.HardpointType); - EquippedItems.Add(gear.ID); - OnBeforeSerialize(); - OnAfterDeserialize(); + // With force option enabled, we'll try to find an empty hardpoint but otherwise any will do + if (hardpoint == null && force) + hardpoint = Hardpoints + .FirstOrDefault(hp => hp.HardpointData.Type == gearData.HardpointType); + + // No compatible hardpoint found, return false + if (hardpoint == null) + return false; + + Equip(gear, hardpoint); + return true; } - // public Guid Build(BlueprintData blueprint) - // { - // var gear = Context.CreateInstance(blueprint.Item, blueprint.Quality * .5f, blueprint.Quality); - // IncompleteGear[gear.ID] = blueprint.ProductionTime; - // RecalculateMass(); - // return gear.ID; - // // IncompleteGear.Add(new IncompleteItem - // // { - // // Item = gear.ID, - // // Blueprint = blueprint.ID, - // // RemainingTime = blueprint.ProductionTime - // // }); - // } - - public List Build(BlueprintData blueprint, float quality, string name, bool equip = false) + public CraftedItemInstance AddCargo(CraftedItemInstance item) { - if (equip) + Cargo.Add(item.ID); + Mass += item.Mass; + ThermalMass += item.ThermalMass; + OccupiedCapacity += item.Size; + _inventoryChanged = true; + return item; + } + + public CraftedItemInstance RemoveCargo(CraftedItemInstance item) + { + if(!Cargo.Contains(item.ID)) + throw new ArgumentException("Attempted to remove an item which is not in cargo!"); + Cargo.Remove(item.ID); + Mass -= item.Mass; + ThermalMass -= item.ThermalMass; + OccupiedCapacity -= item.Size; + _inventoryChanged = true; + return item; + } + + public SimpleCommodity AddCargo(SimpleCommodity item) + { + // Regardless of whether a match is found, the item's mass and size are added to the entity + Mass += item.Mass; + ThermalMass += item.ThermalMass; + OccupiedCapacity += item.Size; + + // Try to find an matching instance of the same commodity in cargo + var existingCommodityID = Cargo.FirstOrDefault(id => + Context.Cache.Get(id) is SimpleCommodity simpleCommodity && + simpleCommodity.ItemData == item.ItemData); + + // A match was found, delete the original item and increment the quantity of the match + if (existingCommodityID != Guid.Empty) + { + var existingCommodity = Context.Cache.Get(existingCommodityID); + existingCommodity.Quantity += item.Quantity; + Context.Cache.Delete(item); + return existingCommodity; + } + + // No match was found, simply add the item instance to the cargo + Cargo.Add(item.ID); + _inventoryChanged = true; + return item; + } + + public SimpleCommodity RemoveCargo(SimpleCommodity item, int quantity) + { + if(!Cargo.Contains(item.ID)) + throw new ArgumentException("Attempted to remove an item which is not in cargo!"); + + // If the quantity matches exactly, huzzah, just remove the instance from cargo + if (item.Quantity == quantity) + Cargo.Remove(item.ID); + else + { + // Quantity does not match, create new item instance and decrement source quantity + var newSimpleCommodity = new SimpleCommodity + { + Context = Context, + Data = item.Data, + Quantity = quantity + }; + item.Quantity -= quantity; + item = newSimpleCommodity; + } + + Mass -= item.Mass; + ThermalMass -= item.ThermalMass; + OccupiedCapacity -= item.Size; + + _inventoryChanged = true; + return item; + } + + public void AddChild(Entity entity) + { + Mass += entity.Mass; + ThermalMass += entity.ThermalMass; + Children.Add(entity.ID); + } + + public void RemoveChild(Entity entity) + { + Mass -= entity.Mass; + ThermalMass -= entity.ThermalMass; + Children.Remove(entity.ID); + } + + public Guid Build(BlueprintData blueprint, float quality, string name, bool direct = false) + { + if (direct) { if(blueprint.FactoryItem!=Guid.Empty) throw new ArgumentException("Attempted to directly build a blueprint which requires a factory!"); @@ -207,109 +322,70 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR if(blueprintItem == null) throw new ArgumentException("Attempted to directly build a blueprint for a missing or incompatible item!"); } + + //var newItemID = Guid.Empty; + + // GetBlueprintIngredients will assign the output lists with the items matching the blueprint, and return false if they are not found + if (!GetBlueprintIngredients(blueprint, out var simpleIngredients, out var compoundIngredients)) + return Guid.Empty; - var newItems = new List(); - if (GetBlueprintIngredients(blueprint, out var simpleIngredients, out var compoundIngredients)) + // These will be bundled with the data for the compound commodity instance + var ingredients = new List(); + ingredients.AddRange(compoundIngredients.Select(RemoveCargo)); + ingredients.AddRange(simpleIngredients.Select(sc => RemoveCargo(sc, blueprint.Ingredients[sc.Data]))); + + var blueprintItemData = Context.Cache.Get(blueprint.Item); + + // Creating new crafted item instances is a bit more complicated + if (blueprintItemData is CraftedItemData) { - var ingredients = new List(); - ingredients.AddRange(compoundIngredients); - foreach (var compoundCommodity in compoundIngredients) - { - Cargo.Remove(compoundCommodity.ID); - } - foreach (var simpleCommodity in simpleIngredients) - { - var blueprintQuantity = blueprint.Ingredients - .First(ingredient => ingredient.Key == simpleCommodity.ItemData.ID).Value; - if (simpleCommodity.Quantity == blueprintQuantity) - { - ingredients.Add(simpleCommodity); - Cargo.Remove(simpleCommodity.ID); - } - else - { - var newSimpleCommodity = new SimpleCommodity - { - Context = Context, - Data = simpleCommodity.Data, - Quantity = blueprintQuantity - }; - simpleCommodity.Quantity -= blueprintQuantity; - ingredients.Add(newSimpleCommodity); - } - } + CraftedItemInstance newItem; - var blueprintItemData = Context.Cache.Get(blueprint.Item); - - if (blueprintItemData is CraftedItemData) + if (blueprintItemData is EquippableItemData equippableItemData) { - for (int i = 0; i < blueprint.Quantity; i++) - { - CraftedItemInstance newItem; - - if (blueprintItemData is EquippableItemData equippableItemData) - { - var newGear = new Gear - { - Context = Context, - Data = blueprintItemData.ID, - Ingredients = ingredients.Select(ii=>ii.ID).ToList(), - Quality = quality, - Blueprint = blueprint.ID, - Name = name - }; - newGear.Durability = Context.Evaluate(equippableItemData.Durability, newGear); - newItem = newGear; - } - else - { - newItem = new CompoundCommodity - { - Context = Context, - Data = blueprintItemData.ID, - Ingredients = ingredients.Select(ii=>ii.ID).ToList(), - Quality = quality, - Blueprint = blueprint.ID, - Name = name - }; - } - Context.Cache.Add(newItem); - if (equip) - IncompleteGear[newItem.ID] = blueprint.ProductionTime; - else - IncompleteCargo[newItem.ID] = blueprint.ProductionTime; - newItems.Add(newItem.ID); - // IncompleteCargo.Add(new IncompleteItem - // { - // Item = newItem.ID, - // Blueprint = blueprint.ID, - // RemainingTime = blueprint.ProductionTime - // }); - } - } - else - { - var newSimpleCommodity = new SimpleCommodity + var newGear = new Gear { Context = Context, Data = blueprintItemData.ID, - Quantity = blueprint.Quantity + Ingredients = ingredients.Select(ii=>ii.ID).ToList(), + Quality = quality, + Blueprint = blueprint.ID, + Name = name, + SourceEntity = ID }; - Context.Cache.Add(newSimpleCommodity); - IncompleteCargo[newSimpleCommodity.ID] = blueprint.ProductionTime; - newItems.Add(newSimpleCommodity.ID); - // IncompleteCargo.Add(new IncompleteItem - // { - // Item = newSimpleCommodity.ID, - // Blueprint = blueprint.ID, - // RemainingTime = blueprint.ProductionTime - // }); + newGear.Durability = Context.Evaluate(equippableItemData.Durability, newGear); + newItem = newGear; } - - RecalculateMass(); + else + { + newItem = new CompoundCommodity + { + Context = Context, + Data = blueprintItemData.ID, + Ingredients = ingredients.Select(ii=>ii.ID).ToList(), + Quality = quality, + Blueprint = blueprint.ID, + Name = name, + SourceEntity = ID + }; + } + Context.Cache.Add(newItem); + if (direct) + IncompleteGear[newItem.ID] = blueprint.ProductionTime; + else + IncompleteCargo[newItem.ID] = blueprint.ProductionTime; + return newItem.ID; } - return newItems; + var newSimpleCommodity = new SimpleCommodity + { + Context = Context, + Data = blueprintItemData.ID, + Quantity = 1 + }; + Context.Cache.Add(newSimpleCommodity); + IncompleteCargo[newSimpleCommodity.ID] = blueprint.ProductionTime; + return newSimpleCommodity.ID; } public bool GetBlueprintIngredients(BlueprintData blueprint, out List simpleIngredients, @@ -349,23 +425,21 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR public void RecalculateMass() { Mass = Context.Cache.Get(Hull).Mass + - EquippedItems.Select(i => Context.Cache.Get(i)).Sum(i => i.Mass) + + Gear.Select(i => Context.Cache.Get(i)).Sum(i => i.Mass) + IncompleteGear.Select(i => Context.Cache.Get(i.Key)).Sum(i => i.Mass) + Cargo.Select(i => Context.Cache.Get(i)).Sum(ii => ii.Mass) + IncompleteCargo.Select(i => Context.Cache.Get(i.Key)).Sum(ii => ii.Mass) + Children.Select(i => Context.Cache.Get(i)).Sum(c=>c.Mass); - SpecificHeat = Context.Cache.Get(Hull).HeatCapacity + - EquippedItems.Select(i => Context.Cache.Get(i)).Sum(i => i.HeatCapacity) + - IncompleteGear.Select(i => Context.Cache.Get(i.Key)).Sum(i => i.HeatCapacity) + - Cargo.Select(i => Context.Cache.Get(i)).Sum(ii => ii.HeatCapacity) + - IncompleteCargo.Select(i => Context.Cache.Get(i.Key)).Sum(ii => ii.HeatCapacity) + - Children.Select(i => Context.Cache.Get(i)).Sum(c=>c.SpecificHeat); + ThermalMass = Context.Cache.Get(Hull).ThermalMass + + Gear.Select(i => Context.Cache.Get(i)).Sum(i => i.ThermalMass) + + IncompleteGear.Select(i => Context.Cache.Get(i.Key)).Sum(i => i.ThermalMass) + + Cargo.Select(i => Context.Cache.Get(i)).Sum(ii => ii.ThermalMass) + + IncompleteCargo.Select(i => Context.Cache.Get(i.Key)).Sum(ii => ii.ThermalMass) + + Children.Select(i => Context.Cache.Get(i)).Sum(c=>c.ThermalMass); - OccupiedCapacity = EquippedItems.Select(i => Context.Cache.Get(i)).Sum(i => i.ItemData.Size) + - Cargo.Select(i => Context.Cache.Get(i)).Sum(ii => Context.GetSize(ii)); - - OnInventoryUpdate?.Invoke(); + OccupiedCapacity = Gear.Select(i => Context.Cache.Get(i)).Sum(i => i.Size) + + Cargo.Select(i => Context.Cache.Get(i)).Sum(ii => ii.Size); } public void ClearInventoryListeners() @@ -373,52 +447,54 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR OnInventoryUpdate = null; } + public T GetBehavior() where T : class, IBehavior + { + foreach (var hardpoint in Hardpoints) + if(hardpoint.Gear!=null) + foreach (var behavior in hardpoint.Behaviors) + if (behavior is T b) + return b; + return null; + } + public IEnumerable GetBehaviors() where T : class, IBehavior { - foreach (var behaviors in Behaviors.Values) - foreach (var behavior in behaviors) - if (behavior is T b) - yield return b; + foreach (var hardpoint in Hardpoints) + if(hardpoint.Gear!=null) + foreach (var behavior in hardpoint.Behaviors) + if (behavior is T b) + yield return b; } public IEnumerable GetBehaviorData() where T : BehaviorData { - foreach (var behaviors in Behaviors.Values) - foreach (var behavior in behaviors) - if (behavior.Data is T b) - yield return b; + foreach (var hardpoint in Hardpoints) + if(hardpoint.Gear!=null) + foreach (var behavior in hardpoint.Behaviors) + if (behavior.Data is T b) + yield return b; } - public int GetAxis(IAnalogBehavior behavior) + public Switch GetSwitch() where T : class, IBehavior { - var axis = Axes.FirstOrDefault(x => x.Value.Behaviors.Contains(behavior)); - if (axis.IsNull()) - return -1; - return axis.Key; + foreach (var hardpoint in Hardpoints) + if(hardpoint.Gear!=null) + foreach (var group in hardpoint.BehaviorGroups) + foreach(var behavior in group.Behaviors) + if (behavior is T) + return group.Switch; + return null; } - public int GetAxis() where T : class, IBehavior + public Trigger GetTrigger() where T : class, IBehavior { - foreach (var axis in Axes) - foreach (var behavior in axis.Value.Behaviors) - if (behavior is T) - return axis.Key; - return -1; - } - - public int GetSwitch() where T : class, IBehavior - { - var s = Behaviors - .FirstOrDefault(x => x.Value.Any(g => g is Switch) && x.Value.Any(g => g is T)) - .Value.First(g => g is Switch) as Switch; - return Switches.FirstOrDefault(kvp => kvp.Value == s).Key; - } - - public Switch GetSwitch(IBehavior behavior) - { - return Behaviors - .FirstOrDefault(x => x.Value.Any(g => g == behavior)) - .Value.First(g => g is Switch) as Switch; + foreach (var hardpoint in Hardpoints) + if(hardpoint.Gear!=null) + foreach (var group in hardpoint.BehaviorGroups) + foreach(var behavior in group.Behaviors) + if (behavior is T) + return group.Trigger; + return null; } public void AddHeat(float heat) @@ -429,29 +505,25 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR // parent.AddHeat(heat); } else - Temperature += heat / SpecificHeat; + Temperature += heat / ThermalMass; } public virtual void Update(float delta) { - foreach(var axis in Axes) - foreach(var analogBehavior in axis.Value.Behaviors) - analogBehavior.SetAxis(AxisOverrides.ContainsKey(axis.Key) ? AxisOverrides[axis.Key] : Axes[axis.Key].Value); - - foreach (var group in Behaviors.Values) - foreach(var behavior in group) - if(!behavior.Update(delta)) - break; - - foreach (var behaviors in Behaviors.Values) - foreach (var behavior in behaviors.Where(b => b is IAlwaysUpdatedBehavior).Cast()) + foreach (var hardpoint in Hardpoints.Where(hp=>hp.Gear!=null)) + { + foreach (var group in hardpoint.BehaviorGroups) + foreach(var behavior in group.Behaviors) + if(!behavior.Update(delta)) + break; + + foreach (var behavior in hardpoint.Behaviors.Where(b => b is IAlwaysUpdatedBehavior).Cast()) behavior.AlwaysUpdate(delta); - - foreach (var item in EquippedItems - .Select(item => Context.Cache.Get(item)) - .Where(item => item.ItemData.Performance(Temperature) < .01f)) - item.Durability -= delta; + + if(hardpoint.Gear.ItemData.Performance(Temperature) < .01f) + hardpoint.Gear.Durability -= delta; + } if (Parent != Guid.Empty) { @@ -462,11 +534,11 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR } // Processing stale item data properly was a pain in my ass, so the shortcut is just persisting and restoring everything - if (GearData.Any(kvp => kvp.Key.ItemData != kvp.Value)) - { - OnBeforeSerialize(); - OnAfterDeserialize(); - } + // if (Hardpoints.Any(hp => hp.Gear.ItemData != hp.ItemData)) + // { + // OnBeforeSerialize(); + // OnAfterDeserialize(); + // } foreach (var message in Messages.Keys.ToArray()) { @@ -478,10 +550,7 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR foreach (var incompleteGear in IncompleteGear.Keys.ToArray()) { IncompleteGear[incompleteGear] = IncompleteGear[incompleteGear] - delta; - if (IncompleteGear[incompleteGear] < 0) - { - Equip(Context.Cache.Get(incompleteGear)); - } + if (IncompleteGear[incompleteGear] < 0) Equip(incompleteGear); } // Here's the PITA way @@ -548,9 +617,9 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR // Filter item behavior collections by those with any persistent behaviors // For each item create an object containing the item ID and a list of persistent behaviors // Then turn that into a dictionary mapping from item ID to an array of every behaviors persistent data - PersistedBehaviors = ItemBehaviors - .Where(x => x.Value.Any(b=>b is IPersistentBehavior)) - .Select(x => new {gear=x.Key, behaviors = x.Value + PersistedBehaviors = Hardpoints + .Where(hp => hp.Behaviors.Any(b=>b is IPersistentBehavior)) + .Select(hp => new {gear=hp.Gear, behaviors = hp.Behaviors .Where(b=>b is IPersistentBehavior) .Cast()}) .ToDictionary(x=> x.gear.ID, x=>x.behaviors.Select(b => b.Store()).ToArray()); @@ -558,32 +627,34 @@ public abstract class Entity : DatabaseEntry, IMessagePackSerializationCallbackR public void OnAfterDeserialize() { - AddItemBehaviors(); - - RecalculateMass(); + Hydrate(); // Iterate only over the behaviors of items which contain persistent data // Filter the behaviors for each item to get the persistent ones, then cast them and combine with the persisted data array for that item - foreach (var persistentBehaviorData in ItemBehaviors - .Where(itemBehaviors => PersistedBehaviors.ContainsKey(itemBehaviors.Key.ID)). - SelectMany(itemBehaviors => itemBehaviors.Value + foreach (var persistentBehaviorData in Hardpoints + .Where(hardpoint => PersistedBehaviors.ContainsKey(hardpoint.Gear.ID)). + SelectMany(hardpoint => hardpoint.Behaviors .Where(b=> b is IPersistentBehavior) .Cast() - .Zip(PersistedBehaviors[itemBehaviors.Key.ID], (behavior, data) => new{behavior, data}))) + .Zip(PersistedBehaviors[hardpoint.Gear.ID], (behavior, data) => new{behavior, data}))) persistentBehaviorData.behavior.Restore(persistentBehaviorData.data); } } -public class AxisSetting +//[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class Hardpoint { - public float Value; - public List Behaviors; + public Gear Gear; + public EquippableItemData ItemData; + public HardpointData HardpointData; + public IBehavior[] Behaviors; + public BehaviorGroup[] BehaviorGroups; } -[MessagePackObject] -public class IncompleteItem +public class BehaviorGroup { - [Key(0)] public Guid Item; - [Key(1)] public Guid Blueprint; - [Key(2)] public double RemainingTime; + public IBehavior[] Behaviors; + public Trigger Trigger; + public Switch Switch; + //public IAnalogBehavior Axis; } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/GameContext.cs b/Assets/Scripts/ServerShared/GameContext.cs index eb1027ea9..67592cd7f 100644 --- a/Assets/Scripts/ServerShared/GameContext.cs +++ b/Assets/Scripts/ServerShared/GameContext.cs @@ -488,7 +488,7 @@ public class GameContext return 0; } - public float GetHeatCapacity(ItemInstance item) + public float GetThermalMass(ItemInstance item) { var data = GetData(item); switch (item) @@ -570,7 +570,8 @@ public class GameContext { var ingredientInstances = item.Ingredients.Select(i => Cache.Get(i)).ToArray(); var ingredients = ingredientInstances.Where(i => activeEffects.Any(e => e.Ingredient == i.Data)).ToArray(); - if(ingredients.Length != activeEffects.Length) + var distinctIngredients = ingredients.Select(i => i.Data).Distinct(); + if(distinctIngredients.Count() != activeEffects.Length) { _logger($"Item {item.ID} does not have the ingredients specified by the stat effects of its blueprint!"); return 0; @@ -868,8 +869,7 @@ public class GameContext public void SetParent(Entity child, Entity parent) { child.Parent = parent.ID; - parent.Children.Add(child.ID); - parent.RecalculateMass(); + parent.AddChild(child); } public void RemoveParent(Entity child) @@ -878,8 +878,7 @@ public class GameContext return; var parent = Cache.Get(child.Parent); - parent.Children.Remove(child.ID); - parent.RecalculateMass(); + parent.RemoveChild(child); child.Parent = Guid.Empty; } @@ -912,117 +911,105 @@ public class GameContext if (efficiency * Random.NextFloat() * _asteroidMiningAccumulator[(asteroidBelt, miner.ID, asteroid)] * resourceCount / GlobalData.MiningDifficulty > 1 && miner.OccupiedCapacity < miner.Capacity - 1) { _asteroidMiningAccumulator.Remove((asteroidBelt, miner.ID, asteroid)); - var simpleCommodityTarget = miner.Cargo - .Select(i => Cache.Get(i)) - .FirstOrDefault(i => i.Data == resource.Key) as SimpleCommodity; - if (simpleCommodityTarget == null) + var newSimpleCommodity = new SimpleCommodity { - var newSimpleCommodity = new SimpleCommodity - { - Context = this, - Data = resource.Key, - Quantity = 1 - }; - Cache.Add(newSimpleCommodity); - miner.Cargo.Add(newSimpleCommodity.ID); - miner.RecalculateMass(); - } - else - { - simpleCommodityTarget.Quantity++; - miner.RecalculateMass(); - } + Context = this, + Data = resource.Key, + Quantity = 1 + }; + Cache.Add(newSimpleCommodity); + miner.AddCargo(newSimpleCommodity); } } - public bool MoveCargo(Entity source, Entity target, ItemInstance item, int quantity = int.MaxValue) - { - if (item is CraftedItemInstance craftedItemInstance) - { - var craftedItemData = Cache.Get(craftedItemInstance.Data); - if (target.Capacity - target.OccupiedCapacity > craftedItemData.Size) - { - // Target has the cargo capacity for the item, simply move the instance - source.Cargo.Remove(item.ID); - target.Cargo.Add(item.ID); - source.RecalculateMass(); - target.RecalculateMass(); - return true; - } - return false; - } - - if (item is SimpleCommodity simpleCommoditySource) - { - quantity = min(quantity, simpleCommoditySource.Quantity); - var simpleCommodityData = Cache.Get(simpleCommoditySource.Data); - var spareCapacity = (int) (target.Capacity - target.OccupiedCapacity); - var simpleCommodityTarget = target.Cargo - .Select(i => Cache.Get(i)) - .FirstOrDefault(i => i.Data == simpleCommodityData.ID) as SimpleCommodity; - var success = spareCapacity >= quantity; - quantity = min(quantity, spareCapacity); - if (simpleCommodityTarget == null) - { - if (quantity == simpleCommoditySource.Quantity) - { - // Target has the cargo capacity to hold the full quantity, - // and the target has no matching item instance; - // simply move the existing item instance to the target - source.Cargo.Remove(simpleCommoditySource.ID); - target.Cargo.Add(simpleCommoditySource.ID); - source.RecalculateMass(); - target.RecalculateMass(); - return success; - } - else - { - // Target has the cargo capacity to hold the desired quantity - // and the target has no matching item instance; - // Create a new item instance on the target and decrement the quantity of the source instance - var newSimpleCommodity = new SimpleCommodity - { - Context = this, - Data = simpleCommodityData.ID, - Quantity = simpleCommoditySource.Quantity - }; - Cache.Add(newSimpleCommodity); - target.Cargo.Add(newSimpleCommodity.ID); - simpleCommoditySource.Quantity -= quantity; - source.RecalculateMass(); - target.RecalculateMass(); - return success; - } - } - else - { - if (quantity == simpleCommoditySource.Quantity) - { - // Target has the cargo capacity to hold the full quantity, - // and there is already a matching item instance; - // delete the source entity's item instance and increment the target's quantity - source.Cargo.Remove(simpleCommoditySource.ID); - Cache.Delete(simpleCommoditySource); - simpleCommodityTarget.Quantity += quantity; - source.RecalculateMass(); - target.RecalculateMass(); - return success; - } - else - { - // Target has the cargo capacity to hold the desired quantity, - // and there is already a matching item instance; - // decrement the source's quantity and increment the target's quantity - simpleCommoditySource.Quantity -= quantity; - simpleCommodityTarget.Quantity += quantity; - source.RecalculateMass(); - target.RecalculateMass(); - return success; - } - } - - } - - return false; - } + // public bool MoveCargo(Entity source, Entity target, ItemInstance item, int quantity = int.MaxValue) + // { + // if (item is CraftedItemInstance craftedItemInstance) + // { + // var craftedItemData = Cache.Get(craftedItemInstance.Data); + // if (target.Capacity - target.OccupiedCapacity > craftedItemData.Size) + // { + // // Target has the cargo capacity for the item, simply move the instance + // source.Cargo.Remove(item.ID); + // target.Cargo.Add(item.ID); + // source.RecalculateMass(); + // target.RecalculateMass(); + // return true; + // } + // return false; + // } + // + // if (item is SimpleCommodity simpleCommoditySource) + // { + // quantity = min(quantity, simpleCommoditySource.Quantity); + // var simpleCommodityData = Cache.Get(simpleCommoditySource.Data); + // var spareCapacity = (int) (target.Capacity - target.OccupiedCapacity); + // var simpleCommodityTarget = target.Cargo + // .Select(i => Cache.Get(i)) + // .FirstOrDefault(i => i.Data == simpleCommodityData.ID) as SimpleCommodity; + // var success = spareCapacity >= quantity; + // quantity = min(quantity, spareCapacity); + // if (simpleCommodityTarget == null) + // { + // if (quantity == simpleCommoditySource.Quantity) + // { + // // Target has the cargo capacity to hold the full quantity, + // // and the target has no matching item instance; + // // simply move the existing item instance to the target + // source.Cargo.Remove(simpleCommoditySource.ID); + // target.Cargo.Add(simpleCommoditySource.ID); + // source.RecalculateMass(); + // target.RecalculateMass(); + // return success; + // } + // else + // { + // // Target has the cargo capacity to hold the desired quantity + // // and the target has no matching item instance; + // // Create a new item instance on the target and decrement the quantity of the source instance + // var newSimpleCommodity = new SimpleCommodity + // { + // Context = this, + // Data = simpleCommodityData.ID, + // Quantity = simpleCommoditySource.Quantity + // }; + // Cache.Add(newSimpleCommodity); + // target.Cargo.Add(newSimpleCommodity.ID); + // simpleCommoditySource.Quantity -= quantity; + // source.RecalculateMass(); + // target.RecalculateMass(); + // return success; + // } + // } + // else + // { + // if (quantity == simpleCommoditySource.Quantity) + // { + // // Target has the cargo capacity to hold the full quantity, + // // and there is already a matching item instance; + // // delete the source entity's item instance and increment the target's quantity + // source.Cargo.Remove(simpleCommoditySource.ID); + // Cache.Delete(simpleCommoditySource); + // simpleCommodityTarget.Quantity += quantity; + // source.RecalculateMass(); + // target.RecalculateMass(); + // return success; + // } + // else + // { + // // Target has the cargo capacity to hold the desired quantity, + // // and there is already a matching item instance; + // // decrement the source's quantity and increment the target's quantity + // simpleCommoditySource.Quantity -= quantity; + // simpleCommodityTarget.Quantity += quantity; + // source.RecalculateMass(); + // target.RecalculateMass(); + // return success; + // } + // } + // + // } + // + // return false; + // } } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index b1d28109a..62b42062f 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -22,7 +22,8 @@ public abstract class ItemInstance : DatabaseEntry [JsonProperty("data"), Key(1)] public Guid Data; public float Mass => Context.GetMass(this); - public float HeatCapacity => Context.GetHeatCapacity(this); + public float ThermalMass => Context.GetThermalMass(this); + public float Size => Context.GetSize(this); } [Union(0, typeof(CompoundCommodity)), @@ -38,6 +39,8 @@ public abstract class CraftedItemInstance : ItemInstance [JsonProperty("blueprint"), Key(4)] public Guid Blueprint; [JsonProperty("name"), Key(5)] public string Name; + + [JsonProperty("sourceEntity"), Key(6)] public Guid SourceEntity; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -54,15 +57,7 @@ public class SimpleCommodity : ItemInstance [MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class Gear : CraftedItemInstance { - [JsonProperty("durability"), Key(5)] public float Durability; + [JsonProperty("durability"), Key(7)] public float Durability; public EquippableItemData ItemData => Context.GetData(this); -} - -[MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class Hardpoint -{ - [JsonProperty("item"), Key(0)] public Gear Item; - - [IgnoreMember] public HardpointData HardpointData; } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/OrbitalEntity.cs b/Assets/Scripts/ServerShared/OrbitalEntity.cs index 63ce26a82..76d5fe517 100644 --- a/Assets/Scripts/ServerShared/OrbitalEntity.cs +++ b/Assets/Scripts/ServerShared/OrbitalEntity.cs @@ -9,7 +9,7 @@ public class OrbitalEntity : Entity { public Guid OrbitData; - public OrbitalEntity(GameContext context, Guid hull, IEnumerable items, IEnumerable cargo, Guid orbit, Guid zone, Guid corporation) : base(context, hull, items, cargo, zone, corporation) + public OrbitalEntity(GameContext context, Guid hull, IEnumerable gear, IEnumerable cargo, Guid orbit, Guid zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation) { OrbitData = orbit; } diff --git a/Assets/Scripts/ServerShared/Ship.cs b/Assets/Scripts/ServerShared/Ship.cs index 753f17ba5..703715223 100644 --- a/Assets/Scripts/ServerShared/Ship.cs +++ b/Assets/Scripts/ServerShared/Ship.cs @@ -10,8 +10,6 @@ using static Unity.Mathematics.math; [MessagePackObject] public class Ship : Entity { - [Key("hardpoints")] - public List Hardpoints = new List(); // [Key("bindings")] public Dictionary Bindings = new Dictionary(); //[IgnoreMember] public int HullHardpointCount; @@ -19,7 +17,7 @@ public class Ship : Entity // [IgnoreMember] public Dictionary Contacts = new Dictionary(); // [IgnoreMember] public Targetable Target; - public Ship(GameContext context, Guid hull, IEnumerable items, IEnumerable cargo, Guid zone, Guid corporation) : base(context, hull, items, cargo, zone, corporation) + public Ship(GameContext context, Guid hull, IEnumerable gear, IEnumerable cargo, Guid zone, Guid corporation) : base(context, hull, gear, cargo, zone, corporation) { } diff --git a/Assets/Scripts/StrategyGameManager.cs b/Assets/Scripts/StrategyGameManager.cs index 0d4499f48..24bd00136 100644 --- a/Assets/Scripts/StrategyGameManager.cs +++ b/Assets/Scripts/StrategyGameManager.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; +using JM.LinqFaster; using NaughtyAttributes; using RethinkDb.Driver.Net; using TMPro; @@ -389,14 +390,14 @@ public class StrategyGameManager : MonoBehaviour belt.Value.Update(); } - foreach (var ship in _zoneShips) - { - ship.Value.transform.position = float3(ship.Key.Position * ZoneSizeScale, .05f); - ship.Value.Icon.transform.up = (Vector2) ship.Key.Direction; - var thrusterScale = ship.Value.Thruster.localScale; - thrusterScale.x = ship.Key.Axes[ship.Key.GetAxis()].Value; - ship.Value.Thruster.localScale = thrusterScale; - } + // foreach (var ship in _zoneShips) + // { + // ship.Value.transform.position = float3(ship.Key.Position * ZoneSizeScale, .05f); + // ship.Value.Icon.transform.up = (Vector2) ship.Key.Direction; + // var thrusterScale = ship.Value.Thruster.localScale; + // thrusterScale.x = ship.Key.GetBehavior().Axis; + // ship.Value.Thruster.localScale = thrusterScale; + // } var entities = _context.GetEntities(_populatedZone); var shipGameObjects = _zoneShips.Keys.ToList(); @@ -451,7 +452,7 @@ public class StrategyGameManager : MonoBehaviour _zoneShips[ship].transform.position = float3(ship.Position * ZoneSizeScale, .05f); _zoneShips[ship].Icon.transform.up = (Vector2) ship.Direction; var thrusterScale = _zoneShips[ship].Thruster.localScale; - thrusterScale.x = ship.Axes[ship.GetAxis()].Value; + thrusterScale.x = ship.GetBehavior().Axis; _zoneShips[ship].Thruster.localScale = thrusterScale; _zoneShips[ship].Message.text = !ship.Messages.Any() ? "" : string.Join("\n", ship.Messages.OrderByDescending(x=>x.Value).Take(2).Select(x=>x.Key)); @@ -731,7 +732,7 @@ public class StrategyGameManager : MonoBehaviour PropertiesPanel.AddProperty("Temperature", () => $"{entity.Temperature:0}°K"); PropertiesPanel.AddProperty("Energy", () => $"{entity.Energy:0}/{entity.GetBehaviors().First().Capacitance:0}"); var gearList = PropertiesPanel.AddList("Gear"); - var equippedItems = entity.EquippedItems.Select(g => _context.Cache.Get(g)); + var equippedItems = entity.Hardpoints.Where(hp => hp.Gear != null).Select(hp => hp.Gear); foreach(var gear in equippedItems) PopulateGearProperties(gearList.AddList(gear.ItemData.Name), gear, entity); if(!entity.Cargo.Any()) diff --git a/Assets/Scripts/TechTreeMsagl.cs b/Assets/Scripts/TechTreeMsagl.cs index 19fc0ec62..be3769bbe 100644 --- a/Assets/Scripts/TechTreeMsagl.cs +++ b/Assets/Scripts/TechTreeMsagl.cs @@ -334,7 +334,7 @@ public class TechTreeMsagl : MonoBehaviour var blueprint = (BlueprintData) vertex.UserData; PropertiesPanel.Title.text = blueprint.Name; PropertiesPanel.AddProperty("Research Time", () => $"{blueprint.ResearchTime:0.##} MH"); - PropertiesPanel.AddProperty("Produces", () => $"{blueprint.Quantity} {Context.Cache.Get(blueprint.Item).Name}"); + PropertiesPanel.AddProperty("Produces", () => $"{Context.Cache.Get(blueprint.Item).Name}"); PropertiesPanel.AddProperty("Production Quality", () => $"{Mathf.RoundToInt(blueprint.Quality * 100)}%"); PropertiesPanel.AddProperty("Production Time", () => $"{blueprint.ProductionTime:0.##} MH"); diff --git a/Assets/Scripts/UI/ColonyTab.cs b/Assets/Scripts/UI/ColonyTab.cs index 03ad47258..c537a35b5 100644 --- a/Assets/Scripts/UI/ColonyTab.cs +++ b/Assets/Scripts/UI/ColonyTab.cs @@ -30,7 +30,7 @@ public class ColonyTab : MonoBehaviour private Guid _selectedColony; private GameContext _context; - private HardpointData _selectedHardpoint; + private Hardpoint _selectedHardpoint; public void Open(Guid colony) { @@ -79,200 +79,190 @@ public class ColonyTab : MonoBehaviour var hull = Context.Cache.Get(entity.Hull); var hullData = Context.Cache.Get(hull.Data); - // Create item data mapping for cargo similar to what Entity.GearData already does for equipped items + // Create item data mapping for cargo var cargoData = entity.Cargo.ToDictionary(id => _context.Cache.Get(id), id => Context.Cache.Get(_context.Cache.Get(id).Data)); - //var incompleteGear = entity.IncompleteGear.Keys.Select(id => _context.Cache.Get(id)); - // var incompleteGear = entity.IncompleteGear.Select(x => - // { - // var gear = _context.Cache.Get(x.Key); - // var productionTime = _context.Cache.Get(gear.Blueprint).ProductionTime; - // var progress = (productionTime - (float) x.Value) / productionTime; - // return (gear, progress); - // }); - var gearList = Inventory.AddList("Gear"); - - // Create temporary list including both equipped items and incomplete items - // This is necessary because the binding between items and hardpoints is implicit - var equippedItems = new List(entity.GearData.Keys.Concat(entity.IncompleteGear.Keys.Select(id => _context.Cache.Get(id)))); - - // Display an entry in the list for each hardpoint on the entity - foreach (var hardpoint in hullData.Hardpoints) + Inventory.AddSection("Gear"); + + // Skip first hardpoint, that one is always the hull + foreach (var hardpoint in entity.Hardpoints.Skip(1)) { - // This corresponds to the first equipped or incomplete gear which matches the hardpoint type - var match = equippedItems.FirstOrDefault(g => g.ItemData.HardpointType == hardpoint.Type); - // These are the items in the inventory which can be equipped to the current hardpoint var matchingCargoGear = cargoData .Where(x => - x.Value is EquippableItemData equippableItemData && - equippableItemData.HardpointType == hardpoint.Type) + x.Value is GearData gearData && + gearData.HardpointType == hardpoint.HardpointData.Type) .Select(x => x.Key as Gear) .ToArray(); - - // There is no item in the inventory which can fill the current hardpoint - if (match == null) - { - var matchingBlueprints = blueprints.Where(bp => - bp.FactoryItem == Guid.Empty && - Context.Cache.Get(bp.Item) is GearData gearData && - gearData.HardpointType == hardpoint.Type).ToArray(); - - Action onClick = null; - if (matchingCargoGear.Any() || matchingBlueprints.Any()) - onClick = data => - { - if (data.button == PointerEventData.InputButton.Left) - { - Details.Clear(); - foreach (var blueprint in matchingBlueprints) - { - var blueprintList = Details.AddList(blueprint.Name); - - foreach (var ingredient in blueprint.Ingredients) - { - var itemData = _context.Cache.Get(ingredient.Key); - blueprintList.AddProperty(itemData.Name, () => ingredient.Value.ToString()); - } - - var bpItemData = _context.Cache.Get(blueprint.Item); - if(entity.GetBlueprintIngredients(blueprint, out _, out _)) - blueprintList.AddButton("Build", _ => entity.Build(blueprint, 1, bpItemData.Name, true)); - } - Details.RefreshValues(); - } - else if (data.button == PointerEventData.InputButton.Right) + // Hardpoint has no gear assigned to it + if (hardpoint.Gear == null) + { + // Check whether we're currently building some gear for this hardpoint + var incompleteGear = entity.IncompleteGear.Keys + .Select(id => Context.Cache.Get(id)) + .FirstOrDefault(g => g.ItemData.HardpointType == hardpoint.HardpointData.Type); + + // We're building something for this hardpoint, show a progress bar! + if (incompleteGear != null) + { + Inventory.AddProgressField(incompleteGear.Name, () => + { + var productionTime = _context.Cache.Get(incompleteGear.Blueprint).ProductionTime; + return (productionTime - (float) entity.IncompleteGear[incompleteGear.ID]) / productionTime; + }); + } + else // We're not building anything + { + // These are the blueprints we could build onto this hardpoint directly + var matchingBlueprints = blueprints.Where(bp => + bp.FactoryItem == Guid.Empty && + Context.Cache.Get(bp.Item) is GearData gearData && + gearData.HardpointType == hardpoint.HardpointData.Type).ToArray(); + + Action onClick = null; + if (matchingCargoGear.Any() || matchingBlueprints.Any()) + onClick = data => { - ContextMenu.gameObject.SetActive(true); - ContextMenu.Clear(); - if (matchingCargoGear.Any()) - ContextMenu.AddDropdown("Install", matchingCargoGear - .Select(gear => (gear.Name, () => entity.Equip(gear), true))); - if(matchingBlueprints.Any()) - ContextMenu.AddDropdown("Build", matchingBlueprints - .Select(blueprint => (blueprint.Name, () => entity.Build(blueprint, 1, _context.Cache.Get(blueprint.Item).Name, true), entity.GetBlueprintIngredients(blueprint, out _, out _)))); - ContextMenu.Show(); - } - }; - gearList.AddProperty($"Empty {Enum.GetName(typeof(HardpointType), hardpoint.Type)} Hardpoint", onClick, matchingBlueprints.Any()); + if (data.button == PointerEventData.InputButton.Left) + PopulateDetails(entity, matchingBlueprints); + + else if (data.button == PointerEventData.InputButton.Right) + { + ContextMenu.gameObject.SetActive(true); + ContextMenu.Clear(); + if (matchingCargoGear.Any()) + ContextMenu.AddDropdown("Install", matchingCargoGear + .Select(gear => (gear.Name, () => entity.Equip(gear, hardpoint), true))); + if (matchingBlueprints.Any()) + ContextMenu.AddDropdown("Build", matchingBlueprints + .Select(blueprint => + (blueprint.Name, () => + entity.Build(blueprint, 1, _context.Cache.Get(blueprint.Item).Name, true), + entity.GetBlueprintIngredients(blueprint, out _, out _)))); + ContextMenu.Show(); + } + }; + Inventory.AddProperty($"Empty {Enum.GetName(typeof(HardpointType), hardpoint.HardpointData.Type)} Hardpoint", null, onClick, matchingBlueprints.Any()); + } } else { - if (entity.IncompleteGear.ContainsKey(match.ID)) + var prop = Inventory.AddProperty(hardpoint.Gear.Name, null, _ => { - gearList.AddProgressField(match.Name, () => - { - var productionTime = _context.Cache.Get(match.Blueprint).ProductionTime; - return (productionTime - (float) entity.IncompleteGear[match.ID]) / productionTime; - }); - } - else - { - var prop = gearList.AddProperty(match.Name, null, _ => - { - _selectedHardpoint = hardpoint; - PopulateDetails(match, entity); - }, true); + _selectedHardpoint = hardpoint; + PopulateDetails(entity, hardpoint); + }, true); - if (hardpoint == _selectedHardpoint) prop.Button.OnPointerClick(new PointerEventData(null){button = PointerEventData.InputButton.Left}); - } - - - equippedItems.Remove(match); + if (hardpoint == _selectedHardpoint) prop.Button.OnPointerClick(new PointerEventData(null){button = PointerEventData.InputButton.Left}); } } if(!entity.Cargo.Any()) - Inventory.AddProperty("No Cargo"); + Inventory.AddSection("No Cargo"); else { - var cargoList = Inventory.AddList("Cargo"); + Inventory.AddSection("Cargo"); foreach (var x in cargoData) { if(x.Key is SimpleCommodity simpleCommodity) - cargoList.AddProperty(x.Value.Name, () => simpleCommodity.Quantity.ToString()); + Inventory.AddProperty(x.Value.Name, () => simpleCommodity.Quantity.ToString()); else - cargoList.AddProperty(x.Value.Name); + Inventory.AddProperty(x.Value.Name); } } Inventory.RefreshValues(); } - void PopulateDetails(ItemInstance item, Entity entity) + void PopulateDetails(Entity entity, IEnumerable blueprints) { Details.Clear(); - if (item is Gear gear) + foreach (var blueprint in blueprints) { - var data = gear.ItemData; - Details.AddProperty("Durability", - () => - $"{gear.Durability.SignificantDigits(Context.GlobalData.SignificantDigits)}/{Context.Evaluate(data.Durability, gear).SignificantDigits(Context.GlobalData.SignificantDigits)}"); - foreach (var behavior in entity.ItemBehaviors[gear]) + var blueprintList = Details.AddList(blueprint.Name); + + foreach (var ingredient in blueprint.Ingredients) { - if (behavior is Factory factory) + var itemData = _context.Cache.Get(ingredient.Key); + blueprintList.AddProperty(itemData.Name, () => ingredient.Value.ToString()); + } + + var bpItemData = _context.Cache.Get(blueprint.Item); + + if(entity.GetBlueprintIngredients(blueprint, out _, out _)) + blueprintList.AddButton("Build", _ => entity.Build(blueprint, 1, bpItemData.Name, true)); + } + Details.RefreshValues(); + } + + void PopulateDetails(Entity entity, Hardpoint hardpoint) + { + Details.Clear(); + Details.AddProperty("Durability", + () => $"{hardpoint.Gear.Durability.SignificantDigits(Context.GlobalData.SignificantDigits)}/{Context.Evaluate(hardpoint.ItemData.Durability, hardpoint.Gear).SignificantDigits(Context.GlobalData.SignificantDigits)}"); + foreach (var behavior in hardpoint.Behaviors) + { + if (behavior is Factory factory) + { + factory.OnProductionUpdate += () => PopulateDetails(entity, hardpoint); + Details.AddField("Production Quality", () => factory.ProductionQuality, f => factory.ProductionQuality = f, 0, 1); + var corporation = Context.Cache.Get(entity.Corporation); + var compatibleBlueprints = corporation.UnlockedBlueprints + .Select(id => _context.Cache.Get(id)) + .Where(bp => bp.FactoryItem == hardpoint.ItemData.ID).ToList(); + if (factory.RetoolingTime > 0) { - factory.OnToolingUpdate += () => PopulateDetails(item, entity); - Details.AddField("Production Quality", () => factory.ProductionQuality, f => factory.ProductionQuality = f, 0, 1); - var corporation = Context.Cache.Get(entity.Corporation); - var compatibleBlueprints = corporation.UnlockedBlueprints - .Select(id => _context.Cache.Get(id)) - .Where(bp => bp.FactoryItem == data.ID).ToList(); - if (factory.RetoolingTime > 0) + Details.AddProgressField("Retooling", () => (factory.ToolingTime - (float) factory.RetoolingTime) / factory.ToolingTime); + } + else + { + Details.AddField("Item", + () => compatibleBlueprints.FindIndex(bp=>bp.ID== factory.Blueprint) + 1, + i => factory.Blueprint = i == 0 ? Guid.Empty : compatibleBlueprints[i - 1].ID, + new []{"None"}.Concat(compatibleBlueprints.Select(bp=>bp.Name)).ToArray()); + if (factory.Blueprint != Guid.Empty) { - Details.AddProgressField("Retooling", () => (factory.ToolingTime - (float) factory.RetoolingTime) / factory.ToolingTime); - } - else - { - Details.AddField("Item", - () => compatibleBlueprints.FindIndex(bp=>bp.ID== factory.Blueprint) + 1, - i => factory.Blueprint = i == 0 ? Guid.Empty : compatibleBlueprints[i - 1].ID, - new []{"None"}.Concat(compatibleBlueprints.Select(bp=>bp.Name)).ToArray()); - if (factory.Blueprint != Guid.Empty) + if (factory.ItemUnderConstruction != Guid.Empty) { - if (factory.ItemsUnderConstruction.Any()) + Details.AddProgressField("Production", () => { - Details.AddProgressField("Production", () => - { - var itemUnderConstruction = factory.ItemsUnderConstruction[0]; - var itemInstance = _context.Cache.Get(itemUnderConstruction); - var blueprintData = _context.Cache.Get(itemInstance.Blueprint); - return (blueprintData.ProductionTime - (float) entity.IncompleteCargo[itemUnderConstruction]) / blueprintData.ProductionTime; - }); - } - else + var itemInstance = _context.Cache.Get(factory.ItemUnderConstruction); + var blueprintData = _context.Cache.Get(itemInstance.Blueprint); + return (blueprintData.ProductionTime - (float) entity.IncompleteCargo[factory.ItemUnderConstruction]) / blueprintData.ProductionTime; + }); + } + else + { + var ingredientsList = Details.AddList("Ingredients Needed"); + var blueprintData = _context.Cache.Get(factory.Blueprint); + foreach (var ingredient in blueprintData.Ingredients) { - var ingredientsList = Details.AddList("Ingredients Needed"); - var blueprintData = _context.Cache.Get(factory.Blueprint); - foreach (var ingredient in blueprintData.Ingredients) - { - var itemData = _context.Cache.Get(ingredient.Key); - ingredientsList.AddProperty(itemData.Name, () => ingredient.Value.ToString()); - } + var itemData = _context.Cache.Get(ingredient.Key); + ingredientsList.AddProperty(itemData.Name, () => ingredient.Value.ToString()); } } } } } - foreach (var behavior in data.Behaviors) + } + foreach (var behavior in hardpoint.ItemData.Behaviors) + { + var type = behavior.GetType(); + if (type.GetCustomAttribute(typeof(RuntimeInspectable)) != null) { - var type = behavior.GetType(); - if (type.GetCustomAttribute(typeof(RuntimeInspectable)) != null) + foreach (var field in type.GetFields().Where(f => f.GetCustomAttribute() != null)) { - foreach (var field in type.GetFields().Where(f => f.GetCustomAttribute() != null)) + var fieldType = field.FieldType; + if (fieldType == typeof(float)) + Details.AddProperty(field.Name, () => $"{((float) field.GetValue(behavior)).SignificantDigits(Context.GlobalData.SignificantDigits)}"); + else if (fieldType == typeof(int)) + Details.AddProperty(field.Name, () => $"{(int) field.GetValue(behavior)}"); + else if (fieldType == typeof(PerformanceStat)) { - var fieldType = field.FieldType; - if (fieldType == typeof(float)) - Details.AddProperty(field.Name, () => $"{((float) field.GetValue(behavior)).SignificantDigits(Context.GlobalData.SignificantDigits)}"); - else if (fieldType == typeof(int)) - Details.AddProperty(field.Name, () => $"{(int) field.GetValue(behavior)}"); - else if (fieldType == typeof(PerformanceStat)) - { - var stat = (PerformanceStat) field.GetValue(behavior); - Details.AddProperty(field.Name, () => $"{Context.Evaluate(stat, gear, entity).SignificantDigits(Context.GlobalData.SignificantDigits)}"); - } + var stat = (PerformanceStat) field.GetValue(behavior); + Details.AddProperty(field.Name, () => $"{Context.Evaluate(stat, hardpoint.Gear, entity).SignificantDigits(Context.GlobalData.SignificantDigits)}"); } } } diff --git a/Assets/Scripts/UI/PropertiesPanel.cs b/Assets/Scripts/UI/PropertiesPanel.cs index eeab81457..107670512 100644 --- a/Assets/Scripts/UI/PropertiesPanel.cs +++ b/Assets/Scripts/UI/PropertiesPanel.cs @@ -61,10 +61,14 @@ public class PropertiesPanel : MonoBehaviour return section; } - public PropertyLabel AddProperty(string name, Func read, Action onClick = null, bool radio = false) + public PropertyButton AddProperty(string name, Func read = null, Action onClick = null, bool radio = false) { - var property = Instantiate(PropertyLabelPrefab, transform); - property.Name.text = name; + PropertyButton property; + if(read != null) + property = Instantiate(PropertyLabelPrefab, transform); + else + property = Instantiate(PropertyPrefab, transform); + property.Label.text = name; if (radio) { RadioSelection = true; @@ -82,36 +86,13 @@ public class PropertiesPanel : MonoBehaviour }; } else if(onClick!=null) property.Button.OnClick += onClick; - RefreshPropertyValues += () => property.Value.text = read?.Invoke() ?? ""; + + if (read != null) + RefreshPropertyValues += () => ((PropertyLabel) property).Value.text = read.Invoke(); Properties.Add(property.gameObject); return property; } - public PropertyButton AddProperty(string name, Action onClick = null, bool radio = false) - { - var property = Instantiate(PropertyPrefab, transform); - property.Label.text = name; - if (radio) - { - RadioSelection = true; - Buttons.Add(property.Button); - property.Button.OnClick += data => - { - if (data.button == PointerEventData.InputButton.Left) - { - if (SelectedChild != null) - SelectedChild.CurrentState = FlatButtonState.Unselected; - SelectedChild = property.Button; - SelectedChild.CurrentState = FlatButtonState.Selected; - } - onClick?.Invoke(data); - }; - } - else if(onClick!=null) property.Button.OnClick += onClick; - Properties.Add(property.gameObject); - return property; - } - public PropertiesList AddList(string name) //, IEnumerable<(string, Func)> elements) { var list = Instantiate(ListPrefab, transform); diff --git a/Assets/Scripts/UI/PropertyLabel.cs b/Assets/Scripts/UI/PropertyLabel.cs index 8aed663a1..a55021d86 100644 --- a/Assets/Scripts/UI/PropertyLabel.cs +++ b/Assets/Scripts/UI/PropertyLabel.cs @@ -4,9 +4,7 @@ using System.Collections.Generic; using TMPro; using UnityEngine; -public class PropertyLabel : MonoBehaviour +public class PropertyLabel : PropertyButton { - public TextMeshProUGUI Name; public TextMeshProUGUI Value; - public FlatFlatButton Button; }