public static int Depressurize(IMyCubeGrid grid, int strength, TimeSpan duration, long effectOwner)
 {
     AirVentDepressurize av;
     if (!Registrar.TryGetValue(grid, out av))
         av = new AirVentDepressurize(grid);
     return av.AddEffect(duration, strength, effectOwner);
 }
Beispiel #2
0
		public static int DisableTurrets(IMyCubeGrid grid, int strength, TimeSpan duration)
		{
			DisableTurret dt;
			if (!Registrar.TryGetValue(grid, out dt))
				dt = new DisableTurret(grid);
			return dt.AddEffect(duration, strength);
		}
Beispiel #3
0
 public PlanetChecker(IMyCubeGrid grid)
 {
     this.m_logger = new Logger(GetType().Name, grid.getBestName, ClosestPlanet.getBestName, CurrentState.ToString);
     this.m_grid = grid;
     this.m_cells = new MyQueue<Vector3I>(8);
     this.m_cellsUnique = new HashSet<Vector3I>();
 }
Beispiel #4
0
		private bool set_enemy(IMyCubeGrid value)
		{
			if (value == value_enemy)
				return true;

			if (value_enemy != null)
				if (GridsClaimed.Remove(value_enemy.EntityId))
					m_logger.debugLog("Removed " + value_enemy.getBestName() + " from GridsClaimed", "Move()", Logger.severity.TRACE);
				else
					m_logger.alwaysLog("Failed to remove " + value_enemy.getBestName() + " from GridsClaimed", "Move()", Logger.severity.WARNING);

			if (value != null)
			{
				if (GridsClaimed.ContainsKey(value.EntityId))
				{
					m_logger.debugLog("Already claimed: " + value.getBestName(), "set_m_enemy()", Logger.severity.INFO);
					return false;
				}
				else
					GridsClaimed.Add(value.EntityId, m_controlBlock.CubeGrid);
				
				m_enemyCells = GridCellCache.GetCellCache(value as IMyCubeGrid);
			}

			m_stage = Stage.None;
			value_enemy = value;
			return true;
		}
Beispiel #5
0
		/// <summary>
		/// creates from a local position
		/// </summary>
		public static RelativeVector3F createFromLocal(Vector3 grid, IMyCubeGrid cubeGrid)
		{
			RelativeVector3F result = new RelativeVector3F();
			result.value__grid = grid;
			result.cubeGrid = cubeGrid;
			return result;
		}
Beispiel #6
0
 public static int ReverseGravity(IMyCubeGrid grid, int strength, TimeSpan duration, long effectOwner)
 {
     GravityReverse gg;
     if (!Registrar.TryGetValue(grid, out gg))
         gg = new GravityReverse(grid);
     return gg.AddEffect(duration, strength, effectOwner);
 }
Beispiel #7
0
		public bool CanTarget(IMyCubeGrid grid)
		{
			CubeGridCache cache = CubeGridCache.GetFor(grid);
			if (m_destroySet && cache.TotalByDefinition() > 0)
				return true;

			TargetType gridType = grid.GridSizeEnum == MyCubeSize.Small ? TargetType.SmallGrid
				: grid.IsStatic ? TargetType.Station
				: TargetType.LargeGrid;

			List<string> targetBlocks;
			if (m_cumulative_targeting.TryGetValue(gridType, out targetBlocks))
			{
				foreach (string blockType in targetBlocks)
				{
					//m_logger.debugLog("checking " + grid.DisplayName + " for " + blockType + " blocks", "CanTarget()");
					if (cache.CountByDefLooseContains(blockType, func => func.IsWorking, 1) != 0)
						return true;
				}
			}
			//else
			//	m_logger.debugLog("no targeting at all for grid type of: " + grid.DisplayName, "CanTarget()");

			return false;
		}
Beispiel #8
0
		/// <summary>
		/// create from a relative world vector (current position - G.P.S.)
		/// </summary>
		public static RelativeVector3F createFromWorld(Vector3 world, IMyCubeGrid cubeGrid)
		{
			RelativeVector3F result = new RelativeVector3F();
			result.value__world = world;
			result.cubeGrid = cubeGrid;
			return result;
		}
Beispiel #9
0
 /// <summary>
 /// Gets the hash value for the grid to identify it
 /// (because apparently DisplayName doesn't work)
 /// </summary>
 /// <param name="grid"></param>
 /// <returns></returns>
 public static String gridIdentifier(IMyCubeGrid grid)
 {
     String id = grid.ToString();
     int start = id.IndexOf('{');
     int end = id.IndexOf('}');
     return id.Substring(start + 1, end - start);
 }
Beispiel #10
0
		public static int LockDoors(IMyCubeGrid grid, int strength, TimeSpan duration, long effectOwner)
		{
			DoorLock dl;
			if (!Registrar.TryGetValue(grid, out dl))
				dl = new DoorLock(grid);
			return dl.AddEffect(duration, strength, effectOwner);
		}
Beispiel #11
0
        public GyroProfiler(IMyCubeGrid grid)
        {
            this.m_logger = new Logger("GyroProfiler", () => grid.DisplayName);
            this.myGrid = grid;

            ClearOverrides();
        }
Beispiel #12
0
        /// <summary>
        /// Gets all the blocks from all valid connected grids.  So a grid connected to another grid that also has a few pistons with blocks on it will return
        /// all the blocks for the connected grids as well as all the blocks for any connected pistons.  (ug)
        /// </summary>
        /// <param name="gridsProcessed"></param>
        /// <param name="grid"></param>
        /// <param name="allBlocks"></param>
        /// <param name="collect"></param>
        public static void GetAllConnectedBlocks(HashSet<IMyEntity> gridsProcessed, IMyCubeGrid grid, List<IMySlimBlock> allBlocks, Func<IMySlimBlock, bool> collect = null)
        {
            List<IMySlimBlock> currentBlocks = new List<IMySlimBlock>();
            List<IMyCubeGrid> connectedGrids = new List<IMyCubeGrid>();

            connectedGrids.Add(grid);
            while(connectedGrids.Count > 0)
            {
                IMyCubeGrid currentGrid = connectedGrids.First();                
                connectedGrids.Remove(currentGrid);
                if (gridsProcessed.Contains(currentGrid))
                    continue;

                gridsProcessed.Add(currentGrid);

                GetGridBlocks(currentGrid, currentBlocks);
                foreach (IMyCubeGrid connectedGrid in GetConnectedGridList(gridsProcessed, currentBlocks))
                {
                    connectedGrids.Add(connectedGrid);
                }

                if (collect != null)
                {
                    foreach (IMySlimBlock slimBlock in currentBlocks.FindAll(s => collect(s)))
                        allBlocks.Add(slimBlock);
                }
                else
                {
                    foreach (IMySlimBlock slimBlock in currentBlocks)
                        allBlocks.Add(slimBlock);
                }
            }
        }
Beispiel #13
0
		public static int TurnTurrets(IMyCubeGrid grid, int strength, TimeSpan duration, long effectOwner)
		{
			TraitorTurret tt;
			if (!Registrar.TryGetValue(grid, out tt))
				tt = new TraitorTurret(grid);
			return tt.AddEffect(duration, strength, effectOwner);
		}
Beispiel #14
0
        private AttachedGrid(IMyCubeGrid grid)
        {
            this.myLogger = new Logger("AttachedGrid", () => grid.DisplayName);
            this.myGrid = grid;
            Registrar.Add(grid, this);

            myLogger.debugLog("Initialized");
        }
Beispiel #15
0
		public Logger(string calling_class, IMyCubeGrid grid, Func<string> default_primary = null, Func<string> default_secondary = null)
		{
			this.m_classname = calling_class;

			this.f_context = () => grid.DisplayName + " - " + grid.EntityId;
			this.f_state_primary = default_primary;
			this.f_state_secondary = default_secondary;
		}
