A client which can initiate and accept multiple connections
Inheritance: Lidgren.Network.NetServer
Exemplo n.º 1
0
		/// <summary>
		/// 16 byte key
		/// </summary>
		public NetXtea(NetPeer peer, byte[] key, int rounds)
			: base(peer)
		{
			if (key.Length < c_keySize)
				throw new NetException("Key too short!");

			m_numRounds = rounds;
			m_sum0 = new uint[m_numRounds];
			m_sum1 = new uint[m_numRounds];
			uint[] tmp = new uint[8];

			int num2;
			int index = num2 = 0;
			while (index < 4)
			{
				tmp[index] = BitConverter.ToUInt32(key, num2);
				index++;
				num2 += 4;
			}
			for (index = num2 = 0; index < 32; index++)
			{
				m_sum0[index] = ((uint)num2) + tmp[num2 & 3];
				num2 += -1640531527;
				m_sum1[index] = ((uint)num2) + tmp[(num2 >> 11) & 3];
			}
		}
Exemplo n.º 2
0
		public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo)
			: base(peer)
		{
			m_algorithm = algo;
			m_algorithm.GenerateKey();
			m_algorithm.GenerateIV();
		}
Exemplo n.º 3
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			s_mainForm = new Form1();

			WriteToConsole("Type 'connect <host> <port>' to connect to another peer, or 'connect <port>' to connect to another localhost peer");

			NetConfiguration config = new NetConfiguration("p2pchat");
			config.MaxConnections = 256;
			s_peer = new NetPeer(config);
			//s_peer.VerboseLog = true;

			s_peer.SetMessageTypeEnabled(NetMessageType.ConnectionRejected | NetMessageType.BadMessageReceived | NetMessageType.VerboseDebugMessage, true);

			// start listening for incoming connections
			s_peer.Start();

			// create a buffer to read data into
			s_readBuffer = s_peer.CreateBuffer();

			Application.Idle += new EventHandler(OnAppIdle);
			Application.Run(s_mainForm);

			s_peer.Shutdown("Application exiting");
		}
Exemplo n.º 4
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="manager">Local NetPeer</param>
        /// <param name="con">NetConnection</param>
        /// <param name="key">Encryption key</param>
        /// <param name="nodeId">Node Id</param>
        public Connection(NetPeer manager, NetConnection con, INetEncryption encryption, String nodeId)
        {
            // This keep alive timer is used to overcome BAD connections that drop ping/pong messages a lot.
            // It simply sends an empty message every five seconds. As long as some messages are retained
            // and received on the connection, all will be well
            _keepAliveTimer = new System.Timers.Timer(5000);
            _keepAliveTimer.Elapsed += new ElapsedEventHandler((Object state, ElapsedEventArgs args) =>
                this.SendMessage(this.NetManager.CreateMessage(0), NetDeliveryMethod.Unreliable));

            this.Username = (con.Tag as Handshake).Username;
            this.NetManager = manager;
            this.NetConnection = con;
            this.NetConnection.Tag = this;
            this.NodeId = nodeId;

            if (encryption != null)
            {
                _netEncryption = encryption;
            }
            else
            {
                // You could write code that makes it possible to transfer users between server
                // where you don't have any encryption key YET. The place to start that would
                // be here.
                this.IsTransfering = true;
                _netEncryption = new NetXtea(new Byte[16]);
            }

            // Not connected until everything is done.
            System.Threading.Thread.MemoryBarrier();

            _connected = true;
            _keepAliveTimer.Start();
        }
Exemplo n.º 5
0
 /// <summary>
 /// Creates and starts a new NetworkPeer object, for servers.
 /// </summary>
 /// <param name="port">The port the server should listen on.</param>
 /// <param name="protocols">An array of messaging protocols.</param>
 public NetworkPeer(int port, params Protocol[] protocols)
 {
     Protocols = new List<Protocol>(protocols);
     netPeer = new NetPeer(new NetPeerConfiguration("N/A").GetStandardConfiguration(port));
     netPeer.RegisterReceivedCallback(OnMessageReceivedCallback);
     Start();
 }
