/// <summary> /// Accounts for block being added to a grid that already exist in the world /// </summary> /// <param name="grid"></param> /// <param name="block"></param> private void MyCubeGridsOnBlockBuilt(MyCubeGrid grid, MySlimBlock block) { if (grid == null || !BlockLimiterConfig.Instance.EnableLimits) { return; } //This adds grid to cache and also prevents double count from MyEntitiesOnEntityAdd if (!GridCache.TryGetGridById(grid.EntityId, out _)) { GridCache.AddGrid(grid); return; } if (_justAdded.Contains(block)) { _justAdded.Remove(block); return; } _justAdded.Add(block); GridCache.AddBlock(block); Block.IncreaseCount(block.BlockDefinition, new List <long> { block.BuiltBy }, 1, grid.EntityId); }
/// <summary> /// Removes blocks on closure /// </summary> /// <param name="__instance"></param> /// <returns></returns> private static bool OnClose(MyEntity __instance) { if (!BlockLimiterConfig.Instance.EnableLimits) { return(true); } if (__instance.Closed || __instance.MarkedForClose) { return(true); } switch (__instance) { case MyCubeBlock cubeBlock: Block.DecreaseCount(cubeBlock.BlockDefinition, cubeBlock.BuiltBy, 1, cubeBlock.CubeGrid.EntityId); break; case MyCubeGrid grid: { GridCache.RemoveGrid(grid.EntityId); break; } } return(true); }
/// <summary> /// Removes blocks on closure /// </summary> /// <param name="__instance"></param> /// <returns></returns> private static void OnClose(MyEntity __instance) { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } if (__instance.MarkedForClose) { return; } if (__instance is MyCubeBlock cubeBlock) { if (_justRemoved.Contains(cubeBlock.SlimBlock)) { _justRemoved.Remove(cubeBlock.SlimBlock); return; } _justRemoved.Add(cubeBlock.SlimBlock); //added filter for projector if (cubeBlock.CubeGrid.Projector == null) { GridCache.RemoveBlock(cubeBlock.SlimBlock); } Block.DecreaseCount(cubeBlock.BlockDefinition, cubeBlock.BuiltBy == cubeBlock.OwnerId ? new List <long> { cubeBlock.BuiltBy } : new List <long> { cubeBlock.BuiltBy, cubeBlock.OwnerId }, 1, cubeBlock.CubeGrid.EntityId); } if (!(__instance is MyCubeGrid grid)) { return; } foreach (var block in grid.CubeBlocks) { if (_justRemoved.Contains(block)) { _justRemoved.Remove(block); continue; } _justRemoved.Add(block); Block.DecreaseCount(block.BlockDefinition, block.BuiltBy == block.OwnerId ? new List <long> { block.BuiltBy } : new List <long> { block.BuiltBy, block.OwnerId }, 1, grid.EntityId); } if (grid.Projector == null) { GridCache.RemoveGrid(grid); } }
private void MyCubeGridsOnBlockBuilt(MyCubeGrid grid, MySlimBlock block) { if (!GridCache.TryGetGridById(grid.EntityId, out _)) { GridCache.AddGrid(grid.EntityId); return; } Block.IncreaseCount(block.BlockDefinition, block.BuiltBy, 1, grid.EntityId); }
public override void Handle() { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } GridCache.GetBlocks(_blockCache); RunPunishment(_blockCache); _blockCache.Clear(); }
public override void Update() { base.Update(); if (MyAPIGateway.Session == null || !BlockLimiterConfig.Instance.EnableLimits) { return; } if (++_updateCounter % 1000 == 0) { GridCache.Update(); } }
/// <summary> ///Checks if grid will violate limit on conversion and updates limits after /// </summary> /// <param name="__instance"></param> /// <returns></returns> private static bool ToStatic(MyCubeGrid __instance) { if (!BlockLimiterConfig.Instance.EnableLimits || !BlockLimiterConfig.Instance.EnableConvertBlock) { return(true); } var grid = __instance; if (grid == null) { Log.Warn("Null grid in GridChange handler"); return(true); } if (grid.GridSizeEnum == MyCubeSize.Small) { return(true); } var remoteUserId = MyEventContext.Current.Sender.Value; var playerId = Utilities.GetPlayerIdFromSteamId(remoteUserId); if (Grid.AllowConversion(grid, out var blocks, out var count, out var limitName) || remoteUserId == 0 || playerId == 0) { var gridId = grid.EntityId; Task.Run(() => { Thread.Sleep(100); GridCache.TryGetGridById(gridId, out var newStateGrid); if (newStateGrid == null) { return; } UpdateLimits.GridLimit(newStateGrid); }); return(true); } var msg = Utilities.GetMessage(BlockLimiterConfig.Instance.DenyMessage, blocks, limitName, count); if (MySession.Static.Players.IsPlayerOnline(playerId)) { BlockLimiter.Instance.Torch.CurrentSession.Managers.GetManager <ChatManagerServer>()? .SendMessageAsOther(BlockLimiterConfig.Instance.ServerName, msg, Color.Red, remoteUserId); } BlockLimiter.Instance.Log.Info( $"Grid conversion blocked from {MySession.Static.Players.TryGetPlayerBySteamId(remoteUserId).DisplayName} due to possible violation"); Utilities.SendFailSound(remoteUserId); Utilities.ValidationFailed(); return(false); }
public override void Update() { base.Update(); if (MyAPIGateway.Session == null || !BlockLimiterConfig.Instance.EnableLimits) { return; } if (++_updateCounter % 100 != 0) { return; } GridCache.Update(); MergeBlockPatch.MergeBlockCache?.Clear(); }
private void MyCubeGridsOnBlockBuilt(MyCubeGrid grid, MySlimBlock block) { if (grid == null || !BlockLimiterConfig.Instance.EnableLimits) { return; } if (!GridCache.TryGetGridById(grid.EntityId, out _)) { GridCache.AddGrid(grid); return; } Block.IncreaseCount(block.BlockDefinition, block.BuiltBy, 1, grid.EntityId); }
/// <summary> ///Checks if grid will violate limit on conversion and updates limits after /// </summary> /// <param name="__instance"></param> /// <returns></returns> private static bool ToStatic(MyCubeGrid __instance) { if (!BlockLimiterConfig.Instance.EnableLimits || !BlockLimiterConfig.Instance.EnableConvertBlock) { return(true); } var grid = __instance; if (grid == null) { if (BlockLimiterConfig.Instance.EnableLog) { BlockLimiter.Instance.Log.Warn("Null grid in GridChange handler"); } return(true); } if (grid.GridSizeEnum == MyCubeSize.Small) { return(true); } var remoteUserId = MyEventContext.Current.Sender.Value; var playerId = Utilities.GetPlayerIdFromSteamId(remoteUserId); if (Grid.AllowConversion(grid) || remoteUserId == 0 || playerId == 0) { var gridId = grid.EntityId; Task.Run(() => { Thread.Sleep(100); GridCache.TryGetGridById(gridId, out var newStateGrid); if (newStateGrid == null) { return; } UpdateLimits.GridLimit(newStateGrid); }); return(true); } MyVisualScriptLogicProvider.SendChatMessage($"{BlockLimiterConfig.Instance.DenyMessage}", BlockLimiterConfig.Instance.ServerName, playerId, MyFontEnum.Red); if (BlockLimiterConfig.Instance.EnableLog) { BlockLimiter.Instance.Log.Info( $"Grid conversion blocked from {MySession.Static.Players.TryGetPlayerBySteamId(remoteUserId).DisplayName} due to violation"); } Utilities.SendFailSound(remoteUserId); Utilities.ValidationFailed(); return(false); }
private static void AddBlocks(MyShipMergeBlock __instance) { var id = __instance.CubeGrid.EntityId; Task.Run((() => { Thread.Sleep(10000); if (!GridCache.TryGetGridById(id, out var grid)) { return; } UpdateLimits.GridLimit(grid); })); }
private void SessionChanged(ITorchSession session, TorchSessionState state) { _running = state == TorchSessionState.Loaded; switch (state) { case TorchSessionState.Loading: timeDataPath = Path.Combine(Torch.CurrentSession.KeenSession.CurrentPath, "BLPlayerTime.json"); if (!File.Exists(timeDataPath)) { File.Create(timeDataPath); } break; case TorchSessionState.Loaded: var data = File.ReadAllText(timeDataPath); if (!string.IsNullOrEmpty(data)) { PlayerTimeModule.PlayerTimes = JsonConvert.DeserializeObject <List <PlayerTimeModule.PlayerTimeData> >( File.ReadAllText(timeDataPath)); } Torch.CurrentSession.Managers.GetManager <IMultiplayerManagerServer>().PlayerJoined += PlayerTimeModule.LogTime; DoInit(); EnableControl(); GetVanillaLimits(); GridCache.Update(); if (BlockLimiterConfig.Instance.EnableLimits) { Activate(); } break; case TorchSessionState.Unloading: break; default: return; } }
private void SessionChanged(ITorchSession session, TorchSessionState state) { _running = state == TorchSessionState.Loaded; switch (state) { case TorchSessionState.Loaded: DoInit(); EnableControl(); GetVanillaLimits(); GridCache.Update(); Utilities.UpdateLimits(BlockLimiterConfig.Instance.UseVanillaLimits, out BlockLimiterConfig.Instance.AllLimits); ResetLimits(); break; case TorchSessionState.Unloading: Dispose(); break; } }
/// <summary> /// Updates limits on grid split /// </summary> /// <param name="originalGrid"></param> private static void OnCreateSplit(MyCubeGrid originalGrid) { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } if (originalGrid == null) { return; } Task.Run(() => { Thread.Sleep(100); if (!GridCache.TryGetGridById(originalGrid.EntityId, out var newStateGrid)) { return; } UpdateLimits.GridLimit(newStateGrid); }); }
/// <summary> /// Adds newly added grids to cache and update count to meet change /// </summary> /// <param name="entity"></param> private void MyEntitiesOnOnEntityAdd(MyEntity entity) { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } if (!(entity is MyCubeGrid grid)) { return; } if (grid.Projector != null || grid.IsPreview) { return; } // Do Not Add to grid cache at this point to allow MyCubeGridsOnBlockBuild to add and prevent double counts var blocks = grid.CubeBlocks; GridCache.AddGrid(grid); foreach (var block in blocks) { if (_justAdded.Contains(block)) { _justAdded.Remove(block); continue; } _justAdded.Add(block); Block.IncreaseCount(block.BlockDefinition, block.BuiltBy == block.OwnerId ? new List <long> { block.BuiltBy } : new List <long> { block.BuiltBy, block.OwnerId }, 1, grid.EntityId); } }
private void SessionChanged(ITorchSession session, TorchSessionState state) { _running = state == TorchSessionState.Loaded; switch (state) { case TorchSessionState.Loaded: DoInit(); EnableControl(); GetVanillaLimits(); GridCache.Update(); if (BlockLimiterConfig.Instance.EnableLimits) { Activate(); } break; case TorchSessionState.Unloading: Dispose(); break; default: return; } }
/// <summary> /// Updates limits on grid split /// </summary> /// <param name="from"></param> /// <param name="to"></param> private static void OnCreateSplit(ref MyCubeGrid from, ref MyCubeGrid to) { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } var toBlocks = new HashSet <MySlimBlock>(to.CubeBlocks); if (toBlocks.Count == 0) { Log.Warn("Could not update count after grid separation"); return; } foreach (var block in toBlocks) { Block.DecreaseCount(block.BlockDefinition, block.BuiltBy == block.OwnerId ? new List <long> { block.BuiltBy } : new List <long> { block.BuiltBy, block.OwnerId }, 1, @from.EntityId); } var grid = from; if (grid == null) { return; } var removeSmallestGrid = false; var owners = new HashSet <long>(GridCache.GetOwners(from)); owners.UnionWith(GridCache.GetBuilders(grid)); if (owners.Count == 0) { return; } foreach (var owner in owners) { if (!Grid.CountViolation(grid, owner)) { continue; } removeSmallestGrid = true; break; } if (!removeSmallestGrid || BlockLimiterConfig.Instance.BlockType != BlockLimiterConfig.BlockingType.Hard) { return; } var grid1 = from; var grid2 = to; BlockLimiter.Instance.Torch.InvokeAsync(() => { Thread.Sleep(100); if (grid1.BlocksCount > grid2.BlocksCount) { grid2.SendGridCloseRequest(); UpdateLimits.GridLimit(grid1); } else { grid1.SendGridCloseRequest(); UpdateLimits.GridLimit(grid2); } }); }
public static void ResetLimits(bool updateGrids = true, bool updatePlayers = true, bool updateFactions = true) { if (!BlockLimiterConfig.Instance.EnableLimits) { foreach (var limit in BlockLimiterConfig.Instance.AllLimits) { limit.FoundEntities.Clear(); } return; } if (updateGrids) { var grids = new HashSet <MyCubeGrid>(); GridCache.GetGrids(grids); Task.Run(() => { Parallel.ForEach(grids, grid => { if (grid == null) { return; } UpdateLimits.GridLimit(grid); }); }); } if (updatePlayers) { var players = MySession.Static.Players.GetAllPlayers(); if (players.Count > 0) { Task.Run(() => { Parallel.ForEach(players, player => { if (player.SteamId == 0) { return; } var identity = Utilities.GetPlayerIdFromSteamId(player.SteamId); if (identity == 0) { return; } UpdateLimits.PlayerLimit(identity); }); }); } } if (updateFactions) { Task.Run(() => { Parallel.ForEach(MySession.Static.Factions, factionInfo => { var(id, faction) = factionInfo; if (faction.IsEveryoneNpc() || id == 0) { return; } UpdateLimits.FactionLimit(id); }); }); } }
public override void Handle() { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } var limitItems = BlockLimiterConfig.Instance.AllLimits; if (!limitItems.Any()) { return; } _blockCache.Clear(); GridCache.GetBlocks(_blockCache); if (!_blockCache.Any()) { return; } var removeBlocks = new MyConcurrentDictionary <MySlimBlock, LimitItem.PunishmentType>(); var punishCount = 0; var blocks = _blockCache.ToList(); foreach (var item in limitItems) { if (!item.FoundEntities.Any() || item.Punishment == LimitItem.PunishmentType.None) { continue; } foreach (var(id, count) in item.FoundEntities) { if (id == 0 || Utilities.IsExcepted(id, item.Exceptions)) { item.FoundEntities.Remove(id); continue; } if (count <= item.Limit) { continue; } for (var i = blocks.Count; i-- > 0;) { var block = blocks[i]; if (!Block.IsMatch(block.BlockDefinition, item)) { continue; } if (Math.Abs(punishCount - count) <= item.Limit) { break; } if (item.IgnoreNpcs) { if (MySession.Static.Players.IdentityIsNpc(block.FatBlock.BuiltBy) || MySession.Static.Players.IdentityIsNpc(block.FatBlock.OwnerId)) { item.FoundEntities.Remove(id); continue; } } if (item.LimitGrids && block.CubeGrid.EntityId == id) { punishCount++; removeBlocks[block] = item.Punishment; continue; } if (item.LimitPlayers) { if (Block.IsOwner(block, id)) { punishCount++; removeBlocks[block] = item.Punishment; continue; } } if (!item.LimitFaction) { continue; } var faction = MySession.Static.Factions.TryGetFactionById(id); if (faction == null || !block.FatBlock.GetOwnerFactionTag().Equals(faction.Tag)) { continue; } punishCount++; removeBlocks[block] = item.Punishment; } } } _blockCache.Clear(); if (!removeBlocks.Keys.Any()) { return; } Task.Run(() => { MySandboxGame.Static.Invoke(() => { foreach (var(block, punishment) in removeBlocks) { try { switch (punishment) { case LimitItem.PunishmentType.DeleteBlock: if (BlockLimiterConfig.Instance.EnableLog) { Log.Info( $"removed {block.BlockDefinition.BlockPairName} from {block.CubeGrid.DisplayName}"); } block.CubeGrid.RemoveBlock(block); continue; case LimitItem.PunishmentType.ShutOffBlock: if (!(block.FatBlock is MyFunctionalBlock funcBlock) || funcBlock.Enabled == false) { continue; } if (BlockLimiterConfig.Instance.EnableLog) { Log.Info( $"Turned off {block.BlockDefinition.BlockPairName} from {block.CubeGrid.DisplayName}"); } funcBlock.Enabled = false; continue; case LimitItem.PunishmentType.Explode: if (BlockLimiterConfig.Instance.EnableLog) { Log.Info( $"Destroyed {block.BlockDefinition.BlockPairName} from {block.CubeGrid.DisplayName}"); } block.DoDamage(block.BlockDefinition.MaxIntegrity * 10, MyDamageType.Explosion); continue; default: throw new ArgumentOutOfRangeException(); } } catch (Exception e) { if (BlockLimiterConfig.Instance.EnableLog) { Log.Error(e); } } } }, "BlockLimiter"); }); }
public void UpdateLimits() { var time = DateTime.Now - _lastRun; if (time.TotalSeconds < 60) { var timeRemaining = TimeSpan.FromMinutes(1) - time; Context.Respond($"Cooldown in effect. Try again in {timeRemaining.TotalSeconds:N0} seconds"); return; } var args = Context.Args; if (args.Count == 0) { if (!_doCheck) { Context.Respond("Warning: This command will drop sim speed for few seconds/minutes while recalculating limits. Run command again to proceed"); _doCheck = true; Task.Run(() => { Thread.Sleep(30000); _doCheck = false; }); return; } _doCheck = false; BlockLimiterConfig.Instance.Save(); GridCache.Update(); BlockLimiter.ResetLimits(); _lastRun = DateTime.Now; Context.Respond("Limits updated"); return; } foreach (var arg in args) { if (arg.StartsWith("-player")) { var name = arg.Replace("-player=", ""); if (!Utilities.TryGetPlayerByNameOrId(name, out var identity)) { Context.Respond($"Player {name} not found"); continue; } Context.Respond($"Updated {identity.DisplayName} limits"); Utility.UpdateLimits.PlayerLimit(identity.IdentityId); continue; } if (arg.StartsWith("-grid")) { var gridName = arg.Replace("-grid=", ""); if (!Utilities.TryGetEntityByNameOrId(gridName, out var entity)) { Context.Respond($"No entity with the name {gridName} found"); continue; } if (!(entity is MyCubeGrid grid)) { Context.Respond("No grid found"); continue; } Context.Respond($"{grid.DisplayName} limits updated"); Utility.UpdateLimits.GridLimit(grid); continue; } if (arg.StartsWith("-faction")) { var factionTag = arg.Replace("-faction=", ""); var faction = MySession.Static.Factions.TryGetFactionByTag(factionTag); if (faction == null) { Context.Respond($"{factionTag} was not found in factions. Check spelling and case."); continue; } Context.Respond($"{faction.Tag} limits updated"); Utility.UpdateLimits.FactionLimit(faction.FactionId); } } }
public void GetViolations() { if (!BlockLimiterConfig.Instance.EnableLimits) { Context.Respond("Plugin disabled"); return; } var limitItems = BlockLimiterConfig.Instance.AllLimits; if (!limitItems.Any(x => x.FoundEntities.Any())) { Context.Respond("No violations found"); return; } var sb = new StringBuilder(); //Todo: Add conditions /* * foreach (var arg in Context.Args) * { * if (arg.StartsWith("--gps=")) * { * * } * * if (arg.StartsWith("--grid=")) * { * * } * * if (arg.StartsWith("--player=")) * { * * } * * if (arg.StartsWith("--faction=")) * { * * } * * } */ var grids = new HashSet <MyCubeGrid>(); GridCache.GetGrids(grids); if (grids.Count > 0) { if (BlockLimiterConfig.Instance.MaxBlockSizeShips > 0) { sb.AppendLine($"Ship Limits"); foreach (var grid in grids.Where(x => x.BlocksCount > BlockLimiterConfig.Instance.MaxBlockSizeShips && !x.IsStatic)) { sb.AppendLine( $"{grid.DisplayName}: {grid.BlocksCount}/{BlockLimiterConfig.Instance.MaxBlockSizeShips}"); } } if (BlockLimiterConfig.Instance.MaxBlockSizeStations > 0) { sb.AppendLine($"Station Limits"); foreach (var grid in grids.Where(x => x.BlocksCount > BlockLimiterConfig.Instance.MaxBlockSizeStations && x.IsStatic)) { sb.AppendLine( $"{grid.DisplayName}: {grid.BlocksCount}/{BlockLimiterConfig.Instance.MaxBlockSizeStations}"); } } if (BlockLimiterConfig.Instance.MaxBlocksLargeGrid > 0) { sb.AppendLine($"Large Grid Block Limits"); foreach (var grid in grids.Where(x => x.BlocksCount > BlockLimiterConfig.Instance.MaxBlocksLargeGrid && x.GridSizeEnum == MyCubeSize.Large)) { sb.AppendLine( $"{grid.DisplayName}: {grid.BlocksCount}/{BlockLimiterConfig.Instance.MaxBlocksLargeGrid}"); } } if (BlockLimiterConfig.Instance.MaxBlocksSmallGrid > 0) { sb.AppendLine($"Small Grid Block Limits"); foreach (var grid in grids.Where(x => x.BlocksCount > BlockLimiterConfig.Instance.MaxBlocksSmallGrid && x.GridSizeEnum == MyCubeSize.Small)) { sb.AppendLine( $"{grid.DisplayName}: {grid.BlocksCount}/{BlockLimiterConfig.Instance.MaxBlocksSmallGrid}"); } } } foreach (var item in limitItems) { if (!item.BlockList.Any() || !item.FoundEntities.Any(x => x.Value > 0)) { continue; } var itemName = string.IsNullOrEmpty(item.Name) ? item.BlockList.FirstOrDefault() : item.Name; sb.AppendLine($"{itemName} Violators"); foreach (var(entity, count) in item.FoundEntities) { if (count <= item.Limit) { continue; } var faction = MySession.Static.Factions.TryGetFactionById(entity); if (faction != null) { sb.AppendLine($"FactionLimit for {faction.Tag} = {count}/{item.Limit}"); continue; } var player = MySession.Static.Players.TryGetIdentity(entity); if (player != null) { sb.AppendLine($"PlayerLimit for {player.DisplayName} = {count}/{item.Limit}"); continue; } if (!GridCache.TryGetGridById(entity, out var grid)) { continue; } sb.AppendLine($"GridLimit for {grid.DisplayName} = {count}/{item.Limit}"); } sb.AppendLine(); } sb.AppendLine(); if (Context.Player == null || Context.Player.IdentityId == 0) { Context.Respond(sb.ToString()); return; } ModCommunication.SendMessageTo(new DialogMessage(BlockLimiterConfig.Instance.ServerName, "List of Violations", sb.ToString()), Context.Player.SteamUserId); }
public static void ResetLimits(bool updateGrids = true, bool updatePlayers = true, bool updateFactions = true) { if (!BlockLimiterConfig.Instance.EnableLimits) { foreach (var limit in BlockLimiterConfig.Instance.AllLimits) { limit.FoundEntities.Clear(); } return; } if (updateGrids) { var grids = new HashSet <MyCubeGrid>(); GridCache.GetGrids(grids); Task.Run(() => { Thread.Sleep(500); foreach (var grid in grids) { if (grid == null) { continue; } Parallel.Invoke(() => { Thread.Sleep(100); UpdateLimits.GridLimit(grid); }); } }); } if (updatePlayers) { Task.Run(() => { Thread.Sleep(300); foreach (var player in MySession.Static.Players.GetAllPlayers()) { if (player.SteamId == 0) { continue; } var identity = Utilities.GetPlayerIdFromSteamId(player.SteamId); if (identity == 0) { continue; } Parallel.Invoke(() => UpdateLimits.PlayerLimit(identity)); } }); } if (updateFactions) { Task.Run(() => { Thread.Sleep(100); foreach (var(id, faction) in MySession.Static.Factions.Factions) { if (faction.IsEveryoneNpc() || id == 0) { continue; } Parallel.Invoke(() => UpdateLimits.FactionLimit(id)); } }); } }
public void Punish() { if (!BlockLimiterConfig.Instance.EnableLimits) { Context.Respond("Plugin disabled"); return; } var blocks = new HashSet <MySlimBlock>(); var punishmentTypes = new List <LimitItem.PunishmentType>(); int count; if (Context.Args.Count == 0) { GridCache.GetBlocks(blocks); count = Punishment.Punish.RunPunishment(blocks); Context.Respond($"Punished {count} blocks"); return; } if (Context.Args.Count == 1 && Context.Args[0].StartsWith("-punishment")) { GridCache.GetBlocks(blocks); if (!Enum.TryParse(Context.Args[0].Replace("-punishment=", ""), true, out LimitItem.PunishmentType punishment)) { Context.Respond("Punishment string error. Use 'DeleteBlock', 'ShutOffBlock', or 'Explode' instead"); return; } punishmentTypes.Add(punishment); count = Punishment.Punish.RunPunishment(blocks, punishmentTypes); Context.Respond($"Punished {count} blocks"); return; } var allOptionIsPunishment = true; foreach (var arg in Context.Args) { if (arg.StartsWith("-punishment=")) { if (!Enum.TryParse(arg.Replace("-punishment=", ""), true, out LimitItem.PunishmentType punishment)) { Context.Respond("Punishment string error. Use 'DeleteBlock', 'ShutOffBlock', or 'Explode' instead"); return; } if (punishmentTypes.Contains(punishment)) { continue; } punishmentTypes.Add(punishment); continue; } if (arg.StartsWith("-player=")) { allOptionIsPunishment = false; var name = arg.Replace("-player=", ""); if (!Utilities.TryGetPlayerByNameOrId(name, out var identity)) { Context.Respond($"Player {name} not found"); return; } GridCache.GetPlayerBlocks(blocks, identity.IdentityId); continue; } if (arg.StartsWith("-grid=")) { allOptionIsPunishment = false; var gridName = arg.Replace("-grid=", ""); if (!Utilities.TryGetEntityByNameOrId(gridName, out var entity)) { Context.Respond($"No entity with the name {gridName} found"); return; } if (!(entity is MyCubeGrid grid)) { Context.Respond("No grid found"); return; } blocks.UnionWith(grid.CubeBlocks); continue; } if (arg.StartsWith("-faction")) { allOptionIsPunishment = false; var factionTag = arg.Replace("-faction=", ""); var faction = MySession.Static.Factions.TryGetFactionByTag(factionTag); if (faction == null) { Context.Respond($"{factionTag} was not found in factions. Check spelling and case."); return; } GridCache.GetFactionBlocks(blocks, faction.FactionId); } } if (allOptionIsPunishment && punishmentTypes.Count > 0) { GridCache.GetBlocks(blocks); } count = Punishment.Punish.RunPunishment(blocks, punishmentTypes.Count > 0 ?punishmentTypes:null); Context.Respond($"Punished {count} blocks"); }
/// <summary> /// Updates limits on grid split /// </summary> /// <param name="originalGrid"></param> private static void OnCreateSplit(ref MyCubeGrid from, ref MyCubeGrid to) { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } var toBlocks = new HashSet <MySlimBlock>(to.CubeBlocks); if (toBlocks.Count == 0) { Log.Error("Not updated breakage"); return; } foreach (var block in toBlocks) { if (block.BuiltBy == block.OwnerId) { Block.DecreaseCount(block.BlockDefinition, block.BuiltBy, 1, from.EntityId); } else { Block.DecreaseCount(block.BlockDefinition, block.BuiltBy, 1, from.EntityId); Block.DecreaseCount(block.BlockDefinition, block.OwnerId); } } var grid = from; if (grid == null) { return; } var removeSmallestGrid = false; var owners = GridCache.GetOwners(from); if (owners == null || owners.Count == 0) { return; } foreach (var owner in owners) { if (!Grid.CountViolation(grid, owner)) { continue; } removeSmallestGrid = true; break; } if (!removeSmallestGrid) { return; } var grid1 = from; var grid2 = to; BlockLimiter.Instance.Torch.InvokeAsync(() => { Thread.Sleep(100); if (grid1.BlocksCount > grid2.BlocksCount) { grid2.SendGridCloseRequest(); UpdateLimits.GridLimit(grid1); } else { grid1.SendGridCloseRequest(); UpdateLimits.GridLimit(grid2); } }); }