Beispiel #16
0
		public InterpreterWeapon(IMyCubeBlock block)
			: base(block as IMyTerminalBlock)
		{
			this.Block = block;
			this.Grid = block.CubeGrid;

			myLogger = new Logger("InterpreterWeapon", () => Grid.DisplayName, () => Block.DefinitionDisplayNameText, () => Block.getNameOnly());
		}
Beispiel #17
0
		public InterpreterWeapon(IMyCubeBlock block)
		{
			this.Block = block;
			this.Grid = block.CubeGrid;
			this.m_instructions = new BlockInstructions(block as IMyTerminalBlock, OnInstruction);

			myLogger = new Logger("InterpreterWeapon", () => Grid.DisplayName, () => Block.DefinitionDisplayNameText, () => Block.getNameOnly());
		}
Beispiel #18
0
        public InterpreterWeapon(IMyCubeBlock block)
            : base(block)
        {
            this.Block = block;
            this.Grid = block.CubeGrid;

            myLogger = new Logger("InterpreterWeapon", () => Grid.DisplayName, () => Block.DefinitionDisplayNameText, () => Block.getNameOnly()) { MinimumLevel = Logger.severity.INFO };
        }
 public GridInventoriesManager(IMyCubeGrid grid, List<MyDefinitionId> watchedItems = null)
 {
     Grid = grid;
     Log = new Logger("SEGarden.World.Inventory.GridInventoriesManager", (() => Grid.EntityId.ToString()));
     Totals = new ItemCountsAggregate();
     InventoryTotals = new Dictionary<MyInventoryBase, ItemCountsAggregate>();
     //InventoryAggregate = new Sandbox.Game.Entities.Inventory.MyInventoryAggregate();
     WatchedItems = watchedItems;
 }
Beispiel #20
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="grid"></param>
 /// <returns>Type of the grid</returns>
 public static GRIDTYPE getGridType(IMyCubeGrid grid)
 {
     if (grid.IsStatic) {
         return GRIDTYPE.STATION;
     } else {
         if (grid.GridSizeEnum == MyCubeSize.Large)
             return GRIDTYPE.LARGESHIP;
         else
             return GRIDTYPE.SMALLSHIP;
     }
 }
Beispiel #21
0
        public ThrustProfiler(IMyCubeGrid grid)
        {
            if (grid == null)
                throw new NullReferenceException("grid");

            myLogger = new Logger("ThrustProfiler", () => grid.DisplayName);
            myLogger = new Logger(grid.DisplayName, "ThrustProfiler");
            myGrid = grid;

            init();
        }
Beispiel #22
0
        public DerelictTimer(IMyCubeGrid grid)
        {
            m_Grid = grid;

            m_TimerInfo = null;
            m_Timer = null;

            CompletedPhase = DT_INFO.PHASE.NONE;

            m_Logger = new Logger(m_Grid.EntityId.ToString(), "DerelictTimer");
        }
Beispiel #23
0
 public static GridCellCache GetCellCache(IMyCubeGrid grid)
 {
     GridCellCache cache;
     using (lock_cellCache.AcquireExclusiveUsing())
         if (!CellCache.TryGetValue(grid, out cache))
         {
             cache = new GridCellCache(grid);
             CellCache.Add(grid, cache);
         }
     return cache;
 }
Beispiel #24
0
        public Shopper(AllNavigationSettings navSet, IMyCubeGrid grid, Dictionary<string, int> shopList)
        {
            this.m_logger = new Logger(GetType().Name, grid);
            this.m_navSet = navSet;
            this.m_shoppingList = shopList;
            this.m_grid = grid;

            this.m_currentTask = Return;

            foreach (var pair in m_shoppingList)
                m_logger.debugLog("Item: " + pair.Key + ", amount: " + pair.Value);
        }
Beispiel #25
0
        public GyroProfiler(IMyCubeGrid grid)
        {
            this.myLogger = new Logger("GyroProfiler", () => grid.DisplayName);
            this.myGrid = grid;
            this.torqueAccelRatio = 0f;

            ReadOnlyList<IMyCubeBlock> blocks = CubeGridCache.GetFor(grid).GetBlocksOfType(typeof(MyObjectBuilder_Gyro));
            if (blocks != null)
                foreach (MyGyro g in blocks)
                    Gyros.Add(g);

            grid.OnBlockAdded += grid_OnBlockAdded;
            grid.OnBlockRemoved += grid_OnBlockRemoved;
        }
        private void DeleteReverse(string id, int remove, IMyCubeGrid grid)
        {
            int count = 0;
            Sandbox.ModAPI.Ingame.IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);

            List<IMyTerminalBlock> blocksToRemove = new List<IMyTerminalBlock>();
            for (int r = gridTerminal.Blocks.Count - 1; r >= 0; r--)
            {
                IMyTerminalBlock block = (IMyTerminalBlock)gridTerminal.Blocks[r];
                if (block.BlockDefinition.TypeId.ToString().Contains(id))
                {
                    blocksToRemove.Add(block);
                    count++;
                }

                if (count == remove)
                    break;
            }

            /*
            List<MyObjectBuilder_CubeBlock> blocksToRemove = new List<MyObjectBuilder_CubeBlock>();
            for (int r = gridBuilder.CubeBlocks.Count - 1; r >= 0; r--)
            {
                MyObjectBuilder_CubeBlock block = gridBuilder.CubeBlocks[r];
                if (block.GetId().ToString().Contains(id))
                {
                    blocksToRemove.Add(block);
                    count++;
                }

                if (count == remove)
                    break;
            }
            */

            if (blocksToRemove.Count < 1)
                return;

            List<VRageMath.Vector3I> razeList = new List<VRageMath.Vector3I>();
            foreach (IMyTerminalBlock block in blocksToRemove)
            {
                razeList.Add(block.Min);
            }

            Wrapper.GameAction(() =>
            {
                grid.RazeBlocks(razeList);
            });
        }
		private void Attach(IMyCubeGrid grid, bool force)
		{
			if (!force && grid == curAttTo)
				return;

			Detach();

			myGrid = myBlock.CubeGrid;
			myGrid.OnClose += Detach;
			grid.OnClose += Detach;

			myLogger.debugLog("attaching " + myGrid.DisplayName + " to " + grid.DisplayName, "Attach()", Logger.severity.DEBUG);
			AttachedGrid.AddRemoveConnection(AttachmentKind, myGrid, grid, true);
			curAttTo = grid;
		}
Beispiel #28
0
        /// <summary>
        /// Determines if two grids are attached.
        /// </summary>
        /// <param name="grid0">The starting grid.</param>
        /// <param name="grid1">The grid to search for.</param>
        /// <param name="allowedConnections">The types of connections allowed between grids.</param>
        /// <returns>True iff the grids are attached.</returns>
        public static bool IsGridAttached(IMyCubeGrid grid0, IMyCubeGrid grid1, AttachmentKind allowedConnections)
        {
            if (grid0 == grid1)
                return true;

            using (lock_search.AcquireExclusiveUsing())
            {
                AttachedGrid attached1 = GetFor(grid0);
                if (attached1 == null)
                    return false;
                AttachedGrid attached2 = GetFor(grid1);
                if (attached2 == null)
                    return false;
                return attached1.IsGridAttached(attached2, allowedConnections, searchIdPool++);
            }
        }
        protected void Detach()
        {
            if (curAttTo == null)
                return;

            myGrid.OnMarkForClose -= Detach;
            curAttTo.OnMarkForClose -= Detach;
            if (curAttToBlock != null)
            {
                curAttToBlock.OnMarkForClose -= Detach;
                curAttToBlock = null;
            }

            myLogger.debugLog("detaching " + myGrid.DisplayName + " from " + curAttTo.DisplayName, Logger.severity.DEBUG);
            AttachedGrid.AddRemoveConnection(AttachmentKind, myGrid, curAttTo, false);
            curAttTo = null;
        }
