void R_AddNetPlayer(NetConnection server, NetBuffer data, ushort numArgs)
        {
            ushort playerId   = data.ReadUInt16();
            string playerName = data.ReadString();

            DashCMD.WriteLine("[NPM] Got NetPlayer[{1}] '{0}'", playerName, playerId);

            NetworkPlayer netPlayer = new NetworkPlayer(playerName, playerId);

            netPlayers.Add(playerId, netPlayer);

            snapshotComponent.WorldSnapshot.NetworkPlayerListSnapshot.AddNetPlayer(netPlayer, false);

            if (OnNetPlayerAdded != null)
            {
                OnNetPlayerAdded(this, netPlayer);
            }
        }
Пример #2
0
 public bool LoadFromFile(string fileName)
 {
     DashCMD.WriteImportant("[ServerWorld] Loading world '{0}'...", fileName);
     try
     {
         Description = WorldIO.Load(CurrentWorldName = fileName);
         SetTerrain(Description.Terrain);
         Terrain.LockBottomLayer = true;
         DashCMD.WriteImportant("[ServerWorld] Successfully loaded world '{0}'.", fileName);
         return(true);
     }
     catch (IOException ioex)
     {
         DashCMD.WriteError("[ServerWorld] Failed to load world '{0}'!", fileName);
         DashCMD.WriteError(ioex);
         return(false);
     }
 }
Пример #3
0
        /// <summary>
        /// Loads a shader from a file.
        /// <para>At this stage, there is no auto-cleanup for this shader.
        /// Auto-Cleanup takes place once this is loaded to a ShaderProgram.</para>
        /// </summary>
        public static GLShader LoadShader(string path, ShaderType type)
        {
            GLShader shader;
            string   fileName = Path.GetFileName(path);

            // If shader is not found, load and compile it
            if (!GManager.TryGetShader(fileName, out shader))
            {
                path = Path.Combine(RootDirectory, "Shaders/", path);

                // Allocate the shader Id
                shader = GManager.CreateShader(fileName, type);
                uint shaderId = shader.Id;
                // Load the shader from the file
                string shaderCode = LoadFileToString(path);
                // Load the shader's sourcecode to the GL shader
                GL.ShaderSource(shaderId, shaderCode);
                // Compile the shader for the GPU
                GL.CompileShader(shaderId);

                // Check the compilation status
                int    status = GL.GetShader(shaderId, ShaderParameter.CompileStatus);
                string log    = GL.GetShaderInfoLog(shaderId);

                // Log
                if (status == 0)
                {
                    throw new GLoaderException(String.Format("Failed to compile {0}. Reason: {1}", Path.GetFileName(path), log));
                }
                else if (LogShaderCompilation)
                {
                    if (string.IsNullOrWhiteSpace(log))
                    {
                        DashCMD.WriteStandard("Compiled {0} with id {1}.", Path.GetFileName(path), shaderId);
                    }
                    else
                    {
                        DashCMD.WriteStandard("Compiled {0} with id {1}. Status: {2}", Path.GetFileName(path), shaderId, log);
                    }
                }
            }

            return(shader);
        }
        void InitializeCMD()
        {
            NetLogger.LogObjectStateChanges = true;
            NetLogger.LogVerboses           = true;

            DashCMD.AddScreen(new DashCMDScreen("network", "", true,
                                                (screen) =>
            {
                screen.WriteLine("Heartbeat Compution Time: {0}ms", client.HeartbeatComputionTimeMS);
                screen.WriteLine("Send Rate: {0}", client.ServerConnection.PacketSendRate);
                screen.WriteLine("MTU: {0}", client.ServerConnection.Stats.MTU);
                screen.WriteLine("Ping: {0}", client.ServerConnection.Stats.Ping);
                screen.WriteLine("VPackets s/s: {0}", client.ServerConnection.Stats.PacketsSentPerSecond);
                screen.WriteLine("VPackets r/s: {0}", client.ServerConnection.Stats.PacketsReceivedPerSecond);
                screen.WriteLine("Packets Lost: {0}", client.ServerConnection.Stats.PacketsLost);
                screen.WriteLine("PPackets s/s: {0}", client.ServerConnection.Stats.PhysicalPacketsSentPerSecond);
                screen.WriteLine("PPackets r/s: {0}", client.ServerConnection.Stats.PhysicalPacketsReceivedPerSecond);
            }));
        }
