From cd98038e882244c11c3d2da01eae580dfbd88a6b Mon Sep 17 00:00:00 2001 From: InvalidArgument3 Date: Tue, 4 Jun 2024 16:05:05 -0500 Subject: [PATCH 1/5] man what forking epic Create modinfo.sbmi Update Hooks.cs --- .../Scripts/Specials/ShipClass/Hooks.cs | 219 ++++++++++++++---- .../LimitedBlock/LimitedBlockNetworking.cs | 17 +- .../Specials/ShipClass/SpecBlock/SpecBlock.cs | 1 + .../ShipClass/SpecBlock/SpecBlockGui.cs | 5 +- TSTSSESCores/modinfo.sbmi | 11 + TSTSSESCoresAddon/Data/CoreKits.sbc | 25 -- .../ScriptsAddon/Specials/SpecBlockHooks.cs | 132 ++++++++--- 7 files changed, 293 insertions(+), 117 deletions(-) create mode 100644 TSTSSESCores/modinfo.sbmi delete mode 100644 TSTSSESCoresAddon/Data/CoreKits.sbc diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs index 7a85c83c..70869517 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs @@ -12,31 +12,30 @@ using C = System.Func; using U = System.Collections.Generic.List; using L = System.Collections.Generic.IDictionary; +using VRage.Utils; namespace MIG.SpecCores { public class Hooks { - private static Action registerCustomLimitConsumer = RegisterCustomLimitConsumer; private static Func getMainSpecCore = GetMainSpecCore; private static Func getMainSpecCoreBlock = GetMainSpecCoreBlock; private static Action getSpecCoreLimits = GetSpecCoreLimits; private static Action getSpecCoreUpgrades = GetSpecCoreUpgrades; - private static Action setSpecCoreUpgrades = SetSpecCoreCustomValues; - + private static Action setSpecCoreUpgrades = SetSpecCoreCustomValues; + private static Func getSpecCoreBlock = GetSpecCoreBlock; - + private static Func>> getGridBlocksByType = GetGridBlocksByType; private static Func>> getGridBlocksById = GetGridBlocksById; - + private static Func getBlockSpecCore = GetBlockSpecCore; private static Func getLimitedBlock = GetLimitedBlock; private static Func getLimitedBlockBlock = GetLimitedBlockBlock; - - private static Action , float>> registerSpecCoreCurrentPointCustomFx = RegisterSpecCoreCurrentPointCustomFx; - - + + private static Action, float>> registerSpecCoreCurrentPointCustomFx = RegisterSpecCoreCurrentPointCustomFx; + private static Action, Dictionary>> addSpecCoreLimitsInterceptor = AddSpecCoreLimitsInterceptor; private static event Action, Dictionary> SpecCoreLimitsInterceptor = null; @@ -44,15 +43,13 @@ public static void InvokeLimitsInterceptor(ISpecBlock block, Dictionary, float>> SpecCoreCurrentCustom = new Dictionary, float>>(); - - + private static Func, string> CanSpecCoreWork; - + public static Dictionary HookedConsumerInfos = new Dictionary(); - - + public static event Action OnSpecBlockCreated; public static event Action OnSpecBlockDestroyed; public static event Action OnLimitedBlockCreated; @@ -84,53 +81,143 @@ public static void TriggerOnLimitedBlockDestroyed(ILimitedBlock block) { OnLimitedBlockDestroyed?.Invoke(block); } - + public static object GetSpecCoreBlock(IMyTerminalBlock block) { + if (block == null) + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: block is null"); + return null; + } + var grid = block.CubeGrid; + if (grid == null) + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: block.CubeGrid is null"); + return null; + } + var ship = grid.GetShip(); - if (ship == null) return null; + if (ship == null) + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: grid.GetShip() is null"); + return null; + } + ISpecBlock specBlock; - ship.SpecBlocks.TryGetValue(block, out specBlock); - return specBlock; + if (ship.SpecBlocks.TryGetValue(block, out specBlock)) + { + return specBlock; + } + else + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: ship.SpecBlocks does not contain the block"); + return null; + } } - + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) { + if (grid == null) + { + MyLog.Default.WriteLine("Hooks.GetGridBlocksByType: grid is null"); + return null; + } + var ship = grid.GetShip(); return ship?.BlocksCache; } - + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) { + if (grid == null) + { + MyLog.Default.WriteLine("Hooks.GetGridBlocksById: grid is null"); + return null; + } + var ship = grid.GetShip(); return ship?.BlocksCacheByType; } public static IMyTerminalBlock GetBlockSpecCore(object block) { - return ((ISpecBlock) block).block; + if (block == null) + { + MyLog.Default.WriteLine("Hooks.GetBlockSpecCore: block is null"); + return null; + } + + var specBlock = block as ISpecBlock; + if (specBlock == null) + { + MyLog.Default.WriteLine($"Hooks.GetBlockSpecCore: block of type {block.GetType().FullName} does not implement ISpecBlock"); + return null; + } + + return specBlock.block; } - + public static object GetLimitedBlock(IMyTerminalBlock block) { + if (block == null) + { + MyLog.Default.WriteLine("Hooks.GetLimitedBlock: block is null"); + return null; + } + var grid = block.CubeGrid; + if (grid == null) + { + MyLog.Default.WriteLine("Hooks.GetLimitedBlock: block.CubeGrid is null"); + return null; + } + var ship = grid.GetShip(); - if (ship == null) return null; + if (ship == null) + { + MyLog.Default.WriteLine("Hooks.GetLimitedBlock: grid.GetShip() is null"); + return null; + } + ILimitedBlock limitedBlock; - ship.LimitedBlocks.TryGetValue(block, out limitedBlock); - return limitedBlock; + if (ship.LimitedBlocks.TryGetValue(block, out limitedBlock)) + { + return limitedBlock; + } + else + { + MyLog.Default.WriteLine("Hooks.GetLimitedBlock: ship.LimitedBlocks does not contain the block"); + return null; + } } public static IMyTerminalBlock GetLimitedBlockBlock(object block) { - return ((ILimitedBlock) block).GetBlock(); - } + if (block == null) + { + MyLog.Default.WriteLine("Hooks.GetLimitedBlockBlock: block is null"); + return null; + } + var limitedBlock = block as ILimitedBlock; + if (limitedBlock == null) + { + MyLog.Default.WriteLine($"Hooks.GetLimitedBlockBlock: block of type {block.GetType().FullName} does not implement ILimitedBlock"); + return null; + } + return limitedBlock.GetBlock(); + } public static object GetMainSpecCore(IMyCubeGrid grid) { + if (grid == null) + { + MyLog.Default.WriteLine("Hooks.GetMainSpecCore: grid is null"); + return null; + } + Ship ship; if (OriginalSpecCoreSession.Instance.gridToShip.TryGetValue(grid.EntityId, out ship)) { @@ -139,9 +226,15 @@ public static object GetMainSpecCore(IMyCubeGrid grid) return null; } - + public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) { + if (grid == null) + { + MyLog.Default.WriteLine("Hooks.GetMainSpecCoreBlock: grid is null"); + return null; + } + Ship ship; if (OriginalSpecCoreSession.Instance.gridToShip.TryGetValue(grid.EntityId, out ship)) { @@ -150,11 +243,15 @@ public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) return null; } - + public static void GetSpecCoreLimits(object specCore, IDictionary dictionary, int mode) { var specBlock = specCore as SpecBlock; - if (specBlock == null) return; + if (specBlock == null) + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreLimits: specCore is not a SpecBlock"); + return; + } switch (mode) { @@ -165,35 +262,51 @@ public static void GetSpecCoreLimits(object specCore, IDictionary di case 5: dictionary.Sum(specBlock.Settings.CustomStatic); break; case 6: dictionary.Sum(specBlock.Settings.CustomDynamic); break; case 7: dictionary.Sum(specBlock.GetLimits()); break; + default: + MyLog.Default.WriteLine($"Hooks.GetSpecCoreLimits: Invalid mode {mode}"); + break; } } - + public static void GetSpecCoreUpgrades(object specCore, List copyTo, int mode) { var specBlock = specCore as SpecBlock; - if (specBlock == null) return; + if (specBlock == null) + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreUpgrades: specCore is not a SpecBlock"); + return; + } + copyTo.AddRange(specBlock.Settings.Upgrades); } - + public static void GetSpecCoreUpgrades(object specCore, List copyTo) { var specBlock = specCore as SpecBlock; - if (specBlock == null) return; + if (specBlock == null) + { + MyLog.Default.WriteLine("Hooks.GetSpecCoreUpgrades: specCore is not a SpecBlock"); + return; + } + copyTo.AddRange(specBlock.Settings.Upgrades); } public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) { var specBlock = specCore as SpecBlock; - if (specBlock == null) return; + if (specBlock == null) + { + MyLog.Default.WriteLine("Hooks.SetSpecCoreCustomValues: specCore is not a SpecBlock"); + return; + } + specBlock.Settings.CustomStatic.Sum(staticValues); specBlock.Settings.CustomDynamic.Sum(dynamicValues); specBlock.ApplyUpgrades(); specBlock.SaveSettings(); } - - /// /// Must be inited in LoadData of MySessionComponentBase /// @@ -202,7 +315,7 @@ public static void Init() ModConnection.Init(); TorchExtensions.Init(); - + ModConnection.SetValue("MIG.SpecCores.RegisterCustomLimitConsumer", registerCustomLimitConsumer); ModConnection.SetValue("MIG.SpecCores.GetMainSpecCore", getMainSpecCore); ModConnection.SetValue("MIG.SpecCores.GetMainSpecCoreBlock", getMainSpecCoreBlock); @@ -217,12 +330,12 @@ public static void Init() ModConnection.SetValue("MIG.SpecCores.GetBlockSpecCore", getBlockSpecCore); ModConnection.SetValue("MIG.SpecCores.GetLimitedBlock", getLimitedBlock); ModConnection.SetValue("MIG.SpecCores.GetLimitedBlockBlock", getLimitedBlockBlock); - + ModConnection.Subscribe("MIG.SpecCores.RegisterCustomLimitConsumer", registerCustomLimitConsumer, (x) => { registerCustomLimitConsumer = x; }); - + ModConnection.SetValue("MIG.SpecCores.RegisterSpecCorePointCustomFx", registerSpecCoreCurrentPointCustomFx); ModConnection.SetValue("MIG.SpecCores.AddSpecCoreLimitsInterceptor", addSpecCoreLimitsInterceptor); - + ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockCreated", OnSpecBlockCreated, (a) => { OnSpecBlockCreated += a; }); ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockDestroyed", OnSpecBlockDestroyed, (a) => { OnSpecBlockDestroyed += a; }); ModConnection.Subscribe("MIG.SpecCores.OnLimitedBlockCreated", OnLimitedBlockCreated, (a) => { OnLimitedBlockCreated += a; }); @@ -231,7 +344,7 @@ public static void Init() ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockChanged", OnSpecCoreChanged, (a) => { OnSpecCoreChanged += a; }); ModConnection.Subscribe("MIG.SpecCores.CanSpecCoreWork", CanSpecCoreWork, (a) => { CanSpecCoreWork = a; }); } - + public static void Close() { ModConnection.Close(); @@ -247,19 +360,31 @@ public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegiste IsDrainingPoints = IsDrainingPoints, Disable = Disable, }; + } - public static void RegisterSpecCoreCurrentPointCustomFx(int id, Func, float> fx) { + if (fx == null) + { + MyLog.Default.WriteLine($"Hooks.RegisterSpecCoreCurrentPointCustomFx: fx is null for id {id}"); + return; + } + SpecCoreCurrentCustom[id] = fx; } - + public static void AddSpecCoreLimitsInterceptor(Action, Dictionary> fx) { + if (fx == null) + { + MyLog.Default.WriteLine("Hooks.AddSpecCoreLimitsInterceptor: fx is null"); + return; + } + SpecCoreLimitsInterceptor += fx; } - + public static string CanBeApplied(ISpecBlock specBlock, List grids) { return CanSpecCoreWork?.Invoke(specBlock, grids) ?? null; @@ -274,7 +399,7 @@ public static float GetCurrentPointValueForSpecCore(ISpecBlock specBlock, List grids, LimitPoint lp) { var fx = SpecCoreCurrentCustom.GetOr(lp.Id, null); diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs index 02fbd2f5..d1cc2eab 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs @@ -66,20 +66,26 @@ public static void Handler (ILimitedBlock block, LimitedBlockSettings settings, public void OnSettingsChanged() { } - public void NotifyAndSave(byte type=255, bool forceSave = false) + public void NotifyAndSave(byte type = 255, bool forceSave = false) { try { if (MyAPIGateway.Session.IsServer) { - Sync.SendMessageToOthers(Block.EntityId, Settings, type: type); - SaveSettings(forceSave); + lock (Settings) + { + Sync.SendMessageToOthers(Block.EntityId, Settings, type: type); + SaveSettings(forceSave); + } } else { if (Sync != null) { - Sync.SendMessageToServer(Block.EntityId, Settings, type: type); + lock (Settings) + { + Sync.SendMessageToServer(Block.EntityId, Settings, type: type); + } } } } @@ -88,7 +94,8 @@ public void NotifyAndSave(byte type=255, bool forceSave = false) Log.ChatError($"NotifyAndSave {type} Exception {ex} {ex.StackTrace}"); } } - + + public void SaveSettings(bool forceSave = false) { if (MyAPIGateway.Session.IsServer) diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs index 4aa7aa75..f7ef1582 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs @@ -162,6 +162,7 @@ public void ApplyUpgrades() private static void Handler(SpecBlock block, UpgradableSpecBlockSettings settings, byte type, ulong userSteamId, bool isFromServer) { + Log.ChatError($"Handler called for block: {block.block.EntityId}, type: {type}, isFromServer: {isFromServer}"); if (isFromServer && !MyAPIGateway.Session.IsServer) { block.Settings = settings; diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs index 6014ecdc..b97e6a65 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs @@ -122,13 +122,14 @@ private static void RemoveUpgradeGui(SpecBlock x) x.block.RefreshDI(); UpdateControls(x); } - + private static void ApplyUpgradesGui(SpecBlock x) { var settings = new UpgradableSpecBlockSettings(); settings.Upgrades.AddRange(x.AddedUpgrades); x.AddedUpgrades.Clear(); x.SelectedUpgrades.Clear(); + Log.ChatError($"Applying upgrades: {string.Join(",", settings.Upgrades)} to block: {x.block.EntityId}"); Sync.SendMessageToServer(x.block.EntityId, settings, type: APPLY_SELECTED); FrameExecutor.addDelayedLogic(30, (xx) => UpdateControls(x)); //1/2 sec if (!MyAPIGateway.Session.IsServer) @@ -136,7 +137,7 @@ private static void ApplyUpgradesGui(SpecBlock x) x.Settings = settings; //Remove gui lag } } - + private static void ApplyRandomUpgradesGui(SpecBlock x) { x.AddedUpgrades.Clear(); diff --git a/TSTSSESCores/modinfo.sbmi b/TSTSSESCores/modinfo.sbmi new file mode 100644 index 00000000..ea5dd8c1 --- /dev/null +++ b/TSTSSESCores/modinfo.sbmi @@ -0,0 +1,11 @@ + + + 76561198071098415 + 0 + + + 3261300687 + Steam + + + \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/CoreKits.sbc b/TSTSSESCoresAddon/Data/CoreKits.sbc deleted file mode 100644 index a4871f1d..00000000 --- a/TSTSSESCoresAddon/Data/CoreKits.sbc +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - Beacon - CoreKit_1 - - {LOC:DisplayName_CoreKit_1} - {LOC:Description_CoreKit_1} - Textures\GUI\Icons\AstronautBackpack.dds - Large - TriangleMesh - - - Models\CoreKit_1.mwm - - - - - - CoreKit_1 - - - diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs index 30830e94..87cff80d 100644 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs @@ -207,67 +207,123 @@ public static object GetLimitedBlock(IMyTerminalBlock block) public static IMyTerminalBlock GetLimitedBlockBlock(object block) { - return getLimitedBlockBlock?.Invoke(block); + if (getLimitedBlockBlock == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: getLimitedBlockBlock is null"); + return null; + } + + if (block == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: block is null"); + return null; + } + + try + { + var limitedBlock = block as ILimitedBlock; + if (limitedBlock == null) + { + MyLog.Default.WriteLine($"SpecBlockHooks: block of type {block.GetType().FullName} does not implement ILimitedBlock"); + return null; + } + + return getLimitedBlockBlock.Invoke(block); + } + catch (InvalidCastException) + { + MyLog.Default.WriteLine($"SpecBlockHooks: Failed to cast block of type {block.GetType().FullName} to ILimitedBlock"); + return null; + } + catch (Exception e) + { + MyLog.Default.WriteLine($"SpecBlockHooks: Error in GetLimitedBlockBlock: {e.Message}"); + return null; + } } public static void RegisterCustomLimitConsumer(string Id, Func creator) { - SpecBlockHooks.RegisterCustomLimitConsumer(Id, + SpecBlockHooks.RegisterCustomLimitConsumer(Id, creator, - (logic)=> + (logic) => { - ((ILimitedBlock) logic).CanWork(); + var limitedBlock = logic as ILimitedBlock; + if (limitedBlock != null) limitedBlock.CanWork(); }, (block, logic) => { - return ((ILimitedBlock) logic).CheckConditions(block); + var limitedBlock = logic as ILimitedBlock; + return limitedBlock != null && limitedBlock.CheckConditions(block); }, - (logic)=> + (logic) => { - return ((ILimitedBlock) logic).CanBeDisabled(); + var limitedBlock = logic as ILimitedBlock; + return limitedBlock != null && limitedBlock.CanBeDisabled(); }, - (logic)=> + (logic) => { - return ((ILimitedBlock) logic).IsDrainingPoints(); + var limitedBlock = logic as ILimitedBlock; + return limitedBlock != null && limitedBlock.IsDrainingPoints(); }, - (logic)=> + (logic) => { - ((ILimitedBlock) logic).Disable(); + var limitedBlock = logic as ILimitedBlock; + if (limitedBlock != null) limitedBlock.Disable(); }); } - + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) { + if (grid == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksByType"); + return null; + } return getGridBlocksByType?.Invoke(grid) ?? null; } - + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) { + if (grid == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksById"); + return null; + } return getGridBlocksById?.Invoke(grid) ?? null; } - - public static void HandleDamage(object target, ref MyDamageInformation damage) - { //Paralell - try - { - var slimBlock = target as IMySlimBlock; - if (slimBlock != null) - { - var cubeGrid = slimBlock.CubeGrid; - var core = SpecBlockHooks.GetMainSpecCore(slimBlock.CubeGrid); - var stats = new Dictionary(); - SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); - if(stats.ContainsKey(-33) && stats[-33]!=0) - { - damage.Amount *= stats [-33]; - } - } - } - catch(Exception e) - { - - } - } - - } + + public static void HandleDamage(object target, ref MyDamageInformation damage) + { //Parallel + try + { + var slimBlock = target as IMySlimBlock; + if (slimBlock == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: target is not IMySlimBlock in HandleDamage"); + return; + } + + var cubeGrid = slimBlock.CubeGrid; + var core = SpecBlockHooks.GetMainSpecCore(cubeGrid); + if (core == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: core is null in HandleDamage"); + return; + } + + var stats = new Dictionary(); + SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); + if (stats != null && stats.ContainsKey(-33) && stats[-33] != 0) + { + damage.Amount *= stats[-33]; + } + } + catch (Exception e) + { + MyLog.Default.WriteLine($"SpecBlockHooks: Error in HandleDamage: {e.Message}"); + } + } + + } } \ No newline at end of file From 13c2fa0694b9f94782578c61f951ecc46c784e08 Mon Sep 17 00:00:00 2001 From: InvalidArgument3 Date: Tue, 4 Jun 2024 18:40:59 -0500 Subject: [PATCH 2/5] Revert "man what" This reverts commit cd98038e882244c11c3d2da01eae580dfbd88a6b. --- .../Scripts/Specials/ShipClass/Hooks.cs | 219 ++++-------------- .../LimitedBlock/LimitedBlockNetworking.cs | 17 +- .../Specials/ShipClass/SpecBlock/SpecBlock.cs | 1 - .../ShipClass/SpecBlock/SpecBlockGui.cs | 5 +- TSTSSESCores/modinfo.sbmi | 11 - TSTSSESCoresAddon/Data/CoreKits.sbc | 25 ++ .../ScriptsAddon/Specials/SpecBlockHooks.cs | 132 +++-------- 7 files changed, 117 insertions(+), 293 deletions(-) delete mode 100644 TSTSSESCores/modinfo.sbmi create mode 100644 TSTSSESCoresAddon/Data/CoreKits.sbc diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs index 70869517..7a85c83c 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs @@ -12,30 +12,31 @@ using C = System.Func; using U = System.Collections.Generic.List; using L = System.Collections.Generic.IDictionary; -using VRage.Utils; namespace MIG.SpecCores { public class Hooks { + private static Action registerCustomLimitConsumer = RegisterCustomLimitConsumer; private static Func getMainSpecCore = GetMainSpecCore; private static Func getMainSpecCoreBlock = GetMainSpecCoreBlock; private static Action getSpecCoreLimits = GetSpecCoreLimits; private static Action getSpecCoreUpgrades = GetSpecCoreUpgrades; - private static Action setSpecCoreUpgrades = SetSpecCoreCustomValues; - + private static Action setSpecCoreUpgrades = SetSpecCoreCustomValues; + private static Func getSpecCoreBlock = GetSpecCoreBlock; - + private static Func>> getGridBlocksByType = GetGridBlocksByType; private static Func>> getGridBlocksById = GetGridBlocksById; - + private static Func getBlockSpecCore = GetBlockSpecCore; private static Func getLimitedBlock = GetLimitedBlock; private static Func getLimitedBlockBlock = GetLimitedBlockBlock; - - private static Action, float>> registerSpecCoreCurrentPointCustomFx = RegisterSpecCoreCurrentPointCustomFx; - + + private static Action , float>> registerSpecCoreCurrentPointCustomFx = RegisterSpecCoreCurrentPointCustomFx; + + private static Action, Dictionary>> addSpecCoreLimitsInterceptor = AddSpecCoreLimitsInterceptor; private static event Action, Dictionary> SpecCoreLimitsInterceptor = null; @@ -43,13 +44,15 @@ public static void InvokeLimitsInterceptor(ISpecBlock block, Dictionary, float>> SpecCoreCurrentCustom = new Dictionary, float>>(); - + + private static Func, string> CanSpecCoreWork; - + public static Dictionary HookedConsumerInfos = new Dictionary(); - + + public static event Action OnSpecBlockCreated; public static event Action OnSpecBlockDestroyed; public static event Action OnLimitedBlockCreated; @@ -81,143 +84,53 @@ public static void TriggerOnLimitedBlockDestroyed(ILimitedBlock block) { OnLimitedBlockDestroyed?.Invoke(block); } - + public static object GetSpecCoreBlock(IMyTerminalBlock block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: block is null"); - return null; - } - var grid = block.CubeGrid; - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: block.CubeGrid is null"); - return null; - } - var ship = grid.GetShip(); - if (ship == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: grid.GetShip() is null"); - return null; - } - + if (ship == null) return null; ISpecBlock specBlock; - if (ship.SpecBlocks.TryGetValue(block, out specBlock)) - { - return specBlock; - } - else - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: ship.SpecBlocks does not contain the block"); - return null; - } + ship.SpecBlocks.TryGetValue(block, out specBlock); + return specBlock; } - + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetGridBlocksByType: grid is null"); - return null; - } - var ship = grid.GetShip(); return ship?.BlocksCache; } - + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetGridBlocksById: grid is null"); - return null; - } - var ship = grid.GetShip(); return ship?.BlocksCacheByType; } public static IMyTerminalBlock GetBlockSpecCore(object block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetBlockSpecCore: block is null"); - return null; - } - - var specBlock = block as ISpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine($"Hooks.GetBlockSpecCore: block of type {block.GetType().FullName} does not implement ISpecBlock"); - return null; - } - - return specBlock.block; + return ((ISpecBlock) block).block; } - + public static object GetLimitedBlock(IMyTerminalBlock block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: block is null"); - return null; - } - var grid = block.CubeGrid; - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: block.CubeGrid is null"); - return null; - } - var ship = grid.GetShip(); - if (ship == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: grid.GetShip() is null"); - return null; - } - + if (ship == null) return null; ILimitedBlock limitedBlock; - if (ship.LimitedBlocks.TryGetValue(block, out limitedBlock)) - { - return limitedBlock; - } - else - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: ship.LimitedBlocks does not contain the block"); - return null; - } + ship.LimitedBlocks.TryGetValue(block, out limitedBlock); + return limitedBlock; } public static IMyTerminalBlock GetLimitedBlockBlock(object block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlockBlock: block is null"); - return null; - } + return ((ILimitedBlock) block).GetBlock(); + } - var limitedBlock = block as ILimitedBlock; - if (limitedBlock == null) - { - MyLog.Default.WriteLine($"Hooks.GetLimitedBlockBlock: block of type {block.GetType().FullName} does not implement ILimitedBlock"); - return null; - } - return limitedBlock.GetBlock(); - } public static object GetMainSpecCore(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetMainSpecCore: grid is null"); - return null; - } - Ship ship; if (OriginalSpecCoreSession.Instance.gridToShip.TryGetValue(grid.EntityId, out ship)) { @@ -226,15 +139,9 @@ public static object GetMainSpecCore(IMyCubeGrid grid) return null; } - + public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetMainSpecCoreBlock: grid is null"); - return null; - } - Ship ship; if (OriginalSpecCoreSession.Instance.gridToShip.TryGetValue(grid.EntityId, out ship)) { @@ -243,15 +150,11 @@ public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) return null; } - + public static void GetSpecCoreLimits(object specCore, IDictionary dictionary, int mode) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreLimits: specCore is not a SpecBlock"); - return; - } + if (specBlock == null) return; switch (mode) { @@ -262,51 +165,35 @@ public static void GetSpecCoreLimits(object specCore, IDictionary di case 5: dictionary.Sum(specBlock.Settings.CustomStatic); break; case 6: dictionary.Sum(specBlock.Settings.CustomDynamic); break; case 7: dictionary.Sum(specBlock.GetLimits()); break; - default: - MyLog.Default.WriteLine($"Hooks.GetSpecCoreLimits: Invalid mode {mode}"); - break; } } - + public static void GetSpecCoreUpgrades(object specCore, List copyTo, int mode) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreUpgrades: specCore is not a SpecBlock"); - return; - } - + if (specBlock == null) return; copyTo.AddRange(specBlock.Settings.Upgrades); } - + public static void GetSpecCoreUpgrades(object specCore, List copyTo) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreUpgrades: specCore is not a SpecBlock"); - return; - } - + if (specBlock == null) return; copyTo.AddRange(specBlock.Settings.Upgrades); } public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.SetSpecCoreCustomValues: specCore is not a SpecBlock"); - return; - } - + if (specBlock == null) return; specBlock.Settings.CustomStatic.Sum(staticValues); specBlock.Settings.CustomDynamic.Sum(dynamicValues); specBlock.ApplyUpgrades(); specBlock.SaveSettings(); } + + /// /// Must be inited in LoadData of MySessionComponentBase /// @@ -315,7 +202,7 @@ public static void Init() ModConnection.Init(); TorchExtensions.Init(); - + ModConnection.SetValue("MIG.SpecCores.RegisterCustomLimitConsumer", registerCustomLimitConsumer); ModConnection.SetValue("MIG.SpecCores.GetMainSpecCore", getMainSpecCore); ModConnection.SetValue("MIG.SpecCores.GetMainSpecCoreBlock", getMainSpecCoreBlock); @@ -330,12 +217,12 @@ public static void Init() ModConnection.SetValue("MIG.SpecCores.GetBlockSpecCore", getBlockSpecCore); ModConnection.SetValue("MIG.SpecCores.GetLimitedBlock", getLimitedBlock); ModConnection.SetValue("MIG.SpecCores.GetLimitedBlockBlock", getLimitedBlockBlock); - + ModConnection.Subscribe("MIG.SpecCores.RegisterCustomLimitConsumer", registerCustomLimitConsumer, (x) => { registerCustomLimitConsumer = x; }); - + ModConnection.SetValue("MIG.SpecCores.RegisterSpecCorePointCustomFx", registerSpecCoreCurrentPointCustomFx); ModConnection.SetValue("MIG.SpecCores.AddSpecCoreLimitsInterceptor", addSpecCoreLimitsInterceptor); - + ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockCreated", OnSpecBlockCreated, (a) => { OnSpecBlockCreated += a; }); ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockDestroyed", OnSpecBlockDestroyed, (a) => { OnSpecBlockDestroyed += a; }); ModConnection.Subscribe("MIG.SpecCores.OnLimitedBlockCreated", OnLimitedBlockCreated, (a) => { OnLimitedBlockCreated += a; }); @@ -344,7 +231,7 @@ public static void Init() ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockChanged", OnSpecCoreChanged, (a) => { OnSpecCoreChanged += a; }); ModConnection.Subscribe("MIG.SpecCores.CanSpecCoreWork", CanSpecCoreWork, (a) => { CanSpecCoreWork = a; }); } - + public static void Close() { ModConnection.Close(); @@ -360,31 +247,19 @@ public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegiste IsDrainingPoints = IsDrainingPoints, Disable = Disable, }; - } + public static void RegisterSpecCoreCurrentPointCustomFx(int id, Func, float> fx) { - if (fx == null) - { - MyLog.Default.WriteLine($"Hooks.RegisterSpecCoreCurrentPointCustomFx: fx is null for id {id}"); - return; - } - SpecCoreCurrentCustom[id] = fx; } - + public static void AddSpecCoreLimitsInterceptor(Action, Dictionary> fx) { - if (fx == null) - { - MyLog.Default.WriteLine("Hooks.AddSpecCoreLimitsInterceptor: fx is null"); - return; - } - SpecCoreLimitsInterceptor += fx; } - + public static string CanBeApplied(ISpecBlock specBlock, List grids) { return CanSpecCoreWork?.Invoke(specBlock, grids) ?? null; @@ -399,7 +274,7 @@ public static float GetCurrentPointValueForSpecCore(ISpecBlock specBlock, List grids, LimitPoint lp) { var fx = SpecCoreCurrentCustom.GetOr(lp.Id, null); diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs index d1cc2eab..02fbd2f5 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs @@ -66,26 +66,20 @@ public static void Handler (ILimitedBlock block, LimitedBlockSettings settings, public void OnSettingsChanged() { } - public void NotifyAndSave(byte type = 255, bool forceSave = false) + public void NotifyAndSave(byte type=255, bool forceSave = false) { try { if (MyAPIGateway.Session.IsServer) { - lock (Settings) - { - Sync.SendMessageToOthers(Block.EntityId, Settings, type: type); - SaveSettings(forceSave); - } + Sync.SendMessageToOthers(Block.EntityId, Settings, type: type); + SaveSettings(forceSave); } else { if (Sync != null) { - lock (Settings) - { - Sync.SendMessageToServer(Block.EntityId, Settings, type: type); - } + Sync.SendMessageToServer(Block.EntityId, Settings, type: type); } } } @@ -94,8 +88,7 @@ public void NotifyAndSave(byte type = 255, bool forceSave = false) Log.ChatError($"NotifyAndSave {type} Exception {ex} {ex.StackTrace}"); } } - - + public void SaveSettings(bool forceSave = false) { if (MyAPIGateway.Session.IsServer) diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs index f7ef1582..4aa7aa75 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs @@ -162,7 +162,6 @@ public void ApplyUpgrades() private static void Handler(SpecBlock block, UpgradableSpecBlockSettings settings, byte type, ulong userSteamId, bool isFromServer) { - Log.ChatError($"Handler called for block: {block.block.EntityId}, type: {type}, isFromServer: {isFromServer}"); if (isFromServer && !MyAPIGateway.Session.IsServer) { block.Settings = settings; diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs index b97e6a65..6014ecdc 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs @@ -122,14 +122,13 @@ private static void RemoveUpgradeGui(SpecBlock x) x.block.RefreshDI(); UpdateControls(x); } - + private static void ApplyUpgradesGui(SpecBlock x) { var settings = new UpgradableSpecBlockSettings(); settings.Upgrades.AddRange(x.AddedUpgrades); x.AddedUpgrades.Clear(); x.SelectedUpgrades.Clear(); - Log.ChatError($"Applying upgrades: {string.Join(",", settings.Upgrades)} to block: {x.block.EntityId}"); Sync.SendMessageToServer(x.block.EntityId, settings, type: APPLY_SELECTED); FrameExecutor.addDelayedLogic(30, (xx) => UpdateControls(x)); //1/2 sec if (!MyAPIGateway.Session.IsServer) @@ -137,7 +136,7 @@ private static void ApplyUpgradesGui(SpecBlock x) x.Settings = settings; //Remove gui lag } } - + private static void ApplyRandomUpgradesGui(SpecBlock x) { x.AddedUpgrades.Clear(); diff --git a/TSTSSESCores/modinfo.sbmi b/TSTSSESCores/modinfo.sbmi deleted file mode 100644 index ea5dd8c1..00000000 --- a/TSTSSESCores/modinfo.sbmi +++ /dev/null @@ -1,11 +0,0 @@ - - - 76561198071098415 - 0 - - - 3261300687 - Steam - - - \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/CoreKits.sbc b/TSTSSESCoresAddon/Data/CoreKits.sbc new file mode 100644 index 00000000..a4871f1d --- /dev/null +++ b/TSTSSESCoresAddon/Data/CoreKits.sbc @@ -0,0 +1,25 @@ + + + + + + Beacon + CoreKit_1 + + {LOC:DisplayName_CoreKit_1} + {LOC:Description_CoreKit_1} + Textures\GUI\Icons\AstronautBackpack.dds + Large + TriangleMesh + + + Models\CoreKit_1.mwm + + + + + + CoreKit_1 + + + diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs index 87cff80d..30830e94 100644 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs @@ -207,123 +207,67 @@ public static object GetLimitedBlock(IMyTerminalBlock block) public static IMyTerminalBlock GetLimitedBlockBlock(object block) { - if (getLimitedBlockBlock == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: getLimitedBlockBlock is null"); - return null; - } - - if (block == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: block is null"); - return null; - } - - try - { - var limitedBlock = block as ILimitedBlock; - if (limitedBlock == null) - { - MyLog.Default.WriteLine($"SpecBlockHooks: block of type {block.GetType().FullName} does not implement ILimitedBlock"); - return null; - } - - return getLimitedBlockBlock.Invoke(block); - } - catch (InvalidCastException) - { - MyLog.Default.WriteLine($"SpecBlockHooks: Failed to cast block of type {block.GetType().FullName} to ILimitedBlock"); - return null; - } - catch (Exception e) - { - MyLog.Default.WriteLine($"SpecBlockHooks: Error in GetLimitedBlockBlock: {e.Message}"); - return null; - } + return getLimitedBlockBlock?.Invoke(block); } public static void RegisterCustomLimitConsumer(string Id, Func creator) { - SpecBlockHooks.RegisterCustomLimitConsumer(Id, + SpecBlockHooks.RegisterCustomLimitConsumer(Id, creator, - (logic) => + (logic)=> { - var limitedBlock = logic as ILimitedBlock; - if (limitedBlock != null) limitedBlock.CanWork(); + ((ILimitedBlock) logic).CanWork(); }, (block, logic) => { - var limitedBlock = logic as ILimitedBlock; - return limitedBlock != null && limitedBlock.CheckConditions(block); + return ((ILimitedBlock) logic).CheckConditions(block); }, - (logic) => + (logic)=> { - var limitedBlock = logic as ILimitedBlock; - return limitedBlock != null && limitedBlock.CanBeDisabled(); + return ((ILimitedBlock) logic).CanBeDisabled(); }, - (logic) => + (logic)=> { - var limitedBlock = logic as ILimitedBlock; - return limitedBlock != null && limitedBlock.IsDrainingPoints(); + return ((ILimitedBlock) logic).IsDrainingPoints(); }, - (logic) => + (logic)=> { - var limitedBlock = logic as ILimitedBlock; - if (limitedBlock != null) limitedBlock.Disable(); + ((ILimitedBlock) logic).Disable(); }); } - + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksByType"); - return null; - } return getGridBlocksByType?.Invoke(grid) ?? null; } - + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksById"); - return null; - } return getGridBlocksById?.Invoke(grid) ?? null; } - - public static void HandleDamage(object target, ref MyDamageInformation damage) - { //Parallel - try - { - var slimBlock = target as IMySlimBlock; - if (slimBlock == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: target is not IMySlimBlock in HandleDamage"); - return; - } - - var cubeGrid = slimBlock.CubeGrid; - var core = SpecBlockHooks.GetMainSpecCore(cubeGrid); - if (core == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: core is null in HandleDamage"); - return; - } - - var stats = new Dictionary(); - SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); - if (stats != null && stats.ContainsKey(-33) && stats[-33] != 0) - { - damage.Amount *= stats[-33]; - } - } - catch (Exception e) - { - MyLog.Default.WriteLine($"SpecBlockHooks: Error in HandleDamage: {e.Message}"); - } - } - - } + + public static void HandleDamage(object target, ref MyDamageInformation damage) + { //Paralell + try + { + var slimBlock = target as IMySlimBlock; + if (slimBlock != null) + { + var cubeGrid = slimBlock.CubeGrid; + var core = SpecBlockHooks.GetMainSpecCore(slimBlock.CubeGrid); + var stats = new Dictionary(); + SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); + if(stats.ContainsKey(-33) && stats[-33]!=0) + { + damage.Amount *= stats [-33]; + } + } + } + catch(Exception e) + { + + } + } + + } } \ No newline at end of file From d6e24798037483fa8b157b09fe3ed9e12846304d Mon Sep 17 00:00:00 2001 From: InvalidArgument3 Date: Tue, 4 Jun 2024 18:42:39 -0500 Subject: [PATCH 3/5] whelp --- .../Scripts/Specials/ShipClass/Hooks.cs | 219 ++++-------------- .../LimitedBlock/LimitedBlockNetworking.cs | 17 +- .../Specials/ShipClass/SpecBlock/SpecBlock.cs | 1 - .../ShipClass/SpecBlock/SpecBlockGui.cs | 5 +- 4 files changed, 54 insertions(+), 188 deletions(-) diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs index 70869517..7a85c83c 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/Hooks.cs @@ -12,30 +12,31 @@ using C = System.Func; using U = System.Collections.Generic.List; using L = System.Collections.Generic.IDictionary; -using VRage.Utils; namespace MIG.SpecCores { public class Hooks { + private static Action registerCustomLimitConsumer = RegisterCustomLimitConsumer; private static Func getMainSpecCore = GetMainSpecCore; private static Func getMainSpecCoreBlock = GetMainSpecCoreBlock; private static Action getSpecCoreLimits = GetSpecCoreLimits; private static Action getSpecCoreUpgrades = GetSpecCoreUpgrades; - private static Action setSpecCoreUpgrades = SetSpecCoreCustomValues; - + private static Action setSpecCoreUpgrades = SetSpecCoreCustomValues; + private static Func getSpecCoreBlock = GetSpecCoreBlock; - + private static Func>> getGridBlocksByType = GetGridBlocksByType; private static Func>> getGridBlocksById = GetGridBlocksById; - + private static Func getBlockSpecCore = GetBlockSpecCore; private static Func getLimitedBlock = GetLimitedBlock; private static Func getLimitedBlockBlock = GetLimitedBlockBlock; - - private static Action, float>> registerSpecCoreCurrentPointCustomFx = RegisterSpecCoreCurrentPointCustomFx; - + + private static Action , float>> registerSpecCoreCurrentPointCustomFx = RegisterSpecCoreCurrentPointCustomFx; + + private static Action, Dictionary>> addSpecCoreLimitsInterceptor = AddSpecCoreLimitsInterceptor; private static event Action, Dictionary> SpecCoreLimitsInterceptor = null; @@ -43,13 +44,15 @@ public static void InvokeLimitsInterceptor(ISpecBlock block, Dictionary, float>> SpecCoreCurrentCustom = new Dictionary, float>>(); - + + private static Func, string> CanSpecCoreWork; - + public static Dictionary HookedConsumerInfos = new Dictionary(); - + + public static event Action OnSpecBlockCreated; public static event Action OnSpecBlockDestroyed; public static event Action OnLimitedBlockCreated; @@ -81,143 +84,53 @@ public static void TriggerOnLimitedBlockDestroyed(ILimitedBlock block) { OnLimitedBlockDestroyed?.Invoke(block); } - + public static object GetSpecCoreBlock(IMyTerminalBlock block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: block is null"); - return null; - } - var grid = block.CubeGrid; - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: block.CubeGrid is null"); - return null; - } - var ship = grid.GetShip(); - if (ship == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: grid.GetShip() is null"); - return null; - } - + if (ship == null) return null; ISpecBlock specBlock; - if (ship.SpecBlocks.TryGetValue(block, out specBlock)) - { - return specBlock; - } - else - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreBlock: ship.SpecBlocks does not contain the block"); - return null; - } + ship.SpecBlocks.TryGetValue(block, out specBlock); + return specBlock; } - + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetGridBlocksByType: grid is null"); - return null; - } - var ship = grid.GetShip(); return ship?.BlocksCache; } - + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetGridBlocksById: grid is null"); - return null; - } - var ship = grid.GetShip(); return ship?.BlocksCacheByType; } public static IMyTerminalBlock GetBlockSpecCore(object block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetBlockSpecCore: block is null"); - return null; - } - - var specBlock = block as ISpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine($"Hooks.GetBlockSpecCore: block of type {block.GetType().FullName} does not implement ISpecBlock"); - return null; - } - - return specBlock.block; + return ((ISpecBlock) block).block; } - + public static object GetLimitedBlock(IMyTerminalBlock block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: block is null"); - return null; - } - var grid = block.CubeGrid; - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: block.CubeGrid is null"); - return null; - } - var ship = grid.GetShip(); - if (ship == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: grid.GetShip() is null"); - return null; - } - + if (ship == null) return null; ILimitedBlock limitedBlock; - if (ship.LimitedBlocks.TryGetValue(block, out limitedBlock)) - { - return limitedBlock; - } - else - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlock: ship.LimitedBlocks does not contain the block"); - return null; - } + ship.LimitedBlocks.TryGetValue(block, out limitedBlock); + return limitedBlock; } public static IMyTerminalBlock GetLimitedBlockBlock(object block) { - if (block == null) - { - MyLog.Default.WriteLine("Hooks.GetLimitedBlockBlock: block is null"); - return null; - } + return ((ILimitedBlock) block).GetBlock(); + } - var limitedBlock = block as ILimitedBlock; - if (limitedBlock == null) - { - MyLog.Default.WriteLine($"Hooks.GetLimitedBlockBlock: block of type {block.GetType().FullName} does not implement ILimitedBlock"); - return null; - } - return limitedBlock.GetBlock(); - } public static object GetMainSpecCore(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetMainSpecCore: grid is null"); - return null; - } - Ship ship; if (OriginalSpecCoreSession.Instance.gridToShip.TryGetValue(grid.EntityId, out ship)) { @@ -226,15 +139,9 @@ public static object GetMainSpecCore(IMyCubeGrid grid) return null; } - + public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) { - if (grid == null) - { - MyLog.Default.WriteLine("Hooks.GetMainSpecCoreBlock: grid is null"); - return null; - } - Ship ship; if (OriginalSpecCoreSession.Instance.gridToShip.TryGetValue(grid.EntityId, out ship)) { @@ -243,15 +150,11 @@ public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) return null; } - + public static void GetSpecCoreLimits(object specCore, IDictionary dictionary, int mode) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreLimits: specCore is not a SpecBlock"); - return; - } + if (specBlock == null) return; switch (mode) { @@ -262,51 +165,35 @@ public static void GetSpecCoreLimits(object specCore, IDictionary di case 5: dictionary.Sum(specBlock.Settings.CustomStatic); break; case 6: dictionary.Sum(specBlock.Settings.CustomDynamic); break; case 7: dictionary.Sum(specBlock.GetLimits()); break; - default: - MyLog.Default.WriteLine($"Hooks.GetSpecCoreLimits: Invalid mode {mode}"); - break; } } - + public static void GetSpecCoreUpgrades(object specCore, List copyTo, int mode) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreUpgrades: specCore is not a SpecBlock"); - return; - } - + if (specBlock == null) return; copyTo.AddRange(specBlock.Settings.Upgrades); } - + public static void GetSpecCoreUpgrades(object specCore, List copyTo) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.GetSpecCoreUpgrades: specCore is not a SpecBlock"); - return; - } - + if (specBlock == null) return; copyTo.AddRange(specBlock.Settings.Upgrades); } public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) { var specBlock = specCore as SpecBlock; - if (specBlock == null) - { - MyLog.Default.WriteLine("Hooks.SetSpecCoreCustomValues: specCore is not a SpecBlock"); - return; - } - + if (specBlock == null) return; specBlock.Settings.CustomStatic.Sum(staticValues); specBlock.Settings.CustomDynamic.Sum(dynamicValues); specBlock.ApplyUpgrades(); specBlock.SaveSettings(); } + + /// /// Must be inited in LoadData of MySessionComponentBase /// @@ -315,7 +202,7 @@ public static void Init() ModConnection.Init(); TorchExtensions.Init(); - + ModConnection.SetValue("MIG.SpecCores.RegisterCustomLimitConsumer", registerCustomLimitConsumer); ModConnection.SetValue("MIG.SpecCores.GetMainSpecCore", getMainSpecCore); ModConnection.SetValue("MIG.SpecCores.GetMainSpecCoreBlock", getMainSpecCoreBlock); @@ -330,12 +217,12 @@ public static void Init() ModConnection.SetValue("MIG.SpecCores.GetBlockSpecCore", getBlockSpecCore); ModConnection.SetValue("MIG.SpecCores.GetLimitedBlock", getLimitedBlock); ModConnection.SetValue("MIG.SpecCores.GetLimitedBlockBlock", getLimitedBlockBlock); - + ModConnection.Subscribe("MIG.SpecCores.RegisterCustomLimitConsumer", registerCustomLimitConsumer, (x) => { registerCustomLimitConsumer = x; }); - + ModConnection.SetValue("MIG.SpecCores.RegisterSpecCorePointCustomFx", registerSpecCoreCurrentPointCustomFx); ModConnection.SetValue("MIG.SpecCores.AddSpecCoreLimitsInterceptor", addSpecCoreLimitsInterceptor); - + ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockCreated", OnSpecBlockCreated, (a) => { OnSpecBlockCreated += a; }); ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockDestroyed", OnSpecBlockDestroyed, (a) => { OnSpecBlockDestroyed += a; }); ModConnection.Subscribe("MIG.SpecCores.OnLimitedBlockCreated", OnLimitedBlockCreated, (a) => { OnLimitedBlockCreated += a; }); @@ -344,7 +231,7 @@ public static void Init() ModConnection.Subscribe("MIG.SpecCores.OnSpecBlockChanged", OnSpecCoreChanged, (a) => { OnSpecCoreChanged += a; }); ModConnection.Subscribe("MIG.SpecCores.CanSpecCoreWork", CanSpecCoreWork, (a) => { CanSpecCoreWork = a; }); } - + public static void Close() { ModConnection.Close(); @@ -360,31 +247,19 @@ public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegiste IsDrainingPoints = IsDrainingPoints, Disable = Disable, }; - } + public static void RegisterSpecCoreCurrentPointCustomFx(int id, Func, float> fx) { - if (fx == null) - { - MyLog.Default.WriteLine($"Hooks.RegisterSpecCoreCurrentPointCustomFx: fx is null for id {id}"); - return; - } - SpecCoreCurrentCustom[id] = fx; } - + public static void AddSpecCoreLimitsInterceptor(Action, Dictionary> fx) { - if (fx == null) - { - MyLog.Default.WriteLine("Hooks.AddSpecCoreLimitsInterceptor: fx is null"); - return; - } - SpecCoreLimitsInterceptor += fx; } - + public static string CanBeApplied(ISpecBlock specBlock, List grids) { return CanSpecCoreWork?.Invoke(specBlock, grids) ?? null; @@ -399,7 +274,7 @@ public static float GetCurrentPointValueForSpecCore(ISpecBlock specBlock, List grids, LimitPoint lp) { var fx = SpecCoreCurrentCustom.GetOr(lp.Id, null); diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs index d1cc2eab..02fbd2f5 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/LimitedBlock/LimitedBlockNetworking.cs @@ -66,26 +66,20 @@ public static void Handler (ILimitedBlock block, LimitedBlockSettings settings, public void OnSettingsChanged() { } - public void NotifyAndSave(byte type = 255, bool forceSave = false) + public void NotifyAndSave(byte type=255, bool forceSave = false) { try { if (MyAPIGateway.Session.IsServer) { - lock (Settings) - { - Sync.SendMessageToOthers(Block.EntityId, Settings, type: type); - SaveSettings(forceSave); - } + Sync.SendMessageToOthers(Block.EntityId, Settings, type: type); + SaveSettings(forceSave); } else { if (Sync != null) { - lock (Settings) - { - Sync.SendMessageToServer(Block.EntityId, Settings, type: type); - } + Sync.SendMessageToServer(Block.EntityId, Settings, type: type); } } } @@ -94,8 +88,7 @@ public void NotifyAndSave(byte type = 255, bool forceSave = false) Log.ChatError($"NotifyAndSave {type} Exception {ex} {ex.StackTrace}"); } } - - + public void SaveSettings(bool forceSave = false) { if (MyAPIGateway.Session.IsServer) diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs index f7ef1582..4aa7aa75 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlock.cs @@ -162,7 +162,6 @@ public void ApplyUpgrades() private static void Handler(SpecBlock block, UpgradableSpecBlockSettings settings, byte type, ulong userSteamId, bool isFromServer) { - Log.ChatError($"Handler called for block: {block.block.EntityId}, type: {type}, isFromServer: {isFromServer}"); if (isFromServer && !MyAPIGateway.Session.IsServer) { block.Settings = settings; diff --git a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs index b97e6a65..6014ecdc 100644 --- a/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs +++ b/TSTSSESCores/Data/Scripts/Scripts/Specials/ShipClass/SpecBlock/SpecBlockGui.cs @@ -122,14 +122,13 @@ private static void RemoveUpgradeGui(SpecBlock x) x.block.RefreshDI(); UpdateControls(x); } - + private static void ApplyUpgradesGui(SpecBlock x) { var settings = new UpgradableSpecBlockSettings(); settings.Upgrades.AddRange(x.AddedUpgrades); x.AddedUpgrades.Clear(); x.SelectedUpgrades.Clear(); - Log.ChatError($"Applying upgrades: {string.Join(",", settings.Upgrades)} to block: {x.block.EntityId}"); Sync.SendMessageToServer(x.block.EntityId, settings, type: APPLY_SELECTED); FrameExecutor.addDelayedLogic(30, (xx) => UpdateControls(x)); //1/2 sec if (!MyAPIGateway.Session.IsServer) @@ -137,7 +136,7 @@ private static void ApplyUpgradesGui(SpecBlock x) x.Settings = settings; //Remove gui lag } } - + private static void ApplyRandomUpgradesGui(SpecBlock x) { x.AddedUpgrades.Clear(); From 438766219af950f68d8a2a3a0f8816e2f5c741cf Mon Sep 17 00:00:00 2001 From: InvalidArgument3 Date: Tue, 4 Jun 2024 18:54:58 -0500 Subject: [PATCH 4/5] xde --- ....sbc => BlockCategories_TSTSSES_Cores.sbc} | 0 .../CubeBlocks_ShipCoreAssemblies_1.sbc | 296 ------- .../Data/Scripts/ScriptsAddon/App.config | 6 - .../Data/Scripts/ScriptsAddon/Language.cs | 53 -- .../Scripts/ScriptsAddon/Shared/Action2.cs | 15 - .../Scripts/ScriptsAddon/Shared/Common.cs | 64 -- .../ScriptsAddon/Shared/FrameExecutor.cs | 166 ---- .../Data/Scripts/ScriptsAddon/Shared/Log.cs | 98 --- .../ScriptsAddon/Shared/ModConnection.cs | 276 ------- .../Scripts/ScriptsAddon/Shared/SharpUtils.cs | 719 ------------------ .../Data/Scripts/ScriptsAddon/Shared/Timer.cs | 79 -- .../ScriptsAddon/Specials/AirFrictionAPI.txt | 44 -- .../Specials/Examples/UpgradeLogic.cs | 431 ----------- .../ScriptsAddon/Specials/SpecBlockHooks.cs | 329 -------- .../Specials/SpecBlockHooks_A.txt | 267 ------- .../ScriptsAddon/Specials/SpecCoreSession.cs | 41 - 16 files changed, 2884 deletions(-) rename TSTSSESCoresAddon/Data/{BlockCategories_SAIDS_Cores.sbc => BlockCategories_TSTSSES_Cores.sbc} (100%) delete mode 100644 TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt delete mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs diff --git a/TSTSSESCoresAddon/Data/BlockCategories_SAIDS_Cores.sbc b/TSTSSESCoresAddon/Data/BlockCategories_TSTSSES_Cores.sbc similarity index 100% rename from TSTSSESCoresAddon/Data/BlockCategories_SAIDS_Cores.sbc rename to TSTSSESCoresAddon/Data/BlockCategories_TSTSSES_Cores.sbc diff --git a/TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc b/TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc deleted file mode 100644 index cc365ca4..00000000 --- a/TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc +++ /dev/null @@ -1,296 +0,0 @@ - - - - - - - Reactor - FrigateCore_Reactor - - FrigateCore_Reactor - Textures\GUI\Icons\Cubes\nuclear_reactor.dds - FrigateCore_Reactor - Large - TriangleMesh - - - Models\Cubes\Large\GeneratorSmall.mwm - - - - - - - - - - - - - - - - - - - - - - - - - Z - Y - Light - 40 - - Reactors - 15 - - - 1 - 1 - 1 - - - - 0.0005 - 0.001 - - - 10.0 - - - - - Ingot - Uranium - - - - - ShipLrgNuclearSm - Damage_Reactor_Damaged - ParticleReactor - Default - BlockDestroyedExplosion_Large - WepSmallWarheadExpl - 25 - false - - 900 - 1800 - 3600 - - - PowerSystems - - - - - - CargoContainer - FrigateCore_Cargo - - FrigateCore_Cargo - Textures\GUI\Icons\Cubes\container.dds - FrigateCore_Cargo - Large - TriangleMesh - - - Models\Cubes\Large\CargoContainerSmall.mwm - - - - - - - - - - - - - - - - - - - - - - - - - - SmallCargoContainer - Z - Y - Light - 15 - Damage_HeavyMech_Damaged - ParticleHeavyMech - BlockDestroyedExplosion_Large - WepSmallWarheadExpl - 10 - true - - - - - - Reactor - DestroyerCore_Reactor - - DestroyerCore_Reactor - Textures\GUI\Icons\Cubes\nuclear_reactor.dds - DestroyerCore_Reactor - Large - TriangleMesh - - - Models\Cubes\Large\GeneratorSmall.mwm - - - - - - - - - - - - - - - - - - - - - - - - - Z - Y - Light - 40 - - Reactors - 15 - - - 1 - 1 - 1 - - - - 0.0005 - 0.001 - - - 10.0 - - - - - Ingot - Uranium - - - - - ShipLrgNuclearSm - Damage_Reactor_Damaged - ParticleReactor - Default - BlockDestroyedExplosion_Large - WepSmallWarheadExpl - 25 - false - - 900 - 1800 - 3600 - - - PowerSystems - - - - - - CargoContainer - DestroyerCore_Cargo - - DestroyerCore_Cargo - Textures\GUI\Icons\Cubes\container.dds - DestroyerCore_Cargo - Large - TriangleMesh - - - Models\Cubes\Large\CargoContainerSmall.mwm - - - - - - - - - - - - - - - - - - - - - - - - - - SmallCargoContainer - Z - Y - Light - 15 - Damage_HeavyMech_Damaged - ParticleHeavyMech - BlockDestroyedExplosion_Large - WepSmallWarheadExpl - 10 - true - - - - - diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config deleted file mode 100644 index bae5d6d8..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs deleted file mode 100644 index 5d8e7d51..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Sandbox.ModAPI; -using Sandbox.Game; -using VRage; -using VRage.Game.Components; -using VRage.Utils; - -namespace Example { - [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] - public class Mod : MySessionComponentBase { - - public MyLanguagesEnum? Language { get; private set; } - - public override void LoadData() { - LoadLocalization("Localization"); - LoadLocalization("Localization/Other"); - - MyAPIGateway.Gui.GuiControlRemoved += OnGuiControlRemoved; - } - - protected override void UnloadData() { - MyAPIGateway.Gui.GuiControlRemoved -= OnGuiControlRemoved; - } - - private void LoadLocalization(string folder) { - var path = Path.Combine(ModContext.ModPathData, folder); - var supportedLanguages = new HashSet(); - MyTexts.LoadSupportedLanguages(path, supportedLanguages); - - var currentLanguage = supportedLanguages.Contains(MyAPIGateway.Session.Config.Language) ? MyAPIGateway.Session.Config.Language : MyLanguagesEnum.English; - if (Language != null && Language == currentLanguage) { - return; - } - - Language = currentLanguage; - var languageDescription = MyTexts.Languages.Where(x => x.Key == currentLanguage).Select(x => x.Value).FirstOrDefault(); - if (languageDescription != null) { - var cultureName = string.IsNullOrWhiteSpace(languageDescription.CultureName) ? null : languageDescription.CultureName; - var subcultureName = string.IsNullOrWhiteSpace(languageDescription.SubcultureName) ? null : languageDescription.SubcultureName; - MyTexts.LoadTexts(path, cultureName, subcultureName); - } - } - - private void OnGuiControlRemoved(object obj) { - if (obj.ToString().EndsWith("ScreenOptionsSpace")) { - LoadLocalization("Localization"); - LoadLocalization("Localization/Other"); - } - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs deleted file mode 100644 index 6fc432bf..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MIG.Shared.CSharp { - public interface Action2 { - void run(T t, K k); - } - - public interface Action1 { - void run(T t); - } -} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs deleted file mode 100644 index 06ec3cf2..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Sandbox.Game; -using Sandbox.Game.World; -using Sandbox.ModAPI; -using ServerMod; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Digi; -using VRage.Game.ModAPI; -using VRageMath; - -namespace MIG.Shared.SE { - public static class Common { - - public static void SendChatMessage(string message, string author = "", long playerId = 0L, string font = "Blue") { - MyVisualScriptLogicProvider.SendChatMessage (message, author, playerId, font); - } - - public static void SendChatMessageToMe(string message, string author = "", string font = "Blue") { - if (MyAPIGateway.Session.Player != null) { - MyVisualScriptLogicProvider.SendChatMessage (message, author, MyAPIGateway.Session.Player.IdentityId, font); - } - } - - public static void ShowNotification(string message, int disappearTimeMs, string font = "White", long playerId = 0L) { - MyVisualScriptLogicProvider.ShowNotification (message, disappearTimeMs, font, playerId); - } - - public static void ShowNotificationForAllInRange(string message, int disappearTimeMs, Vector3D pos, float r, string font = "White") { - var pl = GetOnlinePlayersInRange (pos, r); - foreach (var x in pl) { - MyVisualScriptLogicProvider.ShowNotification (message, disappearTimeMs, font, x.IdentityId); - } - } - - - public static List GetOnlinePlayersInRange (Vector3D pos, float r) { - List players = new List(); - r = r*r; - MyAPIGateway.Multiplayer.Players.GetPlayers(players, (x)=>{ - var ch = x.Character; - if (ch != null) { - return (ch.WorldMatrix.Translation - pos).LengthSquared() < r; - } - return false; - }); - return players; - } - - public static String getPlayerName (long id) { - var p = getPlayer (id); - return p ==null ? "UnknownP" : p.DisplayName; - } - - public static IMyPlayer getPlayer (long id) { - var ind = new List(); - - MyAPIGateway.Players.GetPlayers (ind, (x) => { return x.IdentityId == id; }); - return ind.FirstOrDefault(null) as IMyPlayer; - } - } -} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs deleted file mode 100644 index eaead582..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using Digi; -using MIG.Shared.CSharp; -using VRage.ModAPI; - -namespace MIG.Shared.SE { - public static class FrameExecutor { - private static int frame = 0; - public static int currentFrame { get { return frame; } } - - private static readonly List> onEachFrameLogic = new List>(); - private static readonly List> addOnEachFrameLogic = new List>(); - private static readonly List> removeOnEachFrameLogic = new List>(); - private static bool needRemoveFrameLogic = false; - - public static void Update() { - try { - foreach (var x in onEachFrameLogic) { - x.run(frame); - } - - onEachFrameLogic.AddList(addOnEachFrameLogic); - foreach (var x in removeOnEachFrameLogic) - { - onEachFrameLogic.Remove(x); - } - addOnEachFrameLogic.Clear(); - removeOnEachFrameLogic.Clear(); - frame++; - } catch (Exception e) { - Log.ChatError("FrameExecutor", e); - } - } - - public static void addFrameLogic(Action1 action) { - Log.ChatError("TotalFrameLogics:" + addOnEachFrameLogic.Count + " " + onEachFrameLogic.Count); - addOnEachFrameLogic.Add(action); - } - - public static ActionWrapper addFrameLogic(Action action) { - Log.ChatError("TotalFrameLogics:" + addOnEachFrameLogic.Count + " " + onEachFrameLogic.Count); - ActionWrapper wrapper = new ActionWrapper(action); - addOnEachFrameLogic.Add(wrapper); - return wrapper; - } - - public static BlockWrapperAction addFrameLogic(Timer timer, IMyEntity entity, Action action) - { - return addFrameLogic(timer, entity, new ActionWrapper(action)); - } - - public static BlockWrapperAction addFrameLogic(Timer timer, IMyEntity entity, Action1 action) - { - if (entity == null) - { - Log.ChatError("addFrameLogic:Entity is null"); - return new BlockWrapperAction(entity, timer, action); - } - BlockWrapperAction wrapper = new BlockWrapperAction(entity, timer, action); - addOnEachFrameLogic.Add(wrapper); - return wrapper; - } - - public static void removeFrameLogic(Action1 action) { - removeOnEachFrameLogic.Add(action); - } - - public static void addDelayedLogic(long frames, Action1 action) { - addOnEachFrameLogic.Add(new DelayerAction(frames, action)); - } - - public static DelayerAction addDelayedLogic(long frames, Action action) - { - Log.ChatError("TotalFrameLogics:" + addOnEachFrameLogic.Count + " " + onEachFrameLogic.Count); - var da = new DelayerAction(frames, new ActionWrapper(action)); - addOnEachFrameLogic.Add(da); - return da; - } - - public class ActionWrapper : Action1 - { - Action action; - public ActionWrapper (Action action) - { - this.action = action; - } - - public void run(long t) - { - action(t); - } - - public void Unsub() - { - FrameExecutor.removeFrameLogic(this); - } - } - - - public class BlockWrapperAction : Action1 { - private Timer timer; - private Action1 action; - private IMyEntity entity; - public BlockWrapperAction(IMyEntity entity, Timer timer, Action1 action) { - this.timer = timer; - this.action = action; - this.entity = entity; - if (entity == null) - { - - } - } - - public void Cancel() - { - FrameExecutor.removeFrameLogic(this); - } - - public void RunNow() - { - action.run(-1); - } - - public void run(long k) { - if (timer.tick()) - { - if (entity.MarkedForClose || entity.Closed) - { - Cancel(); - return; - } - action.run(k); - } - } - } - - - public class DelayerAction : Action1 { - private long timer; - private Action1 action; - public DelayerAction(long timer, Action1 action) { - this.timer = timer; - this.action = action; - } - - public void Cancel() - { - FrameExecutor.removeFrameLogic(this); - } - - public void RunNow() - { - action.run(-1); - } - - public void run(long k) { - if (timer > 0) { - timer--; return; - } - FrameExecutor.removeFrameLogic(this); - action.run(k); - } - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs deleted file mode 100644 index dd222ff1..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using MIG.Shared.SE; -using Sandbox.ModAPI; -using ServerMod; -using VRage.Game; -using VRage.Game.Components; -using VRage.Game.ModAPI; -using VRage.Utils; - -namespace Digi { - public static class Log // v1.4 - { - public static string modName = "UNNAMED"; - public static string modFolder = "UNNAMED"; - public static ulong workshopId = 0; - - private static IMyHudNotification notify = null; - private static readonly List preInitMessages = new List(0); - - public static void Error(Exception e) { - Error(e.ToString()); - } - - public static void ServerError(Exception e) { - MyLog.Default.WriteLineAndConsole(e.Message + " " + e.StackTrace); - } - - public static void Error(Exception e, string printText) { - Error(printText +" "+ e.ToString(), printText); - } - - public static void Error(string msg) { - Error(msg, modName + " error - open %AppData%/SpaceEngineers"); - } - - public static void ChatError (String s, Exception e) { - ChatError (s + " " + e.ToString()); - } - - public static void ChatError (Exception e) { - ChatError (e.ToString()); - } - - - public static int MAX_LOGS = 5000; - public static int logged = 0; - - public static void ChatError (String s) { - MyLog.Default.WriteLine("SLIME:" + s); - if (!ShouldShowError ()) return; - - - Info(s); - - if (logged >= MAX_LOGS) return; - logged++; - - Common.SendChatMessageToMe (s, ""); - if (logged == MAX_LOGS) - { - Common.SendChatMessageToMe("Reached limit of messages. Watch logs", ""); - } - } - - public static bool ShouldShowError () { - return (MyAPIGateway.Session.Player == null || MyAPIGateway.Session.Player.PromoteLevel > MyPromoteLevel.None); //is Server or admin - } - - public static void Error(string msg, string printText) { - Info("ERROR: " + msg); - if (ShouldShowError ()) { - try { - if (MyAPIGateway.Session != null) { - //MyAPIGateway.Utilities.CreateNotification(msg, 5000, MyFontEnum.Red).Show(); - if (notify == null) { - notify = MyAPIGateway.Utilities.CreateNotification(msg, 5000, MyFontEnum.Red); - } else { - notify.Text = msg; - notify.ResetAliveTime(); - } - - notify.Show(); - } - } catch (Exception e) { - Info("ERROR: Could not send notification to local client: " + e); - MyLog.Default.WriteLineAndConsole(modName + " error/exception: Could not send notification to local client: " + e); - } - } - } - - public static void Info(string msg) { - MyLog.Default.WriteLineAndConsole(msg); - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs deleted file mode 100644 index d5c796c6..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs +++ /dev/null @@ -1,276 +0,0 @@ -using Sandbox.ModAPI; -using System; -using System.Collections.Generic; -using System.Text; -using ServerMod; -using VRage.Utils; - -namespace MIG.Shared.SE -{ - public static class ModConnection - { - private static string TAG = "MOD"; - private static int PORT1 = 6666666; - private static int PORT2 = 6666667; - private static Dictionary Data; - private static Dictionary>> Subscriptions = new Dictionary>>(); - private const bool DEBUGLOG = true; - private static List> RegisterQueue = new List>(); - - private static bool IsMain = false; - public static bool IsInited => ModConnection.Data != null; - - - public static void Close() - { - MyAPIGateway.Utilities.UnregisterMessageHandler(PORT1, ConnectionPortHandler); - MyAPIGateway.Utilities.UnregisterMessageHandler(PORT2, NotifyChannelHandler); - } - - public static void Init() - { - if (IsInited) - { - return; - } - Log("ModConnectionComponent:MOD Init"); - MyAPIGateway.Utilities.RegisterMessageHandler(PORT1, ConnectionPortHandler); - MyAPIGateway.Utilities.RegisterMessageHandler(PORT2, NotifyChannelHandler); - - MyAPIGateway.Utilities.SendModMessage(PORT1, null); - - if (Data == null) - { - IsMain = true; - Data = new Dictionary(); - foreach (var x in RegisterQueue) //We have to react on own methods too - { - SetValue(x.Key, x.Value, crashOnDuplicate: true); - } - //We dont need react, because we are subscribed on NotifyChannel - } - else - { - foreach (var x in Data) - { - Handle(x.Key, x.Value); - } - foreach (var x in RegisterQueue) - { - SetValue(x.Key, x.Value, crashOnDuplicate: true); - } - } - } - - - private static void ConnectionPortHandler(object data) - { - Log("ConnectionPortHandler"); - if (data == null) //Request data - { - if (IsMain && Data != null) - { - Log("Request data !" + TAG); - MyAPIGateway.Utilities.SendModMessage(PORT1, Data); - } - else - { - Log("Request data Error ! " + TAG + " [" + data+"]"); - //Ignore we are not Main, or not inited yet. - } - } - else - { - var fn = data as Dictionary; - if (fn != null) - { - Log ("Arrived data! "+ TAG); - Data = fn; - } - else - { - Log("Error1 ! " + TAG); - //possible trash; - } - } - } - - public static void Log (string data) - { - if (DEBUGLOG) - { - MyLog.Default.Error($"MCon {TAG}: {data}"); - } - } - - public static void LogError (string data) - { - if (DEBUGLOG) - { - MyLog.Default.Error($"MCon {TAG}: {data}"); - } - } - - private static void NotifyChannelHandler(object data) - { - var pair = data as KeyValuePair?; - if (!pair.HasValue) - { - Log("Something wrong"); - return; - } - var d = pair.Value; - - if (!Data.ContainsKey(d.Key)) - { - Log($"Desynchronization [{d.Key}]/[{d.Value}] -> [{d.Key}]/[null]"); - } - else - { - if (Data[d.Key] != d.Value) - { - Log($"Desynchronization [{d.Key}]/[{d.Value}] -> [{d.Key}]/[{Data[d.Key]}]"); - } - } - - Log($"Registered [{d.Key}]->[{d.Value}]"); - Handle(d.Key, d.Value); - } - - private static string ALL = ""; - private static void Handle(string Name, object O) - { - Log("Handle: " + Name); - if (Name != ALL) - { - if (Subscriptions.ContainsKey(Name)) - { - foreach (var x in Subscriptions[Name]) - { - try - { - x(Name, O); - } - catch (Exception e) - { - Log($"ModConnection: Exception for [{Name}] : {e.ToString()}"); - } - } - } - } - - if (Subscriptions.ContainsKey(ALL)) - { - foreach (var x in Subscriptions[ALL]) - { - try - { - x(Name, O); - } - catch (Exception e) - { - Log($"ModConnection: Exception for [{Name}] : {e.ToString()}"); - } - } - } - } - - - - - - public static void SetValue(string Name, object Data, bool crashOnDuplicate = false, bool notify = true) - { - if (ModConnection.Data == null) - { - RegisterQueue.Add(new KeyValuePair(Name, Data)); - } - else - { - if (crashOnDuplicate && ModConnection.Data.ContainsKey(Name)) - { - PrintAllData(); - throw new Exception($"Key already exists {Name} : [{ModConnection.Data[Name]}"); - } - - ModConnection.Data[Name] = Data; - if (notify) MyAPIGateway.Utilities.SendModMessage(PORT2, new KeyValuePair(Name, Data)); - } - } - - public static T Get(string Name) - { - object o; - if (Data.TryGetValue(Name, out o)) - { - if (o is T) - { - return (T)o; - } - } - - return default(T); - } - - public static void Subscribe(string Name, Action OnDataArrivedOrChanged) - { - Action catched = (a, b) => - { - try - { - OnDataArrivedOrChanged(a, b); - } - catch (Exception e) - { - Log($"{Name}:" + e.ToString()); - } - }; - - Subscriptions.GetOrNew(Name).Add(catched); - if (Data.ContainsKey(Name)) - { - try - { - catched(Name, Data[Name]); - } - catch (Exception e) - { - LogError($"ModConnection:OnDataArrivedOrChanged {Name} {Data[Name]} error: {e}"); - } - - } - } - - public static void Subscribe(string Name, Action OnDataArrivedOrChanged) - { - Subscribe(Name, (name, data) => OnDataArrivedOrChanged((T) data)); - } - - public static void Subscribe(string Name, T intance, Action OnDataArrivedOrChanged) - { - Subscribe(Name, (name, data) => OnDataArrivedOrChanged((T) data)); - } - - public static void SetValueAndSubscribe(string Name, T Data, Action OnDataArrivedOrChanged, bool crashOnDuplicate = true) - { - SetValue(Name, Data, crashOnDuplicate); - Subscribe(Name, OnDataArrivedOrChanged); - } - - public static void SubscribeToAll(Action OnDataArrivedOrChanged) - { - Subscribe(ALL, OnDataArrivedOrChanged); - } - - public static void PrintAllData() - { - var sb = new StringBuilder("ModConnection:\n"); - foreach (var x in Data) - { - sb.AppendLine($"{x.Key} -> {x.Value}"); - } - - Log(sb.ToString()); - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs deleted file mode 100644 index 33c12d13..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs +++ /dev/null @@ -1,719 +0,0 @@ -using Sandbox.ModAPI; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.Text; -using Digi; -using VRage; -using VRage.Game; -using VRage.Game.ModAPI; -using VRage.ObjectBuilders; -using VRageMath; -using Sandbox.Game.EntityComponents; - -namespace ServerMod { - - static class ToStr - { - public static string printContent(this List dict) { - StringBuilder sb = new StringBuilder(); - sb.Append("List["); - foreach (var x in dict) { - sb.Append(x).Append(",\n"); - } - sb.Append("]"); - return sb.ToString(); - } - - public static string printContent(this List dict) { - StringBuilder sb = new StringBuilder(); - sb.Append("List["); - foreach (var x in dict) { - sb.Append(x.DisplayName + "/" + x.PlayerID).Append(", "); - } - sb.Append("]"); - return sb.ToString(); - } - - public static string printContent(this List dict) { - StringBuilder sb = new StringBuilder(); - sb.Append("List["); - foreach (var x in dict) { - sb.Append(x.Name + "/" +x.FactionId).Append(", "); - } - sb.Append("]"); - return sb.ToString(); - } - - - public static string printContent(this List dict) { - StringBuilder sb = new StringBuilder(); - sb.Append("List["); - foreach (var x in dict) { - sb.Append("{").Append(x.ItemId).Append("/").Append(x.Amount).Append("/").Append(x.Blueprint).Append("},\n"); - } - sb.Append("]"); - return sb.ToString(); - } - - public static Dictionary Copy(this Dictionary dict) - { - return new Dictionary(dict); - } - } - - static class SharpUtils { - - - public static DateTime utcZero = new DateTime(1970, 1, 1); - public static DateTime y2020 = new DateTime(2020, 1, 1); - - public static float Lerp2 (float Current, float Desired, float Speed) - { - if (Current < Desired) - { - Current += Speed; - if (Current > Desired) - { - Current = Desired; - } - } - else - { - Current -= Speed; - if (Current < Desired) - { - Current = Desired; - } - } - return Current; - } - - public static float toRadian (this float v) - { - return (float)(v * Math.PI / 180d); - } - - public static double toRadian(this double v) - { - return (v * Math.PI / 180d); - } - - public static float toDegree (this float v) - { - return (float)(v / Math.PI * 180d); - } - - public static double toDegree (this double v) - { - return (v / Math.PI * 180d); - } - - public static int DayOfWeek (DateTime time) //Saturday = 6, Sunday = 7 - { - var utcZero = new DateTime(1970, 1, 1); - if (time < utcZero) return 1; - var d = (y2020 - utcZero).TotalDays; - var dd = (int)d + d%1>0 ? 1 : 0; - dd = dd- (dd / 7)*7 + 4; //1970 was Thursday - if (dd > 7) dd -=7; - return dd; - } - - - public static double Degree (Vector3D v1, Vector3D v2) - { - return Math.Acos(v1.Dot(v2) / (v1.Length() * v2.Length())).toDegree(); - } - - public static double Degree2 (Vector3D v1, Vector3D v2) - { - var d = Degree(v1, v2); - - if ((v1+v2).LengthSquared () < (v1 - v2).LengthSquared()) - { - d*=-1; - } - return d; - } - - public static long timeStamp () { - return (long)(DateTime.UtcNow.Subtract(utcZero)).TotalSeconds; - } - - public static long timeUtcDif() - { - return Math.Abs((long)DateTime.UtcNow.Subtract(DateTime.Now).TotalSeconds); - } - - public static bool HasFlags(this int x, int f) - { - return (x | f) == x; - } - - public static long msTimeStamp () { - return (long)(DateTime.UtcNow.Subtract(utcZero)).TotalMilliseconds; - } - - public static TimeSpan StripMilliseconds(this TimeSpan time) - { - return new TimeSpan(time.Days, time.Hours, time.Minutes, time.Seconds); - } - - - public static void AddOrRemove(this HashSet set, T data, bool add) { - if (add) { set.Add(data); } else { set.Remove(data); } - } - - public static void RemoveWhere(this Dictionary set, Func filter) - { - var list = new List(); - foreach (var t in set) - { - if (filter(t.Key, t.Value)) - { - list.Add(t.Key); - } - } - - foreach (var t in list) - { - set.Remove(t); - } - } - - public static string Print(this Dictionary dict, string separator = "\n", Func Where = null) { - StringBuilder sb = new StringBuilder(); - sb.Append("Dict["); - foreach (var x in dict) { - if (Where != null && !Where.Invoke(x.Key, x.Value)) continue; - sb.Append(x.Key).Append("->").Append(x.Value).Append(separator); - } - sb.Append("]"); - return sb.ToString(); - } - - public static string Print(this List list) - { - StringBuilder sb = new StringBuilder(); - sb.Append("List["); - foreach (var x in list) - { - sb.Append(x).Append(" "); - } - sb.Append("]"); - return sb.ToString(); - } - - private static Dictionary alliases = new Dictionary() { - { MyObjectBuilderType.Parse("MyObjectBuilder_Ingot"), "i/" }, - { MyObjectBuilderType.Parse("MyObjectBuilder_Ore"), "o/" }, - { MyObjectBuilderType.Parse("MyObjectBuilder_Component"), "" } - }; - - - public static string toHumanWeight (this double num) { - if (num <0.000001) return String.Format ("{0:N2} µg", num *1000000000); - if (num <0.001) return String.Format ("{0:N2} mg", num *1000000); - if (num <1) return String.Format ("{0:N2} g", num *1000); - if (num <1000) return String.Format ("{0:N2} kg", num); - if (num <1000000) return String.Format ("{0:N2} t", num /1000); - if (num <1000000000) return String.Format ("{0:N2} kt", num /1000000); - if (num <1000000000000) return String.Format ("{0:N2} Mt", num /1000000000); - if (num <1000000000000000) return String.Format ("{0:N2} Gt", num /1000000000000); - return "TONS"; - } - - - public static string toHumanWeight2 (this double num) - { - if (num <1000) return String.Format(CultureInfo.InvariantCulture, "{0:N0} Kg", num); - if (num <1000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} Ton", num / 1000).Replace(".0", ""); - if (num <1000000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} kTon", num /1000000).Replace(".0", ""); - if (num <1000000000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} MTon", num /1000000000).Replace(".0", ""); - if (num <1000000000000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} GTon", num /1000000000000).Replace(".0", ""); - return "TONS"; - } - - public static string toHumanQuantity (this double num) { - if (num <1000) return String.Format ("{0:N2}", num); - if (num <1000000) return String.Format ("{0:N2} K", num /1000); - if (num <1000000000) return String.Format ("{0:N2} M", num /1000000); - return "TONS"; - } - - public static string toPhysicQuantity (this double num, String s) { - var k = 1000d; - if (num 1000) return $"{num / 1000 :N0} GW"; - if (Math.Abs(num) > 1) return $"{num :N2} MW"; - if (Math.Abs(num) > 0.001) return $"{num * 1000 :N0} KW"; - return $"{num * 1000000 :N0} W"; - } - - public static string toHumanQuantityVolume (this double num) - { - if (Math.Abs(num) > 1000000000) return $"{num / 1000000000 :N2} GL"; - if (Math.Abs(num) > 1000000) return $"{num / 1000000 :N2} ML"; - if (Math.Abs(num) > 1000) return $"{num / 1000 :N2} kL"; - if (Math.Abs(num) > 100) return $"{num / 100 :N2} hL"; - if (Math.Abs(num) > 10) return $"{num / 10 :N2} daL"; - if (Math.Abs(num) > 1) return $"{num :N2} L"; - if (Math.Abs(num) > 0.1) return $"{num * 10 :N2} dL"; - if (Math.Abs(num) > 0.01) return $"{num * 100 :N2} cL"; - return $"{num * 1000 :N2} mL"; - } - - public static string toPercentage (this double num) { - return String.Format ("{0:N2}%", num*100); - } - - public static string toMlt (this double num) { - return String.Format ("{0:N2}", num); - } - - public static string toHumanTime (this double num) { - if (num <120) return String.Format ("{0:N0} s", num); - if (num <3600) return String.Format ("{0:N0} min", num /60); - if (num <3600*24) return String.Format ("{0:N0} h", num /3600); - return String.Format ("{0:N0} days", num/3600/24); - } - public static string toHumanTime2 (this int num, bool isFullWithDays = false) { - if (num < 60) return num + "s"; - if (num < 3600) return num / 60 + "m " + num % 60 + "s"; - if (num < 3600 * 24) return num / 3600 + "h " + (num / 60) % 60 + "m " + num % 60 + "s"; - if (num / 3600 / 24 == 1) return isFullWithDays ? "1 day " + num / 3600 + "h " + (num / 60) % 60 + "m " + num % 60 + "s" : "1 day"; - return isFullWithDays ? num / 3600 / 24 + " days " + num / 3600 % 24 + "h " + (num / 60) % 60 + "m " + num % 60 + "s" : num / 3600 / 24 + " days"; - } - - public static string fixZero (this double num) { - return String.Format ("{0:N2}", num); - } - - public static string fixZero(this float num) - { - return String.Format("{0:N2}", num); - } - - public static string toHumanString (this MyDefinitionId id) { - if (alliases.ContainsKey (id.TypeId)) { - return alliases[id.TypeId] +id.SubtypeName; - } else { - return id.TypeId.ToString().Substring (16) + "/"+id.SubtypeName; - } - } - - public static void Add(this IDictionary dict1, KeyValuePair kv) - { - dict1.Add(kv.Key, kv.Value); - } - - public static bool Remove(this IDictionary dict1, K key, V value) - { - if (dict1.ContainsKeyValue(key, value)) - { - dict1.Remove(key); - return true; - } - - return false; - } - - public static bool ContainsKeyValue(this IDictionary dict1, K key, V value) - { - V value2; - if (dict1.TryGetValue(key, out value2)) - { - return value.Equals(value2); - } - - return false; - } - - public static bool ContainsKeyValue(this IDictionary dict1, KeyValuePair kv) - { - return ContainsKeyValue(dict1, kv.Key, kv.Value); - } - - public static Dictionary SumDuplicates(this ICollection values) - { - var dict = new Dictionary(); - foreach (var u in values) - { - dict.Sum(u, 1); - } - - return dict; - } - - public static void RemoveDuplicates(this IDictionary dict1, IDictionary dict2) - { - foreach (var kv in dict2) - { - dict1.Remove(kv.Key, kv.Value); - } - } - - public static D GetDuplicates(this IDictionary dict1, IDictionary dict2) where D : Dictionary, new() - { - var dict3 = new D(); - foreach (var kv in dict1) - { - if (dict2.ContainsKeyValue(kv)) - { - dict3.Add(kv); - } - } - - return dict3; - } - - public static void RemoveDuplicatesBoth(this Dictionary dict1, Dictionary dict2) - { - var list = new List(); - foreach (var kv in dict2) - { - if (dict1.Remove(kv.Key, kv.Value)) - { - list.Add(kv.Key); - } - } - - foreach (var k in list) - { - dict2.Remove(k); - } - } - - public static string Print (this Dictionary dict, Func printer, string separator = "\r\n") - { - var s = new StringBuilder(); - int c = 0; - foreach (var kv in dict) - { - s.Append(printer (kv.Key, kv.Value)); - if (c != dict.Count-1) - { - s.Append(separator); - } - } - - return s.ToString(); - } - - public static float CurrentPowerInput(this IMyCubeBlock block) => block?.ResourceSink?.CurrentInputByType(MyResourceDistributorComponent.ElectricityId) ?? 0; - public static float MinRequiredPowerInput(this IMyCubeBlock block) => block?.ResourceSink?.RequiredInputByType(MyResourceDistributorComponent.ElectricityId) ?? 0; - public static float MaxRequiredPowerInput(this IMyCubeBlock block) => block?.ResourceSink?.MaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId) ?? 0; - - public static bool IsOneKeyMoreThan (this IDictionary buffer, IDictionary maxLimits) - { - foreach (var y in buffer) - { - if (y.Value > maxLimits[y.Key]) - { - return true; - } - } - return false; - } - - public static T ElementAtOrLast(this T[] array, int at) - { - var min = Math.Min(at, array.Length-1); - return array[min]; - } - - public static T ElementAtOrLast(this IList array, int at) - { - var min = Math.Min(at, array.Count-1); - return array[min]; - } - - - public static Action TryCatch(this Action func, string debugName) - { - return (a) => - { - try - { - func.Invoke(a); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - } - }; - } - - public static Action TryCatch(this Action func, string debugName) - { - return (a,b) => - { - try - { - func.Invoke(a,b); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - } - }; - } - - public static Action TryCatch(this Action func, string debugName) - { - return (a,b,c) => - { - try - { - func.Invoke(a,b,c); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - } - }; - } - - public static Action TryCatch(this Action func, string debugName) - { - return (a,b,c,d) => - { - try - { - func.Invoke(a,b,c,d); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - } - }; - } - - public static Func TryCatch(this Func func, string debugName) - { - return (a) => - { - try - { - return func.Invoke(a); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - return default(R); - } - }; - } - - - public static Func TryCatch(this Func func, string debugName) - { - return (a,b) => - { - try - { - return func.Invoke(a,b); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - return default(R); - } - }; - } - - public static Func TryCatch(this Func func, string debugName) - { - return (a,b,c) => - { - try - { - return func.Invoke(a,b,c); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - return default(R); - } - }; - } - - public static Func TryCatch(this Func func, string debugName) - { - return (a,b,c,d) => - { - try - { - return func.Invoke(a,b,c,d); - } - catch (Exception e) - { - Log.ChatError(debugName, e); - return default(R); - } - }; - } - - public static bool IsOneKeyMoreThan (this IDictionary buffer, IDictionary maxLimits) - { - foreach (var y in buffer) - { - try - { - if (y.Value > maxLimits[y.Key]) - { - return true; - } - } - catch (Exception e) - { - Log.ChatError($"IsOneKeyMoreThan: {y.Key}"); - } - - } - return false; - } - - - public static void Sum (this IDictionary dict, T key, double value) { - if (!dict.ContainsKey(key)) { - dict[key] = value; - } else { - dict[key] = dict[key] + value; - } - } - - public static void Sum (this IDictionary dict, T key, float value) { - if (!dict.ContainsKey(key)) { - dict[key] = value; - } else { - dict[key] = dict[key] + value; - } - } - - public static void Mlt (this IDictionary dict, T key, float value) { - if (!dict.ContainsKey(key)) { - dict[key] = value; - } else { - dict[key] = dict[key] * value; - } - } - - public static void Sum (this IDictionary dict, T key, MyFixedPoint value) { - if (!dict.ContainsKey(key)) { - dict[key] = value; - } else { - dict[key] = dict[key] + value; - } - } - - public static void Sum (this IDictionary dict, T key, int value) { - if (!dict.ContainsKey(key)) { - dict[key] = value; - } else { - dict[key] = dict[key] + value; - } - } - - public static void Sum (this IDictionary dict, IDictionary dict2) { - foreach (var d in dict2) - { - dict.Sum(d.Key, d.Value); - } - } - - - - public static StringBuilder Append(this StringBuilder sb, IMyPlayer player, IMyFaction faction) { - sb.Append (player.DisplayName); - if (faction != null) { - sb.Append("[").Append(faction.Tag).Append("]"); - } - - return sb; - } - - public static StringBuilder Append(this StringBuilder sb, IMyIdentity player, IMyFaction faction) { - sb.Append (player.DisplayName); - if (faction != null) { - sb.Append("[").Append(faction.Tag).Append("]"); - } - - return sb; - } - - - - - public static K GetOr(this IDictionary dict, T t, K k) { - if (dict.ContainsKey(t)) { - return dict[t]; - } else { - return k; - } - } - - public static K GetOrNew(this IDictionary dict, T t) where K : new() { - if (!dict.ContainsKey(t)) - { - var k = new K(); - dict[t] = k; - return dict[t]; - } - else - { - return dict[t]; - } - } - - public static List GetOrCreate(this IDictionary> dict, T t) { - if (!dict.ContainsKey(t)) { - dict.Add (t, new List()); - } - return dict[t]; - } - - public static HashSet GetOrCreate(this IDictionary> dict, T t) { - if (!dict.ContainsKey(t)) { - dict.Add (t, new HashSet()); - } - return dict[t]; - } - - public static Dictionary GetOrCreate(this IDictionary> dict, T t) { - if (!dict.ContainsKey(t)) { - dict.Add (t, new Dictionary()); - } - return dict[t]; - } - - public static K Set(this Dictionary dict, T t, K k) { - K old = default(K); - if (dict.ContainsKey(t)) { - old = dict[t]; - dict.Remove(t); - } - dict.Add(t, k); - return old; - } - } -} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs deleted file mode 100644 index ba52bc39..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MIG.Shared.CSharp { - public class Timer { - protected int time; - - public Timer(int time = 0) { - this.time = time; - } - - public virtual bool tick() { - time--; - return time < 0; - } - - public bool needAction() { - return time < 0; - } - - public int getTime () { - return time; - } - - public void addTime(int time) { - if (this.time < 0) { - this.time = 0; - } - - this.time += time; - } - - public void setTime (int time) { - this.time = time; - } - } - - public class AutoTimer : Timer { - int interval; - - public void setInterval (int interval) { - this.interval = interval; - } - public AutoTimer (int interval, int time = 0) : base(time) { - this.interval = interval; - } - - public int getInterval () { - return interval; - } - - public void setInterval (int interval, int time) { - this.interval = interval; - this.time = time; - } - - public void reset () { - time = interval; - } - - public override bool tick() { - if (base.tick()) { - addTime(interval); - return true; - } else { - return false; - } - } - - public void addTime () { - addTime(interval); - } - - public override string ToString() { return "AutoTimer ["+time + " / " +interval+"]"; } - } -} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt deleted file mode 100644 index 100e2c29..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using MIG.Shared.SE; -using Scripts.Specials.ShipClass; -using VRage.Game.Components; -using VRage.Game.ModAPI; - -namespace Scripts.Specials -{ - [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] - public class SpecCoreSession : MySessionComponentBase - { - public override void LoadData() - { - AirFrictionAPI.Init(); - } - } - - public class AirFrictionAPI - { - private static Func getGridFriction; - - public static int MinSpeed = 0; - public static int MaxSpeed = 1; - public static int CurrentSpeed = 2; - public static int AppliedForce = 3; - - public static void Init() - { - if (!ModConnection.IsInited) - { - ModConnection.Init(); - } - ModConnection.Subscribe>("MIG.AirFriction.GetGridFriction", (x) => - { - getGridFriction = x; - }); - } - - public static double[] GetGridFriction(IMyCubeGrid grid) - { - return getGridFriction?.Invoke(grid); - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs deleted file mode 100644 index 0f5ae60b..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs +++ /dev/null @@ -1,431 +0,0 @@ -using System.Collections.Generic; -using Sandbox.Game.Entities; -using Sandbox.ModAPI; -using Scripts.Specials.ShipClass; -using VRage.Game.Components; -using VRage.Game.ModAPI; -using VRageMath; -using VRage.Utils; -using Sandbox.Game.Entities.Cube; -using System.Runtime.CompilerServices; -using static VRage.Game.ObjectBuilders.Definitions.MyObjectBuilder_GameDefinition; -using ProtoBuf; -using Sandbox.Engine.Utils; -using VRage; -using static VRage.Game.MyObjectBuilder_BehaviorTreeDecoratorNode; - -namespace ServerMod -{ - [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] - public class UpgradeThrusters : MySessionComponentBase - { - private static bool isServer; - private static bool allowOnLimitedBlockCreated; - private static List limitedBlocksToProcess = new List(); - - public override void LoadData() - { - isServer = MyAPIGateway.Session.IsServer; - } - - public override void BeforeStart() - { - //MyAPIGateway.Multiplayer.RegisterMessageHandler(5561, MessageHandler); - } - - static UpgradeThrusters() - { - SpecBlockHooks.OnReady += HooksOnOnReady; - } - - private static void HooksOnOnReady() - { - if (isServer) - SpecBlockHooks.OnSpecBlockChanged += OnSpecBlockChanged; - - SpecBlockHooks.OnLimitedBlockCreated += OnLimitedBlockCreated; - SpecBlockHooks.OnSpecBlockDestroyed += OnSpecBlockDestroyed; - } - - //This takes effect works after the grid is cut/pasted or spec block is deleted - private static void OnSpecBlockChanged(object specBlock, List grids) - { - if (isServer) - { - allowOnLimitedBlockCreated = true; - OnLimitedBlockCreated(null); - SpecBlockHooks.OnSpecBlockChanged -= OnSpecBlockChanged; - - //RunUpgrades(specBlock, grids); - } - /*else - { - MyAPIGateway.Parallel.StartBackground(() => - { - MyLog.Default.WriteLineAndConsole($"Running Code on Client"); - MyAPIGateway.Parallel.Sleep(5000); - RunUpgrades(specBlock, grids); - }); - }*/ - } - - private static void RunUpgrades(object specBlock, List grids, bool reset = false) - { - foreach (var grid in grids) - { - - //npc checking stuff borrowed from Digi - if (grid.BigOwners == null || grid.BigOwners.Count == 0) - continue; - - long owner = grid.BigOwners[0]; // only check the first one, too edge case to check others - var faction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(owner); - - if (faction != null && faction.IsEveryoneNpc()) - continue; - - List blocks = new List(); - //var core = SpecBlockHooks.GetMainSpecCore(grid); - var stats = new Dictionary(); - List upgrades = new List(); - SpecBlockHooks.GetSpecCoreLimits(specBlock, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); - grid.GetBlocks(blocks, x => x.FatBlock is IMyTerminalBlock); - - foreach (var block in blocks) - { - var thrustBlock = block.FatBlock as IMyThrust; - var reactorBlock = block.FatBlock as IMyReactor; - var generatorBlock = block.FatBlock as IMyGasGenerator; - var drillBlock = block.FatBlock as IMyShipDrill; - var gyroBlock = block.FatBlock as IMyGyro; - - if (thrustBlock != null) - { - if (stats.ContainsKey(46) && stats[46] != 0 && !reset) - { - thrustBlock.ThrustMultiplier = stats[46]; - } - else - { - thrustBlock.ThrustMultiplier = 1.0f; - } - //Log.ChatError($"SetMultiplier to: {thrustBlock.ThrustMultiplier}"); - if (stats.ContainsKey(46) && stats[46] != 0 && !reset) - { - thrustBlock.PowerConsumptionMultiplier = 1 / stats[46]; - } - else - { - thrustBlock.PowerConsumptionMultiplier = 1.0f; - } - //Log.ChatError($"SetMultiplier to: {thrustBlock.PowerConsumptionMultiplier}"); - } - - - if (reactorBlock != null) - { - if (stats.ContainsKey(28) && stats[28] != 0 && !reset) - { - reactorBlock.PowerOutputMultiplier = stats[28]; - } - else - { - reactorBlock.PowerOutputMultiplier = 1.0f; - } - //Log.ChatError($"SetMultiplier to: {reactorBlock.PowerOutputMultiplier}"); - } - - if (gyroBlock != null) - { - if (stats.ContainsKey(28) && stats[28] != 0 && !reset) - { - gyroBlock.PowerConsumptionMultiplier = 1 / MathHelper.Max(1, stats[28]); - //gyroBlock.GyroStrengthMultiplier = stats[28]; - } - else - { - gyroBlock.PowerConsumptionMultiplier = 1.0f; - //gyroBlock.GyroStrengthMultiplier = 1.0f; - } - //Log.ChatError($"SetMultiplier to: {gyroBlock.PowerConsumptionMultiplier}"); - } - - - if (generatorBlock != null) - { - if (stats.ContainsKey(29) && stats[29] != 0 && !reset) - { - //This is the rate of ice consumption, NOT the rate of O2/H2 output - generatorBlock.ProductionCapacityMultiplier = stats[29]; - generatorBlock.PowerConsumptionMultiplier = stats[29] / MathHelper.Max(1, stats[28]); - } - else - { - //This is the rate of ice consumption, NOT the rate of O2/H2 output - generatorBlock.ProductionCapacityMultiplier = 1.0f; - generatorBlock.PowerConsumptionMultiplier = 1.0f; - } - //Log.ChatError($"SetMultiplier to: {generatorBlock.ProductionCapacityMultiplier}"); - } - - if (drillBlock != null) - { - if (stats.ContainsKey(27) && stats[27] != 0 && !reset) - { - drillBlock.DrillHarvestMultiplier = stats[27]; - drillBlock.PowerConsumptionMultiplier = 1 / stats[27]; - } - else - { - drillBlock.DrillHarvestMultiplier = 1.0f; - drillBlock.PowerConsumptionMultiplier = 1.0f; - } - //Log.ChatError($"SetMultiplier to: {drillBlock.DrillHarvestMultiplier}"); - } - } - } - } - - private static void UpgradeBlock(object limitedBlock) - { - var tBlock = SpecBlockHooks.GetLimitedBlockBlock(limitedBlock); - if (tBlock == null) - return; - - var grid = tBlock.CubeGrid; - if (grid == null) - return; - - //npc checking stuff borrowed from Digi - if (grid.BigOwners == null || grid.BigOwners.Count == 0) - return; - - long owner = grid.BigOwners[0]; // only check the first one, too edge case to check others - var faction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(owner); - - if (faction != null && faction.IsEveryoneNpc()) - return; - - var thrustBlock = tBlock as IMyThrust; - var reactorBlock = tBlock as IMyReactor; - var generatorBlock = tBlock as IMyGasGenerator; - var drillBlock = tBlock as IMyShipDrill; - var gyroBlock = tBlock as IMyGyro; - - var core = SpecBlockHooks.GetMainSpecCore(grid); - var stats = new Dictionary(); - SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); - - if (thrustBlock != null) - { - if (stats != null && stats.ContainsKey(46) && stats[46] != 0) - { - thrustBlock.ThrustMultiplier = stats[46]; - thrustBlock.PowerConsumptionMultiplier = 1 / stats[46]; - } - else - { - thrustBlock.ThrustMultiplier = 1.0f; - thrustBlock.PowerConsumptionMultiplier = 1.0f; - } - } - - if (reactorBlock != null) - { - if (stats != null && stats.ContainsKey(28) && stats[28] != 0) - { - reactorBlock.PowerOutputMultiplier = stats[28]; - } - else - { - reactorBlock.PowerOutputMultiplier = 1.0f; - } - } - - if (gyroBlock != null) - { - if (stats != null && stats.ContainsKey(28) && stats[28] != 0) - { - gyroBlock.PowerConsumptionMultiplier = 1 / MathHelper.Max(1, stats[28]); - } - else - { - gyroBlock.PowerConsumptionMultiplier = 1.0f; - } - } - - if (generatorBlock != null) - { - if (stats != null && stats.ContainsKey(29) && stats[29] != 0) - { - generatorBlock.ProductionCapacityMultiplier = stats[29]; - generatorBlock.PowerConsumptionMultiplier = stats[29] / MathHelper.Max(1, stats[28]); - } - else - { - generatorBlock.ProductionCapacityMultiplier = 1.0f; - generatorBlock.PowerConsumptionMultiplier = 1.0f; - } - } - - if (drillBlock != null) - { - if (stats != null && stats.ContainsKey(27) && stats[27] != 0) - { - drillBlock.DrillHarvestMultiplier = stats[27]; - drillBlock.PowerConsumptionMultiplier = 1 / stats[27]; - } - else - { - drillBlock.DrillHarvestMultiplier = 1.0f; - drillBlock.PowerConsumptionMultiplier = 1.0f; - } - } - } - //This doesnt seem to work when expected, not sure why, is this even needed? - private static void OnLimitedBlockCreated(object limitedBlock) - { - /*MyAPIGateway.Parallel.StartBackground(() => - { - MyAPIGateway.Parallel.Sleep(5000); - if (!isServer) - { - MyAPIGateway.Utilities.InvokeOnGameThread(() => - { - var tBlock = SpecBlockHooks.GetLimitedBlockBlock(limitedBlock); - if (tBlock == null) - { - MyLog.Default.WriteLineAndConsole($"Limited Block is null!!"); - return; - } - - RequestBlockUpgrade(MyAPIGateway.Multiplayer.MyId); - }); - } - });*/ - - if (!allowOnLimitedBlockCreated && isServer) - { - limitedBlocksToProcess.Add(limitedBlock); - return; - } - - if (isServer) - { - foreach (var block in limitedBlocksToProcess) - UpgradeBlock(block); - - if (limitedBlock == null) - { - limitedBlocksToProcess.Clear(); - return; - } - } - - MyAPIGateway.Parallel.StartBackground(() => - { - MyAPIGateway.Parallel.Sleep(5000); - MyAPIGateway.Utilities.InvokeOnGameThread(() => { UpgradeBlock(limitedBlock); }); - - }); - } - - // Commented out because it breaks mysteriously - private static void OnSpecBlockDestroyed(object specBlock) - { - //var tBlock = SpecBlockHooks.GetBlockSpecCore(specBlock); - //if (tBlock == null) - // return; - // - //IMyCubeGrid grid = tBlock.CubeGrid; - //List grids = new List(); - //MyAPIGateway.GridGroups.GetGroup(grid, GridLinkTypeEnum.Mechanical, grids); - //RunUpgrades(specBlock, grids, true); - } - - /*public static void MessageHandler(byte[] data) - { - try - { - var package = MyAPIGateway.Utilities.SerializeFromBinary(data); - if (package == null) return; - - if (package.Type == DataType.RequestSettings) - { - var packet = MyAPIGateway.Utilities.SerializeFromBinary(package.Data); - if (packet == null) return; - - - return; - } - - if (package.Type == DataType.SendSettings) - { - var packet = MyAPIGateway.Utilities.SerializeFromBinary(package.Data); - if (packet == null) return; - - return; - } - } - catch { }; - } - - public static void RequestBlockUpgrade(ulong steamId) - { - ObjectContainer objectContainer = new ObjectContainer() - { - steamId = steamId - }; - - CommsPackage package = new CommsPackage(DataType.RequestBlockUpgrade, objectContainer); - var sendData = MyAPIGateway.Utilities.SerializeToBinary(package); - MyAPIGateway.Multiplayer.SendMessageToServer(5561, sendData); - } - - public enum DataType - { - - RequestBlockUpgrade, - SendBlockUpgrade, - } - - [ProtoContract] - public class ObjectContainer - { - [ProtoMember(1)] public ulong steamId; - [ProtoMember(2)] public long blockId; - [ProtoMember(3)] public float upgradeValue; - - - - } - - [ProtoContract] - public class CommsPackage - { - [ProtoMember(1)] - public DataType Type; - - [ProtoMember(2)] - public byte[] Data; - - public CommsPackage() - { - Type = DataType.RequestBlockUpgrade; - Data = new byte[0]; - } - - public CommsPackage(DataType type, ObjectContainer oc) - { - Type = type; - Data = MyAPIGateway.Utilities.SerializeToBinary(oc); - } - }*/ - - protected override void UnloadData() - { - //MyAPIGateway.Multiplayer.UnregisterMessageHandler(5561, MessageHandler); - - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs deleted file mode 100644 index 87cff80d..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs +++ /dev/null @@ -1,329 +0,0 @@ -using System; -using System.Collections.Generic; -using MIG.Shared.SE; -using Sandbox.ModAPI; -using VRage.Game; -using VRage.Utils; -using VRage.Game.ModAPI; -using F = System.Func; -using FF = System.Func; -using A = System.Action; -using C = System.Func; -using U = System.Collections.Generic.List; -using L = System.Collections.Generic.IDictionary; - -namespace Scripts.Specials.ShipClass -{ - public class SpecBlockHooks - { - public interface ILimitedBlock - { - bool IsDrainingPoints(); - void Disable(); - void CanWork(); - bool CanBeDisabled(); - bool CheckConditions(IMyTerminalBlock specBlock); - } - - public enum GetSpecCoreLimitsEnum - { - StaticLimits = 1, - DynamicLimits = 2, - FoundLimits = 3, - TotalLimits = 4, - CustomStatic = 5, - CustomDynamic = 6, - CurrentStaticOrDynamic = 7 - } - - - private static Action RegisterCustomLimitConsumerImpl; - private static Func getMainSpecCore; - private static Func getMainSpecCoreBlock; - private static Action getSpecCoreLimits; - private static Action getSpecCoreUpgrades; - private static Action setSpecCoreCustomValues; - - private static Func getSpecCoreBlock; - private static Func getBlockSpecCore; - private static Func getLimitedBlock; - private static Func getLimitedBlockBlock; - - private static Func>> getGridBlocksByType; - private static Func>> getGridBlocksById; - - private static Action , float>> registerSpecCorePointCustomFx; - private static Action, Dictionary>> addSpecCoreLimitsInterceptor; - - public static event Action OnReady; - - public static event Action OnSpecBlockCreated; - public static event Action OnSpecBlockDestroyed; - public static event Action OnLimitedBlockCreated; - public static event Action OnLimitedBlockDestroyed; - - public static event Action> OnSpecBlockChanged; - - public static bool IsReady() - { - return - RegisterCustomLimitConsumerImpl != null && - getMainSpecCore != null && - getMainSpecCoreBlock != null && - getSpecCoreLimits != null && - getSpecCoreUpgrades != null && - setSpecCoreCustomValues != null && - - getSpecCoreBlock != null && - getBlockSpecCore != null && - getLimitedBlock != null && - getLimitedBlockBlock != null && - - getGridBlocksByType != null && - getGridBlocksById != null && - - - addSpecCoreLimitsInterceptor != null && - registerSpecCorePointCustomFx != null; - } - - private static void TriggerIsReady() - { - if (IsReady()) - { - OnReady?.Invoke(); - } - } - - /// - /// Must be inited in LoadData of MySessionComponentBase - /// - public static void Init() - { - ModConnection.Init(); - ModConnection.Subscribe("MIG.SpecCores.RegisterCustomLimitConsumer", RegisterCustomLimitConsumerImpl, (x) => { RegisterCustomLimitConsumerImpl = x; TriggerIsReady(); }); - - ModConnection.Subscribe("MIG.SpecCores.GetMainSpecCore", getMainSpecCore, (x) => { getMainSpecCore = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetMainSpecCoreBlock", getMainSpecCoreBlock, (x) => { getMainSpecCoreBlock = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetSpecCoreLimits", getSpecCoreLimits,(x) => { getSpecCoreLimits = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetSpecCoreUpgrades", getSpecCoreUpgrades, (x) => { getSpecCoreUpgrades = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.SetSpecCoreCustomValues", setSpecCoreCustomValues, (x) => { setSpecCoreCustomValues = x; TriggerIsReady(); }); - - ModConnection.Subscribe("MIG.SpecCores.GetGridBlocksByType", getGridBlocksByType, (x) => { getGridBlocksByType = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetGridBlocksById", getGridBlocksById, (x) => { getGridBlocksById = x; TriggerIsReady(); }); - - ModConnection.Subscribe("MIG.SpecCores.GetSpecCoreBlock", getSpecCoreBlock, (x) => { getSpecCoreBlock = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetBlockSpecCore", getBlockSpecCore, (x) => { getBlockSpecCore = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetLimitedBlock", getLimitedBlock, (x) => { getLimitedBlock = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.GetLimitedBlockBlock", getLimitedBlockBlock, (x) => { getLimitedBlockBlock = x; TriggerIsReady(); }); - - ModConnection.Subscribe("MIG.SpecCores.RegisterSpecCorePointCustomFx", registerSpecCorePointCustomFx, (x) => { registerSpecCorePointCustomFx = x; TriggerIsReady(); }); - ModConnection.Subscribe("MIG.SpecCores.AddSpecCoreLimitsInterceptor", addSpecCoreLimitsInterceptor, (x)=>{ addSpecCoreLimitsInterceptor = x; TriggerIsReady(); }); - - - - Action onSpecBlockCreated = (x) => OnSpecBlockCreated?.Invoke(x); - Action onSpecBlockDestroyed = (x) => OnSpecBlockDestroyed?.Invoke(x); - Action onLimitedBlockCreated = (x) => OnLimitedBlockCreated?.Invoke(x); - Action onLimitedBlockDestroyed = (x) => OnLimitedBlockDestroyed?.Invoke(x); - - Action> onSpecBlockChanged = (x,y) => OnSpecBlockChanged?.Invoke(x,y); - - ModConnection.SetValue("MIG.SpecCores.OnSpecBlockCreated", onSpecBlockCreated); - ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockCreated", OnLimitedBlockCreated); - ModConnection.SetValue("MIG.SpecCores.OnSpecBlockDestroyed", OnSpecBlockDestroyed); - ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockDestroyed", onLimitedBlockDestroyed); - - ModConnection.SetValue("MIG.SpecCores.OnSpecBlockChanged", onSpecBlockChanged); - - MyAPIGateway.Session.DamageSystem.RegisterBeforeDamageHandler(10, HandleDamage); - } - - public static void Close() - { - ModConnection.Close(); - } - - - public static void SetCanSpecCoreWorkFx(Func, string> fx) - { - ModConnection.SetValue("MIG.SpecCores.CanSpecCoreWork", fx); - } - - public static void RegisterSpecCorePointCustomFx(int pointId, Func, float> fx) - { - registerSpecCorePointCustomFx?.Invoke(pointId, fx); - } - - public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegistered, A CanWork, FF CheckConditions, F CanBeDisabled, F IsDrainingPoints, A Disable) - { - RegisterCustomLimitConsumerImpl(Id, OnNewConsumerRegistered, CanWork, CheckConditions, CanBeDisabled, IsDrainingPoints, Disable); - } - - public static object GetMainSpecCore(IMyCubeGrid grid) - { - return getMainSpecCore?.Invoke(grid); - } - - public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) - { - return getMainSpecCoreBlock?.Invoke(grid); - } - - public static void GetSpecCoreLimits(object specCore, IDictionary buffer, GetSpecCoreLimitsEnum limits) - { - getSpecCoreLimits?.Invoke(specCore, buffer, (int) limits); - } - - public static void GetSpecCoreUpgrades(object specCore, List buffer) - { - getSpecCoreUpgrades?.Invoke(specCore, buffer); - } - - public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) - { - setSpecCoreCustomValues?.Invoke(specCore, staticValues, dynamicValues); - } - - public static void AddSpecCoreLimitsInterceptor(Action, Dictionary> fx) - { - addSpecCoreLimitsInterceptor?.Invoke(fx); - } - - public static object GetSpecCoreBlock(IMyTerminalBlock block) - { - return getSpecCoreBlock?.Invoke(block); - } - - public static IMyTerminalBlock GetBlockSpecCore(object block) - { - return getBlockSpecCore?.Invoke(block); - } - - public static object GetLimitedBlock(IMyTerminalBlock block) - { - return getLimitedBlock?.Invoke(block); - } - - public static IMyTerminalBlock GetLimitedBlockBlock(object block) - { - if (getLimitedBlockBlock == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: getLimitedBlockBlock is null"); - return null; - } - - if (block == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: block is null"); - return null; - } - - try - { - var limitedBlock = block as ILimitedBlock; - if (limitedBlock == null) - { - MyLog.Default.WriteLine($"SpecBlockHooks: block of type {block.GetType().FullName} does not implement ILimitedBlock"); - return null; - } - - return getLimitedBlockBlock.Invoke(block); - } - catch (InvalidCastException) - { - MyLog.Default.WriteLine($"SpecBlockHooks: Failed to cast block of type {block.GetType().FullName} to ILimitedBlock"); - return null; - } - catch (Exception e) - { - MyLog.Default.WriteLine($"SpecBlockHooks: Error in GetLimitedBlockBlock: {e.Message}"); - return null; - } - } - - public static void RegisterCustomLimitConsumer(string Id, Func creator) - { - SpecBlockHooks.RegisterCustomLimitConsumer(Id, - creator, - (logic) => - { - var limitedBlock = logic as ILimitedBlock; - if (limitedBlock != null) limitedBlock.CanWork(); - }, - (block, logic) => - { - var limitedBlock = logic as ILimitedBlock; - return limitedBlock != null && limitedBlock.CheckConditions(block); - }, - (logic) => - { - var limitedBlock = logic as ILimitedBlock; - return limitedBlock != null && limitedBlock.CanBeDisabled(); - }, - (logic) => - { - var limitedBlock = logic as ILimitedBlock; - return limitedBlock != null && limitedBlock.IsDrainingPoints(); - }, - (logic) => - { - var limitedBlock = logic as ILimitedBlock; - if (limitedBlock != null) limitedBlock.Disable(); - }); - } - - public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) - { - if (grid == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksByType"); - return null; - } - return getGridBlocksByType?.Invoke(grid) ?? null; - } - - public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) - { - if (grid == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksById"); - return null; - } - return getGridBlocksById?.Invoke(grid) ?? null; - } - - public static void HandleDamage(object target, ref MyDamageInformation damage) - { //Parallel - try - { - var slimBlock = target as IMySlimBlock; - if (slimBlock == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: target is not IMySlimBlock in HandleDamage"); - return; - } - - var cubeGrid = slimBlock.CubeGrid; - var core = SpecBlockHooks.GetMainSpecCore(cubeGrid); - if (core == null) - { - MyLog.Default.WriteLine("SpecBlockHooks: core is null in HandleDamage"); - return; - } - - var stats = new Dictionary(); - SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); - if (stats != null && stats.ContainsKey(-33) && stats[-33] != 0) - { - damage.Amount *= stats[-33]; - } - } - catch (Exception e) - { - MyLog.Default.WriteLine($"SpecBlockHooks: Error in HandleDamage: {e.Message}"); - } - } - - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt deleted file mode 100644 index cdb44e1d..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt +++ /dev/null @@ -1,267 +0,0 @@ -using System; -using System.Collections.Generic; -using Digi; -using MIG.Shared.SE; -using Sandbox.ModAPI; -using ServerMod; -using VRage.Game; -using VRage.Game.ModAPI; -using F = System.Func; -using FF = System.Func; -using A = System.Action; -using C = System.Func; -using U = System.Collections.Generic.List; -using L = System.Collections.Generic.IDictionary; - -using VRageMath; -using VRage.Utils; -using Sandbox.Definitions; -using Sandbox.Game; -using Sandbox.Game.Entities; -using VRage.ObjectBuilders; - -namespace Scripts.Specials.ShipClass -{ - - public class SpecBlockHooks - { - public interface ILimitedBlock - { - bool IsDrainingPoints(); - void Disable(); - void CanWork(); - bool CanBeDisabled(); - bool CheckConditions(IMyTerminalBlock specBlock); - } - - public enum GetSpecCoreLimitsEnum - { - StaticLimits = 1, - DynamicLimits = 2, - FoundLimits = 3, - TotalLimits = 4, - CustomStatic = 5, - CustomDynamic = 6, - CurrentStaticOrDynamic = 7 - } - - - private static Action RegisterCustomLimitConsumerImpl; - private static Func getMainSpecCore; - private static Func getMainSpecCoreBlock; - private static Action getSpecCoreLimits; - private static Action getSpecCoreUpgrades; - private static Action setSpecCoreCustomValues; - - private static Func getSpecCoreBlock; - private static Func getBlockSpecCore; - private static Func getLimitedBlock; - private static Func getLimitedBlockBlock; - - private static Func>> getGridBlocksByType; - private static Func>> getGridBlocksById; - - private static Action , float>> registerSpecCorePointCustomFx; - - public static event Action OnReady; - - public static event Action OnSpecBlockCreated; - public static event Action OnSpecBlockDestroyed; - public static event Action OnLimitedBlockCreated; - public static event Action OnLimitedBlockDestroyed; - - public static event Action> OnSpecBlockChanged; - - public static bool IsReady() - { - return - RegisterCustomLimitConsumerImpl != null && - getMainSpecCore != null && - getMainSpecCoreBlock != null && - getSpecCoreLimits != null && - getSpecCoreUpgrades != null && - setSpecCoreCustomValues != null && - - getSpecCoreBlock != null && - getBlockSpecCore != null && - getLimitedBlock != null && - getLimitedBlockBlock != null && - - getGridBlocksByType != null && - getGridBlocksById != null; - } - - private static void TriggerIsReady() - { - if (IsReady()) - { - OnReady?.Invoke(); - } - } - - /// - /// Must be inited in LoadData of MySessionComponentBase - /// - public static void Init() - { - Log.ChatError("SpecBlockHooks:Init"); - ModConnection.Init(); - ModConnection.Subscribe>("MIG.SpecCores.RegisterCustomLimitConsumer", (x) => { RegisterCustomLimitConsumerImpl = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetMainSpecCore", (x) => { getMainSpecCore = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetMainSpecCoreBlock", (x) => { getMainSpecCoreBlock = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetSpecCoreLimits", (x) => { getSpecCoreLimits = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetSpecCoreUpgrades", (x) => { getSpecCoreUpgrades = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.SetSpecCoreCustomValues", (x) => { setSpecCoreCustomValues = x; TriggerIsReady(); }); - - ModConnection.Subscribe>>>("MIG.SpecCores.GetGridBlocksByType", (x) => { getGridBlocksByType = x; TriggerIsReady(); }); - ModConnection.Subscribe>>>("MIG.SpecCores.GetGridBlocksById", (x) => { getGridBlocksById = x; TriggerIsReady(); }); - - ModConnection.Subscribe>("MIG.SpecCores.GetSpecCoreBlock", (x) => { getSpecCoreBlock = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetBlockSpecCore", (x) => { getBlockSpecCore = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetLimitedBlock", (x) => { getLimitedBlock = x; TriggerIsReady(); }); - ModConnection.Subscribe>("MIG.SpecCores.GetLimitedBlockBlock", (x) => { getLimitedBlockBlock = x; TriggerIsReady(); }); - - ModConnection.Subscribe, float>>>("MIG.SpecCores.RegisterSpecCorePointCustomFx", (x) => { registerSpecCorePointCustomFx = x; TriggerIsReady(); }); - - Action onSpecBlockCreated = (x) => OnSpecBlockCreated?.Invoke(x); - Action onSpecBlockDestroyed = (x) => OnSpecBlockDestroyed?.Invoke(x); - Action onLimitedBlockCreated = (x) => OnLimitedBlockCreated?.Invoke(x); - Action onLimitedBlockDestroyed = (x) => OnLimitedBlockDestroyed?.Invoke(x); - - Action> onSpecBlockChanged = (x,y) => OnSpecBlockChanged?.Invoke(x,y); - - ModConnection.SetValue("MIG.SpecCores.OnSpecBlockCreated", onSpecBlockCreated); - ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockCreated", onSpecBlockDestroyed); - ModConnection.SetValue("MIG.SpecCores.OnSpecBlockDestroyed", onLimitedBlockCreated); - ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockDestroyed", onLimitedBlockDestroyed); - - ModConnection.SetValue("MIG.SpecCores.OnSpecBlockChanged", onSpecBlockChanged); - - //MyAPIGateway.Session.DamageSystem.RegisterBeforeDamageHandler(10, HandleDamage); - } - - public static void Close() - { - ModConnection.Close(); - } - - public static void SetCanSpecCoreWorkFx(Func, string> fx) - { - ModConnection.SetValue("MIG.SpecCores.CanSpecCoreWork", fx); - } - - public static void RegisterSpecCorePointCustomFx(int pointId, Func, float> fx) - { - registerSpecCorePointCustomFx.Invoke(pointId, fx); - } - - public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegistered, A CanWork, FF CheckConditions, F CanBeDisabled, F IsDrainingPoints, A Disable) - { - RegisterCustomLimitConsumerImpl(Id, OnNewConsumerRegistered, CanWork, CheckConditions, CanBeDisabled, IsDrainingPoints, Disable); - } - - public static object GetMainSpecCore(IMyCubeGrid grid) - { - return getMainSpecCore.Invoke(grid); - } - - public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) - { - return getMainSpecCoreBlock.Invoke(grid); - } - - public static void GetSpecCoreLimits(object specCore, IDictionary buffer, GetSpecCoreLimitsEnum limits) - { - getSpecCoreLimits.Invoke(specCore, buffer, (int) limits); - } - - public static void GetSpecCoreUpgrades(object specCore, List buffer) - { - getSpecCoreUpgrades.Invoke(specCore, buffer); - } - - public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) - { - setSpecCoreCustomValues.Invoke(specCore, staticValues, dynamicValues); - } - - public static object GetSpecCoreBlock(IMyTerminalBlock block) - { - return getSpecCoreBlock.Invoke(block); - } - - public static IMyTerminalBlock GetBlockSpecCore(object block) - { - return getBlockSpecCore.Invoke(block); - } - - public static object GetLimitedBlock(IMyTerminalBlock block) - { - return getLimitedBlock.Invoke(block); - } - - public static IMyTerminalBlock GetLimitedBlockBlock(object block) - { - return getLimitedBlockBlock.Invoke(block); - } - - public static void RegisterCustomLimitConsumer(string Id, Func creator) - { - SpecBlockHooks.RegisterCustomLimitConsumer(Id, - creator, - (logic)=> - { - ((ILimitedBlock) logic).CanWork(); - }, - (block, logic) => - { - return ((ILimitedBlock) logic).CheckConditions(block); - }, - (logic)=> - { - return ((ILimitedBlock) logic).CanBeDisabled(); - }, - (logic)=> - { - return ((ILimitedBlock) logic).IsDrainingPoints(); - }, - (logic)=> - { - ((ILimitedBlock) logic).Disable(); - }); - } - - public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) - { - return getGridBlocksByType?.Invoke(grid) ?? null; - } - - public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) - { - return getGridBlocksById?.Invoke(grid) ?? null; - } - - public static void HandleDamage(object target, ref MyDamageInformation damage) - { //Paralell - try - { - var slimBlock = target as IMySlimBlock; - if (slimBlock != null) - { - var cubeGrid = slimBlock.CubeGrid; - var core = SpecBlockHooks.GetMainSpecCore(slimBlock.CubeGrid); - var stats = new Dictionary(); - SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); - if(stats.ContainsKey(55)) - { - damage.Amount *= stats [55]; //here id of property - } - } - } - catch(Exception e) - { - Log.ChatError("CustomDamageHandler:", e); - } - } - } -} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs deleted file mode 100644 index 4246f42a..00000000 --- a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml.Serialization; -using Digi; -using MIG.Shared.CSharp; -using MIG.Shared.SE; -using ProtoBuf; -using Sandbox.ModAPI; -using Scripts.Specials.ShipClass; -using VRage; -using VRage.Game; -using VRage.Game.Components; -using VRage.Game.ModAPI; -using VRage.ModAPI; - -namespace MIG.SpecCores -{ - [MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation)] - public class SpecCoreSession : MySessionComponentBase - { - public override void Init(MyObjectBuilder_SessionComponent sessionComponent) - { - base.Init(sessionComponent); - SpecBlockHooks.Init(); - } - - private bool inited = false; - public override void UpdateBeforeSimulation() - { - base.UpdateBeforeSimulation(); - FrameExecutor.Update(); - - } - - protected override void UnloadData() - { - SpecBlockHooks.Close(); - } - } -} \ No newline at end of file From ff063d3ab0efe42ca5c196a7102504a6c517e894 Mon Sep 17 00:00:00 2001 From: InvalidArgument3 Date: Tue, 4 Jun 2024 19:06:41 -0500 Subject: [PATCH 5/5] Revert "xde" This reverts commit 438766219af950f68d8a2a3a0f8816e2f5c741cf. --- ...es.sbc => BlockCategories_SAIDS_Cores.sbc} | 0 .../CubeBlocks_ShipCoreAssemblies_1.sbc | 296 +++++++ .../Data/Scripts/ScriptsAddon/App.config | 6 + .../Data/Scripts/ScriptsAddon/Language.cs | 53 ++ .../Scripts/ScriptsAddon/Shared/Action2.cs | 15 + .../Scripts/ScriptsAddon/Shared/Common.cs | 64 ++ .../ScriptsAddon/Shared/FrameExecutor.cs | 166 ++++ .../Data/Scripts/ScriptsAddon/Shared/Log.cs | 98 +++ .../ScriptsAddon/Shared/ModConnection.cs | 276 +++++++ .../Scripts/ScriptsAddon/Shared/SharpUtils.cs | 719 ++++++++++++++++++ .../Data/Scripts/ScriptsAddon/Shared/Timer.cs | 79 ++ .../ScriptsAddon/Specials/AirFrictionAPI.txt | 44 ++ .../Specials/Examples/UpgradeLogic.cs | 431 +++++++++++ .../ScriptsAddon/Specials/SpecBlockHooks.cs | 329 ++++++++ .../Specials/SpecBlockHooks_A.txt | 267 +++++++ .../ScriptsAddon/Specials/SpecCoreSession.cs | 41 + 16 files changed, 2884 insertions(+) rename TSTSSESCoresAddon/Data/{BlockCategories_TSTSSES_Cores.sbc => BlockCategories_SAIDS_Cores.sbc} (100%) create mode 100644 TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt create mode 100644 TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs diff --git a/TSTSSESCoresAddon/Data/BlockCategories_TSTSSES_Cores.sbc b/TSTSSESCoresAddon/Data/BlockCategories_SAIDS_Cores.sbc similarity index 100% rename from TSTSSESCoresAddon/Data/BlockCategories_TSTSSES_Cores.sbc rename to TSTSSESCoresAddon/Data/BlockCategories_SAIDS_Cores.sbc diff --git a/TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc b/TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc new file mode 100644 index 00000000..cc365ca4 --- /dev/null +++ b/TSTSSESCoresAddon/Data/CubeBlocks/CubeBlocks_ShipCoreAssemblies_1.sbc @@ -0,0 +1,296 @@ + + + + + + + Reactor + FrigateCore_Reactor + + FrigateCore_Reactor + Textures\GUI\Icons\Cubes\nuclear_reactor.dds + FrigateCore_Reactor + Large + TriangleMesh + + + Models\Cubes\Large\GeneratorSmall.mwm + + + + + + + + + + + + + + + + + + + + + + + + + Z + Y + Light + 40 + + Reactors + 15 + + + 1 + 1 + 1 + + + + 0.0005 + 0.001 + + + 10.0 + + + + + Ingot + Uranium + + + + + ShipLrgNuclearSm + Damage_Reactor_Damaged + ParticleReactor + Default + BlockDestroyedExplosion_Large + WepSmallWarheadExpl + 25 + false + + 900 + 1800 + 3600 + + + PowerSystems + + + + + + CargoContainer + FrigateCore_Cargo + + FrigateCore_Cargo + Textures\GUI\Icons\Cubes\container.dds + FrigateCore_Cargo + Large + TriangleMesh + + + Models\Cubes\Large\CargoContainerSmall.mwm + + + + + + + + + + + + + + + + + + + + + + + + + + SmallCargoContainer + Z + Y + Light + 15 + Damage_HeavyMech_Damaged + ParticleHeavyMech + BlockDestroyedExplosion_Large + WepSmallWarheadExpl + 10 + true + + + + + + Reactor + DestroyerCore_Reactor + + DestroyerCore_Reactor + Textures\GUI\Icons\Cubes\nuclear_reactor.dds + DestroyerCore_Reactor + Large + TriangleMesh + + + Models\Cubes\Large\GeneratorSmall.mwm + + + + + + + + + + + + + + + + + + + + + + + + + Z + Y + Light + 40 + + Reactors + 15 + + + 1 + 1 + 1 + + + + 0.0005 + 0.001 + + + 10.0 + + + + + Ingot + Uranium + + + + + ShipLrgNuclearSm + Damage_Reactor_Damaged + ParticleReactor + Default + BlockDestroyedExplosion_Large + WepSmallWarheadExpl + 25 + false + + 900 + 1800 + 3600 + + + PowerSystems + + + + + + CargoContainer + DestroyerCore_Cargo + + DestroyerCore_Cargo + Textures\GUI\Icons\Cubes\container.dds + DestroyerCore_Cargo + Large + TriangleMesh + + + Models\Cubes\Large\CargoContainerSmall.mwm + + + + + + + + + + + + + + + + + + + + + + + + + + SmallCargoContainer + Z + Y + Light + 15 + Damage_HeavyMech_Damaged + ParticleHeavyMech + BlockDestroyedExplosion_Large + WepSmallWarheadExpl + 10 + true + + + + + diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config new file mode 100644 index 00000000..bae5d6d8 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs new file mode 100644 index 00000000..5d8e7d51 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Language.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Sandbox.ModAPI; +using Sandbox.Game; +using VRage; +using VRage.Game.Components; +using VRage.Utils; + +namespace Example { + [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] + public class Mod : MySessionComponentBase { + + public MyLanguagesEnum? Language { get; private set; } + + public override void LoadData() { + LoadLocalization("Localization"); + LoadLocalization("Localization/Other"); + + MyAPIGateway.Gui.GuiControlRemoved += OnGuiControlRemoved; + } + + protected override void UnloadData() { + MyAPIGateway.Gui.GuiControlRemoved -= OnGuiControlRemoved; + } + + private void LoadLocalization(string folder) { + var path = Path.Combine(ModContext.ModPathData, folder); + var supportedLanguages = new HashSet(); + MyTexts.LoadSupportedLanguages(path, supportedLanguages); + + var currentLanguage = supportedLanguages.Contains(MyAPIGateway.Session.Config.Language) ? MyAPIGateway.Session.Config.Language : MyLanguagesEnum.English; + if (Language != null && Language == currentLanguage) { + return; + } + + Language = currentLanguage; + var languageDescription = MyTexts.Languages.Where(x => x.Key == currentLanguage).Select(x => x.Value).FirstOrDefault(); + if (languageDescription != null) { + var cultureName = string.IsNullOrWhiteSpace(languageDescription.CultureName) ? null : languageDescription.CultureName; + var subcultureName = string.IsNullOrWhiteSpace(languageDescription.SubcultureName) ? null : languageDescription.SubcultureName; + MyTexts.LoadTexts(path, cultureName, subcultureName); + } + } + + private void OnGuiControlRemoved(object obj) { + if (obj.ToString().EndsWith("ScreenOptionsSpace")) { + LoadLocalization("Localization"); + LoadLocalization("Localization/Other"); + } + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs new file mode 100644 index 00000000..6fc432bf --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Action2.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MIG.Shared.CSharp { + public interface Action2 { + void run(T t, K k); + } + + public interface Action1 { + void run(T t); + } +} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs new file mode 100644 index 00000000..06ec3cf2 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Common.cs @@ -0,0 +1,64 @@ +using Sandbox.Game; +using Sandbox.Game.World; +using Sandbox.ModAPI; +using ServerMod; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Digi; +using VRage.Game.ModAPI; +using VRageMath; + +namespace MIG.Shared.SE { + public static class Common { + + public static void SendChatMessage(string message, string author = "", long playerId = 0L, string font = "Blue") { + MyVisualScriptLogicProvider.SendChatMessage (message, author, playerId, font); + } + + public static void SendChatMessageToMe(string message, string author = "", string font = "Blue") { + if (MyAPIGateway.Session.Player != null) { + MyVisualScriptLogicProvider.SendChatMessage (message, author, MyAPIGateway.Session.Player.IdentityId, font); + } + } + + public static void ShowNotification(string message, int disappearTimeMs, string font = "White", long playerId = 0L) { + MyVisualScriptLogicProvider.ShowNotification (message, disappearTimeMs, font, playerId); + } + + public static void ShowNotificationForAllInRange(string message, int disappearTimeMs, Vector3D pos, float r, string font = "White") { + var pl = GetOnlinePlayersInRange (pos, r); + foreach (var x in pl) { + MyVisualScriptLogicProvider.ShowNotification (message, disappearTimeMs, font, x.IdentityId); + } + } + + + public static List GetOnlinePlayersInRange (Vector3D pos, float r) { + List players = new List(); + r = r*r; + MyAPIGateway.Multiplayer.Players.GetPlayers(players, (x)=>{ + var ch = x.Character; + if (ch != null) { + return (ch.WorldMatrix.Translation - pos).LengthSquared() < r; + } + return false; + }); + return players; + } + + public static String getPlayerName (long id) { + var p = getPlayer (id); + return p ==null ? "UnknownP" : p.DisplayName; + } + + public static IMyPlayer getPlayer (long id) { + var ind = new List(); + + MyAPIGateway.Players.GetPlayers (ind, (x) => { return x.IdentityId == id; }); + return ind.FirstOrDefault(null) as IMyPlayer; + } + } +} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs new file mode 100644 index 00000000..eaead582 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/FrameExecutor.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using Digi; +using MIG.Shared.CSharp; +using VRage.ModAPI; + +namespace MIG.Shared.SE { + public static class FrameExecutor { + private static int frame = 0; + public static int currentFrame { get { return frame; } } + + private static readonly List> onEachFrameLogic = new List>(); + private static readonly List> addOnEachFrameLogic = new List>(); + private static readonly List> removeOnEachFrameLogic = new List>(); + private static bool needRemoveFrameLogic = false; + + public static void Update() { + try { + foreach (var x in onEachFrameLogic) { + x.run(frame); + } + + onEachFrameLogic.AddList(addOnEachFrameLogic); + foreach (var x in removeOnEachFrameLogic) + { + onEachFrameLogic.Remove(x); + } + addOnEachFrameLogic.Clear(); + removeOnEachFrameLogic.Clear(); + frame++; + } catch (Exception e) { + Log.ChatError("FrameExecutor", e); + } + } + + public static void addFrameLogic(Action1 action) { + Log.ChatError("TotalFrameLogics:" + addOnEachFrameLogic.Count + " " + onEachFrameLogic.Count); + addOnEachFrameLogic.Add(action); + } + + public static ActionWrapper addFrameLogic(Action action) { + Log.ChatError("TotalFrameLogics:" + addOnEachFrameLogic.Count + " " + onEachFrameLogic.Count); + ActionWrapper wrapper = new ActionWrapper(action); + addOnEachFrameLogic.Add(wrapper); + return wrapper; + } + + public static BlockWrapperAction addFrameLogic(Timer timer, IMyEntity entity, Action action) + { + return addFrameLogic(timer, entity, new ActionWrapper(action)); + } + + public static BlockWrapperAction addFrameLogic(Timer timer, IMyEntity entity, Action1 action) + { + if (entity == null) + { + Log.ChatError("addFrameLogic:Entity is null"); + return new BlockWrapperAction(entity, timer, action); + } + BlockWrapperAction wrapper = new BlockWrapperAction(entity, timer, action); + addOnEachFrameLogic.Add(wrapper); + return wrapper; + } + + public static void removeFrameLogic(Action1 action) { + removeOnEachFrameLogic.Add(action); + } + + public static void addDelayedLogic(long frames, Action1 action) { + addOnEachFrameLogic.Add(new DelayerAction(frames, action)); + } + + public static DelayerAction addDelayedLogic(long frames, Action action) + { + Log.ChatError("TotalFrameLogics:" + addOnEachFrameLogic.Count + " " + onEachFrameLogic.Count); + var da = new DelayerAction(frames, new ActionWrapper(action)); + addOnEachFrameLogic.Add(da); + return da; + } + + public class ActionWrapper : Action1 + { + Action action; + public ActionWrapper (Action action) + { + this.action = action; + } + + public void run(long t) + { + action(t); + } + + public void Unsub() + { + FrameExecutor.removeFrameLogic(this); + } + } + + + public class BlockWrapperAction : Action1 { + private Timer timer; + private Action1 action; + private IMyEntity entity; + public BlockWrapperAction(IMyEntity entity, Timer timer, Action1 action) { + this.timer = timer; + this.action = action; + this.entity = entity; + if (entity == null) + { + + } + } + + public void Cancel() + { + FrameExecutor.removeFrameLogic(this); + } + + public void RunNow() + { + action.run(-1); + } + + public void run(long k) { + if (timer.tick()) + { + if (entity.MarkedForClose || entity.Closed) + { + Cancel(); + return; + } + action.run(k); + } + } + } + + + public class DelayerAction : Action1 { + private long timer; + private Action1 action; + public DelayerAction(long timer, Action1 action) { + this.timer = timer; + this.action = action; + } + + public void Cancel() + { + FrameExecutor.removeFrameLogic(this); + } + + public void RunNow() + { + action.run(-1); + } + + public void run(long k) { + if (timer > 0) { + timer--; return; + } + FrameExecutor.removeFrameLogic(this); + action.run(k); + } + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs new file mode 100644 index 00000000..dd222ff1 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Log.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using MIG.Shared.SE; +using Sandbox.ModAPI; +using ServerMod; +using VRage.Game; +using VRage.Game.Components; +using VRage.Game.ModAPI; +using VRage.Utils; + +namespace Digi { + public static class Log // v1.4 + { + public static string modName = "UNNAMED"; + public static string modFolder = "UNNAMED"; + public static ulong workshopId = 0; + + private static IMyHudNotification notify = null; + private static readonly List preInitMessages = new List(0); + + public static void Error(Exception e) { + Error(e.ToString()); + } + + public static void ServerError(Exception e) { + MyLog.Default.WriteLineAndConsole(e.Message + " " + e.StackTrace); + } + + public static void Error(Exception e, string printText) { + Error(printText +" "+ e.ToString(), printText); + } + + public static void Error(string msg) { + Error(msg, modName + " error - open %AppData%/SpaceEngineers"); + } + + public static void ChatError (String s, Exception e) { + ChatError (s + " " + e.ToString()); + } + + public static void ChatError (Exception e) { + ChatError (e.ToString()); + } + + + public static int MAX_LOGS = 5000; + public static int logged = 0; + + public static void ChatError (String s) { + MyLog.Default.WriteLine("SLIME:" + s); + if (!ShouldShowError ()) return; + + + Info(s); + + if (logged >= MAX_LOGS) return; + logged++; + + Common.SendChatMessageToMe (s, ""); + if (logged == MAX_LOGS) + { + Common.SendChatMessageToMe("Reached limit of messages. Watch logs", ""); + } + } + + public static bool ShouldShowError () { + return (MyAPIGateway.Session.Player == null || MyAPIGateway.Session.Player.PromoteLevel > MyPromoteLevel.None); //is Server or admin + } + + public static void Error(string msg, string printText) { + Info("ERROR: " + msg); + if (ShouldShowError ()) { + try { + if (MyAPIGateway.Session != null) { + //MyAPIGateway.Utilities.CreateNotification(msg, 5000, MyFontEnum.Red).Show(); + if (notify == null) { + notify = MyAPIGateway.Utilities.CreateNotification(msg, 5000, MyFontEnum.Red); + } else { + notify.Text = msg; + notify.ResetAliveTime(); + } + + notify.Show(); + } + } catch (Exception e) { + Info("ERROR: Could not send notification to local client: " + e); + MyLog.Default.WriteLineAndConsole(modName + " error/exception: Could not send notification to local client: " + e); + } + } + } + + public static void Info(string msg) { + MyLog.Default.WriteLineAndConsole(msg); + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs new file mode 100644 index 00000000..d5c796c6 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/ModConnection.cs @@ -0,0 +1,276 @@ +using Sandbox.ModAPI; +using System; +using System.Collections.Generic; +using System.Text; +using ServerMod; +using VRage.Utils; + +namespace MIG.Shared.SE +{ + public static class ModConnection + { + private static string TAG = "MOD"; + private static int PORT1 = 6666666; + private static int PORT2 = 6666667; + private static Dictionary Data; + private static Dictionary>> Subscriptions = new Dictionary>>(); + private const bool DEBUGLOG = true; + private static List> RegisterQueue = new List>(); + + private static bool IsMain = false; + public static bool IsInited => ModConnection.Data != null; + + + public static void Close() + { + MyAPIGateway.Utilities.UnregisterMessageHandler(PORT1, ConnectionPortHandler); + MyAPIGateway.Utilities.UnregisterMessageHandler(PORT2, NotifyChannelHandler); + } + + public static void Init() + { + if (IsInited) + { + return; + } + Log("ModConnectionComponent:MOD Init"); + MyAPIGateway.Utilities.RegisterMessageHandler(PORT1, ConnectionPortHandler); + MyAPIGateway.Utilities.RegisterMessageHandler(PORT2, NotifyChannelHandler); + + MyAPIGateway.Utilities.SendModMessage(PORT1, null); + + if (Data == null) + { + IsMain = true; + Data = new Dictionary(); + foreach (var x in RegisterQueue) //We have to react on own methods too + { + SetValue(x.Key, x.Value, crashOnDuplicate: true); + } + //We dont need react, because we are subscribed on NotifyChannel + } + else + { + foreach (var x in Data) + { + Handle(x.Key, x.Value); + } + foreach (var x in RegisterQueue) + { + SetValue(x.Key, x.Value, crashOnDuplicate: true); + } + } + } + + + private static void ConnectionPortHandler(object data) + { + Log("ConnectionPortHandler"); + if (data == null) //Request data + { + if (IsMain && Data != null) + { + Log("Request data !" + TAG); + MyAPIGateway.Utilities.SendModMessage(PORT1, Data); + } + else + { + Log("Request data Error ! " + TAG + " [" + data+"]"); + //Ignore we are not Main, or not inited yet. + } + } + else + { + var fn = data as Dictionary; + if (fn != null) + { + Log ("Arrived data! "+ TAG); + Data = fn; + } + else + { + Log("Error1 ! " + TAG); + //possible trash; + } + } + } + + public static void Log (string data) + { + if (DEBUGLOG) + { + MyLog.Default.Error($"MCon {TAG}: {data}"); + } + } + + public static void LogError (string data) + { + if (DEBUGLOG) + { + MyLog.Default.Error($"MCon {TAG}: {data}"); + } + } + + private static void NotifyChannelHandler(object data) + { + var pair = data as KeyValuePair?; + if (!pair.HasValue) + { + Log("Something wrong"); + return; + } + var d = pair.Value; + + if (!Data.ContainsKey(d.Key)) + { + Log($"Desynchronization [{d.Key}]/[{d.Value}] -> [{d.Key}]/[null]"); + } + else + { + if (Data[d.Key] != d.Value) + { + Log($"Desynchronization [{d.Key}]/[{d.Value}] -> [{d.Key}]/[{Data[d.Key]}]"); + } + } + + Log($"Registered [{d.Key}]->[{d.Value}]"); + Handle(d.Key, d.Value); + } + + private static string ALL = ""; + private static void Handle(string Name, object O) + { + Log("Handle: " + Name); + if (Name != ALL) + { + if (Subscriptions.ContainsKey(Name)) + { + foreach (var x in Subscriptions[Name]) + { + try + { + x(Name, O); + } + catch (Exception e) + { + Log($"ModConnection: Exception for [{Name}] : {e.ToString()}"); + } + } + } + } + + if (Subscriptions.ContainsKey(ALL)) + { + foreach (var x in Subscriptions[ALL]) + { + try + { + x(Name, O); + } + catch (Exception e) + { + Log($"ModConnection: Exception for [{Name}] : {e.ToString()}"); + } + } + } + } + + + + + + public static void SetValue(string Name, object Data, bool crashOnDuplicate = false, bool notify = true) + { + if (ModConnection.Data == null) + { + RegisterQueue.Add(new KeyValuePair(Name, Data)); + } + else + { + if (crashOnDuplicate && ModConnection.Data.ContainsKey(Name)) + { + PrintAllData(); + throw new Exception($"Key already exists {Name} : [{ModConnection.Data[Name]}"); + } + + ModConnection.Data[Name] = Data; + if (notify) MyAPIGateway.Utilities.SendModMessage(PORT2, new KeyValuePair(Name, Data)); + } + } + + public static T Get(string Name) + { + object o; + if (Data.TryGetValue(Name, out o)) + { + if (o is T) + { + return (T)o; + } + } + + return default(T); + } + + public static void Subscribe(string Name, Action OnDataArrivedOrChanged) + { + Action catched = (a, b) => + { + try + { + OnDataArrivedOrChanged(a, b); + } + catch (Exception e) + { + Log($"{Name}:" + e.ToString()); + } + }; + + Subscriptions.GetOrNew(Name).Add(catched); + if (Data.ContainsKey(Name)) + { + try + { + catched(Name, Data[Name]); + } + catch (Exception e) + { + LogError($"ModConnection:OnDataArrivedOrChanged {Name} {Data[Name]} error: {e}"); + } + + } + } + + public static void Subscribe(string Name, Action OnDataArrivedOrChanged) + { + Subscribe(Name, (name, data) => OnDataArrivedOrChanged((T) data)); + } + + public static void Subscribe(string Name, T intance, Action OnDataArrivedOrChanged) + { + Subscribe(Name, (name, data) => OnDataArrivedOrChanged((T) data)); + } + + public static void SetValueAndSubscribe(string Name, T Data, Action OnDataArrivedOrChanged, bool crashOnDuplicate = true) + { + SetValue(Name, Data, crashOnDuplicate); + Subscribe(Name, OnDataArrivedOrChanged); + } + + public static void SubscribeToAll(Action OnDataArrivedOrChanged) + { + Subscribe(ALL, OnDataArrivedOrChanged); + } + + public static void PrintAllData() + { + var sb = new StringBuilder("ModConnection:\n"); + foreach (var x in Data) + { + sb.AppendLine($"{x.Key} -> {x.Value}"); + } + + Log(sb.ToString()); + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs new file mode 100644 index 00000000..33c12d13 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/SharpUtils.cs @@ -0,0 +1,719 @@ +using Sandbox.ModAPI; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Text; +using Digi; +using VRage; +using VRage.Game; +using VRage.Game.ModAPI; +using VRage.ObjectBuilders; +using VRageMath; +using Sandbox.Game.EntityComponents; + +namespace ServerMod { + + static class ToStr + { + public static string printContent(this List dict) { + StringBuilder sb = new StringBuilder(); + sb.Append("List["); + foreach (var x in dict) { + sb.Append(x).Append(",\n"); + } + sb.Append("]"); + return sb.ToString(); + } + + public static string printContent(this List dict) { + StringBuilder sb = new StringBuilder(); + sb.Append("List["); + foreach (var x in dict) { + sb.Append(x.DisplayName + "/" + x.PlayerID).Append(", "); + } + sb.Append("]"); + return sb.ToString(); + } + + public static string printContent(this List dict) { + StringBuilder sb = new StringBuilder(); + sb.Append("List["); + foreach (var x in dict) { + sb.Append(x.Name + "/" +x.FactionId).Append(", "); + } + sb.Append("]"); + return sb.ToString(); + } + + + public static string printContent(this List dict) { + StringBuilder sb = new StringBuilder(); + sb.Append("List["); + foreach (var x in dict) { + sb.Append("{").Append(x.ItemId).Append("/").Append(x.Amount).Append("/").Append(x.Blueprint).Append("},\n"); + } + sb.Append("]"); + return sb.ToString(); + } + + public static Dictionary Copy(this Dictionary dict) + { + return new Dictionary(dict); + } + } + + static class SharpUtils { + + + public static DateTime utcZero = new DateTime(1970, 1, 1); + public static DateTime y2020 = new DateTime(2020, 1, 1); + + public static float Lerp2 (float Current, float Desired, float Speed) + { + if (Current < Desired) + { + Current += Speed; + if (Current > Desired) + { + Current = Desired; + } + } + else + { + Current -= Speed; + if (Current < Desired) + { + Current = Desired; + } + } + return Current; + } + + public static float toRadian (this float v) + { + return (float)(v * Math.PI / 180d); + } + + public static double toRadian(this double v) + { + return (v * Math.PI / 180d); + } + + public static float toDegree (this float v) + { + return (float)(v / Math.PI * 180d); + } + + public static double toDegree (this double v) + { + return (v / Math.PI * 180d); + } + + public static int DayOfWeek (DateTime time) //Saturday = 6, Sunday = 7 + { + var utcZero = new DateTime(1970, 1, 1); + if (time < utcZero) return 1; + var d = (y2020 - utcZero).TotalDays; + var dd = (int)d + d%1>0 ? 1 : 0; + dd = dd- (dd / 7)*7 + 4; //1970 was Thursday + if (dd > 7) dd -=7; + return dd; + } + + + public static double Degree (Vector3D v1, Vector3D v2) + { + return Math.Acos(v1.Dot(v2) / (v1.Length() * v2.Length())).toDegree(); + } + + public static double Degree2 (Vector3D v1, Vector3D v2) + { + var d = Degree(v1, v2); + + if ((v1+v2).LengthSquared () < (v1 - v2).LengthSquared()) + { + d*=-1; + } + return d; + } + + public static long timeStamp () { + return (long)(DateTime.UtcNow.Subtract(utcZero)).TotalSeconds; + } + + public static long timeUtcDif() + { + return Math.Abs((long)DateTime.UtcNow.Subtract(DateTime.Now).TotalSeconds); + } + + public static bool HasFlags(this int x, int f) + { + return (x | f) == x; + } + + public static long msTimeStamp () { + return (long)(DateTime.UtcNow.Subtract(utcZero)).TotalMilliseconds; + } + + public static TimeSpan StripMilliseconds(this TimeSpan time) + { + return new TimeSpan(time.Days, time.Hours, time.Minutes, time.Seconds); + } + + + public static void AddOrRemove(this HashSet set, T data, bool add) { + if (add) { set.Add(data); } else { set.Remove(data); } + } + + public static void RemoveWhere(this Dictionary set, Func filter) + { + var list = new List(); + foreach (var t in set) + { + if (filter(t.Key, t.Value)) + { + list.Add(t.Key); + } + } + + foreach (var t in list) + { + set.Remove(t); + } + } + + public static string Print(this Dictionary dict, string separator = "\n", Func Where = null) { + StringBuilder sb = new StringBuilder(); + sb.Append("Dict["); + foreach (var x in dict) { + if (Where != null && !Where.Invoke(x.Key, x.Value)) continue; + sb.Append(x.Key).Append("->").Append(x.Value).Append(separator); + } + sb.Append("]"); + return sb.ToString(); + } + + public static string Print(this List list) + { + StringBuilder sb = new StringBuilder(); + sb.Append("List["); + foreach (var x in list) + { + sb.Append(x).Append(" "); + } + sb.Append("]"); + return sb.ToString(); + } + + private static Dictionary alliases = new Dictionary() { + { MyObjectBuilderType.Parse("MyObjectBuilder_Ingot"), "i/" }, + { MyObjectBuilderType.Parse("MyObjectBuilder_Ore"), "o/" }, + { MyObjectBuilderType.Parse("MyObjectBuilder_Component"), "" } + }; + + + public static string toHumanWeight (this double num) { + if (num <0.000001) return String.Format ("{0:N2} µg", num *1000000000); + if (num <0.001) return String.Format ("{0:N2} mg", num *1000000); + if (num <1) return String.Format ("{0:N2} g", num *1000); + if (num <1000) return String.Format ("{0:N2} kg", num); + if (num <1000000) return String.Format ("{0:N2} t", num /1000); + if (num <1000000000) return String.Format ("{0:N2} kt", num /1000000); + if (num <1000000000000) return String.Format ("{0:N2} Mt", num /1000000000); + if (num <1000000000000000) return String.Format ("{0:N2} Gt", num /1000000000000); + return "TONS"; + } + + + public static string toHumanWeight2 (this double num) + { + if (num <1000) return String.Format(CultureInfo.InvariantCulture, "{0:N0} Kg", num); + if (num <1000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} Ton", num / 1000).Replace(".0", ""); + if (num <1000000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} kTon", num /1000000).Replace(".0", ""); + if (num <1000000000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} MTon", num /1000000000).Replace(".0", ""); + if (num <1000000000000000) return String.Format (CultureInfo.InvariantCulture, "{0:N1} GTon", num /1000000000000).Replace(".0", ""); + return "TONS"; + } + + public static string toHumanQuantity (this double num) { + if (num <1000) return String.Format ("{0:N2}", num); + if (num <1000000) return String.Format ("{0:N2} K", num /1000); + if (num <1000000000) return String.Format ("{0:N2} M", num /1000000); + return "TONS"; + } + + public static string toPhysicQuantity (this double num, String s) { + var k = 1000d; + if (num 1000) return $"{num / 1000 :N0} GW"; + if (Math.Abs(num) > 1) return $"{num :N2} MW"; + if (Math.Abs(num) > 0.001) return $"{num * 1000 :N0} KW"; + return $"{num * 1000000 :N0} W"; + } + + public static string toHumanQuantityVolume (this double num) + { + if (Math.Abs(num) > 1000000000) return $"{num / 1000000000 :N2} GL"; + if (Math.Abs(num) > 1000000) return $"{num / 1000000 :N2} ML"; + if (Math.Abs(num) > 1000) return $"{num / 1000 :N2} kL"; + if (Math.Abs(num) > 100) return $"{num / 100 :N2} hL"; + if (Math.Abs(num) > 10) return $"{num / 10 :N2} daL"; + if (Math.Abs(num) > 1) return $"{num :N2} L"; + if (Math.Abs(num) > 0.1) return $"{num * 10 :N2} dL"; + if (Math.Abs(num) > 0.01) return $"{num * 100 :N2} cL"; + return $"{num * 1000 :N2} mL"; + } + + public static string toPercentage (this double num) { + return String.Format ("{0:N2}%", num*100); + } + + public static string toMlt (this double num) { + return String.Format ("{0:N2}", num); + } + + public static string toHumanTime (this double num) { + if (num <120) return String.Format ("{0:N0} s", num); + if (num <3600) return String.Format ("{0:N0} min", num /60); + if (num <3600*24) return String.Format ("{0:N0} h", num /3600); + return String.Format ("{0:N0} days", num/3600/24); + } + public static string toHumanTime2 (this int num, bool isFullWithDays = false) { + if (num < 60) return num + "s"; + if (num < 3600) return num / 60 + "m " + num % 60 + "s"; + if (num < 3600 * 24) return num / 3600 + "h " + (num / 60) % 60 + "m " + num % 60 + "s"; + if (num / 3600 / 24 == 1) return isFullWithDays ? "1 day " + num / 3600 + "h " + (num / 60) % 60 + "m " + num % 60 + "s" : "1 day"; + return isFullWithDays ? num / 3600 / 24 + " days " + num / 3600 % 24 + "h " + (num / 60) % 60 + "m " + num % 60 + "s" : num / 3600 / 24 + " days"; + } + + public static string fixZero (this double num) { + return String.Format ("{0:N2}", num); + } + + public static string fixZero(this float num) + { + return String.Format("{0:N2}", num); + } + + public static string toHumanString (this MyDefinitionId id) { + if (alliases.ContainsKey (id.TypeId)) { + return alliases[id.TypeId] +id.SubtypeName; + } else { + return id.TypeId.ToString().Substring (16) + "/"+id.SubtypeName; + } + } + + public static void Add(this IDictionary dict1, KeyValuePair kv) + { + dict1.Add(kv.Key, kv.Value); + } + + public static bool Remove(this IDictionary dict1, K key, V value) + { + if (dict1.ContainsKeyValue(key, value)) + { + dict1.Remove(key); + return true; + } + + return false; + } + + public static bool ContainsKeyValue(this IDictionary dict1, K key, V value) + { + V value2; + if (dict1.TryGetValue(key, out value2)) + { + return value.Equals(value2); + } + + return false; + } + + public static bool ContainsKeyValue(this IDictionary dict1, KeyValuePair kv) + { + return ContainsKeyValue(dict1, kv.Key, kv.Value); + } + + public static Dictionary SumDuplicates(this ICollection values) + { + var dict = new Dictionary(); + foreach (var u in values) + { + dict.Sum(u, 1); + } + + return dict; + } + + public static void RemoveDuplicates(this IDictionary dict1, IDictionary dict2) + { + foreach (var kv in dict2) + { + dict1.Remove(kv.Key, kv.Value); + } + } + + public static D GetDuplicates(this IDictionary dict1, IDictionary dict2) where D : Dictionary, new() + { + var dict3 = new D(); + foreach (var kv in dict1) + { + if (dict2.ContainsKeyValue(kv)) + { + dict3.Add(kv); + } + } + + return dict3; + } + + public static void RemoveDuplicatesBoth(this Dictionary dict1, Dictionary dict2) + { + var list = new List(); + foreach (var kv in dict2) + { + if (dict1.Remove(kv.Key, kv.Value)) + { + list.Add(kv.Key); + } + } + + foreach (var k in list) + { + dict2.Remove(k); + } + } + + public static string Print (this Dictionary dict, Func printer, string separator = "\r\n") + { + var s = new StringBuilder(); + int c = 0; + foreach (var kv in dict) + { + s.Append(printer (kv.Key, kv.Value)); + if (c != dict.Count-1) + { + s.Append(separator); + } + } + + return s.ToString(); + } + + public static float CurrentPowerInput(this IMyCubeBlock block) => block?.ResourceSink?.CurrentInputByType(MyResourceDistributorComponent.ElectricityId) ?? 0; + public static float MinRequiredPowerInput(this IMyCubeBlock block) => block?.ResourceSink?.RequiredInputByType(MyResourceDistributorComponent.ElectricityId) ?? 0; + public static float MaxRequiredPowerInput(this IMyCubeBlock block) => block?.ResourceSink?.MaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId) ?? 0; + + public static bool IsOneKeyMoreThan (this IDictionary buffer, IDictionary maxLimits) + { + foreach (var y in buffer) + { + if (y.Value > maxLimits[y.Key]) + { + return true; + } + } + return false; + } + + public static T ElementAtOrLast(this T[] array, int at) + { + var min = Math.Min(at, array.Length-1); + return array[min]; + } + + public static T ElementAtOrLast(this IList array, int at) + { + var min = Math.Min(at, array.Count-1); + return array[min]; + } + + + public static Action TryCatch(this Action func, string debugName) + { + return (a) => + { + try + { + func.Invoke(a); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + } + }; + } + + public static Action TryCatch(this Action func, string debugName) + { + return (a,b) => + { + try + { + func.Invoke(a,b); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + } + }; + } + + public static Action TryCatch(this Action func, string debugName) + { + return (a,b,c) => + { + try + { + func.Invoke(a,b,c); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + } + }; + } + + public static Action TryCatch(this Action func, string debugName) + { + return (a,b,c,d) => + { + try + { + func.Invoke(a,b,c,d); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + } + }; + } + + public static Func TryCatch(this Func func, string debugName) + { + return (a) => + { + try + { + return func.Invoke(a); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + return default(R); + } + }; + } + + + public static Func TryCatch(this Func func, string debugName) + { + return (a,b) => + { + try + { + return func.Invoke(a,b); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + return default(R); + } + }; + } + + public static Func TryCatch(this Func func, string debugName) + { + return (a,b,c) => + { + try + { + return func.Invoke(a,b,c); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + return default(R); + } + }; + } + + public static Func TryCatch(this Func func, string debugName) + { + return (a,b,c,d) => + { + try + { + return func.Invoke(a,b,c,d); + } + catch (Exception e) + { + Log.ChatError(debugName, e); + return default(R); + } + }; + } + + public static bool IsOneKeyMoreThan (this IDictionary buffer, IDictionary maxLimits) + { + foreach (var y in buffer) + { + try + { + if (y.Value > maxLimits[y.Key]) + { + return true; + } + } + catch (Exception e) + { + Log.ChatError($"IsOneKeyMoreThan: {y.Key}"); + } + + } + return false; + } + + + public static void Sum (this IDictionary dict, T key, double value) { + if (!dict.ContainsKey(key)) { + dict[key] = value; + } else { + dict[key] = dict[key] + value; + } + } + + public static void Sum (this IDictionary dict, T key, float value) { + if (!dict.ContainsKey(key)) { + dict[key] = value; + } else { + dict[key] = dict[key] + value; + } + } + + public static void Mlt (this IDictionary dict, T key, float value) { + if (!dict.ContainsKey(key)) { + dict[key] = value; + } else { + dict[key] = dict[key] * value; + } + } + + public static void Sum (this IDictionary dict, T key, MyFixedPoint value) { + if (!dict.ContainsKey(key)) { + dict[key] = value; + } else { + dict[key] = dict[key] + value; + } + } + + public static void Sum (this IDictionary dict, T key, int value) { + if (!dict.ContainsKey(key)) { + dict[key] = value; + } else { + dict[key] = dict[key] + value; + } + } + + public static void Sum (this IDictionary dict, IDictionary dict2) { + foreach (var d in dict2) + { + dict.Sum(d.Key, d.Value); + } + } + + + + public static StringBuilder Append(this StringBuilder sb, IMyPlayer player, IMyFaction faction) { + sb.Append (player.DisplayName); + if (faction != null) { + sb.Append("[").Append(faction.Tag).Append("]"); + } + + return sb; + } + + public static StringBuilder Append(this StringBuilder sb, IMyIdentity player, IMyFaction faction) { + sb.Append (player.DisplayName); + if (faction != null) { + sb.Append("[").Append(faction.Tag).Append("]"); + } + + return sb; + } + + + + + public static K GetOr(this IDictionary dict, T t, K k) { + if (dict.ContainsKey(t)) { + return dict[t]; + } else { + return k; + } + } + + public static K GetOrNew(this IDictionary dict, T t) where K : new() { + if (!dict.ContainsKey(t)) + { + var k = new K(); + dict[t] = k; + return dict[t]; + } + else + { + return dict[t]; + } + } + + public static List GetOrCreate(this IDictionary> dict, T t) { + if (!dict.ContainsKey(t)) { + dict.Add (t, new List()); + } + return dict[t]; + } + + public static HashSet GetOrCreate(this IDictionary> dict, T t) { + if (!dict.ContainsKey(t)) { + dict.Add (t, new HashSet()); + } + return dict[t]; + } + + public static Dictionary GetOrCreate(this IDictionary> dict, T t) { + if (!dict.ContainsKey(t)) { + dict.Add (t, new Dictionary()); + } + return dict[t]; + } + + public static K Set(this Dictionary dict, T t, K k) { + K old = default(K); + if (dict.ContainsKey(t)) { + old = dict[t]; + dict.Remove(t); + } + dict.Add(t, k); + return old; + } + } +} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs new file mode 100644 index 00000000..ba52bc39 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Shared/Timer.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MIG.Shared.CSharp { + public class Timer { + protected int time; + + public Timer(int time = 0) { + this.time = time; + } + + public virtual bool tick() { + time--; + return time < 0; + } + + public bool needAction() { + return time < 0; + } + + public int getTime () { + return time; + } + + public void addTime(int time) { + if (this.time < 0) { + this.time = 0; + } + + this.time += time; + } + + public void setTime (int time) { + this.time = time; + } + } + + public class AutoTimer : Timer { + int interval; + + public void setInterval (int interval) { + this.interval = interval; + } + public AutoTimer (int interval, int time = 0) : base(time) { + this.interval = interval; + } + + public int getInterval () { + return interval; + } + + public void setInterval (int interval, int time) { + this.interval = interval; + this.time = time; + } + + public void reset () { + time = interval; + } + + public override bool tick() { + if (base.tick()) { + addTime(interval); + return true; + } else { + return false; + } + } + + public void addTime () { + addTime(interval); + } + + public override string ToString() { return "AutoTimer ["+time + " / " +interval+"]"; } + } +} diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt new file mode 100644 index 00000000..100e2c29 --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/AirFrictionAPI.txt @@ -0,0 +1,44 @@ +using System; +using MIG.Shared.SE; +using Scripts.Specials.ShipClass; +using VRage.Game.Components; +using VRage.Game.ModAPI; + +namespace Scripts.Specials +{ + [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] + public class SpecCoreSession : MySessionComponentBase + { + public override void LoadData() + { + AirFrictionAPI.Init(); + } + } + + public class AirFrictionAPI + { + private static Func getGridFriction; + + public static int MinSpeed = 0; + public static int MaxSpeed = 1; + public static int CurrentSpeed = 2; + public static int AppliedForce = 3; + + public static void Init() + { + if (!ModConnection.IsInited) + { + ModConnection.Init(); + } + ModConnection.Subscribe>("MIG.AirFriction.GetGridFriction", (x) => + { + getGridFriction = x; + }); + } + + public static double[] GetGridFriction(IMyCubeGrid grid) + { + return getGridFriction?.Invoke(grid); + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs new file mode 100644 index 00000000..0f5ae60b --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/Examples/UpgradeLogic.cs @@ -0,0 +1,431 @@ +using System.Collections.Generic; +using Sandbox.Game.Entities; +using Sandbox.ModAPI; +using Scripts.Specials.ShipClass; +using VRage.Game.Components; +using VRage.Game.ModAPI; +using VRageMath; +using VRage.Utils; +using Sandbox.Game.Entities.Cube; +using System.Runtime.CompilerServices; +using static VRage.Game.ObjectBuilders.Definitions.MyObjectBuilder_GameDefinition; +using ProtoBuf; +using Sandbox.Engine.Utils; +using VRage; +using static VRage.Game.MyObjectBuilder_BehaviorTreeDecoratorNode; + +namespace ServerMod +{ + [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] + public class UpgradeThrusters : MySessionComponentBase + { + private static bool isServer; + private static bool allowOnLimitedBlockCreated; + private static List limitedBlocksToProcess = new List(); + + public override void LoadData() + { + isServer = MyAPIGateway.Session.IsServer; + } + + public override void BeforeStart() + { + //MyAPIGateway.Multiplayer.RegisterMessageHandler(5561, MessageHandler); + } + + static UpgradeThrusters() + { + SpecBlockHooks.OnReady += HooksOnOnReady; + } + + private static void HooksOnOnReady() + { + if (isServer) + SpecBlockHooks.OnSpecBlockChanged += OnSpecBlockChanged; + + SpecBlockHooks.OnLimitedBlockCreated += OnLimitedBlockCreated; + SpecBlockHooks.OnSpecBlockDestroyed += OnSpecBlockDestroyed; + } + + //This takes effect works after the grid is cut/pasted or spec block is deleted + private static void OnSpecBlockChanged(object specBlock, List grids) + { + if (isServer) + { + allowOnLimitedBlockCreated = true; + OnLimitedBlockCreated(null); + SpecBlockHooks.OnSpecBlockChanged -= OnSpecBlockChanged; + + //RunUpgrades(specBlock, grids); + } + /*else + { + MyAPIGateway.Parallel.StartBackground(() => + { + MyLog.Default.WriteLineAndConsole($"Running Code on Client"); + MyAPIGateway.Parallel.Sleep(5000); + RunUpgrades(specBlock, grids); + }); + }*/ + } + + private static void RunUpgrades(object specBlock, List grids, bool reset = false) + { + foreach (var grid in grids) + { + + //npc checking stuff borrowed from Digi + if (grid.BigOwners == null || grid.BigOwners.Count == 0) + continue; + + long owner = grid.BigOwners[0]; // only check the first one, too edge case to check others + var faction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(owner); + + if (faction != null && faction.IsEveryoneNpc()) + continue; + + List blocks = new List(); + //var core = SpecBlockHooks.GetMainSpecCore(grid); + var stats = new Dictionary(); + List upgrades = new List(); + SpecBlockHooks.GetSpecCoreLimits(specBlock, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); + grid.GetBlocks(blocks, x => x.FatBlock is IMyTerminalBlock); + + foreach (var block in blocks) + { + var thrustBlock = block.FatBlock as IMyThrust; + var reactorBlock = block.FatBlock as IMyReactor; + var generatorBlock = block.FatBlock as IMyGasGenerator; + var drillBlock = block.FatBlock as IMyShipDrill; + var gyroBlock = block.FatBlock as IMyGyro; + + if (thrustBlock != null) + { + if (stats.ContainsKey(46) && stats[46] != 0 && !reset) + { + thrustBlock.ThrustMultiplier = stats[46]; + } + else + { + thrustBlock.ThrustMultiplier = 1.0f; + } + //Log.ChatError($"SetMultiplier to: {thrustBlock.ThrustMultiplier}"); + if (stats.ContainsKey(46) && stats[46] != 0 && !reset) + { + thrustBlock.PowerConsumptionMultiplier = 1 / stats[46]; + } + else + { + thrustBlock.PowerConsumptionMultiplier = 1.0f; + } + //Log.ChatError($"SetMultiplier to: {thrustBlock.PowerConsumptionMultiplier}"); + } + + + if (reactorBlock != null) + { + if (stats.ContainsKey(28) && stats[28] != 0 && !reset) + { + reactorBlock.PowerOutputMultiplier = stats[28]; + } + else + { + reactorBlock.PowerOutputMultiplier = 1.0f; + } + //Log.ChatError($"SetMultiplier to: {reactorBlock.PowerOutputMultiplier}"); + } + + if (gyroBlock != null) + { + if (stats.ContainsKey(28) && stats[28] != 0 && !reset) + { + gyroBlock.PowerConsumptionMultiplier = 1 / MathHelper.Max(1, stats[28]); + //gyroBlock.GyroStrengthMultiplier = stats[28]; + } + else + { + gyroBlock.PowerConsumptionMultiplier = 1.0f; + //gyroBlock.GyroStrengthMultiplier = 1.0f; + } + //Log.ChatError($"SetMultiplier to: {gyroBlock.PowerConsumptionMultiplier}"); + } + + + if (generatorBlock != null) + { + if (stats.ContainsKey(29) && stats[29] != 0 && !reset) + { + //This is the rate of ice consumption, NOT the rate of O2/H2 output + generatorBlock.ProductionCapacityMultiplier = stats[29]; + generatorBlock.PowerConsumptionMultiplier = stats[29] / MathHelper.Max(1, stats[28]); + } + else + { + //This is the rate of ice consumption, NOT the rate of O2/H2 output + generatorBlock.ProductionCapacityMultiplier = 1.0f; + generatorBlock.PowerConsumptionMultiplier = 1.0f; + } + //Log.ChatError($"SetMultiplier to: {generatorBlock.ProductionCapacityMultiplier}"); + } + + if (drillBlock != null) + { + if (stats.ContainsKey(27) && stats[27] != 0 && !reset) + { + drillBlock.DrillHarvestMultiplier = stats[27]; + drillBlock.PowerConsumptionMultiplier = 1 / stats[27]; + } + else + { + drillBlock.DrillHarvestMultiplier = 1.0f; + drillBlock.PowerConsumptionMultiplier = 1.0f; + } + //Log.ChatError($"SetMultiplier to: {drillBlock.DrillHarvestMultiplier}"); + } + } + } + } + + private static void UpgradeBlock(object limitedBlock) + { + var tBlock = SpecBlockHooks.GetLimitedBlockBlock(limitedBlock); + if (tBlock == null) + return; + + var grid = tBlock.CubeGrid; + if (grid == null) + return; + + //npc checking stuff borrowed from Digi + if (grid.BigOwners == null || grid.BigOwners.Count == 0) + return; + + long owner = grid.BigOwners[0]; // only check the first one, too edge case to check others + var faction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(owner); + + if (faction != null && faction.IsEveryoneNpc()) + return; + + var thrustBlock = tBlock as IMyThrust; + var reactorBlock = tBlock as IMyReactor; + var generatorBlock = tBlock as IMyGasGenerator; + var drillBlock = tBlock as IMyShipDrill; + var gyroBlock = tBlock as IMyGyro; + + var core = SpecBlockHooks.GetMainSpecCore(grid); + var stats = new Dictionary(); + SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); + + if (thrustBlock != null) + { + if (stats != null && stats.ContainsKey(46) && stats[46] != 0) + { + thrustBlock.ThrustMultiplier = stats[46]; + thrustBlock.PowerConsumptionMultiplier = 1 / stats[46]; + } + else + { + thrustBlock.ThrustMultiplier = 1.0f; + thrustBlock.PowerConsumptionMultiplier = 1.0f; + } + } + + if (reactorBlock != null) + { + if (stats != null && stats.ContainsKey(28) && stats[28] != 0) + { + reactorBlock.PowerOutputMultiplier = stats[28]; + } + else + { + reactorBlock.PowerOutputMultiplier = 1.0f; + } + } + + if (gyroBlock != null) + { + if (stats != null && stats.ContainsKey(28) && stats[28] != 0) + { + gyroBlock.PowerConsumptionMultiplier = 1 / MathHelper.Max(1, stats[28]); + } + else + { + gyroBlock.PowerConsumptionMultiplier = 1.0f; + } + } + + if (generatorBlock != null) + { + if (stats != null && stats.ContainsKey(29) && stats[29] != 0) + { + generatorBlock.ProductionCapacityMultiplier = stats[29]; + generatorBlock.PowerConsumptionMultiplier = stats[29] / MathHelper.Max(1, stats[28]); + } + else + { + generatorBlock.ProductionCapacityMultiplier = 1.0f; + generatorBlock.PowerConsumptionMultiplier = 1.0f; + } + } + + if (drillBlock != null) + { + if (stats != null && stats.ContainsKey(27) && stats[27] != 0) + { + drillBlock.DrillHarvestMultiplier = stats[27]; + drillBlock.PowerConsumptionMultiplier = 1 / stats[27]; + } + else + { + drillBlock.DrillHarvestMultiplier = 1.0f; + drillBlock.PowerConsumptionMultiplier = 1.0f; + } + } + } + //This doesnt seem to work when expected, not sure why, is this even needed? + private static void OnLimitedBlockCreated(object limitedBlock) + { + /*MyAPIGateway.Parallel.StartBackground(() => + { + MyAPIGateway.Parallel.Sleep(5000); + if (!isServer) + { + MyAPIGateway.Utilities.InvokeOnGameThread(() => + { + var tBlock = SpecBlockHooks.GetLimitedBlockBlock(limitedBlock); + if (tBlock == null) + { + MyLog.Default.WriteLineAndConsole($"Limited Block is null!!"); + return; + } + + RequestBlockUpgrade(MyAPIGateway.Multiplayer.MyId); + }); + } + });*/ + + if (!allowOnLimitedBlockCreated && isServer) + { + limitedBlocksToProcess.Add(limitedBlock); + return; + } + + if (isServer) + { + foreach (var block in limitedBlocksToProcess) + UpgradeBlock(block); + + if (limitedBlock == null) + { + limitedBlocksToProcess.Clear(); + return; + } + } + + MyAPIGateway.Parallel.StartBackground(() => + { + MyAPIGateway.Parallel.Sleep(5000); + MyAPIGateway.Utilities.InvokeOnGameThread(() => { UpgradeBlock(limitedBlock); }); + + }); + } + + // Commented out because it breaks mysteriously + private static void OnSpecBlockDestroyed(object specBlock) + { + //var tBlock = SpecBlockHooks.GetBlockSpecCore(specBlock); + //if (tBlock == null) + // return; + // + //IMyCubeGrid grid = tBlock.CubeGrid; + //List grids = new List(); + //MyAPIGateway.GridGroups.GetGroup(grid, GridLinkTypeEnum.Mechanical, grids); + //RunUpgrades(specBlock, grids, true); + } + + /*public static void MessageHandler(byte[] data) + { + try + { + var package = MyAPIGateway.Utilities.SerializeFromBinary(data); + if (package == null) return; + + if (package.Type == DataType.RequestSettings) + { + var packet = MyAPIGateway.Utilities.SerializeFromBinary(package.Data); + if (packet == null) return; + + + return; + } + + if (package.Type == DataType.SendSettings) + { + var packet = MyAPIGateway.Utilities.SerializeFromBinary(package.Data); + if (packet == null) return; + + return; + } + } + catch { }; + } + + public static void RequestBlockUpgrade(ulong steamId) + { + ObjectContainer objectContainer = new ObjectContainer() + { + steamId = steamId + }; + + CommsPackage package = new CommsPackage(DataType.RequestBlockUpgrade, objectContainer); + var sendData = MyAPIGateway.Utilities.SerializeToBinary(package); + MyAPIGateway.Multiplayer.SendMessageToServer(5561, sendData); + } + + public enum DataType + { + + RequestBlockUpgrade, + SendBlockUpgrade, + } + + [ProtoContract] + public class ObjectContainer + { + [ProtoMember(1)] public ulong steamId; + [ProtoMember(2)] public long blockId; + [ProtoMember(3)] public float upgradeValue; + + + + } + + [ProtoContract] + public class CommsPackage + { + [ProtoMember(1)] + public DataType Type; + + [ProtoMember(2)] + public byte[] Data; + + public CommsPackage() + { + Type = DataType.RequestBlockUpgrade; + Data = new byte[0]; + } + + public CommsPackage(DataType type, ObjectContainer oc) + { + Type = type; + Data = MyAPIGateway.Utilities.SerializeToBinary(oc); + } + }*/ + + protected override void UnloadData() + { + //MyAPIGateway.Multiplayer.UnregisterMessageHandler(5561, MessageHandler); + + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs new file mode 100644 index 00000000..87cff80d --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks.cs @@ -0,0 +1,329 @@ +using System; +using System.Collections.Generic; +using MIG.Shared.SE; +using Sandbox.ModAPI; +using VRage.Game; +using VRage.Utils; +using VRage.Game.ModAPI; +using F = System.Func; +using FF = System.Func; +using A = System.Action; +using C = System.Func; +using U = System.Collections.Generic.List; +using L = System.Collections.Generic.IDictionary; + +namespace Scripts.Specials.ShipClass +{ + public class SpecBlockHooks + { + public interface ILimitedBlock + { + bool IsDrainingPoints(); + void Disable(); + void CanWork(); + bool CanBeDisabled(); + bool CheckConditions(IMyTerminalBlock specBlock); + } + + public enum GetSpecCoreLimitsEnum + { + StaticLimits = 1, + DynamicLimits = 2, + FoundLimits = 3, + TotalLimits = 4, + CustomStatic = 5, + CustomDynamic = 6, + CurrentStaticOrDynamic = 7 + } + + + private static Action RegisterCustomLimitConsumerImpl; + private static Func getMainSpecCore; + private static Func getMainSpecCoreBlock; + private static Action getSpecCoreLimits; + private static Action getSpecCoreUpgrades; + private static Action setSpecCoreCustomValues; + + private static Func getSpecCoreBlock; + private static Func getBlockSpecCore; + private static Func getLimitedBlock; + private static Func getLimitedBlockBlock; + + private static Func>> getGridBlocksByType; + private static Func>> getGridBlocksById; + + private static Action , float>> registerSpecCorePointCustomFx; + private static Action, Dictionary>> addSpecCoreLimitsInterceptor; + + public static event Action OnReady; + + public static event Action OnSpecBlockCreated; + public static event Action OnSpecBlockDestroyed; + public static event Action OnLimitedBlockCreated; + public static event Action OnLimitedBlockDestroyed; + + public static event Action> OnSpecBlockChanged; + + public static bool IsReady() + { + return + RegisterCustomLimitConsumerImpl != null && + getMainSpecCore != null && + getMainSpecCoreBlock != null && + getSpecCoreLimits != null && + getSpecCoreUpgrades != null && + setSpecCoreCustomValues != null && + + getSpecCoreBlock != null && + getBlockSpecCore != null && + getLimitedBlock != null && + getLimitedBlockBlock != null && + + getGridBlocksByType != null && + getGridBlocksById != null && + + + addSpecCoreLimitsInterceptor != null && + registerSpecCorePointCustomFx != null; + } + + private static void TriggerIsReady() + { + if (IsReady()) + { + OnReady?.Invoke(); + } + } + + /// + /// Must be inited in LoadData of MySessionComponentBase + /// + public static void Init() + { + ModConnection.Init(); + ModConnection.Subscribe("MIG.SpecCores.RegisterCustomLimitConsumer", RegisterCustomLimitConsumerImpl, (x) => { RegisterCustomLimitConsumerImpl = x; TriggerIsReady(); }); + + ModConnection.Subscribe("MIG.SpecCores.GetMainSpecCore", getMainSpecCore, (x) => { getMainSpecCore = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetMainSpecCoreBlock", getMainSpecCoreBlock, (x) => { getMainSpecCoreBlock = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetSpecCoreLimits", getSpecCoreLimits,(x) => { getSpecCoreLimits = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetSpecCoreUpgrades", getSpecCoreUpgrades, (x) => { getSpecCoreUpgrades = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.SetSpecCoreCustomValues", setSpecCoreCustomValues, (x) => { setSpecCoreCustomValues = x; TriggerIsReady(); }); + + ModConnection.Subscribe("MIG.SpecCores.GetGridBlocksByType", getGridBlocksByType, (x) => { getGridBlocksByType = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetGridBlocksById", getGridBlocksById, (x) => { getGridBlocksById = x; TriggerIsReady(); }); + + ModConnection.Subscribe("MIG.SpecCores.GetSpecCoreBlock", getSpecCoreBlock, (x) => { getSpecCoreBlock = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetBlockSpecCore", getBlockSpecCore, (x) => { getBlockSpecCore = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetLimitedBlock", getLimitedBlock, (x) => { getLimitedBlock = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.GetLimitedBlockBlock", getLimitedBlockBlock, (x) => { getLimitedBlockBlock = x; TriggerIsReady(); }); + + ModConnection.Subscribe("MIG.SpecCores.RegisterSpecCorePointCustomFx", registerSpecCorePointCustomFx, (x) => { registerSpecCorePointCustomFx = x; TriggerIsReady(); }); + ModConnection.Subscribe("MIG.SpecCores.AddSpecCoreLimitsInterceptor", addSpecCoreLimitsInterceptor, (x)=>{ addSpecCoreLimitsInterceptor = x; TriggerIsReady(); }); + + + + Action onSpecBlockCreated = (x) => OnSpecBlockCreated?.Invoke(x); + Action onSpecBlockDestroyed = (x) => OnSpecBlockDestroyed?.Invoke(x); + Action onLimitedBlockCreated = (x) => OnLimitedBlockCreated?.Invoke(x); + Action onLimitedBlockDestroyed = (x) => OnLimitedBlockDestroyed?.Invoke(x); + + Action> onSpecBlockChanged = (x,y) => OnSpecBlockChanged?.Invoke(x,y); + + ModConnection.SetValue("MIG.SpecCores.OnSpecBlockCreated", onSpecBlockCreated); + ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockCreated", OnLimitedBlockCreated); + ModConnection.SetValue("MIG.SpecCores.OnSpecBlockDestroyed", OnSpecBlockDestroyed); + ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockDestroyed", onLimitedBlockDestroyed); + + ModConnection.SetValue("MIG.SpecCores.OnSpecBlockChanged", onSpecBlockChanged); + + MyAPIGateway.Session.DamageSystem.RegisterBeforeDamageHandler(10, HandleDamage); + } + + public static void Close() + { + ModConnection.Close(); + } + + + public static void SetCanSpecCoreWorkFx(Func, string> fx) + { + ModConnection.SetValue("MIG.SpecCores.CanSpecCoreWork", fx); + } + + public static void RegisterSpecCorePointCustomFx(int pointId, Func, float> fx) + { + registerSpecCorePointCustomFx?.Invoke(pointId, fx); + } + + public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegistered, A CanWork, FF CheckConditions, F CanBeDisabled, F IsDrainingPoints, A Disable) + { + RegisterCustomLimitConsumerImpl(Id, OnNewConsumerRegistered, CanWork, CheckConditions, CanBeDisabled, IsDrainingPoints, Disable); + } + + public static object GetMainSpecCore(IMyCubeGrid grid) + { + return getMainSpecCore?.Invoke(grid); + } + + public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) + { + return getMainSpecCoreBlock?.Invoke(grid); + } + + public static void GetSpecCoreLimits(object specCore, IDictionary buffer, GetSpecCoreLimitsEnum limits) + { + getSpecCoreLimits?.Invoke(specCore, buffer, (int) limits); + } + + public static void GetSpecCoreUpgrades(object specCore, List buffer) + { + getSpecCoreUpgrades?.Invoke(specCore, buffer); + } + + public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) + { + setSpecCoreCustomValues?.Invoke(specCore, staticValues, dynamicValues); + } + + public static void AddSpecCoreLimitsInterceptor(Action, Dictionary> fx) + { + addSpecCoreLimitsInterceptor?.Invoke(fx); + } + + public static object GetSpecCoreBlock(IMyTerminalBlock block) + { + return getSpecCoreBlock?.Invoke(block); + } + + public static IMyTerminalBlock GetBlockSpecCore(object block) + { + return getBlockSpecCore?.Invoke(block); + } + + public static object GetLimitedBlock(IMyTerminalBlock block) + { + return getLimitedBlock?.Invoke(block); + } + + public static IMyTerminalBlock GetLimitedBlockBlock(object block) + { + if (getLimitedBlockBlock == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: getLimitedBlockBlock is null"); + return null; + } + + if (block == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: block is null"); + return null; + } + + try + { + var limitedBlock = block as ILimitedBlock; + if (limitedBlock == null) + { + MyLog.Default.WriteLine($"SpecBlockHooks: block of type {block.GetType().FullName} does not implement ILimitedBlock"); + return null; + } + + return getLimitedBlockBlock.Invoke(block); + } + catch (InvalidCastException) + { + MyLog.Default.WriteLine($"SpecBlockHooks: Failed to cast block of type {block.GetType().FullName} to ILimitedBlock"); + return null; + } + catch (Exception e) + { + MyLog.Default.WriteLine($"SpecBlockHooks: Error in GetLimitedBlockBlock: {e.Message}"); + return null; + } + } + + public static void RegisterCustomLimitConsumer(string Id, Func creator) + { + SpecBlockHooks.RegisterCustomLimitConsumer(Id, + creator, + (logic) => + { + var limitedBlock = logic as ILimitedBlock; + if (limitedBlock != null) limitedBlock.CanWork(); + }, + (block, logic) => + { + var limitedBlock = logic as ILimitedBlock; + return limitedBlock != null && limitedBlock.CheckConditions(block); + }, + (logic) => + { + var limitedBlock = logic as ILimitedBlock; + return limitedBlock != null && limitedBlock.CanBeDisabled(); + }, + (logic) => + { + var limitedBlock = logic as ILimitedBlock; + return limitedBlock != null && limitedBlock.IsDrainingPoints(); + }, + (logic) => + { + var limitedBlock = logic as ILimitedBlock; + if (limitedBlock != null) limitedBlock.Disable(); + }); + } + + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) + { + if (grid == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksByType"); + return null; + } + return getGridBlocksByType?.Invoke(grid) ?? null; + } + + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) + { + if (grid == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: grid is null in GetGridBlocksById"); + return null; + } + return getGridBlocksById?.Invoke(grid) ?? null; + } + + public static void HandleDamage(object target, ref MyDamageInformation damage) + { //Parallel + try + { + var slimBlock = target as IMySlimBlock; + if (slimBlock == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: target is not IMySlimBlock in HandleDamage"); + return; + } + + var cubeGrid = slimBlock.CubeGrid; + var core = SpecBlockHooks.GetMainSpecCore(cubeGrid); + if (core == null) + { + MyLog.Default.WriteLine("SpecBlockHooks: core is null in HandleDamage"); + return; + } + + var stats = new Dictionary(); + SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); + if (stats != null && stats.ContainsKey(-33) && stats[-33] != 0) + { + damage.Amount *= stats[-33]; + } + } + catch (Exception e) + { + MyLog.Default.WriteLine($"SpecBlockHooks: Error in HandleDamage: {e.Message}"); + } + } + + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt new file mode 100644 index 00000000..cdb44e1d --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecBlockHooks_A.txt @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using Digi; +using MIG.Shared.SE; +using Sandbox.ModAPI; +using ServerMod; +using VRage.Game; +using VRage.Game.ModAPI; +using F = System.Func; +using FF = System.Func; +using A = System.Action; +using C = System.Func; +using U = System.Collections.Generic.List; +using L = System.Collections.Generic.IDictionary; + +using VRageMath; +using VRage.Utils; +using Sandbox.Definitions; +using Sandbox.Game; +using Sandbox.Game.Entities; +using VRage.ObjectBuilders; + +namespace Scripts.Specials.ShipClass +{ + + public class SpecBlockHooks + { + public interface ILimitedBlock + { + bool IsDrainingPoints(); + void Disable(); + void CanWork(); + bool CanBeDisabled(); + bool CheckConditions(IMyTerminalBlock specBlock); + } + + public enum GetSpecCoreLimitsEnum + { + StaticLimits = 1, + DynamicLimits = 2, + FoundLimits = 3, + TotalLimits = 4, + CustomStatic = 5, + CustomDynamic = 6, + CurrentStaticOrDynamic = 7 + } + + + private static Action RegisterCustomLimitConsumerImpl; + private static Func getMainSpecCore; + private static Func getMainSpecCoreBlock; + private static Action getSpecCoreLimits; + private static Action getSpecCoreUpgrades; + private static Action setSpecCoreCustomValues; + + private static Func getSpecCoreBlock; + private static Func getBlockSpecCore; + private static Func getLimitedBlock; + private static Func getLimitedBlockBlock; + + private static Func>> getGridBlocksByType; + private static Func>> getGridBlocksById; + + private static Action , float>> registerSpecCorePointCustomFx; + + public static event Action OnReady; + + public static event Action OnSpecBlockCreated; + public static event Action OnSpecBlockDestroyed; + public static event Action OnLimitedBlockCreated; + public static event Action OnLimitedBlockDestroyed; + + public static event Action> OnSpecBlockChanged; + + public static bool IsReady() + { + return + RegisterCustomLimitConsumerImpl != null && + getMainSpecCore != null && + getMainSpecCoreBlock != null && + getSpecCoreLimits != null && + getSpecCoreUpgrades != null && + setSpecCoreCustomValues != null && + + getSpecCoreBlock != null && + getBlockSpecCore != null && + getLimitedBlock != null && + getLimitedBlockBlock != null && + + getGridBlocksByType != null && + getGridBlocksById != null; + } + + private static void TriggerIsReady() + { + if (IsReady()) + { + OnReady?.Invoke(); + } + } + + /// + /// Must be inited in LoadData of MySessionComponentBase + /// + public static void Init() + { + Log.ChatError("SpecBlockHooks:Init"); + ModConnection.Init(); + ModConnection.Subscribe>("MIG.SpecCores.RegisterCustomLimitConsumer", (x) => { RegisterCustomLimitConsumerImpl = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetMainSpecCore", (x) => { getMainSpecCore = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetMainSpecCoreBlock", (x) => { getMainSpecCoreBlock = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetSpecCoreLimits", (x) => { getSpecCoreLimits = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetSpecCoreUpgrades", (x) => { getSpecCoreUpgrades = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.SetSpecCoreCustomValues", (x) => { setSpecCoreCustomValues = x; TriggerIsReady(); }); + + ModConnection.Subscribe>>>("MIG.SpecCores.GetGridBlocksByType", (x) => { getGridBlocksByType = x; TriggerIsReady(); }); + ModConnection.Subscribe>>>("MIG.SpecCores.GetGridBlocksById", (x) => { getGridBlocksById = x; TriggerIsReady(); }); + + ModConnection.Subscribe>("MIG.SpecCores.GetSpecCoreBlock", (x) => { getSpecCoreBlock = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetBlockSpecCore", (x) => { getBlockSpecCore = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetLimitedBlock", (x) => { getLimitedBlock = x; TriggerIsReady(); }); + ModConnection.Subscribe>("MIG.SpecCores.GetLimitedBlockBlock", (x) => { getLimitedBlockBlock = x; TriggerIsReady(); }); + + ModConnection.Subscribe, float>>>("MIG.SpecCores.RegisterSpecCorePointCustomFx", (x) => { registerSpecCorePointCustomFx = x; TriggerIsReady(); }); + + Action onSpecBlockCreated = (x) => OnSpecBlockCreated?.Invoke(x); + Action onSpecBlockDestroyed = (x) => OnSpecBlockDestroyed?.Invoke(x); + Action onLimitedBlockCreated = (x) => OnLimitedBlockCreated?.Invoke(x); + Action onLimitedBlockDestroyed = (x) => OnLimitedBlockDestroyed?.Invoke(x); + + Action> onSpecBlockChanged = (x,y) => OnSpecBlockChanged?.Invoke(x,y); + + ModConnection.SetValue("MIG.SpecCores.OnSpecBlockCreated", onSpecBlockCreated); + ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockCreated", onSpecBlockDestroyed); + ModConnection.SetValue("MIG.SpecCores.OnSpecBlockDestroyed", onLimitedBlockCreated); + ModConnection.SetValue("MIG.SpecCores.OnLimitedBlockDestroyed", onLimitedBlockDestroyed); + + ModConnection.SetValue("MIG.SpecCores.OnSpecBlockChanged", onSpecBlockChanged); + + //MyAPIGateway.Session.DamageSystem.RegisterBeforeDamageHandler(10, HandleDamage); + } + + public static void Close() + { + ModConnection.Close(); + } + + public static void SetCanSpecCoreWorkFx(Func, string> fx) + { + ModConnection.SetValue("MIG.SpecCores.CanSpecCoreWork", fx); + } + + public static void RegisterSpecCorePointCustomFx(int pointId, Func, float> fx) + { + registerSpecCorePointCustomFx.Invoke(pointId, fx); + } + + public static void RegisterCustomLimitConsumer(string Id, C OnNewConsumerRegistered, A CanWork, FF CheckConditions, F CanBeDisabled, F IsDrainingPoints, A Disable) + { + RegisterCustomLimitConsumerImpl(Id, OnNewConsumerRegistered, CanWork, CheckConditions, CanBeDisabled, IsDrainingPoints, Disable); + } + + public static object GetMainSpecCore(IMyCubeGrid grid) + { + return getMainSpecCore.Invoke(grid); + } + + public static IMyTerminalBlock GetMainSpecCoreBlock(IMyCubeGrid grid) + { + return getMainSpecCoreBlock.Invoke(grid); + } + + public static void GetSpecCoreLimits(object specCore, IDictionary buffer, GetSpecCoreLimitsEnum limits) + { + getSpecCoreLimits.Invoke(specCore, buffer, (int) limits); + } + + public static void GetSpecCoreUpgrades(object specCore, List buffer) + { + getSpecCoreUpgrades.Invoke(specCore, buffer); + } + + public static void SetSpecCoreCustomValues(object specCore, IDictionary staticValues, IDictionary dynamicValues) + { + setSpecCoreCustomValues.Invoke(specCore, staticValues, dynamicValues); + } + + public static object GetSpecCoreBlock(IMyTerminalBlock block) + { + return getSpecCoreBlock.Invoke(block); + } + + public static IMyTerminalBlock GetBlockSpecCore(object block) + { + return getBlockSpecCore.Invoke(block); + } + + public static object GetLimitedBlock(IMyTerminalBlock block) + { + return getLimitedBlock.Invoke(block); + } + + public static IMyTerminalBlock GetLimitedBlockBlock(object block) + { + return getLimitedBlockBlock.Invoke(block); + } + + public static void RegisterCustomLimitConsumer(string Id, Func creator) + { + SpecBlockHooks.RegisterCustomLimitConsumer(Id, + creator, + (logic)=> + { + ((ILimitedBlock) logic).CanWork(); + }, + (block, logic) => + { + return ((ILimitedBlock) logic).CheckConditions(block); + }, + (logic)=> + { + return ((ILimitedBlock) logic).CanBeDisabled(); + }, + (logic)=> + { + return ((ILimitedBlock) logic).IsDrainingPoints(); + }, + (logic)=> + { + ((ILimitedBlock) logic).Disable(); + }); + } + + public static Dictionary> GetGridBlocksByType(IMyCubeGrid grid) + { + return getGridBlocksByType?.Invoke(grid) ?? null; + } + + public static Dictionary> GetGridBlocksById(IMyCubeGrid grid) + { + return getGridBlocksById?.Invoke(grid) ?? null; + } + + public static void HandleDamage(object target, ref MyDamageInformation damage) + { //Paralell + try + { + var slimBlock = target as IMySlimBlock; + if (slimBlock != null) + { + var cubeGrid = slimBlock.CubeGrid; + var core = SpecBlockHooks.GetMainSpecCore(slimBlock.CubeGrid); + var stats = new Dictionary(); + SpecBlockHooks.GetSpecCoreLimits(core, stats, SpecBlockHooks.GetSpecCoreLimitsEnum.CurrentStaticOrDynamic); + if(stats.ContainsKey(55)) + { + damage.Amount *= stats [55]; //here id of property + } + } + } + catch(Exception e) + { + Log.ChatError("CustomDamageHandler:", e); + } + } + } +} \ No newline at end of file diff --git a/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs new file mode 100644 index 00000000..4246f42a --- /dev/null +++ b/TSTSSESCoresAddon/Data/Scripts/ScriptsAddon/Specials/SpecCoreSession.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Xml.Serialization; +using Digi; +using MIG.Shared.CSharp; +using MIG.Shared.SE; +using ProtoBuf; +using Sandbox.ModAPI; +using Scripts.Specials.ShipClass; +using VRage; +using VRage.Game; +using VRage.Game.Components; +using VRage.Game.ModAPI; +using VRage.ModAPI; + +namespace MIG.SpecCores +{ + [MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation)] + public class SpecCoreSession : MySessionComponentBase + { + public override void Init(MyObjectBuilder_SessionComponent sessionComponent) + { + base.Init(sessionComponent); + SpecBlockHooks.Init(); + } + + private bool inited = false; + public override void UpdateBeforeSimulation() + { + base.UpdateBeforeSimulation(); + FrameExecutor.Update(); + + } + + protected override void UnloadData() + { + SpecBlockHooks.Close(); + } + } +} \ No newline at end of file