示例#1
0
        private void startWork()
        {
            SimulationOptionsCurrentExecution = SimulationOptionsForBinding.GetCopy();
            session = new SimulationSession(SimulationOptionsCurrentExecution);

            MainChart.StartDrawData(simulationResultsDictionary);

            threads = null;
            if (!SimulationOptionsCurrentExecution.RemoteExecutionOnly)
            {
                threads = new Thread[threadSlots];
                for (int i = 0; i < threads.Length; i++)
                {
                    threads[i]      = new Thread(this.performWork);
                    threads[i].Name = "Local Thread " + localThreadNumber++;
                    threads[i].Start();
                }
            }

            foreach (TCPSimulatorProxy proxy in TCPConnections)
            {
                if (proxy.Connected)
                {
                    proxy.startNewSession(session);
                }
            }

            btnSimulate.IsEnabled = false;
            btnAbort.IsEnabled    = true;
        }
示例#2
0
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            SimulationSession simulationSession;

            try
            {
                var persistedSimulation = _citySaveStateController
                                          .LoadFile(WebCityFileName);
                simulationSession =
                    new SimulationSession(new SimulationOptions(persistedSimulation,
                                                                new ProcessOptions(() => false, () => false)));
            }
            catch (Exception ex)
            {
                Logger.Instance.LogException(ex, $"Loading file: '{new FileInfo(WebCityFileName).FullName}'", 100);

                simulationSession = new SimulationSession(
                    new SimulationOptions(new Func <TerraformingOptions>(() =>
                {
                    var t             = new TerraformingOptions();
                    t.HorizontalRiver = t.VerticalRiver = true;
                    t.SetWoodlands(80);
                    t.SetLakes(30);
                    t.SetZoneWidthAndHeight(120);
                    return(t);
                })(), new ProcessOptions(() => false, () => false)));
            }
            simulationSession.StartSimulation();
            _gameServer = new GameServer(simulationSession, "http://+:80/", true);
            _gameServer.StartServer();
            return(Task.CompletedTask);
        }
示例#3
0
 public void Start()
 {
     lock (_locker)
     {
         _graphicsManager.StartRendering();
         SimulationSession.StartSimulation();
     }
 }
示例#4
0
 public void Stop()
 {
     lock (_locker)
     {
         Stopping?.Invoke(this, new EventArgs());
         SimulationSession.Dispose();
         _graphicsManager.Dispose();
     }
 }
示例#5
0
    private void SendSimulationDataToServer()
    {
        SimulationAttempt attempt = SimulationAttempt.GetInstance();
        SimulationSession session = SimulationSession.Current;

        session.AddAttemptData(attempt);
        RequestPostBody requestData = RequestPostBody.CreateFromSessionAndAttempt(session, attempt);

        HttpService.SendPostRequest(requestData, serverURL);
    }
示例#6
0
        public static void Main()
        {
            Logger.Instance.OnLogMessage += Instance_OnLogMessage;

            HostFactory.Run(x =>
            {
                var citySaveStateController = new CitySaveStateController(z => { });

                SimulationSession simulationSession;

                try
                {
                    var persistedSimulation = citySaveStateController
                                              .LoadFile(WebCityFileName);
                    simulationSession =
                        new SimulationSession(new SimulationOptions(persistedSimulation,
                                                                    new ProcessOptions(() => false, () => false)));
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogException(ex, $"Loading file: '{new FileInfo(WebCityFileName).FullName}'", 100);

                    simulationSession = new SimulationSession(
                        new SimulationOptions(new Func <TerraformingOptions>(() =>
                    {
                        var t             = new TerraformingOptions();
                        t.HorizontalRiver = t.VerticalRiver = true;
                        t.SetWoodlands(80);
                        t.SetLakes(30);
                        t.SetZoneWidthAndHeight(120);
                        return(t);
                    })(), new ProcessOptions(() => false, () => false)));
                }

                x.Service <GameServer>(s =>
                {
                    s.ConstructUsing(name => new GameServer(simulationSession, "http://+:80/", true));
                    s.WhenStarted(tc =>
                    {
                        tc.StartServer();
                        simulationSession.StartSimulation();
                    });
                    s.WhenStopped(tc =>
                    {
                        citySaveStateController.SaveFile(WebCityFileName, tc.SimulationSession.GeneratePersistedArea());
                        tc.Dispose();
                    });
                });
                x.RunAsLocalSystem();

                x.SetDescription("Hosts the Urbanization web server on TCP Port 80 on all network devices. (For more information, see: https://github.com/Miragecoder/Urbanization)");
                x.SetDisplayName("Urbanization Web Server");
                x.SetServiceName("Urbanization");
            });
        }