Пример #5
0
        static int Main()
        {
            DashCMD.Start();
            DashCMD.Listen(true);

            ProgramExceptionHandler.RunMainWithHandler(
                () =>
            {
                using (MainWindow window = new MainWindow())
                {
                    window.Run(60);
                }
            },
                () => { DashCMD.Stop(); },
                () => { }
                );

            return(0);
        }
        bool OnCustomPacket(NetInboundPacket packet, CustomPacketType type)
        {
            if (type == CustomPacketType.HandshakeInitiate)
            {
                if (handshake != null)
                {
                    DashCMD.WriteError("Got handshake initiate packet, but we are already in a handshake!");
                    return(false);
                }

                // Begin the handshake on our end
                handshake = new Handshake(client, this, packet);
                loadingBar.SetHandshake(handshake);

                // We don't want to have the user staring at a blank skybox,
                // so lets show them pictures :D
                StaticGui.ShowBackground = true;
                return(true);
            }
            else if (type == CustomPacketType.WorldSection)
            {
                if (handshake != null)
                {
                    // Notify the handshake we have received another
                    // piece of the world data.
                    handshake.OnLevelChunkInbound(packet);
                }
                else
                {
                    DashCMD.WriteError("Got handshake world section packet, but we are not in a handshake!");

                    // We did acknowledge the packet,
                    // but since we are not in the right state
                    // act as if its unknown (little extra protection
                    // from a rogue server).
                    return(false);
                }

                return(true);
            }

            return(false);
        }
Пример #7
0
        public void OnCreatableInstantiated(NetCreatableInfo info, WorldSnapshot ws)
        {
            ClientPlayer player = info.Creatable as ClientPlayer;

            // Add the new player
            if (player != null)
            {
                players.Add(info.Id, player);

                if (info.IsAppOwner)
                {
                    // Setup player as our own
                    if (ourPlayer != null)
                    {
                        DashCMD.WriteError("[CSS] Received client player instantiation twice!");
                    }
                    else
                    {
                        // Setup our gamestate
                        // Copy each existing player to the worldsnapshot
                        foreach (ClientPlayer plr in players.Values)
                        {
                            if (plr == player)
                            {
                                // The new player doesn't have stateinfo setup yet
                                ws.AddPlayer(info.Id, true, false);
                            }
                            else if (!ws.PlayerFieldExists(plr.StateInfo.Id))
                            {
                                ws.AddPlayer(plr.StateInfo.Id, false, false);
                            }
                        }

                        // Set our player and our new world snapshot
                        ourPlayer = (ClientMPPlayer)player;
                    }
                }
                else
                {
                    ws.AddPlayer(info.Id, false, false);
                }
            }
        }
        void Loop()
        {
            string txt       = String.Format("Screen - {0}", Name);
            string spaces    = new string(' ', (Console.BufferWidth / 2) - (txt.Length / 2));
            string titleLine = "(Esc to exit)".PadLeft(Console.BufferWidth);
            string title     = String.Format("{0}{1}{2}{3}{4}",
                                             spaces, txt, spaces.Substring(0, spaces.Length - 1), Environment.NewLine, titleLine);
            bool firstStep = true;

            if (AutoUpdate)
            {
                do
                {
                    int top = Console.WindowTop;
                    Console.BackgroundColor = ConsoleColor.Black;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Clear();
                    DashCMD.stdWrite(title);
                    Draw();
                    if (!firstStep)
                    {
                        Console.SetWindowPosition(Console.WindowLeft, top);
                    }
                    else
                    {
                        firstStep = false;
                        Console.SetWindowPosition(Console.WindowLeft, 0);
                    }
                    Thread.Sleep(SleepTime);
                } while (IsActive);
            }
            else
            {
                int top = Console.WindowTop;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Clear();
                DashCMD.stdWrite(title);
                Draw();
                Console.SetWindowPosition(Console.WindowLeft, 0);
            }
        }
        static void NetLogger_MessageLogged(NetLog log)
        {
            switch (log.Type)
            {
            case NetLogType.Error:
                DashCMD.WriteError(log.Message); break;

            case NetLogType.Warning:
                DashCMD.WriteWarning(log.Message); break;

            case NetLogType.Important:
                DashCMD.WriteLine(log.Message, ConsoleColor.Green); break;

            case NetLogType.Verbose:
                DashCMD.WriteLine(log.Message, ConsoleColor.DarkGray); break;

            default:
                DashCMD.WriteStandard(log.Message); break;
            }
        }
Пример #10
0
        protected override void OnPlayerRespawn(NetConnection client)
        {
            // Find the connections networkplayer
            NetworkPlayer netPlayer = NetPlayerComponent.GetPlayer(client);
            Team          team      = netPlayer.Team;

            if (team == Team.None)
            {
                DashCMD.WriteError("[TDMGamemode] Failed to respawn player, they do not have a team!");
            }
            else
            {
                Vector3 spawnLocation = team == Team.A
                    ? redPost.Transform.Position
                    : bluePost.Transform.Position;

                // Create the character
                SpawnPlayer(client, spawnLocation, team);
            }
        }