Beispiel #30
0
        private CubeGridCache(IMyCubeGrid grid)
        {
            myLogger = new Logger("CubeGridCache", () => grid.DisplayName);
            CubeGrid = grid;
            List<IMySlimBlock> allSlims = new List<IMySlimBlock>();
            CubeGrid.GetBlocks_Safe(allSlims, slim => slim.FatBlock != null);

            foreach (IMySlimBlock slim in allSlims)
                CubeGrid_OnBlockAdded(slim);

            CubeGrid.OnBlockAdded += CubeGrid_OnBlockAdded;
            CubeGrid.OnBlockRemoved += CubeGrid_OnBlockRemoved;
            CubeGrid.OnClosing += CubeGrid_OnClosing;

            Registrar.Add(CubeGrid, this);
            myLogger.debugLog("built for: " + CubeGrid.DisplayName, Logger.severity.DEBUG);
        }
 public static int GetTotalMass(this IMyCubeGrid Grid)
 {
     return((Grid as MyCubeGrid).GetCurrentMass());
 }
Beispiel #32
0
        private void OfferPotentialNpcShip(IMyCubeGrid grid)
        {
            //            ModLog.Info("Potentential NPC:" + grid.CustomName);
            NpcGroupSaveData npcGroupSaveData;

            if (restoredNpcGroupData.TryGetValue(grid.EntityId, out npcGroupSaveData))
            {
                //                ModLog.Info(" Potentential NPC: Found in restored NPC Group data:" + npcGroupSaveData.NpcGroupType.ToString() + " Type="+ npcGroupSaveData.LeaderUnitType.ToString());
                if (npcGroupSaveData.NpcGroupType == NpcGroupType.Backup)
                {
                    npcGroups.Add(new BackupGroup(npcGroupSaveData.State, npcGroupSaveData.GroupDestination,
                                                  grid, heatSystem, audioSystem, DateTime.FromBinary(npcGroupSaveData.SpawnTime)));
                }
                else // Must be convoy
                {
                    if (modBuildWhenLastSaved > 30 || !bInitialInit)
                    {
                        restoredConvoys.Add(grid.EntityId,
                                            RegisterConvoy(grid, npcGroupSaveData.State, npcGroupSaveData.LeaderUnitType,
                                                           npcGroupSaveData.GroupDestination, DateTime.FromBinary(npcGroupSaveData.SpawnTime)));
                    }
                    else
                    {
                        // else old drones with scripts that don't work on 1.193.100

                        if (grid.IsControlledByFaction("GCORP")) // see npcgroup.AttemptDespawn()
                        {
                            ModLog.Info("save build#:" + modBuildWhenLastSaved.ToString() + " Initial=" + bInitialInit.ToString());
                            ModLog.Info("Removing dead drone Grid:" + grid.CustomName);
                            bOldRemovals = true;
                            grid.CloseAll();
                        }
                    }
                }
            }
            else
            {
                //                ModLog.Info(" Potentential NPC: NOT in restored NPC Group data:" + grid.CustomName);
                if (modBuildWhenLastSaved > 30 || !bInitialInit)
                {
                    possibleEscorts.Add(grid);
                }
                else
                {
                    // Need better discernment to not delete placed G-Corp grids like G-Corp AP Turret and GCorp Experimental Mech
                    if (grid.IsControlledByFaction("GCORP")) // see npcgroup.AttemptDespawn()
                    {
                        var slimBlocks = new List <IMySlimBlock>();
                        grid.GetBlocks(slimBlocks, b => b.FatBlock is IMyBeacon);
                        foreach (var slim in slimBlocks)
                        {
                            var fb = slim.FatBlock as IMyBeacon;
                            if (fb.CustomName.Contains(EscortName))
                            {
                                ModLog.Info("Removing dead escort drone Grid:" + grid.CustomName);
                                bOldRemovals = true;
                                grid.CloseAll();
                                break;
                            }
                        }
                    }
                }
            }
        }
Beispiel #33
0
 protected void Attach(IMyCubeGrid grid)
 {
     Attach(grid, false);
 }
 public static bool HasDamageHandler(IMyCubeGrid grid)
 {
     return(HasDamageHandler(grid.GetTopMostParent().EntityId));
 }
 public static void AddDamageHandler(IMyCubeGrid grid, BotBase.OnDamageTaken handler)
 {
     AddDamageHandler(grid.GetTopMostParent().EntityId, handler);
 }
