private bool WormholeTransferInFile(FileInfo fileInfo, Utilities.TransferFileInfo fileTransferInfo, Vector3D gatePosition, BoundingSphereD gate) { Log.Info("processing filetransfer:" + fileTransferInfo.createLogString()); var playerid = MySession.Static.Players.TryGetIdentityId(fileTransferInfo.steamUserId); // defaults to 0 if (playerid <= 0) { Log.Error("couldn't find player with steam id: " + fileTransferInfo.steamUserId); return(false); } if (!MyObjectBuilderSerializer.DeserializeXML(fileInfo.FullName, out MyObjectBuilder_Definitions myObjectBuilder_Definitions)) { Log.Error("error deserializing xml: " + fileInfo.FullName); return(true); // if we cant deserializing the file, we still needs the file to be deleted. } var shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints; if (shipBlueprints == null) { Log.Error("can't find any blueprints in xml: " + fileInfo.FullName); return(true); // Again we need ti to be deleted. } foreach (var shipBlueprint in shipBlueprints) { var grids = shipBlueprint.CubeGrids; if (grids == null || grids.Length == 0) { continue; } var pos = Utilities.FindFreePos(gate, Utilities.FindGridsRadius(grids)); if (pos == null) { Log.Warn("no free space available for grid '" + shipBlueprint.DisplayName + "' at wormhole '" + fileTransferInfo.destinationWormhole + "'"); continue; } if (Utilities.UpdateGridsPositionAndStop(grids, pos)) { foreach (var mygrid in grids) { // takeover ownership foreach (MyObjectBuilder_CubeBlock block in mygrid.CubeBlocks) { block.BuiltBy = playerid; block.Owner = playerid; } foreach (MyObjectBuilder_Cockpit cockpit in mygrid.CubeBlocks.Where(block => block is MyObjectBuilder_Cockpit)) { if (cockpit.Pilot == null || !Config.PlayerRespawn) { cockpit.Pilot = null; continue; } // cannot retreive steamId from cockpit.Pilot anylonger. Looking in the servers player cache if a player with the given steamId exists. List <IMyPlayer> players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); var player = (from a in players where a.IdentityId == (cockpit.Pilot.OwningPlayerIdentityId) select a).FirstOrDefault(); // If no player was found it will continue if (player == null) { Log.Info("No active playerinstance for the pilot"); return(false); } long pilotIdentityId = MyAPIGateway.Multiplayer.Players.TryGetIdentityId(player.SteamUserId); cockpit.Pilot.OwningPlayerIdentityId = pilotIdentityId; var pilotIdentity = MySession.Static.Players.TryGetIdentity(pilotIdentityId); if (pilotIdentity.Character != null) { // if there is a character, kill it if (Config.ThisIp != null && Config.ThisIp != "") { ModCommunication.SendMessageTo(new JoinServerMessage(Config.ThisIp), player.SteamUserId); } KillCharacter(player.SteamUserId); } pilotIdentity.PerformFirstSpawn(); pilotIdentity.SavedCharacters.Clear(); pilotIdentity.SavedCharacters.Add(cockpit.Pilot.EntityId); MyAPIGateway.Multiplayer.Players.SetControlledEntity(player.SteamUserId, cockpit.Pilot as VRage.ModAPI.IMyEntity); } } } List <MyObjectBuilder_EntityBase> objectBuilderList = new List <MyObjectBuilder_EntityBase>(grids.ToList()); MyEntities.RemapObjectBuilderCollection(objectBuilderList); if (objectBuilderList.Count > 1) { if (MyEntities.Load(objectBuilderList, out _)) { fileInfo.Delete(); } } else { foreach (var ob in objectBuilderList) { if (MyEntities.CreateFromObjectBuilderParallel(ob, true) != null) { fileInfo.Delete(); } } } MyVisualScriptLogicProvider.CreateLightning(gatePosition); } return(true); }
public static void RunAnnoyance() { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } var limitItems = BlockLimiterConfig.Instance.AllLimits; AnnoyList.Clear(); if (!limitItems.Any()) { return; } var onlinePlayers = MySession.Static.Players.GetOnlinePlayers(); if (onlinePlayers.Count < 1) { return; } foreach (var player in onlinePlayers) { var steamId = MySession.Static.Players.TryGetSteamId(player.Identity.IdentityId); if (AnnoyList.Contains(steamId)) { continue; } var playerGridIds = new HashSet <long>(player.Grids); var playerFaction = MySession.Static.Factions.GetPlayerFaction(player.Identity.IdentityId); foreach (var item in limitItems) { if (item.IsExcepted(player)) { continue; } foreach (var(id, count) in item.FoundEntities) { if (AnnoyList.Contains(steamId)) { break; } if (count <= item.Limit) { continue; } if (id == player.Identity.IdentityId) { AnnoyList.Add(steamId); break; } if (playerGridIds.Contains(id)) { AnnoyList.Add(steamId); break; } if (playerFaction == null || id != playerFaction.FactionId) { continue; } AnnoyList.Add(steamId); break; } } } if (AnnoyList.Count == 0) { return; } foreach (var(id, time) in AnnoyQueue) { if (Math.Abs(time.Second - DateTime.Now.Second) > BlockLimiterConfig.Instance.AnnoyInterval) { continue; } AnnoyList.Add(id); } foreach (var id in AnnoyList) { try { ModCommunication.SendMessageTo(new NotificationMessage($"{BlockLimiterConfig.Instance.AnnoyMessage}", BlockLimiterConfig.Instance.AnnoyDuration, MyFontEnum.White), id); } catch (Exception exception) { Log.Debug(exception); } Log.Info($"Annoy message sent to {id}"); } Log.Info($"Blocklimiter annoyed {AnnoyList.Count} players"); }
private void WormholeTransferOutFile(string sendto, IMyCubeGrid grid, IMyJumpDrive WormholeDrive, Vector3D gatepoint, List <IMyJumpDrive> WormholeDrives) { if (!Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == WormholeDrive.BlockDefinition.SubtypeId) && !Config.WorkWithAllJD) { return; } Request request = default; try { request = MyAPIGateway.Utilities.SerializeFromXML <Request>(WormholeDrive.CustomData); } catch { } string pickeddestination = default; if (request != null) { if (request.PluginRequest) { if (request.Destination != null) { if (sendto.Split(',').Any(s => s.Trim() == request.Destination.Trim())) { pickeddestination = request.Destination.Trim(); } } Request reply = new Request { PluginRequest = false, Destination = null, Destinations = sendto.Split(',').Select(s => s.Trim()).ToArray() }; WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply); } } else { Request reply = new Request { PluginRequest = false, Destination = null, Destinations = sendto.Split(',').Select(s => s.Trim()).ToArray() }; WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply); } if (Config.AutoSend && sendto.Split(',').Length == 1) { pickeddestination = sendto.Split(',')[0].Trim(); } if (pickeddestination == null) { return; } if (!WormholeDrive.IsWorking || WormholeDrive.CurrentStoredPower != WormholeDrive.MaxStoredPower) { return; } var playerInCharge = MyAPIGateway.Players.GetPlayerControllingEntity(grid); if (playerInCharge == null || !Utilities.HasRightToMove(playerInCharge, grid as MyCubeGrid)) { return; } WormholeDrive.CurrentStoredPower = 0; foreach (var DisablingWormholeDrive in WormholeDrives) { if (Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == DisablingWormholeDrive.BlockDefinition.SubtypeId) || Config.WorkWithAllJD) { DisablingWormholeDrive.Enabled = false; } } List <MyCubeGrid> grids = Utilities.FindGridList(grid.EntityId.ToString(), playerInCharge as MyCharacter, Config.IncludeConnectedGrids); if (grids == null) { return; } if (grids.Count == 0) { return; } MyVisualScriptLogicProvider.CreateLightning(gatepoint); //NEED TO DROP ENEMY GRIDS if (Config.WormholeGates.Any(s => s.Name.Trim() == pickeddestination.Split(':')[0])) { foreach (WormholeGate internalwormhole in Config.WormholeGates) { if (internalwormhole.Name.Trim() == pickeddestination.Split(':')[0].Trim()) { var box = WormholeDrive.GetTopMostParent().WorldAABB; var togatepoint = new Vector3D(internalwormhole.X, internalwormhole.Y, internalwormhole.Z); var togate = new BoundingSphereD(togatepoint, Config.RadiusGate); Utilities.UpdateGridsPositionAndStopLive(WormholeDrive.GetTopMostParent(), Utilities.FindFreePos(togate, (float)(Vector3D.Distance(box.Center, box.Max) + 50))); MyVisualScriptLogicProvider.CreateLightning(togatepoint); } } } else { var destination = pickeddestination.Split(':'); if (3 != destination.Length) { throw new ArgumentException("failed parsing destination '" + destination + "'"); } var transferFileInfo = new Utilities.TransferFileInfo { destinationWormhole = destination[0], steamUserId = playerInCharge.SteamUserId, playerName = playerInCharge.DisplayName, gridName = grid.DisplayName, time = DateTime.Now }; Log.Info("creating filetransfer:" + transferFileInfo.ToString()); var filename = transferFileInfo.createFileName(); List <MyObjectBuilder_CubeGrid> objectBuilders = new List <MyObjectBuilder_CubeGrid>(); foreach (MyCubeGrid mygrid in grids) { if (!(mygrid.GetObjectBuilder(true) is MyObjectBuilder_CubeGrid objectBuilder)) { throw new ArgumentException(mygrid + " has a ObjectBuilder thats not for a CubeGrid"); } objectBuilders.Add(objectBuilder); } MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>(); definition.Id = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename); definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray(); HashSet <ulong> sittingPlayerSteamIds = new HashSet <ulong>(); foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids) { foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks) { cubeBlock.Owner = 0L; cubeBlock.BuiltBy = 0L; if (!Config.ExportProjectorBlueprints) { if (cubeBlock is MyObjectBuilder_ProjectorBase projector) { projector.ProjectedGrids = null; } } if (cubeBlock is MyObjectBuilder_Cockpit cockpit) { if (cockpit.Pilot != null) { List <IMyPlayer> players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); var player = (from a in players where a.IdentityId == (cockpit.Pilot.OwningPlayerIdentityId) select a).FirstOrDefault(); var playerSteamId = player.SteamUserId; sittingPlayerSteamIds.Add(playerSteamId); ModCommunication.SendMessageTo(new JoinServerMessage(destination[1] + ":" + destination[2]), playerSteamId); } } } } MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>(); builderDefinition.ShipBlueprints = new[] { definition }; foreach (var playerSteamId in sittingPlayerSteamIds) { KillCharacter(playerSteamId); } if (MyObjectBuilderSerializer.SerializeXML(Utilities.CreateBlueprintPath(Path.Combine(Config.Folder, admingatesfolder), filename), false, builderDefinition)) { if (Config.GridBackup && !MyObjectBuilderSerializer.SerializeXML(Utilities.CreateBlueprintPath(Path.Combine(Config.Folder, backupFolder), filename), false, builderDefinition)) { Log.Error("Failed to save backup of jumping ship"); } // Saves the game if enabled in config. if (Config.SaveOnExit) { grids.ForEach(b => b.Close()); // (re)Starts the task if it has never been started o´r is done if ((saveOnExitTask is null) || saveOnExitTask.IsCompleted) { saveOnExitTask = Torch.Save(); } } else { grids.ForEach(b => b.Close()); } DirectoryInfo gridDirsent = new DirectoryInfo(Config.Folder + "/" + admingatesconfirmsentfolder); //creates just in case fir send gridDirsent.Create(); File.Create(Utilities.CreateBlueprintPath(gridDirsent.FullName, filename)); } } }
public void Wormholetransferout(string name, string sendto, double xgate, double ygate, double zgate) { Vector3D gatepoint = new Vector3D(xgate, ygate, zgate); BoundingSphereD gate = new BoundingSphereD(gatepoint, Config.RadiusGate); foreach (var entity in MyAPIGateway.Entities.GetTopMostEntitiesInSphere(ref gate)) { var grid = (entity as IMyCubeGrid); if (grid != null) { var WormholeDrives = new List <IMyJumpDrive>(); Log.Warn("test a"); var gts = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid); gts.GetBlocksOfType(WormholeDrives); if (WormholeDrives.Count > 0) { foreach (var WormholeDrive in WormholeDrives) { if (Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == WormholeDrive.BlockDefinition.SubtypeId) || Config.WorkWithAllJD) { Request request = null; try { request = MyAPIGateway.Utilities.SerializeFromXML <Request>(WormholeDrive.CustomData); } catch { } string pickeddestination = null; if (request != null) { if (request.PluginRequest) { if (request.Destination != null) { if (sendto.Split(',').Any(s => s.Trim() == request.Destination.Trim())) { pickeddestination = request.Destination.Trim(); } } Request reply = new Request { PluginRequest = false, Destination = null, Destinations = sendto.Split(',').Select(s => s.Trim()).ToArray() }; WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply); } } else { Request reply = new Request { PluginRequest = false, Destination = null, Destinations = sendto.Split(',').Select(s => s.Trim()).ToArray() }; WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply); } if (Config.AutoSend && sendto.Split(',').Length == 1) { pickeddestination = sendto.Split(',')[0].Trim(); } if (pickeddestination != null) { if (WormholeDrive.IsWorking && WormholeDrive.CurrentStoredPower == WormholeDrive.MaxStoredPower) { var playerInCharge = MyAPIGateway.Players.GetPlayerControllingEntity(entity); if (playerInCharge != null && HasRightToMove(playerInCharge, entity as MyCubeGrid)) { WormholeDrive.CurrentStoredPower = 0; foreach (var DisablingWormholeDrive in WormholeDrives) { if (Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == DisablingWormholeDrive.BlockDefinition.SubtypeId) || Config.WorkWithAllJD) { DisablingWormholeDrive.Enabled = false; } } List <MyCubeGrid> grids = GridFinder.FindGridList(grid.EntityId.ToString(), playerInCharge as MyCharacter, Config.IncludeConnectedGrids); if (grids == null) { return; } if (grids.Count == 0) { return; } Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(gatepoint); //NEED TO DROP ENEMY GRIDS if (Config.WormholeGates.Any(s => s.Name.Trim() == pickeddestination.Split(':')[0])) { foreach (WormholeGate internalwormhole in Config.WormholeGates) { if (internalwormhole.Name.Trim() == pickeddestination.Split(':')[0].Trim()) { var box = WormholeDrive.GetTopMostParent().WorldAABB; var togatepoint = new Vector3D(internalwormhole.X, internalwormhole.Y, internalwormhole.Z); var togate = new BoundingSphereD(togatepoint, Config.RadiusGate); Utilities.UpdateGridsPositionAndStopLive(WormholeDrive.GetTopMostParent(), Utilities.FindFreePos(togate, (float)(Vector3D.Distance(box.Center, box.Max) + 50))); Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(togatepoint); } } } else { var destination = pickeddestination.Split(':'); var filename = destination[0] + "_" + playerInCharge.SteamUserId.ToString() + "_" + LegalCharOnly(playerInCharge.DisplayName) + "_" + LegalCharOnly(grid.DisplayName) + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); List <MyObjectBuilder_CubeGrid> objectBuilders = new List <MyObjectBuilder_CubeGrid>(); foreach (MyCubeGrid mygrid in grids) { if (!(grid.GetObjectBuilder(true) is MyObjectBuilder_CubeGrid objectBuilder)) { throw new ArgumentException(mygrid + " has a ObjectBuilder thats not for a CubeGrid"); } objectBuilders.Add(objectBuilder); } MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>(); definition.Id = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename); definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray(); List <ulong> playerIds = new List <ulong>(); foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids) { foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks) { if (!Config.KeepOriginalOwner) { cubeBlock.Owner = 0L; cubeBlock.BuiltBy = 0L; } if (!Config.ExportProjectorBlueprints) { if (cubeBlock is MyObjectBuilder_ProjectorBase projector) { projector.ProjectedGrids = null; } } if (cubeBlock is MyObjectBuilder_Cockpit cockpit) { if (cockpit.Pilot != null) { var playersteam = cockpit.Pilot.PlayerSteamId; var player = PlayerUtils.GetIdentityByNameOrId(playersteam.ToString()); playerIds.Add(playersteam); ModCommunication.SendMessageTo(new JoinServerMessage(destination[1] + ":" + destination[2]), playersteam); } } } } MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>(); builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition }; foreach (var playerId in playerIds) { var player = PlayerUtils.GetIdentityByNameOrId(playerId.ToString()); player.Character.EnableBag(false); Sandbox.Game.MyVisualScriptLogicProvider.SetPlayersHealth(player.IdentityId, 0); player.Character.Close(); } if (MyObjectBuilderSerializer.SerializeXML(CreatePath(Config.Folder + "/" + admingatesfolder, filename), false, builderDefinition)) { foreach (var delgrid in grids) { delgrid.Close(); } } } } } } } } } } } }
public void Wormholetransferin(string name, double xgate, double ygate, double zgate) { Vector3D gatepoint = new Vector3D(xgate, ygate, zgate); BoundingSphereD gate = new BoundingSphereD(gatepoint, Config.RadiusGate); DirectoryInfo gridDir = new DirectoryInfo(Config.Folder + "/" + admingatesfolder); if (gridDir.Exists) { if (gridDir.GetFiles().Any(s => s.Name.Split('_')[0] == name)) { foreach (var file in gridDir.GetFiles()) { if (file != null) { var filedataarray = file.Name.Split('_'); if (filedataarray[0] == name) { Log.Warn("yay we are going to load file: " + file.Name); var player = PlayerUtils.GetIdentityByNameOrId(filedataarray[1]); if (player != null || Config.KeepOriginalOwner) { var playerid = 0L; if (player != null) { playerid = player.IdentityId; } if (File.Exists(file.FullName)) { Log.Warn("test 1"); if (MyObjectBuilderSerializer.DeserializeXML(file.FullName, out MyObjectBuilder_Definitions myObjectBuilder_Definitions)) { var shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints; if (shipBlueprints != null) { Log.Warn("test 2"); foreach (var shipBlueprint in shipBlueprints) { var grids = shipBlueprint.CubeGrids; if (grids != null && grids.Length > 0) { var pos = Utilities.FindFreePos(gate, Utilities.FindGridsRadius(grids)); if (pos != null) { if (Utilities.UpdateGridsPositionAndStop(grids, pos)) { Log.Warn("test 3"); foreach (var mygrid in grids) { foreach (MyObjectBuilder_CubeBlock block in mygrid.CubeBlocks) { if (!Config.KeepOriginalOwner) { block.BuiltBy = playerid; block.Owner = playerid; } if (block is MyObjectBuilder_Cockpit cockpit) { if (cockpit.Pilot != null) { var seatedplayerid = MyAPIGateway.Multiplayer.Players.TryGetIdentityId(cockpit.Pilot.PlayerSteamId); if (seatedplayerid != -1) { Log.Warn("test 4"); var myplayer = MySession.Static.Players.TryGetIdentity(seatedplayerid); if (seatedplayerid != -1 && Config.PlayerRespawn) { cockpit.Pilot.OwningPlayerIdentityId = seatedplayerid; if (myplayer.Character != null) { if (Config.ThisIp != null && Config.ThisIp != "") { ModCommunication.SendMessageTo(new JoinServerMessage(Config.ThisIp), cockpit.Pilot.PlayerSteamId); } myplayer.Character.EnableBag(false); Sandbox.Game.MyVisualScriptLogicProvider.SetPlayersHealth(seatedplayerid, 0); myplayer.Character.Close(); } myplayer.PerformFirstSpawn(); myplayer.SavedCharacters.Clear(); myplayer.SavedCharacters.Add(cockpit.Pilot.EntityId); MyAPIGateway.Multiplayer.Players.SetControlledEntity(cockpit.Pilot.PlayerSteamId, cockpit.Pilot as VRage.ModAPI.IMyEntity); } else { cockpit.Pilot = null; } } else { cockpit.Pilot = null; } } } } } Log.Warn("test 5"); List <MyObjectBuilder_EntityBase> objectBuilderList = new List <MyObjectBuilder_EntityBase>(grids.ToList()); Log.Warn("test 6"); MyEntities.RemapObjectBuilderCollection(objectBuilderList); Log.Warn("test 7"); if (!(objectBuilderList.Count > 1)) { foreach (var ob in objectBuilderList) { MyEntities.CreateFromObjectBuilderParallel(ob, true); } } else { MyStringId?temp; MyEntities.Load(objectBuilderList, out temp); Log.Warn(temp.ToString()); } Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(gatepoint); file.Delete(); } } else { Log.Warn("Unable to load grid no free space found at Wormhole: " + name); } } } } } } } } } } } } }
public void ListPairNames() { var sb = new StringBuilder(); var allDef = MyDefinitionManager.Static.GetAllDefinitions(); var def = new List <MyDefinitionBase>(); if (Context.Args.Count > 0) { var blockType = Context.Args[0]; foreach (var defBase in allDef) { if (!defBase.Id.TypeId.ToString().Substring(16).Equals(blockType, StringComparison.OrdinalIgnoreCase)) { continue; } def.Add(defBase); } if (!def.Any()) { Context.Respond($"Can't find any definition for {blockType}"); return; } } else { def.AddRange(allDef); } if (!def.Any()) { Context.Respond("Na Bruh!"); return; } sb.AppendLine($"Total of {def.Count} definitions found on server"); var definitionDictionary = new Dictionary <MyModContext, List <string> >(); foreach (var myDefinitionId in def) { if (!MyDefinitionManager.Static.TryGetCubeBlockDefinition(myDefinitionId.Id, out var x)) { continue; } if (myDefinitionId.Context == null) { continue; } if (!definitionDictionary.ContainsKey(myDefinitionId.Context)) { definitionDictionary[myDefinitionId.Context] = new List <string> { x.BlockPairName }; continue; } if (definitionDictionary[myDefinitionId.Context].Contains(x.BlockPairName)) { continue; } definitionDictionary[myDefinitionId.Context].Add(x.BlockPairName); } foreach (var(context, thisList) in definitionDictionary) { sb.AppendLine(context.IsBaseGame ? $"[{thisList.Count} Vanilla blocks]" : $"[{thisList.Count} blocks --- {context.ModName} - {context.ModId}]"); thisList.ForEach(x => sb.AppendLine(x)); sb.AppendLine(); } if (Context.Player == null || Context.Player.IdentityId == 0) { Context.Respond(sb.ToString()); return; } if (Utilities.TryGetAimedBlock(Context.Player, out var panel)) { ((IMyTextSurface)panel).WriteText(sb); return; } ModCommunication.SendMessageTo(new DialogMessage(BlockLimiterConfig.Instance.ServerName, "List of pair names", sb.ToString()), Context.Player.SteamUserId); }
public static bool PatchRequestJump(long entityId, Vector3D jumpTarget, long userId) { MyCubeGrid grid = MyAPIGateway.Entities.GetEntityById(entityId) as MyCubeGrid; if (grid == null) { return(false); } //return false; if (userId == 0) { Log.Info("grid name " + grid.DisplayName); Log.Info(FacUtils.GetOwner(grid) + " grid owner id, requested by 0, which is probably a hacker or some shit, these are the people online at the time"); StringBuilder players = new StringBuilder(); foreach (MyPlayer player in MySession.Static.Players.GetOnlinePlayers()) { if (player.Id != null && player.Id.SteamId != null && player.DisplayName != null) { players.AppendLine(player.Id.SteamId + " " + player.DisplayName); } else { players.AppendLine("Something null here, identity id " + player.Identity.IdentityId); } } Log.Info(players); if (AlliancePlugin.config.DisableJumpsWithId0) { return(false); } } else { Log.Info(FacUtils.GetOwner(grid) + " grid owner id, requested by " + userId + " grid name " + grid.DisplayName); } foreach (JumpZone zone in Zones) { float distance = Vector3.Distance(zone.GetPosition(), grid.PositionComp.GetPosition()); if (distance <= zone.Radius && !zone.AllowExit) { if (zone.GetExcludedExit() != null && zone.AllowExcludedExit) { bool canExit = false; foreach (MyJumpDrive drive in grid.GetFatBlocks().OfType <MyJumpDrive>()) { if (!zone.GetExcludedExit().Contains(drive.BlockDefinition.BlockPairName)) { drive.Enabled = false; } else { canExit = true; } } if (canExit) { // newPos = grid.WorldMatrix.Forward + 1000; //worldMatrix = MatrixD.CreateWorld(newPos, grid.WorldMatrix.Forward, grid.WorldMatrix.Up); return(true); } } NotificationMessage message = new NotificationMessage("You cannot jump out of this area.", 8000, "Red"); //this is annoying, need to figure out how to check the exact world time so a duplicate message isnt possible ModCommunication.SendMessageTo(message, MySession.Static.Players.TryGetSteamId(userId)); return(false); } distance = Vector3.Distance(zone.GetPosition(), jumpTarget); if (distance <= zone.Radius && !zone.AllowEntry) { if (zone.GetExcludedEntry() != null && zone.AllowExcludedEntry) { bool canExit = false; foreach (MyJumpDrive drive in grid.GetFatBlocks().OfType <MyJumpDrive>()) { if (!zone.GetExcludedExit().Contains(drive.BlockDefinition.BlockPairName)) { drive.Enabled = false; } else { canExit = true; } } if (canExit) { //newPos = grid.WorldMatrix.Forward + 1000; // worldMatrix = MatrixD.CreateWorld(newPos, grid.WorldMatrix.Forward, grid.WorldMatrix.Up); return(true); } } NotificationMessage message = new NotificationMessage("You cannot jump into this area.", 8000, "Red"); //this is annoying, need to figure out how to check the exact world time so a duplicate message isnt possible ModCommunication.SendMessageTo(message, MySession.Static.Players.TryGetSteamId(userId)); return(false); } } JumpThing thing = new JumpThing(); //MyCockpit controller = null; //foreach (MyCockpit cockpit in grid.GetFatBlocks().OfType<MyCockpit>()) //{ // if (cockpit.Pilot != null) // { // if (cockpit.Pilot.ControlSteamId.Equals(MySession.Static.Players.TryGetSteamId(userId))) // { // controller = cockpit; // } // } //} //AlliancePlugin.Log.Info("1"); //if (controller != null) //{ // AlliancePlugin.Log.Info("2"); // MatrixD worldMatrix = MatrixD.CreateWorld(controller.WorldMatrix.Translation, controller.WorldMatrix.Forward, controller.WorldMatrix.Up); // Vector3D distance2 = worldMatrix.Forward * 1000; // worldMatrix.Translation += distance2; // thing.matrix = worldMatrix; // thing.gridId = grid.EntityId; // AlliancePlugin.jumpies.Add(thing); // Vector3D? newPosition = MyEntities.FindFreePlace(worldMatrix.Translation, (float)GridManager.FindBoundingSphere(controller.CubeGrid).Radius); // return false; //} return(true); }
private static void SendNotificationTo(string message, ulong target, int disappearTimeMs = 10000) { ModCommunication.SendMessageTo(new NotificationMessage(message, disappearTimeMs, "Red"), target); }
private static void SendDialog(string title, string subtitle, string content, ulong target) { ModCommunication.SendMessageTo(new DialogMessage(title, subtitle, content), target); }
public void ListFaction(string factionTag, string gridNameOrEntityId = null) { IMyFaction faction = FactionUtils.GetIdentityByTag(factionTag); if (faction == null) { Context.Respond("Player not found!"); return; } StringBuilder sb = new StringBuilder(); string gridname = null; int i = 1; var factionMembers = faction.Members; if (gridNameOrEntityId == null) { foreach (long playerIdentity in factionMembers.Keys) { MyIdentity identity = PlayerUtils.GetIdentityById(playerIdentity); Utilities.AddListEntriesToSb(Plugin, sb, playerIdentity, i, true, out i); } } else { var relevantGrids = Utilities.FindRelevantGrids(Plugin, factionMembers.Keys); Utilities.AddListEntriesToSb(relevantGrids, sb, gridNameOrEntityId, out gridname); if (gridname == null) { Context.Respond("Grid not found!"); return; } } if (Context.Player == null) { Context.Respond($"Backed up Grids for Faction {faction.Name} [{faction.Tag}]"); if (gridname != null) { Context.Respond($"Grid {gridname}"); } Context.Respond(sb.ToString()); } else { if (gridname != null) { ModCommunication.SendMessageTo(new DialogMessage("Backed up Grids", $"Grid {gridname}", sb.ToString()), Context.Player.SteamUserId); } else { ModCommunication.SendMessageTo(new DialogMessage("Backed up Grids", $"Faction {faction.Name} [{faction.Tag}]", sb.ToString()), Context.Player.SteamUserId); } } }
private static void SendNotification(string message, int disappearTimeMs = 10000) { ModCommunication.SendMessageToClients(new NotificationMessage(message, disappearTimeMs, "Red")); }
public void Find(string gridNameOrEntityId = null) { string basePath = Plugin.CreatePath(); var identities = MySession.Static.Players.GetAllIdentities(); StringBuilder sb = new StringBuilder(); int i = 1; foreach (var identitiy in identities) { long playerId = identitiy.IdentityId; string path = Plugin.CreatePathForPlayer(basePath, playerId); DirectoryInfo gridDir = new DirectoryInfo(path); DirectoryInfo[] dirList = gridDir.GetDirectories("*", SearchOption.TopDirectoryOnly); List <DirectoryInfo> filteredGrids = new List <DirectoryInfo>(); foreach (DirectoryInfo grid in dirList) { if (!Utilities.Matches(grid, gridNameOrEntityId)) { continue; } filteredGrids.Add(grid); } if (filteredGrids.Count == 0) { continue; } string factionTag = FactionUtils.GetPlayerFactionTag(playerId); if (factionTag != "") { factionTag = " [" + factionTag + "]"; } sb.AppendLine(identitiy.DisplayName + factionTag); foreach (DirectoryInfo grid in filteredGrids) { string dateString = Utilities.GenerateDateString(grid); sb.AppendLine((i++) + " " + grid + " - " + dateString); } } if (Context.Player == null) { Context.Respond($"Find results"); Context.Respond($"for grids matching {gridNameOrEntityId}"); Context.Respond(sb.ToString()); } else { ModCommunication.SendMessageTo(new DialogMessage("Find results", $"for grids matching {gridNameOrEntityId}", sb.ToString()), Context.Player.SteamUserId); } }
public void ListBlockDefinitions() { var sb = new StringBuilder(); var allDef = MyDefinitionManager.Static.GetAllDefinitions(); var def = new List <MyDefinitionBase>(allDef.Where(x => x is MyCubeBlockDefinition).OrderBy(x => x.Id.ToString())); if (Context.Args.Count > 0) { string blockType = Context.Args[0]; def.RemoveAll(x => !x.ToString().Substring(16).Contains(blockType, StringComparison.OrdinalIgnoreCase)); /* * foreach (var defBase in allDef) * { * if (!defBase.Id.TypeId.ToString().Substring(16).Equals(blockType,StringComparison.OrdinalIgnoreCase)) * continue; * def.Add(defBase); * } */ if (!def.Any()) { Context.Respond($"Can't find any definition for {blockType}"); return; } } if (def.Count == 0) { Context.Respond("Reading no definitions. Recheck filter and try again!"); return; } sb.AppendLine($"Total of {def.Count} definitions found on server"); var definitionDictionary = new Dictionary <MyModContext, List <string> >(); foreach (var myDefinitionId in def) { if (myDefinitionId.Context == null) { continue; } if (!definitionDictionary.ContainsKey(myDefinitionId.Context)) { definitionDictionary[myDefinitionId.Context] = new List <string> { myDefinitionId.Id.ToString().Substring(16) }; continue; } if (definitionDictionary[myDefinitionId.Context].Contains(myDefinitionId.Id.ToString().Substring(16))) { continue; } definitionDictionary[myDefinitionId.Context].Add(myDefinitionId.Id.ToString().Substring(16)); } foreach (var(context, thisList) in definitionDictionary.OrderBy(x => x.Key.ModName)) { sb.AppendLine(context.IsBaseGame ? $"[{thisList.Count} Vanilla blocks]" : $"[{thisList.Count} blocks --- {context.ModName} - {context.ModId}]"); thisList.ForEach(x => sb.AppendLine(x)); sb.AppendLine(); } if (Context.Player == null || Context.Player.IdentityId == 0) { Context.Respond(sb.ToString()); return; } if (Utilities.TryGetAimedBlock(Context.Player, out var panel)) { ((IMyTextSurface)panel).WriteText(sb); return; } ModCommunication.SendMessageTo(new DialogMessage(BlockLimiterConfig.Instance.ServerName, "List of block definitions", sb.ToString()), Context.Player.SteamUserId); }
public void GetLimits() { if (!BlockLimiterConfig.Instance.EnableLimits) { Context.Respond("Plugin disabled"); return; } var sb = new StringBuilder(); var limiterLimits = BlockLimiterConfig.Instance.AllLimits.ToList(); if (BlockLimiterConfig.Instance.MaxBlockSizeShips > 0) { sb.AppendLine($"Ship Size Limit = {BlockLimiterConfig.Instance.MaxBlockSizeShips} Blocks"); } if (BlockLimiterConfig.Instance.MaxBlockSizeStations > 0) { sb.AppendLine($"Station Size Limit = {BlockLimiterConfig.Instance.MaxBlockSizeStations} blocks"); } if (BlockLimiterConfig.Instance.MaxBlocksLargeGrid > 0) { sb.AppendLine($"Large Grid Size Limit = {BlockLimiterConfig.Instance.MaxBlocksLargeGrid} blocks"); } if (BlockLimiterConfig.Instance.MaxBlocksSmallGrid > 0) { sb.AppendLine($"Small Grid Size Limits = {BlockLimiterConfig.Instance.MaxBlocksSmallGrid} blocks"); } if (BlockLimiterConfig.Instance.MaxSmallGrids > 0) { sb.AppendLine($"Small Grids Limit = {BlockLimiterConfig.Instance.MaxSmallGrids} small grids per player"); } if (BlockLimiterConfig.Instance.MaxLargeGrids > 0) { sb.AppendLine($"Large Grids Limit = {BlockLimiterConfig.Instance.MaxLargeGrids} large grids per player"); } if (!limiterLimits.Any()) { if (sb.Length == 0) { Context.Respond("No block limits found"); } else { if (Context.Player == null || Context.Player.IdentityId == 0) { Context.Respond(sb.ToString()); return; } ModCommunication.SendMessageTo(new DialogMessage(BlockLimiterConfig.Instance.ServerName, "List of Limits", sb.ToString()), Context.Player.SteamUserId); } return; } sb.AppendLine($"Found {limiterLimits.Count(x=>x.BlockList.Any())} items"); foreach (var item in limiterLimits) { if (item.BlockList.Count == 0) { continue; } var name = string.IsNullOrEmpty(item.Name) ? "No Name" : item.Name; sb.AppendLine(); sb.AppendLine(name); item.BlockList.ForEach(x => sb.Append($"[{x}] ")); sb.AppendLine(); sb.AppendLine($"GridType: {item.GridTypeBlock}"); if (item.LimitFilterType > LimitItem.FilterType.None) { sb.AppendLine($"FilterType : {item.LimitFilterType} {item.LimitFilterOperator} {item.FilterValue}"); } sb.AppendLine($"Limits: {item.Limit}"); sb.AppendLine($"PlayerLimit: {item.LimitPlayers}"); sb.AppendLine($"FactionLimit: {item.LimitFaction}"); sb.AppendLine($"GridLimit: {item.LimitGrids}"); } if (Context.Player == null || Context.Player.IdentityId == 0) { Context.Respond(sb.ToString()); return; } if (Utilities.TryGetAimedBlock(Context.Player, out var panel)) { ((IMyTextSurface)panel).WriteText(sb); return; } ModCommunication.SendMessageTo(new DialogMessage(BlockLimiterConfig.Instance.ServerName, "List of Limits", sb.ToString()), Context.Player.SteamUserId); }
public static void RunAnnoyance() { if (!BlockLimiterConfig.Instance.EnableLimits) { return; } var limitItems = BlockLimiterConfig.Instance.AllLimits; if (!limitItems.Any()) { return; } var onlinePlayers = MySession.Static.Players.GetOnlinePlayers(); if (onlinePlayers.Count < 1) { return; } var annoyList = new List <ulong>(); foreach (var player in onlinePlayers) { var steamId = MySession.Static.Players.TryGetSteamId(player.Identity.IdentityId); if (annoyList.Contains(steamId)) { continue; } foreach (var item in limitItems) { if (Utilities.IsExcepted(player, item)) { continue; } foreach (var(id, count) in item.FoundEntities) { if (id == 0 || Utilities.IsExcepted(id, item)) { continue; } if (id == player.Identity.IdentityId && count > item.Limit) { annoyList.Add(steamId); break; } if (player.Grids.Any(x => x == id)) { annoyList.Add(steamId); break; } var playerFaction = MySession.Static.Factions.GetPlayerFaction(player.Identity.IdentityId); if (playerFaction == null || id != playerFaction.FactionId) { continue; } annoyList.Add(steamId); break; } } } if (annoyList.Count < 1) { return; } foreach (var id in annoyList) { try { ModCommunication.SendMessageTo(new NotificationMessage($"{BlockLimiterConfig.Instance.AnnoyMessage}", BlockLimiterConfig.Instance.AnnoyDuration, MyFontEnum.White), id); } catch (Exception exception) { Log.Debug(exception); } } Log.Info($"Blocklimiter annoyed {annoyList.Count} players"); }
public static Boolean GenerateContract(ulong steamid, long identityid) { if (config.UsingWhitelist) { if (!Whitelist.Contains(steamid)) { DialogMessage m = new DialogMessage("Contract Failure", "Fail", config.WhitelistMessage); ModCommunication.SendMessageTo(m, steamid); return(false); } } if (getActiveContract(steamid) != null) { TruckingPlugin.SendMessage("The Boss", "You already have a contract!", Color.Red, steamid); DialogMessage m = new DialogMessage("Contract fail", "", "You already have a contract, to quit use !contract quit"); ModCommunication.SendMessageTo(m, steamid); return(false); } else { //this code is awful and i want to redo it, probably throwing the generation in a new method and changing this reputation check to just change the amount if (reputation.TryGetValue(steamid, out int rep)) { int potentialMax = 1; string type = "easy"; int min = 1; Random random = new Random(); int chance = random.Next(0, 101); if (rep >= config.HardContractRep && chance <= config.HardContractChance) { min += 2; type = "hard"; potentialMax += 2; } else { if (rep >= config.MediumContractRep && chance <= config.MediumContractChance) { min += 1; type = "medium"; potentialMax += 1; } } //change to max in config file if (potentialMax > 5) { potentialMax = 5; } int max = random.Next(min - 1, potentialMax + 1); if (max == 0) { max = 1; } List <ContractItems> items = getRandomContractItem(type, max); MyGps gps = getDeliveryLocation(); Contract contract = new Contract(steamid, items, gps.Coords.X, gps.Coords.Y, gps.Coords.Z); Database.addNewContract(steamid, contract); StringBuilder contractDetails = new StringBuilder(); contractDetails = TruckingPlugin.MakeContractDetails(contract.getItemsInContract()); gps = contract.GetDeliveryLocation(); MyGpsCollection gpscol = (MyGpsCollection)MyAPIGateway.Session?.GPS; gpscol.SendAddGps(identityid, ref gps); // MyAPIGateway.Session?.GPS.AddGps(Context.Player.IdentityId, gps); DialogMessage m = new DialogMessage("Contract Details", "Obtain and deliver these items", contractDetails.ToString()); ModCommunication.SendMessageTo(m, steamid); } else { List <ContractItems> items = getRandomContractItem("easy", 1); MyGps gps = getDeliveryLocation(); Contract contract = new Contract(steamid, items, gps.Coords.X, gps.Coords.Y, gps.Coords.Z); Database.addNewContract(steamid, contract); StringBuilder contractDetails = new StringBuilder(); contractDetails = TruckingPlugin.MakeContractDetails(contract.getItemsInContract()); gps = contract.GetDeliveryLocation(); MyGpsCollection gpscol = (MyGpsCollection)MyAPIGateway.Session?.GPS; gpscol.SendAddGps(identityid, ref gps); // MyAPIGateway.Session?.GPS.AddGps(Context.Player.IdentityId, gps); DialogMessage m = new DialogMessage("Contract Details", "Obtain and deliver these items", contractDetails.ToString()); ModCommunication.SendMessageTo(m, steamid); } return(true); } }
public void Notify(string message, int disappearTimeMs = 2000, string font = "White") { ModCommunication.SendMessageToClients(new NotificationMessage(message, disappearTimeMs, font)); }
public static void NotifyMessage(string message, ulong steamid) { ModCommunication.SendMessageTo(new NotificationMessage(message, 15000, "Blue"), steamid); }