From 9623f0cc66131d9995a413f5b352edff699708b4 Mon Sep 17 00:00:00 2001 From: CommodoreChet <50426713+CommodoreChet@users.noreply.github.com> Date: Tue, 22 Oct 2024 15:59:59 -0500 Subject: [PATCH 1/3] Reapply "Update NHI_Cubeblocks.sbc" This reverts commit 793d9d6939b507cdb8d3aa1e2604e6d596c19dc1. --- .../Data/NHI_Cubeblocks.sbc | 125 +++++++++++++----- 1 file changed, 93 insertions(+), 32 deletions(-) diff --git a/Weapon Mods/Stable/NorseHeavyIndustries/Data/NHI_Cubeblocks.sbc b/Weapon Mods/Stable/NorseHeavyIndustries/Data/NHI_Cubeblocks.sbc index 9f382544d..e848bf0a6 100644 --- a/Weapon Mods/Stable/NorseHeavyIndustries/Data/NHI_Cubeblocks.sbc +++ b/Weapon Mods/Stable/NorseHeavyIndustries/Data/NHI_Cubeblocks.sbc @@ -313,10 +313,17 @@ Most Effective against Missiles, Rockets, and other Similar Guided Munitions, bu [NHI] 'Vanir' Light Autocannon -Light Autocannon that fires an APHE Round. -[Range: 3500] +[Turret Range: 3500m] +[Reload: 8 Seconds] +[Power Draw: 12MW] + +[Ammo Types: APHE] +[Shell Range: 3500m] [Shell Speed: 1250m/s] -[Damage Type: Energy] +[Damage Types: Energy] +[Damage Falloffs: None] + +Light Autocannon that fires an APHE Round. Textures\GUI\Icons\Odin_Defense_Cannon_1x1x2.dds Large @@ -371,7 +378,12 @@ Light Autocannon that fires an APHE Round. [Ammo Types: APHE] [Shell Range: 5000m] [Shell Speed: 1500m/s] -[Damage Type: EN/KIN] +[Damage Types: Energy] +[Damage Falloffs: None] + +General Purpose Autocannon. Uses an APHE round with no specific or special damage capabilities. + +None Textures\GUI\Icons\New_Autocannon_3x3_2.dds Large @@ -668,10 +680,17 @@ Heavy Railgun Turret that fires a single slug every 10 Seconds [NHI] Mk3 Battleship Cannon -A Heavy Battleship Cannon, Can fire either an HE Shell or Canister Shot -[Range: 7000] -[Shell Speed: 1400m/s] -[Damage Type: EN/KIN] +[Turret Range: 7000m] +[Reload: 13 Seconds] +[Power Draw: None] + +[Ammo Types: HE | HVAP] +[Shell Range: 8200m | 5200m] +[Shell Speed: 1800m/s | 3200m/s] +[Damage Types: Energy | Kinetic] +[Damage Falloffs: None] + +A Heavy Battleship Cannon. Fires an HE Shell or an HVAP Shell. Textures\GUI\Icons\Battleship_Cannon_Mk3.dds Large @@ -736,10 +755,17 @@ A Heavy Battleship Cannon, Can fire either an HE Shell or Canister Shot [NHI] Mk3 Battleship Cannon -A Heavy Battleship Cannon, Can fire either an HE Shell or Canister Shot -[Range: 7000] -[Shell Speed: 1400m/s] -[Damage Type: EN/KIN]. +[Turret Range: 7000m] +[Reload: 13 Seconds] +[Power Draw: None] + +[Ammo Types: HE | HVAP] +[Shell Range: 8200m | 5200m] +[Shell Speed: 1800m/s | 3200m/s] +[Damage Types: Energy | Kinetic] +[Damage Falloffs: None] + +A Heavy Battleship Cannon. Fires an HE Shell or an HVAP Shell. Textures\GUI\Icons\Battleship_Cannon_Mk3.dds Large @@ -805,10 +831,17 @@ A Heavy Battleship Cannon, Can fire either an HE Shell or Canister Shot [NHI] Mk2 Battleship Cannon -A Heavy Battleship Cannon, Fires an HE Shell -[Range: 6000] -[Shell Speed: 1100m/s] -[Damage Type: EN] +[Turret Range: 6000m] +[Reload: 9 Seconds] +[Power Draw: None] + +[Ammo Types: HE | HVAP] +[Shell Range: 7200m | 7200m] +[Shell Speed: 1100m/s | 2200m/s] +[Damage Types: Energy | Kinetic] +[Damage Falloffs: None] + +A Medium Battleship Cannon. Fires an HE Shell or an HVAP Shell. Textures\GUI\Icons\Battleship_Cannon_Mk2.dds Large @@ -874,10 +907,17 @@ A Heavy Battleship Cannon, Fires an HE Shell [NHI] Mk2 Battleship Cannon -A Heavy Battleship Cannon, Fires an HE Shell -[Range: 6000] -[Shell Speed: 1100m/s] -[Damage Type: EN] +[Turret Range: 6000m] +[Reload: 9 Seconds] +[Power Draw: None] + +[Ammo Types: HE | HVAP] +[Shell Range: 7200m | 7200m] +[Shell Speed: 1100m/s | 2200m/s] +[Damage Types: Energy | Kinetic] +[Damage Falloffs: None] + +A Medium Battleship Cannon. Fires an HE Shell or an HVAP Shell. Textures\GUI\Icons\Battleship_Cannon_Mk2.dds Large @@ -943,10 +983,17 @@ A Heavy Battleship Cannon, Fires an HE Shell [NHI] Mk1 Battleship Cannon -A Heavy Battleship Cannon, Fires an HE Shell -[Range: 5000] -[Shell Speed: 1100m/s] -[Damage Type: EN] +[Turret Range: 5000m] +[Reload: 4.5 Seconds] +[Power Draw: None] + +[Ammo Types: HE | HVAP] +[Shell Range: 6200m | 6200m] +[Shell Speed: 1100m/s | 2200m/s] +[Damage Types: Energy | Kinetic] +[Damage Falloffs: None] + +A Light Battleship Cannon. Fires an HE Shell or an HVAP Shell. Textures\GUI\Icons\Battleship_Cannon_Mk1.dds Large @@ -995,10 +1042,17 @@ A Heavy Battleship Cannon, Fires an HE Shell [NHI] Mk1 Battleship Cannon -A Heavy Battleship Cannon, Fires an HE Shell -[Range: 5000] -[Shell Speed: 1100m/s] -[Damage Type: EN] +[Turret Range: 5000m] +[Reload: 4.5 Seconds] +[Power Draw: None] + +[Ammo Types: HE | HVAP] +[Shell Range: 6200m | 6200m] +[Shell Speed: 1100m/s | 2200m/s] +[Damage Types: Energy | Kinetic] +[Damage Falloffs: None] + +A Light Battleship Cannon. Fires an HE Shell or an HVAP Shell. Textures\GUI\Icons\Battleship_Cannon_Mk1.dds Large @@ -1925,10 +1979,17 @@ Lacks the Ability to Heal Shields and and Must Completely cool down after reachi [NHI] 'Hurricane' Naval Gun - A Heavy Naval Cannon, Fires an APCBC Shell - [Range: 5000] - [Shell Speed: 1100m/s] - [Damage Type: KIN] +[Turret Range: 5000m] +[Reload: 5 Seconds] +[Power Draw: None] + +[Ammo Types: APCBC] +[Shell Range: 5400m] +[Shell Speed: 1300m/s] +[Damage Types: Kinetic] +[Damage Falloffs: None] + +A Heavy Naval Cannon, Fires an APCBC Shell Textures\GUI\Icons\NHI_Kinetic_Turret.dds Large From 5994dc92aa02d162ff27183dd0db0a204ef0d45e Mon Sep 17 00:00:00 2001 From: CommodoreChet <50426713+CommodoreChet@users.noreply.github.com> Date: Sat, 16 Nov 2024 13:25:52 -0600 Subject: [PATCH 2/3] properly fix --- ...block.sbc => EntityComponent_FieldGen.sbc} | 4 +- .../FieldGenerator/FieldGenerator_Core.cs | 563 +++++++++++------- .../FieldGenerator/FieldGenerator_Session.cs | 40 -- .../FieldGenerator_TerminalControls.cs | 32 +- .../HeartNetworking/ComponentBase.cs | 17 - .../HeartNetworking/Custom/BoolSyncPacket.cs | 65 -- .../HeartNetworking/Custom/FloatSyncPacket.cs | 75 --- .../HeartNetworking/Custom/IntSyncPacket.cs | 65 -- .../Custom/SyncRequestPacket.cs | 29 - .../HeartNetworking/HeartNetwork.cs | 202 ------- .../HeartNetworking/PacketBase.cs | 29 - .../HeartNetworking/PacketQueueManager.cs | 154 ----- 12 files changed, 361 insertions(+), 914 deletions(-) rename Utility Mods/Stable/SCDefenseBlocks/Data/{EntityComponents-resistblock.sbc => EntityComponent_FieldGen.sbc} (79%) delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/ComponentBase.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/BoolSyncPacket.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/FloatSyncPacket.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/IntSyncPacket.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/SyncRequestPacket.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/HeartNetwork.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketBase.cs delete mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketQueueManager.cs diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/EntityComponents-resistblock.sbc b/Utility Mods/Stable/SCDefenseBlocks/Data/EntityComponent_FieldGen.sbc similarity index 79% rename from Utility Mods/Stable/SCDefenseBlocks/Data/EntityComponents-resistblock.sbc rename to Utility Mods/Stable/SCDefenseBlocks/Data/EntityComponent_FieldGen.sbc index c72817b85..615190df2 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/EntityComponents-resistblock.sbc +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/EntityComponent_FieldGen.sbc @@ -3,10 +3,10 @@ ModStorageComponent - ShieldProjector + FieldGenerator - 169803f9-9800-4515-9619-e5385d5208fb + 7A7AC398-FAE3-44E5-ABD5-8AE49434DDF6 diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs index 5c3461e79..e90e0d9b3 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using Sandbox.ModAPI; using Sandbox.Common.ObjectBuilders; +using Sandbox.Game; using Sandbox.Game.EntityComponents; using ProtoBuf; using VRage.Game; @@ -17,8 +18,6 @@ using VRage.ObjectBuilders; using VRageMath; -using Starcore.FieldGenerator.Networking.Custom; - namespace Starcore.FieldGenerator { public class Config @@ -30,6 +29,7 @@ public class Config public const int MaxSiegeTime = 150; public const int SiegePowerDraw = 900; + public const float SiegeModeResistence = 0.9f; public const int DamageEventThreshold = 6; public const int ResetInterval = 3; @@ -49,140 +49,29 @@ public class FieldGenerator : MyGameLogicComponent, IMyEventProxy { private IMyCubeBlock Block; private readonly bool IsServer = MyAPIGateway.Session.IsServer; + public readonly Guid SettingsID = new Guid("7A7AC398-FAE3-44E5-ABD5-8AE49434DDF6"); private int _damageEventCounter = 0; private float _stabilityChange = 0; private int _resetCounter = 0; + private bool _lowStability = false; private int initValueDelayTicks = 60; // 1 second delay (60 ticks) private bool valuesInitialized = false; #region Sync Properties - public bool SiegeMode - { - get { return _siegeMode; } - set - { - if (_siegeMode != value) - { - _siegeMode = value; - BoolSyncPacket.SyncBoolProperty(Block.EntityId, nameof(SiegeMode), _siegeMode); - } - } - } - public bool _siegeMode; - - public bool SiegeCooldownActive - { - get { return _siegeCooldownActive; } - set - { - if (_siegeCooldownActive != value) - { - _siegeCooldownActive = value; - BoolSyncPacket.SyncBoolProperty(Block.EntityId, nameof(SiegeCooldownActive), _siegeCooldownActive); - } - } - } - public bool _siegeCooldownActive; - - public int SiegeElapsedTime - { - get { return _siegeElapsedTime; } - set - { - if (_siegeElapsedTime != value) - { - _siegeElapsedTime = value; - IntSyncPacket.SyncIntProperty(Block.EntityId, nameof(SiegeElapsedTime), _siegeElapsedTime); - } - } - } - public int _siegeElapsedTime; - - public int SiegeCooldownTime - { - get { return _siegeCooldownTime; } - set - { - if (_siegeCooldownTime != value) - { - _siegeCooldownTime = value; - IntSyncPacket.SyncIntProperty(Block.EntityId, nameof(SiegeCooldownTime), _siegeCooldownTime); - } - } - } - public int _siegeCooldownTime; - - public float FieldPower - { - get { return _fieldPower; } - set - { - if (_fieldPower != value) - { - _fieldPower = MathHelper.Clamp(value, MinFieldPower, MaxFieldPower); - FloatSyncPacket.SyncFloatProperty(Block.EntityId, nameof(FieldPower), _fieldPower); - } - } - } - public float _fieldPower; - - public float MaxFieldPower - { - get { return _maxFieldPower; } - set - { - if (_maxFieldPower != value) - { - _maxFieldPower = value; - FloatSyncPacket.SyncFloatProperty(Block.EntityId, nameof(MaxFieldPower), _maxFieldPower); - } - } - } - public float _maxFieldPower; + public MySync SiegeMode; + public MySync SiegeCooldownActive; + public MySync GridStopped = null; - public float MinFieldPower - { - get { return _minFieldPower; } - set - { - if (_minFieldPower != value) - { - _minFieldPower = value; - FloatSyncPacket.SyncFloatProperty(Block.EntityId, nameof(MinFieldPower), _minFieldPower); - } - } - } - public float _minFieldPower; + public MySync SiegeElapsedTime; + public MySync SiegeCooldownTime; - public float SizeModifier - { - get { return _sizeModifier; } - set - { - if (_sizeModifier != value) - { - _sizeModifier = value; - FloatSyncPacket.SyncFloatProperty(Block.EntityId, nameof(SizeModifier), _sizeModifier); - } - } - } - public float _sizeModifier; - - public float Stability - { - get { return _stability; } - set - { - if (_stability != value) - { - _stability = value; - FloatSyncPacket.SyncFloatProperty(Block.EntityId, nameof(Stability), _stability); - } - } - } - public float _stability; + public MySync FieldPower; // add on value change hook for Serverside Resistence + public MySync MaxFieldPower; + public MySync MinFieldPower; + public MySync SizeModifier; + public MySync Stability; // add on value change for handling zero stability if (IsServer && _stability == 0) HandleZeroStability(); #endregion private Dictionary _coreDummies = new Dictionary(); @@ -192,19 +81,18 @@ public float Stability private List _gridBlocks = new List(); private int _gridBlockCount; - public MySync GridStopped = null; - private MyResourceSinkComponent Sink = null; private IMyHudNotification notifSiege = null; private IMyHudNotification notifPower = null; + private IMyHudNotification notifStability = null; #region Overrides public override void Init(MyObjectBuilder_EntityBase objectBuilder) { base.Init(objectBuilder); - Block = (IMyCubeBlock)Entity; + Block = (IMyFunctionalBlock)Entity; NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; } @@ -216,21 +104,41 @@ public override void UpdateOnceBeforeFrame() if (Block?.CubeGrid?.Physics == null) return; - FieldGeneratorControls.DoOnce(ModContext); + FieldGeneratorControls.DoOnce(ModContext); Sink = Block.Components.Get(); - Sink.SetRequiredInputFuncByType(MyResourceDistributorComponent.ElectricityId, CalculatePowerDraw); + if (Sink != null) + { + Sink.SetRequiredInputFuncByType(MyResourceDistributorComponent.ElectricityId, CalculatePowerDraw); + Sink.Update(); + } if (IsServer) { Block.Model.GetDummies(_coreDummies); - Block.CubeGrid.GetBlocks(_gridBlocks); _gridBlockCount = _gridBlocks.Count; - MyAPIGateway.Session.DamageSystem.RegisterBeforeDamageHandler(0, HandleResistence); + LoadSettings(); + + if (!Config.SimplifiedMode) + { + MyAPIGateway.Session.DamageSystem.RegisterBeforeDamageHandler(0, HandleDamageEvents); + } + Block.CubeGrid.OnBlockAdded += OnBlockAdded; Block.CubeGrid.OnBlockRemoved += OnBlockRemoved; + + SiegeCooldownActive.ValueChanged += (obj) => SaveSettings(); + SiegeElapsedTime.ValueChanged += (obj) => SaveSettings(); + SiegeCooldownTime.ValueChanged += (obj) => SaveSettings(); + MaxFieldPower.ValueChanged += (obj) => SaveSettings(); + MinFieldPower.ValueChanged += (obj) => SaveSettings(); + SizeModifier.ValueChanged += (obj) => SaveSettings(); + + SiegeMode.ValueChanged += SiegeMode_ValueChanged; + FieldPower.ValueChanged += FieldPower_ValueChanged; + Stability.ValueChanged += Stability_ValueChanged; } if (!IsServer) @@ -240,77 +148,96 @@ public override void UpdateOnceBeforeFrame() NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME; NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME; - } + } public override void UpdateAfterSimulation() { base.UpdateAfterSimulation(); - if (IsServer && !valuesInitialized) + if (IsServer) { - if (initValueDelayTicks > 0) - { - initValueDelayTicks--; - } - else + if (!valuesInitialized) { - Stability = 100; - InitExistingUpgrades(); - valuesInitialized = true; + if (initValueDelayTicks > 0) + { + initValueDelayTicks--; + } + else + { + Stability.Value = 100; + InitExistingUpgrades(); + valuesInitialized = true; + } } } - if (!IsServer) - return; - if (MyAPIGateway.Session.GameplayFrameCounter % 60 == 0) { if (Block.IsWorking) { - Sink.Update(); - - UpdateSiegeState(); - - if (!Config.SimplifiedMode) + if (IsServer) { - SizeModifier = CalculateSizeModifier(); + UpdateSiegeState(); - if (_damageEventCounter > Config.DamageEventThreshold) + if (!Config.SimplifiedMode) { - _stabilityChange = -((1.6666666666667f * SizeModifier) * (FieldPower / 50)); + if (_lowStability && Stability.Value < 100) + { + Stability.Value = MathHelper.Clamp(Stability + 3, 0, 100); + HandleZeroStability(); + if (Stability.Value == 100) + { + _lowStability = false; + } + return; + } + + SizeModifier.Value = CalculateSizeModifier(); + + if (_damageEventCounter > Config.DamageEventThreshold) + { + _stabilityChange = -((1.6666666666667f * SizeModifier.Value) * (FieldPower.Value / 50)); + } + else + { + _stabilityChange = 3; + } + + Stability.Value = MathHelper.Clamp(Stability + _stabilityChange, 0, 100); + + if (_resetCounter < Config.ResetInterval) + { + _resetCounter++; + return; + } + else if (_resetCounter >= Config.ResetInterval) + { + _resetCounter = 0; + _damageEventCounter = 0; + return; + } } - else - { - _stabilityChange = 3; - } - - _stability = MathHelper.Clamp(_stability + _stabilityChange, 0, 100); - - if (_resetCounter < Config.ResetInterval) - { - _resetCounter++; - return; - } - else if (_resetCounter >= Config.ResetInterval) - { - _resetCounter = 0; - _damageEventCounter = 0; - return; - } - } + } + else + Sink.Update(); } else if (!Block.IsWorking) { - if (FieldPower > 0) - FieldPower = 0; - - if (SiegeMode) + if (IsServer) { - CancelSiegeMode(); - SiegeMode = false; - } + if (FieldPower.Value > 0) + FieldPower.Value = 0; + + if (SiegeMode.Value) + { + CancelSiegeMode(); + SiegeMode.Value = false; + } + } + else + Sink.Update(); } - } + } } public override void UpdateAfterSimulation10() @@ -319,13 +246,13 @@ public override void UpdateAfterSimulation10() if (IsClientInShip() || IsClientNearShip()) { - if (SiegeMode) + if (SiegeMode.Value) { - SetSiegeNotification($" Siege Mode Active | {SiegeElapsedTime} / {Config.MaxSiegeTime}", 600); + SetSiegeNotification($" Siege Mode Active | {SiegeElapsedTime.Value} / {Config.MaxSiegeTime}", 600); } - else if (!SiegeMode && SiegeCooldownActive) + else if (!SiegeMode.Value && SiegeCooldownActive.Value) { - SetSiegeNotification($" Siege Mode On Cooldown | {SiegeCooldownTime}", 600, "Red"); + SetSiegeNotification($" Siege Mode On Cooldown | {SiegeCooldownTime.Value}", 600, "Red"); } if (!Block.IsWorking) @@ -333,11 +260,26 @@ public override void UpdateAfterSimulation10() string reason = Block.IsFunctional ? "Insufficient Power?" : "Block Damaged!"; SetPowerNotification($" Generator Core is Offline! | {reason}", 600, "Red"); } + + if (!Config.SimplifiedMode) + { + SetStabilityNotification($"[Generator Stability: {Stability.Value}]", 600, "Red"); + } } else return; } + public override bool IsSerialized() + { + if (Block == null ) + return false; + + SaveSettings(); + + return base.IsSerialized(); + } + public override void Close() { base.Close(); @@ -346,6 +288,17 @@ public override void Close() { Block.CubeGrid.OnBlockAdded -= OnBlockAdded; Block.CubeGrid.OnBlockRemoved -= OnBlockRemoved; + + SiegeCooldownActive.ValueChanged -= (obj) => SaveSettings(); + SiegeElapsedTime.ValueChanged -= (obj) => SaveSettings(); + SiegeCooldownTime.ValueChanged -= (obj) => SaveSettings(); + MaxFieldPower.ValueChanged -= (obj) => SaveSettings(); + MinFieldPower.ValueChanged -= (obj) => SaveSettings(); + SizeModifier.ValueChanged -= (obj) => SaveSettings(); + + SiegeMode.ValueChanged += SiegeMode_ValueChanged; + FieldPower.ValueChanged -= FieldPower_ValueChanged; + Stability.ValueChanged -= Stability_ValueChanged; } if (!IsServer) @@ -357,7 +310,7 @@ public override void Close() } #endregion - #region Subscription Event Handlers + #region Event Handlers private void OnBlockAdded(IMySlimBlock block) { if (block == null) @@ -370,7 +323,7 @@ private void OnBlockAdded(IMySlimBlock block) if (block.FatBlock != null && block.FatBlock.BlockDefinition.SubtypeId == "FieldGen_Capacity_Upgrade") { - if (IsNeighbour(block)/* && IsModuleValid(block)*/) + if (IsNeighbour(block) && IsModuleValid(block)) { long entityId = block.FatBlock.EntityId; @@ -409,7 +362,7 @@ private void OnBlockRemoved(IMySlimBlock block) } } - private void HandleResistence(object target, ref MyDamageInformation info) + private void HandleDamageEvents(object target, ref MyDamageInformation info) { if (Block == null || !Block.IsWorking) return; @@ -423,21 +376,59 @@ private void HandleResistence(object target, ref MyDamageInformation info) if (targetGrid.EntityId != Block.CubeGrid.EntityId) return; - if (SiegeMode) - { - info.Amount *= 0.1f; - return; - } + _damageEventCounter++; + return; + } + } - if (!Config.SimplifiedMode) - { - _damageEventCounter++; - } + private void HandleResistence() + { + if (Block == null || !Block.IsWorking) + return; - float roundedModifier = (float)Math.Round(1 - ((double)FieldPower / 100), 3); - info.Amount *= roundedModifier; + if (SiegeMode.Value) + { + MyVisualScriptLogicProvider.SetGridGeneralDamageModifier(Block.CubeGrid.Name, (1 - Config.SiegeModeResistence)); return; } + else + MyVisualScriptLogicProvider.SetGridGeneralDamageModifier(Block.CubeGrid.Name, (float)Math.Round(1 - ((double)FieldPower.Value / 100), 3)); + } + + private void HandleZeroStability() + { + if (Block == null || !Block.IsWorking) + return; + + FieldPower.Value = 10; + _lowStability = true; + } + + private void SiegeMode_ValueChanged(MySync obj) + { + SaveSettings(); + Sink.Update(); + + if (IsServer) + HandleResistence(); + } + + private void FieldPower_ValueChanged(MySync obj) + { + FieldPower.Value = MathHelper.Clamp(obj.Value, MinFieldPower.Value, MaxFieldPower.Value); + SaveSettings(); + Sink.Update(); + + if (IsServer) + HandleResistence(); + } + + private void Stability_ValueChanged(MySync obj) + { + SaveSettings(); + + if (IsServer) + HandleZeroStability(); } private void OnGridStopValueChange(MySync obj) @@ -450,12 +441,12 @@ private void OnGridStopValueChange(MySync obj) #region Siege Mode private void UpdateSiegeState() { - if (SiegeMode && !SiegeCooldownActive) + if (SiegeMode.Value && !SiegeCooldownActive.Value) { - if (SiegeElapsedTime + 1 <= Config.MaxSiegeTime) - { - SiegeElapsedTime++; - SiegeBlockEnabler(_gridBlocks, false); + if (SiegeElapsedTime.Value + 1 <= Config.MaxSiegeTime) + { + SiegeElapsedTime.Value++; + SiegeBlockEnabler(_gridBlocks, false); if (Block.CubeGrid.Physics.LinearVelocity != Vector3D.Zero) { @@ -467,26 +458,26 @@ private void UpdateSiegeState() else { EndSiegeMode(); - SiegeMode = false; + SiegeMode.Value = false; return; } } - if (!SiegeMode && !SiegeCooldownActive && SiegeElapsedTime > 0) + if (!SiegeMode.Value && !SiegeCooldownActive.Value && SiegeElapsedTime.Value > 0) { EndSiegeMode(); return; } - if (SiegeCooldownActive) + if (SiegeCooldownActive.Value) { - if (SiegeCooldownTime > 0) + if (SiegeCooldownTime.Value > 0) { - SiegeCooldownTime--; + SiegeCooldownTime.Value--; } else { - SiegeCooldownActive = false; + SiegeCooldownActive.Value = false; } } } @@ -522,9 +513,9 @@ private void EndSiegeMode() SiegeBlockEnabler(_gridBlocks, true); - SiegeCooldownTime = (SiegeElapsedTime > 5) ? (SiegeElapsedTime * 2) : 5; - SiegeElapsedTime = 0; - SiegeCooldownActive = true; + SiegeCooldownTime.Value = (SiegeElapsedTime.Value > 5) ? (SiegeElapsedTime.Value * 2) : 5; + SiegeElapsedTime.Value = 0; + SiegeCooldownActive.Value = true; } private void CancelSiegeMode() @@ -534,8 +525,8 @@ private void CancelSiegeMode() SiegeBlockEnabler(_gridBlocks, true); - SiegeCooldownTime = 0; - SiegeElapsedTime = 0; + SiegeCooldownTime.Value = 0; + SiegeElapsedTime.Value = 0; } #endregion @@ -627,11 +618,11 @@ private bool IsModuleValid(IMySlimBlock neighbor) private void CalculateUpgradeAmounts() { - MaxFieldPower = MinFieldPower + (_moduleCount * Config.PerModuleAmount); + MaxFieldPower.Value = MinFieldPower.Value + (_moduleCount * Config.PerModuleAmount); - if (FieldPower > MaxFieldPower) + if (FieldPower.Value > MaxFieldPower.Value) { - FieldPower = MaxFieldPower; + FieldPower.Value = MaxFieldPower.Value; } } @@ -645,13 +636,13 @@ private float CalculateSizeModifier() private float CalculatePowerDraw() { - if (SiegeMode) + if (SiegeMode.Value) { return Config.SiegePowerDraw; } float maxPossibleFieldPower = Config.PerModuleAmount * Config.MaxModuleCount; - float clampedFieldPower = MathHelper.Clamp(FieldPower, 0, maxPossibleFieldPower); + float clampedFieldPower = MathHelper.Clamp(FieldPower.Value, 0, maxPossibleFieldPower); float t = clampedFieldPower / maxPossibleFieldPower; return Config.MinPowerDraw + t * (Config.MaxPowerDraw - Config.MinPowerDraw); @@ -693,7 +684,96 @@ private bool IsClientNearShip() } return false; - } + } + #endregion + + #region Settings + bool LoadSettings() + { + if (Block.Storage == null) + { + Log.Info($"LoadSettings: Block storage is null for {Block.EntityId}"); + return false; + } + + string rawData; + if (!Block.Storage.TryGetValue(SettingsID, out rawData)) + { + Log.Info($"LoadSettings: No data found for {Block.EntityId}"); + return false; + } + + try + { + var loadedSettings = MyAPIGateway.Utilities.SerializeFromBinary(Convert.FromBase64String(rawData)); + + if (loadedSettings != null) + { + Log.Info($"LoadSettings: Successfully loaded settings for {Block.EntityId}"); + + SiegeMode.Value = loadedSettings.Saved_SiegeMode; + SiegeCooldownActive.Value = loadedSettings.Saved_SiegeCooldownActive; + SiegeElapsedTime.Value = loadedSettings.Saved_SiegeElapsedTime; + SiegeCooldownTime.Value = loadedSettings.Saved_SiegeCooldownTime; + FieldPower.Value = loadedSettings.Saved_FieldPower; + MaxFieldPower.Value = loadedSettings.Saved_MaxFieldPower; + MinFieldPower.Value = loadedSettings.Saved_MinFieldPower; + SizeModifier.Value = loadedSettings.Saved_SizeModifier; + Stability.Value = loadedSettings.Saved_Stability; + + + return true; + } + } + catch (Exception e) + { + Log.Error($"Error loading settings for {Block.EntityId}!\n{e}"); + } + + return false; + } + + void SaveSettings() + { + if (Block == null) + { + Log.Info("SaveSettings called but Block is null."); + return; + } + + try + { + if (MyAPIGateway.Utilities == null) + throw new NullReferenceException($"MyAPIGateway.Utilities == null; entId={Entity?.EntityId};"); + + if (Block.Storage == null) + { + Log.Info($"Creating new storage for {Block.EntityId}"); + Block.Storage = new MyModStorageComponent(); + } + + var settings = new FieldGenSettings + { + Saved_SiegeMode = SiegeMode.Value, + Saved_SiegeCooldownActive = SiegeCooldownActive.Value, + Saved_SiegeElapsedTime = SiegeElapsedTime.Value, + Saved_SiegeCooldownTime = SiegeCooldownTime.Value, + Saved_FieldPower = FieldPower.Value, + Saved_MaxFieldPower = MaxFieldPower.Value, + Saved_MinFieldPower = MinFieldPower.Value, + Saved_SizeModifier = SizeModifier.Value, + Saved_Stability = Stability.Value, + }; + + string serializedData = Convert.ToBase64String(MyAPIGateway.Utilities.SerializeToBinary(settings)); + Block.Storage.SetValue(SettingsID, serializedData); + Log.Info($"SaveSettings: Successfully saved settings for {Block.EntityId}"); + } + catch (Exception e) + { + Log.Error($"Error saving settings for {Block.EntityId}!\n{e}"); + } + } #endregion #region Notifs @@ -720,6 +800,49 @@ public void SetPowerNotification(string text, int aliveTime = 300, string font = notifPower.AliveTime = aliveTime; notifPower.Show(); } + + public void SetStabilityNotification(string text, int aliveTime = 300, string font = MyFontEnum.Green) + { + if (notifStability == null) + notifStability = MyAPIGateway.Utilities.CreateNotification("", aliveTime, font); + + notifStability.Hide(); + notifStability.Font = font; + notifStability.Text = text; + notifStability.AliveTime = aliveTime; + notifStability.Show(); + } #endregion } + + [ProtoContract] + public class FieldGenSettings + { + [ProtoMember(41)] + public bool Saved_SiegeMode; + + [ProtoMember(42)] + public bool Saved_SiegeCooldownActive; + + [ProtoMember(43)] + public int Saved_SiegeElapsedTime; + + [ProtoMember(44)] + public int Saved_SiegeCooldownTime; + + [ProtoMember(45)] + public float Saved_FieldPower; + + [ProtoMember(46)] + public float Saved_MaxFieldPower; + + [ProtoMember(47)] + public float Saved_MinFieldPower; + + [ProtoMember(48)] + public float Saved_SizeModifier; + + [ProtoMember(49)] + public float Saved_Stability; + } } diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs index de62d6eda..104d314c0 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs @@ -5,9 +5,7 @@ using System.Threading.Tasks; using VRage.Game.Components; using CoreSystems.Api; -using Starcore.FieldGenerator.Networking; using Sandbox.ModAPI; -using Starcore.FieldGenerator.Networking.Custom; namespace Starcore.FieldGenerator { @@ -15,55 +13,17 @@ namespace Starcore.FieldGenerator public class FieldGeneratorSession : MySessionComponentBase { public static WcApi CoreSysAPI; - public static HeartNetwork Networking = new HeartNetwork(); - public static PacketQueueManager PacketQueue = new PacketQueueManager(); public override void LoadData() { base.LoadData(); - Networking.Init("FieldGeneratorNetwork"); - PacketQueue.Init(); - CoreSysAPI = new WcApi(); CoreSysAPI.Load(); } - public override void UpdateAfterSimulation() - { - base.UpdateAfterSimulation(); - - if (!PacketQueueManager.I.QueuesWithPackets()) - return; - - foreach (long entityID in PacketQueueManager.I.EntitiesWithQueue()) - { - PacketBase packet = PacketQueueManager.I.FirstInQueue(entityID); - - if (packet != null) - { - if (HeartNetwork.CheckRateLimit(entityID)) - { - Log.Info($"PacketManager: Queued Packet Found for Entity ID: {entityID}"); - - if (MyAPIGateway.Session.IsServer) - HeartNetwork.I.SendToEveryone(packet); - else - HeartNetwork.I.SendToServer(packet); - - Log.Info($"PacketManager: Sent Queued Packet for Entity ID: {entityID}, Removing From Queue"); - - PacketQueueManager.I.DequeuePacket(entityID); - } - } - } - } - protected override void UnloadData() { - Networking.Close(); - PacketQueue.Close(); - if (CoreSysAPI.IsReady) { CoreSysAPI.Unload(); diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_TerminalControls.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_TerminalControls.cs index 544e37c6b..d03d2da6a 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_TerminalControls.cs +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_TerminalControls.cs @@ -63,8 +63,8 @@ static void CreateControls() SiegeModeToggle.OffText = MyStringId.GetOrCompute("Off"); SiegeModeToggle.Visible = IsVisible; SiegeModeToggle.Enabled = CooldownEnabler; - SiegeModeToggle.Getter = (b) => b.GameLogic.GetAs().SiegeMode; - SiegeModeToggle.Setter = (b, v) => b.GameLogic.GetAs().SiegeMode = v; + SiegeModeToggle.Getter = (b) => b.GameLogic.GetAs().SiegeMode.Value; + SiegeModeToggle.Setter = (b, v) => b.GameLogic.GetAs().SiegeMode.Value = v; SiegeModeToggle.SupportsMultipleBlocks = true; MyAPIGateway.TerminalControls.AddControl(SiegeModeToggle); #endregion @@ -84,7 +84,7 @@ static void CreateControls() var logic = GetLogic(b); if (logic != null) { - return !logic.SiegeMode; + return !logic.SiegeMode.Value; } else return true; @@ -94,12 +94,12 @@ static void CreateControls() var logic = GetLogic(b); if (logic != null) { - float value = logic.FieldPower; + float value = logic.FieldPower.Value; w.Append(Math.Round(value, 1, MidpointRounding.ToEven)).Append('%'); } }; - FieldPowerSlider.Getter = (b) => b.GameLogic.GetAs().FieldPower; - FieldPowerSlider.Setter = (b, v) => b.GameLogic.GetAs().FieldPower = (int)Math.Round(v, 1); + FieldPowerSlider.Getter = (b) => b.GameLogic.GetAs().FieldPower.Value; + FieldPowerSlider.Setter = (b, v) => b.GameLogic.GetAs().FieldPower.Value = (int)Math.Round(v, 1); FieldPowerSlider.SupportsMultipleBlocks = true; MyAPIGateway.TerminalControls.AddControl(FieldPowerSlider); #endregion @@ -117,7 +117,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - logic.SiegeMode = !logic.SiegeMode; + logic.SiegeMode.Value = !logic.SiegeMode.Value; } }; SiegeToggleAction.Writer = (b, sb) => @@ -125,7 +125,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - string boolState = logic.SiegeMode ? "Active" : "Inactive"; + string boolState = logic.SiegeMode.Value ? "Active" : "Inactive"; sb.Append(boolState); } }; @@ -149,7 +149,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - logic.FieldPower += 2.5f; + logic.FieldPower.Value += 2.5f; } }; IncreasePowerAction.Writer = (b, sb) => @@ -157,7 +157,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - sb.Append($"{logic.FieldPower}%"); + sb.Append($"{logic.FieldPower.Value}%"); } }; IncreasePowerAction.InvalidToolbarTypes = new List() @@ -171,7 +171,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - return !logic.SiegeMode; + return !logic.SiegeMode.Value; } else return true; @@ -189,7 +189,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - logic.FieldPower -= 2.5f; + logic.FieldPower.Value -= 2.5f; } }; DecreasePowerAction.Writer = (b, sb) => @@ -197,7 +197,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - sb.Append($"{logic.FieldPower}%"); + sb.Append($"{logic.FieldPower.Value}%"); } }; DecreasePowerAction.InvalidToolbarTypes = new List() @@ -211,7 +211,7 @@ static void CreateActions(IMyModContext context) var logic = GetLogic(b); if (logic != null) { - return !logic.SiegeMode; + return !logic.SiegeMode.Value; } else return true; @@ -227,7 +227,7 @@ static float GetMinLimit(IMyTerminalBlock block) var logic = GetLogic(block); if (logic != null) { - return logic.MinFieldPower; + return logic.MinFieldPower.Value; } return 0; } @@ -237,7 +237,7 @@ static float GetMaxLimit(IMyTerminalBlock block) var logic = GetLogic(block); if (logic != null) { - return logic.MaxFieldPower; + return logic.MaxFieldPower.Value; } return 0; } diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/ComponentBase.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/ComponentBase.cs deleted file mode 100644 index 6dd8fd08f..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/ComponentBase.cs +++ /dev/null @@ -1,17 +0,0 @@ - -namespace Starcore.FieldGenerator -{ - public abstract class ComponentBase - { - public string ComponentId; - - public virtual void Init(string id) - { - ComponentId = id; - } - - public abstract void Close(); - - public abstract void UpdateTick(); - } -} \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/BoolSyncPacket.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/BoolSyncPacket.cs deleted file mode 100644 index abbdd2be4..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/BoolSyncPacket.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using ProtoBuf; -using Sandbox.ModAPI; - -namespace Starcore.FieldGenerator.Networking.Custom -{ - [ProtoContract] - public class BoolSyncPacket : PacketBase - { - [ProtoMember(21)] public string propertyName; - [ProtoMember(22)] private bool value; - [ProtoMember(23)] public long entityId; - - public override void Received(ulong SenderSteamId) - { - Log.Info($"Received Bool Sync: {propertyName} = {value}"); - - var fieldGenerator = FieldGenerator.GetLogic(entityId); - - if (fieldGenerator != null) - { - switch (propertyName) - { - case nameof(FieldGenerator.SiegeMode): - fieldGenerator.SiegeMode = value; - break; - case nameof(FieldGenerator.SiegeCooldownActive): - fieldGenerator.SiegeCooldownActive = value; - break; - // Add other bool properties as needed - } - - if (MyAPIGateway.Session.IsServer) - { - HeartNetwork.I.SendToEveryone(this); - } - } - else - { - Log.Info($"Received method failed: FieldGenerator is null. Entity ID: {entityId}"); - } - } - - public static void SyncBoolProperty(long entityId, string propertyName, bool value) - { - try - { - var packet = new BoolSyncPacket - { - entityId = entityId, - propertyName = propertyName, - value = value - }; - - Log.Info($"Bool-Type Packet Added to Queue: {propertyName} = {value}"); - - PacketQueueManager.I.EnqueuePacket(packet); - } - catch (Exception ex) - { - Log.Error(ex); - } - } - } -} \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/FloatSyncPacket.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/FloatSyncPacket.cs deleted file mode 100644 index de8c0fbb9..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/FloatSyncPacket.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Collections.Generic; -using ProtoBuf; -using Sandbox.ModAPI; - -namespace Starcore.FieldGenerator.Networking.Custom -{ - [ProtoContract] - public class FloatSyncPacket : PacketBase - { - [ProtoMember(31)] public string propertyName; - [ProtoMember(32)] private float value; - [ProtoMember(33)] public long entityId; - - public override void Received(ulong SenderSteamId) - { - Log.Info($"Received Float Sync: {propertyName} = {value}"); - - var fieldGenerator = FieldGenerator.GetLogic(entityId); - - if (fieldGenerator != null) - { - switch (propertyName) - { - case nameof(FieldGenerator.FieldPower): - fieldGenerator.FieldPower = value; - break; - case nameof(FieldGenerator.MaxFieldPower): - fieldGenerator.MaxFieldPower = value; - break; - case nameof(FieldGenerator.MinFieldPower): - fieldGenerator.MinFieldPower = value; - break; - case nameof(FieldGenerator.SizeModifier): - fieldGenerator.SizeModifier = value; - break; - case nameof(FieldGenerator.Stability): - fieldGenerator.Stability = value; - break; - // Add other float properties as needed - } - - if (MyAPIGateway.Session.IsServer) - { - HeartNetwork.I.SendToEveryone(this); - } - } - else - { - Log.Info($"Received method failed: FieldGenerator is null. Entity ID: {entityId}"); - } - } - - public static void SyncFloatProperty(long entityId, string propertyName, float value) - { - try - { - var packet = new FloatSyncPacket - { - entityId = entityId, - propertyName = propertyName, - value = value - }; - - Log.Info($"Float-Type Packet Added to Queue: {propertyName} = {value}"); - - PacketQueueManager.I.EnqueuePacket(packet); - } - catch (Exception ex) - { - Log.Error(ex); - } - } - } -} \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/IntSyncPacket.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/IntSyncPacket.cs deleted file mode 100644 index eb71164e9..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/IntSyncPacket.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using ProtoBuf; -using Sandbox.ModAPI; - -namespace Starcore.FieldGenerator.Networking.Custom -{ - [ProtoContract] - public class IntSyncPacket : PacketBase - { - [ProtoMember(41)] public string propertyName; - [ProtoMember(42)] private int value; - [ProtoMember(43)] public long entityId; - - public override void Received(ulong SenderSteamId) - { - Log.Info($"Received Int Sync: {propertyName} = {value}"); - - var fieldGenerator = FieldGenerator.GetLogic(entityId); - - if (fieldGenerator != null) - { - switch (propertyName) - { - case nameof(FieldGenerator.SiegeElapsedTime): - fieldGenerator.SiegeElapsedTime = value; - break; - case nameof(FieldGenerator.SiegeCooldownTime): - fieldGenerator.SiegeCooldownTime = value; - break; - // Add other int properties as needed - } - - if (MyAPIGateway.Session.IsServer) - { - HeartNetwork.I.SendToEveryone(this); - } - } - else - { - Log.Info($"Received method failed: FieldGenerator is null. Entity ID: {entityId}"); - } - } - - public static void SyncIntProperty(long entityId, string propertyName, int value) - { - try - { - var packet = new IntSyncPacket - { - entityId = entityId, - propertyName = propertyName, - value = value - }; - - Log.Info($"Int-Type Packet Added to Queue: {propertyName} = {value}"); - - PacketQueueManager.I.EnqueuePacket(packet); - } - catch (Exception ex) - { - Log.Error(ex); - } - } - } -} \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/SyncRequestPacket.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/SyncRequestPacket.cs deleted file mode 100644 index 88310c4cf..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/Custom/SyncRequestPacket.cs +++ /dev/null @@ -1,29 +0,0 @@ -/*using System; -using ProtoBuf; - -namespace Starcore.FieldGenerator.Networking.Custom -{ - [ProtoContract] - public class SyncRequestPacket : PacketBase - { - [ProtoMember(12)] private long entityId; - - public override void Received(ulong SenderSteamId) - { - Log.Info("Recived Sync Request From: " + SenderSteamId); - SiegeModePacket.UpdateSiegeMode(entityId); - FieldPowerPacket.UpdateFieldPower(entityId); - MaxFieldPowerPacket.UpdateMaxFieldPower(entityId); - } - - public static void RequestSync(long entityID) - { - SyncRequestPacket packet = new SyncRequestPacket - { - entityId = entityID, - }; - - HeartNetwork.I.SendToServer(packet); - } - } -}*/ \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/HeartNetwork.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/HeartNetwork.cs deleted file mode 100644 index e6a8e6db3..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/HeartNetwork.cs +++ /dev/null @@ -1,202 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Sandbox.ModAPI; -using VRage.Game.ModAPI; - -namespace Starcore.FieldGenerator.Networking -{ - public class HeartNetwork : ComponentBase - { - public static HeartNetwork I; - - private int _networkLoadUpdate; - public int NetworkLoadTicks = 240; - - private readonly List TempPlayers = new List(); - public Dictionary TypeNetworkLoad = new Dictionary(); - - public ushort NetworkId { get; private set; } - public int TotalNetworkLoad { get; private set; } - - private Dictionary _rateLimiter = new Dictionary(); - - public override void Init(string id) - { - base.Init(id); - I = this; - - NetworkId = 20877; - MyAPIGateway.Multiplayer.RegisterSecureMessageHandler(NetworkId, ReceivedPacket); - - foreach (var type in PacketBase.PacketTypes) TypeNetworkLoad.Add(type, 0); - } - - public override void UpdateTick() - { - _networkLoadUpdate--; - if (_networkLoadUpdate <= 0) - { - _networkLoadUpdate = NetworkLoadTicks; - TotalNetworkLoad = 0; - foreach (var networkLoadArray in TypeNetworkLoad.Keys.ToArray()) - { - TotalNetworkLoad += TypeNetworkLoad[networkLoadArray]; - TypeNetworkLoad[networkLoadArray] = 0; - } - - TotalNetworkLoad /= NetworkLoadTicks / 60; // Average per-second - - ctr++; - if (ctr % 4 == 0) - { - Log.Info($"Network Load: {TotalNetworkLoad}"); - } - } - } - - public override void Close() - { - MyAPIGateway.Multiplayer.UnregisterSecureMessageHandler(NetworkId, ReceivedPacket); - I = null; - } - - #region Public Methods - /// - /// Used to rate-limit packets by ID. - /// - /// - /// /// Milliseconds to wait before allowing another packet - /// Bool - public static bool CheckRateLimit(long id, double delayMs = 5000 / 60d) - { - if (I == null) - throw new Exception("Null HeartNetwork.I!"); - - DateTime originalTime; - DateTime nowTime = DateTime.Now; // caching because i'm a nerd - if (!I._rateLimiter.TryGetValue(id, out originalTime) || (nowTime - originalTime).TotalMilliseconds >= delayMs) - { - I._rateLimiter[id] = nowTime; - return true; - } - - return false; - } - - /// - /// Gets the Type with the highest network load - /// - /// KeyValuePair (Type,int) - public KeyValuePair HighestNetworkLoad() - { - Type highest = null; - - foreach (var networkLoadArray in TypeNetworkLoad) - if (highest == null || networkLoadArray.Value > TypeNetworkLoad[highest]) - highest = networkLoadArray.Key; - - return new KeyValuePair(highest, TypeNetworkLoad[highest]); - } - - /// - /// Relays Packet to Client - /// - /// - /// /// - /// /// /// - public void SendToPlayer(PacketBase packet, ulong playerSteamId, byte[] serialized = null) - { - RelayToClient(packet, playerSteamId, MyAPIGateway.Session?.Player?.SteamUserId ?? 0, serialized); - } - - /// - /// Relays Packet to Everyone - /// - /// - /// /// - public void SendToEveryone(PacketBase packet, byte[] serialized = null) - { - RelayToClients(packet, MyAPIGateway.Session?.Player?.SteamUserId ?? 0, serialized); - } - - /// - /// Relays Packet to Server - /// - /// - /// /// - public void SendToServer(PacketBase packet, byte[] serialized = null) - { - RelayToServer(packet, MyAPIGateway.Session?.Player?.SteamUserId ?? 0, serialized); - } - #endregion - - #region Private Methods - private int ctr = 0; - - private void ReceivedPacket(ushort channelId, byte[] serialized, ulong senderSteamId, bool isSenderServer) - { - try - { - var packet = MyAPIGateway.Utilities.SerializeFromBinary(serialized); - TypeNetworkLoad[packet.GetType()] += serialized.Length; - HandlePacket(packet, senderSteamId); - } - catch (Exception ex) - { - Log.Error(ex, "[RepairModule] Error in HeatNetwork Sync! See Log for more Details!"); - } - } - - private void HandlePacket(PacketBase packet, ulong senderSteamId) - { - packet.Received(senderSteamId); - } - - private void RelayToClients(PacketBase packet, ulong senderSteamId = 0, byte[] serialized = null) - { - if (!MyAPIGateway.Multiplayer.IsServer) - return; - - TempPlayers.Clear(); - MyAPIGateway.Players.GetPlayers(TempPlayers); - - foreach (var p in TempPlayers) - { - // skip sending to self (server player) or back to sender - if (p.SteamUserId == MyAPIGateway.Multiplayer.ServerId || p.SteamUserId == senderSteamId) - continue; - - if (serialized == null) // only serialize if necessary, and only once. - serialized = MyAPIGateway.Utilities.SerializeToBinary(packet); - - MyAPIGateway.Multiplayer.SendMessageTo(NetworkId, serialized, p.SteamUserId); - } - - TempPlayers.Clear(); - } - - private void RelayToClient(PacketBase packet, ulong playerSteamId, ulong senderSteamId, byte[] serialized = null) - { - if (playerSteamId == MyAPIGateway.Multiplayer.ServerId || playerSteamId == senderSteamId) - return; - - if (serialized == null) // only serialize if necessary, and only once. - serialized = MyAPIGateway.Utilities.SerializeToBinary(packet); - - MyAPIGateway.Multiplayer.SendMessageTo(NetworkId, serialized, playerSteamId); - } - - private void RelayToServer(PacketBase packet, ulong senderSteamId = 0, byte[] serialized = null) - { - if (senderSteamId == MyAPIGateway.Multiplayer.ServerId) - return; - - if (serialized == null) // only serialize if necessary, and only once. - serialized = MyAPIGateway.Utilities.SerializeToBinary(packet); - - MyAPIGateway.Multiplayer.SendMessageToServer(NetworkId, serialized); - } - #endregion - } -} \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketBase.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketBase.cs deleted file mode 100644 index 438a0ff1e..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketBase.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using ProtoBuf; -using Starcore.FieldGenerator.Networking.Custom; - -namespace Starcore.FieldGenerator.Networking -{ - [ProtoContract(UseProtoMembersOnly = true)] - [ProtoInclude(1, typeof(BoolSyncPacket))] - [ProtoInclude(2, typeof(IntSyncPacket))] - [ProtoInclude(3, typeof(FloatSyncPacket))] - //[ProtoInclude(4, typeof(SyncRequestPacket))] - public abstract class PacketBase - { - public static readonly Type[] PacketTypes = - { - typeof(PacketBase), - typeof(BoolSyncPacket), - typeof(IntSyncPacket), - typeof(FloatSyncPacket), - // typeof(SyncRequestPacket), - }; - - /// - /// Called whenever your packet is received. - /// - /// - public abstract void Received(ulong SenderSteamId); - } -} \ No newline at end of file diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketQueueManager.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketQueueManager.cs deleted file mode 100644 index 4658af10b..000000000 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/HeartNetworking/PacketQueueManager.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ProtoBuf; -using Starcore.FieldGenerator.Networking.Custom; - -namespace Starcore.FieldGenerator.Networking -{ - public class PacketQueueManager - { - public static PacketQueueManager I; - - private Dictionary> packetQueues = new Dictionary>(); - - private List entityIds = new List(); - - #region Init - public void Init() - { - I = this; - } - - public void Close() - { - I = null; - } - #endregion - - #region Public Methods - /// - /// Checks for Entities with Open Queues - /// - /// Bool - public bool QueuesWithPackets() - { - return entityIds.Count > 0; - } - - /// - /// Adds Packet to Per-Entity Queue - /// - /// - public void EnqueuePacket(PacketBase packet) - { - long entityId = GetEntityId(packet); - - if (!packetQueues.ContainsKey(entityId)) - { - packetQueues[entityId] = new LinkedList(); - entityIds.Add(entityId); - } - - string propertyName = GetPropertyName(packet); - RemoveStalePackets(packetQueues[entityId], propertyName); - - packetQueues[entityId].AddLast(packet); - } - - /// - /// Removes the first packet from an Entitys Queue. If its the last packet in Queue, closes the Queue for that Entity. - /// - /// - public void DequeuePacket(long entityID) - { - if (packetQueues.ContainsKey(entityID) && packetQueues[entityID].Count > 0) - { - packetQueues[entityID].RemoveFirst(); - } - - if (!EntityHasPackets(entityID)) - { - entityIds.Remove(entityID); - } - } - - /// - /// Gets Entities with a Queue - /// - /// IEnumerable of EntityIDs with Queues - public IEnumerable EntitiesWithQueue() - { - foreach (var entry in packetQueues) - { - if (entry.Value.Count > 0) - yield return entry.Key; - } - } - - /// - /// Retrieves First Packet of an Entities Queue - /// - /// - /// PacketBase Packet Type - public PacketBase FirstInQueue(long entityID) - { - if (packetQueues.ContainsKey(entityID) && packetQueues[entityID].Count > 0) - { - return packetQueues[entityID].First.Value; - } - - return null; - } - #endregion - - #region Private Methods - private void RemoveStalePackets(LinkedList list, string propertyName) - { - var currentNode = list.First; - - while (currentNode != null) - { - var nextNode = currentNode.Next; - - if (GetPropertyName(currentNode.Value) == propertyName) - { - list.Remove(currentNode); - } - - currentNode = nextNode; - } - } - - private bool EntityHasPackets(long entityID) - { - return packetQueues.ContainsKey(entityID) || packetQueues[entityID].Count != 0; - } - - private long GetEntityId(PacketBase packet) - { - if (packet.GetType() == typeof(FloatSyncPacket)) - return ((FloatSyncPacket)packet).entityId; - if (packet.GetType() == typeof(IntSyncPacket)) - return ((IntSyncPacket)packet).entityId; - if (packet.GetType() == typeof(BoolSyncPacket)) - return ((BoolSyncPacket)packet).entityId; - - return 0; - } - - private string GetPropertyName(PacketBase packet) - { - if (packet.GetType() == typeof(FloatSyncPacket)) - return ((FloatSyncPacket)packet).propertyName; - if (packet.GetType() == typeof(IntSyncPacket)) - return ((IntSyncPacket)packet).propertyName; - if (packet.GetType() == typeof(BoolSyncPacket)) - return ((BoolSyncPacket)packet).propertyName; - - return string.Empty; - } - #endregion - } -} \ No newline at end of file From 391ac7447ec2d81ca2efe443c2008d926599e62b Mon Sep 17 00:00:00 2001 From: CommodoreChet <50426713+CommodoreChet@users.noreply.github.com> Date: Sat, 28 Dec 2024 20:56:24 -0600 Subject: [PATCH 3/3] Fix Missing Image + API Thyself --- .../Data/BlockVariantGroups_FieldGen.sbc | 2 +- .../FieldGenerator/API/APIBase.cs | 232 +++++++++++++++++ .../FieldGenerator/API/APIServer.cs | 242 ++++++++++++++++++ .../FieldGenerator/FieldGenerator_Core.cs | 2 +- .../FieldGenerator/FieldGenerator_Session.cs | 139 +++++++++- 5 files changed, 614 insertions(+), 3 deletions(-) create mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIBase.cs create mode 100644 Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIServer.cs diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/BlockVariantGroups_FieldGen.sbc b/Utility Mods/Stable/SCDefenseBlocks/Data/BlockVariantGroups_FieldGen.sbc index 3f121acfa..5887ed448 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/BlockVariantGroups_FieldGen.sbc +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/BlockVariantGroups_FieldGen.sbc @@ -5,7 +5,7 @@ - Textures\GUI\Icons\MyGat.dds + Textures\GUI\Icons\Cubes\Core_Icon.dds [SI] Field Generator diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIBase.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIBase.cs new file mode 100644 index 000000000..f16891d7f --- /dev/null +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIBase.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Sandbox.ModAPI; +using VRage.Game.Entity; + +namespace FieldGenerator.API +{ + public class FieldGeneratorAPI + { + private bool _initialized; + + private Func _getFirstFieldGeneratorOnGrid; + + private Func _isSiegeActive; + private Action _setSiegeActive; + + private Func _isSiegeCooldownActive; + private Action _setSiegeCooldownActive; + + private Func _getSiegeCooldown; + private Action _setSiegeCooldown; + + private Func _getFieldPower; + private Action _setFieldPower; + + private Func _getMaximumFieldPower; + private Func_getMinimumFieldPower; + + private Func _getPowerDraw; + + private Func _getStability; + private Action _setStability; + + /// + /// Returns first valid field generator for the specified grid EntityID. + /// + /// EntityID of the cubegrid to check against. + /// IMyFunctionalBlock of the first field generator if one exists; otherwise, null. + public IMyFunctionalBlock GetFirstFieldGeneratorOnGrid(long entityID) => _getFirstFieldGeneratorOnGrid?.Invoke(entityID) ?? null; + + /// + /// Returns whether or not the specified block is in siege mode. + /// + /// Block to check. + /// true if siege mode is active; otherwise, false. + public bool IsSiegeActive(IMyFunctionalBlock block) => _isSiegeActive?.Invoke(block) ?? false; + + /// + /// Sets the siege mode state on the given block. + /// + /// Block whose siege state will be modified. + /// Whether siege mode should be active (true) or inactive (false). + public void SetSiegeActive(IMyFunctionalBlock block, bool Active) => _setSiegeActive?.Invoke(block, Active); + + /// + /// Returns whether or not the specified blocks siege mode is on cooldown. + /// + /// Block to check. + /// true if the cooldown is active; otherwise, false. + public bool IsSiegeCooldownActive(IMyFunctionalBlock block) => _isSiegeCooldownActive?.Invoke(block) ?? false; + + /// + /// Sets the siege mode cooldown state on the given block. + /// + /// Block whose cooldown state will be modified. + /// Whether the cooldown should be active (true) or inactive (false). + public void SetSiegeCooldownActive(IMyFunctionalBlock block, bool Active) => _setSiegeCooldownActive?.Invoke(block, Active); + + /// + /// Returns the specified blocks current cooldown time. + /// + /// Block to check. + /// The siege cooldown time, or 0 if no cooldown is active. + public int GetSiegeCooldown(IMyFunctionalBlock block) => _getSiegeCooldown?.Invoke(block) ?? 0; + + /// + /// Sets the cooldown time on the given block. + /// + /// Block whose cooldown will be modified. + /// Time to set the cooldown to, in seconds. + public void SetSiegeCooldown(IMyFunctionalBlock block, int Time) => _setSiegeCooldown?.Invoke(block, Time); + + /// + /// Returns the specified block current field power. + /// + /// Block to check. + /// The current field power. + public float GetFieldPower(IMyFunctionalBlock block) => _getFieldPower?.Invoke(block) ?? 0; + + /// + /// Sets the field power on the given block. + /// + /// Block whose field power will be modified. + /// + /// The field power to set as a float, expressed as a percentage and capped by minimum/maximum field power. + /// + public void SetFieldPower(IMyFunctionalBlock block, float Power) => _setFieldPower?.Invoke(block, Power); + + /// + /// Returns the specified blocks maximum field power. + /// + /// Block to check. + /// The maximum field power. + public float GetMaximumFieldPower(IMyFunctionalBlock block) => _getMaximumFieldPower?.Invoke(block) ?? 0; + + /// + /// Returns the specified block minimum field power. + /// + /// Block to check. + /// The minimum field power. + public float GetMinimumFieldPower(IMyFunctionalBlock block) => _getMinimumFieldPower?.Invoke(block) ?? 0; + + /// + /// Returns the specified blocks current power draw. + /// + /// Block to check. + /// The current power draw. + public float GetPowerDraw(IMyFunctionalBlock block) => _getPowerDraw?.Invoke(block) ?? 0; + + /// + /// Returns the specified blocks current stability. + /// + /// Block to check. + /// The current stability. + public float GetStability(IMyFunctionalBlock block) => _getStability?.Invoke(block) ?? 0; + + /// + /// Sets the stability on the given block. + /// + /// Block whose stability will be modified. + /// + /// The stability to set as a float, expressed as a percentage with a maximum of 100. + /// + public void SetStability(IMyFunctionalBlock block, float Stability) => _setStability?.Invoke(block, Stability); + + + private const long HandlerID = 917632; + private bool _APIRegistered; + private Action _ReadyCallback; + + public bool IsReady { get; private set; } + + + public void LoadAPI(Action ReadyCallback = null) + { + if (_APIRegistered) + throw new Exception($"{GetType().Name}.LoadAPI() should not be called multiple times!"); + + _ReadyCallback = ReadyCallback; + _APIRegistered = true; + MyAPIGateway.Utilities.RegisterMessageHandler(HandlerID, HandleMessage); + MyAPIGateway.Utilities.SendModMessage(HandlerID, "APIRequest"); + } + + public void UnloadAPI() + { + MyAPIGateway.Utilities.UnregisterMessageHandler(HandlerID, HandleMessage); + + ApiAssign(null); + + _APIRegistered = false; + _initialized = false; + IsReady = false; + } + + private void HandleMessage(object obj) + { + if (_initialized || obj is string) + return; + + var dict = obj as IReadOnlyDictionary; + + if (dict == null) + return; + + ApiAssign(dict); + + IsReady = true; + _ReadyCallback?.Invoke(); + } + + public void ApiAssign(IReadOnlyDictionary delegates) + { + _initialized = delegates != null; + + AssignMethod(delegates, "GetFirstFieldGeneratorOnGrid", ref _getFirstFieldGeneratorOnGrid); + + AssignMethod(delegates, "IsSiegeActive", ref _isSiegeActive); + AssignMethod(delegates, "SetSiegeActive", ref _setSiegeActive); + + AssignMethod(delegates, "IsSiegeCooldownActive", ref _isSiegeCooldownActive); + AssignMethod(delegates, "SetSiegeCooldownActive", ref _setSiegeCooldownActive); + + AssignMethod(delegates, "GetSiegeCooldown", ref _getSiegeCooldown); + AssignMethod(delegates, "SetSiegeCooldown", ref _setSiegeCooldown); + + AssignMethod(delegates, "GetFieldPower", ref _getFieldPower); + AssignMethod(delegates, "SetFieldPower", ref _setFieldPower); + + AssignMethod(delegates, "GetMaximumFieldPower", ref _getMaximumFieldPower); + AssignMethod(delegates, "GetMinimumFieldPower", ref _getMinimumFieldPower); + + AssignMethod(delegates, "GetPowerDraw", ref _getPowerDraw); + + AssignMethod(delegates, "GetStability", ref _getStability); + AssignMethod(delegates, "SetStability", ref _setStability); + } + + private void AssignMethod(IReadOnlyDictionary delegates, string name, ref T field) + where T : class + { + if (delegates == null) + { + field = null; + return; + } + + Delegate del; + if (!delegates.TryGetValue(name, out del)) + throw new Exception($"{GetType().Name} :: Couldn't find {name} delegate of type {typeof(T)}"); + + field = del as T; + + if (field == null) + throw new Exception( + $"{GetType().Name} :: Delegate {name} is not type {typeof(T)}, instead it's: {del.GetType()}"); + } + } +} diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIServer.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIServer.cs new file mode 100644 index 000000000..106649c4a --- /dev/null +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/API/APIServer.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Sandbox.ModAPI; +using VRage.Game.Entity; +using VRage.ModAPI; +using FieldGeneratorCore = Starcore.FieldGenerator.FieldGenerator; + +namespace Starcore.FieldGenerator.API +{ + public class APIProvider + { + private const long HandlerID = 917632; + private bool _registered; + + public bool IsReady { get; private set; } + + public void LoadAPI() + { + if (!_registered) + { + _registered = true; + MyAPIGateway.Utilities.RegisterMessageHandler(HandlerID, HandleMessage); + } + + IsReady = true; + + try + { + MyAPIGateway.Utilities.SendModMessage(HandlerID, FieldGeneratorSession.I.APIBackend.APIMethods); + } + catch (Exception ex) + { + Log.Error($"Field Generator API Load Failed!" + "\n" + ex); + } + } + + public void UnloadAPI() + { + if (_registered) + { + _registered = false; + MyAPIGateway.Utilities.UnregisterMessageHandler(HandlerID, HandleMessage); + } + IsReady = false; + } + + private void HandleMessage(object o) + { + if ((o as string) == "APIRequest") + MyAPIGateway.Utilities.SendModMessage(HandlerID, FieldGeneratorSession.I.APIBackend.APIMethods); + } + } + + internal class APIBackend + { + internal readonly Dictionary APIMethods; + + internal APIBackend() + { + APIMethods = new Dictionary() + { + ["GetFirstFieldGeneratorOnGrid"] = new Func(GetFirstFieldGeneratorOnGrid), + + ["IsSiegeActive"] = new Func(IsSiegeActive), + ["SetSiegeActive"] = new Action(SetSiegeActive), + + ["IsSiegeCooldownActive"] = new Func(IsSiegeCooldownActive), + ["SetSiegeCooldownActive"] = new Action(SetSiegeCooldownActive), + + ["GetSiegeCooldown"] = new Func(GetSiegeCooldown), + ["SetSiegeCooldown"] = new Action(SetSiegeCooldown), + + ["GetFieldPower"] = new Func(GetFieldPower), + ["SetFieldPower"] = new Action(SetFieldPower), + + ["GetMaximumFieldPower"] = new Func(GetMaximumFieldPower), + ["GetMinimumFieldPower"] = new Func(GetMinimumFieldPower), + + ["GetPowerDraw"] = new Func(GetPowerDraw), + + ["GetStability"] = new Func(GetStability), + ["SetStability"] = new Action(SetStability), + }; + } + + private IMyFunctionalBlock GetFirstFieldGeneratorOnGrid(long entityID) + { + if (entityID == 0) + return null; + + HashSet generators; + if (!FieldGeneratorSession.ActiveGenerators.TryGetValue(entityID, out generators)) + { + return null; + } + + var fieldGeneratorID = generators.FirstOrDefault(); + if (fieldGeneratorID == 0) + { + return null; + } + + IMyEntity generatorEntity; + if (!MyAPIGateway.Entities.TryGetEntityById(fieldGeneratorID, out generatorEntity)) + { + return null; + } + + return generatorEntity as IMyFunctionalBlock; + } + + private bool IsSiegeActive(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.SiegeMode.Value; + } + + return false; + } + private void SetSiegeActive(IMyFunctionalBlock block, bool Active) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + logic.SiegeMode.Value = Active; + } + } + + private bool IsSiegeCooldownActive(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.SiegeCooldownActive.Value; + } + + return false; + } + private void SetSiegeCooldownActive(IMyFunctionalBlock block, bool Active) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + logic.SiegeCooldownActive.Value = Active; + } + } + + private int GetSiegeCooldown(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.SiegeCooldownTime.Value; + } + + return 0; + } + private void SetSiegeCooldown(IMyFunctionalBlock block, int Time) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + logic.SiegeCooldownTime.Value = Time; + } + } + + private float GetFieldPower (IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.FieldPower.Value; + } + + return 0; + } + private void SetFieldPower(IMyFunctionalBlock block, float Power) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + logic.FieldPower.Value = Power; + } + } + + private float GetMaximumFieldPower(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.MaxFieldPower.Value; + } + + return 0; + } + private float GetMinimumFieldPower(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.MinFieldPower.Value; + } + + return 0; + } + + private float GetPowerDraw(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.CalculatePowerDraw(); + } + + return 0; + } + + private float GetStability(IMyFunctionalBlock block) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + return logic.Stability.Value; + } + + return 0; + } + private void SetStability(IMyFunctionalBlock block, float Stability) + { + var logic = FieldGeneratorCore.GetLogic(block.EntityId); + if (logic != null) + { + logic.Stability.Value = Stability; + } + } + } +} diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs index 66b2e4743..5275154c1 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Core.cs @@ -614,7 +614,7 @@ private float CalculateSizeModifier() return Config.SizeModifierMin + t * (Config.SizeModifierMax - Config.SizeModifierMin); } - private float CalculatePowerDraw() + public float CalculatePowerDraw() { if (SiegeMode.Value) { diff --git a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs index 0da744ce0..f78d81277 100644 --- a/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs +++ b/Utility Mods/Stable/SCDefenseBlocks/Data/Scripts/OneFuckingFolderDeeper/FieldGenerator/FieldGenerator_Session.cs @@ -3,20 +3,45 @@ using System.Linq; using System.Text; using System.Threading.Tasks; + +using Sandbox.Game.Entities; +using Sandbox.ModAPI; using VRage.Game.Components; +using VRage.Game.ModAPI; +using VRage.ModAPI; + +using Starcore.FieldGenerator.API; using CoreSystems.Api; using Draygo.API; +using Sandbox.Game.Entities.Cube; namespace Starcore.FieldGenerator { [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)] public class FieldGeneratorSession : MySessionComponentBase { + public static FieldGeneratorSession I; + public static APIProvider APIProvider; public static WcApi CoreSysAPI; public static HudAPIv2 HudAPI; + internal APIBackend APIBackend; + internal static readonly Dictionary> ActiveGenerators = new Dictionary>(); + public override void LoadData() { + I = this; + + InitExistingGeneratorCounts(); + + MyCubeGrid.OnBlockAddedGlobally += OnBlockAddedGlobally; + MyCubeGrid.OnBlockRemovedGlobally += OnBlockRemovedGlobally; + MyAPIGateway.Entities.OnEntityAdd += OnEntityAdd; + + APIBackend = new APIBackend(); + APIProvider = new APIProvider(); + APIProvider.LoadAPI(); + HudAPI = new HudAPIv2(); CoreSysAPI = new WcApi(); @@ -24,7 +49,7 @@ public override void LoadData() } protected override void UnloadData() - { + { if (HudAPI.Heartbeat) { HudAPI.Unload(); @@ -36,6 +61,118 @@ protected override void UnloadData() CoreSysAPI.Unload(); CoreSysAPI = null; } + + APIProvider.UnloadAPI(); + APIProvider = null; + APIBackend = null; + + MyCubeGrid.OnBlockAddedGlobally -= OnBlockAddedGlobally; + MyCubeGrid.OnBlockRemovedGlobally -= OnBlockRemovedGlobally; + MyAPIGateway.Entities.OnEntityAdd -= OnEntityAdd; + + I = null; + } + + private void OnBlockAddedGlobally(T slimBlock) where T : IMySlimBlock + { + if (slimBlock?.FatBlock == null) + return; + if (!string.Equals(slimBlock.FatBlock.BlockDefinition.SubtypeName, "FieldGen_Core", + StringComparison.OrdinalIgnoreCase)) + return; + + var gridId = slimBlock.CubeGrid?.EntityId ?? 0; + if (gridId == 0) + return; + + HashSet set; + if (!ActiveGenerators.TryGetValue(gridId, out set)) + { + set = new HashSet(); + ActiveGenerators[gridId] = set; + } + + set.Add(slimBlock.FatBlock.EntityId); + } + + private void OnBlockRemovedGlobally(T slimBlock) where T : IMySlimBlock + { + if (slimBlock?.FatBlock == null) + return; + if (!string.Equals(slimBlock.FatBlock.BlockDefinition.SubtypeName, "FieldGen_Core", StringComparison.OrdinalIgnoreCase)) + return; + + var gridId = slimBlock.CubeGrid?.EntityId ?? 0; + if (gridId == 0) return; + + HashSet set; + if (ActiveGenerators.TryGetValue(gridId, out set)) + { + set.Remove(slimBlock.FatBlock.EntityId); + if (set.Count == 0) + ActiveGenerators.Remove(gridId); + } + } + + private void OnEntityAdd(IMyEntity ent) + { + var grid = ent as IMyCubeGrid; + if (grid == null) + return; + + var slimBlocks = new List(); + grid.GetBlocks(slimBlocks); + + foreach (var slimBlock in slimBlocks) + { + if (slimBlock?.FatBlock == null) + continue; + + if (string.Equals(slimBlock.FatBlock.BlockDefinition.SubtypeName, "FieldGen_Core", StringComparison.OrdinalIgnoreCase)) + { + var gridId = grid.EntityId; + HashSet set; + if (!ActiveGenerators.TryGetValue(gridId, out set)) + { + set = new HashSet(); + ActiveGenerators[gridId] = set; + } + set.Add(slimBlock.FatBlock.EntityId); + } + } + } + + private void InitExistingGeneratorCounts() + { + var allEntities = new HashSet(); + MyAPIGateway.Entities.GetEntities(allEntities); + foreach (var entity in allEntities) + { + var grid = entity as IMyCubeGrid; + if (grid == null) + continue; + + var slimBlocks = new List(); + grid.GetBlocks(slimBlocks); + + foreach (var slimBlock in slimBlocks) + { + if (slimBlock?.FatBlock == null) + continue; + + if (string.Equals(slimBlock.FatBlock.BlockDefinition.SubtypeName, "FieldGen_Core", StringComparison.OrdinalIgnoreCase)) + { + var gridId = grid.EntityId; + HashSet set; + if (!ActiveGenerators.TryGetValue(gridId, out set)) + { + set = new HashSet(); + ActiveGenerators[gridId] = set; + } + set.Add(slimBlock.FatBlock.EntityId); + } + } + } } } }