Exemplo n.º 1
0
        public override void Tick()
        {
            var openCount = Floors.Count(r => !r.IsFull);

            if (openCount > 0)
            {
                var gateCapacity = (int)(Simulator.Interval.TotalSeconds / 10.0);
                for (int i = 0; i < gateCapacity; i++)
                {
                    var floorsWithRoom = Floors.Where(r => !r.IsFull).ToList();
                    if (InQueue.Count > 0 && floorsWithRoom.Count > 0)
                    {
                        var floor = Simulator.Random.Next(floorsWithRoom.Count);
                        floorsWithRoom[floor].InQueue.Enqueue(InQueue.Dequeue());
                    }
                }
            }
            foreach (var item in Floors)
            {
                item.Tick();
            }
            base.Tick();
            while (OutQueue.Count > 0)
            {
                Parent.OutQueue.Enqueue(OutQueue.Dequeue());
            }
        }
        public override void Tick()
        {
            var openCount = ParkingLocations.Count(r => !r.IsFull);

            if (openCount > 0)
            {
                while (InQueue.Count > 0)
                {
                    var location = FindOpenLocation();
                    if (location != null)
                    {
                        location.ParkAuto(InQueue.Dequeue());
                    }
                    else
                    {
                        break;
                    }
                }
            }

            var departing = ParkingLocations.Where(r => r.Occupant != null && r.Occupant.DateToDepart <= Simulator.Clock.Now);

            foreach (var item in departing)
            {
                AutoExitingFrom(item);
            }
            base.Tick();
            while (OutQueue.Count > 0)
            {
                Parent.OutQueue.Enqueue(OutQueue.Dequeue());
            }
        }
Exemplo n.º 3
0
 public override void Tick()
 {
     if (!IsFull)
     {
         var gateCapacity = (int)(Simulator.Interval.TotalSeconds / 60.0 * 5);
         for (int i = 0; i < gateCapacity; i++)
         {
             if (InQueue.Count > 0 && !IsFull)
             {
                 var ramp = GetOpenRamp();
                 if (ramp != null)
                 {
                     ramp.InQueue.Enqueue(InQueue.Dequeue());
                 }
                 else
                 {
                     break;
                 }
             }
         }
     }
     foreach (var item in ParkingRamps)
     {
         item.Tick();
     }
     base.Tick();
     while (OutQueue.Count > 0)
     {
         var auto = OutQueue.Dequeue();
         Simulator.Notifier.Notify(new AutoDepartingFacility {
             Auto = auto
         });
     }
 }
