Exemplo n.º 1
0
        protected Uniform GetUniform(string name)
        {
            Uniform uniform;

            // See if a quick link exists
            if (uniforms.TryGetValue(name, out uniform))
            {
                return(uniform);
            }
            else
            {
                // Return the uniform id of the effect's program
                int location = GL.GetUniformLocation(Program.ProgramId, name);
                if (location == -1)
                {
                    string msg = String.Format("Uniform {0} does not exist in the shader {1}", name, Name);
                    if (ThrowOnUnknownUniform)
                    {
                        throw new GPUResourceException(msg);
                    }
                    else
                    {
                        DashCMD.WriteWarning(msg);
                    }
                }
                // Add a quick link
                uniform = new Uniform(location);
                uniforms.Add(name, uniform);
                return(uniform);
            }
        }
Exemplo n.º 2
0
        public void Update(float deltaTime)
        {
            // Update internal messenger
            base.Update();

            // Read packets
            for (int i = 0; i < 1000 && AvailablePackets > 0; i++)
            {
                NetInboundPacket packet = ReadPacket();

                if (packet.Position >= packet.Length)
                {
                    DashCMD.WriteError("[AOSServer] 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("[AOSServer] Received unknown custom packet {0}, from {1}",
                                             type, packet.Sender);
                    }
                }
            }

            // Update each component
            foreach (NetComponent c in components.Values)
            {
                c.Update(deltaTime);
            }
        }
        public MasterRenderer(int screenWidth, int screenHeight, GraphicsOptions options = null)
        {
            Instance    = this;
            GFXSettings = options ?? new GraphicsOptions();

            ScreenWidth  = screenWidth;
            ScreenHeight = screenHeight;

            if (GLVersion == 0)
            {
                int major = GL.GetInteger(GetPName.MajorVersion);
                int minor = GL.GetInteger(GetPName.MinorVersion);
                GLVersion = major + minor * 0.1f;

                //if (major < 4)
                //    throw new Exception(string.Format("OpenGL 4.0 or later is required to run this game. This machine is running: {0}", GLVersion));
                if (major < 4)
                {
                    DashCMD.WriteWarning("[OpenGL] OpenGL 4.0 or later is required to run this game properly!. This machine is running: {0}", GLVersion);
                }
                else
                {
                    DashCMD.WriteLine("[OpenGL] Version: {0}", ConsoleColor.DarkGray, GLVersion);
                }
            }

            GLError.Begin();

            Camera camera = new Camera(this);

            camera.MakeActive();

            Lights = new LightList();

            Texture.Blank = GLoader.LoadBlankTexture(Color.White);

            Renderer3Ds = new Dictionary <Type, Renderer3D>();
            Renderer2Ds = new Dictionary <Type, Renderer2D>();

            Gui     = new GuiRenderer(this);
            Sprites = new SpriteRenderer(this);
            Sky     = new SkyboxRenderer(this);

            AddRenderer(Gui);
            AddRenderer(Sprites);

            activePipeline = new ForwardPipeline(this);

            StateManager.Enable(EnableCap.CullFace);
            StateManager.Enable(EnableCap.DepthTest);

            GL.CullFace(CullFaceMode.Back);

            ErrorCode mInitError = GLError.End();

            if (mInitError != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Uncaught master renderer init opengl error: {0}", mInitError));
            }
        }
        public override bool HandlePacket(NetInboundPacket packet, CustomPacketType type)
        {
            if (type == CustomPacketType.Snapshot)
            {
                ushort pid = packet.ReadUInt16();
                NetConnectionSnapshotState connState;
                if (ConnectionStates.TryGetValue(packet.Sender, out connState))
                {
                    //connState.GotPacket = true;
                    if (connState.MeasuringRTT)
                    {
                        connState.MeasuringRTT  = false;
                        connState.RoundTripTime = Interpolation.Linear(connState.RoundTripTime,
                                                                       connState.RTT_TimeSinceLastSend, 0.15f);
                    }

                    ushort ppid = connState.LastInboundSnapshotId;
                    connState.LastInboundSnapshotId = pid;
                    if (pid <= ppid && pid != 0)
                    {
                        DashCMD.WriteWarning("[SnapshotNC] Dropping late client snapshot...");
                        return(true);
                    }

                    snapshotSystem.OnInbound(packet);
                    charSnapshotSystem.OnServerInbound(packet, connState);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
        public static GraphicsOptions Init(ConfigSection graphicsSection)
        {
            ConfigSection presets = graphicsSection.GetSection("Presets");

            if (presets == null)
            {
                DashCMD.WriteError("[game.cfg - GraphicsOptions] Graphics.Presets was not found!");
                return(null);
            }

            string usedPreset = graphicsSection.GetString("preset");

            if (usedPreset == null)
            {
                DashCMD.WriteError("[game.cfg - GraphicsOptions] Graphics.preset was not found!");
                return(null);
            }

            foreach (DictionaryEntry pair in presets.Children)
            {
                ConfigSection preset = pair.Value as ConfigSection;
                if (preset == null)
                {
                    DashCMD.WriteWarning("[game.cfg - GraphicsOptions] Invalid token '{0}' in Graphics.Presets", pair.Key);
                    continue;
                }

                bool       fxaa       = preset.GetBoolean("fxaa") ?? false;
                bool       shadows    = preset.GetBoolean("shadows") ?? false;
                int        shadowRes  = preset.GetInteger("shadowRes") ?? 1;
                int        pcfSamples = preset.GetInteger("shadowPCF") ?? 1;
                FogQuality fogQuality = preset.GetEnum <FogQuality>("fogQuality") ?? FogQuality.Low;

                GraphicsOptions options = new GraphicsOptions()
                {
                    ApplyFXAA        = fxaa,
                    RenderShadows    = shadows,
                    ShadowResolution = shadowRes,
                    ShadowPCFSamples = pcfSamples,
                    FogQuality       = fogQuality
                };

                allOptions.Add((string)pair.Key, options);
            }

            GraphicsOptions usedOptions;

            if (allOptions.TryGetValue(usedPreset, out usedOptions))
            {
                DashCMD.WriteStandard("[game.cfg - GraphicsOptions] Using preset '{0}'", usedPreset);
                return(usedOptions);
            }
            else
            {
                DashCMD.WriteError("[game.cfg - GraphicsOptions] Specified preset '{0}' was not found!", usedPreset);
                return(null);
            }
        }
Exemplo n.º 6
0
        public override bool HandlePacket(NetInboundPacket packet, CustomPacketType type)
        {
            if (type == CustomPacketType.Snapshot)
            {
                if (measuringRTT)
                {
                    rtt          = Interpolation.Linear(rtt, timeSinceSend, 0.15f);
                    measuringRTT = false;
                }

                gotPacket = true;

                ushort pid = packet.ReadUInt16();

                if (pid <= lastServerPId && pid != 0)
                {
                    DashCMD.WriteWarning("[SnapshotNC] Dropping late server snapshot...");
                    return(true);
                }

                snapshotSystem.OnInbound(packet);

                ushort snapshotLength = packet.ReadUInt16();

                if (WorldSnapshot != null)
                {
                    // Read the snapshot
                    WorldSnapshot.Deserialize(packet);

                    // Update players
                    charSnapshotSystem.OnClientInbound(WorldSnapshot);

                    // Invoke event
                    if (OnWorldSnapshotInbound != null)
                    {
                        OnWorldSnapshotInbound(this, WorldSnapshot);
                    }
                }
                else
                {
                    packet.Position += snapshotLength;
                    DashCMD.WriteWarning("[SnapshotNC] Received snapshot before worldsnapshot was intialized!");
                }

                lastServerPId = pid;

                return(true);
            }
            else
            {
                return(false);
            }
        }
        protected internal override void OnAddedToScene()
        {
            PhysicsEngine physics = Scene.GetComponent <PhysicsEngine>();

            if (physics != null)
            {
                physics.AddPhysicsBody(this);
            }
            else
            {
                DashCMD.WriteWarning("[PhysicsBodyComponent] GameObject with physics body added to scene without physics engine!");
            }

            base.OnAddedToScene();
        }
        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;
            }
        }
Exemplo n.º 9
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();
        }
        /// <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(); }
            }
        }