Exemplo n.º 6
0
 public static void ShellCallback(MessageBase msg, NetPeer peer, NetBuffer buff)
 {
     if(CallbackMapping.ContainsKey(msg.Id))
     {
         CallbackMapping[msg.Id](peer, buff, msg);
     }
 }
Exemplo n.º 7
0
        public Peer(NetPeer peer)
        {
            this.peer = peer;

            //start the client
            peer.Start();
        }
Exemplo n.º 8
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="manager">Local NetPeer</param>
 /// <param name="con">NetConnection</param>
 /// <param name="key">Encryption key</param>
 /// <param name="nodeId">Node Id</param>
 public Connection(NetPeer manager, NetConnection con, INetEncryption encryption, String nodeId)
 {
     NetManager = manager;
     NetConnection = con;
     _connected = true;
     _netEncryption = encryption;
     NetConnection.Tag = this;
     NodeId = nodeId;
 }
Exemplo n.º 9
0
 internal NetOutgoingMessage ToOutgoing(NetPeer Sender)
 {
     NetOutgoingMessage msg = Sender.CreateMessage("__msg");
     StringBuilder sb = new StringBuilder();
     StringWriter writer = new StringWriter(sb);
     serializer.Serialize(writer, this);
     msg.Write(sb.ToString());
     return msg;
 }
Exemplo n.º 10
0
        public Program()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("masterserver");
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = API.MasterServer.MasterServerPort;

            peer = new NetPeer(config);
            peer.Start();
        }
Exemplo n.º 11
0
        public void OnLoginMessage(NetPeer server, NetBuffer buff, MessageBase msg)
        {
            var srv = server as NetServer;
            var im = buff as NetIncomingMessage;

            if (srv != null && im != null)
            {
                LoginMessageImpl(srv, im, msg);
            }
        }
Exemplo n.º 12
0
        public void OnLoginMessage(NetPeer client, NetBuffer buff, MessageBase msg)
        {
            var srv = client as NetClient;
            var im = buff as NetIncomingMessage;

            if (srv != null && im != null)
            {
                LoginResultMessageImpl(srv, im, msg);
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("unittests");
            config.EnableUPnP = true;
            NetPeer peer = new NetPeer(config);
            peer.Start(); // needed for initialization

            Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier));

            ReadWriteTests.Run(peer);

            NetQueueTests.Run();

            MiscTests.Run(peer);

            BitVectorTests.Run();

            EncryptionTests.Run(peer);

            var om = peer.CreateMessage();
            peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242));
            try
            {
                peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242));
            }
            catch (NetException nex)
            {
                if (nex.Message != "This message has already been sent! Use NetPeer.SendMessage() to send to multiple recipients efficiently")
                    throw nex;
            }

            peer.Shutdown("bye");

            // read all message
            NetIncomingMessage inc = peer.WaitMessage(5000);
            while (inc != null)
            {
                switch (inc.MessageType)
                {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        Console.WriteLine("Peer message: " + inc.ReadString());
                        break;
                    case NetIncomingMessageType.Error:
                        throw new Exception("Received error message!");
                }

                inc = peer.ReadMessage();
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 14
0
        public void PeerListener(NetPeer peer)
        {
            
            while (true)
            {
                NetIncomingMessage msg;
                while ((msg=peer.ReadMessage())!=null)
                {
                    NetConnection connection = msg.SenderConnection;

                    switch (msg.MessageType)
                    {
                      
                        case NetIncomingMessageType.StatusChanged:
                            switch (msg.SenderConnection.Status)
                            {    
                                case NetConnectionStatus.Connected:
                                    logger.Info("{0}: connected",connection.RemoteEndPoint.Address.ToString());
                                    ExecuteCommand(new CmdInitOk(connection));
                                    break;
                                case NetConnectionStatus.Disconnected:
                                    logger.Info("{0}: disconnected", connection.RemoteEndPoint.Address.ToString());
                                    break;
                                case NetConnectionStatus.Disconnecting:
                                    logger.Info("{0}: disconnecting", connection.RemoteEndPoint.Address.ToString());
                                    break;
                                    
                                                                                                     
                            }
                            break;
                    
                        case NetIncomingMessageType.Data:
                            msg.Decrypt(new NetRC2Encryption(peer, connection.CryptoKey));  
                            string[] OpData = msg.ReadString().Split('&');
                            var OpCode = (LoginOperation)Enum.Parse(typeof(LoginOperation), OpData[0]);

                            switch (OpCode)
                            {                                
                                case LoginOperation.AuthLog:   
                                    string[] authData = OpData[1].Split('#');
                                    string login = authData[0];
                                    string pass = authData[1];
                                    ExecuteCommand(new CmdLoginOkFail(connection, login,pass));
                                    break;
                            }


                            break;                    
                    }

                    peer.Recycle(msg);
                }
            }

        }
Exemplo n.º 15
0
        public void Connect(string ip)
        {
            // Create client with config and tell it to start then connect to the given IP.
            NetClient client = new NetClient(Config);
            client.Start();
            client.Connect(ip, 25000);

            Peer = client;

            Console.WriteLine("Client has started.");
        }
Exemplo n.º 16
0
        public void Host()
        {
            // Create server and tell it to start listening for connections.
            Config.Port = 25000;
            NetServer server = new NetServer(Config);
            server.Start();
            // Assign it to NetPeer so it can be used interchangibly with client.
            Peer = server;

            Console.WriteLine("Server has started.");
        }
Exemplo n.º 17
0
        public void Start()
        {
            peer = new NetPeer(config);
            peer.Start();
            localIdentifier = peer.UniqueIdentifier;

            listener = new peerListener(peer, localIdentifier);
            moveQueue = new Queue<string>();

            NetThread = new Thread(new ThreadStart(listener.processNetwork));
            NetThread.Start();
        }
Exemplo n.º 18
0
        private void button1_Click(object sender, EventArgs e)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MMC");
            config.MaximumConnections = 100;
            config.Port = 3939;
            // Enable DiscoveryResponse messages
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);

            s_server = new NetPeer(config);
            Output("listening on " + config.Port.ToString());
            s_server.Start();
        }
        public NetPeerSettingsWindow(string title, NetPeer peer)
        {
            Peer = peer;
            InitializeComponent();
            RefreshData();
            this.Text = title;

            // auto refresh now and then
            timer = new Timer();
            timer.Interval = 250;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Enabled = true;
        }
        protected override bool HandleMessage(NetPeer peer, NetIncomingMessage msg)
        {
            switch (msg.MessageType)
            {
                case NetIncomingMessageType.DiscoveryResponse:
                {
                    PostNotificationImmediately(NetworkNotifications.LocalServerDiscovered, msg);
                    return true;
                }
            }

            return false;
        }