示例#7
0
    public static RequestPostBody CreateFromSessionAndAttempt(SimulationSession session, SimulationAttempt attempt)
    {
        RequestPostBody body = new RequestPostBody();

        body.nombreDeOperador       = session.operatorName;
        body.modoDeSimulacion       = session.simulationMode.ToString();
        body.intentos               = session.totalAttempts;
        body.simulacionCompletada   = attempt.simulationComplete;
        body.actividadesCompletadas = ConvertTasksToStringArray(attempt.checklist.GetCompletedTasks());
        body.errores       = attempt.errors.ToArray();
        body.erroresTotal  = session.totalErrors;
        body.segundos      = attempt.GetTime();
        body.segundosTotal = session.totalSeconds;
        return(body);
    }
 private Task <SimulationResponse> SendMessage(string message, SimulationSession session)
 {
     return(_api.Skills.Simulate(_locale.SkillID, _locale.Stage.Stage.Value, new SimulationRequest
     {
         Device = new SimulationRequestDevice
         {
             Locale = _locale.Locale
         },
         Input = new SimulationRequestInput
         {
             Content = message
         },
         Session = session
     }));
 }
示例#9
0
        public void startNewSession(SimulationSession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            this.taskRequests = 0;
            this.session      = session;

            try
            {
                networkStream.WriteByte((byte)TrasmissionFlags.NewSession);
                formatter.Serialize(networkStream, session);
                postMessage("New session request sent (session id: " + session.sessionID + ")");
            }
            catch (Exception e)
            {
                postMessage(e.Message);
            }
        }
示例#10
0
        public SimulationRenderHelper(Panel gamePanel, RenderZoneOptions renderZoneOptions, SimulationOptions options)
        {
            if (gamePanel == null)
            {
                throw new ArgumentNullException(nameof(gamePanel));
            }
            gamePanel.Controls.Clear();

            SimulationSession = new SimulationSession(options);

            _zoneSelectionPanel.Width = 160;
            _zoneSelectionPanel.Dock  = DockStyle.Left;

            _viewportPanel.Dock       = DockStyle.Fill;
            _viewportPanel.AutoScroll = true;

            gamePanel.Controls.Add(_viewportPanel);
            gamePanel.Controls.Add(_zoneSelectionPanel);

            _zoneSelectionPanel.BringToFront();
            _viewportPanel.BringToFront();

            if (renderZoneOptions == null)
            {
                throw new ArgumentNullException(nameof(renderZoneOptions));
            }

            _canvasPanel = new Panel
            {
                BackColor = EmptyZoneConsumption.DefaultColor,
                Size      = _tilesetAccessor.GetAreaSize(SimulationSession.Area),
                Dock      = DockStyle.None
            };

            _viewportPanel.Controls.Add(_canvasPanel);

            _zoneSelectionPanelBehaviour = new ZoneSelectionPanelCreator(
                area: SimulationSession.Area,
                targetPanel: _zoneSelectionPanel
                );

            MouseEventHandler eventHandler = (sender, e) =>
            {
                var point = _canvasPanel.PointToClient(Cursor.Position);
                var zone  = GetZoneStateFor(point);

                var zoneConsumption = (e.Button == MouseButtons.Right)
                    ? new EmptyZoneConsumption()
                    : _zoneSelectionPanelBehaviour.CreateNewCurrentZoneConsumption();

                var result = SimulationSession.ConsumeZoneAt(zone, zoneConsumption);
                if (result == null)
                {
                    throw new InvalidOperationException();
                }
            };

            _canvasPanel.MouseDown += eventHandler;
            _canvasPanel.MouseMove += (sender, e) =>
            {
                if (e.Button != MouseButtons.None && _zoneSelectionPanelBehaviour.IsCurrentlyNetworkZoning)
                {
                    eventHandler(sender, e);
                }
            };

            _zoneRenderInfos = SimulationSession.Area
                               .EnumerateZoneInfos()
                               .ToDictionary(x => x,
                                             zoneRenderInfo =>
                                             new ZoneRenderInfo(
                                                 zoneInfo: zoneRenderInfo,
                                                 createRectangle: zonePoint => new Rectangle(
                                                     x: zonePoint.Point.X * _tilesetAccessor.TileWidthAndSizeInPixels,
                                                     y: zonePoint.Point.Y * _tilesetAccessor.TileWidthAndSizeInPixels,
                                                     width: _tilesetAccessor.TileWidthAndSizeInPixels,
                                                     height: _tilesetAccessor.TileWidthAndSizeInPixels
                                                     ),
                                                 tilesetAccessor: _tilesetAccessor,
                                                 renderZoneOptions: renderZoneOptions
                                                 ));

            _graphicsManager = CreateGraphicsManagerWrapperWithFactory(renderZoneOptions.SelectedGraphicsManager.Factory);
        }
