示例#1
0
        public Orbiter(Mover mover, AllNavigationSettings navSet, string entity)
            : base(mover, navSet)
        {
            this.m_logger = new Logger(GetType().Name, m_controlBlock.CubeBlock);
            this.m_navBlock = m_navSet.Settings_Current.NavigationBlock;

            switch (entity.LowerRemoveWhitespace())
            {
                case "asteroid":
                    SetOrbitClosestVoxel(true);
                    CalcFakeOrbitSpeedForce();
                    m_logger.debugLog("Orbiting asteroid: " + OrbitEntity.getBestName(), Logger.severity.INFO);
                    break;
                case "planet":
                    SetOrbitClosestVoxel(false);
                    OrbitSpeed = (float)Math.Sqrt((OrbitEntity as MyPlanet).GetGravityMultiplier(m_navBlock.WorldPosition) * 9.81f * Altitude);
                    if (OrbitSpeed < 1f)
                        CalcFakeOrbitSpeedForce();
                    m_logger.debugLog("Orbiting planet: " + OrbitEntity.getBestName(), Logger.severity.INFO);
                    break;
                default:
                    m_gridFinder = new GridFinder(navSet, mover.Block, entity, mustBeRecent: true);
                    m_logger.debugLog("Searching for a grid: " + entity, Logger.severity.INFO);
                    break;
            }

            m_navSet.Settings_Task_NavMove.NavigatorMover = this;
        }
示例#2
0
        public WeldGrid(Mover mover, AllNavigationSettings navSet, string gridName, bool shopAfter)
            : base(mover, navSet)
        {
            this.m_logger = new Logger(GetType().Name, mover.Block.CubeBlock);
            this.m_finder = new GridFinder(navSet, m_controlBlock, gridName);
            this.m_shopAfter = shopAfter;

            PseudoBlock navBlock = m_navSet.Settings_Current.NavigationBlock;
            if (navBlock.Block is IMyShipWelder)
                m_navWeld = new MultiBlock<MyObjectBuilder_ShipWelder>(navBlock.Block);
            else
            {
                CubeGridCache cache = CubeGridCache.GetFor(m_controlBlock.CubeGrid);
                if (cache == null)
                {
                    m_logger.debugLog("failed to get cache", Logger.severity.WARNING);
                    return;
                }
                if (cache.CountByType(typeof(MyObjectBuilder_ShipWelder)) < 1)
                {
                    m_logger.debugLog("no welders on ship", Logger.severity.WARNING);
                    return;
                }
                m_navWeld = new MultiBlock<MyObjectBuilder_ShipWelder>(() => m_mover.Block.CubeGrid);
            }

            UpdateTimeout();

            m_navSet.Settings_Task_NavMove.NavigatorMover = this;
        }
示例#3
0
        public Orbiter(Pathfinder pathfinder, string entity)
            : base(pathfinder)
        {
            switch (entity.LowerRemoveWhitespace())
            {
            case "asteroid":
                SetOrbitClosestVoxel(true);
                CalcFakeOrbitSpeedForce();
                Log.DebugLog("Orbiting asteroid: " + OrbitEntity.getBestName(), Logger.severity.INFO);
                break;

            case "planet":
                SetOrbitClosestVoxel(false);
                OrbitSpeed = (float)Math.Sqrt((OrbitEntity as MyPlanet).GetGravityMultiplier(m_navBlock.WorldPosition) * 9.81f * Altitude);
                if (OrbitSpeed < 1f)
                {
                    CalcFakeOrbitSpeedForce();
                }
                Log.DebugLog("Orbiting planet: " + OrbitEntity.getBestName(), Logger.severity.INFO);
                break;

            default:
                m_gridFinder = new GridFinder(pathfinder.NavSet, m_mover.Block, entity, mustBeRecent: true);
                Log.DebugLog("Searching for a grid: " + entity, Logger.severity.INFO);
                break;
            }

            m_navSet.Settings_Task_NavMove.NavigatorMover = this;
        }
示例#4
0
        public Grinder(Mover mover, AllNavigationSettings navSet, float maxRange)
            : base(mover, navSet)
        {
            this.m_logger = new Logger(GetType().Name, () => m_controlBlock.CubeGrid.DisplayName, () => m_stage.ToString());
            this.m_startPostion = m_controlBlock.CubeBlock.GetPosition();
            this.m_longestDimension = m_controlBlock.CubeGrid.GetLongestDim();

            PseudoBlock navBlock = m_navSet.Settings_Current.NavigationBlock;
            m_navGrind = navBlock.Block is Ingame.IMyShipGrinder
                ? new MultiBlock<MyObjectBuilder_ShipGrinder>(navBlock.Block)
                : new MultiBlock<MyObjectBuilder_ShipGrinder>(() => m_mover.Block.CubeGrid);

            if (m_navGrind.FunctionalBlocks == 0)
            {
                m_logger.debugLog("no working grinders", Logger.severity.INFO);
                return;
            }

            m_grinderOffset = m_navGrind.Block.GetLengthInDirection(m_navGrind.Block.GetFaceDirection()[0]) * 0.5f + 2.5f;
            if (m_navSet.Settings_Current.DestinationRadius > m_longestDimension)
            {
                m_logger.debugLog("Reducing DestinationRadius from " + m_navSet.Settings_Current.DestinationRadius + " to " + m_longestDimension, Logger.severity.DEBUG);
                m_navSet.Settings_Task_NavRot.DestinationRadius = m_longestDimension;
            }

            this.m_finder = new GridFinder(m_navSet, mover.Block, maxRange);
            this.m_finder.GridCondition = GridCondition;

            m_navSet.Settings_Task_NavRot.NavigatorMover = this;
            m_navSet.Settings_Task_NavRot.NavigatorRotator = this;
        }
示例#5
0
        public Grinder(Pathfinder pathfinder, float maxRange)
            : base(pathfinder)
        {
            this.m_startPostion     = m_controlBlock.CubeBlock.GetPosition();
            this.m_longestDimension = m_controlBlock.CubeGrid.GetLongestDim();

            PseudoBlock navBlock = m_navSet.Settings_Current.NavigationBlock;

            m_navGrind = navBlock.Block is IMyShipGrinder
                                ? new MultiBlock <MyObjectBuilder_ShipGrinder>(navBlock.Block)
                                : new MultiBlock <MyObjectBuilder_ShipGrinder>(() => m_mover.Block.CubeGrid);

            if (m_navGrind.FunctionalBlocks == 0)
            {
                Log.DebugLog("no working grinders", Logger.severity.INFO);
                return;
            }

            m_grinderOffset = m_navGrind.Block.GetLengthInDirection(m_navGrind.Block.FirstFaceDirection()) * 0.5f + 2.5f;
            if (m_navSet.Settings_Current.DestinationRadius > m_longestDimension)
            {
                Log.DebugLog("Reducing DestinationRadius from " + m_navSet.Settings_Current.DestinationRadius + " to " + m_longestDimension, Logger.severity.DEBUG);
                m_navSet.Settings_Task_NavRot.DestinationRadius = m_longestDimension;
            }

            this.m_finder            = new GridFinder(m_navSet, m_controlBlock, maxRange);
            this.m_finder.OrderValue = OrderValue;
            m_navSet.Settings_Task_NavRot.NavigatorMover   = this;
            m_navSet.Settings_Task_NavRot.NavigatorRotator = this;
            m_navSet.Settings_Task_NavRot.IgnoreEntity     = IgnoreEntity;
        }
