예제 #1
0
        static void Main(string[] args)
        {
            Game         game = new Game();
            OpenTKWindow gw   = new OpenTKWindow(game);

            gw.Run(Game.FPS);
        }
예제 #2
0
        public static void Main()
        {
            Scene        scene  = new Exercise1();
            OpenTKWindow window = new OpenTKWindow(scene);

            window.Run();
        }
예제 #3
0
        public override void Dispose( )
        {
            base.Dispose( );

            OpenTKWindow.Dispose( );

            IsDisposed = true;
        }
예제 #4
0
파일: Program.cs 프로젝트: GavinHwa/veldrid
        private static OpenGLRenderContext CreateDefaultOpenGLRenderContext(OpenTKWindow window)
        {
            bool debugContext = false;

#if DEBUG
            debugContext = Preferences.Instance.AllowOpenGLDebugContexts;
#endif
            return(new OpenGLRenderContext(window, debugContext));
        }
예제 #5
0
 //OpenTK window
 public static void RenderFrame(System.Object sender, OpenTK.FrameEventArgs e)
 {
     if (Core.Main.initDone)
     {
         OpenTKWindow main = sender as OpenTKWindow;
         main.Title = $"T-Delta: {(e.Time * 1000).ToString("n0")}ms | Time Elapsed: {GameLoop.stopwatch.Elapsed.ToString(@"mm\:ss")}";
         renderingLoop();
         main.SwapBuffers();
     }
 }
예제 #6
0
 private static RenderContext CreatePlatformDefaultContext(OpenTKWindow window, bool preferOpenGL = false)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !preferOpenGL)
     {
         return(new D3DRenderContext(window));
     }
     else
     {
         return(new OpenGLRenderContext(window, false));
     }
 }
예제 #7
0
        //////// OPTIONAL ////////

        // Processs any SDL2 events manually if required.
        // Return false to not allow the default event handler to process it.
        public bool MyEventHandler(OpenTKWindow _self, TKEvent e)
        {
            // We're replacing OnEvent and thus call ImGuiSDL2CSHelper.OnEvent manually.
            if (!ImGuiOpenTKHelper.HandleEvent(e))
            {
                return(false);
            }

            // Any custom event handling can happen here.

            return(true);
        }
예제 #8
0
        public Space()
        {
            var kernal = new StandardKernel(new TestModule());
            using (var engine = kernal.Get<GameEngine>())
            {
                //engine.Renderer = new OpenTKRenderer();
                //engine.Renderer.Setup();
                //ThreadPool.QueueUserWorkItem(Renderer.Start);
                engine.Timer.TimerMessages.Subscribe(m =>
                {
                   // Console.WriteLine("{0} - {1}".fmt(m.CurrentTickTime.GameTimeElapsed.ToString(), m.Message));
                });

                engine.Timer.Subscribe(t =>
                {
                  // Console.WriteLine("Doing stuff.");
                });

                Setup(engine);

                engine.Bus.OfType<SystemMessage>().Subscribe(m => Console.WriteLine("{0} SYSTEM - {1}", m.TimeSent.ToString(), m.Message));
                engine.Bus.Add(new SystemMessage(engine.Timer.LastTickTime, "OpenTK starting."));
                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state) {
                    using (OpenTKWindow p = new OpenTKWindow(engine))
                    {
                       // p.AddView(typeof(TestUnit), new TestUnitView());
                        p.Run();
                    }
                }), null);

                bool finish = false;
                while (!finish)
                {
                    engine.Start();

                    Console.ReadKey(true);

                    engine.Stop();

                    if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                        finish = true;
                }

                Console.WriteLine("Timer should have stopped.");
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey(true);

            }
        }