Beispiel #36
0
        public Drone(IMyEntity ent)
        {
            var ship = (IMyCubeGrid)ent;

            Ship = ship;
            var lstSlimBlock = new List <IMySlimBlock>();

            GridTerminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(ship);

            //If it has any type of cockipt
            ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is Sandbox.ModAPI.IMyRemoteControl);
            FindWeapons();
            SetupActions();

            //If no cockpit the ship is either no ship or is broken.
            if (lstSlimBlock.Count != 0)
            {
                //Make the controls be the cockpit
                ShipControls = lstSlimBlock[0].FatBlock as IMyControllableEntity;

                #region Activate Beacons && Antennas


                //Maximise radius on antennas and beacons.
                lstSlimBlock.Clear();
                ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is Sandbox.ModAPI.IMyRadioAntenna);
                foreach (var block in lstSlimBlock)
                {
                    Sandbox.ModAPI.IMyRadioAntenna antenna =
                        (Sandbox.ModAPI.IMyRadioAntenna)block.FatBlock;
                    if (antenna != null)
                    {
                        //antenna.GetActionWithName("SetCustomName").Apply(antenna, new ListReader<TerminalActionParameter>(new List<TerminalActionParameter>() { TerminalActionParameter.Get("Combat Drone " + _manualGats.Count) }));
                        antenna.SetValueFloat("Radius", 10000);//antenna.GetMaximum<float>("Radius"));
                        _blockOn.Apply(antenna);
                    }
                }

                lstSlimBlock = new List <IMySlimBlock>();
                ship.GetBlocks(lstSlimBlock, (x) => x.FatBlock is Sandbox.ModAPI.IMyBeacon);
                foreach (var block in lstSlimBlock)
                {
                    Sandbox.ModAPI.IMyBeacon beacon = (Sandbox.ModAPI.IMyBeacon)block.FatBlock;
                    if (beacon != null)
                    {
                        beacon.SetValueFloat("Radius", 10000);//beacon.GetMaximum<float>("Radius"));
                        _blockOn.Apply(beacon);
                    }
                }

                #endregion

                //SetWeaponPower(true);
                //AmmoManager.ReloadReactors(_allReactors);
                //AmmoManager.ReloadGuns(_manualGats);
                ship.GetBlocks(lstSlimBlock, x => x is IMyEntity);


                List <IMyTerminalBlock> allTerminalBlocks = new List <IMyTerminalBlock>();
                GridTerminalSystem.GetBlocksOfType <IMyCubeBlock>(allTerminalBlocks);
                HealthBlockBase = allTerminalBlocks.Count;


                if (ShipControls != null)
                {
                    navigation = new ThrusterGyroControls(ship, ShipControls);
                    _ownerId   = ((Sandbox.ModAPI.IMyTerminalBlock)ShipControls).OwnerId;
                    tc         = new TargetingControls(Ship, _ownerId);
                }
            }

            Ship.OnBlockAdded += RecalcMaxHp;
            myNumber           = numDrones;
            numDrones++;
        }
 public void Init(IMyGridTerminalSystem gts, IMyCubeGrid desiredGrid)
 {
     this.textPanels = GetTextPanels(gts, desiredGrid);
     this.jumpDrives = GetJumpDrives(gts, desiredGrid);
 }
        /// <summary>
        /// Check the ownership of the grid
        /// </summary>
        /// <param name="cubeGrid"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static VRage.Game.MyRelationsBetweenPlayerAndBlock GetUserRelationToOwner(this IMyCubeGrid cubeGrid, long userId, bool ignoreCubeGridList = false)
        {
            var enemies = false;
            var neutral = false;

            try
            {
                if (cubeGrid.BigOwners != null && cubeGrid.BigOwners.Count != 0)
                {
                    foreach (var key in cubeGrid.BigOwners)
                    {
                        var relation = MyIDModule.GetRelationPlayerBlock(key, userId, VRage.Game.MyOwnershipShareModeEnum.Faction);
                        if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Owner || relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.FactionShare)
                        {
                            return(relation);
                        }
                        else if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Enemies)
                        {
                            enemies = true;
                        }
                        else if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Neutral)
                        {
                            neutral = true;
                        }
                    }
                }
                else if (!ignoreCubeGridList)
                {
                    //E.G. the case if a landing gear is directly attatched to piston/rotor (with no ownable block in the same subgrid) and the gear gets connected to something
                    var cubegridsList = MyAPIGateway.GridGroups.GetGroup(cubeGrid, GridLinkTypeEnum.Mechanical);
                    if (cubegridsList != null)
                    {
                        foreach (var cubeGrid1 in cubegridsList)
                        {
                            if (cubeGrid1 == cubeGrid)
                            {
                                continue;
                            }
                            var relation = cubeGrid1.GetUserRelationToOwner(userId, true); //Do not recurse as this list is already complete
                            if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Owner || relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.FactionShare)
                            {
                                return(relation);
                            }
                            else if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Enemies)
                            {
                                enemies = true;
                            }
                            else if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Neutral)
                            {
                                neutral = true;
                            }
                        }
                    }
                }
            }
            catch {
                //The list BigOwners could change while iterating -> a silent catch
            }
            if (enemies)
            {
                return(VRage.Game.MyRelationsBetweenPlayerAndBlock.Enemies);
            }
            if (neutral)
            {
                return(VRage.Game.MyRelationsBetweenPlayerAndBlock.Neutral);
            }
            return(VRage.Game.MyRelationsBetweenPlayerAndBlock.NoOwnership);
        }
 public static bool IsControlledByFaction(this IMyCubeGrid grid, string factionTag)
 {
     return(grid != null && !grid.Closed && IsControlledBy(grid, factionTag));
 }
 public static bool Has <T>(this IMyCubeGrid Grid) where T : class, IMyTerminalBlock
 {
     return(Grid.GetWorkingBlocks <T>().Count > 0);
 }
 public static IMyCockpit GetFirstCockpit(this IMyCubeGrid Grid)
 {
     return(Grid.GetWorkingBlocks <IMyCockpit>()[0]);
 }
 public static bool HasGyros(this IMyCubeGrid Grid)
 {
     return(Grid.GetWorkingBlocks <IMyGyro>().Count > 0);
 }
 public static bool HasCockpit(this IMyCubeGrid Grid)
 {
     return(Grid.GetWorkingBlocks <IMyCockpit>().Count > 0);
 }
Beispiel #44
0
 public static List <long> getPlayerIDsWithinPlacementRadius(this IMyCubeGrid self)
 {
     return(getPlayersWithinPlacementRadius(self).ConvertAll(x => x.PlayerID));
 }
 public static bool IsControlledByNpcFaction(this IMyCubeGrid grid)
 {
     return(true);
     //TODO determine the majority holder (if any) using	Faction.IsKnownNpcFaction()
 }
 public static float GetMaxPowerOutput(this IMyCubeGrid Grid)
 {
     return(Grid.GetMaxReactorPowerOutput() + Grid.GetMaxBatteryPowerOutput());
 }
        /// <summary>
        /// Is the grid a projected grid
        /// </summary>
        public static bool IsProjected(this IMyCubeGrid target)
        {
            var cubeGrid = target as MyCubeGrid;

            return(cubeGrid != null && cubeGrid.Projector != null);
        }