示例#6
0
文件: WeldGrid.cs 项目: zrisher/ARMS
        public WeldGrid(Pathfinder pathfinder, string gridName, bool shopAfter)
            : base(pathfinder)
        {
            this.m_finder    = new GridFinder(pathfinder.NavSet, m_controlBlock, gridName);
            this.m_shopAfter = shopAfter;

            PseudoBlock navBlock = m_navSet.Settings_Current.NavigationBlock;

            if (navBlock.Block is IMyShipWelder)
            {
                m_navWeld = new MultiBlock <MyObjectBuilder_ShipWelder>(navBlock.Block);
            }
            else
            {
                CubeGridCache cache = CubeGridCache.GetFor(m_controlBlock.CubeGrid);
                if (cache == null)
                {
                    Log.DebugLog("failed to get cache", Logger.severity.WARNING);
                    return;
                }
                if (cache.CountByType(typeof(MyObjectBuilder_ShipWelder)) < 1)
                {
                    Log.DebugLog("no welders on ship", Logger.severity.WARNING);
                    return;
                }
                m_navWeld = new MultiBlock <MyObjectBuilder_ShipWelder>(() => m_mover.Block.CubeGrid);
            }

            UpdateTimeout();

            m_navSet.Settings_Task_NavMove.NavigatorMover = this;
        }