Пример #11
0
        protected override void OnStarted()
        {
            Server.OnUserDisconnected += Server_OnUserDisconnected;

            // Send gamemode info
            NetChannel.FireEventForAllConnections("Client_GamemodeInfo", (ushort)SCORE_CAP);

            var commandposts = World.Description.GetObjectsByTag("CommandPost");

            if (commandposts.Count == 2)
            {
                // Load command posts
                foreach (WorldObjectDescription ob in commandposts)
                {
                    Vector3 position = ob.GetVector3("Position");
                    Team    team     = (Team)(ob.GetField <byte>("Team") ?? 0);

                    CommandPost post = new CommandPost(position, team);
                    if (team == Team.A)
                    {
                        redPost = post;
                    }
                    else
                    {
                        bluePost = post;
                    }

                    post.PhysicsBody.OnCollision += Post_OnCollision;

                    objectComponent.NetworkInstantiate(post, "Client_CreateCommandPost", null,
                                                       position.X, position.Y, position.Z, (byte)team);
                }
            }
            else
            {
                DashCMD.WriteWarning("[TDMGamemode] Current world does not have a proper gameobject setup! Falling back to default.");
                LoadFallbackGameObjects();
            }

            base.OnStarted();
        }
Пример #12
0
        void HandleInstantiationPacket(NetInboundPacket packet)
        {
            string eventName = packet.ReadString();
            ushort id        = packet.ReadUInt16();
            bool   isOwner   = packet.ReadBool();

            NetInstantiationCallback callback;

            if (instCallbacks.TryGetValue(eventName, out callback))
            {
                if (netObjects.Creatables.ContainsKey(id))
                {
                    DashCMD.WriteError("[ObjectNC] Creatable with id {0} is already instantiated!", id);
                    return;
                }

                //DashCMD.WriteLine("[ObjectNC] Instantiating creatable with id {0}...", id);

                INetCreatable    creatable = callback(id, isOwner, packet);
                NetCreatableInfo info      = new NetCreatableInfo(packet.Sender, creatable, id, isOwner);
                netObjects.Add(id, info);

                INetEntity entity = creatable as INetEntity;
                if (entity != null && snapshotComponent.WorldSnapshot != null)
                {
                    NetEntityListSnapshot entList = snapshotComponent.WorldSnapshot.NetEntityListSnapshot;
                    entList.AddNetEntity(info, entity);
                }

                creatable.OnNetworkInstantiated(info);

                if (OnCreatableInstantiated != null)
                {
                    OnCreatableInstantiated(this, info);
                }
            }
            else
            {
                DashCMD.WriteError("[ObjectNC] Received instantiation for unknown type: {0}", eventName);
            }
        }
Пример #13
0
        public ServerWorld()
        {
            players      = new ConcurrentDictionary <NetConnection, ServerMPPlayer>();
            physEntities = new Dictionary <ushort, GameObject>();

            server            = AOSServer.Instance;
            snapshotComponent = server.GetComponent <SnapshotNetComponent>();
            objectComponent   = server.GetComponent <ObjectNetComponent>();
            channel           = server.GetChannel(AOSChannelType.World);

            channel.AddRemoteEvent("Server_SetBlock", R_SetBlock);
            channel.AddRemoteEvent("Server_ThrowGrenade", R_ThrowGrenade);
            channel.AddRemoteEvent("Server_ShootMelon", R_ShootMelon);

            objectComponent.OnCreatableInstantiated   += ObjectComponent_OnCreatableInstantiated;
            objectComponent.OnCreatableDestroyed      += ObjectComponent_OnCreatableDestroyed;
            snapshotComponent.OnWorldSnapshotOutbound += Server_OnWorldSnapshotOutbound;

            InitializeCMD();

            ConfigSection gameSection = Program.Config.GetSection("Game");

            if (gameSection == null)
            {
                DashCMD.WriteError("[server.cfg - ServerWorld] Section 'Game' is missing!");
            }
            else
            {
                string worldFile = gameSection.GetString("world-file");

                if (!string.IsNullOrWhiteSpace(worldFile))
                {
                    LoadFromFile(worldFile);
                }
                else
                {
                    DashCMD.WriteError("[server.cfg - ServerWorld] Game.world-file is missing!");
                }
            }
        }
Пример #14
0
        public void Update(float deltaTime)
        {
            // Update internal messenger
            base.Update();

            // Ensure IsConnected is up to date for shared lib
            GlobalNetwork.IsConnected = IsConnected;

            // Read packets
            for (int i = 0; i < 1000 && AvailablePackets > 0; i++)
            {
                NetInboundPacket packet = ReadPacket();
                if (packet.Position >= packet.Length)
                {
                    DashCMD.WriteError("[AOSClient] Received invalid custom packet from {0}! (bad packet position)",
                                       packet.Sender);
                }
                else
                {
                    CustomPacketType type = (CustomPacketType)packet.ReadByte();

                    // Try and handle the packet
                    if (!HandlePacket(packet, type))
                    {
                        DashCMD.WriteWarning("[AOSClient] Received unknown custom packet {0}, from {1}",
                                             type, packet.Sender);
                    }
                }
            }

            // Update each component
            if (IsConnected)
            {
                foreach (NetComponent c in components.Values)
                {
                    c.Update(deltaTime);
                }
            }
        }