Exemplo n.º 21
0
 internal NetConnection(NetPeer peer, IPEndPoint remoteEndpoint)
 {
     m_peer = peer;
     m_peerConfiguration = m_peer.Configuration;
     m_status = NetConnectionStatus.None;
     m_visibleStatus = NetConnectionStatus.None;
     m_remoteEndpoint = remoteEndpoint;
     m_sendChannels = new NetSenderChannelBase[NetConstants.NumTotalChannels];
     m_receiveChannels = new NetReceiverChannelBase[NetConstants.NumTotalChannels];
     m_queuedAcks = new NetQueue<NetTuple<NetMessageType, int>>(4);
     m_statistics = new NetConnectionStatistics(this);
     m_averageRoundtripTime = -1.0f;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Gets a <see cref="NetOutgoingMessage"/>.
        /// </summary>
        /// <param name="netPeer">The <see cref="NetPeer"/> instance that the message is to be used on.</param>
        /// <param name="size">The minimum initial size of the <see cref="NetOutgoingMessage"/> in bytes.</param>
        /// <returns>
        /// The <see cref="NetOutgoingMessage"/> instance to use.
        /// </returns>
        public static NetOutgoingMessage GetNetOutgoingMessage(NetPeer netPeer, int size)
        {
            // Round up to the next power-of-2 size (if not already there) to make allocations a bit more consistency-sized
            // and grabbing from the internal pool will hopefully be faster, even if it does mean over-allocating a bit more.
            // Also, never use less than 16 bytes since there is not much point in cluttering things up with tiny buffers.
            if (size < 16)
                size = 16;
            else
                size = BitOps.NextPowerOf2(size);

            // Grab the NetOutgoingMessage from the internal buffer
            return netPeer.CreateMessage(size);
        }
Exemplo n.º 23
0
		public static void Run(NetPeer peer)
		{
			//
			// Test XTEA
			//
			NetXtea xtea = new NetXtea("TopSecret");

			byte[] original = new byte[16];
			NetRandom.Instance.NextBytes(original);

			byte[] encrypted = new byte[original.Length];
			xtea.EncryptBlock(original, 0, encrypted, 0);
			xtea.EncryptBlock(original, 8, encrypted, 8);

			byte[] decrypted = new byte[original.Length];
			xtea.DecryptBlock(encrypted, 0, decrypted, 0);
			xtea.DecryptBlock(encrypted, 8, decrypted, 8);

			// compare!
			for (int i = 0; i < original.Length; i++)
				if (original[i] != decrypted[i])
					throw new NetException("XTEA fail!");

			Console.WriteLine("XTEA OK");

			NetOutgoingMessage om = peer.CreateMessage();
			om.Write("Hallon");
			om.Write(42);
			om.Write(5, 5);
			om.Write(true);
			om.Write("kokos");
			om.Encrypt(xtea);

			// convert to incoming message
			NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits);
			im.Decrypt(xtea);

			if (im.ReadString() != "Hallon")
				throw new NetException("fail");
			if (im.ReadInt32() != 42)
				throw new NetException("fail");
			if (im.ReadInt32(5) != 5)
				throw new NetException("fail");
			if (im.ReadBoolean() != true)
				throw new NetException("fail");
			if (im.ReadString() != "kokos")
				throw new NetException("fail");

			Console.WriteLine("Message encryption OK");
		}