示例#7
0
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }


        //if (grid == null) grid = MapSpawner.Instance.grid;
    }
        public void Update()
        {
            try {
                UpdateCount++;
                if (UpdateCount > Plugin.Config.DelayTicksBetweenExports)
                {
                    UpdateCount = 0;
                }

                if (UpdateCount != 0)
                {
                    return;
                }

                stopwatch.Start();

                /* We just peek, as we visit this player multiple times. */
                long playerId = stack.Peek();

                ConcurrentBag <List <MyCubeGrid> > gridGroups = GridFinder.FindGridList(playerId, Plugin.Config.BackupConnections);

                string path = Plugin.CreatePath();

                foreach (List <MyCubeGrid> grids in gridGroups)
                {
                    try {
                        /*
                         * if false is returned we already exported the gird and
                         * need to continue with the next one
                         *
                         * If true is returned we added a new grid to the list and therefore
                         * end this tick.
                         */
                        if (BackupSingleGrid(playerId, grids, path))
                        {
                            return;
                        }
                    } catch (Exception e) {
                        Log.Warn(e, "Could not export grids");
                    }
                }

                /* If we reach the end of this for loop this player is basically done. so off of the stack it goes */
                stack.Pop();
            } finally {
                stopwatch.Stop();
            }
        }
        public void ExportGrid(string filename, string gridName = null)
        {
            MyCharacter character = null;

            if (gridName == null)
            {
                if (Context.Player == null)
                {
                    Context.Respond("You need to enter a Grid name where the grid will be spawned at.");
                    return;
                }

                var player = ((MyPlayer)Context.Player).Identity;

                if (player.Character == null)
                {
                    Context.Respond("Player has no character to spawn the grid close to!");
                    return;
                }

                character = player.Character;
            }

            List <MyCubeGrid> grids = GridFinder.FindGridList(gridName, character, Plugin.Config.IncludeConnectedGrids);

            if (grids == null)
            {
                Context.Respond("Multiple grids found. Try to rename them first or try a different subgrid for identification!");
                return;
            }

            if (grids.Count == 0)
            {
                Context.Respond("No grids found. Check your viewing angle or try the correct name!");
                return;
            }

            if (GridManager.SaveGrid(Plugin.CreatePath(filename), filename,
                                     Plugin.Config.KeepOriginalOwner, Plugin.Config.ExportProjectorBlueprints, grids))
            {
                Context.Respond("Export Complete!");
            }
            else
            {
                Context.Respond("Export Failed!");
            }
        }
        public void Save(string gridNameOrEntityId = null)
        {
            MyCharacter character = null;

            if (gridNameOrEntityId == null)
            {
                if (Context.Player == null)
                {
                    Context.Respond("You need to enter a Grid name where the grid will be spawned at.");
                    return;
                }

                var player = ((MyPlayer)Context.Player).Identity;

                if (player.Character == null)
                {
                    Context.Respond("Player has no character to spawn the grid close to!");
                    return;
                }

                character = player.Character;
            }

            List <MyCubeGrid> grids = GridFinder.FindGridList(gridNameOrEntityId, character, Plugin.Config.BackupConnections);

            if (grids == null)
            {
                Context.Respond("Multiple grids found. Try to rename them first or try a different subgrid for identification!");
                return;
            }

            if (grids.Count == 0)
            {
                Context.Respond("No grids found. Check your viewing angle or try the correct name!");
                return;
            }

            if (Plugin.BackupGridsManually(grids, out MyCubeGrid biggestGrid, out long playerId, Context))
            {
                Context.Respond("Export Complete for Grid " + biggestGrid.DisplayName + " (EntityID: #" + biggestGrid.EntityId + ") for PlayerID: #" + playerId);
            }
示例#11
0
        public void Sell(string price, string name)
        {
            if (MyGravityProviderSystem.IsPositionInNaturalGravity(Context.Player.GetPosition()))
            {
                Context.Respond("You cannot use this command in natural gravity!");
                confirmations.Remove(Context.Player.IdentityId);
                return;
            }

            foreach (DeniedLocation denied in AlliancePlugin.HangarDeniedLocations)
            {
                if (Vector3.Distance(Context.Player.GetPosition(), new Vector3(denied.x, denied.y, denied.z)) <= denied.radius)
                {
                    Context.Respond("Cannot sell here, too close to a denied location.");
                    confirmations.Remove(Context.Player.IdentityId);
                    return;
                }
            }
            Int64 amount;

            price = price.Replace(",", "");
            price = price.Replace(".", "");
            price = price.Replace(" ", "");
            try
            {
                amount = Int64.Parse(price);
            }
            catch (Exception)
            {
                Context.Respond("Error parsing amount", Color.Red, "Bank Man");
                return;
            }
            if (amount < 0 || amount == 0)
            {
                Context.Respond("Must be a positive amount", Color.Red, "Bank Man");
                return;
            }
            ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> gridWithSubGrids = GridFinder.FindLookAtGridGroupMechanical(Context.Player.Character);

            List <MyCubeGrid> grids = new List <MyCubeGrid>();


            foreach (var item1 in gridWithSubGrids)
            {
                foreach (MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Node groupNodes in item1.Nodes)
                {
                    MyCubeGrid grid = groupNodes.NodeData;

                    if (FacUtils.IsOwnerOrFactionOwned(grid, Context.Player.IdentityId, false))
                    {
                        if (!grids.Contains(grid))
                        {
                            foreach (MySurvivalKit block in grid.GetFatBlocks().OfType <MySurvivalKit>())
                            {
                                block.CustomData = "Custom Data was cleared.";
                            }
                            foreach (MyMedicalRoom block in grid.GetFatBlocks().OfType <MyMedicalRoom>())
                            {
                                block.CustomData = "Custom Data was cleared.";
                            }
                            List <MyProgrammableBlock> removeThese = new List <MyProgrammableBlock>();
                            foreach (MyProgrammableBlock block in grid.GetFatBlocks().OfType <MyProgrammableBlock>())
                            {
                                removeThese.Add(block);
                            }
                            foreach (MyProgrammableBlock block in removeThese)
                            {
                                grid.RemoveBlock(block.SlimBlock);
                            }
                            grids.Add(grid);
                        }
                    }
                }
            }
            if (grids.Count == 0)
            {
                Context.Respond("Could not find any grids you own. Are you looking directly at it?");
                return;
            }
            MarketItem item = new MarketItem();

            item.Setup(grids, name, amount, Context.Player.SteamUserId);
            if (list.AddItem(item))
            {
                if (GridManager.SaveGridNoDelete(AlliancePlugin.path + "//ShipMarket//Grids//" + item.ItemId + ".xml", item.ItemId.ToString(), false, false, grids))
                {
                    Context.Respond("Added the item to the market!");

                    utils.WriteToJsonFile <MarketItem>(AlliancePlugin.path + "//ShipMarket//ForSale//" + item.ItemId + ".json", item);
                    foreach (MyCubeGrid grid in grids)
                    {
                        if (grid != null)
                        {
                            grid.Close();
                        }
                    }
                }
            }
            else
            {
                Context.Respond("Failed to add the grid to the market. Try again.");
            }
        }
示例#12
0
		public FlyToGrid(Mover mover, AllNavigationSettings navSet, string targetGrid,
			AttachedGrid.AttachmentKind allowedAttachment = AttachedGrid.AttachmentKind.Permanent)
			: base(mover, navSet)
		{
			this.m_logger = new Logger(GetType().Name, m_controlBlock.CubeBlock, () => m_landingState.ToString());
			this.m_targetBlock = m_navSet.Settings_Current.DestinationBlock;
			string blockName = m_targetBlock == null ? null : m_targetBlock.BlockName;
			this.m_gridFinder = new GridFinder(m_navSet, m_mover.Block, targetGrid, blockName, allowedAttachment);
			this.m_contBlock = m_navSet.Settings_Commands.NavigationBlock;

			PseudoBlock landingBlock = m_navSet.Settings_Current.LandingBlock;
			m_navBlock = landingBlock ?? m_navSet.Settings_Current.NavigationBlock;

			if (landingBlock != null)
			{
				if (landingBlock.Block is IMyFunctionalBlock)
					m_landingState = LandingState.Approach;
				else
				{
					m_logger.debugLog("landingBlock is not functional, player error? : " + landingBlock.Block.DisplayNameText, "FlyToGrid()", Logger.severity.INFO);
					m_landingState = LandingState.None;
				}

				if (m_targetBlock == null)
				{
					if (!(landingBlock.Block is IMyLandingGear))
					{
						m_logger.debugLog("cannot land block without a target", "FlyToGrid()", Logger.severity.INFO);
						m_landingState = LandingState.None;
					}
					else
					{
						m_logger.debugLog("golden retriever mode enabled", "FlyToGrid()", Logger.severity.INFO);
						m_landGearWithoutTargetBlock = true;
					}
				}
				else if (landingBlock.Block is Ingame.IMyShipConnector)
				{
					m_gridFinder.BlockCondition = block => {
						Ingame.IMyShipConnector connector = block as Ingame.IMyShipConnector;
						return connector != null && (!connector.IsConnected || connector.OtherConnector == m_navBlock.Block);
					};
					m_landingDirection = m_targetBlock.Forward ?? Base6Directions.GetFlippedDirection(landingBlock.Block.GetFaceDirection()[0]);
				}
				else if (landingBlock.Block is IMyShipMergeBlock)
				{
					m_gridFinder.BlockCondition = block => block is IMyShipMergeBlock;
					m_landingDirection = m_targetBlock.Forward ?? Base6Directions.GetFlippedDirection(landingBlock.Block.GetFaceDirection()[0]);
					(landingBlock.Block as IMyShipMergeBlock).BeforeMerge += MergeBlock_BeforeMerge;
				}
				else if (m_targetBlock.Forward.HasValue)
					m_landingDirection = m_targetBlock.Forward.Value;
				else
				{
					m_logger.debugLog("Player failed to specify landing direction and it could not be determined.", "FlyToGrid()", Logger.severity.INFO);
					m_landingState = LandingState.None;
				}

				if (m_landingState != LandingState.None)
				{
					float minDestRadius = m_controlBlock.CubeGrid.GetLongestDim() * 5f;
					if (m_navSet.Settings_Current.DestinationRadius < minDestRadius)
					{
						m_logger.debugLog("Increasing DestinationRadius from " + m_navSet.Settings_Current.DestinationRadius + " to " + minDestRadius, "FlyToGrid()", Logger.severity.DEBUG);
						m_navSet.Settings_Task_NavRot.DestinationRadius = minDestRadius;
					}

					new UnLander(mover, navSet, landingBlock);

					m_landingHalfSize = landingBlock.Block.GetLengthInDirection(landingBlock.Block.LocalMatrix.GetClosestDirection(landingBlock.LocalMatrix.Forward)) * 0.5f;
					m_logger.debugLog("m_landing direction: " + m_landingDirection + ", m_landingBlockSize: " + m_landingHalfSize, "FlyToGrid()");
				}
			}

			m_navSet.Settings_Task_NavMove.NavigatorMover = this;
		}
        public void Upgrade(Boolean upgrade = false)
        {
            if (!AlliancePlugin.config.HangarEnabled)
            {
                Context.Respond("Hangar not enabled.");
                return;
            }
            if (Context.Player != null)
            {
                IMyFaction faction = FacUtils.GetPlayersFaction(Context.Player.IdentityId);
                if (faction == null)
                {
                    ShipyardCommands.SendMessage("[Hangar]", " You arent in a faction.", Color.Red, (long)Context.Player.SteamUserId);
                    return;
                }
                Alliance alliance = AlliancePlugin.GetAlliance(faction as MyFaction);
                if (alliance == null)
                {
                    Context.Respond("You are not a member of an alliance with an unlocked shipyard.");
                    return;
                }
                if (AlliancePlugin.HasFailedUpkeep(alliance))
                {
                    Context.Respond("Alliance failed to pay upkeep. Upgrades disabled.");
                    return;
                }
                if (!alliance.hasUnlockedHangar)
                {
                    ShipyardCommands.SendMessage("[Alliance Hangar]", "To unlock use !ah unlock", Color.Cyan, (long)Context.Player.SteamUserId);
                    return;
                }
                HangarData  hangar = alliance.LoadHangar();
                UpgradeCost cost   = new UpgradeCost();
                if (!upgrade)
                {
                    ShipyardCommands.SendMessage("[Alliance Hangar]", "To upgrade use !ah upgrade true ,while looking at an owned grid.", Color.Cyan, (long)Context.Player.SteamUserId);
                    StringBuilder sb = new StringBuilder();


                    try
                    {
                        cost = slotUpgrades[hangar.SlotUpgradeNum += 1];
                    }
                    catch (Exception ex)
                    {
                        Context.Respond("Cannot upgrade any further as there are no more defined upgrade files.");
                        return;
                    }
                    if (cost != null)
                    {
                        if (cost.MoneyRequired > 0)
                        {
                            ShipyardCommands.SendMessage("[Alliance Hangar]", "SC Cost for next slot upgrade " + String.Format("{0:n0}", cost.MoneyRequired), Color.Cyan, (long)Context.Player.SteamUserId);
                        }
                        if (cost.MetaPointCost > 0)
                        {
                            ShipyardCommands.SendMessage("[Alliance Hangar]", "Metapoint cost for next slot upgrade " + cost.MetaPointCost, Color.Cyan, (long)Context.Player.SteamUserId);
                        }
                        sb.AppendLine("Items required.");
                        foreach (KeyValuePair <MyDefinitionId, int> id in cost.itemsRequired)
                        {
                            sb.AppendLine(id.Key.ToString() + " - " + id.Value);
                        }
                        Context.Respond(sb.ToString());
                    }
                }
                else
                {
                    ConcurrentBag <MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Group> gridWithSubGrids = GridFinder.FindLookAtGridGroupMechanical(Context.Player.Character);


                    List <MyCubeGrid> grids = new List <MyCubeGrid>();
                    foreach (var item in gridWithSubGrids)
                    {
                        foreach (MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Node groupNodes in item.Nodes)
                        {
                            MyCubeGrid grid = groupNodes.NodeData;



                            if (grid.Projector != null)
                            {
                                continue;
                            }

                            if (FacUtils.GetPlayersFaction(FacUtils.GetOwner(grid)) != null)
                            {
                                if (FacUtils.InSameFaction(FacUtils.GetOwner(grid), Context.Player.IdentityId))
                                {
                                    if (!grids.Contains(grid))
                                    {
                                        grids.Add(grid);
                                    }
                                }
                            }
                            else
                            {
                                if (FacUtils.GetOwner(grid).Equals(Context.Player.Identity.IdentityId))
                                {
                                    if (!grids.Contains(grid))
                                    {
                                        grids.Add(grid);
                                    }
                                }
                            }
                        }
                    }
                    List <VRage.Game.ModAPI.IMyInventory> invents = new List <VRage.Game.ModAPI.IMyInventory>();
                    foreach (MyCubeGrid grid in grids)
                    {
                        invents.AddList(ShipyardCommands.GetInventories(grid));
                    }

                    if (hangar.SlotsAmount >= AlliancePlugin.config.MaxHangarSlots)
                    {
                        Context.Respond("Cannot upgrade any further");
                        return;
                    }

                    try
                    {
                        cost = slotUpgrades[hangar.SlotUpgradeNum += 1];
                    }
                    catch (Exception)
                    {
                        Context.Respond("Cannot upgrade any further as there are no more defined upgrade files.");
                        return;
                    }
                    if (cost != null)
                    {
                        if (cost.MetaPointCost > 0)
                        {
                            if (alliance.CurrentMetaPoints < cost.MetaPointCost)
                            {
                                Context.Respond("Cannot afford the meta point cost of " + cost.MetaPointCost);
                                return;
                            }
                        }
                        if (cost.MoneyRequired > 0)
                        {
                            if (EconUtils.getBalance(Context.Player.IdentityId) >= cost.MoneyRequired)
                            {
                                if (ShipyardCommands.ConsumeComponents(invents, cost.itemsRequired, Context.Player.SteamUserId))
                                {
                                    alliance.CurrentMetaPoints -= cost.MetaPointCost;
                                    EconUtils.takeMoney(Context.Player.IdentityId, cost.MoneyRequired);
                                    hangar.SlotsAmount = (int)cost.NewLevel;
                                    hangar.SlotUpgradeNum++;
                                    hangar.SaveHangar(alliance);
                                    AlliancePlugin.SaveAllianceData(alliance);
                                    ShipyardCommands.SendMessage("[Alliance Hangar]", "Upgrading slots. You were charged: " + String.Format("{0:n0}", cost.MoneyRequired), Color.LightBlue, (long)Context.Player.SteamUserId);
                                }
                            }
                            else
                            {
                                ShipyardCommands.SendMessage("[Alliance Hangar]", "You cant afford the upgrade price of: " + String.Format("{0:n0}", cost.MoneyRequired), Color.Red, (long)Context.Player.SteamUserId);
                            }
                        }
                        else
                        {
                            if (ShipyardCommands.ConsumeComponents(invents, cost.itemsRequired, Context.Player.SteamUserId))
                            {
                                alliance.CurrentMetaPoints -= cost.MetaPointCost;
                                hangar.SlotsAmount          = (int)cost.NewLevel;
                                hangar.SlotUpgradeNum++;
                                hangar.SaveHangar(alliance);
                                AlliancePlugin.SaveAllianceData(alliance);
                            }
                        }
                    }
                    else
                    {
                        Context.Respond("Error loading upgrade details.");
                        return;
                    }
                }
            }
        }
        public void SaveToHangar()
        {
            if (!AlliancePlugin.config.HangarEnabled)
            {
                Context.Respond("Alliance hangar is not enabled.");
                return;
            }
            if (MySession.Static.IsSaveInProgress)
            {
                Context.Respond("World is saving! Try again soon.");
                return;
            }
            if (cooldowns.TryGetValue(Context.Player.IdentityId, out DateTime value))
            {
                if (DateTime.Now <= value)
                {
                    Context.Respond(GetCooldownMessage(value));
                    return;
                }
                else
                {
                    cooldowns[Context.Player.IdentityId] = DateTime.Now.AddSeconds(60);
                }
            }
            else
            {
                cooldowns.Add(Context.Player.IdentityId, DateTime.Now.AddSeconds(60));
            }
            if (MyGravityProviderSystem.IsPositionInNaturalGravity(Context.Player.GetPosition()))
            {
                Context.Respond("You cannot use this command in natural gravity!");
                return;
            }

            foreach (DeniedLocation denied in AlliancePlugin.HangarDeniedLocations)
            {
                if (Vector3.Distance(Context.Player.GetPosition(), new Vector3(denied.x, denied.y, denied.z)) <= denied.radius)
                {
                    Context.Respond("Cannot hangar here! Too close to a denied location.");
                    return;
                }
            }
            Boolean console = false;

            if (Context.Player == null)
            {
                console = true;
            }
            MyFaction fac = MySession.Static.Factions.GetPlayerFaction(Context.Player.IdentityId);

            if (fac == null)
            {
                Context.Respond("You must be in a faction to use alliance features.");
                return;
            }
            Alliance alliance = AlliancePlugin.GetAlliance(fac);

            if (alliance == null)
            {
                Context.Respond("You are not a member of an alliance.");
                return;
            }
            if (AlliancePlugin.HasFailedUpkeep(alliance))
            {
                Context.Respond("Alliance failed to pay upkeep. Upgrades disabled.");
                return;
            }
            if (!alliance.HasAccess(Context.Player.SteamUserId, AccessLevel.HangarSave))
            {
                Context.Respond("Current rank does not have access to hangar save.");
                return;
            }
            if (alliance.hasUnlockedHangar)
            {
                HangarData hangar = alliance.LoadHangar();
                if (hangar == null)
                {
                    Context.Respond("Error loading the hangar.");
                    return;
                }
                string name = "";
                int    pcu  = 0;
                if (hangar.getAvailableSlot() > 0)
                {
                    ConcurrentBag <MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group> gridWithSubGrids = GridFinder.FindLookAtGridGroup(Context.Player.Character);
                    List <MyCubeGrid> grids = new List <MyCubeGrid>();
                    foreach (var item in gridWithSubGrids)
                    {
                        foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in item.Nodes)
                        {
                            MyCubeGrid grid = groupNodes.NodeData;



                            if (grid.Projector != null)
                            {
                                continue;
                            }
                            if (FacUtils.IsOwnerOrFactionOwned(grid, Context.Player.IdentityId, true))
                            {
                                pcu += grid.BlocksPCU;
                                foreach (MyProjectorBase proj in grid.GetFatBlocks().OfType <MyProjectorBase>())
                                {
                                    proj.Clipboard.Clear();
                                }
                                grids.Add(grid);

                                if (name == "")
                                {
                                    name = grid.DisplayName;
                                    name = name.Replace("/", "");
                                    name = name.Replace("-", "");
                                    name = name.Replace("\\", "");
                                }
                            }
                            else
                            {
                                Context.Respond("The grid you are looking at includes a grid that isnt owned by you or a faction member.");
                                return;
                            }
                        }
                    }
                    if (grids.Count == 0)
                    {
                        Context.Respond("Could not find grid.");
                        return;
                    }
                    if (name == "")
                    {
                        name = "Temporary Name";
                    }
                    if (pcu >= AlliancePlugin.config.MaxHangarSlotPCU)
                    {
                        Context.Respond("PCU is greater than the configured maximum");
                        return;
                    }
                    bool result = hangar.SaveGridToHangar(name + "_" + string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now), Context.Player.SteamUserId, alliance, Context.Player.Character.PositionComp.GetPosition(), fac, grids, Context.Player.IdentityId);
                    if (!result)
                    {
                        Context.Respond("Could not save. Are enemies within 15km?");
                    }
                    else
                    {
                        Context.Respond("Grid saved.");

                        foreach (MyCubeGrid grid in grids)
                        {
                            if (grid != null)
                            {
                                grid.Close();
                            }
                        }
                    }
                }
                else
                {
                    Context.Respond("Hangar is full, to upgrade use !ah upgrade true.");
                }
            }
            else
            {
                Context.Respond("Alliance has not unlocked the hangar to unlock use !ah unlock.");
            }
        }
        public void UnlockHangar()
        {
            if (!AlliancePlugin.config.HangarEnabled)
            {
                Context.Respond("Alliance hangar is not enabled.");
                return;
            }
            Boolean console = false;

            if (Context.Player == null)
            {
                console = true;
            }
            MyFaction fac = MySession.Static.Factions.GetPlayerFaction(Context.Player.IdentityId);

            if (fac == null)
            {
                Context.Respond("You must be in a faction to use alliance features.");
                return;
            }
            Alliance alliance = AlliancePlugin.GetAlliance(fac);

            if (alliance == null)
            {
                Context.Respond("You are not a member of an alliance.");
                return;
            }
            if (AlliancePlugin.HasFailedUpkeep(alliance))
            {
                Context.Respond("Alliance failed to pay upkeep. Upgrades disabled.");
                return;
            }
            if (!alliance.hasUnlockedHangar)
            {
                ConcurrentBag <MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group> gridWithSubGrids = GridFinder.FindLookAtGridGroup(Context.Player.Character);


                List <MyCubeGrid> grids = new List <MyCubeGrid>();
                foreach (var item in gridWithSubGrids)
                {
                    foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in item.Nodes)
                    {
                        MyCubeGrid grid = groupNodes.NodeData;



                        if (grid.Projector != null)
                        {
                            continue;
                        }

                        if (FacUtils.GetPlayersFaction(FacUtils.GetOwner(grid)) != null)
                        {
                            if (FacUtils.InSameFaction(FacUtils.GetOwner(grid), Context.Player.IdentityId))
                            {
                                if (!grids.Contains(grid))
                                {
                                    grids.Add(grid);
                                }
                            }
                        }
                        else
                        {
                            if (FacUtils.GetOwner(grid).Equals(Context.Player.Identity.IdentityId))
                            {
                                if (!grids.Contains(grid))
                                {
                                    grids.Add(grid);
                                }
                            }
                        }
                    }
                }
                //Do stuff with taking components from grid storage
                //GridCosts localGridCosts = GetComponentsAndCost(projectedGrid);
                //gridCosts.setComponents(localGridCosts.getComponents());

                UpgradeCost cost = new UpgradeCost();
                List <VRage.Game.ModAPI.IMyInventory> invents = new List <VRage.Game.ModAPI.IMyInventory>();
                foreach (MyCubeGrid grid in grids)
                {
                    invents.AddList(ShipyardCommands.GetInventories(grid));
                }


                cost = ShipyardCommands.LoadUnlockCost(AlliancePlugin.path + "//HangarUnlockCost.txt");
                if (cost != null)
                {
                    if (cost.MetaPointCost > 0)
                    {
                        if (alliance.CurrentMetaPoints < cost.MetaPointCost)
                        {
                            Context.Respond("Cannot afford the meta point cost of " + cost.MetaPointCost);
                            return;
                        }
                    }
                    if (cost.MoneyRequired > 0)
                    {
                        if (EconUtils.getBalance(Context.Player.IdentityId) >= cost.MoneyRequired)
                        {
                            if (ShipyardCommands.ConsumeComponents(invents, cost.itemsRequired, Context.Player.SteamUserId))
                            {
                                alliance.CurrentMetaPoints -= cost.MetaPointCost;
                                EconUtils.takeMoney(Context.Player.IdentityId, cost.MoneyRequired);
                                alliance.hasUnlockedHangar = true;
                                HangarData hangar = alliance.LoadHangar();

                                AlliancePlugin.SaveAllianceData(alliance);
                                ShipyardCommands.SendMessage("[Alliance Hangar]", "Unlocking the hangar. You were charged: " + String.Format("{0:n0}", cost.MoneyRequired) + " and components taken", Color.Green, (long)Context.Player.SteamUserId);
                            }
                        }
                        else
                        {
                            ShipyardCommands.SendMessage("[Alliance Hangar]", "You cant afford the upgrade price of: " + String.Format("{0:n0}", cost.MoneyRequired), Color.Red, (long)Context.Player.SteamUserId);
                        }
                    }
                    else
                    {
                        if (ShipyardCommands.ConsumeComponents(invents, cost.itemsRequired, Context.Player.SteamUserId))
                        {
                            alliance.CurrentMetaPoints -= cost.MetaPointCost;
                            alliance.hasUnlockedHangar  = true;
                            HangarData hangar = alliance.LoadHangar();

                            AlliancePlugin.SaveAllianceData(alliance);
                        }
                    }
                }
                else
                {
                    Context.Respond("Error loading upgrade details.");
                    return;
                }
            }
        }