Пример #15
0
        static void CreateServerConfigIfMissing()
        {
            if (!File.Exists("server.cfg"))
            {
                try
                {
                    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("AceOfSpades.Server.cfg.server.default.cfg"))
                        using (FileStream fs = File.Open("./server.cfg", FileMode.Create, FileAccess.Write))
                        {
                            stream.Seek(0, SeekOrigin.Begin);
                            stream.CopyTo(fs);
                        }

                    DashCMD.WriteImportant("Created default server.cfg");
                }
                catch (Exception e)
                {
                    DashCMD.WriteError("Failed to create server.cfg!");
                    DashCMD.WriteError(e);
                }
            }
        }
        void R_AddInitialNetPlayers(NetConnection server, NetBuffer data, ushort numArgs)
        {
            OurNetPlayerId = data.ReadUInt16();
            ushort numPlayers = data.ReadUInt16();

            for (int i = 0; i < numPlayers; i++)
            {
                ushort playerId   = data.ReadUInt16();
                string playerName = data.ReadString();
                Team   team       = (Team)data.ReadByte();
                ushort?charId     = null;
                if (data.ReadBool()) // Only read charId if the player has a character
                {
                    charId = data.ReadUInt16();
                }

                DashCMD.WriteLine("[NPM] Got NetPlayer[{1}] '{0}' on team {2}", playerName, playerId, team);

                NetworkPlayer player = new NetworkPlayer(playerName, playerId);
                player.Team        = team;
                player.CharacterId = charId;

                if (!netPlayers.ContainsKey(playerId))
                {
                    snapshotComponent.WorldSnapshot.NetworkPlayerListSnapshot.AddNetPlayer(player, false);
                    netPlayers.Add(playerId, player);
                }
                else
                {
                    DashCMD.WriteError("[NPM] Got NetPlayer[{1}] '{0}', but we already added this player!",
                                       playerName, playerId);
                }
            }

            if (OnNetPlayersInitialized != null)
            {
                OnNetPlayersInitialized(this, EventArgs.Empty);
            }
        }
Пример #17
0
        void SwitchGamemode(GamemodeType to)
        {
            if (currentGamemode != null)
            {
                currentGamemode.Stop();
            }

            currentGamemode = null;

            NetworkedGamemode gamemode;

            if (gamemodes.TryGetValue(to, out gamemode))
            {
                currentGamemode = gamemode;
                currentGamemode.Start();

                channel.FireEventForAllConnections("Client_SwitchGamemode", (byte)to);
            }
            else
            {
                DashCMD.WriteError("[MatchScreen] Gamemode type '{0}' is not defined!", to);
            }
        }
        public MultiplayerScreen(MainWindow window)
            : base(window, "Multiplayer")
        {
            debugRenderer = Renderer.GetRenderer3D <DebugRenderer>();

            gamemodes = new Dictionary <GamemodeType, NetworkedGamemode>()
            {
                { GamemodeType.TDM, new TDMGamemode(this) },
                { GamemodeType.CTF, new CTFGamemode(this) }
            };

            // Build the UI elements
            theme = AssetManager.CreateDefaultGameTheme();
            font  = theme.GetField <BMPFont>(null, "SmallFont");

            hud                       = new HUD(Renderer);
            loadingBar                = new MultiplayerLoadingBar(GUISystem, theme);
            chat                      = new ChatBox(new UDim2(0, 40, 1f, -240), new UDim2(0, 350, 0, 165), theme, this);
            menu                      = new MultiplayerMenu(GUISystem, theme, Window);
            menu.OnClosed            += Menu_OnClosed;
            announcementLabel         = new GUILabel(new UDim2(0.5f, 0, 0.5f, 0), UDim2.Zero, "", TextAlign.Center, theme);
            announcementLabel.Font    = AssetManager.LoadFont("karmasuture-32");
            announcementLabel.Visible = false;

            // Add each UI element
            GUIArea.AddTopLevel(chat, announcementLabel);
            GUISystem.Add(loadingBar, menu);
            Windows.Add(loadingBar);
            Windows.Add(menu);

            // Setup default multiplayer cvars
            DashCMD.SetCVar("cl_impacts", false);
            DashCMD.SetCVar("cl_interp", 0.5f);               // Client interpolation with server position
            DashCMD.SetCVar("cl_interp_movement_smooth", 1f); // Client player movement smoothing (1f = no smoothing)
            DashCMD.SetCVar("cl_interp_rep", 20f);            // Replicated entities interpolation
            DashCMD.SetCVar("cl_max_error_dist", 12f);        // Max distance the client's position can be off from the server's
        }
Пример #19
0
        void R_ClientInfo(NetConnection client, NetBuffer data, ushort numArgs)
        {
            try
            {
                if (numArgs == 1)
                {
                    DisconnectClientForGameVersion(client);
                }

                string      playerName    = data.ReadString();
                GameVersion clientVersion = GameVersion.Deserialize(data);

                if (!GameVersion.Current.Equals(clientVersion))
                {
                    DisconnectClientForGameVersion(client);
                }

                ClientInfo ci = new ClientInfo(playerName);

                NetworkPlayer netPlayer;
                if (netPlayers.TryGetValue(client, out netPlayer))
                {
                    // Process information from client info
                    ProcessClientInfo(netPlayer, client, ci);
                }
                else
                {
                    // Just incase the client got here first, just stash it for later
                    stashedClientInfo.Add(client, ci);
                }
            }
            catch (Exception)
            {
                DashCMD.WriteError("[NPM] Client {0} send invalid client info!", client);
                client.Disconnect("Invalid client info.");
            }
        }
        /// <summary>
        /// Attaches the ProgramExceptionHandler.OnException event to the error-handler,
        /// and properly calls the error-handler from exceptions based on debugger status.
        /// </summary>
        public static void RunMainWithHandler(Action tryAction, Action finallyAction, Action shutdownAction)
        {
            ErrorHandlerExists = File.Exists("./ErrorHandler.exe");

            if (!ErrorHandlerExists)
            {
                DashCMD.WriteWarning("[WARNING] ErrorHandler.exe does not exist!");
            }

            OnException += (args) => HandleException(args.Exception, shutdownAction);

            if (Debugger.IsAttached || !ErrorHandlerExists)
            {
                // Exclude the catch if the debugger is attached, so visual studio can do its thing.
                try { tryAction(); }
                finally { finallyAction(); }
            }
            else
            {
                try { tryAction(); }
                catch (Exception e) { HandleException(e, shutdownAction); }
                finally { finallyAction(); }
            }
        }
Пример #21
0
        public void OnLevelChunkInbound(NetInboundPacket packet)
        {
            ushort dataLength = packet.ReadUInt16();

            terrainData[terrainDataI] = packet.ReadBytes(dataLength);

            terrainDataRead += dataLength;

            if (OnTerrainProgressReported != null)
            {
                OnTerrainProgressReported(terrainDataRead, terrainDataFullSize);
            }

            DashCMD.WriteStandard("[HS] Received terrain data {0}/{1} bytes", terrainDataRead, terrainDataFullSize);
            terrainDataI++;

            if (terrainDataI < terrainData.Length)
            {
                // Send terrain ack to ask for next part
                NetOutboundPacket ack = new NetOutboundPacket(NetDeliveryMethod.ReliableOrdered);
                ack.Write((byte)CustomPacketType.WorldSectionAck);

                client.SendPacket(ack);
            }
            else
            {
                if (OnTerrainProgressReported != null)
                {
                    OnTerrainProgressReported(terrainDataFullSize, terrainDataFullSize);
                }

                // Uncompress the data and notify the screen we are done downloading.
                HandshakeTerrainData data = new HandshakeTerrainData(terrainData, terrainUncompressedSize);
                screen.OnHandshakeDoneDownloading(data);
            }
        }
Пример #22
0
 public void HandshakeCompleted(Handshake h)
 {
     DashCMD.WriteStandard("[HS] Completed handshake with {0}.", h.With);
     handshakes.Remove(h.With);
     screen.OnHandshakeComplete(h);
 }
Пример #23
0
        protected override void OnStarted()
        {
            Server.OnUserDisconnected += Server_OnUserDisconnected;

            var commandposts = World.Description.GetObjectsByTag("CommandPost");
            var intels       = World.Description.GetObjectsByTag("Intel");

            if (commandposts.Count == 2 && intels.Count == 2)
            {
                // Load intel
                foreach (WorldObjectDescription ob in intels)
                {
                    Vector3 position = ob.GetVector3("Position");
                    Team    team     = (Team)(ob.GetField <byte>("Team") ?? 0);

                    Intel intel = new Intel(position, team);
                    if (team == Team.A)
                    {
                        redIntel = intel;
                    }
                    else
                    {
                        blueIntel = intel;
                    }

                    intel.OnPickedUp += Intel_OnPickedUp;
                    intel.OnDropped  += Intel_OnDropped;
                    intel.OnReturned += Intel_OnReturned;

                    objectComponent.NetworkInstantiate(intel, "Client_CreateIntel", null,
                                                       position.X, position.Y, position.Z, (byte)team);
                }

                // Load command posts
                foreach (WorldObjectDescription ob in commandposts)
                {
                    Vector3 position = ob.GetVector3("Position");
                    Team    team     = (Team)(ob.GetField <byte>("Team") ?? 0);

                    CommandPost post = new CommandPost(position, team);
                    if (team == Team.A)
                    {
                        redPost = post;
                    }
                    else
                    {
                        bluePost = post;
                    }

                    post.PhysicsBody.OnCollision += Post_OnCollision;

                    objectComponent.NetworkInstantiate(post, "Client_CreateCommandPost", null,
                                                       position.X, position.Y, position.Z, (byte)team);
                }
            }
            else
            {
                DashCMD.WriteWarning("[CTFGamemode] Current world does not have a proper gameobject setup! Falling back to default.");
                LoadFallbackGameObjects();
            }

            base.OnStarted();
        }
Пример #24
0
 public virtual void Stop()
 {
     DashCMD.WriteImportant("[Gamemode] Stopping '{0}'...", Type);
     OnStopped();
 }
Пример #25
0
 private void NetPlayerComponent_OnClientLeave(NetConnection connection, NetworkPlayer player)
 {
     DashCMD.WriteImportant("[MatchScreen] '{0}' has left!", player.Name);
     Chat(string.Format("'{0}' has left!", player.Name));
 }
Пример #26
0
        public MatchScreen(ServerGame game)
            : base(game, "Match")
        {
            gamemodes = new Dictionary <GamemodeType, NetworkedGamemode>()
            {
                { GamemodeType.TDM, new TDMGamemode(this) },
                { GamemodeType.CTF, new CTFGamemode(this) }
            };

            // Setup default multiplayer cvars
            DashCMD.SetCVar("ch_infammo", false);
            DashCMD.SetCVar("ch_infhealth", false);
            DashCMD.SetCVar("mp_friendlyfire", false);

            DashCMD.SetCVar("sv_impacts", false);
            DashCMD.SetCVar("sv_hitboxes", false);

            DashCMD.SetCVar("rp_rollback_constant", false);
            DashCMD.SetCVar("rp_rollback_factor", 0.5f);
            DashCMD.SetCVar("rp_rollback_offset", 0);
            DashCMD.SetCVar("rp_usetargetping", false);

            DashCMD.SetCVar("gm_neverend", false);

            DashCMD.AddCommand("world", "Changes the world", "world [filename | *]",
                               (args) =>
            {
                if (args.Length != 1)
                {
                    DashCMD.WriteImportant("Current World: {0}", World.CurrentWorldName);
                }
                else
                {
                    string worldFile = args[0];
                    ChangeWorld(worldFile);
                }
            });

            DashCMD.AddCommand("worlds", "Lists all worlds", "worlds",
                               (args) =>
            {
                string[] worlds = Directory.GetFiles("Content/Worlds");
                DashCMD.WriteImportant("Available Worlds ({0}):", worlds.Length);
                for (int i = 0; i < worlds.Length; i++)
                {
                    DashCMD.WriteStandard("  {0}", Path.GetFileNameWithoutExtension(worlds[i]));
                }
            });

            DashCMD.AddCommand("gamemode", "Changes the gamemode", "gamemode [mode]",
                               (args) =>
            {
                if (args.Length != 1)
                {
                    DashCMD.WriteImportant("Current Gamemode: {0}",
                                           currentGamemode != null ? currentGamemode.Type.ToString() : "None");
                }
                else
                {
                    GamemodeType type;
                    if (Enum.TryParse(args[0], true, out type))
                    {
                        ChangeWorld(World.CurrentWorldName, type);
                    }
                    else
                    {
                        DashCMD.WriteError("Gamemode '{0}' does not exist!", type);
                    }
                }
            });

            DashCMD.AddCommand("say", "Announces a global message", "say <message>",
                               (args) =>
            {
                if (args.Length == 0)
                {
                    DashCMD.ShowSyntax("say");
                }
                else
                {
                    Announce(DashCMD.CombineArgs(args), 5);
                }
            });

            DashCMD.AddCommand("chat", "Sends a chat message from the user 'SERVER'", "chat <message>",
                               (args) =>
            {
                if (args.Length == 0)
                {
                    DashCMD.ShowSyntax("chat");
                }
                else
                {
                    Chat(DashCMD.CombineArgs(args));
                }
            });
        }
