Exemplo n.º 1
0
        static void LoadGameDll(string BasePath)
        {
            BasePath = Path.Combine(BasePath, "Game.dll");

            Assembly GameAssembly = Reflect.LoadAssembly(BasePath);

            Type[] GameImplementations = Reflect.GetAllImplementationsOf(GameAssembly, typeof(LibTechGame)).ToArray();

            if (GameImplementations.Length == 0)
            {
                GConsole.WriteLine("No game implementations found in " + BasePath);
                Environment.Exit(0);
            }
            else if (GameImplementations.Length > 1)
            {
                GConsole.WriteLine("Too many game implementations in " + BasePath);
                Environment.Exit(0);
            }

            AppDomain.CurrentDomain.AssemblyResolve += (S, E) => TryLoadAssembly(E.Name, BasePath);
            Importers.RegisterAll(GameAssembly);

            Game = (LibTechGame)Activator.CreateInstance(GameImplementations[0]);
            Game.Load();
        }
Exemplo n.º 2
0
        static void Update(float Dt)
        {
            Events.Poll();

            Game.Update(Dt);
            GConsole.Update();
        }
Exemplo n.º 3
0
        static void DrawGUI(float Dt)
        {
            Game.DrawGUI(Dt);

            NuklearAPI.Frame(() => {
                GConsole.NuklearDraw(10, 10);
            });
        }
Exemplo n.º 4
0
        internal static void FatalError(string Msg)
        {
            GConsole.WriteLine(Msg);

            while (true)
            {
                Thread.Sleep(10);
            }
        }
Exemplo n.º 5
0
        static void Update(float Dt)
        {
            Events.Poll();
            Engine.Time = TimeStopwatch.ElapsedMilliseconds / 1000.0f;

            Engine.UI.Update(Dt);
            Engine.Game.Update(Dt);
            Engine.Map?.Update(Dt);
            GConsole.Update();
        }
Exemplo n.º 6
0
        private static void OnChanged(object S, FileSystemEventArgs E)
        {
            GConsole.WriteLine("File changed: {0}", E.FullPath);

            FileWatchHandle H = Watch(E.FullPath);

            if (H != null)
            {
                H.HasChanged = true;
            }
        }
Exemplo n.º 7
0
        static void RunGame()
        {
            InitConsole();

            FileWatcher.Init("content");
            Importers.RegisterAll(Reflect.GetExeAssembly());

            Engine.GUI = new libGUI();

            Engine.Window              = new RenderWindow(Engine.WindowWidth, Engine.WindowHeight, "libTech", Engine.WindowResizable);
            Engine.Window.OnMouseMove += Engine.GUI.OnMouseMove;
            Engine.Window.OnKey       += OnKey;
            Engine.Window.OnChar      += Engine.GUI.OnChar;

            Engine.GUI.Init(Engine.Window, new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "content/shaders/gui.vert"), new ShaderStage(ShaderType.FragmentShader, "content/shaders/gui.frag")));

            GConsole.Init();
            GConsole.WriteLine("Running {0}", RenderAPI.Renderer, RenderAPI.Version);

            GConsole.Color = FishGfx.Color.Orange;
            foreach (var DllName in FailedToLoadDLLs)
            {
                GConsole.WriteLine("Failed to load '{0}'", DllName);
            }
            GConsole.Color = FishGfx.Color.White;

            // Graphics init
            Gfx.ShadersDirectory = "content/shaders";
            //Gfx.Line3D = DefaultShaders.Line3D;
            //Gfx.Point3D = DefaultShaders.Point3D;
            //Gfx.Default3D = DefaultShaders.DefaultColor3D;

            // Camera init
            Engine.Camera2D = new Camera();
            Engine.Camera2D.SetOrthogonal(0, 0, Engine.Window.WindowWidth, Engine.Window.WindowHeight);

            Engine.Camera3D = new Camera();
            Engine.Camera3D.SetPerspective(Engine.Window.WindowWidth, Engine.Window.WindowHeight);

            LoadGameDll(Engine.GamePath);

            float Dt = 0;

            while (!Engine.Window.ShouldClose)
            {
                Update(Dt);
                Draw(Dt);
                Thread.Sleep(0);
            }
        }