예제 #9
0
        public GraphicsSystem(OpenTKWindow window, float renderQuality = 1f, GraphicsBackEndPreference backEndPreference = GraphicsBackEndPreference.None)
        {
            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            bool preferOpenGL = backEndPreference == GraphicsBackEndPreference.OpenGL || !RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            _window = window;
            Context = CreatePlatformDefaultContext(window, preferOpenGL);
            Context.ResourceFactory.AddShaderLoader(new EmbeddedResourceShaderLoader(typeof(GraphicsSystem).GetTypeInfo().Assembly));
            MaterialCache = new MaterialCache(this);
            BufferCache   = new BufferCache(this);

            ShadowMapStage            = new ShadowMapStage(Context);
            _upscaleStage             = new UpscaleStage(Context, "Upscale", null, null);
            _standardStage            = new StandardPipelineStage(Context, "Standard");
            _alphaBlendStage          = new StandardPipelineStage(Context, "AlphaBlend");
            _alphaBlendStage.Comparer = new FarToNearIndexComparer();
            _overlayStage             = new StandardPipelineStage(Context, "Overlay");
            _pipelineStages           = new PipelineStage[]
            {
                ShadowMapStage,
                _standardStage,
                _alphaBlendStage,
                _upscaleStage,
                _overlayStage,
            };
            _renderer = new Renderer(Context, _pipelineStages);
            SetPreupscaleQuality(renderQuality);

            // Placeholder providers so that materials can bind to them.
            Context.RegisterGlobalDataProvider("ViewMatrix", s_identityProvider);
            Context.RegisterGlobalDataProvider("ProjectionMatrix", s_identityProvider);
            Context.RegisterGlobalDataProvider("CameraInfo", s_noCameraProvider);
            Context.RegisterGlobalDataProvider("LightBuffer", s_noLightProvider);
            Context.RegisterGlobalDataProvider("PointLights", _pointLightsProvider);

            window.Resized += OnWindowResized;

            _freeShapeRenderer          = new ManualWireframeRenderer(Context, RgbaFloat.Pink);
            _freeShapeRenderer.Topology = PrimitiveTopology.LineList;
            AddFreeRenderItem(_freeShapeRenderer);

            _mainThreadID      = Environment.CurrentManagedThreadId;
            _taskScheduler     = new GraphicsSystemTaskScheduler(_mainThreadID);
            _rayCastFilterFunc = RayCastFilter;
        }
예제 #10
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="tileSize">Size of a each tile, in pixels.</param>
        /// <param name="tileCount">Number of tiles on the tile board.</param>
        /// <param name="tilemapSize">Size of the tilemaps images to be loaded with <see cref="SetTilemap(int, string)"/>, in pixels.</param>
        public OneBitOfGame(Dimension tileSize, Dimension tileCount, Dimension tilemapSize)
        {
            OpenTKWindow = new OpenTKWindow(this)
            {
                Title = ""
            };

            Files    = new FileSystem();
            Renderer = new TileRenderer(Files, tileSize, tileCount, tilemapSize);
            Audio    = new AudioPlayer(Files);
            Sprites  = new SpriteManager();

            UI    = new UIEnvironment(this);
            Input = new InputManager(this);
        }
예제 #11
0
        // Any custom game loop should end up here.
        // Setting the window.IsActive = false stops the loop.
        public void MyGameLoop(OpenTKWindow _self)
        {
            // This is the default implementation, except for the ClearColor not being 0.1f, 0.125f, 0.15f, 1f

            // Using minimal ImGuiSDL2CS.GL to provide access to OpenGL methods.
            // Alternatively, use SDL_GL_GetProcAddress on your own.
            GL.ClearColor(clear_color.X, clear_color.Y, clear_color.Z, 1f);
            GL.Clear(ClearBufferMask.ColorBufferBit);

            // This calls ImGuiSDL2CSHelper.NewFrame, the overridden ImGuiLayout, ImGuiSDL2CSHelper.Render and renders it.
            // ImGuiSDL2CSHelper.NewFrame properly sets up ImGuiIO and ImGuiSDL2CSHelper.Render renders the draw data.
            ImGuiRender();

            // Finally, swap.
            Swap();
        }
