예제 #1
0
        internal override void JoinAsEscort(IMyCubeGrid escortApplicant, UnitType unitType, MyPlanet marsPlanet)
        {
            var            applicantPosition = escortApplicant.GetPosition();
            var            gravity           = marsPlanet.GetGravityAtPoint(applicantPosition);
            var            closestDistSq     = double.MaxValue;
            EscortPosition?closestPosition   = null;

            foreach (var escortPosition in GetPotentialEscortPositions(unitType))
            {
                if (!escortDic.ContainsKey(escortPosition))
                {
                    var suggestedPosition = GetEscortPositionVector(leader, gravity, escortPosition, GetAdditionalHeightModifier());
                    var distSq            = Vector3D.DistanceSquared(applicantPosition, suggestedPosition);
                    if (distSq < closestDistSq)
                    {
                        closestDistSq   = distSq;
                        closestPosition = escortPosition;
                    }
                }
            }

            if (closestPosition.HasValue)
            {
                escortDic.Add(closestPosition.Value, escortApplicant);
                //TODO: Update the new recruit on our current state and have them act appropriately?
            }
        }
예제 #2
0
        /// <summary>
        /// Returns a list of players within radius of grid
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        public static List <IMyPlayer> getPlayersWithin(this IMyCubeGrid self, float radius)
        {
            log("Getting players near grid " + self.DisplayName);

            Vector3 position = self.GetPosition();

            return(MyAPIGateway.Players.getPlayersNearPoint(position, radius));
        }
예제 #3
0
        public void Update60()
        {
            if (!remoteControl.IsControlledByFaction("GCORP"))
            {
//				return; // No point bothering to remove from the list, it will disappear next time the game reloads
            }

            /*
             * TODO:
             * refill weapon inventory (if designated?)
             * sequence shooting when multiple on same sub-grid
             * appropriate sequencing for missile launchers
             */
            playerTarget = DuckUtils.GetNearestPlayerToPosition(bodyGrid.GetPosition(), Range);
            if (playerTarget != null)
            {
//MyAPIGateway.Utilities.ShowNotification("Found Player: " + info.Type, 2000, MyFontEnum.DarkBlue);

                IHitInfo hitInfo;
                if (MyAPIGateway.Physics.CastLongRay(weapons[0].GetPosition(), playerTarget.GetPosition(), out hitInfo, false))
                {
                    if (!spoken)
                    {
                        bodyGrid.PlaySoundBlocks();
                        spoken = true;
                    }

                    if (timeSincePlayerSeen < 3)
                    {
                        timeSincePlayerSeen++;
                        return;
                    }

                    var info = MyDetectedEntityInfoHelper.Create((MyEntity)hitInfo.HitEntity, remoteControl.OwnerId, hitInfo.Position);
                    if (info.Relationship == MyRelationsBetweenPlayerAndBlock.Enemies ||
                        info.Relationship == MyRelationsBetweenPlayerAndBlock.NoOwnership ||
                        info.Relationship == MyRelationsBetweenPlayerAndBlock.Neutral)
                    {
                        SetWeaponsShooting(true);
                    }
                    else
                    {
                        SetWeaponsShooting(false);
                    }
//					MyAPIGateway.Utilities.ShowNotification("Hit: " + info.Type, 2000, MyFontEnum.DarkBlue);
//					MyAPIGateway.Utilities.ShowNotification("Relation: " + info.Relationship, 2000, MyFontEnum.DarkBlue);
                }
                else
                {
                    SetWeaponsShooting(true);
                }
            }
            else
            {
                SetWeaponsShooting(false);
                StopAllRotors();
            }
        }
예제 #4
0
        public void UpdateSurfaceLocation(TrackedEntity pm)
        {
            //log.Debug("initial location to save: "+ pm.AttackPoint);
            var point = new PointOfInterest(pm.AttackPoint, pm.EntityID);

            //log.Debug(pm.AttackPoint+"");
            PlanetaryData planet = KnownPlanets.FirstOrDefault(x => x.PlanetCenter == pm.Location);
            Region        region = null;

            region = new Region(pm.EntityID, pm.Location, point, iscmd, cubeGrid.GetPosition(), log);
            if (planet != null)
            {
                planet.UpdatePlanetaryData(region, cubeGrid.GetPosition());
            }

            //if no planet
            if (planet == null)
            {
                planet = CreateNewPlanet(pm.EntityID, pm.Location, region, point, cubeGrid.GetPosition());


                //if point is in current region, update region
                if (currentRegion.EntityId == pm.EntityID)
                {
                    currentRegion.UpdatePoints(point);
                }

                //if point in another region, increase its scan density
                //log.Debug("Number of regions: " + nearestPlanet.Regions.Count);
            }
            if (KnownPlanets.Count > 1)
            {
                nearestPlanet = KnownPlanets.OrderBy(x => (x.PlanetCenter - pm.Location).Length()).FirstOrDefault();
            }
        }
        public FoundGrid(IMyCubeGrid g)
        {
            grid  = g;
            type  = g.Physics == null ? "Station" : g.GridSizeEnum == MyCubeSize.Large ? "Large Ship" : "Small Ship";
            owner = calculateOwner();

            gpsValue = MyAPIGateway.Session.GPS.Create(ToString(), "", grid.GetPosition(), true);
            gpsID    = gpsValue.Hash | ~(((long)gpsValue.Hash) << 32);
        }
        public void updateData()
        {
            Vector3D pos = grid.GetPosition();

            position        = pos.X + ", " + pos.Y + ", " + pos.Z;
            gpsValue.Coords = pos;
            gpsValue.Name   = ToString();
            MyAPIGateway.Session.GPS.ModifyGps(gpsID, gpsValue);
        }
예제 #7
0
        public void UpdateRegionInfo(Dictionary <long, Region> regions, IMyCubeGrid grid)
        {
            List <string> lines = new List <string>();

            foreach (var ent in regions.OrderByDescending(x => (x.Value.PointsOfInterest).Count).Take(10))
            {
                var near     = ent.Value.GetNearestPoint(grid.GetPosition());
                var distance = (int)(near - grid.GetPosition()).Length();
                lines.Add(" size: " + ent.Value.PointsOfInterest.Count() + "   distance: " + (int)distance + "m\n" +
                          "       --last scanned: " + (int)(DateTime.Now - ent.Value.LastUpdated).TotalSeconds + "s " +
                          "  scan density: " + ent.Value.GetScanDensity() + "\n" +
                          "       --surface scan coverage: " + ent.Value.GetPercentReached());
            }
            lines.Add(" Number of Detected Regions: " + regions.Count());
            var screens = components.TextPanels.Where(x => x.CustomName.Contains("#planets#")).ToList();

            UpdateLCD(lines, screens, "Regions");
        }
예제 #8
0
        public void Update60()
        {
            // TODO: need a reference to the whole base grid to properly determine ownership
            if (!remoteControl.IsControlledByFaction("GCORP"))
            {
//				return; // No point bothering to remove from the list, it will disappear next time the game reloads
            }

            playerTarget = DuckUtils.GetNearestPlayerToPosition(bodyGrid.GetPosition(), Range);
            if (playerTarget != null)
            {
                IHitInfo hitInfo;
                if (MyAPIGateway.Physics.CastLongRay(weapons[0].GetPosition(), playerTarget.GetPosition(), out hitInfo, false))
                {
                    if (!spoken)
                    {
                        bodyGrid.PlaySoundBlocks();
                        spoken = true;
                    }

                    if (timeSincePlayerSeen < 3)
                    {
                        timeSincePlayerSeen++;
                        return;
                    }

                    var info = MyDetectedEntityInfoHelper.Create((MyEntity)hitInfo.HitEntity, remoteControl.OwnerId, hitInfo.Position);
                    if (info.Relationship == MyRelationsBetweenPlayerAndBlock.Enemies ||
                        info.Relationship == MyRelationsBetweenPlayerAndBlock.NoOwnership ||
                        info.Relationship == MyRelationsBetweenPlayerAndBlock.Neutral)
                    {
                        SetWeaponsShooting(true);
                    }
                    else
                    {
                        SetWeaponsShooting(false);
                    }
                    //	MyAPIGateway.Utilities.ShowNotification("Hit: " + info.Type, 2000, MyFontEnum.DarkBlue);
                    //	MyAPIGateway.Utilities.ShowNotification("Relation: " + info.Relationship, 2000, MyFontEnum.DarkBlue);
                }
                else
                {
                    SetWeaponsShooting(true);
                }
            }
            else
            {
                SetWeaponsShooting(false);
                StopAllRotors();
            }
        }
예제 #9
0
        public static HashSet <IMyVoxelMap> GetNearbyRoids(this IMyCubeGrid Grid, float Radius = 3000)
        {
            BoundingSphereD       Sphere = new BoundingSphereD(Grid.GetPosition(), Radius);
            HashSet <IMyVoxelMap> Roids  = new HashSet <IMyVoxelMap>();

            foreach (var entity in MyAPIGateway.Entities.GetTopMostEntitiesInSphere(ref Sphere))
            {
                if (entity is IMyVoxelMap && !(entity is MyPlanet))
                {
                    Roids.Add(entity as IMyVoxelMap);
                }
            }
            return(Roids);
        }
예제 #10
0
        protected static bool AttemptDespawn(IMyCubeGrid grid)
        {
            if (!grid.IsControlledByNpcFaction())
            {
                return(true);                // If we are not GCorp don't try to despawn, we may be wreckage or player hijacked
            }

            if (!DuckUtils.IsAnyPlayerNearPosition(grid.GetPosition(), 1750))
            {
                grid.CloseAll();
                return(true);
            }

            return(false);
        }
예제 #11
0
        private bool IsGridTooFarFromPlayers(IMyCubeGrid cubeGrid, double distance = cleanupDistance)
        {
            var players = new List <IMyPlayer>();

            MyAPIGateway.Players.GetPlayers(players, (x) => !x.IsBot);
            foreach (var player in players)
            {
                var dis = Vector3D.Distance(player.GetPosition(), cubeGrid.GetPosition());
                if (dis < distance)
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #12
0
        public void SpawnConvoyEscorts(IMyCubeGrid convoyLeaderGrid, UnitType unitType, MyPlanet planet)
        {
            var gravity = planet.GetGravityAtPoint(convoyLeaderGrid.GetPosition());
            var escortsNeededToSpawn = heatSystem.GenerateEscortSpecs();

            if (unitType == UnitType.Air)
            {
                SpawnAirEscorts(escortsNeededToSpawn, gravity, convoyLeaderGrid);
            }
            else
            {
                SpawnLandEscorts(escortsNeededToSpawn, gravity, convoyLeaderGrid);
                SpawnAirEscorts(escortsNeededToSpawn, gravity, convoyLeaderGrid);
            }
        }
예제 #13
0
            public GridSnapshot(IMyCubeGrid entity)
            {
                Name     = entity.DisplayName;
                Position = entity.GetPosition();

                FirstOwnerName       = "<null>";
                FirstOwnerFactionTag = "<null>";
                if (entity.BigOwners.TryGetFirst(out var ownerId))
                {
                    var id = MySession.Static.Players.TryGetIdentity(ownerId);
                    FirstOwnerName = id?.DisplayName ?? "<null>";

                    var faction = MySession.Static.Factions.TryGetPlayerFaction(ownerId);
                    FirstOwnerFactionTag = faction?.Tag ?? "<null>";
                }
            }
예제 #14
0
        protected static bool AttemptDespawn(IMyCubeGrid grid, Int32 minplayerdistance = 1750)
        {
            if (!grid.IsControlledByFaction("GCORP"))
            {
                return(true);                // If we are not GCorp don't try to despawn, we may be wreckage or player hijacked
            }

            // if player is 'near' base, then disabled drones near the base won't be despawned
            //			if (!DuckUtils.IsAnyPlayerNearPosition(grid.GetPosition(), 1750))

            // V26
            if (!DuckUtils.IsAnyPlayerNearPosition(grid.GetPosition(), minplayerdistance))
            {
                grid.CloseAll();
                return(true);
            }

            return(false);
        }
        private string GetCubeGridNameToAnnounce(IMyCubeGrid cubeGrid)
        {
            try
            {
                // Is there an easier way to detect non-human players?

                var owners = cubeGrid.SmallOwners;

                var identities = new List <IMyIdentity>();
                MyAPIGateway.Players.GetAllIdentites(identities, identity => identity != null && owners.Contains(identity.IdentityId));

                var notHuman = identities.Count > 0 && identities
                               .Select(identity => MyAPIGateway.Session.Factions.TryGetPlayerFaction(identity.IdentityId))
                               .All(faction => faction != null && !faction.AcceptHumans);

                var players = new List <IMyPlayer>();
                MyAPIGateway.Players.GetPlayers(players, player => player != null);

                IMyPlayer nearestPlayer         = null;
                var       nearestPlayerDistance = double.NaN;
                if (players.Count > 0)
                {
                    var gridPosition = cubeGrid.GetPosition();

                    Func <IMyPlayer, double> getDistanceToPlayer = player => (player.GetPosition() - gridPosition).Length();
                    players.Sort((player1, player2) => (int)Math.Round(getDistanceToPlayer(player1) - getDistanceToPlayer(player2)));

                    nearestPlayer         = players[0];
                    nearestPlayerDistance = getDistanceToPlayer(nearestPlayer);
                }

                var ownerNameString = Utilities.GetOwnerNameString(owners, identities);
                return(string.Format("{0} (owned by {1}{2}{3})", cubeGrid.DisplayName, ownerNameString,
                                     nearestPlayer != null ? string.Format(", {0:0.##} m to {1}", nearestPlayerDistance, nearestPlayer.DisplayName) : "",
                                     notHuman ? " - is that a drone/cargo ship?" : ""));
            }
            catch (Exception ex)
            {
                Logger.WriteLine("Exception in GetCubeGridNameToAnnounce: {0}", ex);
                return("a thing full of errors :/");
            }
        }
예제 #16
0
        public static bool GetDistanceBetweenGridAndPlayer(IMyCubeGrid grid, IMyPlayer player, out double distance)
        {
            distance = 0d;

            try
            {
                if (player.Controller == null || player.Controller.ControlledEntity == null || player.Controller.ControlledEntity.Entity == null)
                {
                    return(false);
                }

                Vector3D playerPosition = player.Controller.ControlledEntity.Entity.GetPosition();
                distance = Vector3D.Distance(grid.GetPosition(), playerPosition);
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole("GetDistanceBetweenGridAndPlayer(): {0}", ex.ToString());
                return(false);
            }

            return(true);
        }
예제 #17
0
        public void SpawnerCallback(EncounterType encounterType, MySpawnGroupDefinition.SpawnGroupPrefab prefab, Vector3D spawnCoord, Vector3D despawnCoords, IMyFaction ownerFaction)
        {
            Util.Log("Searching for spawned Prefab...");
            IMyCubeGrid      spawnedShip  = null;
            double           minDist      = double.MaxValue;
            BoundingSphereD  searchSphere = new BoundingSphereD(spawnCoord, SPAWNER_SEARCH_RADIUS);
            List <IMyEntity> entityList   = MyAPIGateway.Entities.GetEntitiesInSphere(ref searchSphere);

            foreach (IMyEntity entity in entityList)
            {
                IMyCubeGrid targetGrid = entity as IMyCubeGrid;
                if (targetGrid == null)
                {
                    continue;
                }
                //if (targetGrid.CustomName != prefab.SubtypeId) {
                //continue;
                //}
                if ((targetGrid.GetPosition() - spawnCoord).LengthSquared() < minDist)
                {
                    spawnedShip = targetGrid;
                }
            }
            if (spawnedShip == null)
            {
                Util.Error("Error: Could not find ship " + prefab.SubtypeId + " after spawning.");
                return;
            }
            spawnedShip.ChangeGridOwnership(m_empireData.m_faction.FounderId, MyOwnershipShareModeEnum.None);

            IMyGridTerminalSystem   gts    = spawnedShip.GetTerminalSystem();
            List <IMyRemoteControl> blocks = new List <IMyRemoteControl>();

            gts.GetBlocksOfType(blocks);
            IMyRemoteControl firstRemote = blocks.Find(b => b.IsFunctional);

            LaunchDrone(encounterType, firstRemote, spawnedShip, despawnCoords);
        }
예제 #18
0
        /// <summary>
        /// Group grids in the CP into subfleets
        /// </summary>
        private Dictionary <long, Subfleet> nearbySubfleets()
        {
            var foundSubfleets = new Dictionary <long, Subfleet>();

            log("Grouping nearby grids into Subfleets.", "nearbySubfleets");

            VRageMath.BoundingSphereD bounds           = new VRageMath.BoundingSphereD(Position, (double)Radius);
            List <IMyEntity>          entitiesInBounds = MyAPIGateway.Entities.GetEntitiesInSphere(ref bounds);

            foreach (IMyEntity e in entitiesInBounds)
            {
                // Is it a grid?
                IMyCubeGrid grid = e as IMyCubeGrid;
                if (grid == null)
                {
                    continue;
                }

                // does it have a GE?
                GridEnforcer ge = grid.Components.Get <MyGameLogicComponent>() as GridEnforcer;
                if (ge == null)
                {
                    log("Failed to retrieve GridEnforcer for grid " + grid.EntityId,
                        "nearbySubfleets", Logger.severity.ERROR);
                    continue;
                }

                // Is it classified?
                if (ge.Class == HullClass.CLASS.UNCLASSIFIED)
                {
                    continue;
                }


                // There are no hooks to check if someone changed factions,
                // so reevaluate here to make sure info is up to date for fleet groups
                ge.reevaluateOwnership();

                /*
                 * if (ge.Owner.OwnerType == GridOwner.OWNER_TYPE.UNOWNED) {
                 *      log("Grid " + grid.EntityId + " is unowned, skipping",
                 *              "nearbySubfleets");
                 *      continue;
                 * }
                 */

                // We could check here if the grid is supported by its fleet,
                // or more generally if it's violation any rules
                // But we should notify players, b/c that could be confusing

                /*
                 * if (!ge.SupportedByFleet) {
                 *      log("Grid " + grid.DisplayName + " is unsupported by its fleet, skipping.",
                 *              "getRoundWinner");
                 *      continue;
                 * }
                 */

                // Is its Hull Classifier broadcasting far enough?
                HullClassifier classifier = ge.Classifier;
                if (classifier == null)
                {
                    log("Grid has no classifier but was classified",
                        "nearbySubfleets", Logger.severity.ERROR);
                    continue;
                }

                IMyCubeBlock fatblock = classifier.FatBlock;
                if (fatblock == null)
                {
                    log("Classifier could not be referenced as fatblock",
                        "nearbySubfleets", Logger.severity.ERROR);
                    continue;
                }
                if (!fatblock.IsWorking)
                {
                    log("Classifier not working but grid was classified",
                        "nearbySubfleets", Logger.severity.ERROR);
                    continue;
                }

                InGame.IMyBeacon       beacon  = fatblock as InGame.IMyBeacon;
                InGame.IMyRadioAntenna antenna = fatblock as InGame.IMyRadioAntenna;
                if (beacon == null && antenna == null)
                {
                    log("Classifier not a beacon or antennae, no broadcast radius",
                        "nearbySubfleets", Logger.severity.ERROR);
                    continue;
                }
                if (beacon != null && beacon.Radius <
                    VRageMath.Vector3.Distance(Position, grid.GetPosition()))
                {
                    log("Classifier range too small, skipping", "nearbySubfleets");
                    // TODO notify pilot
                    continue;
                }
                if (antenna != null && antenna.Radius <
                    VRageMath.Vector3.Distance(Position, grid.GetPosition()))
                {
                    log("Classifier range too small, skipping", "nearbySubfleets");
                    // TODO notify pilot
                    continue;
                }

                // Grid passed all tests!
                long fleetID = ge.Owner.FleetID;
                log("Grid '" + ge.Grid.DisplayName + "'passed all tests, including in fleet " + fleetID, "nearbySubfleets");
                if (!foundSubfleets.ContainsKey(fleetID))
                {
                    foundSubfleets[fleetID] = new Subfleet {
                        ID        = fleetID,
                        Enforcers = new List <GridEnforcer>()
                        {
                            ge
                        },
                        TotalValue = ge.CaptureMultiplier,
                    };
                }
                else
                {
                    foundSubfleets[fleetID].Enforcers.Add(ge);
                    foundSubfleets[fleetID].TotalValue += ge.CaptureMultiplier;
                }
            }

            return(foundSubfleets);
        }
예제 #19
0
        private static bool DoesGridHaveTarget(IMyCubeGrid grid, IMySlimBlock block, bool disabling = false)
        {
            if (_scanCache.Count < 1)
            {
                BoundingSphereD sphere = new BoundingSphereD(grid.GetPosition(), PluginSettings.Instance.DynamicTurretTargetDistance);
                _scanCache = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
            }

            /*
             * HashSet<IMyEntity> testEntities = new HashSet<IMyEntity>();
             * try
             * {
             *      MyAPIGateway.Entities.GetEntities(testEntities);
             * }
             * catch
             * {
             *      return false;
             * }
             */
            //bool found = false;
            foreach (IMyEntity testEntity in _scanCache)
            {
                if (grid == testEntity)
                {
                    continue;
                }

                if (!testEntity.InScene)
                {
                    continue;
                }

                if (testEntity is IMyCubeBlock)
                {
                    continue;

                    /*
                     * IMyCubeBlock cubeBlock = (IMyCubeBlock)testEntity;
                     * if (cubeBlock.OwnerId == 0)
                     *      continue;
                     *
                     * if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner)
                     * {
                     *      if (block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) != Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Owner)
                     *      {
                     *              Console.WriteLine("Block: Not owner");
                     *              return true;
                     *      }
                     * }
                     *
                     * if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
                     * {
                     *      if (block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Enemies ||
                     *              block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Neutral)
                     *      {
                     *              Console.WriteLine("Block: Enemy or Neutral: {0} {1} {2}", cubeBlock.OwnerId, cubeBlock.Parent.DisplayName, cubeBlock.BlockDefinition);
                     *              return true;
                     *      }
                     * }
                     *
                     * if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
                     * {
                     *      if (block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Enemies)
                     *      {
                     * //							Console.WriteLine("Block: Enemy: {0} {1} {2}", cubeBlock.OwnerId, cubeBlock.Parent.DisplayName, cubeBlock.BlockDefinition);
                     *              return true;
                     *      }
                     * }
                     */
                }

                if (testEntity is IMyCubeGrid)
                {
                    if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.All)
                    {
                        return(true);
                    }

                    IMyCubeGrid testGrid = (IMyCubeGrid)testEntity;
                    // Always enable if grid has no owner.  Seems suspect.  Might be a user trying to abuse a no ownership ship.

                    /*
                     * if (testGrid.BigOwners.Count < 1 && testGrid.SmallOwners.Count < 1)
                     * {
                     *      //if(!(testEntity is IMyControllableEntity))
                     *      //Console.WriteLine("Grid: No owner");
                     *      return true;
                     * }
                     */

                    foreach (long owner in testGrid.BigOwners)
                    {
                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(owner) != MyRelationsBetweenPlayerAndBlock.Owner)
                            {
                                //Console.WriteLine("Grid: Not owner");
                                return(true);
                            }
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies ||
                                block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Neutral)
                            {
                                //Console.WriteLine("Grid: Enemy or Neutral: {0} {1}", owner, grid.DisplayName);
                                return(true);
                            }
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies)
                            {
                                //Console.WriteLine("{3} Target: Grid - Enemy: {0} - {1} ({2})", block.FatBlock.OwnerId, owner, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);

                                //Console.WriteLine("Grid: Enemy: {0} {1}", owner, grid.DisplayName);
                                return(true);
                            }
                        }
                    }

                    foreach (long owner in testGrid.SmallOwners)
                    {
                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(owner) != MyRelationsBetweenPlayerAndBlock.Owner)
                            {
                                //Console.WriteLine("Grid: Not owner");
                                return(true);
                            }
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies ||
                                block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Neutral)
                            {
                                //Console.WriteLine("Grid: Enemy or Neutral: {0} {1}", owner, grid.DisplayName);
                                return(true);
                            }
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies)
                            {
                                //Console.WriteLine("Grid: Enemy: {0} {1}", owner, grid.DisplayName);
                                return(true);
                            }
                        }
                    }
                }
                else
                {
                    if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.All)
                    {
                        return(true);
                    }

                    if (testEntity is IMyCharacter)
//					var builderBase = testEntity.GetObjectBuilder();
//					if (builderBase is MyObjectBuilder_Character)
                    {
                        IMyPlayer   player = null;
                        IMyIdentity identity;
                        long        playerId = 0;
                        try
                        {
                            identity = IdentityCache.FirstOrDefault(x => x.DisplayName == testEntity.DisplayName);
                            //List<IMyPlayer> players = new List<IMyPlayer>();
                            //MyAPIGateway.Players.GetPlayers(players);
                            //player = players.FirstOrDefault(x => x.DisplayName == testEntity.DisplayName);

                            if (player == null)
                            {
                                /*
                                 * //player = players.FirstOrDefault(x => x.Controller != null && x.Controller.ControlledEntity != null && x.Controller.ControlledEntity.Entity != null && x.Controller.ControlledEntity.Entity.EntityId == testEntity.EntityId);
                                 * if(testEntity is IMyControllableEntity)
                                 * {
                                 *      IMyControllableEntity control = (IMyControllableEntity)testEntity;
                                 *      List<PlayerMap.InternalPlayerItem> items = PlayerMap.Instance.GetPlayerItemsFromPlayerName(control.Entity.DisplayName);
                                 *      if (items != null)
                                 *              playerId = items.First().playerId;
                                 * }
                                 */
                            }
                        }
                        catch
                        {
                            //Console.WriteLine("{3} Target: Character - Unknown: {0} - {1} ({2})", block.FatBlock.OwnerId, testEntity.EntityId, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);
                            //Console.WriteLine("Unknown1: {0}", testEntity.DisplayName);
                            return(true);
                        }

                        if (identity == null)
                        {
                            //Console.WriteLine("{3} Target: Character - Unknown2: {0} - {1} ({2})", block.FatBlock.OwnerId, testEntity.EntityId, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);
                            //Console.WriteLine("Unknown2: {0} - {1}", testEntity.DisplayName, testEntity.GetFriendlyName());
                            return(true);
                            //continue;
                        }

                        if (identity != null)
                        {
                            playerId = identity.PlayerId;
                        }

                        if (player != null)
                        {
                            playerId = player.PlayerID;
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner && block.FatBlock.GetUserRelationToOwner(playerId) != MyRelationsBetweenPlayerAndBlock.Owner)
                        {
                            //Console.WriteLine("Character: Not Owner: {0} - {1}", block.FatBlock.OwnerId, playerId);
                            return(true);
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Enemies ||
                                block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Neutral)
                            {
                                //Console.WriteLine("Character: Enemy or Neutral: {0} - {1}", block.FatBlock.OwnerId, playerId);
                                return(true);
                            }
                        }

                        if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
                        {
                            if (block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Enemies)
                            {
                                //Console.WriteLine("{3} Target: Character - Enemy: {0} - {1} ({2})", block.FatBlock.OwnerId, playerId, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
예제 #20
0
파일: Drone.cs 프로젝트: ESearcy/SE_MOD
 //ship location
 public Vector3D GetPosition()
 {
     return(Ship.GetPosition());
 }
예제 #21
0
        //public bool GravityTest(LineSegmentD line, Vector3D finalDestination, out MyEntity blockingPath, out Vector3? pointOfObstruction)
        //{
        //	if (Vector3.DistanceSquared(line.From, line.To) > 10000f)
        //	{
        //		BoundingBoxD box = line.BoundingBox;
        //		m_voxels.Clear();
        //		MyGamePruningStructure.GetAllVoxelMapsInBox(ref box, m_voxels);

        //		foreach (MyEntity entity in m_voxels)
        //		{
        //			MyPlanet planet = entity as MyPlanet;
        //			if (planet == null)
        //				continue;

        //			Vector3D planetCentre = planet.GetCentre();
        //			Vector3D closestPoint = line.ClosestPoint(planetCentre);

        //			if (!planet.IsPositionInGravityWell(closestPoint))
        //				continue;

        //			m_logger.debugLog("path: " + line.From + " to " + line.To + ", final: " + finalDestination + ", closest point: " + closestPoint + ", planet @ " + planetCentre + " : " + planet.getBestName(), "GravityTest()");

        //			if (closestPoint == line.From)
        //			{
        //				m_logger.debugLog("closest point is start", "GravityTest()");
        //				continue;
        //			}
        //			if (closestPoint == line.To)
        //			{
        //				if (line.To == finalDestination )
        //				{
        //					m_logger.debugLog("closest point is final", "GravityTest()");
        //					continue;
        //				}
        //				if (Vector3D.DistanceSquared(planetCentre, closestPoint) < Vector3D.DistanceSquared(planetCentre, finalDestination))
        //				{
        //					m_logger.debugLog("closest point is end, which is closer to planet than final dest is", "GravityTest()");
        //					blockingPath = entity;
        //					pointOfObstruction = closestPoint;
        //					return false;
        //				}
        //				m_logger.debugLog("closest point is end", "GravityTest()");
        //				continue;
        //			}

        //			//float startGravity = planet.GetWorldGravityGrid( line.From).LengthSquared();
        //			//float closestGravity = planet.GetWorldGravityGrid(closestPoint).LengthSquared();

        //			//double toDistSq = Vector3D.DistanceSquared(planetCentre, line.To);

        //			//if (closestPoint == line.To && (line.To == finalDestination ||     ))
        //			//{
        //			//	m_logger.debugLog("path: " + line.From + " to " + line.To + ", closest point: " + closestPoint + ", planet @ " + planetCentre + " : " + planet.getBestName(), "GravityTest()");
        //			//	m_logger.debugLog("closest point is end", "GravityTest()");
        //			//	continue;
        //			//}

        //			//m_logger.debugLog("path: " + line.From + " to " + line.To + ", closest point: " + closestPoint + ", planet @ " + planetCentre + " : " + planet.getBestName(), "GravityTest()", Logger.severity.DEBUG);


        //			double closestDistSq = Vector3D.DistanceSquared(planetCentre, closestPoint) + 1f;
        //			if (closestDistSq < Vector3D.DistanceSquared(planetCentre, line.From) || closestDistSq < Vector3D.DistanceSquared(planetCentre, line.To))
        //			{
        //				m_logger.debugLog("path moves ship closer to planet. closestDistSq: " + closestDistSq + ", from dist sq: " + Vector3D.DistanceSquared(planetCentre, line.From) + ", to dist sq: " + Vector3D.DistanceSquared(planetCentre, line.To), "GravityTest()", Logger.severity.INFO);
        //				blockingPath = entity;
        //				pointOfObstruction = closestPoint;
        //				return false;
        //			}
        //		}
        //	}

        //	blockingPath = null;
        //	pointOfObstruction = null;
        //	return true;
        //}

        /// <summary>
        /// How far long the line would the ship be able to travel? Uses a capsule derived from previously calculated path.
        /// </summary>
        /// <param name="canTravel">Line along which navigation block would travel</param>
        /// <remarks>
        /// Capsule only test because the ship will not be oriented correctly
        /// </remarks>
        /// <returns>distance from the destination that can be reached</returns>
        public float distanceCanTravel(LineSegment canTravel)
        {
            BoundingBoxD atFrom = m_grid.WorldAABB.Translate(canTravel.From - m_grid.GetPosition());
            BoundingBoxD atTo   = m_grid.WorldAABB.Translate(canTravel.To - m_grid.GetPosition());

            ICollection <MyEntity> offenders = EntitiesInLargeAABB(atFrom, atTo);

            if (offenders.Count == 0)
            {
                m_logger.debugLog("AABB is empty");
                return(0);
            }
            m_logger.debugLog("collected entities to test: " + offenders.Count);
            IOrderedEnumerable <MyEntity> ordered = offenders.OrderBy(entity => Vector3D.Distance(canTravel.From, entity.GetCentre()));

            Capsule path = new Capsule(canTravel.From, canTravel.To, m_path.Radius);
            Vector3?pointOfObstruction = null;

            foreach (MyEntity entity in ordered)
            {
                if (path.IntersectsAABB(entity))
                {
                    MyVoxelBase voxel = entity as MyVoxelBase;
                    if (voxel != null)
                    {
                        if (!TestVoxel(voxel, path, out pointOfObstruction))
                        {
                            m_logger.debugLog("obstruction at " + pointOfObstruction + " distance from dest is " + Vector3.Distance(canTravel.To, (Vector3)pointOfObstruction));
                            return(Vector3.Distance(canTravel.To, (Vector3)pointOfObstruction));
                        }
                    }

                    IMyCubeGrid grid = entity as IMyCubeGrid;
                    if (grid != null)
                    {
                        float         minDistSq = (m_grid.GridSize + grid.GridSize) * (m_grid.GridSize + grid.GridSize);
                        GridCellCache cache     = GridCellCache.GetCellCache(grid);
                        cache.ForEach(cell => {
                            Vector3 cellPos = grid.GridIntegerToWorld(cell);
                            if (canTravel.PointInCylinder(minDistSq, ref cellPos))
                            {
                                pointOfObstruction = cellPos;
                                return(true);
                            }
                            return(false);
                        });
                        if (pointOfObstruction.HasValue)
                        {
                            return(Vector3.Distance(canTravel.To, (Vector3)pointOfObstruction));
                        }
                    }

                    m_logger.debugLog("not a grid, testing bounds");
                    if (!m_path.IntersectsVolume(entity))
                    {
                        continue;
                    }

                    m_logger.debugLog("no more tests for non-grids are implemented", Logger.severity.DEBUG);
                    pointOfObstruction = m_path.get_Line().ClosestPoint(entity.GetCentre());
                    return(Vector3.Distance(canTravel.To, (Vector3)pointOfObstruction));
                }
            }

            // no obstruction
            m_logger.debugLog("no obstruction");
            return(0f);
        }
예제 #22
0
 public int AlignTo(Vector3D position)
 {
     for (int i = 0; i < alignCount && GyrosWork(); i++)
     {
         double realDistance = (position - Ship.GetPosition()).Length();
         DegreesToVector(position);
         PointToVector(0);
     }
     previousAlign = position;
     Util.GetInstance().Log("[DroneNavigation.AlignTo] returning pitch:" + Math.Abs(_degreesToVectorPitch) + " yaw:" + Math.Abs(_degreesToVectorYaw), logPath);
     return((int)(Math.Abs(_degreesToVectorPitch) + Math.Abs(_degreesToVectorYaw)));
 }
		private static bool DoesGridHaveTarget(IMyCubeGrid grid, IMySlimBlock block, bool disabling = false)
		{
			if (_scanCache.Count < 1)
			{
				BoundingSphereD sphere = new BoundingSphereD(grid.GetPosition(), PluginSettings.Instance.DynamicTurretTargetDistance);
				_scanCache = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
			}
			/*
			HashSet<IMyEntity> testEntities = new HashSet<IMyEntity>();
			try
			{
				MyAPIGateway.Entities.GetEntities(testEntities);
			}
			catch
			{
				return false;
			}
			*/
			//bool found = false;
			foreach (IMyEntity testEntity in _scanCache)
			{
				if (grid == testEntity)
					continue;

				if (!testEntity.InScene)
					continue;

				if (testEntity is IMyCubeBlock)
				{
					continue;
					/*
					IMyCubeBlock cubeBlock = (IMyCubeBlock)testEntity;
					if (cubeBlock.OwnerId == 0)
						continue;

					if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner)
					{
						if (block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) != Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Owner)
						{
							Console.WriteLine("Block: Not owner");
							return true;
						}
					}

					if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
					{
						if (block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Enemies ||
							block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Neutral)
						{
							Console.WriteLine("Block: Enemy or Neutral: {0} {1} {2}", cubeBlock.OwnerId, cubeBlock.Parent.DisplayName, cubeBlock.BlockDefinition);
							return true;
						}
					}

					if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
					{
						if (block.FatBlock.GetUserRelationToOwner(cubeBlock.OwnerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.Enemies)
						{
//							Console.WriteLine("Block: Enemy: {0} {1} {2}", cubeBlock.OwnerId, cubeBlock.Parent.DisplayName, cubeBlock.BlockDefinition);
							return true;
						}
					}
					 */ 
				}

				if (testEntity is IMyCubeGrid)
				{
					if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.All)
						return true;

					IMyCubeGrid testGrid = (IMyCubeGrid)testEntity;
					// Always enable if grid has no owner.  Seems suspect.  Might be a user trying to abuse a no ownership ship.
					/*
					if (testGrid.BigOwners.Count < 1 && testGrid.SmallOwners.Count < 1)
					{
						//if(!(testEntity is IMyControllableEntity))
						//Console.WriteLine("Grid: No owner");
						return true;
					}
					*/

					foreach (long owner in testGrid.BigOwners)
					{
						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner)
						{
							if (block.FatBlock.GetUserRelationToOwner(owner) != MyRelationsBetweenPlayerAndBlock.Owner)
							{
								//Console.WriteLine("Grid: Not owner");
								return true;
							}
						}

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
						{
							if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies ||
								block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Neutral)
							{
								//Console.WriteLine("Grid: Enemy or Neutral: {0} {1}", owner, grid.DisplayName);
								return true;
							}
						}

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
						{
							if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies)
							{
								//Console.WriteLine("{3} Target: Grid - Enemy: {0} - {1} ({2})", block.FatBlock.OwnerId, owner, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);

								//Console.WriteLine("Grid: Enemy: {0} {1}", owner, grid.DisplayName);
								return true;
							}
						}
					}

					foreach (long owner in testGrid.SmallOwners)
					{
						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner)
						{
							if (block.FatBlock.GetUserRelationToOwner(owner) != MyRelationsBetweenPlayerAndBlock.Owner)
							{
								//Console.WriteLine("Grid: Not owner");
								return true;
							}
						}

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
						{
							if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies ||
								block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Neutral)
							{
								//Console.WriteLine("Grid: Enemy or Neutral: {0} {1}", owner, grid.DisplayName);
								return true;
							}
						}

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
						{
							if (block.FatBlock.GetUserRelationToOwner(owner) == MyRelationsBetweenPlayerAndBlock.Enemies)
							{
								//Console.WriteLine("Grid: Enemy: {0} {1}", owner, grid.DisplayName);
								return true;
							}
						}
					}
				}
				else
				{
					if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.All)
						return true;

					if(testEntity is IMyCharacter)
//					var builderBase = testEntity.GetObjectBuilder();
//					if (builderBase is MyObjectBuilder_Character)
					{
						IMyPlayer player = null;
						IMyIdentity identity;
						long playerId = 0;
						try
						{
							identity = IdentityCache.FirstOrDefault(x => x.DisplayName == testEntity.DisplayName);
							//List<IMyPlayer> players = new List<IMyPlayer>();
							//MyAPIGateway.Players.GetPlayers(players);							
							//player = players.FirstOrDefault(x => x.DisplayName == testEntity.DisplayName);
							
							if (player == null)
							{
								/*
								//player = players.FirstOrDefault(x => x.Controller != null && x.Controller.ControlledEntity != null && x.Controller.ControlledEntity.Entity != null && x.Controller.ControlledEntity.Entity.EntityId == testEntity.EntityId);
								if(testEntity is IMyControllableEntity)
								{
									IMyControllableEntity control = (IMyControllableEntity)testEntity;
									List<PlayerMap.InternalPlayerItem> items = PlayerMap.Instance.GetPlayerItemsFromPlayerName(control.Entity.DisplayName);
									if (items != null)
										playerId = items.First().playerId;
								}
								 */ 
							}
						}
						catch
						{
							//Console.WriteLine("{3} Target: Character - Unknown: {0} - {1} ({2})", block.FatBlock.OwnerId, testEntity.EntityId, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);
							//Console.WriteLine("Unknown1: {0}", testEntity.DisplayName);
							return true;
						}

						if (identity == null)
						{
							//Console.WriteLine("{3} Target: Character - Unknown2: {0} - {1} ({2})", block.FatBlock.OwnerId, testEntity.EntityId, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);
							//Console.WriteLine("Unknown2: {0} - {1}", testEntity.DisplayName, testEntity.GetFriendlyName());
							return true;
							//continue;
						}

						if (identity != null)
							playerId = identity.PlayerId;

						if (player != null)
							playerId = player.PlayerID;

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.AllButOwner && block.FatBlock.GetUserRelationToOwner(playerId) != MyRelationsBetweenPlayerAndBlock.Owner)
						{
							//Console.WriteLine("Character: Not Owner: {0} - {1}", block.FatBlock.OwnerId, playerId);
							return true;
						}

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.NeutralAndEnemy)
						{
							if (block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Enemies ||
								block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Neutral)
							{
								//Console.WriteLine("Character: Enemy or Neutral: {0} - {1}", block.FatBlock.OwnerId, playerId);
								return true;
							}
						}

						if (PluginSettings.Instance.DynamicTurretManagementMode == DynamicTurretManagementMode.Enemy)
						{
							if (block.FatBlock.GetUserRelationToOwner(playerId) == MyRelationsBetweenPlayerAndBlock.Enemies)
							{
								//Console.WriteLine("{3} Target: Character - Enemy: {0} - {1} ({2})", block.FatBlock.OwnerId, playerId, testEntity.DisplayName, ((IMyTerminalBlock)block.FatBlock).Parent.DisplayName);
								return true;
							}
						}
					}
				}
			}

			return false;
		}