示例#16
0
        private static void FillContainer()
        {
            if (count == 16)
            {
                SendMessageTemp("PvP Event", "Event is over", Color.Red);
                bTimer.Close();
                return;
            }
            count++;
            MyCubeGrid TechGrid = null;
            ConcurrentBag <MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group> groups = GridFinder.FindGridGroup(gridName);

            Parallel.ForEach(MyCubeGridGroups.Static.Physical.Groups, group =>
            {
                foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes)
                {
                    MyCubeGrid grid = groupNodes.NodeData;
                    //does the grid have the same name as the input
                    bool found = false;

                    foreach (VRage.Game.ModAPI.IMySlimBlock block in grid.GetBlocks())
                    {
                        if (block != null && block.BlockDefinition.Id.SubtypeName.Contains("PrizeboxD") && grid.DisplayName.Equals(gridName))
                        {
                            TechGrid = grid;
                            found    = true;
                        }
                    }
                    if (!found)
                    {
                        continue;
                    }
                    break;
                }
            });
            if (TechGrid != null)
            {
                Sandbox.ModAPI.IMyTerminalBlock container = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(TechGrid).GetBlockWithName("Tech Container") as IMyTerminalBlock;
                Random random = new Random();
                int    num    = random.Next(100);
                if (num <= 1)
                {
                    if (!billion)
                    {
                        container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("50000000"), new MyObjectBuilder_PhysicalObject()
                        {
                            SubtypeName = "SpaceCredit"
                        });
                        SendMessageTemp("PvP " + gridName, "50 Million SC.", Color.Red);

                        billion = true;
                    }
                    else
                    {
                        container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("10000000"), new MyObjectBuilder_PhysicalObject()
                        {
                            SubtypeName = "SpaceCredit"
                        });
                        SendMessageTemp("PvP " + gridName, "10 Million SC.", Color.Red);
                        return;
                    }
                    return;
                }
                if (num <= 50)
                {
                    container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("10000000"), new MyObjectBuilder_PhysicalObject()
                    {
                        SubtypeName = "SpaceCredit"
                    });
                    SendMessageTemp("PvP " + gridName, "10 Million SC.", Color.Red);
                    return;
                }
                else
                {
                    num = random.Next(100);
                    if (num <= 10)
                    {
                        int num2 = random.Next(100);
                        if (num2 <= 10)
                        {
                            container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("50"), new MyObjectBuilder_Component()
                            {
                                SubtypeName = "Tech8x"
                            });
                            SendMessageTemp("PvP " + gridName, "50 Exotic", Color.Red);
                        }
                        else
                        {
                            container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("10"), new MyObjectBuilder_Component()
                            {
                                SubtypeName = "Tech8x"
                            });
                            SendMessageTemp("PvP " + gridName, "10 Exotic", Color.Red);
                        }
                        return;
                    }
                    if (num <= 30)
                    {
                        int num2 = random.Next(100);
                        if (num2 <= 40)
                        {
                            container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("75"), new MyObjectBuilder_Component()
                            {
                                SubtypeName = "Tech4x"
                            });
                            SendMessageTemp("PvP " + gridName, "75 Rare", Color.Red);
                        }
                        else
                        {
                            container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("25"), new MyObjectBuilder_Component()
                            {
                                SubtypeName = "Tech4x"
                            });
                            SendMessageTemp("PvP " + gridName, "25 Rare", Color.Red);
                        }
                        return;
                    }
                    if (num <= 100)
                    {
                        int num2 = random.Next(100);
                        if (num2 <= 50)
                        {
                            container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("100"), new MyObjectBuilder_Component()
                            {
                                SubtypeName = "Tech2x"
                            });
                            SendMessageTemp("PvP " + gridName, "100 Common", Color.Red);
                        }
                        else
                        {
                            container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("50"), new MyObjectBuilder_Component()
                            {
                                SubtypeName = "Tech2x"
                            });
                            SendMessageTemp("PvP " + gridName, "50 Common", Color.Red);
                        }
                        return;
                    }
                }
            }
        }
