/// <summary>
        /// Create a new game session.
        /// </summary>
        /// <param name="levelFileName">File name of the level to be loaded (without file extension).</param>
        public void CreateNewGame(string levelFileName)
        {
            if (_isConnected)
            {
                CommandServerNewGame command = new CommandServerNewGame(_client_ID, levelFileName);
                SendCommandToServer(command);

                CommandFeedback feedback = EvaluateFeedback();
                if (feedback is CommandFeedbackOK)
                {
                    _gameSession_ID = ReceiveStringFromServer();
                    _isHost         = true;
                }
                else if (feedback is CommandFeedbackGameException)
                {
                    throw ((CommandFeedbackGameException)feedback).GameException;
                }
                else
                {
                    throw new CommandNotRecognizedException();
                }
            }
            else
            {
                throw new ClientIsNotConnectedToServerException();
            }
        }
示例#2
0
        public IHttpActionResult RobotReport(string robotId)
        {
            try
            {
                //do validation first here.
                if (string.IsNullOrEmpty(robotId))
                {
                    var feedback = new CommandFeedback
                    {
                        IsSuccess    = false,
                        ErrorMessage = "Robot identifier not provided."
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                var robot = RobotService.GetRobot(robotId);

                //if we cannot find robot, we need to return error message.
                if (robot == null)
                {
                    var feedback = new CommandFeedback
                    {
                        IsSuccess = false,
                        ErrorCode = CommandErrorCode.RobotNotPositioned
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                return(Ok(robot.Report()));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        /// <summary>
        /// Creates a new player for the client in the current session.
        /// </summary>
        /// <param name="playerName">Name of the character.</param>
        /// <param name="pClass">The class of character of the character.</param>
        public void CreateNewPlayerForSession(string playerName, CharacterClass pClass)
        {
            if (_isConnected)
            {
                if (_gameSession_ID != null)
                {
                    CommandServerCreatePlayer command = new CommandServerCreatePlayer(_client_ID, _gameSession_ID, playerName, pClass);
                    SendCommandToServer(command);

                    CommandFeedback feedback = EvaluateFeedback();
                    if (feedback is CommandFeedbackOK)
                    {
                    }
                    else if (feedback is CommandFeedbackEndOfTurn)
                    {
                        Thread updateThread = new Thread(new ThreadStart(() => WaitForNextTurn()));
                        updateThread.Start();
                    }
                    else if (feedback is CommandFeedbackGameException)
                    {
                        throw ((CommandFeedbackGameException)feedback).GameException;
                    }
                    else
                    {
                        throw new CommandNotRecognizedException();
                    }
                }
            }
            else
            {
                throw new ClientIsNotConnectedToServerException();
            }
        }
        /// <summary>
        /// Creates a command to move your character on the playing field.
        /// </summary>
        public void MovePlayer(int x, int y)
        { //TODO: Übergabe der Richtung und Anzahl Schritte
            if (_isConnected)
            {
                if (_gameSession_ID != null && _currentStatus == Status.Busy)
                {
                    CommandGameMove command = new CommandGameMove(_client_ID, x, y);
                    SendCommandToServer(command);

                    CommandFeedback feedback = EvaluateFeedback();
                    if (feedback is CommandFeedbackOK)
                    {
                    }
                    else if (feedback is CommandFeedbackEndOfTurn)
                    {
                        Thread updateThread = new Thread(new ThreadStart(() => WaitForNextTurn()));
                        updateThread.Start();
                    }
                    else if (feedback is CommandFeedbackGameException)
                    {
                        throw ((CommandFeedbackGameException)feedback).GameException;
                    }
                    else
                    {
                        throw new CommandNotRecognizedException();
                    }
                }
            }
        }
        /// <summary>
        /// Ends the player's turn earlier than normal.
        /// </summary>
        public void EndTurn()
        {
            if (_isConnected)
            {
                if (_gameSession_ID != null && _currentStatus == Status.Busy)
                {
                    CommandGameEndTurn command = new CommandGameEndTurn(_client_ID);
                    SendCommandToServer(command);

                    CommandFeedback feedback = EvaluateFeedback();
                    if (feedback is CommandFeedbackOK)
                    {
                        Thread updateThread = new Thread(new ThreadStart(() => WaitForNextTurn()));
                        updateThread.Start();
                    }
                    else if (feedback is CommandFeedbackEndOfTurn)
                    {
                        Thread updateThread = new Thread(new ThreadStart(() => WaitForNextTurn())); updateThread.Start();
                    }
                    else if (feedback is CommandFeedbackGameException)
                    {
                        throw ((CommandFeedbackGameException)feedback).GameException;
                    }
                    else
                    {
                        throw new CommandNotRecognizedException();
                    }
                }
            }
        }
        /// <summary>
        /// Gets the update pack for the host in the lobby.
        /// </summary>
        public void GetUpdatePackForLobby()
        {
            if (_isConnected)
            {
                if (_gameSession_ID != null && _currentStatus == Status.Busy)
                {
                    CommandServerGetUpdatePackForLobby command = new CommandServerGetUpdatePackForLobby(_client_ID, _gameSession_ID);
                    SendCommandToServer(command);

                    CommandFeedback feedback = EvaluateFeedback();
                    if (feedback is CommandFeedbackUpdatePack)
                    {
                        _update = ((CommandFeedbackUpdatePack)feedback).Update;
                    }
                    else if (feedback is CommandFeedbackGameException)
                    {
                        throw ((CommandFeedbackGameException)feedback).GameException;
                    }
                    else
                    {
                        throw new CommandNotRecognizedException();
                    }
                }
            }
        }
        /// <summary>
        /// Start the current game.
        /// Can only be executed by the host and only when all players are connected.
        /// </summary>
        public void StartCreatedGame()
        {
            if (_isConnected)
            {
                if (_gameSession_ID != null && _isHost)
                {
                    CommandServerStartGame command = new CommandServerStartGame(_client_ID, _gameSession_ID);
                    SendCommandToServer(command);

                    CommandFeedback feedback = EvaluateFeedback();
                    if (feedback is CommandFeedbackOK)
                    {
                    }
                    else if (feedback is CommandFeedbackGameException)
                    {
                        throw ((CommandFeedbackGameException)feedback).GameException;
                    }
                    else
                    {
                        throw new CommandNotRecognizedException();
                    }
                }
            }
            else
            {
                throw new ClientIsNotConnectedToServerException();
            }
        }
示例#8
0
        /// <summary>
        /// Util function for Right and Left commands
        /// </summary>
        /// <param name="robotId"></param>
        /// <param name="direction"></param>
        /// <returns></returns>
        private IHttpActionResult TurnRobot(string robotId, RotationalDirection direction)
        {
            try
            {
                //do validation first here.
                if (string.IsNullOrEmpty(robotId))
                {
                    var feedback = new CommandFeedback
                    {
                        IsSuccess = false,
                        ErrorCode = CommandErrorCode.RobotNotPositioned
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                var robot = RobotService.GetRobot(robotId);

                //if we cannot find robot, we need to return error message.
                if (robot == null)
                {
                    var feedback = new CommandFeedback
                    {
                        IsSuccess = false,
                        ErrorCode = CommandErrorCode.RobotNotPositioned
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                CommandFeedback result;

                if (direction == RotationalDirection.Left)
                {
                    result = _rotateLeft.Impact(robot);
                }
                else if (direction == RotationalDirection.Right)
                {
                    result = _rotateRight.Impact(robot);
                }
                else
                {
                    throw new Exception("Invalid direction/Face provided for robot move.");
                }

                if (result.IsSuccess)
                {
                    RobotService.PersistRobot(robot);
                }

                return(Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
示例#9
0
        private void HandleLocalCommand(string msg, ref bool sendToOthers)
        {
            if (msg.Length == 0 || msg[0] != '/')
            {
                return;
            }
            var cmdFeedback = new CommandFeedback((format, fields) =>
            {
                MyAPIGateway.Utilities.ShowMessage("EqUtils", string.Format(format, fields));
            });

            try
            {
                var     args = ParseArguments(msg, 1);
                Command cmd;
                lock (m_commands)
                    if (!m_commands.TryGetValue(args[0], out cmd))
                    {
                        Log(MyLogSeverity.Debug, "Unknown command {0}", args[0]);
                        return;
                    }

                var player = MyAPIGateway.Session.Player;
                if (player == null)
                {
                    Log(MyLogSeverity.Warning, "Attempted to run a local command without a player.");
                    return;
                }
                sendToOthers = false;
                if (!cmd.AllowedSessionType.Flagged(MyAPIGateway.Session.SessionType()))
                {
                    Log(MyLogSeverity.Debug, "Unable to run {0} on a session of type {1}; it requires type {2}", args[0], MyAPIGateway.Session.SessionType(), cmd.AllowedSessionType);
                    return;
                }
                if (!cmd.CanPromotionLevelUse(player.PromoteLevel))
                {
                    cmdFeedback.Invoke("EqUtils", "You must be at least " + cmd.MinimumLevel + " to use this command");
                    return;
                }
                var result = cmd.Process(cmdFeedback, args);
                if (result != null)
                {
                    cmdFeedback.Invoke(result);
                }
            }
            catch (ArgumentException e)
            {
                Log(MyLogSeverity.Debug, "Failed to parse \"{0}\".  Error:\n{1}", msg, e.ToString());
            }
            catch (Exception e)
            {
                Log(MyLogSeverity.Critical, "Failed to process \"{0}\".  Error:\n{1}", msg, e.ToString());
            }
        }
示例#10
0
        private void HandleGlobalCommand(ulong steamID, string msg)
        {
            if (msg.Length == 0 || msg[0] != '/')
            {
                return;
            }
            try
            {
                var     args = ParseArguments(msg, 1);
                Command cmd;
                lock (m_commands)
                    if (!m_commands.TryGetValue(args[0], out cmd))
                    {
                        Log(MyLogSeverity.Debug, "Unknown command {0}", args[0]);
                        return;
                    }

                var player = MyAPIGateway.Players.GetPlayerBySteamId(steamID);
                if (player == null)
                {
                    Log(MyLogSeverity.Warning, "Attempted unable to determine player instance for Steam ID {0}", steamID);
                    return;
                }
                if (!MyAPIGateway.Session.SessionType().Flagged(cmd.AllowedSessionType))
                {
                    Log(MyLogSeverity.Debug, "Unable to run {0} on a session of type {1}; it requires type {2}", args[0], MyAPIGateway.Session.SessionType(), cmd.AllowedSessionType);
                    return;
                }
                var cmdFeedback = new CommandFeedback((format, fields) =>
                {
                    var content = string.Format(format, fields);
                    MyVisualScriptLogicProvider.SendChatMessage(content, "EqProcUtils", player.IdentityId);
                });
                if (!cmd.CanPromotionLevelUse(player.PromoteLevel))
                {
                    cmdFeedback.Invoke("You must be at least a {0} to use the {1} command.  You are are {2}", cmd.MinimumLevel, args[0], player.PromoteLevel);
                    Log(MyLogSeverity.Debug, "Player {0} ({1}) attempted to run {2} at level {3}", player.DisplayName, player.PromoteLevel, args[0], cmd.MinimumLevel);
                    return;
                }
                var result = cmd.Process(cmdFeedback, args);
                if (result != null)
                {
                    cmdFeedback.Invoke(result);
                }
            }
            catch (ArgumentException e)
            {
                Log(MyLogSeverity.Debug, "Failed to parse \"{0}\".  Error:\n{1}", msg, e.ToString());
            }
            catch (Exception e)
            {
                Log(MyLogSeverity.Critical, "Failed to process \"{0}\".  Error:\n{1}", msg, e.ToString());
            }
        }
示例#11
0
 private void HandleFailure(string error, object message)
 {
     if (message is ICommand)
     {
         Sender.Tell(CommandFeedback.CreateFailureFeedback(error));
     }
     else
     {
         Log.Error(error);
     }
 }
示例#12
0
 private string RunExport(CommandFeedback feedback)
 {
     MyAPIGateway.Entities.GetEntities(null, x =>
     {
         var grid = x as IMyCubeGrid;
         if (grid != null)
         {
             Process(feedback, grid);
         }
         return(false);
     });
     return(null);
 }
        private string ProcessInfo(CommandFeedback feedback, string partName)
        {
            LogMux logger = (level, format, args) =>
            {
                this.Log(level, format, args);
                feedback?.Invoke(format, args);
            };
            var part = m_partManager.FirstOrDefault(test => test.Prefab.Id.SubtypeName.ToLower().Contains(partName.ToLower()));

            if (part == null)
            {
                return("Unable to find part with name \"" + partName + "\"");
            }
            var info = part.BlockSetInfo;

            logger(MyLogSeverity.Info, "Part info for {0}\nBlock type counts:", part.Name);
            foreach (var kv in info.BlockCountByType)
            {
                logger(MyLogSeverity.Info, "{0}: {1}", kv.Key, kv.Value);
            }
            logger(MyLogSeverity.Info, "Total power consumption/storage: {0:e}:{1:e}  Groups:", info.TotalPowerNetConsumption, info.TotalPowerStorage);
            foreach (var kv in info.PowerConsumptionByGroup)
            {
                logger(MyLogSeverity.Info, "{0}: {1}", kv.Key, kv.Value);
            }
            logger(MyLogSeverity.Info, "Total inventory capacity: {0:e}", info.TotalInventoryCapacity);
            logger(MyLogSeverity.Info, "Total component cost:");
            foreach (var kv in info.ComponentCost)
            {
                logger(MyLogSeverity.Info, "{0}: {1}", kv.Key.Id.SubtypeName, kv.Value);
            }
            logger(MyLogSeverity.Info, "Production quotas:");
            foreach (var pi in MyDefinitionManager.Static.GetPhysicalItemDefinitions())
            {
                logger(MyLogSeverity.Info, "{0}: {1}", pi.Id, info.TotalProduction(pi.Id));
            }
            foreach (var pi in MyDefinitionManager.Static.GetDefinitionsOfType <MyComponentDefinition>())
            {
                logger(MyLogSeverity.Info, "{0}: {1}", pi.Id, info.TotalProduction(pi.Id));
            }
            foreach (var gas in MyDefinitionManager.Static.GetDefinitionsOfType <MyGasProperties>())
            {
                logger(MyLogSeverity.Info, "{0}: {1}", gas.Id, info.TotalProduction(gas.Id));
            }
            logger(MyLogSeverity.Info, "Gas storage");
            foreach (var gas in MyDefinitionManager.Static.GetDefinitionsOfType <MyGasProperties>())
            {
                logger(MyLogSeverity.Info, "{0}: {1}", gas.Id, info.TotalGasStorage(gas.Id));
            }
            return(null);
        }
示例#14
0
        public IHttpActionResult PlaceRobot(RobotViewModel model)
        {
            try
            {
                //do validation first here.
                if (!ModelState.IsValid)
                {
                    var message = string.Join(" | ", ModelState.Values
                                              .SelectMany(v => v.Errors)
                                              .Select(e => e.ErrorMessage));

                    var feedback = new CommandFeedback
                    {
                        IsSuccess    = false,
                        ErrorMessage = "Invalid Data:" + message
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                Robot robot = null;

                //check if we have robot id
                if (model.RobotId != null)
                {
                    robot = RobotService.GetRobot(model.RobotId.ToString());
                }
                //create the robot if it doesn't exist
                if (model.RobotId == null || robot == null)
                {
                    robot = RobotService.CreateRobot();
                }

                var result = _placeCommand.Impact(robot,
                                                  new Position(model.Position.X, model.Position.Y, model.Position.Direction));

                if (result.IsSuccess)
                {
                    RobotService.PersistRobot(robot);
                }

                return(Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
示例#15
0
        public void object_added(IFireObject fireObject)
        {
            if (fireObject.Path == "PlayerMapTile")
            {
                //redraw game
                // this.redrawMap();
                PlayerMapTile gameMapTile = (PlayerMapTile)fireObject;
                PlayerGame    playerGame  = this.flPlayerGames.TypedItems <PlayerGame>().Where(c => c.UserId == me.Id).FirstOrDefault();
                if (playerGame != null)
                {
                    MapTile mapTile = playerGame.Map.MapTiles.Where(c => c.Xpos == gameMapTile.Tile.Xpos && c.Ypos == gameMapTile.Tile.Ypos).FirstOrDefault();
                    if (mapTile != null)
                    {
                        mapTile = gameMapTile.Tile;
                        RedrawMapTile(mapTile);
                    }
                }
            }
            else if (fireObject.Path == "PlayerUnit")
            {
                updateMap();
            }
            else if (fireObject.Path == "CommandFeedback")
            {
                SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                synthesizer.Volume = 100;  // 0...100
                synthesizer.Rate   = -2;   // -10...10

                // Asynchronous
                CommandFeedback feedback = (CommandFeedback)fireObject;

                //foreach (InstalledVoice voice in synthesizer.GetInstalledVoices())
                //{
                //    Debug.Print(voice.VoiceInfo.Name);
                //}
                //synthesizer.SelectVoice(synthesizer.GetInstalledVoices()[1].VoiceInfo.Name);
                synthesizer.SpeakAsync(feedback.Feedback);
            }
            else if (fireObject.Path == "PlayerGame")
            {
                //All visible player units (both own and enemy)
                PlayerGame pg = (PlayerGame)fireObject;
                this.flPlayerUnits = new FireList(this.FAppPrivate, typeof(PlayerUnit), this, new FireListBox(lbxPlayerUnits), userId: pg.GameId, userIDKey: "GameId");
            }

            Debug.Print("Object added : " + fireObject.Revision);
        }
示例#16
0
        private string RunSideload(CommandFeedback feedback, string prefabKey)
        {
            var partManager = Manager.GetDependencyProvider <PartManager>();

            if (partManager == null)
            {
                return("Can't sideload parts when there is no part manager");
            }
            var fileName = prefabKey;

            if (!fileName.EndsWith(".sbc", StringComparison.OrdinalIgnoreCase))
            {
                fileName += ".sbc";
            }
            if (!MyAPIGateway.Utilities.FileExistsInLocalStorage(fileName, typeof(DesignTools)))
            {
                return($"File {fileName} has not been exported.");
            }
            using (var stream = MyAPIGateway.Utilities.ReadFileInLocalStorage(fileName, typeof(DesignTools)))
            {
                var content = stream.ReadToEnd();
                try
                {
                    var data = MyAPIGateway.Utilities.SerializeFromXML <MyObjectBuilder_Definitions>(content);
                    if (data.Prefabs == null || data.Prefabs.Length < 1)
                    {
                        return("The specified file doesn't seem to contain prefabs");
                    }
                    foreach (var prefab in data.Prefabs)
                    {
                        var lks = new MyPrefabDefinition();
                        // We don't actually link this into the definition manager so we can have a null mod context.
                        lks.Init(prefab, null);
                        lks.InitLazy(prefab);
                        partManager.Load(lks, true);
                        this.Debug("Sideloaded {0}", prefab.Id.SubtypeName);
                        feedback.Invoke("Sideloaded {0}", prefab.Id.SubtypeName);
                    }
                }
                catch (Exception e)
                {
                    this.Error("Failed to sideload prefab {0}.  Error:\n{1}", prefabKey, e.ToString());
                    return($"Failed to load: {e.Message}");
                }
            }
            return(null);
        }
        private string ClearStations(CommandFeedback feedback)
        {
            var id = MyAPIGateway.Session.Player.IdentityId;

            foreach (var gps in MyAPIGateway.Session.GPS.GetGpsList(id))
            {
                MyAPIGateway.Session.GPS.RemoveGps(id, gps);
            }
            var ent = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(ent, (x) => x is IMyCubeGrid);
            foreach (var k in ent)
            {
                MyAPIGateway.Entities.RemoveEntity(k);
            }
            return(null);
        }
        private string ProcessSpawn(CommandFeedback feedback, Dictionary <string, object> kwargs)
        {
            var generatorModule = Manager.GetDependencyProvider <StationGeneratorManager>();

            if (generatorModule == null)
            {
                return("No station generator module means no stations");
            }
            var factionModule = Manager.GetDependencyProvider <ProceduralFactions>();

            if (factionModule == null)
            {
                return("No faction module means no stations");
            }

            var debugMode  = (bool)kwargs["debug"];
            var roomCount  = (int?)kwargs["rooms"];
            var seedVal    = (long)kwargs["seed"];
            var population = (int?)kwargs["population"];
            var position   = MyAPIGateway.Session.Camera.Position + MyAPIGateway.Session.Camera.WorldMatrix.Forward * 100;
            var seed       = new ProceduralConstructionSeed(factionModule.SeedAt(position), new Vector4D(position, 0.5), null, seedVal, population);

            MyAPIGateway.Parallel.Start(() =>
            {
                ProceduralConstruction construction = null;
                ConstructionCopy grids;
                if (!generatorModule.GenerateFromSeedAndRemap(seed, ref construction, out grids, roomCount))
                {
                    this.Error("Failed to generate");
                    feedback.Invoke("Failed to generate");
                    return;
                }
                if (grids == null)
                {
                    this.Error("Failed to generate: Output grids are null");
                    feedback.Invoke("Failed to generate: Output grids are null");
                    return;
                }
                MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                {
                    var result             = grids.SpawnAsync();
                    result.ForceDebugDraw |= debugMode;
                });
            });
            return(null);
        }
示例#19
0
        public IHttpActionResult MoveRobot(string robotId)
        {
            try
            {
                //do validation first here.
                if (string.IsNullOrEmpty(robotId))
                {
                    var message = string.Join(" | ", ModelState.Values
                                              .SelectMany(v => v.Errors)
                                              .Select(e => e.ErrorMessage));

                    var feedback = new CommandFeedback
                    {
                        IsSuccess    = false,
                        ErrorMessage = message
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                var robot = RobotService.GetRobot(robotId);

                //if we cannot find robot, we need to return error message.
                if (robot == null)
                {
                    var feedback = new CommandFeedback
                    {
                        IsSuccess = false,
                        ErrorCode = CommandErrorCode.RobotNotPositioned
                    };
                    return(Ok(JsonConvert.SerializeObject(feedback)));
                }

                var result = _moveCommand.Impact(robot);

                if (result.IsSuccess)
                {
                    RobotService.PersistRobot(robot);
                }

                return(Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
示例#20
0
        /// <summary>
        /// Send Command to client
        /// </summary>
        /// <param name="server">TcpClient to which data is to be sent.</param>
        /// <param name="command">Command you want to send</param>
        private static void SendFeedbackToClient(TcpClient client, CommandFeedback command)
        {
            NetworkStream nwStream   = client.GetStream();
            MemoryStream  dataStream = new MemoryStream();
            IFormatter    formatter  = new BinaryFormatter();

            // set the binder to the custom binder:
            //formatter.Binder = TypeOnlyBinder.Default;

            var ms = new MemoryStream();

            formatter.Serialize(ms, command);

            byte[] bytesToSend = ms.ToArray();

            nwStream.Write(bytesToSend, 0, bytesToSend.Length);
            nwStream.Flush();
        }
示例#21
0
        /// <summary>
        /// Send Command to client
        /// </summary>
        /// <param name="command">Command you want to send</param>
        /// <param name="client">Client to which the command is to be sent</param>
        private void SendFeedbackToClient(TcpClient client, CommandFeedback command)
        {
            if (GetTcpClientState(client))
            {
                try
                {
                    NetworkStream nwStream = client.GetStream();
                    IFormatter formatter = new BinaryFormatter();

                    formatter.Serialize(nwStream, command);
                    nwStream.Flush();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        private string ProcessStationLocations(CommandFeedback feedback)
        {
            if (!MyAPIGateway.Session.HasCreativeRights)
            {
                return("You must have creative rights to use the station location command");
            }
            var stationModule = Manager.GetDependencyProvider <ProceduralStationModule>();

            if (stationModule == null)
            {
                return("No station module means no stations");
            }
            var factionModule = Manager.GetDependencyProvider <ProceduralFactions>();

            if (factionModule == null)
            {
                return("No faction module means no stations");
            }
            var stationNoise = stationModule.StationNoise;
            var sphere       = new BoundingSphereD(MyAPIGateway.Session.Camera.Position, MyAPIGateway.Session.SessionSettings.ViewDistance * 10);
            var id           = MyAPIGateway.Session.Player.IdentityId;
            var aabb         = new BoundingBoxD(sphere.Center - sphere.Radius, sphere.Center + sphere.Radius);

            foreach (var s in stationNoise.TryGetSpawnIn(aabb, sphere.Intersects))
            {
                var position = new Vector3D(s.Item2.X, s.Item2.Y, s.Item2.Z);
                var cseed    = new ProceduralConstructionSeed(factionModule.SeedAt(s.Item2.XYZ()), s.Item2, null, s.Item1.GetHashCode());
                var name     = "[" + cseed.Faction.Tag + "] " + cseed.Name;
                foreach (var gps2 in MyAPIGateway.Session.GPS.GetGpsList(id))
                {
                    if (gps2.Name.Equals(name))
                    {
                        MyAPIGateway.Session.GPS.RemoveGps(id, gps2);
                    }
                }
                var gps = MyAPIGateway.Session.GPS.Create(name, "", position, true, true);
                gps.DiscardAt = MyAPIGateway.Session.ElapsedPlayTime + new TimeSpan(0, 5, 0);
                MyAPIGateway.Session.GPS.AddGps(id, gps);
            }
            return(null);
        }
        /// <summary>
        /// Establish a connection to the game session.
        /// </summary>
        /// <param name="session_ID">The SessionID of the game to be joined.</param>
        public void ConnectToGame(string session_ID)
        {
            if (_isConnected)
            {
                CommandServerJoinGame command = new CommandServerJoinGame(_client_ID, session_ID);
                SendCommandToServer(command);

                CommandFeedback feedback = EvaluateFeedback();
                if (feedback is CommandFeedbackOK)
                {
                    _gameSession_ID = session_ID;
                }
                else if (feedback is CommandFeedbackGameException)
                {
                    throw ((CommandFeedbackGameException)feedback).GameException;
                }
                else
                {
                    throw new CommandNotRecognizedException();
                }
            }
        }
示例#24
0
        public void ExecuteCommand(string[] sep)
        {
            if (sep.Length == 0)
            {
                return;
            }

            string         first = sep[0];
            ConsoleCommand cmd;

            if (!commands.TryGetValue(first, out cmd))
            {
                ConsoleU.WriteLine("Unknown command", Palette.Error);
                return;
            }

            CommandFeedback feedback = cmd.Execute(sep);

            if (feedback != CommandFeedback.Success)
            {
                ConsoleU.WriteLine(feedback.ToString(), Palette.Error);
            }
        }
        private string ProcessDebugPart(CommandFeedback feedback, string partName)
        {
            var part = m_partManager.FirstOrDefault(test => test.Prefab.Id.SubtypeName.ToLower().Contains(partName.ToLower()));

            if (part == null)
            {
                return("Unable to find part with name \"" + partName + "\"");
            }
            var position = MyAPIGateway.Session.Camera.Position + MyAPIGateway.Session.Camera.WorldMatrix.Forward * 100;
            var seed     = new ProceduralConstructionSeed(new ProceduralFactionSeed("dummy", 0), new Vector4D(position, 0.5), null, 0);

            MyAPIGateway.Parallel.Start(() =>
            {
                var construction = new ProceduralConstruction(RootLogger, seed);
                var room         = new ProceduralRoom();
                room.Init(new MatrixI(Base6Directions.Direction.Forward, Base6Directions.Direction.Up), part);
                construction.AddRoom(room);
                var remapper = new RoomRemapper(RootLogger)
                {
                    DebugRoomColors = true
                };
                var grids = GridCreator.RemapAndBuild(construction, remapper);
                if (grids == null)
                {
                    return;
                }
                MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                {
                    var component = grids.SpawnAsync();
                    if (component != null)
                    {
                        component.ForceDebugDraw = true;
                    }
                });
            });
            return(null);
        }
示例#26
0
 private void Handle(ZetPapierUit command)
 {
     RaiseEvent(new PapierSettingPersoonPapierUitgezet(command.PerNummer),
                e => Sender.Tell(CommandFeedback.CreateSuccessFeedback()));
 }
示例#27
0
 private void Handle(SchrijfPapierSettingPersoonUit command)
 {
     RaiseEvent(new PapierSettingPersoonUitgeschreven(command.PerNummer),
                e => Sender.Tell(CommandFeedback.CreateSuccessFeedback()));
 }
示例#28
0
 private void Handle(RegistreerPapierSettingPersoon command)
 {
     RaiseEvent(new PapierSettingPersoonGeregistreerd(command.PerNummer, command.Naam, command.Voornaam, command.Straat, command.Nummer,
                                                      command.Bus, command.Postcode, command.Gemeente),
                e => Sender.Tell(CommandFeedback.CreateSuccessFeedback()));
 }
示例#29
0
        public string Process(CommandFeedback feedback, string[] args)
        {
            if (args.Length < m_orderedArguments.Count + 1)
            {
                // Not enough arguments.
                return("Not enough ordered args");
            }
            var kwargs    = new Dictionary <string, object>();
            var pArgCount = 0;
            var pargs     = new object[m_orderedArguments.Count];

            foreach (var kvs in m_namedArguments)
            {
                if (kvs.Value.HasDefault)
                {
                    kwargs[kvs.Key] = kvs.Value.Default;
                }
            }
            for (var i = 1; i < args.Length; i++)
            {
                // Parse as named argument/flag
                if (args[i].StartsWith("--"))
                {
                    var idx  = args[i].IndexOf('=');
                    var name = args[i].Substring(2, (idx < 0 ? args[i].Length : idx) - 2);
                    NamedArgumentWrapper arg;
                    if (m_namedArguments.TryGetValue(name, out arg))
                    {
                        object value      = null;
                        string parseValue = null;
                        if (arg.IsFlag && idx > 0)
                        {
                            return("Flag " + name + " doesn't expect a value");
                        }
                        if (arg.IsFlag)
                        {
                            value = true;
                        }
                        else if (idx > 0)
                        {
                            parseValue = args[i].Substring(idx + 1);
                        }
                        else if (i + 1 >= args.Length)
                        {
                            return("Named argument " + name + " doesn't have a value");
                        }
                        else
                        {
                            parseValue = args[i + 1];
                            i++;
                        }
                        if (parseValue != null && !arg.TryParse(parseValue, out value))
                        {
                            return("Unable to parse " + parseValue + " as " + arg.Type);
                        }
                        foreach (var s in arg.Names)
                        {
                            kwargs[s] = value;
                        }
                    }
                    else
                    {
                        return("Unknown named argument: " + name);
                    }
                }
                else if (args[i].StartsWith("-"))
                {
                    var aux = args[i].Substring(1);
                    var ai  = 0;
                    while (ai < aux.Length - 1)
                    {
                        NamedArgumentWrapper arg;
                        if (!m_namedArguments.TryGetValue(aux[ai].ToString(), out arg))
                        {
                            return("Unknown flag " + aux[ai]);
                        }
                        if (!arg.IsFlag)
                        {
                            return(aux[ai] + " isn't a flag");
                        }
                        foreach (var s in arg.Names)
                        {
                            kwargs[s] = true;
                        }
                        ai++;
                    }
                    NamedArgumentWrapper arg2;
                    if (!m_namedArguments.TryGetValue(aux[aux.Length - 1].ToString(), out arg2))
                    {
                        return("Unknown named argument " + aux[aux.Length - 1]);
                    }
                    if (arg2.IsFlag)
                    {
                        foreach (var s in arg2.Names)
                        {
                            kwargs[s] = true;
                        }
                    }
                    else if (i >= args.Length - 1)
                    {
                        return("No value for argument " + aux[aux.Length - 1]);
                    }
                    else
                    {
                        object result = null;
                        if (!arg2.TryParse(args[i + 1], out result))
                        {
                            return("Unable to parse " + args[i + 1] + " as " + arg2.Type);
                        }
                        foreach (var s in arg2.Names)
                        {
                            kwargs[s] = result;
                        }
                        i++;
                    }
                }
                else
                {
                    // parse as ordered argument
                    if (pArgCount >= m_orderedArguments.Count)
                    {
                        return("Too many ordered arguments");
                    }
                    var arg = m_orderedArguments[pArgCount];
                    if (!arg.TryParse(args[i], out pargs[pArgCount]))
                    {
                        return("Unable to parse " + args[i] + " as " + arg.Type);
                    }
                    pArgCount++;
                }
            }
            while (pArgCount < m_orderedArguments.Count && m_orderedArguments[pArgCount].HasDefault)
            {
                pargs[pArgCount] = m_orderedArguments[pArgCount].Default;
                pArgCount++;
            }
            // ReSharper disable once ConvertIfStatementToReturnStatement
            if (pArgCount < m_orderedArguments.Count)
            {
                return("Unable to find enough ordered arguments");
            }
            return(m_handler.Invoke(feedback, kwargs, pargs));
        }
示例#30
0
        private void Process(CommandFeedback feedback, IMyCubeGrid grid)
        {
            if (grid.CustomName == null || !grid.CustomName.StartsWithICase("EqProcBuild"))
            {
                return;
            }
            var ob = grid.GetObjectBuilder(true) as MyObjectBuilder_CubeGrid;

            if (ob == null)
            {
                return;
            }
            this.Info("Begin processing {0}", grid.CustomName);
            feedback?.Invoke("Processing {0}", grid.CustomName);
            try
            {
                var dummyDel  = new List <MyTuple <MyObjectBuilder_CubeBlock, string> >();
                var blockKeep = new List <MyObjectBuilder_CubeBlock>();
                var blockMap  = new Dictionary <Vector3I, MyObjectBuilder_CubeBlock>(Vector3I.Comparer);
                foreach (var block in ob.CubeBlocks)
                {
                    var mount = false;
                    foreach (var name in block.ConfigNames())
                    {
                        if (!name.StartsWithICase(MountDelegated) && !name.StartsWithICase(ReservedSpaceDelegated))
                        {
                            continue;
                        }
                        dummyDel.Add(MyTuple.Create(block, name));
                        mount = true;
                        break;
                    }
                    if (mount)
                    {
                        continue;
                    }

                    var      blockMin = (Vector3I)block.Min;
                    Vector3I blockMax;
                    BlockTransformations.ComputeBlockMax(block, out blockMax);
                    for (var rangeItr = new Vector3I_RangeIterator(ref blockMin, ref blockMax); rangeItr.IsValid(); rangeItr.MoveNext())
                    {
                        blockMap[rangeItr.Current] = block;
                    }
                    blockKeep.Add(block);
                }
                this.Info("Found {0} blocks to keep, {1} block mounts to remap", blockKeep.Count, dummyDel.Count);
                foreach (var pair in dummyDel)
                {
                    var block   = pair.Item1;
                    var useName = pair.Item2;

                    IEnumerable <Base6Directions.Direction> dirs = Base6Directions.EnumDirections;
                    var def       = MyDefinitionManager.Static.GetCubeBlockDefinition(pair.Item1);
                    var transform = new MatrixI(block.BlockOrientation);
                    if (def?.MountPoints != null)
                    {
                        var mountDirs = new HashSet <Base6Directions.Direction>();
                        foreach (var mount in def.MountPoints)
                        {
                            mountDirs.Add(Base6Directions.GetDirection(Vector3I.TransformNormal(mount.Normal, ref transform)));
                        }
                    }

                    var args     = useName.Split(' ');
                    var keepArgs = new List <string>(args.Length);
                    foreach (var arg in args)
                    {
                        if (arg.StartsWithICase(PartDummyUtils.ArgumentMountDirection))
                        {
                            Base6Directions.Direction dir;
                            if (Enum.TryParse(arg.Substring(2), out dir))
                            {
                                dirs = new[] { transform.GetDirection(Base6Directions.GetOppositeDirection(dir)) }
                            }
                            ;
                            else
                            {
                                this.Error("Failed to parse direction argument \"{0}\"", arg);
                                feedback?.Invoke("Error: Failed to parse direction argument \"{0}\"", arg);
                            }
                        }
                        else
                        {
                            keepArgs.Add(arg);
                        }
                    }
                    useName = string.Join(" ", keepArgs);

                    MyObjectBuilder_CubeBlock outputBlock = null;
                    var outputDir = Base6Directions.Direction.Forward;
                    foreach (var dir in dirs)
                    {
                        MyObjectBuilder_CubeBlock tmp;
                        if (!blockMap.TryGetValue(block.Min + Base6Directions.GetIntVector(dir), out tmp))
                        {
                            continue;
                        }
                        if (tmp.ConfigNames().Any(x => x.StartsWithICase(MountDelegated)))
                        {
                            continue;
                        }
                        if (outputBlock != null)
                        {
                            this.Error("Multiple directions found for {0}", pair.Item2);
                            feedback?.Invoke("Error: Multiple directions found for {0}", pair.Item2);
                        }
                        outputBlock = tmp;
                        outputDir   = dir;
                    }
                    if (outputBlock == null || !ApplyDelegate(ob, block, useName, outputBlock, outputDir))
                    {
                        this.Error("Failed to find delegated mount point for {0}", pair.Item2);
                        feedback?.Invoke("Error: Failed to find delegated mount point for {0}", pair.Item2);
                    }
                }
                ob.CubeBlocks = blockKeep;

                // Grab related grids!
                var relatedGrids = new HashSet <IMyCubeGrid> {
                    grid
                };
                var scanRelated           = new Queue <IMyCubeGrid>();
                var relatedGridController = new Dictionary <IMyCubeGrid, IMyCubeBlock>();
                scanRelated.Enqueue(grid);
                while (scanRelated.Count > 0)
                {
                    var          subGrid = scanRelated.Dequeue();
                    IMyCubeBlock controllerForThisGrid = null;
                    relatedGridController.TryGetValue(subGrid, out controllerForThisGrid);

                    subGrid.GetBlocks(null, (y) =>
                    {
                        var x = y?.FatBlock;
                        if (x == null)
                        {
                            return(false);
                        }
                        var childGrid = (x as IMyMechanicalConnectionBlock)?.TopGrid;
                        if (childGrid != null && relatedGrids.Add(childGrid))
                        {
                            scanRelated.Enqueue(childGrid);
                            relatedGridController[childGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        var parentGrid = (x as IMyAttachableTopBlock)?.Base?.CubeGrid;
                        // ReSharper disable once InvertIf
                        if (parentGrid != null && relatedGrids.Add(parentGrid))
                        {
                            scanRelated.Enqueue(parentGrid);
                            relatedGridController[parentGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        return(false);
                    });
                }
                relatedGrids.Remove(grid);
                var removedNoController = relatedGrids.RemoveWhere(x => !relatedGridController.ContainsKey(x));
                if (removedNoController > 0)
                {
                    this.Error("Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                               removedNoController);
                    feedback?.Invoke("Error: Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                                     removedNoController);
                }
                // Need to add reserved space for subgrids so they don't overlap.  So compute that.  Yay!
                foreach (var rel in relatedGrids)
                {
                    IMyCubeBlock root;
                    if (!relatedGridController.TryGetValue(rel, out root))
                    {
                        this.Error("Unable to find the mechanical connection for grid {0}", rel.CustomName);
                        feedback?.Invoke("Error: Unable to find the mechanical connection for grid {0}",
                                         rel.CustomName);
                        continue;
                    }
                    MyObjectBuilder_CubeBlock blockDest;
                    if (blockMap.TryGetValue(root.Min, out blockDest))
                    {
                        var blockLocal = (MatrixD) new MatrixI(blockDest.BlockOrientation).GetFloatMatrix();
                        blockLocal.Translation = (Vector3I)blockDest.Min * grid.GridSize;
                        var blockWorld = MatrixD.Multiply(blockLocal, grid.WorldMatrix);

                        var worldAABB = rel.WorldAABB;
                        worldAABB = Utilities.TransformBoundingBox(worldAABB, MatrixD.Invert(blockWorld));
                        var gridAABB = new BoundingBoxI(Vector3I.Floor(worldAABB.Min / grid.GridSize), Vector3I.Ceiling(worldAABB.Max / grid.GridSize));
                        var code     = $"{PartMetadata.ReservedSpacePrefix} NE:{gridAABB.Min.X}:{gridAABB.Min.Y}:{gridAABB.Min.Z} PE:{gridAABB.Max.X}:{gridAABB.Max.Y}:{gridAABB.Max.Z}";
                        this.Info("Added reserved space for subgrid {0}: Spec is \"{1}\"", rel.CustomName, code);
                        if (blockDest.Name == null || blockDest.Name.Trim().Length == 0)
                        {
                            blockDest.Name = code;
                        }
                        else
                        {
                            blockDest.Name += PartMetadata.MultiUseSentinel + code;
                        }
                    }
                    else
                    {
                        this.Error("Unable to find the OB for grid block {0} ({1}, {2}, {3}).  Is it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                        feedback?.Invoke("Unable to the find OB for grid block {0} ({1}, {2}, {3}).  Was it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                    }
                }

                var allGrids = new List <MyObjectBuilder_CubeGrid>(relatedGrids.Count + 1)
                {
                    ob
                };
                allGrids.AddRange(relatedGrids.Select(relGrid => relGrid.GetObjectBuilder(false)).OfType <MyObjectBuilder_CubeGrid>());

                // Compose description: TODO I'd love if this actually worked :/
                // var storage = new MyPartMetadata();
                // storage.InitFromGrids(ob, allGrids);
                // var data = Convert.ToBase64String(MyAPIGateway.Utilities.SerializeToBinary(storage.GetObjectBuilder()));

                var defOut = new MyObjectBuilder_PrefabDefinition()
                {
                    Id        = new SerializableDefinitionId(typeof(MyObjectBuilder_PrefabDefinition), grid.CustomName),
                    CubeGrids = allGrids.ToArray()
                };

                var fileName = grid.CustomName + ".sbc";
                this.Info("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);
                feedback?.Invoke("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);

                var mishMash = new MyObjectBuilder_Definitions()
                {
                    Prefabs = new MyObjectBuilder_PrefabDefinition[] { defOut }
                };
                var writer = MyAPIGateway.Utilities.WriteBinaryFileInLocalStorage(fileName, typeof(DesignTools));
                var obCode = MyAPIGateway.Utilities.SerializeToXML(mishMash);
                obCode = obCode.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\"");
                writer.Write(Encoding.UTF8.GetBytes(obCode));
                writer.Close();
            }
            catch (Exception e)
            {
                this.Error("Failed to parse.  Error:\n{0}", e.ToString());
            }
        }