Beispiel #48
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.DockingEnabled)
            {
                return(false);
            }

            if (words.Length < 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            if (m_docking)
            {
                Communication.SendPrivateInformation(userId, "Server is busy");
                return(true);
            }

            m_docking = true;
            try
            {
                string pylonName = string.Join(" ", words);

                /*
                 * int timeLeft;
                 * if (Entity.CheckCoolDown(pylonName, out timeLeft))
                 * {
                 *      Communication.Message(String.Format("The docking zone '{0}' is on cooldown.  Please wait a {1} seconds before trying to dock/undock again.", pylonName, Math.Max(0, timeLeft)));
                 *      return;
                 * }
                 */

                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, $"Unable to find player Id: {userId}");
                    return(true);
                }

                long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First();

                Dictionary <string, List <IMyCubeBlock> > testList;
                List <IMyCubeBlock> beaconList;
                DockingZone.FindByName(pylonName, out testList, out beaconList, playerId);
                if (beaconList.Count == 4)
                {
                    // Check ownership
                    foreach (IMyCubeBlock entityBlock in beaconList)
                    {
                        IMyTerminalBlock terminal = (IMyTerminalBlock)entityBlock;
                        if (!terminal.HasPlayerAccess(playerId))
                        {
                            Communication.SendPrivateInformation(userId, $"You do not have permission to use '{pylonName}'.  You must either own all the beacons or they must be shared with faction.");
                            return(true);
                        }
                    }

                    // Check for bounding box intsection of other docking zones
                    int intersectElement = 0;
                    if (Entity.CheckForIntersection(testList, beaconList, out intersectElement))
                    {
                        Communication.SendPrivateInformation(userId, $"The docking zone '{pylonName}' intersects with docking zone '{testList.ElementAt( intersectElement ).Key}'.  Make sure you place your docking zones so they don't overlap.");
                        return(true);
                    }

                    // Check if ship already docked in this zone
                    IMyCubeBlock       e             = beaconList[0];
                    IMyCubeGrid        parent        = (IMyCubeGrid)e.Parent;
                    long[]             beaconListIds = beaconList.Select(b => b.EntityId).ToArray();
                    long               ownerId       = beaconList.First().OwnerId;
                    List <DockingItem> checkItems    = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count() == 4);
                    if (checkItems.Count >= PluginSettings.Instance.DockingShipsPerZone)
                    {
                        Communication.SendPrivateInformation(userId, $"Docking zone '{pylonName}' already contains the maximum capacity of ships.");
                        return(true);
                    }

                    // Figure out center of docking area, and other distance information
                    double   maxDistance = 99;
                    Vector3D vPos        = new Vector3D(0, 0, 0);

                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        vPos += beaconPos;
                    }

                    vPos = vPos / 4;
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos));
                    }

                    // Find ship in docking area
                    IMyCubeGrid         dockingEntity = null;
                    HashSet <IMyEntity> cubeGrids     = new HashSet <IMyEntity>();
                    Wrapper.GameAction(() =>
                    {
                        MyAPIGateway.Entities.GetEntities(cubeGrids, f => f is IMyCubeGrid);
                    });
                    foreach (IMyCubeGrid gridCheck in cubeGrids)
                    {
                        if (gridCheck.IsStatic || gridCheck == parent)
                        {
                            continue;
                        }

                        double distance = Vector3D.Distance(gridCheck.GetPosition(), vPos);
                        if (distance < maxDistance)
                        {
                            dockingEntity = gridCheck;
                            break;
                        }
                    }

                    // Figure out if the ship fits in docking area, and then save ship
                    if (dockingEntity != null)
                    {
                        // Get bounding box of both the docking zone and docking ship
                        OrientedBoundingBoxD targetBounding  = Entity.GetBoundingBox(beaconList);
                        OrientedBoundingBoxD dockingBounding = Entity.GetBoundingBox(dockingEntity);

                        // Make sure the docking zone contains the docking ship.  If they intersect or are disjointed, then fail
                        if (!Entity.GreaterThan(dockingBounding.HalfExtent * 2, targetBounding.HalfExtent * 2))
                        {
                            Communication.SendPrivateInformation(userId, $"The ship '{dockingEntity.DisplayName}' is too large for it's carrier.  The ship's bounding box must fit inside the docking zone bounding box!");
                            return(true);
                        }

                        if (targetBounding.Contains(ref dockingBounding) != ContainmentType.Contains)
                        {
                            Communication.SendPrivateInformation(userId, $"The ship '{dockingEntity.DisplayName}' is not fully inside the docking zone '{pylonName}'.  Make sure the ship is fully contained inside the docking zone");
                            return(true);
                        }

                        // Calculate the mass and ensure the docking ship is less than half the mass of the dock
                        float parentMass  = Entity.CalculateMass(parent);
                        float dockingMass = Entity.CalculateMass(dockingEntity);
                        if (dockingMass > parentMass)
                        {
                            Communication.SendPrivateInformation(userId, $"The ship you're trying to dock is too heavy for it's carrier.  The ship mass must be less than half the large ship / stations mass! (DM={dockingMass}kg CM={parentMass}kg)");
                            return(true);
                        }

                        // Check to see if the ship is piloted, if it is, error out.
                        // TODO: Check to see if we can get a real time copy of this entity?
                        List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                        dockingEntity.GetBlocks(blocks, x => x.FatBlock is MyCockpit);
                        foreach (IMySlimBlock slim in blocks)
                        {
                            //MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)slim.FatBlock.GetObjectBuilderCubeBlock();
                            var c = (MyShipController)slim.FatBlock;
                            if (c.Pilot != null)
                            {
                                Communication.SendPrivateInformation(userId, $"Ship in docking zone '{pylonName}' has a pilot!  Please exit the ship before trying to dock.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)");
                                return(true);
                            }
                        }

                        // Save position and rotation information.  Some fun stuff here.
                        // Get our dock rotation as a quaternion
                        Quaternion saveQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                        // Transform docked ship's local position by inverse of the the parent (unwinds parent) and save it for when we undock
                        Vector3D savePos = Vector3D.Transform(dockingEntity.GetPosition() - parent.GetPosition(), Quaternion.Inverse(saveQuat));
                        // Get local rotation of dock ship, and save it for when we undock
                        saveQuat = Quaternion.Inverse(saveQuat) * Quaternion.CreateFromRotationMatrix(dockingEntity.WorldMatrix.GetOrientation());

                        // Save ship to file and remove
                        FileInfo info = new FileInfo(Path.Combine(Essentials.PluginPath, "Docking", $"docked_{ownerId}_{parent.EntityId}_{dockingEntity.EntityId}.sbc"));
                        if (!Directory.Exists(info.DirectoryName))
                        {
                            Directory.CreateDirectory(info.DirectoryName);
                        }
                        //CubeGridEntity dockingGrid = new CubeGridEntity((MyObjectBuilder_CubeGrid)dockingEntity.GetObjectBuilder(), dockingEntity);
                        MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(dockingEntity);
                        if (gridBuilder == null)
                        {
                            Communication.SendPrivateInformation(userId, $"Failed to load entity for export: {dockingEntity.DisplayName}");
                            return(true);
                        }

                        // Save item
                        DockingItem dockItem = new DockingItem
                        {
                            DockedEntityId   = dockingEntity.EntityId,
                            TargetEntityId   = parent.EntityId,
                            PlayerId         = ownerId,
                            DockingBeaconIds = beaconList.Select(s => s.EntityId).ToArray( ),
                            DockedName       = dockingEntity.DisplayName,
                            SavePos          = savePos,
                            SaveQuat         = saveQuat
                        };
                        Docking.Instance.Add(dockItem);

                        // Serialize and save ship to file
                        MyObjectBuilderSerializer.SerializeXML(info.FullName, false, gridBuilder);
                        Wrapper.BeginGameAction(() => dockingEntity.Close( ));

                        Communication.SendPrivateInformation(userId, $"Docked ship '{dockItem.DockedName}' in docking zone '{pylonName}'.");
                        Log.Info("Docked ship \"{0}\" in docking zone \"{1}\". Saved to {2}", dockItem.DockedName, pylonName, info.FullName);

                        /*
                         * // Add a cool down
                         * DockingCooldownItem cItem = new DockingCooldownItem();
                         * cItem.name = pylonName;
                         * cItem.startTime = DateTime.Now;
                         * PluginDocking.CooldownList.Add(cItem);
                         */
                    }
                    else
                    {
                        Communication.SendPrivateInformation(userId, $"No ships in docking zone '{pylonName}'.");
                    }
                }
                else if (beaconList.Count > 4)
                {
                    Communication.SendPrivateInformation(userId, $"Too many beacons with the name or another zone with the name '{pylonName}'.  Place only 4 beacons to create a zone or try a different zone name.");
                }
                else
                {
                    Communication.SendPrivateInformation(userId, string.Format("Can not locate docking zone '{0}'.  There must be 4 beacons with the name '{0}' to create a docking zone.  Beacons must be fully built!", pylonName));
                }

                return(true);
            }
            catch (SecurityException ex)
            {
                Log.Error("Can't access docked ship file.", ex);
                return(false);
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.Error("Can't access docked ship file.", ex);
                return(false);
            }
            catch (DirectoryNotFoundException ex)
            {
                Log.Error("Directory does not exist", ex);
                return(false);
            }
            catch (IOException ex)
            {
                Log.Error(ex);
                return(false);
            }
            finally
            {
                m_docking = false;
            }
        }
        private void CheckPlayerInDockingZone(IMyPlayer player)
        {
            if (player.Controller == null || player.Controller.ControlledEntity == null || player.Controller.ControlledEntity.Entity == null)
            {
                return;
            }

            IMyEntity entity   = player.Controller.ControlledEntity.Entity;
            long      playerId = player.PlayerID;
            IMyEntity parent   = entity.GetTopMostParent();

            // Not a ship?  let's not process
            if (!(parent is IMyCubeGrid))
            {
                if (m_playersInside.Contains(playerId))
                {
                    m_playersInside.Remove(playerId);
                    ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                    Communication.Notification(steamId, MyFontEnum.DarkBlue, 7, "You have exited a ship in a docking zone");
                }

                return;
            }

            // Get All ships with 500m
            BoundingSphereD  sphere         = new BoundingSphereD(parent.GetPosition(), 500);
            List <IMyEntity> nearByEntities = null;

            // Live dangerously (no wrapper for speed!)
            try
            {
                nearByEntities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole(string.Format("CheckPlayerInDockingZone(): {0}", ex.ToString()));
                return;
            }

            if (nearByEntities == null)
            {
                return;
            }

            List <IMyEntity> nearByGrids = nearByEntities.FindAll(x => x is IMyCubeGrid);

            // See if player's ship is inside a docking zone
            foreach (IMyEntity nearByEntity in nearByGrids)
            {
                // Sanity Check
                if (!(nearByEntity is IMyCubeGrid))
                {
                    return;
                }

                IMyCubeGrid cubeGrid = (IMyCubeGrid)nearByEntity;
                // Does this grid contain a docking zone?
                if (m_zoneCache.Contains(cubeGrid))
                {
                    Dictionary <String, List <IMyCubeBlock> > zoneList = DockingZone.GetZonesInGrid(cubeGrid);
                    if (zoneList == null)
                    {
                        continue;
                    }

                    // Get zones
                    foreach (KeyValuePair <String, List <IMyCubeBlock> > p in zoneList)
                    {
                        // Check if we're inside
                        if (DockingZone.IsGridInside((IMyCubeGrid)parent, p.Value))
                        {
                            if (!m_playersInside.Contains(playerId))
                            {
                                m_playersInside.Add(playerId);
                                ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                                Communication.Notification(steamId, MyFontEnum.Green, 7, string.Format("You are inside a valid docking zone: {0}", p.Key));
                            }

                            return;
                        }
                    }
                }
            }

            // We've left
            if (m_playersInside.Contains(playerId))
            {
                m_playersInside.Remove(playerId);
                ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                Communication.Notification(steamId, MyFontEnum.Red, 7, "You have left a docking zone");
            }
        }