示例#17
0
        private void AutoHangarWorker(Hangar Plugin)
        {
            //Significant performance increase
            if (MySession.Static.Ready)
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                List <MyCubeGrid> ExportedGrids          = new List <MyCubeGrid>();
                List <MyIdentity> ExportPlayerIdentities = new List <MyIdentity>();

                Hangar.Debug("AutoHangar: Getting Players!");
                var PlayerIdentities = MySession.Static.Players.GetAllIdentities().OfType <MyIdentity>();


                foreach (MyIdentity player in PlayerIdentities)
                {
                    if (player == null)
                    {
                        continue;
                    }

                    DateTime LastLogin;
                    LastLogin = player.LastLoginTime;

                    ulong SteamID = MySession.Static.Players.TryGetSteamId(player.IdentityId);
                    if (LastLogin.AddDays(Plugin.Config.AutoHangarDayAmount) < DateTime.Now)
                    {
                        //AutoHangarBlacklist
                        if (!Plugin.Config.AutoHangarPlayerBlacklist.Any(x => x.SteamID == SteamID))
                        {
                            ExportPlayerIdentities.Add(player);
                        }
                    }
                }

                Hangar.Debug("AutoHangar: Total players to check-" + ExportPlayerIdentities.Count());
                int GridCounter = 0;

                //This gets all the grids
                foreach (MyIdentity player in ExportPlayerIdentities)
                {
                    ulong id = 0;
                    try
                    {
                        id = MySession.Static.Players.TryGetSteamId(player.IdentityId);
                    }
                    catch
                    {
                        Hangar.Debug("Identitiy doesnt have a SteamID! Shipping!");
                        continue;
                    }


                    if (id == 0)
                    {
                        //Sanity check
                        continue;
                    }

                    GridMethods methods = new GridMethods(id, Plugin.Config.FolderDirectory);
                    //string path = GridMethods.CreatePathForPlayer(Config.FolderDirectory, id);

                    if (!methods.LoadInfoFile(out PlayerInfo Data))
                    {
                        return;
                    }



                    ConcurrentBag <List <MyCubeGrid> > gridGroups = GridFinder.FindGridList(player.IdentityId, false);
                    if (gridGroups.Count == 0)
                    {
                        continue;
                    }


                    long LargestGridID = 0;

                    if (Plugin.Config.KeepPlayersLargestGrid)
                    {
                        //First need to find their largets grid
                        int BlocksCount = 0;

                        foreach (List <MyCubeGrid> grids in gridGroups)
                        {
                            int        GridBlockCounts        = 0;
                            int        LargestSingleGridCount = 0;
                            MyCubeGrid LargetsGrid            = grids[0];
                            foreach (MyCubeGrid grid in grids)
                            {
                                if (grid.BlocksCount > LargestSingleGridCount)
                                {
                                    LargestSingleGridCount = grid.BlocksCount;
                                    LargetsGrid            = grid;
                                }
                            }

                            GridBlockCounts = LargetsGrid.BlocksCount;

                            if (GridBlockCounts > BlocksCount)
                            {
                                BlocksCount   = GridBlockCounts;
                                LargestGridID = LargetsGrid.EntityId;
                            }
                        }
                    }



                    foreach (List <MyCubeGrid> grids in gridGroups)
                    {
                        if (grids.Count == 0)
                        {
                            continue;
                        }


                        if (grids[0].IsRespawnGrid && Plugin.Config.DeleteRespawnPods)
                        {
                            grids[0].Close();
                            continue;
                        }


                        Result result = new Result();
                        result.grids = grids;

                        var BiggestGrid = grids[0];
                        foreach (MyCubeGrid grid in grids)
                        {
                            if (grid.BlocksCount > BiggestGrid.BlocksCount)
                            {
                                BiggestGrid = grid;
                            }
                        }


                        if (Plugin.Config.KeepPlayersLargestGrid)
                        {
                            if (BiggestGrid.EntityId == LargestGridID)
                            {
                                //Skip players largest grid
                                continue;
                            }
                        }


                        //Grid Size Checks
                        if (BiggestGrid.GridSizeEnum == MyCubeSize.Large)
                        {
                            if (BiggestGrid.IsStatic && !Plugin.Config.AutoHangarStaticGrids)
                            {
                                continue;
                            }
                            else if (!BiggestGrid.IsStatic && !Plugin.Config.AutoHangarLargeGrids)
                            {
                                continue;
                            }
                        }
                        else if (BiggestGrid.GridSizeEnum == MyCubeSize.Small && !Plugin.Config.AutoHangarSmallGrids)
                        {
                            continue;
                        }



                        result.biggestGrid = BiggestGrid;
                        result.GetGrids    = true;

                        //Check for existing grid names
                        Utils.FormatGridName(Data, result);



                        if (methods.SaveGrids(result.grids, result.GridName, Plugin))
                        {
                            //Load player file and update!
                            //Fill out grid info and store in file
                            HangarChecks.GetBPDetails(result, Plugin.Config, out GridStamp Grid);

                            Grid.GridName = result.GridName;
                            Data.Grids.Add(Grid);


                            GridCounter++;
                            Hangar.Debug(result.biggestGrid.DisplayName + " was sent to Hangar due to inactivity!");
                        }
                        else
                        {
                            Hangar.Debug(result.biggestGrid.DisplayName + " FAILED to Hangar due to inactivity!");
                        }
                    }

                    //Save players file!
                    methods.SaveInfoFile(Data);
                }
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                Hangar.Debug("AutoHangar: Finished Hangaring -" + GridCounter + " grids! Action took: " + ts.ToString());
            }
        }