예제 #12
0
        static void Main(string[] args)
        {
            Queue <string> argq = new Queue <string>(args);

            while (argq.Count > 0)
            {
                string arg = argq.Dequeue();
                if (arg == "--debug")
                {
                    Debugger.Launch();
                }
            }

            /*ImGuiOpenTKCSWindow*/ Instance = new YourGameWindow();
            Instance.Run();
            Instance.Dispose();
        }
예제 #13
0
        public static int Main(string[] args)
        {
            EngineLaunchOptions launchOptions = new EngineLaunchOptions(args);

            ProjectManifest projectManifest;
            string          currentDir   = AppContext.BaseDirectory;
            string          manifestName = null;

            foreach (var file in Directory.EnumerateFiles(currentDir))
            {
                if (file.EndsWith("manifest"))
                {
                    if (manifestName != null)
                    {
                        Console.WriteLine("Error: Multiple project manifests in this directory: " + currentDir);
                        return(-1);
                    }

                    manifestName = file;
                }
            }

            using (var fs = File.OpenRead(manifestName))
                using (var sr = new StreamReader(fs))
                    using (var jtr = new JsonTextReader(sr))
                    {
                        var js = new JsonSerializer();
                        try
                        {
                            projectManifest = js.Deserialize <ProjectManifest>(jtr);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("An error was encountered while loading the project manifest.");
                            Console.WriteLine(e);
                            return(-1);
                        }
                    }

            Game game = new Game();

            AssemblyLoadSystem als = new AssemblyLoadSystem();

            als.LoadFromProjectManifest(projectManifest, AppContext.BaseDirectory);
            game.SystemRegistry.Register(als);

            GraphicsPreferencesProvider graphicsProvider;
            string graphicsProviderName = projectManifest.GraphicsPreferencesProviderTypeName;

            if (graphicsProviderName != null)
            {
                graphicsProvider = GetProvider(als, graphicsProviderName);
            }
            else
            {
                graphicsProvider = new DefaultGraphicsPreferencesProvider();
            }

            var          desiredInitialState = GraphicsPreferencesUtil.MapPreferencesState(graphicsProvider.WindowStatePreference);
            OpenTKWindow window = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? (OpenTKWindow) new DedicatedThreadWindow(960, 540, desiredInitialState)
                : new SameThreadWindow(960, 540, desiredInitialState);

            window.Title = "ge.Main";
            GraphicsSystem gs = new GraphicsSystem(window, graphicsProvider);

            game.SystemRegistry.Register(gs);
            window.Closed += game.Exit;

            game.LimitFrameRate = false;

            InputSystem inputSystem = new InputSystem(window);

            inputSystem.RegisterCallback((input) =>
            {
                if (input.GetKeyDown(Key.F4) && (input.GetKey(Key.AltLeft) || input.GetKey(Key.AltRight)))
                {
                    game.Exit();
                }
                if (input.GetKeyDown(Key.F11))
                {
                    window.WindowState = window.WindowState == WindowState.Normal ? WindowState.BorderlessFullScreen : WindowState.Normal;
                }
            });
            game.SystemRegistry.Register(inputSystem);

            SceneLoaderSystem sls = new SceneLoaderSystem(game, game.SystemRegistry.GetSystem <GameObjectQuerySystem>());

            game.SystemRegistry.Register(sls);
            sls.AfterSceneLoaded += () => game.ResetDeltaTime();

            EngineLaunchOptions.AudioEnginePreference?audioPreference = launchOptions.AudioPreference;
            AudioEngineOptions audioEngineOptions =
                !audioPreference.HasValue ? AudioEngineOptions.Default
                : audioPreference == EngineLaunchOptions.AudioEnginePreference.None ? AudioEngineOptions.UseNullAudio
                : AudioEngineOptions.UseOpenAL;
            AudioSystem audioSystem = new AudioSystem(audioEngineOptions);

            game.SystemRegistry.Register(audioSystem);

            ImGuiRenderer imGuiRenderer = new ImGuiRenderer(gs.Context, window.NativeWindow, inputSystem);

            gs.SetImGuiRenderer(imGuiRenderer);

            AssetSystem assetSystem = new AssetSystem(Path.Combine(AppContext.BaseDirectory, projectManifest.AssetRoot), als.Binder);

            game.SystemRegistry.Register(assetSystem);

            BehaviorUpdateSystem bus = new BehaviorUpdateSystem(game.SystemRegistry);

            game.SystemRegistry.Register(bus);
            bus.Register(imGuiRenderer);

            PhysicsSystem ps = new PhysicsSystem(projectManifest.PhysicsLayers);

            game.SystemRegistry.Register(ps);

#if DEBUG
            ConsoleCommandSystem ccs = new ConsoleCommandSystem(game.SystemRegistry);
            game.SystemRegistry.Register(ccs);
#endif

            game.SystemRegistry.Register(new SynchronizationHelperSystem());

            SceneAsset scene;
            AssetID    mainSceneID = projectManifest.OpeningScene.ID;
            if (mainSceneID.IsEmpty)
            {
                var scenes = assetSystem.Database.GetAssetsOfType(typeof(SceneAsset));
                if (!scenes.Any())
                {
                    Console.WriteLine("No scenes were available to load.");
                    return(-1);
                }
                else
                {
                    mainSceneID = scenes.First();
                }
            }

            scene = assetSystem.Database.LoadAsset <SceneAsset>(mainSceneID);
            scene.GenerateGameObjects();

            RunStartupFunctions(projectManifest, als, game);

            game.RunMainLoop();

            return(0);
        }