Exemplo n.º 24
0
        /// <summary>
        /// Start local network peer.  
        /// </summary>
        public Network()
        {
            m_netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            m_netPeerConfiguration.Port = APIMain.MasterServerPort;

            m_netPeer = new NetPeer(m_netPeerConfiguration);
            m_netPeer.Start();

            m_updateThread = new Thread(Update);
            m_updateThread.Start();

            m_updateServersListThread = new Thread(UpdateServerList);
            m_updateServersListThread.Start();
        }
Exemplo n.º 25
0
 public NetworkGame(Settings settings, NetPeer peer)
 {
     this.settings = settings;
     this.peer = peer;
     localPlayerField = new Playfield(settings.GameType, new Vector2(780f, 325f), settings.PlayfieldSize);
     remotePlayerField = new RemotePlayfield(settings.GameType, new Vector2(300f, 325f), settings.PlayfieldSize);
     xDiff = localPlayerField.Position.X - remotePlayerField.Position.X;
     backgroundImage = new Image();
     pauseImage = new Image();
     timeText = new Text();
     countdownText = new OutlineText();
     if (peer.ConnectionsCount == 0)
         NewScreen(new NetworkGameSetup(), "No Connection");
     else
         connection = peer.Connections.ToArray()[0];
 }
Exemplo n.º 26
0
		internal NetConnection(NetPeer peer, NetEndPoint remoteEndPoint)
		{
			m_peer = peer;
			m_peerConfiguration = m_peer.Configuration;
			m_status = NetConnectionStatus.None;
			m_outputtedStatus = NetConnectionStatus.None;
			m_visibleStatus = NetConnectionStatus.None;
			m_remoteEndPoint = remoteEndPoint;
			m_sendChannels = new NetSenderChannelBase[NetConstants.NumTotalChannels];
			m_receiveChannels = new NetReceiverChannelBase[NetConstants.NumTotalChannels];
			m_queuedOutgoingAcks = new NetQueue<NetTuple<NetMessageType, int>>(4);
			m_queuedIncomingAcks = new NetQueue<NetTuple<NetMessageType, int>>(4);
			m_statistics = new NetConnectionStatistics(this);
			m_averageRoundtripTime = -1.0f;
			m_currentMTU = m_peerConfiguration.MaximumTransmissionUnit;
		}
Exemplo n.º 27
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MainForm = new Form1();

            NetPeerConfiguration config = new NetPeerConfiguration("unconntest");
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.AcceptIncomingConnections = false; // don't accept connections; we're just using unconnected messages in this sample

            Peer = new NetPeer(config);
            Peer.Start();

            Application.Idle += new EventHandler(AppLoop);
            Application.Run(MainForm);
        }