示例#18
0
        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();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
示例#19
0
文件: FlyToGrid.cs 项目: zrisher/ARMS
        public FlyToGrid(Pathfinder pathfinder, string targetGrid = null, AttachedGrid.AttachmentKind allowedAttachment = AttachedGrid.AttachmentKind.Permanent, GridFinder finder = null, PseudoBlock landingBlock = null)
            : base(pathfinder)
        {
            this.m_targetBlock = m_navSet.Settings_Current.DestinationBlock;
            string blockName = m_targetBlock == null ? null : m_targetBlock.BlockName;

            if (finder != null)
            {
                this.m_gridFinder = finder;
            }
            else
            {
                this.m_gridFinder = new GridFinder(m_navSet, m_controlBlock, targetGrid, blockName, allowedAttachment);
            }
            this.m_landingFriend = !(this.m_gridFinder is EnemyFinder);

            if (landingBlock == null)
            {
                landingBlock = m_navSet.Settings_Current.LandingBlock;
            }
            m_navSet.Settings_Task_NavRot.NavigationBlock = landingBlock;

            if (landingBlock != null)
            {
                if (landingBlock.Block is IMyFunctionalBlock)
                {
                    m_landingState = LandingState.Approach;
                }
                else
                {
                    Log.DebugLog("landingBlock is not functional, player error? : " + landingBlock.Block.DisplayNameText, Logger.severity.INFO);
                    m_landingState = LandingState.None;
                }

                if (m_targetBlock == null)
                {
                    if (!(landingBlock.Block is IMyLandingGear))
                    {
                        Log.DebugLog("cannot land block without a target", Logger.severity.INFO);
                        m_landingState = LandingState.None;
                    }
                    else
                    {
                        Log.DebugLog("golden retriever mode enabled", Logger.severity.INFO);
                        m_landGearWithoutTargetBlock = true;
                    }
                }
                else if (landingBlock.Block is Ingame.IMyShipConnector)
                {
                    m_gridFinder.BlockCondition = block => {
                        Ingame.IMyShipConnector connector = block as Ingame.IMyShipConnector;
                        return(connector != null && (connector.Status == Ingame.MyShipConnectorStatus.Unconnected || connector.OtherConnector == m_navBlock.Block) && CanReserveTarget(connector.EntityId));
                    };
                    m_landingDirection = m_targetBlock.Forward ?? Base6Directions.GetFlippedDirection(landingBlock.Block.FirstFaceDirection());
                }
                else if (landingBlock.Block is IMyShipMergeBlock)
                {
                    m_gridFinder.BlockCondition = block => block is IMyShipMergeBlock && CanReserveTarget(block.EntityId);
                    m_landingDirection          = m_targetBlock.Forward ?? Base6Directions.GetFlippedDirection(landingBlock.Block.FirstFaceDirection());
                    (landingBlock.Block as IMyShipMergeBlock).BeforeMerge += MergeBlock_BeforeMerge;
                }
                else if (m_targetBlock.Forward.HasValue)
                {
                    m_landingDirection = m_targetBlock.Forward.Value;
                }
                else
                {
                    Log.DebugLog("Player failed to specify landing direction and it could not be determined.", Logger.severity.INFO);
                    m_landingState = LandingState.None;
                }

                if (m_landingState != LandingState.None)
                {
                    //float minDestRadius = m_controlBlock.CubeGrid.GetLongestDim() * 5f;
                    //if (m_navSet.Settings_Current.DestinationRadius < minDestRadius)
                    //{
                    //	Log.DebugLog("Increasing DestinationRadius from " + m_navSet.Settings_Current.DestinationRadius + " to " + minDestRadius, "FlyToGrid()", Logger.severity.DEBUG);
                    //	m_navSet.Settings_Task_NavRot.DestinationRadius = minDestRadius;
                    //}

                    new UnLander(m_pathfinder, landingBlock);

                    m_landingHalfSize = landingBlock.Block.GetLengthInDirection(landingBlock.Block.LocalMatrix.GetClosestDirection(landingBlock.LocalMatrix.Forward)) * 0.5f;
                    Log.DebugLog("m_landing direction: " + m_landingDirection + ", m_landingBlockSize: " + m_landingHalfSize);
                }
            }

            m_settingLevel = m_landingState != LandingState.None ? AllNavigationSettings.SettingsLevelName.NavRot : AllNavigationSettings.SettingsLevelName.NavMove;
            m_navSet.GetSettingsLevel(m_settingLevel).NavigatorMover = this;
        }