예제 #14
0
        public OpenGLRenderContext(OpenTKWindow window,
#if DEBUG
                                   bool debugContext = true)
예제 #15
0
        private unsafe void UpdateImGuiInput(OpenTKWindow window, InputSnapshot snapshot)
        {
            IO         io          = ImGui.GetIO();
            MouseState cursorState = Mouse.GetCursorState();
            MouseState mouseState  = Mouse.GetState();

            if (window.NativeWindow.Bounds.Contains(cursorState.X, cursorState.Y) && !RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // TODO: This does not take into account viewport coordinates.
                if (window.Exists)
                {
                    Point windowPoint = window.NativeWindow.PointToClient(new Point(cursorState.X, cursorState.Y));
                    io.MousePosition = new System.Numerics.Vector2(
                        windowPoint.X / window.ScaleFactor.X,
                        windowPoint.Y / window.ScaleFactor.Y);
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                io.MousePosition = new System.Numerics.Vector2(
                    cursorState.X,
                    cursorState.Y);
            }
            else
            {
                io.MousePosition = new System.Numerics.Vector2(-1f, -1f);
            }

            io.MouseDown[0] = mouseState.LeftButton == ButtonState.Pressed;
            io.MouseDown[1] = mouseState.RightButton == ButtonState.Pressed;
            io.MouseDown[2] = mouseState.MiddleButton == ButtonState.Pressed;

            float delta = snapshot.WheelDelta;

            io.MouseWheel = delta;

            ImGui.GetIO().MouseWheel = delta;

            IReadOnlyList <char> keyCharPresses = snapshot.KeyCharPresses;

            for (int i = 0; i < keyCharPresses.Count; i++)
            {
                char c = keyCharPresses[i];
                ImGui.AddInputCharacter(c);
            }

            IReadOnlyList <KeyEvent> keyEvents = snapshot.KeyEvents;

            for (int i = 0; i < keyEvents.Count; i++)
            {
                KeyEvent keyEvent = keyEvents[i];
                io.KeysDown[(int)keyEvent.Key] = keyEvent.Down;
                if (keyEvent.Key == Key.ControlLeft)
                {
                    _controlDown = keyEvent.Down;
                }
                if (keyEvent.Key == Key.ShiftLeft)
                {
                    _shiftDown = keyEvent.Down;
                }
                if (keyEvent.Key == Key.AltLeft)
                {
                    _altDown = keyEvent.Down;
                }
            }

            io.CtrlPressed  = _controlDown;
            io.AltPressed   = _altDown;
            io.ShiftPressed = _shiftDown;
        }
예제 #16
0
 public override void Exit( )
 {
     OpenTKWindow.Exit( );
 }
예제 #17
0
 public override void ProcessEvents( )
 {
     OpenTKWindow.ProcessEvents( );
 }
예제 #18
0
 public GraphicsSystem(OpenTKWindow window, GraphicsPreferencesProvider preferences)
     : this(window, preferences.RenderQuality, preferences.BackEndPreference)
 {
 }
예제 #19
0
        private static OpenGLRenderContext GetDefaultOpenGLContext(OpenTKWindow window)
        {
            bool debug = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            return(new OpenGLRenderContext(window, debug));
        }
예제 #20
0
        public static void Main(string[] args)
        {
            OpenTKWindow window = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? (OpenTKWindow) new DedicatedThreadWindow() : new SameThreadWindow();

            window.Title   = "ge.Main";
            window.Visible = true;
            Game           game = new Game();
            GraphicsSystem gs   = new GraphicsSystem(window);

            game.SystemRegistry.Register(gs);
            gs.AddFreeRenderItem(new ShadowMapPreview(gs.Context));

            InputSystem inputSystem = new InputSystem(window);

            inputSystem.RegisterCallback((input) =>
            {
                if (input.GetKeyDown(Key.F4) && (input.GetKey(Key.AltLeft) || input.GetKey(Key.AltRight)))
                {
                    game.Exit();
                }
                if (input.GetKeyDown(Key.F11))
                {
                    window.WindowState = window.WindowState == WindowState.Normal ? WindowState.FullScreen : WindowState.Normal;
                }
                if (input.GetKeyDown(Key.F12))
                {
                    gs.ToggleOctreeVisualizer();
                }
            });

            game.SystemRegistry.Register(inputSystem);

            ImGuiRenderer imGuiRenderer = new ImGuiRenderer(gs.Context, window.NativeWindow, inputSystem);

            gs.AddFreeRenderItem(imGuiRenderer);
            ImGuiNET.ImGui.GetIO().FontAllowUserScaling = true;

            AssetSystem assetSystem = new AssetSystem(Path.Combine(AppContext.BaseDirectory, "Assets"));

            game.SystemRegistry.Register(assetSystem);

            BehaviorUpdateSystem bus = new BehaviorUpdateSystem(game.SystemRegistry);

            game.SystemRegistry.Register(bus);
            bus.Register(imGuiRenderer);

            PhysicsSystem ps = new PhysicsSystem();

            game.SystemRegistry.Register(ps);

            ScoreSystem ss = new ScoreSystem();

            game.SystemRegistry.Register(ss);

            ConsoleCommandSystem ccs = new ConsoleCommandSystem(game.SystemRegistry);

            game.SystemRegistry.Register(ccs);

            window.Closed += game.Exit;

            LooseFileDatabase db = new LooseFileDatabase(AppContext.BaseDirectory);

            AddBinGameScene();
            SceneAsset scene = new SceneAsset();
            var        goqs  = game.SystemRegistry.GetSystem <GameObjectQuerySystem>();

            scene.GameObjects = goqs.GetAllGameObjects().Select(go => new SerializedGameObject(go)).ToArray();
            db.SaveDefinition(scene, "BINSCENE.scene");

            //var scene = db.LoadAsset<SceneAsset>("BINSCENE.scene_New");
            //scene.GenerateGameObjects();

            game.RunMainLoop();
        }
예제 #21
0
 public override void Run( )
 {
     OpenTKWindow.Run( );
 }
예제 #22
0
파일: Program.cs 프로젝트: zhuowp/ge
        public static void Main(string[] args)
        {
            CommandLineOptions commandLineOptions = new CommandLineOptions(args);
            // Force-load prefs.
            var prefs = EditorPreferences.Instance;

            OpenTKWindow window = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? (OpenTKWindow)new DedicatedThreadWindow(960, 540, WindowState.Maximized)
                : new SameThreadWindow(960, 540, WindowState.Maximized);
            window.Title = "ge.Editor";
            Game game = new Game();
            GraphicsBackEndPreference backEndPref = commandLineOptions.PreferOpenGL ? GraphicsBackEndPreference.OpenGL : GraphicsBackEndPreference.None;
            GraphicsSystem gs = new GraphicsSystem(window, prefs.RenderQuality, backEndPref);
            gs.Context.ResourceFactory.AddShaderLoader(new EmbeddedResourceShaderLoader(typeof(Program).GetTypeInfo().Assembly));
            game.SystemRegistry.Register(gs);
            game.LimitFrameRate = false;

            InputSystem inputSystem = new InputSystem(window);
            inputSystem.RegisterCallback((input) =>
            {
                if (input.GetKeyDown(Key.F4) && (input.GetKey(Key.AltLeft) || input.GetKey(Key.AltRight)))
                {
                    game.Exit();
                }
            });

            game.SystemRegistry.Register(inputSystem);

            ImGuiRenderer imGuiRenderer = new ImGuiRenderer(gs.Context, window.NativeWindow, inputSystem);
            gs.SetImGuiRenderer(imGuiRenderer);

            var als = new AssemblyLoadSystem();
            game.SystemRegistry.Register(als);

            AssetSystem assetSystem = new EditorAssetSystem(Path.Combine(AppContext.BaseDirectory, "Assets"), als.Binder);
            game.SystemRegistry.Register(assetSystem);

            EditorSceneLoaderSystem esls = new EditorSceneLoaderSystem(game, game.SystemRegistry.GetSystem<GameObjectQuerySystem>());
            game.SystemRegistry.Register<SceneLoaderSystem>(esls);
            esls.AfterSceneLoaded += () => game.ResetDeltaTime();

            CommandLineOptions.AudioEnginePreference? audioPreference = commandLineOptions.AudioPreference;
            AudioEngineOptions audioEngineOptions =
                !audioPreference.HasValue ? AudioEngineOptions.Default
                : audioPreference == CommandLineOptions.AudioEnginePreference.None ? AudioEngineOptions.UseNullAudio
                : AudioEngineOptions.UseOpenAL;
            AudioSystem audioSystem = new AudioSystem(audioEngineOptions);
            game.SystemRegistry.Register(audioSystem);

            BehaviorUpdateSystem bus = new BehaviorUpdateSystem(game.SystemRegistry);
            game.SystemRegistry.Register(bus);
            bus.Register(imGuiRenderer);

            PhysicsSystem ps = new PhysicsSystem(PhysicsLayersDescription.Default);
            game.SystemRegistry.Register(ps);

            ConsoleCommandSystem ccs = new ConsoleCommandSystem(game.SystemRegistry);
            game.SystemRegistry.Register(ccs);

            game.SystemRegistry.Register(new SynchronizationHelperSystem());

            window.Closed += game.Exit;

            var editorSystem = new EditorSystem(game.SystemRegistry, commandLineOptions, imGuiRenderer);
            editorSystem.DiscoverComponentsFromAssembly(typeof(Program).GetTypeInfo().Assembly);
            // Editor system registers itself.

            game.RunMainLoop();

            window.NativeWindow.Dispose();

            EditorPreferences.Instance.Save();
        }
예제 #23
0
 public override void Present( )
 {
     OpenTKWindow.SwapBuffers( );
 }