Exemplo n.º 28
0
        public static void Run(NetPeer peer)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("Test");

            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == false)
                throw new NetException("setting enabled message types failed");

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, false);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == true)
                throw new NetException("setting enabled message types failed");

            Console.WriteLine("Misc tests OK");

            Console.WriteLine("Hex test: " + NetUtility.ToHexString(new byte[]{0xDE,0xAD,0xBE,0xEF}));
        }
Exemplo n.º 29
0
		internal void Discover(NetPeer peer)
		{
			string str =
"M-SEARCH * HTTP/1.1\r\n" +
"HOST: 239.255.255.250:1900\r\n" +
"ST:upnp:rootdevice\r\n" +
"MAN:\"ssdp:discover\"\r\n" +
"MX:3\r\n\r\n";

			byte[] arr = System.Text.Encoding.UTF8.GetBytes(str);

			peer.Socket.Broadcast = true;
			peer.RawSend(arr, 0, arr.Length, new IPEndPoint(IPAddress.Broadcast, 1900));
            peer.Socket.Broadcast = false;

			// allow some extra time for router to respond
			// System.Threading.Thread.Sleep(50);
		}
Exemplo n.º 30
0
        private void Initialize() {
            if(_role == AgentRole.Server) {
                _config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
                _config.Port = _port;
                _config.PingInterval = _pingInterval;
                _config.ConnectionTimeout = _pingInterval + 1;
                _peer = new NetServer(_config);
                
                Log("Server starting on " + _config.LocalAddress + ":" + _config.Port);
            } else if(_role == AgentRole.Client) {
                _config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
                _config.PingInterval = _pingInterval;
                _config.ConnectionTimeout = _pingInterval + 1;
                _peer = new NetClient(_config);
            }

            _peer.Start();
        }
 /// <summary>
 /// NetBlockEncryptionBase constructor
 /// </summary>
 public NetBlockEncryptionBase(NetPeer peer)
     : base(peer)
 {
 }
Exemplo n.º 32
0
 /// <summary>
 /// NetXorEncryption constructor
 /// </summary>
 public NetXorEncryption(NetPeer peer, byte[] key)
     : base(peer)
 {
     m_key = key;
 }
Exemplo n.º 33
0
 /// <summary>
 /// NetXorEncryption constructor
 /// </summary>
 public NetXorEncryption(NetPeer peer, string key)
     : base(peer)
 {
     m_key = Encoding.UTF8.GetBytes(key);
 }
        public NetAESEncryption(NetPeer peer)
#if UNITY
            : base(peer, new RijndaelManaged())
#else
            : base(peer, new AesCryptoServiceProvider())
Exemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetDESEncryption"/> class.
 /// </summary>
 /// <param name="peer">The peer.</param>
 /// <param name="key">The key.</param>
 public NetDESEncryption(NetPeer peer, string key)
     : base(peer, new DESCryptoServiceProvider())
 {
     SetKey(key);
 }
 internal NetPeerStatistics(NetPeer peer)
 {
     m_peer = peer;
     Reset();
 }
Exemplo n.º 37
0
 /// <summary>
 /// NetUPnP constructor
 /// </summary>
 public NetUPnP(NetPeer peer)
 {
     m_peer = peer;
     m_discoveryResponseDeadline = double.MinValue;
 }
Exemplo n.º 38
0
 /// <summary>
 /// 16 byte key
 /// </summary>
 public NetXtea(NetPeer peer, byte[] key)
     : this(peer, key, 32)
 {
 }
Exemplo n.º 39
0
 /// <summary>
 /// String to hash for key
 /// </summary>
 public NetXtea(NetPeer peer, string key)
     : this(peer, NetUtility.ComputeSHAHash(Encoding.UTF8.GetBytes(key)), 32)
 {
 }
 public LidgrenNetProvider(NetPeerConfiguration config)
 {
     _peer   = new NetPeer(config);
     _stream = new MemoryStream(_buffer);
     _reader = new BinaryReader(_stream);
 }