Пример #27
0
        private void World_OnPlayerKilled(PlayerDamage damageEvent)
        {
            ServerMPPlayer killer    = (ServerMPPlayer)damageEvent.Attacker;
            ServerMPPlayer assistant = (ServerMPPlayer)damageEvent.AttackerAssistant;
            ServerMPPlayer killed    = (ServerMPPlayer)damageEvent.Attacked;
            string         item      = damageEvent.Cause;

            if (killer == killed)
            {
                // Kill was actually suicide
                killer = null;
            }

            // Killer only gets credit within 6.5s of players death
            if (Environment.TickCount - damageEvent.DamagedAt >= 6500)
            {
                killer = null;
            }
            // Assistant only gets credit within 8s of players death
            if (Environment.TickCount - damageEvent.AttackerAssistedAt >= 8000)
            {
                assistant = null;
            }

            // Get network players
            string        leftName = "", rightName = "", assistantName = "";
            NetworkPlayer killerNetPlayer = null, killedNetPlayer = null, assistantNetPlayer = null;

            if (killer != null && netPlayerComponent.TryGetPlayer(killer.StateInfo.Owner, out killerNetPlayer))
            {
                leftName = killerNetPlayer.Name;
            }
            if (killed != null && netPlayerComponent.TryGetPlayer(killed.StateInfo.Owner, out killedNetPlayer))
            {
                rightName = killedNetPlayer.Name;
            }
            if (assistant != null && netPlayerComponent.TryGetPlayer(assistant.StateInfo.Owner, out assistantNetPlayer))
            {
                assistantName = assistantNetPlayer.Name;
            }

            // Announce feed item
            AddFeedItem(
                leftName, assistantName,
                killer != null ? World.GetTeamColor(killer.Team) : Color.White,
                item,
                rightName, killed != null ? World.GetTeamColor(killed.Team) : Color.White);

            // Notify gamemode
            currentGamemode.OnPlayerKilled(killer, killerNetPlayer, assistant, assistantNetPlayer, killed, killedNetPlayer, item);

            // Debug
            if (killer != null)
            {
                if (assistant != null)
                {
                    DashCMD.WriteLine("[MatchScreen] '{0} + {1} [ {2} ] {3}'", leftName, assistantName, item, rightName);
                }
                else
                {
                    DashCMD.WriteLine("[MatchScreen] '{0} [ {1} ] {2}'", leftName, item, rightName);
                }
            }
            else
            {
                DashCMD.WriteLine("[MatchScreen] '[ {0} ] {1}'", item, rightName);
            }
        }
Пример #28
0
        public void LoadServerTerrain(NetBuffer data)
        {
            SetTerrain(new FixedTerrain(Renderer));

            DashCMD.WriteStandard("[MPWorld] Loading server world...");

            ushort numChunks    = data.ReadUInt16();
            Chunk  currentChunk = null;
            int    blockI       = 0;
            int    ci           = 0;

            while (ci <= numChunks && data.Position < data.Data.Length)
            {
                byte type = data.ReadByte();

                if (type == 0) // New Chunk
                {
                    int ix = data.ReadInt16();
                    int iy = data.ReadInt16();
                    int iz = data.ReadInt16();

                    if (currentChunk != null)
                    {
                        currentChunk.BakeColors();
                    }

                    IndexPosition ipos = new IndexPosition(ix, iy, iz);
                    currentChunk = new Chunk(Terrain, ipos, AceOfSpades.Terrain.ChunkToWorldCoords(ipos));
                    currentChunk.InitBlocks(Chunk.HSIZE, Chunk.VSIZE, Chunk.HSIZE);
                    currentChunk.State   = ChunkState.Unlit;
                    currentChunk.IsDirty = true;
                    Terrain.Chunks.TryAdd(ipos, currentChunk);

                    blockI = 0;
                    ci++;
                }
                else if (type == 1) // Block section
                {
                    ushort  numBlocks = data.ReadUInt16();
                    byte    d = data.ReadByte();
                    Nybble2 n = new Nybble2(d);
                    byte    r, g, b;
                    byte    mat = n.Lower;

                    if (mat == Block.CUSTOM.Material)
                    {
                        r = data.ReadByte();
                        g = data.ReadByte();
                        b = data.ReadByte();
                    }
                    else
                    {
                        if (mat == Block.GRASS.Material)
                        {
                            r = Block.GRASS.R;
                            g = Block.GRASS.G;
                            b = Block.GRASS.B;
                        }
                        else
                        {
                            r = Block.STONE.R;
                            g = Block.STONE.G;
                            b = Block.STONE.B;
                        }
                    }

                    Block block = new Block(n, r, g, b);

                    for (int i = 0; i < numBlocks; i++)
                    {
                        int z = blockI % Chunk.HSIZE;
                        int y = (blockI / Chunk.HSIZE) % Chunk.VSIZE;
                        int x = blockI / (Chunk.VSIZE * Chunk.HSIZE);

                        currentChunk.Blocks[z, y, x] = block;
                        blockI++;
                    }
                }
            }

            if (currentChunk != null)
            {
                currentChunk.BakeColors();
            }

            Terrain.CreatedFromFile();
        }