Beispiel #50
0
        private void _cubeGrid_OnBlockOwnershipChanged(IMyCubeGrid cubeGrid)
        {
            // only execute on server instance
            if (ChatCommandLogic.Instance != null && ChatCommandLogic.Instance.ServerCfg == null)
            {
                return;
            }

            if (_firstOwnershipChange)
            {
                _firstOwnershipChange = false;
                _cachedOwners         = new List <long>(cubeGrid.GetAllSmallOwners());
                return;
            }

            var allSmallOwners = cubeGrid.GetAllSmallOwners();

            if (_cachedOwners == allSmallOwners)
            {
                return;
            }

            // if the grid wasn't owned or a owner was removed, we dont need to do anything but update the cached owners
            if (_cachedOwners.Count == 0 || _cachedOwners.Count > allSmallOwners.Count)
            {
                _cachedOwners = new List <long>(allSmallOwners);
                return;
            }

            var newOwners = allSmallOwners.Except(_cachedOwners).ToList();

            if (newOwners.Count == 0)
            {
                return;
            }

            if (!ProtectionHandler.IsProtected(cubeGrid))
            {
                _cachedOwners = new List <long>(allSmallOwners);
                return;
            }

            Dictionary <long, int> blocksPerOwner = new Dictionary <long, int>();

            foreach (IMyCubeGrid attachedCubeGrid in cubeGrid.GetAttachedGrids(AttachedGrids.Static))
            {
                List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                attachedCubeGrid.GetBlocks(blocks, b => b.FatBlock != null);


                foreach (IMySlimBlock block in blocks)
                {
                    long ownerId = block.FatBlock.OwnerId;

                    // we dont want the new owners, the small owners or the 'nobody' (0)
                    if (ownerId == 0 || !attachedCubeGrid.BigOwners.Contains(ownerId) || newOwners.Contains(ownerId))
                    {
                        continue;
                    }

                    if (!blocksPerOwner.ContainsKey(ownerId))
                    {
                        blocksPerOwner.Add(ownerId, 1);
                    }
                    else
                    {
                        blocksPerOwner[ownerId]++;
                    }
                }
            }

            var sortedBpo = new List <KeyValuePair <long, int> >(blocksPerOwner.OrderBy(pair => pair.Value));

            // if we cannot identify an owner we allow the change
            if (sortedBpo.Count == 0)
            {
                _cachedOwners = new List <long>(allSmallOwners);
                return;
            }

            var bigOwner = sortedBpo[0].Key;

            List <IMySlimBlock> ownershipChangedBlocks = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(ownershipChangedBlocks, b => b.FatBlock != null && newOwners.Contains(b.FatBlock.OwnerId));
            foreach (IMySlimBlock slimBlock in ownershipChangedBlocks)
            {
                var block = (Sandbox.Game.Entities.MyCubeBlock)slimBlock.FatBlock; // TODO check if the block was created/built just moments ago, do not change owner otherwise
                block.ChangeOwner(bigOwner, MyOwnershipShareModeEnum.None);
                ConnectionHelper.SendMessageToAllPlayers(new MessageSyncBlockOwner()
                {
                    OwnerId = bigOwner, EntityId = block.EntityId
                });
                // no need to update the cached owners as we don't want them to change
            }

            // TODO maybe allow the faction to build...
        }
        // admin deletearea x y z radius
        public override bool HandleCommand(ulong userId, string[] words)
        {
            HashSet <IMyEntity> entities          = new HashSet <IMyEntity>();
            HashSet <IMyEntity> entitiesToConfirm = new HashSet <IMyEntity>();
            HashSet <IMyEntity> entitiesConnected = new HashSet <IMyEntity>();
            HashSet <IMyEntity> entitiesFound     = new HashSet <IMyEntity>();

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid);
            });

            foreach (IMyEntity entity in entities)
            {
                if (!(entity is IMyCubeGrid))
                {
                    continue;
                }

                IMyCubeGrid grid = (IMyCubeGrid)entity;
                MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid);
                if (gridBuilder == null)
                {
                    continue;
                }

                bool found = false;
                foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks)
                {
                    if (block.TypeId == typeof(MyObjectBuilder_Beacon))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    entitiesToConfirm.Add(grid);
                }
            }

            CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm);

            foreach (IMyEntity entity in entitiesFound)
            {
                CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId);
                if (gridEntity == null)
                {
                    Log.Info("A found entity gridEntity was null!");
                    continue;
                }
                Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, entity.EntityId, General.Vector3DToString(entity.GetPosition())));
            }

            for (int r = entitiesFound.Count - 1; r >= 0; r--)
            {
                //MyAPIGateway.Entities.RemoveEntity(entity);
                IMyEntity      entity     = entitiesFound.ElementAt(r);
                CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);
                gridEntity.Dispose();
            }

            Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids with no beacons", entitiesFound.Count));

            return(true);
        }
        private int SwitchShipSystemsOnOff(IMyCubeGrid cubeGrid, SwitchSystems control, bool mode)
        {
            int counter = 0;
            var blocks  = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(blocks, f => f.FatBlock != null);

            foreach (var block in blocks)
            {
                // reactors, batteries
                if ((SwitchSystems.Power & control) == SwitchSystems.Power && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Reactor) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_BatteryBlock)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                // refineries, arc furnaces, assemblers
                if ((SwitchSystems.Production & control) == SwitchSystems.Production && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Programmable & control) == SwitchSystems.Programmable && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MyProgrammableBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Projectors & control) == SwitchSystems.Projectors && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Projector))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Timers & control) == SwitchSystems.Timers && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_TimerBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Weapons & control) == SwitchSystems.Weapons && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_InteriorTurret) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeGatlingTurret) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_LargeMissileTurret) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallGatlingGun) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallMissileLauncher) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SmallMissileLauncherReload)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.SpotLights & control) == SwitchSystems.SpotLights && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ReflectorLight))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Sensors & control) == SwitchSystems.Sensors && block.FatBlock is IMyFunctionalBlock &&
                    block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_SensorBlock))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Medical & control) == SwitchSystems.Medical && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom) ||
                     block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_CryoChamber)))
                {
                    // Switch the power systems that control the grid instead.
                    // I'm unsure if we should go with it like this, which is why it is as yet undocumented.
                    // The idea is, if you have turned the power off to all ships, you can turn the power back on only for grids with Medical and Cryo.
                    SwitchShipSystemsOnOff(cubeGrid, SwitchSystems.Power, mode);
                    counter++;
                }
                if ((SwitchSystems.Mass & control) == SwitchSystems.Mass && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_VirtualMass)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Grinder & control) == SwitchSystems.Grinder && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipGrinder)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
                if ((SwitchSystems.Welder & control) == SwitchSystems.Welder && block.FatBlock is IMyFunctionalBlock &&
                    (block.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipWelder)))
                {
                    ((IMyFunctionalBlock)block.FatBlock).RequestEnable(mode); // turn power on/off.
                    counter++;
                }
            }

            return(counter);
        }
 public static void RemoveDamageHandler(IMyCubeGrid grid)
 {
     RemoveDamageHandler(grid.GetTopMostParent().EntityId);
 }