Exemplo n.º 41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetDESEncryption"/> class.
 /// </summary>
 /// <param name="peer">The peer.</param>
 /// <param name="data">The data.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="count">The count.</param>
 public NetDESEncryption(NetPeer peer, byte[] data, int offset, int count)
     : base(peer, new DESCryptoServiceProvider())
 {
     SetKey(data, offset, count);
 }
Exemplo n.º 42
0
 /// <summary>
 /// NetUPnP constructor
 /// </summary>
 public NetUPnP(NetPeer peer)
 {
     m_peer = peer;
 }
Exemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetDESEncryption"/> class.
 /// </summary>
 /// <param name="peer">The peer</param>
 public NetDESEncryption(NetPeer peer)
     : base(peer, new DESCryptoServiceProvider())
 {
 }
 /// <summary>
 /// String to hash for key
 /// </summary>
 public NetXtea(NetPeer peer, string key)
     : this(peer, NetUtility.CreateSHA1Hash(key), 32)
 {
 }
Exemplo n.º 45
0
        public Rts(EventHandler callback, Lidgren.Network.NetPeer netpeer, short myTeam)
            : base(callback)
        {
            netPeer   = netpeer;
            iAmServer = netPeer is NetServer;

            Game1.Game.DebugMonitor.Position = Direction.NorthEast;
            //Game1.Game.Graphics.SynchronizeWithVerticalRetrace = false;
            //Game1.Game.IsFixedTimeStep = false;
            //Game1.Game.Graphics.ApplyChanges();
            //GameTimer.Restart();

            //map = new Map(@"Content/map1.muh");
            map        = new Map("C:\\rts maps\\map2.muh");
            pathFinder = new PathFinder(map);
            map.InstantiateMapResources();
            //Player.Me.Team = myTeam;
            Player.Me = Player.Players[myTeam];

            actualMapWidth  = map.Width * map.TileSize;
            actualMapHeight = map.Height * map.TileSize;

            Unit.UnitCollisionSweeper.Thread.Suspend();
            Unit.UnitCollisionSweeper.Thread.Resume();
            Rts.pathFinder.ResumeThread();

            uiViewport      = GraphicsDevice.Viewport;
            worldViewport   = GraphicsDevice.Viewport;
            minimapViewport = new Viewport(minimapBorderSize, uiViewport.Height - minimapSize - minimapBorderSize, minimapSize, minimapSize);
            //minimapViewport = new Viewport(0, 0, minimapSize, minimapSize);
            worldViewport.Height   -= (minimapSize + minimapBorderSize * 2);
            GraphicsDevice.Viewport = worldViewport;

            camera     = new Camera();
            camera.Pos = new Vector2(worldViewport.Width / 2, worldViewport.Height / 2);

            button1 = new BaseObject(new Rectangle(10, 25, 25, 25));
            button2 = new BaseObject(new Rectangle(10, 52, 25, 25));
            button3 = new BaseObject(new Rectangle(10, 79, 25, 25));
            button4 = new BaseObject(new Rectangle(10, 106, 25, 25));
            button5 = new BaseObject(new Rectangle(10, 133, 25, 25));

            if (!contentLoaded)
            {
                pauseFont             = Content.Load <SpriteFont>("spritefonts/pausefont");
                fpsFont               = Content.Load <SpriteFont>("spritefonts/fpsfont");
                unitInfoUnitNameFont  = Content.Load <SpriteFont>("spritefonts/UnitInfoUnitNameFont");
                unitInfoHpFont        = Content.Load <SpriteFont>("spritefonts/UnitInfoHpFont");
                unitInfoKillCountFont = Content.Load <SpriteFont>("spritefonts/UnitInfoKillCountFont");
                resourceCountFont     = Content.Load <SpriteFont>("spritefonts/ResourceCountFont");
                bigFont               = Content.Load <SpriteFont>("spritefonts/BigMessage");
                //brownGuyTexture = Content.Load<Texture2D>("unit textures/browncircleguy");
                //brownGuySelectingTexture = Content.Load<Texture2D>("unit textures/browncircleguyselected2");
                //brownGuySelectedTexture = Content.Load<Texture2D>("unit textures/browncircleguyselecting2");
                greenTeamIndicatorTexture        = Content.Load <Texture2D>("unit textures/green team indicator");
                redTeamIndicatorTexture          = Content.Load <Texture2D>("unit textures/red team indicator");
                buttonTexture                    = Content.Load <Texture2D>("titlebutton1");
                moveCommandShrinkerTexture       = Content.Load <Texture2D>("greencircle2");
                attackMoveCommandShrinkerTexture = Content.Load <Texture2D>("redcircle2");
                //normalCursorTexture = Content.Load<Texture2D>("greencursor2");
                //attackCommandCursorTexture = Content.Load<Texture2D>("crosshair");
                normalCursor            = Util.LoadCustomCursor(@"Content/cursors/SC2-cursor.cur");
                attackCursor            = Util.LoadCustomCursor(@"Content/cursors/SC2-target-none.cur");
                boulder1Texture         = Content.Load <Texture2D>("boulder1");
                tree1Texture            = Content.Load <Texture2D>("tree2");
                rallyFlagTexture        = Content.Load <Texture2D>("redflag");
                redCircleTexture        = Content.Load <Texture2D>("redcircle");
                transparentTexture      = Content.Load <Texture2D>("transparent");
                transparentGrayTexture  = Content.Load <Texture2D>("transparentgray");
                transparentBlackTexture = Content.Load <Texture2D>("transparentblack");
                whiteBoxTexture         = Content.Load <Texture2D>("whitebox");
                cogWheelTexture         = Content.Load <Texture2D>("cogwheel");
                rtsMusic         = Content.Load <Song>("music/58 - Weapons Factory");
                errorSoundEffect = Content.Load <SoundEffect>("sounds/Error");
                //Unit.BulletTexture = Content.Load<Texture2D>("bullet");
                Unit.Explosion1Textures      = Util.SplitTexture(Content.Load <Texture2D>("explosionsheet1"), 45, 45);
                Structure.Explosion1Textures = Util.SplitTexture(Content.Load <Texture2D>("explosionsheet1"), 45, 45);
                contentLoaded = true;
            }

            winForm = (Form)Form.FromHandle(Game1.Game.Window.Handle);
            //Cursor.Clip = new System.Drawing.Rectangle(winForm.Location, winForm.Size);
            winForm.Cursor = normalCursor;

            initializeMapTexture();
            initializeCommandCardArea();
            initializeSelectionInfoArea();
            line.Alpha = .75f;

            VisionUpdater = new VisionUpdater(map, Rts.pathFinder, Player.Me.Team);

            SelectBox.InitializeSelectBoxLine(GraphicsDevice, Color.Green);
            Initializeline(GraphicsDevice, Color.Yellow);

            minimapScreenIndicatorBoxLine        = new PrimitiveLine(GraphicsDevice, 1);
            minimapScreenIndicatorBoxLine.Colour = Color.White;

            for (int i = 0; i < HotkeyGroups.Length; i++)
            {
                HotkeyGroups[i] = new List <RtsObject>();
            }

            MediaPlayer.Play(rtsMusic);
            MediaPlayer.Volume      = MusicVolume;
            MediaPlayer.IsRepeating = true;

            /*new TownHall(map.StartingPoints[myTeam], myTeam);
             * camera.Pos = new Vector2(map.StartingPoints[myTeam].X * map.TileSize, map.StartingPoints[myTeam].Y * map.TileSize);
             * Player.Me.MaxSupply += StructureType.TownHall.Supply;*/
            initializeStartingPoints();

            //new Barracks(new Point(10, 14), 2);
            //new Roks(new Point(3, 3));
            //new Roks(new Point(3, 30));

            Player.Me.Roks = 25;

            clampCameraToMap();

            initialHandShake();
        }
Exemplo n.º 46
0
 /// <summary>
 /// NetBlockEncryptionBase constructor
 /// </summary>
 public NetBlockEncryptionBase(NetPeer peer)
     : base(peer)
 {
     m_tmp = new byte[BlockSize];
 }
 public LidgrenNetProvider(NetPeerConfiguration config, ILidgrenEvents logger = null)
 {
     _logger = logger;
     _peer   = new NetPeer(config);
 }
 public NetCryptoProviderEncryption(NetPeer peer)
     : base(peer)
 {
 }