Пример #29
0
        public PlayerTransform RollbackTransform(int timeFrame, bool suppressLog = false)
        {
            PlayerTransform pt1 = null, pt2 = null;

            for (int i = 0; i < playerTransforms.Count; i++)
            {
                PlayerTransform pt      = playerTransforms[i];
                int             tickOff = Math.Abs(pt.Ticks - timeFrame);

                // Don't process anything more than a second off
                if (tickOff > 1000)
                {
                    continue;
                }

                if (pt1 == null || tickOff < Math.Abs(pt1.Ticks - timeFrame))
                {
                    pt1 = pt;
                }
            }

            for (int i = 0; i < playerTransforms.Count; i++)
            {
                PlayerTransform pt = playerTransforms[i];
                if (pt == pt1)
                {
                    continue;
                }

                int tickOff = Math.Abs(pt.Ticks - timeFrame);

                // Don't process anything more than a second off
                if (tickOff > 1000)
                {
                    continue;
                }

                if (pt2 == null || tickOff < Math.Abs(pt2.Ticks - timeFrame))
                {
                    pt2 = pt;
                }
            }

            if (pt1 != null && pt2 != null)
            {
                if (pt2.Ticks > pt1.Ticks)
                {
                    PlayerTransform temp = pt2;
                    pt2 = pt1;
                    pt1 = temp;
                }

                // Interpolate
                float timeI = pt1.Ticks == pt2.Ticks ? 0f : (float)(timeFrame - pt2.Ticks) / (pt1.Ticks - pt2.Ticks);
                //timeI = MathHelper.Clamp(timeI, 0f, 1f);

                if (DashCMD.GetCVar <bool>("sv_hitboxes") && !suppressLog)
                {
                    DashCMD.WriteImportant("[RB] Rolling back transform by {0}%. [timeFrame: {3}, pt2: {1}, pt1: {2}]",
                                           timeI * 100, pt2.Ticks, pt1.Ticks, timeFrame);
                }

                Vector3 position = Interpolation.Lerp(pt2.Position, pt1.Position, timeI);
                float   camPitch = Interpolation.LerpDegrees(pt2.CameraPitch, pt1.CameraPitch, timeI);
                float   camYaw   = Interpolation.LerpDegrees(pt2.CameraYaw, pt1.CameraYaw, timeI);

                return(new PlayerTransform(position, camYaw, camPitch, timeFrame));
            }
            else if (pt1 != null && pt2 == null)
            {
                // Take pt1
                return(pt1);
            }
            else
            {
                // Take current
                return(new PlayerTransform(Transform.Position, camera.Yaw, camera.Pitch, Environment.TickCount));
            }
        }
        public override void Update(float deltaTime)
        {
            // Complete handshake when terrain is done
            if (handshake != null && World.Terrain != null && World.Terrain.UnfinishedChunks == 0)
            {
                handshake.Complete();
            }

            // Toggle the menu via user input
            if (Input.GetControlDown("ToggleMenu"))
            {
                chat.Unfocus();
                menu.Visible = !menu.Visible;
                ToggleFPSUserInput(!menu.Visible);
            }

            // Toggle chat focus
            if (Input.GetControlDown("Chat"))
            {
                ToggleFPSUserInput(false);
                chat.Focus();
            }

            // Show the leaderboard via user input
            if (leaderboard != null)
            {
                leaderboard.Visible = Input.GetControl("ShowLeaderboard");
            }

            // Read terrain changes
            if (client != null && snapshotComponent.WorldSnapshot != null)
            {
                TerrainDeltaSnapshot terrainDelta = snapshotComponent.WorldSnapshot.TerrainSnapshot;

                // Simply apply each change sent by the server to the specified chunks.
                foreach (TerrainDeltaChange change in terrainDelta.ReceivedChanges)
                {
                    Chunk chunk;
                    if (World.Terrain.Chunks.TryGetValue(change.ChunkIndex, out chunk))
                    {
                        if (change.Block.Material == Block.AIR.Material)
                        {
                            chunk.RemoveBlock(change.BlockIndex);
                        }
                        else
                        {
                            chunk.SetBlock(change.Block, change.BlockIndex);
                        }
                    }
                    else
                    {
                        DashCMD.WriteError("[AOSNet - TerrainDelta] Received update for non-existant chunk! IPos: {0}",
                                           change.ChunkIndex);
                    }
                }

                // Clear the changes so we don't apply them twice
                terrainDelta.ReceivedChanges.Clear();
            }

            // Update the world
            if (World != null)
            {
                World.Update(deltaTime);
            }

            // Update the gamemode
            if (currentGamemode != null && currentGamemode.IsActive)
            {
                currentGamemode.Update(deltaTime);
            }

            // Update the hud
            hud.Update(deltaTime);

            // Run down the message timer if shown
            if (messageTime > 0)
            {
                messageTime -= deltaTime;
            }
            if (announcementTime > 0)
            {
                announcementTime -= deltaTime;
            }
        }