示例#20
0
        public void Outboundwormhole(string ip, string outfile, double xgate, double ygate, double zgate)
        {
            BoundingSphereD gate = new BoundingSphereD(new Vector3D(xgate, ygate, zgate), Config.InRadiusGate);

            foreach (var entity in MyAPIGateway.Entities.GetTopMostEntitiesInSphere(ref gate))
            {
                var grid = (entity as VRage.Game.ModAPI.IMyCubeGrid);
                if (grid != null)
                {
                    var playerInCharge = MyAPIGateway.Players.GetPlayerControllingEntity(entity);
                    if (playerInCharge != null && OwnershipUtils.GetOwner(entity as MyCubeGrid) == playerInCharge.IdentityId)//hasrighttomove(playerInCharge, entity as MyCubeGrid))
                    {
                        var WormholeDrives = new List <IMyJumpDrive>();
                        var gts            = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);
                        gts.GetBlocksOfType(WormholeDrives);
                        if (Config.DontNeedJD)
                        {
                            List <MyCubeGrid> grids = GridFinder.FindGridList(grid.EntityId.ToString(), playerInCharge as MyCharacter, Config.IncludeConnectedGrids);
                            if (grids == null)
                            {
                                return;
                            }
                            if (grids.Count == 0)
                            {
                                return;
                            }
                            var filename = playerInCharge.SteamUserId.ToString() + "_" + grid.GetFriendlyName() + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");

                            Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(new Vector3D(xgate, ygate, zgate));
                            if (GridManager.SaveGrid(CreatePath(outfile, filename), filename, ip, Config.KeepOriginalOwner, Config.ExportProjectorBlueprints, grids))
                            {
                                foreach (var delgrid in grids)
                                {
                                    delgrid.Delete();
                                }
                            }
                        }
                        else if (WormholeDrives.Count > 0)
                        {
                            foreach (var WormholeDrive in WormholeDrives)
                            {
                                if (WormholeDrive.OwnerId == playerInCharge.IdentityId && WormholeDrive.Enabled && WormholeDrive.CurrentStoredPower == WormholeDrive.MaxStoredPower && (WormholeDrive.BlockDefinition.SubtypeId.ToString() == Config.JumpDriveSubid || Config.WorkWithAllJD))
                                {
                                    WormholeDrive.CurrentStoredPower = 0;
                                    if (Config.DisableJD)
                                    {
                                        foreach (var jd in WormholeDrives)
                                        {
                                            jd.Enabled = false;
                                        }
                                    }
                                    List <MyCubeGrid> grids = GridFinder.FindGridList(grid.EntityId.ToString(), playerInCharge as MyCharacter, Config.IncludeConnectedGrids);
                                    if (grids == null)
                                    {
                                        return;
                                    }
                                    if (grids.Count == 0)
                                    {
                                        return;
                                    }
                                    var filename = playerInCharge.SteamUserId.ToString() + "_" + playerInCharge.DisplayName + "_" + grid.DisplayName + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");

                                    Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(new Vector3D(xgate, ygate, zgate));
                                    if (GridManager.SaveGrid(CreatePath(outfile, filename), filename, ip, Config.KeepOriginalOwner, Config.ExportProjectorBlueprints, grids))
                                    {
                                        foreach (var delgrid in grids)
                                        {
                                            delgrid.Delete();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }