Пример #1
0
        public string SendHttpResponseResponse(HttpListenerRequest request)
        {
            StringBuilder sb     = new StringBuilder();
            JsonWriter    writer = new JsonWriter(sb);

            switch (request.Url.AbsolutePath)
            {
            //case "/gc/collect/0":
            //    GC.Collect(0);
            //    break;
            //case "/gc/collect/1":
            //    GC.Collect(1);
            //    break;
            //case "/gc/collect/2":
            //    GC.Collect(2);
            //    break;
            case "/metrics/v1/server":
                int    usedPCU            = 0;
                int    maxPlayers         = 0;
                int    maxFactionCount    = 0;
                int    maxFloatingObjects = 0;
                int    maxGridSize        = 0;
                int    maxBlocksPerPlayer = 0;
                string blockLimit         = "";
                int    totalPCU           = 0;
                int    modCount           = 0;
                if (MySession.Static != null)
                {
                    if (MySession.Static.GlobalBlockLimits != null)
                    {
                        usedPCU = MySession.Static.GlobalBlockLimits.PCUBuilt;
                    }
                    maxPlayers         = MySession.Static.MaxPlayers;
                    maxFactionCount    = MySession.Static.MaxFactionsCount;
                    maxFloatingObjects = MySession.Static.MaxFloatingObjects;
                    maxGridSize        = MySession.Static.MaxGridSize;
                    maxBlocksPerPlayer = MySession.Static.MaxBlocksPerPlayer;
                    totalPCU           = MySession.Static.TotalPCU;
                    modCount           = MySession.Static.Mods.Count;
                    switch (MySession.Static.BlockLimitsEnabled)
                    {
                    case MyBlockLimitsEnabledEnum.GLOBALLY:
                        blockLimit = "globally";
                        break;

                    case MyBlockLimitsEnabledEnum.NONE:
                        blockLimit = "none";
                        break;

                    case MyBlockLimitsEnabledEnum.PER_FACTION:
                        blockLimit = "faction";
                        break;

                    case MyBlockLimitsEnabledEnum.PER_PLAYER:
                        blockLimit = "player";
                        break;
                    }
                }
                writer.WriteObjectStart();
                writer.WritePropertyName("Version");
                writer.Write(MyFinalBuildConstants.APP_VERSION_STRING_DOTS.ToString());
                writer.WritePropertyName("ServerName");
                writer.Write(MySandboxGame.ConfigDedicated.ServerName);
                writer.WritePropertyName("WorldName");
                writer.Write(MySandboxGame.ConfigDedicated.WorldName);
                writer.WritePropertyName("IsReady");
                writer.Write(MySession.Static != null && MySession.Static.Ready);
                writer.WritePropertyName("SimSpeed");
                writer.Write(Sync.ServerSimulationRatio);
                writer.WritePropertyName("SimulationCpuLoad");
                writer.Write((float)(int)Sync.ServerCPULoad);
                writer.WritePropertyName("TotalTime");
                writer.Write(MySandboxGame.TotalTimeInMilliseconds / 1000);
                writer.WritePropertyName("Players");
                writer.Write((Sync.Clients != null) ? (Sync.Clients.Count - 1) : 0);
                writer.WritePropertyName("UsedPCU");
                writer.Write(usedPCU);
                writer.WritePropertyName("MaxPlayers");
                writer.Write(maxPlayers);
                writer.WritePropertyName("MaxFactionsCount");
                writer.Write(maxFactionCount);
                writer.WritePropertyName("MaxFloatingObjects");
                writer.Write(maxFloatingObjects);
                writer.WritePropertyName("MaxGridSize");
                writer.Write(maxGridSize);
                writer.WritePropertyName("MaxBlocksPerPlayer");
                writer.Write(maxBlocksPerPlayer);
                writer.WritePropertyName("BlockLimitsEnabled");
                writer.Write(blockLimit);
                writer.WritePropertyName("TotalPCU");
                writer.Write(totalPCU);
                writer.WritePropertyName("ModCount");
                writer.Write(modCount);
                writer.WritePropertyName("SaveDuration");
                writer.Write(saveDuration);
                writer.WriteObjectEnd();
                break;

            case "/metrics/v1/load":
                writer.WriteArrayStart();
                LoadEvent loadEv;
                while (!loadEvents.Empty)
                {
                    if (loadEvents.TryDequeueBack(out loadEv))
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("ServerCPULoad");
                        writer.Write(loadEv.ServerCPULoad);
                        writer.WritePropertyName("ServerCPULoadSmooth");
                        writer.Write(loadEv.ServerCPULoadSmooth);
                        writer.WritePropertyName("ServerSimulationRatio");
                        writer.Write(loadEv.ServerSimulationRatio);
                        writer.WritePropertyName("ServerThreadLoad");
                        writer.Write(loadEv.ServerThreadLoad);
                        writer.WritePropertyName("ServerThreadLoadSmooth");
                        writer.Write(loadEv.ServerThreadLoadSmooth);
                        writer.WritePropertyName("MillisecondsInThePast");
                        writer.Write((DateTime.Now - loadEv.Occurred).TotalMilliseconds);
                        writer.WriteObjectEnd();
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/process":
                System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
                writer.WriteObjectStart();
                writer.WritePropertyName("PrivateMemorySize64");
                writer.Write(currentProcess.PrivateMemorySize64);
                writer.WritePropertyName("VirtualMemorySize64");
                writer.Write(currentProcess.VirtualMemorySize64);
                writer.WritePropertyName("WorkingSet64");
                writer.Write(currentProcess.WorkingSet64);
                writer.WritePropertyName("NonpagedSystemMemorySize64");
                writer.Write(currentProcess.NonpagedSystemMemorySize64);
                writer.WritePropertyName("PagedMemorySize64");
                writer.Write(currentProcess.PagedMemorySize64);
                writer.WritePropertyName("PagedSystemMemorySize64");
                writer.Write(currentProcess.PagedSystemMemorySize64);
                writer.WritePropertyName("PeakPagedMemorySize64");
                writer.Write(currentProcess.PeakPagedMemorySize64);
                writer.WritePropertyName("PeakVirtualMemorySize64");
                writer.Write(currentProcess.PeakVirtualMemorySize64);
                writer.WritePropertyName("PeakWorkingSet64");
                writer.Write(currentProcess.PeakWorkingSet64);
                writer.WritePropertyName("GCLatencyMode");
                writer.Write((int)System.Runtime.GCSettings.LatencyMode);
                writer.WritePropertyName("GCIsServerGC");
                writer.Write(System.Runtime.GCSettings.IsServerGC);
                writer.WritePropertyName("GCTotalMemory");
                writer.Write(GC.GetTotalMemory(false));
                writer.WritePropertyName("GCMaxGeneration");
                writer.Write(GC.MaxGeneration);
                writer.WritePropertyName("GCCollectionCount0");
                writer.Write(GC.CollectionCount(0));
                writer.WritePropertyName("GCCollectionCount1");
                writer.Write(GC.CollectionCount(1));
                writer.WritePropertyName("GCCollectionCount2");
                writer.Write(GC.CollectionCount(2));
                writer.WriteObjectEnd();
                break;

            case "/metrics/v1/events":
                writer.WriteArrayStart();
                Event ev;
                while (!events.Empty)
                {
                    if (events.TryDequeueBack(out ev))
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("Type");
                        writer.Write(ev.Type);
                        writer.WritePropertyName("Text");
                        writer.Write(ev.Text);
                        writer.WritePropertyName("Tags");
                        writer.WriteArrayStart();
                        foreach (var tag in ev.Tags)
                        {
                            writer.Write(tag);
                        }
                        writer.WriteArrayEnd();
                        writer.WritePropertyName("SecondsInThePast");
                        writer.Write((DateTime.Now - ev.Occurred).TotalSeconds);
                        writer.WriteObjectEnd();
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/players":
                writer.WriteArrayStart();
                PlayerEvent playerEv;
                while (!playerEvents.Empty)
                {
                    if (playerEvents.TryDequeueBack(out playerEv))
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("Type");
                        writer.Write(playerEv.Type);
                        writer.WritePropertyName("SteamId");
                        writer.Write(playerEv.SteamId);
                        writer.WritePropertyName("MillisecondsInThePast");
                        writer.Write((DateTime.Now - playerEv.Occurred).TotalMilliseconds);
                        writer.WriteObjectEnd();
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/session/grids":
                writer.WriteArrayStart();
                if (MySession.Static != null && MySession.Static.Ready)
                {
                    ICollection <MyPlayer>         onlinePlayers = MySession.Static.Players.GetOnlinePlayers();
                    MyConcurrentHashSet <MyEntity> entities      = MyEntities.GetEntities();

                    Type      type  = typeof(MyEntities);
                    FieldInfo info  = type.GetField("m_entitiesForUpdateOnce", BindingFlags.NonPublic | BindingFlags.Static);
                    object    value = info.GetValue(null);
                    CachingList <MyEntity> m_entitiesForUpdateOnce = value as CachingList <MyEntity>;
                    List <long>            x_entitiesForUpdateOnce = new List <long>();

                    info  = type.GetField("m_entitiesForUpdate", BindingFlags.NonPublic | BindingFlags.Static);
                    value = info.GetValue(null);
                    MyDistributedUpdater <ConcurrentCachingList <MyEntity>, MyEntity> m_entitiesForUpdate = value as MyDistributedUpdater <ConcurrentCachingList <MyEntity>, MyEntity>;
                    List <long> x_entitiesForUpdate = new List <long>();

                    info  = type.GetField("m_entitiesForUpdate10", BindingFlags.NonPublic | BindingFlags.Static);
                    value = info.GetValue(null);
                    MyDistributedUpdater <CachingList <MyEntity>, MyEntity> m_entitiesForUpdate10 = value as MyDistributedUpdater <CachingList <MyEntity>, MyEntity>;
                    List <long> x_entitiesForUpdate10 = new List <long>();

                    info  = type.GetField("m_entitiesForUpdate100", BindingFlags.NonPublic | BindingFlags.Static);
                    value = info.GetValue(null);
                    MyDistributedUpdater <CachingList <MyEntity>, MyEntity> m_entitiesForUpdate100 = value as MyDistributedUpdater <CachingList <MyEntity>, MyEntity>;
                    List <long> x_entitiesForUpdate100 = new List <long>();

                    info  = type.GetField("m_entitiesForSimulate", BindingFlags.NonPublic | BindingFlags.Static);
                    value = info.GetValue(null);
                    MyDistributedUpdater <CachingList <MyEntity>, MyEntity> m_entitiesForSimulate = value as MyDistributedUpdater <CachingList <MyEntity>, MyEntity>;
                    List <long> x_entitiesForSimulate = new List <long>();

                    Torch.InvokeBlocking(() =>
                    {
                        x_entitiesForUpdateOnce = m_entitiesForUpdateOnce.Select((x) => x.EntityId).ToList();
                        x_entitiesForUpdate     = m_entitiesForUpdate.List.Select((x) => x.EntityId).ToList();
                        x_entitiesForUpdate10   = m_entitiesForUpdate10.List.Select((x) => x.EntityId).ToList();
                        x_entitiesForUpdate100  = m_entitiesForUpdate100.List.Select((x) => x.EntityId).ToList();
                        x_entitiesForSimulate   = m_entitiesForSimulate.List.Select((x) => x.EntityId).ToList();
                    });

                    bool IsConcealed(MyCubeGrid grid)
                    {
                        int NeedsUpdateMatches = 0;
                        int RegistedMatches    = 0;

                        if ((grid.NeedsUpdate & MyEntityUpdateEnum.BEFORE_NEXT_FRAME) > MyEntityUpdateEnum.NONE)
                        {
                            NeedsUpdateMatches++;
                            if (x_entitiesForUpdateOnce.Any((x) => x == grid.EntityId))
                            {
                                RegistedMatches++;
                            }
                        }
                        if ((grid.NeedsUpdate & MyEntityUpdateEnum.EACH_FRAME) > MyEntityUpdateEnum.NONE)
                        {
                            NeedsUpdateMatches++;
                            if (x_entitiesForUpdate.Any((x) => x == grid.EntityId))
                            {
                                RegistedMatches++;
                            }
                        }
                        if ((grid.NeedsUpdate & MyEntityUpdateEnum.EACH_10TH_FRAME) > MyEntityUpdateEnum.NONE)
                        {
                            NeedsUpdateMatches++;
                            if (x_entitiesForUpdate10.Any((x) => x == grid.EntityId))
                            {
                                RegistedMatches++;
                            }
                        }
                        if ((grid.NeedsUpdate & MyEntityUpdateEnum.EACH_100TH_FRAME) > MyEntityUpdateEnum.NONE)
                        {
                            NeedsUpdateMatches++;
                            if (x_entitiesForUpdate100.Any((x) => x == grid.EntityId))
                            {
                                RegistedMatches++;
                            }
                        }
                        if ((grid.NeedsUpdate & MyEntityUpdateEnum.SIMULATE) > MyEntityUpdateEnum.NONE)
                        {
                            NeedsUpdateMatches++;
                            if (x_entitiesForSimulate.Any((x) => x == grid.EntityId))
                            {
                                RegistedMatches++;
                            }
                        }

                        return(NeedsUpdateMatches > 0 && RegistedMatches == 0);
                    }

                    foreach (MyEntity item in entities)
                    {
                        MyCubeGrid myCubeGrid = item as MyCubeGrid;
                        if (myCubeGrid != null && !myCubeGrid.Closed && myCubeGrid.Physics != null)
                        {
                            long   steamId       = 0L;
                            string displayName   = string.Empty;
                            string factionTag    = string.Empty;
                            string factionName   = string.Empty;
                            long   groupEntityId = 0L;
                            if (myCubeGrid.BigOwners.Count > 0)
                            {
                                steamId = myCubeGrid.BigOwners[0];

                                MyIdentity myIdentity = MySession.Static.Players.TryGetIdentity(steamId);
                                if (myIdentity != null)
                                {
                                    displayName = myIdentity.DisplayName;
                                }

                                IMyFaction myFaction = MySession.Static.Factions.TryGetPlayerFaction(steamId);
                                if (myFaction != null)
                                {
                                    factionTag  = myFaction.Tag;
                                    factionName = myFaction.Name;
                                }
                            }

                            foreach (var group in MyCubeGridGroups.Static.Physical.Groups)
                            {
                                bool found = false;

                                foreach (var node in group.Nodes)
                                {
                                    if (node.NodeData != myCubeGrid)
                                    {
                                        continue;
                                    }

                                    groupEntityId = group.Nodes.OrderByDescending(x => x.NodeData.BlocksCount).First().NodeData.EntityId;
                                    found         = true;
                                    break;
                                }

                                if (found)
                                {
                                    break;
                                }
                            }

                            int conveyorInventoryBlockCount = 0;
                            int conveyorEndpointBlockCount  = 0;
                            int conveyorLineCount           = 0;
                            int conveyorConnectorCount      = 0;
                            if (myCubeGrid?.GridSystems?.ConveyorSystem != null)
                            {
                                type = myCubeGrid.GridSystems.ConveyorSystem.GetType();
                                conveyorInventoryBlockCount = (type.GetField("m_inventoryBlocks", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(myCubeGrid.GridSystems.ConveyorSystem) as HashSet <MyCubeBlock>).Count;
                                conveyorEndpointBlockCount  = (type.GetField("m_conveyorEndpointBlocks", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(myCubeGrid.GridSystems.ConveyorSystem) as HashSet <IMyConveyorEndpointBlock>).Count;
                                conveyorLineCount           = (type.GetField("m_lines", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(myCubeGrid.GridSystems.ConveyorSystem) as HashSet <MyConveyorLine>).Count;
                                conveyorConnectorCount      = (type.GetField("m_connectors", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(myCubeGrid.GridSystems.ConveyorSystem) as HashSet <MyShipConnector>).Count;
                            }

                            writer.WriteObjectStart();
                            writer.WritePropertyName("DisplayName");
                            writer.Write(myCubeGrid.DisplayName);
                            writer.WritePropertyName("EntityId");
                            writer.Write(myCubeGrid.EntityId);
                            writer.WritePropertyName("PhysicsGroupEntityId");
                            writer.Write(groupEntityId);
                            writer.WritePropertyName("GridSize");
                            writer.Write(myCubeGrid.GridSizeEnum == MyCubeSize.Large ? "Large" : "Small");
                            writer.WritePropertyName("BlocksCount");
                            writer.Write(myCubeGrid.BlocksCount);
                            writer.WritePropertyName("Mass");
                            writer.Write(myCubeGrid.Physics.Mass);
                            writer.WritePropertyName("LinearSpeed");
                            writer.Write(myCubeGrid.Physics.LinearVelocity.Length());
                            writer.WritePropertyName("DistanceToPlayer");
                            writer.Write(MySession.GetPlayerDistance(myCubeGrid, onlinePlayers));
                            writer.WritePropertyName("OwnerSteamId");
                            writer.Write(steamId);
                            writer.WritePropertyName("OwnerDisplayName");
                            writer.Write(displayName);
                            writer.WritePropertyName("OwnerFactionTag");
                            writer.Write(factionTag);
                            writer.WritePropertyName("OwnerFactionName");
                            writer.Write(factionName);
                            writer.WritePropertyName("IsPowered");
                            writer.Write(myCubeGrid.GridSystems.ResourceDistributor.ResourceStateByType(MyResourceDistributorComponent.ElectricityId, withRecompute: false) != MyResourceStateEnum.NoPower);
                            writer.WritePropertyName("PCU");
                            writer.Write(myCubeGrid.BlocksPCU);
                            writer.WritePropertyName("IsConcealed");
                            writer.Write(IsConcealed(myCubeGrid));
                            writer.WritePropertyName("DampenersEnabled");
                            writer.Write(myCubeGrid.DampenersEnabled);
                            writer.WritePropertyName("IsStatic");
                            writer.Write(myCubeGrid.Physics.IsStatic);
                            writer.WritePropertyName("ConveyorSystemInventoryBlockCount");
                            writer.Write(conveyorInventoryBlockCount);
                            writer.WritePropertyName("ConveyorSystemEndpointBlockCount");
                            writer.Write(conveyorEndpointBlockCount);
                            writer.WritePropertyName("ConveyorSystemLineCount");
                            writer.Write(conveyorLineCount);
                            writer.WritePropertyName("ConveyorSystemConnectorCount");
                            writer.Write(conveyorConnectorCount);
                            writer.WriteObjectEnd();
                        }
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/session/asteroids":
                writer.WriteArrayStart();
                if (MySession.Static != null && MySession.Static.Ready)
                {
                    MyConcurrentHashSet <MyEntity> entities = MyEntities.GetEntities();
                    foreach (MyEntity item in entities)
                    {
                        MyVoxelBase myVoxelBase = item as MyVoxelBase;
                        if (myVoxelBase != null && !(myVoxelBase is MyPlanet) && !myVoxelBase.Closed)
                        {
                            writer.WriteObjectStart();
                            writer.WritePropertyName("DisplayName");
                            writer.Write(myVoxelBase.StorageName);
                            writer.WritePropertyName("EntityId");
                            writer.Write(myVoxelBase.EntityId);
                            writer.WriteObjectEnd();
                        }
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/session/planets":
                writer.WriteArrayStart();
                if (MySession.Static != null && MySession.Static.Ready)
                {
                    MyConcurrentHashSet <MyEntity> entities = MyEntities.GetEntities();
                    foreach (MyEntity item in entities)
                    {
                        MyPlanet myPlanet = item as MyPlanet;
                        if (myPlanet != null && !myPlanet.Closed)
                        {
                            string storageName = myPlanet.StorageName;
                            long   entityId    = myPlanet.EntityId;
                            writer.WriteObjectStart();
                            writer.WritePropertyName("DisplayName");
                            writer.Write(storageName);
                            writer.WritePropertyName("EntityId");
                            writer.Write(entityId);
                            writer.WriteObjectEnd();
                        }
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/session/floatingObjects":
                writer.WriteArrayStart();
                if (MySession.Static != null && MySession.Static.Ready)
                {
                    ICollection <MyPlayer>         onlinePlayers = MySession.Static.Players.GetOnlinePlayers();
                    MyConcurrentHashSet <MyEntity> entities      = MyEntities.GetEntities();
                    foreach (MyEntity item in entities)
                    {
                        MyFloatingObject     myFloatingObject     = item as MyFloatingObject;
                        MyInventoryBagEntity myInventoryBagEntity = item as MyInventoryBagEntity;
                        if (myFloatingObject != null || myInventoryBagEntity != null)
                        {
                            string value  = string.Empty;
                            long   value2 = 0L;
                            string value3 = string.Empty;
                            float  value4 = 0f;
                            float  value5 = 0f;
                            float  value6 = 0f;
                            string value7 = string.Empty;
                            if (myFloatingObject != null)
                            {
                                if (myFloatingObject.Closed || myFloatingObject.Physics == null)
                                {
                                    continue;
                                }
                                value  = myFloatingObject.DisplayName;
                                value2 = myFloatingObject.EntityId;
                                value3 = "FloatingObject";
                                value4 = myFloatingObject.Physics.Mass;
                                value5 = myFloatingObject.Physics.LinearVelocity.Length();
                                value6 = MySession.GetPlayerDistance(myFloatingObject, onlinePlayers);
                                var def = MyDefinitionManager.Static.GetPhysicalItemDefinition(new MyDefinitionId(myFloatingObject.Item.Content.TypeId, myFloatingObject.Item.Content.SubtypeId));
                                value7 = def.DisplayNameText;
                            }
                            else if (myInventoryBagEntity != null)
                            {
                                if (myInventoryBagEntity.Closed || myInventoryBagEntity.Physics == null)
                                {
                                    continue;
                                }
                                value  = myInventoryBagEntity.DisplayName;
                                value2 = myInventoryBagEntity.EntityId;
                                value3 = "Bag";
                                value4 = myInventoryBagEntity.Physics.Mass;
                                value5 = myInventoryBagEntity.Physics.LinearVelocity.Length();
                                value6 = MySession.GetPlayerDistance(myInventoryBagEntity, onlinePlayers);
                                value7 = "Bag";
                            }
                            writer.WriteObjectStart();
                            writer.WritePropertyName("DisplayName");
                            writer.Write(value);
                            writer.WritePropertyName("EntityId");
                            writer.Write(value2);
                            writer.WritePropertyName("Kind");
                            writer.Write(value3);
                            writer.WritePropertyName("Mass");
                            writer.Write(value4);
                            writer.WritePropertyName("LinearSpeed");
                            writer.Write(value5);
                            writer.WritePropertyName("DistanceToPlayer");
                            writer.Write(value6);
                            writer.WritePropertyName("TypeDisplayName");
                            writer.Write(value7);
                            writer.WriteObjectEnd();
                        }
                    }
                }
                writer.WriteArrayEnd();
                break;

            case "/metrics/v1/session/factions":
                writer.WriteArrayStart();
                if (MySession.Static != null && MySession.Static.Ready)
                {
                    List <MyFaction> factions = MySession.Static.Factions.Select((x) => x.Value).ToList();
                    foreach (MyFaction myfaction in factions)
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("AcceptHumans");
                        writer.Write(myfaction.AcceptHumans);
                        writer.WritePropertyName("AutoAcceptMember");
                        writer.Write(myfaction.AutoAcceptMember);
                        writer.WritePropertyName("AutoAcceptPeace");
                        writer.Write(myfaction.AutoAcceptPeace);
                        writer.WritePropertyName("EnableFriendlyFire");
                        writer.Write(myfaction.EnableFriendlyFire);
                        writer.WritePropertyName("FactionId");
                        writer.Write(myfaction.FactionId);
                        writer.WritePropertyName("FounderId");
                        writer.Write(myfaction.FounderId);
                        writer.WritePropertyName("MemberCount");
                        writer.Write(myfaction.Members.Count);
                        writer.WritePropertyName("Name");
                        writer.Write(myfaction.Name);
                        writer.WritePropertyName("Tag");
                        writer.Write(myfaction.Tag);
                        writer.WritePropertyName("NPCOnly");
                        writer.Write(myfaction.Members.All((x) => MySession.Static.Players.IdentityIsNpc(x.Value.PlayerId)));
                        writer.WriteObjectEnd();
                    }
                }
                writer.WriteArrayEnd();
                break;
            }

            return(sb.ToString());
        }
Пример #2
0
        public override void BeforeStart()
        {
            try
            {
                IsServer          = MyAPIGateway.Multiplayer.IsServer;
                IsDedicatedServer = MyAPIGateway.Utilities.IsDedicated;

                _logger      = new Logger("AQDResearch.log", IsDedicatedServer);
                _researchLab = new MyDefinitionId(typeof(MyObjectBuilder_Assembler), "AQD_LG_ResearchLab");
                _dataStorage = new MyDefinitionId(typeof(MyObjectBuilder_CargoContainer), "AQD_LG_DataStorage");

                _researchSettings = new ResearchGroupSettings();

                StringBuilder sb = new StringBuilder();
                foreach (var def in MyDefinitionManager.Static.GetEntityComponentDefinitions())
                {
                    if (def.Id.SubtypeName.StartsWith("ProgressionFramework"))
                    {
                        sb.Clear();
                        foreach (var ch in def.DescriptionText)
                        {
                            if (ch == '[')
                            {
                                sb.Append('<');
                            }
                            else if (ch == ']')
                            {
                                sb.Append('>');
                            }
                            else
                            {
                                sb.Append(ch);
                            }
                        }

                        var buffer = sb.ToString().Trim();
                        try
                        {
                            var settings = MyAPIGateway.Utilities.SerializeFromXML <ResearchGroupSettings>(buffer);

                            foreach (var group in settings.ResearchGroupList)
                            {
                                _researchSettings.AddResearchGroup(group);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Log($"Error trying to deserialize EntityComponentDefinition: {ex.Message}\n{ex.StackTrace}\nBuffer = \n{buffer}\n", MessageType.ERROR);
                        }
                    }
                }

                var ents = MyEntities.GetEntities();
                foreach (var e in ents)
                {
                    ProcessEntity(e);
                }

                MyEntities.OnEntityCreate += MyEntities_OnEntityCreate;
            }
            catch (Exception ex)
            {
                _logger?.Log($"Exception in AQDResearch.BeforeStart: {ex.Message}\n{ex.StackTrace}", MessageType.ERROR);
                UnloadLocal();
            }

            base.BeforeStart();
        }
Пример #3
0
        private void RevokeOwnership(ulong steamId, string blocktype, bool isSubtype)
        {
            long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);

            int counter = 0;

            HashSet <MyEntity> entities = new HashSet <MyEntity>();

            Wrapper.GameAction(() => entities = MyEntities.GetEntities());

            foreach (var entity in entities)
            {
                var grid = entity as MyCubeGrid;
                if (grid == null)
                {
                    continue;
                }

                if (!grid.SmallOwners.Contains(playerId))
                {
                    continue;
                }

                foreach (var block in grid.GetFatBlocks())
                {
                    if (block.OwnerId != playerId)
                    {
                        continue;
                    }

                    if (isSubtype && block.BlockDefinition.Id.SubtypeId.ToString().Contains(blocktype, StringComparison.CurrentCultureIgnoreCase))
                    {
                        //set owner to nobody in block enforcement
                        lock (PlayerBlockEnforcement.BlockOwners)
                            if (PlayerBlockEnforcement.BlockOwners.ContainsKey((MyTerminalBlock)block))
                            {
                                PlayerBlockEnforcement.BlockOwners[(MyTerminalBlock)block] = 0;
                            }

                        Wrapper.GameAction(() =>
                        {
                            //change owner to nobody and reduce build to 1%
                            block.ChangeOwner(0, MyOwnershipShareModeEnum.None);
                            block.SlimBlock.DecreaseMountLevelToDesiredRatio(0.1f, null);
                        });
                        counter++;
                    }

                    if (!isSubtype && block.BlockDefinition.Id.TypeId.ToString().Contains(blocktype, StringComparison.CurrentCultureIgnoreCase))
                    {
                        lock (PlayerBlockEnforcement.BlockOwners)
                            if (PlayerBlockEnforcement.BlockOwners.ContainsKey((MyTerminalBlock)block))
                            {
                                PlayerBlockEnforcement.BlockOwners[(MyTerminalBlock)block] = 0;
                            }

                        Wrapper.GameAction(() =>
                        {
                            block.ChangeOwner(0, MyOwnershipShareModeEnum.None);
                            block.SlimBlock.DecreaseMountLevelToDesiredRatio(0.1f, null);
                        });
                        counter++;
                    }
                }
            }

            Communication.SendPrivateInformation(steamId, $"Revoked ownership of {counter} {blocktype} blocks");
        }
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD      line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I   cubePos;
                double     distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix  = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block      = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
            {
                return(handled);
            }

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl  = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                //MyInventoryItem item = new MyInventoryItem(100,
                var oreBuilder = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var item       = new MyInventoryItem(1, oreBuilder);
                var obj        = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List <HkShape>       trShapes = new List <HkShape>();
                List <HkConvexShape> shapes   = new List <HkConvexShape>();
                List <Matrix>        matrices = new List <Matrix>();

                var         grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List <HkShape>()
                            {
                                box
                            }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List <Vector3>(), new List <int>());

                var list         = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp         = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType  = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape       = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType <MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType <MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                var oreBuilder = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var obj        = new MyObjectBuilder_FloatingObject()
                {
                    Item = new MyObjectBuilder_InventoryItem()
                    {
                        Content = oreBuilder, Amount = 1000
                    }
                };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags        = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyStructuralIntegrity.Enabled         = true;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType <MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                    {
                        continue;
                    }

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType <MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                    {
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;
                    }

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.ControlledEntity != null ? MySession.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;
                if (invObject != null)
                {
                    MyFixedPoint amount = 20000;

                    var         oreBuilder = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory  = invObject.GetInventory(0);
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType <MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType <MyFloatingObject>())
                {
                    if (obj == MySession.ControlledEntity)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.ControlledEntity && (MySession.ControlledEntity == null || obj != MySession.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                    {
                        obj.Close();
                    }
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType <MyFloatingObject>().ToArray())
                {
                    e.Close();
                }
            }

            return(handled);
        }
Пример #5
0
        private static int CleanupReputations()
        {
            var collection  = _relationsGet(MySession.Static.Factions);
            var collection2 = _playerRelationsGet(MySession.Static.Factions);


            var validIdentities = new HashSet <long>();

            //find all identities owning a block
            foreach (var entity in MyEntities.GetEntities())
            {
                var grid = entity as MyCubeGrid;
                if (grid == null)
                {
                    continue;
                }
                validIdentities.UnionWith(grid.SmallOwners);
            }


            //find online identities
            foreach (var online in MySession.Static.Players.GetOnlinePlayers())
            {
                validIdentities.Add(online.Identity.IdentityId);
            }

            foreach (var identity in MySession.Static.Players.GetAllIdentities().ToList())
            {
                if (MySession.Static.Players.IdentityIsNpc(identity.IdentityId))
                {
                    validIdentities.Add(identity.IdentityId);
                }
            }

            //Add Factions with at least one member to valid identities
            foreach (var faction in MySession.Static.Factions.Factions.Where(x => x.Value.Members.Count > 0))
            {
                validIdentities.Add(faction.Key);
            }


            //might not be necessary, but just in case
            validIdentities.Remove(0);
            var result = 0;

            var collection0List = collection.Keys.ToList();
            var collection1List = collection2.Keys.ToList();

            foreach (var pair in collection0List)
            {
                if (validIdentities.Contains(pair.RelateeId1) && validIdentities.Contains(pair.RelateeId2))
                {
                    continue;
                }
                collection.Remove(pair);
                result++;
            }

            foreach (var pair in collection1List)
            {
                if (validIdentities.Contains(pair.RelateeId1) && validIdentities.Contains(pair.RelateeId2))
                {
                    continue;
                }
                collection2.Remove(pair);
                result++;
            }


            //_relationsSet.Invoke(MySession.Static.Factions,collection);
            //_playerRelationsSet.Invoke(MySession.Static.Factions,collection2);
            return(result);
        }
Пример #6
0
        public void CleanSandbox()
        {
            int count           = 0;
            var validIdentities = new HashSet <long>();
            var idCache         = new HashSet <long>();

            //find all identities owning a block
            foreach (var entity in MyEntities.GetEntities())
            {
                var grid = entity as MyCubeGrid;
                if (grid == null)
                {
                    continue;
                }
                validIdentities.UnionWith(grid.SmallOwners);
            }

            foreach (var online in MySession.Static.Players.GetOnlinePlayers())
            {
                validIdentities.Add(online.Identity.IdentityId);
            }

            //might not be necessary, but just in case
            validIdentities.Remove(0);

            //clean identities that don't own any blocks, or don't have a steam ID for whatever reason
            foreach (var identity in MySession.Static.Players.GetAllIdentities().ToList())
            {
                if (MySession.Static.Players.IdentityIsNpc(identity.IdentityId))
                {
                    validIdentities.Add(identity.IdentityId);
                    continue;
                }

                if (validIdentities.Contains(identity.IdentityId))
                {
                    continue;
                }

                RemoveFromFaction_Internal(identity);
                MySession.Static.Players.RemoveIdentity(identity.IdentityId);
                validIdentities.Remove(identity.IdentityId);
                count++;
            }

            //reset ownership of blocks belonging to deleted identities
            count += FixBlockOwnership();

            //clean up empty factions
            count += CleanFaction_Internal();

            //cleanup reputations

            count += CleanupReputations();


            //Keen, for the love of god why is everything about GPS internal.
            var playerGpss = GpsDicField.GetValue(MySession.Static.Gpss) as Dictionary <long, Dictionary <int, MyGps> >;

            foreach (var id in playerGpss.Keys)
            {
                if (!validIdentities.Contains(id))
                {
                    idCache.Add(id);
                }
            }

            foreach (var id in idCache)
            {
                playerGpss.Remove(id);
            }

            count += idCache.Count;
            idCache.Clear();

            var g = MySession.Static.GetComponent <MyProceduralWorldGenerator>();
            var f = SeedParamField.GetValue(g) as HashSet <MyObjectSeedParams>;

            count += f.Count;
            f.Clear();

            //TODO

            /*
             * foreach (var history in MySession.Static.ChatHistory)
             * {
             *  if (!validIdentities.Contains(history.Key))
             *      idCache.Add(history.Key);
             * }
             *
             * foreach (var id in idCache)
             * {
             *  MySession.Static.ChatHistory.Remove(id);
             * }
             * count += idCache.Count;
             * idCache.Clear();
             *
             * //delete chat history for deleted factions
             * for (int i = MySession.Static.FactionChatHistory.Count - 1; i >= 0; i--)
             * {
             *  var history = MySession.Static.FactionChatHistory[i];
             *  if (MySession.Static.Factions.TryGetFactionById(history.FactionId1) == null || MySession.Static.Factions.TryGetFactionById(history.FactionId2) == null)
             *  {
             *      count++;
             *      MySession.Static.FactionChatHistory.RemoveAtFast(i);
             *  }
             * }
             */

            var cf = AllCamerasField.GetValue(CamerasField.GetValue(MySession.Static)) as Dictionary <MyPlayer.PlayerId, Dictionary <long, MyEntityCameraSettings> >;

            count += cf.Count;
            cf.Clear();

            Context.Respond($"Removed {count} unnecessary elements.");
        }