Beispiel #54
0
 public void GridSplit(IMyCubeGrid gridA, IMyCubeGrid gridB)
 {
     CleanBlockLists();
 }
Beispiel #55
0
        public static void FindLookAtEntity(IMyControllableEntity controlledEntity, bool ignoreOccupiedGrid, bool ignoreProjection, out IMyEntity lookEntity, out double lookDistance, out Vector3D hitPoint, bool findShips, bool findCubes, bool findPlayers, bool findAsteroids, bool findPlanets, bool findReplicable)
        {
            const float range = 5000000;
            Matrix      worldMatrix;
            Vector3D    startPosition;
            Vector3D    endPosition;
            IMyCubeGrid occupiedGrid = null;

            if (controlledEntity.Entity.Parent == null)
            {
                worldMatrix   = controlledEntity.GetHeadMatrix(true, true, false); // dead center of player cross hairs, or the direction the player is looking with ALT.
                startPosition = worldMatrix.Translation + worldMatrix.Forward * 0.5f;
                endPosition   = worldMatrix.Translation + worldMatrix.Forward * (range + 0.5f);
            }
            else
            {
                occupiedGrid = controlledEntity.Entity.GetTopMostParent() as IMyCubeGrid;
                worldMatrix  = controlledEntity.Entity.WorldMatrix;
                // TODO: need to adjust for position of cockpit within ship.
                startPosition = worldMatrix.Translation + worldMatrix.Forward * 1.5f;
                endPosition   = worldMatrix.Translation + worldMatrix.Forward * (range + 1.5f);
            }

            var entites = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(entites, e => e != null);

            var list = new Dictionary <IMyEntity, double>();
            var ray  = new RayD(startPosition, worldMatrix.Forward);

            foreach (var entity in entites)
            {
                if (findShips || findCubes)
                {
                    var cubeGrid = entity as IMyCubeGrid;

                    if (cubeGrid != null)
                    {
                        if (ignoreOccupiedGrid && occupiedGrid != null && occupiedGrid.EntityId == cubeGrid.EntityId)
                        {
                            continue;
                        }

                        // Will ignore Projected grids, new grid/cube placement, and grids in middle of copy/paste.
                        if (ignoreProjection && cubeGrid.Physics == null)
                        {
                            continue;
                        }

                        // check if the ray comes anywhere near the Grid before continuing.
                        if (ray.Intersects(entity.WorldAABB).HasValue)
                        {
                            var hit = cubeGrid.RayCastBlocks(startPosition, endPosition);
                            if (hit.HasValue)
                            {
                                var distance = (startPosition - cubeGrid.GridIntegerToWorld(hit.Value)).Length();
                                var block    = cubeGrid.GetCubeBlock(hit.Value);

                                if (block.FatBlock != null && findCubes)
                                {
                                    list.Add(block.FatBlock, distance);
                                }
                                else if (findShips)
                                {
                                    list.Add(entity, distance);
                                }
                            }
                        }
                    }
                }

                if (findPlayers)
                {
                    var controller = entity as IMyControllableEntity;
                    if (controlledEntity.Entity.EntityId != entity.EntityId && controller != null && ray.Intersects(entity.WorldAABB).HasValue)
                    {
                        var distance = (startPosition - entity.GetPosition()).Length();
                        list.Add(entity, distance);
                    }
                }

                if (findReplicable)
                {
                    var replicable = entity as Sandbox.Game.Entities.MyInventoryBagEntity;
                    if (replicable != null && ray.Intersects(entity.WorldAABB).HasValue)
                    {
                        var distance = (startPosition - entity.GetPosition()).Length();
                        list.Add(entity, distance);
                    }
                }

                if (findAsteroids)
                {
                    var voxelMap = entity as IMyVoxelMap;
                    if (voxelMap != null)
                    {
                        var aabb = new BoundingBoxD(voxelMap.PositionLeftBottomCorner, voxelMap.PositionLeftBottomCorner + voxelMap.Storage.Size);
                        var hit  = ray.Intersects(aabb);
                        if (hit.HasValue)
                        {
                            var center   = voxelMap.PositionLeftBottomCorner + (voxelMap.Storage.Size / 2);
                            var distance = (startPosition - center).Length();  // use distance to center of asteroid.
                            list.Add(entity, distance);
                        }
                    }
                }

                if (findPlanets)
                {
                    // Looks to be working against Git and public release.
                    var planet = entity as Sandbox.Game.Entities.MyPlanet;
                    if (planet != null)
                    {
                        var aabb = new BoundingBoxD(planet.PositionLeftBottomCorner, planet.PositionLeftBottomCorner + planet.Size);
                        var hit  = ray.Intersects(aabb);
                        if (hit.HasValue)
                        {
                            var center   = planet.WorldMatrix.Translation;
                            var distance = (startPosition - center).Length(); // use distance to center of planet.
                            list.Add(entity, distance);
                        }
                    }
                }
            }

            if (list.Count == 0)
            {
                lookEntity   = null;
                lookDistance = 0;
                hitPoint     = Vector3D.Zero;
                return;
            }

            // find the closest Entity.
            var item = list.OrderBy(f => f.Value).First();

            lookEntity   = item.Key;
            lookDistance = item.Value;
            hitPoint     = startPosition + (Vector3D.Normalize(ray.Direction) * lookDistance);
        }
Beispiel #56
0
        public GridEntity(IMyEntity entity) : base(entity)
        {
            Type     = EntityType.Grid;
            CubeGrid = entity as IMyCubeGrid;

            LinkedGrids = new List <GridEntity>();

            AllTerminalBlocks = new List <BlockEntity>();
            Antennas          = new List <BlockEntity>();
            Beacons           = new List <BlockEntity>();
            Containers        = new List <BlockEntity>();
            Controllers       = new List <BlockEntity>();
            Gravity           = new List <BlockEntity>();
            Guns       = new List <BlockEntity>();
            JumpDrives = new List <BlockEntity>();
            Mechanical = new List <BlockEntity>();
            Medical    = new List <BlockEntity>();
            NanoBots   = new List <BlockEntity>();
            Production = new List <BlockEntity>();
            Power      = new List <BlockEntity>();
            RivalAi    = new List <BlockEntity>();
            Shields    = new List <BlockEntity>();
            Thrusters  = new List <BlockEntity>();
            Tools      = new List <BlockEntity>();
            Turrets    = new List <BlockEntity>();

            BlockListReference = new Dictionary <BlockTypeEnum, List <BlockEntity> >();
            BlockListReference.Add(BlockTypeEnum.All, AllTerminalBlocks);
            BlockListReference.Add(BlockTypeEnum.Antennas, Antennas);
            BlockListReference.Add(BlockTypeEnum.Beacons, Beacons);
            BlockListReference.Add(BlockTypeEnum.Containers, Containers);
            BlockListReference.Add(BlockTypeEnum.Controllers, Controllers);
            BlockListReference.Add(BlockTypeEnum.Gravity, Gravity);
            BlockListReference.Add(BlockTypeEnum.Guns, Guns);
            BlockListReference.Add(BlockTypeEnum.JumpDrives, JumpDrives);
            BlockListReference.Add(BlockTypeEnum.Mechanical, Mechanical);
            BlockListReference.Add(BlockTypeEnum.Medical, Medical);
            BlockListReference.Add(BlockTypeEnum.NanoBots, NanoBots);
            BlockListReference.Add(BlockTypeEnum.Production, Production);
            BlockListReference.Add(BlockTypeEnum.Power, Power);
            BlockListReference.Add(BlockTypeEnum.RivalAi, RivalAi);
            BlockListReference.Add(BlockTypeEnum.Shields, Shields);
            BlockListReference.Add(BlockTypeEnum.Thrusters, Thrusters);
            BlockListReference.Add(BlockTypeEnum.Tools, Tools);
            BlockListReference.Add(BlockTypeEnum.Turrets, Turrets);

            if (CubeGrid.Physics == null)
            {
                CubeGrid.OnPhysicsChanged += PhysicsCheck;
            }
            else
            {
                HasPhysics = true;
            }

            if (string.IsNullOrWhiteSpace(MyVisualScriptLogicProvider.GetEntityName(CubeGrid.EntityId)))
            {
                MyVisualScriptLogicProvider.SetName(CubeGrid.EntityId, CubeGrid.EntityId.ToString());
            }

            var blockList = new List <IMySlimBlock>();

            CubeGrid.GetBlocks(blockList);

            foreach (var block in blockList)
            {
                NewBlockAdded(block);
            }

            CubeGrid.OnBlockAdded += NewBlockAdded;
            CubeGrid.OnGridSplit  += GridSplit;
        }