예제 #24
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            int  page   = 1;
            bool dialog = false;

            if (words.Length > 0)
            {
                if (words[0] == "dialog")
                {
                    dialog = true;
                }

                int.TryParse(words[0], out page);
                if (page < 1)
                {
                    page = 1;
                }
            }

            if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1 && userId != 0)
            {
                Communication.SendPrivateInformation(userId, "Error occurred while processing this command. (1)");
                return(true);
            }

            long playerId = 0;

            if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count > 0)
            {
                playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First();
            }

            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
            List <IMyPlayer>    players  = new List <IMyPlayer>();

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

            IMyPlayer player = players.FirstOrDefault(x => x.SteamUserId == userId);

            string result = "";
            int    count  = 0;

            foreach (IMyEntity entity in entities)
            {
                IMyCubeGrid grid = (IMyCubeGrid)entity;

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

                if (CubeGrids.GetAllOwners(gridBuilder).Contains(playerId))
                {
                    if (result != "")
                    {
                        result += "\r\n";
                    }

                    if (CubeGrids.IsFullOwner(gridBuilder, playerId, player) && !dialog)
                    {
                        result += string.Format("Grid '{0}' at {2}", grid.DisplayName, grid.EntityId, ShowCoordinates(grid.GetPosition()));
                    }
                    else if (CubeGrids.IsFullOwner(gridBuilder, playerId, player) && dialog)
                    {
                        result += string.Format("{0} - {1} - {2}bl - {3}", grid.DisplayName, ShowCoordinates(grid.GetPosition()), gridBuilder.CubeBlocks.Count, gridBuilder.GridSizeEnum);
                    }
                    else
                    {
                        result += string.Format("Grid '{0}'", grid.DisplayName, grid.EntityId);
                    }

                    count++;
                }
            }

            if (dialog)
            {
                Communication.SendClientMessage(userId, string.Format("/dialog \"{0}\" \"{1}\" \"{2}\" \"{3}\" \"{4}\"", "User Grid List", "Ships / Stations you ", "own:", result.Replace("\r\n", "|"), "OK"));
                return(true);
            }

            string[] resultLines = result.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            int pages = ((resultLines.Length - 1) / 6) + 1;

            if (page > pages)
            {
                page = pages;
            }

            string output = "";

            for (int r = ((page - 1) * 6); r < resultLines.Length && r < ((page) * 6); r++)
            {
                string line = resultLines[r];
                if (output != "")
                {
                    output += "\r\n";
                }

                output += line;
            }
            Communication.SendPrivateInformation(userId, output);

            Communication.SendPrivateInformation(userId, string.Format("Displaying page {0} of {1} - {2} grids", page, pages, count));
            return(true);
        }
