// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() != 4 && words.Count() != 0) { return(false); } if (!words.Any()) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } // Test Input float test = 0; for (int r = 0; r < 4; r++) { if (!float.TryParse(words[r], out test)) { Communication.SendPrivateInformation(userId, string.Format("The value at position {0} - '{1}' is invalid. Please try the command again.", r + 1, words[r])); return(true); } } Vector3D startPosition = new Vector3(float.Parse(words[0]), float.Parse(words[1]), float.Parse(words[2])); float radius = float.Parse(words[3]); CubeGrids.RemoveGridsInSphere(userId, startPosition, radius, RemoveGridTypes.Stations); return(true); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { try { HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesToConfirm = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesConnected = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { continue; } bool found = false; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.TypeId == typeof(MyObjectBuilder_Beacon)) { found = true; break; } } if (!found) { entitiesToConfirm.Add(grid); } } CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId); Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, gridEntity.EntityId, General.Vector3DToString(entity.GetPosition()))); } Communication.SendPrivateInformation(userId, string.Format("Found {0} grids with no beacons", entitiesFound.Count)); } catch (Exception ex) { Logging.WriteLineAndConsole(string.Format("Scan error: {0}", ex.ToString())); } return(true); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { string linkType = ""; if (words.Length > 0 && words[0].ToLower( ) == "physical") { linkType = " physical"; } try { string command = $"excludesblocksubtype:beacon quiet{linkType}"; HashSet <GridGroup> groups = CubeGrids.ScanGrids(0, CommandParser.GetCommandParts(command).ToArray()); int groupsCount = groups.Count; int gridsCount = 0; foreach (var group in groups) { //if ( group.GetFatBlocks( ).Any( x => x is IMyBeacon ) ) // continue; //groupsCount++; gridsCount += group.Grids.Count; Communication.SendPrivateInformation(userId, $"Found group with parent {group.Parent.DisplayName} ({group.Parent.EntityId}) at {group.Parent.PositionComp.GetPosition( )} with no beacon."); } Communication.SendPrivateInformation(userId, $"Found {gridsCount} grids in {groupsCount} groups with no beacon."); } catch (Exception ex) { Log.Info(string.Format("Scan error: {0}", ex.ToString( ))); } return(true); }
private HashSet <long> GetAllOwners() { HashSet <long> owners = new HashSet <long>(); HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); MyAPIGateway.Entities.GetEntities(entities); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { continue; } foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.Owner != 0 && !owners.Contains(block.Owner)) { owners.Add(block.Owner); } } } return(owners); }
/// <exception cref="OverflowException"></exception> private void ProcessTriggerItem(SettingsCleanupTriggerItem item) { if (_triggerdItem != null && _triggerdItem != item) { return; } if (_triggerdItem == null) { // Increase to 5 minutes if (DateTime.Now - item.LastRan > TimeSpan.FromMinutes(5)) { item.LastRan = DateTime.Now; string command = string.Format("{0} quiet", item.ScanCommand); HashSet <IMyEntity> entities = CubeGrids.ScanGrids(0, command); if (entities.Count >= item.MaxCapacity) { Communication.SendPublicInformation(string.Format("[NOTICE]: Cleanup triggered. ({0} of {1}) triggered grids found. Cleanup will run in {2} minutes. Reason: {3}", entities.Count, item.MaxCapacity, item.MinutesAfterCapacity, item.Reason)); item.NotificationItemsRan.Clear( ); _triggerdItem = item; return; } } } else { if (DateTime.Now - item.LastRan > TimeSpan.FromMinutes(item.MinutesAfterCapacity)) { string command = string.Format("{0} quiet", item.ScanCommand); HashSet <IMyEntity> entities = CubeGrids.ScanGrids(0, command); CubeGrids.DeleteGrids(entities); Communication.SendPublicInformation(string.Format("[NOTICE]: Triggered cleanup has run. {0} entities removed. Have a nice day.", entities.Count)); _triggerdItem = null; return; } foreach (SettingsCleanupNotificationItem notifyItem in PluginSettings.Instance.CleanupNotificationItems) { if (item.NotificationItemsRan.Contains(notifyItem)) { continue; } if (notifyItem.MinutesBeforeCleanup > item.MinutesAfterCapacity) { continue; } if (DateTime.Now - item.LastRan > TimeSpan.FromMinutes(item.MinutesAfterCapacity - notifyItem.MinutesBeforeCleanup)) { item.NotificationItemsRan.Add(notifyItem); string notification = notifyItem.Message.Replace("%cleanup_reason%", item.Reason); Communication.SendPublicInformation(notification); } } } }
// /admin movefrom x y z x y z radius public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() < 2) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } string sourceName = words[0]; float distance = 50f; // TODO Allow quotes so we can do distance? bool parse = false; if (words.Count() > 2) { parse = float.TryParse(words[words.Count() - 1], out distance); } string targetName; if (parse) { targetName = string.Join(" ", words.Skip(1).Take(words.Count() - 2).ToArray()); } else { targetName = string.Join(" ", words.Skip(1).ToArray()); } Vector3D position; IMyEntity entity = Player.FindControlledEntity(targetName); if (entity == null) { entity = CubeGrids.Find(targetName); if (entity == null) { Communication.SendPrivateInformation(userId, string.Format("Can not find user or grid with the name: {0}", targetName)); return(true); } } position = entity.GetPosition(); Communication.SendPrivateInformation(userId, string.Format("Trying to move {0} to within {1}m of {2}. This may take about 20 seconds.", sourceName, distance, targetName)); Vector3D startPosition = MathUtility.RandomPositionFromPoint((Vector3)position, distance); if (!Player.Move(sourceName, startPosition)) { Communication.SendPrivateInformation(userId, string.Format("Can not move user: {0} (Is user in a cockpit or not in game?)", sourceName)); return(true); } Communication.SendPrivateInformation(userId, string.Format("Moved {0} to within {1}m of {2}", sourceName, (int)Math.Round(Vector3D.Distance(startPosition, position)), targetName)); return(true); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { try { CubeGrids.ScanGrids(userId, words); } catch (Exception ex) { Log.Info(ex, "scan grid"); return(false); } return(true); }
public void Process() { lock (m_items) { if (!m_items.Any()) { return; } for (int r = m_items.Count() - 1; r >= 0; r--) { TimedEntityCleanupItem item = m_items[r]; if (DateTime.Now - item.addedTime > TimeSpan.FromSeconds(item.secondsAfterAdding)) { try { IMyEntity entity = null; Wrapper.GameAction(() => { MyAPIGateway.Entities.TryGetEntityById(item.entityId, out entity); }); if (entity != null) { MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (gridBuilder == null) { continue; } CubeGridEntity entityToDispose = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); entityToDispose.Dispose(); } else { Logging.WriteLineAndConsole("Entity is null"); } } catch (Exception ex) { Logging.WriteLineAndConsole(string.Format("Dispose Error: {0}", ex.ToString())); } m_items.RemoveAt(r); } } } }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { HashSet <IMyEntity> grids = CubeGrids.ScanGrids(userId, words); bool confirm = true; /* * if (words.FirstOrDefault(x => x.ToLower() == "confirm") != null) * { * confirm = true; * } */ int count = 0; foreach (IMyEntity entity in grids) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (confirm) { BaseEntityNetworkManager.BroadcastRemoveEntity(entity, true); } long ownerId = 0; string ownerName = ""; if (CubeGrids.GetBigOwners(gridBuilder).Count > 0) { ownerId = CubeGrids.GetBigOwners(gridBuilder).First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } if (confirm) { Logging.WriteLineAndConsole("Cleanup", string.Format("Cleanup Removed Grid - Id: {0} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName)); } count++; } Communication.SendPrivateInformation(userId, string.Format("Operation deletes {0} grids", count)); return(true); }
/// <exception cref="OverflowException"></exception> private void ProcessTimedItem(SettingsCleanupTimedItem item) { _start = DateTime.Now; // this needs to be updated for each run so multi-day runtimes are handled properly DateTime itemTime = new DateTime(_start.Year, _start.Month, _start.Day, item.Restart.Hour, item.Restart.Minute, 0); if (DateTime.Now - itemTime > _twentySeconds) { itemTime = itemTime.AddDays(1); } if (DateTime.Now - item.LastRan < _oneMinute) { return; } if (itemTime - DateTime.Now < _oneSecond && DateTime.Now - item.LastRan > _oneMinute) { string command = string.Format("{0} quiet", item.ScanCommand); HashSet <IMyEntity> entities = CubeGrids.ScanGrids(0, CommandParser.GetCommandParts(command).ToArray( )); CubeGrids.DeleteGrids(entities); Communication.SendPublicInformation(string.Format("[NOTICE]: Timed cleanup has run. {0} entities removed. Have a nice day.", entities.Count)); item.LastRan = DateTime.Now; item.NotificationItemsRan.Clear( ); return; } foreach (SettingsCleanupNotificationItem notifyItem in PluginSettings.Instance.CleanupNotificationItems) { if (item.NotificationItemsRan.Contains(notifyItem)) { continue; } if (itemTime - DateTime.Now < TimeSpan.FromMinutes(notifyItem.MinutesBeforeCleanup)) { item.NotificationItemsRan.Add(notifyItem); if (DateTime.Now - notifyItem.lastRan > _oneMinute) { notifyItem.lastRan = DateTime.Now; string notification = notifyItem.Message.Replace("%cleanup_reason%", item.Reason); Communication.SendPublicInformation(notification); } } } }
/// <exception cref="OverflowException"></exception> private void ProcessTimedItem(SettingsCleanupTimedItem item) { DateTime time = new DateTime(_start.Year, _start.Month, _start.Day, item.Restart.Hour, item.Restart.Minute, 0); if (time - DateTime.Now < TimeSpan.FromSeconds(-20)) { time = new DateTime(_start.Year, _start.Month, _start.Day + 1, item.Restart.Hour, item.Restart.Minute, 0); } if (DateTime.Now - item.LastRan < TimeSpan.FromMinutes(1)) { return; } if (time - DateTime.Now < TimeSpan.FromSeconds(1) && DateTime.Now - item.LastRan > TimeSpan.FromMinutes(1)) { string command = string.Format("{0} quiet", item.ScanCommand); HashSet <IMyEntity> entities = CubeGrids.ScanGrids(0, command); CubeGrids.DeleteGrids(entities); Communication.SendPublicInformation(string.Format("[NOTICE]: Timed cleanup has run. {0} entities removed. Have a nice day.", entities.Count)); item.LastRan = DateTime.Now; item.NotificationItemsRan.Clear( ); return; } foreach (SettingsCleanupNotificationItem notifyItem in PluginSettings.Instance.CleanupNotificationItems) { if (item.NotificationItemsRan.Contains(notifyItem)) { continue; } if (time - DateTime.Now < TimeSpan.FromMinutes(notifyItem.MinutesBeforeCleanup)) { item.NotificationItemsRan.Add(notifyItem); if (DateTime.Now - notifyItem.lastRan > TimeSpan.FromMinutes(1)) { notifyItem.lastRan = DateTime.Now; string notification = notifyItem.Message.Replace("%cleanup_reason%", item.Reason); Communication.SendPublicInformation(notification); } } } }
private void ExtractCommandFromEntity(IMyEntity entity) { IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { return; } string command = string.Empty; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { MyObjectBuilder_Beacon beacon = block as MyObjectBuilder_Beacon; if (beacon != null) { command = beacon.CustomName; break; } } string player = entity.DisplayName.Replace("CommRelay", string.Empty); long playerId = long.Parse(player); ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId); Wrapper.GameAction(() => { entity.DisplayName = string.Empty; BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false); }); Essentials.Log.Info("COMMAND {1} - {2}: {0}", command, playerId, entity.EntityId); if (!m_processedRelays.Contains(entity.EntityId)) { m_processedRelays.Add(entity.EntityId); Essentials.Instance.HandleChatMessage(steamId, command); } else { Essentials.Log.Info("Ignoring repeat beacon: {0}"); } }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { HashSet <GridGroup> groups = CubeGrids.ScanGrids(userId, words); bool confirm = true; /* * if (words.FirstOrDefault(x => x.ToLower() == "confirm") != null) * { * confirm = true; * } */ int gridCount = 0; int groupCount = 0; foreach (GridGroup group in groups) { long ownerId = 0; string ownerName = ""; if (group.BigOwners.Count > 0) { ownerId = group.BigOwners.First( ); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } if (confirm) { Log.Info("Cleanup removed group with parent - Id: {0} Display: {1} OwnerId: {2} OwnerName: {3}", group.Parent.EntityId, group.Parent.DisplayName, ownerId, ownerName); } gridCount += group.Grids.Count; groupCount++; if (confirm) { group.Close( ); } } Communication.SendPrivateInformation(userId, $"Operation deletes {gridCount} grids in {groupCount} groups."); return(true); }
public GridGroup(MyCubeGrid grid, GridLinkTypeEnum linkType = GridLinkTypeEnum.Logical) { _linkType = linkType; if (grid.InScene) { List <MyCubeGrid> tmpList = new List <MyCubeGrid>( ); //find the group containing this grid with the given link type Wrapper.GameAction(() => tmpList = MyCubeGridGroups.Static.GetGroups(linkType).GetGroupNodes(grid)); _grids.UnionWith(tmpList); } //manually create a group for out of scene grids because they have a null group (yay Dusan fixed the crash) else { //use the old method to filter out grids with pistons or rotors, for safety HashSet <IMyEntity> thisEntity = new HashSet <IMyEntity>(); HashSet <IMyEntity> returnSet = new HashSet <IMyEntity>(); thisEntity.Add((IMyEntity)grid); CubeGrids.GetGridsUnconnected(returnSet, thisEntity); if (returnSet.Count > 0) { _grids.Add(grid); } else { return; } } //populate our internal lists ComputeParent( ); ComputeCubeBlocks( ); ComputeFatBlocks( ); ComputeSmallOwners( ); ComputeBigOwners( ); }
public override bool HandleCommand(ulong userId, string[] words) { HashSet <IMyEntity> entitiesFound = CubeGrids.ScanCleanup(userId, words); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity removeEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); removeEntity.Dispose(); IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (grid.BigOwners.Count > 0) { ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } Log.Info("Cleanup", string.Format("Cleanup Removed Grid - Id: {0} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName)); } return(true); }
public override bool HandleCommand(ulong userId, string[] words) { int page = 1; bool dialog = false; if (words.Length > 0) { if (words[0] == "dialog") { dialog = true; } int.TryParse(words[0], out page); if (page < 1) { page = 1; } } if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1 && userId != 0) { Communication.SendPrivateInformation(userId, "Error occurred while processing this command. (1)"); return(true); } long playerId = 0; if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count > 0) { playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First(); } HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); List <IMyPlayer> players = new List <IMyPlayer>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); MyAPIGateway.Players.GetPlayers(players); IMyPlayer player = players.FirstOrDefault(x => x.SteamUserId == userId); string result = ""; int count = 0; foreach (IMyEntity entity in entities) { MyCubeGrid grid = entity as MyCubeGrid; if (grid == null) { continue; } if (grid.SmallOwners.Contains(playerId)) { if (result != "") { result += "\r\n"; } if (CubeGrids.IsFullOwner(grid, playerId, player) && !dialog) { result += string.Format("Grid '{0}' at {2}", grid.DisplayName, grid.EntityId, ShowCoordinates(entity.GetPosition())); } else if (CubeGrids.IsFullOwner(grid, playerId, player) && dialog) { result += string.Format("{0} - {1} - {2}bl - {3}", grid.DisplayName, ShowCoordinates(entity.GetPosition()), grid.CubeBlocks.Count, grid.GridSizeEnum); } else { result += string.Format("Grid '{0}'", grid.DisplayName, grid.EntityId); } count++; } } if (dialog) { Communication.DisplayDialog(userId, "User Grid List", "Ships / Stations you own:", result.Replace("\r\n", "|"), "OK"); return(true); } string[] resultLines = result.Split(new string[] { "\r\n" }, StringSplitOptions.None); int pages = ((resultLines.Length - 1) / 6) + 1; if (page > pages) { page = pages; } string output = ""; for (int r = ((page - 1) * 6); r < resultLines.Length && r < ((page) * 6); r++) { string line = resultLines[r]; if (output != "") { output += "\r\n"; } output += line; } Communication.SendPrivateInformation(userId, output); Communication.SendPrivateInformation(userId, string.Format("Displaying page {0} of {1} - {2} grids", page, pages, count)); return(true); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() != 2) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } string blockType = words[0].ToLower(); int blockCount = 0; if (!int.TryParse(words[1], out blockCount)) { Communication.SendPrivateInformation(userId, string.Format("Invalid block count: {0}", words[1])); return(true); } blockCount = Math.Max(blockCount, 1); Communication.SendPrivateInformation(userId, string.Format("Looking for grids that contain more than {0} of type {1}", blockCount, blockType)); HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); HashSet <IMyEntity> entitiesToConfirm = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesUnconnected = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { continue; } if (PluginSettings.Instance.LoginEntityWhitelist.Contains(entity.EntityId.ToString())) { continue; } entitiesToConfirm.Add(entity); } CubeGrids.GetGridsUnconnected(entitiesUnconnected, entitiesToConfirm); foreach (IMyEntity entity in entitiesUnconnected) { IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (gridBuilder == null) { continue; } int count = 0; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.GetId().SubtypeName.ToLower().Contains(blockType)) { count++; } } if (count >= blockCount) { Communication.SendPrivateInformation(userId, string.Format("Found grid '{0}' ({1}) owned by '{5}' which has more than {3} blocks of type {4}. BlockCount={2}", entity.DisplayName, entity.EntityId, ((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder()).CubeBlocks.Count, blockCount, blockType, grid.BigOwners.Count > 0 ? PlayerMap.Instance.GetPlayerItemFromPlayerId(grid.BigOwners.First()).Name : "No one")); entitiesFound.Add(entity); continue; } } /* * foreach(IMyEntity entity in entitiesFound) * { * IMyCubeGrid grid = (IMyCubeGrid)entity; * } */ Communication.SendPrivateInformation(userId, string.Format("Found {0} grids considered to be overlimit", entitiesFound.Count)); return(true); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string command) { string[] words = command.Split(' '); CubeGrids.ScanCleanup(userId, words); return(true); }
public static bool ToggleMedbayGrids(ulong steamId) { if (_checkConceal || _checkReveal) { Communication.SendPrivateInformation(steamId, "Server busy"); return(false); } _checkConceal = true; _checkReveal = true; try { DateTime start = DateTime.Now; // Toggle off HashSet <IMyEntity> entities = new HashSet <IMyEntity>( ); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>( ); try { MyAPIGateway.Entities.GetEntities(entities); } catch { Essentials.Log.Info("Error getting entity list, skipping check"); return(false); } CubeGrids.GetGridsUnconnected(entitiesFound, entities); HashSet <IMyEntity> entitiesToConceal = new HashSet <IMyEntity>( ); FilterEntitiesForMedbayCheck(steamId, entitiesFound, entitiesToConceal); if (entitiesToConceal.Count > 0) { //if (PluginSettings.Instance.DynamicClientConcealEnabled) //{ //ClientEntityManagement.Refresh(steamId); //} Communication.SendClientMessage(steamId, string.Format("/conceal {0}", string.Join(",", entitiesToConceal.Select(x => x.EntityId.ToString( ) + ":" + ((MyObjectBuilder_CubeGrid)x.GetObjectBuilder( )).CubeBlocks.Count.ToString( ) + ":" + x.DisplayName).ToArray( )))); Thread.Sleep(1500); ConcealEntities(entitiesToConceal); //CheckAndRevealEntities(); } if ((DateTime.Now - start).TotalMilliseconds > 2000 && PluginSettings.Instance.DynamicShowMessages) { Essentials.Log.Info("Completed Toggle: {0}ms", (DateTime.Now - start).TotalMilliseconds); } } catch (Exception ex) { Essentials.Log.Error(ex); } finally { _checkConceal = false; _checkReveal = false; } return(true); }
public override bool HandleCommand(ulong userId, string[] words) { if (!PluginSettings.Instance.DockingEnabled) { return(false); } if (words.Length < 1) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } if (m_docking) { Communication.SendPrivateInformation(userId, "Server is busy"); return(true); } m_docking = true; try { string pylonName = string.Join(" ", words); /* * int timeLeft; * if (Entity.CheckCoolDown(pylonName, out timeLeft)) * { * Communication.Message(String.Format("The docking zone '{0}' is on cooldown. Please wait a {1} seconds before trying to dock/undock again.", pylonName, Math.Max(0, timeLeft))); * return; * } */ if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1) { Communication.SendPrivateInformation(userId, $"Unable to find player Id: {userId}"); return(true); } long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First(); Dictionary <string, List <IMyCubeBlock> > testList; List <IMyCubeBlock> beaconList; DockingZone.FindByName(pylonName, out testList, out beaconList, playerId); if (beaconList.Count == 4) { // Check ownership foreach (IMyCubeBlock entityBlock in beaconList) { IMyTerminalBlock terminal = (IMyTerminalBlock)entityBlock; if (!terminal.HasPlayerAccess(playerId)) { Communication.SendPrivateInformation(userId, $"You do not have permission to use '{pylonName}'. You must either own all the beacons or they must be shared with faction."); return(true); } } // Check for bounding box intsection of other docking zones int intersectElement = 0; if (Entity.CheckForIntersection(testList, beaconList, out intersectElement)) { Communication.SendPrivateInformation(userId, $"The docking zone '{pylonName}' intersects with docking zone '{testList.ElementAt( intersectElement ).Key}'. Make sure you place your docking zones so they don't overlap."); return(true); } // Check if ship already docked in this zone IMyCubeBlock e = beaconList[0]; IMyCubeGrid parent = (IMyCubeGrid)e.Parent; long[] beaconListIds = beaconList.Select(b => b.EntityId).ToArray(); long ownerId = beaconList.First().OwnerId; List <DockingItem> checkItems = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count() == 4); if (checkItems.Count >= PluginSettings.Instance.DockingShipsPerZone) { Communication.SendPrivateInformation(userId, $"Docking zone '{pylonName}' already contains the maximum capacity of ships."); return(true); } // Figure out center of docking area, and other distance information double maxDistance = 99; Vector3D vPos = new Vector3D(0, 0, 0); foreach (IMyCubeBlock b in beaconList) { Vector3D beaconPos = Entity.GetBlockEntityPosition(b); vPos += beaconPos; } vPos = vPos / 4; foreach (IMyCubeBlock b in beaconList) { Vector3D beaconPos = Entity.GetBlockEntityPosition(b); maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos)); } // Find ship in docking area IMyCubeGrid dockingEntity = null; HashSet <IMyEntity> cubeGrids = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(cubeGrids, f => f is IMyCubeGrid); }); foreach (IMyCubeGrid gridCheck in cubeGrids) { if (gridCheck.IsStatic || gridCheck == parent) { continue; } double distance = Vector3D.Distance(gridCheck.GetPosition(), vPos); if (distance < maxDistance) { dockingEntity = gridCheck; break; } } // Figure out if the ship fits in docking area, and then save ship if (dockingEntity != null) { // Get bounding box of both the docking zone and docking ship OrientedBoundingBoxD targetBounding = Entity.GetBoundingBox(beaconList); OrientedBoundingBoxD dockingBounding = Entity.GetBoundingBox(dockingEntity); // Make sure the docking zone contains the docking ship. If they intersect or are disjointed, then fail if (!Entity.GreaterThan(dockingBounding.HalfExtent * 2, targetBounding.HalfExtent * 2)) { Communication.SendPrivateInformation(userId, $"The ship '{dockingEntity.DisplayName}' is too large for it's carrier. The ship's bounding box must fit inside the docking zone bounding box!"); return(true); } if (targetBounding.Contains(ref dockingBounding) != ContainmentType.Contains) { Communication.SendPrivateInformation(userId, $"The ship '{dockingEntity.DisplayName}' is not fully inside the docking zone '{pylonName}'. Make sure the ship is fully contained inside the docking zone"); return(true); } // Calculate the mass and ensure the docking ship is less than half the mass of the dock float parentMass = Entity.CalculateMass(parent); float dockingMass = Entity.CalculateMass(dockingEntity); if (dockingMass > parentMass) { Communication.SendPrivateInformation(userId, $"The ship you're trying to dock is too heavy for it's carrier. The ship mass must be less than half the large ship / stations mass! (DM={dockingMass}kg CM={parentMass}kg)"); return(true); } // Check to see if the ship is piloted, if it is, error out. // TODO: Check to see if we can get a real time copy of this entity? List <IMySlimBlock> blocks = new List <IMySlimBlock>(); dockingEntity.GetBlocks(blocks, x => x.FatBlock is MyCockpit); foreach (IMySlimBlock slim in blocks) { //MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)slim.FatBlock.GetObjectBuilderCubeBlock(); var c = (MyShipController)slim.FatBlock; if (c.Pilot != null) { Communication.SendPrivateInformation(userId, $"Ship in docking zone '{pylonName}' has a pilot! Please exit the ship before trying to dock. (Sometimes this can lag a bit. Wait 10 seconds and try again)"); return(true); } } // Save position and rotation information. Some fun stuff here. // Get our dock rotation as a quaternion Quaternion saveQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()); // Transform docked ship's local position by inverse of the the parent (unwinds parent) and save it for when we undock Vector3D savePos = Vector3D.Transform(dockingEntity.GetPosition() - parent.GetPosition(), Quaternion.Inverse(saveQuat)); // Get local rotation of dock ship, and save it for when we undock saveQuat = Quaternion.Inverse(saveQuat) * Quaternion.CreateFromRotationMatrix(dockingEntity.WorldMatrix.GetOrientation()); // Save ship to file and remove FileInfo info = new FileInfo(Path.Combine(Essentials.PluginPath, "Docking", $"docked_{ownerId}_{parent.EntityId}_{dockingEntity.EntityId}.sbc")); if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); } //CubeGridEntity dockingGrid = new CubeGridEntity((MyObjectBuilder_CubeGrid)dockingEntity.GetObjectBuilder(), dockingEntity); MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(dockingEntity); if (gridBuilder == null) { Communication.SendPrivateInformation(userId, $"Failed to load entity for export: {dockingEntity.DisplayName}"); return(true); } // Save item DockingItem dockItem = new DockingItem { DockedEntityId = dockingEntity.EntityId, TargetEntityId = parent.EntityId, PlayerId = ownerId, DockingBeaconIds = beaconList.Select(s => s.EntityId).ToArray( ), DockedName = dockingEntity.DisplayName, SavePos = savePos, SaveQuat = saveQuat }; Docking.Instance.Add(dockItem); // Serialize and save ship to file MyObjectBuilderSerializer.SerializeXML(info.FullName, false, gridBuilder); Wrapper.BeginGameAction(() => dockingEntity.Close( )); Communication.SendPrivateInformation(userId, $"Docked ship '{dockItem.DockedName}' in docking zone '{pylonName}'."); Log.Info("Docked ship \"{0}\" in docking zone \"{1}\". Saved to {2}", dockItem.DockedName, pylonName, info.FullName); /* * // Add a cool down * DockingCooldownItem cItem = new DockingCooldownItem(); * cItem.name = pylonName; * cItem.startTime = DateTime.Now; * PluginDocking.CooldownList.Add(cItem); */ } else { Communication.SendPrivateInformation(userId, $"No ships in docking zone '{pylonName}'."); } } else if (beaconList.Count > 4) { Communication.SendPrivateInformation(userId, $"Too many beacons with the name or another zone with the name '{pylonName}'. Place only 4 beacons to create a zone or try a different zone name."); } else { Communication.SendPrivateInformation(userId, string.Format("Can not locate docking zone '{0}'. There must be 4 beacons with the name '{0}' to create a docking zone. Beacons must be fully built!", pylonName)); } return(true); } catch (SecurityException ex) { Log.Error("Can't access docked ship file.", ex); return(false); } catch (UnauthorizedAccessException ex) { Log.Error("Can't access docked ship file.", ex); return(false); } catch (DirectoryNotFoundException ex) { Log.Error("Directory does not exist", ex); return(false); } catch (IOException ex) { Log.Error(ex); return(false); } finally { m_docking = false; } }
static public void RevealAll( ) { HashSet <IMyEntity> entities = new HashSet <IMyEntity>( ); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities); }); List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>( ); int count = 0; Wrapper.GameAction(() => { foreach (IMyEntity entity in entities) { if (entity.InScene) { continue; } if (!(entity is IMyCubeGrid)) { continue; } MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (builder == null) { continue; } count++; IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (CubeGrids.GetBigOwners(builder).Count > 0) { ownerId = CubeGrids.GetBigOwners(builder).First( ); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } //grid.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); //grid.InScene = true; //grid.CastShadows = true; builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); MyAPIGateway.Entities.RemapObjectBuilder(builder); if (PluginSettings.Instance.DynamicShowMessages) { Essentials.Log.Info("Force Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, builder.EntityId); } IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder); if (newEntity == null) { Essentials.Log.Warn("CreateFromObjectBuilder failed: {0}", builder.EntityId); continue; } //these methods no longer exist. //KEEEEEEEEN! //BaseEntityNetworkManager.BroadcastRemoveEntity( entity, false ); /* * MyAPIGateway.Entities.AddEntity( newEntity ); * addList.Add( newEntity.GetObjectBuilder( ) ); * MyAPIGateway.Multiplayer.SendEntitiesCreated( addList ); * addList.Clear( ); */ MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(newEntity.GetObjectBuilder()); } }); if (PluginSettings.Instance.DynamicShowMessages) { Essentials.Log.Info("Revealed {0} grids", count); } }
static public void RevealAll() { HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities); }); List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>(); int count = 0; Wrapper.GameAction(() => { foreach (IMyEntity entity in entities) { if (entity.InScene) { continue; } if (!(entity is IMyCubeGrid)) { continue; } MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (builder == null) { continue; } count++; IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (CubeGrids.GetBigOwners(builder).Count > 0) { ownerId = CubeGrids.GetBigOwners(builder).First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } //grid.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); //grid.InScene = true; //grid.CastShadows = true; builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); MyAPIGateway.Entities.RemapObjectBuilder(builder); Logging.WriteLineAndConsole("Conceal", string.Format("Force Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, builder.EntityId)); IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder); if (newEntity == null) { Logging.WriteLineAndConsole("Conceal", string.Format("Issue - CreateFromObjectBuilder failed: {0}", newEntity.EntityId)); continue; } BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false); MyAPIGateway.Entities.AddEntity(newEntity, true); addList.Add(newEntity.GetObjectBuilder()); MyAPIGateway.Multiplayer.SendEntitiesCreated(addList); addList.Clear(); } }); Logging.WriteLineAndConsole(string.Format("Revealed {0} grids", count)); }
public static bool ToggleMedbayGrids(ulong steamId) { if (_checkConceal || _checkReveal) { Communication.SendPrivateInformation(steamId, "Server busy"); return(false); } _checkConceal = true; _checkReveal = true; try { DateTime start = DateTime.Now; // Toggle off HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); try { MyAPIGateway.Entities.GetEntities(entities); } catch { Logging.WriteLineAndConsole("CheckAndConcealEntities(): Error getting entity list, skipping check"); return(false); } CubeGrids.GetGridsUnconnected(entitiesFound, entities); HashSet <IMyEntity> entitiesToConceal = new HashSet <IMyEntity>(); foreach (IMyEntity entity in entitiesFound) { if (!(entity is IMyCubeGrid)) { continue; } if (entity.DisplayName.Contains("CommRelay")) { continue; } if (!entity.InScene) { continue; } if (((IMyCubeGrid)entity).GridSizeEnum != MyCubeSize.Small && !PluginSettings.Instance.ConcealIncludeLargeGrids) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId); if (!grid.BigOwners.Contains(playerId) && !grid.SmallOwners.Contains(playerId)) { continue; } bool found = false; // Check to see if grid is close to dock / shipyard foreach (IMyCubeGrid checkGrid in ProcessDockingZone.ZoneCache) { try { if (Vector3D.Distance(checkGrid.GetPosition(), grid.GetPosition()) < 100d) { found = true; break; } } catch { continue; } } if (!found) { // Check for block type rules } if (!found) { entitiesToConceal.Add(entity); } } if (entitiesToConceal.Count > 0) { //if (PluginSettings.Instance.DynamicClientConcealEnabled) //{ //ClientEntityManagement.Refresh(steamId); //} Communication.SendClientMessage(steamId, string.Format("/conceal {0}", string.Join(",", entitiesToConceal.Select(x => x.EntityId.ToString() + ":" + ((MyObjectBuilder_CubeGrid)x.GetObjectBuilder()).CubeBlocks.Count.ToString() + ":" + x.DisplayName).ToArray()))); Thread.Sleep(1500); ConcealEntities(entitiesToConceal); //CheckAndRevealEntities(); } if ((DateTime.Now - start).TotalMilliseconds > 2000) { Logging.WriteLineAndConsole(string.Format("Completed Toggle: {0}ms", (DateTime.Now - start).TotalMilliseconds)); } } catch (Exception ex) { Logging.WriteLineAndConsole(string.Format("CheckAndConceal(): {0}", ex.ToString())); } finally { _checkConceal = false; _checkReveal = false; } return(true); }
private static void ConcealEntity(IMyEntity entity) { int pos = 0; try { if (!entity.InScene) { return; } MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (builder == null) { return; } pos = 1; IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (CubeGrids.GetOwner(builder, out ownerId)) { //ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } pos = 2; if (entity.Physics != null) { entity.Physics.LinearVelocity = Vector3.Zero; entity.Physics.AngularVelocity = Vector3.Zero; } /* * entity.InScene = false; * entity.CastShadows = false; * entity.Visible = false; */ builder.PersistentFlags = MyPersistentEntityFlags2.None; MyAPIGateway.Entities.RemapObjectBuilder(builder); pos = 3; if (RemovedGrids.Contains(entity.EntityId)) { Logging.WriteLineAndConsole("Conceal", string.Format("Concealing - Id: {0} DUPE FOUND - Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, builder.EntityId)); BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false); } else { if (!PluginSettings.Instance.DynamicConcealServerOnly) { /* * if (PluginSettings.Instance.DynamicBlockManagementEnabled) * { * bool enable = false; * lock (BlockManagement.Instance.GridDisabled) * { * if(BlockManagement.Instance.GridDisabled.Contains(entity.EntityId)) * enable = true; * } * * if(enable) * BlockManagement.Instance.EnableGrid((IMyCubeGrid)entity); * } */ IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder); Logging.WriteLineAndConsole("Conceal", string.Format("Start Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, newEntity.EntityId)); if (newEntity == null) { Logging.WriteLineAndConsole("Conceal", string.Format("Issue - CreateFromObjectBuilder failed: {0}", newEntity.EntityId)); return; } RemovedGrids.Add(entity.EntityId); BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false); MyAPIGateway.Entities.AddEntity(newEntity, false); Logging.WriteLineAndConsole("Conceal", string.Format("End Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, newEntity.EntityId)); } else { Logging.WriteLineAndConsole("Conceal", string.Format("Start Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, builder.EntityId)); entity.InScene = false; Logging.WriteLineAndConsole("Conceal", string.Format("End Concealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName, builder.EntityId)); } } } catch (Exception ex) { Logging.WriteLineAndConsole(string.Format("ConcealEntity({1}): {0}", ex.ToString(), pos)); } }
private static void RevealEntity(KeyValuePair <IMyEntity, string> item) { IMyEntity entity = item.Key; string reason = item.Value; //Wrapper.GameAction(() => //{ MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (builder == null) { return; } IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (CubeGrids.GetBigOwners(builder).Count > 0) { ownerId = CubeGrids.GetBigOwners(builder).First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } /* * entity.InScene = true; * entity.CastShadows = true; * entity.Visible = true; */ builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); MyAPIGateway.Entities.RemapObjectBuilder(builder); //builder.EntityId = 0; if (RemovedGrids.Contains(entity.EntityId)) { Logging.WriteLineAndConsole("Conceal", string.Format("Revealing - Id: {0} DUPE FOUND Display: {1} OwnerId: {2} OwnerName: {3} Reason: {4}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, reason)); BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false); } else { if (!PluginSettings.Instance.DynamicConcealServerOnly) { IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder); Logging.WriteLineAndConsole("Conceal", string.Format("Start Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3} Reason: {5}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, newEntity.EntityId, reason)); if (newEntity == null) { Logging.WriteLineAndConsole("Conceal", string.Format("Issue - CreateFromObjectBuilder failed: {0}", newEntity.EntityId)); return; } RemovedGrids.Add(entity.EntityId); BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false); MyAPIGateway.Entities.AddEntity(newEntity, true); /*CC * if (PluginSettings.Instance.DynamicClientConcealEnabled) * { * ClientEntityManagement.AddEntityState(newEntity.EntityId); * } */ builder.EntityId = newEntity.EntityId; List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>(); addList.Add(newEntity.GetObjectBuilder()); MyAPIGateway.Multiplayer.SendEntitiesCreated(addList); Logging.WriteLineAndConsole("Conceal", string.Format("End Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3} Reason: {5}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, newEntity.EntityId, reason)); } else { Logging.WriteLineAndConsole("Conceal", string.Format("Start Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3} Reason: {4}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, reason)); entity.InScene = true; // Send to users, client will remove if doesn't need - this solves login problem /*CC * if (PluginSettings.Instance.DynamicClientConcealEnabled) * { * ClientEntityManagement.AddEntityState(entity.EntityId); * List<MyObjectBuilder_EntityBase> addList = new List<MyObjectBuilder_EntityBase>(); * addList.Add(entity.GetObjectBuilder()); * MyAPIGateway.Multiplayer.SendEntitiesCreated(addList); * } */ Logging.WriteLineAndConsole("Conceal", string.Format("End Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3} Reason: {4}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, reason)); } } //}); }
public static void CheckAndConcealEntities() { if (_checkConceal) { return; } _checkConceal = true; try { DateTime start = DateTime.Now; double distCheck = 0d; double blockRules = 0d; double getGrids = 0d; double co = 0f; ProcessedGrids.Clear(); List <IMyPlayer> players = new List <IMyPlayer>(); HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesFiltered = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); try { MyAPIGateway.Players.GetPlayers(players); } catch (Exception ex) { Logging.WriteLineAndConsole(string.Format("Error getting players list. Check and Conceal failed: {0}", ex.ToString())); return; } try { MyAPIGateway.Entities.GetEntities(entities); } catch { Logging.WriteLineAndConsole("CheckAndConcealEntities(): Error getting entity list, skipping check"); return; } foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } if (!entity.InScene) { continue; } entitiesFiltered.Add(entity); } DateTime getGridsStart = DateTime.Now; CubeGrids.GetGridsUnconnected(entitiesFound, entitiesFiltered); getGrids += (DateTime.Now - getGridsStart).TotalMilliseconds; HashSet <IMyEntity> entitiesToConceal = new HashSet <IMyEntity>(); foreach (IMyEntity entity in entitiesFound) { if (!(entity is IMyCubeGrid)) { continue; } if (entity.DisplayName.Contains("CommRelay")) { continue; } if (entity.Physics == null) // Projection { continue; } if (!entity.InScene) { continue; } if (((IMyCubeGrid)entity).GridSizeEnum != MyCubeSize.Small && !PluginSettings.Instance.ConcealIncludeLargeGrids) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; bool found = false; DateTime distStart = DateTime.Now; foreach (IMyPlayer player in players) { double distance = 0f; if (Entity.GetDistanceBetweenGridAndPlayer(grid, player, out distance)) { if (distance < PluginSettings.Instance.DynamicConcealDistance) { found = true; } } } distCheck += (DateTime.Now - distStart).TotalMilliseconds; if (!found) { // Check to see if grid is close to dock / shipyard foreach (IMyCubeGrid checkGrid in ProcessDockingZone.ZoneCache) { try { if (Vector3D.Distance(checkGrid.GetPosition(), grid.GetPosition()) < 100d) { found = true; break; } } catch { continue; } } } if (!found) { // Check for block type rules DateTime blockStart = DateTime.Now; if (CheckConcealBlockRules(grid, players)) { found = true; } blockRules += (DateTime.Now - blockStart).TotalMilliseconds; } if (!found) { entitiesToConceal.Add(entity); } } DateTime coStart = DateTime.Now; if (entitiesToConceal.Count > 0) { ConcealEntities(entitiesToConceal); } co += (DateTime.Now - coStart).TotalMilliseconds; if ((DateTime.Now - start).TotalMilliseconds > 2000) { Logging.WriteLineAndConsole(string.Format("Completed Conceal Check: {0}ms (gg: {3}, dc: {2} ms, br: {1}ms, co: {4}ms)", (DateTime.Now - start).TotalMilliseconds, blockRules, distCheck, getGrids, co)); } } catch (Exception ex) { Logging.WriteLineAndConsole(string.Format("CheckAndConceal(): {0}", ex.ToString())); } finally { _checkConceal = false; } }
// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string command) { string[] words = command.Split(' '); if (words.Length > 3) { return(false); } if (!words.Any()) { Communication.SendPrivateInformation(userId, GetHelp()); return(true); } int days = -1; if (!int.TryParse(words[0], out days) || days < 0) { Communication.SendPrivateInformation(userId, string.Format("Invalid argument. Days argument must be an integer that is 0 or greater.")); return(true); } // Just assume that anything after the days is going to "ignorenologin" bool removeNoLoginInformation = true; bool removeOwnerless = true; if (words.Count() > 1) { foreach (string word in words) { if (word.ToLower() == "ignorenologin") { removeNoLoginInformation = false; } if (word.ToLower() == "ignoreownerless") { removeOwnerless = false; } } } Communication.SendPrivateInformation(userId, string.Format("Scanning for grids with owners that haven't logged in {0} days. (Must Have Login Info={1})", days, removeNoLoginInformation)); HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(grid.EntityId); MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { continue; } // This entity is protected by whitelist if (PluginSettings.Instance.LoginEntityWhitelist.Length > 0 && PluginSettings.Instance.LoginEntityWhitelist.Contains(grid.EntityId.ToString())) { continue; } if (CubeGrids.GetAllOwners(gridBuilder).Count < 1 && removeOwnerless) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) not owned by anyone.", gridEntity.Name, entity.EntityId)); entitiesFound.Add(entity); continue; } foreach (long player in CubeGrids.GetBigOwners(gridBuilder)) { // This playerId is protected by whitelist if (PluginSettings.Instance.LoginPlayerIdWhitelist.Length > 0 && PluginSettings.Instance.LoginPlayerIdWhitelist.Contains(player.ToString())) { continue; } MyObjectBuilder_Checkpoint.PlayerItem checkItem = PlayerMap.Instance.GetPlayerItemFromPlayerId(player); if (checkItem.IsDead || checkItem.Name == "") { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by dead player - ID: {2}", gridEntity.Name, entity.EntityId, player)); entitiesFound.Add(entity); continue; } PlayerItem item = Players.Instance.GetPlayerById(player); if (item == null) { if (removeNoLoginInformation) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by a player with no login info: {2}", gridEntity.Name, entity.EntityId, checkItem.Name)); entitiesFound.Add(entity); } } else if (item.LastLogin < DateTime.Now.AddDays(days * -1)) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by inactive player: {2}", gridEntity.Name, entity.EntityId, PlayerMap.Instance.GetPlayerItemFromPlayerId(player).Name)); entitiesFound.Add(entity); } } } Communication.SendPrivateInformation(userId, string.Format("Found {0} grids owned by inactive users", entitiesFound.Count)); foreach (IMyEntity entity in entitiesFound) { if (!(entity is IMyCubeGrid)) { continue; } CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids owned by inactive users", entitiesFound.Count)); return(true); }
// admin nobeacon scan public override bool HandleCommand(ulong userId, string[] words) { CubeGrids.ScanCleanup(userId, words); return(true); }
// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string[] words) { HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesToConfirm = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesConnected = new HashSet <IMyEntity>(); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) { continue; } bool found = false; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.TypeId == typeof(MyObjectBuilder_Beacon)) { found = true; break; } } if (!found) { entitiesToConfirm.Add(grid); } } CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId); if (gridEntity == null) { Log.Info("A found entity gridEntity was null!"); continue; } Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, entity.EntityId, General.Vector3DToString(entity.GetPosition()))); } for (int r = entitiesFound.Count - 1; r >= 0; r--) { //MyAPIGateway.Entities.RemoveEntity(entity); IMyEntity entity = entitiesFound.ElementAt(r); CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids with no beacons", entitiesFound.Count)); return(true); }
public override bool HandleCommand(ulong userId, string[] words) { bool showConcealed = true; if (words.Length > 0 && words[0].ToLower() == "revealed") { showConcealed = false; } if (showConcealed) { HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities); }); Communication.SendPrivateInformation(userId, "==== Concealed Entities ==="); int count = 0; foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) { continue; } if (entity.InScene) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (grid.BigOwners.Count > 0) { ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } if (ownerName == "") { ownerName = "No one"; } Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()))); count++; } Communication.SendPrivateInformation(userId, string.Format("Total concealed entities: {0}", count)); } else { HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities); }); Communication.SendPrivateInformation(userId, "==== Revealed Entities ==="); Communication.SendPrivateInformation(userId, "==== Unconnected Entities ==="); HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>(); CubeGrids.GetGridsUnconnected(entitiesFound, entities); int count = 0; List <IMySlimBlock> slimBlocks = new List <IMySlimBlock>(); foreach (IMyEntity entity in entitiesFound) { if (!(entity is IMyCubeGrid)) { continue; } if (!entity.InScene) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (grid.BigOwners.Count > 0) { ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } if (ownerName == "") { ownerName = "No one"; } grid.GetBlocks(slimBlocks, null); Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count)); slimBlocks.Clear(); count++; } Communication.SendPrivateInformation(userId, string.Format("Total unconnected revealed entities: {0}", count)); Communication.SendPrivateInformation(userId, "==== Connected Entities ==="); HashSet <IMyEntity> connectedFound = new HashSet <IMyEntity>(); CubeGrids.GetConnectedGrids(connectedFound); Console.WriteLine("Here: {0} : {1} {2}", connectedFound.Intersect(entitiesFound).Count(), entitiesFound.Count, connectedFound.Count); count = 0; slimBlocks.Clear(); foreach (IMyEntity entity in connectedFound) { if (!(entity is IMyCubeGrid)) { continue; } if (entitiesFound.Contains(entity)) { continue; } if (!entity.InScene) { continue; } if (CubeGrids.GetRecursiveGridList((IMyCubeGrid)entity).Count < 2) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (grid.BigOwners.Count > 0) { ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } if (ownerName == "") { ownerName = "No one"; } grid.GetBlocks(slimBlocks, null); Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count, CubeGrids.GetRecursiveGridList(grid).Count)); //Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count)); slimBlocks.Clear(); count++; } Communication.SendPrivateInformation(userId, string.Format("Total connected revealed entities: {0}", count)); } return(true); }