示例#11
0
        public void handleConnection()
        {
            tcpClient     = tcpListener.AcceptTcpClient();
            networkStream = tcpClient.GetStream();

            // initialization
            header = networkStream.ReadByte();
            if (header != (byte)TrasmissionFlags.ClientName)
            {
                Console.WriteLine("Client does not respect protocol.");
                networkStream.Close();
                tcpClient.Close();
                return;
            }

            try
            {
                clientName = (string)formatter.Deserialize(networkStream);
                Console.WriteLine("Connected to " + clientName + " on port " + port);
            }
            catch
            {
                Console.WriteLine("Client does not respect protocol.");
                networkStream.Close();
                tcpClient.Close();
                return;
            }

            // main message loop
            try
            {
                while (!requestClose)
                {
                    header = networkStream.ReadByte();
                    if (header == -1)
                    {
                        break;
                    }
                    switch (header)
                    {
                    case (byte)TrasmissionFlags.NewSession:
                        this.simulationSession = (SimulationSession)formatter.Deserialize(networkStream);
                        Console.WriteLine("Starting new session with " + clientName + " (session id: " + this.simulationSession.sessionID + ")");
                        for (int i = 0; i < numberOfWorkerThreads; i++)
                        {
                            workerThreads[i].abortCurrentTask();
                            sendTaskRequest();
                        }
                        lock (taskBuffer)     // cleanse taskBuffer of older parasite tasks
                        {
                            int taskBufferCount = taskBuffer.Count;
                            for (int i = 0; i < taskBufferCount; i++)
                            {
                                TaskPackage t = taskBuffer.Dequeue();
                                if (t.sessionID == this.simulationSession.sessionID)
                                {
                                    taskBuffer.Enqueue(t);
                                }
                            }
                        }
                        break;

                    case (byte)TrasmissionFlags.Task:
                        TaskPackage taskPackage = (TaskPackage)formatter.Deserialize(networkStream);
                        if (this.simulationSession != null && taskPackage.sessionID == this.simulationSession.sessionID)
                        {
                            lock (taskBuffer)
                            {
                                taskBuffer.Enqueue(taskPackage);
                            }
                            for (int i = 0; i < numberOfWorkerThreads; i++)
                            {
                                workerThreads[i].awake();
                            }
                            Console.WriteLine("TaskPackage received from " + clientName);
                        }
                        else
                        {
                            Console.WriteLine("TaskPackage received from " + clientName + ", but belonging to a closed session.");
                        }
                        break;

                    case (byte)TrasmissionFlags.AbortSession:
                        uint sessionIdAborted = (uint)formatter.Deserialize(networkStream);
                        if (this.simulationSession != null && sessionIdAborted == this.simulationSession.sessionID)
                        {
                            for (int i = 0; i < numberOfWorkerThreads; i++)
                            {
                                if (workerThreads[i] != null)
                                {
                                    workerThreads[i].abortCurrentTask();
                                }
                            }
                            Console.WriteLine("Session " + sessionIdAborted + " aborted.");
                        }
                        else
                        {
                            Console.WriteLine("Session abort message received (" + sessionIdAborted + ") but not for the current session. ");
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Connection to " + clientName + " terminated");

            networkStream.Close();
            tcpClient.Close();
        }