Exemplo n.º 8
0
        static void InitConsole()
        {
            Engine.GamePath = ConVar.Register("game", "basegame", ConVarType.Replicated | ConVarType.Init);
            //Engine.GamePath = ConVar.Register("game", "legprocessor", ConVarType.Replicated | ConVarType.Init);

            Engine.MaxFPS       = ConVar.Register("maxfps", 60, ConVarType.Archive);
            Engine.WindowWidth  = ConVar.Register("width", 1366, ConVarType.Archive);
            Engine.WindowHeight = ConVar.Register("height", 768, ConVarType.Archive);

            //Engine.WindowWidth = CVar.Register("width", 800, CVarType.Archive);
            //Engine.WindowHeight = CVar.Register("height", 600, CVarType.Archive);

            Engine.WindowBorderless = ConVar.Register("borderless", false, ConVarType.Archive);
            Engine.WindowResizable  = ConVar.Register("resizable", false, ConVarType.Archive);
            Engine.ShowFPS          = ConVar.Register("showfps", true, ConVarType.Archive);

            Engine.MSAA = ConVar.Register("msaa", 32, ConVarType.Archive);

            Engine.SourceGameDirs = ConVar.Register("source_game_dirs", "C:/Program Files (x86)/Steam/steamapps/common/GarrysMod", ConVarType.Archive);
            Engine.DebugDraw      = ConVar.Register("debugdraw", true, ConVarType.Cheat);

            // Parse all arguments and set CVars
            foreach (var Arg in ArgumentParser.All)
            {
                switch (Arg.Key)
                {
                case "console":
                    GConsole.Open = true;
                    break;

                case "game":
                    Engine.GamePath.Value = Arg.Value.Last();
                    break;

                default:
                    GConsole.Error("Invalid switch '{0}' with value '{1}'", Arg.Key, Arg.Value);
                    break;
                }
            }

            foreach (var CVar in ConVar.GetAll())
            {
                GConsole.WriteLine(CVar);
            }

            ConCmd.Register("exit", (Argv) => Environment.Exit(0));
            GConsole.RegisterAlias("quit", "exit");
        }
Exemplo n.º 9
0
        static void InitConsole()
        {
            Engine.GamePath = ConVar.Register("game", "basegame", ConVarType.Replicated | ConVarType.Init);
            //Engine.GamePath = ConVar.Register("game", "legprocessor", ConVarType.Replicated | ConVarType.Init);

            Engine.WindowWidth  = ConVar.Register("width", 1366, ConVarType.Archive);
            Engine.WindowHeight = ConVar.Register("height", 768, ConVarType.Archive);

            //Engine.WindowWidth = CVar.Register("width", 800, CVarType.Archive);
            //Engine.WindowHeight = CVar.Register("height", 600, CVarType.Archive);

            Engine.WindowBorderless = ConVar.Register("borderless", false, ConVarType.Archive);
            Engine.WindowResizable  = ConVar.Register("resizable", false, ConVarType.Archive);

            // Parse all arguments and set CVars
            foreach (var Arg in ArgumentParser.All)
            {
                switch (Arg.Key)
                {
                case "console":
                    GConsole.Open = true;
                    break;

                case "game":
                    Engine.GamePath.Value = Arg.Value.Last();
                    break;

                default:
                    GConsole.Error("Invalid switch '{0}' with value '{1}'", Arg.Key, Arg.Value);
                    break;
                }
            }

            foreach (var CVar in ConVar.GetAll())
            {
                GConsole.WriteLine(CVar);
            }

            ConCmd.Register("exit", (Argv) => Environment.Exit(0));
            GConsole.RegisterAlias("quit", "exit");
        }
Exemplo n.º 10
0
        static void LoadGameDll(string BasePath)
        {
            string   GameDllPath   = Path.Combine(BasePath, "Game.dll");
            Assembly GameAssembly  = Assembly.GetExecutingAssembly();
            bool     LoadImporters = false;

            if (File.Exists(GameDllPath))
            {
                GameAssembly  = Reflect.LoadAssembly(GameDllPath);
                LoadImporters = true;
            }

            Type[] GameImplementations = Reflect.GetAllImplementationsOf(GameAssembly, typeof(LibTechGame)).ToArray();

            if (GameImplementations.Length == 0)
            {
                GConsole.WriteLine("No game implementations found in " + GameDllPath);
                Environment.Exit(0);
            }
            else if (GameImplementations.Length > 1)
            {
                GConsole.WriteLine("Too many game implementations in " + GameDllPath);
                Environment.Exit(0);
            }

            AppDomain.CurrentDomain.AssemblyResolve += (S, E) => TryLoadAssembly(E.Name, GameDllPath);

            if (LoadImporters)
            {
                Importers.RegisterAll(GameAssembly);
            }

            Entity.LoadAllTypes();

            Engine.Game = (LibTechGame)Activator.CreateInstance(GameImplementations[0]);
            Engine.Game.Load();
        }