Exemplo n.º 4
0
        public override void ResetDirtyFlag()
        {
            lock (dirtyLock)
            {
                Resources.ResetDirtyFlag();
                Serfs.ResetDirtyFlag();
                OutQueue.ResetDirtyFlag();

                ResetDirtyFlagUnlocked();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Writes the packet now and flushes the packet queue.
        /// </summary>
        /// <param name="packetDisconnectPlayer">The packet disconnect player.</param>
        internal void WritePacketNowAndFlush(Packet packet)
        {
            if (OutQueue != null)
            {
                OutQueue.Clear();
            }

            if (PacketWriter != null)
            {
                PacketWriter.WritePacket(packet);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Writes the packet.
        /// </summary>
        /// <param name="packet">The packet.</param>
        public void WritePacket(Packet packet)
        {
            if (startThread != Thread.CurrentThread)
            {
                throw new IOException("You can only send packet on thread that created packet queue");
            }

            if (OutQueue != null)
            {
                OutQueue.Enqueue(packet);
            }
        }
Exemplo n.º 7
0
 private void _filter(Func <TI, TO> action)
 {
     while (producer.IsRunningOrNotEmpty)
     {
         if (producer.TryDequeue(out var t))
         {
             if (t.Equals(default(TI)))
             {
                 continue;
             }
             var o = action(t);
             if (o.Equals(default(TO)))
             {
                 continue;
             }
             OutQueue.Enqueue(o);
         }
     }
 }
Exemplo n.º 8
0
 protected void SendMessageLoop()
 {
     try
     {
         while ((_clientSocket.Connected))
         {
             string outboundMessage;
             while (OutQueue.TryDequeue(out outboundMessage))
             {
                 SendMessage(outboundMessage);
             }
             Thread.Sleep(10);
         }
     }
     catch (Exception ex)
     {
         InQueue.Enqueue(" >> " + ex.ToString());
     }
 }
Exemplo n.º 9
0
        internal void Enqueue(T msg)
        {
            if (msg == null)
            {
                return;
            }

            try
            {
                if (OutQueueLocked)
                {
                    WaitForQueueToOpen();
                }

                if (OutQueueLocked)
                {
                    ExceptionRecorder.RecordException("Output queue lock could not be opened 2. Count = " + OutQueue.Count + ". Failing to send command: " + msg);
                    return;
                }

                OutQueueLocked = true;
                lock (OutQueueLock)
                {
                    OutQueue.Enqueue(msg);
                    if (outQueue.Count > capacity)
                    {
                        InformCapacityLimitReached();
                        outQueue.Dequeue();
                    }
                }
            }
            catch (Exception ex)
            {
                var s = string.Format(CultureInfo.InvariantCulture, "{0}{1}", "Exception while sending message: ", ex.Message);
                ExceptionRecorder.RecordException(s);
            }
            finally
            {
                OutQueueLocked = false;
            }
        }
Exemplo n.º 10
0
        void WritePackets()
        {
            try {
                while (Running)
                {
                    Packet packet = null;
                    lock (WriteLock)
                        packet = OutQueue.Dequeue();

                    if (packet != null)
                    {
                        PacketWriter.WritePacket(packet);
                    }
                }
            }
            catch {
                CloseConnection();
            }

            CloseConnection();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Closes the connection.
        /// </summary>
        public void CloseConnection()
        {
            Stop();

            try {
                if (PacketReader != null)
                {
                    PacketReader.Close();
                    PacketReader.Dispose();
                    PacketReader = null;
                }
            }
            catch (ObjectDisposedException) { }
            catch (IOException) { }

            try {
                if (PacketWriter != null)
                {
                    PacketWriter.Close();
                    PacketWriter.Dispose();
                    PacketWriter = null;
                }
            }
            catch (ObjectDisposedException) { }
            catch (IOException) { }

            if (InQueue != null)
            {
                InQueue.Clear();
                InQueue = null;
            }

            if (OutQueue != null)
            {
                OutQueue.Clear();
                OutQueue = null;
            }
        }
        public void createBomb(PlayerID _id)
        {
            Player      player   = PlayerManager.getPlayer(_id);
            OutputQueue outqueue = new OutputQueue();

            player.removeBombSprite();

            Ship pShip     = player.playerShip;
            Body pShipBody = pShip.physicsObj.body;

            Bomb bomb;

            if (_id == PlayerID.one)
            {
                bomb = new Bomb(GameObjType.p1Bomb, _id, pShip);
            }
            else
            {
                bomb = new Bomb(GameObjType.p2Bomb, _id, pShip);
            }

            OutQueue.add(QueueType.bomb, bomb, _id);
        }
Exemplo n.º 13
0
        private void MessageHandlerLoop()
        {
            bool     continueToLoop = true;
            DateTime lastMessage    = DateTime.Now;

            try
            {
                while (continueToLoop && _clientSocket.Connected)
                {
                    //Need to make the thread sleep
                    Thread.Sleep(10);

                    IPlayerCharacter pc = null;

                    TimeOutIdleConnection(lastMessage, pc);

                    #region Get Message From Client
                    //Handle message from client
                    try
                    {
                        if (InQueue.TryDequeue(out string messageFromClient))
                        {
                            IPAddress address = ((IPEndPoint)_clientSocket.Client.RemoteEndPoint).Address;

                            switch (_loginState)
                            {
                            case LoginState.UserName:

                                if (ConnectionAccessManager.CanLogin(address))
                                {
                                    _userName   = messageFromClient;
                                    _loginState = LoginState.Password;
                                    OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("What is your password?"));
                                    ConnectionAccessManager.FlushOldFailedAttempts();
                                }
                                else
                                {
                                    OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("IP temporarily/permanently banned."));
                                }
                                break;

                            case LoginState.Password:
                                _password = messageFromClient;

                                pc = GlobalReference.GlobalValues.World.LoadCharacter(_userName);
                                if (pc == null)
                                {
                                    GlobalReference.GlobalValues.Logger.Log(LogLevel.ALL, string.Format("{0} is an unknown user, offered to make a new one.", _userName, _password));
                                    _loginState = LoginState.CreateCharacter;
                                    OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Character not found.  Would you like to create the character?"));
                                }
                                else
                                {
                                    if (pc.Password == _password)
                                    {
                                        //clear out the exp and money message from loading
                                        while (pc.DequeueMessage() != null)
                                        {
                                        }

                                        GlobalReference.GlobalValues.Logger.Log(LogLevel.ALL, string.Format("{0} logged in successfully.", _userName));
                                        GlobalReference.GlobalValues.World.AddPlayerQueue.Enqueue(pc);
                                        RemoveOldConnectionsToSamePc(pc);
                                        GuidToCharacter.AddOrUpdate(_guid, pc, (k, v) => v = pc);
                                        _loginState = LoginState.LoggedIn;
                                    }
                                    else
                                    {
                                        ConnectionAccessManager.AddFailedLogin(address);
                                        GlobalReference.GlobalValues.Logger.Log(LogLevel.ALL, $"{_userName} failed to log in with password {_password} from address {address}.");
                                        _loginState = LoginState.AsciiArt;
                                        OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Invalid username/password."));
                                    }
                                }
                                break;

                            case LoginState.LoggedIn:
                                //player character should be loaded
                                GuidToCharacter.TryGetValue(_guid, out pc);
                                if (pc != null)
                                {
                                    //don't accept commands from possessed mobs
                                    if (pc.PossingMob == null)
                                    {
                                        pc.EnqueueCommand(messageFromClient);
                                        //if (messageFromClient.ToUpper() == "LOGOUT")
                                        //{
                                        //    continueToLoop = false;
                                        //}
                                    }
                                    else if (pc.AttributesCurrent.Contains(MobileAttribute.Frozen))     //don't allow frozen players to play
                                    {
                                        pc.EnqueueMessage("You are frozen and can not do anything until you thaw.");
                                    }
                                }
                                //not sure why we could not find the player character.  Relogin.
                                else
                                {
                                    _loginState = LoginState.AsciiArt;
                                }
                                break;

                            case LoginState.CreateCharacter:
                                if (messageFromClient.Substring(0, 1).ToUpper() == "Y")
                                {
                                    pc = GlobalReference.GlobalValues.World.CreateCharacter(_userName, _password);
                                    GuidToCharacter.AddOrUpdate(_guid, pc, (k, v) => v = pc);
                                    _loginState = LoginState.LoggedIn;
                                }
                                else if (messageFromClient.Substring(0, 1).ToUpper() == "N")
                                {
                                    _loginState = LoginState.AsciiArt;
                                }
                                else
                                {
                                    OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Character not found.  Would you like to create the character? Yes/No"));
                                }
                                break;
                            }

                            lastMessage = DateTime.Now;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.InnerException != null && ex.InnerException.Message != "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond")
                        {
                            throw;
                        }
                    }
                    #endregion Get Message From Client

                    #region Send Message To Client
                    switch (_loginState)
                    {
                    case LoginState.AsciiArt:
                        OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag(GlobalReference.GlobalValues.Settings.AsciiArt, TagType.AsciiArt));

                        OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Welcome adventurer. What is your name?"));
                        _loginState = LoginState.UserName;
                        break;
                    }


                    if (_guid != null)
                    {
                        pc = null;
                        GuidToCharacter.TryGetValue(_guid, out pc);
                        if (pc != null)
                        {
                            string messageToClient = pc.DequeueMessage();
                            if (messageToClient != null)
                            {
                                OutQueue.Enqueue(messageToClient);
                            }
                        }
                    }
                    #endregion Send Mesage To Client
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> " + ex.ToString());
            }
        }
Exemplo n.º 14
0
        void ServerThread()
        {
            string pipename;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                pipename = "tmp-app.eoncore";
            }
            else
            {
                pipename = "/tmp/app.eoncore";
            }

            while (true)
            {
                using (var pipe = new NamedPipeServerStream(pipename, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough))
                {
                    pipe.WaitForConnection();
#if DEBUG
                    Console.WriteLine("Client connected.");
#endif
                    var wctks  = new CancellationTokenSource();
                    var wtoken = wctks.Token;
                    try
                    {
                        Task.Run(() =>
                        {
                            while (!wtoken.IsCancellationRequested)
                            {
                                try
                                {
                                    var obj = OutQueue.Take(wtoken);
                                    if (obj == null)
                                    {
                                        break;
                                    }
                                    var wmsg = JsonConvert.SerializeObject(obj);
                                    pipe.Write(Encoding.UTF8.GetBytes(wmsg + "\f"));
#if DEBUG
                                    Console.WriteLine("[SENT] " + wmsg);
#endif
                                }
                                catch (JsonException json)
                                {
#if DEBUG
                                    Console.WriteLine("ERROR: {0}", json.Message);
#endif
                                }
                                catch (Exception e) when(e is IOException || e is OperationCanceledException)
                                {
                                    break;
                                }
                                catch (Exception e)
                                {
#if DEBUG
                                    Console.WriteLine("ERROR: {0}", e.Message);
#endif
                                    break;
                                }
                            }
                        }, wtoken);

                        ClientConnected?.Invoke(null, EventArgs.Empty);

                        var inBuffer = new byte[1024].AsSpan();
                        while (true)
                        {
                            var read = pipe.Read(inBuffer);
                            if (read < 1)
                            {
                                break;
                            }
                            var msg = Encoding.UTF8.GetString(inBuffer.Slice(0, read));
#if DEBUG
                            Console.WriteLine("[RECEIVED] " + msg);
#endif
                            try
                            {
                                InQueue.Add(JsonConvert.DeserializeObject <Message>(msg));
                            }
                            catch (JsonException json)
                            {
#if DEBUG
                                Console.WriteLine("[ERROR] " + json);
#endif
                            }
                        }
                    }
                    catch (IOException)
                    {
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: {0}", e.Message);
                    }
                    finally
                    {
                        wctks.Cancel();
                    }
#if DEBUG
                    Console.WriteLine("Client disconnected.");
#endif
                }
            }
        }
        public void AutoExitingFrom(ParkingLocation location)
        {
            var auto = location.AutoDeparts();

            OutQueue.Enqueue(auto);
        }
Exemplo n.º 16
0
 internal T Dequeue()
 {
     return(OutQueue.Dequeue());
 }
Exemplo n.º 17
0
        private void MessageHandlerLoop()
        {
            bool     continueToLoop = true;
            DateTime lastMessage    = DateTime.Now;

            try
            {
                while (continueToLoop && _clientSocket.Connected)
                {
                    //Need to make the thread sleep
                    Thread.Sleep(10);

                    IPlayerCharacter pc = null;

                    TimeOutIdleConnection(lastMessage, pc);

                    #region Get Message From Client
                    //Handle message from client
                    try
                    {
                        string messageFromClient;
                        if (InQueue.TryDequeue(out messageFromClient))
                        {
                            switch (_loginState)
                            {
                            case LoginState.UserName:
                                _userName   = messageFromClient;
                                _loginState = LoginState.Password;
                                OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("What is your password."));

                                break;

                            case LoginState.Password:
                                _password = messageFromClient;

                                pc = GlobalReference.GlobalValues.World.LoadCharacter(_userName);
                                if (pc == null)
                                {
                                    GlobalReference.GlobalValues.Logger.Log(LogLevel.ALL, string.Format("{0} is an unknown user, offered to make a new one.", _userName, _password));
                                    _loginState = LoginState.CreateCharacter;
                                    OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Character not found.  Would you like to create the character?"));
                                }
                                else
                                {
                                    if (pc.Password == _password)
                                    {
                                        GlobalReference.GlobalValues.Logger.Log(LogLevel.ALL, string.Format("{0} logged in successfully.", _userName));
                                        GlobalReference.GlobalValues.World.AddPlayerQueue.Enqueue(pc);
                                        GuidToCharacter.AddOrUpdate(_guid, pc, (k, v) => v = pc);
                                        _loginState = LoginState.LoggedIn;
                                    }
                                    else
                                    {
                                        GlobalReference.GlobalValues.Logger.Log(LogLevel.ALL, string.Format("{0} failed to log in with password {1}.", _userName, _password));
                                        _loginState = LoginState.AsciiArt;
                                        OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Invalid username/password."));
                                    }
                                }
                                break;

                            case LoginState.LoggedIn:
                                //player character should be loaded
                                GuidToCharacter.TryGetValue(_guid, out pc);
                                if (pc != null)
                                {
                                    pc.EnqueueCommand(messageFromClient);
                                    if (messageFromClient.ToUpper() == "LOGOUT")
                                    {
                                        continueToLoop = false;
                                    }
                                }
                                //not sure why we could not find the player character.  Relogin.
                                else
                                {
                                    _loginState = LoginState.AsciiArt;
                                }
                                break;

                            case LoginState.CreateCharacter:
                                if (messageFromClient.Substring(0, 1).ToUpper() == "Y")
                                {
                                    pc = GlobalReference.GlobalValues.World.CreateCharacter(_userName, _password);
                                    GuidToCharacter.AddOrUpdate(_guid, pc, (k, v) => v = pc);
                                    _loginState = LoginState.LoggedIn;
                                }
                                else if (messageFromClient.Substring(0, 1).ToUpper() == "N")
                                {
                                    _loginState = LoginState.AsciiArt;
                                }
                                else
                                {
                                    OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Character not found.  Would you like to create the character? Yes/No"));
                                }
                                break;
                            }

                            lastMessage = DateTime.Now;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.InnerException != null && ex.InnerException.Message != "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond")
                        {
                            throw;
                        }
                    }
                    #endregion Get Message From Client

                    #region Send Message To Client
                    switch (_loginState)
                    {
                    case LoginState.AsciiArt:
                        OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag(GlobalReference.GlobalValues.Settings.AsciiArt, TagType.AsciiArt));

                        OutQueue.Enqueue(GlobalReference.GlobalValues.TagWrapper.WrapInTag("Welcome adventure. What is your name?"));
                        _loginState = LoginState.UserName;
                        break;
                    }


                    if (_guid != null)
                    {
                        pc = null;
                        GuidToCharacter.TryGetValue(_guid, out pc);
                        if (pc != null)
                        {
                            string messageToClient = pc.DequeueMessage();
                            if (messageToClient != null)
                            {
                                OutQueue.Enqueue(messageToClient);
                            }
                        }
                    }
                    #endregion Send Mesage To Client
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> " + ex.ToString());
            }
        }
Exemplo n.º 18
0
        public void createMissile()
        {
            OutputQueue p = new OutputQueue();

            Ship pShip     = playerShip;
            Body pShipBody = pShip.physicsObj.body;

            Sprite       missileSprite = (Sprite)DisplayManager.Instance().getDisplayObj(SpriteEnum.Missile);
            Sprite_Proxy proxyMissile  = new Sprite_Proxy(missileSprite, (int)pShip.spriteRef.pos.X, (int)pShip.spriteRef.pos.Y, 0.5f, pShip.spriteRef.color);
            Missile      missile       = new Missile(missileType, proxyMissile, id);

            SBNode missileBatch = SpriteBatchManager.Instance().getBatch(batchEnum.missiles);

            missileBatch.addDisplayObject(proxyMissile);

            World world = Game1.GameInstance.getWorld();

            var missileShape = new PolygonShape();

            missileShape.SetAsBox(3, 3);

            var fd = new FixtureDef();

            fd.shape       = missileShape;
            fd.restitution = 0.0f;
            fd.friction    = 0.0f;
            fd.density     = 0.0001f;
            fd.userData    = missile;

            // Grab ship orientation vector
            Vector2 direction = new Vector2((float)(Math.Cos(pShipBody.GetAngle())), (float)(Math.Sin(pShipBody.GetAngle())));

            direction.Normalize();

            BodyDef bd = new BodyDef();

            bd.fixedRotation = true;

            bd.type     = BodyType.Dynamic;
            bd.position = (new Vector2(pShip.spriteRef.pos.X, pShip.spriteRef.pos.Y)) + (direction * 10);



            var body = world.CreateBody(bd);

            body.SetBullet(true);
            body.Rotation = pShipBody.Rotation;
            body.CreateFixture(fd);
            body.SetUserData(missile);


            direction *= 1000;

            body.ApplyLinearImpulse(direction, body.GetWorldCenter());



            GameObjManager.Instance().addGameObj(missile);
            PhysicsMan.Instance().addPhysicsObj(missile, body);

            OutQueue.add(QueueType.missile, missile, this.id);
            //p.pushToNetwork();

            if (numMissiles > 0)
            {
                numMissiles--;
            }
        }