예제 #25
0
        void Work(int ticks = 1)
        {
            if (!MyAPIGateway.Multiplayer.IsServer)
            {
                return;
            }
            LineD           WeldRay = new LineD(BeamStart, BeamEnd);
            List <IHitInfo> Hits    = new List <IHitInfo>();
            List <MyLineSegmentOverlapResult <MyEntity> > Overlaps = new List <MyLineSegmentOverlapResult <MyEntity> >();

            MyGamePruningStructure.GetTopmostEntitiesOverlappingRay(ref WeldRay, Overlaps);

            List <IMyCubeGrid>       Grids      = new List <IMyCubeGrid>();
            List <IMyCharacter>      Characters = new List <IMyCharacter>();
            List <IMyFloatingObject> Flobjes    = new List <IMyFloatingObject>();

            Overlaps.Select(x => x.Element as IMyEntity).SortByType(Grids, Characters, Flobjes);

            ClosestGrid = Grids.OrderBy(Grid => Vector3D.DistanceSquared(Tool.GetPosition(), Grid.GetPosition())).FirstOrDefault();
            foreach (IMyCharacter Char in Characters)
            {
                Char.DoDamage(GrinderSpeed, MyDamageType.Grind, true, null, Tool.EntityId);
            }

            foreach (IMyCubeGrid Grid in Grids)
            {
                if (Grid == Tool.CubeGrid)
                {
                    continue;
                }
                try
                {
                    List <IMySlimBlock> Blocks = Grid.GetBlocksOnRay(WeldRay.From, WeldRay.To);
                    //if (!SessionCore.Debug && Blocks.Count == 0) return;

                    if (IsWelder)
                    {
                        Weld(Blocks, ticks);
                    }
                    if (IsGrinder)
                    {
                        Grind(Blocks, ticks);
                    }
                }
                catch (Exception Scrap)
                {
                    SessionCore.LogError(Grid.DisplayName, Scrap);
                }
            }

            foreach (IMyFloatingObject Flobj in Flobjes)
            {
                ToolCargo.PickupItem(Flobj);
            }
        }
예제 #26
0
        public static IMySlimBlock GetClosestBlock(Vector3D fromCoords, Vector3D coords, IMyCubeGrid cubeGrid)
        {
            IMySlimBlock closestBlock    = null;
            double       closestDistance = 0;
            Vector3D     closestPosition = Vector3D.Zero;

            var directionToGridCenter = Vector3D.Normalize(cubeGrid.GetPosition() - coords);
            var toCoords = directionToGridCenter * 1500 + coords;
            var cellHits = new List <Vector3I>();

            cubeGrid.RayCastCells(coords, toCoords, cellHits);

            foreach (var cell in cellHits)
            {
                var thisBlock = cubeGrid.GetCubeBlock(cell);

                if (thisBlock == null)
                {
                    continue;
                }

                var thisBlockPos = Vector3D.Zero;
                thisBlock.ComputeWorldCenter(out thisBlockPos);
                var distance = Vector3D.Distance(coords, thisBlockPos);

                if (closestBlock == null)
                {
                    closestBlock    = thisBlock;
                    closestDistance = distance;
                    closestPosition = thisBlockPos;
                    continue;
                }

                if (distance < closestDistance)
                {
                    closestBlock    = thisBlock;
                    closestDistance = distance;
                    closestPosition = thisBlockPos;
                }
            }

            if (closestBlock != null)
            {
                return(closestBlock);
            }

            var blockList = new List <IMySlimBlock>();

            cubeGrid.GetBlocks(blockList);

            foreach (var block in blockList)
            {
                var thisBlockPos = Vector3D.Zero;
                block.ComputeWorldCenter(out thisBlockPos);
                var distance = Vector3D.Distance(coords, thisBlockPos);

                if (closestBlock == null)
                {
                    closestBlock    = block;
                    closestDistance = distance;
                    closestPosition = thisBlockPos;
                    continue;
                }

                if (distance < closestDistance)
                {
                    closestBlock    = block;
                    closestDistance = distance;
                    closestPosition = thisBlockPos;
                }
            }

            return(closestBlock);
        }
예제 #27
0
        public BroadcastInfo GridToBroadcastInfo()
        {
            IMyCubeGrid cubeGrid  = FetchCurrentCubeGrid(entityName);
            string      ownerName = MyVisualScriptLogicProvider.GetPlayersName(ownerId);

            if (cubeGrid != null)
            {
                return(new BroadcastInfo(blockCount, entityId, cubeGrid.CustomName, cubeGrid.IsStatic, cubeGrid.GetPosition(), ownerId, ownerName, gridStatus));
            }
            else
            {
                // dead grid, return Vector3D, ModEntry will trash
                return(new BroadcastInfo(blockCount, entityId, "cubeGrid null", false, Vector3D.Zero, ownerId, ownerName, gridStatus));
            }
        }
 public static bool MoveShipToVoxel(IMyCubeGrid sourceGrid, IMyVoxelBase targetVoxel, bool safely,
     Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage)
 {
     // TODO: find a more accurate position to transport a ship to around a planet and asteroid.
     var worldOffset = targetVoxel.WorldMatrix.Translation - sourceGrid.GetPosition();
     return MoveShipByOffset(sourceGrid, worldOffset, safely, updatedPosition, noSafeLocationMessage);
 }