Exemplo n.º 11
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();
        }
Exemplo n.º 12
0
        public static TextureMesh LoadOBJ(string filePath, BufferUsageHint usageHint = BufferUsageHint.StaticDraw)
        {
            string finalPath = GLoader.GetContentRelativePath(filePath);

            string           line;
            List <OBJVertex> vertices = new List <OBJVertex>();
            List <Vector2>   uvs      = new List <Vector2>();
            List <Vector3>   normals  = new List <Vector3>();
            List <uint>      indexes  = new List <uint>();

            try
            {
                using (StreamReader sr = new StreamReader(File.Open(finalPath, FileMode.Open, FileAccess.Read)))
                {
                    // Read Part one of the OBJ file (till the f's start)
                    int i = 0;
                    while (true)
                    {
                        // Get the current line
                        line = sr.ReadLine();

                        // Split it by spaces
                        string[] currentLine = line.Split(' ');

                        // Handle Vertex
                        if (line.StartsWith("v "))
                        {
                            float x, y, z;
                            if (!float.TryParse(currentLine[1], out x))
                            {
                                LogFloatParseError(i, line);
                            }
                            if (!float.TryParse(currentLine[2], out y))
                            {
                                LogFloatParseError(i, line);
                            }
                            if (!float.TryParse(currentLine[3], out z))
                            {
                                LogFloatParseError(i, line);
                            }

                            vertices.Add(new OBJVertex(vertices.Count, new Vector3(x, y, z)));
                        }
                        // Handle UV
                        else if (line.StartsWith("vt "))
                        {
                            float x, y;
                            if (!float.TryParse(currentLine[1], out x))
                            {
                                LogFloatParseError(i, line);
                            }
                            if (!float.TryParse(currentLine[2], out y))
                            {
                                LogFloatParseError(i, line);
                            }

                            uvs.Add(new Vector2(x, y));
                        }
                        // Handle Normal
                        else if (line.StartsWith("vn "))
                        {
                            float x, y, z;
                            if (!float.TryParse(currentLine[1], out x))
                            {
                                LogFloatParseError(i, line);
                            }
                            if (!float.TryParse(currentLine[2], out y))
                            {
                                LogFloatParseError(i, line);
                            }
                            if (!float.TryParse(currentLine[3], out z))
                            {
                                LogFloatParseError(i, line);
                            }

                            normals.Add(new Vector3(x, y, z));
                        }
                        // Handle Index Start
                        else if (line.StartsWith("f "))
                        {
                            break;
                        }
                        else if (!line.StartsWith("# "))
                        {
                            DashCMD.WriteWarning("Unrecognized OBJ line: {0}", line);
                        }

                        i++;
                    }

                    // Read the indexes
                    while (line != null)
                    {
                        // Skip non-index lines
                        if (!line.StartsWith("f "))
                        {
                            line = sr.ReadLine();
                            continue;
                        }

                        // Split the current line by spaces
                        string[] currentLine = line.Split(' ');
                        // Get each vertex
                        string[] vertex1 = currentLine[1].Split('/');
                        string[] vertex2 = currentLine[2].Split('/');
                        string[] vertex3 = currentLine[3].Split('/');

                        // Process each vertex to the arrays
                        ProcessVertex(vertex1, vertices, indexes);
                        ProcessVertex(vertex2, vertices, indexes);
                        ProcessVertex(vertex3, vertices, indexes);

                        // Move to the next line
                        // This is at the end because the first line this loop will read,
                        // will be the previous one that broke out of the part 1 loop.
                        line = sr.ReadLine();
                    }
                }
            }
            catch (IOException)
            {
                // TEMP:
                throw;
            }

            // Remove and unused vertices
            RemoveUnusedVertices(vertices);

            // Finalize
            float[] finalVertices = new float[vertices.Count * 3];
            float[] finalUvs      = new float[vertices.Count * 2];
            float[] finalNormals  = new float[vertices.Count * 3];

            float furthest = ConvertDataToArrays(vertices, uvs, normals, finalVertices, finalUvs, finalNormals);

            uint[] finalIndexes = indexes.ToArray();

            // Load mesh to a VAO
            return(new TextureMesh(usageHint, finalVertices, finalIndexes, finalUvs, finalNormals));
        }