Beispiel #57
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            bool showConcealed = true;

            if (words.Length > 0 && words[0].ToLower() == "revealed")
            {
                showConcealed = false;
            }

            if (showConcealed)
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Concealed Entities ===");
                int count = 0;
                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entity.InScene)
                    {
                        continue;
                    }

                    IMyCubeGrid grid      = (IMyCubeGrid)entity;
                    long        ownerId   = 0;
                    string      ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId   = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition())));
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total concealed entities: {0}", count));
            }
            else
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Revealed Entities ===");
                Communication.SendPrivateInformation(userId, "==== Unconnected Entities ===");
                HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>();
                CubeGrids.GetGridsUnconnected(entitiesFound, entities);
                int count = 0;
                List <IMySlimBlock> slimBlocks = new List <IMySlimBlock>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    IMyCubeGrid grid      = (IMyCubeGrid)entity;
                    long        ownerId   = 0;
                    string      ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId   = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total unconnected revealed entities: {0}", count));

                Communication.SendPrivateInformation(userId, "==== Connected Entities ===");
                HashSet <IMyEntity> connectedFound = new HashSet <IMyEntity>();
                CubeGrids.GetConnectedGrids(connectedFound);
                Console.WriteLine("Here: {0} : {1} {2}", connectedFound.Intersect(entitiesFound).Count(), entitiesFound.Count, connectedFound.Count);
                count = 0;
                slimBlocks.Clear();
                foreach (IMyEntity entity in connectedFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entitiesFound.Contains(entity))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    if (CubeGrids.GetRecursiveGridList((IMyCubeGrid)entity).Count < 2)
                    {
                        continue;
                    }

                    IMyCubeGrid grid      = (IMyCubeGrid)entity;
                    long        ownerId   = 0;
                    string      ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId   = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count, CubeGrids.GetRecursiveGridList(grid).Count));
                    //Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total connected revealed entities: {0}", count));
            }

            return(true);
        }
Beispiel #58
0
        private static Dictionary <long, long> ProcessAsteroidOwnership()
        {
            Dictionary <long, long> result   = new Dictionary <long, long>();
            HashSet <IMyEntity>     entities = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(entities);

            foreach (IMyEntity entity in entities)
            {
                if (!(entity is IMyVoxelMap))
                {
                    continue;
                }

                if (!entity.Save)
                {
                    continue;
                }
                IMyVoxelMap            voxel         = (IMyVoxelMap)entity;
                BoundingSphereD        sphere        = new BoundingSphereD(entity.GetPosition(), 500);   // Size of sphere around Roid
                List <IMyEntity>       blocks        = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
                Dictionary <long, int> asteroidScore = new Dictionary <long, int>();

                foreach (IMyEntity block in blocks)
                {
                    if (block is IMyCubeBlock)
                    {
                        IMyCubeBlock cube = (IMyCubeBlock)block;

                        if (!(cube.GetTopMostParent() is IMyCubeGrid))
                        {
                            continue;
                        }

                        IMyCubeGrid parent = (IMyCubeGrid)cube.GetTopMostParent();
                        if (!parent.IsStatic)
                        {
                            continue;
                        }
                        if (cube.OwnerId != 0 && TestBeacon(cube))                         // Test Valid Beacon.
                        {
                            if (!asteroidScore.ContainsKey(cube.OwnerId))
                            {
                                asteroidScore.Add(cube.OwnerId, 0);
                            }

                            asteroidScore[cube.OwnerId] = asteroidScore[cube.OwnerId] + 1;
                        }
                    }
                }

                long asteroidOwner = asteroidScore.OrderBy(x => x.Value).Where(x => x.Value > 0).Select(x => x.Key).FirstOrDefault();
                if (asteroidOwner != 0)
                {
                    MyObjectBuilder_Checkpoint.PlayerItem item = PlayerMap.Instance.GetPlayerItemFromPlayerId(asteroidOwner);
                    //Console.WriteLine(string.Format("Owner of asteroid at: {0} is {1}", General.Vector3DToString(entity.GetPosition()), item.Name));
                    result.Add(entity.EntityId, asteroidOwner);
                }
            }

            return(result);
        }
Beispiel #59
0
        /// <summary>
        /// Attempts to place count of a physical object in inventory of grid
        /// Will place as many of the object as possible in each inventory until
        /// nothing remains to place. Returns number remaining to place.
        /// </summary>
        public static int placeInCargo(this IMyCubeGrid grid,
                                       SerializableDefinitionId def, MyObjectBuilder_Component builder,
                                       int count)
        {
            if (count <= 0)
            {
                return(0);
            }
            int remaining = count;

            var containers = new List <IMySlimBlock>();

            grid.GetBlocks(containers, x =>
                           x.FatBlock != null &&
                           x.FatBlock as Interfaces.IMyInventoryOwner != null
                           );
            if (containers.Count == 0)
            {
                return(remaining);
            }

            foreach (IMySlimBlock block in containers)
            {
                if (remaining == 0)
                {
                    break;
                }

                var inventoryOwner = block.FatBlock as Interfaces.IMyInventoryOwner;
                var inventory      = inventoryOwner.GetInventory(0) as IMyInventory;

                if (inventory == null)
                {
                    // log error, invOwner existed but not inventory>?
                    continue;
                }

                if (inventory.CanItemsBeAdded((VRage.MyFixedPoint)remaining, def))
                {
                    // Add all the items if it has enough space
                    inventory.AddItems(remaining, builder);
                    remaining = 0;
                }
                else
                {
                    // Add them incrementally if there's some space
                    // I would prefer to do some math to tell how many we can add,
                    // instead of just continually looping through with 1.
                    // But the logic to get the volume of a component
                    // is surprisingly complex without access to the Adapter
                    // and we'd need to check the inventory's supported types
                    while (remaining > 0 && inventory.CanItemsBeAdded((VRage.MyFixedPoint) 1, def))
                    {
                        inventory.AddItems(1, builder);
                        remaining--;
                    }
                }
            }

            return(remaining);
        }
 public static List <T> GetTerminalBlocksOfType <T>(this IMyCubeGrid grid) where T : IMyTerminalBlock
 {
     return(GetTerminalBlocksOfType <T>(grid, null));
 }