예제 #29
0
        private static bool CheckRevealBlockRules(IMyCubeGrid grid, List<IMyPlayer> players, out string reason)
        {
            reason = "";
            // This is actually faster, but doesn't include power checks

            // Live dangerously
            List<IMySlimBlock> blocks = new List<IMySlimBlock>();
            grid.GetBlocks(blocks, x => x.FatBlock != null);
            //CubeGrids.GetAllConnectedBlocks(m_processedGrids, grid, blocks, x => x.FatBlock != null);
            //bool found = false;
            //bool powered = false;
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Beacon))
                {
                    //MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyBeacon beacon = (Sandbox.ModAPI.Ingame.IMyBeacon)cubeBlock;
                    if (!beacon.Enabled)
                        continue;

                    //Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!functionalBlock.Enabled)
                    //	continue;

                    //Console.WriteLine("Beacon: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
                    //if (!terminalBlock.IsWorking)
                    //	continue;

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < beacon.Radius)
                            {
                                //found = true;
                                //break;
                                reason = string.Format("{0} distance to beacon broadcast: {1}", player.DisplayName, distance);
                                return true;
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RadioAntenna))
                {
                    //MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyRadioAntenna antenna = (Sandbox.ModAPI.Ingame.IMyRadioAntenna)cubeBlock;

                    if (!antenna.Enabled)
                        continue;

                    //Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!functionalBlock.Enabled)
                    //	continue;

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < antenna.Radius)
                            {
                                //found = true;
                                //break;
                                reason = string.Format("{0} distance to antenna broadcast: {1}", player.DisplayName, distance);
                                return true;
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    //MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyMedicalRoom medical = (Sandbox.ModAPI.Ingame.IMyMedicalRoom)cubeBlock;
                    if (!medical.Enabled)
                        continue;

                    Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    if (!functionalBlock.IsFunctional)
                        continue;

                    //if (!functionalBlock.Enabled)
                    //	continue;

                    if (PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (m_online)
                        {
                            foreach (ulong connectedPlayer in m_online)
                            {
                                long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                                //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                                if (functionalBlock.OwnerId == playerId)
                                {
                                    reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
                                    return true;
                                }

                                if(functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare)
                                {
                                    reason = string.Format("Grid has medbay and player is factionshare - playerid: {0}", playerId);
                                    return true;
                                }
                            }
                        }

                        /*
                        foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
                        {
                            long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                            //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                            //if (functionalBlock.OwnerId == playerId || (functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare))
                            if(medical.HasPlayerAccess(playerId))
                            {
                                reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
                                return true;
                            }
                        }
                         */
                    }
                    else
                    {
                        reason = string.Format("Grid has medbay and conceal can not include medbays");
                        return true;
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ProductionBlock))
                {
                    MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock();
                    if (!production.Enabled)
                        continue;

                    Sandbox.ModAPI.Ingame.IMyProductionBlock productionBlock = (Sandbox.ModAPI.Ingame.IMyProductionBlock)cubeBlock;
                    if (production.Queue.Length > 0)
                    {
                        reason = string.Format("Grid has production facility that has a queue");
                        return true;
                    }
                }
            }

            return false;
        }
예제 #30
0
        public static OrientedBoundingBoxD GetBoundingBox(IMyCubeGrid entity)
        {
            var min = new Vector3D(int.MaxValue, int.MaxValue, int.MaxValue);
            var max = new Vector3D(int.MinValue, int.MinValue, int.MinValue);

            float multiplier = 2.5f;
            if (entity.GridSizeEnum == MyCubeSize.Small)
                multiplier = 0.5f;

            List<IMySlimBlock> blocks = new List<IMySlimBlock>();
            entity.GetBlocks(blocks, null);

            foreach (IMySlimBlock block in blocks)
            {
                //Vector3 pos = Entity.GetBlockEntityPosition(block);
                min = Vector3D.Min(block.Position * multiplier, min);
                max = Vector3D.Max(block.Position * multiplier, max);
            }

            Vector3D size = max - min;
            BoundingBoxD bb = new BoundingBoxD(new Vector3D(0, 0, 0), size).Translate(entity.GetPosition() - (size / 2));
            return new OrientedBoundingBoxD(bb.Center, bb.HalfExtents, Quaternion.CreateFromRotationMatrix(entity.WorldMatrix.GetOrientation()));
        }
예제 #31
0
        private static bool CheckConcealBlockRules(IMyCubeGrid grid, List<IMyPlayer> players)
        {
            List<IMySlimBlock> blocks = new List<IMySlimBlock>();

            // Live dangerously
            grid.GetBlocks(blocks, x => x.FatBlock != null);
            //CubeGrids.GetAllConnectedBlocks(m_processedGrids, grid, blocks, x => x.FatBlock != null);

            int beaconCount = 0;
            //bool found = false;
            //bool powered = false;
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Beacon))
                {
                    Sandbox.ModAPI.Ingame.IMyBeacon beacon = (Sandbox.ModAPI.Ingame.IMyBeacon)cubeBlock;
                    //MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
                    beaconCount++;
                    // Keep this return here, as 4 beacons always means true
                    if(beaconCount >= 4)
                    {
                        return true;
                    }

                    if (!beacon.Enabled)
                        continue;

                    Sandbox.ModAPI.Ingame.IMyTerminalBlock terminalBlock = (Sandbox.ModAPI.Ingame.IMyTerminalBlock)cubeBlock;
            //					Console.WriteLine("Found: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
                    //if (!terminalBlock.IsWorking)
                    //{
            //						continue;
                    //}

                    foreach(IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if(Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < beacon.Radius)
                            {
            //								Console.WriteLine("Not concealed due to broadcast radius");
                                //found = true;
                                //break;
                                return true;
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RadioAntenna))
                {
                    //MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyRadioAntenna antenna = (Sandbox.ModAPI.Ingame.IMyRadioAntenna)cubeBlock;

                    if (!antenna.Enabled)
                        continue;

                    Sandbox.ModAPI.Ingame.IMyTerminalBlock terminalBlock = (Sandbox.ModAPI.Ingame.IMyTerminalBlock)cubeBlock;
                    //if (!terminalBlock.IsWorking)
                    //	continue;

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < antenna.Radius)
                            {
            //								Console.WriteLine("Not concealed due to antenna broadcast radius");
                                //found = true;
                                //break;
                                return true;
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    //MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyMedicalRoom medical = (Sandbox.ModAPI.Ingame.IMyMedicalRoom)cubeBlock;

                    if (!medical.Enabled)
                        continue;

                    Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!terminalBlock.IsWorking)
                    //	continue;

                    if(PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (m_online)
                        {
                            foreach (ulong connectedPlayer in m_online)
                            {
                                //if (PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).Count < 1)
                                //continue;

                                //long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).First();
                                long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);

                                if (functionalBlock.OwnerId == playerId || (functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare))
                                //if (functionalBlock.Owner == playerId || (functionalBlock.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(functionalBlock.Owner, playerId)))
                                //if (medical.HasPlayerAccess(playerId))
                                {
                                    return true;
                                }
                            }
                        }

                        /*
                        foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
                        {
                            //if (PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).Count < 1)
                                //continue;

                            //long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(connectedPlayer).First();
                            long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                            //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                            if(medical.HasPlayerAccess(playerId))
                            {
                                return true;
                            }
                        }
                         */
                    }
                    else
                    {
                        return true;
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Refinery) || cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler))
                {
                    //MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyProductionBlock production = (Sandbox.ModAPI.Ingame.IMyProductionBlock)cubeBlock;
                    if (!production.Enabled)
                        continue;

                    if (production.IsProducing)
                        return true;
                }

                foreach(string subType in PluginSettings.Instance.DynamicConcealIgnoreSubTypeList)
                {
                    if (cubeBlock.BlockDefinition.SubtypeName.Contains(subType))
                    {
            //						Console.WriteLine("Not concealed due subtype");
                        //found = true;
                        return true;
                    }
                }
            }

            return false;
        }