Exemplo n.º 11
0
        static void RunGame()
        {
            TimeStopwatch = Stopwatch.StartNew();
            InitConsole();

            Engine.VFS = new VirtualFileSystem(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            Engine.VFS.Mount("/content/", "./content");
            Engine.VFS.Mount("/materials/", "C:/Program Files (x86)/Steam/steamapps/common/GarrysMod/garrysmod/addons/quake_3_gmod_160207505/materials");

            string[] SourceGameDirs = Engine.SourceGameDirs.Value.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Where(Pth => Directory.Exists(Pth)).ToArray();

            if (SourceGameDirs.Length > 0)
            {
                foreach (var GameDir in SourceGameDirs)
                {
                    Engine.VFS.GetSourceProvider().AddRoot(GameDir);
                }
            }

            if (Directory.Exists(Path.Combine(Engine.GamePath, "content")))
            {
                Engine.VFS.Mount("/content/", Path.Combine(Engine.GamePath, "content"));
            }

            List <string> ZipResources = new List <string>();

            ZipResources.AddRange(Engine.VFS.GetFiles("/content/").Where(P => Path.GetExtension(P) == ".pk3" || Path.GetExtension(P) == ".zip"));

            foreach (var ZipResource in ZipResources)
            {
                Engine.VFS.MountArchive("/content/", ZipResource);
            }

            FileWatcher.Init("content");
            Importers.RegisterAll(Reflect.GetExeAssembly());

            Engine.GUI = new NuklearGUI();

            Engine.Window              = new RenderWindow(Engine.WindowWidth, Engine.WindowHeight, "libTech", Engine.WindowResizable);
            Engine.Window.OnMouseMove += Engine.GUI.OnMouseMove;
            Engine.Window.OnKey       += OnKey;
            Engine.Window.OnChar      += Engine.GUI.OnChar;

            RenderDoc.Init();

            GConsole.Init();
            GConsole.WriteLine("Running {0}", RenderAPI.Renderer, RenderAPI.Version);

            string ExtensionsFile = "extensions.txt";

            if (File.Exists(ExtensionsFile))
            {
                File.Delete(ExtensionsFile);
            }

            File.WriteAllLines(ExtensionsFile, RenderAPI.Extensions);
            EngineRenderer.Init();

            Engine.GUI.Init(Engine.Window, new ShaderProgram(new ShaderStage(ShaderType.VertexShader, "content/shaders/gui.vert"), new ShaderStage(ShaderType.FragmentShader, "content/shaders/gui.frag")));
            Engine.UI = new libGUI(Engine.Window);

            DbgDraw.Init();
            Lua.Init();

            GConsole.Color = Color.Orange;
            foreach (var DllName in FailedToLoadDLLs)
            {
                GConsole.WriteLine("Failed to load '{0}'", DllName);
            }
            GConsole.Color = Color.White;

            // Graphics init
            Gfx.ShadersDirectory = "content/shaders";
            //Gfx.Line3D = DefaultShaders.Line3D;
            //Gfx.Point3D = DefaultShaders.Point3D;
            //Gfx.Default3D = DefaultShaders.DefaultColor3D;

            // Camera init
            Engine.Camera2D = new Camera();
            Engine.Camera2D.SetOrthogonal(0, 0, Engine.Window.WindowWidth, Engine.Window.WindowHeight);

            Engine.Camera3D = new Camera();
            Engine.Camera3D.SetPerspective(Engine.Window.WindowWidth, Engine.Window.WindowHeight, FarPlane: 16000);

            LoadGameDll(Engine.GamePath);

            Stopwatch SWatch = Stopwatch.StartNew();

            int MaxFPS = Engine.MaxFPS;

            if (MaxFPS <= 0)
            {
                MaxFPS = 900;
            }

            float FrameCap = 1.0f / MaxFPS;
            float Dt       = 1.0f / 60.0f;

            while (!Engine.Window.ShouldClose)
            {
                Engine.FrameTime.Push(Dt);

                Update(Dt);
                EngineRenderer.Draw(Dt);

                // TODO: Move frame cap somewhere else
                while ((SWatch.ElapsedMilliseconds / 1000.0f) < FrameCap)
                {
                    Thread.Sleep(0);
                }

                Dt = SWatch.ElapsedMilliseconds / 1000.0f;
                SWatch.Restart();
            }
        }
Exemplo n.º 12
0
        static void CreateContext(/*params string[] RequiredExtensions*/)
        {
            GConsole.WriteLine("Initializing OpenGL");

#if DEBUG
            Khronos.KhronosApi.Log += (S, E) => {
                if (E.Name == "glGetError")
                {
                    return;
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("OpenGL> {0}", string.Format("{0}({1}) = {2}", E.Name, string.Join(", ", E.Args), E.ReturnValue ?? "null"));
                Console.ResetColor();
            };
            Khronos.KhronosApi.LogEnabled = false;            //*/
#endif

            GConsole.WriteLine("Initializing GLFW");
            Glfw.ConfigureNativesDirectory("native/glfw3_64");
            if (!Glfw.Init())
            {
                FatalError("Could not initialize GLFW");
            }

            Glfw.SetErrorCallback((Err, Msg) => {
                FatalError("GLFW({0}) {1}", Err, Msg);
            });

            Width  = CVar.GetInt("width", 800);
            Height = CVar.GetInt("height", 600);

            Glfw.WindowHint(Glfw.Hint.Resizable, CVar.GetBool("resizable"));

            //Glfw.WindowHint(Glfw.Hint.ClientApi, Glfw.ClientApi.None);
            Glfw.WindowHint(Glfw.Hint.ClientApi, Glfw.ClientApi.OpenGL);
            Glfw.WindowHint(Glfw.Hint.ContextCreationApi, Glfw.ContextApi.Native);
            Glfw.WindowHint(Glfw.Hint.Doublebuffer, CVar.GetBool("gl_doublebuffer"));
            Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, CVar.GetInt("gl_major"));
            Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, CVar.GetInt("gl_minor"));

            Glfw.WindowHint(Glfw.Hint.Samples, CVar.GetInt("gl_samples"));
            Glfw.WindowHint(Glfw.Hint.OpenglForwardCompat, CVar.GetBool("gl_forwardcompat"));
            Glfw.WindowHint(Glfw.Hint.OpenglProfile, Glfw.OpenGLProfile.Core);
#if DEBUG
            Glfw.WindowHint(Glfw.Hint.OpenglDebugContext, true);
#endif

            GConsole.WriteLine("Creating window");
            Window = Glfw.CreateWindow(Width, Height, "libTech");
            if (!Window)
            {
                FatalError("Could not create window({0}x{1})", Width, Height);
            }

            Gl.Initialize();
            Glfw.MakeContextCurrent(Window);

            /*bool AllSupported = true;
             *
             * for (int i = 0; i < RequiredExtensions.Length; i++) {
             *      if (!Glfw.ExtensionSupported(RequiredExtensions[i])) {
             *              GConsole.WriteLine("{0} not supported", RequiredExtensions[i]);
             *              AllSupported = false;
             *      }
             * }
             *
             * if (!AllSupported)
             *      while (true)
             *              Thread.Sleep(10);*/

#if DEBUG
            Gl.DebugMessageCallback((Src, DbgType, ID, Severity, Len, Buffer, UserPtr) => {
                if (Severity == Gl.DebugSeverity.Notification)
                {
                    return;
                }

                GConsole.WriteLine("OpenGL {0} {1} {2}, {3}", Src, DbgType, ID, Severity);
                GConsole.WriteLine(Encoding.ASCII.GetString((byte *)Buffer, Len));

                if ((/*Severity == Gl.DebugSeverity.Medium ||*/ Severity == Gl.DebugSeverity.High) && Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }, IntPtr.Zero);

            Gl.Enable((EnableCap)Gl.DEBUG_OUTPUT);
            Gl.Enable((EnableCap)Gl.DEBUG_OUTPUT_SYNCHRONOUS);
#endif

            GConsole.WriteLine("{0}, {1}", Gl.GetString(StringName.Vendor), Gl.GetString(StringName.Renderer));
            GConsole.WriteLine("OpenGL {0}", Gl.GetString(StringName.Version));
            GConsole.WriteLine("GLSL {0}", Gl.GetString(StringName.ShadingLanguageVersion));

            Gl.ClearColor(69 / 255.0f, 112 / 255.0f, 56 / 255.0f, 1.0f);

            // F**k the police
            Gl.Enable((EnableCap)Gl.DEPTH_CLAMP);
            Gl.Enable(EnableCap.Blend);
            //Gl.VERTEX_PROGRAM_POINT_SIZE;
            Gl.Enable((EnableCap)Gl.VERTEX_PROGRAM_POINT_SIZE);
            //Gl.Enable((EnableCap)Gl.SAMPLE_SHADING);
            //Gl.Enable(EnableCap.FramebufferSrgb);

            Gl.BlendEquationSeparate(BlendEquationMode.FuncAdd, BlendEquationMode.FuncAdd);
            Gl.BlendFuncSeparate(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha, BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);

            //Gl.BlendEquation(BlendEquationMode.FuncAdd);
            //Gl.BlendFunc(BlendingFactor.One, BlendingFactor.One);

            ShaderProgram.LoadDefaultShaders();
        }
Exemplo n.º 13
0
        internal static void Init()
        {
            /*ConsoleWindow = new Window();
             * ConsoleWindow.ResizableHorizontal = false;
             * ConsoleWindow.Movable = false;
             * ConsoleWindow.Color = new Color(255, 255, 255, 200);
             * ConsoleWindow.MinimumSize = new Vector2(0, 100);
             *
             * Input = ConsoleWindow.AddChild(new InputBox(DefaultFonts.ConsoleFont));
             * Input.OnTextEntered += (In, Txt) => {
             *      In.String = "";
             *      SendInput(Txt);
             * };
             *
             * Output = ConsoleWindow.AddChild(new Label(DefaultFonts.ConsoleFont));
             * Output.Multiline = true;
             * ConsoleWindow.OnResize += (Wnd, Sz) => {
             *      float SpacingOffset = 1.5f;
             *      Output.Position = new Vector2(0, DefaultFonts.ConsoleFont.LineSpacing * SpacingOffset);
             *      Output.DrawRegion = new AABB(new Vector2(Sz.X, Sz.Y - DefaultFonts.ConsoleFont.LineSpacing * SpacingOffset));
             *
             *      Input.DrawRegion = new AABB(new Vector2(Sz.X, DefaultFonts.ConsoleFont.LineSpacing));
             * };
             *
             * if (TempBuffer.Length > 0) {
             *      Output.AppendString(TempBuffer.ToString());
             *      TempBuffer.Clear();
             * }//*/

            ConVar <float> ConHeight = ConVar.Register("con_height", 0.4f, ConVarType.Archive);

            //const float Padding = 10;

            //ConsoleWindow.Position = new Vector2(Padding, (int)(Engine.WindowHeight * ConHeight) + Padding);
            //ConsoleWindow.Size = new Vector2(Engine.WindowWidth - Padding * 2, (int)(Engine.WindowHeight * (1.0f - ConHeight)) - Padding * 2);


            ConCmd.Register("clear", (Argv) => {
                Clear();
            });

            ConCmd.Register("rainbow", (Argv) => {
                string Rnd = Utils.RandomString(40, 60);

                Color Clr = Color;
                foreach (var Char in Rnd)
                {
                    Color = Utils.RandomColor();
                    Write(Char.ToString());
                }
                Write("\n");

                Color = Clr;
            });

            ConCmd.Register("echo", (Argv) => {
                for (int i = 1; i < Argv.Length; i++)
                {
                    string Arg = Argv[i];

                    /*if (Arg.StartsWith("$")) {
                     *      if (ConVar.TryFind(Arg.Substring(1), out ConVar Var))
                     *              Write(Var.ObjectValue);
                     *      else
                     *              Write("null");
                     * } else*/
                    Write(Arg);
                }
                Write("\n");
            });

            ConCmd.Register("alias", (Argv) => {
                if (Argv.Length == 1)
                {
                    foreach (var Alias in GetAliases())
                    {
                        WriteLine("{0} -> {1}", Alias.Item1, Alias.Item2);
                    }
                }
                else if (Argv.Length == 2)
                {
                    foreach (var Alias in GetAliases())
                    {
                        if (Alias.Item1.StartsWith(Argv[1]))
                        {
                            WriteLine("{0} -> {1}", Alias.Item1, Alias.Item2);
                        }
                    }
                }
                else if (Argv.Length == 3)
                {
                    WriteLine("{0} -> {1}", Argv[1], Argv[2]);
                    RegisterAlias(Argv[1], Argv[2]);
                }
                else
                {
                    Error("alias\nalias <command_alias>\nalias <command_alias> <command>");
                }
            });

            ConCmd.Register("var", (Argv) => {
                if (Argv.Length != 2)
                {
                    Error("var <variable_name>");
                    return;
                }

                ConVar.Register(Argv[1], 0);
            });

            ConCmd.Register("inc", (Argv) => {
                if (Argv.Length != 2)
                {
                    Error("inc <variable_name>");
                    return;
                }

                if (ConVar.TryFind(Argv[1], out ConVar Var))
                {
                    ((ConVar <int>)Var).Value++;
                }
            });

            ConCmd.Register("dec", (Argv) => {
                if (Argv.Length != 2)
                {
                    Error("dec <variable_name>");
                    return;
                }

                if (ConVar.TryFind(Argv[1], out ConVar Var))
                {
                    ((ConVar <int>)Var).Value--;
                }
            });

            ConCmd.Register("toggle", (Argv) => {
                if (Argv.Length != 2)
                {
                    Error("toggle <variable_name>");
                    return;
                }

                if (ConVar.TryFind(Argv[1], out ConVar Var))
                {
                    ConVar <int> IntVar = (ConVar <int>)Var;

                    if (IntVar.Value == 0)
                    {
                        IntVar.Value = 1;
                    }
                    else
                    {
                        IntVar.Value = 0;
                    }
                }
            });

            ConCmd.Register("cvarlist", (Argv) => {
                foreach (var CVar in ConVar.GetAll())
                {
                    WriteLine(CVar);
                }
            });

            ConCmd.Register("cmdlist", (Argv) => {
                foreach (var Cmd in ConCmd.GetAll())
                {
                    WriteLine(Cmd);
                }
            });

            ConCmd.Register("eval", (Argv) => {
                SendInputQuiet(string.Join("", Argv.Skip(1)));
            });

            ConCmd.Register("mousepos", (Argv) => {
                GConsole.WriteLine((Engine.Window.WindowSize.GetHeight() - Engine.Window.MousePos).Abs());
            });

            ConCmd.Register("crash", (Argv) => {
                throw new InvalidOperationException("Crashing the program!");
            });
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            CVar.InitMode = true;
            CVar.Register("game", "basegame", CVarType.Replicated | CVarType.Init, (This, Old, New) => This.Value = Path.GetFullPath((string)New));

            CVar.Register("width", 1366, CVarType.Archive);
            CVar.Register("height", 768, CVarType.Archive);
            CVar.Register("borderless", false, CVarType.Archive);
            CVar.Register("resizable", false, CVarType.Archive);
            CVar.Register("gl_doublebuffer", true, CVarType.Archive);
            CVar.Register("gl_samples", 8, CVarType.Archive);

            CVar.Register("gl_forwardcompat", true, CVarType.Archive | CVarType.Init | CVarType.Unsafe);
            CVar.Register("gl_major", 4, CVarType.Archive | CVarType.Init | CVarType.Unsafe);
            CVar.Register("gl_minor", 5, CVarType.Archive | CVarType.Init | CVarType.Unsafe);

            // Parse all arguments and set CVars
            foreach (var Arg in ArgumentParser.All)
            {
                switch (Arg.Key)
                {
                case "console":
                    GConsole.Open = true;
                    break;

                default: {
                    CVar CVar = CVar.Find(Arg.Key);

                    if (CVar != null)
                    {
                        CVar.Value = Arg.Value.LastOrDefault();
                    }
                    else
                    {
                        CVar.Register(Arg.Key, Arg.Value.LastOrDefault());
                    }

                    break;
                }
                }
            }

            CVar.InitMode = false;
            foreach (var CVar in CVar.GetAll())
            {
                GConsole.WriteLine(CVar);
            }

            FileWatcher.Init("content");
            Importers.RegisterAll(Reflect.GetExeAssembly());

            CreateContext();
            InitPhysics();

            LoadContent();

            Stopwatch SWatch = Stopwatch.StartNew();
            float     Target = 1.0f / 120;
            float     Dt     = Target;

            TextureTarget Tgt = TextureTarget.Texture2dMultisample;

            if (CVar.GetInt("gl_samples") == 0)
            {
                Tgt = TextureTarget.Texture2d;
            }

            Texture ColorTex = new Texture(Width, Height, Tgt, 1, InternalFormat.Rgb16f);
            Texture DepthTex = new Texture(Width, Height, Tgt, 1, InternalFormat.Depth24Stencil8);

            Framebuffer FB = new Framebuffer();

            FB.AttachColorTexture(ColorTex);
            FB.AttachDepthTexture(DepthTex);

            Texture SkyboxCubeMap = new Texture(1024, 1024, TextureTarget.TextureCubeMap, 1, InternalFormat.Srgb8Alpha8);

            SkyboxCubeMap.SetFilter(Gl.LINEAR, Gl.LINEAR);
            SkyboxCubeMap.SubImage3D(Image.FromFile("content/textures/skybox/interstellar/front.png"), Z: Texture.FRONT);
            SkyboxCubeMap.SubImage3D(Image.FromFile("content/textures/skybox/interstellar/back.png"), Z: Texture.BACK);
            SkyboxCubeMap.SubImage3D(Image.FromFile("content/textures/skybox/interstellar/left.png"), Z: Texture.LEFT);
            SkyboxCubeMap.SubImage3D(Image.FromFile("content/textures/skybox/interstellar/right.png"), Z: Texture.RIGHT);
            SkyboxCubeMap.SubImage3D(Image.FromFile("content/textures/skybox/interstellar/top.png"), Z: Texture.TOP);
            SkyboxCubeMap.SubImage3D(Image.FromFile("content/textures/skybox/interstellar/bottom.png"), Z: Texture.BOTTOM);

            //FB.Clear(new Vector4(1, 0, 0, 1));

            Model SkyboxCube = Importers.Load <Model>("content/models/cube.obj");

            SkyboxCube.Scale = new Vector3(2);
            SkyboxCube.Meshes[0].Material.Shader  = ShaderProgram.Skybox;
            SkyboxCube.Meshes[0].Material.Diffuse = SkyboxCubeMap;

            //bool DoDebug = true;

            while (!Glfw.WindowShouldClose(Window))
            {
                /*if (Khronos.KhronosApi.LogEnabled) {
                 *      Khronos.KhronosApi.LogCommand("END FRAME", null, null);
                 *      Khronos.KhronosApi.LogEnabled = false;
                 * }
                 *
                 * if (DoDebug) {
                 *      DoDebug = false;
                 *      Khronos.KhronosApi.LogEnabled = true;
                 *      Khronos.KhronosApi.LogCommand("BEGIN FRAME", null, null);
                 * }*/

                Update(Dt);
                Gl.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit | ClearBufferMask.StencilBufferBit);

                FB.Bind();
                {
                    Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
                    SetupState();

                    Gl.Disable(EnableCap.CullFace);
                    Gl.DepthMask(false);
                    SkyboxCube.Position = Camera.ActiveCamera?.Position ?? Vector3.Zero;
                    SkyboxCube.Draw();
                    Gl.DepthMask(true);

                    DrawScene(Dt);
                }
                FB.Unbind();

                // Swap to GUI camera
                Gl.Disable(EnableCap.DepthTest);
                Gl.Disable(EnableCap.CullFace);
                Camera.ActiveCamera = Camera.GUICamera;

                Immediate.UseShaders(() => {
                    if (ColorTex.Multisampled)
                    {
                        Immediate.TriangleShader = ShaderProgram.PostMultisample;
                        Immediate.TriangleShader.Uniform2f("TexSize", new Vector2(ColorTex.Width, ColorTex.Height));
                    }
                    else
                    {
                        Immediate.TriangleShader = ShaderProgram.Post;
                    }

                    Immediate.TriangleShader.Uniform1f("Exposure", 1.0f);

                    Gl.Enable(EnableCap.FramebufferSrgb);
                    Immediate.Texture2D(Vector2.Zero, ColorTex, UVInvertY: true);
                    Gl.Disable(EnableCap.FramebufferSrgb);
                });

                DrawGUI(Dt);
                Glfw.SwapBuffers(Window);

                // Cap at Target framerate
                while ((float)SWatch.ElapsedMilliseconds / 1000 < Target)
                {
                    ;
                }

                Dt  = (float)SWatch.ElapsedMilliseconds / 1000;
                FPS = (int)(1.0f / Dt);
                SWatch.Restart();
            }

            Environment.Exit(0);
        }
Exemplo n.º 15
0
 private static void OnCreated(object S, FileSystemEventArgs E)
 {
     GConsole.WriteLine("File created: {0}", E.FullPath);
 }