예제 #32
0
        static public OrientedBoundingBoxD GetBoundingBox(IMyCubeGrid entity)
        {
            var min = new Vector3D(int.MaxValue, int.MaxValue, int.MaxValue);
            var max = new Vector3D(int.MinValue, int.MinValue, int.MinValue);

            float multiplier = 2.5f;

            if (entity.GridSizeEnum == MyCubeSize.Small)
            {
                multiplier = 0.5f;
            }

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

            entity.GetBlocks(blocks, null);

            foreach (IMySlimBlock block in blocks)
            {
                //Vector3 pos = Entity.GetBlockEntityPosition(block);
                min = Vector3D.Min(block.Position * multiplier, min);
                max = Vector3D.Max(block.Position * multiplier, max);
            }

            Vector3D     size = max - min;
            BoundingBoxD bb   = new BoundingBoxD(new Vector3D(0, 0, 0), size).Translate(entity.GetPosition() - (size / 2));

            return(new OrientedBoundingBoxD(bb.Center, bb.HalfExtents, Quaternion.CreateFromRotationMatrix(entity.WorldMatrix.GetOrientation())));
        }
예제 #33
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;
            }
        }
예제 #34
0
 //ship location
 public Vector3D GetPosition()
 {
     return(_cubeGrid.GetPosition());
 }
예제 #35
0
        /// <summary>
        /// Returns a list of players near a grid.  Used to send messages
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private List<long> getPlayersNearGrid(IMyCubeGrid grid)
        {
            log("Getting players near grid " + grid.DisplayName);

            Vector3 gridPos = grid.GetPosition();
            VRageMath.Vector3 gridSize = grid.LocalAABB.Size;
            float gridMaxLength =
                Math.Max(gridSize.X, Math.Max(gridSize.Y, gridSize.Z));
            int maxDistFromGrid = (int)gridMaxLength + INGAME_PLACEMENT_MAX_DISTANCE;

            List<IMyPlayer> allPlayers = new List<IMyPlayer>();
            MyAPIGateway.Players.GetPlayers(allPlayers);

            float pDistFromGrid = 0.0f;
            List<long> nearbyPlayerIds = new List<long>();
            foreach (IMyPlayer p in allPlayers)
            {
                pDistFromGrid = VRageMath.Vector3.Distance(p.GetPosition(), gridPos);
                if (pDistFromGrid < maxDistFromGrid) {
                    nearbyPlayerIds.Add((long)p.PlayerID);
                }
            }

            log(nearbyPlayerIds.Count + " Nearby players: " + String.Join(" ,", nearbyPlayerIds));
            return nearbyPlayerIds;
        }
예제 #36
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_undocking)
            {
                Communication.SendPrivateInformation(userId, string.Format("Server is busy, try again"));
                return(true);
            }

            m_undocking = true;
            try
            {
                String pylonName = String.Join(" ", words);
                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Unable to find player Id: {0}", 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)
                {
                    foreach (IMyCubeBlock entity in beaconList)
                    {
                        if (!Entity.CheckOwnership(entity, playerId))
                        {
                            Communication.SendPrivateInformation(userId, string.Format("You do not have permission to use '{0}'.  You must either own all the beacons or they must be shared with faction.", pylonName));
                            return(true);
                        }
                    }

                    IMyCubeBlock e      = beaconList.First( );
                    IMyCubeGrid  parent = (IMyCubeGrid)e.Parent;

                    long[]             beaconListIds = beaconList.Select(p => p.EntityId).ToArray( );
                    long               ownerId       = beaconList.First( ).OwnerId;
                    List <DockingItem> dockingItems  = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count( ) == 4);
                    if (dockingItems.Count < 1)
                    {
                        Communication.SendPrivateInformation(userId, string.Format("You have no ships docked in docking zone '{0}'.", pylonName));
                        return(true);
                    }

                    DockingItem dockingItem = dockingItems.First( );

                    // 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));
                    }

                    List <IMySlimBlock> blocks = new List <IMySlimBlock>( );
                    parent.GetBlocks(blocks);
                    foreach (IMySlimBlock slim_cbe in blocks)
                    {
                        if (slim_cbe is IMyCubeBlock)
                        {
                            IMyCubeBlock cbe = slim_cbe.FatBlock;
                            if (cbe.GetObjectBuilderCubeBlock( ) is MyObjectBuilder_Cockpit)
                            {
                                MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)cbe.GetObjectBuilderCubeBlock( );
                                if (c.Pilot != null)
                                {
                                    Communication.SendPrivateInformation(userId,
                                                                         string.Format(
                                                                             "Carrier ship has a pilot.  The carrier should be unpiloted and fully stopped before undocking.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)",
                                                                             pylonName));
                                    return(true);
                                }
                            }
                        }
                    }

                    String dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", ownerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    // Load Entity From File and add to game
                    FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    //CubeGridEntity cubeGrid = new CubeGridEntity(fileInfo);

                    MyObjectBuilder_CubeGrid cubeGrid = BaseObjectManager.ReadSpaceEngineersFile <MyObjectBuilder_CubeGrid, MyObjectBuilder_CubeGridSerializer>(dockedShipFileName);

                    // Rotate our ship relative to our saved rotation and the new carrier rotation
                    cubeGrid.PositionAndOrientation =
                        new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( )) * dockingItem.SaveQuat).GetOrientation( ));
                    // Move our ship relative to the new carrier position and orientation
                    Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( ));
                    Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                    //cubeGrid.Position = rotatedPos + parent.GetPosition();
                    cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(rotatedPos + parent.GetPosition( ), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId( );
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);
                            List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>( );
                            addList.Add(cubeGrid);
                            MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                            undock = true;
                        }
                        catch (Exception Ex)
                        {
                            Log.Info(string.Format("Error undocking ship: {0}", Ex.ToString( )));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

                    if (!undock)
                    {
                        return(true);
                    }

                    //SectorObjectManager.Instance.AddEntity(cubeGrid);

                    // Remove the docking file
                    File.Delete(dockedShipFileName);
                    Docking.Instance.Remove(dockingItem);

                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", dockingItem.DockedName, pylonName));

                    /*
                     * // Queue for cooldown
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.Name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     *
                     * lock (m_cooldownList)
                     *      m_cooldownList.Add(cItem);
                     *
                     * IMyEntity gridEntity = MyAPIGateway.Entities.GetEntityById(dockingItem.DockedEntityId);
                     * IMyCubeGrid cubeGrid = (IMyCubeGrid)gridEntity;
                     *
                     * Quaternion q = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()) * dockingItem.SaveQuat;
                     * Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                     * Vector3 parentPosition = parent.GetPosition();
                     * Vector3 rotatedPos = Vector3.Transform(dockingItem.savePos, newQuat);
                     * Vector3 position = rotatedPos + parentPosition;
                     * Matrix positionMatrix = Matrix.CreateFromQuaternion(q);
                     *
                     * cubeGrid.ChangeGridOwnership(playerId, MyOwnershipShareModeEnum.None);
                     * gridEntity.SetPosition(dockingItem.savePos);
                     *
                     * gridEntity.WorldMatrix = positionMatrix;
                     * gridEntity.SetPosition(position);
                     *
                     * // We need to update again, as this doesn't seem to sync properly?  I set world matrix, and setposition, and it doesn't go where it should, and I
                     * // have to bump into it for it to show up, it's mega weird.
                     *
                     * if (PluginDocking.Settings.DockingItems == null)
                     *      throw new Exception("DockingItems is null");
                     *
                     * // Remove from docked items
                     * PluginDocking.Settings.DockingItems.Remove(dockingItem);
                     *
                     * // Notify user
                     * Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", gridEntity.DisplayName, pylonName));
                     */
                    // Queue for cooldown

                    /*
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     * PluginDocking.CooldownList.Add(cItem);
                     */
                }
                else if (beaconList.Count > 4)                   // Too many beacons, must be 4
                {
                    Communication.SendPrivateInformation(userId,
                                                         string.Format("Too many beacons with the name or another zone with the name '{0}'.  Place only 4 beacons to create a zone or try a different zone name.",
                                                                       pylonName));
                }
                else                 // Can't find docking zone
                {
                    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));
                }
            }
            catch (NullReferenceException ex)
            {
                Log.Error(ex);
            }
            finally
            {
                m_undocking = false;
            }

            return(true);
        }
예제 #37
0
        public static bool GetDistanceBetweenGridAndPlayer(IMyCubeGrid grid, IMyPlayer player, out double distance)
        {
            distance = 0d;

            try
            {
                if (player.Controller == null || player.Controller.ControlledEntity == null || player.Controller.ControlledEntity.Entity == null)
                    return false;

                Vector3D playerPosition = player.Controller.ControlledEntity.Entity.GetPosition();
                distance = Vector3D.Distance(grid.GetPosition(), playerPosition);
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole("GetDistanceBetweenGridAndPlayer(): {0}", ex.ToString());
                return false;
            }

            return true;
        }